text string | label_name string | labels int64 |
|---|---|---|
#[derive(Debug, PartialEq)]
struct Config {
// if `-E` is supplied, this will be `false`
interpretations: bool,
// if `-n` is supplied, this will be `true`
newline: bool,
// if `-s` is supplied, this will become `true`
spaces: bool,
// the color of the output, will be automatically guessed... | Rust | 0 |
Some(
scope
.offset(usize::from(exit_anchor_offset))
.read::<Anchor>()?,
)
} else {
None
};
Ok(EntryExitRecord {
entry_anchor,
exit_anchor,
})
}
}
impl<'a> ReadFixedSizeDep<'a> fo... | Rust | 0 |
ys be a tuple, even for a single component.
///
/// ### Example
///
/// ```
/// use shipyard::{AllStoragesViewMut, World};
///
/// let mut world = World::new();
/// let mut all_storages = world.borrow::<AllStoragesViewMut>().unwrap();
///
/// let entity = all_storages.add_entity(... | Rust | 0 |
not set'")
def get_mmtf_reduced_path():
'''Returns the path to the reduced MMTF-Hadoop sequence file.
It looks for the environmental variable "MMTF_REDUCED", if not set, an error
message will be shown.
Returns
-------
str
path to the mmtf_reduced directory
'''
if 'MMTF_REDUCE... | Python | 1 |
", link_section = ".CRT$XIB" )]
#[cfg_attr ( target_os = "macos", link_section = "__DATA,__mod_init_func" )]
static INIT_ARRAY: [unsafe extern "C" fn(); 1] = [run_static_initializers];
<filename>examples/7GUIs/counter.rs
use vizia::prelude::*;
#[derive(Lens)]
pub struct AppData {
count: i32,
}
pub enum AppEvent {... | Rust | 0 |
gs::String(_font) => _font,
},
None => String::from(""),
};
let mut font_argument = String::from("");
if font != "" {
let mut found: bool = false;
for _font in IMPRESSIVE_FONTS {
if _font == font {
found = true;
break;
... | Rust | 0 |
[inline]
fn get_entry(memory: &Memory<S>, table_data: Allocation, entry_index: u32) -> Entry<C, S> {
debug_assert!(entry_index < Self::entry_array_len(memory, table_data));
let entry_addr = Self::entry_addr(table_data, entry_index);
Entry {
metadata: u64::read_at(memory, entry_ad... | Rust | 0 |
> {
let mut decompressed = Vec::with_capacity(compressed_keys.len());
for key in compressed_keys {
decompressed.push(key.decompress().unwrap());
}
decompressed
}
}
#[cfg(test)]
mod test {
extern crate test;
use crate::tests_helper::*;
use test::Bencher;
... | Rust | 0 |
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
from __future__ import annotations
from typing import List, Optional
from typing_extensions import Literal, Required, TypedDict
from ..._types import SequenceNotStr
from .velocity_limit_params_period_window_param import VelocityLim... | Python | 1 |
fdm = CreateFDM(self.sandbox)
fdm.set_engine_path('.')
fdm.load_script(self.sandbox.path_to_jsbsim_file('scripts',
'Short_S23_1.xml'))
fdm.run_ic()
pm = fdm.get_property_manager()
self.assertTrue(pm.hasNode('propulsion/eng... | Python | 1 |
pub enum MailboxDatum<'a> {
Exists(u32),
Flags(Vec<Cow<'a, str>>),
List {
flags: Vec<Cow<'a, str>>,
delimiter: Option<Cow<'a, str>>,
name: Cow<'a, str>,
},
Search(Vec<u32>),
Sort(Vec<u32>),
Status {
mailbox: Cow<'a, str>,
status: Vec<StatusAttribute>,
... | Rust | 0 |
};{128,7,674};{135,7,680};{142,7,689};{146,7,696};{150,7,705};{153,7,712};{155,7,720};{158,7,727};{161,7,736};{164,7,744};{166,7,752};{168,7,759};{169,7,768};{172,7,775};{174,7,784};{176,7,792};{177,7,895};{176,7,1104};{173,7,1118};{171,7,1131};{170,7,1149};{169,7,1641};{168,7,1657};{167,7,1704};{167,7,2144};',
... | Python | 1 |
import torch
import torchvision
from torch import nn
vgg16 = torchvision.models.vgg16(weights=None)
# 保存方式1(保存网络模型结构和参数)
torch.save(vgg16, "related_data/vgg16_method1.pth")
# 加载模型1
model = torch.load("related_data/vgg16_method1.pth")
print(model)
# * 加载模型1的陷阱
model = torch.load("related_data/MyNetwork.pth")
'''
At... | Python | 1 |
_sessions/freemocap_test_data/synchronized_videos").glob("*.mp4")
config_file_path = Path("python_code/animal_tracking/multi_video_labeller/helpers/face_points.json")
videos = []
image_counts = set()
for video_path in video_paths:
cap = cv2.VideoCapture(str(video_path))
if not cap.isOp... | Python | 1 |
: u32 = 3;
pub const KVM_EXIT_DEBUG: u32 = 4;
pub const KVM_EXIT_HLT: u32 = 5;
pub const KVM_EXIT_MMIO: u32 = 6;
pub const KVM_EXIT_IRQ_WINDOW_OPEN: u32 = 7;
pub const KVM_EXIT_SHUTDOWN: u32 = 8;
pub const KVM_EXIT_FAIL_ENTRY: u32 = 9;
pub const KVM_EXIT_INTR: u32 = 10;
pub const KVM_EXIT_SET_TPR: u32 = 11;
pub const K... | Rust | 0 |
rate of extractions."""
if self.total_cases == 0:
return 0.0
return self.successful_extractions / self.total_cases
def to_dict(self) -> dict:
"""Convert to dictionary for JSON serialization."""
return {
"cases": [case.to_dict() for case in self.cases],
... | Python | 1 |
let source = MetronomeSource::new(self.interval, self.origin_uri.clone());
builder.spawn(source, source_context).map(Some)
}
}
struct MetronomeSource {
interval_ns: u64,
next: u64,
origin_uri: EventOriginUri,
id: u64,
}
impl MetronomeSource {
fn new(interval_ns: u64, origin_ur... | Rust | 0 |
oml::Value;
fn deref(&self) -> &toml::Value {
&self.0
}
}
impl ToTokens for TomlValue {
fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
match self.0.clone() {
toml::Value::String(value) => value.to_tokens(cx),
toml::Value::Integer(value) => value.to_tokens(cx),... | Rust | 0 |
#!/usr/bin/env python
from __future__ import with_statement, print_function
from pyrabbit.api import Client
from boto.ec2.cloudwatch import CloudWatchConnection
import os
from time import sleep
def get_queue_depths(host, username, password, vhost):
cl = Client(host, username, password)
if not cl.is_alive():
... | Python | 1 |
SEVENT_VOLUMELIMIT_CHANGED: KSEVENT_VOLUMELIMIT = 0i32;
#[doc = "*Required features: 'Win32_Media_KernelStreaming'*"]
pub type KSEVENT_VPNOTIFY = i32;
#[doc = "*Required features: 'Win32_Media_KernelStreaming'*"]
pub const KSEVENT_VPNOTIFY_FORMATCHANGE: KSEVENT_VPNOTIFY = 0i32;
#[doc = "*Required features: 'Win32_Media... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
comment: 重力场反演线程
@author: GanAH 2020/7/28.
@version 1.0.
@contact: dinggan@whu.edu.cn
"""
import os
from PyQt5.QtCore import pyqtSignal, QThread
from scipy import integrate
from numpy import sin, cos, pi
from database.database import Database
from geodeticSurvey imp... | Python | 1 |
from drf_spectacular.extensions import OpenApiSerializerFieldExtension
from drf_spectacular.plumbing import build_object_type
from kpi.schema_extensions.v2.generic.schema import (
GENERIC_ARRAY_SCHEMA,
GENERIC_OBJECT_SCHEMA,
GENERIC_STRING_SCHEMA,
USER_URL_SCHEMA,
)
class MetadataFieldExtension(OpenA... | Python | 1 |
`AUXIO5`"]
#[inline]
pub fn is_auxio5(&self) -> bool {
*self == COMPA_INR::AUXIO5
}
#[doc = "Checks if the value of the field is `AUXIO6`"]
#[inline]
pub fn is_auxio6(&self) -> bool {
*self == COMPA_INR::AUXIO6
}
#[doc = "Checks if the value of the field is `AUXIO7`"]
... | Rust | 0 |
TS as usize {
Self::enforce_in_field_le(bits)?;
}
Ok(crate::fields::fp::AllocatedFp::new(value, variable, cs.clone()).into())
}
}
/// Enforces that `bits`, when interpreted as a integer, is less than
/// `F::characteristic()`, That is, interpret bits as a lit... | Rust | 0 |
# Scrapy settings for crawler_project project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://docs.scrapy.org/en/latest/topics/settings.html
# https://docs.scrapy.org/en/latest/topics/downloader-mi... | Python | 1 |
family & 0xFF) << 8) | (number & 0xFF)
}
pub fn get_vmo_copy_from_file(file: &File) -> Result<zx::Vmo, zx::Status> {
unsafe {
let mut vmo_handle: zx::sys::zx_handle_t = zx::sys::ZX_HANDLE_INVALID;
match fdio_sys::fdio_get_vmo_copy(file.as_raw_fd(), &mut vmo_handle) {
0 => Ok(zx::Vmo::fr... | Rust | 0 |
_like_for_array!(i32, 2);
impl_array_like_for_array!(i32, 3);
impl_array_like_for_array!(i32, 4);
impl_array_like_for_array!(i32, 5);
impl_array_like_for_array!(i32, 6);
impl_array_like_for_array!(i32, 7);
impl_array_like_for_array!(i32, 8);
impl_array_like_for_array!(i64, 0);
impl_array_like_for_array!(i64, 1);
impl_... | Rust | 0 |
let mut transform = from_config(&config).unwrap();
let event = Event::new_empty_log();
let event = transform.transform(event).unwrap();
assert_eq!(event.as_log()[&"new field".into()], "new value".into());
}
#[test]
fn lua_pairs() {
let mut transform = from_config(... | Rust | 0 |
self.context.reset(Reset::STATE);
self.state_score(&instance)?;
self.level = Level::Set;
Ok(())
}
fn transition_score(&mut self) -> io::Result<()> {
// Compute transition scores between two labels
let l = self.num_labels as usize;
for i in 0..l {
... | Rust | 0 |
())
}
#[fixture]
pub fn public_keys() -> Option<Vec<Vec<u8>>> {
let mut public_keys = Vec::new();
for _ in 0..10 {
let pk = thread_rng().sample_iter(&Alphanumeric).take(60).collect::<Vec<_>>();
public_keys.push(pk);
}
Some(public_keys)
}
#[fixture]
pub fn did_document_metadata() -> Option<Vec<u8>> {
Some(
... | Rust | 0 |
import socket
import ipaddress
import threading
import time
import contextlib
import errno
maxPacketSize = 1024
defaultPort = 27017
serverIP = '127.0.0.1'
tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
try:
tcpPort = int(input("Please enter the TCP port of the host: \n"));
except:
tcpPort = ... | Python | 1 |
pub struct TryFromIntError(pub(crate) ());
impl TryFrom<u64> for TeeTech {
type Error = TryFromIntError;
fn try_from(value: u64) -> core::result::Result<Self, Self::Error> {
match value {
0 => Ok(Self::None),
1 => Ok(Self::Sev),
2 => Ok(Self::Sgx),
_ =>... | Rust | 0 |
in pk_type_string
@pytest.mark.parametrize("pk_dtype, np_dtype", [
(pk.uint8, np.uint8),
(pk.uint16, np.uint16),
(pk.uint32, np.uint32),
(pk.uint64, np.uint64),
])
def test_unsigned_int_overflow(pk_dtype, np_dtype):
# test for gh-86
actual = pk.View([1], dtype=pk_dtype)
if np.__versio... | Python | 1 |
import json
import os.path
from ntchat2.wc import wcprobe, SUPPORT_VERSIONS
from ntchat2.utils.xdg import get_helper_file, is_support_version, has_helper_file
from ntchat2.exception import WeChatVersionNotMatchError, WeChatBindError, WeChatRuntimeError
from ntchat2.utils.singleton import Singleton
from ntchat2.const im... | Python | 1 |
params = {'symbol': symbol}
async with session.get(url, params=params) as response:
if response.status == 200:
data = await response.json()
return float(data['price'])
except:
pass
return 0.0
asy... | Python | 1 |
= v;
if i == -0.0 { i = 0.0; }
let mut ui = float_to_bits(i);
if i >= 0.0 {
ui += 1;
} else {
ui -= 1;
}
bits_to_float(ui)
}
pub fn next_float_down(v: f32) -> f32 {
if v.is_infinite() && v < 0.0 { return v; }
let mut i = v;
if i == 0.0 { i = -0.0; }
let mut... | Rust | 0 |
from typing import Optional
import numpy as np
import torch
class NearestNeighboursClassifier(torch.nn.Module):
"""Nearest neighbours classifier.
It computes the similarity between the query and the supports using the
cosine similarity and then applies a softmax to obtain the logits.
Args:
... | Python | 1 |
_org_clip.contiguous().view(B * D, C, H, W)
#
# # TODO : CNN-model
# rgb_clip = self.backbone(rgb_clip)[0]
# # rgb_clip = self.conv_tmp(rgb_clip)
#
# # TODO: Transformer
# rgb_clip = self.pool(rgb_clip)
#
# _C, _H, _W = rgb_clip.shape[-3], rgb_clip.shape[-2], ... | Python | 1 |
})?;
}
}
WindowEvent::KeyboardInput { input, .. } => {
let _ = root_panel.on_keyboard_input(*input)?;
}
WindowEvent::CursorMoved { position, .. } => {
let positi... | Rust | 0 |
ctId> {
for &method in &self.methods {
let method = vm.fcts.idx(method);
let method = method.read();
if method.name == name && method.is_static == is_static {
return Some(method.id);
}
}
None
}
pub fn find_method_with_rep... | Rust | 0 |
und())
}
}
}
#[cfg(test)]
mod test {
use super::*;
use super::super::dynamic_environment::*;
#[test]
fn can_find_tool_in_first_environment() {
let first = DynamicEnvironment::new();
let second = DynamicEnvironment::new();
first.define("first-tool", Box::new(make... | Rust | 0 |
["files"], "files")
project_name = prompt("What's your project name?", default=Path("./").absolute().name)
included_paths = list()
if prompt_yn("Would you like to watch all files in the directory?", True):
included_paths.append("*")
elif prompt_yn("Would you like to add include pat... | Python | 1 |
# 1) Musbat bo‘lishi kerak
# x musbat bo‘lishi shart, aks holda AssertionError.
# x must be positive, otherwise AssertionError.
x = -3
assert x > 0, "UZ: x musbat bo'lishi kerak | EN: x must be positive"
# 2) Parametr tekshiruvi (tur va qiymat)
# factorial faqat n >= 0 bo‘lgan butun son qabul qiladi.
# factorial acce... | Python | 1 |
Valid Users: {len(valid_users)}'])
writer.writerow([f'# Bots Filtered: {self.session_stats["bots_filtered"]}'])
writer.writerow(['# Data Columns: username,id,access_hash,name,phone,is_premium,is_bot'])
writer.writerow(['username', 'id', 'access_hash', 'name', ... | Python | 1 |
'''В файле 17-390.txt содержится последовательность целых чисел. Элементы последовательности
могут принимать целые значения от –100 000 до 100 000 включительно. Определите количество
троек, для которых выполняются следующие условия: – ровно два числа в тройке четырёхзначные; –
хотя бы одно число в тройке делится на 7; ... | Python | 1 |
)
.await?;
// Add the runner to the environment the child will be launched in.
let mut realm_decl = builder.get_realm_decl().await?;
realm_decl.environments.push(cm_rust::EnvironmentDecl {
name: String::from(environment_name),
extends: fdecl::EnvironmentExtends::Realm,
res... | Rust | 0 |
20 mins (it takes around ~12 mins)
)
run_one_test(test)
# ------ Testing Zero Quota Failover ------
@pytest.mark.aws
def test_aws_zero_quota_failover():
name = _get_cluster_name()
region = get_aws_region_for_quota_failover()
if not region:
pytest.xfail(
'Unable to test zero ... | Python | 1 |
_height_map() -> diamond_square::PixelMap<u8> {
let buffer = diamond_square::construct(map::DETAILS);
diamond_square::normalize_pixel_map(buffer)
}
pub fn create_default_layer(w: u32, h: u32) -> Layer<Tile> {
let mut layer = Layer::new(Rect::new(0, 0, w, h));
create_default_tiles_for_layer(&mut layer, ... | Rust | 0 |
import random
import uuid
from typing import List
import game_decider
import game_service
from models.roll import Roll
def game_loop(player1, player2, rolls):
game_id = str(uuid.uuid4())
count = 1
p1_wins = 0
p2_wins = 0
while count <= 5 or (p1_wins == p2_wins and count > 5):
print(" ----... | Python | 1 |
import pandas as pd
import matplotlib.pyplot as plt
#Leer datos
datos = pd.read_excel('gastos.xlsx')
print('**************************************************')
print(datos.columns)
# 2.1. Asignar tipo fecha
print('**************************************************')
datos['Fecha'] = pd.to_datetime(datos['Fecha'])
pri... | Python | 1 |
print(Fore.WHITE + " - Set up new projects")
print(Fore.CYAN + "=" * 70 + "\n")
agent = CodingAgent()
while True:
user_input = input(Fore.RED + "\n💻 You: " + Style.RESET_ALL)
if user_input.lower() in ["quit", "exit"]:
print(Fore.GREEN + "\n👋 Goodbye!\n")
br... | Python | 1 |
s_repo = AsyncMock()
mock_users_repo.get.return_value = None
mock_users_repo.get_role.return_value = "admin" # Пользователь - админ
mock_users_repo_class.return_value = mock_users_repo
# Тестируем переход по deeplink
self.message.text = "/start 1"
await... | Python | 1 |
MeleeWeaponsLevel1 = 1186,
ResearchZergMeleeWeaponsLevel2 = 1187,
ResearchZergMeleeWeaponsLevel3 = 1188,
ResearchZergMissileWeapons = 3706,
ResearchZergMissileWeaponsLevel1 = 1192,
ResearchZergMissileWeaponsLevel2 = 1193,
ResearchZergMissileWeaponsLevel3 = 1194,
ScanMove = 19,
Stop = 3... | Rust | 0 |
}
println!("DEBUG: query_gpu_conv_bwd_w_algo: algo: {} accepted", k);
found_k = Some(k);
break;
}
found_k.map(|k| XGPUConvBwdWConfig::Cudnn(CudnnGPUConvBwdWConfig{
algo_desc: algo_results[k].algo,
workspace: algo_results[k].memory
}))
};
if let Some(ref algo) = maybe_a... | Rust | 0 |
false
)?.latent())
);
b.rule_1_terminal("week-end",
b.reg(r#"(周|週)末"#)?,
|_| {
let friday = helpers::day_of_week(Weekday::Fri)?
.intersect(&helpers::hour(18, false)?)?;
... | Rust | 0 |
tart_upload = int(round(time.time() * 1000))
s3_client.upload_file("/tmp/" + model_name, bucket_name, "ML_Pipeline/"+model_name, Config=config)
end_upload = int(round(time.time() * 1000))
print("model uploaded " + model_name )
#end_time = int(round(time.time() * 1000))
#print("duration: " + str(end_time-start_ti... | Python | 1 |
Ecdh1PU<'_, X25519KeyPair>,
X25519KeyPair,
AesKey<A256Kw>,
AesKey<A256Gcm>,
EcdhEs<'_, X25519KeyPair>,
X25519KeyPair,
AesKey<A256Kw>,
>(
BOB_DID,
vec![
&BOB_SECRET_KEY_AGREEMENT_KEY_X25519_1,
... | Rust | 0 |
"""Module implementing various data transformers for PyTorch."""
from __future__ import annotations
import abc
import torch
class Transformer(metaclass=abc.ABCMeta):
"""Abstract base class defining a data transformer."""
@abc.abstractmethod
def transform(self, data: torch.Tensor):
"""Transform... | Python | 1 |
Guard`.
///
/// # Differences from the standard library `Mutex`
///
/// - No poisoning, the lock is released normally on panic.
/// - Only requires 1 byte of space, whereas the standard library boxes the
/// `Mutex` due to platform limitations.
/// - A `MutexGuard` can be sent to another thread and unlocked there.
//... | Rust | 0 |
8d 0x21908d
0x21918c 0x20928c 0x20928c 0x20938c 0x1f948c 0x1f958b 0x1f968b 0x1f978b
0x1f988b 0x1f998a 0x1f9a8a 0x1e9b8a 0x1e9c89 0x1e9d89 0x1f9e89 0x1f9f88
0x1fa088 0x1fa188 0x1fa187 0x1fa287 0x20a386 0x20a486 0x21a585 0x21a685
0x22a785 0x22a884 0x23a983 0x24aa83 0x25ab82... | Rust | 0 |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import Any, Dict
from collections import Counter
from .base import BaseClient, MessageRole, AIMessage
# https://docs.anthropic.com/en/api/messages
class ClaudeClient(BaseClient):
MODEL = "claude-sonnet-4-20250514"
ENV_API_KEY = "ANTHROPIC_API_KEY"
... | Python | 1 |
};
}
macro_rules! delegate_hash {
([$($bounds: tt)*] $typ: ty) => {
coarbitrary!([$($bounds)*] $typ; self, var =>
$crate::coarbitrary::coarbitrary_hash(self, var));
};
($typ: ty) => {
delegate_hash!([] $typ);
};
}
macro_rules! delegate_deref {
([$($bounds: tt)*] $ty... | Rust | 0 |
from unittest import TestCase
import pandas as pd
from pytz import UTC
from .test_trading_calendar import ExchangeCalendarTestBase
from trading_calendars.exchange_calendar_xswx import XSWXExchangeCalendar
class XSWXCalendarTestCase(ExchangeCalendarTestBase, TestCase):
answer_key_filename = 'xswx'
calendar_c... | Python | 1 |
import os
import pandas as pd
import numpy as np
from scipy.spatial.distance import pdist, squareform
import metrics
from sklearn.cluster import KMeans
def find_reads_files(root_dir):
reads_files = []
for dirpath, dirnames, filenames in os.walk(root_dir):
for file in filenames:
if file == ... | Python | 1 |
import os, keyboard, curses
from pickle import FALSE
appname = "DuckExplorer"
focus = 0
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(True)
curses.start_color()
def handleUpKey(e):
global focus
focus = (focus - 1) % len(os.listdir(os.getcwd()))
render()
def handleDownKey(e):
... | Python | 1 |
]);
zero_idx + GridIdx::from(self.min)
}
}
impl GridSpaceToLinearSpace for GridBoundingBox<[isize; 2]> {
type IndexArray = [isize; 2];
fn strides(&self) -> Self::ShapeArray {
[self.axis_size_x(), 1]
}
fn linear_space_index_unchecked<I: Into<GridIdx<Self::IndexArray>>>(&self, index... | Rust | 0 |
glushkov::LocalLang::from_hir(hir, 0).into_automaton()
}
pub fn compile_raw(regex: &str) -> Automaton {
let hir = parse::Hir::from_regex(®ex, true);
glushkov::LocalLang::from_hir(hir, 0).into_automaton()
}
#[cfg(test)]
pub fn is_match(regex: &str, text: &str) -> bool {
let automaton = compile(®... | Rust | 0 |
# contacts/urls.py
from django.urls import path
from .views import upload_contacts, upload_csv
app_name = 'contacts_uploader'
urlpatterns = [
path("", upload_contacts, name="upload_contacts"),
path('upload_csv/', upload_csv, name='upload_csv'),
]
| Python | 1 |
from memory_store import load_history, save_message
from config import DEFAULT_CONTEXT_TURNS
class SessionManager:
"""Thin wrapper that handles chat history for ONE session."""
def __init__(self, session_id: str = "default"):
self.session_id = session_id
# --------- public helpers ---------
d... | Python | 1 |
distance(c1: &GeoCoordinate, c2: &GeoCoordinate) -> Result<f64> {
let u1 = f64::atan((1.0 - FLATTENING_ELIPSOID) * f64::tan(f64::to_radians(c1.lat)));
let u2 = f64::atan((1.0 - FLATTENING_ELIPSOID) * f64::tan(f64::to_radians(c2.lat)));
let init_lambda = f64::to_radians(c2.lng - c1.lng);
let lambda = ini... | Rust | 0 |
fn test_builder() {
let _: Security = Security::new().ssl_redirect();
}
#[test]
fn test_all_builders() {
static ALLOWED_HOSTS: &[&str] = &["rocalhost:8000", "localhost:8000"];
static HOST_PROXY_HEADERS: &[&str] = &["X-Forwarded-Host"];
static SSL_HOST: &str = "example.com";
... | Rust | 0 |
import json
from magic_doc.conv.base import BaseConv
from magic_doc.progress.filepupdator import FileBaseProgressUpdator
from magic_doc.contrib.magic_html import GeneralExtractor
from magic_doc.progress.pupdator import ConvProgressUpdator
from loguru import logger
extractor = GeneralExtractor()
class Html(BaseConv):... | Python | 1 |
::strdup(cell_extended_gcluster(plane, cell)) as i32 as u32)
// }
}
// Misc. -----------------------------------------------------------------------
/// Saves the [NcStyleMask] and the [NcChannelPair],
/// and returns the [NcEgc], of an [NcCell].
#[inline]
pub fn cell_extract(
plane: &NcPlane,
cell: &NcCe... | Rust | 0 |
total_steps=10000,
batch_size=32,
checkpoint_interval=10000,
eval_interval=100,
pipeline="PromptPipeline",
trainer="AcceleratePPOTrainer",
),
model=ModelConfig(model_path="lvwerra/gpt2-imdb", num_layers_unfrozen=2),
tokenizer=TokenizerConfig(tokenizer_path="gpt2", truncation_side="right"),
optimi... | Python | 1 |
.ptr.as_ref() };
return inner.rc.load(Ordering::SeqCst);
}
}
impl<T> Deref for Arc<T> {
type Target = T;
fn deref(&self) -> &T {
let inner = unsafe { self.ptr.as_ref() };
return &inner.data;
}
}
impl<T> Clone for Arc<T> {
fn clone(&self) -> Arc<T> {
let inner = uns... | Rust | 0 |
o keep track of whether a game is currently in progress
let mut game_in_progress = false;
// Variable to keep track of when new items should be generated
let mut need_items_in = 0;
// Variable to keep track of the selected option in the menu
let mut selected_option = 0;
// Main app loop
loo... | Rust | 0 |
import torch
import torch.nn as nn
class YoloLoss(nn.Module):
def __init__(self,S=7 ,B=2, C=20):
super(YoloLoss,self).__init__()
self.mse = nn.MSELoss(reduction="sum")
self.lambda_coord = 5
self.lambda_noobj = 0.5
self.S = S
self.B = B
self.C = C
# predictions = (c0 to c19,p20,x21,y22,... | Python | 1 |
from dataclasses import dataclass
from app.domain.values.base import BaseValueObject
from app.domain.exceptions.messages import TitleTooLongException
from app.domain.exceptions.messages import EmptyTextException
@dataclass(frozen=True)
class Text(BaseValueObject):
value: str
def validate(self):
if n... | Python | 1 |
r_pairs_to_ref_indexes_unstable(
mut ref_index_str_pairs: Vec<(usize, &str)>,
) -> Vec<(usize, usize)> {
ref_index_str_pairs.sort_unstable_by(|a, b| compare_str(a.1, b.1));
ref_index_str_pairs_to_ref_indexes_inner(ref_index_str_pairs)
}
#[cfg(feature = "std")]
#[inline]
fn ref_index_str_pairs_to_ref_index... | Rust | 0 |
from django.contrib import admin
from app.models import User
from app.internal.admin.admin_user import AdminUserAdmin
from app.internal.bank_card.db.models import BankCard
from app.internal.money_account.db.models import MoneyAccount
class CardInline(admin.TabularInline):
model = BankCard
extra = 0
class Ac... | Python | 1 |
callbacks return `rlua::Result`, an Ok value is a normal return, and an Err return
// turns into a Lua 'error'. Again, any type that is convertible to lua may be returned.
Ok(list1 == list2)
})?;
globals.set("check_equal", check_equal)?;
// You can also accept runtime variadic arguments to... | Rust | 0 |
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("IntoService")
.field("make", &self.make)
.finish()
}
}
impl<M, S, Target, Request> Service<Target> for IntoService<M, Request>
where
M: Service<Target, Response = S>,
S: Service<Request>,
{
type Res... | Rust | 0 |
from functions import *
# case 1: 6 points without damping
#Initialize the matrix with the mass array m and the length array l
nb = 6
m = 0.2 * np.ones(nb)
l = 0.75/nb * np.ones(nb)
print(l)
K = stiffness_matrix(m, l)
M = mass_matrix(m, l)
C = np.zeros((nb,nb))
#Initial conditions
u_0 = np.zeros((nb,2))
#Number of po... | Python | 1 |
# Generated by Django 4.2.20 on 2025-03-22 10:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Library', '0002_rename_sectiion_students_section'),
]
operations = [
migrations.CreateModel(
name='Teacher',
fields... | Python | 1 |
nsert_row(1);
tbl.insert_row(0);
tbl.insert_row(1);
// When order_by is empty, the initial ordering is preserved.
assert_eq!(
tbl.iter().map(|r| r.f1).collect::<Vec<_>>(),
vec![1, 0, 2, 1, 0, 1]
);
// Table ordered by a single column.
let... | Rust | 0 |
from typing import List
from collections import deque
class Solution:
def maxCandies(
self,
status: List[int],
candies: List[int],
keys: List[List[int]],
containedBoxes: List[List[int]],
initialBoxes: List[int],
) -> int:
answer = 0
queue = deque... | Python | 1 |
callerid"), String::from(caller_id));
fields.insert(String::from("topic"), String::from(topic));
fields.insert(String::from("md5sum"), T::md5sum());
fields.insert(String::from("type"), T::msg_type());
encode(&mut stream, &fields)?;
Ok(())
}
fn read_response<T: Message, U: std::io::Read>(mut stream:... | Rust | 0 |
# ///////////////////////////////////////////////////////////////
#
# BY: WANDERSON M.PIMENTA
# PROJECT MADE WITH: Qt Designer and PySide6
# V: 1.0.0
#
# This project can be used freely for all uses, as long as they maintain the
# respective credits only in the Python scripts, any information in the visual
# interface ... | Python | 1 |
if passing_grade:
# Grade was good, but submission arrived too late
status = 'failed'
reason = {
'current_date': now,
'deadline': deadline
}
... | Python | 1 |
n read_generated_100_interval() -> Result<()> {
test_file("1.0.0-littleendian", "generated_interval")
}
#[test]
fn read_generated_100_decimal() -> Result<()> {
test_file("1.0.0-littleendian", "generated_decimal")
}
#[test]
fn read_generated_100_union() -> Result<()> {
test_file("1.0.0-littleendian", "gene... | Rust | 0 |
from netmiko.ssh_dispatcher import platforms
from netmiko import SSHDetect
if __name__ == '__main__':
'''
netmiko 是基于paramiko封装的一个支持多厂商的ssh工具包
实现对设备的ssh(telnet)登陆操作,部分支持文件传输
Multi-vendor library to simplify Paramiko SSH connections to network devices
github地址:https://github.com/ktbyers/netmiko
... | Python | 1 |
rature
probs.append(F.softmax(logits, dim=-1)[res_idx].item())
current_output.append(res_idx)
if len(instance['input_ids']) >= 512:
# the easiest way is to break
break
# beam search score
rest = sum(np.log(probs))
length_norm = ... | Python | 1 |
.0
.checked_add(to_add)
.ok_or(MetaplexError::NumericalOverflowError)?,
amount_ranges[their_ctr].1,
));
their_ctr += 1;
// dont increment my_ctr since i still have length to give
... | Rust | 0 |
preds = (scores >= best_threshold).astype(int)
f1 = f1_score(labels, preds)
precision = precision_score(labels, preds)
acc = accuracy_score(labels, preds)
cm = confusion_matrix(labels, preds)
print("📝 บันทึกผลลัพธ์ลงไฟล์ log...")
with open(output_log, "w") as f:
f.write(f"AUC: {au... | Python | 1 |
oken) => builder.bearer_auth(token).send(),
SrAuthorization::Basic(username, password) => {
let p = match password {
None => None,
Some(v) => Some(v),
};
builder.basic_auth(username, p).send()
}
};
match call {
Ok(v) => ... | Rust | 0 |
_tokio_codec are the items that belong in the `tokio_codec` crate. However, because we need to
// maintain backward compatibility until the next major breaking change, they are defined here.
// When the next breaking change comes, they should be moved to the `tokio_codec` crate and become
// independent.
//
// The pri... | Rust | 0 |
# program.py - This file contains the class for the Program commands.
# Section 1.5 - Program Commands
class Program:
def __init__(self, parent):
self.parent = parent
# 1.5.1
def run(self, progname: str, parameters=None) -> None:
"""Run the appointed program
Command:
... | Python | 1 |
redeem")
.body(serde_json::to_string(&body)?)
.reply(&filter)
.await;
assert!(res.status().is_client_error());
// Step 3: Ensure that after redemption, fetching state works.
let res = test::request_from_ip(test::EXPERIMENT_SUBCIDR_PEER_IP)
.path("... | Rust | 0 |
00`.e AS `?e`, \
`datoms00`.v AS `?t` \
FROM `datoms` AS `datoms00` \
WHERE `datoms00`.a = 99) \
GROUP BY `?e`) \
WHERE `(max ?t)` IS NOT NULL");
assert_eq!(args, vec![]);
let query = r#"[:find (max ... | Rust | 0 |
# Copyright (C) 2013 SPARTA, Inc. a Parsons Company
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND SPARTA DISC... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.