text string | label_name string | labels int64 |
|---|---|---|
y 1 return at the end - just pop it
insts.pop(-1)
elif len(returns) > 0:
# create jump target - if the last inst is a return,
# we can replace it with a NOP and make that the jump target.
if insts[-1] is returns[-1]:
insts[-1].opname = "NOP"
... | Python | 1 |
from django.urls import path
from .views import (
ForecastListCreateAPIView,
ForecastRetrieveUpdateDestroyAPIView,
ForecastByLocationAPIView
)
urlpatterns = [
path('forecasts/', ForecastListCreateAPIView.as_view(), name='forecasts-list-create'),
path('forecasts/<int:id>/', ForecastRetrieveUpdateDes... | Python | 1 |
trix
the sparse matrix to write
hb_info : HBInfo
contains the meta-data for write
Returns
-------
None
Notes
-----
At the moment not the full Harwell-Boeing format is supported. Supported
features are:
- assembled, non-symmetric, real matrices
- integer... | Python | 1 |
});
let err = unsafe {
ffi::uc_hook_add(
self.inner().uc,
&mut hook_ptr,
HookType::INTR,
ffi::intr_hook_proxy::<D, F> as _,
user_data.as_mut() as *mut _ as _,
0,
0,
)... | Rust | 0 |
!(
decrement_state_by_const_filter,
filter,
DecrementStateByConstFilter,
("0xabababab~u32", 0xabab_abab),
("0xbabababa~u32", Value::U32(0xbaba_baba))
);
impl_tests_for_item_arg1!(
decrement_state_by_value_filter,
filter,
DecrementStateByValueFilter... | Rust | 0 |
# Copyright (c) 2025, Al-Aswany and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class EmployeeProject(Document):
pass
| Python | 1 |
{
OpType::Put => {
memtable.put(kv.key, kv.value.unwrap(), file_num);
}
OpType::Del => {
memtable.delete(kv.key.as_slice());
}
}
}
... | Rust | 0 |
ict(type='ResizeCropFlipImage', data_aug_conf = ida_aug_conf, training=False),
dict(type='NormalizeMultiviewImage', **img_norm_cfg),
dict(type='LoadPointsFromFile',load_dim=5,coord_type='LIDAR'),
dict(type='LoadAnnotations3D', with_bbox_3d=False, with_label_3d=False, with_attr_label=False,with_seg_3d=True),... | Python | 1 |
"*Required features: `\"Win32_UI_Controls\"`*"]
pub const PROP_SM_CYDLG: u32 = 188u32;
#[doc = "*Required features: `\"Win32_UI_Controls\"`*"]
pub const PSBTN_APPLYNOW: u32 = 4u32;
#[doc = "*Required features: `\"Win32_UI_Controls\"`*"]
pub const PSBTN_BACK: u32 = 0u32;
#[doc = "*Required features: `\"Win32_UI_Control... | Rust | 0 |
)
}
pub fn transit(abilities: Vec<Abilities>, hints: Vec<Hints>) -> PeerMessage {
PeerMessage::Transit(TransitType {
abilities_v1: abilities,
hints_v1: hints,
})
}
pub fn direct_type(priority: f32, hostname: &str, port: u16) -> DirectType {
DirectType {
priority,
hostname: ... | Rust | 0 |
ut file path, only works
# for local path since no standard way for remote url
file_is_modified = False # initialize with a default value
if (
vector_storage_instance.status().vector_count != 0
and not self.is_url
)... | Python | 1 |
reg_class(RC::GR64) .named("lhs").into(), (reg_class(RC::GR64) | any_i32_imm()).named("rhs").into()]);
let sub8 = ir(IROpcode::Sub).named("bin").ty(Type::i8) .args(vec![(any_i8_imm() | reg_class(RC::GR8)) .named("lhs").into(), (reg_class(RC::GR8) | any_i8_imm()) .named("rhs").into()]);
let sub... | Rust | 0 |
age": f"代理内存使用率平均 {avg}%,接近上限",
"recommendation": "监控内存使用,考虑增加代理内存资源"
})
# Response time alert
elif measurement == "PolarProxy_AvgResponseTime":
if avg > 200:
alerts.append({
"level": "warning",
... | Python | 1 |
e provided filename before the extension.
:param str filename: filename to use as template
:param int nbFrames: Number of frames to generate
"""
plot3d = self.getPlot3DWidget()
assert plot3d is not None
# Define filename template
nbDigits = int(numpy.log10(nbFra... | Python | 1 |
// #region mstoken-real-sinppest
from f2.apps.tiktok.utils import TokenManager
if __name__ == "__main__":
print("tiktok real msToken:", TokenManager.gen_real_msToken())
// #endregion mstoken-real-sinppest
// #region mstoken-false-sinppest
from f2.apps.tiktok.utils import TokenManager
if __name__ == "__main__":... | Python | 1 |
AST, AString> {
match &self.task_val {
AST::Subscript(x) => {
let rw = x.read();
Ok(rw.a().clone())
}
_ => Err("Task val must be a subscript".into()),
}
}
fn get_right_of_task_val(&self) -> Result<AString, AString> {
mat... | Rust | 0 |
if state_root != *node.state_root() {
warn!(
target: LOG_TARGET,
"Calculated state root did not match the state root provided by the leader: Expected: {:?} Leader \
provided:{:?}",
state_root,
node.state_root()
... | Rust | 0 |
fn as_slice_unsafe(&self) -> &[u8] {
slice::from_raw_parts(self.buf.as_ptr(), self.buf_len as usize)
}
/// Gets the buffer from this message as slice, with the corrent length.
#[inline]
pub fn as_slice<SHM: ShMem>(&self, map: &mut LlmpSharedMap<SHM>) -> Result<&[u8], Error> {
unsafe {
... | Rust | 0 |
r) -> ::std::fmt::Result {
f.debug_struct(&format!("GActionMapInterface @ {:?}", self as *const _))
.field("g_iface", &self.g_iface)
.field("lookup_action", &self.lookup_action)
.field("add_action", &self.add_action)
.field("remove_action", &self.remove_action)
.fini... | Rust | 0 |
[serde(rename = "totalMessages")]
pub total_messages: u64,
pub chatters: Cow<'a, [ChatterStats<'a>]>,
pub hashtags: Cow<'a, [HashtagStats<'a>]>,
pub commands: Cow<'a, [CommandStats<'a>]>,
#[serde(rename = "bttvEmotes")]
pub bttv_emotes: Cow<'a, [EmoteStats<'a>]>,
#[serde(rename = "ffzEmotes"... | Rust | 0 |
`Aberration<&mut M, &mut F>`
///
/// # Examples
///
/// ```
/// # use outcome::prelude::*;
/// fn mutate(x: &mut Aberration<u32, i32>) {
/// match x.as_mut() {
/// Aberration::Mistake(m) => *m = 42,
/// Aberration::Failure(f) => *f = 47,
/// }
/// }
///
/// let mut x: Aberration<u... | Rust | 0 |
@parameterized.expand([(True,), (False,)])
def test_tae_roundtrip(self, enable_tiling):
model = self.get_sd_vae_model()
if enable_tiling:
model.enable_tiling()
image = -torch.ones(1, 3, 1024, 1024, device=torch_device)
image[..., 256:768, 256:768] = 1.0
with torch.no_grad():
sample =... | Python | 1 |
#!/usr/bin/env python3
"""
작업 종료 자동화 스크립트
집/학원에서 작업을 완료할 때 실행
"""
import subprocess
import sys
from datetime import datetime
from pathlib import Path
def run_command(cmd, description):
"""명령어 실행 및 결과 출력"""
print(f"[{description}] 실행 중...")
try:
result = subprocess.run(cmd, shell=True, capture_outp... | Python | 1 |
/// Ok(Date::from_ymd(2019, 1, 2))
/// );
/// ```
#[inline(always)]
pub fn parse_language(s: &str, format: &str, language: Language) -> ParseResult<Self> {
Self::try_from_parsed_items(parse(s, format, language)?)
}
/// Given the items already parsed, attempt to create a `Date`.
... | Rust | 0 |
"))
print(f"🔍 Starting memory watcher for {project_root}")
event_handler = MemoryCapture(project_root)
observer = Observer()
observer.schedule(event_handler, project_root, recursive=True)
print(f"🔍 Watching {project_root} for significant changes...")
observer.start()
try:
while... | Python | 1 |
re
I: Iterator<Item = T> + ExactSizeIterator,
{
let iter = iter.into_iter();
let len = iter.len();
if len <= INLINE_LEN {
let mut this = Self::uninit_inline_storage();
let inline_storage = unsafe { this.storage.inline_storage.deref_mut() };
ite... | Rust | 0 |
fn from_bytes(bytes: &[u8]) -> Result<Vec<u32>, Error> {
if !bytes.is_empty() && *bytes.last().unwrap() & 128 != 0 {
return Err(Error::IncompleteNumber);
}
let mut result = Vec::new();
let mut value: u32 = 0;
for &byte in bytes {
let checked_value = value.checked_mul(128).ok_or(Erro... | Rust | 0 |
#!/usr/bin/env python
import subprocess
import glob
import os
import sys
default_simulators = ['MOCK', 'NEST', 'NEURON', 'Brian2']
simulator_names = sys.argv[1:]
if len(simulator_names) > 0:
for name in simulator_names:
if name not in default_simulators:
print("Simulator must be one of: " + ",... | Python | 1 |
let bytes = replace(&mut self.buffered, None);
Ok(Async::Ready(bytes.map(|bytes| bytes.freeze().into())))
}
}
}
Err(e) => Err(EitherError::A(e)),
}
}
}
//! <https://www.codewars.com/kata/588a3c3ef0fbc9c8e1000095/tra... | Rust | 0 |
import os
import pytest
from test_utils import run_query, redshift_connector
here = os.path.dirname(__file__)
def test_s2_fromlonglat_success():
results = run_query(
"""WITH resContext AS(
SELECT 0 AS res, -150 AS long, 60 AS lat UNION ALL
SELECT 1, -150, 60 UNION ALL
... | Python | 1 |
(
math.sin(stick_rad - 3 * math.pi / 4)
* duty_max
* math.sqrt(LS_X**2 + LS_Y**2)
)
v3 = (
math.sin(stick_rad - 5 * math.pi / 4)
* duty_max
* math.sqrt(LS_X**2 + LS_Y**2)
)
v4... | Python | 1 |
w,
lmul,
avl,
);
for i in 0..avl as usize {
let range = i * sew_bytes..(i + 1) * sew_bytes;
let left = &lhs[range.clone()];
let right = &rhs[range.clone()];
let res = &result[range.clone()];
let exp = &expected[range.clone()];
if res != exp {
... | Rust | 0 |
BlockChallengeResponse>(
"BlockChallengeResponse",
fields,
file_descriptor_proto()
)
})
}
}
fn default_instance() -> &'static BlockChallengeResponse {
static mut instance: ::protobuf::lazy::Lazy<BlockChallen... | Rust | 0 |
a=int(input("enter the number for vote"))
if a>=18:
print("the man is vote")
else:
print("the man is note vote")
| Python | 1 |
# https://leetcode.com/problems/product-of-array-except-self/
from typing import List
class Solution:
def productExceptSelf1(self, nums: List[int]) -> List[int]:
"""
[Complexity]
- TC: O(n)
- SC: O(n)
[Approach]
division operation 없이 각 원소마다 자기 자신을 제외한 모... | Python | 1 |
"::",
stringify!(d_val)
)
);
assert_eq!(
unsafe { &(*(0 as *const dynamic__bindgen_ty_1)).d_ptr as *const _ as usize },
0usize,
concat!(
"Alignment of field: ",
stringify!(dynamic__bindgen_ty_1),
"::",
stringify!(d_pt... | Rust | 0 |
.union(&other.tombstones).cloned().collect();
}
}
impl<T: Hash + Eq + Clone> ObserveRemoveSet<T> {
pub fn new() -> ObserveRemoveSet<T> {
ObserveRemoveSet {
members: HashMap::new(),
tombstones: HashSet::new(),
}
}
pub fn value(&self) -> HashSet<T> {
self.... | Rust | 0 |
ll(),
mint::Point2 {
x: MARGIN.0 + POSITION_SIZE.0 * *i as f32 + POSITION_SIZE.0 / 2.0,
y: MARGIN.1 + POSITION_SIZE.1 * *j as f32 + POSITION_SIZE.1 / 2.0,
},
6.0,
6.0,
Color::BLACK,
)
.unwrap();
}
}
pub fn a... | Rust | 0 |
self.batchsize]
yield np.array([inputs[idx:idx + 2 * self.offset + 1] for idx in excerpt]),\
targets[excerpt + self.offset].reshape(-1, 1)
class DoubleSourceProvider3(object):
def __init__(self, nofWindows, offset):
self.nofWindows = nofWindows
self.offset = offset... | Python | 1 |
ut is a string containing several web information. This function will call a web search engine to return the search results. This tool is especially useful when answering knowledge-based questions."""
assistant_prefix = f"""<think>\nOkay, to answer the user's question, I will answer user's problem by deep reas... | Python | 1 |
entity_maps.joints.remove(entity);
}
}
}
extern crate fix;
extern crate nom;
use fix::frame;
use nom::IResult;
#[test]
fn begin_string_parsing_42_should_succeed() {
let res = frame::begin_string( b"FIX.4.2\x01" );
assert_eq!(res, IResult::Done( &b"\x01"[..], "FIX.4.2") );
}
#[test]... | Rust | 0 |
data.to_vec(),
Err(_) => {
*response.status_mut() = StatusCode::BAD_REQUEST;
return Ok(response);
}
};
let path = parts.uri.path();
*response.body_mut() = Body::from(
match path {
"/log" => basic::read_log(data),
"/log/remove" => bas... | Rust | 0 |
from rest_framework import generics
from .models import Post
from .serializers import PostSerializers
class PostListCreateView(generics.ListCreateAPIView):
queryset = Post.objects.all()
serializer_class = PostSerializers
class PostDetailRetrieveDestroyAPIView(generics.RetrieveDestroyAPIView):
queryset = P... | Python | 1 |
_type,
port,
destination: Destination::Ipv4Addr(address)
});
}
if address_type == 0x03 /* Domain Name */ {
let name_length = data[4] as usize;
let name = std::str::from_utf8(&data[5..(5 + name_length)])?.to_owned();
let por... | Rust | 0 |
def input_reader(path: str = "input"):
with open(path, "r", encoding="utf-8") as reader:
return [list(map(int,list(l))) for l in reader.read().rstrip().split("\n")]
topo = input_reader()
# topo = input_reader("test")
offsets = (
(0,1),(0,-1),(1,0),(-1,0)
)
def count_trailheads(x,y,start, table) -> in... | Python | 1 |
_triangle_inequality([1, 2, 3], "abc")
# Different lengths
with pytest.raises(ValueError):
seminorm.check_triangle_inequality([1, 2, 3], [1, 2, 3, 4])
@pytest.mark.unit
def test_unsupported_input_type():
"""Test that compute raises TypeError for unsupported input types."""
seminorm = PartialS... | Python | 1 |
Rule(rule, Some(c)) => {
write!(f, "Failed to match builtin rule [{}]: found character [{}]", rule, c)
}
PegErrorContent::FailedToMatchBuiltinRule(rule, None) => {
write!(f, "Failed to match biultin rule [{}]: reached end of input",... | Rust | 0 |
:{loop_map.keys()}"
raise ValueError(e)
if kernel is None:
if Application.initialized():
kernel = getattr(Application.instance(), "kernel", None)
if kernel is None:
msg = (
"You didn't specify a kernel,"
" and no IPython Application wit... | Python | 1 |
_test]
fn cargo_compile_with_nested_deps_longhand() {
let p = project()
.file(
"Cargo.toml",
r#"
[project]
name = "foo"
version = "0.5.0"
authors = ["<EMAIL>"]
[dependencies.bar]
path = ... | Rust | 0 |
Error>> {
let adapters = bluetooth_utils::get_adapters()?;
for adapter in adapters {
if adapter == object_path {
return Ok(BluetoothAdapter::new(adapter.clone()));
}
}
Err(Box::from("Bluetooth adapter not found"))
}
pub fn get_id(&self) -... | Rust | 0 |
disable_pbar, seed=seed)
samples = samples.to(ldm_patched.modules.model_management.intermediate_device())
cleanup_additional_models(models)
cleanup_additional_models(set(get_models_from_cond(positive_copy, "control") + get_models_from_cond(negative_copy, "control")))
return samples
def sample_custom(m... | Python | 1 |
'a $res> for $res {
type Output = $res;
#[inline]
fn $method(self, other: &$res) -> $res {
(&self).$method(other)
}
}
};
}
macro_rules! forward_all_binop {
(impl $imp:ident for $res:ty, $method:ident) => {
forward_val_val_binop!(i... | Rust | 0 |
mask_ratio * mask_ratio
mask_len = (seq_len * mask_ratio).floor()
# do not mask more than amount previously masked
mask_len = torch.min(unknown_map.sum(dim=-1, keepdim=True) - 1, mask_len)
# mask at least one
mask_len = torch.max(torch.tensor([1], device=mode... | Python | 1 |
Err(Err(NotFound("File or directory not found")))
}
}
}
}
#[get("/")]
pub fn index() -> Result<Html<String>, Result<NamedFile, NotFound<&'static str>>> {
let root_dir = PathBuf::from("./");
render_from_path(root_dir)
}
#[get("/<relative_path>")]
pub fn filez(relative_path: &RawStr) ->... | Rust | 0 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class PosConfig(models.Model):
_inherit = 'pos.config'
epson_printer_ip = fields.Char(string='Epson Printer IP', help="Local IP address of an Epson receipt printer.")
@... | Python | 1 |
from _videocore6.v3d import (
# Core registers and fields
CORE_IDENT0,
CORE_IDENT0_VER,
CORE_IDENT1,
CORE_IDENT1_NSEM,
CORE_IDENT1_NSLC,
CORE_IDENT1_NTMU,
CORE_IDENT1_QUPS,
CORE_IDENT1_REV,
CORE_IDENT1_VPM_SIZE,
CORE_IDENT2,
CORE_IDENT2_BCG,
CORE_L2CACTL,
CORE_L2C... | Python | 1 |
from selenium import webdriver
import time
class RadioButtonsAndCheckboxes():
def test(self):
baseUrl = "https://letskodeit.teachable.com/pages/practice"
driver = webdriver.Firefox()
driver.maximize_window()
driver.get(baseUrl)
driver.implicitly_wait(10)
bmwRadioBt... | Python | 1 |
和召回率
precision = tp / (tp + fp + 1e-10)
recall = tp / (tp + fn + 1e-10)
# 计算F1分数
f1 = 2 * precision * recall / (precision + recall + 1e-10)
return f1
################################################
# 5. 预测函数
################################################
def detect_r_peaks(ecg_signal,... | Python | 1 |
msg: msg.to_string(),
}
.into()
}
pub fn func_invalid_sig(env: &FuncEnv, func_name: &str) -> RuntimeFailure {
RuntimeError::FuncInvalidSignature {
target: env.target_addr().clone(),
template: env.template_addr().clone(),
func: func_name.to... | Rust | 0 |
example_rng(7348172934612063328);
simulator.tick(
world.tick_time_interval(),
world.properties().updates_per_tick as usize,
&mut Some(&mut rng),
&mut None,
);
assert_eq!(
simulator.unit().position(),
Vec2::new(13.5, 1.333333333333341)
);
}
#[test]
fn tes... | Rust | 0 |
#!/usr/bin/env python
# coding:utf-8
import struct
import socket
import sys
MEMCACHED_REQUEST_MAGIC = "\x80"
OPCODE_PREPEND_Q = "\x1a"
key_len = struct.pack("!H", 0xfa)
extra_len = "\x00"
data_type = "\x00"
vbucket = "\x00\x00"
body_len = struct.pack("!I", 0)
opaque = struct.pack("!I", 0)
CAS = struct.pack("!Q", 0)
bo... | Python | 1 |
raph.nodes:
if node.op == "placeholder":
if version.parse(torch.__version__) < version.parse("1.11.0"):
base_mod_env[node.name] = base_mod_graph.placeholder(node.name, type_expr=node.type)
else:
default_value = node.args[0] if len(node.args) > 0 else inspe... | Python | 1 |
&mut self, bytes : &'a [u8]) {
match &mut self.port {
&mut None => (),
&mut Some(ref mut s) => {
match s.reconfigure(&|settings| {
match settings.set_baud_rate(serial::Baud9600) { Err(e) => {return Err(e);}, _ => () }
settings.set_c... | Rust | 0 |
# Copyright 2010 Gregory Szorc
#
# 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 w... | Python | 1 |
: {}", raw.len(), length),
});
}
Ok(raw)
}
fn check_key(key_hex: &str, length: usize) -> Result<(), String> {
let r = decode_hex_with_length_check(key_hex, length);
if r.is_ok() {
return Ok(());
} else {
return Err(r.unwrap_err().to_string());
}
}
pub fn check_secret_... | Rust | 0 |
from event_log import Event_log
from db_access import database_conn
from notification import Notification
import re
class Validation:
def __init__(self):
self.notify = Notification()
def validation_rls_field(self, ti):
# 3.驗證欄位正確性及rule是否達標
# 3-1. verify rls field
# 3-2. sys_l... | Python | 1 |
83,
MedivacSpeedBoost = 89,
Purify = 97,
OracleWeapon = 99,
ImmortalOverload = 102,
Lockon = 116,
SeekerMissile = 120,
TemporalField = 121,
VoidRaySwarmDamageBoost = 122,
OracleStasisTrapTarget = 129,
ParasiticBomb = 132,
ParasiticBombUnitKu = 133,
ParasiticBombSecondaryU... | Rust | 0 |
{
let game = GameState::new();
let tiles = game.tiles();
for tile in tiles {
match tile.tile {
Tile::Empty | Tile::Base(_) => {}
Tile::Alive(_) => panic!("Alive tile on new board"),
Tile::Squashed(_) => panic!("Squashed tile on new bo... | Rust | 0 |
"""
Author: Radek Danecek
Copyright (c) 2022, Radek Danecek
All rights reserved.
# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
# holder of all proprietary rights on this computer program.
# Using this computer program means that you agree to the terms
# in the LICENSE file included with thi... | Python | 1 |
physical_device_properties(pdevice);
/*let properties = PhysicalDeviceProperties {
api_version: properties.api_version,
driver_version: properties.driver_version,
vendor_id: properties.vendor_id,
device_id: properties.device... | Rust | 0 |
model_name=model_name,
local_model_store_dir_path=root)
return net
def shufflenetv2b_wd2(**kwargs):
"""
ShuffleNetV2(b) 0.5x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'
https://arxiv.org/abs/1807.11164.
Parameters:
----------
... | Python | 1 |
ways)]
pub fn set_dynamic(&mut self, sci: DynamicSCI) {
self.dynamics = sci;
}
#[inline(always)]
pub fn set_pipeline_cache(&mut self, cache: vk::PipelineCache) {
self.cache = Some(cache);
}
}
impl VkObjectDiscardable for vk::Pipeline {
fn discard_by(self, device: &VkDevice) {
... | Rust | 0 |
oblib_object_from_bytes(scaler_bytes)
if scaler_bytes
else None
)
self._scaler_cache[scaler_key] = scaler
final_results.append(
FullCellData (
i_cell=i_cell,
pair_id=pair_id,
... | Python | 1 |
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import re
import sys
import json
import datetime
import shutil
import subprocess
import time
import signal
import zipfile
from multiprocessing import Process, Queue
from functools import wraps
from threading import Timer
import platform
from . imp... | Python | 1 |
value, inclusive }| {
Bound::new(value.to_bigint().expect("infallible"), inclusive)
});
Range::<BigInt>::new(min, max)
}
pub fn u64_range_to_big_int_range(range: &Range<u64>) -> Range<BigInt> {
let min = range.get_min().map(|Bound { value, inclusive }| {
Bound::new(value.to_bigint().expec... | Rust | 0 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(ver... | Python | 1 |
# Copyright 2023 Flavien Solt, ETH Zurich.
# Licensed under the General Public License, Version 3.0, see LICENSE for details.
# SPDX-License-Identifier: GPL-3.0-only
# This is a function to capture the output of a process in real time and to apply a timeout without losing this output.
# It was initially designed for R... | Python | 1 |
unwrap().clients.contains_key(&CLIENT_ADDR), true);
let msg = fake_device
.next_mlme_msg::<fidl_mlme::AuthenticateIndication>()
.expect("expected MLME message");
assert_eq!(
msg,
fidl_mlme::AuthenticateIndication {
peer_sta_address: CLIENT... | Rust | 0 |
"""
Configuration manager should manager the configuration of the hub system, that include the intergration.
"""
from typing import Dict, List
from integration_hub.connection._hub_connection import HubConnection
from integration_hub.connection import HubConnectionFactory
class HubConnectionManager:
def __new__(... | Python | 1 |
g" approach, clone <https://github.com/emilk/egui_template> and get started using egui right away.
//!
//! ### A simple example
//!
//! Here is a simple counter that can be incremented and decremented using two buttons:
//! ```
//! fn ui_counter(ui: &mut egui::Ui, counter: &mut i32) {
//! // Put the buttons and lab... | Rust | 0 |
anything */ }`."]
pure fn times(&self, it: fn() -> bool) {
if *self < 0 {
fail fmt!("The .times method expects a nonnegative number, \
but found %?", self);
}
let mut i = *self;
while i > 0 {
if !it() { break }
i -= 1;
... | Rust | 0 |
, 10_f64),
("UMA/USDT", 0.1_f64),
("UNI/USDT", 0.1_f64),
("VET/USDT", 1_f64),
("WAVES/USDT", 0.1_f64),
("WAXP/USDT", 10_f64),
("XCH/USDT", 0.01_f64),
("XEC/USDT", 10000_f64),
("XEM/USDT", 1_f64),
("XLM/USDT", 10_... | Rust | 0 |
class WordDistance:
# to-do : check
'''
1. Shortest distance between 2 string from array
2. dis = i, j --> abs(i-j)
3. two pointer
["WordDistance", "shortest", "shortest"]
[[["practice", "makes", "perfect", "coding", "makes"]], ["coding", "practice"], ["makes", "coding"]]
output - [null... | Python | 1 |
ified version of the total size in bytes.
size: Quoted<u64>,
},
}
#[derive(Debug)]
struct Quoted<D>(pub D);
impl<D: fmt::Display> serde::Serialize for Quoted<D> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.collect_s... | Rust | 0 |
print(f" ✓ 已清理 {dir_name}")
def clean_python_cache():
"""清理Python缓存文件"""
print("🧹 清理Python缓存文件...")
# 清理所有 .pyc 文件
pyc_files = glob.glob("**/*.pyc", recursive=True)
for pyc_file in pyc_files:
try:
os.remove(pyc_file)
print(f" ✓ 已删除 {pyc_file}")
e... | Python | 1 |
# Now perform all_gather with correctly sized tensors
dist.all_gather(output, v, group=group)
for i, t in enumerate(output):
gathered_dicts[i][k] = t
else:
# Use all_gather_object for non-tensor values
object_list = [None for _ in range(worl... | Python | 1 |
t(interp: &mut Artichoke) -> InitializeResult<()> {
let spec = crate::class::Spec::new("Prime", None, None)?;
interp.0.borrow_mut().def_class::<Prime>(spec);
let spec = crate::module::Spec::new(interp, "Singleton", None)?;
interp.0.borrow_mut().def_module::<Singleton>(spec);
... | Rust | 0 |
_padding(len as u32) as usize;
buffer_pad_fixed(buf, padding)
}
pub(crate) fn buffer_unpad(buf: &[u8]) -> Result<Vec<u8>> {
let len = buf.len();
// We pass the buffer's length as the block size because due to padme there's always some variable-sized padding.
buffer_unpad_fixed(buf, len)
}
pub(crate)... | Rust | 0 |
import torch
import torchaudio
import pytest
from beans.utils import divide_waveform_to_chunks, divide_annotation_to_chunks
def test_divide_waveform_to_chunks(tmp_path):
sr = 16000
# create a 5-second wave file that has a monotonically increasing waveform
waveform = torch.arange(0, 1, 1/(5*sr)).unsqueeze(0... | Python | 1 |
nment if possible to do so.
`assignment` is a mapping from variables (keys) to words (values).
If no assignment is possible, return None.
"""
## garantees the recursivity end
if(self.assignment_complete(assignment)):
return assignment
## se... | Python | 1 |
from .base import *
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
'default': {
... | Python | 1 |
er_fea.append(np.dot(user_emb[user_id], articles_emb[article_id]))
single_user_fea.extend([score, rank, label])
# 加入到总的表中
all_user_feas.append(single_user_fea)
# 定义列名
id_cols = ["user_id", "click_article_id"]
sim_cols = ["sim" + str(i) for i in range(N)]
time_cols =... | Python | 1 |
from flask_webgoat import create_app
app = create_app()
@app.after_request
def add_csp_headers(response):
# vulnerability: Broken Access Control
response.headers['Access-Control-Allow-Origin'] = '*'
# vulnerability: Security Misconfiguration
response.headers['Content-Security-Policy'] = "script-src 's... | Python | 1 |
"""The controller module, the main method of this module starts DockerENT."""
from DockerENT import output_worker
from DockerENT import scanner_workers
from multiprocessing import pool
import logging
import multiprocessing
# Define module-level logger.
_log = logging.getLogger(__name__)
def main(docker_containers,
... | Python | 1 |
"""LlamaIndex toolkit."""
from typing import List
from llama_index.core.bridge.langchain import BaseTool, BaseToolkit
from llama_index.core.bridge.pydantic import Field
from llama_index.core.langchain_helpers.agents.tools import (
IndexToolConfig,
LlamaIndexTool,
)
class LlamaToolkit(BaseToolkit):
"""To... | Python | 1 |
from flask import Flask, request, render_template
import sqlite3
from datetime import datetime
app = Flask(__name__)
DB_NAME = 'notes.db'
def init_db():
conn = sqlite3.connect(DB_NAME)
c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, note TEXT, timestamp TEXT)')
... | Python | 1 |
(0, &interaction) {
Some(n) => match n.value.as_ref() {
Some(n) => match n.as_str() {
Some(n) => {
let n = n
.chars()
.into_iter()
.filter(|x| x.is_alphanumeric())
.col... | Rust | 0 |
::with_name("source-map-prefix")
.help("Remap source paths in all output (i.e. FROM/foo => TO/foo)")
.long("source-map-prefix")
.hidden(true)
.takes_value(true)
.value_name("FROM=TO"),
)
.arg(
Arg::with_name("def... | Rust | 0 |
ns
class LocationInfo:
def __init__(self,city):
self.city = city
def info (self):
geolocator = Nominatim(user_agent = "my_app")
location = geolocator.geocode(f"{self.city}")
url = f"https://api.openweathermap.org/data/2.5/weather?lat={location.latitude:.2f}&lon={locati... | Python | 1 |
se function to get header, but don't verify body
ExternalBody,
// don't parse function; function can't be called directly from verified code
External,
// hide body (from all modules) until revealed
Opaque,
// publish body
Publish,
// publish body with zero fuel
OpaqueOutsideModule,
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.