text string | label_name string | labels int64 |
|---|---|---|
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import i2c, sensor
from esphome.const import (
CONF_ID,
CONF_TEMPERATURE,
DEVICE_CLASS_TEMPERATURE,
ICON_BRIEFCASE_DOWNLOAD,
STATE_CLASS_MEASUREMENT,
UNIT_METER_PER_SECOND_SQUARED,
ICON_SCREEN_ROTATIO... | Python | 1 |
18 => self.luminous_area_height_c0.to_string(),
19 => self.luminous_area_height_c90.to_string(),
20 => self.luminous_area_height_c180.to_string(),
21 => self.luminous_area_height_c270.to_string(),
... | Rust | 0 |
, state: &mut H)
where
H: std::hash::Hasher,
{
self.span.start().hash(state);
self.span.end().hash(state);
self.value.hash(state);
}
}
impl<T, Pos> Spanned<T, Pos> {
pub fn map<U, F>(self, mut f: F) -> Spanned<U, Pos>
where
F: FnMut(T) -> U,
{
Spa... | Rust | 0 |
: EcdsaKeyPair) -> Self {
KeyPair::ECDSA(ec_key)
}
/// Creates an ED25519 keypair.
#[cfg(feature = "ring")]
pub fn from_ed25519(ed_key: Ed25519KeyPair) -> Self {
KeyPair::ED25519(ed_key)
}
}
impl<K: HasPublic> KeyPair<K> {
/// Converts this keypair to the DNS binary form of the... | Rust | 0 |
// Serialize it to a JSON string.
let j = serde_json::to_string(&self)?;
// Print, write to a file, or send to an HTTP server.
Ok(j)
}
fn box_to_raw(&self) -> &dyn Any {
self
}
// fn to_concrete<T>(&self) -> T {
// let def: Box<dyn CommandConversion> = ... | Rust | 0 |
c_void,
func: *const c_void,
arg0: *const RUBase,
) {
let f: &&(Fn(&FocusEvent) + 'static) = transmute(func);
let obj_arg0_0 = FocusEvent::new_from_temporary(*(arg0 as *const RUFocusEvent));
f(&obj_arg0_0);
}
pub(crate) unsafe extern "C" fn line_edit_focus_out_trampoline_ud<T>(
self_c: *const ... | Rust | 0 |
Piece for ZonedDateTime<'a> {
fn hour(&self) -> i8 { self.adjusted.hour() }
fn minute(&self) -> i8 { self.adjusted.minute() }
fn second(&self) -> i8 { self.adjusted.second() }
fn millisecond(&self) -> i16 { self.adjusted.millisecond() }
}
/// The “type” of time that a transition is specified in.
#[der... | Rust | 0 |
-> PyResult<Vec<T>>
where
T: FromPyObject<'s>,
{
let seq = <PySequence as PyTryFrom>::try_from(obj)?;
let mut v = Vec::with_capacity(seq.len().unwrap_or(0) as usize);
for item in seq.iter()? {
v.push(item?.extract::<T>()?);
}
Ok(v)
}
impl<'v> PyTryFrom<'v> for PySequence {
fn try_fr... | Rust | 0 |
from textwrap import dedent
import pytest
from pandas import (
DataFrame,
Series,
)
pytest.importorskip("jinja2")
from pandas.io.formats.style import Styler
@pytest.fixture
def df():
return DataFrame(
{"A": [0, 1], "B": [-0.61, -1.22], "C": Series(["ab", "cd"], dtype=object)}
)
@pytest.fi... | Python | 1 |
#18870
import sys
input = sys.stdin.readline
#입력
n = int(input())
arr = list(map(int,input().split()))
#데이터 가공
tmp = arr[:]
tmp = list(set(tmp))#중복값 제거
tmp.sort()#정렬 -> 인덱스 = 압축된 좌표
#IDEA
dict = {}
for index, num in enumerate(tmp):#인덱스 = 압축된 좌표 이므로 enumerate 사용
dict[num] = index#key = 숫자, value = 압축된 좌표
#출력
for... | Python | 1 |
hable,
Operator::End*/
])
}
_ => {}
}
}
state.push_operator(operator);
Ok(())
}
}<filename>tests/project-with-version/src/lib.rs<gh_stars>100-1000
//! A test project with a version provided.
// https://l... | Rust | 0 |
(
&mut mlme_stream,
1,
fidl_mlme::AssociateResultCodes::Success,
true,
);
// Drain the RSNA negotiation timeout message.
assert_variant!(time_stream.try_next(), Ok(Some(_)));
for _i in 0..4 {
client.verify_eapol_req(&mut mlme_... | Rust | 0 |
from datetime import datetime, timezone
from ingestion.schema import Envelope, OpenAlexWork
import ingestion.producer as prod
def test_strip_run_alias_removes_second_token():
args = ["-m", "run", "--batch-size", "10"]
prod._strip_run_alias(args)
assert args == ["-m", "--batch-size", "10"]
def make_batch... | Python | 1 |
load()?;
check_lock(&state)?;
if env.message.signer != state.oracle {
unauthorized()?;
} else {
valid_ecostate(&ecostate)?;
let ecostate_delta = ecostate - state.ecostate;
state.ecostate = ecostate;
if ecostate_delta > 0 {
state = execute_payout(state, ... | Rust | 0 |
Sleep mode"]
pub struct FSMCLPEN_W<'a> {
w: &'a mut W,
}
impl<'a> FSMCLPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: FSMCLPEN_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Selected module is disabled during Sleep mode"]
... | Rust | 0 |
ground": "#3498db",
"highlight": {
"border": "#2c3e50",
"background": "#e74c3c"
},
"hover": {
"border": "#2c3e50",
"background": "#e74c3c"
}
... | Python | 1 |
mentation used in rustc
pub type HashMap<K, V> = rustc_hash::FxHashMap<K, V>;
/// Faster hashSet implementation used in rustc
pub type HashSet<K> = rustc_hash::FxHashSet<K>;
/// IndexMap data implementation used in rustc
pub type IndexMap<K, V> = indexmap::IndexMap<K, V, BuildHasherDefault<rustc_hash::FxHasher>>;
pu... | Rust | 0 |
from queue import Queue
import confuse
from trakt_scrobbler import config, logger
from trakt_scrobbler.backlog_cleaner import BacklogCleaner
from trakt_scrobbler.log_config import LOG_PATH
from trakt_scrobbler.notifier import notify
from trakt_scrobbler.player_monitors import collect_monitors
from trakt_scrobbler.scrob... | Python | 1 |
from generator import generator as gen
from generator import make_z_normal
import tensorflow as tf
from absl import app, flags
import cv2
import numpy as np
import matplotlib.pyplot as plt
import os
from categories import indx2category
from scipy.stats import truncnorm
# Random states: 4, 99, 3, 900, 412, 109
flags.DE... | Python | 1 |
"""
Dataclasses para dados públicos da API do Mercado Bitcoin.
Estes dados não requerem autenticação para serem acessados.
"""
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal
from typing import Any, Dict
@dataclass
class TickerData:
"""Representa os dados de um ticker ... | Python | 1 |
index_mut(&mut self, index: u16) -> &mut Self::Output {
&mut self.memory[index as usize]
}
}
impl Memory for SimpleMemory {
fn read_byte(&mut self, _regs: &mut Registers, addr: u16) -> u8 {
self.memory[addr as usize]
}
fn write_byte(&mut self, _regs: &mut Registers, addr: u16, value: u... | Rust | 0 |
"""
This file is part of Criadex.
Criadex 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.
Criadex is distributed in the hope that it will b... | Python | 1 |
a `HSV.D`
/// instruction which is effectively an unreference to any memory address.
#[inline]
pub unsafe fn hsv_d(dst: *mut i64, src: i64) {
asm!(".insn r 0x73, 0x4, 0x37, x0, {}, {}", in(reg) dst, in(reg) src, options(nostack));
}
//! # Market
//!
//! Contains functions for retrieving market order data from the... | Rust | 0 |
別を元に合法手を列挙して返す
///
/// # Arguments
/// * `t` - 手を列挙したい手番
/// * `state` - 盤面の状態
/// * `dst` - 移動元の位置
///
/// 移動元の位置からさらに移動できる位置を取得するときに使う。
/// 渡した引数の状態が不正な場合の動作は未定義
pub fn legal_moves_with_dst_put(t:Teban,state:&State,dst:KomaDstPutPosition)
-> Vec<LegalMove> {
match dst {
KomaDstPutPosition(... | Rust | 0 |
import matplotlib.pyplot as plt
def plot_data_quality_scores(scores, title='Data Quality Scores'):
"""Plot bar chart of data quality scores."""
categories = list(scores.keys())
values = list(scores.values())
plt.figure(figsize=(10, 5))
plt.bar(categories, values, color='skyblue')
plt.xlabel('Da... | Python | 1 |
n = int(input("Число, факторіал якого будем розраховувать "))
factorial = 1
for i in range(1, n + 1):
factorial *= i
print(f"Факторіал числа {n} дорівнює: {factorial}")
| Python | 1 |
_pw_w) = pw.generate_curve_data(pc_pw_d[l], 0.0, sl_pw_d[l], npoint)?;
// curve
let mut curve_bc_d = Curve::new();
let mut curve_vg_d = Curve::new();
let mut curve_pw_d = Curve::new();
let mut curve_bc_w = Curve::new();
let mut curve_vg_w = Curve::new();
let mut curve_pw_w = Curve::new();
... | Rust | 0 |
import logging
from aiogram import Bot, Dispatcher, executor, types
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
import re
from environs import Env
from instagram import instagram_download
from tik_tok import tik_tok_download
from yt import get_video_data
logging.basicConfig(level=logging.INFO)... | Python | 1 |
S3 redirect
response = await client.get(polar_download_url, follow_redirects=False)
assert response.status_code == 302
s3_download_url = response.headers.get("location", None)
assert s3_download_url
# S3 Download works & matches our expectations
async with AsyncClient()... | Python | 1 |
you should assume not. On Windows 10+ you
/// must use the [`enable_ansi_support()`] function to turn on support.
#[inline(always)]
pub fn fmt_supported_stdout() -> bool {
atty::is(atty::Stream::Stdout)
}
/// Are ANSI format sequences supported on stderr?
///
/// - On Unix this is reliable, returning `true` onl... | Rust | 0 |
#!/usr/bin/env python
"""
Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import os
import re
from lib.core.common import singleTimeWarnMessage
from lib.core.enums import DBMS
from lib.core.enums import PRIORITY
__priority__ = PRIORITY.HIGHEST
de... | Python | 1 |
######################################################################################
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
i = 0
j = 0
result = []
# 동시에 만족하는 경우까지만 append
while i < len(word1) and j < len(word2):
result.append... | Python | 1 |
[str] | None = None,
) -> dict[str, float]:
"""Return body longitudes for the Davison chart at the time midpoint."""
mid_dt, _, _ = davison_midpoints(dt_a, loc_a, dt_b, loc_b)
positions = provider(mid_dt)
if bodies is None:
return dict(positions)
return {key: positions[key] for key in bodie... | Python | 1 |
5% tax
tax_amount = subtotal * tax_rate
total_amount = subtotal + tax_amount
totals_data = [
['Subtotal:', f"${subtotal:.2f}"],
['Tax (5%):', f"${tax_amount:.2f}"],
['Total:', f"${total_amount:.2f}"]
]
totals_table = Table(totals_data, colWidths=[1*inch, 1*inch])
... | Python | 1 |
2_weeks['MA50'].iloc[-2]
#today_ma200 = df_52_weeks['MA200'].iloc[-1]
#yesterday_ma200 = df_52_weeks['MA200'].iloc[-2]
#today = df_52_weeks['timestamp'].iloc[-1]
#today_close = df_52_weeks['adjusted_close'].iloc[-1]
# Check for crossover (above or below)
#if (today_ma50 > today_ma200 and yesterday_ma50 < yesterday_ma... | Python | 1 |
class Solution:
def subarraySum(self, arr, target):
# code here
l=0
res=0
for r in range(len(arr)):
res+=arr[r]
if res==target:
return [l+1,r+1]
elif res>target:
while l<=r and res>target:
res-=ar... | Python | 1 |
import multiprocessing
from allmodels.Task import Task
from core.decorator.normal_functions import *
from core.const.Do import *
from service.HttpService import HttpService
from core.config.InitConfig import isClusterConf
class TaskProgress(multiprocessing.Process):
def __init__(self,taskExecuteId = 0,runTaskSer... | Python | 1 |
'''
Extracción DNS con Python
Query ¿Para qué lo uso?
A IPv4
AAAA IPv6
MX MailServers
NS NameServers
'''
import dns.resolver
import sys
def dnsQuery(domain, lookuptype):
try:
answer = dns.resolver.query(domain,lookuptype)
for ans in answer:
if lookupt... | Python | 1 |
MIT_MODEL_CONFIG = {
"MiT_B0": {"embed_dims": [32, 64, 160, 256], "depths": [2, 2, 2, 2]},
"MiT_B1": {"embed_dims": [64, 128, 320, 512], "depths": [2, 2, 2, 2]},
"MiT_B2": {"embed_dims": [64, 128, 320, 512], "depths": [3, 4, 6, 3]},
"MiT_B3": {"embed_dims": [64, 128, 320, 512], "depths": [3, 4, 18, 3]},... | Python | 1 |
36C0, 4),
}
tornPageLocks = {
"TornPage1": WorldLocationData(0x1DB7, 4), # --Scenario_1_start
"TornPage2": WorldLocationData(0x1DB7, 7), # --Scenario_2_start
"TornPage3": WorldLocationData(0x1DB8, 2), # --Scenario_3_start
"TornPage4": WorldLocationData(0x1DB8, 4), # --Scenario_4_start
"TornPage... | Python | 1 |
e: frame rate
Returns a list of TrackingBboxes
Implementation inspired from code found here: https://github.com/ifzhang/FairMOT/blob/master/src/track.py
"""
self.opt.conf_thres = conf_thres
self.opt.track_buffer = track_buffer
self.opt.min_box_area = min_box_area
... | Python | 1 |
ormat,
SafeSearch,
XBingApisSDK,
)
__all__ = [
"Airport",
"Answer",
"CivicStructure",
"ContractualRulesAttribution",
"ContractualRulesContractualRule",
"ContractualRulesLicenseAttribution",
"ContractualRulesLinkAttribution",
"ContractualRulesMediaAttribution",
"ContractualRu... | Python | 1 |
50", alpha=0.7)
# Plot signals
for signal in signals:
if signal["signal"] == "buy":
plt.scatter(
signal["date"],
signal["price"],
color="green",
marker="^",
s=100,
)
else:
plt.sc... | Python | 1 |
self.model_name = model_name
class BaiChuanChat(Base):
def __init__(self, key, model_name="Baichuan3-Turbo", base_url="https://api.baichuan-ai.com/v1"):
if not base_url:
base_url = "https://api.baichuan-ai.com/v1"
super().__init__(key, model_name, base_url)
@staticmethod
... | Python | 1 |
urn Output(metadata={"empty_metadata": True}, value=None)
PublishConnectorLifecycle.log(
context,
PublishConnectorLifecycleStage.REGISTRY_ENTRY_GENERATION,
StageStatus.IN_PROGRESS,
f"Generating registry entry for {metadata_entry.file_path}",
)
spec_cache = SpecCache()
... | Python | 1 |
frame_num-wind_leng+1):
keypoint_sample = keypoint_tensor[:, i:i+wind_leng]
keypoint_input.append(keypoint_sample[np.newaxis,:])
return keypoint_input
def map_result_to_step(action_result, frame_step):
action_list = []
action_list.extend(["step: unknown"]*frame_step)
for action_type i... | Python | 1 |
# to pass in the functions for each.
if "upload_call_conversions" not in self._stubs:
self._stubs["upload_call_conversions"] = (
self._logged_channel.unary_unary(
"/google.ads.googleads.v20.services.ConversionUploadService/UploadCallConversions",
... | Python | 1 |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
distance = float(input("nhập độ dài đoạn đường đến trường(m): "))
if distance < 300:
print("đường đến trường quá gần. Thôi! Đi bộ")
elif distance > 1200:
print("Đường đến trường xa quá. Thôi! Đi xe máy")
elif distance >= 300 and dis... | Python | 1 |
tokens or "goodbye" in tokens or "bye" in tokens:
self.save_data()
self.speak("Goodbye! Thank you for using Athena AI Assistant!")
self.is_running = False
else:
self.speak("I didn't understand that command. Say 'athena help' for available commands.")
... | Python | 1 |
from typing import Any, Dict, Optional
from sahi.utils.file import import_model_class
MODEL_TYPE_TO_MODEL_CLASS_NAME = {
"yolov8": "Yolov8DetectionModel",
"mmdet": "MmdetDetectionModel",
"yolov5": "Yolov5DetectionModel",
"detectron2": "Detectron2DetectionModel",
"huggingface": "HuggingfaceDetectio... | Python | 1 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | Python | 1 |
# 택배 상하차 알바
# 택배가 내려오는 레일의 순서를 조작해 최소한의 무게만 들고싶다
# N개 레일
# N번째 레일의 택배무게 Ni
# 택배 바구니 무게 M
# 바구니 무게 초과하지 않게 담아서 이동하면 1번 일한거
# K번 일할 때 최소한의 무게로 일하도록
# N M K
# N1 N2 N3...
import sys
import itertools
N,M,K = map(int,sys.stdin.readline().split())
Nlist = list(map(int, input().split()))
def cal_weight(T):
current_su... | Python | 1 |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Contains common test fixtures used to run unit tests.
"""
import sys
import boto3
import pytest
import os
script_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(script_dir)
import iotsit... | Python | 1 |
upplied modelgrid
#
# In some cases it may be necessary to override the model's modelgrid instance with a seperate modelgrid. An example of this is if the model discretization is in feet and the user would like it projected in meters. Exporting can be accomplished by supplying a modelgrid as a `kwarg` in any of the `ex... | Python | 1 |
21.note.Note F>
{4.25} <music21.note.Note G>
{5.25} <music21.note.Note A>
{6.25} <music21.note.Note B>
{7.25} <music21.note.Note C>
...
'''
from music21 import audioSearch as audioSearchBase
freqFromAQList = audioSearchBase.getFrequenciesFromAudioFile(waveFilename=fileName)
detecte... | Python | 1 |
import logging
import os
import sys
# Define a custom formatter for Nexion
class NexionFormatter(logging.Formatter):
"""Custom formatter with colored output for different log levels"""
COLORS = {
logging.DEBUG: "\033[36m", # Cyan
logging.INFO: "\033[32m", # Green
logging.WARNING: "\... | Python | 1 |
f,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/interfaces/ip",
defining_module="openconfig-if-ip",
yang_type="leafref",
is_config=False,
)
interface... | Python | 1 |
be scaled
plt.quiver3d(x2v, y2v, z2v, dhdx, dhdy, dhdz, mode='arrow',
scale_mode='none', opacity=0.5)
# end draw 3D vector field with countours of 3D scalar field
# Save figures to files
plt.figure(1)
plt.savefig('images/simple_plot_mayavi.png')
plt.figure(2)
plt.savefig('images/simple_plot_colours_mayav... | Python | 1 |
ect_list = []
mock_request = create_mock_request(user=mock_user)
# Act
results = query_views.format_local_results(
results=mock_results, request=mock_request
)
# Assert
self.assertIsInstance(results, list)
@override_settings(INSTALLED_APPS=[])
def t... | Python | 1 |
""" Access control utilities for core_main_app.
"""
import logging
from core_main_app.access_control.exceptions import AccessControlError
from core_main_app.components.group import api as group_api
from core_main_app.permissions import api as permissions_api, rights
logger = logging.getLogger(__name__)
def check_ha... | Python | 1 |
"""
Author: Reuben Ferrante
Date: 10/05/2017
Description: General scripts for graphing instead of notebook.
"""
from evaluation_scripts.plotting_trajectory import *
def plot_single_trajectories(res):
# Low Disc
x_planned = np.load('C://Users//REUBS_LEN//PycharmProjects//RocketLanding//control_and_ai//evalu... | Python | 1 |
"""
Google Search Example for Langflow Agents
This example demonstrates how to use the Google Search tool with Langflow agents
in a production environment.
"""
import os
import logging
import sys
# Add the project root to the Python path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
#... | Python | 1 |
from __future__ import annotations
import asyncio
from typing import Callable, Generic, TypeVar, Awaitable
from .channel import Channel
from .core import Effect
from .context import Context
from .stream import StreamE
from .queue import Queue, QueueClosed
A = TypeVar('A'); B = TypeVar('B')
class Stage(Generic[A,B]):
... | Python | 1 |
Ref(Mean($close, 15), 225) Ref(Mean($close, 15), 465) Ref(Mean($close, 15), 705)
# instrument datetime
# SH600519 2021-05-31 241.769897 243.077942 244.712997
# 2021-06-01 244.... | Python | 1 |
)
```
Returns:
[`~pipelines.ImagePipelineOutput`] or `tuple`:
If `return_dict` is `True`, [`~pipelines.ImagePipelineOutput`] is returned, otherwise a `tuple` is
returned where the first element is a list with the generated images
"""
# Sample... | Python | 1 |
f(isinstance(outputs1, tuple) or isinstance(outputs1, list)):
outputs1 = outputs1[0]
p_argmax = torch.argmax(outputs1, dim = 1, keepdim = True)
p_soft = get_soft_label(p_argmax, class_num, self.tensor_type)
p_soft, y = reshape_prediction_and_ground_truth(p_soft, y)... | Python | 1 |
llbackManagerForChainRun,
) -> List[Document]:
"""Get docs."""
return self.retriever.invoke(
question, config={"callbacks": run_manager.get_child()}
)
async def _aget_docs(
self,
question: str,
*,
run_manager: AsyncCallbackManagerForChainRun,
... | Python | 1 |
from fasthtml.common import *
def footer():
return Footer(
Div( P("Jairo Cogollo"), cls="top-footer"
),
Div(
Ul(
Li(
A("Home",href="#home"), cls="footer_menu_list",),
Li(
A("About",href="#about"), cls="foo... | Python | 1 |
ervice = NotificationServices()
# 模擬渠道
mock_channel = MagicMock()
mock_channel.is_enabled.return_value = True
mock_channel.name = "test"
mock_channel.timeout = 30
mock_channel.retry_count = 3
service.channels["test"] = mock_channel
... | Python | 1 |
if chunk_idx >= fallback_chunk_size:
chunk_sparse = process_chunk()
if chunk_sparse is not None:
all_sparse_chunks.append(chunk_sparse)
... | Python | 1 |
r r r r r r r r r r- r* rd rd !)+r- rd c 4 \ rS rSr\" S5 r\" S5 rSrg)rc r rawr Nri r r r rh r r r r r- r* rc rc '"E
Cr- rc r -r# weakref r r contextr... | Python | 1 |
from alerts import send_alert # Importing send_alert function from alerts.py
from db import mongo
CPU_THRESHOLD = 80.0 # threshold for CPU usage
DISK_THRESHOLD = 90.0 # threshold for disk usage (%)
MEMORY_THRESHOLD = 75.0 # threshold for memory usage (%)
def analyze_data():
try:
# Retrieve metrics fro... | Python | 1 |
, int, float, bool).
Args:
obj: A dictionary structure composed of dictionaries, lists, and primitive types.
Returns:
A cleaned version of the input structure with all empty values removed.
"""
if isinstance(obj, str):
return obj.strip()
elif isinstance(obj, (int, float, b... | Python | 1 |
undo: typing.Optional[bool] = None):
''' Remove color attribute from geometry
:type override_context: typing.Union[typing.Dict, 'bpy.types.Context']
:type execution_context: typing.Union[str, int]
:type undo: typing.Optional[bool]
'''
pass
def color_attribute_render_set(
overr... | Python | 1 |
missing_columns = [col for col in required_columns if col not in df.columns]
# if missing_columns:
# raise ValueError(f"Missing required columns: {', '.join(missing_columns)}")
# if df['Subcategory'].isnull().any() or df['Feedback'].isnull().any() or df['Subcategory'].eq('').any() or df['Feedback'].eq('... | Python | 1 |
r_hdr_film import PhasorHDRFilm
if not (isinstance(sensor.film(), TransientHDRFilm) or isinstance(sensor.film(), PhasorHDRFilm)):
raise AssertionError(
"The film of the sensor must be of type transient_hdr_film or phasor_hdr_film"
)
del TransientHDRFilm
def... | Python | 1 |
# Copyright (c) 2019-2022, NVIDIA CORPORATION.
import pytest
import cudf
from cudf.core.column import column
from cudf.testing._utils import assert_eq, gen_rand_series
def _kernel_multiply(a, b, out):
for i, (x, y) in enumerate(zip(a, b)):
out[i] = x * y
@pytest.mark.parametrize("dtype", ["float32", "... | Python | 1 |
import cv2
import os
import numpy as np
## 训练特征模型
# 读取多张脸
# 用于保存人脸
faces = []
# 用于保存训练后的标签
labels = []
# 标签对应的名称
labels_text = {"0": "yangmi"}
# 将目录下的jpg文件以灰度图的方式读取到图像列表中
for f in os.listdir("yangmi"):
# 不是jpg文件就跳过
if '.jpg' not in f:
continue
# 读取人脸图片到列表中,注意这里要使用灰度图
face... | Python | 1 |
import cv2
import os
import os.path as osp
from pathlib import Path
class ImageCache:
data = {}
def get_image(name, to_rgb=False, use_cache=True):
key = (name, to_rgb)
if key in ImageCache.data:
return ImageCache.data[key]
images_dir = osp.join(Path(__file__).parent.absolute(), 'images')
e... | Python | 1 |
#!/usr/bin/env python
from vtkmodules.vtkIOImage import vtkPNGReader
from vtkmodules.vtkImagingCore import (
vtkImageAppendComponents,
vtkImageClip,
)
from vtkmodules.vtkImagingGeneral import vtkImageGaussianSmooth
from vtkmodules.vtkImagingStatistics import vtkImageAccumulate
from vtkmodules.vtkInteractionImag... | Python | 1 |
| 0 | 0 | 0 | 0 | 0 | 1 |
+----------------------------------+----------------+----------------+----------------+----------------+----------------+----------------+----------------+----------------+
| 128/256 ... | Python | 1 |
global_logger.critical("BitTorrent core initialization failed!")
core_doneflag.set()
rawserver.stop()
try:
gui_wrap(mainloop.ExitMainLoop)
except:
pass
try:
gui_wrap(mainloop.doneflag.set)
ex... | Python | 1 |
import os.path as path
import numpy as np
import pandas as pd
def read_dataset(dataset, subname=None):
if dataset == "NASA":
assert subname in ["A-4", "T-1", "C-2"]
data_root = "./datasets/NASA"
train_data = pd.read_csv(path.join(data_root, f"{subname}.train.csv")).values[:, 1:-1]
... | Python | 1 |
import torch
import neuralop.mpu.comm as comm
def setup(config):
"""A convenience function to intialize the device, setup torch settings and
check multi-grid and other values. It sets up distributed communitation, if used.
Parameters
----------
config : dict
this function checks:
... | Python | 1 |
# Conversor Ton-Kgr y Pies-Mts
"""
Elaborar un algoritmo tal que dado como datos el nombre de un dinosaurio, su peso y su longitud,
expresados estos dos últimos en toneladas y pies respectivamente; que imprima el nombre del
dinosaurio, su peso en kilogramos y su longitud en metros.
"""
dinosaurio = input("Ingre... | Python | 1 |
AWS_CONFIG = {
"region": "us-east-1",
"endpoints": [
{
"s3": "http://localhost:4566",
"sts": "http://localhost:4566",
"apigateway": "http://localhost:4566",
"apigatewayv2": "http://localhost:4566",
"cloudformation": "http://localhost:4566",
... | Python | 1 |
ha_url or config.get("waha_url", DEFAULT_WAHA_URL)
api_key = args.api_key or config.get("api_key", DEFAULT_API_KEY)
session = args.session or config.get("session", DEFAULT_SESSION)
# Verificar se o servidor WAHA está configurado
logger.info("Verificando configuração do servidor WAHA...")
#... | Python | 1 |
from typing import List
from pyrep.backend import sim
from pyrep.const import ObjectType
from pyrep.objects.force_sensor import ForceSensor
from pyrep.objects.object import Object
from pyrep.objects.shape import Shape
class Accelerometer(Object):
"""An object able to measure accelerations that are applied to it.... | Python | 1 |
fpath.__unicode__.return_value = '/tmp/000.jpg'
fpath.__str__.return_value = '/tmp/000.jpg'
camera.target_page = 'odd'
camera.capture(fpath)
cap_args = tuple(camera._device.shoot.mock_calls[0])[-1]
assert cap_args['dng']
@mock.patch('spreadsplug.dev.chdkcamera.JPEGImage')
def test_capture_noprep... | Python | 1 |
slot = self.current_inventory.slots[self.selected_slot]
if slot.is_empty():
return
item_instance = slot.item_instance
if item_instance is None:
return
item = item_manager.get_item(item_instance.item_id)
# タイトル
title_text ... | Python | 1 |
unpermuted_global_hidden.scatter_add(
0, global_local_map, unpermuted_local_hidden
)
if self.add_bias:
unpermuted_global_bias = torch.zeros_like(unpermuted_global_hidden)
output_bias_total = unpermuted_global_bias.scatter_add(
0... | Python | 1 |
# Copyright 2019 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Python | 1 |
def print_abs_stats(task_name, alpha, num_true, num_false, num_abstain, max_abs
):
total = num_true + num_false
tot_pred = total - num_abstain
abs_frac = num_abstain / total
abs_acc = 1.0
if tot_pred > 0:
abs_acc = num_true / tot_pred
print(
' task, alpha, tr... | Python | 1 |
import bpy
outdated_types = {"game.arm" : "game.limbs.arm",
"game.basic_spine" : "game.spines.basic_spine",
"game.basic_tail" : "game.spines.basic_tail",
"game.copy_chain" : "game.basic.copy_chain",
"game.front_paw" : "game.limbs.front_paw... | Python | 1 |
import os
import random
import sys
from maths.greatest_common_divisor import gcd_by_iterative
from . import cryptomath_module, rabin_miller
def main() -> None:
print("Making key files...")
make_key_files("rsa", 1024)
print("Key files generation successful.")
def generate_key(key_size: int) -> tuple[tu... | Python | 1 |
]])
output1 = qnn.forward(x)
output2 = qnn.forward(x)
np.testing.assert_array_almost_equal(output1, output2)
def test_vqe_parameter_sensitivity(self):
"""Test VQE parameter sensitivity."""
vqe = VQE(n_qubits=2)
# Small parameter change
... | Python | 1 |
import torch
from torch import nn
import torch.nn.functional as F
from configs.paths_config import model_paths
class MocoLoss(nn.Module):
def __init__(self):
super(MocoLoss, self).__init__()
print("Loading MOCO model from path: {}".format(model_paths["moco"]))
self.model = self.__load_mod... | Python | 1 |
import numpy as np
#translate generalized velocity b into cartesian velocity v
#Input derivative of the spline, b, and the number of path sections
def translate_velocity(spline_diff, b,N_discretization):
#discretization lenght
deltatheta = 1/(N_discretization-1)
#midpoints discretization
d... | Python | 1 |
#!/usr/bin/python3
"""Unittest for max_integer([..])"""
import unittest
max_integer = __import__('6-max_integer').max_integer
class TestMaxInteger(unittest.TestCase):
def test_value(self):
""" Test random order list """
self.assertEqual(max_integer([65, 54, 98, 51, 0, -65]), 98)
""" Test ... | Python | 1 |
return tuple(result_lines)
except ValueError:
return ("", "", "", "", "")
#======提取特定行
class ExtractSpecificLines:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"input_text": ("STRING", {"multiline": True, "default": ""}),
"... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.