text string | label_name string | labels int64 |
|---|---|---|
fn value(&self) -> usize {
match self.packet_type {
PacketType::Literal(v) => v,
PacketType::Operator(id, ref sub_packets) => {
match id {
0 => {
let mut val = 0;
self.run(|p, val| *val += p.value(), &mu... | Rust | 0 |
me = (pygame.time.get_ticks() - start_pause_time) / 1000
if elapsed_time >= pause_time:
if self.coin.result == choices:
self.toss(1)
self.call_menu()
else:
self.toss(0)
result = random.choice([0, ... | Python | 1 |
from .series import BaseSeries
class GroupedBarSeries(BaseSeries):
def __init__(self, groups, categories, values, group_colors=None, bar_width=0.8):
self.groups = groups
self.categories = categories
self.values = values # 2D list: [group][category]
self.group_colors = group_colors ... | Python | 1 |
e abi_stable::{std_types::RArc, DynTrait, RMut, RRef};
///
/// unsafe {
/// let to: DynTrait<'static, RRef<'_, ()>, ()> = DynTrait::from_any_ptr(&9u8, ());
///
/// assert_eq!(to.unchecked_downcast_as::<u8>(), &9u8);
/// }
/// unsafe {
/// let m... | Rust | 0 |
fn drw_two_byte_sprite_overlap_collision() {
uses!(mut cpu);
let bytes = &[0x9A, 0x3C];
cpu.memory.store(0x100, bytes);
cpu.ri = 0x100;
cpu.v[0x0] = 2;
cpu.decode_execute(0xD001);
cpu.ri = 0x101;
cpu.decode_execute(0xD001);
assert_eq!(1, cpu.v[0xF]... | Rust | 0 |
_inference.infer_type(value, &[]));
let type_checked_filter = typed_filter.map(|value| self.type_checker.type_check(value));
let type_coerced_filter = type_checked_filter.map(|value| self.type_coercion.coerce(value));
Ok(TypedQuery::Update(TypedUpdateQuery {
... | Rust | 0 |
messages/{}",
self.api_key, self.storage_endpoint, self.domain, message_id
))
.send()
.await?
.json::<T>()
.await;
response
}
}
#[tokio::test]
async fn shoul_send_email_with_text() {
use super::EmailParams;
use dotenv::dot... | Rust | 0 |
fix}.pth'
save_path = os.path.join(config.output, filename)
torch.save(save_state, save_path)
##### this is for per epoch saving, easy for resuming #####
if suffix == 'best_miou':
print('saving best iou checkpoint')
filename = 'best_miou.pth' # only save the best one
... | Python | 1 |
import os
import sys
import yaml
from signLanguage.utils.main_utils import read_yaml_file
from signLanguage.logger import logging
from signLanguage.exception import SignException
from signLanguage.entity.artifacts_entity import ModelTrainerArtifact
from signLanguage.entity.config_entity import ModelTrainerConfig
class... | Python | 1 |
);
if let Some(nc::WchResult::Char(chr)) = key {
if let Some(mut key) = Curses::key_from_char(chr) {
key.modifier |= KeyPress::ALT;
return Some(Event::KeyPress(key));
}
}
... | Rust | 0 |
VK_SPACE => Key::Space,
VK_BACK => Key::Backspace,
VK_SHIFT => Key::Shift,
VK_CONTROL => Key::CtrlL,
VK_ESCAPE => Key::Esc,
VK_F1 => Key::F1,
VK_F2 => Key::F2,
VK_F3 => Key::F3,
VK_F4 => Key::F4,
VK_F5... | Rust | 0 |
*/
/* input to be strictly less than the prime modulus (m), and also */
/* require the input to be in the unique saturated representation. */
/* All functions also ensure that these two properties are true of */
/* return values. */
#![allow(unused_parens)... | Rust | 0 |
存放实际偏移,其余非关键点处的偏移量为0
incmap_valid: [h,w] 关键点位置为1,其余为0,用于训练时屏蔽对非关键点偏移量的训练,只关注关键点的偏移量
"""
height = self.height
width = self.width
# localmap = self.localmap.clone()
# padded_heatmap = torch.zeros(
# (height+self.g_paddings*2, width+self.g_paddings*2), dtyp... | Python | 1 |
c = get_config() # noqa
# our user list
c.Authenticator.allowed_users = ['minrk', 'ellisonbg', 'willingc']
service_name = 'shared-notebook'
service_port = 9999
group_name = 'shared'
# ellisonbg and willingc are in a group that will access the shared server:
c.JupyterHub.load_groups = {group_name: ['ellisonbg', 'wi... | Python | 1 |
32 = 1000;
const DEFAULT_NESTED_OBJECTS_LIMIT: i32 = 10000;
const DEFAULT_TOTAL_FIELDS_LIMIT: i32 = 1000;
const DEFAULT_MAX_TERMS_COUNT: i32 = 65535;
const DEFAULT_MAX_ANALYZE_TOKEN_COUNT: i32 = 10000;
const DEFAULT_URL: &str = "default";
const DEFAULT_TYPE_NAME: &str = "doc";
const DEFAULT_REFRESH_INTERVAL: &str = "-1... | Rust | 0 |
ans = (str(a1)+'.'+str(b1)+'.'+str(c1)+'.'+str(d1)+" "+netmask)
return(ans)
elif n < p:
j = p/n
j2 = int(o/j)
i = int(256/j)
c1 = int(c1/n)*n+j2
d1 = int((o%j-1)*i+ip)
a1,b1,c1,d1 = Carry(a1,b1,c1,d1)
m = int(256-i)
netmask = ("255.255.255... | Python | 1 |
serde_json::Value>,
unitary_state: Matrix,
number_of_operations: usize
}
impl UnitarySimulator {
pub fn new(compiled_circuit: String) -> Result<UnitarySimulator, String> {
let circuit : serde_json::Value = match serde_json::from_str(compiled_circuit.as_str()) {
Ok(_circuit) => _circuit... | Rust | 0 |
efexp.
images = {}
# Maps annotation id to annotation object that concatenates the annotation info from both coco and refexp.
annotations = {}
# Maps refering expression id to refexp object that contains refering expression info from Google refexp.
refexps = {}
# Annotations from GoogleRefexp.
googleRe... | Python | 1 |
common::{exp_0sim::*, output::OutputManager, paths::setup00000::*},
settings,
};
pub fn cli_options() -> clap::App<'static, 'static> {
fn is_usize(s: String) -> Result<(), String> {
s.as_str()
.parse::<usize>()
.map(|_| ())
.map_err(|e| format!("{:?}", e))
}
... | Rust | 0 |
from itertools import takewhile
nums = [1,1,2,3,4,2,6,8,10,11,13,15,1,4]
print(list(takewhile(lambda x: x < 10, nums)))
print(nums)
| Python | 1 |
null::<cudaExternalMemoryMipmappedArrayDesc>())).offset as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(cudaExternalMemoryMipmappedArrayDesc),
"::",
stringify!(offset)
)
);
assert_eq!(
... | Rust | 0 |
map = build_codons("inputs/codons")?;
let input = fs::read_to_string("inputs/rosalind_prot.txt")?;
let output = translate(&input, &map);
println!("{}", output);
Ok(())
}
#[test]
fn sample() {
let map = build_codons("inputs/codons").unwrap();
let input = "AUGGCCAUGGCGCCCAGAACUGAGAUCAAUAGUACCCGUAUUAACGGGUGA... | Rust | 0 |
Condition::new("countriesOrRegions", CONTAINS_ANY, vec!["US", "GB"]),
Condition::new("countryOrRegion", IN, vec!["US"]),
])
.set_pagination(pagination);
let mut reporting_request = ReportingRequest::new(
"2020-08-04".parse().unwrap(),
"2020-08-1... | Rust | 0 |
Router-Uncredentialed">
<ReportHost name="10.129.121.252">
<HostProperties>
<tag name="cpe-3">cpe:/a:mysql:mysql:5.5.9 -> MySQL 5.5.9</tag>
<tag name="cpe-2">cpe:/a:mysql:mysql:5.5.9 -> MySQL 5.5.9</tag>
<tag name="netbios-name">ECLIPSE</tag>
<tag name="... | Rust | 0 |
, 10.0).map_err(anyhow::Error::msg)?;
let creator = canvas.texture_creator();
let mut texture = creator.create_texture_target(PixelFormatEnum::RGB24, 32, 32)?;
let mut screen_state = [0; 32 * 3 * 32];
let mut rng = rand::thread_rng();
let rom_file = std::fs::read("roms/snake.nes")?;
let rom =... | Rust | 0 |
Parens(expr) => eval_b(expr),
}
}
}
fn eval(expr: &[TermOrOp]) -> usize {
let mut it = expr.iter();
assert!(expr.len() >= 3);
// dbg!(expr.len());
assert!(expr.len() % 2 == 1);
let mut accum: usize = it.next().unwrap().as_term().eval();
while let Some(orop) = it.next() {
... | Rust | 0 |
} else {
Some(b)
}
})
.flatten()
.collect();
});
}
// Update known weights
bags
.iter()
.for_each(|bag| {
i... | Rust | 0 |
### pip install polyglot morfessor==2.0.6 pycld2==0.41 pyicu
### polyglot download pos2.da
from polyglot.tag import NEChunker, POSTagger
from polyglot.text import Text, WordList
from spacy.lang.da import Danish
from spacy.tokens import Doc
from spacy.training import Example
from .apply_fn_utils import add_iob, apply_... | Python | 1 |
tmul0_latency}\n{h1_matmul1_latency}\n{h2_matmul2_latency}\n{rope_latency}\n{softmax_latency}\n{add_latency}\n{add_latency}\n{add_latency}\n{rmsnorm_latency}\n{rmsnorm_latency}\n{rmsnorm_latency}\n{silu_latency}\n{element_wise_multiply_latency}\n{allreduce_total_latency}\n"
)
print("total:")
pri... | Python | 1 |
IsTooBig),
cmp::Ordering::Equal => {
let mut t = [0u8; 64];
t.copy_from_slice(bytes);
Ok(Signature(t))
}
})
}
}
impl Default for Signature {
#[inline]
fn default() -> Self {
Signature([0; 64])
}
}
impl Display for ... | Rust | 0 |
Zpyh?\<ߥ1n~+_[H]^ zߚE 43 d;֚_ZSv~uu~L|KիɗdoCdﯽˤBx:+HZJ,FFYjq%@@z {N* 9\rQLb?<QZJD~}Ѿܚ"O|]Q87[S\鶣
Ьr>WEc5@WSj6cӕV]Pm_Q 8|f";)SAjSIAbl$*MNf>o?9;N!Wc'ؼ;/,ۡ`%ī_ m|We>χv|AN$~LJí;IZe?"lwbbR**:ޤ ~F;i
oCmv%h4-s`Fzj
b+5;{u;8O{6;$CVl:tԑK`'q> @EG\Kx437Hs=N... | Python | 1 |
# Generated by Django 4.2.7 on 2025-09-11 06:49
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('compliance', '0002_initial'),
('kyc', '0001_initial'),
... | Python | 1 |
x),
_ => {
println!("Warning: ignoring unknown query option {}", arg);
}
}
}
fn main() {
let mut conf = ResolvConf::default();
let mut names = Vec::new();
for arg in env::args().skip(1) {
if arg.starts_with('+') {
parse_queryopt(&mut conf, &arg)
}... | Rust | 0 |
1')
save_model = os.path.join(self.temp_dir.name, 'save2')
input_spec = [
paddle.static.InputSpec(shape=[1, 3, 224, 224], dtype='float32')
]
paddle.jit.save(net, save_json, input_spec)
# load and save to pdmodel
with paddle.pir_utils.OldIrGuard():
... | Python | 1 |
}
// Convenience for this module
pub(crate) fn into_vector(self) -> Vec3<$Point<T>> {
self.into_vec3()
}
/// Converts this curve into a `Vec3` of points.
pub fn into_vec3(self) -> Vec3<$Point<T>> {
self.into()
}
... | Rust | 0 |
#!/usr/bin/python3
import os
import sys
from topologic_core import Vertex, Edge, Face, Cell, CellUtility
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
import topologist.edge
assert topologist.edge
def test_horizontal():
"""Test horizontal edge detection"""
point1 = Ver... | Python | 1 |
f mode == 'train':
log_dict['time'] = trainer.logs['time']
log_dict['data_time'] = trainer.logs['data_time']
for name, val in trainer.logs.items():
if name in ['time', 'data_time']:
continue
log_dict[name] = val
self._log_info(log_dict, t... | Python | 1 |
usize::from(self.kilo_bytes()) * 1024
}
}
/// ADC VREF calibration value is stored in at the factory
#[derive(Debug)]
#[repr(C)]
pub struct VREFIN_CAL(u16);
#[cfg(not(feature = "rm0455"))]
define_ptr_type!(VREFIN_CAL, 0x1FF1_E860);
#[cfg(feature = "rm0455")]
define_ptr_type!(VREFIN_CAL, 0x08FF_F810);
impl ... | Rust | 0 |
tex,
timer: MovingWindowRenderTimer,
on_plugin_changed: PubSub<JsPerspectiveViewerPlugin>,
on_limits_changed: PubSub<RenderLimits>,
}
#[wasm_bindgen]
pub fn register_plugin(name: &str) {
PLUGIN_REGISTRY.register_plugin(name);
}
#[derive(Clone)]
pub struct Renderer(Rc<RefCell<PluginData>>);
impl Rende... | Rust | 0 |
# Code generated by Lark OpenAPI.
import lark_oapi as lark
from lark_oapi.api.hire.v1 import *
def main():
# 创建client
client = lark.Client.builder() \
.app_id(lark.APP_ID) \
.app_secret(lark.APP_SECRET) \
.log_level(lark.LogLevel.DEBUG) \
.build()
# 构造请求对象
request: Up... | Python | 1 |
}
/// Step when control contains an expression.
#[cfg_attr(feature = "cek-no-inlining", inline(never))]
fn step_expr(&mut self, ctrl: &mut Ctrl<'a>, binding: &'a Binding) {
let Binding { binder, ref bindee } = *binding;
match bindee {
Bindee::Error(span) => panic!("Bindee::Error... | Rust | 0 |
_ids = vec![type_effect.attacking_type_id, type_effect.defending_type_id];
let type_names = db.get_type_name_all(&type_ids)?;
let response = TypeEffectResponse::new(&type_effect_id, &type_effect, &type_names);
Ok(Json(response))
}
#[openapi]
#[post(
"/types/effects/<type_effect_id>",
format = "ap... | Rust | 0 |
import time
from fcntl import ioctl
from array import array
from struct import unpack_from
from struct import unpack
from struct import pack
import errno
import sys
charmap = {}
hichar = None
def updateCharMap(screen):
global hichar
ttyno = '4'
tty = open('/dev/tty' + screen, 'rb')
GIO_UNIMAP = 0x4B66
... | Python | 1 |
le.name: toggle.status for toggle in toggle_list}),
"FEATURE_TOGGLE_WHITE_LIST": json.dumps(
{
toggle.name: toggle.biz_id_white_list
for toggle in toggle_list
if isinstance(toggle.biz_id_white_list, list)
}
),
"FEATURE_TOGGL... | Python | 1 |
import MDAnalysis as mda
import numpy as np
import os
topology_file_0 = "./topology/lammps/box.data"
try:
u_0 = mda.Universe(topology_file_0)
box_size_0 = u_0.dimensions[:3]
except:
f = open(topology_file_0, "r")
for l in f:
if "xlo xhi" in l:
x = np.float32(l.split(" ")[1])-np.floa... | Python | 1 |
# Copyright 2024 The JAX 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | Python | 1 |
lo")
assert "Test error" in str(exc_info.value)
@pytest.mark.asyncio
async def test_chat_stream_method_error_handling(agent):
"""Test error handling in the chat method."""
mock_chat_manager = AsyncMock(spec=ChatManager)
async def mock_generate_response(*args, **kwargs):
yield json.dumps(... | Python | 1 |
`Acker` in order ot be able to
/// provide acking based on the responses from the underlying service.
fn into_driver<S>(self, service: S, acker: Acker) -> Driver<Self, S>
where
Self: Sized,
Self::Item: Ackable + Finalizable,
S: Service<Self::Item>,
S::Error: Debug + 'static,... | Rust | 0 |
r) -> Result<SocketAddr> {
self.shutdown_handler
.start_service(listening, None, self.build_router(listening))
.await
}
}
#[async_trait::async_trait]
impl Server for HttpHandler {
async fn shutdown(&mut self, graceful: bool) {
self.shutdown_handler.shutdown(graceful).awa... | Rust | 0 |
+ dir.x * halfl, center.y + dir.y * halfl),
];
d.prim_context_debug(w).draw_line(l1, &lp, c);
}
fn complex_sweeps_exe(st: &mut StateData, d: &mut DrawData, c: &Context, w: &mut PistonWindow) {
let mut lp0 = prims::DrawParms::new();
lp0.thickness = [30.0, 30.0];
if d.prim_no_connect {
lp0.... | Rust | 0 |
#!/usr/bin/env python
# coding: utf-8
# In[76]:
#import libraries
#!pip install kaggle
import kaggle
!kaggle datasets download ankitbansal06/retail-orders -f orders.csv
# In[77]:
#extract file from zip file
import zipfile
zip_ref = zipfile.ZipFile('orders.csv.zip')
zip_ref.extractall() # extract file to dir
zi... | Python | 1 |
from foundations_spec import *
from unittest.mock import mock_open, patch
class TestBundleDeployment(Spec):
@let
def job_name(self):
return self.faker.uuid4()
@let
def user_token(self):
return self.patch('foundations_authentication.user_token.user_token')
@let_now
def config... | Python | 1 |
ef _execute_uninstall_script(self):
"""执行卸载脚本"""
click.echo("⚙️ 执行卸载脚本...")
uninstall_script = self.target_dir / 'uninstall.sh'
if not uninstall_script.exists():
raise RuntimeError("卸载脚本不存在")
try:
# 切换到脚本目录执行
result = subprocess.run(
... | Python | 1 |
: [
"修复share_pwd权限提升漏洞",
"修复几处XSS漏洞",
"修复rssh dockerfile换源错误,现可通过远程pull和本地原生两种方式构建镜像",
"修复非'utf-8'编码文件读取出错的BUG",
"修复客户端生成界面切换页数失效的BUG",
"修复更改rssh端口后无法回连的BUG",
"新增分组备注历史记录存储功能,现数据校准后分组记录不会丢失,可在设置中清除历史冗余缓存",
... | Python | 1 |
from typing import List
from uuid import UUID
from mayim import PostgresExecutor
from api.models.generic_model import GenericModel
class NIRFExecutor(PostgresExecutor):
generic_prefix = ""
path = "./queries/fetch/NIRF/"
async def get_NIRF_C3_post_interation(self, year: int) -> List[GenericModel]:
... | Python | 1 |
from ipaddress import IPv6Address
from typing import Iterable, Iterator, Optional
from pych_client import ClickHouseClient
from diamond_miner.defaults import (
DEFAULT_PREFIX_SIZE_V4,
DEFAULT_PREFIX_SIZE_V6,
DEFAULT_PROBE_DST_PORT,
DEFAULT_PROBE_SRC_PORT,
PROTOCOLS,
UNIVERSE_SUBSET,
)
from dia... | Python | 1 |
import numpy as np
import os
from chainercv.datasets import VOCSemanticSegmentationDataset
from chainercv.evaluations import calc_semantic_segmentation_confusion
def run(args):
dataset = VOCSemanticSegmentationDataset(split=args.chainer_eval_set, data_dir=args.voc12_root)
# labels = [dataset.get_example_by_ke... | Python | 1 |
from click.testing import CliRunner
from inventree_amazon_plugin.cli import cli
def test_version():
runner = CliRunner()
with runner.isolated_filesystem():
result = runner.invoke(cli, ["--version"])
assert result.exit_code == 0
assert result.output.startswith("cli, version ")
| Python | 1 |
")
server.add_tool(tool_func, tool_name, description)
logger.info(f"Registered tool: {tool_name}")
async def _run_server() -> None:
"""Run the FastMCP server with both HTTP and SSE transports."""
tasks = [
server.run_http_async(
transport="streamable-http",
host... | Python | 1 |
subgraph_id: &graph::prelude::SubgraphDeploymentId,
) -> Result<Option<String>, failure::Error> {
self.store.network_name(subgraph_id)
}
}
impl EthereumCallCache for NetworkStore {
fn get_call(
&self,
contract_address: ethabi::Address,
encoded_call: &[u8],
bl... | Rust | 0 |
for name in src.subdatasets:
click.echo(name)
elif meta_member == 'stats':
st = src.statistics(bidx)
click.echo("{st.min} {st.max} {st.mean} {st.std}".format(st=st))
elif meta_member == 'checksum':
click.echo(str(src.checks... | Python | 1 |
/// [`usrsctp_socket()`]: fn.usrsctp_socket.html
pub fn usrsctp_close(so: *mut socket);
pub fn usrsctp_getassocid(arg1: *mut socket, arg2: *mut libc::sockaddr) -> sctp_assoc_t;
/// At the end of the program `usrsctp_finish()` should be called to
/// free all the memory that has been allocated befo... | Rust | 0 |
;
}
if let Some(value) = &self.ports {
::serde::ser::SerializeStruct::serialize_field(&mut state, "ports", value)?;
}
::serde::ser::SerializeStruct::end(state)
}
}
<gh_stars>0
use num::{ToPrimitive, FromPrimitive};
use std::ffi::{CString, CStr};
use libc::c_char;
use sys... | Rust | 0 |
ct("couldn't get connection from pool");
let trailer_node = web::block(move || {
let db = Db(&conn);
TrailerNode::fetch(db, trailer_id)
})
.await
.map_err(|e| {
error!("{}", e);
HttpResponse::InternalServerError().finish()
})?;
if trailer_nod... | Rust | 0 |
tyle_success(light: bool) -> Style {
*theme_styles(light).get(&Styles::Success).unwrap()
}
pub fn style_primary(light: bool) -> Style {
*theme_styles(light).get(&Styles::Primary).unwrap()
}
pub fn style_help(light: bool) -> Style {
*theme_styles(light).get(&Styles::Help).unwrap()
}
pub fn style_secondary(light: ... | Rust | 0 |
Unreal,
/// [Relay] The envelope, which contained only a transaction, was discarded by the
/// dynamic sampling rules.
TransactionSampled,
}
impl DiscardReason {
pub fn name(self) -> &'static str {
match self {
DiscardReason::Duplicate => "duplicate",
DiscardReason::Pro... | Rust | 0 |
mock::Mock::default();
let mut ctx = mock.create_ctx();
Consensus::set_params(
ctx.runtime_state(),
Parameters {
consensus_scaling_factor: 1_000, // Everything is multiplied by 1000.
..Default::default()
},
);
// Not representable.
Consensus::amount... | Rust | 0 |
u16, u16>);
impl KCAL_RATIO_2412_R {
pub(crate) fn new(bits: u16) -> Self {
KCAL_RATIO_2412_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for KCAL_RATIO_2412_R {
type Target = crate::FieldReader<u16, u16>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
... | Rust | 0 |
""get a :mod:`pandas.Series` with the aggregated load"""
dfr = self.data_frame
load_cols = [s for s in dfr.columns if s.startswith("load")]
load_series = dfr[load_cols[0]].copy()
for col in load_cols[1:]:
load_series += dfr[col]
return load_series
def get_load... | Python | 1 |
import os
import subprocess
import numpy as np
####################################################################################################
python = "python3"
# python = "CUDA_VISIBLE_DEVICES=-1 python3"
####################################################################################################
D, c... | Python | 1 |
-> Self {
Self { changes, idx: 0 }
}
}
impl<'a> Iterator for NoallocChangeIter<'a> {
type Item = (u32, NoallocChangeBuff);
fn next(&mut self) -> Option<Self::Item> {
let retval = self
.changes
.get(self.idx)
.copi... | Rust | 0 |
visual_dicts = []
pred_dicts = {}
counter = 0
for frame_name in tqdm(sorted(os.listdir(args.input_data_dir))):
if counter == args.num_frame:
break
else:
counter += 1
pc_name = os.path.join(args.input_data_dir, frame_name)
points = pickle.load(open(p... | Python | 1 |
import discord
from src.api.request import url_web_users, accountRequest
from src.api.api import embed_color, commandPing
from discord.ext import commands
class AccountCommand(commands.Cog):
def __init__(self, bot: discord.Bot):
self.bot = bot
@commands.slash_command(
name="account",
... | Python | 1 |
# analise_turma.py
alunos = [
{"matricula": "2025A01", "nome": "Ana Silva", "nota_final": 8.5, "frequencia": 80.0, "status_matricula": "ativo"},
{"matricula": "2025A02", "nome": "Bruno Costa", "nota_final": 6.8, "frequencia": 95.0, "status_matricula": "ativo"},
{"matricula": "2025A03", "nome": "Carla Dias",... | Python | 1 |
(NodeAddress, f64)>, f64)> {
self.reader
.get_node_plugin_and::<Dirichlet, _, _>(na, |p| {
let mut dir = p.clone();
if let Some(e) = self.running_evidence.get(&na) {
dir.add_evidence(e)
}
dir.prob_vector()
... | Rust | 0 |
# Copyright 2023 ROS-Industrial
#
# 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 writin... | Python | 1 |
, valid_pred, average='macro')
f1 = f1_score(valid_true, valid_pred, average='macro')
if bestf1 < f1:
bestf1 = f1
torch.save(model.state_dict(), 'model_en_ptv1mlp.pth')
print(f'valid precision:{p},recall:{r},f1:{f1}')
def cls_test(model,testloader,label2idx):
mode... | Python | 1 |
# This script can be used to test a trained YOLO model.
from ultralytics import YOLO
from ultralytics.engine.results import Results
from wed.utils.bounding_box import BoundingBox, BoundingBoxType
from wed.utils.draw_bb import draw_bounding_boxes
import cv2
from os.path import join, isfile
from os import listdir
if __... | Python | 1 |
nd_args)
.ok_or_else(|| anyhow!("Failed to split command from {:?}", command_and_args))?;
let (cmd, arguments) = s.split_at(1);
let cmd = cmd
.get(0)
.ok_or_else(|| anyhow!("Failed to extract command from {:?}", command_and_args))?;
let compatible_toolchain_builder = match version {... | Rust | 0 |
o_tag(&self, tag: Tag, lattice: &Lattice) -> Vec<V3>
{ match tag {
Tag::Cart => self.to_carts(lattice),
Tag::Frac => self.to_fracs(lattice),
}}
}
fn dot_n3_33(c: &[V3], m: &M33) -> Vec<V3>
{ c.iter().map(|v| v * m).collect() }
impl<V> Permute for CoordsKind<V>
where V: Permute,
{
fn permut... | Rust | 0 |
of pages");
let mut node = Self::construct_node(page, allocator);
unsafe {
node.as_mut().previous = Some(self.top);
self.top.as_mut().next = Some(node);
}
}
self.top = unsafe { self.top.as_mut() }.next.unwrap();
}
unsafe { self.top.as_mut() }.frames[index] = Some(frame);
self.size += ... | Rust | 0 |
xample
net_name = 'vgg16'
from torchvision.models.vgg import vgg16
net_torch = vgg16(True).eval()
elif args.model == 'densenet121':
net_name = 'densenet121'
from torchvision.models.densenet import *
net_torch = densenet121(True).eval()
elif args.model == 'MobileNe... | Python | 1 |
;
use std::collections::HashMap;
use glium::Surface;
use clap::{Arg, ArgSettings};
use dark_light;
lazy_static! {
pub static ref ASSETS_FOLDER: std::path::PathBuf = find_folder::Search::ParentsThenKids(3, 5).for_folder("assets").unwrap();
}
enum AppTheme {
Auto,
Dark,
Light
}
fn get_cli_options() -> clap::ArgMat... | Rust | 0 |
/// email: "<EMAIL>";
/// };
/// ...
/// };
/// ...
/// };
///
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Contact {
/// The identifying name of the contact person/organization.
#[prost(string, tag = "1")]
pub name: ::prost::alloc::string::String,
/// The URL pointin... | Rust | 0 |
e to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
#[no_mangle]
fn pdf_font_open_pkfont(font: *mut pdf_font) -> i32;
#[no_mangle]
fn pdf_font_load_pkfont(font: *mut pdf_font) -> i32;
#[no_mangle]
fn PKFont_set_dpi(dpi: i32);
/* This... | Rust | 0 |
#!/usr/bin/env python3
################################################################################
# SPDX-FileCopyrightText: Copyright (c) 2019-2021 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you... | Python | 1 |
[a],) # anchors
tcls += (c,) # class
tmasks += (mask_m_t,)
return (
ops.stack(tcls),
ops.stack(tbox),
ops.stack(indices),
ops.stack(anch),
ops.stack(tmasks),
) # class, box, (image, anchor, gridj, gridi), anchors, ma... | Python | 1 |
in() {
CLIExecutor::new(cli::get_matches()).execute();
}
<reponame>zhenkyle/lpc11xx<gh_stars>1-10
#[doc = "Reader of register CANIF%s_MSK1"]
pub type R = crate::R<u32, super::CANIF_MSK1>;
#[doc = "Writer for register CANIF%s_MSK1"]
pub type W = crate::W<u32, super::CANIF_MSK1>;
#[doc = "Register CANIF%s_MSK1 `reset... | Rust | 0 |
LoadChip('ED6_DT07/CH00170._CH', 'ED6_DT07/CH00170P._CP', 4)
LoadChip('ED6_DT07/CH00171._CH', 'ED6_DT07/CH00171P._CP', 5)
Jump('loc_3A3')
def _loc_347(): pass
label('loc_347')
LoadChip('ED6_DT27/CH04080._CH', 'ED6_DT27/CH04080P._CP', 4)
LoadChip('ED6_DT27/CH04081._CH', 'ED6_DT27/CH04081... | Python | 1 |
64);
total_primitives_per_leaf::inc_total();
BVHBuildNode::Leaf {
bounds: bbox,
first_prim_offset,
num_prims,
}
}
fn bounds(&self) -> &Bounds3f {
match self {
BVHBuildNode::Interior { ref bounds, .. } | BVHBuildNode::Leaf { ref bou... | Rust | 0 |
32 = 275.0;
pub const HOWTOPLAY_AND_ABOUT_AREA_WIDTH: f32 = 300.0;
pub const HOWTOPLAY_AND_ABOUT_TEXT_POSITION_X: f32 = 73.0;
pub const HOWTOPLAY_CONTROLS_CHAR_SCALE: f32 = 19.5;
pub const HOWTOPLAY_CONTROLS_TEXT_POSITION_Y: f32 = 132.5;
pub const HOWTOPLAY_CONTROLS_LEFTSIDE_TEXT_POSITION_X: f32 = HOWTOPLAY_AND_ABOUT_T... | Rust | 0 |
(self.module.solenoid_blacklist() & (1 << self.channel)) != 0
}
pub fn set_pulse_duration(&mut self, seconds: f64) -> HalResult<()> {
let duration_ms: i32 = (seconds * 1000.0) as i32;
hal_call!(HAL_SetOneShotDuration(self.handle, duration_ms))
}
pub fn start_pulse(&mut self) ->... | Rust | 0 |
NodeData {
node_type: NodeType::Label(if self.cells[(x - 1) * 3 + y] == Cell::X {
DomString::Static("x")
} else {
DomString::Static("o")
}),
ids: vec![Dom... | Rust | 0 |
import os
import json
import torch
from torch import nn
from safetensors.torch import load_file
from transformers import AutoModelForCausalLM, AutoTokenizer
def to_buffer(module, mark_param=True):
"""Turns all parameters of a module into buffers."""
if module is None:
return
modules = module.module... | Python | 1 |
_get_dps_code("FAN_SPEED"): self.vacuum.getRoboVacCommandValue(
RobovacCommand.FAN_SPEED, normalized_fan_speed
)
})
async def async_send_command(
self,
command: str,
params: dict[str, Any] | list | None = None,
**kwargs: Any
) -> None:
... | Python | 1 |
import unittest
from ctypes import *
import _ctypes_test
class ReturnFuncPtrTestCase(unittest.TestCase):
def test_with_prototype(self):
# The _ctypes_test shared lib/dll exports quite some functions for testing.
# The get_strchr function returns a *pointer* to the C strchr function.
dll =... | Python | 1 |
]["json"])
else:
# Convert direct schema to proper format
normalized["inputSchema"] = {"json": normalize_schema(normalized["inputSchema"])}
return normalized
class PythonAgentTool(AgentTool):
"""Tool implementation for Python-based tools.
This class handles to... | Python | 1 |
Network::Bitcoin => 8332,
Network::Testnet => 18332,
Network::Regtest => 18443,
}
)
},
|url| url.trim_end_matches('/').into()
),
match self.bitcoind_wallet {
... | Rust | 0 |
ts, params, reuse=tf.AUTO_REUSE, \
weak_learner_id=learner_id)
residual_eval_model_spec = model_fn('vali', eval_inputs, params, reuse=True, \
weak_learner_id=learner_id)
logging.info("- done.")
args.restore_dir = 'best_weights'
global_epoch... | Python | 1 |
from __future__ import annotations
import pytest
from dials.command_line.frame_orientations import extract_experiment_data
def test_extract_experiment_data():
"""Test basic operation of the extract_experiment_data function. Does not
test extraction of data from scan-varying models"""
# Set up an Experi... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.