text string | label_name string | labels int64 |
|---|---|---|
, return `I2C` bus instance
pub fn destroy(self) -> I2C {
self.i2c
}
/// `WHO_AM_I` register
pub fn get_device_id(&mut self) -> Result<u8, Error<E>> {
self.read_reg(Register::WHO_AM_I).map_err(Into::into)
}
/// Operating mode selection,
/// `CTRL_REG1`: `LPen` bit,
/// ... | Rust | 0 |
et app_name = "ffx";
let app_version = "1";
let uname = os_and_release_desc().replace(" ", "+");
let cid = "test";
let expected = format!(
"an={}&av={}&cd1={}&cid={}&ea={}&ec=general&el={}&t=event&tid={}&v=1",
&app_name, &app_version, &uname, &cid, &args_encoded, ... | Rust | 0 |
PROC1_NMI_MASK {}
#[doc = "Processor core 1 NMI source mask\\n Set a bit high to enable NMI from that IRQ"]
pub mod proc1_nmi_mask;
#[doc = "Configuration for processors\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_w... | Rust | 0 |
!(list.head(), None);
let list = list
.prepend(Num(1.0))
.prepend(Num(2.0))
.prepend(Num(3.0));
assert_eq!(list.head(), Some(Num(3.0)));
let list = list.tail();
assert_eq!(list.head(), Some(Num(2.0)));
let list = list.tail();
assert_eq!(list.head(), Some(Num(1.0)));
... | Rust | 0 |
32)
}
}
impl From<BufferRef<u8>> for TypedBufferRef {
fn from(buffer: BufferRef<u8>) -> TypedBufferRef {
TypedBufferRef::new(buffer.any(), EncodingType::U8)
}
}
impl From<BufferRef<Nullable<i64>>> for TypedBufferRef {
fn from(buffer: BufferRef<Nullable<i64>>) -> TypedBufferRef {
... | Rust | 0 |
import os
from pydantic_settings import BaseSettings
from typing import Optional
class Settings(BaseSettings):
# Database
DB_URL: str = os.getenv("DB_URL", "postgresql://flip:secure_password@localhost:5433/pokemon_arbitrage")
# Telegram
TG_TOKEN: Optional[str] = os.getenv("TG_TOKEN")
TG_ADMIN_... | Python | 1 |
(rolename, GUNNERS[user]))
@event_listener("revealroles_role", listener_id="gunners.<{}>.on_revealroles_role".format(rolename))
def on_revealroles_role(evt: Event, var: GameState, user: User, role: str):
if role == rolename and user in GUNNERS:
evt.data["special_case"].append(messages["gunn... | Python | 1 |
eck that the server is healthy and running"""
if FLAGS.no_server:
return
if self.proc is None:
raise ServerError('Server is not yet started')
if self.proc.poll() is not None:
out, err = self.proc.communicate()
msg = [f'Server died unexpectedly wit... | Python | 1 |
from unittest.mock import Mock, call
from uuid import UUID, uuid4
import pytest
from pytest_mock import MockerFixture
from supriya import AddAction, Server, Synth, default
from supriya.contexts import ContextObject
from supriya.patterns.events import Event, Priority, SynthAllocateEvent
id_ = uuid4()
@pytest.mark.p... | Python | 1 |
{
for j in 0..16 {
let cc = tls_get!(sets)[i].chars().nth(j).unwrap();
tls_set!(SETS, |ns| ns.push(cc));
}
}
// -_CP_init_SETS
init_screen()?;
init_pipes();
loop {
thread::sleep(time::Duration::from_millis(1000 / tls_get!(f) as u64));
let mu... | Rust | 0 |
= subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.read().decode()
chunk.logger.debug(metadata)
lmeta = metadata.split('\n')
for i in range(1, len(lmeta)-1):
l = lmeta[i].split(':... | Python | 1 |
;
pub mod timestamp;<gh_stars>0
use std::fmt;
use crate::descriptor::field_descriptor_proto;
use crate::reflect::EnumDescriptor;
use crate::reflect::MessageDescriptor;
use crate::reflect::MessageRef;
use crate::reflect::ReflectValueBox;
use crate::reflect::ReflectValueRef;
use crate::text_format;
use crate::text_forma... | Rust | 0 |
;
let response = v1::gifs::SearchRequest::new("rage")
.send_to(&api)
.await
.unwrap();
assert!(response.pagination.count > 0);
}
#[tokio::test]
async fn api_trending_200_ok() {
dotenv().ok();
let api_key = env::var("GIPHY_API_KEY_TEST")
... | Rust | 0 |
f6\xdb\xb8\xb4\xd6\xbb\x8e(\xc66\x97\
0\x94gR1\xcfw\xc6\x9b\x8a|\xd7^\x99Y>\
s\x5cP\xa7^\x1c5#\x9f'\xe2\x8e\xbf\xf7\x1f\xda\
{\xd3\xb2\xcb\xa4\x9bq\xa9\xaaV\x9ao\xf9\x14\xd7\xfe\
\x10/55\xae\xd6\xf5\xe7\xc1\xa5\xed}\x13l\xd1\x97\
\xf7\xfdV\xfb\xdfU1\xe6\xa1K\x92~\xa6z\xd3{\
5\xdd7\x1a\x85\x1b\xfd\xcf\xda^\xe0\xb8\xadNj... | Python | 1 |
", (0, 0)),
("CircleT", (0, 0)),
("ugrav", (0, 0)),
("simd", (0, 0)),
("Longleftrightarrow", (0, 0)),
("Or;", (10836, 0)),
("RightUpVectorBa", (0, 0)),
("xs", (0, 0)),
("NotVer", (0, 0)),
("roang;", (10221, 0)),
("LeftArrowRightA", (0, 0)),... | Rust | 0 |
);
}
#[allow(unused_mut)]
let mut scope_4300 = writer.prefix("UserGroup");
if let Some(var_4301) = &input.user_groups {
let mut list_4303 = scope_4300.start_list(true, Some("UserGroup"));
for item_4302 in var_4301 {
#[allow(unused_mut)]
let mut entry_4304 = list_4... | Rust | 0 |
or("bold red");
assert_eq!(c.fg.unwrap(), Color::Indexed(9));
assert!(c.bg.is_none());
let c = Config::get_tcolor("on green");
assert!(c.fg.is_none());
assert_eq!(c.bg.unwrap(), Color::Indexed(2));
let c = Config::get_tcolor("on red");
assert!(c.fg.is_none());
... | Rust | 0 |
id, \
" mse:", round(mse.item(), 5), " psnr:", {psnr}, " ssim:", {ssim}, " lpips:", {lpips})
all_view_mse.append(mse.item())
all_view_psnr.append(psnr)
all_view_ssim.append(ssim)
all_view_lpips.append(lpips)
all_pose_mse.ap... | Python | 1 |
or:
msg = f'Workspace ID must be castable to integer, not "{ws_id}".'
raise GristApiNotConfigured(msg)
self.server = self.make_server()
self.raise_option = (self.config['GRIST_RAISE_ERROR'] == 'Y')
self.safemode = (self.config['GRIST_SAFEMODE'] == 'Y')
def make_serve... | Python | 1 |
#!/usr/bin/env python3 -u
"""Implement interval based time series regression estimators."""
__author__ = ["mloning"]
__all__ = ["TimeSeriesForestRegressor"]
from sktime.regression.interval_based._tsf import TimeSeriesForestRegressor
| Python | 1 |
import numpy as np
class ExponentialSchedule:
def __init__(self, value_from, value_to, num_steps):
"""Exponential schedule from `value_from` to `value_to` in `num_steps` steps.
$value(t) = a \exp (b t)$
:param value_from: Initial value
:param value_to: Final value
:param ... | Python | 1 |
();
assert_eq!(file_to_value(OK_FILE), response_to_value(response));
}
#[test]
fn test_excluded() {
let (_, rocket) = start_test_server_with_excludes(vec!["/test"]);
let client = Client::new(rocket).expect("valid rocket instance");
let req = client.get("/test");
let response = req.dispatch();
a... | Rust | 0 |
import re
import math
def Leer(archivo_entrada):
with open(archivo_entrada, encoding="utf-8") as entrada:
texto = entrada.read()
return texto
def Extraer(texto):
numeros = re.findall(r'-?\d+', texto)
numeros = [int(num) for num in numeros]
return numeros
def Distancia_centros(x1,y1,x2,y2)... | Python | 1 |
k": "Vacuum is stuck",
"maint_vacuum_slip": "Vacuum is stuck",
"maint_left_drop_stuck": "Vacuum is stuck",
"maint_left_wheel_stuck": "Vacuum is stuck",
"maint_right_drop_stuck": "Vacuum is stuck",
"maint_right_wheel_stuck": "Vacuum is stuck",
"not_on_charge_base": "Not on the charge base",
"... | Python | 1 |
is full, requestes will get an immediate error instead of running in a
// timeout, thus requesters can immediately try another peer and be faster.
//
// From this perspective we would not want parallel response sending at all, but we don't
// want a single slow requester slowing everyone down, so we want so... | Rust | 0 |
._set_property("legendgrouptitle", arg, legendgrouptitle)
self._set_property("legendrank", arg, legendrank)
self._set_property("legendwidth", arg, legendwidth)
self._set_property("line", arg, line)
self._set_property("marker", arg, marker)
self._set_property("meta", arg, meta)
... | Python | 1 |
& output,
arguments,
)
};
match command_result {
Ok (_) =>
0,
Err (error_message) => {
output.clear_status ();
output.message_format (
format_args! (
"{}",
error_message));
1
},
}
}
// ex: noet ts=4 filetype=rust
extern crate easynn;
extern crate rust_mnist;
ext... | Rust | 0 |
type: WirelessEncryptionType,
key: Option<String>,
}
#[derive(Deserialize, Debug)]
pub struct GetNetworkStatusResponse {
network_name: String,
connection: ConnectionType,
dhcp: Option<bool>,
ip_address: Option<IpAddr>,
subnet_mask: Option<IpAddr>,
default_gateway: Option<IpAddr>,
dns_se... | Rust | 0 |
from distutils.command.build import build
from io import BufferedRandom
from xml.dom import NO_MODIFICATION_ALLOWED_ERR
import scrapy
from spider_gsmarena .items import SpiderGsmarenaItem
class GsmarenaSpider(scrapy.Spider):
name = 'gsmarena'
allowed_domains = ['www.gsmarena.com']
start_urls = ['https://w... | Python | 1 |
qr: self.clone(),
tau: vec![0.0; min(m, n)],
};
let qr_data = qr.qr.data();
let info = lapack::c::dgeqrfp(Layout::ColumnMajor, m as i32, n as i32,
&mut qr_data.values_mut()[..], lda as i32,
&mut qr.tau[..]);
if info < 0 {
Err... | Rust | 0 |
up_id = new_group_id
current_group_label_dict = new_group_label_dict
else:
x_tick_label_list.append(current_group_label_dict[flux_id])
total_item_num = len(x_tick_label_list)
group_separator_array = np.array(group_separator_list) / total_item_num
group_name_location_array... | Python | 1 |
g_ssid(Some(target_ssid));
let current_status = fidl_sme::ClientStatusResponse {
connected_to: connected_to_bss_info,
connecting_to_ssid: vec![],
};
assert!(is_connect_to_target_network_needed(
stay_connected,
target_ssid.as_bytes().to_vec(),
... | Rust | 0 |
import heapq
with open("input.txt") as file:
maze = [x.strip() for x in file.read().split("\n") if x.strip()]
ROWS = len(maze)
COLS = len(maze[0])
DIRS = [(1, 0), (0, 1), (-1, 0), (0, -1)]
INF = float("inf")
start_x = [x.index("S") for x in maze if "S" in x][0]
start_y = [x for x in range(len(maze)) if "S" in... | Python | 1 |
},
PartitionSummary {
key: "1970-01-05T15".into(),
table: TableSummary {
name: "mem".into(),
columns: vec![
ColumnSummary {
name: "frob".into(),
influxdb_ty... | Rust | 0 |
update_todo_route(item_id):
if "user_id" not in session:
return jsonify({"error": "Unauthorized"}), 401
data = request.json
completed = data.get("completed")
if completed is None:
return jsonify({"error": "Invalid request"}), 400
update_todo_item(item_id, int(completed))
retur... | Python | 1 |
omain))?;
// write certificate data to disk
let mut cert_file = File::create(certs_path.join(format!(
"{}/{}",
domain,
certificates::CERT_FILE_NAME
)))?;
cert_file.write_all(&cert.serialize_der()?... | Rust | 0 |
) => StorageClass::CONST,
Some(b'C') => StorageClass::VOLATILE,
Some(b'D') => StorageClass::CONST | StorageClass::VOLATILE,
Some(b'E') => StorageClass::FAR,
Some(b'F') => StorageClass::CONST | StorageClass::FAR,
Some(b'G') => StorageClass::VOLATILE | StorageCl... | Rust | 0 |
import random
from datetime import datetime, timedelta
import os
from pyrogram import Client, filters
from DAXXMUSIC import app
from config import BOT_USERNAME
def luhn_checksum(card_number):
def digits_of(n):
return [int(d) for d in str(n)]
digits = digits_of(card_number)
odd_digits = digits[-1::-... | Python | 1 |
// camera_vertices[t - 1].f(light_vertices[s - 1], TransportMode::Radiance)
// );
// print!(
// "G: {:?}, ",
// g(
// scene,
// sampler,
// light_vertices[s - 1],
// camera_verti... | Rust | 0 |
> {};
",
);
assert_eq!(data.types.len(), 2);
let c1_item = CppPathItem {
name: "C1".to_string(),
template_arguments: Some(vec![CppType::TemplateParameter(CppTemplateParameter {
nested_level: 0,
index: 0,
name: "T".into(),
})]),
};
a... | Rust | 0 |
agroup: list/tuple of (datalist *or* datagroup, title, comment)
-> one field for each member of a datalist
-> one tab for each member of a top-level datagroup
-> one page (of a multipage widget, each page can be selected with a combo
box) for each member of a datagroup inside a datagroup
Suppor... | Python | 1 |
import calendar
name=input("enter your name: ")
year=int(input("enter year: "))
month=int(input("enter month: "))
cal=calendar.month(year,month)
print("Hey",name,"Your required calendar is here")
print(cal)
| Python | 1 |
x = [1,2,3]
x.append(4)
x.append(4)
x.append(10)
print(x)
x.insert(3,42)
print(x)
print(x.count(4))
| Python | 1 |
# Generated by Django 4.2.11 on 2024-05-30 10:37, manually extended.
from django.db import migrations
from django.db.migrations.state import StateApps
NEW_NAME = "Data Access API Key"
def migrate_access_to_api_keys(apps: StateApps, schema_editor):
ResearcherOld = apps.get_model('database', 'Researcher')
Api... | Python | 1 |
############################################################
#
# TODO
#
############################################################
import liboofem
############################################################
# engngModel
problem = liboofem.engngModel("nldeidynamic",1,nSteps=5,dumpCoef=30,deltaT=10000,outFile="/tmp/m... | Python | 1 |
"", None)
.unwrap_err();
assert_eq!(mock.call_called(), 16);
Ok(())
}
#[test]
fn test_storage_uploader_form_uploader_upload_stream_with_503_error() -> Result<(), Box<dyn Error>> {
let file = create_temp_file(1 << 10)?.into_file();
let mock = CounterCallMock::new(Erro... | Rust | 0 |
ge_fn = merge_rewrap)]
#[derive(Clone, Debug, PartialEq)]
struct Original<'a, T> {
number: u32,
text: &'a str,
generic: T,
optional: Option<&'a [u8]>,
}
let original = Original {
number: 12,
text: "test",
generic: "testing".to_string(),
op... | Rust | 0 |
from . import ( # noqa: F401
MediCompass_diagnosis,
MediCompass_management,
)
| Python | 1 |
import pytest
@pytest.fixture(scope="module")
def btc_burner(BTCBurner, alice, receiver):
yield BTCBurner.deploy(receiver, receiver, alice, alice, {"from": alice})
@pytest.fixture(scope="module")
def lp_burner(LPBurner, alice, receiver):
yield LPBurner.deploy(receiver, alice, alice, {"from": alice})
token... | Python | 1 |
in the attentuation equation, see [`PointLight`].
pub linear_attenuation: f32,
/// The quadratic term in the attentuation equation, see [`PointLight`].
pub quadratic_attenuation: f32,
}
impl PointLight {
/// Create a new `PointLight` with the given color.
pub fn new(color: [f32; 3]) -> Self {
... | Rust | 0 |
LOAD 2,
END 3,
DISABLED 4,
DEVMATCH 5,
DEVMISS 6,
RSSIEND 7,
BCMATCH 10
],
CrcStatus [
CRCSTATUS OFFSET(0) NUMBITS(1) [
CRCError = 0,
CRCOk = 1
]
],
RxMatch [
/// Logical address of which previous packet wa... | Rust | 0 |
matcher))
.unwrap_or(false);
}
false
}
/// Checks the current matched set of elements against a matcher and
/// returns true if at least one of these elements matches.
pub fn is_matcher(&self, matcher: &Matcher) -> bool {
if self.length() > 0 {
retur... | Rust | 0 |
lHistorial.setItem(fila,1,QTableWidgetItem("{} {} {} {}".format(str(item[9]),str(item[10]),str(item[11]),str(item[12]))))
nombre="{} {} {} {}".format(str(item[9]),str(item[10]),str(item[11]),str(item[12]))
if item[6]=="True":
self.historial.tblHistorial.setItem(fila,2,QTableW... | Python | 1 |
(0, mipmaps),
// Swizzle::new(),
// ).unwrap();
// Ok(Self {
// texture_view,
// _texture: texture,
// average_albedos,
// })
// }
// pub(crate) fn get_average_albedo(&self, material: MaterialType) -> [u8; 4] {
// ... | Rust | 0 |
ate(|platform_id| *platform_id += 1);
Self::deposit_event(RawEvent::NewPlatform(
platform_id,
admin,
pool_account,
asset_id,
plan,
));
Ok(())
}
#[weight = <T as Config>::WeightInfo::update_platform()]
fn update_platform(origin,
id: u128,
plan: Vec<Plan<T::SGAssetBalance>>,... | Rust | 0 |
import string
# Alphabet setup
alphabet = string.ascii_uppercase
letter_to_num = {letter: idx for idx, letter in enumerate(alphabet)}
num_to_letter = {idx: letter for idx, letter in enumerate(alphabet)}
# Function to encrypt using Vigenère cipher
def vigenere_encrypt(plaintext, keyword):
# Prepare plaintext and ... | Python | 1 |
Factor::AlphaDst => vk::BlendFactor::DST_ALPHA,
BlendFactor::OneMinusAlphaDst => vk::BlendFactor::ONE_MINUS_DST_ALPHA,
}
}
}
impl BlendOp {
fn get_vk_type(&self) -> vk::BlendOp {
match self {
BlendOp::None => vk::BlendOp::ADD, //Blending will be disabled for this
... | Rust | 0 |
"""Update
Revision ID: 112656f95ef5
Revises: 532f15df83c5
Create Date: 2024-01-21 19:24:51.152969
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '112656f95ef5'
down_revision = '532f15df83c5'
branch_labels = None
depends_on = None
def upgrade():
# ### com... | Python | 1 |
= items
return obj
def re_matchall(self, regex, value):
objects = list()
regex = re.compile(regex)
for match in re.findall(regex.pattern, value, re.M):
obj = {}
obj['matches'] = match
if regex.groupindex:
for name, index in iterite... | Python | 1 |
os.path.join(
logdir, 'adsac', str(time_now)
)
writer = SummaryWriter(log_path)
logger = TensorboardLogger(writer)
# Create actor and critic networks
actor, actor_optim = create_actor(state_shape, action_shape)
critic1, critic1_optim, critic2, critic2_optim = create_critic(state_shape,... | Python | 1 |
37 = writer.prefix("NewServerCertificateName");
if let Some(var_838) = &input.new_server_certificate_name {
scope_837.string(var_838);
}
writer.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_update_service_specific_credential(
input: &crate::input::UpdateSe... | Rust | 0 |
_in_goods = attrs['stock_in_goods']
goods = stock_in_goods.goods
if stock_in_goods.remain_quantity < attrs['stock_in_quantity']:
raise ValidationError(f'产品[{goods.name}]入库数量错误')
if goods.enable_batch_control:
if not (attrs.get('batch') or attrs['batc... | Python | 1 |
XmlEvent::ProcessingInstruction { .. }) => (),
Ok(XmlEvent::Characters(text)) => {
let t = format!("{}\n", &escape(text));
xml_text.push_str(&t);
}
Err(e) => {
panic!("Error: {}", e);
}
_ => {}
}
}
return xml_text;
}
use crate::message::MessageInfo;
pub st... | Rust | 0 |
grep -i notredame |wc -l",
'phyml' : "--help |grep -i Guindon|wc -l",
'raxml-pthreads' : "-help |grep -i stamatakis|wc -l",
'raxml' : "-help |grep -i stamatakis|wc -l",
'raxml-pthreads-sse3' : "-help |grep -i stamatakis|wc -l",
'raxml-sse3' : "-help |grep -i... | Python | 1 |
#[doc = "*Required features: `\"Win32_System_Diagnostics_Debug\"`*"]
pub const UNW_FLAG_UHANDLER: RTL_VIRTUAL_UNWIND_HANDLER_TYPE = 2u32;
#[doc = "*Required features: `\"Win32_System_Diagnostics_Debug\"`*"]
pub const UNW_FLAG_CHAININFO: RTL_VIRTUAL_UNWIND_HANDLER_TYPE = 4u32;
#[doc = "*Required features: `\"Win32_Syst... | Rust | 0 |
"""
@author : Hyunwoong
@when : 2019-10-24
@homepage : https://github.com/gusdnd852
"""
from torch import nn
import torch
from model.layers.layer_norm import LayerNorm
from model.layers.multi_head_attention import MultiHeadAttention
from model.layers.position_wise_feed_forward import PositionwiseFeedForward
class Enc... | Python | 1 |
feelings = status_results[entity_id]['feelings']
print(f" - Current mood: {feelings.get('current_mood', 'N/A')}")
print(f" - Energy level: {feelings.get('energy_level', 'N/A')}")
else:
print(f" - Error: {result['message']}")
... | Python | 1 |
/// # let expr = exmex::parse_val::<i32, f64>("fact(3.5)")?;
/// # let res = expr.eval(&[])?;
/// # assert!(format!("{:?}", res) == "Error(ExError { msg: \"did not expect Float(3.5)\" })");
/// assert!(res.to_int().is_err());
/// #
/// # Ok(())
/// # }
/// ```
///
#[derive(Clone, Debug)]
pub enum Val<I = i32, F = f... | Rust | 0 |
, || c0)?;
let c1 = Fp2Gadget::<P, ConstraintF>::alloc_input(&mut cs.ns(|| "c1"), || c1)?;
let c2 = Fp2Gadget::<P, ConstraintF>::alloc_input(&mut cs.ns(|| "c2"), || c2)?;
Ok(Self::new(c0, c1, c2))
}
}
<reponame>mh84/seed_heroicons
use seed::{prelude::*, *};
use super::{solid_trait_private::... | Rust | 0 |
_run_status};
use mega_coll::util::fs::lock_file;
use pg::DbSize;
use postgres::{Connection, TlsMode};
use regex::Regex;
use std::borrow::Cow;
use std::process;
use std::thread;
fn mask_url(url: &str) -> Cow<str> {
lazy_static! {
static ref REP_RE: Regex = Regex::new(r"//\S*@").unwrap();
}
// e.g.... | Rust | 0 |
.take() {
::std::option::Option::Some(Type_oneof_type_kind::dyn(v)) => v,
_ => panic!(),
}
} else {
::protobuf::well_known_types::Empty::new()
}
}
// .google.protobuf.NullValue null = 2;
pub fn get_null(&self) -> ::protobuf::well_kno... | Rust | 0 |
_ => panic!("Unknown instruction: {}", &captures[1]),
};
}
grid.len()
}
fn get_brightness(input: String) -> isize {
let mut grid: HashMap<(usize, usize), isize> = HashMap::new();
let instruction =
Regex::new(r"^(turn on|toggle|turn off) (\d+),(\d+) through (\d+),(\d+)$").... | Rust | 0 |
gion = region
current_run.run_name = run_name
# Load map data
from OutpostRunner import map_loader
data = map_loader.load_map_data(current_run.region, current_run.run_name)
outpost_id = data["ids"]["outpost_id"]
yield from Routines.Yield.... | Python | 1 |
vec![];
let mut offset = PACKET_HEADER_SIZE;
loop {
// Exact match, no more chunks
if offset == raw.len() {
break;
} else if offset + CHUNK_HEADER_SIZE > raw.len() {
return Err(Error::ErrParseSctpChunkNotEnoughData.into());
... | Rust | 0 |
[test]
fn send_eapol_frame_failure() {
let mut m = MockObjects::new();
let device = m.fake_device.as_device_fail_wlan_tx();
let mut me = m.make_mlme_with_device(device);
let mut client = make_client_station();
let mut client = client.bind(&mut me.scanner, &mut me.chan_sched, ... | Rust | 0 |
match zero_polynomial_via_multiplication(zero_eval.as_mut_ptr(), &mut zero_poly, domain_size as u64,
idxs.as_ptr() as *const u64,
idxs.len() as u64, self, RUN_PARALLEL)
{
KzgRet::KzgOk =... | Rust | 0 |
t}"#,
export = if type_script {
"".to_string()
} else {
format!(
r#"
exports.{base_class} = {base_class};"#,
base_class = class_name
)
}
)?;
}
Ok(())
}
//
// Copyright © 2020 <NAM... | Rust | 0 |
import discord
from discord.ext import commands
class ChannelManager(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
@commands.has_permissions(manage_channels=True)
async def crtchan(self, ctx, category_name: str, name: str, channel_type: str, privacy: str):
... | Python | 1 |
(download_4dgt_model(
output_dir=Path(cfg.checkpoint).parent,
filename=Path(cfg.checkpoint).name
))
# Create dataset and dataloader
dataloader = create_dataloader(cfg)
# Initialize the demo class
device = cfg.get('device', 'cuda')
demo = FourDGTDemo(
config_... | Python | 1 |
from pydantic import BaseModel, Field
from typing import Optional, List, Dict, Any
class Action(BaseModel):
name: str = Field(description="工具或指令名称")
args: Optional[Dict[str, Any]] = Field(description="工具或指令参数,由参数名称和参数值组成")
class Thought(BaseModel):
text: str = Field(description="思考内容")
reasoning: str ... | Python | 1 |
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2024)
#
# 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 |
Error> {
let is_user = ensure_is_user(deps.as_ref(), info.sender.as_str());
let is_contract = ensure_is_contract_self(&env, &info.sender);
if is_user.is_err() && is_contract.is_err() {
is_user?;
is_contract?;
}
LABEL.update(deps.storage, |l| {
if l == new_label {
... | Rust | 0 |
'."
)
return_type = arg_types[0]
else:
raise AssertionError(
"Only calls to 'FieldOperator', 'ScanOperator' or 'minimum' and 'maximum' builtins allowed."
)
except ValueError as ex:
raise errors.DSLEr... | Python | 1 |
_point) as f32 * self.scale);
Ok(output)
}
}
impl Op for DequantizeLinearF32 {
fn name(&self) -> Cow<str> {
"DequantizeLinearF32".into()
}
fn info(&self) -> TractResult<Vec<String>> {
Ok(vec![format!("scale: {} zero_point: {}", self.scale, self.zero_point)])
}
fn valid... | Rust | 0 |
#!/usr/bin/env python
import requests
import tweepy
import re
import os
# create a file twitter_keys.py and add the tokens/keys below as variables
# in the file
from twitter_keys import consumer_key, consumer_secret
# Create the OAuthHandler
auth = tweepy.OAuthHandler(consumer_key=consumer_key, consumer_secret=consu... | Python | 1 |
[int] = set()
ch_prog: dict[int, int] = {}
tracks: set[int] = set()
sel_has_nondrum = False
for name in selected_names:
sec = parts.get(name)
if not sec:
continue
meta = getattr(sec, 'meta', {}) if hasatt... | Python | 1 |
# In[ ]:
system = BSS.IO.readMolecules(node.getInput("file"))
# We now need to grab the molecule from the system so that we can parameterise it. The system object can be indexed by molecule. Here we grab the first (and only) molecule from the system.
# In[ ]:
molecule = system[0]
# Now let's paramterise the m... | Python | 1 |
ts(dataset_path)
if is_cached:
# 获取文件夹大小
size_bytes = 0
for path, dirs, files in os.walk(dataset_path):
for f in files:
fp = os.path.join(path, f)
if os.path.exists(fp):
size_bytes += os.... | Python | 1 |
;
let lines = BufReader::new(f)
.lines()
.map(|l| l.unwrap())
.map(|l| {
l.trim()
.split(",")
.map(|x| String::from(x))
.collect::<Vec<String>>()
})
.collect::<Vec<Vec<String>>>();
let mut pos_x: i32 = 0;
le... | Rust | 0 |
line6, =plt.plot(x,yed, label="exact")
plt.legend(handles=[line1, line2, line3, line4, line5, line6])
plt.title("Plot of derivatives")
plt.xlabel("x")
plt.ylabel("F")
plt.show()
error=[]
lnn=[]
energy=[]
for n in nelem:
yh,yhd,ye,yed,x=FEMsolver(n,1,choice,bc1,bc2,aeco,cco,fco)
er=np.log... | Python | 1 |
from fastapi import APIRouter, UploadFile, status
from fastapi.responses import JSONResponse
from helper.config import get_settings, Settings
from controllers import DataController, ProjectController, ProcessController
from models import ResponseSignal
from .schemes.ProcessRequest import ProcessRequest
import os
data_r... | Python | 1 |
plus[n-1,:,i]),np.conj((u_hat_plus[n,:,i]-u_hat_plus[n-1,:,i])))
uDiff = np.abs(uDiff)
#Postprocessing and cleanup
#discard empty space if converged early
Niter = np.min([Niter,n])
omega = omega_plus[:Niter,:]
idxs = np.flip(np.arange(1,T//2+1),axis = 0)
#... | Python | 1 |
f'''<p>© Kevin R. Baumgarten, 2024. All rights reserved.</p>''' \
f'''</div></div>'''
w(f'{page = }\n')
return page
def record_accepted(onerec: namedtuple):
# Create the "record accepted" page.
page=f'''\
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8">
<title>Record accepted</title><link rel="st... | Python | 1 |
turn model
except Exception as e:
if isinstance(e, TencentCloudSDKException):
raise
else:
raise TencentCloudSDKException(type(e).__name__, str(e))
def DescribeUpstreamBindApis(self, request):
"""查询后端通道所绑定的API列表
:param request: Reques... | Python | 1 |
::BondedAmount));
} else {
self.judgments.push(Judgement::Fault(Context::BondedAmount));
}
}
pub async fn judge_node_uptime(&mut self, candidate: &Candidate) -> Result<()> {
let info = self
.store
.has_downtime_violation(candidate, self.config.max_down... | Rust | 0 |
salt '*' net.discard_config
"""
return __proxy__['napalm.call'](
'discard_config',
**{}
)
def compare_config():
'''
Returns the difference between the running config and the candidate config.
CLI Example:
.. code-block:: bash
salt '*' net.compare_conf... | Python | 1 |
278000 + (DbWeight::get().read * 5) + (DbWeight::get().write * 4);
let call = StakingCall::bond::<Runtime>(controller, 1 * DOLLARS, Default::default());
let info = call.get_dispatch_info();
assert_eq!(info.weight, expected_weight);
report_portion("staking_bond", info, call.encode().len())
}
#[test]
fn weight_of_s... | Rust | 0 |
"No update needed.")
return
else:
timestamp = last_sync_event['ts']
else:
timestamp = 0 # first update ever
# get the list of builds since last event
output = subprocess.check_output(['koji', 'list-builds', '--quiet', '--state=COMPLETE',
... | Python | 1 |
ert_eq!(unwrapped_cast(src_z00), dst_z0);
assert_eq!(unwrapped_cast(src_p01), dst_p1);
assert_eq!(unwrapped_cast(src_p07), dst_p7);
assert_eq!(unwrapped_cast(src_p08), dst_m8);
assert_eq!(unwrapped_cast(src_p0f), dst_m1);
assert_eq!(unwrapped_cast(src_p10), dst_z0);
}
fn signed_to_larger_same_wrapp... | Rust | 0 |
_idx
return waveforms, dict(shift_samples = total_shift,
peak_value = extremum,
sampling_rate = output_sampling_rate)
return waveforms
def pad_matrix_with_decay(matrix, target_channels=10):
n_channels, _ = matrix.shape
padding_needed = t... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.