text string | label_name string | labels int64 |
|---|---|---|
);
let end = points.next().unwrap();
let mut parts = end.split(',');
let x: usize = parts.next().unwrap().parse().unwrap();
let y: usize = parts.next().unwrap().parse().unwrap();
let end = Point::new(x, y);
LineSegment::new(start, end)
}
fn get_max_x_coord(line_segments: &[LineSegment]) -> us... | Rust | 0 |
D BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPEC... | Rust | 0 |
cross_2() {
let a = Matrix::from([[2f64, 3f64, 4f64]]);
let b = Matrix::from([[5f64, 6f64, 7f64]]);
let c = a.cross(&b);
assert_matrix_approx_eq_float(&c, &Matrix::from([[-3f64, 6f64, -3f64]]), 1e-7);
// assert_eq!(c, Matrix::from([[-3f64, 6f64, -3f64]]));
}
#[test]
fn test_cross_3() {
let a = ... | Rust | 0 |
from PIL import Image, ImageDraw
class Punto:
def __init__(self, x, y):
self.x = x
self.y = y
class Poligono:
def __init__(self, puntos, color):
self.puntos = puntos # Lista de objetos Punto
self.color = color # Color en tupla RGB (por ejemplo: (255, 0, 0))
def dibuja... | Python | 1 |
conversion to nano seconds
pub fn to_nsec(&self) -> i32 {
let cuc_time_fine = ((self.t_fine0 as u64) * 0x010000_u64) +
((self.t_fine1 as u64) * 0x000100_u64) +
((self.t_fine2 as u64) * 0x000001_u64);
((cuc_time_fine as f64) * CUCFINE3_TO_NSEC)... | Rust | 0 |
"""Tests the merge cell api."""
INITIAL_CELLS = [
"foo = 5",
"bar = 10",
"baz = 15",
"print(foo)",
"print(bar)",
"print(baz)",
]
def test_merge_cells(prefill_notebook):
notebook = prefill_notebook(INITIAL_CELLS)
a, b, c, d, e, f = INITIAL_CELLS
# Before merging, there are 6 separa... | Python | 1 |
agent_initial_pubkey: agent_pubkey.clone(),
agent_latest_pubkey: agent_pubkey,
}))
}
#[cfg(test)]
#[cfg(feature = "slow_tests")]
pub mod test {
use crate::fixt::ZomeCallHostAccessFixturator;
use ::fixt::prelude::*;
use holochain_types::test_utils::fake_agent_pubkey_1;
use holochain_w... | Rust | 0 |
if len(history) > 0:
motion_history = motion_frame/(len(history)+1)
else:
motion_history = motion_frame
for newframe in history:
motion_history += newframe/(len(history)+1)
# or however long history you would l... | Python | 1 |
FIXME: 512-bit wide).
}
simd_i_ty! {
i32x16: 16, i32, m1x16, i32x16_tests, test_v512 |
i32, i32, i32, i32, i32, i32, i32, i32,
i32, i32, i32, i32, i32, i32, i32, i32 |
x0, x1, x2, x3, x4, x5, x6, x7,
x8, x9, x10, x11, x12, x13, x14, x15 |
/// A 512-bit vector with 16 `i32` lanes.
}
simd_u_ty! ... | Rust | 0 |
_sys as ffi;
use thiserror::Error;
use crate::api::API;
use crate::component::Component;
use crate::core::CoreRef;
use crate::format::Format;
use crate::map::{MapRef, MapRefMut};
use crate::video_info::Resolution;
/// An error indicating that the frame data has non-zero padding.
#[derive(Error, Debug, Clone, Copy, E... | Rust | 0 |
cases {
let actual = match Part::parse_lit2(Literal::string(template)) {
Ok(template) => template,
Err(e) => panic!("failed to parse {:?}: {}", template, e),
};
assert_eq!(
format!("{:?}", expected),
format!("{:?}", ac... | Rust | 0 |
c,0x5c,0x5c,0x5c,0x5c,],
pt: [0x5c,0x5c,0x5c,0x5c,0x5c,0x5c,0x5c,0x5c,0x5c,0x5c,0x5c,0x5c,0x5c,0x5c,0x5c,0x5c,],
ct: [0x28,0x54,0x74,0x9b,0x66,0xb3,0x23,0xdf,0x05,0x6b,0x06,0x57,0xc9,0x0e,0x89,0x19,]
},
Aes128Test {
key: [0x5d,0x5d,0x5d,0x5d,0x5d,0x5d,0x5d,0x5d,0x5d,0x5d,0x5d,0x5d,0x5d,0... | Rust | 0 |
guage governing permissions and
* limitations under the License.
*/
//! This file contains code for interfacing with souffle (a dialect and
//! implementation of Datalog).
use std::fs;
use std::process::Command;
use crate::{
ast::*,
parsing::astconstructionvisitor,
souffle::{lowering_ast_datalog::*, sou... | Rust | 0 |
from micropython import const
from machine import Pin, ADC
from utime import sleep_ms
from rp2 import PIO, asm_pio, StateMachine
import dht
DAT_pin = const(16)
CLK_pin = const(17)
seg = 0
value_1 = 1234
value_2 = 5678
seg_code_list = [
0x03, # 0
0x9F, # 1
0x25, # 2
0x0D, # 3
0x99, # 4
... | Python | 1 |
nager the user event manager.
*/
unsafe extern "C" fn opj_j2k_read_qcd(
mut p_j2k: *mut opj_j2k_t,
mut p_header_data: *mut OPJ_BYTE,
mut p_header_size: OPJ_UINT32,
mut p_manager: *mut opj_event_mgr_t,
) -> OPJ_BOOL {
/* preconditions */
assert!(!p_header_data.is_null());
assert!(!p_j2k.is_n... | Rust | 0 |
let loaded_library = result.unwrap();
PluginLibrary::load_symbols(loaded_library, lib_full_path)
}
fn load_symbols(
loaded_library: libloading::Library,
path: &str,
) -> Result<PluginLibrary, MinerError> {
unsafe {
let ret_val = PluginLibrary {
lib_full_path: String::from(path),
cuckoo_create_s... | Rust | 0 |
import ctypes
import platform
import sys
import traceback
import qdarkstyle
from PyQt5 import QtGui, QtWidgets, QtCore
from .mainwindow import MainWindow
from ..setting import SETTINGS
from ..utility import get_icon_path
def excepthook(exctype, value, tb):
"""
Raise exception under debug mode, otherwise
... | Python | 1 |
x
@ct.lattice
def workflow(x):
res = g(x)
return res**2
workflow.build_graph(2)
mock_electron_get_op_function.assert_called_with(ANY, 2, "**")
@pytest.mark.parametrize(
"module_inputs",
[
"isort",
isort,
ct.DepsModule("isort"),
["isort", "fla... | Python | 1 |
l_analysis(
output_folder, [input_file_path], schema, features)
stats = json.loads(
file_io.read_file_to_string(
os.path.join(output_folder, analyze.constant.STATS_FILE)).decode())
self.assertEqual(stats['column_stats']['color']['vocab_size'], 3)
# Color column.
... | Python | 1 |
println!("Bitte gib eine gültige ID an.");
return None;
}
return Some(id);
},
_ => {
println!("Bitte gib eine gültige ID an.");
None
}
};
}
fn abfrage_entscheidung(entscheidung: &mut String) {
*entscheidung... | Rust | 0 |
print(format_exc())
else:
loader: Optional[Loader] = spec.loader
if not isinstance(loader, ExecutionLoader):
# If failed to get data from loader then just print entire traceback
print(format_exc())
return
# TODO: Fix re... | Python | 1 |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | Python | 1 |
append(reg_model)
model_ver = reg_model.create_version()
model_ver.log_model(LogisticRegression(), custom_modules=[])
model_ver.log_environment(Python(["scikit-learn"]))
with pytest.raises(requests.HTTPError, match="^403 Client Error: Forbidden"):
endpoint.update(model_ver)
... | Python | 1 |
"""
生产环境配置
"""
import os
from .settings import *
# 安全设置
DEBUG = False
SECRET_KEY = os.environ.get('SECRET_KEY')
# 允许的主机
ALLOWED_HOSTS = [
'localhost',
'127.0.0.1',
'.railway.app',
'.vercel.app',
'.netlify.app',
]
# 数据库配置 (Railway MySQL)
DATABASES = {
'default': {
'ENGINE': 'django.db.... | Python | 1 |
import json
import pytest
from indy import ledger, did, error
from tests.ledger.test_submit_request import ensure_previous_request_applied
@pytest.mark.asyncio
async def test_build_nym_request_works_for_invalid_identifier():
identifier = "invalid_base58_identifier"
dest = "FYmoFw55GeQH7SRFa37dkx1d2dZ3zUF8ck... | Python | 1 |
finish_reason_to_finish_type("stop"), "success")
# Scenario 2: Anthropic-style response through LangChain
anthropic_style_response = SimpleNamespace(
response_metadata={
"usage": {"input_tokens": 10, "output_tokens": 20},
"model": "claude-3-sonnet",
... | Python | 1 |
,
len(builder.special_actions)])
initial_carry = (initial_step_state, initial_step_special)
_, (scan_states, scan_specials) = jax.lax.scan(
step, initial_carry, None, length=steps - 1)
in_tagged_states = jnp.concatenate([initial_step_state[None], scan_states],
ax... | Python | 1 |
ol>>,
/// Caches whether traits are object safe
pub object_safety_cache: RefCell<DefIdMap<bool>>,
/// Maps Expr NodeId's to their constant qualification.
pub const_qualif_map: RefCell<NodeMap<check_const::ConstQualif>>,
}
// Flags that we track on types. These flags are propagated upwards
// through ... | Rust | 0 |
information used to process some portion of the content. (optional)
pub technique: Vec<Technique>,
}
impl Source {
/// Construct a new `Source` given an inline array and access information.
pub fn new_local(
id: impl Into<String>,
param: Vec<Param>,
array: impl Into<ArrayElement>,
... | Rust | 0 |
eck_for_updates)
self.refresh_mirrors_button = QPushButton("刷新镜像源")
self.refresh_mirrors_button.setStyleSheet("""
QPushButton {
border-radius: 8px;
padding: 8px;
min-width: 100px;
background-color: #2196F3;
col... | Python | 1 |
a.cpu().numpy()
vox_actors = []
aabb = torch.tensor([[-1,-1,-1], [1,1,1]], dtype=torch.float, device=device)
spacing = ((aabb[1]-aabb[0]) / occ.resolution).tolist()
for i, occ_val_grid in enumerate(batched_val_grid):
origin = (aabb[0] + torch.tensor([2. * i, 0., 0.], device=d... | Python | 1 |
import collections
import numpy
class Summary(object):
def __init__(self):
self. header = ["variant", "sample","allele", "key","value"]
self.stats = []
def addVariantResults(self, dataHub):
variant = str(dataHub.variant)
for sampleName, sample in dataHub.samples.items():
... | Python | 1 |
, 0x03],
vec![0x44, 0x01, 0x02, 0x03],
vec![0x65, 0x49, 0x45, 0x54, 0x46],
vec![0x82, 0x02],
vec![0xA2, 0x61, 0x61, 0x01],
vec![0x18],
vec![0x99],
vec![0xBA],
vec![0x5B],
vec![0x3B],
vec![0x99, 0x01],... | Rust | 0 |
_display_name: &str = "MAKE_close_child_window_display_name";
#[derive(Serialize, Deserialize, Debug)]
pub struct close_child_window_display {
#[serde(rename = "type")]
pub type_:String,
pub parent:String,
pub sender:String,
pub window:String,
}
pub const SetFocusedWindow_name: &str = "MAKE_SetFocus... | Rust | 0 |
Instant Exchange of CryptoMarket.
///
pub async fn get_order_instant(
&self,
order_type: OrderType,
amount: f32,
) -> CryptoMktResult<OrdersInstant> {
let mut params = HashMap::new();
params.insert("market".to_string(), self.name.clone());
params.insert("amou... | Rust | 0 |
import json
# Define file paths
trophies_file = "out/trophies.json"
trophies_extracted_file = "out/trophies_extracted.json"
output_file = "out/trophies_codes.json"
# Function to match trophies and add the code
def add_trophy_code():
# Read the trophies data from trophies.json
with open(trophies_file, "r") as... | Python | 1 |
from odoo import models
class AccountMoveReversal(models.TransientModel):
_inherit = 'account.move.reversal'
def reverse_moves(self, is_modify=False):
action = super().reverse_moves(is_modify=is_modify)
if is_modify:
# In Hungary, if we do `Reverse and Create Invoice`, the new inv... | Python | 1 |
Y_ARRAY_CAPACITY: NonZeroUsize = unsafe { NonZeroUsize::new_unchecked(CHUNK_SIZE * 4) };
pub(crate) const TOPOLOGY_BUFFER_SIZE: NonZeroUsize = unsafe { NonZeroUsize::new_unchecked(100) };
static TRANSFORM_CONCURRENCY_LIMIT: Lazy<usize> = Lazy::new(|| {
crate::app::WORKER_THREADS
.get()
.map(std::nu... | Rust | 0 |
= pheader.p_offset as usize;
let size = pheader.p_filesz as usize;
if start + size > data.len() {
return Err(Error::FormatError("Invalid program header".into()));
}
let padded_size = (pheader.p_filesz as usize + 3) & !3;
let mut seg_data: Vec<u8> = Vec::with_capacity... | Rust | 0 |
ern "C" fn cuCtxGetApiVersion(
ctx: CUcontext,
version: *mut ::std::os::raw::c_uint,
) -> CUresult {
r#impl::context::get_api_version(ctx.decuda(), version).encuda()
}
#[cfg_attr(not(test), no_mangle)]
pub extern "C" fn cuCtxGetStreamPriorityRange(
leastPriority: *mut ::std::os::raw::c_int,
greates... | Rust | 0 |
#[derive(Debug, StructOpt)]
#[structopt(rename_all = "kebab-case")]
enum Command {
Copy { path: Option<PathBuf> },
Render { path: Option<PathBuf> },
View { path: PathBuf },
}
#[async_std::main]
async fn main() -> tide::Result<()> {
log::set_logger(&logger::CONSOLE_LOGGER).unwrap_or_default();
log:... | Rust | 0 |
self.sanity_check instead?
try:
import docker # noqa: PLC0415
except ImportError:
return
client = docker.from_env()
for c in client.containers.list(filters={"label": "owner=molecule"}):
log.info("Stopping docker container %s ...", c.id)
c... | Python | 1 |
);
info!("BTLEPlug scanning finished.");
if device_sender
.send(DeviceCommunicationEvent::ScanningFinished)
.await
.is_err()
{
error!("Error sending scanning finished from btleplug.");
}
tried_addresses_handler.clear();
info!("Exiti... | Rust | 0 |
.. math::
Z_n^m(\theta, \varphi) :=
\begin{cases}
\frac{Y_n^m(\theta, \varphi) + \overline{Y_n^m(\theta, \varphi)}}{\sqrt{2}} &\quad m > 0 \\
Y_n^m(\theta, \varphi) &\quad m = 0 \\
\frac{Y_n^m(\theta, \varphi) - \overline{Y_n^m(\theta, \varphi)}}{i \sqrt{2}} &\quad m <... | Python | 1 |
x57, 0b11_001_010], "vxorpd xmm1, xmm0, xmm2");
test_instr(&[0xc4, 0b110_00001, 0b1_0111_101, 0x57, 0b11_001_010], "vxorpd ymm1, ymm0, ymm2");
test_instr(&[0xc4, 0b110_00001, 0b1_0111_000, 0x58, 0b11_001_010], "vaddps xmm1, xmm0, xmm2");
test_instr(&[0xc4, 0b110_00001, 0b1_0111_100, 0x58, 0b11_001_010], "va... | Rust | 0 |
poll_id, tallied_quorum);
}
}
use intbits::Bits;
use crate::bus::{Bus, BusAlignedExt};
use super::{
reg::{LR_INDEX, PC_INDEX, SP_INDEX},
Cpu, OperationState,
};
#[allow(clippy::cast_sign_loss, clippy::cast_possible_wrap)]
fn execute_add_impl(cpu: &mut Cpu, update_cond: bool, a: u32, b: u32, c: u32) -> u3... | Rust | 0 |
y.deepcopy(measurements_dict)
while self.setting_i2c:
time.sleep(0.1)
self.sensor.start_ranging()
self.sensor.clear_interrupt()
distance = self.sensor.distance * 10 # convert cm to to mm
self.logger.debug(f"Timing Budget: {self.sensor.timing_budget} ms")
... | Python | 1 |
class Solution:
def numberOfAlternatingGroups(self, colors, k):
length = len(colors)
result = 0
# Tracks the length of the current alternating sequence
alternating_elements_count = 1
last_color = colors[0]
# First pass through the array
for index in range(1, ... | Python | 1 |
ef _encode_message(self, event: LogEventField,
message: Union[str, dict],
call_info: Tuple[str, int]) -> str:
if isinstance(message, str):
message ={LogKeys.other_message: message}
message = OrderedDict({
LogKeys.event: event.name,
... | Python | 1 |
.node.is_pub();
}
Node::TraitItem(..) => {
return true;
}
_ => {
debug!("def_id is not an item {:?}", node);
return false;
}
}
} else {
debug!("def_id is not local {}", summary_key_str(tcx, de... | Rust | 0 |
from openai import OpenAI
from together import Together
class GPT:
def __init__(self, model, system_prompt):
self.client = OpenAI()
self.model = model
self.system_prompt = system_prompt
if self.system_prompt == "":
self.messages = []
else:
self.messag... | Python | 1 |
import multiprocessing
max_requests = 1000
max_requests_jitter = 50
log_file = "-"
bind = "0.0.0.0"
timeout = 230
# https://learn.microsoft.com/en-us/troubleshoot/azure/app-service/web-apps-performance-faqs#why-does-my-request-time-out-after-230-seconds
num_cpus = multiprocessing.cpu_count()
workers = (num_cpus * 2)... | Python | 1 |
a = int (input("Enter the number 1: "))
b = int (input ("Enter the number 2: "))
print(a>=b)
| Python | 1 |
"""Airflow Imports"""
from airflow.plugins_manager import AirflowPlugin
from airflow_powerbi_plugin.hooks.powerbi import PowerBIHook
from airflow_powerbi_plugin.operators.powerbi import PowerBILink
# Defining the plugin class
class AirflowExtraLinkPlugin(AirflowPlugin):
"""
PowerBI plugin.
"""
name =... | Python | 1 |
import numpy as np
from collections import Iterable
from scipy.ndimage.filters import gaussian_filter
from .base import BatchAttack
from .base import generator_decorator
class GaussianBlurAttack(BatchAttack):
"""Blurs the input until it is misclassified."""
@generator_decorator
def as_generator(self, a... | Python | 1 |
Handler<TownWorkerEventMsg> for TownWorker {
type Result = ();
fn handle(&mut self, msg: TownWorkerEventMsg, _ctx: &mut Context<Self>) {
self.event_queue.add_event(msg.0, msg.1);
}
}
use register::mmio::*;
#[allow(non_snake_case)]
#[repr(C)]
pub struct MiscPP {
reserved0: [u8; 0x8], ... | Rust | 0 |
_variables(user_id, platform))
.await
.map(|response| response.platform_id())
}
}
impl ResponseData {
/// The id associated with a given RCOS user for a given platform (as specified
/// in the query).
fn platform_id(self) -> Option<String> {
Some(self.user_accounts_by_pk... | Rust | 0 |
domika",
chip="it8xxx2/it81302bx",
)
teliks = register_nissa_project(
project_name="teliks",
chip="it8xxx2/it81302bx",
)
telith = register_nissa_project(
project_name="telith",
chip="it8xxx2/it81302bx",
)
register_ish_project(
project_name="orisa-ish",
zephyr_board="intel_ish_5_4_1",
... | Python | 1 |
POW[i] == 0 {
i += 1;
c += 1;
}
c
}
/// `add` adds a and b and carry, stores the sum and new carry.
fn add(a: u32, b: u32, carry: &mut u32, res: &mut u32) {
let sum = a + b + *carry;
if sum >= WORD_BASE {
*res = sum - WORD_BASE;
*carry = 1;
} else {
*res = su... | Rust | 0 |
) == BrotliEncoderParameter::BROTLI_PARAM_LGBLOCK as (i32) {
params.lgblock = value as (i32);
return 1i32;
}
if p as (i32) == BrotliEncoderParameter::BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING as (i32) {
if value != 0u32 && (value != 1u32) {
return 0i32;
}
params.disable_literal_context... | Rust | 0 |
i::rocksdb_t> + super::Write,
{
fn merge_cf_full<K, V>(
&self,
cf: Option<&ColumnFamily>,
key: K,
value: V,
writeopts: Option<&WriteOptions>,
) -> Result<(), Error>
where
K: AsRef<[u8]>,
V: AsRef<[u8]>,
{
let mut default_writeopts = None;
... | Rust | 0 |
class Solution:
def takeCharacters(self, s: str, k: int) -> int:
# https://leetcode.com/problems/take-k-of-each-character-from-left-and-right/?envType=daily-question&envId=2024-11-20
# O(n)
if k == 0: return 0
left = -1
right = len(s) - 1
freq = {'a':0, 'b':0, 'c':0... | Python | 1 |
t out.iter_mut() {
*c = match *c {
b'(' => b'C',
b'{' => b'F',
b')' => b'7',
b'}' => b'3',
_ => *c,
}
}
String::from_utf8(out).unwrap()
}
fn align_of(t: &GVariantType) -> usize {
match t {
GVariantType::B | GVariantType::Y ... | Rust | 0 |
dx
# We use SparseTensor for this, which codes the triplets (row_idx, col_idx, value)
# Here we define the triplet as (base_idx, the_original_node_sending_to_this, lifted_idx)
# In particular the combination base_idx -> lifted_idx is going to be useful to lookup which
# lifted nodes are ... | Python | 1 |
-> Vec<Schedule> {
let date_as_str = date_to_tempo_format(date);
let params = format!("from={}&to={}", &date_as_str, &date_as_str);
self.client
.get::<ListSchedulesResponse>(format!("user-schedule?{}", params).as_str())
.await
.results
}
pub async fn... | Rust | 0 |
from typing import Any, Callable, Optional, TypeVar, Union, cast
import reactivex
from reactivex import Observable, abc, typing
from reactivex.disposable import CompositeDisposable
_T = TypeVar("_T")
def sample_observable(
source: Observable[_T], sampler: Observable[Any]
) -> Observable[_T]:
def subscribe(
... | Python | 1 |
"Boston";
const _ORD: &str = "Chicago";
const _PHL: &str = "Philadelphia";
const _DCA: &str = "Washington, D.C.";
const _SAN: &str = "San Diego";
// PATH: 1 -> 3 -> 6 -> 5 COST: 20
// 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// DTW ATL IAH JFK SFO LAS MCO PHX MIA DEN LAX BOS OR... | Rust | 0 |
# coding=utf-8
import bcrypt
from flask_login import UserMixin
from mycodo.databases import CRUDMixin
from mycodo.databases import set_uuid
from mycodo.mycodo_flask.extensions import db
from mycodo.mycodo_flask.extensions import ma
class User(UserMixin, CRUDMixin, db.Model):
__tablename__ = "users"
__table_a... | Python | 1 |
}
}
}
Err(_) => false,
}
} else {
false
}
}
}
pub struct FileIterFactory {
options: Rc<ReadOptions>,
table_cache: Arc<TableCache>,
}
impl FileIterFactory {
pub fn new(options: Rc<ReadOpt... | Rust | 0 |
Some(Hertz(ref_x_ck * pll_x_n / dividers.$DD))
}
None => {
rcc.pllcfgr.modify(|_, w| w.$diven().disabled());
None
}
}... | Rust | 0 |
from Screens.Screen import Screen
from Components.config import config, ConfigSubsection, ConfigInteger
config.plugins.OSDPositionSetup = ConfigSubsection()
config.plugins.OSDPositionSetup.dst_left = ConfigInteger(default = 0)
config.plugins.OSDPositionSetup.dst_width = ConfigInteger(default = 720)
config.plugins.OSDP... | Python | 1 |
send(config, addr, b"world!").await?;
assert!(io.get_ref().1.is_early_data_accepted());
let stdout = handle.0.stdout.as_mut().unwrap();
let mut lines = BufReader::new(stdout).lines();
let has_msg1 = lines.by_ref().any(|line| line.unwrap().contains("hello"));
let has_msg2 = lines.by_ref().any(|line... | Rust | 0 |
::types::*;
/// Order of attributes is significant, we want this to translate to a specific
/// data layout in memory and use byte offsets when setting the vertex
/// attributes.
#[derive(Clone)]
pub struct Vertex {
pub position: [GLfloat; 3],
pub normal: [GLfloat; 3],
pub texcoords: [GLfloat; 2],
//pu... | Rust | 0 |
elta)
- (fov * 0.5 * (self.sensor.res().1 as f64 / self.sensor.res().0 as f64));
if let Some(super_sample_power) = self.sensor.super_sample_power() {
let sub_delta = delta / f64::from(super_sample_power);
let sx = f64::from(sub_sample % super_... | Rust | 0 |
>(&self, serializer: S) -> Result<S::Ok, S::Error> {
if serializer.is_human_readable() {
self.to_hex_string().serialize(serializer)
} else {
self.to_bytes_be().serialize(serializer)
}
}
}
#[cfg(feature = "serde")]
impl<'a> Deserialize<'a> for U256 {
fn deserializ... | Rust | 0 |
from transformers import AutoProcessor, BarkModel
import scipy
processor = AutoProcessor.from_pretrained("suno/bark")
model = BarkModel.from_pretrained("suno/bark")
voice_preset = "v2/en_speaker_6"
inputs = processor("Hello, my dog is cute", voice_preset=voice_preset)
audio_array = model.generate(**inputs)
audio_a... | Python | 1 |
Data,
}
}
pub(crate) fn set_baudrate<USIC>(
usic: &mut USIC,
scu: &mut Scu,
bps: Bps,
oversampling: u8,
) -> Result<(), ()>
where
USIC: Deref<Target = UsicRegisterBlock>,
{
// Pretty much the code from XMCLib
let peripheral_clock = scu.clocks.sysclk().0 / 100;
let mut clock_divider_... | Rust | 0 |
_MAC_TIMER_TX_MAC_TIMER_R {
TX_MAC_TIMER_TX_MAC_TIMER_R::new(((self.bits >> 8) & 0xff) as u8)
}
#[doc = "Bits 0:7 - Time to wait after the Rx mode."]
#[inline(always)]
pub fn rx_mac_timer_rx_mac_timer(&self) -> RX_MAC_TIMER_RX_MAC_TIMER_R {
RX_MAC_TIMER_RX_MAC_TIMER_R::new((self.bits & 0... | Rust | 0 |
early_dr = date_range(start=early_start, end=early_end, tz=tz, freq=MonthEnd())
late_dr = date_range(start=late_start, end=late_end, tz=tz, freq=MonthEnd())
early_dr.union(late_dr, sort=sort)
@td.skip_if_windows
def test_month_range_union_tz_dateutil(self, sort):
from pandas._libs... | Python | 1 |
import re
import unittest
import pyarabic.araby as araby
# ~ TOKEN_PATTERN_SPLIT = re.compile(u"([\w\u064b-\u0652']+)", re.UNICODE)
# ~ def tokenize_with_location(text: str) -> list:
# ~ """
# ~ Tokenize text into words with their positions.
# ~ Example:
# ~ >>> text = "حدثنا ابن أبي عامر، قال:... | Python | 1 |
import decimal
from datetime import date
import pytest
import edgy
from edgy.core.db import fields
from edgy.exceptions import FieldDefinitionError
from edgy.testclient import DatabaseTestClient
from tests.settings import DATABASE_URL
pytestmark = pytest.mark.anyio
database = DatabaseTestClient(DATABASE_URL)
models... | Python | 1 |
import pickle
import torch
import torch.nn.functional as F
import numpy as np
import argparse
import pandas as pd
import seaborn as sns
import matplotlib
matplotlib.use('AGG')
import matplotlib.pyplot as plt
from metric_utils import *
recall_level_default = 0.95
parser = argparse.ArgumentParser(description='Evaluate... | Python | 1 |
g = self.g(input)
else:
theta = input
phi = input
g = input
if self.nonlocal_type in ['gaussian', 'dot']:
# reshape [BxC'xTxHxW] to [BxC'x(T)HW]
theta = theta.reshape(theta.shape[:2] + (-1, ))
phi = phi.reshape(theta.shape[:2... | Python | 1 |
mass)")
# Multiply by (1 / (4 pi eps_0)) in a.u. (1 / (e^2 / a0 Eh)) to get to units of (Eh a0 / me)
conv_kmmol *= psi4.constants.conversion_factor("(e^2 * bohr^2)/(bohr^2 * atomic_unit_of_mass) * (1 / (e^2 / (bohr * hartree)))", "hartree * bohr / atomic_unit_of_mass")
# Multiply by (Na pi / 3 c^2) in a.u. (Na = mol^-1... | Python | 1 |
人走,夜晚更加寂寞。</voice>
<voice id="123">荷塘四面,长着许多树,蓊蓊郁郁的。</voice>
<voice id="124">路的一旁,是些杨柳,和一些不知道名字的树。</voice>
<voice id="125">没有月光的晚上,这路上阴森森的,有些怕人。</voice>
<voice id="126">今晚却很好,虽然月光也还是淡淡的。</voice><break time="2s"/>
<voice id="127">路上只我一个人,背着手踱着。</voice>
... | Python | 1 |
f.output[maps_dict.PRED_ANGLE_RES][index]
# decode predictions
pred_anchors_3d = self.encoder_decoder.decode(base_xyz, pred_offset, pred_angle_cls, pred_angle_res, self.is_training, anchors) # [bs, points_num, cls_num, 7]
# decode classification
if cfg.MODEL.FIRST_STAGE.CLS_ACT... | Python | 1 |
_or(&[&rb1, &rb2, &rb3]);
println!("{:?}", rb4);
}
#[cfg(test)]
fn cardinality_round(data: Vec<u32>) -> bool {
let original = Bitmap::of(&data);
let mut a = data.clone();
a.sort();
a.dedup();
a.len() == original.cardinality() as usize
}
#[test]
fn cardinality_roundtrip() {
QuickCheck::new... | Rust | 0 |
tWriteFile not found");
// Get `OUT_DIR` path.
let path = env::var("OUT_DIR").expect("Missing environment variable 'OUT_DIR'");
// Create file at `$OUT_DIR/syscall.rs`
let path = Path::new(&path).join("syscall.rs");
let mut syscall =
File::create(&path).unwrap_or_else(|_| panic!("Failed to o... | Rust | 0 |
k
else:
curr_start = last_curr_end
# Sleep for half a second every rate_limit requests to prevent rate limiting issues
if cnt % rate_limit == 0:
time.sleep(1)
# Catch if endless loop.
if cnt > 500:
break
... | Python | 1 |
if selected_library_match:
selected_tool = selected_library_match.group(1).strip()
if explanation_match:
explanation = explanation_match.group(1).strip()
# Validate against available tools
available_tools = set(registry.tools.keys())
if selected_tool and s... | Python | 1 |
: Vec<u8> = vec![];
let run_result = run_test(
"fuchsia-pkg://fuchsia.com/run_test_suite_integration_tests#meta/incomplete-test-example.cmx"
.to_string(),
&mut output,
)
.await
.expect("Running test should not fail");
let expected_output = "[RUNNING] Example.Test1
[R... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
Author: Guo Fei
Email: me@guofei.site
GitHub: https://github.com/guofei9987/text_blind_watermark
"""
import random
class TextBlindWatermarkDeprecated:
def __init__(self, password):
self.password = password
self.text, self.wm_bin = None, None
def read_wm(self, wate... | Python | 1 |
s = (global_ranks[i].0).0;
let g = (global_ranks[i].0).1;
let f = global_ranks[i].1;
self.species[s].mut_genomes()[g].set_global_rank(i as u32+1);
}
/*
for i in 0..self.species.len() {
for j in 0..self.species[i].genomes().len() {
println!("Rank: {} Fit: {}", self.species[i]... | Rust | 0 |
lementation can be found in the sections below.
//!
//! ### Installation
//!
//! #### GitHub Releases
//!
//! Binaries for Linux, macOS and Windows can be downloaded from GitHub
//! [Releases](https://github.com/anweiss/cddl/releases).
//!
//! #### Cargo
//!
//! ```sh
//! cargo install cddl
//! ```
//!
//! #### Docker
... | Rust | 0 |
ts = UnionFind::new(g.node_count());
for edge in g.raw_edges() {
let (a, b) = (edge.source(), edge.target());
// union the two vertices of the edge
// -- if they were already the same, then we have a cycle
if !edge_sets.union(a.index(), b.index()) {
return true
... | Rust | 0 |
# fileparse.py
import csv
def parse_csv(filename, select=None, types=None, has_headers=True, delimiter=','):
'''
Parse a CSV file into a list of records with type conversion.
'''
with open(filename) as f:
rows = csv.reader(f, delimiter=delimiter)
# Read the file headers (if any)
... | Python | 1 |
(blocks[0]
.parent_ptr()
.expect("genesis block cannot be reverted"))
}
}
pub struct FirehoseMapper {}
impl FirehoseMapperTrait<Chain> for FirehoseMapper {
fn to_block_stream_event(
&self,
_logger: &Logger,
response: &bstream::BlockResponseV2,
_adapter: ... | Rust | 0 |
import tkinter as tk
from tkinter import ttk
# window
window = tk.Tk()
window.title('Grid')
window.geometry('600x400')
# widgets
label1 = ttk.Label(window, text = 'Label 1', background = 'red')
label2 = ttk.Label(window, text = 'Label 2', background = 'blue')
label3 = ttk.Label(window, text = 'Label 3', background =... | Python | 1 |
_connect};
use tungstenite::handshake::{
HandshakeError, MidHandshake,
server::{ServerHandshake, NoCallback},
};
use tungstenite::error::{Error};
use url::Url;
use std::sync::{Mutex};
use std::net::{SocketAddr, TcpStream as StdTcpStream};
use std::io::{self, ErrorKind};
use std::ops::{DerefMut};
/// Max mess... | Rust | 0 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/api/servicecontrol/v1/metric_value.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf im... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.