text string | label_name string | labels int64 |
|---|---|---|
rt.ht}, d = {start.d}, next = {start.next.data if start.next else None}")
self._show(start.right)
def show(self):
print()
self._show(self.root)
def example1():
t = BinarySearchTree()
l = [2, 6, 8, 0, 9, 9, 7]
for i in l:
t.insert(i)
t.show()
t.delete(8)
... | Python | 1 |
import pandas as pd
# 文件路径常量定义
# 你需要更改为你自己的正确路径
INPUT_FILE = '成绩表.csv'
OUTPUT_FILE = '成绩表-历史均分.csv'
# 读取CSV文件,并处理空值
print(f"正在读取{INPUT_FILE}...")
df = pd.read_csv(INPUT_FILE).fillna(0)
print(f"成功读取 {len(df)} 条成绩记录")
df['学分'] = pd.to_numeric(df['学分'], errors='coerce').fillna(0)
df['最终成绩'] = pd.to_numeric(df['最终成绩'],... | Python | 1 |
ining,
* EmitEvent, */
}
pub type BuiltinFunction = Spanned<BuiltinFunction_>;
#[derive(Debug, PartialEq)]
#[allow(clippy::large_enum_variant)]
pub enum Exp_ {
Value(Value),
Move(Var),
Copy(Var),
Use(Var),
ModuleCall(ModuleIdent, FunctionName, Option<Vec<BaseType>>, Box<Exp>),
MethodCall(... | Rust | 0 |
.1]);
let out: [f64; 2] = cast(a.floor_rhs0(a));
assert_eq!(out, [5.0_f64, -1.1]);
}
#[test]
fn m128i_cmp_eq_i64() {
let ai: m128i = cast([core::i64::MAX, core::i64::MIN]);
let bi: m128i = cast([core::i64::MAX, 3]);
let out: [i64; 2] = cast(ai.cmp_eq_i64(bi));
assert_eq!(out, [-1, 0]);
}
#[test]
fn m128i_... | Rust | 0 |
import torch
from torch import distributed as dist
from torch.utils import data
def get_rank():
if not dist.is_available() or not dist.is_initialized():
return 0
return dist.get_rank()
def synchronize():
if not dist.is_available() or not dist.is_initialized() or dist.get_world_size() == 1:
... | Python | 1 |
C>;
#[doc = "PWM Comparator Register 4"]
pub mod pwm_cmpdat4;
#[doc = "PWM_CMPDAT5 register accessor: an alias for `Reg<PWM_CMPDAT5_SPEC>`"]
pub type PWM_CMPDAT5 = crate::Reg<pwm_cmpdat5::PWM_CMPDAT5_SPEC>;
#[doc = "PWM Comparator Register 5"]
pub mod pwm_cmpdat5;
#[doc = "PWM_DTCTL0_1 register accessor: an alias for `... | Rust | 0 |
class Solution:
def thirdMax(self, nums: List[int]) -> int:
# First we will convert nums into set
new = set(nums)
# Checking some conditions if len of nums is less than three it means 1,2 will be present only so, in this case we will return maximum number which is 2
if len(new) < 3:
... | Python | 1 |
Ok(valid_n)
);
let long = zero_vec(1025);
let long_n = a.new_atom(&long).unwrap();
assert_eq!(
sanitize_announce_msg(&a, long_n, ErrorCode::InvalidCondition),
Err(ValidationErr(long_n, ErrorCode::InvalidCondition))
);
let pair = a.new_pair(valid_n, long_n).unwrap();
... | Rust | 0 |
, SmbusSize::Byte, None)
}
pub fn smbus_read_byte(fd: c_int, command: u8) -> Result<u8> {
let mut buffer = SmbusBuffer::new();
smbus_request(
fd,
SmbusReadWrite::Read,
command,
SmbusSize::ByteData,
Some(&mut buffer),
)?;
Ok(buffer.data[0])
}
pub fn smbus_read_w... | Rust | 0 |
as np
import matplotlib.pyplot as plt
from skimage.measure import label, regionprops
import pandas as pd
def process_data(data):
labels = label(data, connectivity=2)
props = regionprops(labels)
diameters = []
for prop in props:
if prop.area > 10: # Area th... | Python | 1 |
let mut out = _mm_mul_ps(a, b);
// 0 1 2 3 -> 1 1 3 3
let hi = _mm_movehdup_ps(out);
// 0 1 2 3 + 1 1 3 3 -> (0 + 1, 1 + 1, 2 + 3, 3 + 3)
let sum = _mm_add_ps(hi, out);
// unpacklo: 0 0 1 1
out = _mm_add_ps(sum, _mm_unpacklo_ps(out, out));
// (1 + 2 + 3, _... | Rust | 0 |
c_void { self.as_raw_mut() }
}
impl crate::cudacodec::RawVideoSourceConst for PtrOfRawVideoSource {
#[inline] fn as_raw_RawVideoSource(&self) -> *const c_void { self.inner_as_raw() }
}
impl crate::cudacodec::RawVideoSource for PtrOfRawVideoSource {
#[inline] fn as_raw_mut_RawVideoSource(&mut self) -> *mut ... | Rust | 0 |
= get_p(xx + 1) + yy;
let ba = get_p(b) + zz;
let bb = get_p(b + 1) + zz;
lerp(w,
lerp(v,
lerp(u, grad(get_p(aa), x, y, z), grad(get_p(ba), x - 1.0, y, z)),
lerp(u, grad(get_p(ab), x, y - 1.0, z), grad(get_p(bb), x - 1.0, y - 1.0, z))),
lerp(v,
l... | Rust | 0 |
from sparkai.embedding.spark_embedding import Embeddingmodel, SparkEmbeddingFunction
import chromadb
import os
try:
from dotenv import load_dotenv
except ImportError:
raise RuntimeError(
'Python environment for SPARK AI is not completely set up: required package "python-dotenv" is missing.') from None
... | Python | 1 |
}
}
/// A type to represent iteration through all the elements (zeros and explicit non-zeros) of a
/// `CsMatrix`.
///
/// As an iterator yields `(major_index, minor_index, value)` as `(usize, usize, SparseEntry<'_,
/// T>)`, for every index. Note that for most matrices you probably don't want this, since this
///... | Rust | 0 |
sets[n,4]:(offsets[n,5]-1),:] = resized_images[offsets[n,6]:(offsets[n,7]-1+offsets[n,6]),offsets[n,8]:(offsets[n,9]+offsets[n,8]-1),:]
self.make_mp4(org_image,name)
def make_mp4(self,images,name):
num = images.shape[0]
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
output_movie = cv2.Vid... | Python | 1 |
backRetaining,
};
tr.put_u32(op as u32);
tr.put_u32(tr_handle);
tr.freeze()
}
/// Execute immediate request
pub fn exec_immediate(
tr_handle: u32,
dialect: u32,
sql: &str,
charset: &Charset,
) -> Result<Bytes, FbError> {
let bytes = charset.encode(sql)?;
let mut req = BytesMut... | Rust | 0 |
.get_precommit(2));
let pc3 = new_pre_commit_on_chain(3, make_sealed_cid("2".as_bytes()), TokenAmount::from(1), 1);
let pc4 = new_pre_commit_on_chain(4, make_sealed_cid("2".as_bytes()), TokenAmount::from(1), 1);
h.put_precommitted_sectors(vec![pc3.clone(), pc4.clone()]).unwrap();
assert_eq!(pc3, h.get_... | Rust | 0 |
mp('loc_2C4')
def _loc_2BD(): pass
label('loc_2BD')
OP_6F(0x0000, 60)
def _loc_2C4(): pass
label('loc_2C4')
If(
(
(Expr.TestScenaFlags, ScenaFlag(0x02A6, 2, 0x1532)),
Expr.Ez,
Expr.Return,
),
'loc_2D6',
)
OP_6F(0x0001, 0)... | Python | 1 |
}
impl<AccountId, AssetId, Balance: Zero + PartialOrd + SafeMul, BlockNumber: Zero>
BondOffer<AccountId, AssetId, Balance, BlockNumber>
{
/// An offer is completed once all it's nb_of_bonds has been sold.
pub fn completed(&self) -> bool {
self.nb_of_bonds.is_zero()
}
/// The total price of the offer, which is t... | Rust | 0 |
gs but also vector types with the same editing properties
//! * It supports attaching attributes to regions in the rope. This makes it suitable
//! for tasks like representing text with attached formatting information.
//! * It supplies a 'push' and 'pull' model for mirroring changes to a rope elsewhere.
//! (f... | Rust | 0 |
86);
assert_cash(b.discounted_sum_from_base(d + 800), 4.031044985042786);
assert_cash(b.discounted_sum(d + 28, d + 210), 0.9562351685379344);
}
fn create_sample_divstream() -> DividendStream {
// Early divs are purely cash. Later ones are mixed cash/relative
let d = Date::from... | Rust | 0 |
/// Reads an unsigned 16-bit integer at an offset.
#[inline]
fn read_u16_at<T: ByteOrder>(&self, pos: u64) -> io::Result<u16> {
let mut buf = [0; 2];
self.read_exact_at(pos, &mut buf)?;
Ok(T::read_u16(&buf))
}
/// Reads a signed 16-bit integer at an offset.
#[inline]
fn ... | Rust | 0 |
nal da cópia. Imprima ambas as listas para
verificar que a original não foi modificada.
2.3. Transforme a string resultante da junção das palavras em uma lista, utilizando o espaço como separador. Imprima a
nova lista.
"""
palavras = ['Python', 'é', 'uma', 'linguagem', 'poderosa']
# 1
palavras_str = ' '.join(palav... | Python | 1 |
from __future__ import division, unicode_literals
from re import sub, split
from django.conf import settings
from django.utils.timezone import now
def order_by_score(queryset, score_fields, date_field, reverse=True):
"""
Take some queryset (links or comments) and order them by score,
which is basically ... | Python | 1 |
务
schedule.clear()
for tid in _SCHEDULED_TASKS:
_SCHEDULED_TASKS[tid]["status"] = "stopped"
return "⏹️ 已停止所有定时任务", get_current_tasks()
except Exception as e:
error = f"❌ 停止定时任务失败: {e}"
print(error)
return error, get_current_tasks()
# ===... | Python | 1 |
static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT;
descriptor.get(|| {
let mut fields = ::std::vec::Vec::new();
fields.push(::protobuf::reflect::accessor::make_option_accessor::<_, ::protobuf::types::ProtobufTypeUint32>(... | Rust | 0 |
HIGH,
}
impl PAD13STRNGR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value... | Rust | 0 |
;
use crate::typelevel::{Is, NoneT, Sealed};
//=============================================================================
// Pad configuration
//=============================================================================
/// Configure the `DIPO` and `DOPO` fields based on a set of [`Pads`]
///
/// The `spi` modu... | Rust | 0 |
"CAP": (
conv2d_capsule_nhwijc,
[
# all conv2d capsule layers in matrix capsules withemrouting (ICLR 2018)
(1, 16, 16, 32, 32, 3, 2, 1),
(1, 8, 8, 32, 32, 3, 1, 1),
(1, 16, 16, 8, 16, 3, 2, 1),
(1, 8, 8, 16, 16, 3, 1, 1),
],
),
... | Python | 1 |
#!/usr/bin/env python
# Copyright (C) 2006-2021 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation (FSF), e... | Python | 1 |
def preprocess_train(examples):
all_pixel_values = []
images = [Image.open(io.BytesIO(im_bytes)).convert('RGB') for im_bytes in
examples['jpg_0']]
original_sizes = [(image.height, image.width) for image in images]
crop_top_lefts = []
for col_name in ['jpg_0', 'jpg_1']:
images = [Imag... | Python | 1 |
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub(crate) enum LoginFinalization {
$($(#[$attr])? $cipher_suite(opaque_ke::CredentialFinalization<$cipher_suite>),)+
}
};
}
cipher_suite!(
[Ristretto255Sha2Argon2, RistrettoPoint, RistrettoPoint, Sha512, Argon2<'static>],
#[cfg(feature ... | Rust | 0 |
println!("We are connected to the BLE peripheral");
peripheral.discover_services().await.unwrap();
println!("We have discovered services");
for characteristic in peripheral.characteristics() {
// Subscribe to all characteristics that are readable and notify.
println!(
"Looki... | Rust | 0 |
def CloseViewPresets():
op.LM.store('VIEW_PRESET_CONTROLS', 0)
op.PRESET_CONTROLS_VIEW.op('window').par.winclose.pulse()
op.PRESET_CONTROLS_VIEW.par.display = 0
def InitClipLanes():
op.CLIP_LANES_UI.store('PrevPlugin', tdu.Dependency(op.NO_CLIP.op('plugin')))
curSelClip = op.CLIP_LANES_UI.fetch('CurSelClip')
... | Python | 1 |
Cookie
#[get("/some/url/308")]
async fn new_visitor() -> impl Responder {
HttpResponse::PermanentRedirect()
.append_header((
"location",
format!(
"/some/url/308={}",
// Generate unique address to redirect to
random_string::generate(16,... | Rust | 0 |
a=[35,6,8,34,99,100]
largest=0
second=0
for i in a:
if i>largest:
second=largest
largest=i
elif i>second and i!=largest:
second=i
print(second)
| Python | 1 |
"""
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import torch
import torch.nn.functional as F
class Act(torch.nn.Module):
def __init__(self, act, slope=0.05):
super(Act, self).... | Python | 1 |
node.info(policy.base_policy.timeout, &[&cmd])?;
for v in response.values() {
if v.to_uppercase() == "OK" {
return Ok(());
} else if v.starts_with("FAIL:") {
let result = v.split(':').skip(1).next().unwrap().parse::<u8>()?;
bail!(ErrorKin... | Rust | 0 |
_8 = 8,
#[doc = "9: Sample interrupt input once per 2*256 clocks"]
_9 = 9,
#[doc = "10: Sample interrupt input once per 4*256 clocks"]
_10 = 10,
#[doc = "11: Sample interrupt input once per 8*256 clocks"]
_11 = 11,
#[doc = "12: Sample interrupt input once per 16*256 clocks"]
_12 = 12,
... | Rust | 0 |
import requests,re,json,base64,execjs
from urllib import request
from gap import *
from track import *
with open('shumei.js', 'r', encoding='utf-8') as f:
js = execjs.compile(f.read())
def get_image(organization):
url = 'https://captcha1.fengkongcloud.cn/ca/v1/register'
params = {
"organization": or... | Python | 1 |
OpenMlsRustCrypto::default();
//!
//! let credential_bundle = CredentialBundle::new(
//! b"Sasha".to_vec(),
//! CredentialType::Basic,
//! SignatureScheme::from(ciphersuite),
//! &backend,
//! )
//! .expect("Error creating credential.");
//! let key_package_bundle =
//! KeyPackageBundle::new(&[ciph... | Rust | 0 |
err
);
};
// Header length too short.
p(a.as_mut()).set_header_len_rsvd_ns(OPTIONS_OFFSET.checked_sub(1).unwrap(), false);
look_for_error(a.as_ref(), Error::HeaderLen);
// Header length too large.
p(a.as_mut()).set_header_len_rsvd_ns(MAX_HEADER_LEN.... | Rust | 0 |
MUTE_0W)>::XMVectorPermute(R0, V1);
M.r[3] = g_XMIdentityR3.v;
return M;
}
#[cfg(_XM_SSE_INTRINSICS_)]
unsafe {
// PERFORMANCE: static const
const Constant1110: XMVECTORF32 = XMVECTORF32 { f: [ 1.0, 1.0, 1.0, 0.0 ] };
let Q0: XMVECTOR = _mm_add_ps(Quaternion, Quater... | Rust | 0 |
import json
import matplotlib.pyplot as plt
import numpy as np
from pathlib import Path # For easier path manipulation, especially for dummy file cleanup
# --- 1. 定义您的JSON文件路径 ---
# !!! 重要: 请将这里的示例路径替换为您真实的JSON文件路径 !!!
json_file_paths = [
"/Users/lightman/Code/Github/Code/MachineLearning/New_Epoch/ml_visualizatio... | Python | 1 |
32_UI_Input_Ime'*"]
pub const FEID_KOREAN: u32 = 6u32;
#[doc = "*Required features: 'Win32_UI_Input_Ime'*"]
pub const FEID_KOREAN_JOHAB: u32 = 7u32;
#[doc = "*Required features: 'Win32_UI_Input_Ime'*"]
pub const FEID_NONE: u32 = 0u32;
#[doc = "*Required features: 'Win32_UI_Input_Ime'*"]
pub const FELANG_CLMN_FIXD: u32 ... | Rust | 0 |
self.next_id;
self.next_id += 1;
id
}
}
/*
* Copyright 2020 Nuclei Studio OÜ
*
* 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... | Rust | 0 |
)?;
v.serialize(&mut *self)?;
}
Ok(())
}
None => {
self.write_code(codes::MAP)?;
self.begin_closed_list()?;
for (k,v) in iter {
k.serialize(&mut *self)?;
v.... | Rust | 0 |
import pandas as pd
import streamlit as st
import plotly.express as px
import re
# Carregar o dataset
df = pd.read_csv('winemag-data-130k-v2.csv')
# Função para extrair o ano do título ou descrição
def extract_year(title):
match = re.search(r'\b(19|20)\d{2}\b', title)
return int(match.group(0)) if match else ... | Python | 1 |
#[derive(Default, Debug)]
struct Backoff(u32, Duration);
impl Backoff {
pub fn new(delay: Duration) -> Self {
Backoff(0, delay)
}
pub fn next_delay(&mut self) -> Duration {
self.0 += 1;
self.0 * self.1
}
}
pub struct Bootstrapper {
config: BootstrapConfig,
peer_id: Peer... | Rust | 0 |
# Copyright Materialize, Inc. and contributors. All rights reserved.
#
# Use of this software is governed by the Business Source License
# included in the LICENSE file at the root of this repository.
#
# As of the Change Date specified in that file, in accordance with
# the Business Source License, use of this software... | Python | 1 |
3].into_boxed_slice());
assert_eq!(packet, Some(vec![1, 2, 3].into_boxed_slice()));
let packets: Vec<Box<[u8]>> = channel.iter_mut().collect();
assert!(packets.is_empty());
if sequencing_index < SequencingIndex::MAX - SequencingIndex::from_masked_u32(500) {
... | Rust | 0 |
["openvino_tensorflow_lite_frontend"])
openvino_runtime.requires.extend(["flatbuffers::flatbuffers"])
if self.options.enable_tf_frontend or self.options.enable_tf_lite_frontend:
openvino_runtime.libs.extend(["openvino_tensorflow_common"])
if self.options.enable_pa... | Python | 1 |
SeatLocation {
row: 70,
column: 7,
id: 567
}
);
}
#[test]
fn parse_example_seat_2() {
let seat_info = "FFFBBBFRRR";
let seat = SeatLocation::parse(seat_info).unwrap();
assert_eq!(
seat,
... | Rust | 0 |
x03H\x04\xa9\x01\x0d \x12\x90\x05 \x12\x90\x09H\
\x02\x80\x0a@%\x00\x14\x80JC\x0a\x00)\x0c(\x00\
\xa0\x02\x80\x0a\x00(\x00\xa0\x02\x80\x0a\x00(\x00\xa0\x02\
\x80\x0a\x00(\x00\xa0\x02\x80\x0a\x00)\x80\xb4\x08)\x88\
Z`\x14\xc0Z`-0\x14\x1a\xa0\x14S\xb8\x0a*\
\x80p5I\x80\xb9\xaaL\x05\x06\xaa\xe2\x1c\x0dU\xc0\
Pj\xb9\x80p5\... | Python | 1 |
"""advisory areas
Revision ID: 17b1c787f420
Revises: 62d35d76e1bf
Create Date: 2022-08-31 22:46:45.138215
"""
from alembic import op
import sqlalchemy as sa
import geoalchemy2
# revision identifiers, used by Alembic.
revision = '17b1c787f420'
down_revision = '62d35d76e1bf'
branch_labels = None
depends_on = None
d... | Python | 1 |
#region Modules
#region Sys modules
import sys
sys.path.insert(0, ".")
#endregion
#region User defined modules
from commons.utils import FolderConfig
#endregion
#region Spark modules
from pyspark import SparkConf
from pyspark.sql import SparkSession
import pyspark.sql.functions as F
#endregion
#endregion
if __name__... | Python | 1 |
number(pid as f64),
Err(_err) => lua.push_integer(-1),
}
1
}
#[cfg(target_os = "windows")]
#[lua_function]
unsafe fn bring_process_to_front(lua: gmod::lua::State) -> i32 {
let pid = lua.check_integer(-1);
if pid <= 0 {
lua.push_boolean(false);
return 1;
}
match window... | Rust | 0 |
dst
}
/// 他のStyle指定を取り込みます
pub fn concat(self: &mut Style<'a>, arg: &Style<'a>) {
for block_assign in &arg.block_assigns {
self.block_assigns.push(block_assign.clone());
}
}
/// BlockAssign指定ごと取り込みます、これはHTML上でのStyle属性等で指定された内容のマージに使用する想定です
pub fn add(self: &mu... | Rust | 0 |
Interp::Vertex => sys::OIIO_ParamValue_Interp_INTERP_VERTEX,
}
}
}
<filename>src/osu_xexxar/beatmap.rs
use super::math_util;
use rosu_pp::{
parse::{
DifficultyPoint, HitObject, HitObjectKind, ParseError, ParseResult, PathType, Pos2,
TimingPoint,
},
GameMode, Mods,
};
us... | Rust | 0 |
Vec<Vec<PollId>>> = IntHashMap::with_capacity_and_hasher(1000000, IntHasher::default());
pub static mut TOMORROWS_POLLS_BY_CATEGORY: IntHashMap<CategoryId, Vec<Vec<PollId>>> = IntHashMap::with_capacity_and_hasher(1000000, IntHasher::default());
pub static mut DAY_AFTER_TOMORROWS_POLLS_BY_CATEGORY: IntHashMap<CategoryI... | Rust | 0 |
ry_parser::ParseError;
pub struct BinaryParserV1 {
c_parser: *mut ::std::os::raw::c_void,
atom: lib_conv_capi::type_c_atom,
}
// initialize parser
pub fn make_parser(filename: &str, ranks: u32)
-> std::result::Result<BinaryParserV1, ParseError> {
let filename_cstring = CString::new(file... | Rust | 0 |
..Default::default()
})
.insert(ColliderPositionSync::Discrete)
.insert(ColliderDebugRender::default());
commands
.spawn_bundle(ColliderBundle {
position: Vec2::new(0.0, 0.0).into(),
shape: ColliderShape::cuboid(12.0, 0.1),
..Default::d... | Rust | 0 |
`pl.Int64` will return `False`.
"""
return self.equals(other, null_equal=null_equal, strict=strict)
# Keep the `list` and `str` properties below at the end of the definition of Series,
# as to not confuse mypy with the type annotation `str` and `list`
@property
def bin(self) ->... | Python | 1 |
_schema(next, self.flavour());
Ok(infer(current_database_schema, expected_database_schema, self.flavour()))
}
#[tracing::instrument(skip(self, previous_migrations, target_schema))]
async fn infer_next_migration(
&self,
previous_migrations: &[MigrationDirectory],
target_sche... | Rust | 0 |
255, 255)
blue = (0, 0, 128)
gray = (128, 128, 128)
green = (0, 128, 0)
red = (255,0,0)
X, Y = 1280, 720
pygame.init()
pygame.mixer.init()
pygame.display.set_caption("Play")
pauza = pygame.image.load("Pauza.png")
wyjscie = pygame.image.load("Exit.png")
display_surface = pyga... | Python | 1 |
ingress_list_by_cluster.bulk_request(
bulk_request_params, ignore_exceptions=True
)
ingress_list = []
for ingress in itertools.chain.from_iterable(item for item in api_ingress if item):
bcs_cluster_id = ingress.get("bcs_cluster_id")
bk_biz_id = params[bcs_clu... | Python | 1 |
self.colmap_thread.start()
def start_recording(self):
"""Start video recording"""
if self.recording:
print("⚠️ Already recording!")
return
try:
# Generate filename with timestamp
timestamp = datetime.datetime.now().strftime("%Y%... | Python | 1 |
import os
import logging
from werkzeug.security import generate_password_hash
from app import db, User
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def create_super_admin():
try:
# Load super admin credentials from environment variables
super_adm... | Python | 1 |
# Combine all DataFrames
if not data_dict:
raise ValueError("No data could be downloaded for any tickers")
combined_df = pd.concat(data_dict.values(), axis=0)
combined_df.sort_index(inplace=True)
# Final data validation
if combined_df.empty:
... | Python | 1 |
def compute_similarity(self, v_emb, name='default', fake=False):
if fake:
return None
v_emb = v_emb / (v_emb.norm(dim=-1, keepdim=True) + 1e-07)
t_emb = getattr(self, '{}_text_embeddings'.format(name))
output = self.logit_scale.exp() * v_emb @ t_emb.unsqueeze(0).transpose(1, 2
)
retu... | Python | 1 |
attheta', type=float, default=1.5)
parser.add_argument('--show_progress', action='store_true')
parser.add_argument('--exclude_kw', action='store_true')
parser.add_argument('--testset', action='store_true', help='if true will generate from test set, if false will generate from dev set')
parser.add_argume... | Python | 1 |
': personal_info['profile']['common_data']['first_name'],
'last_name': personal_info['profile']['common_data']['last_name'],
'middle_name': personal_info['profile']['common_data']['middle_name'],
'birth_date': personal_info['profile']['common_data']['birth_date'],
'region': personal_info['profile']['add... | Python | 1 |
(val)
}
}
impl FromVulkan<f32> for f32 {
#[inline]
fn from_vulkan(val: f32) -> Option<Self> {
Some(val)
}
}
impl<const N: usize> FromVulkan<[f32; N]> for [f32; N] {
#[inline]
fn from_vulkan(val: [f32; N]) -> Option<Self> {
Some(val)
}
}
impl<const N: usize> FromVulkan<[std... | Rust | 0 |
# lengths
WIDTH, HEIGHT = 780, 540
ROAD_WIDTH = 60
HOUSE_SIZE = 60
CAR_LENGTH = 30
CAR_WIDTH = 20
PEDESTRIAN_SIZE = (10, 10)
LITTER_SIZE = 5
AGENT_SIZE = 10
VISION_SIZE = 59
# colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (200, 200, 200)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
DIRECTIONS =... | Python | 1 |
er consistency* of the atomic
/// integer. This normally relies on the integer having the same address. The processor may not
/// track 'overlapping footprints' of the smaller integer (as the paper calls it). So when the
/// smaller integer part of an atomic starts at a different address, we would have to use orderings... | Rust | 0 |
when you have this enabled.");
let optimize_not_renamed_packedfiles_tip = QString::from_std_str("If you enable this, when running the 'Optimize PackFile' feature RPFM will optimize Tables and Locs that have the same name as their vanilla counterparts.\nUsually, those files are intended to fully override their v... | Rust | 0 |
);
}
}
<gh_stars>1-10
use std::collections::HashSet;
pub struct Group {
members: Vec<String>,
}
impl Group {
pub fn new(members: Vec<String>) -> Group {
Group {
members,
}
}
pub fn count_unanimous_votes(&self) -> usize {
let mut result = HashSet::new();... | Rust | 0 |
from redbot.core import errors # isort:skip
import importlib
import sys
try:
import AAA3A_utils
except ModuleNotFoundError:
raise errors.CogLoadError(
"The needed utils to run the cog were not found. Please execute the command `[p]pipinstall git+https://github.com/AAA3A-AAA3A/AAA3A_utils.git`. A resta... | Python | 1 |
}
if include_details:
result["detailed_diagnostics"] = {
"memory_breakdown": {
"index_data": "1.8 GB",
"cache": "0.4 GB",
"metadata": "0.1 GB"
},
... | Python | 1 |
nner_as_raw() }
}
impl crate::text::OCRBeamSearchDecoderTrait for PtrOfOCRBeamSearchDecoder {
#[inline] fn as_raw_mut_OCRBeamSearchDecoder(&mut self) -> *mut c_void { self.inner_as_raw_mut() }
}
impl crate::text::BaseOCRConst for PtrOfOCRBeamSearchDecoder {
#[inline] fn as_raw_BaseOCR(&self) -> *const c_voi... | Rust | 0 |
from datetime import datetime, timedelta
from random import randint, choice, uniform
from app import db
from app.models.payment import PaymentOrder, PaymentChannel
from app.models.user import User
def generate_order_no():
timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
random_num = str(randint(1000, 9999))... | Python | 1 |
lty(golden_index, eval_index) *
similarity_matrix[golden_index][eval_index])
if (best_value <= penalized_value):
best_index = eval_index
best_value = penalized_value
golden_to_eval[golden_index] = best_index
# Now, the converse: loo... | Python | 1 |
) -> /*Unknown conversion*//*Unimplemented*/HashTable TypeId { ns_id: 0, id: 28 }/TypeId { ns_id: 0, id: 28 } {
// unsafe { TODO: call ffi:soup_header_parse_semi_param_list_strict() }
//}
#[cfg(any(feature = "v2_26", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_26")))]
#[doc(alias = "soup_he... | Rust | 0 |
ke_trie(cls, data_st, data)
def f():
bin = trie.tobytes()
trie2 = cls().frombytes(bin)
assert trie2 == trie
assert dict(trie2) == as_dict
run_threaded(f)
@parametrize()
@given(st.data())
def test_dumps_loads(cls, data_st, data):
"""Different threads call pickle.dumps() on... | Python | 1 |
pool.insert_orphaned_block(b1.into());
assert_eq!(pool.len(), 1);
assert!(!pool.contains_unknown_block(&b1_hash));
assert_eq!(pool.unknown_blocks().len(), 0);
}
#[test]
fn orphan_block_pool_insert_unknown_block() {
let mut pool = OrphanBlocksPool::new();
let b1 = test_data::block_h1();
let b1_hash ... | Rust | 0 |
import os
import sys
print("###### Model Selection Tool ##################################################")
# Hash out to use OpenAI GPT-40
openai_api_base = os.getenv("OPENAI_API_BASE")
openai_model_name = os.getenv("OPENAI_MODEL_NAME")
model = os.getenv("MODEL")
openai_api_key = os.getenv("OPENAI_API_KEY")
print("\... | Python | 1 |
defiend_tags)
pos = []
replacements = [[], []]
for i, tag_list in enumerate(tag_lists):
tag_list = self.Normalize_length(tag_list, "O", self.model1.n)
for j, tag in enumerate(tag_list):
if tag != "O":
pos.append([i,j+1])
... | Python | 1 |
"total_x {}", total_x);
println!("self {:?}", self);
println!("user {:?}", user_fov);
assert!(false);
}
return ratio;
}
}
// each frame has multiple viewport
#[derive(Debug)]
pub struct Frame {
pub index: i32,
pub traces: Vec<Viewport>,
}
impl Frame {
... | Rust | 0 |
abort_on_not_found=True)],
start_to_close_timeout=timedelta(seconds=60),retry_policy=RetryPolicy(maximum_attempts=30))
return output
except ActivityError as e:
workflow.logger.exception(f"Failed to get biosim simulation run with id {biosim_run_id}.... | Python | 1 |
0);
for cu in &self.cus {
res.0 += cu.l1.cache_table.hit_cnt;
res.1 += cu.l1.cache_table.miss_cnt;
res.2 += cu.l1.cache_table.evict_cnt;
}
res
}
fn get_sampler_metrics(&self) -> (u32, u32, u32) {
let mut res: (u32, u32, u32) = (0, 0, 0);
... | Rust | 0 |
ares
#[serde(deserialize_with = "fix_common::workarounds::from_str")]// https://github.com/serde-rs/serde/issues/1183
#[serde(rename = "32")]
pub last_shares: i32,
/// LastPx
#[serde(deserialize_with = "fix_common::workarounds::from_str")]// https://github.com/serde-rs/serde/issues/1183
#[serde(rename = "31")]
p... | Rust | 0 |
#[inline(always)]
pub fn roscal_sten(&self) -> ROSCAL_STEN_R {
ROSCAL_STEN_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 7"]
#[inline(always)]
pub fn clkpll_cal_sten(&self) -> CLKPLL_CAL_STEN_R {
CLKPLL_CAL_STEN_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "B... | Rust | 0 |
# Based on the date range, will give a history of dividend and total payout till date.
import yfinance as yf
import sys
# Get the command line arguments
args = sys.argv
total = 0
def convert_timestamp(timestamp):
return timestamp.strftime('%Y-%m-%d')
def get_historical_ex_dividends(ticker):
# Download the ... | Python | 1 |
plicated_cargo_library/cargo/vendor/syn-0.10.8/src/nom.rs
// Adapted from nom <https://github.com/Geal/nom> by removing the
// IResult::Incomplete variant, which we don't use and which unfortunately more
// than doubles the compilation time.
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum IResult<I, O> {
/// indic... | Rust | 0 |
um_B, T] = [D, B, T]
"""
# logging.info(f"Jagged bmm backward called")
(x, y, x_offsets) = ctx.saved_tensors
N = ctx.N
grad_x = triton_jagged_dense_bmm(
grad_output, y.permute(0, 2, 1), x_offsets, N, allow_tf32=ctx.allow_tf32
)
grad_y = triton_jagged... | Python | 1 |
xyz": cube_xyzs,
"cube_rgb": cube_rgb,
"torus_xyz": torus_xyzs,
"torus_rgb": torus_rgb,
"frame": 0,
"alpha": False,
"checkbox": False,
},
sync={"selected_region_i", "cube_rgb"},
)
| Plot.html(
[
"label",
... | Python | 1 |
um_attributes {
let attribute: WebGlActiveInfo = gl
.get_active_attrib(&gl_program, i as u32)
.ok_or(
gl
.get_program_info_log(&gl_program)
.unwrap_or(format!("Failed to get attribute {}", i))
)?;
let loc = {
... | Rust | 0 |
prep_SD = ut.prepare(ser, 22)
assert "Z_score" in prep_SD.columns
assert num == lf
def test_L2D(self, gen_series):
ser = gen_series
lf = len(ser)
num, prep_L2D = ut.prepare(ser, -2)
assert "Z_score" in prep_L2D.columns
assert num == lf
def test_F1D_N(sel... | Python | 1 |
l {
let ok = match execute_sandboxed(
&code,
&[
Value::I32(0x1336),
]
) {
Ok(sp_sandbox::ReturnValue::Value(Value::I32(0x1337))) => true,
_ => false,
};
ok
}
fn test_sandbox_instantiate(code: Vec<u8>) -> u8 {
let env_builder = sp_sandbox::EnvironmentDefinitionBuilder::new();
let code ... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.