text string | label_name string | labels int64 |
|---|---|---|
anos. With the help of remaining allies, the Avengers must assemble once more in order to undo Thanos' actions and restore order to the universe once and for all, no matter what consequences may be in store.",
"director": "<NAME>",
"producer": "<NAME>",
"genres": [
"Adventure",
... | Rust | 0 |
from flask import request, jsonify, make_response
from tables.dbModels import db
from routes.authentication.accessToken import token_required
from sqlalchemy import text as t
from sqlalchemy.exc import SQLAlchemyError
@token_required
def delete_user_appointment_details(current_user):
if request.method == "OPTIONS... | Python | 1 |
t body = engine.render_template(err_vals, config)?;
response::not_found(path_info, body);
return Ok(())
}
let status_opt = doc.head.status.clone();
let loc_opt = doc.head.redirect.clone();
match loc_opt {
Some(location) =>... | Rust | 0 |
from ..smp import *
from ..utils import *
from .image_base import ImageBaseDataset
from .utils import build_judge, DEBUG_MESSAGE
class ImageYORNDataset(ImageBaseDataset):
TYPE = 'Y/N'
DATASET_URL = {
'MME': 'https://opencompass.openxlab.space/utils/VLMEval/MME.tsv',
'HallusionBench': 'https:... | Python | 1 |
!(b["type"], "bind");
}
_ => panic!(),
}
if let Some(_) = w.get_action() {
panic!()
};
w.websocket_connection_lost(wsh);
match w.get_action() {
Some(StartTimer(handle, duration)) => {
assert_eq!(duration, 5.0);
... | Rust | 0 |
"""Pymode support functions."""
import sys
from importlib.machinery import PathFinder as _PathFinder
import vim # noqa
if not hasattr(vim, 'find_module'):
vim.find_module = _PathFinder.find_module
def auto():
"""Fix PEP8 erorrs in current buffer.
pymode: uses it in command PymodeLintAuto with pymode#... | Python | 1 |
ts[name] / total_samples[name]
acc = round(100 * acc, 3)
eval_acces[name] = acc
### only compare top-1 accuracy
if "top-1" in name or "highest" in name:
if acc >= best_top1:
best_top1 = acc
best_top1_name = name
... | Python | 1 |
import re
def filter_number(unfiltered_number):
filtered_number = ""
for digit in unfiltered_number:
if digit.isdigit():
filtered_number += digit
return filtered_number
def filter_date(unfiltered_date):
filtered_date = ""
for i in unfiltered_date:
if i.isdigit() or i ... | Python | 1 |
or::Color, hittable::HitRecord, materials::Material, ray::Ray};
use rand::Rng;
pub struct MixedMaterial<'a> {
pub primary: &'a (dyn Material + Sync),
pub secondary: &'a (dyn Material + Sync),
pub chance: f32,
}
impl Material for MixedMaterial<'_> {
fn scatter(&self, r_in: &Ray, rec: &HitRecord) -> Opt... | Rust | 0 |
import random
WORDS = []
with open('words.txt', 'r') as file:
for line in file:
word = line.strip()
if len(word) == 5 and word.isalpha():
WORDS.append(word.lower())
class Wordle:
def __init__(self):
self.correct_word = None
self.guesses = []
self.max_gues... | Python | 1 |
# Copyright (c) 2024 Seb Holzapfel <me@sebholzapfel.com>
#
# SPDX-License-Identifier: CERN-OHL-S-2.0
"""
Collect some information about Tiliqua health, display it on the video
output and log it over serial. This is mostly used to check for
hardware issues and for bringup.
"""
import os
from amaranth import *
from ama... | Python | 1 |
import json
import os
import sys
from utils import get_active_monitor, read_config
CONFIG_FILE = os.path.join(os.path.expanduser("~"), ".config", "sway",
"scripts", "sway_gaps_manager", "gaps_config.json")
def cycle_modes(config):
active_monitor = get_active_monitor()
current_pro... | Python | 1 |
leBlockRecordResults {
pub fn record(&self) -> ScMutableBytes {
ScMutableBytes::new(self.proxy.root(RESULT_RECORD))
}
}
#[derive(Clone)]
pub struct ImmutableBlockRecordsResults {
pub(crate) proxy: Proxy,
}
impl ImmutableBlockRecordsResults {
pub fn count(&self) -> ScImmutableUint32 {
ScImmutableUint32::... | Rust | 0 |
ry(|p| p.accept_mac_joined_with(b'-')) {
return Ok(mac)
}
if let Some(mac) = self.try(|p| p.accept_mac_joined_with(b':')) {
return Ok(mac)
}
Err(())
}
#[cfg(feature = "proto-ipv6")]
fn accept_ipv4_mapped_ipv6_part(&mut self, parts: &mut [u16], idx: &m... | Rust | 0 |
new_value: impl Into<String>) -> &mut Self {
self.display_name = new_value.into();
self
}
pub fn email(&mut self, new_value: impl Into<String>) -> &mut Self {
self.email = Some(new_value.into());
self
}
pub fn token(&mut self, new_value: impl Into<String>) -> &mut Self ... | Rust | 0 |
from easydict import EasyDict
spaceinvaders_sqil_config = dict(
exp_name='spaceinvaders_sqil_seed0',
env=dict(
collector_env_num=8,
evaluator_env_num=8,
n_evaluator_episode=8,
stop_value=10000000000,
env_id='SpaceInvaders-v4',
#'ALE/SpaceInvaders-v5' is available... | Python | 1 |
import string
from PIL import Image
from PIL import ImageFilter
from PIL import ImageOps
from .config import Config
from .image_container import ImageContainer
from ..enums.constant import GRAY
from ..enums.constant import TRANSPARENT
from utils import append_image_by_side
from utils import concatenate_image
from uti... | Python | 1 |
Event::KeyDown {
keycode: Some(keycode),
keymod: _modifiers,
..
} => {
//log::trace!("Key Down {:?} {:?}", keycode, modifiers);
if keycode == Keycode::Escape {
return false;
}
... | Rust | 0 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# NO CHECKED-IN PROTOBUF GENCODE
# source: protos/perfetto/metrics/android/mem_metric.proto
# Protobuf Python Version: 5.27.3
'''Generated protocol buffer code.'''
from google.protobuf import descriptor as _descriptor
from google.protobu... | Python | 1 |
::FromPrimitive;
use serde::Serialize;
use std::collections::HashMap;
use std::fmt;
use crate::syscall::{Definition, Direction};
use crate::traits::{CToCall, Humanize};
use crate::value::{Value, ValueTransformer};
use crate::{Definitions, Ident, TraceOutput};
use crate::{Syscall, TraceError};
mod helpers;
mod prelude... | Rust | 0 |
ing: c_int,
}
impl Default for ibv_exp_ec_calc_init_attr
{
#[inline(always)]
fn default() -> Self
{
unsafe { zeroed() }
}
}
impl Debug for ibv_exp_ec_calc_init_attr
{
#[inline(always)]
fn fmt(&self, f: &mut Formatter) -> Result
{
write!(f, "ibv_exp_ec_calc_init_attr {{ encode_matrix: {:?} }}", self.encode_... | Rust | 0 |
externally backed Endpoint. It behaves like a
// socketpair.
pub fn NewExternal(stype: i32, queue: Queue, receiver: Arc<Receiver>, connected: Arc<ConnectedEndpoint>) -> Self {
let baseEndpoint = BaseEndpoint::New(queue, receiver, connected);
let internal = ConnectionedEndPointInternal {
... | Rust | 0 |
).unwrap();
/// run_cmd!(ls / /x >> > /tmp/f).unwrap();
/// ```
fn test_redirect_fail() {}
#[test]
fn test_buitin_stdout_redirect() {
use_builtin_cmd!(echo);
let f = "/tmp/builtin";
let msg = run_fun!(echo xx &> $f).unwrap();
assert_eq!(msg, "");
assert_eq!("xx", run_fun!(cat $f).unwrap());
run... | Rust | 0 |
struct BashRunner {
shell: String
}
impl Runner for BashRunner {
fn run_command(&mut self, command: String) {
let mut child = Command::new(String::clone(&self.shell))
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.arg("-c")
... | Rust | 0 |
import streamlit as st
import json
LIBRARY_FILE = "library.json"
def load_library():
try:
with open(LIBRARY_FILE, "r") as file:
return json.load(file)
except (FileNotFoundError, json.JSONDecodeError):
return []
def save_library(library):
with open(LIBRARY_FILE, "w") as file:
... | Python | 1 |
developer.mozilla.org/en-US/docs/Web/API/SVGMarkerElement/orientAngle)"]
#[doc = ""]
#[doc = "*This API requires the following crate features to be activated: `SvgAnimatedAngle`, `SvgMarkerElement`*"]
pub fn orient_angle(this: &SvgMarkerElement) -> SvgAnimatedAngle;
#[cfg(feature = "SvgAnimatedRect")]
... | Rust | 0 |
from functools import wraps
# 1. дефиниция на декоратора
def to_string(func):
@wraps(func)
def wrapper(*args, **kwargs):
args = [ f'{v}' for v in args]
return func(*args, **kwargs)
return wrapper
@to_string
def concat( *args, **kwargs):
'''Concatenate args with separator sep'''
s... | Python | 1 |
cpu.get_r8(R::DL), ds, si);
}
0x48 => {
// DOS 2+ - ALLOCATE MEMORY
// BX = number of paragraphs to allocate
// Return:
// CF clear if successful
// AX = segment of allocated block
... | Rust | 0 |
"""
@Author : Yuqi Liang 梁彧祺
@File : __init__.py
@Time : 08/08/2025 15:50
@Desc :
Suffix Tree Framework - exposes core indicators and utilities for sequence convergence analysis.
"""
from .system_level_indicators import (
build_suffix_tree,
compute_suffix_count,
compute_merging_factor,
com... | Python | 1 |
import sqlite3
import psycopg2
# steps for working with databases
## connect to database
## create a cursor object
## apply sql query
## commit changes to database
## close database connection
conn=sqlite3.connect("lite.db")
cur=conn.cursor()
cur. | Python | 1 |
_step() -> int:
dac_step: int = ParameterStateSingleton.get_instance().dac_step
if dac_step is None:
raise Exception('DAC_step has not been set.')
return dac_step
@staticmethod
def get_v_step() -> float:
v_step: float = ParameterStateSingleton.get_instance().v_step... | Python | 1 |
SEC_OTP_DATA64 to BSEC_OTP_DATA95 until next system-reset. Write to shadow write locked BSEC_OTP_DATA word are silently ignored. Writing to OTP word 0 shadow is always prevented.
pub mod BSEC_OTP_SWLOCK1 {
pub use super::BSEC_OTP_SWLOCK0::SWLOCK;
}
/// BSEC_OTP_SWLOCK0 is used to prevent writing to BSEC_OTP_DATA0 ... | Rust | 0 |
# -*- coding: utf-8 -*-
# Copyright 2020 Google 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 applicable law or... | Python | 1 |
urn
if self.is_panic_fn(func):
# we want to ignore panic functions
return
self.fns[func.start_ea] = func
self.fns_reached[func.start_ea] = (func, self.path.copy())
self.push_path(func_str(func))
# we go over it basic block by basic block!
cfg = get... | Python | 1 |
# 检查所有可能的跳过按钮
if False == found:
break
# 定义一个变量长度为skip_elements长度
skip_elements_length = len(skip_elements)
for selector, log_msg in skip_elements:
... | Python | 1 |
#! /usr/bin/env python
import openturns as ot
ot.TESTPREAMBLE()
# Create a KarhunenLoeveResult
mesh = ot.IntervalMesher([9]).build(ot.Interval(-1.0, 1.0))
cov1D = ot.AbsoluteExponential([1.0])
algo = ot.KarhunenLoeveP1Algorithm(mesh, cov1D, 0.0)
algo.run()
result = algo.getResult()
lifting = ot.KarhunenLoeveLifting(... | Python | 1 |
// 移除所有按钮的active类
const buttons = document.querySelectorAll('#points-page .tab-btn');
buttons.forEach(btn => btn.classList.remove('active'));
// 显示目标tab
document.getElementById(tabName + '-tab').classList.add('active');
// 添加对应... | Python | 1 |
{
Instruction::Mask(inst_mask) => mask = inst_mask,
Instruction::MemSet(inst_memset) => {
mem.insert(inst_memset.addr, mask.apply(inst_memset.val));
()
}
}
}
mem.values().sum()
}
}
#[derive(Debug, ... | Rust | 0 |
a['tree']['children'][1]['options']['cx'],
'(3+7j)')
dval = cr.problem_metadata['tree']['children'][1]['children'][4]['val']
key, val = [(k, v) for k, v in dval[0].items()][0]
self.assertTrue("Discrete_o', <class" in key)
self.assertEqual(val, [2, {'((1,), (2,))... | Python | 1 |
mock.expect_pop::<NodeT, NodeT>()
.once()
.with(eq(addrl), always())
.return_once(move |_, _| future::ok(Box::new(leafnode)).boxed());
mock.expect_repay()
.once()
.withf(|credit| *credit == 16)
.returning(mem::forget);
mock.expect_repay()
.once()
... | Rust | 0 |
admin: String,
token_addr: String,
start_time: Uint128
},
SetProjectInfo{
project_id: Uint128,
project_info: ProjectInfo
},
SetProjectConfig {
project_id: Uint128,
admin:String,
token_addr:String,
start_time: Uint128
},
... | Rust | 0 |
arr = [1, 2, None, 4, 5, None, 7]
result = [x for x in arr if x is not None]
print(result[0])
| Python | 1 |
Length of the hash to verify."]
#[doc = ""]
#[doc = " @retval CRYS_OK Signature was successfully verified."]
#[doc = " @retval CRYS_ECDSA_VERIFY_INVALID_USER_CONTEXT_PTR_ERROR p_context was NULL."]
#[doc = " @retval CRYS_ECDSA_VERIFY_USER_CONTEXT_VALIDATION_TAG_ERROR p_context was not initializ... | Rust | 0 |
def deepview_iteration_provider(model):
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate,
betas=(beta1, beta2))
def iteration(inputs, targets):
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs.view(-1,... | Python | 1 |
use regex::*;
use std::fmt;
use std::io;
use weft::*;
#[test]
fn should_render_trivial_example() {
struct TrivialExample;
// This simulates what a template of the form `<p>Hello</p>` should compile to.
impl WeftRenderable for TrivialExample {
fn render_to(&self, target: &mut impl RenderTarget) -> ... | Rust | 0 |
p) {
unsafe { ffi::blContextSetStrokeCap(self.core_mut(), pos.into(), cap.into()) };
}
#[inline]
pub fn set_stroke_start_cap(&mut self, cap: StrokeCap) {
self.set_stroke_cap(StrokeCapPosition::Start, cap)
}
#[inline]
pub fn set_stroke_end_cap(&mut self, cap: StrokeCap) {
... | Rust | 0 |
PT[\\\bbehkmbnn$)8UY`aaaggjmpsgttTYL>[_fgggmmpsvymzz6SW^___eehknqerr
diT\?\`mnnnttwz} GJt K K$)1AGdhuvvv|| @C FI PS| T TTYDOIfjwxxx~~ BE HK RU~ V VTYDOSWSc jG NX ag h h ... | Python | 1 |
$$
I_r = x \lambda \int_{d}^{\infty} \Phi(t) e^{t\lambda} \d t, \quad I_l = x \lambda \int_{d}^\infty \Phi(t) e^{-t\lambda} \d t.
$$
The last approximation is similar to [Section 3.2, Galway] and both $I_l$ and $I_r$ have a closed form solution. Unlike [Galway], we are making use of the fact that $f(u) ... | Rust | 0 |
vie..." if x == "" else x,
key="selectbox_tfidf"
)
if selected_movie and selected_movie != "":
st.session_state["active_movie_tfidf"] = selected_movie
else:
st.warning("No movies found matching your search.")
active_movie = st.... | Python | 1 |
Some(RawSelection::All),
s![..5, ..5, ..5],
Some(Selection::All),
);
check(
&[0; 6],
s![.., 0.., ..0, 0..0, ..;1, ..;2],
vec![
RawSlice::new(0, 1, Some(0), 1),
RawSlice::new(0, 1, Some(0), 1),
... | Rust | 0 |
], [-1, 4, -1], [0, -1, 0]], dtype=image.dtype, device=image.device)
# Apply to all channels at once: (H, W, 3) → (1, 3, H, W) for conv2d
image_chw = image.permute(2, 0, 1).unsqueeze(0) # (1, 3, H, W)
laplacian_3ch = laplacian.unsqueeze(0).repeat(3, 1, 1).unsqueeze(1) # (3, 1, 3, 3)
# 3-channel convolution ... | Python | 1 |
ure.clone();
} else {
*cached_texture =
Some(tools::import_bitmap(r, &image.to_rgba8(), self.size.into()).unwrap());
texture = cached_texture.as_ref().unwrap().clone();
}
frame.render_texture_at(
&texture,
... | Rust | 0 |
teValue>) -> Self {
let note_id = attr_map
.get("noteId")
.and_then(|v| v.s.clone())
.unwrap_or_default();
let user_id = attr_map
.get("userId")
.and_then(|v| v.s.clone())
.unwrap_or_default();
let notebook = attr_map
... | Rust | 0 |
import logging
import os
import pygame
# Set up logging
logging.basicConfig(level=logging.INFO)
# Color definitions
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BACKGROUND = (40, 44, 52)
GRID_COLOR = (50, 54, 62)
SNAKE_COLOR = (152, 195, 121)
FOOD_COLOR = (224, 108, 117)
SCORE_COLOR = (229, 192, 123)
GAME_OVER_COLOR = (... | Python | 1 |
import logging
import pathlib
from typing import Dict
from chia.consensus.constants import ConsensusConstants
from chia.consensus.default_constants import DEFAULT_CONSTANTS
from chia.server.outbound_message import NodeType
from chia.server.start_service import run_service
from chia.timelord.timelord import Timelord
fr... | Python | 1 |
de(requests.get(img_url, timeout=10).content)
try:
prompt_text = re.sub(r'\[CQ:.*\]', '', msg_list[1]).strip()
if not prompt_text:
return "请念咒语 (prompt 参数)"
prompt_tags = list(map(lambda x: x.strip(), re.split('[,,]', prompt_text)))
prompt_tags = filter_nsfw(prompt_tags)
... | Python | 1 |
ce("%x", &format!("{}", now));
if !format.contains("%") {
return res;
}
}
let epoch = if format.contains("%u") {
Epoch::Unix
} else {
Epoch::Gregorian
};
let calendar = if format.contains("%s") {
Calendar::Solar
} else {
Calendar::Lu... | Rust | 0 |
as u64);
let content = page.as_slice();
let ring = &self.ring;
let file = &self.file;
#[cfg(target_os = "linux")]
return {
// immediately start writing
let completion = ring.write_at(file, &content, pos);
PageWrite {
file,
... | Rust | 0 |
ut.await;
assert_matches!(result, Ok(_));
Ok(())
}
#[fasync::run_singlethreaded]
#[test]
async fn client_gets_cached_player_status() -> Result<()> {
let (mut status_sink, status_stream) = mpsc::channel(CHANNEL_BUFFER_SIZE);
let (session_control_proxy, session_control_se... | Rust | 0 |
ialize(item)
self._VolumeInfoList.append(obj)
if params.get("VolumeMountInfoList") is not None:
self._VolumeMountInfoList = []
for item in params.get("VolumeMountInfoList"):
obj = VolumeMountInfo()
obj._deserialize(item)
sel... | Python | 1 |
appears in [`xcb_protocol_request_t::opcode`], and
/// [`xcb_protocol_request_t::ext`] is [`XcbXf86dri::xcb_xf86dri_id()`], then the type of the request is
/// [`xcb_xf86dri_auth_connection_request_t`].
pub const XCB_XF86DRI_AUTH_CONNECTION: u8 = 11i32 as u8;
/// The `XF86Dri::AuthConnection` request.
#[derive(Copy, ... | Rust | 0 |
_table_test;
#[cfg(test)]
mod configs_table_test;
#[cfg(test)]
mod contributors_table_test;
#[cfg(test)]
mod credits_table_test;
#[cfg(test)]
mod databases_table_test;
#[cfg(test)]
mod functions_table_test;
#[cfg(test)]
mod metrics_table_test;
#[cfg(test)]
mod settings_table_test;
#[cfg(test)]
mod tables_table_test;
#[... | Rust | 0 |
num)
data = {
"venues": page.object_list,
"page": page,
}
return render(request, "venues.html", data)
@login_required
def restricted_page(request):
data = {
"title": "Restricted Page",
"content": "<h1>You are logged in</h1>",
}
return render(request, "general... | Python | 1 |
& 0x10 == 0x10 {
self.left = true;
self.right = false;
} else {
self.right = true;
self.left = false;
}
}
if fourth_byte == 0 {
self.scrolling_up = false;
... | Rust | 0 |
, Body<'s>>,
start: &'s str,
) -> ParentIter<'h, 's> {
ParentIter(map, Some(start))
}
fn create_bodies<'s>(orbits: &[Orbit<'s>]) -> Result<HashMap<&'s str, Body<'s>>> {
let mut bodies: HashMap<&str, Body> = HashMap::with_capacity(orbits.len());
for orbit in orbits {
match bodies.entry(... | Rust | 0 |
import wandb
from easydict import EasyDict
from accelerate import Accelerator
from GenerativeClassify.classify.improved_classify.train import train
def make_config(device):
model_type="ICFM"
method="Pretrain"
type=f"GenerativeClassifyUNet_{model_type}"
classes = 1000
image_size = 64
project_nam... | Python | 1 |
feature = "rafx-gles3"
))
))]
RafxCommandBuffer::Empty(inner) => Some(inner),
}
}
}
<reponame>tomijaga/tnb-rs
use serde::{Deserialize, Serialize};
/// Enum for Supported Node Requests
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum ChainData... | Rust | 0 |
f.width - MIN_SIZE)
new_y = min(y + self.border_width, self.height - MIN_SIZE)
new_w = max(MIN_SIZE, w - 2 * self.border_width)
new_h = max(MIN_SIZE, h - 2 * self.border_width)
if new_x + new_w > self.width:
new_x = max(0, self.width - new_w)
... | Python | 1 |
.lock().unwrap().push(self.0);
}
}
let (w, s) = deque::lifo();
let dropped = Arc::new(Mutex::new(Vec::new()));
let remaining = Arc::new(AtomicUsize::new(COUNT));
for i in 0..COUNT {
w.push(Elem(i, dropped.clone()));
}
let threads = (0..THREADS)
.map(|_| {
... | Rust | 0 |
rd::storage_prefix) {
content.parse::<keyword::storage_prefix>()?;
content.parse::<syn::Token![=]>()?;
let renamed_prefix = content.parse::<syn::LitStr>()?;
// Ensure the renamed prefix is a proper Rust identifier
syn::parse_str::<syn::Ident>(&renamed_prefix.value()).map_err(|_| {
let msg = format!(... | Rust | 0 |
e load boilerplate
for (name, resource) in resources.iter() {
// Generate custom load method declaration
let resource_type = match resource {
PipelineResource::Texture => "Texture2D",
PipelineResource::Sampler { .. } => "SamplerState",
};
result.push_str(resource_type);
result.... | Rust | 0 |
}
pub struct BasicType<'hir> {
pub id: HirId<'hir>,
pub path: &'hir Path<'hir>,
pub generics: &'hir [GenericArg<'hir>],
}
impl<'hir> HirPretty<'hir> for BasicType<'hir> {
fn pretty_print(&self, ctx: &HirContext<'hir>) -> PrettyOutput {
let Self {
id: _,
path,
generics,
} = self;
... | Rust | 0 |
bounds",
Error::NoCharmap => "no charmap loaded",
Error::Unimplemented(_) => "unimplemented: {}",
}
}
fn cause(&self) -> Option<&dyn std::error::Error> {
match self {
Error::Io(ref e) => Some(e),
_ => None,
}
}
}
<gh_stars>10-100
pub ... | Rust | 0 |
= await fetch_all_parsed(
database, Tournament, tournaments.select().where(tournaments.c.id == tournament_id)
)
if len(tournaments_fetched) < 1:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials or page is not publicly a... | Python | 1 |
# 直接使用数字
.filter(last_known_institutions={"id": inst_id_clean}))
# 添加概念过滤(如果有研究领域)
if concept_ids:
for concept_id in concept_ids:
concept_id_clean = concept_id.replace("https://openalex.org/", "")
... | Python | 1 |
((new_i-1, new_j))
if new_j != (BOARD_Y-1) and (not explored.__contains__((new_i, new_j+1))) and board[new_i, new_j+1] != 1:
explored.append((new_i, new_j+1))
queue.appendleft(board[new_i, new_j + 1])
point_queue.appendleft((new... | Python | 1 |
#Sum of elements in list
def sum_numbers(list1):
sum=0
for i in list1:
sum=sum+i
return(sum)
print(sum_numbers([5,6,7,9,10]))
| Python | 1 |
# Though -N15 is undocumented, it works with
# Absoft 8.0 on Linux
opt.append('-N15')
return opt
def get_flags_f90(self):
opt = FCompiler.get_flags_f90(self)
opt.extend(["-YCFRL=1", "-YCOM_NAMES=LCS", "-YCOM_PFX", "-YEXT_PFX",
... | Python | 1 |
#!/usr/bin/env python3
#
# Copyright (C) 2013-2019 Christoph Sommer <sommer@ccs-labs.org>
#
# Documentation for these modules is at http://veins.car2x.org/
#
# SPDX-License-Identifier: GPL-2.0-or-later
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Publ... | Python | 1 |
import test.test_support, unittest
import os, popen2, subprocess, sys
def test_isatty(label, thingy):
os_isatty = os.isatty(thingy.fileno())
thingy_isatty = thingy.isatty()
if 'in' in label: expected = stdin_isatty
elif 'out' in label: expected = stdout_isatty
elif 'err' in label: expected = stderr... | Python | 1 |
pub fn new(
region: MMapPath,
permissions: Option<&str>,
process: &'a ProcessManager,
) -> Result<MemoryModuleManager<'a>, &'a str> {
let linux_process = LinuxProcess::new(process.pid).unwrap();
match linux_process.maps().unwrap().iter().find(|&x| {
if let So... | Rust | 0 |
import pandas as pd
import tushare as ts
from datetime import datetime, timedelta
import asyncio
from tqdm import tqdm
import akshare as ak
class Getreportdata:
def __init__(self,start_date,hyppb):
self.start_date = start_date
self.df = hyppb
def get_report(self):
stock_report = ak.s... | Python | 1 |
of frame in the first trajectory
Returns:
traj1: Dict mapping each id to a list of trajectory
Raises:
"""
for id_1 in id_mapper.keys():
id_2 = id_mapper[id_1]
traj_id1 = traj1[id_1]
traj_id2 = traj2[id_2]
for data_points in traj_id2:
x, y, frame = dat... | Python | 1 |
ogger.error(f"❌ 获取角色ID失败: {e}")
# 最终备用方案
return segment_info.get('role_name', '未知角色').replace(' ', '')
async def _calculate_plot_order_for_date(self, segment_id: str, date_str: str) -> int:
"""计算指定日期在片段中的剧情顺序"""
try:
# 🆕 尝试使用生命系统数据库,如果失败则使用主数据库
try:
... | Python | 1 |
surface: None,
surface_loader: None,
physical_device: None,
device: None,
}
}
}
impl SwapchainBuilder {
pub fn instance(mut self, instance: Arc<Instance>) -> Self {
self.instance = Some(instance);
self
}
pub fn surface(mut self, surface: vk:... | Rust | 0 |
te(f"SELECT COUNT(*) FROM {test_db}.test_table")
assert result.rows[0][0] == initial_count + 1
# Insert multiple records
tx.execute(
f"""
INSERT INTO {test_db}.test_table (name, age, email) VALUES
('Mixed Test 2', 46, 'mixed2@example.... | Python | 1 |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
name: 获取信息
by: baby7
blog: https://www.baby7blog.com
annotation: 获取信息
"""
import time
import random
import requests
from lxml import etree
def get_base_info():
try:
# 输出时间戳
now_timestamp = int(time.time() * 1000)
... | Python | 1 |
confusion_matrix=ConfusionMatrixSchema(
true_positives=int(tp),
false_positives=int(fp),
true_negatives=int(tn),
false_negatives=int(fn)
),
message="Evaluation completed successfully using provided gr... | Python | 1 |
from pydantic import BaseModel
from typing import Optional, List, Dict
class QueryRequest(BaseModel):
question: str
gpt_id: Optional[str] = "default" # ← clave para selección de colección
class SourceDocument(BaseModel):
content: str
metadata: dict
class QueryResponse(BaseModel):
answer: str
... | Python | 1 |
(requires `BigInt`).
///
/// [`OpKind.NearBranch64`]: enum.OpKind.html#variant.NearBranch64
///
/// # Arguments
///
/// * `hi`: High 32 bits
#[wasm_bindgen(setter)]
#[wasm_bindgen(js_name = "nearBranch64Hi")]
#[cfg(feature = "encoder")]
#[cfg(not(feature = "bigint"))]
pub fn set_near_branch64_hi(&mut self, h... | Rust | 0 |
])
>>> def onselect(vmin, vmax):
... print(vmin, vmax)
>>> span = mwidgets.SpanSelector(ax, onselect, 'horizontal',
... props=dict(facecolor='blue', alpha=0.5))
>>> fig.show()
See also: :doc:`/gallery/widgets/span_selector`
r FNrX minspanr r1 onmove_callbackinteractiver ... | Python | 1 |
std::ptr;
use std::sync::Arc;
use tokio::sync::{oneshot, Notify};
use tokio::time::Duration;
use x11_dl::xlib;
pub struct XWrap {
pub xlib: xlib::Xlib,
pub display: *mut xlib::Display,
pub root: xlib::Window,
task_notify: Arc<Notify>,
_task_guard: oneshot::Receiver<()>,
}
impl Default for XWrap {... | Rust | 0 |
cat', 5.658252888451898e-08], ... ]
# no need to remove forbidden classes from the predictions, that will happen in infrence_lib.py
# this is also the place to preprocess the image if that need to happen
def get_classification(PIL_crop):
PIL_crop = PIL_crop.convert('RGB')
tensor_cropped = classifier.preprocess... | Python | 1 |
'block1', nn.Sequential(OrderedDict(
[('unit1', PreActBottleneck(cin=width, cout=width * 4, cmid=width))] +
[(f'unit{i:d}', PreActBottleneck(cin=width * 4, cout=width * 4, cmid=width)) for i in
range(2, block_units[0] + 1)],
))),
('block2', nn.Seq... | Python | 1 |
from latex2sympy2 import latex2sympy
import sympy as sp
import re
def replace_function_name(source_code, old_name, new_name):
"""
Replaces a specified function name with a new name in Python source code
Args:
source_code (str): Source code string
old_name (str): Original function name ... | Python | 1 |
= 'Amplitude'
THLA.manager.objects[1].attributes[5].trick_name = 'P.packing.amp'
THLA.manager.objects[1].attributes[5].config = trick.CONFIG_CYCLIC
THLA.manager.objects[1].attributes[5].subscribe = True
THLA.manager.objects[1].attributes[5].locally_owned = False
THLA.manager.objects[1].attrib... | Python | 1 |
import json
import sys
from dialogue_generator import DialogueGenerator
from config import API_CONFIG, FILE_PATHS, GENERATION_CONFIG
def main():
print("=== Skeleton-Guided Multi-turn Dialogue Generation ===")
try:
# Initialize generator
generator = DialogueGenerator(
base_url=... | Python | 1 |
::Regex;
use static_init::dynamic;
use std::collections::{HashMap, HashSet};
use std::convert::TryInto;
use std::fmt;
use std::hash::Hash;
use std::io::prelude::*;
use std::str::FromStr;
use std::thread;
const N_WORKER_THREADS: usize = 8;
/// Number of nucleobases in a sequence
const N_NUCLEOBASES: usize = 6;
const SE... | Rust | 0 |
num = 7
| Python | 1 |
import importlib.abc, importlib.util
import os.path
import zipimport
class MetaPathFinder(importlib.abc.MetaPathFinder):
def add_file(self, filename, modulename=None):
if not hasattr(self, "_registered_files"):
self._registered_files = {}
if not os.path.exists(filename):
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.