text string | label_name string | labels int64 |
|---|---|---|
return logging_dict['loss']
@torch.no_grad()
def generate(self, text=None, img=None, src_key_padding_mask = None, return_logits=False, **kwargs):
pred_tokens, logits = self._generate(text=text, img=img, src_key_padding_mask=src_key_padding_mask, **kwargs)
pred = self.tokenizer_y.d... | Python | 1 |
c.shape, dtype=np.float16)
style_inp = cuda.DeviceView(ptr=style_c.reshape(-1).data_ptr(), shape=style_c.shape, dtype=np.int64)
freqs_cis_img0_inp = cuda.DeviceView(ptr=freqs_cis_img0_c.reshape(-1).data_ptr(),
shape=freqs_cis_img0_c.shape, dtype=n... | Python | 1 |
) -> Point3<f32> {
Point3::new(
(-WIDTH / 2 + i * CELL_WIDTH) as f32,
(HEIGHT / 2 - j * CELL_HEIGHT) as f32,
0.0,
)
}
fn setup() {
size(800, 800);
background(0.2);
unsafe {
GRID = Some(Grid::new(COLS, ROWS, CELL_WIDTH, CELL_HEIGHT));
if let Some(ref mut grid)... | Rust | 0 |
template=TEMPLATE,
),
# vehicles to be placed in the network at the start of a rollout (see
# flow.core.params.VehicleParams)
veh=vehicles,
# parameters specifying the positioning of vehicles upon initialization/
# reset (see flow.core.params.InitialConfig)
initial=InitialConfig(
... | Python | 1 |
sports[line["qcode"]] = set(line["values"])
i += 1
if is_test and i > 10000:
break
return sports
def get_qcode_classes(
qcode: str, occupations, sports, country, instance_of, class_explorer, subclasses
) -> Set[str]:
classes = set()
# subclasses disabled as t... | Python | 1 |
ssign chosen object as parent to all selected objects'''
bl_idname = "object.assign_parent"
bl_label = "Assign Parent Object"
def available_objects(self,context):
objs_to_ignore = ["Camera", "Lamp", "Image", "ImageStackLadder"]
items = [(str(i),x.name,x.name) for i,x in enumerate(bpy.data.o... | Python | 1 |
p).await,
}
}
//! Prelude module with common types used for unit tests.
pub use crate::test::transport::TestTransport;
use futures::future::FutureExt;
pub use serde_json::json;
use std::future::Future;
pub use web3::api::Web3;
/// An extension future to wait for a future.
pub trait FutureTestExt: Future {
///... | Rust | 0 |
_err();
}
}
<filename>src/codec/tests.rs<gh_stars>0
use std::str::FromStr;
use super::*;
use crate::{types::*, util::*};
#[test]
fn decoder_simple() {
let mut codec = Codec::new();
let buf = &mut BytesMut::new();
buf.reserve(1024);
buf.put("ping\r\npOnG\r\n");
assert_eq!(
codec.decode(b... | Rust | 0 |
Vec3::new(a as f32 + 0.9 * rng.gen::<f32>(), 0.2, b as f32 + 0.9 * rng.gen::<f32>());
if (center - Vec3::new(4.0, 0.2, 0.0)).length() < 0.9 {
continue;
}
world.push(Box::new(Sphere::new(center, 0.2,
if choose_nat < 0.8 {
Box::new(L... | Rust | 0 |
'''
@Description:
@Author: shenlei
@Date: 2023-12-18 16:54:50
@LastEditTime: 2024-01-07 00:22:50
@LastEditors: shenlei
'''
query_instruction_for_retrieval_dict = {
"BAAI/bge-large-en": "Represent this sentence for searching relevant passages: ",
"BAAI/bge-base-en": "Represent this sentence for searching relev... | Python | 1 |
features: 'Win32_System_SystemServices'*"]
pub const D3DVIS_MASK_BOTTOM: u32 = 768u32;
#[doc = "*Required features: 'Win32_System_SystemServices'*"]
pub const D3DVIS_MASK_FAR: u32 = 12288u32;
#[doc = "*Required features: 'Win32_System_SystemServices'*"]
pub const D3DVIS_MASK_FRUSTUM: u32 = 3u32;
#[doc = "*Required fea... | Rust | 0 |
from net.swordie.ms.constants import BossConstants
from net.swordie.ms.enums import EventType
# Mode, Required Level, Map ID, Death Count, Event Type
destinations = [
["Normal", 160, 270050100, 5, EventType.Pinkbean, 64800000],
["Chaos", 160, 270051100, 5, EventType.CPinkbean, 64800000],
]
runsPerDay = 1
if... | Python | 1 |
, .. })) =
&module.maybe_types_dependency
{
pending.push(specifier);
}
}
}
}
}
// clear out all the mapped modules
for specifier in specifiers.mapped_packages.keys() {
modules.remove(specifier);
}
// at this point, the remaining modules are t... | Rust | 0 |
proof: &InRangeProof,
rng: &mut Rng,
) -> Fallible<()> {
// Generators for Pedersen commitments.
let pc_gens = PedersenGens::default();
// Generators for Bulletproofs, valid for proofs up to bitsize 64
// and aggregation size up to 1.
let bp_gens = BulletproofGens::new(64, 1);
// Transcrip... | Rust | 0 |
1.l = -0.3
# x2.l = -0.39
# x3.l = 0.3
# x4.l = -0.344
# x5.l = -1.2
# x6.l = 2.69
# x7.l = 1.59
# x8.l = -1.5
# Initial point (Variant 3)
x1.l = -0.041
x2.l = -0.775
x3.l = 0.03
x4.l = -0.047
x5.l = -2.565
x6.l = 2.565
x7.l = -0.754
x8.l = 0.754
... | Python | 1 |
toPoint::random(&mut OsRng));
assert_eq!(
set.iter()
.verify(&gens, &mut t.clone(), &proof)
.unwrap_err(),
ProofError::VerificationFailed
);
set.push(RistrettoPoint::random(&mut OsRng));
assert_eq!(
set.iter()
... | Rust | 0 |
Mary"), B("had"), B("a little lamb")]);
///
/// let x: Vec<_> = b"".splitn_str(3, "X").collect();
/// assert_eq!(x, vec![b""]);
///
/// let x: Vec<_> = b"lionXXtigerXleopard".splitn_str(3, "X").collect();
/// assert_eq!(x, vec![B("lion"), B(""), B("tigerXleopard")]);
///
/// let x: Vec<_... | Rust | 0 |
er: W) -> BufferWriter<W> {
BufferWriter {
inner,
buf: Vec::with_capacity(capacity),
written: 0,
}
}
pub fn get_ref(&self) -> &W {
&self.inner
}
pub fn get_mut(&mut self) -> &mut W {
&mut self.inner
}
fn get_pin_mut(self: Pin... | Rust | 0 |
atus(self, mode):
'''
Set remote control status.
Input:
mode(int) :
0 : "Local and locked",
1 : "Remote and locked",
2 : "Local and unlocked",
3 : "Remote and unlocked",
Output:
None
'''
status = {
... | Python | 1 |
导出成功", f"表格内容已保存到 {file_path}")
def load_param_json(self):
file_path, _ = QFileDialog.getOpenFileName(self, "选择参数库JSON", "", "JSON Files (*.json)")
if not file_path:
return
with open(file_path, "r", encoding="utf-8") as f:
data = json.load(f)
self.param_li... | Python | 1 |
odes with slope estimation methods
//! * `SlopeMethod`: Enum for slope estimation methods
//! * `Akima`: Akima's method to estimate slopes ([Akima (1970)](https://dl.acm.org/doi/abs/10.1145/321607.321609))
//! * `Quadratic`: Using quadratic interpolation to estimate slopes
//!
//! ## Usage
//!
//! ```rust
//!... | Rust | 0 |
import numpy as np
a = np.arange(49).reshape(7,7)
# Use fancy indexing to specify rows and columns desired.
ridx = [0, 2, 4]
cidx = [1, 3, 5]
result = a[ridx, cidx]
print('result.shape', result.shape)
print('result ', result) | Python | 1 |
title_duplicate: false,
};
return HttpResponse::build(StatusCode::OK).json(response);
}
let result = connection.transaction::<_, Error, _>(|| {
let insert_file = InsertFile {
uploader_id: auth.user_id,
t... | Rust | 0 |
# -*- coding: utf-8 -*-
import unittest
import os
from pprint import pprint
from itertools import cycle
from .fixtures import Memo, PublicKey, PrivateKey
from graphenebase.memo import get_shared_secret, _pad, _unpad, encode_memo, decode_memo
test_cases = [
{
"from": "GPH7FPzbN7hnRk24T3Nh9MYM1xBaF5xyRYu8Wty... | Python | 1 |
), ScratchData))
self.assertTrue(isinstance(self.nwbfile.scratch['test'], ScratchData))
self.assertEqual(self.nwbfile.scratch['test'].data, [1, 2, 3, 4])
def test_get_scratch_df_convert_false(self):
data = pd.DataFrame(data={'col1': [1, 2, 3, 4], 'col2': ['a', 'b', 'c', 'd']})
self.... | Python | 1 |
ring,
}
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
struct BigStruct {
id: String,
name: String,
comment: String,
objects: Vec<Obj>,
hi: String,
counter: u32,
}
impl TryFrom for BigStruct {
type TryFrom = BigStruct;
}
fn build_big() -> BigStruct {
let mut objects = Vec::new();
for i in... | Rust | 0 |
name + " - %s" % instance
self.submit_job(
context,
payload,
instances=[instance],
deadline=AVALON_DEADLINE
)
else:
# Submit a single job
self.submit_job(
conte... | Python | 1 |
pace() {
word_list.push({
let mut internal_annotations: Vec<InternalWordAnnotation> = vec![];
if config.srt_config.timestamp_linking {
internal_annotations.push(InternalWordAnnotation::SRTUrlSuffix(
SRTWordListGe... | Rust | 0 |
=================================================================
# Disable supplies, close plots, log files, and FPGA on exit
# =============================================================================
finally:
dut.FrameController.end_blitz()
print("Finished blitzing histograms")
... | Python | 1 |
executive::Executive<Runtime, Block, ChainContext<Runtime>, Runtime, AllPallets>;
pub type ClassId = u32;
pub type InstanceId = u32;
pub type OctopusAssetId = u32;
pub type OctopusAssetBalance = u128;
pub struct OctopusAppCrypto;
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to ... | Rust | 0 |
68, but rather
/// is inspired by the OpenSSL PEM decoder.
///
/// Returns a slice which starts at the beginning of the encapsulated text.
///
/// From RFC7468:
/// > Data before the encapsulation boundaries are permitted, and
/// > parsers MUST NOT malfunction when processing such data.
pub(crate) fn strip_preamble(mu... | Rust | 0 |
# coding: utf-8
from requests.utils import quote
class Downloader(object):
header = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) "
"AppleWebKit 537.36 (KHTML, like Gecko) Chrome",
"Accept-Language": "zh-CN,zh;q=0.8",
"Accept": "text/html,application/xhtml+xml,a... | Python | 1 |
action_get_user_info = "user.get_user_info"
action_freeze_balance = "user.freeze_balance"
action_unfreeze_balance = "user.unfreeze_balance"
action_freeze_stock = "product.freeze_stock"
action_unfreeze_stock = "product.unfreeze_stock"
action_fetch_product_details = "product.fetch_product_details"
action_purchase_product... | Python | 1 |
import sys
import sympy
assert sys.version_info >= (3, 5)
def dot(left, right):
assert(isinstance(left, sympy.Matrix))
assert(isinstance(right, sympy.Matrix))
sum = 0
for c in range(0, left.cols):
for r in range(0, left.rows):
sum += left[r, c] * right[r, c]
return sum
def... | Python | 1 |
let mut decomp: Vec<u8> = Vec::new();
lzma_rs::xz_decompress(&mut f, &mut decomp)?;
decomp.shrink_to_fit();
Ok(String::from_utf8(decomp)?)
}
/// Get the network graph as a string.
pub fn load_network_graph(graph_options: &GraphOptions) -> Result<String, Box<dyn Error>> {
Ok(match graph_options {
... | Rust | 0 |
def count_upper(s):
"""
Given a string s, count the number of uppercase vowels in even indices.
For example:
count_upper('aBCdEf') returns 1
count_upper('abcdefg') returns 0
count_upper('dBBE') returns 0
"""
count = 0
for i in range(0, len(s), 2):
if s[i].isupper():
... | Python | 1 |
if !predicate(&value) {
Some(value)
} else {
None
}
}
})
.collect();
for i in garbage {
(self as &dyn KeyValueStoreBackend<S>).delete(&i)?;
}
Ok(())
... | Rust | 0 |
raise ValueError('Cant run multiples sets '
'if source is a generator')
return (_frequencies_from_records(source,
ids=get_indices(s),
size_mb=size_mb)
... | Python | 1 |
(16384, 16384, 16384, 32, 32): (1, 4, 32, 32, 1, 1),
(16384, 16384, 16384, 64, 64): (1, 2, 64, 32, 1, 2),
(16384, 16384, 16384, 128, 128): (3, 1, 32, 64, 1, 4),
(16384, 16384, 32768, 16, 16): (1, 4, 16, 64, 3, 1),
(16384, 16384, 32768, 32, 32): (1, 2, 32, 32, 1, 1),
(1638... | Python | 1 |
145,8193,12289,16385,24577];
const DIST_EXTRA: [u8; 30] = [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
const HCORD: [usize; 19] = [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
// PNG types
const TYPE_L1: u16 = 0x0100;
const TYPE_C1: u16 = 0x0103;
const TYPE_L2: u16 = 0x0200;
const TYPE_C2... | Rust | 0 |
result = self.form_table(table)
return result
def process_scopes(self):
result = ""
table = [['level', 'type']]
for i, level in enumerate(self.scopes):
if ord(level) == JERRY_DEBUGGER_SCOPE_WITH:
table.append([str(i), 'with'])
elif o... | Python | 1 |
, "/test_shm", 0
)
async def test_unregister_system_shared_memory(self):
await self._triton_client.unregister_system_shared_memory()
async def test_get_cuda_shared_memory_status(self):
await self._triton_client.get_cuda_shared_memory_status()
async def test_register_cuda_share... | Python | 1 |
import bpy
from os.path import basename, dirname
from .types import ExportDataType
from .status import ArnoldStatus
import arnold
BTOA_PACKAGE_NAME = basename(dirname(dirname(__file__)))
BTOA_TYPE_CONSTANTS = {
"UINT": arnold.AI_TYPE_UINT,
"STRING": arnold.AI_TYPE_STRING,
"MATRIX": arnold.AI_TYPE_MATRIX... | Python | 1 |
));
}
}
}
}
}
Ok(IrValue::String(Shared::new(buf)))
}
}
<reponame>jsirex/habitat<filename>test-services/test-probe/src/config.rs
use crate::error::{Error,
Result};
use clap::ArgMatches;
use std::{fs,
... | Rust | 0 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'main.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, ... | Python | 1 |
test_management_command_sends_email_with_pending_feeds(self):
call_command("send_pending_approval_email", verbosity=0)
self.assertEqual(1, len(mail.outbox))
self.assertEqual(mail.outbox[0].to, [self.user.email])
def test_feeditem_approved(self):
self.assertQuerySetEqual(
... | Python | 1 |
.add_attribute("owner", owner.into_string())
.add_attribute("staking_addr", staking_addr.into_string())
.add_attribute("reward_token", reward_token.into_string())
.add_attribute("reward_rate", reward_rate))
}
pub fn validate_cw20(deps: Deps, cw20_addr: Addr) -> bool {
let response: Result<... | Rust | 0 |
self.radio.events_disabled.reset();
if !self.state().is_disabled() {
// In case we're currently receiving, stop that
self.radio.tasks_disable.write(|w| w.bits(1));
// Then wait until disable event is triggered
while self.radio.ev... | Rust | 0 |
AN_POS_5_R(crate::FieldReader<u8, u8>);
impl GPADC_SCAN_POS_5_R {
pub(crate) fn new(bits: u8) -> Self {
GPADC_SCAN_POS_5_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for GPADC_SCAN_POS_5_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::T... | Rust | 0 |
l_dt::f32, dnnl_tag::oihw);
auto w_mem = dnnl::memory(w_md, engine, (float*) w);
auto dy_md = dnnl::memory::desc({bs, o, oh, ow}, dnnl_dt::f32, dnnl_tag::nchw);
auto dy_mem = dnnl::memory(dy_md, engine, (float*) dy);
std::vector<dnnl_dim_t> strides{sh, sw};
std::vector<dnnl_dim_t> pad_l{ph... | Rust | 0 |
ove these 2 ops and
# reduce the output range which in turn helps to improve accuracy
if next_node is not None:
if next_node.op_type == "Clip":
clip_min = next_node.attribute[0].f
clip_max = next_node.attribute[1].f
if range_min < clip_min:
... | Python | 1 |
system = platform.system().lower()
ffmpeg_url = ""
if system == "windows":
ffmpeg_url = "https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-essentials.zip"
else:
print("Ce script ne supporte actuellement que Windows.")
return
download_path = "ffmp... | Python | 1 |
)
def current_frame() -> lldb.SBFrame:
global current_exec_context
if lldb.frame:
return lldb.frame
if current_exec_context:
return current_exec_context.GetFrame()
raise Exception('No current execution context')
def nat_eval(sbframe, expr):
val = sbframe.FindVariable(expr)
if... | Python | 1 |
__author__ = 'zaxlct'
__date__ = '2017/4/3 下午12:29'
from django import forms
from captcha.fields import CaptchaField
from .models import UserProfile
class LoginForm(forms.Form):
username = forms.CharField(required=True)
password = forms.CharField(required=True, min_length=5)
class RegisterForm(forms.Form):... | Python | 1 |
type_size),
);
ret.insert(
"seed_nonce_revelation_tip",
UniversalValue::big_num(self.seed_nonce_revelation_tip.clone()),
);
ret.insert(
"origination_size",
UniversalValue::num(self.origination_size),
);
ret.insert(
... | Rust | 0 |
-> Self {
Self {
paillier_keys: PaillierKeys::random(),
zkp_setup: ZkpSetup::random(DEFAULT_GROUP_ORDER_BIT_LENGTH),
}
}
}
#[test]
fn bob_zkp() {
let _ = env_logger::builder().is_test(true).try_init();
(0..5).for_each(|_| {
... | Rust | 0 |
ncluded in API response")
return True
else:
print(f"\n[ISSUE] No ML fields in response")
return False
else:
print(f"\n[ISSUE] Result is not a dict: {result}")
return False
except Exception as e:
print(f... | Python | 1 |
def give_sum(n,d,m):
s = n//d*m
r = n%d
if r==0:
return s
elif r <=6:
return s+15
elif r <=8:
return s+20
elif r <=10:
return s+25
def main():
t = int(input())
for i in range(t):
n = int(input())
if n <= 6:
print(15)
e... | Python | 1 |
else {
rulerTop = height;
rulerBottom = screenCoord.y;
}
const float halfWidth = lineWidth * 0.5f;
const float x0 = trunc(cards[i].detailLineOffset.x + screenCoord.x - halfWidth);
const float... | Rust | 0 |
_owner.task);
let addr = map_memory(&ctx, UserAddress::default(), *PAGE_SIZE);
ctx.task
.mm
.write_memory(addr, &[0u8; std::mem::size_of::<sigset_t>() * 2])
.expect("failed to clear struct");
let original_mask = Signal::SIGTRAP.mask();
{
*... | Rust | 0 |
e() + f2.clone()) +
prime_field::fmul(
fri_eval_point_divbyx_squared, f0.clone() + (m_prime.clone() - f2.clone())
);
let mut f4 = ctx[evals_on_coset_idx + 4].clone();
let fri_eval_point_div_by_x2 = prime_field::fmul( fri_eval_point_divbyx.clone(), ctx[fri_half_inv_group_idx + 4].clone() );
let f5 = ctx[ev... | Rust | 0 |
ocusIn>", lambda event: onclick_entry(event, "Nama Lengkap"))
nama.bind("<FocusOut>", lambda event: onleave_entry(event, "Nama Lengkap"))
frame2 = tk.Frame(register_frame, width=295, height=2, bg="#eaebf1").pack(pady=(5, 20))
# Input email
email = tk.Entry(register_frame, width=36, fg="#eaebf1", border... | Python | 1 |
num.append(20)
high_num.append(10)
low_num.append(10)
overall_num.append(20)
high_num.append(10)
low_num.append(10)
overall_num.append(20)
high_num.append(10)
low_num.append(10)
acc_close = acc_high_near + acc_high_far
acc_far = acc_low_near + acc_low_far
test_dat = pd.DataFrame([name, acc_overall, acc_close, acc_fa... | Python | 1 |
(source);
}
});
// configure appsink
appsink.set_emit_signals(true);
appsink.set_caps(Some(&audio_caps));
let data_weak = Arc::downgrade(&data);
appsink.connect_new_sample(move |_| {
let data = match data_weak.upgrade() {
Some(data) => data,
None => retu... | Rust | 0 |
from scapy.all import *
from typing import Dict, Any
import ipaddress
from datetime import datetime
def extract_packet_info(packet) -> Dict[str, Any]:
"""
Extract relevant information from a packet.
Args:
packet: Scapy packet object
Returns:
dict: Dictionary containing packet ... | Python | 1 |
ex!(MoveOutIndex, "mo");
}
pub use self::indexes::MovePathIndex;
pub use self::indexes::MoveOutIndex;
impl self::indexes::MoveOutIndex {
pub fn move_path_index(&self, move_data: &MoveData) -> MovePathIndex {
move_data.moves[*self].path
}
}
/// `MovePath` is a canonicalized representation of a path th... | Rust | 0 |
hp')
gdf = get_alloc_pred()
gdf = gdf[gdf.Alloc_type == alloc]
gdf['Com_abs'] = gdf['Commodity'].apply(lambda x: x.split('_')[1])
gdf = gdf[gdf.Com_abs.isin(['Copper', 'Nickel', 'Zinc'])]
# Spatial join
w_regions = gpd.sjoin(w_regions, gdf, how='inner', predicate='intersects')
# ... | Python | 1 |
c = "The last calibration operation completed to meet 1% accuracy"]
#[inline(always)]
pub fn sysctl_pioscstat_crpass(self) -> &'a mut W {
self.variant(SYSCTL_PIOSCSTAT_CRW::SYSCTL_PIOSCSTAT_CRPASS)
}
#[doc = "The last calibration operation failed to meet 1% accuracy"]
#[inline(always)]
p... | Rust | 0 |
clone());
match avg_fixed.clone() {
Some(ref version) => {
if let Some(ref v) = a.fixed {
let cmp = alpm::vercmp(version.to_string(), v.to_string());
if let Ordering::Greater = cmp {
avg_fixed = ... | Rust | 0 |
_base_ = './mask_rcnn_swin-t-p4-w7_fpn_fp16_ms-crop-3x_coco.py'
pretrained = 'https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_small_patch4_window7_224.pth' # noqa
model = dict(
backbone=dict(
depths=[2, 2, 18, 2],
init_cfg=dict(type='Pretrained', checkpoint=pretrained)))
| Python | 1 |
#!/usr/bin/python
# This is to test label arithmetic on x86
# Github issue: #66
# Author: Ingmar Steen
from keystone import *
import regress
VALID_ENCODINGS_1 = [
[0x2d, 0x0a, 0x00, 0x00, 0x00],
[0x81, 0xe8, 0x0b, 0x00, 0x00, 0x00],
[0x83, 0xe8, 0x0b],
]
VALID_ENCODINGS_2 = [
[0x2d, 0x08, 0x00, ... | Python | 1 |
.. Default::default() },
&consts::ALPHA_PHONE_MAPPINGS).national);
}
#[test]
fn international_prefix() {
assert_eq!(Number {
country: country::Source::Idd,
national: "45677003898003".into(),
.. Default::default()
}, helper::international_prefix(Some(&CachedRegex::new(DATABASE.cache(), "00[39]").... | Rust | 0 |
import ast
class ConditionEvaluator:
"""
Evaluate simple boolean expressions with &&, ||, comparison ops,
variables and numeric literals (dec, hex, bin). Also extracts all
equality tests of the form `var == const`.
"""
# AST node types allowed in expressions
_ALLOWED_NODES = {
ast.E... | Python | 1 |
<T>);
#[derive(Debug, Arbitrary)]
struct T4(T3<NotArbitrary>);
#[derive(Debug, Arbitrary)]
struct T5<T>(PhantomData<T>);
#[derive(Debug, Arbitrary)]
struct T6(T5<NotArbitrary>);
#[derive(Debug, Arbitrary)]
struct T7<T>(std::marker::PhantomData<T>);
#[derive(Debug, Arbitrary)]
struct T8(T7<NotArbitrary>);
#[derive... | Rust | 0 |
odel.num_dofs),
figureheight = '\\figureheight', figurewidth = '\\figurewidth', show_info=False)
if idf.opt['outputAs'] == 'html':
path = os.path.dirname(os.path.abspath(__file__))
template_environment = Environment(autoescape=False,
... | Python | 1 |
print!("\x1B[2J\x1B[1;1H"); //clear the screen
c = ctrl.chars().collect::<Vec<char>>()[0];
if c.is_numeric() {
ctrl = ctrl.chars().filter(|d| d.is_digit(10)).collect();
print!("You chose {: }: ", ctrl);
let index = ctrl.parse::<usize>().expect("Invalid entr... | Rust | 0 |
y", InventoryInformation_json)
except:
raise HTTPException(status_code=500, detail="Invalid data")
return db_inventory
@inventory_router.put("/{id}", response_model=InventoryRead)
async def replace_inventory(session: Annotated[Session, Depends(get_session)], producer: Annotated[AIOKafkaProducer, Depend... | Python | 1 |
is deprecated and will be removed in Python {remove}; use value insteadU{name} is deprecated and will be removed in Python {remove}; use ast.Constant insteadr c L SSK nUR S[ SS9 U R $ )Deprecated. Use value instead.r NAttribute nr ... | Python | 1 |
.txt";
let expected_file = "./flamegraph/test/results/perf-vertx-stacks-01-collapsed-all.txt";
// Test with file passed in
let output = Command::cargo_bin("inferno-collapse-perf")
.unwrap()
.arg("--all")
.arg(input_file)
.output()
.expect("failed to execute process")... | Rust | 0 |
pieces(&["fae50"]),
mode: Mode::Multiple {
files: vec![FileInfo {
length: Bytes(1024),
md5sum: None,
path: FilePath::from_components(&["a", "b"]),
}],
},
},
};
#[rustfmt::skip]
let want = concat!(
"d",
"8:announce",... | Rust | 0 |
import pytest
from dbt.tests.util import run_dbt, run_dbt_and_capture
from tests.functional.adapter.basic.files import (
base_table_sql,
base_view_sql,
generic_test_seed_yml,
generic_test_table_yml,
generic_test_view_yml,
schema_base_yml,
seeds_base_csv,
)
class BaseGenericTests:
@pyt... | Python | 1 |
row.prop(props, "use_display_roughness", text="")
row.prop(props, "batch_display_roughness", text="Roughness")
layout.operator("material.batch_material_helper", text="Apply to Selected Objects")
def register():
try:
bpy.utils.register_class(BatchMaterialProperties)
... | Python | 1 |
esponses.append(llm_response)
try:
nctid_list = run_search_ctgov(query, search_api)
recall = len(set(nctid_list) & set(ground_truth)) / len(ground_truth)
batch_recalls.append(recall)
except Exception as e:
print(f"Error in search query: {str(e)}")... | Python | 1 |
from datetime import datetime
from metrics.logic.celery_tasks.util import bulk_create_from_csv
from metrics.models.video import VideoInteractionChart, VideoInteraction, VideoPlayCountChart, VideoPlayCount
def create_video_interaction_chart(course_id: str) -> VideoInteractionChart:
return bulk_create_from_csv(
... | Python | 1 |
ition relative to 0 level of the gkm 31 ellipsoid
Absolute,
/// Position relative to ground level
Relative,
}
#[cfg(test)]
mod test {
use crate::{
CameraInfo, DroneInfo, Fov, Image, Label, LatLon, LocationInfo, PolyDEM, TexturePolygon,
Utm, GKM31,
};
use geo_utm::{Band, Zone};
... | Rust | 0 |
run very slowly, but it will work.)
///
/// Also note that this limit is *per thread of execution*. That is, if the
/// same regex is used to search text across multiple threads simultaneously,
/// then the DFA cache is not shared. Instead, copies are made.
///
/// TODO(burntsushi): This feels like a knob that a calle... | Rust | 0 |
process.SetSelectedThread(stepping_thread)
self.runCmd(step_cmd)
frame = stepping_thread.GetFrameAtIndex(0)
current_line = frame.GetLineEntry().GetLine()
# Make sure we're still where we thought we were
self.assertTrue(
current_line >... | Python | 1 |
on == other.focus_position && self.zoom == other.zoom
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn camera_new() {
let cam = Camera2D::new();
assert_eq!(cam, Camera2D { focus_position: Vector2D { x: 0.0, y: 0.0 }, zoom: 1.0 });
}
#[test]
fn camera_from() {
... | Rust | 0 |
!{interface ITargetFileRequest(ITargetFileRequestVtbl): IInspectable(IInspectableVtbl) [IID_ITargetFileRequest] {
fn get_TargetFile(&self, out: *mut *mut super::super::IStorageFile) -> HRESULT,
fn put_TargetFile(&self, value: *mut super::super::IStorageFile) -> HRESULT,
fn GetDeferral(&self, out: *mut *mut ... | Rust | 0 |
HttpResponse::InternalServerError().body("")
}
}
///
///
///
async fn get_invocations(
_req: HttpRequest,
pool: web::Data<DbPool>,
) -> HttpResponse {
let conn = pool.get().expect(MSG_NO_DB_CONNECTION);
let invocations = db::invocations.load::<Invocation>(&conn);
if let Ok(invocations) =... | Rust | 0 |
# Copyright 2023 The Google Earth Engine Community 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... | Python | 1 |
171a}', Script::Ahom), ('\u{1171d}', '\u{1171f}',
Script::Ahom), ('\u{11720}', '\u{11721}', Script::Ahom), ('\u{11722}', '\u{11725}',
Script::Ahom), ('\u{11726}', '\u{11726}', Script::Ahom), ('\u{11727}', '\u{1172b}',
Script::Ahom), ('\u{11730}', '\u{11739}', Script::Ahom), ('\u{1173a}', ... | Rust | 0 |
': False
}
consumer = Consumer(consumer_config)
consumer.subscribe([args.topic])
print(f"Subscribed to topic: {args.topic}")
try:
conn = create_db_connection(
args.sql_server,
args.database,
username=args.db_username,
password=args.db_passwor... | Python | 1 |
Hasher::<()>::new(label).empty()`.
impl MerkleItem for () {
fn commit(&self, t: &mut Transcript) {
t.append_message(b"", b"");
}
}
impl AsRef<[u8]> for Hash {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl core::ops::Deref for Hash {
type Target = [u8];
fn deref(&self) -> &Self::... | Rust | 0 |
== GPIO34OUTCFG_A::PUSHPULL
}
#[doc = "Checks if the value of the field is `OD`"]
#[inline(always)]
pub fn is_od(&self) -> bool {
*self == GPIO34OUTCFG_A::OD
}
#[doc = "Checks if the value of the field is `TS`"]
#[inline(always)]
pub fn is_ts(&self) -> bool {
*self == GPI... | Rust | 0 |
ash_length = OUTBYTES as u8;
state
};
let mut root_state = base_params
.clone()
.node_offset(0)
.node_depth(1)
.last_node(true)
.to_state();
// Clear the keybytes from the root state buffer. Only the leaf nodes will hash the... | Rust | 0 |
import sys
sys.stdin = open('input12712.txt')
def sqaure(N, M, pari):
#정방향 data_row, col 구분
data_row = [0, 1, 0, -1]
data_col = [1, 0, -1, 0]
#일단 정방형 + 노즐 기반으로 가장 큰 값 구하기
total_max = 0
#모든 노즐은 일단 탐색
for row in range(N):
for col in range(N):
four_sum = 0
for ... | Python | 1 |
model_data:
print(f'PROCESSING {data["file_path"]} (model: {data["model"]}, exp_type: {data["exp_type"]}, size: {len(data["data"])})...\n{"#" * 50}\n')
embed_data(data)
save_data(data['data'], os.path.join(OUTPUT_DIR, model, os.path.basename(data["file_path"])))
print(f'... | Python | 1 |
"""将创造对象 和 使用对象分开"""
from db_configs import db_configs
class DatabaseConnection:
def __init__(self, host, port, username, password):
self.host = host
self.port = port
self.username = username
self.password = password
def connect(self):
return f"Connecting to databse at ... | Python | 1 |
b = Vec3::new(vals[1][0], vals[1][1], vals[1][2]) * radius + offset;
let c = Vec3::new(vals[2][0], vals[2][1], vals[2][2]) * radius + offset;
let d = Vec3::new(vals[3][0], vals[3][1], vals[3][2]) * radius + offset;
let e = Vec3::new(vals[4][0], vals[4][1], vals[4][2]) * radius + off... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.