text string | label_name string | labels int64 |
|---|---|---|
# 1. ---------------- Encabezado -----------------------------------
'''
Programa: Simulación de Dulcería Cinépolis (Atención Eficiente)
Autores: Politrón Díaz Josué Yered,
Pacheco Cedillo Jorge Anuar,
Fuertes Espinosa Ioshua Daniel,
Rodriguez de Matias Adrian
Robles Cedillo Irving Xn... | Python | 1 |
prefetch;
pub mod compression;
pub mod utils;
pub mod errors;
pub mod fileinfo;
pub mod metrics;
pub mod tracechain;
pub mod volume;
pub mod filestrings;
<filename>src/config.rs<gh_stars>1-10
use std::net::SocketAddr;
use config::{Config as RowConfig, ConfigError, File, FileFormat};
use serde::Deserialize;
#[derive(... | Rust | 0 |
a = int(input())
b = int(input())
print(a+b)
print(a-b)
print(a*b) | Python | 1 |
7Function::Output {
regs.po_pointer_update_time = Instant::now();
}
Ok(())
}
struct AudioWorker {
func: Ac97Function,
regs: Arc<Mutex<Ac97BusMasterRegs>>,
mem: GuestMemory,
thread_run: Arc<AtomicBool>,
lvi_semaphore: Arc<Condvar>,
message_interval: Duration,
stream: Box<dyn... | Rust | 0 |
# Copyright (c) OpenMMLab. All rights reserved.
import cv2
import numpy as np
import torch
from mmcv.ops import pixel_group
from mmocr.core import points2boundary
from mmocr.models.builder import POSTPROCESSOR
from .base_postprocessor import BasePostprocessor
@POSTPROCESSOR.register_module()
class PANPostprocessor(B... | Python | 1 |
entree = input("Entrez des nombres séparés par des espaces : ")
liste = [int(x) for x in entree.split()]
somme_pairs = 0
for nombre in liste:
if nombre % 2 == 0:
somme_pairs += nombre
print(f"Somme des nombres pairs : {somme_pairs}") | Python | 1 |
from neuralhydrology.training.basetrainer import BaseTrainer
from neuralhydrology.training.umaltrainer import UMALTrainer
from neuralhydrology.utils.config import Config
def start_training(cfg: Config):
"""Start model training.
Parameters
----------
cfg : Config
The run configuration.
... | Python | 1 |
# adapted from https://cs.stackexchange.com/a/65744
def parse_from_numeral_system(digits: str, alphabet: str) -> int:
"""Compute the integer value represented by string 'digits' in a custom
base.
Parameters
----------
digits : str
A string of digits in the custom base.
alphabet : str
... | Python | 1 |
g
}
pub fn split_timespan_max_days(timespan: &TimeSpan, max_days: i64) -> Vec<TimeSpan> {
if (timespan.end - timespan.start).num_days() < max_days {
return vec![TimeSpan {
start: timespan.start,
end: timespan.end,
}];
}
let mut timespans: Vec<TimeSpan> = vec![];
... | Rust | 0 |
::nix::Error::Sys(errno)) => {
if errno != Errno::ENOENT {
let msg = format!("could not set sysctl {} to {}", key, value);
Err(::nix::Error::Sys(errno)).chain_err(|| msg)?;
}
warn!("could not set {} because it doesn't exist", key);
return O... | Rust | 0 |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import sys
import numpy as np
aggregate_funcs = {
"std": np.std,
"var": np.var,
"median": np.median,
"mean"... | Python | 1 |
[*u].push(*v);
t[*v].push(*u);
}
let mut label = vec![n; n];
let mut l = 0 as usize;
for i in 0..n {
if label[i] != n { continue; }
label[i] = l;
let mut que = std::collections::VecDeque::new();
que.push_back(i);
whi... | Rust | 0 |
noise
size = 256
img = img.resize((size, size))
img = np.asarray(img)
h_noise = np.random.randint(10, int(size // 8))
w_noise = np.random.randint(10, int(size // 8))
start_h_noise = np.random.randint(1, size - h_noise)
start_w_noise = np.random.randint(1, size - w... | Python | 1 |
preço = float(input('Qual é o preço do produto? Kz'))
novo = preço - (preço * 5 / 100)
print('O produto qu valia {:.2f}Kz, com o desconto de 5% vai custar {:.2f}Kz'.format(preço, novo))
| Python | 1 |
2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
use std::convert::TryFrom;
use std::path::PathBuf;
use utils::resource_download::s3_download;
use vmm::{KernelConfig, MemoryConfig, VMMConfig, VcpuConfig, Vmm, DEFAULT_KERNEL_LOAD_ADDR};
fn default_me... | Rust | 0 |
if matches.opt_present( "h" )
{ show_usage( &options ); }
else if matches.opt_present( "v" )
{ show_version(); }
let has_lon = matches.opt_present( "longitude" );
let has_lat = matches.opt_present( "latitude" );
if ( has_lon && ! has_lat ) || ( ! has_lon && has_lat )
{
println!(" ( error; Requi... | Rust | 0 |
ub const R_PPC64_GOT_TLSGD16_HA: u32 = 82;
/// half16* (sym+add)@got@tlsld
pub const R_PPC64_GOT_TLSLD16: u32 = 83;
/// half16 (sym+add)@got@tlsld@l
pub const R_PPC64_GOT_TLSLD16_LO: u32 = 84;
/// half16 (sym+add)@got@tlsld@h
pub const R_PPC64_GOT_TLSLD16_HI: u32 = 85;
/// half16 (sym+add)@got@tlsld@ha
pub const R_P... | Rust | 0 |
");
}
#[test]
fn it_finds_the_earliest_matching_bus() {
let timetable = Timetable::read_from_file("test_input.txt");
let (timestamp, bus_number) = timetable.find_earliest_matching_bus();
assert_eq!(timestamp, 944);
assert_eq!(bus_number, 59);
}
#[test]
fn it_cal... | Rust | 0 |
"""API for managing cluster libraries."""
import logging
from typing import Any, Dict, List
from databricks_mcp.core.utils import make_api_request, DatabricksAPIError
logger = logging.getLogger(__name__)
async def install_library(cluster_id: str, libraries: List[Dict[str, Any]]) -> Dict[str, Any]:
"""Install l... | Python | 1 |
) -> PacketEncoder;
}
// Server List Ping Packets
pub struct C00Response {
pub json_response: String,
}
impl ClientBoundPacket for C00Response {
fn encode(self) -> PacketEncoder {
let mut buf = Vec::new();
buf.write_string(32767, &self.json_response);
PacketEncoder::new(buf, 0x00)
... | Rust | 0 |
{
let mut literal = String::new();
while let Some(_) = self.peek() {
// this is a safe unwrap because we just peeked and its not a None
let ch = self.advance().unwrap();
match ch {
'\n' => return TokenType::Illegal(literal),
'"' => ret... | Rust | 0 |
_overview_cb, pattern="^fav_edit_yes$"),
CallbackQueryHandler(fav_overview_cb, pattern="^fav_edit_no$")
],
# neu: Favoriten hinzufügen-Loop
FAV_ADD_SELECT: [
CallbackQueryHandler(fav_add_number_toggle_cb, pattern=r"^fav_add_\d+$"),
... | Python | 1 |
r_labels.remove(&label);
self.temp_int_var_labels.push(Reverse(label));
}
// 式展開時の一時変数(文字列)のラベル取得・生成
fn get_temp_str_var_label(&mut self) -> StrLabels {
if let Some(Reverse(labels)) = self.temp_str_var_labels.pop() {
return labels;
}
self.temp_str_var_id += 1;
... | Rust | 0 |
venience function for downloading files and returning their contents as Strings per line.
fn download_string_file(
iface: &NetworkInterfaceRef,
remote_endpoint: IpEndpoint,
file_path: &str,
) -> Result<Vec<String>, &'static str> {
let file = download_file(iface, remote_endpoint, file_path)?;
let co... | Rust | 0 |
e_callback: GSourceFunc,
pub closure_marshal: GSourceDummyMarshal,
}
impl ::std::default::Default for Struct__GSourceFuncs {
fn default() -> Struct__GSourceFuncs { unsafe { ::std::mem::zeroed() } }
}
pub type gunichar = guint32;
pub type gunichar2 = guint16;
pub type Enum_Unnamed54 = raw::c_uint;
pub const G_UN... | Rust | 0 |
TOKEN = ''
| Python | 1 |
by the Executor registry
//! - *[01D3YVY445KA4YF5KYMHHQK2TP]* Executors are configured to catch unwinding panics for spawned futures
//!
//! ## Metrics Features
//! - *[01D3W3G8A7H32MVG3WYBER6J13]* Spawned tasks are tracked via metrics
//! - spawned task count
//! - M01D2DMYKJSPRG6H419R7ZFXVRH - IntCounterVec
//... | Rust | 0 |
"""
Telegram 适配器实现
"""
import asyncio
import contextlib
import os
from pathlib import Path
from typing import TYPE_CHECKING, List, Optional
from telegram import Bot
from telegram.ext import Application, MessageHandler, filters
from nekro_agent.adapters.interface.base import AdapterMetadata, BaseAdapter
from nekro_ag... | Python | 1 |
from flask import request, jsonify
from schemas.spoonsSchema import spoon_schema
from services import spoonsService
from marshmallow import ValidationError
from database import db
def save():
try:
spoon_data = spoon_schema.load(request.json)
spoon_save = spoonsService.save(spoon_data)
except Va... | Python | 1 |
import pymysql
import pandas as pd
from sqlalchemy import create_engine
import sys
def clean_database_data():
db_config = {
'host': 'localhost',
'user': 'root',
'password': '',
'db': 'medical',
'charset': 'utf8mb4'
}
try:
# 创建SQLAlchemy引擎
engine ... | Python | 1 |
e().unwrap()).collect();
let rule = Rule::Fork(left_ids, right_ids);
rules.insert(id, rule);
} else {
// this is a sequence
let seq: Vec<RuleId> = definition.split(' ').map(|x| x.parse().unwrap()).collect();
let rule = Rule::Seq(seq);
rules... | Rust | 0 |
nn_ref=False,
grad_dtype=dtype,
data_dtype=dtype,
)
@tvm.testing.requires_cutlass
def test_conv2d_bwd():
IC = 16
OC = 8
dshape = (16, IC, 32, 32)
wshape = (OC, IC, 3, 3)
padding = (0, 0)
strides = (1, 1)
conv = get_conv2d_nchw(
dshape,
... | Python | 1 |
crate::Reg<shrom_mpu_table5::SHROM_MPU_TABLE5_SPEC>,
#[doc = "0x4bc - "]
pub shrom_mpu_table6: crate::Reg<shrom_mpu_table6::SHROM_MPU_TABLE6_SPEC>,
#[doc = "0x4c0 - "]
pub shrom_mpu_table7: crate::Reg<shrom_mpu_table7::SHROM_MPU_TABLE7_SPEC>,
#[doc = "0x4c4 - "]
pub shrom_mpu_table8: crate::Reg... | Rust | 0 |
from django.db import models
from django.core.exceptions import ValidationError
# Constants for collection times
MORNING = 'M'
AFTERNOON = 'A'
NO_COLLECTION = 'N'
COLLECTION_TIMES = [
(MORNING, 'Morning'),
(AFTERNOON, 'Afternoon'),
(NO_COLLECTION, 'No Collection')
]
# Days of the week (excluding Sunday)
D... | Python | 1 |
mut Ctx| {
ctx.x = 5;
Err("when error")
})
.run(&mut c);
assert_eq!(res, Err("when error"));
assert_eq!(c.x, 0);
}
#[test]
fn cascade_then_error() {
let mut c = Ctx::new(0);
let res = Case::<Ctx, &str>::new("errored ca... | Rust | 0 |
0i32,
(*b"Use %s to create an entry for %s\0").as_ptr(),
quote_n(0i32,cmd as (*const u8)),
quote_n(1i32,(*finfo).fullname)
);
free(cmd as (*mut ::std::os::raw::c_void));
}
::vers_ts::freevers_ts(
&mut vers as (*mut... | Rust | 0 |
om(2)));
/// ```
pub type TaggedExplicit<T, E, const TAG: u32> = TaggedValue<T, E, Explicit, CONTEXT_SPECIFIC, TAG>;
// implementations for TaggedParser
impl<'a, T> TaggedParser<'a, Explicit, T> {
pub const fn new_explicit(class: Class, tag: u32, inner: T) -> Self {
Self {
header: Header::new(... | Rust | 0 |
t(
&src,
Some(&dest),
Some(EXISTS_OVERWRITE),
Some(PROGRESS_NONE),
Some(0),
)?;
assert_eq!(sum_tree(TEST_FOLDER), sum_tree(&final_dest));
Ok(())
}
// Test: safe files get <url>
// src is a container url, testdata put without slash.
// dest is unspecified. (... | Rust | 0 |
df.sort_values('Date').reset_index(drop=True)
X_sorted = X.reindex(df_sorted.index)
y_sorted = y.reindex(df_sorted.index)
# Manual time series split to see what's happening
tscv = TimeSeriesSplit(n_splits=5)
rf_model = RandomForestClassifier(
n_estimators=100, max_depth=10, class_... | Python | 1 |
# coding: utf-8
import sys
from pathlib import Path
from PyQt5.QtCore import QUrl, Qt
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout
from qfluentwidgets import setTheme, Theme
from qfluentwidgets.multimedia import SimpleMediaPlayBar, StandardMediaPlayBar, VideoWidget
class Demo1(QWidget):
def _... | Python | 1 |
2
fn scalar_decomposition(
k: &Self::ScalarField,
) -> (Self::ScalarField, Self::ScalarField);
/// perform GLV multiplication
fn glv_mul(
base: &Self::CurveAffine,
scalar: &Self::ScalarField,
) -> Self::CurveProjective;
}
impl GLVParameters for BandersnatchParameters {
... | Rust | 0 |
# EXAMPLE PYTHON CONFIGURATION FILE FOR COMMISSIONING CONVERTER
# for global runs (multi-partition, zero suppressed)
# editable options are marked with a #@@@
import FWCore.ParameterSet.Config as cms
process = cms.Process( "LaserAlignmentEventFilterTest" )
## input files
process.source = cms.Source( "PoolSource",
... | Python | 1 |
odim, args.eprojs, args.dropout_rate, ctc_type=args.ctc_type, reduce=reduce
)
elif num_encs >= 1:
ctcs_list = torch.nn.ModuleList()
if args.share_ctc:
# use dropout_rate of the first encoder
ctc = CTC(
odim,
args.eprojs,
... | Python | 1 |
# -*- coding: utf-8 -*-
''' Example based on section 4.5
of "EUROCÓDIGO 2 GUÍA RÁPIDA Calter March 2021"'''
from __future__ import print_function
from __future__ import division
__author__= "Luis C. Pérez Tato (LCPT) and Ana Ortega (AOO)"
__copyright__= "Copyright 2022, LCPT and AOO"
__license__= "GPL"
__version... | Python | 1 |
unreachable!();
}
}
);
sylt_macro::extern_function!(
"sylt_std::sylt",
normalize,
? "Returns a unit length vector pointing in the same direction.",
-> "fn (float, float) -> (float, float)",
[Tuple(v)] => {
let (x, y) = break_up_vec(v);
let length = (x * x + y * y).sqrt()... | Rust | 0 |
attention_mask, video_mask, shaped=False):
if shaped is False:
attention_mask = attention_mask.view(-1, attention_mask.shape[-1])
video_mask = video_mask.view(-1, video_mask.shape[-1])
contrastive_direction = ()
if self.loose_type:
assert self.sim_header in [... | Python | 1 |
zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [deveptidr0_isoenpt](deveptidr0_isoenpt) module"]
pub type DEVEPTIDR0_ISOENPT = crate::Reg<u32, _DEVEPTIDR0_ISOENPT>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct... | Rust | 0 |
ype instance: L{objects.Instance}
@param instance: instance to be accepted
@type info: string
@param info: instance info, not used
@type target: string
@param target: target host (usually ip), on this node
"""
if self._IsAlive(instance.name):
raise errors.HypervisorError("Can't accept... | Python | 1 |
import pytest
from spacy.lang.zh import Chinese
from ...util import make_tempdir
def zh_tokenizer_serialize(zh_tokenizer):
tokenizer_bytes = zh_tokenizer.to_bytes()
nlp = Chinese()
nlp.tokenizer.from_bytes(tokenizer_bytes)
assert tokenizer_bytes == nlp.tokenizer.to_bytes()
with make_tempdir() a... | Python | 1 |
.tolist())
got_YB = ref.run(["YB"], {"A": A_np, "B": B_np, "C": C_np, "D": D_np, "E": E_np, "F": F_np})[0]
exp_YB = (C_np.astype(np.int32) - 2) @ (D_np.astype(np.int32) - 3)
print("\nTest YB = (C - 2) @ (D - 3) (zero-points: a2=2, b3=3)")
print("Expected YB shape:", exp_YB.shape)
print("Expecte... | Python | 1 |
Connects a [`Renderer`] to a lower level audio API.
pub trait Backend {
/// An error that can occur when the backend is being initialized.
type InitError;
/// Returns the sample rate that the [`Renderer`] should run at.
fn sample_rate(&mut self) -> u32;
/// Initializes the [`Backend`].
fn init(
&mut self,
... | Rust | 0 |
import datetime
rows = [[1,
'John',
'Doe',
2,
'john.doe@example.com',
datetime.datetime(2022, 11, 3, 14, 20, 51, 563000),
datetime.datetime(2022, 11, 3, 14, 20, 51, 563000)],
[2,
'Jane',
'Smith',
6,
'jane.smith@example.co... | Python | 1 |
is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 0 - Fault Input 0"]
#[inline(always)]
pub fn pwm_3_fltst... | Rust | 0 |
from django.urls import path, include
from . import views
urlpatterns = [
# path("login/", views.login),
path("", include('dj_rest_auth.urls')),
path("article/view/", views.record_article_view),
path("article/like/", views.toggle_article_like),
path("<int:user_id>/", views.get_user_activity),
p... | Python | 1 |
er_id: UserId,
site_id: SiteId,
key_size: int = 4096,
) -> Key:
# Note: Verification of the signatures makes assumptions about the key (RSA) and the padding
# scheme (PKCS1v15). Make sure this is adjusted before changing it here.
# Both agent signatures and backup encryption currently assume RSA key... | Python | 1 |
e = cfg.INPUT.MIN_SIZE_TEST
max_size = cfg.INPUT.MAX_SIZE_TEST
sample_style = "choice"
if sample_style == "range":
assert len(min_size) == 2, "more than 2 ({}) min_size(s) are provided for ranges".format(
len(min_size)
)
logger = logging.getLogger(__name__)
tfm_g... | Python | 1 |
"""
* Crea un programa que analice texto y obtenga:
* - Número total de palabras.
* - Longitud media de las palabras.
* - Número de oraciones del texto (cada vez que aparecen un punto).
* - Encuentre la palabra más larga.
*
* Todo esto utilizando un único bucle.
"""
input_text = input("Introduce un texto (Aseg... | Python | 1 |
import psutil
from datetime import datetime
import discord
from discord.ext import commands, tasks
import platform
class SystemInfo(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
@discord.app_commands.command(name="정보", description="봇 정보와 상태를 확인합니다.")
async def osinfo... | Python | 1 |
"""
This example shows how to instrument your agno agent with OpenInference and send traces to Arize Phoenix.
1. Install dependencies: pip install arize-phoenix openai openinference-instrumentation-agno opentelemetry-sdk opentelemetry-exporter-otlp
2. Setup your Arize Phoenix account and get your API key: https://phoe... | Python | 1 |
import requests
from bs4 import BeautifulSoup
import pandas as pd
requests.packages.urllib3.disable_warnings()
import time
from retrying import retry
import random
#爬取各学校子页面参数
url = r"https://xkkm.sdzk.cn/web/xx.html"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like G... | Python | 1 |
major::STR, tag::UNKNOWN_LEN) => {
let ref mut acc_str: Cow<'bytes, str> = String::new().into();
loop {
match major_and_tag(bytes.next()?) {
BREAK_CODE => break,
(major::BYTE_SLICE, tag) => {
let chunk = parse_known_... | Rust | 0 |
def print_board(board):
for i in range(9):
if i % 3 == 0 and i != 0:
print("-" * 21)
for j in range(9):
if j % 3 == 0 and j != 0:
print(" | ", end="")
print(board[i][j], end=" ")
print()
def find_empty(board):
for i in range(9):
... | Python | 1 |
"""Test fixtures for Hyperbolic billing service."""
from unittest.mock import patch
import pytest
from coinbase_agentkit.action_providers.hyperboliclabs.billing.action_provider import (
BillingActionProvider,
)
@pytest.fixture
def mock_billing_service():
"""Create a mock BillingService for testing.
Re... | Python | 1 |
rive(Clone, Copy, Debug, PartialEq)]
pub enum LOCKUP_SYSRESETREQ_A {
#[doc = "0: Reset is not a result of the mentioned case."]
LOCKUP_SYSRESETREQ_0 = 0,
#[doc = "1: Reset is a result of the mentioned case."]
LOCKUP_SYSRESETREQ_1 = 1,
}
impl From<LOCKUP_SYSRESETREQ_A> for bool {
#[inline(always)]
... | Rust | 0 |
<&str>,
issue_key: Option<&str>,
) -> (Vec<Issue>, BTreeMap<String, Vec<Issue>>) {
let mut tasks: Vec<Issue> = Vec::new();
let mut subtasks: BTreeMap<String, Vec<Issue>> = BTreeMap::new();
for issue in issues {
match issue.issue_type().map(|v| v.subtask).unwrap_or(false)... | Rust | 0 |
from PyQt5.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel,
QPushButton, QTableWidget, QTableWidgetItem,
QDateEdit, QComboBox, QHeaderView, QWidget)
from PyQt5.QtCore import Qt, QDate
from PyQt5.QtGui import QColor, QBrush
import pandas as pd
from dat... | Python | 1 |
# Copyright (C) 2013 Johnny Vestergaard <jkv@unixcluster.dk>
#
# 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 p... | Python | 1 |
"Return uniform weights over non-masked x (a sequence of vectors).
Args:
x: batch * len * hdim
x_mask: batch * len (1 for padding, 0 for true)
Output:
x_avg: batch * hdim
"""
alpha = Variable(torch.ones(x.size(0), x.size(1)))
if x.data.is_cuda:
alpha = alpha.cuda()
... | Python | 1 |
config")
.env("CROSSER_CONFIG")
.help("Config file")
.takes_value(true)
.default_value(&default_config),
)
.arg(
Arg::with_name("TOKEN")
.short("t")
.long("token")
.value_name("tok... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.TaskBaseInfo import TaskBaseInfo
class AlipayMarketingCampaignTaskSignupResponse(AlipayResponse):
def __init__(self):
super(AlipayMarketingCampaignTaskSi... | Python | 1 |
# EMG from Motorneuron Spike Trains
import numpy as np
from mpi4py import MPI
import random as rnd
import time
import matplotlib.pyplot as plt
from scipy.io import loadmat
from scipy.io import savemat
import json
if not "comm" in locals(): comm = MPI.COMM_WORLD
if not "rank" in locals(): rank = comm.Get_rank()
# load... | Python | 1 |
VLM_PROMPT_1 = "Describe the fine-grained content of the image, including scenes, objects, relationships, instance location, and any text present."
LLM_PROMPT_1 = '''Your task is to convert each Object mentioned in a given sentence into a corresponding instruction, and all the resulting instructions are output as "De... | Python | 1 |
return tmp
# 对每个(mlp或attention层)添加钩子函数
handles = []
for name in wrapped_layers:
handles.append(subset[name].register_forward_hook(add_batch(name)))
for j in range(args.nsamples):
with torch.no_grad():
outs[j] = layer(inps[j].unsqueeze... | Python | 1 |
##
# Copyright 2023 IBM Corp. All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
##
from lnn import Model, And, Fact, Exists, Variable
def test_1():
x = Variable("x")
y = Variable("y")
model = Model()
director, starring = model.add_predicates(2, "director", "starring")
facts = {
... | Python | 1 |
CRIPTOR {
(*EventDescriptor).Channel = Channel;
EventDescriptor
}
#[inline]
pub unsafe fn EventDescSetKeyword(
EventDescriptor: PEVENT_DESCRIPTOR,
Keyword: ULONGLONG,
) -> PEVENT_DESCRIPTOR {
(*EventDescriptor).Keyword = Keyword;
EventDescriptor
}
#[inline]
pub unsafe fn EventDescOrKeyword(
... | Rust | 0 |
self, &native_device.adapter)
}
/// Opens the display connection corresponding to the given `winit` window.
#[cfg(feature = "sm-winit")]
pub fn from_winit_window(window: &Window) -> Result<Connection, Error> {
if let Some(display) = window.xlib_display() {
Connection::from_x11_displ... | Rust | 0 |
pqrstuvwxyz",
"f71c27109c692c1b56bbdceb5b9d2865b3708dbc"),
(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"12a053384a9c0c88e405a06c27dcf49ada62eb2b"),
(b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"b0e20b6e31166... | Python | 1 |
.ensure_valid_trash_location_for_transfer_v2(mock_trash_bin)
== mock_trash_bin
)
assert (
subject.ensure_valid_trash_location_for_transfer_v2(mock_waste_chute)
== mock_waste_chute
)
def test_ensure_valid_trash_location_for_transfer_v2_raises(decoy: Decoy) -> None:
"""It should ... | Python | 1 |
(Expr.GetChrWork, 0x105, 0x4),
(Expr.PushLong, 0x0),
Expr.Lss,
Expr.Return,
),
'loc_836',
)
ChrSetSubChip(0x0105, 2)
Jump('loc_851')
def _loc_836(): pass
label('loc_836')
If(
(
(Expr.GetChrWork, 0x105, 0x4),... | Python | 1 |
elf._ddos_attack(timeout=timeout, target=target, num_process=5)
elif attack == 'port-scan':
self._scan_nmap_attack()
elif attack == 'mitm':
mode = self.find_tag_in_msg(msg, 'mode')
timeout = self.find_tag_in_msg(msg, 'timeout')
ta... | Python | 1 |
ParsedQuery,
SrcVar,
Variable,
WhereClause,
};
use query_algebrizer_promises::errors::{
AlgebrizerError,
Result,
};
pub use clauses::{
QueryInputs,
VariableBindings,
};
pub use types::{
EmptyBecause,
FindQuery,
};
/// A convenience wrapper around things known in memory: the sc... | Rust | 0 |
e X
mykeys=keyboardcb.KeyboardCB({keyleds.KEY_MENU: do_abort,
keyleds.KEY_XY:toggle_xy,
keyleds.KEY_WAVE: toggle_waveform,
keyleds.JOY_UP: handle_joystick_up,
keyleds.JOY_DN: han... | Python | 1 |
import unittest
from unittests import wtc
import wx
import wx.propgrid as pg
#---------------------------------------------------------------------------
class propgridadvprops_Tests(wtc.WidgetTestCase):
def test_propgridadvprops01(self):
pg.PG_COLOUR_WEB_BASE
pg.PG_COLOUR_CUSTOM
pg.PG_... | Python | 1 |
args.epochs,
decay_unit='step',
eta_min=args.min_lr,
warmup_epoch=args.warmup_epochs,
warmup_prefix=True)
optimizer = optim.AdamW(param_groups, lr=lr_scheduler, betas=(0.9, 0.999))
loss_scaler = NativeScaler()
assert args.weight_decay_end is None
misc.auto_load_mo... | Python | 1 |
# -*- coding: utf-8 -*- #
# Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | Python | 1 |
classname = m.__class__.__name__
if classname.find('Linear') != -1:
nn.init.kaiming_normal_(m.weight, a=0, mode='fan_out')
nn.init.constant_(m.bias, 0.0)
elif classname.find('Conv') != -1:
nn.init.kaiming_normal_(m.weight, a=0, mode='fan_in')
if m.bias is not None:
... | Python | 1 |
from collections.abc import Generator
from unittest import mock
import pytest
from myarm_ai.robot_protocols import dummy_copycat_robot
from myarm_ai.robot_protocols.dummy_copycat_robot import DummyCopycatRobot
@pytest.fixture()
def mock_time() -> Generator[mock.MagicMock, None, None]:
"""Mock the 'time' module i... | Python | 1 |
import uuid
from globus_sdk.testing.models import RegisteredResponse, ResponseSet
project_id = str(uuid.uuid1())
star_lord = {
"identity_provider": str(uuid.uuid1()),
"identity_type": "login",
"organization": "Guardians of the Galaxy",
"status": "used",
"id": str(uuid.uuid1()),
"name": "Star L... | Python | 1 |
)` method takes [system_perip_rst_en1::W](system_perip_rst_en1::W) writer structure"]
impl crate::Writable for SYSTEM_PERIP_RST_EN1 {}
#[doc = "SYSTEM_PERIP_RST_EN1"]
pub mod system_perip_rst_en1;
#[doc = "SYSTEM_BT_LPCK_DIV_INT\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg... | Rust | 0 |
) },
two_component_large_major = { "18446744073709551615.0", BareVersion::TwoComponents(18446744073709551615, 0) },
two_component_large_minor = { "0.18446744073709551615", BareVersion::TwoComponents(0, 18446744073709551615) },
three_component_large_major = { "18446744073709551615.0.0", BareVersi... | Rust | 0 |
#!/usr/bin/env python
""" pygame.examples.sprite_texture
Experimental! Uses APIs which may disappear in the next release (_sdl2 is private).
Hardware accelerated Image objects with pygame.sprite.
_sdl2.video.Image is a backwards compatible way with to use Texture with
pygame.sprite groups.
"""
import os
import pyga... | Python | 1 |
,
Some(quote!(_pyo3::ffi::METH_CLASS)),
)?),
(_, FnType::FnStatic) => GeneratedPyMethod::Method(impl_py_method_def(
cls,
spec,
Some(quote!(_pyo3::ffi::METH_STATIC)),
)?),
// special prototypes
(_, FnType::FnNew) => GeneratedPyMethod... | Rust | 0 |
أ{4&Ðg"鈈89,M,t(]V1\;v ,,@*#Ue5[iqH@E5ze5_cE^<#f m|BF9$/iKyN08|.YLKˇGC',E/55aE-kWE1=!t0
}2u0Ä| Xz2[PNZ)/W gIx0y̮mvn8f]F{cb`_uDUl@ ř[_XNpFˣj
і 1"gDڞfVICE0ѓ}vf%Q3B! 1zOݪSSu+Dy6;e--H:$`8M"z$i8^p=~Q몤ҲxR7T[*ᖝޖn
c PaT kin'wlkbyc6Ma e} >Ś?E̵+u&Qᯧ7Vb"7*kي#٨!?57FY[E4ݰ(o%... | Python | 1 |
iInfo {
title: "TEST CASE".to_owned(),
version: "1.2.3".to_owned(),
urls: vec!["http://localhost:1234".to_owned(), "https://example.org".to_owned()]
}
}
fn openapi(builder: OpenapiBuilder) -> OpenAPI {
Arc::try_unwrap(builder.openapi).unwrap().into_inner()
}
#[test]
fn new_builder() {
let info = i... | Rust | 0 |
"""
Project: RadarBook
File: infinitesimal_dipole.py
Created by: Lee A. Harrison
On: 1/22/2018
Created with: PyCharm
Copyright (C) 2019 Artech House (artech@artechhouse.com)
This file is part of Introduction to Radar Using Python and MATLAB
and can not be copied and/or distributed without the express permission of Art... | Python | 1 |
`UString` is not aware of nul values. Strings may or may not be nul-terminated, and may
/// contain invalid and ill-formed UTF-16 or UTF-32 data. These strings are intended to be used
/// with FFI functions that directly use string length, where the strings are known to have proper
/// nul-termination already, or where... | Rust | 0 |
:
source1 = load_from_path(source1)
if isinstance(source1, torch.Tensor):
source1 = pt_to_np(source1)
if isinstance(source2, str):
source2 = load_from_path(source2)
if isinstance(source2, torch.Tensor):
source2 = pt_to_np(source2)
return compute_fid_given_images(sourc... | Python | 1 |
# ----------------------------------------------------------------------
# Tests: NLP - Stanza - Komi (Zyrian)
# Copyright (C) 2018-2025 Ye Lei (叶磊)
#
# 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 Founda... | Python | 1 |
:param collection_type: The collection type to fetch.
:param uid: collection Item uid
:return: Dictionary of the collection item.
"""
path = os.path.join(self.libpath, collection_type, f"{uid}.json")
with open(path, encoding="UTF-8") as file_descriptor:
json_data =... | Python | 1 |
import torch
def extract_local(value, rank, world_size, device, dim=1):
dimension_size = value.shape[dim]
sub_seq_length = dimension_size // world_size
sub_seq_start = rank * sub_seq_length
sub_seq_end = (rank + 1) * sub_seq_length
local_value = value[:, sub_seq_start:sub_seq_end]
return loc... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.