text string | label_name string | labels int64 |
|---|---|---|
write!(f, " [")?;
if self.castle_rights[0] {
write!(f, "K")?;
}
if self.castle_rights[1] {
write!(f, "Q")?;
}
if self.castle_rights[2] {
write!(f, "k")?;
}
if self.castle_rights[3] {
... | Rust | 0 |
);
assert_eq!(just_str, "hi");
let just_num = Builder::default().number(254).to_string();
assert_eq!(just_num, "254");
let a = Builder::default()
.string("hello, world!")
.number(200)
.to_string();
assert_eq!(a, "hello, world! 200");
let b = Builder::default()
... | Rust | 0 |
import gzip
default_path = '.'
with gzip.open(default_path + "sumdata/train/train.article.txt.gz", "rb") as gz:
with open(default_path + "sumdata/train/train.article.txt", "wb") as out:
out.write(gz.read())
with gzip.open(default_path + "sumdata/train/train.title.txt.gz", "rb") as gz:
with open(defau... | Python | 1 |
elf.a.mul(&f3);
self.b.copy(&f1); self.b.mul(&f3);
self.c.copy(&f2); self.c.mul(&f3);
}
/* self=self^p using Frobenius */
pub fn frob(&mut self,f: &FP2,n:isize) {
let mut f2=FP2::new_copy(f);
let mut f3=FP2::new_copy(f);
f2.sqr();
f3.mul(&f2);
f3.mul_ip(); f3.norm();
for _i in 0..n {
self.a.fr... | Rust | 0 |
gs::archive::init(&lua)?;
bindings::crypto::init(&lua)?;
bindings::string::init(&lua)?;
bindings::system::init(&lua)?;
bindings::text::init(&lua)?;
bindings::web::init(&lua)?;
bindings::number::init(&lua)?;
bindings::net::init(&lua)?;
lua.context(|lua| -> ... | Rust | 0 |
Path::new("FOO/bar/baz.qux")
);
assert_eq!(
modify_path(Path::new("foo/bar/baz.qux"), "_/BAR/_"),
Path::new("foo/BAR/baz.qux")
);
assert_eq!(
modify_path(Path::new("foo/bar/baz.qux"), "_/_/BAZ"),
Path::new("foo/bar/BAZ")
... | Rust | 0 |
import numpy as np
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
# Dot product
print(np.dot(x, y))
#addition
print(x + y) # [5 7 9]
#substraction
print(x - y) # [-3 -3 -3]
#multiplication
print(x * y) # [4 10 18]
#division
print(x / y) # [0.25 0.4 0.5 ]
#exponent
print(x ** 2)
print("********... | Python | 1 |
oincrement=False, nullable=False))
else:
op.add_column('attendee', sa.Column('requested_any_dept', sa.BOOLEAN(), server_default=sa.text('false'), autoincrement=False, nullable=False))
connection = op.get_bind()
requests_for_any = connection.execute(dept_membership_request_table.select().where(
... | Python | 1 |
config = LdapAuthProviderModule.parse_config(config)
else:
config = LdapAuthProviderModule.parse_config(
{
"enabled": True,
"uri": "ldap://localhost:%d" % server.listener.getHost().port,
"base": "ou=people,dc=example,dc=org",
"a... | Python | 1 |
adratic>,
pub bboxes: Vec<Rect>,
pub lut: Vec<(usize, usize)>,
pub face: &'a Face<'a>,
}
#[derive(Debug)]
pub struct Outline {
pub ctrl_pts: Vec<(f32, f32)>,
pub bbox: Rect,
}
impl<'a> Atlas<'a> {
/// Create a new font atlas from a given font face.
/// This is a relatively expensive operat... | Rust | 0 |
, "chanop"], autohelp=False)
def listignores(db, conn, chan):
"""- List all active ignores for the current channel"""
rows = db.execute(
select(table.c.mask).where(
and_(
table.c.connection == conn.name.lower(),
table.c.channel == chan.lower(),
),... | Python | 1 |
pool_size=5,
schema_config="normalize",
)
print(
f"Pool size configured for non-encrypted with key: "
f"{config_with_key.pool_size}"
)
try:
pool, profile_name, path, effective_release_number = (
config_with_key.provisi... | Python | 1 |
w to manage the synchronization?
Vec::new()
}
pub fn input_helper_get_nameplate_completions(
&mut self,
prefix: &str,
) -> Result<Vec<String>, InputHelperError> {
self.input.get_nameplate_completions(prefix)
}
pub fn input_helper_get_word_completions(
&mut s... | Rust | 0 |
of the field is `P2IV_12`"]
#[inline(always)]
pub fn is_p2iv_12(&self) -> bool {
*self == P2IV_A::P2IV_12
}
#[doc = "Checks if the value of the field is `P2IV_14`"]
#[inline(always)]
pub fn is_p2iv_14(&self) -> bool {
*self == P2IV_A::P2IV_14
}
#[doc = "Checks if the val... | Rust | 0 |
er();
let serializer = self.encoding.encoding();
let encoder = Encoder::<()>::new(serializer);
let request_builder = KinesisRequestBuilder {
compression: self.compression,
encoder: (transformer, encoder),
};
let sink = KinesisSink {
batch_set... | Rust | 0 |
s.display();
// creating/ opening the file in write mode
match File::create(path_for_sides) {
Err(why) => error!("error: [suggest side] couldn't create {}: {}", display, why),
Ok(mut file) => {
// format side suggestion message
let side_suggestion ... | Rust | 0 |
Fingerprint::from_hex_string(
"84d89877f0d4041efb6bf91a16f0248f2fd573e6af05c19f96bedb9f882f7882",
)
.unwrap();
let digest_1 = Digest(fingerprint_1, 10);
let bytes_2 = Bytes::from("9876543210");
let fingerprint_2 = Fingerprint::from_hex_string(
"7619ee8cea49187f309616e30ecf54be072259b4376... | Rust | 0 |
ific examples.
///
/// #Example
///
/// ```rust
///
/// extern crate crossterm;
///
/// use self::crossterm::cursor;
///
/// // Get cursor and goto pos X: 5, Y: 10
/// let mut cursor = cursor::cursor();
/// cursor.goto(5,10);
///
/// //Or you can do it in one line.
/// cursor::cursor().goto(5,10);
///
/// ```
pu... | Rust | 0 |
00u16);
for _ in 0..4 {
led.toggle().unwrap();
hal::Delay.delay_ms(100u16);
}
}
}
#![feature(collections)]
#![allow(dead_code, unused_variables, unused_must_use)]
mod parse;
/*
This source code file is distributed subject to the terms of the GNU Affero General Public License... | Rust | 0 |
class GameDirection:
def __init__(self, title, point_guide, objective, control, title_color, images):
self.title = title
self.point_guide = point_guide
self.objective = objective
self.control = control
self.title_color = title_color
self.images = images
def get_... | Python | 1 |
#
# @lc app=leetcode id=27 lang=python
#
# [27] Remove Element
#
# @lc code=start
class Solution(object):
def removeElement(self, nums, val):
i = 0
for x in nums:
if x != val:
nums[i] = x
i += 1
return i
# @lc code=end
# add
| Python | 1 |
on/distribute:input_lib_test_multiworker_gpu, the
# argv[0] is in the form of
# /.../tensorflow/python/distribute/input_lib_test.py
# and the binary is
# /.../tensorflow/python/distribute/input_lib_test_multiworker_gpu
package_root_base = sys.argv[0][: sys.argv[0].rfind(package_r... | Python | 1 |
_strategy.set_graph_config(is_training=False)
program = paddle.static.IpuCompiledProgram(
inference_program, ipu_strategy=ipu_strategy
).compile(feed_list, fetch_list)
else:
program = inference_program
tmp = exe.run(program, feed=self.feed, fetch_list... | Python | 1 |
yonReceiveResult {
pub fn default() -> Self {
let result = TachyonReceiveResult {
channel: 0,
address: NetworkAddress::default(),
length: 0,
error: 0,
};
return result;
}
}
<reponame>envoylabs/cw2981-token-level-royalties
#[cfg(not(feature ... | Rust | 0 |
Addr> for SockaddrStorage {
fn from(s: net::SocketAddr) -> Self {
match s {
net::SocketAddr::V4(sa4) => Self::from(sa4),
net::SocketAddr::V6(sa6) => Self::from(sa6),
}
}
}
impl Hash for SockaddrStorage {
fn hash<H: Hasher>(&self, s: &mut H) {
unsafe {
... | Rust | 0 |
yStem,
) -> Result<(), Error> {
unimplemented!()
}
}
#[async_trait]
impl Execute for Here {
async fn exec(&self, api: &Api, message: &Message) -> Result<(), Error> {
let members: Vec<telegram_bot::User> =
db::get_members(message.chat.id(), 60).unwrap_or(vec![telegram_bot::User {... | Rust | 0 |
import datetime
import random
import secrets
import time
from collections.abc import Callable
import pytz
def gen_random_str(length: int = 32, *, crypto: bool = False) -> str:
choice: Callable[[str], str] = secrets.choice if crypto else random.choice
alphabet = 'qwertyuiopasdfghjkzxcvbnmQWERTYUPASDFGHJKLZXC... | Python | 1 |
# Part of Softhealer Technologies.
# Copyright (C) Softhealer Technologies.
from odoo import models, fields
class ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
pos_sh_enable_default_customer = fields.Boolean(
related="pos_config_id.sh_enable_default_customer", string="En... | Python | 1 |
n.get('FALLBACK','chat') == 'chat':
return 'chat'
if os.environ.get('FALLBACK') == 'bbq':
return 'bbq'
return 'raw'
def dedup(output):
checkx1, prompt_num = check_dup_line(output)
if checkx1 == True:
prompt_line = output.split("\n")
if len(prompt_line) == 1:
... | Python | 1 |
c.read())
elapsed = time.perf_counter() - t0
# Guess original friendly name
base = Path(enc_name_in).name
if base.lower().endswith(".encrypted"):
friendly_dec = base[:-10] # remove ".encrypted"
if not friendly_dec:
friendly_dec = "restored.bin"
... | Python | 1 |
from PyQt5.QtWidgets import QPushButton, QLabel, QLineEdit, QComboBox, QDateTimeEdit
from PyQt5.QtCore import QDate, QDateTime, QTime
def input(page):
# 标题
label_main = QLabel()
label_main.setFont(page.font_main)
label_main.setText(" 指点江山")
page.grid.addWidget(label_main, 0, 0, 1, 4)
# 选择当前时间... | Python | 1 |
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# 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/LICENSE-2.0
#
# Unless requir... | Python | 1 |
tein_pos,
protein_atom_feature = batch.protein_atom_feature.float(),
ligand_pos = batch.ligand_context_pos,
ligand_atom_feature = batch.ligand_context_feature_full.float(),
ligand_bond_index = batch.ligand_context_bond_index,
... | Python | 1 |
import pandas as pd
from sklearn.calibration import calibration_curve
import numpy as np
from matplotlib import pyplot as plt
from tools.feature_tools import rolling_accuracy
import yfinance as yf
# Load data
model_predictions = pd.read_csv('logs/Rolling.csv', index_col=0)
model_predictions.index = pd.to_datetime(mod... | Python | 1 |
_,
comma,
event,
body,
}
} else {
Handler::Predefined(input.parse().map_err(|error| {
Error::new(error.span(), "Expected `fn` or path of event handler")
})?)
}
};
let component_name = cx
.component_name
.ok_or_else(|| {
Error::new(
on.span,
"Event bindings ... | Rust | 0 |
91\x9e\xf2QE\xfa\xe8\x84\x93\xe5LMt\
\x0a\xcc\xcb\x00\x11\x81}\xa7\x90b\xdb\x8e\xe5\x18\xa9\xbd\
\x13K\xc1\xdf'g\xac\x03hjo\x00\xd5\xbc\x09O\
\x17\x94k\x0868\xbf\x8b\x01\xdc\x19`~\x97\xf9w\
\xc1\xbc%\xcag\xaf\xeb_\xa6\xe8\x1eQ\x0d\xc4\x91\xd2\
\x9a)8\xd00/\xca;\xb7\x96I\xb1+l\xed\xa4\
\xe7a\xa8\xf5\xe4\x0a\x06\x96o\xbc... | Python | 1 |
.unwrap();
},
_ => {}
}
}
#[no_mangle]
pub extern "system" fn Java_io_zbox_fs_RepoOpener_jniOpsLimit(
env: JNIEnv,
obj: JObject,
limit: jint,
) {
let mut opener = unsafe {
env.get_rust_field::<&str, RepoOpener>(obj, RUST_OBJ_FIELD)
.unwrap()
}... | Rust | 0 |
reject any transactions that use
/// that `recent_blockhash` in a transaction. Lowering this value reduces memory consumption,
/// but requires clients to update its `recent_blockhash` more frequently. Raising the value
/// lengthens the time a client must wait to be certain a missing transaction will
/// not be proce... | Rust | 0 |
None => return Err(AVRError::MalformedReportBody.into()),
};
Ok(quote_body)
}
}
/// Attestation verification report.
#[derive(Debug, Default, Clone, cbor::Encode, cbor::Decode)]
pub struct AVR {
pub body: Vec<u8>,
pub signature: Vec<u8>,
pub certificate_chain: Vec<u8>,
}
///... | Rust | 0 |
f.write("\n")
plt.figure()
plt.plot(self.epoches, self.maps, 'red', linewidth = 2, label='train map')
plt.grid(True)
plt.xlabel('Epoch')
plt.ylabel('Map %s'%str(self.MINOVERLAP))
plt.title('A Map Curve')
pl... | Python | 1 |
let one = VWrap::new_with_val(OpConst::new(), ValType::F(1.));
let a = Div(one, Mul(Cos(inputs[0].clone()), Cos(inputs[0].clone())));
vec![Mul(a, out_adj.clone())]
},
)
}
}
impl FWrap for OpPow {
fn new() -> Box<dyn FWrap>
where
... | Rust | 0 |
# Generated by Django 3.2.8 on 2024-01-11 20:52
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('employee', '0200_alter_employee_options'),
]
operations = [
migrations.AlterField(
model_name='... | Python | 1 |
e_dir or model_cache_dir,
)
else:
data_args.p_max_len = max_len
hf_dataset = HFCorpusDataset(
tokenizer=tokenizer,
data_args=data_args,
cache_dir=data_args.data_cache_dir or model_cache_dir,
)
encode_dataset... | Python | 1 |
vif,image/webp,image/apng,*[inserted by cython to avoid comment closer]/[inserted by cython to avoid comment start]*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'sec-fetch-site': 'same-origin', 'sec-fetch-mode': 'navigate', 'sec-fetch-user': '?1', 'sec-fetch-dest': 'document', 'accept-encoding': 'gzip, deflate, br',... | Python | 1 |
#[doc = "*Required features: `\"Win32_Graphics_Direct3D12\"`*"]
pub const D3D12_FEATURE_ARCHITECTURE1: D3D12_FEATURE = 16i32;
#[doc = "*Required features: `\"Win32_Graphics_Direct3D12\"`*"]
pub const D3D12_FEATURE_D3D12_OPTIONS2: D3D12_FEATURE = 18i32;
#[doc = "*Required features: `\"Win32_Graphics_Direct3D12\"`*"]
pu... | Rust | 0 |
bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | ((value as u32 & 0x01) << 3);
self.w
}
}
#[doc = "Field `RX_FILTER_EN_CH3` reader - reg_rx_filter_en_ch3."]
pub struct RX_... | Rust | 0 |
Enter(Field(_)) => {
ctx.skip_value(seq)?;
break;
}
Enter(CollectionIndex(idx)) => {
if let Some(value_ref) = self.get_mut(idx) {
... | Rust | 0 |
/// register.
///
/// ## Parameters
///
/// - `value`: The counter value to mark as a position. This must be in the
/// range `0 .. R::BITS`.
///
/// ## Returns
///
/// This unconditionally marks `pos` as a valid bit-position.
///
/// ## Safety
///
/// If the `pos` value is outside the valid range, then... | Rust | 0 |
F.pixel_shuffle(kernel_tensor, self.up_factor) # (N, S^2 * Kup^2, H, W)->(N, Kup^2, S*H, S*W)
kernel_tensor = F.softmax(kernel_tensor, dim=1) # (N, Kup^2, S*H, S*W)
kernel_tensor = kernel_tensor.unfold(2, self.up_factor, step=self.up_factor) # (N, Kup^2, H, W*S, S)
kernel_tensor = kernel_tenso... | Python | 1 |
istant.")
from anyasfriend.config import config
llm = DeepSeekLLM(
config=DeepSeekLLMConfig(
base=LLMBaseConfig(
api_key=config.chatbot.llm.api_key,
base_url=config.chatbot.llm.base_url,
),
request=DeepSeekLLMRequestConfig(stream=True)... | Python | 1 |
import marimo
__generated_with = "0.15.5"
app = marimo.App()
@app.cell
def _():
import marimo as mo
return (mo,)
@app.function
def euclid_mcd(a: int, b: int) -> int:
"""Return the MCD between positive a, b.
>>> euclid_mcd(42, 24)
6
>>> euclid_mcd(24, 42)
6
>>> euclid_mcd(42, 42)
... | Python | 1 |
undry_dev_tools.clients.multipass.DEFAULT_MAX_DURATION_IN_SECONDS`
if it does not meet the condition
"""
self._context.multipass.api_update_group_member_expiration_settings(
self.id, max_expiration, max_duration_in_seconds
).json()
return self
def get_exp... | Python | 1 |
import hashlib
import string
import random
characters = string.ascii_uppercase + string.ascii_lowercase + string.digits
random_key = ''.join(random.choices(characters, k=30))
input_password = "123456"
hashed_password = hashlib.sha256(random_key.encode() + input_password.encode()).hexdigest()
print("Random key : "+ r... | Python | 1 |
unt
# 记录比对结果
results[filename] = {
'same_count': same_count,
'diff_count': diff_count,
'success_rate': same_count / len(code_first_characters) * 100 if len(
code_first_characters) > 0 else 0
... | Python | 1 |
'''
Projeto desafio 1: vendas online
Nas etapas anteriores, já trabalhamos com vários tipos de dados, agora podemos trabalhar com os dados de tempo.
Na coluna Data de venda, temos datas em formato 'dia/mês/ano' (dd/mm/AAAA). Transforme esses dados para o tipo datetime e busque uma forma de visualização de subconjunto ... | Python | 1 |
# -*- coding: utf-8 -*-
# TencentBlueKing is pleased to support the open source community by making
# 蓝鲸智云 - PaaS 平台 (BlueKing - PaaS System) available.
# Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
# Licensed under the MIT License (the "License"); you may not use this file except
# in c... | Python | 1 |
}
Ok(Cuboid {
a: a.to_f64(),
b: b.to_f64(),
c: c.to_f64(),
})
}
}
impl Volume for Cuboid {
/// Calculates the volume of a cuboid
/// # Remarks
/// Formula for a cuboid is A = a * b * c
///
/// If a = b = c, the cuboid is a cube
/// ... | Rust | 0 |
(self.excludes, Some(ref excludes) if excludes.is_match(input))
}
/// Determine whether a given [`Uri`] should be excluded.
///
/// # Details
///
/// 1. If any of the following conditions are met, the URI is excluded:
/// - If it's a mail address and it's configured to ignore mail address... | Rust | 0 |
u"""Fixer for 'g.throw(E(V).with_traceback(T))' -> 'g.throw(E, V, T)'"""
from lib2to3 import fixer_base
from lib2to3.pytree import Node, Leaf
from lib2to3.pgen2 import token
from lib2to3.fixer_util import Comma
class FixThrow(fixer_base.BaseFix):
PATTERN = u"""
power< any trailer< '.' 'throw' >
trail... | Python | 1 |
the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.
//! Traits and types for controller of the dataflow subsystem.
// This appears to be defective at the moment, with fals... | Rust | 0 |
().unwrap_or(1));
Some(initializer)
})
.collect();
(weights, initializers, ignore_chances)
}
fn constraints_prelude() -> TokenStream {
quote! {
// Make a copy of the constraints that will remain immutable for
// this function. Here we ensure that the ba... | Rust | 0 |
common: CommonProductConfig = CommonProductConfig(
input_path="456",
output_dir="789",
)
product_config: ProductConfig = LiftConfig(
common=common,
)
return PrivateComputationInstance(
infra_config=infra_config,
product_config=... | Python | 1 |
_grandpa_precommits: Counter<U64>,
}
impl Metrics {
pub(crate) fn register(
registry: &prometheus_endpoint::Registry,
) -> Result<Self, PrometheusError> {
Ok(Self {
finality_grandpa_round: register(
Gauge::new("finality_grandpa_round", "Highest completed GRANDPA round.")?,
registry,
)?,
finality... | Rust | 0 |
#!/usr/bin/env python3
'''
This script has a function def np_elementwise(mat1, mat2)
that performs element-wise addition,
subtraction, multiplication, and division:
'''
def np_elementwise(mat1, mat2):
'''
def np_elementwise(mat1, mat2)
that performs element-wise addition,
subtr... | Python | 1 |
loading configuration"
use std::process::Command;
let output = Command::new("kubectl")
.arg("cluster-info")
.output()
.with_context(|| "failed to executed 'kubectl cluster-info'")?;
if !output.status.success() {
return Err(anyhow!("`kubectl cluster-info` failed with: {:?}", &... | Rust | 0 |
Special::F64 => 27,
Special::Break => 31,
}
}
pub fn from_byte(byte: u8) -> Result<Self, CborError> {
match byte {
20 => Ok(Special::Bool(false)),
21 => Ok(Special::Bool(true)),
22 => Ok(Special::Null),
23 => Ok(Special::Und... | Rust | 0 |
beefy_primitives::ValidatorSet;
use codec::{Decode, Encode};
use hex_literal::hex;
use sp_core::H256;
use sp_io::TestExternalities;
use sp_runtime::{traits::Keccak256, DigestItem};
use frame_support::traits::OnInitialize;
use crate::mock::*;
fn init_block(block: u64) {
System::set_block_number(block);
Sess... | Rust | 0 |
'''
在线验证邮箱真实性
'''
import random
import smtplib
from termcolor import cprint
import dns.resolver
import time
from queue import Queue
from threading import Thread
# 查询邮件服务器
def get_mailServer(server):
print('查找[{}]邮箱服务器...'.format(server))
try:
answers = dns.resolver.query(server, 'MX')
res = [s... | Python | 1 |
error......
Technically the script didn't fail.... but...
You need at least 2 different points... make sure you don't have an
incorrect selection
---- Try again
|
"""
tweet(dedent(msg2))
# ---- demo section ----
if len(sys.argv) == 1:
testing = True
a... | Python | 1 |
= window.mouse(request.mode);
Ok(WindowMouseResponse { rid: request.rid, value })
}
fn op_minifb_window_size(_state: &mut OpState, request: WindowSizeRequest, _zero_copy: Option<ZeroCopyBuf>) -> Result<WindowSizeResponse, AnyError> {
let window = DenoWindow::get(request.rid).unwrap();
let value = window.size();... | Rust | 0 |
GasCost::new(1, 1)),
(Gt, GasCost::new(1, 1)),
(Pack(StructDefinitionIndex::new(0)), GasCost::new(2, 1)),
(
PackGeneric(StructDefInstantiationIndex::new(0)),
GasCost::new(2, 1),
),
(Nop, GasCost::new(1, 1)),
];
// Note that the DiemVM is expecting ... | Rust | 0 |
u64 {
self.size_bytes
}
pub fn get_pass(&self) -> usize {
self.pass
}
pub fn set_pass(&mut self, pass: usize) {
self.pass = pass;
}
pub fn next_pass(&mut self) {
self.pass += 1;
}
pub fn read_from_stream<R>(read: R) -> Result<MapFile, Box<Error>> where... | Rust | 0 |
Human give me attention meow.";
let (len, v) = f.get_wrap(text_to_wrap, 250);
println!("{} {:?}", len, v);
assert_eq!(len, 250);
/*
let wrapped_text = vec![
"Walk on car leaving trail of paw prints",
"on hood and windshield sniff other",
"cat\... | Rust | 0 |
PartialEq<T>,
{
fn eq(&self, other: &Host<T>) -> bool {
match (self, other) {
(Host::Domain(a), Host::Domain(b)) => a == b,
(Host::Ipv4(a), Host::Ipv4(b)) => a == b,
(Host::Ipv6(a), Host::Ipv6(b)) => a == b,
(_, _) => false,
}
}
}
fn write_ipv6(a... | Rust | 0 |
}
let config = load_configuration(&conf_json, verbose);
match op {
0 => write_configuration(&conf_json, verbose),
1 => connect_to_portal(&config, verbose),
2 => get_status(&config),
3 => get_configuration(&config),
_ => {
display_error(&program,
... | Rust | 0 |
test = {
'name': 'Comprehensions',
'points': 0,
'suites': [
{
'cases': [
{
'code': r"""
>>> [2 * x for x in range(4)]
[0, 2, 4, 6]
>>> [y for y in [6, 1, 6, 1] if y > 2]
[6, 6]
>>> [[1] + s for s in [[4], [5, 6]]]
[[1, 4], [1,... | Python | 1 |
/// Prepare wrapper scripts for `zig cc` and `zig c++` and returns their paths
///
/// We want to use `zig cc` as linker and c compiler. We want to call `python -m ziglang cc`, but
/// cargo only accepts a path to an executable as linker, so we add a wrapper script. We then also
/// use the wrapper script to pass argu... | Rust | 0 |
from light_training.dataloading.dataset import get_train_val_test_loader_from_train
from monai.utils import set_determinism
import torch
import os
import numpy as np
import SimpleITK as sitk
from medpy import metric
import argparse
from tqdm import tqdm
import numpy as np
set_determinism(123)
parser = argparse.Arg... | Python | 1 |
print(self) {
println!("{}", self.format().elements)
}
/// Get string of formatted sentence
///
/// # Example
///
/// ```
/// use naromat::entities::sentence::Sentence;
/// let sentence = Sentence::new("我が[輩:.]は[猫:ねこ]である");
/// assert_eq!(sentence.get(), "我が|輩《・》は|猫《ねこ》である"... | Rust | 0 |
()
raw = result['vector']
if format == 'AmpPha':
return 10*np.log(np.abs(raw)**2 * 1000 / 50), np.angle(raw)
elif format == 'RealImag':
return np.real(raw), np.imag(raw)
# MW Source Stuff
def do_set_frequency(self, frequency, channel):
synth = sel... | Python | 1 |
:Xoshiro256StarStar;
criterion_group!(
benches,
round_trip_u32_u64_u16_12,
round_trip_u32_u64_u16_16,
round_trip_u16_u32_u8_8,
round_trip_u16_u32_u16_8,
round_trip_u16_u32_u16_12
);
criterion_main!(benches);
fn round_trip_u32_u64_u16_12(c: &mut Criterion) {
round_trip::<u32, u64, u16, 12>(... | Rust | 0 |
ic_jeem: Keysym = 0x05cc; /* U+062C ARABIC LETTER JEEM */
pub const KEY_Arabic_hah: Keysym = 0x05cd; /* U+062D ARABIC LETTER HAH */
pub const KEY_Arabic_khah: Keysym = 0x05ce; /* U+062E ARABIC LETTER KHAH */
pub const KEY_Arabic_dal: Keysym = 0x05cf; /* U+062F ARABIC LETTER DAL */
pub const KEY_Arabic_thal: Keysym ... | Rust | 0 |
"""
Author : Mohit Kumar
Python program to find triplets in a given array whose sum is zero
"""
# function to print triplets with 0 sum
def find_Triplets_with_zero_sum(arr, num):
"""find triplets in a given array whose sum is zero
Parameteres :
arr : input array
num = size of input ... | Python | 1 |
class OnionRuntimeError(Exception):
"""Base class for all Onion runtime exceptions"""
class OnionTypeError(OnionRuntimeError):
"""Raised for type-related errors"""
class OnionNameError(OnionRuntimeError):
"""Raised for undefined variable/function errors"""
class OnionArgumentError(OnionRuntimeError):
... | Python | 1 |
r
def test_make_block_no_pandas_array(block_maker):
# https://github.com/pandas-dev/pandas/pull/24866
arr = pd.arrays.NumpyExtensionArray(np.array([1, 2]))
# NumpyExtensionArray, no dtype
result = block_maker(arr, BlockPlacement(slice(len(arr))), ndim=arr.ndim)
assert result.dtype.kind in ["i", "... | Python | 1 |
"año",
],
"ð ý": [
"Þórr",
"Ýmir",
"Óðinn",
"Æsir",
"Ragnarök",
"Miðgarðr",
"Ásgarðr",
"Helheim",
],
"þ æ": [
"Ægir",
"Þrúðr",
"Friðr",
"V... | Python | 1 |
# write report concerning the selection of a mask (if desired)
if self.map_write_report is True:
if self.map_mask is None:
if type(self.map_cube) is hys.SpectralLibrary:
report.add_information("No mask necessary for spectral library")
els... | Python | 1 |
.map_err(|e| Error::CannotDeserializeUserSettings(e.to_string()))?;
let user = devand_core::User {
id: devand_core::UserId(self.id),
username: self.username,
email: self.email,
email_verified: self.email_verified,
visible_name: self.visible_name,
... | Rust | 0 |
# dump_link.py - dumps information about shell shortcuts
#
import glob
import os
import sys
import pythoncom
from win32com.shell import shell, shellcon
from win32com.storagecon import *
def DumpLink(fname):
shellLink = pythoncom.CoCreateInstance(
shell.CLSID_ShellLink,
None,
pythoncom.CLS... | Python | 1 |
0.5
}
/// Transforms a time given in `hh:mm::ss.s` in a fraction of SI day (i.e. day of 86400 seconds).
/// # Returns
/// * `day_fract` in `[0, 1[`.
/// # Example
/// ```rust
/// use moc_cli::{hms2day_fract};
/// assert_eq!(hms2day_fract(12, 0, 0.0), 0.5);
/// ```
pub fn hms2day_fract(hours: u8, minutes: u8, seconds:... | Rust | 0 |
from django.core import validators
from django.utils.deconstruct import deconstructible
from django.utils.translation import gettext_lazy
@deconstructible
class IndianMobileNumberValidator(validators.RegexValidator):
regex = r"^(?:\+91|91)?[789]\d{9}$"
message = gettext_lazy("Enter a valid Indian mobile numbe... | Python | 1 |
#[inline]
pub fn rect(p0: Point, p1: Point) -> Self {
let top_left = Point {
x: p0.x.min(p1.x),
y: p0.y.min(p1.y),
};
let bottom_right = Point {
x: p0.x.max(p1.x),
y: p0.y.max(p1.y),
};
QueryShape::Rect {
top_... | Rust | 0 |
import tiktoken
from config import config as Config
class TokenCounter:
def __init__(self):
self.encodings = {
"deepseek": tiktoken.get_encoding("cl100k_base"), # DeepSeek использует cl100k_base как OpenAI
"moonshot": tiktoken.get_encoding("cl100k_base") # Moonshot тоже
}... | Python | 1 |
from typing import Callable, Any, List
from .request import Request
from .response import Response
SERVER_HOST = "localhost"
SERVER_PORT = 8000
class Middleware:
def __init__(self, app: Any):
self.app = app
self.middleware_stack: List[Callable] = []
def add_middleware(self, middlew... | Python | 1 |
# Copyright 2013 Google, Inc. All Rights Reserved.
#
# Google Author(s): Matt Fontaine
from . import E_B_L_C_
class table_C_B_L_C_(E_B_L_C_.table_E_B_L_C_):
dependencies = ["CBDT"]
| Python | 1 |
1;
if b < 0x80 {
return (r, i);
}
}
panic!("Invalid varint");
} else {
decode_u64_slow(buf)
}
}
pub fn decode_u32(buf: &[u8]) -> (u32, usize) {
let (val, bytes_consumed) = decode_u64(buf);
assert!(val < u32::MAX as u64, "varint is not a u... | Rust | 0 |
import torch
import tqdm
from pytorch_grad_cam.base_cam import BaseCAM
class ScoreCAM(BaseCAM):
def __init__(
self,
model,
target_layers,
reshape_transform=None):
super(ScoreCAM, self).__init__(model,
target_layers,
... | Python | 1 |
.collect::<Vec<String>>();
categories = categories
.into_iter()
.filter(|c| vals.contains(c.get_name()))
.collect();
}
categories.sort();
for category in &categories {
print_category(category, size_enabled);
}
}
pub fn show_subcommand(mut hupas: Vec<H... | Rust | 0 |
from flask import Blueprint, request, jsonify
from app.services.ESP32_service import process_device_data, register_device
esp32_blueprint = Blueprint('esp32', __name__)
# Ruta para procesar datos de mediciones
@esp32_blueprint.route('/api/esp32/data', methods=['POST'])
def register_device_data():
try:
dat... | Python | 1 |
from PyQt5.QtWidgets import QLabel, QPushButton, QProgressBar
from PyQt5.QtCore import QTimer
from PyQt5.QtMultimedia import QMediaPlayer
class RefreshManager:
@staticmethod
def refresh_ui(window):
"""重启UI的所有组件和状态"""
try:
# 停止所有正在进行的操作
if window.play_timer.isActive():
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.