text string | label_name string | labels int64 |
|---|---|---|
.len() - 1);
}
curr_block = BasicBlock::new();
}
curr_label = Some(label.clone());
}
bril_rs::Code::Instruction(bril_rs::Instruction::Effect { op, .. })
if op == bril_rs::EffectOps::Jump
|| op == bril_rs::EffectOps::Branch
|| ... | Rust | 0 |
EqEq | BinaryOp::EqEqEq) {
return self.eqeq(left, right);
}
if matches!(op, BinaryOp::NotEq | BinaryOp::NotEqEq) {
return !self.eqeq(left, right);
}
}
_ => {}
}
true
}
// walk and record idents
fn walk_stmts(&mut self, stmts: &Vec<Stmt>) -> bool {
for stmt in stmts {
match stmt ... | Rust | 0 |
"""获取GPU信息接口"""
try:
# 使用优化系统的GPU管理器
if optimized_whisper_system:
system_status = optimized_whisper_system.get_system_status()
gpu_status = system_status.get('gpu_status', {})
# 转换为前端期望的格式
gpus = []
for gpu_id, status in gpu_status.item... | Python | 1 |
# === 6. Utilisateurs (CustomUser) ===
user_data = [
{
"username": "secretaire1",
"email": "sec1@example.com",
"first_name": "Léa",
"last_name": "Martin",
"role": "secretaire",
"phone_number": "613-111-2222",
"password": "secret123"
},
{
"us... | Python | 1 |
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
u8,
);
// Test vectors by lane ... | Rust | 0 |
obj.log_riskratio_se, self.log_riskratio_se)
def test_riskratio_pvalue(self):
assert_allclose(self.tbl_obj.riskratio_pvalue(), self.riskratio_pvalue)
def test_riskratio_confint(self):
lcb1, ucb1 = self.tbl_obj.riskratio_confint(0.05)
lcb2, ucb2 = self.riskratio_confint
assert... | Python | 1 |
let mut mock = MockHelloWorld::new();
let method = mock.method_foo().never_called();
mock.set_foo(method);
mock.foo();
}
#[test]
fn max_calls() {
let mut mock = MockHelloWorld::new();
let method = mock.method_foo().called_at_most(10).return_result_of(|| 10);
mock.set_foo(method);
for... | Rust | 0 |
(graph_info, (folium.Map, go.Figure)):
if isinstance(graph_info, folium.Map):
folium_static(graph_info, width=1400, height=500)
elif isinstance(graph_info, go.Figure):
st.plotly_chart(graph_info, use_container_width=... | Python | 1 |
import torch
from tools.align_utils import estimateSimilarityTransform, estimateSimilarityUmeyama
import numpy as np
import matplotlib
from PIL import Image
import open3d as o3d
def render_depth(values, colormap_name="magma_r") -> Image:
min_value, max_value = values.min(), values.max()
normalized_values = (va... | Python | 1 |
TlsConfig),
}
if let Some(trust_anchor) = tls_client_auth {
server = server.client_auth_required_path(trust_anchor);
}
Ok(server)
}
#[cfg(not(feature = "tls"))]
/// Runs a server with the provided filter routes.
async fn run_http<F>(filter: F, api_settings: ApiSettings) -> Result<(), Infallible... | Rust | 0 |
#!/usr/bin/python
#
# Copyright 2015 Google Inc. 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 b... | Python | 1 |
2548328edcf57,
0x5c4dfea657d1fec3,
0xb697d43a98f62e41,
0xb714def984f62c9d,
0x1594a6dba3f94c1b,
0x9f6e13bdc1fd4b87,
0xed5a346cbdcf69e3,
0xb21f87a32fe3a961,
0x91c8ba532ce496bd,
0x638ce4a54ae8c63b,
0xcde9b5f658ebd4a7,
0xc54d8b3a98cde415,
0xf4ea89cdc9e32481,
0x3ed4a67cb6c... | Rust | 0 |
from django.db import models
class StudentTag(models.Model):
"""Model relating students to tags"""
student = models.ForeignKey(
"NssUser", on_delete=models.CASCADE, related_name="tags")
tag = models.ForeignKey(
"Tag", on_delete=models.CASCADE, related_name="students")
class Meta:
... | Python | 1 |
var closeButtonHtml = arguments[4];
var closeButtonStyle = arguments[5];
var infoButtonHtml = arguments[6];
var infoButtonStyle = arguments[7];
var isNoneMode = arguments[8];
if (!container) return false;
... | Python | 1 |
# basically from /opt/MVS/Samples/64/Python/GrabImage
import sys
import cv2
import numpy as np
import time
sys.path.append("/opt/MVS/Samples/64/Python/MvImport")
from MvCameraControl_class import *
SDKVersion = MvCamera.MV_CC_GetSDKVersion()
print ("SDKVersion[0x%x]" % SDKVersion)
deviceList = MV_CC_DEVICE_INFO_LI... | Python | 1 |
&" ".repeat(3)]
.try_into()
.unwrap(),
vec![" ".repeat(5), " ".repeat(5)].try_into().unwrap(),
vec![" ".repeat(5), " ".repeat(5)].try_into().unwrap(),
vec![" ".repeat(5), " ".repeat(5)].try_into().unwrap(),
];
assert_eq!(drawing, expec... | Rust | 0 |
) -> RX_RESET_ST_R {
RX_RESET_ST_R::new(((self.bits >> 29) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Set this bit to reset transmitter."]
#[inline(always)]
pub fn tx_reset(&mut self) -> TX_RESET_W {
TX_RESET_W { w: self }
}
#[doc = "Bit 1 - Set this bit to reset receiver."]
... | Rust | 0 |
# SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2025 Oxford Quantum Circuits Ltd
from pathlib import Path
from qat.model.loaders.purr.base import BaseLegacyModelLoader
from qat.purr.backends.qblox.live import QbloxLiveHardwareModel
from qat.purr.compiler.hardware_models import (
QuantumHardwareModel as Leg... | Python | 1 |
),
I(I),
J(J),
}
impl<A, B, C, D, E, F, G, H, I, J> Future for Either10<A, B, C, D, E, F, G, H, I, J>
where
A: Future,
B: Future<Error = A::Error>,
C: Future<Error = A::Error>,
D: Future<Error = A::Error>,
E: Future<Error = A::Error>,
F: Future<Error = A::Error>,
G: Future<Error = A... | Rust | 0 |
.partition::<Vec<&str>, _>(|&&s| contains_chars(s, six[0], 5));
// if it contains 7's parts, it must be 3
let (three, remaining_digits) = remaining_digits
.iter()
.partition::<Vec<&str>, _>(|s| contains_chars(s, seven[0], 3));
... | Rust | 0 |
ing())
}
}
/// Parses a number that may or may not have prefixes.
pub fn parse_full_number(s: &[char], base: u8) -> Result<NumValue, String> {
if s[0] == '#' {
parse_prefixed_number(&s[1..], Some(base))
} else {
parse_number(s, base, Exactness::Default)
}
}
/// Parses a number with pre... | Rust | 0 |
oute('/') # Asi indico que es la pagina principal
def home():
return render_template('home.html', tables=[cotizaciones.value.to_html(classes='data', index=False)], titles=cotizaciones.value.columns.values)
@app.route('/sesgos') # Creo una pagina de about en mi web
def about():
... | Python | 1 |
macro_rules! assert_disabled_renders {
($($input:expr => $expected:expr,)*) => {
let _lock = LOCK.lock();
$(
Paint::disable();
let (actual, expected) = ($input.to_string(), $expected.to_string());
Paint::enable();
assert_eq!(actual, expected);
... | Rust | 0 |
#
# Copyright (c) 2008 Daniel Truemper truemped@googlemail.com
#
# forms.py 31-Jul-2011
#
# 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
#
# Unle... | Python | 1 |
ne)]
struct Value {
value: u32,
}
/// Тестирует запись перечислений со значениями разных видов
#[test]
fn test_enum_externally_tagged() {
#[derive(Serialize)]
enum E {
Unit,
Newtype1(u32),
Newtype2(Value),
Tuple1(u32, u32),
... | Rust | 0 |
itePoint::D60) => {
Some(Mat3::from_cols_array(&BT_2020_D65_TO_P3_D60).transpose())
}
(RGBPrimaries::BT_2020, WhitePoint::D65, RGBPrimaries::P3, WhitePoint::P3_DCI) => {
Some(Mat3::from_cols_array(&BT_2020_D65_TO_P3_P3_DCI).transpose())
}
(RGBPrimaries::BT_2020, W... | Rust | 0 |
\x03\x02\x14\n\r\n\x05\x05\x01\x02\x01\x02\x12\x04\xa7\x03\x17\
\x18\n\xda\x02\n\x04\x05\x01\x02\x02\x12\x04\xae\x03\x02\x1b\x1a\xcb\x02\
\x20The\x20Stackdriver\x20Premium\x20tier,\x20a\x20higher,\x20more\x20ex\
pensive\x20tier\x20of\x20service\n\x20that\x20provides\x20access\x20to\
\x20all\x20Stackdriv... | Rust | 0 |
&FUTEX as *const i32,
libc::FUTEX_WAIT,
0,
ptr::null::<libc::timespec>(),
), 0);
}
assert!((200..500).contains(&start.elapsed().as_millis()));
}
fn main() {
wake_nobody();
wake_dangling();
wait_wrong_val();
wait_timeout();
wait_wake();
... | Rust | 0 |
import os
import hydra
from omegaconf import DictConfig
import pytorch_lightning as pl
from pytorch_lightning.callbacks import ModelCheckpoint
from mydpr.model.biencoder import MyEncoder
from mydpr.dataset.cath35 import PdDataModule
import torch
from pytorch_lightning.callbacks import BasePredictionWriter
from typing i... | Python | 1 |
tHelpType {
type GlibType = gtk_sys::GtkWidgetHelpType;
fn to_glib(&self) -> gtk_sys::GtkWidgetHelpType {
match *self {
WidgetHelpType::Tooltip => gtk_sys::GTK_WIDGET_HELP_TOOLTIP,
WidgetHelpType::WhatsThis => gtk_sys::GTK_WIDGET_HELP_WHATS_THIS,
WidgetHelpType::__Un... | Rust | 0 |
= self.load_trimmed_reads('BC03.fasta')
bc04_trimmed_reads = self.load_trimmed_reads('BC04.fasta')
bc05_trimmed_reads = self.load_trimmed_reads('BC05.fasta')
bc06_trimmed_reads = self.load_trimmed_reads('BC06.fasta')
none_trimmed_reads = self.load_trimmed_reads('none.fasta')
bc0... | Python | 1 |
#!/usr/bin/env python3
import torch
from ..distributions import Delta, Distribution, MultivariateNormal
from ._variational_distribution import _VariationalDistribution
class DeltaVariationalDistribution(_VariationalDistribution):
"""
This :obj:`~gpytorch.variational._VariationalDistribution` object replaces... | Python | 1 |
terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/raphaelcohn/olympus-xmp/master/COPYRIGHT. No part of olympus-xmp, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT ... | Rust | 0 |
()`` as the third output.
This is only used by the radiative-backpropagation style
integrators.
"""
raise Exception('PSIntegrator does not provide the sample() method. '
'It should be implemented by subclasses that '
'specialize th... | Python | 1 |
from ebooklib import epub
import warnings
# 忽略 UserWarning 和 FutureWarning
warnings.filterwarnings("ignore", category=UserWarning)
warnings.filterwarnings("ignore", category=FutureWarning)
def remove_chapters(epub_file, output_file, chapters_to_remove):
"""从EPUB文件中删除指定章节并保存为新文件。
Args:
epub_file (str... | Python | 1 |
from pathlib import Path
from typing import Optional
import git
from phi.utils.log import logger
def get_remote_origin_for_dir(
ws_root_path: Optional[Path],
) -> Optional[str]:
"""Returns the remote origin for a directory"""
if ws_root_path is None or not ws_root_path.exists() or not ws_root_path.is_d... | Python | 1 |
"description" : "transmitted bytes per sec",
}))
descriptors.append(create_desc(Desc_Skel, {
"name" : "trans_pkts_" + target_device,
"units" : "pkts/sec",
"description" : "transmitted packets per sec",
}))
descript... | Python | 1 |
import torch
import torch.nn as nn
class RiskAwareLoss(nn.Module):
def __init__(self, alpha_over=1.0, alpha_under=1.5, lower_bound=-13, upper_bound=10):
super(RiskAwareLoss, self).__init__()
self.alpha_over = alpha_over # Penalty multiplier for overestimation
self.alpha_under = alpha_unde... | Python | 1 |
+ min);
}
use std::{
collections::VecDeque,
fmt::{self, Debug},
sync::{Arc, Mutex},
thread,
time::{Duration, Instant},
};
use std_semaphore::Semaphore;
pub mod interval;
pub type IntervalFn = dyn Fn(Option<&ThrottleLog>) -> Duration + Send + Sync + 'static;
/// Limiting resource access speed by ... | Rust | 0 |
pect("required argument");
let count = count
.parse::<usize>()
.map_err(|_| PastelError::CouldNotParseNumber(count.into()))?;
if count < 2 {
return Err(PastelError::GradientNumberMustBeLargerThanOne);
}
let mut print_spectrum = PrintSpectrum::Yes;
... | Rust | 0 |
from jar import Jar
import pytest
def test_init():
# 測試有效容量
jar = Jar(10)
assert jar.capacity == 10
assert jar.size == 0
# 測試預設容量
jar_default = Jar()
assert jar_default.capacity == 12
assert jar_default.size == 0
# 測試無效容量
with pytest.raises(ValueError):
Jar(-1) # 負數容量... | Python | 1 |
icon: "gs_emp.png".to_owned(),
});
// NOTE: There are things that depend on the order of this list, and this game must ALWAYS be the last one.
// Otherwise, stuff that uses this list will probably break.
// Arena
map.insert("arena", GameInfo {
display_name: "Arena".t... | Rust | 0 |
"""
===================
Stacked line charts
===================
"""
# sphinx_gallery_thumbnail_number = 2
###############################
# Read in tutorial data and show a summary
# ****************************************
#
# This gallery uses the scenario data from the first-steps tutorial.
#
# If you haven't clo... | Python | 1 |
import matplotlib
matplotlib.use('TKAgg')
import sys
import math
import random
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
J=1.0
nstep=10000
#input
if(len(sys.argv) != 3):
print ("Usage python ising.animation.py N T")
sys.exit()
lx=int(sys.argv[1])
ly=lx
kT... | Python | 1 |
pub use byteorder::{BE, LE};
pub use byteorder::NativeEndian as NE;
pub mod endian;
pub use endian::Endian;
pub mod order;
pub use order::Order;
pub mod traits;
pub use traits::ByteCast;
<filename>src/lib.rs<gh_stars>1-10
//! Abstractions for performing memory-mapped I/O.
//!
//! Memory-mapped I/O (MMIO) requires wo... | Rust | 0 |
/ 2).collect();
let late_validators: Vec<u64> =
(DEFAULT_VALIDATORS as u64 / 2..DEFAULT_VALIDATORS as u64).collect();
let mut scenario = TestBuilder::default()
.build()
.set_slot(early_slot)
.register_validators(&early_validators)
.set_slot(l... | Rust | 0 |
id IN (1, 2, 3)",
"SELECT * FROM x WHERE id IN (SELECT id FROM account)",
"SELECT * FROM x WHERE id NOT IN (1, 2, 3)",
"SELECT * FROM x INNER JOIN (SELECT n FROM z) b ON a.id = b.id",
"SELECT * FROM x WHERE y = z[?]",
"SELECT (foo(1)).y",
"SELECT proname, (SELECT regexp_s... | Rust | 0 |
xts = [
(c.get("label", "") or "") + " " + (c.get("description", "") or "")
for c in candidates
]
candidate_embs = self._model.encode(candidate_texts)
sims = [
(self._similarity_fn(to_numpy(sentence_emb), to_numpy(emb)), c)
... | Python | 1 |
IES OR CONDITIONS OF ANY KIND, either express or implied.
//! See the License for the specific language governing permissions and
//! limitations under the License.
pub mod gremlin;
pub use self::gremlin::*;
use std::sync::Arc;
use std::sync::mpsc::channel;
use grpcio::*;
use std::thread;
use std::time::Duration;
use... | Rust | 0 |
_click_rank = r
propensity_weights.append(pw)
return propensity_weights
def sampleClick(self, rank, last_click_rank, relevance_label):
if not relevance_label == int(relevance_label):
print('RELEVANCE LABEL MUST BE INTEGER!')
relevance_label = int(relevance_label) if relevance_label > 0 else 0
exam_p = s... | Python | 1 |
, G, H, I);
one_of!(OneOf10, A, B, C, D, E, F, G, H, I, J);
one_of!(OneOf11, A, B, C, D, E, F, G, H, I, J, K);
one_of!(OneOf12, A, B, C, D, E, F, G, H, I, J, K, L);
one_of!(OneOf13, A, B, C, D, E, F, G, H, I, J, K, L, M);
one_of!(OneOf14, A, B, C, D, E, F, G, H, I, J, K, L, M, N);
one_of!(OneOf15, A, B, C, D, E, F, G, ... | Rust | 0 |
class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
cur_sum = 0
n = len(nums)
for i in range(k):
cur_sum += nums[i]
max_avg = cur_sum / k
for i in range(k,n):
cur_sum += nums[i]
cur_sum -= nums[i-k]
... | Python | 1 |
https://webassembly.github.io/spec/core/binary/types.html#memory-types)
#[derive(Clone, Debug)]
pub struct MemType { pub lim: Limits }
/// [Table types](https://webassembly.github.io/spec/core/binary/types.html#table-types)
#[derive(Clone, Debug)]
pub struct TableType { pub et: RefType, pub lim: Limits }
/// [Global ... | Rust | 0 |
from openai import OpenAI
import os
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
def chat_in(input_text, system_prompt="You are a helpful assistant", model="gpt-4o-mini"):
try:
# Add chat messages
messages = []
if system_prompt:
messages.append({"role": "system... | Python | 1 |
# ------------------------------------------------------
# Convierte un número decimal positivo a binario usando un
# determinado número de bits.
# El binario resultante es un string e.g. "101"
# Se usa la función bin() que transforma e.g. 3 en "0b11".
# En esta función se quita el "0b" para dejar el "11"
# --------... | Python | 1 |
els[tp_rank].lm_head.dense.weight.data.copy_(lm_head_dense_weight)
models[tp_rank].lm_head.dense.bias.data.copy_(lm_head_dense_bias)
models[tp_rank].lm_head.norm.weight.data.copy_(lm_head_norm_weight)
if md.norm_has_bias:
models[tp_rank... | Python | 1 |
{
match uuid.iter().all(|i| *i == 0) {
true => None,
false => Some(Uuid::from_bytes(uuid)),
}
}
impl From<btrfsutil_sys::btrfs_util_subvolume_info> for SubvolumeInfo {
fn from(i: btrfsutil_sys::btrfs_util_subvolume_info) -> Self {
Self {
id: i.id,
parent_id:... | Rust | 0 |
'''
test cases for issue #8
check the calculation if:
1. edges are collinear
2. boxes are exactly the same
3. input in different scale level
'''
import torch
from oriented_iou_loss import cal_iou
device = torch.device('cuda:0')
box_0 = torch.tensor([.0, .0, 2., 2., .0], device=device)
def test_same_box():... | Python | 1 |
print("1. Encryption\n2. Decryption")
choice = int(input("Choose either (1 or 2): "))
if choice == 1:
print("Encryption\n")
print("Message can only be lower or upper case\n")
message = input("Enter Message: ")
shift = int(input("Enter key (0-25): "))
encryptedMessage = ""
for cha... | Python | 1 |
= hal::Keypad::new(pins.keypad, &mut pins.port);
let keypad_inputs = keypad.decompose();
let mut keypad_state = [false; hal::NEOPIXEL_COUNT];
let mut toggle_values = [false; hal::NEOPIXEL_COUNT];
loop {
for j in 0..(256 * 5) {
for (i, value) in color_values.iter_mut().enumerate() {... | Rust | 0 |
: Specifies if this handler should handle
only updates with :attr:`telegram.Update.my_chat_member`,
:attr:`telegram.Update.chat_member` or both.
pass_update_queue (:obj:`bool`): Determines whether ``update_queue`` will be
passed to the callback function.
pass_job_queu... | Python | 1 |
transmute(&mut back_buffer_ptr));
let mut render_target: Box<ID3D11RenderTargetView> = Box::new(mem::zeroed());
let mut render_target_ptr: *mut ID3D11RenderTargetView = Box::into_raw(render_target);
(*device).CreateRenderTargetView(back_buffer_ptr, null_mut(), mem::transmute(&mut re... | Rust | 0 |
sqrtを取りたい場合は、自分で計算してください
"""
return ((x1 - x2) ** 2) + ((y1 - y2) ** 2)
def manhattan_dis(x1: int, y1: int, x2: int, y2: int) -> int:
"""
マンハッタン距離を計算します
"""
return abs(x1 - x2) + abs(y1 - y2)
def manhattan_45turn(x: int, y: int) -> Tuple[int]:
"""
座標を45度回転します
回転すると、マンハッタン距... | Python | 1 |
44, 110], OperandSize::Qword)
}
fn vshuff32x4_6() {
run_test(&Instruction { mnemonic: Mnemonic::VSHUFF32x4, operand1: Some(Direct(ZMM29)), operand2: Some(Direct(ZMM4)), operand3: Some(IndirectScaledIndexed(RSI, RBX, Four, Some(OperandSize::Dword), None)), operand4: Some(Literal8(98)), lock: false, rounding_mode: ... | Rust | 0 |
#!/usr/bin/python
# Copyright 2020 Makani Technologies LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | Python | 1 |
#!/usr/bin/env python3
"""
Test script for TradePulse Unified Data Access System
Verifies that modules can access both API and uploaded data
"""
import sys
import os
import pandas as pd
import numpy as np
import logging
from pathlib import Path
# Add project root to path
project_root = Path(__file__).parent
sys.path.... | Python | 1 |
# PYTHON CALCULATOR
# Ask the user to enter an operator (+, -, /, *).
# Ask the user to enter the first number.
# Ask the user to enter the second number.
# Check the operator:
# If operator is +:
# Add the two numbers and print the result.
# If operator is -:
# Subtract the second number from the first and print the ... | Python | 1 |
unwrap();
}
//! Macro to generate completion-based async functions and blocks. This crate shouldn't be used
//! directly, instead use `completion`.
use proc_macro::TokenStream as TokenStream1;
use proc_macro2::{Group, Literal, Punct, Span, TokenStream, TokenTree};
use quote::{quote, quote_spanned, ToTokens, TokenStrea... | Rust | 0 |
rm, rngs::StdRng, Rng, SeedableRng};
use std::ops::{Index, IndexMut};
use rayon::prelude::*;
// A struct to contain the grid and the various metadata
// The grid is 2d, but it is stored as a 1d vec.
// Here are the rules: Each has a state n from 0..num_states
// If the number of its neighbours whose state is n+1
// is... | Rust | 0 |
import torch
import os
### rotate and flip
class Augment_RGB_torch:
def __init__(self):
pass
def transform0(self, torch_tensor):
return torch_tensor
def transform1(self, torch_tensor):
torch_tensor = torch.rot90(torch_tensor, k=1, dims=[-1,-2])
return torch_tensor
def... | Python | 1 |
/// A size parameter was incorrectly specified, either number or on the form 10M
ER_WRONG_SIZE_NUMBER = 1531,
/// The size number was correct but we don't allow the digit part to be more than 2 billion
ER_SIZE_OVERFLOW_ERROR = 1532,
/// Failed to alter: %s
ER_ALTER_FILEGROUP_FAILED = 1533,
... | Rust | 0 |
nd.month(), nd.day()).and_hms(0, 0, 0);
return Ok(dt);
}
if let Ok(nd) = NaiveDate::parse_from_str(ts, "%Y-%m-%d") {
let dt = tz.ymd(nd.year(), nd.month(), nd.day()).and_hms(0, 0, 0);
return Ok(dt);
}
if let Ok(nt) = NaiveTime::parse_from_str(ts, "%H:%M:%S") {
let dt = t... | Rust | 0 |
0);
}
#[test]
fn test_neg_complex_integer() {
let num1 = parse_var("-90-11i");
let num2 = parse_var("90-11i");
assert!(num1.get_real() == -90.0);
assert!(num1.get_imag() == -11.0);
assert!(num2.get_real() == 90.0);
assert!(num2.get_imag() == -11.0);
}
... | Rust | 0 |
ed = true;
} else {
return Err(MapToError::FrameAllocationFailed);
}
} else {
created = false;
}
if entry.flags().contains(Flags::HUGE_PAGE) {
return Err(MapToError::ParentEntryHugePage);
... | Rust | 0 |
}
}
#[derive(StructOpt, Debug)]
#[structopt(rename_all = "kebab-case")]
pub struct Opt {
/// A path to directory with all schema files
#[structopt(parse(from_os_str), short = "i", long = "input-dir")]
input_dir: PathBuf,
/// A path to directory to output generate data contract files to
#[structo... | Rust | 0 |
from opcodes import AND, SDIV, MUL, EQ, ISZERO, OR, SLT
from rule import Rule
from util import BVSignedUpCast, BVSignedMin, BVSignedCleanupFunction
from z3 import BVMulNoOverflow, BVMulNoUnderflow, BitVec, Not, Or
"""
Overflow checked signed integer multiplication.
"""
# Approximation with 16-bit base types.
n_bits =... | Python | 1 |
t_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
REGION... | Rust | 0 |
*
* Input: boxes = [1,3,2,2,2,3,4,3,1]
* Output: 23
* Explanation:
* [1, 3, 2, 2, 2, 3, 4, 3, 1]
* ----> [1, 3, 3, 4, 3, 1] (3*3=9 points)
* ----> [1, 3, 3, 3, 1] (1*1=1 points)
* ----> [1, 1] (3*3=9 points)
* ----> [] (2*2=4 points)
*
* Example 2:
*
* Input: boxes = [1,1,1]
* Output: 9
*
* Example 3:
... | Rust | 0 |
// }
// }
// see https://wiki.parity.io/Extrinsic
pub fn transfer(from: &str, to: &str, amount: U256, index: U256, genesis_hash: Hash) -> UncheckedExtrinsic {
let signer = Sr25519::pair_from_suri(from, Some(""));
let to = sr25519::Public::from_string(to).ok().or_else(||
sr25519::Pair::from_string(to, Some("... | Rust | 0 |
n as e:
raise HTTPException(
status_code=500, detail=f"Error during enhancement: {str(e)}"
)
@router.get("/images/{imageId}")
def upscale_image(imageId: str):
fileImageBasePath = getImagesBasePath()
imageFilePath = os.path.join(fileImageBasePath, imageId)
return FileResponse(im... | Python | 1 |
number_obstacles=max_num_obstacles,
limits=panda_limits,
)
planner.concretize()
return planner
@hydra.main(
version_base=None, config_path=".", config_name="config_panda"
)
def test(cfg: ExampleConfig):
cfg.isaacgym.viewer = True
sim = IsaacGymWrapper(
cfg.isaacgym,
c... | Python | 1 |
, Seven, Eight, Nine or Ten",
_ => "Dunno",
};
println!("{}", s); // Five
let t = (5, 3, "Hello");
match t {
(1, 3, "Hello") => println!("one, tree and hi"),
(5, _, "Boo") => println!("five, whatevs and boo"),
(_, _, "Hello") => println!("whatevs, whatevs and hi"),
... | Rust | 0 |
f.cfg['last_observe']:, 2:4] # 2nd and 3rd columes as traj label
# predict_list = []
result, label = dict(), dict()
for i in range(batch_size):
polyline_feature = self.traj_subgraphnet(trajectory_batch[i, :self.cfg['last_observe']]).unsqueeze(0)
# print(polyline_feature... | Python | 1 |
import math
import torch
from toma import toma
from tqdm.auto import tqdm
def compute_conditional_entropy(log_probs_N_K_C: torch.Tensor) -> torch.Tensor:
N, K, C = log_probs_N_K_C.shape
entropies_N = torch.empty(N, dtype=torch.double)
pbar = tqdm(total=N, desc="Conditional Entropy", leave=False)
@... | Python | 1 |
ault=128, type=int,
help='Per-replica batch size')
parser.add_argument('-e', '--epochs', default=10, type=int,
help='Number of epochs')
return parser.parse_args()
if __name__ == '__main__':
args = parse_args()
print('arguments:', args)
batch_size =... | Python | 1 |
#!/usr/bin/env python3
"""
Simple test script for the momo_tokenizer Python bindings
"""
import time
from tokenizer import Tokenizer
def main():
print("=== MoMo Tokenizer Test ===\n")
# Create tokenizer
print("Creating tokenizer...")
tokenizer = Tokenizer()
# Load the gpt-oss-120b tokenizer
... | Python | 1 |
import RPi.GPIO as GPIO
import time
def sweep_servo():
# Set up GPIO
servo_pin = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(servo_pin, GPIO.OUT)
# Set PWM frequency to 50Hz for servos
pwm = GPIO.PWM(servo_pin, 50)
pwm.start(0)
def set_angle(angle):
duty = angle / 18 + 2.5
pw... | Python | 1 |
= keras.layers.Dense(1, kernel_initializer='zeros')(x1)
model = keras.Model(inputs, outputs)
model.add_metric(
math_ops.reduce_mean(x1), name='mid_mean', aggregation='mean')
return model
x = np.ones((64, 10)).astype('float32')
y = np.ones((64, 1)).astype('float32')
model = _mak... | Python | 1 |
@github_agent.tool
async def get_repo_structure(ctx: RunContext[GitHubDeps], github_url: str) -> str:
"""Get the directory structure of a GitHub repository.
Args:
ctx: The context.
github_url: The GitHub repository URL.
Returns:
str: Directory structure as a formatted string.
"... | Python | 1 |
new_names.items():
ex = [x[0] for x in examples[name]]
out = []
for e in ex:
processed = self.nlp(unicode(str(e)))
raw_indexes = [(processed[i].text, processed[i].idx, exp['prediction']) for i in idxs]
out.appen... | Python | 1 |
ata source uploading a "<data>" file
And I wait until the source is ready less than <time_1> secs
And I create a dataset
And I wait until the dataset is ready less than <time_2> secs
And I create a deepnet
And I wait until the deepnet is ready less than <time_... | Python | 1 |
.analyze(&data, &mut writer);
}
<gh_stars>1-10
use bevy::prelude::*;
use bevy_kira_audio::Audio;
use crate::{
components::{AttackType, Enemy, Health, Player},
enemy,
events::Damage,
events::{EnemyAttackTime, PlayerDefendAction},
Icons,
game_state::GameState,
loading::Sounds,
};
use std::time... | Rust | 0 |
v", "dev");
//! current = envs.current()?;
//! assert_eq!(current.name(), "Development");
//! assert_eq!(current.key(), &None);
//! # Ok(())
//! # }
//! ```
//!
//! # Custom Environment Hierarchy
//! If you wish to forego using the `Environment` hierarchy supplied by this
//! library, implement a custom hierarchy ins... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
Recurrence and Sum Functions
A recurrence relation is an equation that recursively defines a sequence or multidimensional array of values, once one or more initial terms are given; each further term of the sequence or array is defined as a function of the preceding terms.
"""
from sympy.f... | Python | 1 |
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. 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 requir... | Python | 1 |
remove (or do nothing) the given direction to the set.
pub fn set(&mut self, key: Cardinal, value: bool) {
let i = key.index() as u8;
let mask = 1u8 << i;
if value {
self.byte |= mask;
} else {
self.byte &= !mask;
}
}
/// Returns `true` if the given direction is in the set.
... | Rust | 0 |
", attr)
}
pub fn set_attribute(&self, attr: &str, value: &str) -> Result<()> {
set_dir_val(&self.path, "attrib", attr, value)
}
pub fn param(&self, attr: &str) -> Result<String> {
get_dir_val(&self.path, "param", attr)
}
pub fn set_param(&self, attr: &str, value: &str) -> Resul... | Rust | 0 |
# type: ignore
import torch
from transformers import GroundingDinoConfig
from transformers.models.grounding_dino.modeling_grounding_dino import GroundingDinoEncoderLayer
from jurassic_open_world.modeling.model.encoder.cross_scale.encoder_layer import CrossScaleEncoderLayer
from ....utils.convert_huggingface import c... | Python | 1 |
from dataclasses import dataclass
from enum import Enum, auto
class KeyEventType(Enum):
"""Enum describing keyboard input event types.
The enum integer values are arbitrary and may change in the future.
"""
PRESS = auto()
"""A key was pressed"""
AUTO_REPEAT = auto()
"""A key was automat... | Python | 1 |
import streamlit as st
import matplotlib.pyplot as plt
import pandas as pd
st.title("Empleatronix")
st.write("Todos los datos sobre los empleados en una aplicación.")
# Leemos y mostramos los datos
employees = pd.read_csv('employees.csv')
st.dataframe(employees)
# Creamos los botones de elección
color, name_election... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.