text string | label_name string | labels int64 |
|---|---|---|
= Ok::<_, ()>(vec![1, 2, 3]);
let future2 = Ok(vec![10, 20, 30]);
let future3 = Ok(vec![100, 200, 300]);
let results = block_on(join_all(vec![future1, future2, future3])).unwrap();
println!("Results of joining 3 futures: {:?}", results);
// For parameters with a lifetime
fn sum_vecs<'a>(vecs:... | Rust | 0 |
Alt,
RCtrl, LCtrl, Ctrl,
RShift, LShift, Shift,
Super,
Esc,
Backspace,
Return,
Space,
Tab,
UK,
XF86AudioRaiseVolume, XF86AudioLowerVolume,
XF86AudioMute,
XF86AudioPrev, XF86AudioNext,
XF86AudioPlay, XF86AudioStop,
// Find out the exact key codes of these
XF... | Rust | 0 |
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | Python | 1 |
/// LE Static Device Address
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct StaticDeviceAddress(BdAddr);
impl StaticDeviceAddress {
const TAG: u8 = 0b11;
}
impl TryFrom<[u8; 6]> for StaticDeviceAddress {
type Error = InvalidBitsForAddressType;
fn try_from(v: [u8; 6]) -> Result<Self, Self::Erro... | Rust | 0 |
ozone_mixture, sr = librosa.load(
f"{args.musdb_XL_train_root}/ozone_train_random/{random_song[0]}.wav",
sr=44100,
mono=False,
)
mixture[mixture == 0.0] = np.finfo(np.float32).eps # to avoid 'divided by zero'
ratio = ozone_mixture / mixture
... | Python | 1 |
".py") and len(lines) > 0 and lines[0].startswith('#'):
insert_position = 1
license = [e + '\n' for e in TEXT.format("Copyright {} (C) Alexey Dynda".format(YEAR)).split('\n')]
if not copyright_exists:
license.append("\n")
if name.endswith(".py"):
for i in range(len(license)):
... | Python | 1 |
excitedstatepopulation=excitedstatepopulation,
)
# dmc.rz(0,theta = i*np.pi/1.5)
dmc.h(0)
val = dmc.expectation_ps(z=[0])
p = (1 - val) / 2.0
pex.append(p)
timelist = np.array([i * time for i in range(nstep)])
measurement = np.array(np.real(pex))
... | Python | 1 |
from skmultiflow.data.file_stream import FileStream
from skmultiflow.transform import MissingValuesCleaner
def demo():
""" _test_filters
This demo test the MissingValuesCleaner filter. The transform is set
to clean any value equal to -47, replacing it with the median value
of the last 10 sample... | Python | 1 |
"function": {"name": tool_choice},
}
# 'any' is not natively supported by OpenAI API.
# We support 'any' since other models use this instead of 'required'.
if tool_choice == "any":
tool_choice = "required"
... | Python | 1 |
&& raw_pcm) {
panic!("Repeating input is only allowed when outputting raw PCM samples to STDOUT.")
}
Options {
input,
output,
repeat,
mdpm: matches
.value_of("MDPS")
.unwrap()
.parse()
.expect("Invalid number."),
f... | Rust | 0 |
e.MaxValue, Double.MaxValue)
#See Dev10 409981 for more info
AssertError(StandardError, com_obj.mDouble, Double.MaxValue)
AssertError(StandardError, com_obj.mCy, Decimal(0))
#------------------------------------------------------------------------------
def test_variant_bool():
for t... | Python | 1 |
# see http://python4astronomers.github.com/contest/bounce.html
figure(1)
clf()
axis([-10, 10, -10, 10])
# Define properties of the "bouncing balls"
n = 10
pos = (20 * random_sample(n*2) - 10).reshape(n, 2)
vel = (0.3 * normal(size=n*2)).reshape(n, 2)
sizes = 100 * random_sample(n) + 100
# Colors where each row is (Re... | Python | 1 |
# -*- coding: utf-8 -*-
"""Specific environment for the gripper.
"""
__authors__ = ("emenager")
__contact__ = ("etienne.menager@ens-rennes.fr")
__version__ = "1.0.0"
__copyright__ = "(c) 2021, Inria"
__date__ = "Feb 3 2021"
from sofagym.AbstractEnv import AbstractEnv
from sofagym.rpc_server import start_scene
from g... | Python | 1 |
ze x pool_size x pool_size x final_size`.
# ResNet does an Average Pooling layer over pool_size,
# but that is the same as doing a reduce_mean. We do a reduce_mean
# here because it performs better than AveragePooling2D.
axes = [2, 3] if self.data_format == 'channels_first' else [1, 2]
inp... | Python | 1 |
init_rng, init_key = random.split(init_rng)
x = ops.LinearLayer(in_features=x.shape[1],
out_features=nf(0),
activation=self.activation,
param_dict=self.param_dict['block_4x4'] if self.param_dict is not None else None,
... | Python | 1 |
copy_from_slice(&data);
Ok(())
}
/// Reads `size` blocks from the given `offset` for every `LeafVdev`.
fn read_raw(&self, size: Block<u32>, offset: Block<u64>) -> Vec<Box<[u8]>> {
let data = self.data.lock().unwrap();
let offset = offset.to_bytes() as usize;
let range = off... | Rust | 0 |
import pika
credentials = pika.PlainCredentials("foroozan" , "123")
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost' , credentials = credentials))
ch = connection.channel()
ch.queue_declare('queue-request')
def on_request_message_recived(ch , method , properties , body ):
print(f... | Python | 1 |
import argparse
from pathlib import Path
from visualization import manipulation
def get_env(task_config_path):
env = manipulation.get_env(task_config_path)
return env
def visualize(env, output_path):
manipulation.visualize(env, output_path)
def main(args):
output_dir = Path(args.output_dir)
outp... | Python | 1 |
projection.to_vec();
projection.extend(after.iter().copied());
Place::make(loan.local, &projection, tcx)
} else {
*loan
}
});
aliases.extend(region_aliases);
aliases
}
pub fn build(
tcx: TyCtxt<'tcx>,
def_id: DefId,
body_with_facts: &'a BodyWithBorrowckF... | Rust | 0 |
import base64
import typing as t
from abc import ABCMeta
from abc import abstractmethod
from urllib.parse import quote
SupportedAlgorithms = t.Literal["SHA1", "SHA256", "SHA512"]
Self = t.TypeVar("Self", bound="OTP")
class OTP(metaclass=ABCMeta):
TYPE: t.ClassVar[str]
#: The supportted algorithms
ALGORI... | Python | 1 |
<dyn Write> =
if let Some(filename) = matches.value_of("output") {
Box::new(BufWriter::new(
File::create(filename).expect("cannot create file"),
))
} else {
Box::new(BufWriter::new(stdout()))
};
let mut world = World::new();
let mut r... | Rust | 0 |
# Run strategy immediately on startup and force a check
last_bar_time = run_volatility_strategy(force_check=True)
while True:
# Calculate time until next 4-hour bar closes (plus buffer)
seconds_to_wait, next_check_time = calculate_next_4h_bar_time()
... | Python | 1 |
# Copyright 2020 The KNIX Authors
#
# 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 or agree... | Python | 1 |
or='darkred', linestyle='--', alpha=0.7, linewidth=1, label='80% Loss')
plt.legend(loc='upper right')
plt.tight_layout()
# Save
output_file = self.output_dir / 'all_tokens_simple_line_chart.png'
plt.savefig(output_file, dpi=300, bbox_inches='tight')
logg... | Python | 1 |
value_dict.update({f"{k}": state_dict["ip_adapter"][f"{key_id}.{k}"].astype(str_dtype)})
if from_diffusers:
convert_pytorch_state_dict_to_paddle(attn_procs[name], value_dict)
attn_procs[name].load_dict(value_dict)
key_id += 2
self.set_at... | Python | 1 |
I_TabletPC\"`*"]
pub const DISPID_IRecoCtx2_EnabledUnicodeRanges: DISPID_InkRecoContext2 = 0i32;
#[doc = "*Required features: `\"Win32_UI_TabletPC\"`*"]
pub type DISPID_InkRecognitionAlternates = i32;
#[doc = "*Required features: `\"Win32_UI_TabletPC\"`*"]
pub const DISPID_InkRecognitionAlternates_NewEnum: DISPID_InkRe... | Rust | 0 |
stilBertModel.from_pretrained(model_name)
self.assertIsNotNone(model)
@require_tf
class TFDistilBertModelIntegrationTest(unittest.TestCase):
@slow
def test_inference_masked_lm(self):
model = TFDistilBertModel.from_pretrained("distilbert-base-uncased")
input_ids = tf.constant([[0, 1... | Python | 1 |
_labels, mut exp_labels) = setup_create_label_memory(
sector_size,
DEGREE,
Some(default_cache_size as usize),
&parents_cache.path,
)?;
for layer in 1..=layers {
info!("Layer {}", layer);
// Cache reset happens in two parts.
// The second part (the finish... | Rust | 0 |
::from_ymd(2021, 01, 26).and_hms(11, 00, 00),
Utc
)).unwrap().as_secs(),
"3w 5d 23h".secs()
);
assert_eq!(
every(4).weeks().on(Weekday::Mon).at(10, 00, 00).in_timezone(&Utc)
.time_to_sleep_at_until(&DateTime::from_utc(
... | Rust | 0 |
# Copyright 2023 The Qwen team, Alibaba Group. 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 required by... | Python | 1 |
, &raw.0)?;
// No change to context
Ok(*ctx)
}
None => Err(Error::UpcastError("Need a SignatureScheme to upcast a Signature")),
}
}
}
impl CryptoUpcast for crate::crypto::ecies::EciesCiphertext {
fn upcast_crypto_values(&mut self, ctx: &CryptoCtx)... | Rust | 0 |
tm.assert_series_equal(s1.append(s2, ignore_index=True), exp)
tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), exp)
tm.assert_series_equal(s2.append(s1, ignore_index=True), exp)
def test_categorical_concat_append(self):
cat = Categorical(["a", "b"], categories=["a", ... | Python | 1 |
5NOSYNC_A::DIS,
true => TMRB5NOSYNC_A::NOSYNC,
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline(always)]
pub fn is_dis(&self) -> bool {
*self == TMRB5NOSYNC_A::DIS
}
#[doc = "Checks if the value of the field is `NOSYNC`"]
#[inline(always)]
pub... | Rust | 0 |
: 0 1px 3px rgba(0,0,0,.12),0 1px 2px rgba(0,0,0,.24);flex:0 1 220px;overflow:auto\">"
).to_owned();
if let Some(window) = TEST_CASES
.windows(2)
.find(|window| window[0].0 >= window[1].0)
{
panic!("Sort: {:#?}", (window[0].0, window[1].0));
}
for (title, test_cases) in TEST_... | Rust | 0 |
ght, height) = if ctx.length == 3 {
let js_height = ctx.get::<JsNumber>(2)?;
let height = js_height.get_uint32()?;
if height * width * 4 != arraybuffer_length as u32 {
return Err(Error::new(
Status::InvalidArg,
"Index or size is negative or greater t... | Rust | 0 |
cs,
hl_defs,
affected_segments,
row,
);
}
/// Clears whole `da` with `hl_defs.default_bg`.
pub fn clear(da: &DrawingArea, ctx: &mut Context, hl_defs: &HlDefs) {
let cr = &ctx.cairo_context;
let w = da.get_allocated_width();
let h = da.get_allocated_height();
let bg = &hl_def... | Rust | 0 |
CLASS_QUANTITY = 11
OPTION_DEFAULT_VALUE = 0
TEACHER_ID_DEFAULT = -1
ROLE_DEFAULT_OPTION = -1
TEACHER_NAME_POS = 0
TEACHER_ID_POS = 1
STUDENT_NAME_POS = 0
STUDENT_EMAIL_POS = 2
WEEKDAYS = (
'Понеділок',
'Вівторок',
'Середа',
'Четвер',
"П'ятниця",
'Субота',
)
WEEKDAYS_DB = (
'Monday',
... | Python | 1 |
();
if idx == 0 {
for bit in &chars {
borders[0] = (borders[0] << 1) | (*bit == '.') as u64;
}
}
if idx == 9 {
for bit in &chars {
borders[2] = (borders[2] << 1) | (*bit == '.') as u64;
... | Rust | 0 |
t - timedelta(days=1) for point in points] + [all_df.index.max()]
for i, (start, end) in enumerate(zip(starts, ends)):
phase_df = all_df.loc[start: end, :]
param, _ = curve_fit(self._linear_f, phase_df[r], phase_df[logS], maxfev=10000)
all_df[self.num2str(i)] = self._linear_f... | Python | 1 |
# This serves as a template which will guide you through the implementation of this task. It is advised
# to first read the whole template and get a sense of the overall structure of the code before trying to fill in any of the TODO gaps
# First, we import necessary libraries:
import numpy as np
import pandas as pd
... | Python | 1 |
_PLACEMENT_ALIGNMENT as u64);
pub const UAV_SLOT_COUNT: u32 = D3D12_UAV_SLOT_COUNT;
pub const UNBOUND_MEMORY_ACCESS_RESULT: u32 =
D3D12_UNBOUND_MEMORY_ACCESS_RESULT;
pub const VIDEO_DECODE_MAX_ARGUMENTS: u32 = D3D12_VIDEO_DECODE_MAX_ARGUMENTS;
pub const VIDEO_DECODE_MAX_HISTOGRAM_COMPONENTS: u32 =
D3D12_VIDEO_D... | Rust | 0 |
windSpeed");
weather.wind_speed = xml.read_text(e.name(), &mut Vec::new()).expect("Failed to read text at windSpeed");
}
(State::Root, b"directionCompass") => {
let weather = weather_data.last_mut().expect(... | Rust | 0 |
p c0 c1 = c
// ...
// {(F a0 b0 c0 ...) (F a1 b1 c1 ...)}
if get_tag(ask_arg(rt, term, *idx)) == SUP {
//println!("fun-sup");
let funx = get_ext(term);
let arit = rt.get_arity(funx);
rt.set_mana(rt.get_mana() + Fun... | Rust | 0 |
!((g.idct(4) - 1.481487836406659).abs() < 0.000001);
assert!((g.idct(5) - 1.456220246978134).abs() < 0.000001);
assert!((g.idct(6) - 3.7141071965451276).abs() < 0.000001);
}
}
<filename>core/src/fnargs.rs
/*
MIT License
Copyright (c) 2017 <NAME>
Permission is hereby granted, free of charge, to any... | Rust | 0 |
first, second + 1)
class AlsoNotUselessSuperPy3(NotUselessSuperPy3):
def not_passing_keyword_only(self, first, *, second="second"):
return super().not_passing_keyword_only(first, second=second)
class UselessSuperPy3:
def useless(self, *, first): # [useless-parent-delegation]
super().useless... | Python | 1 |
from fastapi import APIRouter, HTTPException
from datetime import datetime
from typing import List, Dict, Any
import aiohttp
from models.incidentes import AnaliseEntidadeModel
from models.openapi_examples import AnaliseIncidenteResponseModelOpenAPI
from utils.newrelic_advanced_collector import get_all_entities, get_ent... | Python | 1 |
ataFrameGroupBy
klass = DataFrameGroupBy
else: # pragma: no cover
raise TypeError(f"invalid type: {obj}")
return klass(
obj=obj,
keys=by,
axis=axis,
grouper=grouper,
group_keys=group_keys,
)
def _insert_quantile_level(idx: Index, qs: npt.NDArray[n... | Python | 1 |
import pyperclip
import keyboard
import time
from pypdf import PdfReader
DOCUMENT_NAME = "example.pdf"
START_LINE = 0
def wait_for_key():
while True:
# Wait for the next event.
event = keyboard.read_event()
if event.event_type == keyboard.KEY_DOWN:
if event.name == "ctrl":
... | Python | 1 |
(Signal::SIGCHLD),
uapi::SIGCONT => Ok(Signal::SIGCONT),
uapi::SIGSTOP => Ok(Signal::SIGSTOP),
uapi::SIGTSTP => Ok(Signal::SIGTSTP),
uapi::SIGTTIN => Ok(Signal::SIGTTIN),
uapi::SIGTTOU => Ok(Signal::SIGTTOU),
uapi::SIGURG => Ok(Signal::SIGURG),
... | Rust | 0 |
-------------------------------------------------------------------
use std::num::NonZeroU32;
use controlled_option::ControlledOption;
use controlled_option::Niche;
#[test]
fn can_option_references() {
let none = ControlledOption::<&u32>::none();
assert!(none.is_none());
// `None` references should be re... | Rust | 0 |
),
(24, 275),
(32, 287),
(33, 288),
(40, 296),
(48, 303),
(56, 309),
(64, 314),
(65, 314),
(72, 318),
(80, 322),
(96, 328),
(100, 330),
(110, 333),
(128, 338),
(178, 350),
(323, 369),
(333, 370),
(343, 371),
(380, 374),
(384, 375),
];
fn l... | Rust | 0 |
age = 22
if age >= 18:
message = "Eligible"
else:
message = "Not eligible"
message = "Eligible" if age >= 18 else "Not eligible"
print(message)
| Python | 1 |
for TotalTimeElapsed<A, C> {
type E = C;
fn enter(&self) -> Self::E {
C::now()
}
}
impl<A: CounterIncrementer, C: Instant> Default for TotalTimeElapsed<A, C> {
fn default() -> Self {
TotalTimeElapsed(A::default(), std::marker::PhantomData)
}
}
impl<A: CounterIncrementer, C: Instan... | Rust | 0 |
idx, row in val_annotations.iterrows()
]
print(f"------ Train: {len(train_annotations)}, Val: {len(val_annotations)} ------")
train = []
count = 0
for label, youtube_id, time_start, time_end in train_annotations:
# Downloader was made by geniuses as you can tell
path = (
... | Python | 1 |
U_pred = U_pred.cpu().detach().numpy()
savemat(f'dgpinn_heat_NTK_seed_{seeds_num}.mat',
{'u_pred': u_pred, 'u_test': u_test, 'U_pred': U_pred.reshape(201,201), 'u_true': U,
'loss_r': epoch_loss_r, 'loss_i': epoch_loss_i, 'loss_b': epoch_loss_b, 'loss_d': epoch_loss_d, 'beta': epo... | Python | 1 |
import uuid
import pytest
def test_get_agents(docker_services, test_client):
response = test_client.get("/")
assert response.status_code == 200
assert isinstance(response.json(), list)
for agent in response.json():
assert agent.get("name") in ["Ensemble", "Router", "rag_environment", "rag_educa... | Python | 1 |
import cv2
import numpy as np
import robomaster
from robomaster import robot
import time
from pymycobot import MyCobotSocket
ID = {'1', '2', '3', '4', '5'}
markers = []
markers_info = []
distance = []
dist_threshold = 1000
mc = MyCobotSocket("192.168.43.38", 9000)
# 树莓派版本需要输入connect函数,默认值为("/dev/ttyAMA0","1000000")
... | Python | 1 |
#[repr(i8)]
pub(crate) enum MsgType {
Query = 'Q' as i8,
Terminate = 'X' as i8,
EOF = -1,
}
pub(crate) async fn write_message<T: Message>(stream: &mut Sock, msg: &T) {
// ignore error, just as PostgreSQL.
msg.serialize(&mut stream.serbuf);
let _ = stream.s.write_all(&stream.serbuf).await;
... | Rust | 0 |
the type inferencer more
// information and helps to produce tighter bounds
// when necessary.
do indent {
do self.bnds(a.lb, b.ub).then {
do self.bnds(b.lb, a.ub).then {
do self.merge_bnd(a.ub, b.ub, |x, y| x.glb(self, y) ).chain |ub| {
do self.merge_bnd(a.lb, b... | Rust | 0 |
ion<unsafe extern "C" fn()>,
pub _gtk_reserved3: Option<unsafe extern "C" fn()>,
pub _gtk_reserved4: Option<unsafe extern "C" fn()>,
}
impl ::std::fmt::Debug for GtkIMMulticontextClass {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
f.debug_struct(&format!("GtkIMMulticontextC... | Rust | 0 |
import logging
import unittest
from slack_sdk import WebClient
from slack_sdk.web import base_client
from tests.helpers import create_copy
from tests.mock_web_api_server import cleanup_mock_web_api_server, setup_mock_web_api_server
from tests.slack_sdk.web.mock_web_api_handler import MockHandler
class TestWebClientL... | Python | 1 |
0]][lirpa_model.input_name[0]]['uA'], A_dict[lirpa_model.output_name[0]][lirpa_model.input_name[0]]['ubias']
print(f'lower bound linear coefficients size (batch, output_dim, *input_dims): {list(lower_A.size())}')
print(f'lower bound linear coefficients norm (smaller is better): {lower_A.norm()}')
print(f'lo... | Python | 1 |
import pyblish.api
class ValidateWorkfileData(pyblish.api.ContextPlugin):
"""Validate mark in and out are enabled and it's duration.
Mark In/Out does not have to match frameStart and frameEnd but duration is
important.
"""
label = "Validate Workfile Data"
order = pyblish.api.ValidatorOrder
... | Python | 1 |
miner = MinerActor::<C, TxPoolService, ChainActorRef<C>, Storage>::launch(
config.clone(),
bus.clone(),
storage.clone(),
txpool.get_service(),
chain.clone(),
default_account,
)?;
let miner_client = if config.miner.enable_miner_client {
Some(MinerClientAct... | Rust | 0 |
validation_circle_icon(self):
check_circle = self.locator.get_by_label("check-circle")
close_circle = self.locator.get_by_label("close-circle")
expect(check_circle.or_(close_circle)).to_be_visible()
return check_circle if check_circle.is_visible() else close_circle
@property
def... | Python | 1 |
{}", heading),
},
_ => panic!(),
}
}
dbg!(north, east, heading);
dbg!(north.abs() + east.abs());
let mut north = 0;
let mut east = 0;
let mut heading = (10, 1);
for (i, n) in instructions {
match i {
'N' => heading.1 = heading.1 + n,
... | Rust | 0 |
# s = int(input("Enter The Number Of Rows:"))
# for i in range( 1 , s+1 ):
# for j in range(i):
# print("*" , end = "")
# print()
s = int(input("Enter The Number Of Rows:"))
for i in range(s ,0 , -1 ):
for j in range(i , 0 , -1):
print("*" , end = "")
print()
| Python | 1 |
weight(10_000)]
pub fn submit_challenge_prove(
origin: OriginFor<T>,
miner_id: u64,
file_id: Vec<u8>,
mu: Vec<Vec<u8>>,
sigma: Vec<u8>
) -> DispatchResult {
let _sender = ensure_signed(origin)?;
let acc = Self::get_current_scheduler();
let challenge_list = Self::challenge_map... | Rust | 0 |
ling))
else:
ctrl_cost = 0
if self.contact_cost_coeff > 0:
contact_cost = 0.5 * self.contact_cost_coeff * np.sum(
np.square(np.clip(self.model.data.cfrc_ext, -1, 1))),
else:
contact_cost = 0
reward = (goal_reward + velocity_reward + s... | Python | 1 |
sitor.visit_import(&*import_stmt, &mut *arena, &mut *env)?)
}
}
}
<reponame>jiegec/RustOS
extern crate cc;
use std::fs::File;
use std::io::{Result, Write};
use std::path::Path;
fn main() {
if let Ok(file_path) = gen_payload_asm() {
cc::Build::new().file(&file_path).compile("payload");
}
}
... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: latin-1 -*-
#
# Copyright 2009-2022 Ghent University
#
# This file is part of logstash-patterns,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (http... | Python | 1 |
snd_timer_status_copy(dst: *mut snd_timer_status_t, src: *const snd_timer_status_t);
}
extern "C" {
pub fn snd_timer_status_get_timestamp(status: *mut snd_timer_status_t) -> snd_htimestamp_t;
}
extern "C" {
pub fn snd_timer_status_get_resolution(
status: *mut snd_timer_status_t,
) -> ::std::os::raw:... | Rust | 0 |
lt = value as i128;
}
"#;
assert!(crate::semantic::tests::compile_entry(input).is_ok());
}
#[test]
fn ok_integer_unsigned_to_field() {
let input = r#"
fn main() {
let value: u64 = 0;
let result = value as field;
}
"#;
assert!(crate::semantic::tests::compile_entry(input).is_ok());
}
#[test]
fn ok... | Rust | 0 |
<"
join_ts!(0..nbr_elements, i,
"<" Mi(i) "as" cm.fuzzcheck_traits_Mutator "<" Ti(i) "> >::RecursingPartIndex "
, separator: ",")
">;
#[doc(hidden)]
type ArbitraryStep = ();
#[doc(hidden)]
type UnmutateToken = UnmutateToken <"
... | Rust | 0 |
st_series_non_zero_index(self):
# GH 19020
data = {
0: {"id": 1, "name": "Foo", "elements": {"a": 1}},
1: {"id": 2, "name": "Bar", "elements": {"b": 2}},
2: {"id": 3, "name": "Baz", "elements": {"c": 3}},
}
s = Series(data)
s.index = [1, 2, 3]
... | Python | 1 |
import sys
from database import init_db, SessionLocal
from models import Tasa, UsdtCache
import bcv_scraper
def test_scraping():
"""Prueba el scraping directo del BCV. / Test direct BCV scraping."""
print("\n--- Scraping BCV --- / --- BCV Scraping ---")
tasas = bcv_scraper.obtener_tasas_bcv()
print("Ta... | Python | 1 |
nodes = Vec::new();
let tree = parse_tree(input, &mut nodes);
let node = find_explodable_node(tree.root, &nodes);
assert!(matches!(node, Some(..)), "input: {}", input);
explode_node(node.unwrap(), &mut nodes);
assert_eq!(
node_to_string(tree.root, &nodes),
... | Rust | 0 |
from torch import nn
from torchvision.models import ViT_B_16_Weights, vit_b_16
class Net(nn.Module):
"""Neural network model for human perception prediction using Vision Transformer.
This model was developed by Ouyan (2023) and uses a pre-trained ViT-B-16 backbone
with custom classification head for pred... | Python | 1 |
}
}
#[test]
fn test_count_min_sketch_estimate() {
let mut s = CountMinSketch::new(16).unwrap();
s.increment(1);
s.increment(1);
assert_eq!(s.estimate(1), 2);
assert_eq!(s.estimate(0), 0);
}
#[test]
fn test_count_min_sketch_reset() {
let mut s ... | Rust | 0 |
_size - size;
} else {
return Ok(MutationResult::Skipped);
}
}
input.bytes_mut().resize(size + len, 0);
buffer_self_copy(input.bytes_mut(), off, off + len, size - off);
buffer_copy(input.bytes_mut(), token, 0, off, len);
Ok(MutationResult... | Rust | 0 |
).finish()
}
let res = thread::spawn(move || {
csml_engine::delete_client_memories(&client)
}).join().unwrap();
match res {
Ok(_) => HttpResponse::NoContent().finish(),
Err(err) => {
eprintln!("EngineError: {:?}", err);
HttpResponse::InternalServerError(... | Rust | 0 |
ProtectionResult,
"PromptTokensDetails": PromptTokensDetails,
"RerankTextDetails": RerankTextDetails,
"RerankTextResult": RerankTextResult,
"ResponseFormat": ResponseFormat,
"ResponseJsonSchema": ResponseJsonSchema,
"SearchEntryPoint": SearchEntryPoint,
"SearchQuery": SearchQuery,
"Servi... | Python | 1 |
ld()
self.assertAllClose(u[0] * np.ones(X.get_shape(0)),
5*p*np.ones((10,1)))
pass
def test_lower_bound(self):
r"""
Test lower bound for multinomial node.
"""
# Test for a bug found in multinomial
X = Multinomial(10, [0.3, 0.5, ... | Python | 1 |
import os
Import("env")
# XXX __file__ does not work here.
dir_path = Dir('.').abspath
src_filter = []
env.Replace(SRC_FILTER=src_filter)
src_defined = False
if 'BUILD_FLAGS' in env:
build_flags = env.ParseFlags(env['BUILD_FLAGS'])
cppdefines = build_flags.get("CPPDEFINES")
if "LIGHT_WS2812_AVR" in cppde... | Python | 1 |
the target mask. Use fancy indexing
self.idc: List[int] = kwargs["idc"]
print(f"Initialized {self.__class__.__name__} with {kwargs}")
def __call__(self, probs: Tensor, target: Tensor) -> Tensor:
assert simplex(probs)
assert simplex(target)
assert probs.shape == target.shape... | Python | 1 |
end of store_complex.i64 (I64)
// 000147: symbol_value.i64 (I64)
// skip 2 unless PredicateView(16)
0x3035,
// --> [RexOp1gvaddr8#80b8]
0x0270, 0x80b8,
// skip 3 unless PredicateView(14)
0x4033,
// skip 2 unless inst_predicate_35
0x3023,
// --> [RexOp1pcrel_gvaddr8#808d]
0x0... | Rust | 0 |
import pygame
import time
delay = 20 # 搜索动画延迟
def dfs_search(maze, start, end, win, CELL_WIDTH, CELL_HEIGHT, ROWS, COLS, offset_x=0):
stack = [(start, [start])]
visited = set()
search_visited = []
final_path = None
current_pos = start
total_steps = 0 # 总步数计数器
while stack:
fo... | Python | 1 |
from .dartel3 import dartel3
from .optimN import optimN
from .optimNn import optimNn
from .optim_compat import optim_compat
from .spm_dartel_dotprods import spm_dartel_dotprods
from .spm_dartel_import import spm_dartel_import
from .spm_dartel_invnorm import spm_dartel_invnorm
from .spm_dartel_jacobian import spm_dartel... | Python | 1 |
ENT3IN_SEL_W { w: self }
}
#[doc = "Bit 26 - ENET2 input timer event3 source select"]
#[inline(always)]
pub fn enet2_event3in_sel(&mut self) -> ENET2_EVENT3IN_SEL_W {
ENET2_EVENT3IN_SEL_W { w: self }
}
#[doc = "Bit 28 - GPT1 1 MHz clock source select"]
#[inline(always)]
pub fn vr... | Rust | 0 |
p.zeros((11700,241))
for item in alloc_out:
row, col, value = map(float, item.split('[')[1].split(']')[0].split(',') + [item.split('=')[1]])
x_vals[int(row)][int(col)] = value
if value:
pos.append(int(row))
data_list = optp
product_number = []
allocs_str = []
for data_str in data_list:
product... | Python | 1 |
///
/// This information corresponds to the `sin6_flowinfo` field in C's `netinet/in.h`,
/// as specified in [IETF RFC 2553, Section 3.3].
/// It combines information about the flow label and the traffic class as specified
/// in [IETF RFC 2460], respectively [Section 6] and [Section 7].
///
/... | Rust | 0 |
zeros(3, 3, device="meta"),
offsets=torch.zeros(3, device="meta", dtype=torch.int64),
).detach()
return _dummy_instance
def nested_view_from_values_offsets(
values, offsets, ragged_idx=1, min_seqlen=None, max_seqlen=None
):
min_seqlen_tensor = None
if min_seqlen is not None:
... | Python | 1 |
_SFLOAT
| VkFormat::R16G16_UNORM
| VkFormat::R16G16_SNORM
| VkFormat::R16G16_UINT
| VkFormat::R16G16_SINT
| VkFormat::R16G16_SFLOAT
| VkFormat::R16G16B16_UNORM
| VkFormat::R16G16B16_SNORM
| VkFormat::R16G16B16_UINT
| VkFormat::R16G16B16_SINT
... | Rust | 0 |
hrase_cnt[phrase] += 1
else:
cur_cnt = 0
phrase_cnt[phrase] = 1
res.append(get_phrase_idx(tokenizer, phrase, prompt, num=cur_cnt)[0])
return res
def get_float(self, str_in):
list_str = str_in.split(",")
float_box = [float(x) for x ... | Python | 1 |
from __future__ import annotations
import hashlib
from functools import cached_property
from typing import Generator
import pandas as pd
from sdgx.data_connectors.base import DataConnector
class CsvConnector(DataConnector):
"""
Wraps csv file into :ref:`DataConnector`
Args:
path (str): Path to... | Python | 1 |
'''
裁判系统统合类
'''
import time
import numpy as np
from serial_package import offical_Judge_Handler, Game_data_define
import queue
from radar_class.config import enemy,BO
###### 采自官方demo ###########
ind = 0 # 发送id序号(0-4)
Id_red = 1
Id_blue = 101
buffercnt = 0
buffer = [0]
buffer *= 1000
cmdID = 0
indecode = 0
def Contro... | Python | 1 |
r",
"deepseek-v2",
"deepseek-lite"
]
logger.info(f"成功获取DeepSeek模型列表: {models}")
return models
else:
logger.error(f"DeepSeek获取模型列表失败: {response.status_code}, {response.text}")
... | Python | 1 |
iency maps for a batch of data using the given model.
Parameters:
- data: Tensor of shape (batch_size, channels, sequence_length), the input data.
- model: A PyTorch model that accepts `data` as input and outputs predictions.
Returns:
- saliency_maps: Tensor of shape (batch_size, sequence_length),... | Python | 1 |
a BCP-47 language tag.
pub language_code: String,
/// Preferred voice gender.
pub gender: Option<SynthesisVoiceGender>,
/// Speaking rate/speed.
///
/// Interpretation of this value is up to speech synthesis provider.
pub speaking_rate: Option<f64>,
/// Speaking pitch.
///
//... | Rust | 0 |
criptorProto {
::protobuf::Message::parse_from_bytes(file_descriptor_proto_data).unwrap()
}
pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {
file_descriptor_proto_lazy.get(|| {
parse_descriptor_proto()
})
}
use anyhow::{ensure, Result};
use bitvec_helpers::{b... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.