text string | label_name string | labels int64 |
|---|---|---|
// modified faux xpub string that uses the regular p2pkh xpub version bytes it expects.
// TODO make extkeys seralize back to a string using their original version bytes
let version = &data[0..4];
let (network, script_type) = parse_xyz_version(version)?;
data.splice(0..4, get_xpub_... | Rust | 0 |
w,
decoy: Decoy,
model: ModuleModel,
) -> None:
"""It should raise if the labware is on a stacker module."""
decoy.when(mock_labware_view.get("labware-id")).then_return(
LoadedLabware(
id="labware-id",
loadName="test",
definitionUri="def-uri",
loca... | Python | 1 |
e.unwrap_or(0) + piece.base_price.unwrap_or(0),
PriceType::Tip => piece.tip_price.unwrap_or(0),
PriceType::Base => piece.base_price.unwrap_or(0),
};
Some(match op {
PriceOp::GreaterEqual => &value >= against,
PriceOp::LesserEqual =... | Rust | 0 |
.iter()
.filter_map(|bytes| TransactionPostCondition::from_bytes(bytes).ok())
.map(|condition| (condition.1).num_items())
.sum()
}
fn current_post_condition(&self) -> Result<TransactionPostCondition, ParserError> {
TransactionPostCondition::from_bytes(self.condi... | Rust | 0 |
_dict = None
if tool_result_dict is not None:
if "error" in tool_result_dict:
error_message = tool_result_dict['error']
raw_response_content = f"Error from tool '{tool_id}': {error_message}"
status = f"error: tool execution failed: {error_message}"
... | Python | 1 |
etrizineError> = $b;
log_any_error!(
context: $msg_arg,
res
);
Ok(())
}
};
}
use std::borrow::Cow;
use super::todo;
use crate::{
gc::Handle,
vm::value::{array::Array, function::CallContext, PropertyKey, Value, ValueKind},
};
/// T... | Rust | 0 |
= 0x0202;
#[allow(dead_code, non_upper_case_globals)] pub const EXTENSIONS: types::GLenum = 0x1F03;
#[allow(dead_code, non_upper_case_globals)] pub const FALSE: types::GLboolean = 0;
#[allow(dead_code, non_upper_case_globals)] pub const FASTEST: types::GLenum = 0x1101;
#[allow(dead_code, non_upper_case_globals)] pub co... | Rust | 0 |
ributes: Attributes,
) -> fmt::Result {
for attr in Attribute::iterator() {
if attributes.has(attr) {
write!(f, csi!("{}m"), attr.sgr())?;
}
}
Ok(())
}
pub(crate) const RESET_CSI_SEQUENCE: &str = csi!("0m");
impl fmt::Display for Colored {
fn fmt(&self, f: &mut Formatter<'_... | Rust | 0 |
s<'a> {
pub fn new(buffer: &'a[u8]) -> DedupBeads<'a> {
DedupBeads {
buffer
}
}
pub fn len(&self) -> Result<usize, String> {
let root = IndexedBeads::new(self.buffer)?;
let index_beads = FixedSizeBeads::new(root.get(0)?)?;
Ok(index_beads.len())
}
... | Rust | 0 |
from bokeh.core.properties import AngleSpec, BoolSpec, Include, NumberSpec
from bokeh.core.property_mixins import FillProps, HatchProps, LineProps
from bokeh.models.glyph import Glyph
class Gear(Glyph):
""" Render gears.
The details and nomenclature concerning gear construction can
be quite involved. For... | Python | 1 |
out_payload(
checkout_with_items, available_shipping_methods=methods
)
)
# then
assert len(json_payload["shipping_methods"]) == 3
assert json_payload["shipping_methods"][0]["id"] == graphene.Node.to_global_id(
"ShippingMethod", methods[0].id
)
assert json_payload["shi... | Python | 1 |
::new(&device, wgpu::TextureFormat::Rgba8UnormSrgb);
vger.begin(512.0, 512.0, 1.0);
let cyan = vger.color_paint(Color::CYAN);
vger.fill_circle([100.0, 100.0], 20.0, cyan);
render_test(&mut vger, &device, &queue, "circle.png", false);
}
#[test]
fn fill_circle_array() {
let (device, queue) = block_... | Rust | 0 |
ic']
inputs[('K_ori', 0)].append(K)
if self.is_train:
if self.opt.use_sfm_spatial:
pkl_path = os.path.join(os.path.join(self.match_path, cam_sample['filename'][:-4] + '.pkl'))
with open(pkl_path, 'rb') as f:
match_s... | Python | 1 |
.collect::<Vec<_>>();
tokens.append(quote! {
#[allow(dead_code)]
impl #name {
#(#[inline(always)] pub fn #function_names(&self) -> #variant_types {
if let &#getter_names::#variant_names(#(ref #tuple_args),*) = self {
(#(#tuple_args2.clo... | Rust | 0 |
import speech_recognition as sr
import pyttsx3
import threading
# Initialize text-to-speech engine globally
engine = pyttsx3.init()
def listen_for_command():
recognizer = sr.Recognizer()
microphone = sr.Microphone()
while True:
with microphone as source:
print("Listening for command..... | Python | 1 |
class Solution:
def rob(self, root: Optional[TreeNode]) -> int:
def robOrNot(root: Optional[TreeNode]) -> tuple:
if not root:
return (0, 0)
robLeft, notRobLeft = robOrNot(root.left)
robRight, notRobRight = robOrNot(root.right)
return (root.val + notRobLeft + notRobRight,
... | Python | 1 |
rr) = ctx.take_stdio().unwrap();
if ctx.env().get("LANG") != Some(&"C".into()) {
panic!()
}
async move {
assert_eq!("cat /proc/cpuinfo", prog.to_str().unwrap());
tokio::io::copy(&mut stdin, &mut stdout).await.unwrap();
stderr.write(b"hello, stderr!... | Rust | 0 |
TypeConstraint,
projected_subject: TypeId,
field: Buffer,
input_product: TypeConstraint,
) {
with_core(scheduler_ptr, |core| {
core.tasks.add_select_projection(product, projected_subject, field.to_string().expect("field to be a string"), input_product);
})
}
#[no_mangle]
pub extern fn task_end(scheduler... | Rust | 0 |
r>"
"y: %{y:.4f} [m]<br>"
)
try:
indices = np.where(abs(y_elipse)>aper_2)
x_new = np.delete(x_elipse, indices)
y_new = np.delete(y_elipse, indices)
indices = np.where(abs(x_elipse)>aper_1)
x_new = np.delete(x_new, indices)
y_new = np.delete(y_n... | Python | 1 |
# -------------------------------------------------
# Run additional GMAP jobs after Cogent is done
# NOTE: must first confirm that all Cogent jobs are done! check with other scripts
# -------------------------------------------------
import os, sys, glob
GMAP_CMD_GFF = "-n 0 -t 1 -f gff3_gene --max-intronlength-en... | Python | 1 |
(0-59, or 60 for leap second)
pub fn second(&self) -> u8 {
self.second
}
/// Get the nanosecond (0-999_999_999)
pub fn nanosecond(&self) -> u32 {
self.nanosecond
}
}
impl fmt::Display for TimeOffset {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.0 {... | Rust | 0 |
t_vec = path
.split("/")
.map(|x| x.to_string())
.collect::<Vec<String>>();
if split_vec.len() < 4 {
Err(io::Error::new(
io::ErrorKind::InvalidData,
"invalid http path",
))?
}
result.extend([b'/']);
result.extend(split_vec[3..].join("/").as... | Rust | 0 |
nhan=tds.nhan_xu('PAGE', id)
try:
xu = nhan[1]
msg = nhan[0]
dem+=1
hoanthanh(dem, id, 'PAGE', msg, xu)
loipage = 0
if dem % doinick == 0:
namtool(14); print(f'\033[1;32mSố Xu Hiện Tại: \033[1;33m{xu} \033[1;31m| \033[1;32mSố Tài Khoản F... | Python | 1 |
coordenadas = (10, 20)
print(coordenadas[0])
| Python | 1 |
# applications/core/forms/doctor.py
from django import forms
from applications.core.models import Doctor
# Clases de CSS para mantener la consistencia visual
TAILWIND_INPUT_CLASSES = "shadow-sm bg-white border border-gray-300 text-gray-900 rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5"
TAILW... | Python | 1 |
in dataset:
x, edge_index = data.x, data.edge_index
with torch.no_grad():
embedding = model.extract_embedding(x, edge_index, data.batch)
embeddings_list.append(embedding.numpy())
embeddings_all = np.concatenate(embeddings_list)
return embeddings_all
def predict_labels(model,... | Python | 1 |
};
use std::time::Duration;
use systems::{
electrical::{
consumption::SuppliedPower, AlternatingCurrentElectricalSystem, Contactor, ElectricalBus,
EmergencyGenerator, EngineGenerator, ExternalPowerSource, Potential, PotentialSource,
PotentialTarget, TransformerRectifier,
},
shared::{... | Rust | 0 |
et_partial_segment(&self, left: usize, max_width: usize) -> SegmentPartial {
let segment_length = unicode_column_width(self.text.as_str());
// segment is hidden to the left of the line/scroll
if segment_length <= left {
SegmentPartial::new("", 0)
}
else {
let graphemes = UnicodeSegmentation::graphemes(... | Rust | 0 |
votes) need to have voted in favor of the proposal (“Yes”).
(true, "")
};
// Update poll status
a_poll.status = if passed {
PollStatus::passed
} else {
PollStatus::rejected
};
a_poll.total_balance_at_end_poll = Some(state.total_weight);
if env.block.height < a_poll.... | Rust | 0 |
lts(
func=build_disable_individual_passes)
add_default_parser_args(disable_individual_passes_parser)
disable_individual_pass_parser = subparsers.add_parser(
'disable_individual_pass',
description=textwrap.dedent("""
Run build-script disabling only the specified passes.
"""))
... | Python | 1 |
from transformers.models.llama.modeling_llama import apply_rotary_pos_emb
llama_config = get_config()
device = "cpu"
lev_config = LlamaConfig.from_hf_config(llama_config)
Pos = lev_config.Pos
Heads = lev_config.attention_config().Heads
HeadSize = lev_config.attention_config().HeadSize
Bat... | Python | 1 |
(inplace=True, drop=True)
result_two_df.reset_index(inplace=True, drop=True)
result_two_df.columns.name = None
return result_one_df, result_two_df
def option_czce_daily(
symbol: str = "白糖期权", trade_date: str = "20191017"
) -> pd.DataFrame:
"""
郑州商品交易所-期权-日频行情数据
:param trade_date: 交易日
... | Python | 1 |
from pydantic import BaseModel
class CargoWithCount(BaseModel):
cargo_id: str
cargo_count: int
class Task(BaseModel):
city_from_id: str
city_to_id: str
cargos: list[CargoWithCount]
class Truck(BaseModel):
id: str
name: str
speed: float
weight: float
max_cargo_weight: float
... | Python | 1 |
import json
import os
import argparse
import logging
import logging.config
logging.config.dictConfig({
"version": 1,
"formatters": {
"standard": {
"format": "[%(asctime)s] [%(levelname)s] [%(name)s::%(funcName)s::%(lineno)d] %(message)s"
}
},
"handlers": {
"console": {
"class": "logging... | Python | 1 |
#coding=utf-8
import logging
import interface
import os ,re
import utls.tpl
import sys
from utls.rg_io import rg_logger
from utls.rg_sh import shexec
from string import *
from res.base import *
_logger = logging.getLogger()
class php_rest_parser:
def __init__(self) :
self.rest_rule = None
s... | Python | 1 |
PointLayout,
);
}
extern "C" {
pub fn alt_Vector_float_3_PointLayout_Create_2_CAPI_Heap(
elements: *mut f32,
) -> *mut alt_Vector_float_3_PointLayout;
}
extern "C" {
pub fn alt_Vector_float_3_PointLayout_Access_size_t(
_instance: *mut alt_Vector_float_3_PointLayout,
key: ::std::o... | Rust | 0 |
t` - Specifies limit on body size, if not specified uses default 4kb
///- `charset` - Specifies charset to use, if omitted assumes `UTF-8`. Available only with feature `encoding`
pub async fn json_charset_notify<S, I, E, N, J>(body: S, encoding: ContentEncoding, limit: Option<usize>, charset: &'static Encoding, notify:... | Rust | 0 |
h
}
criterion_main!(benches);
#[doc = "Register `IN_PRI_CH1` reader"]
pub struct R(crate::R<IN_PRI_CH1_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<IN_PRI_CH1_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<IN_PRI_CH1_SPEC>> for R {
... | Rust | 0 |
#
# Copyright 2018-2025 Elyra 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 agreed to in writ... | Python | 1 |
s
}
}
}
/*
* DMNTK - Decision Model and Notation Toolkit
*
* MIT license
*
* Copyright (c) 2018-2022 <NAME>
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AN... | Rust | 0 |
visited.add(u)
# For each nontree edge going out of node u...
edges = []
for w, v, d in H.edges:
if w == u and d["nontree"] == True:
edges.append((w, v))
# edges = ((u, v) for u, v, d in H.out_edges(u, data="nontree") if d)
for u, v in edges:
... | Python | 1 |
# /ai_research_assistant/ingest.py
import os
from langchain_community.document_loaders import TextLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_chroma import Chroma
from langchain_openai import OpenAIEmbeddings
# 定义文档目录和持久化存储目录
DOCUMENTS_DIR = "documents"
CHROMA_PERSIST_DIR... | Python | 1 |
AND am.state IN %s
AND "account_move_line".journal_id IN %s
AND """ + query_get_clause[1] + """
GROUP BY rel.account_tax_id"""
self.env.cr.execute(query, tuple(params))
ids = []
base_amounts = {}
for row in self.env.cr.fetchall():
... | Python | 1 |
std_compressed_size_vec.iter().map(|(_, y)| *y).max().unwrap(),
columnar_compressed_size_vec.iter().map(|(_, y)| *y).max().unwrap(),
))
.unwrap();
ctx.configure_mesh()
.x_desc("batch size")
.y_desc("compressed size (bytes)")
.draw().unwrap();
ctx.dra... | Rust | 0 |
# -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2017 Boundless Spatial
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, eithe... | Python | 1 |
if !found
{ state.auto_reduce = true;
state.default_reduce_rule = r_best;
}
}
// Make a second pass over all states and actions. Convert every action that is a SHIFT to an autoReduce state into a SHIFTREDUCE action.
for stp in states.array.iter()
{ for action in stp.actions.iter()
{ let mut actio... | Rust | 0 |
from rest_framework import serializers
from poll.models import Question, Choice, Tag
from employee.serializers import EmployeeSerializer
class ChoiceSerializer(serializers.ModelSerializer):
id = serializers.IntegerField(required=False)
class Meta:
model = Choice
fields = [
'id',
... | Python | 1 |
(&mut self, table: &mut [OpcodeProperties]){
if self.jump.is_none(){
self.jump = Some(PipelineBehavior::None);
}
if self.gas_level.is_none(){
self.gas_level = Some(GasCost::Low);
}
if self.len == 0{
panic!("Incorrect opcode configuration");
... | Rust | 0 |
operand1: Some(IndirectScaledIndexed(RDI, RDI, Eight, Some(OperandSize::Dword), None)), operand2: Some(Direct(XMM5)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 250, 17, 44, 255], OperandSize::Qword)
}
fn vmovss_13() {
run_... | Rust | 0 |
pe_.unwrap() {
Type::Directional => Kind::Directional,
Type::Point => Kind::Point,
Type::Spot => {
let args = self.json.spot.as_ref().unwrap();
Kind::Spot {
inner_cone_angle: args.inner_cone_angle,
outer_cone_ang... | Rust | 0 |
# Author (C) @abirxdhackz
# Channel : https://t.me/abir_xd_bio
import telebot
from telebot import types
import time
import random
import string
import threading
from datetime import datetime, timedelta
API_TOKEN = '7726534009:AAFyem3q10Xr-r9btWHzdNCtXophdr5jNsM' # Replace with your bot's API token
bot = telebot.Tele... | Python | 1 |
activity_levels = user_activity['activity_level'].value_counts()
# 各活跃度等级总消息数量
message_by_level = user_activity.groupby('activity_level')['message_count'].sum()
# 定义每个活跃度级别对应的消息范围
ranges = {
'不活跃': f'1 - {int(0.1 * average_message_count)}',
'低活跃': f'{int(0.1 * average_message_count)} - {int(average_message_c... | Python | 1 |
"""
Crop signal axes
================
This example shows various ways to crop the signal axes of an
:class:`~kikuchipy.signals.EBSD` signal using HyperSpy's ``isig`` slicer and the
:meth:`~kikuchipy.signals.EBSD.crop` and
:meth:`~hyperspy._signals.signal2d.Signal2D.crop_signal` methods (see
:ref:`hyperspy:signal.index... | Python | 1 |
import sys
import os
sys.path.append(os.path.abspath('.'))
from agent.Medical_Consultation_Agent.tools import gen_tools_desc,tools_map, query_user_for_details
# 医疗助手的任务描述与限制
constraints = [
"仅使用下面列出的动作,特别是在为用户提供医疗建议时,确保所有建议都是基于可用的医学数据和信息,且必须询问内置的医疗知识库来获取必要的医学信息。",
"只处理医学相关的查询,并确保所有医疗建议都是基于内置医疗知识库中最新和最可靠的医学数据。"... | Python | 1 |
cket or workload. See `SubmitNodeBlock` for
/// implementation details.
pub trait RenderFeatureSubmitNodeBlock: Downcast + Send + Sync {
fn render_phase(&self) -> RenderPhaseIndex;
fn num_submit_nodes(&self) -> usize;
fn get_submit_node(
&self,
submit_node_id: SubmitNodeId,
) -> Render... | Rust | 0 |
ustfmt::skip]
let a = _mm512_set_epi32(0, 1, -1, u32::MAX as i32, i32::MAX, i32::MIN, 100, -100,
0, 1, -1, u32::MAX as i32, i32::MAX, i32::MIN, 100, -100);
let b = _mm512_set1_epi32(-1);
let mask = 0b01111010_01111010;
let r = _mm512_mask_cmp_epu32_mask(m... | Rust | 0 |
.event_pump()
.expect("Unable to obtain event pump handle!");
let texture = LTexture::from_file("resources/dot2.bmp", &creator);
let mut dot = Dot::new(0, 0, &texture);
let other_dot = Dot::new(WIDTH as i32 / 4, HEIGHT as i32 / 4, &texture);
'running: loop {
// Extract any pen... | Rust | 0 |
" {
pub fn DAQmxSetup4302Cal(
calHandle: CalHandle,
channelNames: *const ::std::os::raw::c_char,
rangeMin: float64,
rangeMax: float64,
) -> int32;
}
extern "C" {
pub fn DAQmxGet4302CalAdjustPoints(
calHandle: CalHandle,
adjustmentPoints: *mut float64,
... | Rust | 0 |
32,
pub err: i32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for JET_COLUMNCREATE_W {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for JET_COLUMNCREATE_W {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: 'Win32_Storage_Jet'*"]
pub ... | Rust | 0 |
re
/// checked manually by using the online LCH color picker https://css.land/lch. We did not found any
/// equations which allow for mathematical approximations of those, but in case you are aware of
/// such equations, you are more than welcome to improve this code.
///
/// ## WARNING
/// Please note that for conveni... | Rust | 0 |
# -*- coding: utf-8 -*-
#
# This file is part of SENAITE.CORE.
#
# SENAITE.CORE is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, bu... | Python | 1 |
type Buffer = [u8; 8];
fn buffer() -> Self::Buffer {
[0; 8]
}
fn sql_type() -> SqlType {
SqlType::UInt64
}
}
impl StatBuffer for i8 {
type Buffer = [u8; 1];
fn buffer() -> Self::Buffer {
[0; 1]
}
fn sql_type() -> SqlType {
SqlType::Int8
}
}
... | Rust | 0 |
'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_cancel_bubble_trampoline<P, F: Fn(&P) + 'static>(this: *mut ffi::WebKitDOMEvent, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer)
where P: IsA<DOMEvent>
{
let f: &F = &*(f as *const F);
f(... | Rust | 0 |
.collect::<Vec<_>>();
let framebuffers = views
.iter()
.map(|view| {
dev.create_framebuffer(
&FramebufferCreateInfo::new()
.attachment(&view)
.width(extent.0)
.height(extent.1)
.layers(1)
... | Rust | 0 |
Sink, StreamSink},
};
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct BlackholeConfig {
pub rate: Option<usize>,
}
inventory::submit! {
SinkDescription::new::<BlackholeConfig>("blackhole")
}
impl_generate_config_from_default!(BlackholeConfig);
#[async_trait]... | Rust | 0 |
u32 = 7u32;
#[doc = "*Required features: 'Win32_NetworkManagement_WiFi'*"]
pub const DOT11_WFD_STATUS_FAILED_PREVIOUS_PROTOCOL_ERROR: u32 = 6u32;
#[doc = "*Required features: 'Win32_NetworkManagement_WiFi'*"]
pub const DOT11_WFD_STATUS_FAILED_REJECTED_BY_USER: u32 = 11u32;
#[doc = "*Required features: 'Win32_NetworkMa... | Rust | 0 |
, -1.2420140846E-1);
const_f32_as_f32x8!(P6logf, 1.1676998740E-1);
const_f32_as_f32x8!(P7logf, -1.1514610310E-1);
const_f32_as_f32x8!(P8logf, 7.0376836292E-2);
const_f32_as_f32x8!(p2expf, 1.0 / 2.0); // coefficients for Taylor expansion of exp
const_f32_as_f32x8!(p3expf, 1.0 / 6.0);
const_f32_a... | Rust | 0 |
> Result<()> {
unsafe {
let mut buf = [0u32; 8192 / 4];
let mut nlmsg = Nlmsg::new(&mut buf);
nfq_hdr_put(&mut nlmsg, NFQNL_MSG_CONFIG as u16, queue_num);
let params = nfqnl_msg_config_params {
copy_range: be32_to_cpu(range as u32),
... | Rust | 0 |
= callback.data.split(":")
order_id = order_id.strip()
qr_data = f"SelfStorage Order #{order_id}"
qr_img = qrcode.make(qr_data)
bio = BytesIO()
qr_img.save(bio, format='PNG')
bio.seek(0)
qr_bytes = bio.read()
doc = BufferedInputFile(qr_bytes, filename="order_qr.png")
patch_url ... | Python | 1 |
path : str, optional
Path to XML file to read. If not provided,
openmc.config['cross_sections'] will be used.
Returns
-------
data : openmc.data.DataLibrary
Data library object initialized from the provided XML
"""
data = cls()
... | Python | 1 |
::connection::parse::Parse,
) -> crate::Result<Option<Self>> {
let res = match tag {
"gt" => Some(GtLt::Gt),
"lt" => Some(GtLt::Lt),
_ => None,
};
Ok(res)
}
#[inline]
#[must_use]
pub const fn is_none(self) -> bool {
matches!(self, G... | Rust | 0 |
P) -> Result<Self, ConfigErr> {
let path = path.as_ref();
let config_file = fs::read_to_string(path).map_err(ConfigErr::InvalidPath)?;
(toml::de::from_str(&config_file)).map_err(ConfigErr::ConfFileParse)
}
pub fn discover<P: AsRef<Path>>(path: P) -> Result<Self, ConfigErr> {
let ... | Rust | 0 |
serializing_if = "Option::is_none")]
pub provisioning_state: Option<String>,
}
impl VmssExtensionProperties {
pub fn new(publisher: String, type_: String, type_handler_version: String) -> Self {
Self {
publisher,
type_,
type_handler_version,
auto_upgrade_m... | Rust | 0 |
| a.id == album.id) {
Some(_) => (),
None => self.add_album(album.clone())?,
}
}
Ok(())
}
pub fn add_track(&mut self, track: Track) -> Result<(), Error> {
let conn = conn()?;
let stmt = conn.prepare("INSERT INTO track_entries (trac... | Rust | 0 |
kas::resvg::{tiny_skia::*, Canvas, CanvasDrawable};
use kas::widgets::Window;
#[derive(Debug)]
struct Program;
impl CanvasDrawable for Program {
fn draw(&self, pixmap: &mut Pixmap) {
let size = (200.0, 200.0);
let scale = Transform::from_scale(
f32::conv(pixmap.width()) / size.0,
... | Rust | 0 |
end_frame = start, end
end_frame = min(end_frame, video_len)
offset = self.get_index(end_frame - start_frame, 8)
frame_indices = offset + start_frame
buffer = torch.stack([frames[idx] for idx in frame_indices])
buffer = buffer.numpy()
... | Python | 1 |
# coding=utf-8
# Copyright 2022-present, the HuggingFace Inc. team.
#
# 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 a... | Python | 1 |
#!/usr/bin/python3
#The UPPER function is used to convert alphabets into their respective capital case
#Here is how to use it:
name='antwiwaa'
print(name.upper())
#The LOWER function is used to convert alphabets into their respective lower case
#Here is how to use it:
animal='CAT'
print(animal.lower())
#REPLACE ... | Python | 1 |
fase):
return {
"modalidade": "Ciclismo",
"tipo": tipo.capitalize(),
"descricao": f"Treino de ciclismo {tipo} para fase {fase}",
"zona": "Z2-Z4",
"tempo": int(tempo_max * 60),
"fase": fase
}
def gerar_treino_corrida(tipo, tempo_max, fase):
return {
"m... | Python | 1 |
# Generate all combinations of noise levels and dataset size multipliers
if sweep and name.startswith("Nguyen"):
noises = [0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.10]
for noise in noises:
d = BenchmarkDataset(
name=name,
... | Python | 1 |
TAU);
let mut y = (angle * model.freq + deg_to_rad(model.phi)).sin();
y *= win.h() / 4.0;
pt2(win.left() + i as f32, y)
})
.enumerate()
.map(|(_i, p)| {
let rgba = rgba(0.0, 0.0, 0.0, 1.0);
(p, rgba)
... | Rust | 0 |
if let Some(nd) = map.get(&old) {
log::debug!(
"{} Reused already copied {} for {:?}",
self.depth_str(),
nd.node_id(),
old
);
return *nd;
}
let new_node = self.graph.copy_node_without_ins(old, target_blo... | Rust | 0 |
witzerland'), ('cy', 'Welsh'), ('cy-GB', 'Welsh - United Kingdom'), ('wal', 'Wolaytta'), ('wal-ET', 'Wolaytta - Ethiopia'), ('wo', 'Wolof'), ('wo-SN', 'Wolof - Senegal'), ('xh', 'Xhosa'), ('xh-ZA', 'Xhosa - South Africa'), ('yav', 'Yangben'), ('yav-CM', 'Yangben - Cameroon'), ('ii', 'Yi'), ('ii-CN', "Yi - People's Repu... | Python | 1 |
O (listado compacto)\n"
"[n] **Nombre del lugar**\n"
"🏷️ {tipo}\n"
"📍 {dirección/barrio}\n"
"⏰ {horarios o 'Horarios no disponibles; verifica la web o Maps'}\n"
"🗺️ Google Maps: {si hay place_id -> 'https://www.google.com/maps/place/?q=place_id:{p... | Python | 1 |
ient_attention()
return DiffuserTextModel(unet, text_encoder)
def build_model(cfg):
return DhariwalUNet(
img_resolution=cfg.TRAIN.IMAGE_SIZE,
in_channels=cfg.MODEL.IN_CHANNELS,
out_channels=cfg.MODEL.OUT_CHANNELS,
label_dim=cfg.MODEL.LABEL_DIM,
augment_dim=0,
m... | Python | 1 |
output = np.zeros(shape=negative_users.shape, dtype=rconst.ITEM_DTYPE) - 1
left_index = self.index_bounds[negative_users]
right_index = self.index_bounds[negative_users + 1] - 1
num_positives = right_index - left_index + 1
num_negatives = self._num_items - num_positives
neg_item_choice = stat... | Python | 1 |
&self,
deps: DepsMut,
env: Env,
info: MessageInfo,
msg: Vec<u8>,
) -> AnyResult<Response<T>>;
fn query(&self, deps: Deps, env: Env, msg: Vec<u8>) -> AnyResult<Binary>;
fn sudo(&self, deps: DepsMut, env: Env, msg: Vec<u8>) -> AnyResult<Response<T>>;
fn reply(&s... | Rust | 0 |
#!/usr/bin/env python
# coding=utf-8
import MySQLdb
import logging
from xutils import encode_utf8
LOGIN_TIMEOUT = 12
class MysqlAuth:
def __init__(self, (host,port)):
self.addr = (host, port)
def login(self, username, password, timeout=LOGIN_TIMEOUT):
conn_ok, auth_ok, anonymous,... | Python | 1 |
-10
use owning_ref::OwningHandle;
use slice_deque::SliceDeque;
use std::cell::{Cell, RefCell};
use std::io::Read;
use std::marker::PhantomData;
use std::rc::{Rc, Weak};
use std::str::Chars;
use tinyvec::ArrayVec;
use super::Streamer;
use super::StreamerError;
use super::StreamerRange;
const ITEM_INDEX_SIZE: usize = 1... | Rust | 0 |
+ 146; $c }
};
(@$v:ident, $a:expr, 148, $c:block) => {
unroll!(@$v, $a, 74, $c);
unroll!(@$v, $a + 74, 74, $c);
};
(@$v:ident, $a:expr, 149, $c:block) => {
unroll!(@$v, $a, 148, $c);
{ const $v: usize = $a + 148; $c }
};
(@$v:ident, $a:expr, 150, $c:block) => ... | Rust | 0 |
,
&mut self.search_matches.as_mut(),
self.focused_search_match,
)?;
if quoted {
self.highlight_str(
"\"",
Some(value_close_quote_range_start),
highlighting::PREVIEW_STYLES,
)?;
}
Ok(space_us... | Rust | 0 |
t<()> {
let gil = Python::acquire_gil();
let py = gil.python();
// Prepare required module(s)
PyModule::from_code(
py,
ADD_EMOJI_GSUB_PY,
"add_emoji_gsub.py",
"add_emoji_gsub"
)?;
let map_pua_module = PyModule::from_code(
py,
MAP_PUA_EMOJI_PY,
... | Rust | 0 |
is test case."),
(true, false) => assert_eq!(status, TINFLStatus::NeedsMoreInput),
(false, true) => assert_eq!(status, TINFLStatus::HasMoreOutput),
// NOTE: In case both "NeedsMoreInput" and "HasMoreOutput" are both true,
// HasMoreOutput should be preferred as the user g... | Rust | 0 |
stored values and their corresponding
/// tree node indices held by `self`. The values are returned in the order
/// of the corresponding search keys.
fn values(&'slf self) -> Box<dyn Iterator<Item=(NodeIndex, &'slf V)> + 'slf> {
if self.root == self.nil {
return Box::new(empty::<(NodeIn... | Rust | 0 |
import math
from functools import partial
import torch
import torch.nn as nn
class Fcos_Loss(nn.Module):
def __init__(self, strides = [8, 16, 32, 64, 128], limit_range = [[-1,64],[64,128],[128,256],[256,512],[512,999999]], sample_radiu_ratio=1.5):
super().__init__()
self.strides = stri... | Python | 1 |
init = get_initialization(x, len(components))
(ab, pi, usedsteps) = estimate_mixture(x, init, steps=steps, tolerance=tolerance)
return (ab, pi, usedsteps)
class AccumHistogram1D():
"""https://raw.githubusercontent.com/NichtJens/numpy-accumulative-histograms/master/accuhist.py"""
def __init__(self... | Python | 1 |
adds a fixed displacement
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConstantDisplacement {
dim: usize,
nodes: Vec<usize>,
displacement: DVector<f64>,
}
/// Boundary condition that adds a constant and uniform displacement to the given nodes
#[derive(Debug, Clone, Serialize, Deserialize)]
#... | Rust | 0 |
import pytest
import torch
from ludwig.constants import ENCODER_OUTPUT_STATE, HIDDEN
from ludwig.decoders import sequence_decoder_utils
from ludwig.modules.reduction_modules import SequenceReducer
@pytest.mark.parametrize("num_layers", [1, 2])
def test_get_rnn_init_state_uses_hidden(num_layers):
batch_size = 16
... | Python | 1 |
)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
WAKEUP1_LW::DETECT_LOW_LEVEL => false,
WAKEUP1_LW::DETECT_HIGH_LEVEL => true,
}
}
}
#[doc = r" Proxy"]
pub struct _WAKEUP1_LW<'a> {
w: &'a mut W,
}
impl<'a> _WAKEUP1_LW<'a> {
#[doc = r" Writes `variant` ... | Rust | 0 |
<filename>packages/rust/wasm/math.rs<gh_stars>1-10
pub fn main() {}
#[no_mangle]
pub extern fn square (x: u32) -> u32 {
x * x
}// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Ap... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.