text string | label_name string | labels int64 |
|---|---|---|
# Contents of ~/my_app/streamlit_app.py
import streamlit as st
def Home():
st.markdown("# Stock Price Prediction")
st.sidebar.markdown("# Home")
def Predictions():
st.markdown("# Predictions")
st.sidebar.markdown("# Predictions")
def Trending():
st.markdown("# Trending")
st.sidebar.markdown("# T... | Python | 1 |
be avoided in some implementations,
/// such as the ones that explicitly store the column data, by giving this associated type a
/// lifetime parameter. Keep an eye on <https://github.com/rust-lang/rust/issues/44265>.
/// TODO(ARCHITECTURE): When specializing on the generic arguments of trait methods is ... | Rust | 0 |
import torch
from tqdm import tqdm
import torch.nn.functional as F
import lpips
class Evaluator(object):
def __init__(self, args, meta_args):
self.args = args
self.meta_args = meta_args
self.lpips_loss = lpips.LPIPS(net='vgg').cuda()
def evaluate(self, images, model, weighted_loss,... | Python | 1 |
#!/home/darkpaper/.conda/envs/regicide/bin/python
# type: ignore
from pwn import *
from src.test.test_config import url as tu
user_a = remote(*tu)
user_a.recv()
user_a.sendline(b"log in#a a")
user_a.recv()
user_a.sendline(b"create#2")
user_a.recv()
user_a.sendline(b"prepare#")
user_a.interactive()
| Python | 1 |
V'18.
This function takes an optic flow tensor and uses this to warp the channels of an
event voxel grid to an image. The variance of this image is the resulting loss.
:param voxel: [N x C x H x W] input voxel
:param displacement: [N x 2 x H x W] displacement map from previous flow tens... | Python | 1 |
VED_STATE_INVALID: CK_RV = 0x00000160;
pub const CKR_INFORMATION_SENSITIVE: CK_RV = 0x00000170;
pub const CKR_STATE_UNSAVEABLE: CK_RV = 0x00000180;
pub const CKR_CRYPTOKI_NOT_INITIALIZED: CK_RV = 0x00000190;
pub const CKR_CRYPTOKI_ALREADY_INITIALIZED: CK_RV = 0x00000191;
pub const CKR_MUTEX_BAD: CK_RV = 0x000001A0;
pub... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__author__ = 'AJay'
__mtime__ = '2019/6/22 0022'
"""
#多线程版本,速度有待提高
import time
from time import sleep
import requests
import threading
import queue
import random
import string
import re
from html import unescape
class ZZSpider():
def __init__(self):
sel... | Python | 1 |
pub fn load_location(ops: &mut Assembler, bus: &ExternalBus, loc: Location) {
use Location::*;
match loc {
Reg(r) => load_halfreg(ops, r),
Mem => {
dynasm!(ops
; mov di, dx
;; call_read(ops, bus)
);
}
}
}
pub fn store_location(... | Rust | 0 |
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | Python | 1 |
'\u{1D05}' | // ᴅ [LATIN LETTER SMALL CAPITAL D]
'\u{1D06}' | // ᴆ [LATIN LETTER SMALL CAPITAL ETH]
'\u{1E0A}' | // Ḋ [LATIN CAPITAL LETTER D WITH DOT ABOVE]
'\u{1E0C}' | // Ḍ [LATIN CAPITAL LETTER D WITH DOT BELOW]
'\u{1E0E}' | // Ḏ [LATIN CAPITAL LETTER D WITH LINE BELOW]
... | Rust | 0 |
# flake8: noqa: N815
from rest_framework import serializers
from cryptoarchive.kyberswaps.models import KyberswapRouteSummary
class KyberswapRouteSummarySerializer(serializers.ModelSerializer):
tokenIn = serializers.CharField(
source="token_in",
allow_null=True,
allow_blank=True,
)
... | Python | 1 |
se libraries like `python-decouple` or `python-dotenv` to load environment variables.
- For tests, mock or set environment variables temporarily within the test environment.
9. **Grouping and Marking Tests**:
- Use `@pytest.mark` decorator to mark tests (e.g., `@pytest.mark.slow`).
- This allows f... | Python | 1 |
rough a sorted list of frusta for a target volume, and find the height at that volume."""
bottom_section_volume = 0.0
if target_volume == 0.0:
return 0.0
for section, capacity in zip(sorted_well, volumetric_capacity):
section_top_height, section_volume = capacity
if target_volume == ... | Python | 1 |
platform
///
/// Prefer this over [`linked`](Self::linked) when your application can gracefully handle
/// environments that lack Vulkan support, and when the build environment might not have Vulkan
/// development packages installed (e.g. the Vulkan SDK, or Ubuntu's `libvulkan-dev`).
///
/// #... | Rust | 0 |
,
&buf[..],
&self.frame.key_mic[..],
);
ensure!(valid_mic, Error::InvalidMic);
Ok(self.frame)
}
}
pub enum KeyFrameKeyDataState<'a> {
Encrypted(EncryptedKeyData<'a>),
Unencrypted(&'a [u8]),
}
impl<'a> KeyFrameKeyDataState<'a> {
pub fn from_frame(frame: ... | Rust | 0 |
#!/usr/bin/env python3
# Copyright (c) 2019-2020 Hajo Kortmann <hajo.kortmann@gmx.de>
# License: GNU GPL v2 (see License.txt)
'''
Code for mnemonic generation for the device's secret. This code is following
the Bitcoin BIP39 standard and uses the english wordlist of Electron Cash
version 3.2.1. The last part of BIP39... | Python | 1 |
d::fmt::Display for CPLookup<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let entry = &self.0[self.2];
if let &CPEntry::Unset = entry {
write!(f, "{:?} at {} containing ", self.1, self.2)?;
return Ok(());
}
let entry_type = CPEntryKind::from(entry);
if !self.1.is(entry_typ... | Rust | 0 |
# utils/pdf.py
from django.template.loader import render_to_string
from weasyprint import HTML,CSS
from io import BytesIO
from django.conf import settings
def generate_purchase_order_pdf(po):
tax = sum(line_item.tax_amount for line_item in po.line_items.all())
discount = sum(line_item.discount for line_item in... | Python | 1 |
right);
mesh.add_colored_rect(this_rect, colour);
prev_freq = freq.freq;
last_colour = colour;
}
let top_left = to_screen * Pos2::new(x as f32 * col_width, upper_bound as f32);
let bottom_right = to_screen * P... | Rust | 0 |
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from projects.models import Projects, Modules
from django.db.models import Q
from pure_pagination import Paginator, EmptyPage, PageNotAnInteger
# Create your views here.
@login_required(l... | Python | 1 |
and word[-5:-2] != "gem"
):
word = word[:-2]
r1 = r1[:-2]
r2 = r2[:-2]
if word.endswith(("kk", "dd", "tt")):
word = word[:-1]
r1 = r1[:-1]
r2 = r2[:-1]
# STEP 3b: D... | Python | 1 |
'exponential':
start, end = dynamic_roi['dynamic_roi_start'], dynamic_roi['dynamic_roi_end']
min_roi = max(end, start * np.exp(-dynamic_roi['dynamic_roi_rate']*trade_dur))
elif dynamic_roi['dynamic_roi_type'] == 'connect':
# connect the points in the defined ... | Python | 1 |
D_COORD = {
1: (111, 197),
2: (224, 361),
3: (429, 384),
4: (545, 231),
5: (661, 311),
}
XINLAI = False
class Map20250715(HuodongMapBase):
N_slice = 1
NAME = "浪漫萨拉萨莉亚 沙漠的新娘与不可思议的神灯"
XY11 = (148, 386)
XY_VH_BOSS = (837, 299)
HARD_COORD = {
... | Python | 1 |
ICE_NOT_OPENED_FOR_ERASE = DEVICE_NOT_OPENED_FOR_ERASE,
DEVICE_NOT_OPENED_FOR_WRITE = DEVICE_NOT_OPENED_FOR_WRITE,
FAILED_TO_WRITE_DEVICE = FAILED_TO_WRITE_DEVICE,
EEPROM_READ_FAILED = EEPROM_READ_FAILED,
EEPROM_WRITE_FAILED = EEPROM_WRITE_FAILED,
EEPROM_ERASE_FAILED = EEPROM_ERASE_FAILED,
EEPRO... | Rust | 0 |
nst EPOLLOUT: u64 = 0x4;
pub const EPOLLPRI: u64 = 0x2;
pub const EPOLLRDBAND: u64 = 0x80;
pub const EPOLLRDHUP: u64 = 0x2000;
pub const EPOLLRDNORM: u64 = 0x40;
pub const EPOLLWRBAND: u64 = 0x200;
pub const EPOLLWRNORM: u64 = 0x100;
pub const EPOLL_CLOEXEC: u64 = 0x80000;
pub const EPOL... | Rust | 0 |
eature(enable = "simd128")]
#[inline]
pub unsafe fn simd_blend_i8(a: Simd, b: Simd, mask: Simd) -> Simd { v128_bitselect(b, a, mask) }
#[target_feature(enable = "simd128")]
#[inline]
pub unsafe fn simd_load(ptr: *const Simd) -> Simd { v128_load(ptr) }
#[target_feature(enable = "simd128")]
#[inline]
pub unsafe fn simd... | Rust | 0 |
},
|step_id: &StepId| {
check_fail(fail_on_exit, step_id, &mut failed_exit)
},
step_store);
// handle result
match next {
Ok(step_id_opt) => {
if let Some(step_id) = step_id_opt {
if step_id != *expected_child {
break;
... | Rust | 0 |
import json
import pytest
from django.urls import reverse
from django_scopes import scopes_disabled
from pytest_factoryboy import LazyFixture, register
from cookbook.tests.factories import FoodFactory, KeywordFactory, UnitFactory
RECIPE_URL = 'api:recipe-detail'
FOOD_URL = 'api:food-detail'
register(FoodFactory, 'f... | Python | 1 |
: completion_time,
}
dataset = Dataset.from_dict(data)
from ragas import evaluate
from ragas.metrics import (
faithfulness,
answer_relevancy,
context_recall,
context_precision,
context_relevancy,
context_entity_rec... | Python | 1 |
Tensor(s)
return tokens
def sort_all(batch, lens):
""" Sort all fields by descending order of lens, and return the original indices. """
unsorted_all = [lens] + [range(len(lens))] + list(batch)
sorted_all = [list(t) for t in zip(*sorted(zip(*unsorted_all), reverse=True))]
return sorted_all[2:], sor... | Python | 1 |
from flask import Flask,request, abort, render_template_string, jsonify
from google import genai
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
from linebot.models import *
import os
# from dotenv import load_dotenv
# load_dotenv()
app = Flask(__name__)
client = ge... | Python | 1 |
MAX_VAL: u8 = 13;
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum Suit {
Heart,
Diamond,
Club,
Spade
}
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub enum Card {
RegularCard(Suit, u8),
Joker
}
fn suit_to_int(suit: Suit) -> u8 {
match suit {
Heart => 1,
Club ... | Rust | 0 |
# Generated by Django 5.1.1 on 2024-11-01 02:13
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('modulo_clientes', '0002_cliente__foto'),
('modulo_evento', '0028_delete_cliente'),
('modulo_stock', '0009_re... | Python | 1 |
elf {
Self::Get(cmd) => cmd,
Self::Set(cmd) => cmd,
Self::SetHerb(cmd) => cmd,
}
}
}
/// Get and set configuration values.
#[derive(Debug, StructOpt)]
pub struct ConfigCommand {
#[structopt(subcommand)]
pub cmd: ConfigCommandType,
}
impl Command for ConfigComman... | Rust | 0 |
查询用户列表
"""
return self._db.query(CONFIGUSERS).all()
def is_user_exists(self, name):
"""
判断用户是否存在
"""
if not name:
return False
count = self._db.query(CONFIGUSERS).filter(CONFIGUSERS.NAME == name).count()
if count > 0:
retu... | Python | 1 |
ght + tf.maximum(crop_height - image_height, 0)
target_width = image_width + tf.maximum(crop_width - image_width, 0)
# Pad image with mean pixel value.
mean_pixel = tf.reshape(
feature_extractor.mean_pixel(model_variant), [1, 1, 3])
processed_image = preprocess_utils.pad_to_bounding_box(
processed_... | Python | 1 |
sion": [
7,
2
],
"svn_revision": "5155",
"platform_info": "x86_64-linux-5.14.0-503.11.1.el9_5.x86_64",
"build_info": "(local build)",
"argv": [
"smartctl",
"-H",
"-d",
"scsi",
"/dev/sdb",
"-j"
],
"exit_status": 0
},
"device": {
"name": ... | Python | 1 |
mem,
)
.map_err(Error::VhostNetDeviceNew)?;
Box::new(dev) as Box<dyn VirtioDevice>
} else {
let dev = virtio::Net::<Tap>::new(features, host_ip, netmask, mac_address, vq_pairs)
.map_err(Error::NetDeviceNew)?;
Box::new(dev) as Box<dyn VirtioDevice>
};
... | Rust | 0 |
s_samples
num_neg_samples = min(num_neg_samples, neg_inds.size(0))
topk_loss_cls_neg, _ = loss_cls_all[neg_inds].topk(num_neg_samples)
loss_cls_pos = loss_cls_all[pos_inds].sum()
loss_cls_neg = topk_loss_cls_neg.sum()
loss_cls = (loss_cls_pos + loss_cls_neg) / avg_factor
... | Python | 1 |
y2 += roi_y_large
cv2.rectangle(undistorted_frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
# Draw the label and confidence
text = f'{label} {confidence:.2f}'
... | Python | 1 |
2 = (plane_org.as_ptr() as usize).trailing_zeros() as usize;
// The largest unaligned-safe function is for 8x8
let ptr_align = 1 << ptr_align_log2.max(3);
let mut sum = 0 as u32;
let org_stride = (plane_org.plane.cfg.stride * mem::size_of::<T>()) as libc::ptrdiff_t;
let ref_stride = (plane_ref.plane... | Rust | 0 |
s.data_test[0], args.scale[0], psnrs.mean(axis=0)[0]))
print('Mean ssim of %s x%s is %.4f' % (args.data_test[0], args.scale[0], ssims.mean(axis=0)[0]))
return np.mean(psnrs)
if __name__ == '__main__':
device_id = int(os.getenv('DEVICE_ID', '0'))
# context.set_context(mode=context.GRAPH_MODE, device_tar... | Python | 1 |
bot_procs[proc.pid] = (proc, room_url)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to start subprocess: {e}")
return RedirectResponse(room_url)
@app.post("/connect")
async def rtvi_connect(request: Request) -> Dict[Any, Any]:
"""RTVI connect endpoint that cre... | Python | 1 |
s for more details
pub fn reward_funds(origin, to_reward: T::AccountId, reward: BalanceOf<T>) {
let _ = ensure_signed(origin)?;
let mut total_imbalance = <PositiveImbalanceOf<T>>::zero();
let r = T::Currency::deposit_into_existing(&to_reward, reward).ok();
total... | Rust | 0 |
.unwrap()).clone());
}
}
// Border
let apply_border = match get_attribute(e, b"applyBorder") {
Some(v) if v == "1" => true,
Some(_) => false,
None => apply_defalut.clone()
};
if apply_border {
let id = get_attribute(e, b"borderId").unwrap().parse::<usize>().u... | Rust | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: 闲欢
"""
import numpy as np
print(np.char.center('argsort() 函数', 15, '*'))
a = np.array([3, 4, 2])
print("初始数组:")
print(a)
print('\n')
print(np.char.center('调用 argsort() 函数', 15, '*'))
b = np.argsort(a)
print(b)
print('\n')
print(np.char.center('以排序后的顺序重构原数组... | Python | 1 |
let res = unsafe {
let out_opts_ptr = output_options.out_opts.as_ptr();
nvttSetOutputOptionsErrorHandler(out_opts_ptr, Some(err_callback));
if !output_options.write_to_file {
nvttSetOutputOptionsOutputHandler(
out_opts_ptr,
... | Rust | 0 |
VkStencilOp_VK_STENCIL_OP_INCREMENT_AND_CLAMP: VkStencilOp = 3;
pub const VkStencilOp_VK_STENCIL_OP_DECREMENT_AND_CLAMP: VkStencilOp = 4;
pub const VkStencilOp_VK_STENCIL_OP_INVERT: VkStencilOp = 5;
pub const VkStencilOp_VK_STENCIL_OP_INCREMENT_AND_WRAP: VkStencilOp = 6;
pub const VkStencilOp_VK_STENCIL_OP_DECREMENT_A... | Rust | 0 |
def Bellman_Ford_matrix(W, s):
n = W.shape[0]
d = [float("Inf")] * n
p = [None] * n
d[s - 1] = 0
for k in range(1, n):
for i in range(1, n + 1):
for j in range(1, n + 1):
if d[j - 1] > d[i - 1] + W[i - 1, j - 1]:
d[j - 1] = d[i - 1] + W[i - 1,... | Python | 1 |
ait?)?;
let variants1 = parse_variants(&group1.variants)?;
let variants2 = parse_variants(&group2.variants)?;
let indices = find_common_sorted(&variants1, &variants2);
let n_variants1 = variants1.len();
let n_variants2 = variants2.len();
if config.dry {
println!("{} variants in dataset {... | Rust | 0 |
def is_valid(board, row, col):
now = board[row][col]
for i in range(9):
# row
if now == board[row][i]:
if col == i: continue
return False
# col
if now == board[i][col]:
if row == i: continue
return False
# Grid
bigRow = row ... | Python | 1 |
from datetime import datetime
from enum import Enum
from uuid import UUID
from typing import List, Optional
from pydantic import BaseModel, Field
from app.schemas.folders import FolderInfo
class WorkspaceBase(BaseModel):
name: str = Field(..., min_length=1, max_length=100)
class CreateWorkspaceRequest(Workspace... | Python | 1 |
ys_back)
# 獲取系統日誌
logs = monitoring_service.get_system_logs(
level=log_level if log_level else None,
module=module_filter if module_filter else None,
start_date=start_date,
end_date=end_date,
keyword=keyword if keyword else None,
l... | Python | 1 |
nder = TpuRotationSender;
pub type TvuRotationReceiver = TpuRotationReceiver;
pub struct Tvu {
fetch_stage: BlobFetchStage,
retransmit_stage: RetransmitStage,
replay_stage: ReplayStage,
entry_stream_stage: Option<EntryStreamStage>,
storage_stage: StorageStage,
exit: Arc<AtomicBool>,
last_en... | Rust | 0 |
}
// Get transform
let transform = path.transform;
let mut pathops = vec![];
for subpath in path.data.subpaths() {
for segment in subpath.0 {
match *segment {
PathSe... | Rust | 0 |
"""
Tests for management command for enabling commerce configuration.
"""
from django.core.management import call_command
from django.test import TestCase
from ....models import CommerceConfiguration
class TestCommerceConfigurationCommand(TestCase):
"""
Test django management command for enabling commerce ... | Python | 1 |
# This is an example test settings file for use with the Django test suite.
#
# The 'sqlite3' backend requires only the ENGINE setting (an in-
# memory database will be used). All other backends will require a
# NAME and potentially authentication information. See the
# following section in the docs for more informatio... | Python | 1 |
::std::io::ErrorKind::NotFound => (),")?;
writeln!(output, " Err(err) => return Err(err),")?;
writeln!(output, " }}")?;
writeln!(output, " }}")?;
writeln!(output)?;
writeln!(output, " config.merge_env()?;")?;
writeln!(output, " let remaining_args =... | Rust | 0 |
ependencies).
fn try_collect(&self, last_changed: Revision, revision_now: Revision) -> bool {
let accessed_at = self.accessed_at.load().unwrap();
if accessed_at < last_changed {
match self.accessed_at.compare_exchange(Some(accessed_at), None) {
Ok(_) => true,
... | Rust | 0 |
: &Workspace, data: &Workspace, env: &Env) {
self.selected_glyph.update(ctx, data, env);
}
fn layout(
&mut self,
ctx: &mut LayoutCtx,
bc: &BoxConstraints,
data: &Workspace,
env: &Env,
) -> Size {
let child_size = self.selected_glyph.layout(ctx, bc, da... | Rust | 0 |
_u32);
assert_eq!(v, v.xy());
assert_eq!(v.xxxx(), uvec4(1_u32, 1_u32, 1_u32, 1_u32));
assert_eq!(v.xxxy(), uvec4(1_u32, 1_u32, 1_u32, 2_u32));
assert_eq!(v.xxyx(), uvec4(1_u32, 1_u32, 2_u32, 1_u32));
assert_eq!(v.xxyy(), uvec4(1_u32, 1_u32, 2_u32, 2_u32));
assert_eq!(v.xyxx(), uvec4(1_u32, 2_u3... | Rust | 0 |
TATIC_FILES: Dir = include_dir!("static");
/// Markdown preview server.
///
/// Listens for HTTP connections and serves a page containing a live markdown preview. The page
/// contains JavaScript to open a websocket connection back to the server for rendering updates.
#[derive(Debug)]
pub struct Server {
addr: Soc... | Rust | 0 |
::{self, Display, Formatter};
use crate::{u6, Unsigned6Bit};
#[derive(Debug, Clone, Copy)]
pub struct NoSubscriptKnown(char);
impl Display for NoSubscriptKnown {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
write!(
f,
"no subscript mapping is yet implemented fo... | Rust | 0 |
# This file was auto-generated by Fern from our API Definition.
import typing
import pydantic
from ..core.pydantic_utilities import IS_PYDANTIC_V2
from ..core.unchecked_base_model import UncheckedBaseModel
class TipSettings(UncheckedBaseModel):
allow_tipping: typing.Optional[bool] = pydantic.Field(default=None)... | Python | 1 |
import numpy as np
import pytest
from pandas import Series
import pandas._testing as tm
def test_mask():
# compare with tested results in test_where
s = Series(np.random.default_rng(2).standard_normal(5))
cond = s > 0
rs = s.where(~cond, np.nan)
tm.assert_series_equal(rs, s.mask(cond))
rs =... | Python | 1 |
import time
from ctypes import POINTER, c_ulong, Structure, c_ushort, c_short, c_long, byref, windll, pointer, sizeof, Union
SendInput = windll.user32.SendInput
PUL = POINTER(c_ulong)
class KeyBdInput(Structure):
_fields_ = [("wVk", c_ushort), ("wScan", c_ushort), ("dwFlags", c_ulong),
("time", c... | Python | 1 |
(Some(info))
} else {
Ok(None)
}
}
fn get_git_revision(&self) -> Option<String> {
let VcsInfoJsonGit::Sha1(ref s) = self.git;
Some(s.to_string())
}
}
pub fn vcs_info_to_revision_string(vcs: Option<VcsInfoJson>) -> String {
vcs.and_then(|vcs| vcs.get_git_revis... | Rust | 0 |