text string | label_name string | labels int64 |
|---|---|---|
enum.
#![allow(clippy::too_many_arguments)] // TODO: builder patterm
use crate::util::Util;
use feather_core::packet::PacketEntityMetadata;
use feather_core::{BlockPosition, EntityMetadata, Slot};
use specs::storage::ComponentEvent;
use specs::{
BitSet, Component, Entities, FlaggedStorage, Join, Read, ReaderId, ... | Rust | 0 |
import os
import sys
import pytest
from pathlib import Path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from src.dot.git import get_short_commit_hash, get_full_commit_hash
@pytest.mark.parametrize("ref", ["HEAD", "main"])
def test_get_full_commit_hash_various(ref: str):
try... | Python | 1 |
# MOFTransformer version 2.0.0
from moftransformer.utils.prepare_data import prepare_data
from moftransformer.utils.install_griday import install_griday, uninstall_griday
__all__ = ["prepare_data", "install_griday", "uninstall_griday"]
| Python | 1 |
lf.
num_instance].flatten()
max_overlaps_ignore = overlaps_ignore[:, :self.num_instance].flatten()
gt_assignment_ignore = overlaps_ignore_indices[:, :self.
num_instance].flatten()
# ign... | Python | 1 |
*const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_notations_trampoline::<Self, F> as *const (),
)),
Box_::into_raw(f),
)
}
}
fn connect_public_id_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {... | Rust | 0 |
def update(self, models):
"""
更新所有子模块的 EMA 参数。
"""
for model in models:
device = next(model.parameters()).device
for name, param in model.named_parameters():
if param.requires_grad:
self.shadow[f"{model}.{name}"] = (
... | Python | 1 |
utes.
:param attrs_to_dump: A list of plugin attributes to dump
"""
ensure_plugins_loaded()
integrate_macros_plugins()
initialize_web_ui_plugins()
initialize_fastapi_plugins()
initialize_extra_operators_links_plugins()
if not attrs_to_dump:
attrs_to_dump = PLUGINS_ATTRIBUTES_TO_... | Python | 1 |
#Task 2 : In this exercise, you will read in a file using a bigger DataFrame chunk size and then process the data from the first chunk.
import pandas as pd # type: ignore
# Initialize reader object: urb_pop_reader
urb_pop_reader = pd.read_csv('WDICSV.csv', chunksize = 1000)
# Get the first DataFrame chunk: df_urb_pop... | Python | 1 |
izer IO 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 writing, ... | Rust | 0 |
ams["attributes"]
conti = Ec2EcsInstance(module, cluster, ec2_instance_id)
attrs = EcsAttributes(module, attributes)
results = {
"changed": False,
"attributes": [
{
"cluster": cluster,
"ec2_instance_id": ec2_instance_id,
"attribut... | Python | 1 |
d a fixed execution time
return [0, 1], 0.1
clustering = RadiusClustering(manner="exact", radius=1.5)
# Set the custom clusterer
assert hasattr(clustering, 'set_solver'), "RadiusClustering should have a set_solver method."
assert callable(clustering.set_solver), "set_solver should be callable."
... | Python | 1 |
oubleFacedPiece::Knight1,
DoubleFacedPiece::Lance1,
DoubleFacedPiece::Pawn1,
],
[
// King なし
DoubleFacedPiece::Rook2,
DoubleFacedPiece::Bishop2,
DoubleFacedPiece::Gold2,
DoubleFacedPie... | Rust | 0 |
si_rot = apply_1q_statevector(nb, psi_rot, gate_sd(), q, n)
psi_rot = apply_1q_statevector(nb, psi_rot, gate_h(), q, n)
# probs once
probs = nb.square(nb.abs(psi_rot)) if hasattr(nb, 'square') else nb.abs(psi_rot) ** 2
dim = 1 << n
# evaluate each term in group
fo... | Python | 1 |
pub fn set_log_channel(&mut self, ch: Option<ChannelId>) -> Result<(), Error> {
self.log_channel = ch;
Config::serialize(self)
}
pub fn log_channel(&self) -> Option<ChannelId> {
self.log_channel
}
pub fn add_user_group(&mut self, ch: RoleId, desc: String) -> Result<(), Er... | Rust | 0 |
"""Base interfaces for tracing runs."""
from langchain_core.exceptions import TracerException
from langchain_core.tracers.base import BaseTracer
__all__ = ["BaseTracer", "TracerException"]
| Python | 1 |
import torch.nn as nn
from prosim.models.layers.mlp import MLP
from .pointnet_encoder import PointNetPolylineEncoder
def get_obs_input_dim(cfg):
in_dim = len(cfg.DATASET.FORMAT.HISTORY.ELEMENTS.split(','))
if cfg.DATASET.FORMAT.HISTORY.WITH_EXTEND:
in_dim += 2
if cfg.DATASET.FORMAT.HISTORY.WITH_AGENT_T... | Python | 1 |
}
impl Default for Capabilities {
fn default() -> Self {
Self {
max_msg_fds: default_max_msg_fds(),
max_data_xfer_size: default_max_data_xfer_size(),
migration: default_migration_capabilities(),
}
}
}
pub struct Client {
stream: UnixStream,
next_mess... | Rust | 0 |
i_fe
})
.fold(I0_inv, |acc, x| acc.add_point(&x.get_element()));
// defining g_w
let mut g_vec_w: Vec<GE> = vec![*G, *Gt];
g_vec_w.extend_from_slice(&Y_hat_vec);
g_vec_w.push(I_hat);
g_vec_w = (0..p_len)
.map(|i| {
... | Rust | 0 |
ption<PrecompileResult> {
let target_gas = match target_gas {
Some(t) => t,
None => return Some(PrecompileResult::Err(ExitError::OutOfGas)),
};
match address.to_low_u64_be() {
1 => Some(ECRecover::run(input, target_gas, context)),
2 => Some(SHA256::run(input, target_gas, con... | Rust | 0 |
@property
def token(self) -> str:
return "<sound>"
@property
def data_key(self) -> str:
return "sounds"
@property
def token_width(self) -> int:
return self.num_tokens_output
def to(self, dtype: torch.dtype, device: torch.device) -> "MERTAudioModality":
self.dt... | Python | 1 |
ferentialGeometry> {
// The disk lies in the XY plane so if the ray doesn't cross this plane
// there won't be any intersection
if f32::abs(ray.d.z) == 0.0 {
return None;
}
// We still treat the disk as an infinite XY plane for just a little longer
// and here... | Rust | 0 |
hine, bitwise::slt, gas::VERYLOW),
opcode::SGT => op2_u256_fn!(machine, bitwise::sgt, gas::VERYLOW),
opcode::EQ => op2_u256_bool_ref!(machine, eq, gas::VERYLOW),
opcode::ISZERO => op1_u256_fn!(machine, bitwise::iszero, gas::VERYLOW),
opcode::AND => op2_u256!(machine, bitand, gas::VERYLOW... | Rust | 0 |
.len() < len {
return Err(Error::IncompleteNbtValue);
}
let bytes = &bytes[..len];
self.cursor.set_position(pos + len as u64);
let decoded = from_java_cesu8(bytes)?;
let reference = match decoded {
Cow::Borrowed(s) => Reference::Borrowed(s),
C... | Rust | 0 |
import numpy as np
import matplotlib.pyplot as plt
from skimage import io
import numpy.matlib
from skimage import img_as_float
file_name='D:/Visual Effects/PS Algorithm/4.jpg';
img=io.imread(file_name)
img = img_as_float(img)
row, col, channel = img.shape
color_map = img.copy()
rNW = 0.5
rNE = 1.0
rSW = 0.0
r... | Python | 1 |
url, frag_index, fragment_request_data, headers)
else:
success, continuation_id, offset, click_tracking_params = download_and_parse_fragment(
chat_page_url, frag_index)
if not success:
return False
if test:
break... | Python | 1 |
SyntaxVariant::ScopeResolutionExpression { .. }
)
}
fn is_object_creation_expression(&self) -> bool {
matches!(
self.children,
SyntaxVariant::ObjectCreationExpression { .. }
)
}
fn is_qualified_name(&self) -> bool {
matches!(self.chi... | Rust | 0 |
okio::test]
async fn test_publish_raw_log_sends_message_to_kafka(ctx: &mut PipelineIngressTestContext) {
let event_source_id = Uuid::new_v4();
let tenant_id = Uuid::new_v4();
let log_event: Bytes = "test".into();
let bootstrap_servers = ctx.bootstrap_servers.clone();
let sasl_username = ctx.sasl_us... | Rust | 0 |
ir(root.join("c")).unwrap();
fs::create_dir(root.join("c/cobalt.cmx")).unwrap();
let child_dir_name = root.join("c/cobalt.cmx/13579");
fs::create_dir(&child_dir_name).unwrap();
fs::create_dir(child_dir_name.join("in")).unwrap();
File::create(child_dir_name.join("job-id")).unwrap(... | Rust | 0 |
# Copyright Allo authors. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
from allo.ir.types import float32
import allo.dataflow as df
import allo.backend.hls as hls
import numpy as np
Ty = float32
M, N, K = 16, 16, 16
P0, P1 = 2, 2
Mt, Nt = M // P0, N // P1
@df.region()
def top():
pipe = df.array(df... | Python | 1 |
s().as_slice());
let result2 = Poly1305::new(key.as_ref().into())
.chain(&msg[0..32])
.chain(&msg[32..96])
.chain(&msg[96..112])
.chain(&msg[112..120])
.chain(&msg[120..124])
.chain(&msg[124..126])
.chain(&msg[126..127])
.chain(&msg[127..128])
... | Rust | 0 |
i16(&self) -> Option<i16> {
T::to_i16(&self.value)
}
fn to_i32(&self) -> Option<i32> {
T::to_i32(&self.value)
}
fn to_i128(&self) -> Option<i128> {
T::to_i128(&self.value)
}
fn to_usize(&self) -> Option<usize> {
T::to_usize(&self.value)
}
fn to_u8(&sel... | Rust | 0 |
Start(n1_1),
End(n1_1),
Start(n1_2),
End(n1_2),
Start(n1_3),
End(n1_3),
End(n1),
]
);
n1_3.remove(&mut arena);
// arena
// `-- 1
// |-- 1_1
// `-- 1_2
assert_eq!(
n1.traverse(&arena).co... | Rust | 0 |
_data_paths(
&mut self,
data_paths: flatbuffers::WIPOffset<
flatbuffers::Vector<'b, flatbuffers::ForwardsUOffset<&'b str>>,
>,
) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(
ExecuteQueryInput::VT_DATA_PATHS,
data_paths,
);
... | Rust | 0 |
test]
fn expr() {
check(
TopEntryPoint::Expr,
"",
expect![[r#"
ERROR
error 0: expected expression
"#]],
);
check(
TopEntryPoint::Expr,
"2 + 2 == 5",
expect![[r#"
BIN_EXPR
BIN_EXPR
LITERAL
... | Rust | 0 |
((vm, simple_spill_v1) <int64> blk_ret_t7);
ssa! ((vm, simple_spill_v1) <int64> blk_ret_t8);
ssa! ((vm, simple_spill_v1) <int64> blk_ret_t9);
ssa! ((vm, simple_spill_v1) <int64> blk_ret_t10);
ssa! ((vm, simple_spill_v1) <int64> blk_ret_t11);
ssa! ... | Rust | 0 |
|resp| (*slave, resp.1))
})
.collect::<HashMap<_, _>>();
*SLAVE_INFO.write() = res;
}
fn env_list_cb(r: &mut SlaveRes) {
let res = r
.msg
.iter()
.filter(|(_, raw)| raw.status == RetStatus::Success)
.filter_map(|(slave, raw)| {
info!(
... | Rust | 0 |
mponent)]
#[storage(VecStorage)]
pub struct Image {
pub image: graphics::Image,
}
#[derive(Clone, Debug, Component)]
#[storage(VecStorage)]
pub struct Text {
pub text: String,
pub font_size: f32,
pub font: FontType,
pub align: Alignment,
pub color: graphics::Color,
}
#[derive(Clone, Debug, Com... | Rust | 0 |
h = [
218, 57, 163, 238, 94, 107, 75, 13, 50, 85, 191, 239, 149, 96, 24, 144, 175, 216, 7, 9
];
#[derive(PartialEq)]
pub enum DxvkStateCacheEdition {
Standard,
Legacy
}
pub struct DxvkStateCacheHeader {
pub magic: [u8; 4],
pub version: u32,
pub entry_size: u32
}
pub struct DxvkStateCa... | Rust | 0 |
);
let secp = Secp256k1::without_caps();
proto_signed_tx.set_signature(self.signature.serialize_compact(&secp).1.to_vec());
Ok(proto_signed_tx)
}
fn from_proto(_prototype: &Self::ProtoType) -> Result<Self, Box<Error>> {
unimplemented!()
}
}
impl Encode for SignedTx {
fn ... | Rust | 0 |
(HEADER_SIZE - header_len);
header.clear();
// write length to header
len_var.write(&mut header)?;
// write data length to header if compression enabled
if let Some(data_len_var) = &data_len_var {
data_len_var.write(&mut header)?;
}
// swap so heade... | Rust | 0 |
] <paths-file> <dst>
///
/// FLAGS:
/// -h, --help Prints help information
/// -V, --version Prints version information
///
/// OPTIONS:
/// -t <n-tasks> number of tokio tasks. Default is 4.
/// -o <offset> number of files to skip. Default is 0.
///
/// ARGS:
/// <paths-file>... | Rust | 0 |
["save_folder"],
"splits": hparams["splits"],
"seed": hparams["seed"],
"skip_prep": hparams["skip_prep"],
},
)
# Fetch device
device = get_device(not hparams["no_cuda"])
logger.info(f"Loading encoder model from HF hub: {hparams['encoder_hub']}")
encoder ... | Python | 1 |
import torch
import torch.nn.functional as F
# DCGAN loss
def loss_dcgan_dis(dis_fake, dis_real):
L1 = torch.mean(F.softplus(-dis_real))
L2 = torch.mean(F.softplus(dis_fake))
return L1, L2
def loss_dcgan_gen(dis_fake):
loss = torch.mean(F.softplus(-dis_fake))
return loss
# Hinge Loss
def loss_hinge_dis(d... | Python | 1 |
rint("hide with slide_up")
# Create slide-up animation (y from original y to -height)
original_y = widget.get_y()
height = widget.get_height()
anim = lv.anim_t()
anim.init()
anim.set_var(widget)
anim.set_values(original_y, original_y - ... | Python | 1 |
})
.and_then(move |(ev, t_stream)| match ev {
RpcInput::Notification(EventMessage::Log(LogMessageParams { ref message, .. })) => {
match (message.as_ref(), waiting) {
("Processing", false) => {
debug!("Processing 1 started.");
... | Rust | 0 |
const PHASECAL_TARGET: TuningParm = LLD_PUBLIC_MIN_ADDRESS + 4;
pub const LITE_CAL_REPEAT_RATE: TuningParm = LLD_PUBLIC_MIN_ADDRESS + 5;
pub const LITE_RANGING_GAIN_FACTOR: TuningParm = LLD_PUBLIC_MIN_ADDRESS + 6;
pub const LITE_MIN_CLIP_MM: TuningParm = LLD_PUBLIC_MIN_ADDRESS + 7;
pub const LITE_LONG_SIGMA_THRESH_MM:... | Rust | 0 |
ath)?.as_slice(),
load_key_from_file(pk_filepath)?.as_slice(),
)
}
fn sign_base64<P: AsRef<Path>>(
msg: String,
sk_filepath: P,
pk_filepath: P,
) -> Results<String> {
Ok(Base64::encode(sign(
msg.as_bytes(),
load_key_from_file(sk_fi... | Rust | 0 |
terface"""
self.page.add(
ft.Container(
content=ft.Text("Real-time Waveform Viewer", style=ft.TextThemeStyle.HEADLINE_LARGE),
margin=ft.margin.only(bottom=20)
),
# Status panel
ft.Container(
content=ft.C... | Python | 1 |
:ArrayBuffer::new();
vbo2.bind();
vbo2.static_draw_data(&vertices2);
let vao2 = buffer::VertexArray::new();
vao2.bind();
Vertex::vertex_attrib_pointers();
vbo2.unbind();
// Build indice buffer
let indices: Vec<u32> = vec![0, 1, 2, 1, 2, 3];
let ib... | Rust | 0 |
fy--write-api).\n\nFor information about available fields see [efuse_rd_key3_data6](efuse_rd_key3_data6) module"]
pub type EFUSE_RD_KEY3_DATA6 = crate::Reg<u32, _EFUSE_RD_KEY3_DATA6>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _EFUSE_RD_KEY3_DATA6;
#[doc = "`read()` method returns [efuse_rd_key3_data6::R](efuse_r... | Rust | 0 |
el.layers.{idx}.post_attention_layernorm",
rms_norm_eps = config.rms_norm_eps,
)
interm_size = int(2 * cfg_ffn["ffn_mult"] * config.hidden_size / 3)
interm_size = ((interm_size + 255) // 256) * 256
mlp = GatedMLP(
co... | Python | 1 |
_Graphics_Direct3D11\"`*"]
pub const D3D11_MESSAGE_ID_TEXTURE3D_MAP_INVALIDFLAGS: D3D11_MESSAGE_ID = 316i32;
#[doc = "*Required features: `\"Win32_Graphics_Direct3D11\"`*"]
pub const D3D11_MESSAGE_ID_TEXTURE3D_MAP_ALREADYMAPPED: D3D11_MESSAGE_ID = 317i32;
#[doc = "*Required features: `\"Win32_Graphics_Direct3D11\"`*"]
... | Rust | 0 |
ED: &str = "x-ms-server-encrypted";
pub const BLOB_TYPE: &str = "x-ms-blob-type";
pub const CONTENT_CRC64: &str = "x-ms-content-crc64";
pub const BLOB_CONTENT_LENGTH: &str = "x-ms-blob-content-length";
pub const BLOB_ACCESS_TIER: &str = "x-ms-access-tier";
pub const BLOB_SEQUENCE_NUMBER: &str = "x-ms-blob-sequence-numb... | Rust | 0 |
removed.\n\
\n\
CAUTION: Note that shred relies on a very important assumption:\n\
that the file system overwrites data in place. This is the traditional\n\
way to do things, but many modern file system designs do not satisfy this\n\
assumption. The following are examples of file systems on ... | Rust | 0 |
ent `Instance` or if this instance is not
/// already taken.
#[cfg(not(feature = "nosync"))]
#[inline]
pub fn release(inst: Instance) {
external_cortex_m::interrupt::free(|_| unsafe {
if TZC_TAKEN && inst.addr == INSTANCE.addr {
TZC_TAKEN = false;
} else {... | Rust | 0 |
API
if inf.router_api.value not in apis_to_serve:
continue
apis_to_serve.add(inf.routing_table_api.value)
apis_to_serve.add("inspect")
for api_str in apis_to_serve:
api = Api(api_str)
endpoints = all_endpoints[api]
impl = impls[api]
if is_passthrou... | Python | 1 |
"""Metrics for classification with soft (probabilistic) labels"""
import logging
import numpy as np
from . import make_scorer
logger = logging.getLogger(__name__)
EPS = 1e-10 # clipping threshold to prevent NaN
def _soft_log_loss(true_probs, predicted_probs):
"""Both args must be 2D pandas/numpy arrays"""
... | Python | 1 |
let mut z = NodeQuery::new(Some(new_node), self.nil);
let mut y = NodeQuery::new(y_node, self.nil);
z.set_parent(y.inner());
if y.is_nil() {
self.root = z.inner();
} else if z.get_key() < y.get_key() {
y.set_left(z.inner());
} else {
y... | Rust | 0 |
from __future__ import division, print_function, absolute_import
import argparse
import tensorflow as tf
import copy
import logging
from tensorflow.contrib import slim
import vgg
from cpm import PafNet
import common
from tensblur.smoother import Smoother
from estimator import PoseEstimator, TfPoseEstimator
import warni... | Python | 1 |
sequence_number = match account_state {
Some(av) => av.sequence_number,
None => 0,
};
let script = if is_operator {
transaction_builder::encode_minerstate_commit_by_operator_script_function(
tx_params.owner_address.clone(),
block.preimage.clone(),
... | Rust | 0 |
)
.render(f, disk_layout[0]);
}
fn render_graphics(
app: &CPUTimeApp,
layout: Rect,
f: &mut Frame<'_, ZBackend>,
zf: &u32,
update_number: &u32,
gfx_device_index: &usize,
offset: &usize,
selected_section: &Section,
) {
let style = match selected_section {
Sect... | Rust | 0 |
te("exporterSettings", "Status"))
self.toolBox.setItemText(self.toolBox.indexOf(self.content), _translate("exporterSettings", "Content"))
self.label_3.setText(_translate("exporterSettings", "Between folders:"))
self.cmbSepFF.setItemText(0, _translate("exporterSettings", "Empty line"))
se... | Python | 1 |
# -*- coding: utf-8 -*-
# Created on 2018-08-15
# author: 欧度智能,https://www.odooai.cn
# email: 300883@qq.com
# resource of odooai
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
# Odoo在线中文用户手册(长期更新)
# https://www.odooai.cn/documentation/user/10.0/zh_CN/index.html
# Odoo10离线中文用户手册下载
# https://www.odooa... | Python | 1 |
"""This script runs through docker-compose.yml and checks if any of the commit hashes
are out of date.
"""
import os
import re
import subprocess
import tqdm
import yaml
def main() -> None:
with open(f"{os.path.dirname(__file__)}/../docker-compose.yml", "r", encoding="ascii") as f:
services: dict = yaml.... | Python | 1 |
# Section 4.14 Self Check snippets
# Exercise 2
import decimal as dec
dec.Decimal('2.5') ** 2
Decimal('6.25')
##########################################################################
# (C) Copyright 2019 by Deitel & Associates, Inc. and #
# Pearson Education, Inc. All Rights Reserved. ... | Python | 1 |
!("listening on {}", opts.address);
axum::Server::bind(&opts.address)
.serve(app.into_make_service())
.await
.unwrap();
}
async fn accept_form(
ContentLengthLimit(mut multipart): ContentLengthLimit<Multipart, { 250 * 1024 * 1024 }>,
) -> Result<String, StatusCode> {
let mut text: S... | Rust | 0 |
u8] = unsafe {
core::slice::from_raw_parts(
(t_1 as *const T1) as *const u8,
size_of::<T1>(),
)
};
let bytes_2: &[u8] = unsafe {
core::slice::from_raw_parts(
(t_2 as *const T2) as *const u8,
size_of::<T2>(),
)
};
self.encode_bytes_2(bytes_1, bytes_2)
}
pub(crate) fn encode_header_... | Rust | 0 |
(c_);
let m = vsub(ring, offset);
let mut counter = 0;
for mi in m {
counter += (mi <= 2u32.pow(31)) as usize;
}
assert!(counter == 0, "counter is {}", counter);
}
#[test]
fn test_external_product() {
use super::sampling::random_bool_initialization;
use super::trlwe::TRLWE;
le... | Rust | 0 |
# -*- coding: utf-8 -*-
import os
import sys
import pickle
def replace_sep(fin, fout, sep_ini, sep_fin):
"""
Replace delimiter in a file.
"""
fin = open(fin, "r")
fout = open(fout, "w")
for line in fin:
fout.write(line.replace(sep_ini, sep_fin))
fin.close()
fout.close()
def r... | Python | 1 |
from django.urls import path
from . import views
urlpatterns = [
path("signup/",views.usersSignup.as_view()),
path("getMembershipDetails/<email>/",views.userMembership.as_view()),
path("getEventDetails/<email>/",views.EventDetailsView.as_view()),
path("getRegistrationDetails/<email>/",views.registratio... | Python | 1 |
xpected results
use snafu::{OptionExt, Snafu};
use std::{fmt::Display, sync::Arc};
use crate::scenarios::{get_all_setups, get_db_setup, DbSetup};
const IOX_SETUP_NEEDLE: &str = "-- IOX_SETUP: ";
#[allow(clippy::enum_variant_names)]
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(display(
"No setup foun... | Rust | 0 |
from odoo import fields, models
class PosOrderLine(models.Model):
_inherit = 'pos.order.line'
note = fields.Text(string="Note")
| Python | 1 |
Decode, Default, Clone, PartialEq)]
#[cfg_attr(feature = "std", derive(Debug))]
pub struct FungibleItemType<AccountId> {
pub collection: u64,
pub owner: AccountId,
pub value: u128,
pub item_hash: H160,
}
#[derive(Encode, Decode, Default, Clone, PartialEq)]
#[cfg_attr(feature = "std", derive(Debug))]
pu... | Rust | 0 |
) -> Result<
Ref<'_, T>,
std::sync::PoisonError<std::sync::RwLockReadGuard<'_, crate::RawEventQueue<T>>>,
> {
self.0.eq.read().map(|eq| Ref { eq, key: self.0.key })
}
}
impl<T> std::ops::Deref for Ref<'_, T> {
type Target = T;
#[inline]
fn deref(&self) -> &T {
... | Rust | 0 |
from abc import ABC, abstractmethod
class OnChainManagement(ABC):
"""
An abstract base class for on-chain management.
"""
@abstractmethod
def get_treasury_balance(self) -> float:
"""
Gets the balance of the treasury.
"""
pass
@abstractmethod
def add_to_vau... | Python | 1 |
esp - stack_space & 0xFFFF
};
return_on_pagefault!(translate_address_system_write(new_stack_pointer));
return_on_pagefault!(translate_address_system_write(
ss_segment_descriptor.base() + new_esp - 1
));
// no exceptions below
... | Rust | 0 |
)
/// itself, usually as one of the first lines.
///
pub const NCDIRECT_OPTION_INHIBIT_SETLOCALE: NcDirectFlags =
crate::bindings::ffi::NCDIRECT_OPTION_INHIBIT_SETLOCALE as NcDirectFlags;
/// Flag that inhibits registration of the SIGINT, SIGSEGV, SIGABRT & SIGQUIT
/// signal handlers.
pub const NCDIRECT_OPTION_NO... | Rust | 0 |
selected_columns = [eval(x) for x in selected_columns]
selected_columns = union_lists(selected_columns)
selected_columns = match_real_column(selected_columns, table_info["table_text"][0])
real_selected_columns = []
table_text = table_info["table_text"]
table = twoD_list_transpose(table_text)
... | Python | 1 |
ut_op_kwargs': None,
'nonlin': nn.LeakyReLU, 'nonlin_kwargs': {'inplace': True},
}
}
conv_or_blocks_per_stage = {
'n_conv_per_stage': configuration_manager.n_conv_per_stage_encoder,
'n_conv_per_stage_decoder': configuration_manager.n_conv_per_stage_decoder
}
model =... | Python | 1 |
= "/src/fetch.js")]
extern "C" {
type FetchedData;
#[wasm_bindgen(method, getter)]
fn data(this: &FetchedData) -> Vec<u8>;
#[wasm_bindgen(method, getter)]
fn text(this: &FetchedData) -> String;
#[wasm_bindgen(method, getter)]
fn mime(this: &FetchedData) -> String;
#[wasm_bindgen(method,... | Rust | 0 |
notification_sent = True
return sign_dict
formhash = formhash_match.group(1)
logger.info(f"成功获取formhash: {formhash[:10]}...")
except requests.Timeout:
logger.error("访问阡陌居首页超时")
# 常规重试逻辑
... | Python | 1 |
struct ParamDictionaryLink {
uniforms: Vec<usize>,
blocks: Vec<usize>,
textures: Vec<usize>,
}
impl<R: Resources> ShaderParam for ParamDictionary<R> {
type Resources = R;
type Link = ParamDictionaryLink;
fn create_link(this: Option<&ParamDictionary<R>>, info: &shade::ProgramInfo)
... | Rust | 0 |
c,
UF: Send + 'static,
Msg: 'static,
{
}
impl<M, UF, Msg> DispatchMsg<Msg> for AppEl<M, UF, Msg>
where
M: Send + 'static,
UF: Fn(&mut M, Msg) -> Option<DynCmd<Msg>> + Send + 'static,
Msg: Send + 'static,
{
fn dispatch_msg(self: Arc<Self>, msg: Msg) {
Runtime::dispatch_msg(self, msg);
... | Rust | 0 |
h(first_index + 2);
}
}
Ok(self)
}
/// Takes the accumulated geometry and return it as [MeshData].
pub fn build(&self) -> MeshData {
MeshData {
vertices: &self.buffer.vertices,
indices: &self.buffer.indices,
}
}
}
#[derive(Copy, Clone... | Rust | 0 |
t_dir);
let contents = read_graphql_file(&file_path).map_err(Error::FileError)?;
file_path.pop();
add_imported_fragments(&file_path, imports, &contents, root_dir)?;
let mut parsed = graphql_parser::parse_query(&contents)
.map_err(|e| Error::GraphqlFileParseError(file_path.clo... | Rust | 0 |
import json
import sys
import os
# This script deals with pushshift zst data, was used to build out LegendLore on posts > 1000 posts ago (Reddit API's limit)
# Builds a big, proper json file out of every year/month's data - it switched from yearly to monthly at some point, ugh
# Honestly don't use this for anything it... | Python | 1 |
0 | 2 | 2 | 1 | 1 | 3 | 3 | 0 | 2 | 2 | 4 | 4 | 1 | 1 | 3 | 3 | 5 | 5 | ... |
//!
//! where n, m, and j are the radial order, the azimuthal order and the polynomial index, respectively
use rayon::prelude::*;
const PI: f64 = std::f64::consts::PI;
const E: f64 = std::f64::consts::E;
fn ln_gamma(f64:... | Rust | 0 |
import streamlit as st
from streamlit_option_menu import option_menu
import requests
import os
# --- Config --- #
st.set_page_config(page_title="Ajitha Pamula | AI Portfolio", page_icon="🤖", layout="wide")
# --- Sidebar --- #
with st.sidebar:
st.image("https://avatars.githubusercontent.com/u/151291194?v=4", widt... | Python | 1 |
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, software
// distributed un... | Rust | 0 |
# Problem link - https://leetcode.com/problems/search-a-2d-matrix/
# Solution - https://www.youtube.com/watch?v=JXU4Akft7yk&list=PLgUwDviBIf0pMFMWuuvDNMAkoQFi-h0ZF&index=26
class Solution:
@staticmethod
def search(mtx, x):
"""
Time complexity is O(log(nm)) and space complexity is O(1).
... | Python | 1 |
import os
import json
distances_file = 'distancesl.jsonl'
fixresultp_dir = 'D:\\py\\pub\\fixresultpl'
def load_distances(jsonl_file):
distances = {}
with open(jsonl_file, 'r') as f:
for line in f:
data = json.loads(line)
distances[data['id']] = {
'disturbed': da... | Python | 1 |
batch["prompts"]
gold_labels = batch["hard_labels"].to(device) # (B,)
enc = tokenizer(
prompts,
return_tensors="pt",
padding=True,
truncation=True,
max_length=768,
).to... | Python | 1 |
services (Google) so we can
give modules a temporary token.
On success, ModuleSecret "secret" sub-dict will have keys:
* `"token_type"`: token type (expect `"Bearer"`)
* `"access_token"`: OAuth 2.0 token
Otherwise, ModuleSecret "error" value will be an I18nMessage... | Python | 1 |
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the F... | Python | 1 |
#!/usr/bin/env python
"""
Simple, ctypes-based Python 2/3 interface to C API of xylib.
It would be possible to wrap it neatly in classes,
or to make bindings to C++ API of xylib,
but it is not planned due to low demand.
"""
from __future__ import print_function
from ctypes import cdll, c_char_p, c_double
import os
_... | Python | 1 |
col in required_columns if col not in parts_df.columns]
if missing_columns:
raise HTTPException(
status_code=503,
detail=f"Missing columns in parts data: {missing_columns}"
)
return {
"status": "healthy",
... | Python | 1 |
shape, sqrt_one_minus_alphas[index], device=device)
# direction pointing to x_t
dir_b_t = (1. - a_t_m_1 - sigma_t ** 2).sqrt() * e_t
noise = sigma_t * torch.randn_like(l_t).to(device)
# reparameterize x_0
b_0_reparam = (l_t - sqrt_one_minus_at * e_t) / a_t.s... | Python | 1 |
def solve(grid):
orig_header = grid[0][:]
m = len(orig_header)
ring_color = {j: orig_header[j] for j in range(m) if orig_header[j] != 0}
center_color = ring_color.get(0)
ci = cj = None
for i in range(2, len(grid)):
for j in range(m):
if grid[i][j] == center_color:
... | Python | 1 |
wrap_all import GLOBAL_EMPTY_STRING_ENUM
assert GLOBAL_EMPTY_STRING_ENUM == ""
def test_int_to_string():
from wrap_all import int_to_string
if is_pyd: # FIXME
with pytest.raises(RuntimeError):
assert int_to_string(42) == "42"
else:
assert int_to_string(42) == "42"
... | Python | 1 |
();
let mut new_request_builder = Request::builder()
.method(request.method())
.uri(url.unwrap());
// Pass on the headers
let mut other_headers = HashMap::new();
for (name, value) in request.headers() {
if name.as_str() ==... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.