text string | label_name string | labels int64 |
|---|---|---|
always your label dictionary.
final_loss = criterion(ouput_dict, batch_data['ego']['label_dict'])
criterion.logging(epoch, i, len(train_loader))
if supervise_single_flag:
final_loss += criterion(ouput_dict, batch_data['ego']['label_dict_single'], suffix="_single")
... | Python | 1 |
exec
pub fn load<'lua, 'a, S>(&'lua self, source: &'a S) -> Chunk<'lua, 'a>
where
S: ?Sized + AsRef<[u8]>,
{
Chunk {
lua: self,
source: source.as_ref(),
name: None,
env: None,
}
}
fn load_chunk<'lua>(
&'lua self,
... | Rust | 0 |
user_properties: vec![("test".to_owned(), "test".to_owned())],
};
let mut filter = SubscribeFilter::new("hello".to_owned(), QoS::AtLeastOnce);
filter
.set_nolocal(true)
.set_preserve_retain(true)
.set_retain_forward_rule(RetainForwardRule::Never);
Su... | Rust | 0 |
[str, int] = WORKER_LOGLEVEL,
logfile: Optional[str] = None,
WorkController: Any = TestWorkController,
perform_ping_check: bool = True,
shutdown_timeout: float = 10.0,
**kwargs) -> Iterable[worke... | Python | 1 |
_get_display()
screen = libX11.XDefaultScreen(display)
root = libX11.XRootWindow(display, screen)
if not flags:
flags = PIX11Flags(100, 100, width, height, 1, 0, 0)
window = libX11.XCreateSimpleWindow(
display,
root,
flags.x,
flags.y,
flags.width,
... | Python | 1 |
clone();
original_p.truncate(original_p.len() - 4);
let original_f = fs::File::open(original_p).unwrap();
let original: Vec<u8> = original_f.bytes().map(|x| x.unwrap()).collect();
let mut success = true;
if original.len() != result.len() {
panic!(
"R... | Rust | 0 |
er.color.a = 1.0 # Don't forget to set the alpha!
marker.color.r = 1.0
marker.color.g = 0.0
marker.color.b = 0.0
self.marker_pub.publish(marker)
# Draw the axes on the marker
cv2.drawFrameAxes(current_frame, self.mtx, self... | Python | 1 |
_ => {},
}
}
let label = local_label.unwrap_or(None);
let direction = local_direction.unwrap_or(None);
let speed = local_speed.unwrap_or(None);
let bullet = local_bullet.ok_or_else(|| M::Error::missing_field("bullet or bulletRef"))?;
Ok(Fire {
... | Rust | 0 |
"Checking for new activities (public and private)".to_uppercase()
);
eprintln!("This may take a few minutes depending on the number of activities.");
for c in characters.characters {
let character_id = &c.id;
let character_row_id = self
.insert_charact... | Rust | 0 |
_dashboard(dash_json, folder_id)
migrated += 1
print(f"Progress: {migrated}/{total_dashboards}")
except Exception as e:
print(f"Error migrating dashboard {dash['title']}: {str(e)}")
def main():
SOURCE_URL = "http://old-grafana:3000"
T... | Python | 1 |
"""
Copyright 2019 kivou.2000607@gmail.com
This file is part of yata.
yata is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
yata is dist... | Python | 1 |
not yet supported. HW breakpoints are not available.", ctrl_reg.rev())));
}
// This is fine as FpRev1CompX and Rev2CompX are just two different
// interpretations of the same memory region as Rev2 can handle bigger
// address spaces than Rev1.
let reg_addr = FpRev1CompX::ADDRESS... | Rust | 0 |
ssh2_sftp_fsync(locked.raw) })
}
fn lock(&self) -> Result<LockedFile, Error> {
match self.inner.as_ref() {
Some(file_inner) => {
let sftp_inner = file_inner.sftp.0.as_ref().expect(
"We are holding an Arc<SftpInnerDropWrapper>, \
so... | Rust | 0 |
}', GC_Extend), ('\u{1a65}',
'\u{1a6c}', GC_Extend), ('\u{1a6d}', '\u{1a72}', GC_SpacingMark), ('\u{1a73}', '\u{1a7c}',
GC_Extend), ('\u{1a7f}', '\u{1a7f}', GC_Extend), ('\u{1ab0}', '\u{1abe}', GC_Extend),
('\u{1b00}', '\u{1b03}', GC_Extend), ('\u{1b04}', '\u{1b04}', GC_SpacingMark), ('\u{1b34}'... | Rust | 0 |
ens::{Pallet, Storage, Call, Event<T>},
AssetRegistry: orml_asset_registry::{Pallet, Storage, Call, Event<T>},
PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin},
OrmlXcm: orml_xcm::{Pallet, Call, Event<T>},
}
);
//! ITM module
use cortex_m::{itm};
use core::fmt;
/// ITM based destination
pub struct It... | Rust | 0 |
import json
json_data = '{"nombre": "python", "tipo": "backend", "paradigma": "POO"}'
json_to_python = json.loads(json_data)
print("nuestro dato tipo json a python {}".format(json_to_python))
print("El tipo de dato de nuestra variable es: {}".format(type(json_to_python))) | Python | 1 |
impl Debug for Field {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
writeln!(f, "")?;
for y in 0..MAX_FIELD_HEIGHT {
let y = MAX_FIELD_HEIGHT - y - 1;
write!(f, "{:02}: ", y)?;
for x in 0..MAX_FIELD_WIDTH {
let cell = self.get_cell(x, ... | Rust | 0 |
# Copyright (C) 2015 KillerInstinct
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in... | Python | 1 |
re": (
max(self.metrics.quality_scores)
if self.metrics.quality_scores
else 0
),
},
"hospital_distribution": self._analyze_hospital_distribution(results),
"processing_details": [
... | Python | 1 |
import re
from logging import Filter
from config.components.global_settings import DEBUG
class SensitiveInfoFilter(Filter):
"""Filter to mask sensitive information in logs."""
def filter(self, record):
if hasattr(record, 'msg'):
pattern = r'(".*password"\s*:\s*")([^"]+)'
rep... | Python | 1 |
ordering at the time of commit. This is where
//! your application **should** act on information.
//!
//! In the `StateMachine` there are both mutable (`.apply()`) and immutable (`.query()`) calls.
//! There is a considerable performance difference, as `.query()` calls do not pass through the
//! durable `Log` while `... | Rust | 0 |
eed in distributed evrionment.
sampler_seed=dict(type=DistSamplerSeedHook),
)
# configure environment
env_cfg = dict(
# whether to enable cudnn benchmark
cudnn_benchmark=False,
# set multi process parameters
mp_cfg=dict(mp_start_method="fork", opencv_num_threads=0),
# set distributed parameters... | Python | 1 |
"message": f"Ошибка обработки запроса: {str(e)}"}), 500
elif inns:
invalid_inns = [inn for inn in inns if not is_valid_inn(inn)]
if invalid_inns:
return jsonify({"status": "error", "message": f"Неверный формат ИНН: {invalid_inns}"}), 400
try:
results = await process_m... | Python | 1 |
_base_ = [
'../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/voc0712.py',
'../_base_/default_runtime.py'
]
model = dict(bbox_head=dict(num_classes=20))
# optimizer
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=None)
# learning policy
# actu... | Python | 1 |
_min: u32,
w2_dx: u32,
w2_dy: u32,
r_min: u32,
r_dx: u32,
r_dy: u32,
g_min: u32,
g_dx: u32,
g_dy: u32,
b_min: u32,
b_dx: u32,
b_dy: u32,
a_min: u32,
a_dx: u32,
a_dy: u32,
w_inverse_min: u32,
w_inverse_dx: u32,
w_inverse_dy: u32,
z_min: u32,
z_d... | Rust | 0 |
tv/TvInputManager$TvInputCallback\0", "<init>\0", "()V\0");
__jni_env.new_object_a(__jni_class, __jni_method, __jni_args.as_ptr())
}
}
/// [onInputStateChanged](https://developer.android.com/reference/android/media/tv/TvInputManager.TvInputCallback.html#onInputStateChanged(j... | Rust | 0 |
# coding=utf-8
import requests
from core import printmodels
r = '\033[31m'
g = '\033[32m'
y = '\033[33m'
b = '\033[34m'
m = '\033[35m'
c = '\033[36m'
w = '\033[37m'
Headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:28.0) Gecko/20100101 Firefox/28.0'}
ShellPresta = 'files/up.php'
Jce_Deface_image = 'fi... | Python | 1 |
AddressingMode)?;
self.send_command(mode)?;
Ok(())
}
}
<reponame>stackabletech/operator-rs
// This file is modeled after the K8S controller_ref.go file from the apimachinery package
use k8s_openapi::apimachinery::pkg::apis::meta::v1::OwnerReference;
use kube::Resource;
/// Returns a reference to t... | Rust | 0 |
from sklearn import metrics
from tabulate import tabulate
def get_binary_class_scores(labels, predictions):
accuracy = metrics.accuracy_score(labels, predictions)
f1 = metrics.f1_score(labels, predictions, zero_division=1)
precision = metrics.precision_score(labels, predictions, zero_division=1)
recall... | Python | 1 |
from typing import Dict, Any, Optional, Tuple
from os import path
from tensorboardX import SummaryWriter
import numpy as np
class Reporter:
def __init__(self, writer, counter):
self._writer = writer
self._times_counter = counter
def add_scalars(self, info: Dict[str, Any], prefix: str):
... | Python | 1 |
integ.simps(mdot_loc, y)
Ma_ma = u_ma/c
pt_ma = integ.simps(mdot_loc * p_tot, y) / integ.simps(mdot_loc, y)
p_ma = integ.simps(mdot_loc * pd, y) / integ.simps(mdot_loc, y)
#rhot_ma = integ.simps(mdot_loc * rho_tot, y) / integ.simps(mdot_loc, y)
rho_ma = rhoe_ip(x_rot)
Tt_ma = integ.simps(mdo... | Python | 1 |
semidap_timestamp() -> u32 {
crate::cyccnt() >> 6
}
#[repr(C)]
union Vector {
stack_pointer: *const u32,
handler: unsafe extern "C" fn(),
reserved: usize,
}
extern "C" {
static __stack_top__: u32;
// Cortex-M exceptions
fn NMI();
fn HardFault();
fn MemManage();
fn BusFault();
... | Rust | 0 |
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
root.title("Cadastro de clientes básico")
# Configurações principais
root.geometry("400x300") | Python | 1 |
'#0070250177V#560F#2P我、我说……\n',
'你是叫小玲吧?',
TxtCtl.Enter,
TxtCtl.Clear,
'#0070250175V和我一起\n',
'聊聊天吧?',
TxtCtl.Enter,
TxtCtl.Clear,
'#0070250176V#061F我很想\n',
'了解小玲。',
TxtCtl.Enter,
),
... | Python | 1 |
}
0i32
}
#[no_mangle]
pub unsafe extern "C" fn CMap_add_bfchar(
mut cmap: *mut CMap,
mut src: *const u8,
mut srcdim: size_t,
mut dst: *const u8,
mut dstdim: size_t,
) -> i32 {
CMap_add_bfrange(cmap, src, src, srcdim, dst, dstdim)
}
#[no_mangle]
pub unsafe extern "C" fn CMap_add_bfrange(... | Rust | 0 |
"""
2D and 3D doublet point
Reference:
[1] Branlard (2017) Wind turbine aerodynamics and vorticity-based methods
"""
import numpy as np
# --------------------------------------------------------------------------------}
# --- 2D
# ------------------------------------------------------------------------------... | Python | 1 |
ice
# Create a test device
device = Device(
name="VDISK0",
path=os.environ.get("SANDBOX_DEVICE", "/app/virtual_media/vdisk0.img"),
model="Sandbox VDisk",
transport="file",
media_type="Flash Memory",
size="2G"
)... | Python | 1 |
lr_init=lr_init,
lr_decay_steps=400e3,
visit_softmax_temperature_fn=visit_softmax_temperature,
known_bounds=KnownBounds(-1, 1))
def make_go_config() -> MuZeroConfig:
return make_board_game_config(
action_space_size=362, max_moves=722, dirichlet_alpha=0.03, lr_init=0.01)
de... | Python | 1 |
.right {
flags.insert(Control::RIGHT);
}
if control.up {
flags.insert(Control::UP);
}
if control.down {
flags.insert(Control::DOWN);
}
if control.fire {
flags.insert(Control::FIRE);
}
if control.jets {
... | Rust | 0 |
:open_default_paths().expect("Could not open library");
println!("Library opened, version is {}", lib.version());
lib
}
<reponame>daogangtang/rust-libp2p<filename>core/src/upgrade/either.rs
// Copyright 2018 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any person obtainin... | Rust | 0 |
request.offsets[idx] = plane_offset;
request.pitches[idx] = line_bytes;
// This can overflow buy later will be checked more strictly in `DrmLayout::new`.
plane_offset = plane_offset.wrapping_add(bytes);
}
DrmLayout::new(&request)
}
fn plane_width(self, width... | Rust | 0 |
import paramiko
# 定义服务器列表,包括服务器名称、IP地址、端口号、用户名和密码
servers = [
{"name": "美国", "hostname": "1.1.1.1", "port": 22, "username": "root", "password": "123456"},
{"name": "不丹", "hostname": "1.1.1.1", "port": 22, "username": "root", "password": "123456"},
{"name": "毛里求斯", "hostname": "1.1.1.1", "port": 22,... | Python | 1 |
g --oneline --graph --decorate --all",
"last": "log -1 HEAD",
"unstage": "reset HEAD --",
"visual": "!gitk",
"hist": "log --pretty=format:'%h %ad | %s%d [%an]' --graph --date=short",
"type": "cat-file -t",
"dump": "cat-file -p",
"amend"... | Python | 1 |
"""
=====================================================
Gaussian process classification (GPC) on iris dataset
=====================================================
This example illustrates the predicted probability of GPC for an isotropic
and anisotropic RBF kernel on a two-dimensional version for the iris-dataset.
... | Python | 1 |
::internal::Profiler::resume(__profiler_scope.0);
/// let result = { input };
/// std::mem::drop(__profiler_scope);
/// result
/// }
/// }
/// ```
///
/// # Limitations
///
/// ## `.await` expressions with attributes
///
/// `#[profile]` must rewrite `.await` expressions; it separates the ba... | Rust | 0 |
rs=headers).json()
print(response)
if response["code"] == 0:
print("智能微秘书 推送成功!")
else:
print(f'智能微秘书 推送失败!{response["error"]}')
def smtp(title: str, content: str) -> None:
"""
使用 SMTP 邮件 推送消息。
"""
if (
not push_config.get("SMTP_SERVER")
or not push_... | Python | 1 |
template.debug_interface.clone(),
storage: template.storage.clone(),
mempool: template.mempool.clone(),
state_sync: template.state_sync.clone(),
log_collector: template.log_collector.clone(),
vm_config: template.vm_config.clone(),
secret_service: ... | Rust | 0 |
st_cloud_list_page_per_item(appliance, request, page, value, set_list):
""" Tests list items per page
Metadata:
test_flag: visuals
Polarion:
assignee: pvala
casecomponent: Settings
caseimportance: medium
initialEstimate: 1/10h
tags: settings
"""
if i... | Python | 1 |
(r2, carry) = crate::ff::mac_with_carry_by_value(r2, a, b2, carry);
let (r1, red_carry) =
crate::ff::mac_with_carry_by_value(r2, m, MODULUS.0[2usize], red_carry);
let (r3, carry) = crate::ff::mac_with_carry_by_value(r3, a, b3, carry);
let (r2, red_carry) =
... | Rust | 0 |
target to ensure we don't try to dirve through any goalposts to reach it
if abs(agent.me.location[1]) > 5150:
final_target[0] = cap(final_target[0], -750, 750)
agent.line(final_target-Vector3(0, 0, 100), final_target +
Vector3(0, 0, 100), [255, 255, 255])
angles... | Python | 1 |
match (&value.code_hash, &value.code) {
(Some(expected_code), Some(code)) => {
let code_hash = H256::from_slice(Keccak256::digest(&code.0).as_slice());
assert_eq!(code_hash, expected_code.0, "Code hash mismatched")
}
(None, None) =>... | Rust | 0 |
b_params()
two_limb_val = 1 << (1 * limb_bits) # ~2 limbs
five_limb_val = 1 << (4 * limb_bits) # ~5 limbs
a = ak.array([two_limb_val], dtype=ak.bigint)
base = int(a.nbytes)
a[0] = five_limb_val
grown = int(a.nbytes)
delta = grown - base
assert delta ... | Python | 1 |
"a").unwrap();
let b = forward_val(&mut engine, "b").unwrap();
assert_eq!(a.to_number(), 1.405_647_649_380_269_9);
assert_eq!(b.to_number(), 0.165_148_677_414_626_83);
}
#[test]
fn cbrt() {
let realm = Realm::create();
let mut engine = Interpreter::new(realm);
let init = r#"
var a = M... | Rust | 0 |
le!(),
}
}
fn mutator(ins: &mut Ins, rng: &mut R) {
use std::mem;
*ins = unsafe { mem::transmute(rng.gen_range::<u8>(0, Ins::MAX as u8)) };
}
#[derive(Clone)]
pub struct Decision {
pub mate: i64,
pub node: i64,
// This will be ran through a sigmoid
pub rate: i64,
pub signal: i64,
p... | Rust | 0 |
state and children
let stopwatch = make_widget! {
#[widget{
layout = row: *;
}]
struct {
#[widget] display: impl HasString = Frame::new(Label::new("0.000".to_string())),
#[widget(use_msg = reset)] _ = TextButton::new_msg("&reset", ()),
#[widge... | Rust | 0 |
or(
ContributeError::VerifiedLocationWasNoneForChunkID(chunk.chunk_id.to_string()),
)?;
Ok(url)
}
fn get_download_url_of_last_challenge_for_verifying(
&self,
chunk: &ChunkDownloadInfo,
) -> Result<String> {
let url = chunk.previous_challenge_url.clone().o... | Rust | 0 |
#!/usr/bin/env python
"""Configure a plot by grabbing the matplotlib backend
This example demonstrates the use of setp and getp, which is a
typical matlab/pyplot way to set properties of objects
setp(handler, 'something', value) or getp(handler [, 'something'])
will call set_something or get_something from handler
... | Python | 1 |
r empty.
InvalidFileNameLength,
/// The provided file name contains an invalid character.
UnsupportedFileNameCharacter,
}
#[derive(Debug)]
pub enum IOError {
/// buffer size is smaller than requested
NotEnoughBuffer
}//! Bridge to provide a client implementation for the `hyper` crate.
//!
//! # Exa... | Rust | 0 |
QueuePresent: bool,
queuePairNumber: QueuePairNumber,
) -> Self
{
Self
{
responderResourcesAlsoKnownAsMaximumOutstandingRdmaReadAndAtomicOperationsRemotely,
initiatorDepthAlsoKnownAsMaximumOutstandingRdmaReadAndAtomicOperationsLocally,
hardwareFlowControlAvailable,
maximumNumberOfRetriesForARemoteSe... | Rust | 0 |
atural embeddings found for Number Field in a with defining polynomial x^2 - 5 and Number Field in b with defining polynomial x^2 + 3
"""
if K is QQ:
if P in ZZ or isinstance(P, (Integer, int)):
P = Integer(P)
if P.is_prime():
return P
else:
... | Python | 1 |
"""
Exact Riemann solvers for Burgers' equation in 1D and interactive plot function.
"""
import sys, os
import numpy as np
from utils import riemann_tools
from ipywidgets import widgets
from ipywidgets import interact
from IPython.display import display
import matplotlib.pyplot as plt
def speed(q, xi):
"Characte... | Python | 1 |
x = 54 + 12 * 3 - 47 / 4
print(x)
print(x)
| Python | 1 |
个用于显示下载进度的窗口
Args:
title (str): 窗口标题,默认为"下载进度"
initial_text (str): 初始状态文本,默认为"准备中..."
Returns:
进度窗口实例
"""
return self.ui_manager.create_progress_window(title, initial_text)
def create_extraction_progress_window(self):
... | Python | 1 |
import math
#friends = 10
#friends = friends + 1
#friends += 1 # augmented assignment operator
#friends = friends - 2
#friends -= 2
#friends = friends * 3
#friends *= 3
#friends = friends / 2
#friends /= 2
#friends = friends ** 2
#friends **= 2
#remainder = friends % 3 # modulus operator
#print(remainder)
#print(frie... | Python | 1 |
+ Debug + PartialEq + SchemeRepr,
{
fn to_repr_string(&self) -> String {
format!(
"{}{}{}{}",
SYNTAX_VECTOR_PREFIX,
SYNTAX_LEFT_PARENTHESIS_CHAR,
self.iter()
.map(|v| v.to_repr_string())
.collect::<Vec<String>>()
... | Rust | 0 |
ne', input_size=codec['input_size']),
dict(type='mmdet.YOLOXHSVRandomAug'),
dict(
type='Albumentation',
transforms=[
dict(type='Blur', p=0.1),
dict(type='MedianBlur', p=0.1),
dict(
type='CoarseDropout',
max_holes=1,
... | Python | 1 |
ry_executed_duration",
"Duration of a single query in seconds.",
// 10µs, 20µs, 50µs, 100µs, ..., 1s, 2s, 5s
decimal_buckets(-5, 0),
),
}
}
}
/// Struct that is responsible for handling queries sent by user.
pub struct HttpQueryHandlerImpl {
l... | Rust | 0 |
class PrivacyView(TemplateView):
template_name = 'core/privacy.html'
class TermsView(TemplateView):
template_name = 'core/terms.html'
class FAQView(TemplateView):
template_name = 'core/faq.html'
class StatsView(LoginRequiredMixin, TemplateView):
template_name = 'core/stats.html'
def get_contex... | Python | 1 |
actual = Req::from_str("pyOpenSSL (>=0.14) ; extra == 'security'", true).unwrap();
let expected = Req {
name: "pyOpenSSL".into(),
constraints: vec![Constraint::new(Gte, Version::new(0, 14, 0))],
extra: Some("security".into()),
sys_platform: None,
pyth... | Rust | 0 |
RepositoryManager;
use crate::service::file_store::FileStoreService;
use lightspeed_core::error::LightSpeedError;
use log::*;
use std::sync::Arc;
pub mod config;
pub mod dto;
pub mod model;
pub mod repository;
pub mod service;
pub mod utils;
pub mod web;
#[derive(Clone)]
pub struct FileStoreModule<RepoManager: DBFile... | Rust | 0 |
rom e
return info_json["container"]["recognized"]
def verify_supported(
file_path: str | os.PathLike[Any],
mkvmerge_path: str | os.PathLike | Iterable[str] = "mkvmerge",
) -> bool:
"""Verify if the file format is supported by mkvmerge.
Parameters
----------
file_path : str | os.PathLike[A... | Python | 1 |
ns(&mut lint_store, &sess, &conf);
clippy_lints::register_pre_expansion_lints(&mut lint_store, &conf);
clippy_lints::register_renamed(&mut lint_store);
}));
}
fn fetch_input_files(sess: &Session) -> Vec<PathBuf> {
let cwd = &sess.working_dir.0;
sess.source_map()
.files()
.i... | Rust | 0 |
e.read(&mut label).unwrap();
labels.push(label[0]);
}
return labels;
}
fn main() {
// Create our network
let mut feed_network = network::network::FeedFoward::new();
//println!("{:?}", network::network::helloo());
// Teaching image labels
let mut teach_labels = get_image_labels("train-labe... | Rust | 0 |
lds.Date(string='Pregnancy Diagnosis Date')
date_due_to_calve = fields.Date(string='Date Due To Calve')
calved_date = fields.Date(string='Calved Date')
calving_notes = fields.Text(string='Calving Notes')
age_of_cow_at_calving = fields.Integer(string='Age of Cow At Calving')
class Weight(models.Model):... | Python | 1 |
let mut i = 0;
let mut sum = 0;
let mut last = 0;
let mut curr = 1usize;
while i < n - 1 {
sum = curr.wrapping_add(last);
last = curr;
curr = sum;
i += 1;
}
sum
}
fib(100_000_000) % 1000
}
pub(crate) fn mul... | Rust | 0 |
simple_string(ctx),
self.hi.as_simple_string(ctx),
))
}
}
}
impl IntBitsRange {
fn upper_bound(self, bound: IntBits) -> Option<Self> {
Self {
hi: min(self.hi, bound),
lo: self.lo,
}
.is_valid()
}
fn lower_bound(self, bound: IntBits) -> Option<Self> {
Self {
... | Rust | 0 |
.cmp(right_kind) {
Ordering::Equal => left.cmp(right),
different => different,
}
}
}
});
// Tada! If we replace each ID with its index in `all_ids`,
// ones with callsign info are [0..flight.callsign... | Rust | 0 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models
class ChooseDestinationLocation(models.TransientModel):
_inherit = "stock.package.destination"
def _compute_move_line_ids(self):
destination_without_batch = self.env['stock... | Python | 1 |
rate = 0
hours = 0
class work_rate:
def __init__(self, hours, rate):
self.hours = hours
self.rate = rate
def calculate(self):
return self.hours * self.rate
while not ValueError or hours <= 0:
hours = input("Whats your hours: ")
try:
hours = float(hours)
if ho... | Python | 1 |
calibrator.save_calibration_results(report)
# Print summary
print("\n" + "="*60)
print("BRAIN-FORGE HARDWARE CALIBRATION SUMMARY")
print("="*60)
summary = report['calibration_summary']
print(f"Devices calibrated: {summary['successful_devices']}/{summary['t... | Python | 1 |
teln( "利きテスト1");
let kms = KmSyurui::PH; // ぱわーあっぷひよこ
let km = sn_kms_to_km( Sengo::Go, kms );// △ph
let ms_dst = 79;
LOGGER.try_write().unwrap().writeln( &format!("kms={} km={} ms_dst={}",kms,km,ms_dst) );
let mut mv_src_hashset : HashSet<umasu> = HashSet::ne... | Rust | 0 |
ther to include RV distribution annotations in the plot.
:param bool render_params: Whether to show params in the plot.
"""
relations = get_model_relations(
model,
model_args=model_args,
model_kwargs=model_kwargs,
)
graph_spec = generate_graph_specification(relations, render_... | Python | 1 |
tlab.pdfbase._fontdata_widths_helveticaboldoblique.widths,
'Times-Roman':
reportlab.pdfbase._fontdata_widths_timesroman.widths,
'Times-Bold':
reportlab.pdfbase._fontdata_widths_timesbold.widths,
'Times-Italic':
reportlab.pdfbase._fontdata_widths_timesitalic.widths,
'Times-BoldItalic':
re... | Python | 1 |
,
(r"textures\tx_s_doorlatch.dds", 0x5865_632E, 0x3718_3169),
(r"textures\tx_s_forgebase.dds", 0x5865_632E, 0x4B35_E8F1),
(r"textures\tx_s_dirtfloor.dds", 0x5865_632E, 0x5E6B_AB02),
(r"textures\tx_s_doorpanel.dds", 0x5865_632E, 0x9919_3CF3),
(r"textures\tx_s_bluebear.dds", 0x5865_632E, 0xA018_1... | Rust | 0 |
cookies=cookies,
ssl=AIOHTTP_CLIENT_SESSION_TOOL_SERVER_SSL,
allow_redirects=False,
) as response:
if response.status >= 400:
text = await response.text()
raise Exception(f"HTTP error {... | Python | 1 |
tton instead of two separate buttons\n" if SINGLE_BUTTON else "SINGLE_BUTTON is disabled , filename and file_sixe will be shown as different buttons\n")
LOG_STR += (f"CUSTOM_FILE_CAPTION enabled with value {CUSTOM_FILE_CAPTION}, your files will be send along with this customized caption.\n" if CUSTOM_FILE_CAPTION else ... | Python | 1 |
xt OCR quality check processing:
def clean_string(input_string):
# Use regex to keep Chinese characters, English letters and numbers
# input_string = input_string.replace('\\t', '').replace('\\n', '').replace('\t', '').replace('\n', '').replace('/t', '').replace('/n', '')
input_string = input_string.replace... | Python | 1 |
use rand::distributions::{Distribution, Uniform};
use nthash::{nthash, NtHashIterator};
fn nthash_bench(c: &mut Criterion) {
let range = Uniform::from(0..4);
let mut rng = rand::thread_rng();
let seq = (0..10000)
.map(|_| match range.sample(&mut rng) {
0 => 'A',
1 => 'C',
... | Rust | 0 |
def wibbledmean(array):
return array / 4 + wibble * np.random.uniform(-wibble, wibble, array.shape)
| Python | 1 |
import streamlit as st
import joblib
import re
from nltk.stem.porter import PorterStemmer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from nltk.corpus import stopwords
# Load precomputed TF-IDF vectors and vectorizer during Streamlit initialization
ve... | Python | 1 |
value=color.RED)
radio_chart1_red.grid(row=0, column=3, sticky=TK.W, padx=0, pady=0)
radio_chart1_blue = ttk.Radiobutton(frame_radio_chart1, text="b", variable=var_radio_chart1_color,
value=color.BLUE)
radio_chart1_blue.grid(row=0, column=4, sticky=T... | Python | 1 |
per_env_class.calc_next_obs(state=obs, action=action, helper_env=helper_env)
# print(f"next_obs from dynamics: {next_obs_calculated_from_dynamics}")
assert np.allclose(next_obs, next_obs_calculated_from_dynamics), f"Observation mismatch at step {i+1}: {next_obs} != {next_obs_calculated_from_dyn... | Python | 1 |
self) -> &'a mut W {
self.variant(SCSP_A::SCSP_0)
}
#[doc = "Clock is logic 1 when stopped by SCEN"]
#[inline(always)]
pub fn scsp_1(self) -> &'a mut W {
self.variant(SCSP_A::SCSP_1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#... | Rust | 0 |
from services.path_fixer import PathFixer
def get_fixes_from_raw(content: str, fix: PathFixer) -> dict[str, dict]:
files: dict[str, dict] = {}
files_long_comments: dict[str, tuple[list[int], list[int]]] = {}
_cur_file = None
for line in content.splitlines():
if line:
try:
... | Python | 1 |
if !include.is_match(name) {
continue;
}
if !req.exclude.is_empty() && exclude.is_match(name) {
continue;
}
info!("running test {}", name);
let mut result = ABITestResponse_TestResult::new();
result.set_... | Rust | 0 |
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
from typing import Optional
from typing_extensions import Literal
from ..._models import BaseModel
__all__ = ["FileSearchTool", "FileSearch", "FileSearchRankingOptions"]
class FileSearchRankingOptions(BaseModel):
score_thresh... | Python | 1 |
es::default()
} else {
(*features).clone()
};
let covenant = if covenant.is_null() {
TariCovenant::default()
} else {
(*covenant).clone()
};
let message_string;
if message.is_null() {
error = LibWalletError::from(InterfaceError::NullError("message".to_string... | Rust | 0 |
import _thread as thread
import base64
import datetime
import hashlib
import hmac
import json
from urllib.parse import urlparse
import ssl
from datetime import datetime
from time import mktime
from urllib.parse import urlencode
from wsgiref.handlers import format_date_time
import websocket # 使用websocket_client
answer... | Python | 1 |
"""initial
Revision ID: 48948cfd5852
Revises:
Create Date: 2024-01-31 11:39:13.218938
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '48948cfd5852'
down_revision: Union[str, None] = None
branch_labels: Union[str, Seque... | Python | 1 |
import openai
from retrieval import HierarchicalIndexer # Import the retrieval process from the retrieval.py file
# Set your OpenAI API Key
openai.api_key = "not entering my own api key as it is personal. please use your own."
# Function to generate the answer using GPT-3, augmented by the retrieved content
def gene... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.