text string | label_name string | labels int64 |
|---|---|---|
y_origin(GlyphId(0)).is_some() as i32
}
#[no_mangle]
pub extern "C" fn rb_ot_get_y_origin(ttf_parser_data: *const ffi::rb_ttf_parser_t, glyph: u32) -> i32 {
ttf_parser_from_raw(ttf_parser_data).glyph_y_origin(GlyphId(u16::try_from(glyph).unwrap())).unwrap_or(0) as i32
}
mod metrics {
use crate::Tag;
pub ... | Rust | 0 |
GGCGCGTCCCGCACACATTTCGCTGCCCGATACGCAGATGAAAGAGG";
fn init() {
let _ = env_logger::builder()
.is_test(true)
.filter_level(log::LevelFilter::Trace)
.try_init();
}
fn get_solid() -> pcon::solid::Solid {
let mut data: pcon::solid::Solid = pcon::solid::Solid:... | Rust | 0 |
#
# This file is part of CasADi.
#
# CasADi -- A symbolic framework for dynamic optimization.
# Copyright (C) 2010-2014 Joel Andersson, Joris Gillis, Moritz Diehl,
# K.U. Leuven. All rights reserved.
# Copyright (C) 2011-2014 Greg Horn
#
# CasADi is free software; you can... | Python | 1 |
48),
},
textscript: TextScriptConsts {
encoding: TextScriptEncoding::ShiftJIS,
encrypted: true,
animated_face_pics: false,
textbox_rect_top: Rect { left: 0, top: 0, right: 244, bottom: 8 },
textbox_rect_middle: Rect... | Rust | 0 |
ponse_mock = mock.Mock()
response_mock.status_code = 500
response_mock.headers = []
response_mock.raise_for_status.side_effect = HTTPError
# Download this model to make sure it's in the cache.
_ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert")
# Unde... | Python | 1 |
zonemap.next_zonemap_size;
self.backup_next_zonemap_ptr = zonemap.backup_next_zonemap_ptr;
Some(zonemap)
} else {
None
}
}
}
<filename>core_protocol/src/payloads/block/new_block_content.rs
use failure::Error;
use payloads::Payload;
use protocol_builder_parser::{... | Rust | 0 |
加入发送缓冲区
unsafe {
let tail = (&mut *self.inner.buf.get()).as_mut().unwrap();
tail.append(buf);
//解锁,并返回
let len = tail.len();
if len == 0 {
self... | Rust | 0 |
?id={message.from_user.id}">{message.from_user.first_name}</a> [<i>{find['role']}</i>]</b>
<b>○</b> TIME TAKING: {get_time_taken(started_time)}'s
<b>○</b> BOT BY: <b>@RoldexVerse</b>"""
await msg.edit_text(text)
antidb.set(message.from_user.id, int... | Python | 1 |
-> Result<[Option<Type>; 3], ()> {
let mut ops = matching_operators.filter(|a| a.iter().zip(&givens).map(|(a, b)| b.map_or(true, |b| a == b.kind())).all(|v| v == true));
let output = ops.next().ok_or(())?;
// The answer has to be unanimous(all output have to give the specific type), for the inferrence to
... | Rust | 0 |
, width: f32) {
unsafe {
gl::LineWidth(width);
self.uniform_color(color);
let u: GLint;
u = self.uloc[Uniform::Model as usize];
gl::UniformMatrix4fv(u, 1, gl::FALSE, trans.as_ptr());
}
}
pub fn uniform_transformations(&self, projecti... | Rust | 0 |
from pyramid.security import Allow
from adhocracy_core.authorization import IRootACMExtension
from adhocracy_core.interfaces import IResource
from adhocracy_core.schema import ACM
# flake8: noqa
def root_acm_extension_adapter(root: IResource) -> dict:
"""Adpater to extend the `root_acm`."""
acm = \
... | Python | 1 |
utils::{
draw, ev_handler,
term::{cleanup, setup},
},
Pager,
};
#[cfg(any(feature = "tokio_lib", feature = "async_std_lib"))]
use async_mutex::Mutex;
use crossterm::{cursor::MoveTo, event, execute};
#[cfg(feature = "search")]
use std::convert::{TryFrom, TryInto};
use std::io::{self, Write ... | Rust | 0 |
bool {
filelike::is_read_vectored_at(self)
}
#[cfg(feature = "io-streams")]
#[inline]
fn read_via_stream_at(&self, offset: u64) -> io::Result<StreamReader> {
filelike::read_via_stream_at(self, offset)
}
}
#[cfg(feature = "async-std")]
impl WriteAt for async_std::fs::File {
#[in... | Rust | 0 |
# Copyright 2025 Google LLC
#
# 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 required by applicable law or agreed to in writing, s... | Python | 1 |
());
let constructor_desc = "(Ljava/lang/ClassLoader;)V";
let constructor = Class::get_constructor(class_of_class.clone(), constructor_desc);
let object = Some(boxed(class_object));
let parameters = vec![
Parameter::Object(object.clone()),
... | Rust | 0 |
DUTY_CHNG_END_LSCH5_INT_ST_R {
DUTY_CHNG_END_LSCH5_INT_ST_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 8"]
#[inline(always)]
pub fn duty_chng_end_lsch4_int_st(&self) -> DUTY_CHNG_END_LSCH4_INT_ST_R {
DUTY_CHNG_END_LSCH4_INT_ST_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[... | Rust | 0 |
# modules/kinematics.py
import math
# Parametri cinematici (lunghezze dei bracci)
L1 = 140 # Lunghezza primo braccio (base al gomito) in mm
L2 = 140 # Lunghezza secondo braccio (gomito a polso) in mm
def forward_kinematics(angles):
"""
Calcola la posizione cartesiana (x, y, z) per un robot articolato a 3 DO... | Python | 1 |
import sys
from fontTools.ttLib import TTFont
outfile, infile, subft=sys.argv[1], sys.argv[2], sys.argv[3]
font=TTFont(infile)
font2=TTFont(subft)
cmap=font.getBestCmap()
cmap2=font2.getBestCmap()
go=font.getGlyphOrder()
uvg=set()
for table in font['cmap'].tables:
if table.format==14:
for vsl in table.uvsDict.key... | Python | 1 |
0x2E, 0x34, 0xB6,
0xA0, 0x56, 0xA6, 0x30, 0x89, 0x63, 0x6B, 0xE8, 0x85, 0x8C, 0x14, 0xB5, 0x38, 0x2A, 0xA2,
0xD7, 0xEA, 0x21, 0xA3, 0xB2, 0xBD, 0x74, 0x3E, 0x3C, 0x1A, 0x82, 0x8F, 0xCA, 0x27, 0xE0,
0x68, 0x44, 0x40, 0x9E, 0x42, 0x90, 0x8A, 0x72, 0x26, 0x0C, 0xF7, 0xB1, 0x0A, 0x71, 0x20,
... | Rust | 0 |
import os
import time
import cv2
import numpy as np
from Drivers import CameraDriver, MicroscopeDriver
from Utils.preprocessor_functions import remove_vignette_fast
file_path = os.path.dirname(os.path.abspath(__file__))
ff_path = "Path/To/The/Flatfield.png"
microscope = MicroscopeDriver()
camera = CameraDriver()
V... | Python | 1 |
addr = new_addr
msg[0].append(str(addr))
continue
# -- Otherwise try to parse the value
if addr.section:
if addr.section.is_executable() and addr.is_in_text_segment() and not is_ascii_string(addr.value):
insn = gef_cu... | Python | 1 |
import pygame
import sys
# Initialize Pygame
pygame.init()
# Set up the window
WINDOW_WIDTH = 400
WINDOW_HEIGHT = 300
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('Text Input')
# Set up fonts
font = pygame.font.Font(None, 32)
text = ''
lines = []
# Main loop
while True:... | Python | 1 |
assert!(let Err(_) = data.reshape(&[4, 5, 6, 1]).as_image_guess_rgb().map(|x| x.info));
}
#[test]
fn tensor_info_interlaced_with_known_format() {
let data = tch::Tensor::of_slice(&(0..60).collect::<Vec<u8>>());
// Monochrome
assert!(data.reshape(&[12, 5, 1]).as_mono8().map(|x| x.info) == Ok(ImageInfo::mono... | Rust | 0 |
if not started:
return None # Probably not >= Python 3.9, so no manager is needed.
# Create the remote manager and have monitor call its process_command()
# method to execute commands from clients.
manager = RemoteManager(layers)
# RemoteManager will process incoming command from the moni... | Python | 1 |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# Author: Donny You(youansheng@gmail.com)
# Visualize the log files.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
import numpy as np
import matplotlib.pyplot as plt
class LogVisualizer(object):
... | Python | 1 |
ensor:
_sum_and_numel = torch.tensor(
[x.sum(), x.numel()], dtype=torch.float32, device=x.device
)
if world_size > 1:
dist.all_reduce(_sum_and_numel, op=dist.ReduceOp.SUM)
return _sum_and_numel[0] / _sum_and_numel[1]
def add_to_summary_writer(
writer: Optional[SummaryWriter],
b... | Python | 1 |
R_EXTENDED.is_prime_order().unwrap_u8(), 1);
}
#[test]
fn test_affine_point_generator_nums_has_order_p() {
assert_eq!(GENERATOR_NUMS.is_prime_order().unwrap_u8(), 1);
}
#[test]
fn test_affine_point_generator_is_not_identity() {
assert_ne!(
JubJubExtended::from(GENERATOR.mul_by_cofactor()),
Jub... | Rust | 0 |
# Code generated by Lark OpenAPI.
import lark_oapi as lark
from lark_oapi.api.okr.v1 import *
def main():
# 创建client
client = lark.Client.builder() \
.app_id(lark.APP_ID) \
.app_secret(lark.APP_SECRET) \
.log_level(lark.LogLevel.DEBUG) \
.build()
# 构造请求对象
request: Upd... | Python | 1 |
)
);
bbt = Default::default();
bbt.bar = 0;
assert_eq!(
TransportBBT::default().with_bbt(0, 1, 0).validated(),
Err(TransportBBTValidationError::BarZero)
);
bbt = Default::default();
bbt.tick = bbt.ticks... | Rust | 0 |
irs = []
for result in results:
page = None
if 'metadata' in result and 'page_index' in result['metadata']:
page = result['metadata']['page_index']
elif 'page' in result and result['page'] is not None:
page = result['page']
if page... | Python | 1 |
::<Fr, BasicRadix2Domain<Fr>>(
c,
1 << 22,
"radix-2 DensePolynomial::mul - 2^22 - tweedle",
);
bench_dense_poly_muls::<Fr, BasicRadix2Domain<Fr>>(
c,
1 << 23,
"radix-2 DensePolynomial::mul - 2^23 - tweedle",
);
}
fn bench_dense_poly_div_by_vanishing_poly<F: P... | Rust | 0 |
iple_artifacts_processing(self, mock_agent):
"""Test processing multiple artifacts."""
# Create inputs with multiple artifacts
artifacts = [
Artifact(
type="TaskModel",
payload={"name": f"Task {i}", "priority": i},
produced_by="generato... | Python | 1 |
[800, 600]
)
.opengl(opengl)
.exit_on_esc(true)
.build()
.unwrap();
let vp = Viewport {
x_rot: 0.0,
y_rot: 0.0,
z_rot: 0.0,
x_trans: 0.0,
y_trans: 0.0,
z_trans: 500.0
};
let mut app = App {
gl: GlGr... | Rust | 0 |
'timestamp']}")
print(f" Size: {human_readable_size(file_info['size'])}")
print(f" Original: {file_info['original_path']}")
print()
def _show_help(self):
"""Show available commands"""
print("\n" + "="*50)
print("VAULTUSB COMMANDS")
... | Python | 1 |
th(1), True, dc_ratio, bn_momentum)
)
#print("initing stage 3")
self.stage3 = nn.Sequential(
SameConv(renew_width(320), renew_width(1280), 1, stride=1),
nn.BatchNorm2d(renew_width(1280), bn_momentum),
swish(),
nn.AdaptiveAvgPool2d(1),
n... | Python | 1 |
l_images)
@property
def tiling_scheme(self) -> TilingScheme:
return self._tiling_scheme
@property
def num_level_zero_tiles(self) -> Size2D:
return self._tiling_scheme.num_level_zero_tiles_x, self._tiling_scheme.num_level_zero_tiles_y
@property
def tile_size(self) -> Size2D:
... | Python | 1 |
<reponame>becmer/rsass
//! Tests auto-converted from "sass-spec/spec/libsass-closed-issues/issue_550/operator.hrx"
#[allow(unused)]
fn runner() -> crate::TestRunner {
super::runner()
}
#[test]
fn test() {
assert_eq!(
runner().ok("$x: .03;\
\n$y: 0.7;\n\
\n#foo {\
... | Rust | 0 |
perform op '{}' on {} and {}", name, x, y)),
}
}
fn or_bool(a: Term, b: Term) -> Term {
term![Op::BoolNaryOp(BoolNaryOp::Or); a, b]
}
pub fn or(a: CTerm, b: CTerm) -> Result<CTerm, String> {
wrap_bin_logical("||", None, Some(or_bool), a, b)
}
fn and_bool(a: Term, b: Term) -> Term {
term![Op::BoolNar... | Rust | 0 |
#!/usr/bin/env python3
# Software License Agreement (BSD License)
#
# Copyright (c) 2019, UFACTORY, Inc.
# All rights reserved.
#
# Author: Vinman <vinman.wen@ufactory.cc> <vinman.cub@gmail.com>
"""
Description: save force sensor zero data to xArm controller.
"""
import os
import sys
import time
sys.path.append(os.p... | Python | 1 |
search("(site:(?P<domain>[^ ]+))?( ?(?P<query>.*))?",data["query"]).groupdict()
if groups.get("query", False) and groups.get("domain", False) :
# expression in domain query
response = client.search(index="web-*", doc_type="page", body=query.domain_expression_query(groups["domain"], groups["query"]),... | Python | 1 |
import sys
import speech_recognition as sr
import pyttsx3
import webbrowser
import pywhatkit
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QPushButton
from PyQt5.QtCore import Qt, QThread, pyqtSignal
class ListenerThread(QThread):
signal = pyqtSignal(str)
def __init__(self):
super()._... | Python | 1 |
"post" ...) for given model.
/// Find one unique semantics.
fn find_unique_field(ctx: &mut BuilderContext, model: &ModelRef) -> Option<OutputField> {
arguments::where_unique_argument(ctx, model).map(|arg| {
let field_name = ctx.pluralize_internal(camel_case(&model.name), format!("findUnique{}", model.name)... | Rust | 0 |
ndle,
wallet_config: *const c_char,
cb: Option<extern fn(xcommand_handle: CommandHandle, err: u32)>) -> u32 {
info!("vcx_create_wallet >>>");
check_useful_c_callback!(cb, VcxErrorKind::InvalidOption);
check_useful_c_str!(wallet_config, VcxErro... | Rust | 0 |
ith_playwright(html_file_path, screenshot_path):
"""
Capture a full-page screenshot of the HTML file directly using Playwright.
"""
try:
# Launch Playwright in headless mode
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new... | Python | 1 |
# Problem #2: Index Game
# As a warmup, read this code and play the game a few times. Use this mental model of the list:
# Objective:
# Create a Python program that helps you practice accessing and manipulating elements in a list. This exercise will help you get comfortable with indexing, slicing, and modifying list e... | Python | 1 |
TY_MSB: u32 = 1;
pub const SIO_DIV_CSR_DIRTY_LSB: u32 = 1;
pub const SIO_DIV_CSR_DIRTY_ACCESS: &'static [u8; 3usize] = b"RO\0";
pub const SIO_DIV_CSR_READY_RESET: u32 = 1;
pub const SIO_DIV_CSR_READY_BITS: u32 = 1;
pub const SIO_DIV_CSR_READY_MSB: u32 = 0;
pub const SIO_DIV_CSR_READY_LSB: u32 = 0;
pub const SIO_DIV_CSR... | Rust | 0 |
m_text(text);
println!("Empty: {}\nLength: {}", index.is_empty(), index.len());
}
3 => {
let text = &args[1].to_string();
let word_match = &args[2].to_string();
let mut index = KWIndex::new();
index = index.extend_from_text(text);
p... | Rust | 0 |
# coding: utf-8
"""
codebeamer swagger API
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
The version of the OpenAPI document: 3.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # no... | Python | 1 |
# Generated by Django 5.1.1 on 2024-10-14 18:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('delivery', '0004_rename_delivery_address_delivery_delivery_postal_code_and_more'),
]
operations = [
migrations.RenameField(
mode... | Python | 1 |
.as_ref().clone().into(), vec![parent], id)
}
#[no_mangle]
pub extern "C" fn destroy_getv_operator(ptr: *const c_void) {
destroy_ptr::<pb::GetV>(ptr)
}
/// To initialize an path expand operator from an expand base
#[no_mangle]
pub extern "C" fn init_pathxpd_operator(
ptr_ex... | Rust | 0 |
# Copyright 2017 F5 Networks Inc.
#
# 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 required by applicable law or agreed to in writ... | Python | 1 |
import requests
import csv
import time
from bs4 import BeautifulSoup
class HaikuScraper:
"""
This scraper is designed with the purpose of scraping Haikus (Japanese poems) from Reddit.
"""
def __init__(self, url: str, headers: dict):
self.url = url
self.headers = headers
def make_request(se... | Python | 1 |
mut Self as *mut Self::Access) }.store(value);
}
}
/// Batch implementation of `BitStore` for appropriate types.
macro_rules! bitstore {
($($t:ty => $a:ty),* $(,)?) => { $(
impl seal::Sealed for $t {}
impl BitStore for $t {
/// The unsigned integers are only the `BitStore` parameter for
/// unaliased slic... | Rust | 0 |
available_space = self.width - len(leading_space) - len(' $')
space = available_space
while True:
space = text.rfind(' ', 0, space)
if (space < 0 or
self._count_dollars_before_index(text, space) % 2 == 0):
break
... | Python | 1 |
PhantomData;
use crate::v7400::object::property::{loaders::check_attrs_len, LoadProperty, PropertyHandle};
/// `rgb` crate color type loader.
///
/// This does minimal checks about `data_type` and `label`.
/// If you want to check property type precisely, you should make another
/// loader type by purpose.
///
/// No... | Rust | 0 |
xx, M1, N1, S1>) -> ()
where
M: Dim,
N: Dim,
M1: Dim,
N1: Dim,
S: Storage<Fxx, M, N>,
S1: StorageMut<Fxx, M1, N1>,
{
debug_assert!(mat.nrows() + dest_row <= dest.nrows(), "row overflow {} + {} > {}", dest_row, mat.nrows(), dest.nrows());
debug_assert!(mat.ncols() + dest_col <= dest.ncol... | Rust | 0 |
from typing import NamedTuple
from fastapi import HTTPException, status
from utilties.error_code import ErrorCode
class Errors(NamedTuple):
rating_mark_400 = HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=ErrorCode.RATING_EXCEPTION
)
question_not_exists_404 = HTTPExcepti... | Python | 1 |
documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum AmazonopensearchserviceS3BackupMode {
#[allow(missing_docs)] // documentation missing in mo... | Rust | 0 |
'''
Given a list of integers, let's decide that two consecutive items in the list are
neighbours if their difference is 1.
So, items 1 and 2 would be neighbours, and so would items 56 and 55.
Please write a function named longest_series_of_neighbours, which looks for the
longest series of neighbours within the list... | Python | 1 |
tor_tool, hammer_vlsi.HammerSRAMGeneratorTool)
output_libs = c.driver.sram_generator_tool.output_libraries # type: List[ExtraLibrary]
print(output_libs)
assert isinstance(output_libs, list)
# Should have an SRAM for each corner(2) and parameter(2) for a total of 4
assert len(outp... | Python | 1 |
request data");
return Packet::Binary(buf);
}
}
impl<E: fmt::Display + Send + 'static> WrapTrait for ErrorWrap<E> {
fn is_request(&self) -> bool {
false
}
fn serialize_req(&self, _: u64) -> Packet { unreachable!(); }
fn send_error(&mut self, _err: String) { unreachable!(); }
fn... | Rust | 0 |
alue,
}
#[repr(C)]
#[derive(Clone, Copy)]
pub struct AlvrOpenvrDeviceProp {
pub top_level_path: u64,
pub prop: AlvrOpenvrProp,
}
#[repr(C)]
#[derive(Clone, Copy)]
pub union AlvrButtonInputValue {
pub bool_: bool,
pub float_: f32,
}
// the profile is implied
#[repr(C)]
#[derive(Clone, Copy)]
pub struc... | Rust | 0 |
as not been
established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be
raised.
:return: Value to use for the read timeout.
:rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None
:raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect`
has ... | Python | 1 |
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional
from .memory import Memory
from .types import Message, Response, Tool
class BaseLLM(ABC):
"""Base class for all LLM implementations."""
@abstractmethod
async def generate(self, messages: List[Message], **kwargs) -> Resp... | Python | 1 |
stment_rate'] = stats['positive_adjustments'] / total_adjustments
else:
stats['positive_adjustment_rate'] = 0.0
return stats
def get_adjustment_history(self, limit: Optional[int] = None) -> List[WeightAdjustment]:
"""獲取調整歷史"""
if limit:
return self.adjustmen... | Python | 1 |
}
}
use std::io;
pub fn ask(question: &str) -> Result<String, io::Error> {
println!("{}", question);
let stdin = io::stdin();
let input = &mut String::new();
stdin.read_line(input)?;
Ok(input.trim_end().to_string())
}
<filename>unit2/module6-borrowing-and-mutability/01-02-in-functions-without-mut/... | Rust | 0 |
ttings.setValue("externalApiKey", self.external_api_key)
self.status_label.setText("已更新网络配置")
def show_about(self):
"""显示关于对话框"""
QMessageBox.about(
self,
"关于(!本代码完全免费!)",
"arXiv论文搜索工具\n版本 1.2.0\n\n"
"该工具可以搜索arXiv上的论... | Python | 1 |
").unwrap(), ImageFormat::Hdr);
assert_eq!(from_path("./a.pbm").unwrap(), ImageFormat::Pnm);
assert_eq!(from_path("./a.pAM").unwrap(), ImageFormat::Pnm);
assert_eq!(from_path("./a.Ppm").unwrap(), ImageFormat::Pnm);
assert_eq!(from_path("./a.pgm").unwrap(), ImageFormat::Pnm);
asse... | Rust | 0 |
:configure().diff_unicode_words(old, new)
}
/// Creates a diff of graphemes.
///
/// For more information see [`TextDiffConfig::diff_graphemes`].
///
/// This requires the `unicode` feature.
#[cfg(feature = "unicode")]
pub fn from_graphemes<T: DiffableStrRef + ?Sized>(
old: &'ol... | Rust | 0 |
=> convert_number::<i32>(row.get_opt(n).ok_or(FromSqlError::with_msg("got NULL"))??),
INT8 => convert_number::<i64>(row.get_opt(n).ok_or(FromSqlError::with_msg("got NULL"))??),
OID => convert_number::<u32>(row.get_opt(n).ok_or(FromSqlError::with_msg("got NULL"))??),
FLOAT4 => convert_float(row.g... | Rust | 0 |
le = max(files, key=lambda x: x.stat().st_mtime)
# JSON 파일 읽기
with open(latest_file, 'r', encoding='utf-8') as f:
character_data = json.load(f)
logger.info(f"캐릭터 데이터를 JSON 파일에서 불러왔습니다: {latest_file}")
print(f"📂 캐릭터 데이터를 불러왔습니다: {latest_file}")
... | Python | 1 |
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("gen_safe_prime 1", |b| b.iter(|| new(256).unwrap()));
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
//! Implements run observation by autosaving runs into the database on reset.
use std::rc::Rc;
use log::{info, warn};
us... | Rust | 0 |
def mul(self, scale):
"""
Args:
scale (tuple | list | int): the scale for four coords.
"""
if isinstance(scale, Number):
scale = to_4tuple(scale)
assert isinstance(scale, (tuple, list))
assert len(scale) == 4
self.bboxes[:, 0] *= scale[0]
self.bboxes[:, 1] *= ... | Python | 1 |
extension trait for `clap::ArgMatches`.
pub trait ArgMatchesExt<'a> {
/// Returns the result of `--[no-]ligatures`.
fn ligatures_flag(&self) -> Option<LigaturesFlag>;
}
impl<'a> ArgMatchesExt<'a> for clap::ArgMatches<'a> {
fn ligatures_flag(&self) -> Option<LigaturesFlag> {
if self.is_present("lig... | Rust | 0 |
"""SCons.Tool.dvips
Tool-specific initialization for dvips.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a cop... | Python | 1 |
lor='grey')
# plt.errorbar(x_delta_pmt, y_delta_pmt, yerr = y_delta_pmt_std,fmt ='o',markersize=0.1, capsize=3,color='grey')
# plt.ylabel('<$\delta$>, º',fontsize=14)
# plt.xlabel('Число ФЭУ',fontsize=14)
# plt.ylim(0,5)
# plt.xticks(fontsize=12)
# plt.yticks(fontsize=12)
# plt.show()
# # Dependance: delta(lenght of t... | Python | 1 |
stack![Axis(0), e, e],
stack![Axis(0), e, Array2::zeros((k, m))],
stack![Axis(0), Array2::zeros((k, m)), e]
];
let m = 3 * m;
assert_eq!((n, m), e.dim());
(m, e)
}
}
#[allow(clippy::many_single_char_names)] // REASON: match up with symbols in the ... | Rust | 0 |
# encoding: utf-8
"""
@author: xingyu liao
@contact: sherlockliao01@gmail.com
"""
import torch.nn.functional as F
from fastreid.modeling.heads import REID_HEADS_REGISTRY, EmbeddingHead
@REID_HEADS_REGISTRY.register()
class ClasHead(EmbeddingHead):
def forward(self, features, targets=None):
"""
... | Python | 1 |
# SPDX-FileCopyrightText: Copyright (c) 2021 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of sourc... | Python | 1 |
ocation(&mut self, mut stackmap: StackMap, value_reg: R64) {
let alloc_size = self.universe.fixnum_info.sizeof_instance() as i32;
if OPTIMIZE_FIXNUM_ALLOC_FAST_PATH {
self.emit_allocation(stackmap, alloc_size, &[(false, value_reg)]);
} else {
self.push_word(value_reg, &mu... | Rust | 0 |
ad.x_full,
residual_norm=float(payload.residual_norm),
iterations=int(payload.iterations),
half_period=payload.half_period,
)
def _initial_guess(self, domain_obj: "PeriodicOrbit", cfg: OrbitCorrectionConfig) -> np.ndarray:
"""Get the initial guess.
... | Python | 1 |
(self.root_dir, f"{frame['file_path']}.png"))
img = img.resize(self.img_wh, Image.LANCZOS)
img = self.toTensor(img) # (4, H, W)
valid_mask = (img[-1]>0).flatten() # (H*W) valid color area
img = img[:3, :, :]*img[-1:, :, :] + (1-img[-1:, :, :]) # blend A to... | Python | 1 |
.unwrap();
write!(stdout, "FAILED").unwrap();
}
stdout.reset().unwrap();
let elapsed = self.timer.elapsed();
writeln!(
stdout,
". {} passed; {} failed; 0 ignored; 0 measured; 0 filtered out; finished in {}.{:02}s\n",
tests_num - ... | Rust | 0 |
_index);
current_meta_index += jump_to_next_pixel;
}
current_meta_index += jump_to_next_row;
}
return in_sharp_actual_depth;
}
// Distance transform in processing layers in pass one from the back-most to
// the sharp depth.
void __attribute__((kernel))
ComputeLayerMatteBehindFocalDepth(uchar4 in, uin... | Rust | 0 |
let bytes = vec![0x00, 0x02, 0x00, 0x03];
(config, bytes)
}
/// Return a masked vector and its serialized version
pub fn mask_vect() -> (MaskVect, Vec<u8>) {
let (config, mut bytes) = mask_config();
let data = vec![
BigUint::from(1_u8),
BigUint::from(2... | Rust | 0 |
(2019 - 01 - 01));
assert_eq!(date!(2020 - 01 - 01) - 1.std_days(), date!(2019 - 12 - 31));
}
#[test]
fn sub_assign() {
let mut date = date!(2020 - 01 - 01);
date -= 1.days();
assert_eq!(date, date!(2019 - 12 - 31));
}
#[test]
fn sub_assign_std() {
let mut date = date!(2020 - 01 - 01);
date -=... | Rust | 0 |
(N, ...), make one-hot transformation
target = F.one_hot(target, num_classes=input.size(1)).permute(tuple([0, -1] + [i for i in range(1, target.dim())])).float()
elif input.dim() == target.dim():
# Assuming input and target are both tensors with same shape of (N, C, ...), wh... | Python | 1 |
import unittest
import numpy as np
import tensorflow as tf
from pymatgen.core.structure import Lattice, Structure
from m3gnet.graph import (
Index,
RadiusCutoffGraphConverter,
get_pair_vector_from_graph,
tf_compute_distance_angle,
)
def _loop_indices(bond_atom_indices, pair_dist, cutoff=4.0):
bi... | Python | 1 |
whether a refresh happened.
pub fn refresh(&mut self) -> bool {
if !self.vertex_source.as_ref().map(|s| s.needs_update(self.last_update)).unwrap_or(false)
&& !self
.fragment_source
.as_ref()
.map(|s| s.needs_update(self.last_update))
... | Rust | 0 |
I'm a [Marie](https://github.com/PaulSonOfLars/tgbot) fork.
I'm built in python3, using the \
python-telegram-bot library, and am fully opensource - you can find what makes me tick\
[here](https://github.com/peaktogoo/HarukaAya))!
Feel free to submit pull requests on github, or to contact my support group, @EchelonTe... | Python | 1 |
support_outputs, _ = fmodel(support_inputs)
inner_loss = nn.CrossEntropyLoss()(support_outputs, support_labels)
diffopt.step(inner_loss)
# 适应新任务(模拟查询集)
query_inputs, query_targets... | Python | 1 |
# Copyright 2017 Insurance Australia Group Limited
#
# 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 required by applicable law or ag... | Python | 1 |
!["sys/mount.h"],
"fstatfs64" => vec!["sys/vfs.h"],
"outl" => vec!["sys/io.h"],
"clone3" => vec!["sched.h"],
"getgroups" => vec!["unistd.h", "sys/types.h", "grp.h"],
"symlink" => vec!["fcntl.h", "unistd.h"],
"wait3" => vec!["sys/types.h", "sys/wait.h", "sys/time.h", "sys/... | Rust | 0 |
ite.clone()));
objects.add(sphere);
}
let radius = 300.0;
let num = radius as usize * 4;
let unit_theta = 2.0 * PI / num as f32;
for i in 0..num {
let x = (i as f32 * unit_theta).cos() * radius + 320.0;
let z = (i as f32 * unit_theta).sin() * radius + 320.0;
let sphe... | Rust | 0 |
nt: Event) -> Event:
"""Processes an event, updates the task state if applicable, stores it, and returns the event.
If the event is task-related (`Task`, `TaskStatusUpdateEvent`, `TaskArtifactUpdateEvent`),
the internal task state is updated and persisted.
Args:
event: The ... | Python | 1 |
import torch.nn as nn
import torch.nn.functional as F
class IncUpsamplingModule(nn.Module):
def __init__(
self,
input_channels,
output_channels,
ConvTranspose,
Dropout,
InstanceNorm,
dropout_p=0.3,
leakiness=1e-2,
conv_bias=True,
inst... | Python | 1 |
sys::fillellipse(x as c_int, y as c_int, rx as c_int, ry as c_int);
}
}
/// Draws a poly-line on the screen,
/// with the given flat list of XY coordinates in pixels.
///
/// Only makes sense in graphics mode.
///
/// # Panic
///
/// Panics if the given list of points is empty or not even.
#[inline]
pub fn draw_po... | Rust | 0 |
),
(None, Some(host)) => f.write_str(host),
(None, None) => Ok(()),
_ => return Err(fmt::Error),
}?;
if let Some(port) = &self.port {
f.write_char(':')?;
f.write_fmt(format_args!("{}", port))?;
}
f.write_str(self.path.to_str_los... | Rust | 0 |
,
obj: PyObjectRef,
cls: OptionalArg<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult;
fn _cls_is<T>(cls: &OptionalArg<PyObjectRef>, other: &T) -> bool
where
T: IdProtocol,
{
match cls {
OptionalArg::Present(cls) => cls.is(other),
Optional... | Rust | 0 |
HirKind::Concat(ref mut x) => {
stack.extend(x.drain(..));
}
HirKind::Alternation(ref mut x) => {
stack.extend(x.drain(..));
}
}
}
}
}
/// A type that documents various attributes of an HIR expression.
///
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.