text string | label_name string | labels int64 |
|---|---|---|
0]);
let (x1, y1) = (pad.xxt[0][1], pad.xxt[1][1]);
let (x2, y2) = (pad.xxt[0][2], pad.xxt[1][2]);
let (a0, a1, a2) = (y1 - y2, y2 - y0, y0 - y1);
let (b0, b1, b2) = (x2 - x1, x0 - x2, x1 - x0);
let (f0, f1, f2) = (x1 * y2 - x2 * y1, x2 * y0 - x0 * y2, x0 * y1 - x1 * y0);
... | Rust | 0 |
re 0
if any(kw in lower for kw in [
"short a", "short b", "short c",
"long d", "long e", "long f",
"total short-term", "total long-term", "total undetermined"
]):
return True
return False
def has_nonzero_div(text: str) -> bool:
"""
Detects if a 1099-DIV form has an... | Python | 1 |
event_client_mock()
.expect_update_room()
.with(pred::eq(event_room_id), pred::always())
.returning(move |_room_id, _| Ok(()));
state
.conference_client_mock()
.expect_update_room()
.with(pred::eq(conference_room_id), pred::always())
... | Rust | 0 |
"""
Tencent is pleased to support the open source community by making 蓝鲸智云 - 监控平台 (BlueKing - Monitor) available.
Copyright (C) 2017-2025 Tencent. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at... | Python | 1 |
OYED: ::std::os::raw::c_uchar = 38;
pub const KERN_LOCK_UNSTABLE: ::std::os::raw::c_uchar = 39;
pub const KERN_LOCK_OWNED: ::std::os::raw::c_uchar = 40;
pub const KERN_LOCK_OWNED_SELF: ::std::os::raw::c_uchar = 41;
pub const KERN_SEMAPHORE_DESTROYED: ::std::os::raw::c_uchar = 42;
pub const KERN_RPC_SERVER_TERMINATED: :... | Rust | 0 |
Copyright 2020-2021, The Tremor Team
//
// 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 agree... | Rust | 0 |
let f_gene = *f_genes.get(&conn.innov).unwrap();
let mut gene = if rng.gen::<f64>() < 0.5 {
f_gene.clone()
} else {
conn.clone()
};
let m_e = conn.enabled;
let f_e = f_gene.enabled;
... | Rust | 0 |
data.execute(&st.get_ref().schema, &ctx);
Ok(HttpResponse::Ok()
.content_type("application/json")
.body(serde_json::to_string(&res)?))
}
#[cfg(feature = "postgres")]
type DbConnection = diesel::pg::PgConnection;
#[cfg(feature = "sqlite")]
type DbConnection = diesel::sqlite::SqliteConnection;
#[a... | Rust | 0 |
ool = NoteData::new();
cool.charts = vec![vec![
vec![(vec![Note::new(NoteType::Tap, 3)], Fraction::new(1, 2))],
vec![(
vec![Note::new(NoteType::Mine, 0), Note::new(NoteType::Tap, 3)],
Fraction::new(1, 2),
)],
vec![],
vec... | Rust | 0 |
// [2] Collary 5.3
_ if x >= 5393 => n / (ln - 1.),
// [2] Collary 5.2
_ if x >= 599 => n * invln * (1. + invln),
// [2] Collary 5.2
_ => n * invln,
};
let hi = match () {
// [2] Theorem 5.1, valid for x > 4e9, intersect... | Rust | 0 |
f_final):,} registros inseridos com sucesso")
# Verificar inserção
with engine.connect() as conn:
result = conn.execute(text("SELECT COUNT(*) FROM sep_events"))
count = result.scalar()
print(f"🔍 Verificação: {count:,} registros na tabela")
r... | Python | 1 |
clogon_leak_local
type: bool
default: False
- name: use_seclogon_leak_remote
type: bool
default: False
- name: seclogon_leak_remote_binary
type: str
default: ""
- name: use_seclogon_duplicate
type: bool
default: False
- name: spoof_... | Python | 1 |
sert("Thai_maiyamok", 0x0de6);
keysyms.insert("Thai_maitaikhu", 0x0de7);
keysyms.insert("Thai_maiek", 0x0de8);
keysyms.insert("Thai_maitho", 0x0de9);
keysyms.insert("Thai_maitri", 0x0dea);
keysyms.insert("Thai_maichattawa", 0x0deb);
keysyms.insert("Thai_thanthakhat", 0x0dec);
keysyms.insert("Thai_nikhahit... | Rust | 0 |
### DO NOT REMOVE IMPORTS, THEY ARE NECESSARY! ###
def register():
from . import equidistant_node_generator
from . import first_type_chebyshev_node_generator
from . import second_type_chebyshev_node_generator | Python | 1 |
_btn.click()
time.sleep(4)
notes_shortlist_field = driver.find_element(By.XPATH, '/html[1]/body[1]/div[1]/div[1]/div[2]/div[2]/div[1]/div[1]/form[1]/div[2]/div[1]/div[1]/div[1]/div[2]/textarea[1]')
notes_shortlist_field.send_keys("Seems nice IDK.")
time.sleep(2)
shortlist_save_btn = driver.find_element(By.XPATH, '/ht... | Python | 1 |
class Solution:
def recoverTree(self, root: Optional[TreeNode]) -> None:
pred = None
x = None # 1st wrong node
y = None # 2nd wrong node
def findPredecessor(root: Optional[TreeNode]) -> Optional[TreeNode]:
pred = root.left
while pred.right and pred.right != root:
pred = pred.rig... | Python | 1 |
air();
// TODO: quickcheck
let mut ptx = libproto::Transaction::new();
ptx.set_data(vec![1]);
ptx.set_nonce(String::from("0"));
ptx.set_to_v1(vec![1, 2, 3]);
ptx.set_valid_until_block(66);
ptx.set_quota(314159265);
ptx.set_value(vec![1]);
ptx.set_... | Rust | 0 |
[derive(Storage, Serialize, Deserialize, Debug)]
#[store_at = "meta.json"]
pub struct Meta {
pub token: String,
}
///
/// The Shortcut struct.
///
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Shortcut {
pub id: u32,
pub key: ShortcutKey,
pub url: String,
pub title: String,
pub com... | Rust | 0 |
ma50_period}'
),
row=1, col=1
)
fig.add_trace(
go.Scatter(
x=df['date'], y=df['EMA200'],
line=dict(color='purple', width=1),
name=f'EMA{ema200_period}'
),
row=1, col=1
)
# CKS Lin... | Python | 1 |
# Copyright 2016-2024 Swiss National Supercomputing Centre (CSCS/ETH Zurich)
# ReFrame Project Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
import os
import reframe as rfm
import reframe.utility.typecheck as typ
import reframe.utility.sanity as sn
class fetch_osu_... | Python | 1 |
l_fuchsia_io::OPEN_RIGHT_WRITABLE,
)
.await?;
Status::ok(blob0.truncate(BLOB_CONTENTS.len() as u64).await?)?;
let res = Status::ok(blob1.truncate(BLOB_CONTENTS.len() as u64).await?);
assert_matches!(res, Err(zx::Status::BAD_STATE));
blobfs_server.stop().await
}
#[fuchsia_async::run_singlethr... | Rust | 0 |
from dash.dependencies import Input, Output, State, MATCH
from server import app
import feffery_antd_components as fac
from dash_components import MessageManager
from database.sql_db.dao import dao_listen
import dash
from uuid import uuid4
from dash import dcc
import json
from typing import List
from common.listen impo... | Python | 1 |
on(
"_chdb",
sources=["programs/local/LocalChdb.cpp"],
libraries=[],
library_dirs=[libdir],
extra_objects=[chdb_so],
define_macros=[("Py_LIMITED_API", "0x03080000")],
py_limited_api=True,
),
... | Python | 1 |
elf).modify(|_, w| w.attribute_controller_register_index().bits(index));
self.io.write(ARX::<Self>::ABS_ADDRESS_W, data);
}
}
io_handler_type!(pub struct ColorPaletteIo);
impl_abs_address_io!(rw, ColorPaletteIo, ColorPaletteGroup);
io_handler_type!(pub struct CrtControllerIo);
impl_abs_address_io!(rw, Crt... | Rust | 0 |
}
pub fn get_stack_range(&self) -> &VMRange {
&self.stack_range
}
pub fn get_base_addr(&self) -> usize {
self.get_process_range().start()
}
pub fn get_stack_base(&self) -> usize {
self.get_stack_range().end()
}
pub fn get_stack_limit(&self) -> usize {
sel... | Rust | 0 |
"""
https://leetcode.com/problem-list/sliding-window/
url: https://leetcode.com/problems/arithmetic-slices
""" # noqa: E501
class Solution:
def numberOfArithmeticSlices(self, nums: list[int]) -> int:
seq_lengths = [0] * len(nums)
for i in range(2, len(nums)):
if nums[i] - nums[i - 1] ... | Python | 1 |
let mut msg = Message::empty();
let start_offset = offset;
// The name is mandatory (NOT!)
let mut next_type: u16 = decoder::read_u16(slice, offset); offset += 2;
let mut next_length: u16 = decoder::read_u16(slice, offset); offset += 2;
msg.name_length = next_length as usize;
... | Rust | 0 |
())
}<reponame>mapkts/binate
use super::*;
use bytes::{Buf, BufMut, Bytes, BytesMut};
/// The payload frame.
///
/// # Frame Contents
///
/// The payload frame is structured as follows:
///
/// ```text
/// 0 1 2 3
/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2... | Rust | 0 |
ies."]
#[doc = " Buffer must be freed by the caller when is no longer needed."]
#[doc = " @param[in] key_val_sep character used to separate key from value"]
#[doc = " @param[in] pairs_sep character used to separate two pairs from each other"]
#[doc = " @return ... | Rust | 0 |
# 论文:An Effective Intraday Momentum Strategy for SP500
# 用于数据处理
import numpy as np
import pandas as pd
# 用于获取高频数据
import akshare as ak
# 用于可视化
import matplotlib.pyplot as plt
# 设置中文显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# 忽略警告
import warnings
warnings.filterwarnings('... | Python | 1 |
city, country))
if json_data is not None:
logging.error("[%s]: Received data from server: %s"
% (self._log_tag, json_data))
if self._fail_ctr >= max_tolerated_fails:
with self.updateLock:
... | Python | 1 |
Assets, Handle, HandleUntyped},
core::{cast_slice, FloatOrd, Pod, Time, Zeroable},
core_pipeline::Transparent3d,
ecs::{
prelude::*,
system::{lifetimeless::*, SystemState},
},
log::{trace, warn},
math::{const_vec3, Mat4, Vec2, Vec3, Vec4Swizzles},
reflect::TypeUuid,
rende... | Rust | 0 |
})
.collect(),
);
let routes = Routes::random(size_generation, distances.n_units());
let max_fit = routes.get_n_fittest(1, &distances)[0].fitness(&distances);
let routes = evolve_population(routes, n_generations, size_generation, &distances, 0);
let max_fit_new = routes.get_... | Rust | 0 |
puHeap>,
gpu_visible: Vec<GpuHeap>,
free_list: Arc<Mutex<DescriptorFreeList>>,
}
#[derive(Default)]
pub struct DescriptorFreeList {
cpu_free: Vec<Vec<u32>>,
gpu_free: Vec<BestFit>,
}
struct CpuHeap {
// Retained for lifetime reasons.
#[allow(unused)]
dx12_heap: DescriptorHeap,
cpu_hand... | Rust | 0 |
t_item_type, game);
}
pub fn buy_item_internal(boost_item_type: BoostItemTypes, game: &mut Game) {
if can_buy_item(boost_item_type, game) {
info!("Can buy item");
game.register_input(boost_item_type);
let item: &BoostItem = &game.world.boost_items[boost_item_type as usize];
game.sta... | Rust | 0 |
from .animal_controller import animal_bp
__all__ = ['animal_bp']
| Python | 1 |
if caps.get('vision'): cap_icons.append('👁️ vision')
if caps.get('document'): cap_icons.append('📄 document')
if caps.get('video'): cap_icons.append('🎥 video')
if caps.get('audio'): cap_icons.append('🎧 audio')
if caps.get('citations'): cap_icon... | Python | 1 |
utable.0.into()],
"",
);
}
pub(crate) fn free_execution_result<'ctx>(
context: &mut QCSCompilerContext<'ctx>,
execution_result: &ExecutionResult<'ctx>,
) {
context.builder.build_call(
context.values.free_execution_result_function(),
&[execution_result.0.into()],
"",
... | Rust | 0 |
from state import State
from isentropic import isentropic
from isochoric import isochoric
from specific_heat import specific_heats, get_temperature_by_integrating_cv_dT, get_heat_by_integrating_cv_dT
from myarray import array
from print import *
from work import work
from pvts import *
from conversion import celsius
d... | Python | 1 |
ero_and_nine.iter()
.filter(|cs| **cs != zero)
.map(|cs| cs.clone())
.collect();
let nine: HashSet<char> = nine.first().unwrap().clone();
// find a
let a_encoded: Vec<&char> = seven.symmetric_difference(&one).collect();
let a_encoded: char = **a_encod... | Rust | 0 |
t]
fn test_take_char_by_ptr_in_wrapped_method() {
let hdr = indoc! {"
#include <cstdint>
#include <memory>
struct C {
C() { test = \"hi\"; }
uint32_t a;
char* test;
};
class A {
public:
A() {};
uint32_t take_... | Rust | 0 |
#[cfg(test)]
mod tests {
use super::*;
fn make_positions() -> Vec<[f32; 3]> {
vec![
[0.5, -0.5, 0.5],
[-0.5, -0.5, 0.5],
[0.5, 0.5, 0.5],
[-0.5, 0.5, 0.5],
[-0.5, -0.5, -0.],
[0.5, -0.5, -0.5],
[-0.5, 0.5, -0.5],
... | Rust | 0 |
Encrypted, extract IV
if (action & TeleportAction::Encrypted as u8) == TeleportAction::Encrypted as u8 {
if input.len() < 25 {
return Err(Error::new(ErrorKind::InvalidData, "Not enough data for IV"));
}
let iv: [u8; 12] = input[13..25].try_into().expect("Erro... | Rust | 0 |
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import uvicorn
from pydantic import BaseModel
# 导入你的LLM类
from LLM import HuanhuanLLM
app = FastAPI()
app.mount("/static", StaticFiles(directory="st... | Python | 1 |
_FG: GtkRcFlags = GtkRcFlags::FG;
pub const GTK_RC_BG: GtkRcFlags = GtkRcFlags::BG;
pub const GTK_RC_TEXT: GtkRcFlags = GtkRcFlags::TEXT;
pub const GTK_RC_BASE: GtkRcFlags = GtkRcFlags::BASE;
bitflags! {
#[repr(C)]
pub struct GtkRecentFilterFlags: c_uint {
const URI = 1;
const DISPLAY_NAME = 2;... | Rust | 0 |
8() {
// "ÄÅÆÇÈÉÊËÌÍÎÏ": some umlauts and Latin letters.
let input = [
0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
];
let expected = [
0xc3, 0x84, 0xc3, 0x85, 0xc3, 0x86, 0xc3, 0x87, 0xc3, 0x88, 0xc3, 0x89, 0xc3, 0x8a,
0xc3,... | Rust | 0 |
001, lambda_2C7F)
Sleep(50)
@scena.Lambda('lambda_2C9F')
def lambda_2C9F():
ChrWalkTo(0x000C, -29200, 0, 39180, 3000, 0x00)
ExitThread()
DispatchAsync(0x000C, 0x0001, lambda_2C9F)
Sleep(50)
@scena.Lambda('lambda_2CBF')
def lambda_2CBF():
ChrWalkTo(0x0109, -30140... | Python | 1 |
variant as _
}
}
#[doc = "Reader of field `DSP_PRAM_EMA`"]
pub type DSP_PRAM_EMA_R = crate::R<u8, DSP_PRAM_EMA_A>;
impl DSP_PRAM_EMA_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, DSP_PRAM_EMA_A> {
use crate::Variant::*;
... | Rust | 0 |
# in case the foldseek output is empty
if foldseek_df.empty:
logger.warning(
"Foldseek found no custom hits whatsoever - please check your custom database and input."
)
logger.warning(
"Phold will continue using only the default databases."
)
# gets... | Python | 1 |
target_at = helpers::target_at_fn::<T>(&targets);
let mut assignments = compact.into_assignment(voter_at, target_at).unwrap();
// make a voter cache and some helper functions for access
let cache = helpers::generate_voter_cache::<T>(&voters);
let voter_index = helpers::voter_index_fn::<T>(&cache);
let targe... | Rust | 0 |
import logging
from typing import Any, Literal, TypedDict, cast
import jwt
from app.infrastructure.auth.session.model import AuthSession
from app.presentation.http.auth.constants import (
ACCESS_TOKEN_INVALID_OR_EXPIRED,
ACCESS_TOKEN_PAYLOAD_MISSING,
ACCESS_TOKEN_PAYLOAD_OF_INTEREST,
)
log = logging.getL... | Python | 1 |
um_iterations
samples_per_second = (batch_size * num_iterations) / total_time
print(f"Benchmark Results:")
print(f" Total time: {total_time:.2f}s")
print(f" Average time per batch: {avg_time_per_batch*1000:.2f}ms")
print(f" Throughput: {samples_per_second:.1f} samples/second")
print(f" ... | Python | 1 |
import numpy as numpy
from functools import cmp_to_key
INPUT_FILE_PATH = './input.txt'
def main():
ordering_rules, updates = parse_input_file()
total = calculate_middle_page_number_of_sorted_not_allowed_updates(ordering_rules, updates)
print(total)
def calculate_middle_page_number_of_sorted_not_allowed... | Python | 1 |
in(s['length'], 150)))
return best_sentence['sentence']
# 否则返回优先级最高、关键词最多的句子
best_sentence = max(relevant_sentences, key=lambda s: (s['priority'], s['keyword_count'], min(s['length'], 150)))
return best_sentence['sentence']
# 如果没有找到合适的句子,尝试提取包含基本关键词的句子
for s... | Python | 1 |
)
else:
physical_setup_graph.nodes[resource["id"]]["data"].update(resource["data"])
self.lab_logger().info(f"[Host Node-Resource] Add request completed, success: {success}")
return response
def _resource_get_callback(self, request: ResourceGet.Request, response:... | Python | 1 |
sitive, predictions_with_sensitive, sensitive_feature
),
"conditional_statistical_parity": conditional_statistical_parity_regression(
y_test_with_sensitive, predictions_with_sensitive, sensitive_feature
),
"equal_opportunity": equal_opportunity_regression(... | Python | 1 |
import numpy as np
from mcdm_kit.data import DecisionMatrix
from mcdm_kit.core import CIMAS, ARTASI
# Step 1: Define decision matrices for 3 experts
# Each matrix: alternatives × criteria
expert_matrices = [
np.array([
[80, 70, 60],
[85, 65, 55],
[90, 60, 50]
]),
np.array([
... | Python | 1 |
} = make_state(addr, &ws, incoming_rx);
let sa = sock_addr();
let (web_sock, _ws_rx) = websocket_for(Role::Client, NoExt).await;
let host1 = SchemeHostPort::new(Scheme::Ws, "my_host".to_string(), 80);
let host2 = SchemeHostPort::new(Scheme::Ws, "other".to_string(), 80);
let (req_tx, _req_rx)... | Rust | 0 |
rty card.
PropertyCard(PropertyCard),
/// Represents an action card.
ActionCard(ActionCard),
/// Represents a money card.
MoneyCard(MoneyCard),
/// Represents a rent card.
RentCard(RentCard),
/// Represents a property wild card.
PropertyWildCard(PropertyWildCard),
}
/// Represents cards that can be banked... | Rust | 0 |
from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph, START
from agents.flight_team.db.database import Database
from agents.orchestrator.state import State
from agents.orchestrator.supervisor import create_supervisor
from agents.flight_team.agents import (
flight_team_db_node,
flight_t... | Python | 1 |
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.preprocessing import StandardScaler, PolynomialFeatures
from sklearn.impute import SimpleImputer
import matplotlib.pyplot as plt
def load_data(file_path, tar... | Python | 1 |
onds
# and nanoseconds should be coerced to microseconds by default
expected = pa.Table.from_arrays([a_ms, a_ms, a_us, a_us], names)
_check_roundtrip(table, expected, version='1.0')
_check_roundtrip(table, expected, version='2.4')
# Using Parquet version 2.6, seconds should be coerced to millisecon... | Python | 1 |
o_input.reshape(-1, D) # [B*N, D]
a = self.audio_vlad(x_audio) # [B, 512]
fused, z = self.fusion(v, a) # [B, 512]
x = self.dropout(fused) # [B, 512]
logits = self.fc(x) # [B, num_classes]
return logits
# ---
# LateFusio... | Python | 1 |
", {}).get("first_air_date"),
"emby_episode_count": emby_episode_count_display,
"latest_episode": latest_episode_info,
"missing_info": missing_info,
"chasing_season_number": chasing_season_number
})
except Excep... | Python | 1 |
= format!("{}{}.{}", name, add_text_text, extension);
}
}
_ => panic!("Invalid Rule Place for AddText"),
},
_ => panic!("Invalid Rule Type for AddText"),
}
return_string
}
#[cfg(test)]
mod test {
use crate::rule_add_text::rule_add_text;
use crat... | Rust | 0 |
}
impl<T: Holder> IntoOwned for PlaceHolder<T>
where
T::Table: EntityTable<T>,
{
type Owned = T::Owned;
type Table = T::Table;
/// Get owned value, or look up entity table and clone it for a reference.
///
/// Errors
/// -------
/// - if table lookup failed, i.e. unknown entity id not r... | Rust | 0 |
_scale)
mOp.scale.value = qkv_scale.to(torch_dtype)
# Load weights from AWQ checkpoint into TRT-LLM module
# 1. embedding
v = load(awq_key_list[0])
# TRT-LLM requires vocab_size to be multiple of 64 for successful GEMM
if v.shape[0] % 64 != 0:
v = torch.nn.functional.pad(v, [0, 0, 0... | Python | 1 |
valid_indices = [idx for idx in sorted_indices if idx in remaining_indices]
indices = valid_indices[-pixel_counts[i]:]
remaining_indices -= set(indices)
color_map[indices] = i
color_map = color_map.reshape(size)
final_map = modal(col... | Python | 1 |
e) -> usize {
// Fallback for non-sse2 platforms.
line_to_byte_idx_inner::<usize>(text, line_idx)
}
#[inline(always)]
fn line_to_byte_idx_inner<T: ByteChunk>(text: &str, line_idx: usize) -> usize {
let mut bytes = text.as_bytes();
let mut line_break_count = 0;
// Handle unaligned bytes at the star... | Rust | 0 |
pboard between the start and end seq
TIMESTAMP_MESSAGES = True # If this is true a timestamp will be added to the end of each of your messages
INPUT_HANDLER = "autohotkey" # Alternatively you can use "autohotkey"
MAX_PROMPT_TOKENS = 4096 # The message list will be cut down to fit within this number of tokens
DOUBLE_T... | Python | 1 |
// parse the pubkey that server send to us, then hash it and we will use that
// hash to get the key from the enclave to sign
let pubkey = EcdsaSha2Nistp256::read(pubkey);
let mut hasher = Sha1::new();
let mut hash: [u8; 20] = [0; 20];
hasher.input(pubkey.as_slice());
hasher.result(&mut hash);
//... | Rust | 0 |
lse).to(post_trans.device)
# undo post-transformation
# B x N x D x H x W x 3
points = frustum - post_trans.view(B, N, 1, 1, 1, 3)
points = torch.inverse(post_rots).view(B, N, 1, 1, 1, 3, 3).matmul(points.unsqueeze(-1))
# cam_to_ego
points = torch.cat((points[:, :, :, :, :, :2] * points[:, :, :... | Python | 1 |
from .drop import DropPath
from .inverted_residual import InvertedResidual, InvertedResidualV3
from .make_divisible import make_divisible
from .res_layer import ResLayer
from .se_layer import SELayer
from .self_attention_block import SelfAttentionBlock
from .up_conv_block import UpConvBlock
from .weight_init import tru... | Python | 1 |
check_credentials()
elif choice == "4":
check_file_structure()
elif choice == "5":
validate_json_files()
elif choice == "6":
test_python_syntax()
elif choice == "7":
start_dev_server()
elif choi... | Python | 1 |
from neo4j import GraphDatabase
import csv
#################################################################
# Obtenció arestes ANY_VIU (dinàmiques)
VIU = "dades/VIU.csv"
# Connexió amb Neo4j
uri = "bolt://localhost:7687"
usuario = "neo4j"
contraseña = ""
driver = GraphDatabase.driver(uri, auth=(usuario, contraseña))... | Python | 1 |
import pytest
from clients.http.request import EnhancedRequest, Request
class TestEnhancedRequest:
@pytest.fixture
def sample_request(self) -> str:
return Request("GET", "https://httpbin.org/get")
@pytest.fixture
def sample_enhanced_request(self, sample_request: Request) -> EnhancedRequest:
... | Python | 1 |
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, matthews_corrcoef, \
roc_auc_score, precision_recall_curve, auc
import torch
import torch.nn.functional as func
def null_metrics():
return {
'acc': 0.0,
'f1-score': 0.0,
'precision': 0.0,
'reca... | Python | 1 |
import os
import pytest
import sentry_sdk
from squadmanager.plugins.sentry_plugin import SentryPlugin
class DummyException(Exception):
pass
def test_init_without_dsn_raises():
with pytest.raises(ValueError) as excinfo:
SentryPlugin(config={})
assert 'DSN Sentry est manquant' in str(excinfo.value)... | Python | 1 |
# -*- coding: utf-8 -*-
"""网易云课堂 MOOC"""
import time
from .utils import *
CANDY = Crawler()
CONFIG = {}
FILES = {}
def get_summary(url):
"""从课程主页面获取信息"""
res = CANDY.get(url).text
term_id = re.search(r'termId : "(\d+)"', res).group(1)
names = re.findall(r'name:"(.+)"', res)
dir_name = course_... | Python | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
import datetime as dt
import json
import secrets
import socket
import threading
import traceback
import random
import uuid
from base64 import b64encode
# Для импорта common
import sys
sys.path.append("..")
from common import send_msg, recv_msg
... | Python | 1 |
work = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6']
st = [0, 3, 1, 5, 5, 8]
fn = [6, 4, 2, 9, 7, 9]
print(work)
print(st)
print(fn)
print()
s = len(work)
for i in range(0, s):
for j in range(0, s - i - 1):
if fn[j] > fn[j + 1]:
work[j], work[j + 1] = work[j + 1], work[j]
st[j], st[j + 1] = ... | Python | 1 |
print_message(&self) {
if self.phy_queues.is_empty() {
println!("Physical queue has not yet generated.");
} else {
println!("[Info] Single Family - Multi Queues Strategy.");
println!("[Info] Generate Physical Queue:");
println!("\tfamily index | queue ... | Rust | 0 |
"beyond_1_0":self.beyond_1_0,
"beyond_2_5":self.beyond_2_5,
"beyond_5_0":self.beyond_5_0,
"beyond_10":self.beyond_10
}
return res
def avr_results(self):
avr_res = {
"pm1_0_std_avr":self.pm1_0_std_sum/self.count,
"pm2_5_std... | Python | 1 |
# -*- coding: utf-8 -*-
# Copyright (c) 2013 by Pablo Martín <goinnn@gmail.com>
#
# This software is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) a... | Python | 1 |
st!(s, recv_mpst_c_from_s, {
Branching1fromStoC::Continue(s) => {
let (_, s) = recv_mpst_c_from_s(s)?;
endpoint_c_2(s)
},
Branching1fromStoC::Loop(s) => {
let (_, s) = recv_mpst_c_from_s(s)?;
let (_, s) = recv_mpst_c_from_s(s)?;
endpo... | Rust | 0 |
ipt"
};
let target_arg = match target {
"nodejs" => "--nodejs",
"no-modules" => "--no-modules",
_ => "--browser",
};
let bindgen_path = bindgen.binary("wasm-bindgen")?;
let mut cmd = Command::new(bindgen_path);
cmd.arg(&wasm_path)
.arg("--out-dir")
.arg(ou... | Rust | 0 |
x(self):
return self.request.headers.get('X-Requested-With') == 'XMLHttpRequest'
def form_invalid(self, form):
if self.is_ajax():
return JsonResponse({'error': form.errors}, status=400)
return super().form_invalid(form)
def form_valid(self, form):
comment = form.sav... | Python | 1 |
tr),
}
#[doc(hidden)]
#[derive(Default)]
pub struct NoSettings;
#[doc(hidden)]
#[derive(Clone)]
pub enum NoSettingsVariant { }
impl settings::Settings for NoSettings {
type Variant = NoSettingsVariant;
fn to_variant(name: &str, _value: Value) -> Result<Self::Variant> {
Err(Error::Setting(SettingErro... | Rust | 0 |
ayload);
let record = match partition {
Some(partition) => record.partition(*partition),
None => record,
};
record
}
}
<filename>crates/layout/force-simulation/src/lib.rs
pub mod coordinates;
pub mod force;
pub mod simulation;
pub use self::coordinates::{Coordinates,... | Rust | 0 |
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from imblearn.under_sampling import TomekLinks
rng = np.random.RandomState(42)
def main():
#generate data
n_samples_1 = 500
n_samples_2 = 50... | Python | 1 |
details and example usage.
///
/// # Arguments
///
/// * `runtime` - [`Runtime`](`crate::circuit::Runtime`) within which operators are created.
/// * `worker_index` - index of the current worker.
/// * `partition` - partitioning logic that, for each element of the input stream, returns
/// an iterator with exactly... | Rust | 0 |
re = 25
}";
let (_, _) = technology_parser(input).unwrap();
}
#[test]
fn test_technology2() {
let input = "Technology {
name = \"scc40nll_hd\"
dielectric = 4.2e-05
unitTimeName = \"ns\"
timePrecision = 1000
... | Rust | 0 |
EmptyBytecodeHelper:
def __init__(self) -> None:
# generate bytecode for empty functions with/without a docstring
def _empty_with_docstring() -> None:
"""""" # noqa: D419
def _empty_without_docstring() -> None:
pass
self.empty_bytecode = (
_empt... | Python | 1 |
.stdout()
.is(expected_output)
.unwrap();
}
#[test]
fn dry_run_escaped_env() {
let defaults_path = asset_path().join("defaults-escaped.yml");
let expected_output =
"==> defaults write com.apple.desktopservices DSDontWriteNetworkStores -bool true
==> defaults write com.apple.dock autohi... | Rust | 0 |
"""Tests for concatenation utilities."""
import chex
import jax
import jax.numpy as jnp
from prxteinmpnn.utils.concatenate import concatenate_neighbor_nodes
def test_concatenate_neighbor_nodes():
"""Test the concatenation of node features with neighbor edge features.
Raises:
AssertionError: If the o... | Python | 1 |
_bits=a_bits, kv_bits=kv_bits, quantize_kv=quantize_kv)
m.v_proj = FakeQuantLinear.from_float(
m.v_proj, weight_quant, act_quant, w_bits=w_bits, a_bits=a_bits, kv_bits=kv_bits, quantize_kv=quantize_kv)
m.o_proj = FakeQuantLinear.from_float(
m.o_proj, weight_quant,... | Python | 1 |
from functools import partial
from typing import Any
import numpy as np
from PIL import Image as PilImage
from positronic.dataset import Signal, transforms
from positronic.dataset.episode import Episode
from positronic.dataset.transforms import image
class ObservationEncoder(transforms.KeyFuncEpisodeTransform):
... | Python | 1 |
))
)
def test_get_filled_value_and_weight_tensor_with_weights_and_fill_value(self):
values, weights = WeightedTensor.get_filled_value_and_weight(
self.weighted_tensor_3_x_3,
fill_value=1000.0,
)
self.assertTrue(
torch.equal(
value... | Python | 1 |
fn state_free_d_mut(&mut self) -> &mut Value {
&mut self.state[13]
}
pub fn state_free_e_mut(&mut self) -> &mut Value {
&mut self.state[14]
}
pub fn state_free_f_mut(&mut self) -> &mut Value {
&mut self.state[15]
}
}
// stack
impl Counter {
pub fn stack(&self) -> &Stack... | Rust | 0 |
def test_inference_cifar10(self):
model_id = 'google/ddpm-cifar10-32'
unet = UNet2DModel.from_pretrained(model_id)
scheduler = DDIMScheduler()
ddim = DDIMPipeline(unet=unet, scheduler=scheduler)
ddim.to(torch_device)
ddim.set_progress_bar_config(disable=None)
generator = torch.manual_seed(0)... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.