text string | label_name string | labels int64 |
|---|---|---|
import json
import random
import logging
from message_sender import send_group_message_async, send_user_message_async
from utils.plugin_loader import load_plugins
# 初始化插件
plugins = load_plugins()
async def process_message(data: dict, access_token: str):
"""处理消息主逻辑"""
try:
event_type = data['t']
... | Python | 1 |
ndexed_count == len(topics):
pass
elif indexed_count < len(topics):
raise EventError(
"Event log does not contain enough topics for the given ABI - this"
" is usually because an event argument is not marked as indexed"
)
else:
... | Python | 1 |
left_y = bin_y[bin_x <=cutPoint] # 获取左箱y数据
left_finish = checkBinFinish(left_y,min_sample) # 检查左箱是否不需再分
if (left_finish): # 如果左箱不需再分
finish_bins.append(left_bin... | Python | 1 |
/// # Example usage
///
/// ```
/// # use valor::camera::Camera;
/// let mut camera = Camera::new();
///
/// let view_proj_matrix: [[f32; 4]; 4] = camera.get_view_proj().into();
/// ```
pub struct Camera {
position: Vector3<f32>,
perspective: Matrix4<f32>,
pitch: f32,
yaw: f32,
sensitivity: f32,
}
... | Rust | 0 |
\x06Xf\xaei#\xe4\xaa\x9f\x98\xa2uJ!\x96r\
]\x17\xfa\x80\xe4\xb9\xfc\x19\xdb\xf8\xc0\x8b]'V\x81\
\x90K\xea;\xe9\xb8\xbf\xb9\x8f\x95 \x054\x86\x1e\x98\
L\xcb#^\x94\xdeg^q\xaa\xfe$\xc1t\x89\x04\
\xd0\xd7[\xca\xb3\x99\x8f}\xd4\xf9\xab\x0b}>\x11B\
\xef%~\x15u\x88\x14\xdd?Bp\x02\x17\xb7\x8b\xcc\
}\xab.\xbbP\xd9\x0b\xc70N\x82... | Python | 1 |
'''
Métodos úteis dos dicionários em Python
(As marcações com asterisco são os temas falados nessa aula.)
len - quantas chaves
keys - iterável com as chaves
values - iterável com os valores
items - iterável com chaves e valores
setdefault - adiciona valor se a chave não existe
copy - retorna uma cópia rasa (sh... | Python | 1 |
# 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 u... | Python | 1 |
d 0 blocks.
// let mut v = vec![0;empty_block_c];
let mut v = Vec::with_capacity( self.capacity() + empty_block_c);
for _ in 0..empty_block_c {
v.push( 0);
}
// Shift the existing blocks.
let mut carry : Block = 0;
for i in 0..self.size() {
let lbi : LongBlock = (self.content[i] as LongBlock) << sh... | Rust | 0 |
r::parse`] -> `Term`s ->⋯
┌───────────────[`token::flatten_term`]────────────────┐
⋯->*│*-> [`TermIter`] -> `Cell`s -> [`order_registers`] ->*│*->⋯
└──────────────────────────────────────────────────────┘
⋯-> `Token`s -> [`compile_tokens`] -> `Cell`s/instructions ->⋯
⋯-> [`unify`] -> Success/Fail
... | Rust | 0 |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Constants
cell_voltage = 3.0000 # V
load_current = 0.300 # mA
internal_resistance = 2.00 # Ohms
# Calculate the equivalent resistance of the circuit
equivalent_resistance = internal_resistance
# Calculate the voltage drop... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
from ..config import Configuration
class Attack(object):
"""Contains functionality common to all attacks."""
target_wait = min(60, Configuration.wpa_attack_timeout)
def __init__(self, target):
self.target = target
def run(self):
... | Python | 1 |
= ReserveConfig {
optimal_utilization_rate: 80,
loan_to_value_ratio: 50,
liquidation_bonus: 5,
liquidation_threshold: 55,
min_borrow_rate: 0,
optimal_borrow_rate: 4,
max_borrow_rate: 30,
fees: ReserveFees {
borrow_fee_wad: 100_000_000_000,
/// 0.00001% (Aave borrow fee)
... | Rust | 0 |
te!(
f,
"PathSegment::{}",
match *self {
PathSegment::MoveTo(_) => "MoveTo",
PathSegment::LineTo(_) => "LineTo",
PathSegment::CurveTo(_, _, _) => "CurveTo",
PathSegment::ClosePath => "ClosePath",
}
)
... | Rust | 0 |
in(*args, **kwargs):
if trainer.global_rank == 0:
import pudb;
pudb.set_trace()
import signal
signal.signal(signal.SIGUSR1, melk)
signal.signal(signal.SIGUSR2, divein)
# run
if opt.train:
try:
trainer.fit... | Python | 1 |
ight(ctx: &mut Context) -> Self {
// create a buffer of (u8, u8, u8, u8), because rgba, big enough to hold each pixel
let mut pixel_color_buf: [(u8, u8, u8, u8);
NUM_PIXEL_ROWS_PER_TILEGRAPHIC as usize * NUM_PIXEL_ROWS_PER_TILEGRAPHIC as usize] =
[WHITE;
NUM_PIXEL... | Rust | 0 |
lidate the
referenced tensors. The NumPy API doesn't allow any mutability of the
the underlying buffers.
WRONG:
```
input = interpreter.tensor(interpreter.get_input_details()[0]["index"])()
output = interpreter.tensor(interpreter.get_output_details()[0]["index"])()
interpreter.allocate_ten... | Python | 1 |
# -*- coding: utf-8 -*-
import tkinter as tk
import webbrowser
from urllib.parse import quote
from database import Database
#クラスRecipeの定義
class Recipe:
def __init__(self,name,ingredients):
self.name = name
self.ingredients = ingredients
class RecipeWindow:
def __init__(self,db: Database):
... | Python | 1 |
None => 0,
};
self.state.select(Some(i));
}
pub fn previous(&mut self) {
let i = match self.state.selected() {
Some(i) => {
if i == 0 {
self.items.len() - 1
} else {
i - 1
}
}... | Rust | 0 |
])
def _reduce_meld_kinds_by_rank_id(self, card: Card):
rank_id = utils.get_rank_id(card)
meld_kinds = self.meld_kinds_by_rank_id[rank_id]
if len(meld_kinds) > 1:
suits = ['S', 'H', 'D', 'C']
self.meld_kinds_by_rank_id[rank_id] = [[Card(suit, card.rank) for suit in s... | Python | 1 |
f.mock_view.painter.cross.call_count)
def test_single_peak_selection(self, mock_peaks_list_presenter):
name = "ws1"
mock_model = create_mock_model(name)
mock_model.has_representations_drawn.return_value = True
viewlimits = (-1, 1), (-2, 2)
mock_model.viewlimits.return_value ... | Python | 1 |
end_with_label("smartstream-map-setup");
web_sys::console::time_with_label("smartstream-map-test");
test()
.await
.map_err(FluvioError::try_from)
.expect("Test failed");
web_sys::console::time_end_with_label("smartstream-map-test");
web_sys::console::time_with_label("smartstream-... | Rust | 0 |
"""Snakemake wrapper for BUSCO assessment"""
__author__ = "Tessa Pierce"
__copyright__ = "Copyright 2018, Tessa Pierce"
__email__ = "ntpierce@gmail.com"
__license__ = "MIT"
import tempfile
from snakemake.shell import shell
log = snakemake.log_fmt_shell(stdout=True, stderr=True)
extra = snakemake.params.get("extra"... | Python | 1 |
ault() -> OptColorWhen {
OptColorWhen::Auto
}
}
impl ::std::str::FromStr for OptColorWhen {
type Err = OptColorWhenParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let oc = match s {
"always" => OptColorWhen::Always,
"never" => OptColorWhen::Never,
... | Rust | 0 |
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# Load MNIST dataset
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_test = x_test.astype('float32') / 255.0
x_test = np.expand_dims(x_test, axis=-1)
# Define a simple CNN model
model = tf.keras.Sequential([
tf... | Python | 1 |
import pandas as pd
import tkinter as tk
from tkinter import ttk,messagebox
import time
import matplotlib.pyplot as plt
import numpy as np
def manuel():
gun_sayisi = int(input("Kaç günlük veri girmek istiyorsunuz? "))
gunler = []
vakalar = []
olumler = []
for i in range(gun_sayisi):
gun... | Python | 1 |
image[image == 0] = min_val
# Set the axis invisible
plt.xticks([])
plt.yticks([])
# Set the frame invisible
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["bottom"].set_visible(False)
... | Python | 1 |
import os
from datetime import timedelta
import pandas
import pendulum
from airflow import DAG
from airflow.operators.python import PythonOperator, get_current_context
from airflow.providers.postgres.operators.postgres import PostgresOperator
from airflow.sensors.filesystem import FileSensor
from lib.config import ge... | Python | 1 |
# features/rv_logret_15m.py
from __future__ import annotations
import datetime as dt
import numpy as np
import pandas as pd
from feature_base import BaseFeature, FeatureContext
class RVLogret15mFeature(BaseFeature):
"""
RV on 15-minute resampled close (last in bin), within 09:30–15:59.
"""
name = "rv_... | Python | 1 |
_epoch)
if args.local_rank == 0:
logger.info('Scheduled epochs: {}'.format(num_epochs))
try:
best_record, best_ep = 0, 0
for epoch in range(start_epoch, num_epochs):
if distributed:
loader_train.sampler.set_epoch(epoch)
train_metrics = train_epoc... | Python | 1 |
#! /usr/bin/env python
# Usage: calibration.py [target/calibration_data_file.csv] [output_file.png]
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
CALIBRATION_FILE = sys.argv[1]
OUT_IMG_FILE = sys.argv[2]
labels = []
counts = []
prec = []
counts_train = []
for ... | Python | 1 |
QF").unwrap();
assert_eq!(id, 5);
assert_eq!(val, 42);
}
#[test]
fn response_splits_string() {
let res = LssResponse::new("*5QFHEH\r".to_owned());
let (id, val) = res.separate_string("QF").unwrap();
assert_eq!(id, 5);
assert_eq!(val, "HEH");
}
#[test... | Rust | 0 |
Handle: i32, FrameIndex: i32, MeshIndex: i32) -> i32;
pub fn dx_MV1RefreshCollInfo(MHandle: i32, FrameIndex: i32, MeshIndex: i32) -> i32;
pub fn dx_MV1CollCheck_Line(
MHandle: i32,
FrameIndex: i32,
PosStart: Vector,
PosEnd: Vector,
MeshIndex: i32,
) -> Mv1CollResultPo... | Rust | 0 |
import os
from langchain_huggingface import HuggingFaceEndpoint
import streamlit as st
from langchain_core.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser
list_model=["mistralai/Mistral-7B-Instruct-v0.3",
"allenai/Llama-3.1-Tulu-3-8B",
"Qwen/Qwen2.5-1.5B-Inst... | Python | 1 |
of making the product good
# we need to do a directed search . the direction we move in has to be well bounded but also free
# how free the algorithm is really depends on how large we want our sample size to be
# for example, if we want to optimize button size, should we first try an extra large and a small size,... | Python | 1 |
[inline]
pub fn variant(self, variant: SELECTEDW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable"]
#[inline]
pub fn clear(self) -> &'a mut W {
self.variant(SELECTEDW::CLEAR)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a... | Rust | 0 |
"""
CUDA Virtual Memory Management - Main Header
This is the main header file for CUDA VMM bindings, providing C-style
organization of all VMM functionality. Include this file to get access
to all VMM types, constants, and API functions.
"""
# =========================================================================... | Python | 1 |
import responses
from pytest import raises
from darwin.future.core.client import ClientCore
from darwin.future.core.datasets import create_dataset
from darwin.future.exceptions import BadRequest
from darwin.future.tests.core.fixtures import * # noqa: F401, F403
from .fixtures import * # noqa: F401, F403
def test_... | Python | 1 |
type Bytes16<'a> = BytesFix<'a, 16>;
pub type Bytes17<'a> = BytesFix<'a, 17>;
pub type Bytes18<'a> = BytesFix<'a, 18>;
pub type Bytes19<'a> = BytesFix<'a, 19>;
pub type Bytes20<'a> = BytesFix<'a, 20>;
pub type Bytes21<'a> = BytesFix<'a, 21>;
pub type Bytes22<'a> = BytesFix<'a, 22>;
pub type Bytes23<'a> = BytesFix<'a, ... | Rust | 0 |
hing, Multi-Probe Consistent Hashing, Rendezvous Hashing,
//! Weighted Rendezvous Hashing, Maglev Hashing, and Jump Hashing. It also provides clients for
//! Consistent Hashing, Rendezvous Hashing, and Weighted Rendezvous Hashing to efficiently
//! redistribute items as nodes are inserted and removed from the ring.
//!... | Rust | 0 |
"""
@author: liujiming
@email: jimingLiu@sjtu.edu.cn
@software: PyCharm
@file: uni_samples.py
@time: 2024/9/9 8:04
"""
import numpy as np
import pandas as pd
def uni_array(array_del, max_value, min_value):
return (2.0 * (array_del - min_value) / (max_value - min_value)) - 1.0
def uni_input(ori_sam_filepath, pro... | Python | 1 |
pective lists.
# ```python
# cam = cv2.VideoCapture(0)
# start_recorded = False
# end_recorded = False
# current_person_name = None
# previous_person_name = None
# ```
# 6. **Initializes variables and starts the webcam:**
# - `cam`: Captures video from the default webcam.
# - `start_recorded`: Tracks whether a p... | Python | 1 |
imm_model.state_dict(), model)
model.load_state_dict(new_state_dict)
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image_processor = AutoImageProcessor.from_pretrained("microsoft/{}".format(swin_name.replace("_", "-")))
image = Image.open(requests.get(url, stream=True).raw)
inputs... | Python | 1 |
and variant index coincide.
/// The variant `dataful_variant` contains a niche at an arbitrary
/// offset (field `tag_field` of the enum), which for a variant with
/// discriminant `d` is set to
/// `(d - niche_variants.start).wrapping_add(niche_start)`.
///
/// For example, `Option<(usize, &T)... | Rust | 0 |
from amis import (
Action,
Divider,
Form,
InputText,
LevelEnum,
Page,
PageSchema,
Switch,
Remark,
InputNumber,
InputTime,
InputTimeRange,
Alert,
Editor,
Select,
InputTag
)
action_button = [Action(label='保存', level=LevelEnum.success, type='submit'),
... | Python | 1 |
from datetime import datetime
from sqlalchemy import Boolean, Column, DateTime, Integer, String
from sqlalchemy.orm import relationship
from app.config import settings
from app.db.base_class import Base
from app.models.model import Model # noqa
class ModelGroup(Base):
__tablename__ = "model_group"
id = Col... | Python | 1 |
sheets[zmax - 1];
window_on(sheet_manager, task_manager, active_window);
}
}
}
if KEYBOARD_OFFSET <= i && i <= 511 {
let key = i - KEYBOARD_OFFSET;
let mut chr = 0 as u8;
if key < KEYTABL... | Rust | 0 |
print("Separador de unidades")
num = int(input("Digite um número de 3 dígitos\n"))
centenas = num - num % 100
dezenas = (num - centenas) - (num - centenas) % 10
unidades = num - centenas - dezenas
print(f"As centenas são {centenas}, as dezenas são {dezenas}, as unidades são {unidades}")
| Python | 1 |
clientY: element.getBoundingClientRect().top + 10,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
button: 0,
relatedTarget: null
... | Python | 1 |
ize_of::<SecPkgContext_SubjectAttributes>(), 8);
assert_eq!(align_of::<SecPkgContext_SubjectAttributes>(), 8);
assert_eq!(size_of::<SecPkgContext_CredInfo>(), 8);
assert_eq!(align_of::<SecPkgContext_CredInfo>(), 4);
assert_eq!(size_of::<SecPkgContext_NegoPackageInfo>(), 4);
assert_eq!(align_of::<Sec... | Rust | 0 |
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, _, Command
from odoo.addons.account.models.chart_template import template
class AccountChartTemplate(models.AbstractModel):
_inherit = 'account.chart.template'
@template('es_common')
def _get_es_common_tem... | Python | 1 |
ying `code` will be shared.
/// - The destination address is computed based on the sender, code_hash and the salt.
/// - The smart-contract account is created at the computed address.
/// - The `endowment` is transferred to the new account.
/// - The `deploy` function is executed in the context of the newly-cre... | Rust | 0 |
p = position.clamp(0.0, 1.0);
match axis {
Axis::Vertical => self.split_x(p),
Axis::Horizontal => self.split_y(p),
Axis::Both => todo!(),
Axis::None => panic!("Cannot split by axis None!"),
}
}
/// Splits along the x axis.
pub fn split_x(self,... | Rust | 0 |
min)
policy = np.argmax(Q, axis=-1)
return policy
def ValueFunctionSARSA(env, beta, Nepisodes, alpha):
max_queue = 20
epsilon = 1.0
epsilon_min = 0.05
epsilon_decay = 0.995
nu = 1e-6
V = np.zeros((max_queue + 1, max_queue + 1, 2, 11))
for ep in range(Nepisodes):
state, _ ... | Python | 1 |
import os
def remove_null_bytes(directory):
for root, _, files in os.walk(directory):
for file in files:
file_path = os.path.join(root, file)
try:
with open(file_path, "rb") as f:
content = f.read()
clean_content =... | Python | 1 |
i32(r as i32);
ctx.builder.const_i32(imm8 as i32);
ctx.builder.call_fn3("instr_660FC6");
}
pub fn instr_C6_0_reg_jit(ctx: &mut JitContext, r: u32, imm: u32) {
// reg8[r] = imm;
ctx.builder.const_i32(imm as i32);
codegen::gen_set_reg8_unmasked(ctx, r);
}
pub fn instr_C6_0_mem_jit(ctx: &mut JitConte... | Rust | 0 |
arm_home(self, code: str | None = None) -> None:
"""Send arm home command."""
try:
self._egardiasystem.alarm_arm_home()
except requests.exceptions.RequestException as err:
_LOGGER.error(
"Egardia device exception occurred when sending arm home command: %s"... | Python | 1 |
32> = Vector::new_column(vec![1.0, 2.0, 3.0, 4.0, 5.0]);
assert_relative_eq!(res, res_ref);
}
#[test]
fn get_slice_0()
{
let res: Vector<f32> = Vector::new_column(vec![1.0, 2.0, 3.0, 4.0, 5.0]);
let res_ref: Vector<f32> = Vector::new_column(vec![3.0, 4.0, 5.0]);
let slice: Vector<f32> = res.get_slice... | Rust | 0 |
(), "path for saving verification key exists: {}", path.display());
}
{
File::create(path).expect("can't create file at verification key path");
remove_file(path).unwrap_or_default()
}
log::info!("Transpiling circuit");
let (gates_count, transpilation_hints) = transpile_with_gates_c... | Rust | 0 |
ident: u32,
pub loc: CodeLoc,
}
#[derive(Debug, Clone, Copy)]
pub struct TCParamsDeclarator {
pub params: &'static [TCParamDecl],
pub varargs: bool,
}
pub struct TCFunctionDeclarator {
pub is_static: bool,
pub return_type: TCType,
pub ident: u32,
pub params: Option<TCParamsDeclarator>,
... | Rust | 0 |
, x1, x2 -> y1, x1, y2, x1
bboxes = tf.stack([bboxes[..., 0], bboxes[..., 2], bboxes[..., 1], bboxes[..., 3]], axis=-1)
if ignore_regions is not None:
ignore_regions = tf.stack([ignore_regions[..., 0], ignore_regions[..., 2], ignore_regions[..., 1],
ignore_regions[..., 3]], axis=-... | Python | 1 |
= env.contains_key(&OsString::from(def_name));
let bs_name = format!("CT_TASK_{}_BOOTSTRAP", name);
let bootstrap = env.contains_key(&OsString::from(bs_name));
let help_name = format!("CT_TASK_{}_HELP", name);
let help = env
.get(&OsString::from(help_name... | Rust | 0 |
cept Exception as e:
logger.error(f"Error during validation step: {e}")
continue
del batch
torch.cuda.empty_cache()
gc.collect()
... | Python | 1 |
, feat in enumerate(res_endpoints)])
@register
@serializable
class ResNetC5(ResNet):
__doc__ = ResNet.__doc__
def __init__(self,
depth=50,
freeze_at=2,
norm_type='affine_channel',
freeze_norm=True,
norm_decay=0.,
... | Python | 1 |
# --- Day 4: The Ideal Stocking Stuffer ---
#
# Santa needs help mining some AdventCoins (very similar to bitcoins) to use as gifts for all the economically forward-thinking little girls and boys.
#
# To do this, he needs to find MD5 hashes which, in hexadecimal, start with at least five zeroes. The input to the MD5 ... | Python | 1 |
uration::from_millis(100))
.build();
let begin = Instant::now();
for _ in 0..10 {
rate_limiter.acquire_one().await.expect("No reason to fail");
}
let elapsed = Instant::now().duration_since(begin);
println!("Elapsed: {:?}", elapsed);
assert!((elapsed.as_secs_f64() - 1.).abs() ... | Rust | 0 |
time.sleep(1)
# tab.get_screenshot(path='temp', name=f'scroll_{time.strftime("%Y%m%d%H%M%S")}.jpg', full_page=False)
time.sleep(1)
logger.info(check_button.text)
check_button.click()
logger.info("Button clicked.")
wait_for_load(tab)
... | Python | 1 |
','ply_yacc.py',90),
('EL -> epsilon','EL',1,'p_EL','ply_yacc.py',91),
('for -> FOR IDENTIFIER ASSIGN expr TO expr DO statement','for',8,'p_for','ply_yacc.py',94),
('return -> RETURN SEMICOLON','return',2,'p_return','ply_yacc.py',97),
('call -> CALL IDENTIFIER LPAREN E RPAREN SEMICOLON','call',6,'p_call','ply_y... | Python | 1 |
_layout = QVBoxLayout()
self.start_msg = self.tr("开始任务")
self.start_stop_button = QPushButton(self.start_msg)
self.start_stop_button.clicked.connect(self.toggle_production)
self.box_msg = self.tr("等待期间关闭游戏")
self.kill_game_box = QCheckBox(self.box_msg)
button_layout.addW... | Python | 1 |
xlimit[0] + xlimit[1])
ycenter = 0.5 * (ylimit[0] + ylimit[1])
# Create the line
manager = roi.RegionOfInterestManager(self.plot)
item = roi_items.BandROI()
item.setGeometry(
(xlimit[0], ycenter),
(xlimit[1], ycenter),
20,
)
it... | Python | 1 |
oad_state_dict(checkpoint['optimizer'])
checkpoint = None # free up memory
# compile the model
if compile:
print("compiling the model... (takes a ~minute)")
unoptimized_model = model
model = torch.compile(model) # requires PyTorch 2.0
# wrap model into DDP container
if ddp:
model = DDP(model, device_i... | Python | 1 |
import pydeck as pdk
def to_pydeck_layer_points(records, name="Points", heat=False):
if not records:
return []
if heat:
return [pdk.Layer(
"HeatmapLayer",
data=records,
get_position='[lon, lat]',
get_weight='weight',
aggregation='MEAN'... | Python | 1 |
);
res.headers_mut().insert(
ACCESS_CONTROL_ALLOW_METHODS,
HeaderValue::from_str("GET, POST, PUT, PATCH, DELETE, CALL").unwrap(),
);
res.headers_mut().insert(
ACCESS_CONTROL_ALLOW_ORIGIN,
... | Rust | 0 |
from datetime import datetime
from unittest.mock import Mock
from pytest import fixture
class TestAuditlog:
def call_fut(self, *args, **kwargs):
from .ad_auditlog import auditlog_show
return auditlog_show(*args, **kwargs)
@fixture
def mock_timestamp(self):
return datetime(2016,1,... | Python | 1 |
from form.comment.form_tester import CommentFormTester
class EditCommentFormTester(CommentFormTester):
@property
def of_which_action(self):
return 'редактирования'
| Python | 1 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Create your views here.
from django.shortcuts import render
from django.core.exceptions import PermissionDenied,SuspiciousOperation
from django.http import Http404,HttpResponsePermanentRedirect
STORE_LIST = [{'id':0,'name':'Corporate','address':'624 B... | Python | 1 |
let index = worker.index();
let timer = worker.timer();
let mut input = InputSession::new();
let mut probe = ProbeHandle::new();
worker.dataflow::<Time,_,_>(|scope| {
let edges = input.to_collection(scope);
pagerank(iterations, &edges)
.... | Rust | 0 |
from .source import SourceTempo
__all__ = ["SourceTempo"]
| Python | 1 |
taset.feat_dim, dataset.n_offsets, dataset.voxel_size, dataset.update_depth, dataset.update_init_factor, dataset.update_hierachy_factor, dataset.use_feat_bank, dataset.appearance_dim, dataset.ratio, dataset.add_opacity_dist, dataset.add_cov_dist, dataset.add_color_dist, dataset.data_type)
scene = Scene(dataset,... | Python | 1 |
d"' in subs:
return {}
subs = self._parse_json(subs, video_id, fatal=False)
if not subs:
return {}
fixed_subs = self._fix_subtitles(subs)
if fixed_subs:
return {'en': [{'ext': 'srt', 'data': fixed_subs}]}
return {}
class LyndaCourseIE(LyndaBa... | Python | 1 |
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth import get_user_model
from django.urls import reverse
# Create your models here.
class CustomUser(AbstractUser):
age = models.PositiveIntegerField(null=True, blank=True)
class Profile(models.Model):
user... | Python | 1 |
import pytest
import requests
import time
import os
@pytest.fixture(autouse = True, scope="module")
def image():
image_name = 'test_image_' + str(int(time.time()*1000))
print(f"image: {image_name}")
print("setup_module ", os.system(f"docker build -t {image_name} ."))
yield image_name
print("teard... | Python | 1 |
# ishelve2.py
import os
import shelve
import plac
class ShelveInterface(object):
"A minimal interface over a shelve object."
commands = 'set', 'show', 'showall', 'delete'
@plac.annotations(
configfile=('path name of the shelve', 'option'))
def __init__(self, configfile):
self.configfi... | Python | 1 |
(&self,
context: &BehaviorTreeBuildingContext) -> Result<RootBTNode, BehaviorTreeBuildingError>;
}
pub struct OneOffRootBTNodeDefinition {
id: i32,
child_id: i32
}
impl OneOffRootBTNodeDefinition {
pub fn new(id: i32,
child_id: i32) -> OneOffRootBTNodeDefinition {
O... | Rust | 0 |
of threads in a block
threadsperblock_bfacet = 128
num_blocks_bfacet = (
bfacet_dofmap.size + (threadsperblock_bfacet - 1)
) // threadsperblock_bfacet
# Allocate memory on the device
detJ_f_d = cuda.to_device(detJ_f)
bfacet_constants_d = cuda.to_device(bfacet_constants)
bfacet_dofmap_d = cuda.to_device(bfacet_dofm... | Python | 1 |
impl<A, B> FuncMap<A, B> for UnsafeCell<A> {
type Output = UnsafeCell<B>;
fn func_map<F>(self, mut f: F) -> Self::Output
where
F: FnMut(A) -> B,
{
f(self.into_inner()).into()
}
}
impl<A, B> TryFuncMap<A, B> for UnsafeCell<A> {
type Ou... | Rust | 0 |
TestDhtOp>;
/// test struct
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, SerializedBytes)]
struct TestHeader(String);
impl_hashable_content!(TestDhtOp, DhtOp);
impl_hashable_content!(TestHeader, Header);
#[tokio::test(threaded_scheduler)]
async fn check_hashed_type() {
let my_type = TestDhtOp {
... | Rust | 0 |
ht = subplot_width * aspect_ratio * rows
fig, axs = plt.subplots(2, 1 + len(args.model_names), figsize=(fig_width, fig_height))
axs[0, 0].imshow(input_img)
axs[0, 0].axis('off')
axs[1, 0].imshow(gt_img)
axs[1, 0].axis('off')
for i, (pred_img, deltaE00_map) in enumerate(zip(pred_img_list, deltaE... | Python | 1 |
Burst, maxBurst):
jj = ii - minBurst
####Process the top bursts
reference = topReference.bursts[jj]
secondary = topCoreg.bursts[jj]
referencename = reference.image.filename
secondaryname = secondary.image.filename
rdict = {'ran... | Python | 1 |
ntUsage: 0,
modBaseAddr: std::ptr::null_mut(),
modBaseSize: 0,
hModule: std::ptr::null_mut(),
szModule: [0; winapi::um::tlhelp32::MAX_MODULE_NAME32 + 1],
szExePath: [0; winapi::shared::minwindef::MAX_PATH],
};
let snapshot: winapi::um::winnt::HANDLE =
rlwindows::... | Rust | 0 |
# 15.7 Case Study: Unsupervised Machine Learning, Part 2—k-Means Clustering
# Iris Dataset
# 15.7.1 Loading the Iris Dataset
from sklearn.datasets import load_iris
iris = load_iris()
print(iris.DESCR)
# Checking the Numbers of Samples, Features and Targets
iris.data.shape
iris.target.shape
iris.target_names
iris... | Python | 1 |
eRequest>
+ Send
{
}
impl<REv> ReactorEventT for REv where
REv: From<Event>
+ From<ApiRequest<NodeId>>
+ From<StorageRequest<Storage>>
+ From<LinearChainRequest<NodeId>>
+ From<ContractRuntimeRequest>
+ Send
+ 'static
{
}
#[derive(DataSize, Debug)]
pub(crate) st... | Rust | 0 |
xt: Text to chunk into passages.
max_sentence_len: Maximum number of chars of each sentence before being filtered.
Returns:
passages: Chunked passages from the text.
"""
passages = []
try:
logger.info("========web text len: {} =======".format((len(text... | Python | 1 |
def digits(n):
"""Given a positive integer n, return the product of the odd digits.
Return 0 if all digits are even.
For example:
digits(1) == 1
digits(4) == 0
digits(235) == 15
"""
product = 1
for digit in str(n):
if int(digit) % 2 == 1:
product *= int(digit)
... | Python | 1 |
提供该次请求的 RequestId。
:type RequestId: str
"""
self._CertificateId = None
self._RequestId = None
@property
def CertificateId(self):
r"""证书ID
:rtype: str
"""
return self._CertificateId
@CertificateId.setter
def CertificateId(self, Certificate... | Python | 1 |
}
pub trait GsBufferUploadable<D> {
fn upload_func(&self) -> Box<dyn Fn(&Self, &mut GsBufferDataUploader, &D) -> VkResult<()>>;
}
use std::sync::Arc;
use std::collections::HashMap;
use crossbeam_channel::{Sender, Receiver};
use libc::{c_int, c_ulong};
use crate::config::ConfHash;
use crate::bbi::*;
const Z_OK... | Rust | 0 |
{
link_libs_static(libs);
}
}
#[inline]
fn link_libs_static(libs: &[&str]) {
for lib in libs {
link_lib_static(lib);
}
}
#[inline]
fn link_libs_dylib(libs: &[&str]) {
let llvm_link_llvm_dylib = env::var(ENV_LLVM_LINK_LLVM_DYLIB).unwrap_or("OFF".to_owned());
if llvm_link_llvm_dylib... | Rust | 0 |
ag_impl!(zipzag_encode128, zipzag_decode128, i128, u128);
#[test]
fn zipzag_encoding() {
const MN: i8 = <i8>::min_value();
const MX: i8 = <i8>::max_value();
for v in MN..=MX {
assert_eq!(v, zipzag_decode8(zipzag_encode8(v)));
}
for &v in &[0, -1, -2, -21, 34, 1, 2, 4] {
assert_eq!(... | Rust | 0 |
from abc import ABC, abstractmethod
from ray import tune
from autogluon.common import space as ag_space
class RaySpaceConverter(ABC):
@property
@abstractmethod
def space_type(self):
"""Type of the converter"""
raise NotImplementedError
@staticmethod
@abstractmethod
def conve... | Python | 1 |
lta: f32 = max_item_f / 100.0;
let max_perc_delta: f32 = delta / one_perc_delta;
let one_perc_distance: f32 = max_distance / 100.0;
t::DataOps {
max_perc_delta: max_perc_delta,
max_val_delta: delta,
one_perc_delta: one_perc_delta,
max_idx: max_idx_int,
min_idx: min_idx_int,
extrem_distan... | Rust | 0 |
could not connect to socket"),
};
HttpResponse::Ok().json(j)
}
#[derive(Serialize, Deserialize)]
pub struct TmdbSearchTerm {
pub term: String,
}
pub async fn search_movie_term (
tmpl: web::Data<tera::Tera>,
body: web::Bytes
) -> Result<HttpResponse, Error> {
let result : TmdbSearchTerm... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.