text string | label_name string | labels int64 |
|---|---|---|
call_params.callee());
let transferred_value =
self.append_encode_into_buffer(call_params.transferred_value());
let call_data = self.append_encode_into_buffer(call_params.input_data());
// Resolve the encoded regions into actual byte slices.
let callee = &self.buffer[callee];... | Rust | 0 |
oad=edge_dict,
username=username,
)
with Session(self.engine) as session:
session.add(event)
session.commit()
session.refresh(event)
return self._to_edge(event.payload)
def delete_edge(
self,
source_id: NodeId,
target_i... | Python | 1 |
# Copyright (c) OpenMMLab. All rights reserved.
from mmdet.registry import MODELS
from mmdet.utils import ConfigType, OptConfigType, OptMultiConfig
from .single_stage import SingleStageDetector
@MODELS.register_module()
class AutoAssign(SingleStageDetector):
"""Implementation of `AutoAssign: Differentiable Label ... | Python | 1 |
https://doc.rust-lang.org/nightly/std/primitive.f64.html#method.sqrt"]' 'f64::sqrt'
/// [`f64::mul_add`]
// @has - '//*[@href="https://doc.rust-lang.org/nightly/std/primitive.f64.html#method.mul_add"]' 'f64::mul_add'
pub fn f64_methods() {}
<gh_stars>1-10
//! This module defines a `DynMap` -- a container for heterogene... | Rust | 0 |
#!/usr/bin/env python
# coding: utf-8
import numpy as np
import cv2
import csv
import open3d as o3d
from sklearn.neighbors import NearestNeighbors
data_3D = np.loadtxt("points3D.txt")
xyz=data_3D[:,1:4].astype(float)
rgb=data_3D[:,4:7].astype(int)
points_3D = np.loadtxt("sparse_3D_points.txt")
rgb_3D = np.loadtxt("sp... | Python | 1 |
point = Self::switchpoint(pred_plf, live, t_soon);
if t_soon.fuzzy_lt(switchpoint.at) {
live_ipps.push(TTFPoint { at: t_soon, val: live });
}
live_ipps.push(switchpoint);
debug_assert!(
pred_plf.evaluate(switchpoint.... | Rust | 0 |
n(titles):
msg = (
msg
+ "⁍ [{}]".format(titles[counter])
+ "({})".format(shorted_links[counter])
+ "\n\n"
)
counter += 1
await event.edit(msg, link_preview=False)
CMD_HELP.update(
{
"torrent": f"**Plugin : **`torrent`\
\n... | Python | 1 |
Attempted"])
- 1.07 * (
totals_df.loc["OffensiveRebounds"] /
totals_df.loc["DefensiveRebounds", ::-1]
) * (fga - fgm)
+ totals_df.loc["Turnovers"]
)
df = pd.DataFrame(
{
"Possessions (simple)": possessions_s... | Python | 1 |
unks
- For images[], attach all images from slide hits only
- Items are ordered by certainty score descending
"""
content: List[str] = []
images: List[Dict[str, str]] = []
# Normalize inputs
slide_hits = slide_hits or []
video_chunk_hits = video_chunk_hit... | Python | 1 |
Type, ResponseType], Call, metaclass=ABCMeta
):
@abstractmethod
def __aiter__(self) -> AsyncIterator[ResponseType]:
"""Returns the async iterator representation that yields messages.
Under the hood, it is calling the "read" method.
Returns:
An async iterator object that yield... | Python | 1 |
}
);
}
#[test]
fn test_parse_capabilities_unknown() {
assert_eq!(
"jetpack,text,lasersword".parse::<Capabilities>().unwrap(),
Capabilities {
text: true,
image: false,
video: false,
audio: false,
... | Rust | 0 |
td::io::Write;
pub use structopt;
use structopt::{
clap::{self, AppSettings},
StructOpt,
};
use tracing_subscriber::{
fmt::time::ChronoLocal,
EnvFilter,
FmtSubscriber,
Layer,
layer::SubscriberExt,
};
pub use sc_tracing::logging;
pub use logging::PREFIX_LOG_SPAN;
#[doc(hidden)]
pub use tracing;
/// Substrate cl... | Rust | 0 |
}
},
Ok(_) => {
let pout = pout.as_mut().unwrap();
if pout.write_all(&recv_buf).await.is_err() || pout.flush().await.is_err() {
log::debug!("local output failed");
... | Rust | 0 |
from pydantic import BaseModel, Field
from typing import List, Optional
from datetime import date, datetime
class Vo2MaxModel(BaseModel):
id: str
day: date
vo2_max: Optional[float] = Field(
None, alias="vo2_max"
) # User's estimated VO2 max in mL/kg/min
# Based on typical VO2 max reports,... | Python | 1 |
;
/// profile.analyze("Three");
/// profile.analyze("Four");
/// profile.analyze("Five");
/// profile.analyze("Six");
///
/// profile.pre_generate();
///
/// print!("The size ranks are {:?}", profile.size_ranks);
/// // The size ranks are [(3, 50), (4, 83.33333333333333)... | Rust | 0 |
s\\HP\\Downloads\\ChicagoCrimeData.csv"
df = pd.read_csv(file_path)
total_crimes = len(df)
crime_per_district = df["DISTRICT"].value_counts().sort_index()
probability_per_district = crime_per_district / total_crimes
print(probability_per_district)
import matplotlib.pyplot as plt
import seaborn as sns
plt.figure(figsi... | Python | 1 |
: 0.4361561, w: 1.0 } }
dragon.set_transformation(translation(0., 0.69, 0.));
eprintln!("Finished parsing dragon");
dragon
}
fn get_scene_element(
mut dragon: GroupShape,
element_transform: Matrix,
dragon_material: Material,
display_case_material: Option<Material>,
) -> GroupShape {
l... | Rust | 0 |
//! The module for parsing method attributes.
pub mod code;
use crate::{constant_pool::ConstantPool, error::Result};
use self::code::{attribute::CodeAttribute, instruction::Instruction, parse_code_attr, Exception};
use super::Attribute;
/// All possible method attributes.
pub enum MethodAttribute {
/// The [Cod... | Rust | 0 |
, PartialEq, Eq, Serialize, Deserialize)]
pub struct LinearElasticMaterial;
#[allow(non_snake_case)]
fn infinitesimal_strain_tensor<T, D>(deformation_gradient: &OMatrix<T, D, D>) -> OMatrix<T, D, D>
where
T: RealField,
D: DimName,
DefaultAllocator: DimAllocator<T, D>,
{
let F = deformation_gradient;
... | Rust | 0 |
(n);
}
}
}
// Any black tile with zero or more than 2 black tiles
// immediately adjacent to it is flipped to white.
// Any white tile with exactly 2 black tiles
// immediately adjacent to it is flipped to black.
// iterate through them and ... | Rust | 0 |
del has 24 transformer layers, layer_id goes from 0 to 23.
Arguments:
config: An object of LSTransformerEncoderLayer config, see get_config
initial_weights: Optional: Only used for unit test
initial_biases: Optional: Only used for unit test
"""
@staticmethod
def get_config(**k... | Python | 1 |
t rhs_nodes = rhs_nodes;
let mut changed = false;
while let (Some(lhs_node), Some(rhs_node)) = (lhs_nodes.first(), rhs_nodes.first()) {
// We don't consider TINY_TREE_THRESHOLD here because we are
// only considering equal nodes at the beginning or end of the
// file. There's no risk we... | Rust | 0 |
}
fn l577_2_checkcom2(&mut self, chn: usize, mut mixer: &mut Mixer) {
match self.voice[chn].n_2_cmd & 0xf {
0xe => self.l577_h_setfilt(chn, &mut mixer),
0xd => self.l577_i_pattbreak(),
0xb => self.l577_j_mt_posjmp(chn),
0xc => self.l577_k_setvol(chn),
... | Rust | 0 |
"""
Copyright (c) 2020 Alan Yorinks All rights reserved.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
Version 3 as published by the Free Software Foundation; either
or (at your option) any later version.
This library is distribut... | Python | 1 |
from src.utils.logging import get_logger
logger = get_logger(__file__)
def main():
pass
if __name__ == "__main__":
main()
| Python | 1 |
max_guess = guess
return LlmClient.__truncate_message(message, direction_callback, min_guess, max_guess)
@abstractmethod
def chat_completion(
self,
messages: Iterable[ChatCompletionMessageParam],
model: str,
frequency_penalty: Optional[float] | NotGiven = NO... | Python | 1 |
ext( ) );
// Light source 2 and 4 contribute on the right
tree.insert( rng.next_in_range( 2, 4 ), Vec3::new( 0.5 + 0.5 * rng.next( ), rng.next( ), rng.next( ) ), rng.next( ) );
}
//println!( "{:?}", tree );
println!( "Added: {:?}", SystemTime::now( ).duration_since( t1 ) );
println!( "Sampling l... | Rust | 0 |
/// of operation is proportional to the depth of the tree
pub fn replace_with(&self, replacement: GreenNode) -> GreenNode {
assert_eq!(self.kind(), replacement.kind());
match self.parent() {
None => replacement,
Some(parent) => {
let me = self.parent_data().un... | Rust | 0 |
int_array_def(self.ptr, "data7").unwrap();
qv.into_value().unwrap()
}
pub fn data7(&self) -> &Vec<i64>{
let qv = root::get_immutable_int_array(self.ptr, "data7").unwrap();
qv.into_value().unwrap()
}
pub fn data7_mut(&mut self) -> &mut Vec<i64>{
let qv = root::get_mutable_int_array(self.ptr, "data7").unwrap(... | Rust | 0 |
"""
Cart-pole balancing with continuous / Kernelized iFDD
"""
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from past.utils import old_div
from r... | Python | 1 |
7, 0xE0E2_F13B),
(r"meshes\c\c_glove_expensive1_gnd.nif", 0x0906_1A67, 0xF711_C7B5),
(r"meshes\c\c_glove_balmolagmer_gnd.nif", 0x0906_7867, 0x00CA_D6C6),
(r"meshes\c\c_glove_balmolagmer.1st.nif", 0x0906_7867, 0xF204_9DD0),
(r"meshes\c\c_glove_extravagant1_gnd.nif", 0x0906_7F67, 0x4757_3D75),
(r... | Rust | 0 |
..)` method takes [tcd4_slast::W](tcd4_slast::W) writer structure"]
impl crate::Writable for TCD4_SLAST {}
#[doc = "TCD Last Source Address Adjustment"]
pub mod tcd4_slast;
#[doc = "TCD Destination Address\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](cra... | Rust | 0 |
match self.msg.get() {
Some(msg) => write!(f, "deflate compression error: {}", msg),
None => write!(f, "deflate compression error"),
}
}
}
#[cfg(test)]
mod tests {
use std::io::Write;
use crate::write;
use crate::{Compression, Decompress, FlushDecompress};
#[cf... | Rust | 0 |
import requests
import tkinter as tk
from tkinter import ttk
def main():
response = requests.get("https://api.opendota.com/api/heroes")
list_of_heroes= response.json()
root = tk.Tk()
root.title("DOTA_HEROES")
title = root.title()
window_width = 600
window_height = 400
#Screen d... | Python | 1 |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# Using the implementation provided at
# https://github.com/aaron-xichen/pytorch-playground/blob/master/mnist/model.py
... | Python | 1 |
inp.witness.clone()
});
}
Transaction {
version : tx.version,
lock_time : tx.lock_time,
input : signed_inp,
output: tx.output
}
}
/// Serialize a signature into bytes with the SIGHASH flag appened inside
/// the signature which is how Bitcoin Script expects it
/... | Rust | 0 |
0xA9, 0x20, 0x8D, 0x00, 0x44];
/// let asm = dasm.disassemble(&code);
///
/// assert_eq!(Disassembler::clean_asm("
///
/// LDA #$20
/// STA $4400
///
/// "), Disassembler::clean_asm(asm));
/// ```
pub fn with_code_only() -> Disassembler {
Disassembler {
... | Rust | 0 |
ort::serde::{Deserialize, Serialize};
use sp_std::convert::{TryFrom, TryInto};
use cumulus_primitives_core::{
relay_chain, relay_chain::BlockNumber as RelayBlockNumber, ServiceQuality, XcmpMessageFormat,
XcmpMessageHandler,
};
use xcm::VersionedXcm;
type XCMPMessageOf<T> = XCMPMessage<
<T as frame_system::Config>... | Rust | 0 |
otocols/009_florence.html#endorsements-now-checked-in-linear-time-attention-indexers
//! and https://tezos.gitlab.io/protocols/009_florence.html#new-failing-noop-operation.
pub use super::super::proto_008_2::operation::{
ActivateAccountOperation, BallotOperation, ContractId, DelegationOperation,
DoubleBakingEv... | Rust | 0 |
ize) -> u64 {
let mut circle = CupsCircle::new(data, end);
for _ in 0..moves {
let tripple_begin = circle.take_tripple();
let position = circle.find_position();
circle.put_tripple_back(tripple_begin, position);
}
let ptr = (unsafe { &*circle.number_1.as_ptr() }).next.as_ptr();
... | Rust | 0 |
"""
Expose version
"""
from __future__ import annotations
__version__ = "3.4.1"
VERSION = __version__.split(".")
| Python | 1 |
propriate authoritative source has been found
/// for clearing each specific channel.
#[derive(Clone, AtatCmd)]
#[at_cmd("+UWCL", WifiScanResponse, timeout_ms = 10000)]
pub struct SetChannelList {
#[at_arg(position = 0)]
pub channels: Vec<u8, 10>,
}
/// 7.5 Wi-Fi station status +UWSSTAT
///
/// Writes the re... | Rust | 0 |
"""The wsdot component."""
| Python | 1 |
/// # let mut group: Group = todo!();
/// use serenity::utils;
///
/// // assuming a `guild` has already been bound
///
/// let base64_icon = utils::read_image("./group_icon.png")?;
///
/// group.edit(&http, |mut g| g.icon(Some(&base64_icon))).await?;
/// # Ok(())
/// # }... | Rust | 0 |
::piped())
.arg("-i")
.arg("-F")
.arg(&cpio_filename)
.spawn()?;
proc.wait()?;
let o_filename = o_dir.join(o_name);
if fs::metadata(&o_filename)?.is_file() {
if let Some(x) = rename {
let dest_filename = o_dir.join(x);
fs::copy(&o_filename, &de... | Rust | 0 |
&s;
let r2 = &s;
//let r3 = &mut s; //mutable borrow occurs here
println!("s, r1, r2: {} {} {}", s, r1, r2);
}
fn calc_len(s: &String) -> usize {
//s.push_str(", world"); //cannot borrow as mutable
println!("(calc_len) s: {}", s);
s.len()
}
fn change(s: &mut String) {
s.push_str(", world"... | Rust | 0 |
# generate new data
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import tclab
import time
n = 3600 # Number of second time points (60 min)
tm = np.linspace(0,n,n+1) # Time values
lab = tclab.TCLab()
T1 = [lab.T1]
T2 = [lab.T2]
Q1 = np.zeros(n+1)
Q2 = np.zeros(n+1)
# random duration on (10-3... | Python | 1 |
for field in reported_fields:
if field not in new_store[sensor]:
initial_val = _round_null(status[sensor][field], 2)
new_store[sensor][field] = deque(
[initial_val], maxlen=self.temp_store_size
... | Python | 1 |
fn check_display() {
let a = Conformer::new("A", None, None).unwrap();
format!("{:?}", a);
format!("{}", a);
}
}
<filename>src/n0128_longest_consecutive_sequence.rs<gh_stars>1-10
/**
* [128] Longest Consecutive Sequence
*
* Given an unsorted array of integers, find the length of the longe... | Rust | 0 |
PresetSpeke20Video::PresetVideo1 => "PRESET-VIDEO-1",
PresetSpeke20Video::Unknown(s) => s.as_ref(),
}
}
}
impl AsRef<str> for PresetSpeke20Video {
fn as_ref(&self) -> &str {
self.as_str()
}
}
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,... | Rust | 0 |
from gmpy2 import isqrt
from Crypto.Util.number import long_to_bytes
x = 0x152a1447b61d023bebab7b1f8bc9d934c2d4b0c8ef7e211dbbcf841136d030e3c829f222cec318f6f624eb529b54bcda848f65574896d70cd6c3460d0c9064cd66e826578c2035ab63da67d069fa302227a9012422d2402f8f0d4495ef66104ebd774f341aa62f493184301debf910ab3d1e72e357a99c460370... | Python | 1 |
verb
if wordtag_const.verbPattern[170].search(starword) and starword.count("*")>=2 :
return -170;
# the word ends with an added araby.TEH
if wordtag_const.verbPattern[180].search(guessed_word):
return -180;
# the word starts with an added araby.YEH
if wordtag... | Python | 1 |
io_tensor)
# Extract pitch and uncertainty
pitch_outputs = model_output["pitch"].numpy()
uncertainty_outputs = model_output["uncertainty"].numpy()
# Convert uncertainty to confidence
confidence_outputs = 1.0 - uncertainty_outputs
# Convert SPICE pitch outpu... | Python | 1 |
rts)
def download_file(url: str, filename: Path, attempts: int = 3):
assert attempts > 0
while True:
attempts -= 1
try:
urllib.request.urlretrieve(url, filename)
return
except Exception as e:
if attempts == 0:
raise e
else... | Python | 1 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-09-08 16:08
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Info',
... | Python | 1 |
: Vec<Vec<i32>> = vec![
vec![-1, -1, 2],
vec![-1, 0, 1]
];
assert_eq!(ans.sort(), Solution::three_sum(case).sort());
}
}
use serde_json::{ Value, from_value };
use serde::Deserialize;
use serde::Deserializer;
use algorithm::data_structure::graph::Graph;
#[derive(Serialize, D... | Rust | 0 |
from Drivers.Driver import Driver
import smbus
from time import sleep
class AntennaDoor(Driver):
def __init__(self):
super().__init__("AntennaDoor") #Calls parent constructor
"""
Sets up I2C bus for communication
"""
self.DEVICE_BUS = 1
self.DEVICE_ADDR = 0x33
... | Python | 1 |
# Code generated by lark_sdk_gen. DO NOT EDIT.
from pylark.lark_request import RawRequestReq, _new_method_option
import attr
import typing
import io
@attr.s
class GetHireOfferByApplicationReqUserIDType(object):
pass
@attr.s
class GetHireOfferByApplicationReq(object):
user_id_type: GetHireOfferByApplication... | Python | 1 |
) -> c_int;
pub fn Sylvan_mtbdd_fprintdot(out: *mut FILE, mtbdd: MTBDD) -> c_void;
pub fn Sylvan_fprintdot(out: *mut FILE, mtbdd: MTBDD) -> c_void;
pub fn Sylvan_mtbdd_printdot(mtbdd: MTBDD) -> c_void;
pub fn Sylvan_printdot(mtbdd: MTBDD) -> c_void;
pub fn Sylvan_mtbdd_fprintdot_nc(out: *mut FILE, m... | Rust | 0 |
= cx.argument(0)?;
let blinding_buffer: Handle<JsArrayBuffer> = cx.argument(1)?;
let token_bytes = cx.borrow(&token_buffer, |data| data.as_slice());
let blinding_bytes = cx.borrow(&blinding_buffer, |data| data.as_slice());
if token_bytes.len() != Token::BYTES ||
blinding_bytes.len() != Blindi... | Rust | 0 |
, "mac: {}", mac).unwrap();
write(&mut display, textbuffer.as_str(), Point::new(3, 3));
textbuffer.truncate(0);
let ip_info = unsafe {
WIFI.as_mut()
.map(|wifi| {
wifi.connect_to_ap(
&mut delay,
"NETWORK_NAME",
... | Rust | 0 |
import torch
from diffusers import DDIMScheduler
def rescale_noise_scheduler_to_zero_terminal_snr(noise_scheduler: DDIMScheduler):
"""
From: Common Diffusion Noise Schedules and Sample Steps are Flawed (https://arxiv.org/abs/2305.08891)
Rescales the
Args:
noise_scheduler: The noise schedule... | Python | 1 |
b struct Pins {
pub rxd: GpioPin<Input<Floating>>,
pub txd: GpioPin<Output<PushPull>>,
pub cts: Option<GpioPin<Input<Floating>>>,
pub rts: Option<GpioPin<Output<PushPull>>>,
}
mod private {
pub trait Sealed {}
impl Sealed for crate::pac::UARTE0 {}
#[cfg(any(feature = "52833", feature = "52... | Rust | 0 |
fn fresh(&self) -> Self {
Self::new(self.inner.fresh())
}
fn finish(mut self) -> Self::Output {
let key = self.key.take().unwrap();
let inner = self.inner.finish();
PartitionInnerBuffer { inner, key }
}
fn num_items(&self) -> usize {
self.inner.num_items()... | Rust | 0 |
bsdf.add(bxdf);
// Sheen if enabled
if sheen_weight > 0.0 {
let bxdf: &mut BxDFs = arena.alloc(DisneySheen::new(csheen * sheen_weight * dweight).into());
bsdf.add(bxdf);
}
}
// Create the microfacet distribution for metallic and/or sp... | Rust | 0 |
file.seek(SeekFrom::Start(0)).await.into_diagnostic()?;
file.write_all(minified.as_bytes())
.await
.into_diagnostic()?;
Ok(())
}
#[async_trait]
impl Command for Compress {
/// Display a help menu for the `volt compress` command.
fn help() -> String {
format!(
r#"vo... | Rust | 0 |
: &'static str = "~";
pub const STR_NOT2: &'static str = "!";
pub const STR_AND : &'static str = "&";
pub const STR_AND2: &'static str = "^";
pub const STR_OR : &'static str = "v";
pub const STR_IF : &'static str = "->";
pub const STR_IFF : &'static str = "<->";
pub const STR_PRETTY_NOT: &'static str = "¬";
pub con... | Rust | 0 |
0x2143);
/// ```
pub const fn swap_bits(bits: u64, m1: u64, m2: u64) -> u64 {
// now make the ALU hot
(bits & !(m1|m2)) // clear affected bits
| (((bits&m1) >> m1.trailing_zeros()) << m2.trailing_zeros()) // move m1 bits to m2
| (((bits&m2) >> m2.trailing_zeros()) << m1... | Rust | 0 |
/// [`read_remote_version_information`](crate::host::Hci::read_remote_version_information)
/// command. The connection handle shall be for an ACL connection.
pub conn_handle: ConnectionHandle,
/// Version of the Current LMP in the remote Controller. See [LMP] version and [Link Layer]
/// version in... | Rust | 0 |
l_start: compat_off_t,
pub l_len: compat_off_t,
pub l_pid: compat_pid_t,
}
/// using 'struct flock64'
pub const F_GETLK64: i32 = 12;
pub const F_SETLK64: i32 = 13;
pub const F_SETLKW64: i32 = 14;
/// IA32 uses 4 byte alignment for 64 bit quantities,
/// so we need to pack this structure.
#[repr(C)]
#[derive(... | Rust | 0 |
import matplotlib.pyplot as plt
import numpy as np
x = np.array([])
y = np.array([])
previous = 0
highest_gradiant = 0
highest_gradiant_at = 0
g = np.array([])
for n in range(50):
product = 1
denominator = 1
for i in range(n):
product *= 366-n
denominator *= 365
# calculate the probabil... | Python | 1 |
global obf8wrkwncw
'# difficulties_punches_electrolyte -> trick_relief_swing'
r8aym0smfhu = ''
'# difficulties_punches_electrolyte -> trick_relief_swing'
return
p_n8chdb601
raise c2k_1lvwn_s
pass
'# difficulties_punches_electrolyte -> trick_relief_swing'
@(b'' for ob58_ddl4j0 in zsa... | Python | 1 |
// If the example wrote to `stderr` it must have failed.
if !output.stderr.is_empty() {
panic!("example {} wrote to stderr: {:?}", name, output);
}
}
}
<gh_stars>10-100
extern crate batch_example_rabbitmq_warp as example;
use tokio::prelude::Future;
use crate::example::{endpoints, ... | Rust | 0 |
'''
实验名称:ADC-电压测量
版本:v1.0
作者:WalnutPi
说明:通过对ADC数据采集,转化成电压在显示屏上显示。ADC精度12位(0~4095),测量电压0-3.3V。
'''
#导入相关模块
from machine import Pin,ADC,Timer
import time
#构建ADC对象
adc1 = ADC(Pin(0)) #使用引脚9
adc1.atten(ADC.ATTN_11DB) #开启衰减器,测量量程增大到3.3V
#构建ADC对象
adc2 = ADC(Pin(1)) #使用引脚9
adc2.atten(ADC.ATTN_11DB) #开启衰减器,测量量程增大到3.3V
def A... | Python | 1 |
convert_to_base: |value| {
(value + KELVIN_FAHRENHEIT_1.clone()) / KELVIN_FAHRENHEIT_0.clone()
},
convert_from_base: |value| {
(value * KELVIN_FAHRENHEIT_0.clone()) - KELVIN_FAHRENHEIT_1.clone()
},
},
],
... | Rust | 0 |
Encoder + Decoder,
<Codec as Encoder>::Item: 'static,
<Codec as Encoder>::Error: std::fmt::Debug,
{
type Item = ();
type Error = ServiceError<C::Error, Codec>;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match self.inner {
FramedServiceImplResponseInner::Connect(ref mu... | Rust | 0 |
st Lorem ipsum dolor sit amet.";
#[test]
fn basic_static() {
test_static(EMPTY);
test_static(ONE);
test_static(MANY);
test_static(LARGE.as_bytes());
}
fn test_static(slice: &'static [u8]) {
let slice_ptr = slice.as_ptr();
let bin = NewBin::from_static(slice);
assert_eq!(slice.len(), bin.le... | Rust | 0 |
import numpy as np
# from https://github.com/songrotek/DDPG/blob/master/ou_noise.py
class OUNoise:
def __init__(self, action_dimension, scale=0.1, mu=0, theta=0.15, sigma=0.2):
self.action_dimension = action_dimension
self.scale = scale
self.mu = mu
self.theta = theta
self.... | Python | 1 |
>
+ Send
+ Sync
+ 'static,
>(
&self,
digest: Digest,
path_so_far: PathBuf,
f: Arc<F>,
accumulator: Arc<Mutex<Vec<T>>>,
workunit_store: WorkUnitStore,
) -> BoxFuture<(), String> {
let store = self.clone();
self
.load_directory(digest, workunit_store.clone())
... | Rust | 0 |
let r = rotations::<T>().unwrap();
a = U(a, b); d = d ^ a; d = d.rotate_right(r[0]);
c = U(c, d); b = b ^ c; b = b.rotate_right(r[1]);
a = U(a, b); d = d ^ a; d = d.rotate_right(r[2]);
c = U(c, d); b = b ^ c; b = b.rotate_right(r[3]);
return (a, b, c, d);
}
#[allow(non_snake_case)]
fn F<T: Int>(x ... | Rust | 0 |
#
# This is a barebones script that tries to detect all cameras.
#
# It works by cycling through all possible IDs from 0 to 99 and seeing if they exist
# and if they do, tries to get info about it, such as serial number and USB port
# location. This will run under both Linux/Pi and Windows, but you'll get much more inf... | Python | 1 |
}],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.depth_pass.texture.view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: self.selected_pass == Selecte... | Rust | 0 |
IDER;
let expiryDate: u64 = f.params.expiry_date().value() / NANO_TIME_DIVIDER;
let ppNew = ProductPass{
id: id,
did: did,
name: name,
issuer: issuer,
version: version,
purpose: purpose,
charge_weight: chargeWeight, // in miligramm
package_weight:... | Rust | 0 |
dma_write(&mut self, address: u8, xfer_len: u8) {
if !self.get_smart_mode() {
self.disable();
self.set_smart_mode(true);
self.enable();
}
self.i2c_master().addr.write(|w| unsafe {
w.addr().bits(encode_write_address(address));
w.len().b... | Rust | 0 |
| ((header.version.1 as u32) << 8)
| header.version.2 as u32;
PhysicalLayout {
magic_number: MAGIC_NUMBER,
version,
generator: header.generator,
bound: 0,
instruction_schema: 0x0u32,
}
}
pub(super) fn in_words... | Rust | 0 |
# Copyright 2024 Google LLC
#
# 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 writing, ... | Python | 1 |
"""
交易模式處理器模組
此模組負責處理不同的交易模式執行邏輯,整合各個模式處理器:
- 回測模式處理
- 模擬交易模式處理
- 實盤交易模式處理
主要功能:
- 提供統一的模式處理介面
- 整合各個專門的處理器模組
- 向後相容性支援
Example:
>>> from src.core.mode_handlers import run_backtest_mode
>>> config = {"mode": "backtest", ...}
>>> results, report = run_backtest_mode(config)
"""
import logging
from typing ... | Python | 1 |
0db8:85a3:0000:0000:8a2e:0370:7334 是无效的。
示例 1:
输入:IP = "172.16.254.1"
输出:"IPv4"
解释:有效的 IPv4 地址,返回 "IPv4"
示例 2:
输入:IP = "2001:0db8:85a3:0:0:8A2E:0370:7334"
输出:"IPv6"
解释:有效的 IPv6 地址,返回 "IPv6"
示例 3:
输入:IP = "256.256.256.256"
输出:"Neither"
解释:既不是 IPv4 地址,又不是 IPv6 地址
示例 4:
输入:IP = "2001:0db8:85a3:0:0:8A2E:0370:7334:"
输出:... | Rust | 0 |
_batch is not None:
pred_hand_contact_prob_seq = pred_hand_contact_prob_batch[bs].to(device) # [T, 3]
# Convert probabilities to 0/1 labels
pred_contact_labels = (pred_hand_contact_prob_seq > 0.5).bool()
pred_lhand_contact_labels_seq = pred... | Python | 1 |
time_http3 and total_time_http2:
latencies['http3'].append(total_time_http3)
latencies['http2'].append(total_time_http2)
else:
print("Skipped iteration due to missing curl output.")
return latencies
# Interface and URL to test
interface = "wlp2s0" # Replace wi... | Python | 1 |
00, 0x64, 0x63, 0x58,
0x4d, 0x42, 0x37, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00,
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
... | Rust | 0 |
mut self) -> Result<TokenKind, Error> {
let symbol = match self.consume_char() {
',' => Symbol::Comma,
':' => Symbol::Colon,
'[' => Symbol::LBracket,
']' => Symbol::RBracket,
'+' => Symbol::Plus,
'-' => Symbol::Minus,
';' => {
... | Rust | 0 |
].strip()
if base_role_before in avail and base_role_before != '酒鬼':
avail.remove(base_role_before)
if base_role in avail:
avail.remove(base_role)
else:
base_role = row[-1]
if base... | Python | 1 |
riter.write_all(&buf)
}
fn write_tag_ids_dictionary<W>(
writer: &mut W,
tag_ids_dictionary: &TagIdsDictionary,
) -> io::Result<()>
where
W: Write,
{
let mut buf = Vec::new();
for keys in tag_ids_dictionary.iter() {
for key in keys {
let id = key.id();
buf.push((id >... | Rust | 0 |
exp: String::from("") });
let while_stmt = to_pos!(Node::While { cond, body });
let (core_cond, core_body) = match desugar(&while_stmt) {
Ok(Core::While { cond, body }) => (cond, body),
other => panic!("Expected reassign but was {:?}", other)
};
assert_eq!(*core_cond, Core::Id { lit: S... | Rust | 0 |
ut2[:, -1:, :, :] #B, 1, N, hidden
output2 = self.dropout2(output2[:, -1:, :, :])
output2 = self.end_conv2(output2)
return self.alpha*output1 + (1-self.alpha)*output2
# return output1
# if i == 1:
# init_state1 = self.encoder1.ini... | Python | 1 |
.0) < std::f32::EPSILON);
d = DistanceAlg::Manhattan.distance3d(Point3::new(0, 0, 0), Point3::new(5, 5, 5));
assert!(f32::abs(d - 15.0) < std::f32::EPSILON);
}
#[test]
fn test_chebyshev_distance() {
let mut d = DistanceAlg::Chebyshev.distance2d(Point::new(0, 0), Point::new(5, 0));
... | Rust | 0 |
git/rust
// compile-flags: --edition=2018
use core::{
future::Future,
marker::Send,
pin::Pin,
};
fn non_async_func() {
println!("non_async_func was covered");
let b = true;
if b {
println!("non_async_func println in block");
}
}
async fn async_func() {
println!("async_func ... | Rust | 0 |
ranslate_fn("/2/groups/", group_name, "/rename"):
rlib2.R_2_groups_name_rename,
translate_fn("/2/groups/", group_name, "/assign-nodes"):
rlib2.R_2_groups_name_assign_nodes,
translate_fn("/2/groups/", group_name, "/tags"):
rlib2.R_2_groups_name_tags,
"/2/jobs": rlib2.R_2_jobs,
translat... | Python | 1 |
import os
import torch
import discord
from discord.ext import commands
from transformers import pipeline
from PIL import Image
import io
from cogs.premium.premium import PremiumDatabase
class NSFWDetection(commands.Cog):
def __init__(self, bot):
device_id = 0 if torch.cuda.is_available() else -1
se... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.