text string | label_name string | labels int64 |
|---|---|---|
class DjangoElasticsearchDslError(Exception):
pass
class VariableLookupError(DjangoElasticsearchDslError):
pass
class RedeclaredFieldError(DjangoElasticsearchDslError):
pass
class ModelFieldNotMappedError(DjangoElasticsearchDslError):
pass
| Python | 1 |
|500|480| ... | item2 | item1 |
// +---+---+---+--------------------------+-------+-------+
// |
// index of index
// of last item
// Copyright 2020 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.... | Rust | 0 |
from abc import ABC, abstractmethod
from typing import Any
import numpy as np
from sportslabkit import Tracklet
class BaseMotionModel(ABC):
"""Abstract base class for motion models.
This class defines a common interface for all motion models.
Derived classes should implement the update, and predict met... | Python | 1 |
Fields::Named(fields_named) => bitfield_struct_impl(ast, fields_named),
Fields::Unnamed(fields_unnamed) => bitfield_tuple_struct_impl(ast, fields_unnamed),
Fields::Unit => Err(Error::new(
Span::call_site(),
"#[bitfield] does not work with unit struct",
... | Rust | 0 |
text: &'input str,
(_, _, _): (usize, Tok<'input>, usize),
(_, b, _): (usize, Vec<(Annotated<Pattern>, Vec<Annotated<SingleExpression>>)>, usize),
(_, _, _): (usize, Tok<'input>, usize),
) -> Vec<(Annotated<Pattern>, Vec<Annotated<SingleExpression>>)>
{
b
}
#[allow(unused_variables)]
fn __action52<
... | Rust | 0 |
"""
* Crea una función que encuentre todas las combinaciones de los números
* de una lista que suman el valor objetivo.
* - La función recibirá una lista de números enteros positivos
* y un valor objetivo.
* - Para obtener las combinaciones sólo se puede usar
* una vez cada elemento de la lista (pero pueden e... | Python | 1 |
#!/usr/bin/env python
#
# Copyright Allister Levi Sanchez 2008.
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
#
# This program sets up a CGI HTTP Server at port 8000 on localhost
# It will be ... | Python | 1 |
if benson_black.is_alive(point) {
status_list.push((point, vec! [StoneStatus::Alive, StoneStatus::BlackTerritory]));
} else if benson_white.is_eye(point) {
status_list.push((point, vec! [StoneStatus::Dead, StoneStatus::WhiteTerritory]));
} else {
... | Rust | 0 |
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{
components::{alert_indicator, attrs, font_awesome, paging, tooltip, Placement},
generated::css_classes::C,
get_target_from_managed_target,
route::RouteId,
GMsg, Route,
};
use iml_wir... | Rust | 0 |
mod test;
use crate::arch::*;
use core::{mem, ptr};
macro_rules! expand_round {
($t1:expr, $t3:expr, $round:expr) => {{
let mut t1 = $t1;
let mut t2;
let mut t3 = $t3;
let mut t4;
t2 = _mm_aeskeygenassist_si128(t3, $round);
t2 = _mm_shuffle_epi32(t2, 0x55);
... | Rust | 0 |
i + 1",
|lc| lc,
|lc| lc,
|lc| lc + i_new.get_variable() - CS::one() - i.get_variable(),
);
// Compute z_{i+1}
let z_input = conditionally_select(
cs.namespace(|| "select input to F"),
&z_0,
&z_i,
&Boolean::from(is_base_case),
)?;
let z_next = self
.... | Rust | 0 |
xP7x */
EM_NDS32 = 167, /* Andes Tech. compact code emb. RISC */
EM_ECOG1X = 168, /* Cyan Technology eCOG1X */
EM_MAXQ30 = 169, /* Dallas Semi. MAXQ30 mc */
EM_XIMO16 = 170, /* New Japan Radio (NJR) 16-bit DSP */
EM_MANIK = 171, /* M2000 Reconfigurable ... | Rust | 0 |
Only is an additional flag. Using the HttpOnly flag when generating a cookie helps mitigate the risk of client side script accessing the protected cookie (if the browser supports it).
pub http_only: bool,
/// Secure attribute. A secure cookie is only sent to the server with an encrypted request over the HTTPS p... | Rust | 0 |
}
}
true
}
KeyCode::F(n) => {
let n = n as usize - 1;
if n < self.tabs.len() {
self.current_tab = n as usize;
}
false
... | Rust | 0 |
# PROVA
# Desenvolva um programa em Python para calcular a média de notas de alunos em uma disciplina.
# O programa deve solicitar ao usuário o número de alunos e, em seguida, para cada
# aluno, pedir o nome e três notas. Utilize um loop 'for' para iterar sobre os alunos e suas notas.
# Além disso, implemente uma e... | Python | 1 |
eKind<'a> {
Node(Ident<'a>),
Modified(Box<ValidNode<'a>>, Modifier),
StaticToken(Ident<'a>),
DynamicToken(Ident<'a>),
Group {
nodes: Vec<ValidNode<'a>>,
inline: bool,
},
Choice {
nodes: Vec<ValidNode<'a>>,
inline: bool,
},
Delimited(Box<ValidNode<'a>>, Ident<'a>),
Todo,
End,
}
#[d... | Rust | 0 |
ror": error_message}, status=400)
except asyncio.TimeoutError:
logger.error(f"LLM响应测试超时")
return web.json_response({"success": False, "error": f"请求超时: {timeout}s"}, status=500)
except Exception as e:
logger.error(f"LLM响应测试时发生未知错误: {e}")
return web.json_response({"success": False,... | Python | 1 |
let js_this = ctx.this_unchecked::<JsObject>();
let napi_node = ctx.env.unwrap::<NapiBiquadFilterNode>(&js_this)?;
let node = napi_node.unwrap();
let js_str = ctx.get::<JsString>(0)?;
let uf8_str = js_str.into_utf8()?.into_owned()?;
let value = match uf8_str.as_str() {
"lowpass" => Biqu... | Rust | 0 |
-> Result<OutputStream, ShellError> {
let cmd_args = DecimalArgs {
range: args.opt(0)?,
};
let (min, max) = if let Some(range) = &cmd_args.range {
(range.item.min_f64()?, range.item.max_f64()?)
} else {
(0.0, 1.0)
};
match min.partial_cmp(&max) {
Some(Ordering:... | Rust | 0 |
crate log;
use x86::shared::io;
pub const INVALID_VENDOR: u16 = 0xffff;
const CONFIG_ADDRESS: u16 = 0xcf8;
const CONFIG_DATA: u16 = 0xcfc;
pub const REALTEK: u16 = 0x10ec;
pub const RTL_8139: u16 = 0x8139;
pub const VEND_ID_OFFSET: u8 = 0;
pub const DEV_ID_OFFSET: u8 = 2;
pub const CMD_REG_OFFSET: u8 = 4;
pub cons... | Rust | 0 |
help="Path to the directory with trace files.")
gather_all_args.add_argument('--results', type=str, required=True, help="Folder where to write results.")
gather_all_args.add_argument('--alias', type=str, required=True, help="Alias for the change being tested.")
gather_all_args.add_... | Python | 1 |
load().unwrap();
let thermostat = thermostats.get(serial).expect("Unknown thermostat serial. You need to do a read first.");
let secret = &thermostat.secret;
let connected_peripheral = bluetooth::connect(|name| is_thermostat_name(name) && &stripped_name(name) == serial, false).unwrap();
update_charact... | Rust | 0 |
argument
to use the :class:`_postgresql.REGCONFIG` datatype automatically,
and applies a return type of :class:`_postgresql.TSQUERY`.
Assuming the PostgreSQL dialect has been imported, either by invoking
``from sqlalchemy.dialects import postgresql``, or by creating a PostgreSQL
engine using ``cre... | Python | 1 |
ters
noise_x: Noise = None,
noise_y: Noise = None,
# other parameters
init_x: Callable = brainstate.init.Uniform(0, 0.05),
init_y: Callable = brainstate.init.Uniform(0, 0.05),
method: str = 'exp_euler',
):
super().__init__(
in_size,
no... | Python | 1 |
ata = a_rec
# b_rec = get_structure_features(gro2,
# xtc2,
# start_frame, features=['sc-torsions'])
# b_rec_feat, b_rec_data = b_rec
# # relen_dat = relen_block_analysis(a_rec_feat['sc-torsions'],
# # b_rec_feat['sc-torsio... | Python | 1 |
history = trainer.train(
train_data=train_data,
val_data=val_data,
epochs=5, # Small number for demonstration
batch_size=8,
save_attention=True
)
# Plot training history
print("\n📈 Plotting training history...")
trainer.plot_training_history()
# T... | Python | 1 |
min_version: i16,
max_version: i16,
}
impl ApiVersion {
pub fn new(api_key: ApiKey, min_version: i16, max_version: i16) -> Self {
ApiVersion {
api_key,
min_version,
max_version,
}
}
}
use std::convert::TryFrom;
use serde::{Deserialize, Serialize};
... | Rust | 0 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright © 2014, 2015, 2017 Kevin Thibedeau
# (kevin 'period' thibedeau 'at' gmail 'punto' com)
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software... | Python | 1 |
dropout_rate=dropout_rate,
use_bias=use_bias,
)
]
for i in range(n_downsampling): # add upsampling layers
mult = 2 ** (n_downsampling - i)
model += [
SuperConvTranspose2d(
ngf * mult,
... | Python | 1 |
'''
Hey friend! Glad you're curious about this, but please don't touch this file :>)
'''
from csv_utils import *
import os
def main():
# fstream writing tests!
binary_to_csv(
R"D:\Projects\2024-2-26-CS106L\Assignments\Assignment1_simpleenroll/utils/courses_not_offered.bin",
R"D:\Projects\2024-2-26-CS106L\... | Python | 1 |
41, 55, 46,
245, 40, 244, 102, 143, 54, 65, 25, 63, 161,
1, 216, 80, 73, 209, 76, 132, 187, 208, 89,
18, 169, 200, 196, 135, 130, 116, 188, 159, 86,
164, 100, 109, 198, 173, 186, 3, 64, 52, 217,
226, 250, 124, 123, 5, 202, 38, 147, 11... | Rust | 0 |
nt'"
assert value >= 0 and value < 65536, \
"The 'n_dop' field must be an unsigned integer in [0, 65535]"
self._n_dop = value
@builtins.property
def e_dop(self):
"""Message field 'e_dop'."""
return self._e_dop
@e_dop.setter
def e_dop(self, value):
... | Python | 1 |
P2ps, TypedUsize, VecMap},
crypto_tools::{hash::Randomness, k256_serde, mta::Secret, paillier, vss, zkp::pedersen},
gg20::{
keygen::{KeygenShareId, SecretKeyShare},
sign::{
r3::{
self,
common::{check_message_types, R3Path},
},
... | Rust | 0 |
bor::de::Deserialize::deserialize(raw)?;
Ok(SscProof::Openings(commhash, vss))
},
2 => {
let commhash = raw_cbor::de::Deserialize::deserialize(raw)?;
let vss = raw_cbor::de::Deserialize::deserialize(raw)?;
Ok(SscProof::Shares(c... | Rust | 0 |
(hn, hv) in &cp.program_options.request_headers {
b.header(hn, hv);
}
let request = b.body(()).unwrap();
http_request_peer(&request, p, l2r)
})
}
specifier_boilerplate!(noglobalstate has_subspec);
self_0_is_subspecifier!(proxy_is_multiconnect);
}
... | Rust | 0 |
.xctrunner.name
plist["CFBundleIdentifier"] = config.xctrunner.bundle_identifier
plistlib.dump(plist, open(config.xctrunner.info_plist_path, "wb"))
# Copy dependencies to the bundle and remove unwanted architectures
for framework in FRAMEWORK_DEPS:
log.info("Bundling fwk: %s", framework... | Python | 1 |
return f'ceph<{self.ceph.name}>@pool<{self.pool_name}>'
class GlobalConfig(models.Model):
"""全局配置表-站点参数"""
class ConfigName(models.TextChoices):
SITE_NAME = 'siteName', _('站点名称[siteName]')
POWERED_BY = 'poweredBy', _('技术支持[poweredBy]')
NOVNC_ACCESS = 'novncAccess', _('vnc http协议'... | Python | 1 |
string += &format!(
" {}({}): #({}, {})\n",
token.name(),
token.text(),
token.associativity(),
token.precedence()
);
}
if self.tags.len() > 0 {
string += " Tags:\n";
for tag i... | Rust | 0 |
PartialEq)]
pub enum UnaryKind {
BitNot,
Not,
}
impl TryFrom<String> for OperatorKind {
type Error = ();
fn try_from(value: String) -> Result<Self, Self::Error> {
#[rustfmt::skip]
return match value.as_ref() {
"+" => Ok(Self::BinaryOperator(BinaryKind::Add)),
... | Rust | 0 |
,
random_seed: int,
) -> None:
"""
Move UMAP points so they cover some fraction of the plot area without overlapping.
**Input**
The input annotated ``adata`` is expected to contain the per-observation properties
``<prefix>x`` and ``<prefix>y`` (default prefix: {prefix}) which contain the UMAP ... | Python | 1 |
t::skip]
const FROBENIUS_COEFF_FP6_C1: &'static [Fq] = &[
FQ_ONE,
field_new!(Fq, BigInteger([
2665418275744511426,
7073776242814464967,
4441331072847607829,
5681016258918493042,
18254896527151449163,
10681724016023285331,
... | Rust | 0 |
import os
import time
import numpy as np
import torch
import torch.nn as nn
from torch import optim
from torch.autograd import Variable
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
from torchvision import transforms
from load_data import CHARS,LPRDataLoader
from LPRNet import build_lprnet
# ... | Python | 1 |
import pandas as pd
import sqlite3
class PresencialDataProcessor:
def __init__(self, csv_path, db_path):
self.csv_path = csv_path
self.db_path = db_path
self.df_presencial = None
def load_data(self):
"""Carrega os dados do arquivo CSV."""
self.df_presencial = pd.read_cs... | Python | 1 |
from langchain import hub
prompt = hub.pull("hwchase17/react-chat")
prompt.template = """
Pastry Customer Service Assistant is a large language model trained by OpenAI.
Pastry Customer Service Assistant is designed to be able to assist with its current pastry business products catalog related tasks, from answering s... | Python | 1 |
.
use {
crate::ie::*,
paste,
std::{
cmp::{max, min},
collections::HashSet,
ops::BitAnd,
},
zerocopy::LayoutVerified,
};
// TODO(fxbug.dev/42763): HT and VHT intersections defined here are best effort only.
// For example:
// struct Foo { a: u8, b: u8 };
// impl_intersect!(... | Rust | 0 |
).map_err(|e| format!("{}", e))?;
let winner = pos.turn();
let looser = winner.opponent();
if pos.valid() { Ok(()) } else { Err("invalid position".to_string()) }?;
if pos.validEndgame() { Ok(()) } else { Err("no endgame".to_string()) }?;
let mut e_hash = HashMap::new();
let mut m_hash = HashMap:... | Rust | 0 |
is controlled by a :class:`TimedeltaIndex`.
"""
axis: Axis
@staticmethod
def format_timedelta_ticks(x, pos, n_decimals: int) -> str:
"""
Convert seconds to 'D days HH:MM:SS.F'
"""
s, ns = divmod(x, 10**9) # TODO(non-nano): this looks like it assumes ns
m, s = d... | Python | 1 |
n('--groupname', required=True, help='Groupname to remove username(s)')
def remove_user_from_group(username: list[str], groupname: str):
"""
Remove username(s) from a group.
"""
context = ClusterManagerUtils.get_soca_cli_context_cluster_manager()
result = None
try:
result = context.unix_... | Python | 1 |
k endpoint
@app.post("/api/v1/processing/callback/{task_id}")
async def processing_callback(task_id: str, result: dict):
"""Handle processing results from Celery workers"""
try:
# Update document status based on processing result
document_id = result.get("document_id")
status = result.ge... | Python | 1 |
def strangeCounter(t):
# counter = []
# initial = 3
# current_initial = initial
# for i in range(t):
# if current_initial == 1:
# counter.append(current_initial)
# initial = initial * 2
# current_initial = initial
# else:
# counter.appen... | Python | 1 |
Normal_3
0x77,// 119 = "btc"
0x6C,// 'l'
0x01,// 0x1 = MnemonicSuffixIfMem
// Btc_rm64_imm8
0x05,// Normal_3
0x77,// 119 = "btc"
0x71,// 'q'
0x01,// 0x1 = MnemonicSuffixIfMem
// Btc_rm16_r16
0x02,// Normal_2a
0x77,// 119 = "btc"
0x77,// 'w'
// Btc_rm32_r32
0x02,// Normal_2a
0x77,// 119 = "btc"
0x6C,/... | Rust | 0 |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler
import seaborn as sns
import os
def setup_style():
plt.style.use('default')
plt.rcParams['figure.figsize'] = [10, 6]
plt.rcParams['font.sans-serif'] = ['Ari... | Python | 1 |
* **Parameters:**
*
* * `field_name: &str` -- The license key provided with your New Relic account.
* * `on_behalf_of: &str` -- The license key provided with your New Relic account.
*/
pub async fn get_contactdb_recipients_search(
&self,
field_name: &str,
) -> Result<crate::t... | Rust | 0 |
# Copyright (c) OpenMMLab. All rights reserved.
from .inference import (inference_bottom_up_pose_model,
inference_top_down_pose_model, init_pose_model,
process_mmdet_results, vis_pose_result)
from .inference_3d import (extract_pose_sequence, inference_interhand_3d_model,
... | Python | 1 |
= Rc::new(Cons(Rc::clone(&value), Rc::new(Nil))); // a: 含 value 的 Cons 变体
// b 和 c 同时指向 a
let b = Cons(Rc::new(RefCell::new(6)), Rc::clone(&a));
let c = Cons(Rc::new(RefCell::new(10)), Rc::clone(&a));
// *value.borrow_mut() += 10; // 调用 borrow_mut 将 value 指向的值增加 10
// 自... | Rust | 0 |
e()
////// .mount("/user", routes![update, delete])
////// .mount("/users", routes![read])
//// .manage(db::connect())
//// .launch();
//}
// run-pass
// Test that unsafe impl for Sync/Send can be provided for extern types.
#![feature(extern_types)]
extern "C" {
type A;
}
unsafe impl ... | Rust | 0 |
"""
encode: TC: O(n), SC: O(l)
decode: TC: O(n), SC: O(l)
input으로 들어온 string들의 길이를 전부 더한 값을 l이라고 하자.
input에 들어있는 아이템 개수를 n이라고 하자.
아이디어:
- 인풋을 처리한 값 앞쪽에 인풋을 해석하기 위한 정보를 두자.
- 즉, 인풋을 처리한 값을 일종의 body로 보고 앞에 header를 붙이는 접근.
- header는 body의 값이 어떻게 들어와도 영향을 받지 않는다!
- 다음과 같이 encode를 한다.
- encode한 string은 f'{hea... | Python | 1 |
c_i_bw1(&self) -> GAIN_CTRL6_ROSDAC_I_BW1_R {
GAIN_CTRL6_ROSDAC_I_BW1_R::new(((self.bits >> 18) & 0x3f) as u8)
}
#[doc = "Bits 12:17"]
#[inline(always)]
pub fn gain_ctrl6_rosdac_q_bw1(&self) -> GAIN_CTRL6_ROSDAC_Q_BW1_R {
GAIN_CTRL6_ROSDAC_Q_BW1_R::new(((self.bits >> 12) & 0x3f) as u8)
... | Rust | 0 |
List[PIL.Image.Image]], output_video_path: str = None, fps: int = 10
) -> str:
# TODO: Dhruv. Remove by Diffusers release 0.33.0
# Added to prevent breaking existing code
if not is_imageio_available():
logger.warning(
(
"It is recommended to use `export_to_video` with `i... | Python | 1 |
from . import start_button
from . import contact | Python | 1 |
import os
from setuptools import find_packages, setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="djangobench",
version="0.10",
description="A harness and a set of benchmarks for measuring Django's performance over time.",
long_description=rea... | Python | 1 |
atch_normalize(
&g_lagrange_projective[starts..(starts + g_lagrange.len())],
g_lagrange,
);
});
drop(g_lagrange_projective);
g_lagrange
};
let hasher = C::CurveExt::hash_to_curve("Halo2-Parameters");
let... | Rust | 0 |
import torch
import torch.nn.functional as F
import numpy as np
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def get_mask_from_lengths(lengths, max_len=None):
batch_size = lengths.shape[0]
if max_len is None:
max_len = torch.max(lengths).item()
ids = torch.arange(0, max_l... | Python | 1 |
world);
spawn_two::<15>(world);
spawn_two::<16>(world);
spawn_two::<17>(world);
spawn_two::<18>(world);
spawn_two::<19>(world);
spawn_two::<20>(world);
spawn_two::<21>(world);
spawn_two::<22>(world);
spawn_two::<23>(world);
spawn_two::<24>(... | Rust | 0 |
n): '
'(%(vol_id)s,%(host)s,%(port)s,%(iqn)s)'), log_params)
if (volume_id is None or
target_host is None or
target_iqn is None):
raise StorageError(_('Unable to obtain target information'
' %s') % connection_data)
volume_info = {}
volu... | Python | 1 |
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 18 09:51:20 2017
@author: Quantum Liu
"""
import re,requests
import argparse
def get_video(videopage):
#从播放页抓取视频详情,返回一个图片来了包括不同质量的MP4文件地址的一个字典,时长(秒),一个包含浏览数、赞/踩比率和数量以及所属分类的字典。可单独使用。
#Crawling detail of the video, return a tuple which has a dict of MP4 file's addre... | Python | 1 |
okm.fill(&mut r).unwrap();
My(r)
}
}
use clap::Parser;
use std::fs::create_dir_all;
use std::path::PathBuf;
use std::str::FromStr;
/// Configuration option for setting and getting:
/// setting requires name and value, getting only requires name
#[derive(Clone)]
pub struct ConfigOption {
pub nam... | Rust | 0 |
)
weather_text = f"Weather forecast:\n{weather}" if weather else ""
universal_prompt = f"""You are a creative, fun Task Planning Agent. Based on the user's goal: '{goal}', create a tailored, universal response for ANY query type (travel, learning, tasks, etc.).
Universal Guidelines (apply to ALL responses... | Python | 1 |
lib as lib;
use lib::*;
use std::rc::Rc;
struct Local;
impl<T> Remote2<Rc<T>, Local> for usize { }
fn main() {}
use gedcomx::{
Agent, Attribution, Date, Fact, FactType, Gedcomx, GenderType, Name, NameForm, NamePart,
NamePartType, Person, PersonBuilder, PlaceDescription, PlaceReference, Relationship,
Relat... | Rust | 0 |
//!
use amethyst::{
assets::{AssetStorage, Handle, Loader, ProgressCounter},
prelude::*,
renderer::{ImageFormat, SpriteRender, SpriteSheet, SpriteSheetFormat, Texture},
};
///
/// For when you're too lazy to decide/remember if your whole numbers are i16 or u8, use `Int`.
///
pub(crate) type Int = i16;
//... | Rust | 0 |
from langchain_core.runnables.configurable import (
DynamicRunnable,
RunnableConfigurableAlternatives,
RunnableConfigurableFields,
StrEnum,
make_options_spec,
)
__all__ = [
"DynamicRunnable",
"RunnableConfigurableAlternatives",
"RunnableConfigurableFields",
"StrEnum",
"make_opti... | Python | 1 |
default() -> Scissor {
Scissor::irrelevant()
}
}
impl From<Scissor> for ash::vk::Rect2D {
#[inline]
fn from(val: Scissor) -> Self {
ash::vk::Rect2D {
offset: ash::vk::Offset2D {
x: val.origin[0] as i32,
y: val.origin[1] as i32,
},
... | Rust | 0 |
import json
import jsonpickle
import pytest
from rasa.core import utils
from rasa.core.domain import Domain
from rasa.core.tracker_store import InMemoryTrackerStore
from tests.core.utilities import tracker_from_dialogue_file
from tests.core.conftest import TEST_DIALOGUES, EXAMPLE_DOMAINS
@pytest.mark.parametrize("f... | Python | 1 |
from abaqusConstants import *
from .ConstrainedSketchGeometry import ConstrainedSketchGeometry
class ArcByCenterEnds(ConstrainedSketchGeometry):
def __init__(
self,
center: tuple[float],
point1: tuple[float],
point2: tuple[float],
direction: SymbolicConstant,
):
... | Python | 1 |
D\r\n";
assert_eq!(parse(input), Err(ParseError::from(ParseErrorKind::InvalidCommand)));
let input = "MKD bla\r\n";
assert_eq!(parse(input), Ok(Command::Mkd { path: "bla".into() }));
}
#[test]
fn parse_mkd_eols() {
let input = "MKD \r";
assert_eq!(parse(input), Err(ParseError::from(ParseErrorKind:... | Rust | 0 |
e_thread,
prefetch_batches=4,
)
# Force execution of the iterator.
# This step should not raise an exception.
list(output_batches)
try:
e = q.get(block=False, timeout=0.1)
raise e
except queue.Empty:
pass
# Test for 3 cases
# 1. Batch size is less than block s... | Python | 1 |
from utils.affiliation.integral_interval import interval_intersection
def t_start(j, Js=None, Trange=(1, 10)):
if Js is None:
Js = [(1, 2), (3, 4), (5, 6)]
b = max(Trange)
n = len(Js)
if j == n:
return 2 * b - t_stop(n - 1, Js, Trange)
else:
return Js[j][0]
def t_stop(j, ... | Python | 1 |
e_in_broker
events: Vec<Event<I>>,
}
impl<I, MT> EventFirer<I> for SimpleEventManager<I, MT>
where
I: Input,
MT: Monitor, //CE: CustomEvent<I, OT>,
{
fn fire<S>(&mut self, _state: &mut S, event: Event<I>) -> Result<(), Error> {
match Self::handle_in_broker(&mut self.monitor, &event)? {
... | Rust | 0 |
r that watches the channel referred to by the given outpoint.
///
/// Calls back to [`chain::Filter`] with the funding transaction and outputs to watch.
///
/// Note that we persist the given `ChannelMonitor` while holding the `ChainMonitor`
/// monitors lock.
fn watch_channel(&self, funding_outpoint: OutPoint, m... | Rust | 0 |
AccountId, Balance, BlockNumber),
// sender, dest, amount, block number
TransferFunds(AccountId, AccountId, Balance, BlockNumber),
}
);
decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
fn deposit_event() = default;
pub fn lock_funds(origin, amo... | Rust | 0 |
default_filter: if matches.is_present("system") {
DefaultFilter::System
} else if matches.is_present("all") {
DefaultFilter::All
} else {
DefaultFilter::Data
},
filter: matches.value_of("filter").map(|s| s.to_string(... | Rust | 0 |
ze_structure_crate_model_placement_constraint(
object: &mut aws_smithy_json::serialize::JsonObjectWriter,
input: &crate::model::PlacementConstraint,
) -> Result<(), aws_smithy_http::operation::SerializationError> {
if let Some(var_385) = &input.r#type {
object.key("type").string(var_385.as_str());
... | Rust | 0 |
in_once(test, timeout_sec=1.0) # wait for poseCallback
while test.costmap == None:
test.info_msg('Getting initial map')
rclpy.spin_once(test, timeout_sec=1.0)
test.moveToFrontiers()
rclpy.spin(test)
# result = test.run(True)
# assert result
# # preempt with new point
# t... | Python | 1 |
efunction(method):
@functools.wraps(method)
async def method_async_wrapper(flow_instance: Any, *args: Any, **kwargs: Any) -> T:
method_coro = method(flow_instance, *args, **kwargs)
if asyncio.iscoroutine(method_coro):
result... | Python | 1 |
# -*- coding: utf-8 -*-
import scrapy
import json
import time
from scrapy.http import Request
from ..items import IceItem
from scrapy.loader import ItemLoader
from urllib import parse
class XueqiuSpider(scrapy.Spider):
"""
雪球投资网头条模块页面解析类
https://xueqiu.com/
"""
name = 'xueqiu'
# allowed domai... | Python | 1 |
(RefCell::new(None));
let HostImportDescriptor {
host_exported_func,
argument_types,
output_type,
error_handler,
} = descriptor;
let output_type_to_types = |output_type| match output_type {
Some(ty) => vec![ty],
None => vec![],
};
let raw_args = ity... | Rust | 0 |
import numpy as np
import matplotlib.pyplot as plt
#Number of samples:
num_samples = 10000
# Values of N:
N_values = [2, 20, 200, 5000]
# Equation for the calculation of the mean value for X and Y variables:
def calculate_mean(data):
return np.mean(data)
# Determine the means of X and Y variables as matrices in... | Python | 1 |
#
# SPDX-License-Identifier: MIT
#
# Copyright (c) 2025 Carsten Igel.
#
# This file is part of simplepycons
# (see https://github.com/carstencodes/simplepycons).
#
# This file is published using the MIT license.
# Refer to LICENSE for more information
#
""""""
# pylint: disable=C0302
# Justification: Code is generated
... | Python | 1 |
else {
//! o.set_state(Timestamp(0));
//! }
//! }
//!
//! fn next(i: NextIn<Self>, o: &mut Out<Self>) {
//! let Event::Receive(src, MsgWithTimestamp(timestamp)) = i.event;
//! if timestamp > i.state.0 {
//! o.set_state(Timestamp(timestamp + 1));
//! o... | Rust | 0 |
emoteEntryLinkRequest { remote_entry, target_entries, removed_entries } = indexes;
Ok(sync_remote_index(
&COMMITMENT_ENTRY_TYPE, &remote_entry,
&PROCESS_ENTRY_TYPE,
target_entries.as_slice(),
removed_entries.as_slice(),
&COMMITMENT_INPUT_OF_LINK_TAG, &PROCESS_COMMITMENT_INPU... | Rust | 0 |
h (s mod 2^c) P parts
let mut exp = exp;
exp.shr(skip);
let exp = exp.as_ref()[0] % mask;
if exp != 0 {
let idx = (exp - 1) as usize;
if buffers[idx].len() == BUFFER_SIZE {
... | Rust | 0 |
""" Copied from [NeuralRecon](https://github.com/zju3dv/NeuralRecon) by Jiaming Sun and Yiming Xie. """
import torch.nn as nn
import torch.nn.functional as F
import torchvision
def _round_to_multiple_of(val, divisor, round_up_bias=0.9):
""" Asymmetric rounding to make `val` divisible by `divisor`. With default
... | Python | 1 |
= Point(waypoint['point']['x'], waypoint['point']['y'])
if path_buffer.contains(waypoint_point):
self.filtered_waypoints.append(waypoint)
# 현재 위치 가져오기
try:
trans = self.tf_buffer.lookup_transform('map', 'base_link', rclpy.time.Time())
robot_position ... | Python | 1 |
monitor(&self, mut writer: BufWriter<&TcpStream>) {
let listener = self.monitor.listen();
loop {
match listener.recv() {
Some(data) => {
let value = Value::String(data);
if writer.write(&value.encode()).is_err() { break; }
... | Rust | 0 |
import tkinter as tk
from ui.interface import UserInterface
from scanner.subdomain_finder import SubdomainFinder
from scanner.vulnerability_scanner import VulnerabilityScanner
from scanner.stop_scan import StopScan
class BugHuntingTool:
def __init__(self):
self.ui = UserInterface()
self.subdomain_f... | Python | 1 |
ault CLIP model setting. If you forget to use multiples of 64px in your dimensions, DD will adjust the dimensions of your image to make it so."
)
self.arg_input_group.add_argument(
'--n_batches',
type=int,
default=1,
help=
"This variable sets ... | Python | 1 |
#[token("min")]
#[token("mins")]
Minute,
#[token("h")]
#[token("hr")]
#[token("hour")]
#[token("hours")]
Hour,
#[token("dy")]
#[token("day")]
#[token("days")]
Day,
#[token("wk")]
#[token("week")]
#[token("weeks")]
Week,
#[token("mth")]
#[token("mths")]... | Rust | 0 |
from crewai import Agent, Task
from ai_trading_crew.config import PROJECT_LLM, AGENT_OUTPUTS_FOLDER, settings
from ai_trading_crew.utils.dates import get_today_str_no_min
import yaml
import os
today_str_no_min = get_today_str_no_min()
class MarketOverviewAnalyst:
"""Market Overview Analysis crew component"""
... | Python | 1 |
from typing import TypedDict
from opencc import OpenCC
class Credential_Azure(TypedDict):
azure_endpoint: str
api_version: str
api_key: str
class Credential_OpenAI(TypedDict):
api_key: str
base_url: str
def passage_splitter(passage: str, length: int = 1000) -> tuple[str, str]:
if len(passag... | Python | 1 |
:cafe::17]",for=unknown"#)?
.forwarded_for(),
Forwarded::parse(r#"for=192.0.2.43, for="[2001:db8:cafdf8:f53e:61e4::187]", for=unknown"#)?
.forwarded_for()
);
assert_eq!(
Forwarded::parse(
r#"for=192.0.2.43,for="this is a valid quot... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.