text string | label_name string | labels int64 |
|---|---|---|
category = meta.get(META_KEY_CATEGORY).cloned().unwrap_or_else(|| {
path.parent()
.expect("post file had no parent")
.file_name()
.expect("post parent had no name")
.to_str()
.expect("post parent had non-utf8 name")
... | Rust | 0 |
ut(ratio=1, name="main"),
Layout(size=10, name="footer"),
)
layout["main"].split_row(Layout(name="side"), Layout(name="body", ratio=2))
layout["body"].split_row(Layout(name="content", ratio=2), Layout(name="s2"))
layout["s2"].split_column(
Layout(name="top"), Layout(name="middle"), La... | Python | 1 |
info(file, line, module_path, target, &msg),
Level::Debug => debug(file, line, module_path, target, &msg),
Level::Trace => trace(file, line, module_path, target, &msg),
}
}
fn flush(&self) {}
}
/// Try to set lttng-ust as the logging facility, reporting an error if the
/// ope... | Rust | 0 |
char) {
let prev: u8;
if register == 'm' {
prev = self.ram[self.reg["hl"]];
} else {
prev = self.reg[register];
}
let result = prev.wrapping_add(1);
self.reg.set_flag("zero", (result & 0xff) == 0);
self.reg.set_flag("sign", (result & 0x80)... | Rust | 0 |
::NotPresent) => default,
Err(VarError::NotUnicode(_)) => panic!("Environment variable is not unicode: {}", key),
}
}
let linear_interpolation = parse_env("XM_LINEAR_INTERPOLATION", true);
let ramping = parse_env("XM_RAMPING", true);
let debug = parse_env("XM_DEBUG", false);
let... | Rust | 0 |
= "[Bardo de valor]"
self.name = "bardo_de_valor"
class ZeroDivisionBardo(RTError):
def __init__(self, pos_start, pos_end, details, context):
super().__init__(pos_start, pos_end, f'Ah, mirá qué pillo, queriendo dividir por cero. Dale, probá otra vez: {details}', context)
self.error_nam... | Python | 1 |
th the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express o... | Rust | 0 |
= True
model_cfg['masked_softmax_fusion'] = False
model_cfg['bias_gelu_fusion'] = False
model = ModelPT.restore_from(
restore_path=nemo_in,
save_restore_connector=connector,
trainer=trainer,
... | Python | 1 |
: no
sqlsrv.sybpcidb_device_physical_name: PUT_THE_PATH_OF_YOUR_SYBPCIDB_DATA_DEVICE_HERE
sqlsrv.sybpcidb_device_size: USE_DEFAULT
sqlsrv.sybpcidb_database_size: USE_DEFAULT
# If sqlsrv.do_optimize_config is set to yes, both sqlsrv.avail_physical_memory and sqlsrv.avail_cpu_num need to be set.
sqlsrv.do_optimize_config... | Rust | 0 |
(1.0, Rgba::WHITE),
Fill::Solid(session.fg.into()),
));
// Bg color
canvas.add(Shape::Rectangle(
Rect::origin(11., 11.).with_origin(
(session.width * 0.4).floor() + 25.,
self::LINE_HEIGHT + self::MARGIN + 2.,
... | Rust | 0 |
new.filter_similar,
Vec::<String>::new()
);
update_if_not_default!(
&mut conf.filter_word_count,
new.filter_word_count,
Vec::<usize>::new()
);
update_if_not_default!(
&mut conf.filter_line_count,
new.fil... | Rust | 0 |
body(GetDepositAddressesRequest { asset, method })?
.send()
.await
}
}
}
use criterion::criterion_group;
use criterion::criterion_main;
use criterion::BenchmarkId;
use criterion::Criterion;
use holochain_serialized_bytes::prelude::*;
use holochain_websocket::*;
use tokio::ru... | Rust | 0 |
from gridtime import gridtime as gt
from datetime import date, datetime
if __name__ == "__main__":
h = gt.MonthDecade(2025, 10, 1) # ↑1st (noc cofnięcia czasu)
print(h.shift(-3))
print(h.shift(-2))
print(h.shift(-1))
print(h.shift(0))
print(h.shift(1))
print(h.shift(2))
pr... | Python | 1 |
from controller import *
from findimg import *
from utilities import *
from img.party_img import *
from img.utilities_img import *
import img
from findimg import *
import random
def waiting_for_refreshing():
while pyautogui.pixelMatchesColor(1030, 543, (255, 255, 255)):
time.sleep(0.1)
def enter_yaoqi_pa... | Python | 1 |
# -*- coding: utf-8 -*-
import os
from quadpype.pipeline import (
load,
get_representation_path,
)
from quadpype.hosts.houdini.api import pipeline
class HdaLoader(load.LoaderPlugin):
"""Load Houdini Digital Asset file."""
families = ["hda"]
label = "Load Hda"
representations = ["hda"]
ord... | Python | 1 |
return
try:
result = translator.translate_text(text, target_lang=lang_to)
await ctx.send(result.text)
except Exception as e:
await ctx.send(f"Ошибка: {str(e)}")
@bot.command(name='help')
async def help_command(ctx):
embed = discord.Embed(
title="💾Main information abt... | Python | 1 |
cmap = chosenCmap, aspect='auto') # copper_r autumn_r Greys my_cmap gist_rainbow
cbar = colorbar(im)
xlabel('Target excitatory neuron number')
ylabel('Source excitatory neuron number')
title(name)
savefig(str(fi.number))
if name == 'XeAe' + ending:
XA_values = np.copy(values)#.tr... | Python | 1 |
output=arguments.o,
seed=seeds[i],
includes=arguments.include,
)
print(arguments.sep, file=arguments.o)
if not arguments.fake:
# repeat not supported for all docs
break
def execute_from_command... | Python | 1 |
(digit=digit, dists=dists[:3])
cur_round += digit * base
base *= 10
index -= 1
else:
break
if cur_round == 0:
return -1
# merge remain bboxes, detect round text
if index < 0:
return -1
... | Python | 1 |
hed.index, 'inception3_50.2'] = smoothed
# also do this for others
others = ['inception3_50.1', 'inception3_50.0']
df[others] = df[others].interpolate(method='time', limit_area='inside')
smoothed = df[others].rolling(15).mean().dropna()
smoothed = smoothed.query('index >= @tmin and index <= @tmax')... | Python | 1 |
r::new(5);
let lambda = Lambda::new(Box::new(estring), Box::new(integer),
Box::new(i2));
// Uncomment the following line to see the term type checker assist in action
// stringterm = integerterm;
assert!(estring2.native().to_string() == "Test native".to_string() );
}
<gh_stars>0
u... | Rust | 0 |
# Copyright (c) 2022, Frappe Technologies and contributors
# License: MIT. See LICENSE
import frappe
from frappe.core.utils import set_timeline_doc
from frappe.model.document import Document
from frappe.query_builder import DocType, Interval
from frappe.query_builder.functions import Now
from frappe.utils import get_f... | Python | 1 |
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
st.title("Data Cleaning and Visualization Model")
uploaded_file = st.file_uploader("Upload a CSV file", type=["csv"])
if uploaded_file is not None:
df = pd.read_csv(uploaded_file)
st.write("###... | Python | 1 |
= 0x1A;
pub const CONJOINT_NV: c_uint = 0x9284;
pub const CONSERVATIVE_RASTERIZATION_INTEL: c_uint = 0x83FE;
pub const CONSERVATIVE_RASTERIZATION_NV: c_uint = 0x9346;
pub const CONSERVATIVE_RASTER_DILATE_GRANULARITY_NV: c_uint = 0x937B;
pub const CONSERVATIVE_RASTER_DILATE_NV: c_uint = 0x9379;
... | Rust | 0 |
=> "North Brabant",
"1DDN-NL-BB" => "Breda",
"1DDN-NL-BE" => "Eindhoven",
"1DDN-NL-BH" => "s-Hertogenbosch",
"1DDN-NL-BT" => "Tilburg",
"1DDN-NL-D" => "Drenthe",
"1DDN-NL-DA" => "Assen",
"1DDN-NL-DE" => "Emmen",
"1DDN-NL-F" => "Flevoland",
"1DDN-NL-FA" => "Almere",
"1DDN-NL-FL" ... | Rust | 0 |
16':
nuscenes16_palette = []
for _, value in NUSCENES16_COLORMAP.items():
nuscenes16_palette.append(np.array(value))
palette = np.concatenate(nuscenes16_palette)
else:
n = num_cls
palette = [0]*(n*3)
for j in range(0,n):
lab = j
pal... | Python | 1 |
json::from_str::<BG<f32, U4>>(&s).unwrap();
assert_eq!(ds, bg);
assert!(serde_json::from_str::<BG<f32, U2>>(&s).is_err());
assert!(serde_json::from_str::<BG<i64, U4>>(&s).is_err());
}
#[test]
fn test_serdes_rgb() {
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
struct Rgb {
... | Rust | 0 |
from miio.descriptors import ValidSettingRange
from ..spec_helper import YeelightSpecHelper, YeelightSubLightType
def test_get_model_info():
spec_helper = YeelightSpecHelper()
model_info = spec_helper.get_model_info("yeelink.light.bslamp1")
assert model_info.model == "yeelink.light.bslamp1"
assert mo... | Python | 1 |
from_bytes("87B13133".as_bytes())) // mama maria
.expect("To start playlist");
cx.spawn.user_cyclic().expect("To start user cyclic task");
cx.spawn.leds_cyclic().expect("To start leds cyclic task");
cx.spawn
.battery_status()
.expect("To start battery status t... | Rust | 0 |
.clone())
.or_else(|_| parse_uncompressed_content(path, content)),
}
}
fn parse_compressed_content(path: &Path, content: String) -> Result<Mxfile> {
let mxfile_with_compressed_diagrams: MxfileWithCompressDiagrams =
serde_xml_rs::from_reader(content.as_bytes())
.with_context(|| f... | Rust | 0 |
import tensorflow as tf
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
from tensorflow import keras
from keras import Input, layers
import sys
import hw2_template as hw
model1 = hw.build_model1()
model2 = hw.build_model2()
model3 = hw.build_model3()
# Load CIFAR 10 dataset
(train_imag... | Python | 1 |
def count_code(str):
return sum(1 for i in range(len(str) - 3)
if str[i:i + 2] == 'co' and str[i + 3] == 'e'
) | Python | 1 |
[cfg(test)]
mod tests {
use utility::io::Parseable;
use super::*;
#[test]
fn ddeg() -> Result<(), Error> {
let (input_file, output_file) = utility::testing::get_input_output_file("rosalind_ddeg")?;
let output = usize::parse_line(&utility::io::input_from_file(&output_file)?)?;
a... | Rust | 0 |
import graphene
from graphql_auth.schema import UserQuery, MeQuery
class QueryUser(UserQuery, MeQuery, graphene.ObjectType):
pass | Python | 1 |
v[n.kwargs["offsets"]].shape
batches = offsets_shape[0] - int(n.kwargs["include_last_offset"])
output_dtype = weight.dtype
embedding_size = weight.shape[1]
if op.endswith("acc_ops.embedding_bag_byte_rowwise_offsets"):
embedding_size -= 8
#... | Python | 1 |
slot = bits.into();
self
}
};
// Set bit range of [msb..lsb] with U.
(@field ($(#[$attribute:meta])*) ($($vis:tt)*) _, $setter:tt : $sty:tt [$msb:tt..$lsb:tt] in $slot:tt as $vty:tt) => {
$(#[$attribute])*
$($vis)* fn $setter(&mut self, value: $vty) -> &mut Self {
... | Rust | 0 |
?
)
;
builder = builder.set_db_subnet_group(var_46);
}
,
_ => {}
}
}
} else {
return Err(aws_smithy_xml::decode::XmlError::custom(
"expected CreateDBSubnetGroupResult tag",
))... | Rust | 0 |
# -*- coding: utf-8 -*-
""" Porting example tests. """
import pytest
import math
import types
class TestPorting:
def test_load_module(self, step):
mod = step.import_step()
assert isinstance(mod, types.ModuleType)
assert mod.__name__ == step.name
assert mod.__doc__.startswith("Poi... | Python | 1 |
Ok(file) => file
};
let mut encoder = png::Encoder::new(file, width, height);
encoder.set(png::ColorType::RGB).set(png::BitDepth::Eight);
let mut writer = match encoder.write_header() {
Err(why) => panic!("couldn't write png header to {}: {}", path_display, why.de... | Rust | 0 |
self.element_controller.show_message(f"Objeto '{obj.name}' rotacionado em {angle}° em torno do eixo definido.")
def get_object_center(self, obj):
"""
Calcula o centro geométrico de um objeto em 3D.
Args:
obj (objeto): O objeto para calcular o centro.
... | Python | 1 |
s)
logger.debug('stdevs %s' % stds)
# map up to original set of anchors
labels = _unmap(labels, total_anchors, inds_inside, fill=-1)
bbox_targets = _unmap(bbox_targets, total_anchors, inds_inside, fill=0)
bbox_weights = _unmap(bbox_weights, total_anchors, inds_inside, fill=0)
if logger.lev... | Python | 1 |
message_builder.embed(|embeded|
{
embeded.title("Ferris"); //Title
embeded.description("He is my trusty companion that helps me to live.");
embeded.image("attachment://ferris_eyes.png");
embeded.fields(vec![
... | Rust | 0 |
{:?}", rule);
}
let my_ticket_lines = groups.next().unwrap();
let my_ticket = my_ticket_lines
.lines()
.nth(1)
.unwrap()
.split(',')
.map(|x| x.parse().unwrap())
.collect();
println!("{:?}", my_ticket);
let neary_ticket_lines = groups.next().unwrap(... | Rust | 0 |
from pathlib import Path
from jinja2 import Template
from src.utils.network import Request
from src.utils.time import Time
from src.utils.generate import generate
from src.templates import HTMLSourceCode
from ._template import template_dh, table_dunhao_head
import datetime
async def get_dh(type_: str) -> str | list... | Python | 1 |
import os
import subprocess
import sys
def run_command(command, cwd=None):
try:
subprocess.run(command, shell=True, check=True, cwd=cwd)
return True
except subprocess.CalledProcessError as e:
print(f"执行命令失败: {command}")
print(f"错误信息: {str(e)}")
return False
def build_fr... | Python | 1 |
hod isn't ideal. The correct method would be to ask the Fuchsia
// font service for the font data.
static FONT_DATA: &'static [u8] = include_bytes!(
"../../../../../prebuilt/third_party/fonts/robotomono/RobotoMono-Regular.ttf"
);
static FONT_FACE: Lazy<FontFace> =
Lazy::new(|| FontFace::... | Rust | 0 |
if hasattr(l, "reset_parameters"):
l.reset_parameters(method)
def verify(self, inputs: torch.Tensor, eps: float, epochs: int, lr: float) -> bool:
def run_optimization(
input_bounds: BackwardsBounds, epochs: int, lr: float, index: int = None
) ->... | Python | 1 |
/// An alias definition.
#[derive(Debug, Clone)]
pub struct Alias {
/// The full source range of this definition.
pub range: Range<usize>,
/// Doc comment.
pub doc: Arc<[String]>,
/// Name of this definition.
pub name: String,
/// The term that is aliased.
pub term: Arc<Term>,
}
impl ... | Rust | 0 |
};
}
let mut group = criterion.benchmark_group("update_clone");
group.plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic));
macro_rules! bench_balanced {
($name:ident, $p:ident, $new_vec:expr, $push:ident) => {
group.bench_with_input(BenchmarkId:... | Rust | 0 |
from pathlib import Path
from qgis.PyQt.QtCore import Qt
from qgis.PyQt.QtGui import QPixmap, QColor
from qgis.PyQt.QtWidgets import QSplashScreen, QGraphicsDropShadowEffect, QApplication
PATH_SPLASHSCREEN = Path(__file__).parent / 'splashscreen.png'
class EnMAPBoxSplashScreen(QSplashScreen):
"""
Thr EnMAP-... | Python | 1 |
{
self.metric_unknown_dcop.inc();
}
}
/// Computes the weight of nodes operated by `node_operator`.
///
/// Weight should be inversely proportional to the RTT EMA, so it is
/// computed as `1_000 / rtt_ema`, where `rtt_ema` is the exponential
/// moving average of roundtrip ... | Rust | 0 |
import asyncclick as click
from misc.fill_db import fill_test_data
@click.group()
def cli() -> None: ...
@click.command()
async def filldb() -> None:
"""Заполняем БД тестовыми данными."""
await fill_test_data()
cli.add_command(filldb)
if __name__ == "__main__":
cli(_anyio_backend="asyncio")
| Python | 1 |
"""
Challenge: Friendship Compatibility Calculator
Build a Python script that calculates a fun "compatibility score" between two friends based on their names.
Your program should:
1. Ask for two names (friend A and friend B).
2. Count shared letters, vowels, and character positions to create a compatibility score (0... | Python | 1 |
import sys
from threading import Thread
from rsudp import printM, printW, printE
from rsudp.test import TEST
class Consumer(Thread):
"""
The main consumer process. This consumer reads
queue messages from the :class:`rsudp.p_producer.Producer`
and distributes those messages to each sub-consumer in ``destinations``... | Python | 1 |
ONE_MINUS_SRC_ALPHA)
.alpha_blend_op(vk::BlendOp::ADD)
.color_write_mask(
vk::ColorComponentFlags::R
| vk::ColorComponentFlags::G
| vk::ColorComponentFlags::B
| vk::ColorComponentFlags::A,
)];
let co... | Rust | 0 |
import logging, time
from core.garobot import Garobot
from core.shop import Appointment
from api.notification import Notification
from core.constants import FREQUENCY, FREQUENCY_VARIATION
from core.utils import generate_frequency_variation
logger = logging.getLogger(__name__)
class Scheduler:
def __init__(self, g... | Python | 1 |
a_compromise])
)
assert_crl(stdout, signer=usable_root, idp=idp)
def test_unknown_error(usable_root: CertificateAuthority) -> None:
"""Test that creating a CRL fails for an unknown reason."""
method = "django_ca.managers.crl_scope_validator"
with mock.patch(method, side_effect=Exception("foo")), a... | Python | 1 |
0 => Window::Win0,
1 => Window::Win1,
2 => Window::Outside,
3 => Window::OBJ,
_ => panic!("Invalid window."),
}
}
// @TODO this can be made const when `match` is enabled in const fns in stable Rust.
pub unsafe fn from_index_unsafe(index: u16) -> Wi... | Rust | 0 |
3b49065ba50f\
567660179368a651c05e611fd8ed57a5";
pub const TESTVEC_MULTI_BLS12_381_3_PK: &str = "a6a627ecde572a33a0c6dfd939e1dc48\
e588bd6d457c0d5560aa6bb9d31aa7c8\
0d05c5c95ae... | Rust | 0 |
{len(tags)} 个标签到MongoDB (ID范围: {start_id}-{end_id})")
await self.save_batch_to_mongodb(tags)
await asyncio.sleep(1 + (time.time() % 2)) # 增加随机延迟
return len(tags)
async def fetch_all_tags(self):
"""异步获取所有标签"""
logger.info("开始异步获取所有Danbooru标签...")
# 确保数据库已初始化
... | Python | 1 |
ht = Parameter(np.ones(hidden_size), 'weight')
# self.epsilon = eps
#
# def forward(self, x):
# x_shape = x.shape
# x = x * ((x ** 2).sum(axis=x.ndim - 1) / x_shape[-1] + self.epsilon).reshape(*(x_shape[:-1] + (1,))) ** (-1 / 2)
# x = self.weight * x
# return x
class RoPELla... | Python | 1 |
'เปอร์เซีย', 'ti': 'ፋርስኛ', 'tk': 'pars dili', 'to': 'lea fakapēsia', 'tr': 'Farsça', 'tt': 'фарсы', 'twq': 'Farsi senni', 'tzm': 'Tafarisit', 'ug': 'پارسچە', 'uk': 'перська', 'ur': 'فارسی', 'uz': 'fors', 'uz-Arab': 'دری', 'uz-Cyrl': 'форсий', 'uz-Latn': 'fors', 'vai': 'ꗨꗡꔻꘂꘋ', 'vai-Latn': 'Pɛɛsiyɛŋ', 'vai-Vaii': 'ꗨꗡꔻꘂ... | Python | 1 |
use super::*;
use crate::fp::N_BITS;
use crate::pedersen_ops::rnd_scalar_vec;
use crate::rand_proof::{ElGamalGens, ElGamalPair};
use crate::rand_proof_vec::create_randproof_vec;
use crate::range_proof_vec::create_rangeproof;
use bulletproofs::PedersenGens;
#[test]
fn test_bincode_rp_ve... | Rust | 0 |
import os
import src.db.db as db
from src.llms.llm import LLM
user1 = "user1"
user2 = "user2"
def initDatabase():
chroma_url = os.getenv("CHROMA_URL", "localhost")
database = db.Database(chroma_url, 8000)
database.checkHeartBeat()
return database
database = initDatabase()
database.createCollection(us... | Python | 1 |
is useful to ensure that enum variants do not cause the enum
/// to become too large.
#[derive(Clone)]
pub struct Spanned<T> {
node: Box<T>,
span: Span,
}
impl<T> Spanned<T> {
/// Creates a new spanned node.
pub fn new(node: T, span: Span) -> Spanned<T> {
Spanned {
node: Box::new(n... | Rust | 0 |
pub mod put;
pub use delete::run as delete;
pub use put::run as put;
use std::time::Duration;
use cloudflare::framework::auth::Credentials;
use cloudflare::framework::{Environment, HttpApiClient, HttpApiClientConfig};
use crate::http::feature::headers;
use crate::settings::global_user::GlobalUser;
// Create a spec... | Rust | 0 |
txt ../
popd
rm -rf $model_name
sed -i.bak 's/Zipformer/Zipformer CTC supporting Chinese 中文/g' ../index.html
git diff
""",
),
]
return models
def main():
args = get_args()
index = args.index
total = args.total
assert 0 <= inde... | Python | 1 |
f"insert into orders VALUES ('{dt}','{symbol}', {price} , {quan} , {val},'SELL',{cb})"
cursor.execute(query)
con.commit()
v=s-quan
cursor.execute(f"update portfolio set quantity ={v} , value = {gg} where name = '{symbol}'")
con.commit()
... | Python | 1 |
: i32, b: i32| a.rotate_left(b as u32)),
InstructionKind::I32Rotr => self.binop(|a: i32, b: i32| a.rotate_right(b as u32)),
InstructionKind::I64Clz => self.unop(|v: i64| v.leading_zeros() as i64),
InstructionKind::I64Ctz => self.unop(|v: i64| v.trailing_zeros() as i64),
... | Rust | 0 |
2::new(0.0, 1.0);
let v3 = glam::Vec3A::new(0.0, 0.0, 1.0);
let v3_dx = glam::Vec3A::new(0.0, 1.0, 0.5);
let v3_dy = glam::Vec3A::new(0.0, 1.0, 0.5);
*output = image.sample_depth_reference_by_gradient(*sampler, v2, 1.0, v2_dx, v2_dy);
*output += image_array.sample_depth_reference_by_gradient(*sample... | Rust | 0 |
"ZJared/Haha-7B",
"speakleash/Bielik-11B-v2.3-Instruct",
"NovaSky-AI/Sky-T1-32B-Preview",
"tiiuae/Falcon3-10B-Instruct-FC",
"tiiuae/Falcon3-7B-Instruct-FC",
"tiiuae/Falcon3-3B-Instruct-FC",
"tiiuae/Falcon3-1B-Instruct-FC",
"uiuc-convai/CoALM-8B",
"uiuc-convai/CoALM-70B",
"uiuc-c... | Python | 1 |
max_distance,
pools: Vec::new(),
})))
}
/// Allocates read-, write- & executable memory close to `origin`.
pub fn allocate(&self, origin: usize, size: usize) -> Result<ExecutableMemory, ProximityError> {
let mut allocator = self.0.lock().unwrap();
allocator
... | Rust | 0 |
# test_episode_only.py
from tetris_env import TetrisEnvironment
from train import TetrisTrainer
print("Testing episode collection only...")
trainer = TetrisTrainer()
print("Calling collect_episode...")
experience = trainer.collect_episode()
print(f"Episode complete: {experience['steps']} steps, reward {experience['t... | Python | 1 |
self.language_model = java_generator.JavaLanguageModel()
def _CreateDataValue(self, value, val_type):
def_dict = {
'className': 'Foo',
'type': val_type,
}
prototype = data_types.DataType(
def_dict, None, language_model=self.language_model)
dv = data_value.DataValue(valu... | Python | 1 |
a = 20
b = 10
print(a+b)
print(a-b)
print(a*b)
print(a/b)
print(a%b)
print(a**b)
a = 10
b = 2
a *= b
print(a)
a = 10
b = 2
print(a>b)
a = 18
b = 11
c = 20.2
if a > b and a > c:
print('True')
else :
print("False") | Python | 1 |
PV4, MDNS_IPV6};
use multicast::{MdnsQueryType, MdnsStream};
use xfer::{DnsClientStream, SerialMessage};
use BufDnsStreamHandle;
use DnsStreamHandle;
/// A UDP client stream of DNS binary packets
#[must_use = "futures do nothing unless polled"]
pub struct MdnsClientStream {
mdns_stream: MdnsStream,
}
impl MdnsCli... | Rust | 0 |
es<std::io::BufReader<std::fs::File>>,
) -> Self::Output {
let line = lines.next().unwrap().unwrap();
let crabs = line.split(',').map(|c| c.parse::<usize>().unwrap());
let mut board = [0_u64; SIZE];
for c in crabs {
board[c] += 1;
}
(0..SIZE).map(|p| fin... | Rust | 0 |
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... | Python | 1 |
If neither is wrong, draw.
// お互いがミスしなければ引き分け。
match bestmove.pred_result {
WayValue::Lose => {
// If it gets better, change it to this. Generally called 'Update alpha evaluation'.
// 良くなるならこの手に変えます... | Rust | 0 |
ister modules
port_scan_detector = PortScanDetector(
alert_callback=self.send_alert,
loop=self.loop,
threshold=self.scan_threshold,
time_window=self.time_window,
cooldown=self.cooldown
)
self.register_module("PortScanDetector", port_sca... | Python | 1 |
Option<i64>, bs: &[u8]) -> Action {
let diagnostics: Vec<_> = ck_one_file(bs).into_iter().collect();
Action::Respond(
Outgoing::Notification(OutgoingNotification::PublishDiagnostics(
PublishDiagnosticsParams {
uri,
version,
diagnostics,
},
))
.into(),
)
}
fn ck_on... | Rust | 0 |
connection attempts
const MAX_CONNECTION_ATTEMPTS: usize = 5;
struct VsockSocket {
socket_fd: RawFd,
}
impl VsockSocket {
fn new(socket_fd: RawFd) -> Self {
VsockSocket { socket_fd }
}
}
impl Drop for VsockSocket {
fn drop(&mut self) {
shutdown(self.socket_fd, Shutdown::Both)
... | Rust | 0 |
` or `* mut os_eventq`
extern_type: Box<String>,
/// Wrapped type to be exposed e.g. `:: cty :: c_int` or `* mut os_eventq`
wrap_type: Box<String>,
/// Declare the result type e.g. `BlResult< * mut os_eventq >`
declare_result_tokens: Box<proc_macro2::TokenStream>,
/// Assign the result e.g. `let... | Rust | 0 |
while i <= give_num:
id = random.choice(give_elixir_id_list)
if int(id) == 1999:#不给渡厄丹了
continue
else:
try:
give_dict[id] += 1
i += 1
... | Python | 1 |
import numpy as np
def softmax(vector):
'''
vector: np.array of shape (n, m)
return: np.array of shape (n, m)
Matrix where softmax is computed for every row independently
'''
nice_vector = vector - vector.max()
exp_vector = np.exp(nice_vector)
exp_denominator = np.sum(exp_vecto... | Python | 1 |
state, services }
}
pub fn get_spotify(&self) -> Arc<dyn SpotifyApiClient + Send + Sync> {
Arc::clone(&self.services.spotify_api)
}
pub fn get_batch_loader(&self) -> BatchLoader {
self.services.batch_loader.clone()
}
pub fn get_state(&self) -> Ref<'_, AppState> {
self.... | Rust | 0 |
from unittest.mock import Mock, patch
from PySide6 import QtCore, QtTest
from pytestqt.qtbot import QtBot
from spectrumapp.helpers import (
find_action,
find_menu,
)
from spectrumapp.windows.main_window import BaseMainWindow
@patch('spectrumapp.windows.main_window.BaseMainWindow.not_implemented_plug')
def t... | Python | 1 |
from accounts.models import Stock
class StockController:
@staticmethod
def create_stock(symbol, name, current_price, previous_close, market_cap):
stock = Stock.objects.create(
symbol=symbol,
name=name,
current_price=current_price,
previous_close=previous_... | Python | 1 |
&'a syn::TypePath> {
if is_generic_param(field_ty) {
if let syn::Type::Path(ret) = field_ty {
return Some(ret);
}
}
if let syn::Type::Path(ty) = field_ty {
for seg in ty.path.segments.iter() {
if let syn::PathArguments::AngleBracketed(args) = &seg.arguments {... | Rust | 0 |
ce", self.strategy_engine.strategy_settings)
setting = self.strategy_engine.strategy_settings["test_instance"]
self.assertEqual(setting["class_name"], "TestStrategy")
self.assertEqual(setting["symbol"], "BTCUSDT")
self.assertEqual(setting["parameters"]["test_parameter"], 123)
de... | Python | 1 |
#GreaterAmongTwoNumbers
a=int(input())
b=int(input())
if a>b :
print(a," is greater")
else :
print(b," b is greater")
| Python | 1 |
panic!(format!("file not found. Check {}", path.to_str().unwrap()));
}
};
write!(&file, "{}", text);
}
pub fn get_extension(path: &std::path::PathBuf) -> Option<String> {
// 拡張子を取得
let filename_osstr = path.file_name();
if filename_osstr.is_none() {
return None;
}
... | Rust | 0 |
Hex(ref err) => write!(f, "Hex parsing error: {}", err),
}
}
}
impl From<ethabi::Error> for Error {
fn from(err: ethabi::Error) -> Self {
Error::Ethabi(err)
}
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Self {
Error::Io(err)
}
}
impl From<rustc_hex::FromHexError> for Error {
fn from(err: ... | Rust | 0 |
# Choose targets uniformly from neighbors.
v = seed.choice(list(G.neighbors(u)))
y = seed.choice(list(G.neighbors(x)))
# If the target nodes are the same, skip this pair.
if v == y:
continue
if x not in ... | Python | 1 |
::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [status](status) module"]
pub type STATUS = crate::Reg<u8,... | Rust | 0 |
from engine.core_engine import CoreEngine
import os
def run_conversational_ai():
# Initialize the engine
engine = CoreEngine(max_history_length=50)
# Load conversation history from a file (if available)
history_file = "conversation_history.json"
if os.path.exists(history_file):
engine.load... | Python | 1 |
[END_X,END_Y])
CROP1=[332,854,656,855]
time.sleep(3)
START=time.time()
dis_list=[]
# for i in range (10):
# if IF_START==0:break
# dis=pos_r(white_pos(get_screen_arry(CROP)))
# dis=abs(pos_r(white_pos(get_screen_arry(CROP)))-dis)
# if dis!=0:dis_list.append(dis)
# dis=np.median(dis_list)
di... | Python | 1 |
node1 被选中(实际中可加逻辑确保)
self.assertIn(final_method, ["method_b"], "node1 should have been replaced with method_b for lower loss")
@patch.object(GraphEvoTrainer, '_evaluate_loss_with_instance')
@patch.object(GraphEvoTrainer, '_evaluate_accuracy_with_instance')
def test_refinement_full_sweep_no_improve... | Python | 1 |
)?;
}
_ => panic!("Not implemented"),
}
}
Ok(())
}
fn draw_entity_details_table(
&mut self,
window: &mut Window,
e: Entity,
area: &Rectangle,
text_provider: &mut TableTextProvider,
res_comp: &mut ... | Rust | 0 |
n);
*tc_seqno = tc_seqno.checked_add(1).unwrap();
None
}
}
fn cancel_burn_with_amount_new(
executor: &mut FakeExecutor,
amount: u64,
tc_account: &Account,
tc_seqno: &mut u64,
should_fail: bool,
) -> Option<TransactionOutput> {
let txn = tc_account
.transaction()
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.