text string | label_name string | labels int64 |
|---|---|---|
from __future__ import annotations
import os
from dotenv import load_dotenv
load_dotenv()
from src.bank_payout import BankConfig, BankBeneficiary, send_bank_payout
def main() -> int:
cfg = BankConfig()
bene = BankBeneficiary(
name=os.getenv("BANK_BENEFICIARY_NAME", "Beneficiary"),
account_n... | Python | 1 |
"timed_out": false,
"hits": {
"total": 2,
"hits": [""" + """
{
"_id": "1",
"timestamp": 1609780186,
"sort": [1609780186, "1"]
},""" * 100 + """
... | Python | 1 |
of a mockable function. Checks if mock is set and if it is, calls it.
fn call_mock(&self, input: T) -> MockResult<T, O>;
#[doc(hidden)]
/// Returns a unique ID of the function, which is used to set and get its mock.
unsafe fn get_mock_id(&self) -> TypeId;
}
/// Controls mocked function behavior when ... | Rust | 0 |
// ===== FilterFn =====
pub(crate) fn filter_fn<F, U>(func: F) -> FilterFn<F>
where
F: Fn(&mut Route) -> U,
U: TryFuture,
U::Ok: Tuple,
U::Error: IsReject,
{
FilterFn { func }
}
pub(crate) fn filter_fn_one<F, U>(
func: F,
) -> FilterFn<impl Fn(&mut Route) -> future::MapOk<U, fn(U::Ok) -> (U::O... | Rust | 0 |
import sqlite3
import sqlite_vec # type: ignore
from ..config import DB_PATH, EMBED_DIM
def ensure_db() -> sqlite3.Connection:
con = sqlite3.connect(DB_PATH)
con.enable_load_extension(True)
sqlite_vec.load(con)
con.enable_load_extension(False)
con.execute("PRAGMA journal_mode=WAL;")
# per‑... | Python | 1 |
;
use tikv::raftstore::Result;
use tikv_util::config::*;
use tikv_util::HandyRwLock;
#[test]
fn test_replica_read_not_applied() {
let mut cluster = new_node_cluster(0, 3);
// Increase the election tick to make this test case running reliably.
configure_for_lease_read(&mut cluster, Some(50), Some(10_000));... | Rust | 0 |
"Generating LALR tables\n"
))
def test_yacc_uprec(self):
self.assertRaises(ply.yacc.YaccError,run_import,"yacc_uprec")
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"yacc_up... | Python | 1 |
],
);
let mut exec = BatchLimitExecutor::new(src_exec, 4, false).unwrap();
let r = exec.next_batch(1);
assert_eq!(&r.logical_rows, &[1, 2]);
assert_eq!(r.physical_columns.rows_len(), 3);
assert!(!r.is_drained.unwrap());
let r = exec.next_batch(1);
... | Rust | 0 |
# -*- coding: utf-8 -*-
"""Adhikansh Gami ANN DEEP learning
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1FR2x3W_n-BWgLrPGAXlgFmYW_tXtyOeC
"""
pip install tensorflow
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(... | Python | 1 |
FrameIndex: i32, VisibleFlag: i32) -> i32;
pub fn dx_MV1GetFrameBaseVisible(MHandle: i32, FrameIndex: i32) -> i32;
pub fn dx_MV1SetFrameTextureAddressTransform(
MHandle: i32,
FrameIndex: i32,
TransU: f32,
TransV: f32,
ScaleU: f32,
ScaleV: f32,
RotCenterU:... | Rust | 0 |
!student_in_workshop(conn, student_id, workshop_id) {
return Err(());
}
let workshop: Result<Workshop, diesel::result::Error> =
workshops_t.filter(ws_id.eq(workshop_id)).first(conn);
if workshop.is_err() {
return Err(());
}
let workshop = workshop.unwrap();
let students... | Rust | 0 |
>, usize>,
ctx: &Context,
compilation_unit_dirs: &[&str],
cu: &DebuggingInformationEntry<EndianBuf<LittleEndian>, usize>,
entry: &DebuggingInformationEntry<EndianBuf<LittleEndian>, usize>,
start_address: u64,
size: u64,
) -> Procedure<PM> {
let NameInfo {
name,
linkage_name,
... | Rust | 0 |
lt<CurrentBranches, _>>()
.map_err(|err| err.message().to_string())
}
pub mod line22;
pub mod line28;
pub mod line34;
pub mod line36;
pub mod line44;
pub mod line47;
pub mod line49;
pub mod line55;
use core::marker::Sized;
use embedded_hal::{
blocking::{delay::*, spi::Write},
digital::v2::*,
};
/// All... | Rust | 0 |
}
')' => {
plevel -= 1;
if plevel == 0 {
last = Some(i + 1);
}
if plevel == -1 {
last = Some(i + 1);
break;
}
}
_ => {}
}
... | Rust | 0 |
import sys
import random
import collections
# @include
MPG = 20
# gallons[i] is the amount of gas in city i, and distances[i] is the
# distance city i to the next city.
def find_ample_city(gallons, distances):
remaining_gallons = 0
CityAndRemainingGas = collections.namedtuple('CityAndRemainingGas',
... | Python | 1 |
"""renpy
init python:
"""
def mix(a, b, k):
return a + (b-a) * k
class ParticleDust(renpy.Displayable):
def __init__(self, image, speed=1.0, center=None, lock=True):
super().__init__()
self.speed = speed
self.center = center
self.lock = lock
# 1层图像层
self.dust... | Python | 1 |
|_| tar.finish())
})
})
.wrap_err(format!(
"Folca: Cannot write to cache {}",
&cached_path.to_string_lossy()
))
.unwrap_or_else(|e| warn!("{}", e));
let output_size = self.output_size(output_path).unwrap();
... | Rust | 0 |
/// lanewise i8x16 subtraction
#[inline(always)]
pub fn sub_i8(self, other: m128i) -> m128i {
m128i(unsafe { _mm_sub_epi8(self.0, other.0) })
}
/// lanewise i8x16 subtraction with saturation
#[inline(always)]
pub fn saturating_sub_i8(self, other: m128i) -> m128i {
m128i(unsafe { _mm_subs_epi8(self... | Rust | 0 |
(_OSUnalignedU32))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_OSUnalignedU32>())).__val as *const _ as usize },
0usize,
concat!("Offset of field: ", stringify!(_OSUnalignedU32), "::", stringify!(__val))
);
}
#[repr(C, packed)]
#[derive(Debug, Copy, Clone)]
pub struct _OSUnaligne... | Rust | 0 |
=0,y=0)
root.title("Account")
# Imagine on label
img=ImageTk.PhotoImage(Image.open('Additional_Files/main.jpg'))
lbImg=Label(f1,width=600,height=500,image=img)
lbImg.place(x=0,y=0)
lblWel = Label(f1, text=f'Welcome\n{account_userName.get()}',bg="#FF6868",fg="white",font='Helvetica 10 bold')... | Python | 1 |
"/repos/{}/{}/issues/{}/comments",
self.owner, self.repo, self.number
)
}
}
// representations
#[derive(Debug, Deserialize)]
pub struct Comment {
pub id: u64,
pub url: String,
pub html_url: String,
pub body: String,
pub user: User,
pub created_at: String,
... | Rust | 0 |
from_slice(&ecrc);
let enc_len = to_encode.len();
let aes_enc = aessafe::AesSafe128Encryptor::new(&key[..]);
let mut encryptor = blockmodes::EcbEncryptor::new(aes_enc, blockmodes::NoPadding);
let mut out = Vec::<u8>::with_capacity(enc_len);
out.resize(enc_len, 0u8);
{... | Rust | 0 |
from rdflib import Literal, Namespace, URIRef
from rdflib.namespace import RDF, RDFS, SKOS
PRODUCTS = Namespace("https://vocab.sentier.dev/products/")
CUSTOM_PRODUCTS_DATA = [
("electrolyzer", "type", "Concept"),
("electrolyzer", "broader", "http://data.europa.eu/xsp/cn2024/854330700080"),
("electrolyzer"... | Python | 1 |
r line in mount_out.split('\n'):
fields = line.split()
if len(fields) != 0 and fields[0] != 'node' and fields[0][0] != '-' and re.match('^/.*|^[a-zA-Z].*|^[0-9].*', fields[0]):
if re.match('^/', fields[0]):
# normal mount
... | Python | 1 |
import torch
import math
import warnings
from torch.nn.init import _calculate_fan_in_and_fan_out
def _no_grad_trunc_normal_(tensor, mean, std, a, b):
# Cut & paste from PyTorch official master until it's in a few official releases - RW
# Method based on https://people.sc.fsu.edu/~jburkardt/presentations/trun... | Python | 1 |
: i64) -> Option<Range> {
if min >= max {
return None;
}
let min_value = evaluate(terms, min);
let max_value = evaluate(terms, max);
// printlnerr!(" Values {:?}:{:?}, {:?}:{:?}", min, min_value, max, max_value);
if min_value.includes_0() {
if max_value.includes_0() {
Some(Range::new(min, max... | Rust | 0 |
TargetMachineAsmVerbosity, LLVMCreateTargetMachine, LLVMGetTargetMachineCPU, LLVMGetTargetMachineFeatureString, LLVMGetDefaultTargetTriple, LLVMAddAnalysisPasses, LLVMCodeGenOptLevel, LLVMCodeModel, LLVMRelocMode, LLVMCodeGenFileType, LLVMTargetMachineEmitToMemoryBuffer, LLVMTargetMachineEmitToFile};
use crate::{Addre... | Rust | 0 |
(cookie.clone())
.set_json(&item_data)
.uri("/reference_items")
.to_request();
let resp = call_service(m_app, req).await;
assert_eq!(resp.status(), http::StatusCode::OK);
// make GET list request
let req = TestRequest::get()
.cookie(cookie... | Rust | 0 |
.create_user(account_id("carol"), to_yocto("100")),
];
(root, list)
}
pub fn assert_burnt_gas(
message: &str,
result: &ExecutionResult,
tera_gas: &str,
has_error: Option<usize>,
) {
print!("{}: ", message);
assert_eq!(
result.promise_errors().len(),
has_error.unwrap_or_d... | Rust | 0 |
from enum import Enum
import numpy as np
class SeperatorLines(Enum):
empty = 0 # 打印空行
short = 1 # 打印10个'-'
middle = 2 # 打印30个'-'
long = 3 # 打印40个'='
def print_seperator_line(style: SeperatorLines, info=None):
if style == SeperatorLines.empty:
print("")
elif style == Seperator... | Python | 1 |
0x0090 => Err(Self::Error::NeitherDefinedNorReserved(0x0090)),
0x0091 => Ok(LANG_GD),
0x0092 => Ok(LANG_KU),
0x0093 => Err(Self::Error::Reserved(0x0093, "quc")),
0x0401 => Ok(LANG_AR_SA),
0x0402 => Ok(LANG_BG_BG),
0x0403 => Ok(LANG_CA_ES),
... | Rust | 0 |
"""Exception classes raised by urllib.
The base exception class is URLError, which inherits from IOError. It
doesn't define any behavior of its own, but is the base class for all
exceptions defined in this package.
HTTPError is an exception class that is also a valid HTTP response
instance. It behaves this way beca... | Python | 1 |
from easydict import EasyDict
ant_trex_sac_config = dict(
exp_name='ant_trex_sac_seed0',
env=dict(
manager=dict(shared_memory=True, reset_inplace=True),
env_id='Ant-v3',
norm_obs=dict(use_norm=False, ),
norm_reward=dict(use_norm=False, ),
collector_env_num=1,
eva... | Python | 1 |
import cv2
import imutils
import numpy as np
import math
from PIL import Image
def erode(mask, kernel_size=(3,3), iterations=1):
kernel = np.ones(kernel_size, np.uint8)
eroded_mask = mask.copy()
for _ in range(iterations):
eroded_mask = np.minimum.reduce([eroded_mask[i:mask.shape[0]-kernel_siz... | Python | 1 |
d AVX512BW`
///
/// `16/32/64-bit`
EVEX_Vpbroadcastb_xmm_k1z_r32 = 3208,
/// `VPBROADCASTB ymm1 {k1}{z}, r32`
///
/// `EVEX.256.66.0F38.W0 7A /r`
///
/// `AVX512VL and AVX512BW`
///
/// `16/32/64-bit`
EVEX_Vpbroadcastb_ymm_k1z_r32 = 3209,
/// `VPBROADCASTB zmm1 {k1}{z}, r32`
///
/// `EVEX.512.66.0F38.W0 7... | Rust | 0 |
aises((TypeError, AttributeError), f, 10)
def test_iterable_args(self):
for f in (self.module.nlargest, self.module.nsmallest):
for s in ("123", "", range(1000), (1, 1.2), range(2000,2200,5)):
for g in (G, I, Ig, L, R):
self.assertEqual(list(f(2, g(s))), list... | Python | 1 |
Manual, Volume 2: System Programming
pkru: u32,
/// Reserved.
reserved_7a: [u8; 20],
/// Reserved.
reserved_8: u64,
/// RCX register.
rcx: u64,
/// RDX register.
rdx: u64,
/// RBX register.
rbx: u64,
/// Reserved.
reserved_9: u64,
/// RBP register.
rbp... | Rust | 0 |
this.evict_target(t_clone).await;
}
});
if self
.target_cache
.borrow_mut()
.replace(CachedTarget::new_with_task(t.clone(), eviction_task))
.is_none()
{
self.publish_event(bridge::MdnsEventType::TargetFound... | Rust | 0 |
, 2, 3], [4, 5, 6]],
/// [[7, 8, 9], [10, 11, 12]],
/// ];
/// let sum = arr
/// .producer()
/// .fold_axes(axes((0, 2)), into_repeat(0), |acc, &elem| acc + elem)
/// .collect_array();
/// assert_eq!(sum, array![1 + 2 + 3 + 7 + 8 + 9, 4 + 5 + 6 + 10 + 11 + 12]);
/// ```
... | Rust | 0 |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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 app... | Python | 1 |
.first::<models::User>(conn)
.optional()?;
Ok(user)
}
/// 使用 Diesel 插入一个新数据并返回值
pub fn insert_new_user(
nm: &str,
conn: &SqliteConnection,
) -> Result<models::User, diesel::result::Error> {
use schema::users::dsl::*;
let new_user = models::User {
id: Uuid::new_v4().to_stri... | Rust | 0 |
",
"mov r8, {q_3}",
"mulx r9, rdi, r8",
"adox r10, r11",
"adcx r12, r11",
"adox r12, rdi",
"adcx r13, r9",
"adox r13, r11",
// round 2
"mov rdx, qword ptr [{a_ptr} + 16]",
"mulx r9, r8, qword ptr [{b... | Rust | 0 |
opt(alt((
map(Self::parse_language_tag, |(first, repeating)| {
let mut all_parts = vec![first];
all_parts.extend_from_slice(&repeating);
either::Either::Left(Cow::Owned(all_parts.join("-")))
}),
... | Rust | 0 |
" Starts a new preboard service on the specified device and connects to it."]
#[doc = ""]
#[doc = " @param device The device to connect to."]
#[doc = " @param client Pointer that will point to a newly allocated"]
#[doc = " preboard_client_t upon successful return. Must be freed using"]
#[doc = ... | Rust | 0 |
e.device.cuda.synchronize()
def _move_past_key_values_to_cpu(self, past_key_values):
if past_key_values is None:
return None
return tuple(tuple(t.cpu() for t in layer) for layer in past_key_values)
def _move_past_key_values_to_gpu(self, past_key_values, device="gpu:0"):
if ... | Python | 1 |
map_res(
preceded(
alt((tag("0x"), tag("0X"))),
recognize(many1(terminated(
one_of("0123456789abcdefABCDEF"),
many0(complete::char('_')),
))),
),
|out: &str| i64::from_str_radix(&str::replace(&out... | Rust | 0 |
):
all_sequence = read_data(file_path)
sequences = list(all_sequence.values())
sca_total_number, genome_total_length, sca_gap_length, sca_avg_length, sca_N50, sca_N90, sca_max_length, sca_min_length, sca_GC = scaffold_statics(sequences)
filename = os.path.basename(file_path)
return f"{filename}\t... | Python | 1 |
IpeINTEL",
5804 => "SubgroupAvcSicEvaluateWithSingleReferenceINTEL",
5805 => "SubgroupAvcSicEvaluateWithDualReferenceINTEL",
5806 => "SubgroupAvcSicEvaluateWithMultiReferenceINTEL",
5807 => "SubgroupAvcSicEvaluateWithMultiReferenceInterlacedINTEL",
5808 => "SubgroupAvcSicConvertToMceResultINTEL",
... | Rust | 0 |
v(LoadSource::Gpr(GPR_C), StoreTarget::Gpr(GPR_D)), // mov d,c
0x13 => Instruction::Mov(LoadSource::Gpr(GPR_A), StoreTarget::TransferLow), // mov tl,a
0x14 => Instruction::Mov(LoadSource::Gpr(GPR_B), StoreTarget::TransferLow), // mov tl,b
0x15 => Instruction::Mov(LoadSource::Gpr(GPR_C), StoreTa... | Rust | 0 |
.unwrap()
.post("https://localhost:3032/contracts_post/")
.json(&command_list_all);
let res = builder.send();
println!("{:#?}", res);
println!();
println!("Press <Enter> to create a Keep");
io::stdin()
.read_line(&mut user_input)
.expect("Failed to read line");... | Rust | 0 |
APPLE_TVOS: Platform = Platform {
target_triple: "x86_64-apple-tvos",
target_arch: Arch::X86_64,
target_os: OS::TvOS,
target_env: Env::None,
target_endian: Endian::Little,
target_pointer_width: PointerWidth::U64,
tier: Tier::Three,
};
/// [Fortanix ABI] for 64-bit Intel SGX
pub(crate) const... | Rust | 0 |
s.update(keys)
player_bullets.update()
enemy_bullets.update()
# collisions
for b in player_bullets:
hit = pygame.sprite.spritecollideany(b, enemy_group)
if hit:
b.kill()
hit.kill()
score += 100
for b in ene... | Python | 1 |
X_treinamento, X_teste, y_treinamento, y_teste = train_test_split(
imagens, rotulos, test_size=0.2, random_state=42
)
#normalizar pixels:
X_treinamento = X_treinamento / 255.0
X_teste = X_teste / 255.0
num_folds = 5
acuracias = []
kf = KFold(n_splits=num_folds, shuffle=True)
def criar_modelo():
modelo = Seq... | Python | 1 |
listener.warning(format!("Found built asset with non-path source '{:?}'", asset));
}
}
}
if separate_file {
// If we want to debug symols included in a separate file, add these files to the debian assets
options.add_debug_assets();
}
Ok(())
}
<repon... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
Internationalization module.
"""
from typing import Optional, TypeAlias
NestedDict: TypeAlias = dict[str, 'str | NestedDict']
"""@litedoc-hide"""
i18n_dict: dict[str, NestedDict] = { # @litedoc-hide
"en" : {
"docstring" : {
"args" ... | Python | 1 |
::get_or_create_evm_address(&who);
let info = T::Runner::create(source, init, value, gas_limit, storage_limit, T::config())?;
let used_gas: u64 = info.used_gas.unique_saturated_into();
Ok(PostDispatchInfo {
actual_weight: Some(T::GasToWeight::convert(used_gas)),
pays_fee: Pays::Yes,
})
}
///... | Rust | 0 |
nt::DRSDisabled),
"TMPT" => {
let vehicle_index = cursor.byte_order().read_u8().await?;
Ok(Event::TeamMateInPits(TeamMateInPits { vehicle_index }))
}
"CHQF" => Ok(Event::ChequeredFlag),
"RCWN" => {
let vehicle_index = cursor.byte_order().read_u8().awa... | Rust | 0 |
'J': 10, 'K': 10, 'L': 10, 'M': 10, 'N': 10, 'O': 10, 'P': 10, 'Q': 10, 'R': 10, 'S': 10, 'T': 10, 'U': 10, 'V': 10, 'W': 10, 'X': 10, 'Y': 10, 'Z': 10, ' ': 10, '!': 10, '"': 10, '#': 10, '$': 10, '%': 10, '&': 10, "'": 10, '(': 10, ')': 10, '*': 10, '+': 10, ',': 10, '-': 10, '.': 10, '/': 10, ':': 10, ';': 10, '<':... | Python | 1 |
ants(name, variants)?;
self.leave_class();
Ok(())
}
fn output_variants(
&mut self,
base: &str,
variants: &BTreeMap<u32, Named<VariantFormat>>,
) -> Result<()> {
for (index, variant) in variants {
self.output_variant(
base,
... | Rust | 0 |
import json
import pytest
from typing import List
def test_json_method(simple_app):
app_client = simple_app.test_client()
headers = {"Content-type": "application/json"}
# Test with valid JSON
payload = {"key": "value"}
response = app_client.post("/v1.0/test_json", headers=headers, json=payload... | Python | 1 |
from .. import codegen as cg
import sympy as sp
def cross(A, B):
return sp.Matrix(
[
A[1] * B[2] - A[2] * B[1],
A[2] * B[0] - A[0] * B[2],
A[0] * B[1] - A[1] * B[0],
]
)
def dot(A, B):
return sum(A[i] * B[i] for i in range(A.shape[0]))
if __name__ ==... | Python | 1 |
() returns zero on success, or one of the error values listed in the next section on failure. The value of errno is not set. On Linux (and other systems),
// posix_memalign() does not modify memptr on failure. A requirement standardizing this behavior was added in POSIX.1-2016.
if ptr.is_null() && si... | Rust | 0 |
ChatCompletionResponseChoice(
index=0,
message=Message(role="assistant", content=formatted_response),
finish_reason="stop"
)
]
)
logger.info(f"发送响应内容: \n{response}")
# 返回fast... | Python | 1 |
common::EXTENSION_AST_EXPORTS) => {
let file = File::create(path).into_diagnostic()?;
common::serialize(file, &(&ast.module_name, &ast.exports))?;
}
Some(common::EXTENSION_CHECKER_WARNINGS) => {
let file = File::create(path).into_diagnostic()?;
... | Rust | 0 |
Database is the list of gesture templates in Recognizer
database = GestureDatabase(recognizer=self.recognizer)
database_screen = Screen(name='database')
database_screen.add_widget(database)
self.database = database
self.manager.add_widget(database_screen)
# Settings scr... | Python | 1 |
::SparseBinaryVec;
use crate::util::get_both_indices;
use serde::{Deserialize, Serialize};
use std::mem::size_of;
// Stores a matrix in sparse representation, with an optional dense block for the right most columns
// The logical storage is as follows:
// |---------------------------------------|
// | ... | Rust | 0 |
# Section 3.6 snippets
grade = 85
if grade >= 60:
print('Passed')
else:
print('Failed')
grade = 57
if grade >= 60:
print('Passed')
else:
print('Failed')
grade = 99
if grade >= 60:
print('Passed')
else:
print('Failed')
# Conditional Expressions
grade = 87
if grade >= 60:
result = '... | Python | 1 |
class Solution:
def pacificAtlantic(self, matrix: list[list[int]]) -> list[list[int]]:
if not matrix or not matrix[0]:
return []
R, C = len(matrix), len(matrix[0])
pacific, atlantic = set(), set()
def dfs(r, c, seen):
if (r, c) in seen:
return... | Python | 1 |
let (input, _) = parse_tag(",")(input)?;
let (input, _) = parse_tag("expire")(input)?;
let (input, expires) = parse_token(input)?;
Ok((input, expires))
}
let end = preceded(multispace0, alt((eof, tag(";"))));
let (input, expire) = alt((parse_expire, end))(input)?;
let expire = ... | Rust | 0 |
def constant_init(module, constant, bias=0):
nn.init.constant_(module.weight, constant)
if hasattr(module, 'bias'):
nn.init.constant_(module.bias, bias)
| Python | 1 |
# Generated by Django 5.1.6 on 2025-03-03 06:14
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='CardType',
fields=[
... | Python | 1 |
}
}
#[derive(Debug)]
pub struct InvitationByToken;
impl View for InvitationByToken {
type Collection = Invitation;
type Key = u64;
type Value = ();
fn unique(&self) -> bool {
true
}
fn version(&self) -> u64 {
0
}
fn name(&self) -> Result<bonsaidb::core::schema::N... | Rust | 0 |
enum Event {
Tick,
Message(AlertSenderMessage),
}
let event = select! {
_ = interval.tick().fuse() => Event::Tick,
message = receiver.recv().fuse() => match message {
None => break,
Some(message) => Event::Message(message),
}
};
tracing::info!("Begin alert_sender heartbeat");
let mut ... | Rust | 0 |
import torch
import torch.optim as optim
from data.prepare_data import get_dataloader
from models.autoregressive import AutoregressiveModel
from models.diffusion import DiffusionLoss
from utils.args import parse_config
from utils.plot import plot_losses
device = torch.device("cuda" if torch.cuda.is_available() else "c... | Python | 1 |
not in results:
# get hdf5_nb_tracers, hdf5_mz_tracer and set idx_calibration
with h5py.File(tracer_file_path, 'r') as hdf5_f:
ds = hdf5_f[ini['tracer']['detected_masses_column']]
hdf5_nb_tracers = ds.shape[0]
hdf5_mz_tracer = n... | Python | 1 |
mut items = PrintItems::new();
let text = if context.parse_string_content {
// don't trim this because it's the content
&node.content
} else {
let should_trim = if let Some(Node::BreakableString(parent)) = context.parent() {
if let Some(BreakableStringComponent::String(str)) = parent.compon... | Rust | 0 |
""" EJERCICIO:
- Crea ejemplos de funciones básicas que representen las diferentes
posibilidades del lenguaje:
Sin parámetros ni retorno, con uno o varios parámetros, con retorno...
- Comprueba si puedes crear funciones dentro de funciones.
- Utiliza algún ejemplo de funciones ya creadas en el lenguaje.
- Pon a pru... | Python | 1 |
## Copyright 2011, IOActive, Inc. All rights reserved.
##
## AndBug is free software: you can redistribute it and/or modify it under
## the terms of version 3 of the GNU Lesser General Public License as
## published by the Free Software Foundation.
##
## AndBug is distributed in the hope that it will be useful, but W... | Python | 1 |
false);
assert_eq!(Float::new(1.1), 1.1);
}
#[test]
fn test_display() {
assert_eq!(Float::new(22.0).to_string(), "22".to_string());
assert_eq!(
Float::new(3.14159265359).to_string(),
"3.1415927".to_string()
);
assert_eq!(
Float::n... | Rust | 0 |
te::common::{BanjoLibraryName, ElementType, File};
use crate::json::JsonObject;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct BanjoLibrary {
pub name: BanjoLibraryName,
pub root: File,
#[serde(rename = "type")]
pub kind: ElementType,
pub sou... | Rust | 0 |
tx_hash),
Err(BatchError::Shutdown) => Err(RpcError::Provided {
code: INTERNAL_ERROR_ERR_CODE,
message: "mem pool is unavailable due to batch shutdown",
}),
Err(BatchError::ExceededMaxLimit) => Err(RpcError::Provided {
code: MEMPOOL_IS_FULL_ERR_CODE,
... | Rust | 0 |
::<MiEI>().unwrap().write().unwrap();
if let Some(guild) = msg.guild_id {
let rm_roles = args
.raw()
.filter_map(|x| roles.remove_role(x, &ctx, guild).ok())
.collect::<Vec<&str>>();
if rm_roles.is_empty() {
msg.channel_id
.say(&ctx.http... | Rust | 0 |
,
'🃒': 113,
'🃓': 113,
'🃔': 113,
'🃕': 113,
'🃖': 113,
'🃗': 113,
'🃘': 113,
'🃙': 113,
'🃚': 113,
'🃛': 113,
'🃜': 113,
'🃝': 113,
'🃞': 113,
'🃟': 113,
'🐭': 115,
'🐮': 130,
'🐱': 115,
'🐵': 127,
'😀': 115,
'😁': 115,
'😂': 129,
'😃': 115,
'😄': 115,
'😅': 115,
'😆': 115,
'😇': 115,
'😈': 115,
'😉': 115,
'😊': 115,... | Python | 1 |
a().map(|v| v.element.reference_mut()),
// FIXME generate match and propagate the binding
Binding { name, ty } => ty.data().map(|field| {
let node = ValueNode::Destructure {
parent: self.index,
accessor: field.accessor.clone(),
... | Rust | 0 |
expected membership degrees.
Returns:
None
"""
triangular_mf = Triangular.create(
n_variables=4, n_terms=4, device=AVAILABLE_DEVICE, method="random"
)
element = np.array([[0.0001712, 0.00393354, -0.03641258, -0.01936134]])
target_membership_degree... | Python | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 19 17:33:12 2021
@author: bmoseley
"""
# This module imports and calls various plotting functions depending on the dimensionality of the FBPINN / PINN problem
# This module is used during training by main.py
import plot_main_1D
import plot_main_2... | Python | 1 |
f(p0 + three * h))
/ (h * sixty)
}
#[test]
fn numeric_differentiation_produces_correct_results() {
// function x*sin(x)+x^2*cos(x)
let f = |x: f64| x * x.sin() + x.powi(2) * x.cos();
// derivative: d/dx(x sin(x) + x^2 cos(x)) = x^2 (-sin(x)) + sin(x) + 3 x cos(x)
let df = |x: f64| -x.powi(2) *... | Rust | 0 |
/// This should not be visible during normal usage. The only time this would
/// affect you is if you were attempting to use `sql_query` with tuples.
/// Your code would not compile in that case, as the `ToSql` trait itself is
/// not implemented.
///
/// You can implement `ToSql` for named composit... | Rust | 0 |
#this program prints a inputted name
firstname=input("What is your first name? ")
lastname=input("What is your last name? ")
print(firstname + " " + lastname) | Python | 1 |
e!("cmp {} {} {:?} {:?}", args, required_args, callable, {
let function_index = self.stack.len() - 1 - args;
&(*self.stack)[(function_index + 1) as usize..]
});
match args.cmp(&required_args) {
Ordering::Equal => Ok(enter_scope(self, false)),
Ordering::Les... | Rust | 0 |
"0xbc - lodist."]
pub lodist: crate::Reg<lodist::LODIST_SPEC>,
#[doc = "0xc0 - sdm1."]
pub sdm1: crate::Reg<sdm1::SDM1_SPEC>,
#[doc = "0xc4 - sdm2."]
pub sdm2: crate::Reg<sdm2::SDM2_SPEC>,
#[doc = "0xc8 - sdm3."]
pub sdm3: crate::Reg<sdm3::SDM3_SPEC>,
_reserved48: [u8; 32usize],
#[d... | Rust | 0 |
import matplotlib.pyplot as plt
from pystressed.models import SectionForce
from pystressed.SLS import plot_magnel, optimize_magnel, optimize_and_plot_magnel
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = ['Arial']
plt.rcParams.update({'font.size': 12})
# Author: James Whiteley (github.co... | Python | 1 |
ic modes in
the Jordan-Wigner representation.
Locally equivalent to iSwap and ``Can(1/2, 1/2, 0)``
.. math::
\text{FSwap} = \begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & 0 & i & 0 \\
0 & i & 0 & 0 \\
0 & 0 & 0 & ... | Python | 1 |
a> {
str_to_ocamlrep(self.borrow(), alloc)
}
fn from_ocamlrep(value: Value<'_>) -> Result<Self, FromError> {
Ok(Cow::Owned(String::from(str_from_ocamlrep(value)?)))
}
}
/// Allocate an OCaml string using the given allocator and copy the given string
/// slice into it.
pub fn str_to_ocamlre... | Rust | 0 |
*const BIGNUM,
ctx: *mut BN_CTX,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn BN_mod_exp_mont(
r: *mut BIGNUM,
a: *const BIGNUM,
p: *const BIGNUM,
m: *const BIGNUM,
ctx: *mut BN_CTX,
mont: *const BN_MONT_CTX,
) -> ::std::os::raw::c_int;
}
extern ... | Rust | 0 |
ult=False, help='can been used in mdn scoring model traing')
parser.add_argument('--atom_type_prediction', action='store_true', default=False, help='used in mdn scoring model traing')
parser.add_argument('--bond_type_prediction', action='store_true', default=False, help='used in mdn scoring model traing')
p... | Python | 1 |
let initial_state = GameState::new(player_positions[0], player_positions[1]);
let mut state_space = HashMap::new();
state_space.insert(initial_state, 1usize);
while state_space
.iter()
.any(|(g, _)| g.winner() == GameOutcome::NoWinnerYet)
{
for player in &[0, 1] {
... | Rust | 0 |
aloader = dgl.dataloading.DataLoader(
g,
train_nid,
sampler,
batch_size=2048 * 8,
shuffle=True,
drop_last=True,
use_uva=False
)
num_batches = len(dataloader)
print("Number of batches: ", num_batches)
count_time = 0
start = time.time()
for ... | Python | 1 |
from GPT2_QG.interact import *
if __name__ == "__main__":
run()
| Python | 1 |
ools/mkeficapsule --index 1 --guid 058B7D83-50D5-4C47-A195-60D86AD341C4 uboot_bin_env.itb Test05' %
(data_dir, u_boot_config.build_dir),
shell=True)
if capsule_auth_enabled:
# firmware signed with proper key
check_call('cd %s; '
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.