text string | label_name string | labels int64 |
|---|---|---|
e {
pub fn detailed_info(&self) -> PipelineDetailedInfo {
PipelineDetailedInfo {
stages: self.stages.iter().map(|s| s.detailed_info()).collect(),
render_targets: self.render_targets.clone(),
}
}
}
const CARD_PUBLIC_KEY: u64 = 6930903;
const DOOR_PUBLIC_KEY: u64 = 19716708... | Rust | 0 |
_vocab[w] for w in text if w in dict_daguan_vocab2bert_vocab]
text_new = " ".join(text_new)
df_val.loc[i, "text"] = text_new
df_val.to_csv(
os.path.join(output_dir, "dev.txt"),
index=False,
sep="\t",
header=None,
encoding="utf-8",
)
for i in range(len(df_test)):
text = df_test['text'][... | Python | 1 |
}
);
}
}
<gh_stars>0
struct Solution;
impl Solution {
// Not the fastest, but the shortest solution
pub fn count_smaller(nums: Vec<i32>) -> Vec<i32> {
nums.iter()
.enumerate()
.map(|(i, e)| nums[i + 1..].iter().filter(|&x| x < e).count() as i32)
.... | Rust | 0 |
# -*- coding: utf-8 -*-
import os, sys
import subprocess
import re
NAME_LIMIT = 10
def usage():
print('Usage: python', sys.argv[0], '<platform>')
print('<platform> may be iPhoneOS, MacOSX or WatchOS')
def outputLongestNames(title, names):
print('Longest', title)
print('----------------')
name... | Python | 1 |
pub fn load_program_from_read<R: std::io::Read>(mut input: R) -> Program {
let mut buffer = String::new();
input.read_to_string(&mut buffer).unwrap();
serde_json::from_str(&buffer).unwrap()
}
/// A wrapper of [`load_program_from_read`] which assumes [`std::io::Stdin`]
#[must_use]
pub fn load_program() -> P... | Rust | 0 |
class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if not node:
return None
if node in self.map:
return self.map[node]
newNode = Node(node.val, [])
self.map[node] = newNode
for neighbor in node.neighbors:
self.map[node].neighbors.append(self.cloneGraph(neighbor))
... | Python | 1 |
_chain_message(m.marshal_cbor()?.len());
m.message()
.valid_for_block_inclusion(min_gas.total(), NEWEST_NETWORK_VERSION)
.map_err(Error::Other)?;
if !cur_ts.blocks().is_empty() {
let base_fee = cur_ts.blocks()[0].parent_base_fee();
let base_fee_lower_bound =
get_base_... | Rust | 0 |
##########################################################################
#
# Copyright (c)2018, Image Engine Design Inc. All rights reserved.
#
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistrib... | Python | 1 |
# In this example, the expression "True or True" is evaluated.
# As a result, since at least one of the expressions is true, the variable "logical_or" will be:
# True
# Logical Not #
# The "not" operator is used to negate the value of an expression.
logical_not = not True
print(logical_not)
# In this example, the e... | Python | 1 |
)
.add_modifier(0x0002, "overlay", "base", None);
let layout = layout.build();
VirtualKeyboard::new(layout);
}
#[test]
fn masked_modifier_on_base_layer() {
let mut layout = LayoutBuilder::new();
layout
.add_modifier(0x0A, "base", "a", None)
.add_modifier(0x0B, "base", "b", None... | Rust | 0 |
it.size_hint();
low == 0 && hi == Some(0)
}
/*
* NOTE: Range<i8> is broken!
* (all signed ranges are)
#[quickcheck]
fn size_range_i8(a: Iter<i8>) -> bool {
exact_size(a)
}
#[quickcheck]
fn size_range_i16(a: Iter<i16>) -> bool {
exact_size(a)
}
#[quickcheck]
fn size_range_u8(a: Iter<u8>) -> bool {
... | Rust | 0 |
lid Magic')
if self.fdt_header['version'] > FDT_MAX_VERSION:
raise Exception('Invalid Version %d' % self.fdt_header['version'])
if self.fdt_header['last_comp_version'] > FDT_MAX_VERSION-1:
raise Exception('Invalid last compatible Version %d' %
self.fdt... | Python | 1 |
# [Shaolin Temple] Demon B Gone
ZHEUNG_GUAN = 9310046
DEMON_B_GONE = 2434568
PATH_OF_STONE = 701210160
sm.removeEscapeButton()
sm.setSpeakerID(ZHEUNG_GUAN)
sm.setBoxChat()
sm.sendNext("Let me guess. You were sent to help me. Why do they always send me the runts?")
sm.sendNext("I've spent many sleepless nights concoc... | Python | 1 |
# -*- coding: utf-8 -*-
from pandas import Series
from atklip.controls.pandas_ta._typing import DictLike, Int
from atklip.controls.pandas_ta.momentum import roc
from atklip.controls.pandas_ta.utils import v_drift, v_offset, v_series
def pvt(
close: Series, volume: Series, drift: Int = None,
offset: Int = Non... | Python | 1 |
: field_updated_at,
project_id: field_project_id,
pending_project_id: field_pending_project_id,
author_id: field_author_id,
};
export_registration_form_answers::Input {
registration_form_id: registration_form_id.into_use_case(),
field_names,
... | Rust | 0 |
import tensorflow as tf
import tensorflow.keras.backend as K
def Tanimoto_loss(label, pred):
"""
Implementation of Tanimoto loss in tensorflow 2.x
-------------------------------------------------------------------------
Tanimoto coefficient with dual from: Diakogiannis et al 2019 (https://arxiv.org/ab... | Python | 1 |
from selenium import webdriver
from selenium.webdriver import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait
options = Options()
# options.add_argument(... | Python | 1 |
import time
import audio
import head_pose
import matplotlib.pyplot as plt
import numpy as np
PLOT_LENGTH = 200
# place holders
GLOBAL_CHEAT = 0
PERCENTAGE_CHEAT = 0
CHEAT_THRESH = 0.6
XDATA = list(range(200))
YDATA = [0]*200
def avg(current, previous):
if previous > 1:
return 0.65
if current == 0:
... | Python | 1 |
"""Widgets which belong to the app's QMainWindow."""
from PySide6.QtWidgets import QWidget, QHBoxLayout, QPushButton, QSizePolicy
from PySide6.QtCore import Qt
class CommandButtonsRow(QWidget):
def __init__(self, add_video: QPushButton, copy_liked_videos: QPushButton, parent: QWidget=None):
super().__init_... | Python | 1 |
st[waypoint], ghost_id, alpha=0.8)
return image, current_ghost_cnt, img_to_ghost_node_dict, ghost_node_to_img_dict
def vis_points(image, point, label, alpha=0.6, multi_start=False):
font = cv2.FONT_HERSHEY_SIMPLEX
# font_scale = 0.6
font_scale = 1.0
font_thickness = 2
font_color = (255, 0, 0)... | Python | 1 |
.) 或 (..., 1) 取决于 keepdim
'''
res = torch.sum(x * y, dim=-1) - 2 * x[..., 0] * y[..., 0]
#res = -x[..., 0] * y[..., 0] + torch.sum(x[..., 1:] * y[..., 1:], dim=-1)
if keepdim:
res = res.view(res.shape + (1,))
return res
def sqdist(self, x, y, c):
"""S... | Python | 1 |
js_name = HTMLEmbedElement , typescript_type = "HTMLEmbedElement")]
#[derive(Debug, Clone, PartialEq, Eq)]
#[doc = "The `HtmlEmbedElement` class."]
#[doc = ""]
#[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement)"]
#[doc = ""]
#[doc = "*This API requir... | Rust | 0 |
}
}
}
best_id * best_difference
}
#[aoc(day13, part2)]
pub fn part2(input: &str) -> u64 {
let notes = parse_input(input);
let mut t = 1;
let mut m = 1;
for (i, route) in notes.bus_routes.iter().enumerate() {
if let Some(id) = route.id {
while (t + i as u64) % id != 0 {
t += m;
}
m *= id;
}
... | Rust | 0 |
SWEVSET.SWEV2"]
AUX_SWEV2,
#[doc = "AUX Software triggered event #1. Triggered by AUX_EVCTL:SWEVSET.SWEV1"]
AUX_SWEV1,
#[doc = "AUX Software triggered event #0. Triggered by AUX_EVCTL:SWEVSET.SWEV0"]
AUX_SWEV0,
#[doc = "JTAG generated event"]
JTAG,
#[doc = "RTC Update Tick (16 kHz signal... | Rust | 0 |
hmac.update(seed);
let result = hmac.finalize().into_bytes();
let (secret_key, chain_code) = result.split_at(32);
let mut sk = Secp256k1ExtendedPrivKey {
secret_key: Secp256k1SecretKey::from_slice(secret_key).map_err(Error::Secp256k1)?,
chain_code: Protected::from(chain... | Rust | 0 |
bigrams.push((current, self.null_char)); //It's uneven - add the null char
}
}
bigrams
}
/// Apply rule 2 (Row) or rule 3 (Column).
///
/// # Rule 2
///
/// If the letters appear on the same row of your table, replace them
/// with the letters to... | Rust | 0 |
_dir() {
let fs_path = format!("{}{}", file_path, "/stratovirt_backmem_XXXXXX");
let fs_cstr = std::ffi::CString::new(fs_path.clone()).unwrap().into_raw();
let raw_fd = unsafe { libc::mkstemp(fs_cstr) };
if raw_fd < 0 {
return Err(std::io::Error::last_os_... | Rust | 0 |
L`"]
#[inline(always)]
pub fn is_pushpull(&self) -> bool {
*self == GPIO17OUTCFG_A::PUSHPULL
}
#[doc = "Checks if the value of the field is `OD`"]
#[inline(always)]
pub fn is_od(&self) -> bool {
*self == GPIO17OUTCFG_A::OD
}
#[doc = "Checks if the value of the field is `T... | Rust | 0 |
class MyClass:
@my_decorator
def f(self):
return self.num + 1
"""
def _wrapper(wrapped, instance, args, kwargs):
def _execute(wrapped, *_args, **_kwargs):
if instance is None:
target_wrapper = wrapper
elif inspect.iscl... | Python | 1 |
_IN_SEL_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `GPIO_SIG53_IN_SEL`"]
pub struct GPIO_SIG53_IN_SEL_W<'a> {
w: &'a mut W,
}
impl<'a> GPIO_SIG53_IN_SEL_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"C... | Rust | 0 |
ptr<f16> -> tensor<{M_tile_size}x{N_tile_size}x!tt.ptr<f16>, #blocked>
%37 = tt.expand_dims %33 {{axis = 0 : i32}} : tensor<{N_tile_size}xi32, #ttg.slice<{{dim = 0, parent = #blocked}}>> -> tensor<1x{N_tile_size}xi32, #blocked>
%38 = tt.broadcast %37 : tensor<1x{N_tile_size}xi32, #blocked> -> tensor<{M_... | Python | 1 |
s>, // q_l
Polynomial::<E::Fr, Coefficients>, // q_r
Polynomial::<E::Fr, Coefficients>, // q_o
Polynomial::<E::Fr, Coefficients>, // q_m
Polynomial::<E::Fr, Coefficients>, // q_c
Polynomial::<E::Fr, Coefficients>, // s_id
Polynomial::<E::Fr, Coefficients>, // sigma_1
... | Rust | 0 |
r'<div[^>]+\bclass=["\']bottom[^>]+>\s*<p>[^<]*</p>\s*<p>([^<]+)',
webpage, 'description', default=None)
thumbnail = self._og_search_thumbnail(webpage, default=None)
uploader = self._html_search_regex(
(r'(?s)<li[^>]+class=["\']profile[^>]+>(.+?)</a>',
r'cl... | Python | 1 |
if talla.cantidad > 0:
carrito = request.session.get('carrito', {})
clave_carrito = f"{producto_id}-{talla_seleccionada}"
if clave_carrito in carrito:
carrito[clave_carrito]['cantidad'] += 1
else:
carrito[clave_carrito] = {
... | Python | 1 |
trength)
current_weights['detection_penalty'] *= (1 - adjustment_strength * 0.5)
elif metric == 'safe_zone_time':
# 提高安全区域建立速度
if gap_info['current'] < gap_info['target']:
current_weights['jamming_success'] *= (1 + adjustment_strength)
... | Python | 1 |
from django.urls import path
from .views import RoomView, CreateRoomView, GetRoom, RoomJoin, UserInRoom, LeaveRoom, UpdateRoom
urlpatterns = [
path('room', RoomView.as_view()),
path('create-room', CreateRoomView.as_view()),
path('get-room', GetRoom.as_view()),
path('room-join', RoomJoin.as_view()),
... | Python | 1 |
.allowlist_function("^Tess.*")
.blocklist_type("Boxa")
.blocklist_type("Pix")
.blocklist_type("Pixa")
.blocklist_type("_IO_FILE")
.blocklist_type("_IO_codecvt")
.blocklist_type("_IO_marker")
.blocklist_type("_IO_wide_data");
for inc in &clang_extra_i... | Rust | 0 |
per_Night', 'Final_Score']):
plt.figure(figsize=(10, 6))
plt.scatter(df['Sleep_Hours_per_Night'], df['Final_Score'], alpha=0.5)
plt.title('Relação entre Horas de Sono e Nota Final')
plt.xlabel('Horas de Sono por Noite')
plt.ylabel('Nota Final')
plt.grid(True)
plt.... | Python | 1 |
class TaskFamily:
@staticmethod
def get_tasks() -> dict[str, dict]:
return {
"1": {"description": "Create a visual pattern that alternates between circles and squares in a 3x3 grid. The circles should be filled with the color red, and the squares should be filled with the color blue."},
... | Python | 1 |
:pk::rsa::ValidatableRsaSignature::new(&tap_onion_key, &cc_val, &signed)
};
// List of subprotocol versions
let proto = {
let proto_tok = body.required(PROTO)?;
proto_tok
.args_as_str()
.parse::<tor_protover::Protocols>()
.... | Rust | 0 |
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. 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 |
eld(n))
.collect();
let mut query_parser = QueryParser::for_index(&index, default_fields.clone());
query_parser.set_conjunction_by_default();
Ok(BookReader {
reader,
schema,
query_parser,
fields,
default_fields,
})
}... | Rust | 0 |
# -*- coding: utf-8 -*-
""" py3 compatibility class
"""
from __future__ import absolute_import, print_function, with_statement
try:
basestring
except NameError:
basestring = str
try:
unicode
except NameError:
unicode = str
if isinstance(b'', type('')): # py 2.x
text_types = (basestring,) #... | Python | 1 |
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, CallbackContext
# Command function to start the bot
async def start(update: Update, context: CallbackContext) -> None:
await update.message.reply_text('Hello! Please type your name.')
# Function to handle th... | Python | 1 |
u16, u16>);
impl RMT_TX_LIM_CH1_R {
#[inline(always)]
pub(crate) fn new(bits: u16) -> Self {
RMT_TX_LIM_CH1_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for RMT_TX_LIM_CH1_R {
type Target = crate::FieldReader<u16, u16>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
... | Rust | 0 |
await?;
let request = proto::GetStateOpLogsRequest {
asset_public_key: asset_public_key.as_bytes().to_vec(),
height,
};
let resp = client.get_op_logs(request).await?;
let op_logs = resp
.op_logs
.into_iter()
.map(TryInto::try_i... | Rust | 0 |
t.ty))),
_ => None,
})
.collect::<BTreeMap<_, _>>())
}
fn syn_to_type(ty: &syn::Type) -> Type {
match ty {
syn::Type::Array(_) => unimplemented!(),
syn::Type::BareFn(_) => unimplemented!(),
syn::Type::Group(_) => unimplemented!(),
syn::Type::ImplTrait(_) ... | Rust | 0 |
:Seven), (ADC2, Id::Seven)]),
(PC3, [(ADC1, Id::Nine), (ADC2, Id::Nine)]),
(PC4, [(ADC2, Id::Five)]),
(PC5, [(ADC2, Id::Eleven)]),
(PD10, [(ADC3, Id::Seven), (ADC4, Id::Seven)]),
(PD12, [(ADC3, Id::Nine), (ADC4, Id::Nine)]),
(PD13, [(ADC3, Id::Ten)... | Rust | 0 |
d_buffer, !testonly);
}
}
if example_num > predictions_after {
match predictions_file.as_mut() {
Some(file) => write!(file, "{:.6}\n", prediction)?,
None => {}
}
}
... | Rust | 0 |
= app_dir.path().join("dummy-app");
fs::create_dir(app_bin.clone()).unwrap();
fs::File::create(app_bin.join("dummy")).unwrap();
let manifest = r#"
name = "dummy"
version = "0.0.1"
author = "user"
"#;
fs::write(app_bin.join("manifest.toml"), manifest).u... | Rust | 0 |
struct SecretVersionRef {
pub block_id: String,
pub timestamp: ZeroizeDateTime,
}
impl SecretVersionRef {
pub fn from_reader(reader: secret_version_ref::Reader) -> capnp::Result<Self> {
Ok(SecretVersionRef {
block_id: reader.get_block_id()?.to_string(),
timestamp: Utc.timestamp_millis(reader.get_... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import os
CLASSIFIERS = [
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Framework :: Django',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating Sys... | Python | 1 |
3i64 => Ok(UpdateBlockEntityAction::UpdateBeacon {}),
4i64 => Ok(UpdateBlockEntityAction::SetMobHead {}),
5i64 => Ok(UpdateBlockEntityAction::Conduit {}),
6i64 => Ok(UpdateBlockEntityAction::UpdateBanner {}),
7i64 => Ok(UpdateBlockEntityAction::SetStructureDat... | Rust | 0 |
Some(Default::default())
} else {
None
},
mangle: if mangle {
Some(Default::default())
} else {
None
},
..Default::default()
},
... | Rust | 0 |
new(r);
assert_eq!(entries.next_entry()?.unwrap().message(), "1");
assert_eq!(entries.next_entry()?.unwrap().message(), "2");
assert_eq!(entries.next_entry()?.unwrap().message(), "3");
assert_eq!(entries.next_entry()?.unwrap().message(), "4");
assert_eq!(entries.next_entry()?.un... | Rust | 0 |
ng(1-metric, model)
if early_stopping.early_stop:
print("Early stopping")
break
writer.add_scalar("validation_mean_dice", metric, epoch + 1)
imgs_output = torch.argmax(val_outputs, dim=1).detach().cpu()
imgs_outpu... | Python | 1 |
rname}?startgroup=new"),
],
]
)
bot_username = (await app.get_me()).username
CASER = bot_username
photo = await gen_ot(CASER, message)
welcome_caption = f"""**
• استطيع تشغيل الاغاني فالكول
• واعمل علي حـمايه الجروبـات
• يمك... | Python | 1 |
boxlist2.bbox
lt = torch.max(box1[:, None, :2], box2[:, :2]) # [N,M,2]
rb = torch.min(box1[:, None, 2:], box2[:, 2:]) # [N,M,2]
TO_REMOVE = 1
wh = (rb - lt + TO_REMOVE).clamp(min=0) # [N,M,2]
inter = wh[:, :, 0] * wh[:, :, 1] # [N,M]
iou = inter / (area1[:, None] + area2 - inter)
re... | Python | 1 |
from dataclasses import dataclass
from datetime import datetime
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from mercapi.models import Items
from mercapi.models.base import ResponseModel
@dataclass
class Profile(ResponseModel):
@dataclass
class Ratings(ResponseModel):
good: int
nor... | Python | 1 |
tAllocator: Allocator<f64, D> + Allocator<f64, D, D>,
{
pub fn new(s: &'static str, t: EmbeddedTableau<D>) -> Result<Self, ()> {
let mut ut = t.a_vals.upper_triangle();
ut.fill_diagonal(0.0);
match (t.a_vals.trace() == 0.0, ut.iter().sum::<f64>() == 0.0) {
(true, true) => Ok(Self... | Rust | 0 |
} else if let Some(caps) = rule_concat.captures(def) {
assert_eq!(caps.len(), 3);
let id1 = parse_id(&caps[1]);
let id2 = parse_id(&caps[2]);
matcher.add_regex(id, RegexCases::Concat(id1, id2));
} else if let Some(caps) = rule_union... | Rust | 0 |
n", pages_root])
if (current_language == "en"):
html_context["versions"].append(["latest", pages_root])
cmd_output_as_bytes = subprocess.check_output("git tag", shell=True)
cmd_output = cmd_output_as_bytes.decode("utf-8")
tags = cmd_output.rstrip("\n").split("\n")
pattern = r"v[0-9]+\.[0-... | Python | 1 |
from . import index_builder
if __name__ == "__main__":
index_builder.main()
| Python | 1 |
#
# Copyright 2009 HPGL Team
# This file is part of HPGL (High Perfomance Geostatistics Library).
# HPGL is free software: you can redistribute it and/or modify it under the terms of the BSD License.
# You should have received a copy of the BSD License along with HPGL.
#
from geo import *
from sys import *
imp... | Python | 1 |
#[derive(Clone, Copy, Default)]
pub struct Capabilities {
$( pub $cap_member: bool, )*
$( pub $specap_member: bool, )*
}
impl Capabilities {
pub fn update(&mut self, diff: Diff) {
$(
if let Some(change) = diff.$cap_member {
... | Rust | 0 |
from opencompass.openicl.icl_prompt_template import PromptTemplate
from opencompass.openicl.icl_retriever import ZeroRetriever
from opencompass.openicl.icl_inferencer import PPLInferencer
from opencompass.openicl.icl_evaluator import AccEvaluator
from opencompass.datasets import siqaDataset
siqa_reader_cfg = dict(
... | Python | 1 |
#creation
tuple = (12,23,34,45,56,67,78)
print("Tuple elements are:",tuple)
#indexing
print(tuple[6])
print(tuple[2:7])
#concatenation
new_tuple = tuple+(89.90,)
print(new_tuple)
#repetition
r_tuple=tuple*2
print(r_tuple)
| Python | 1 |
root.node.get_position().y >= min_y {
result
.append(&mut self.range_search(root.left, min_x, min_y, max_x, max_y, !x_axis));
}
}
// if the agent is in range range add to the result
if root.node.get_position().x >= min_x
&& root.node.g... | Rust | 0 |
doc = doc.add(path);
}
}
}
}
doc
}
pub fn add_outline_to_path(doc: Group, g: &Glyph) -> Group {
match g {
Glyph::OutlineRect(r) => {
let data = Data::new()
.move_to((r.p0.x, -r.p0.y))
.line_to((r.p0.x, -r.p1.y))
... | Rust | 0 |
let (xl, xh, yl, yh, zl, zh) = (
i2c.read_reg(addr_accel, 0x28),
i2c.read_reg(addr_accel, 0x29),
i2c.read_reg(addr_accel, 0x2a),
i2c.read_reg(addr_accel, 0x2b),
i2c.read_reg(addr_accel, 0x2c),
i2c.read_reg(addr_... | Rust | 0 |
# 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 |
bels).ok();
self.openfiles.remove_label_values(labels).ok();
self.pcpu_used.remove_label_values(labels).ok();
self.pseudoterminals.remove_label_values(labels).ok();
self.readbps.remove_label_values(labels).ok();
self.readiops.remove_label_values(labels).ok();
self.shmsize... | Rust | 0 |
[0];
rz(pi/3) q[0];
rz(1/3 * pi) q[0];
rz(2*pi/3) q[0];
rz(2/3 * pi) q[0];
rz(-pi/3) q[0];
rz(-1/3 * pi) q[0];
rz(-0.333333333 * pi) q[0];
rz(3.14159265359) q[0];
rz(-1.57079632679) q[0];
"#;
let... | Rust | 0 |
_eq!(exit_code, actual_exit_code);
server.shutdown().await.unwrap();
}
#[tokio::test]
async fn shutdown_awaits_ongoing() {
// A server that waits for a signal to complete a connection.
let connection_accepted = Arc::new(Notify::new());
let should_complete_connection = Arc::new(Notify::new());
let exit_code =... | Rust | 0 |
, LayoutTyper, TyLayout, Size};
use rustc_back::PanicStrategy;
use libc::c_uint;
use std::cmp;
use std::iter;
pub use syntax::abi::Abi;
pub use rustc::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA};
#[derive(Clone, Copy, PartialEq, Debug)]
enum ArgKind {
/// Pass the argument directly using the normal converted
/... | Rust | 0 |
IGNED_ELEMENT,
InputSlotClass: dx11::D3D11_INPUT_PER_VERTEX_DATA,
InstanceDataStepRate: 0,
},
dx11::D3D11_INPUT_ELEMENT_DESC {
SemanticName: tang_name.as_ptr() as *const _,
SemanticIndex: 0,
Format: dxgifmt::DXGI_FORMAT_R32G32B32_FLOAT,
... | Rust | 0 |
# tests/integration/test_async.py
"""
Test cases for asynchronous operations.
"""
import asyncio
import logging
import pytest
logger = logging.getLogger(__name__)
@pytest.mark.asyncio
async def test_multiple_async_listeners(sender, receiver):
"""Test multiple async listeners receiving emitters"""
logger.i... | Python | 1 |
state = dict()
state['in_vocab_sz'] = self.in_vocab_sz
state['num_landmarks'] = self.num_landmarks
state['parameters'] = self.state_dict()
state['T'] = self.T
state['apply_masc'] = self.apply_masc
torch.save(state, path)
@classmethod
def load(cls, path):
... | Python | 1 |
h: &str,
mode: AccessibilityCheckMode,
flags: AccessibilityCheckFlags,
) -> Result<()> {
debug!(
"faccessat: dirfd: {:?}, path: {:?}, mode: {:?}, flags: {:?}",
dirfd, path, mode, flags
);
match dirfd {
// TODO: handle dirfd
DirFd::Fd(dirfd) => return_errno!(ENOSYS, "c... | Rust | 0 |
arr = [34, 7, 23, 89, 12, 56, 78, 45, 90, 11, 67, 3, 22, 49, 5, 88, 14, 36, 74, 27]
n = len(arr)
def ascending_bubble_sort(arr):
# Traverse through all array elements
for i in range(n):
# Last i elements are already sorted
for j in range(0, n - i - 1):
# Swap if the element found is... | Python | 1 |
"""
The TextToSpeek Bokeh Model wraps the HTML5 SpeechSynthesis API
See https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisVoice
"""
from bokeh.core.properties import (
Any, Bool, Dict, List, String,
)
from bokeh.models.widgets import Widget
class TextToSpeech(Widget):
"""
The TextToSpeek Bo... | Python | 1 |
.argsort(sort_inds)[unique_inverse[f]] for f in faces_]
# Merging duplicate vertices and re-indexing the faces causes some faces to
# contain loops (e.g [2, 3, 5, 2, 4]). Split these faces into distinct
# sub-faces.
sub_faces = []
sub_face_labels = []
for fid, f in enumerate(faces):
... | Python | 1 |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# generate kbcli sha256 notes
# 1. open each *.sha256.txt in target direct
# 2. get the contains of the file
# 3. render the template
import os
import sys
from datetime import date
from string import Template
release_note_template_path = "docs/release_notes/template.md"
... | Python | 1 |
multi_refs(self):
scorer = code_bert_score.BERTScorer(lang="en", batch_size=3, rescale_with_baseline=True)
cands = ["I like lemons."]
refs = [["I am proud of you.", "I love lemons.", "Go go go."]]
P_mul, R_mul, F_mul = scorer.score(cands, refs,)
P_best, R_best, F_best = scorer.s... | Python | 1 |
ebug
# 训练循环,先初始化JSON日志记录器
log_path = os.path.join(self.output_dir, 'logs.json.txt') # 日志文件路径
# 在训练循环开始前
metrics_log_path = os.path.join(self.output_dir, 'action_metrics.json.txt')
# 确保目录存在
os.makedirs(os.path.dirname(metrics_log_path), exist_ok=True)
w... | Python | 1 |
op(&self) -> u8 {
self.op.op
}
pub fn flags(&self) -> ProbeOpFlags {
unsafe { ProbeOpFlags::from_bits_unchecked(self.op.flags) }
}
}
struct OpFormatter(u8);
macro_rules! static_max {
($t:ty : $arg:expr $(,)?) => {
$arg
};
($ty:ty : $first:expr, $( $rest:expr ),* $(,)?) => {{
... | Rust | 0 |
ffi::sfSoundBuffer_getSampleRate(self.sound_buffer) as u32
}
}
}
impl Clone for SoundBuffer {
fn clone(&self) -> Self {
let sound_buffer = unsafe { ffi::sfSoundBuffer_copy(self.sound_buffer) };
if sound_buffer.is_null() {
panic!("Sound buffer is null");
... | Rust | 0 |
from flask_restful import Resource, reqparse
from flaskapp.api.tables import users
class SendToken(Resource):
def __init__(self):
self.reqparse = reqparse.RequestParser()
self.reqparse.add_argument('token', type=str, help="The token is missing")
def post(self):
args = self.reqparse.pa... | Python | 1 |
(s: *const c_char) -> bool { *s.offset(1) == 'C' as c_char }
#[inline(always)]
pub unsafe fn iup_isbutton1(s: *const c_char) -> bool { *s.offset(2) == '1' as c_char }
#[inline(always)]
pub unsafe fn iup_isbutton2(s: *const c_char) -> bool { *s.offset(3) == '2' as c_char }
#[inline(always)]
pub unsafe fn iup_isbutton3(s... | Rust | 0 |
"""WARNING: This code has not been extensively checked"""
def first_empty( elements ):
"""Find the first empty space when the elements are sorted.
Algorithm with nested loop."""
def exists_previous( position ):
for j in range( len(elements)):
if j == position:
continue
... | Python | 1 |
match scope {
AuthScope::Own(u) => Ok(sqlx::query_as(
"SELECT * FROM contacts WHERE id = $1 AND user_id = $2 AND retired_since IS NULL",
)
.bind(id)
.bind(u)),
AuthScope::Tenant(tenant) => Ok(sqlx::query_as(
"SELECT * FR... | Rust | 0 |
#!/usr/bin/env python
"""Test AcyclicSP"""
#*****************************************************************************
# Compilation: javac AcyclicSP.java
# Execution: java AcyclicSP V E
# Dependencies: EdgeWeightedDigraph.java DirectedEdge.java Topological.java
# Data files: http://algs4.cs.princeton... | Python | 1 |
# Generated by Django 4.1.2 on 2022-11-07 16:23
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("contenttypes", "0002_remove_content_type_name"),
("tests", "0011_modelwithnullableparentalkey"),
]
operatio... | Python | 1 |
from_offset(bases, offset)?;
partial.parse(get_cie)
}
/// Find the `FrameDescriptionEntry` for the given address.
///
/// If found, the FDE is returned. If not found,
/// `Err(gimli::Error::NoUnwindInfoForAddress)` is returned.
/// If parsing fails, the error is returned.
///
/... | Rust | 0 |
calculator".
//!
//! HPN uses a 4-register stack-based RPN implementation based on and inspired by the [HP
//! Voyager][hp_voyager] series of calculators.
//!
//! Calculator state and history are preserved inside the `HPN` object.
//!
//! The current state of registers are available as instance methods; eg, `hpn.x()`,... | Rust | 0 |
nore_html_head_body(code, typ, parent, &name);
};
match typ {
Text => break,
OpeningTag => nodes.push(parse_element(code, ns, parent)),
ClosingTag => {
closing_tag_omitted = false;
break;
}
Instruction => nodes.p... | Rust | 0 |
}
fn init_state(&self, place: StateAddr) {
place.write(|| AggregateSumState::<SumT> {
value: SumT::default(),
});
}
fn state_layout(&self) -> Layout {
Layout::new::<AggregateSumState<SumT>>()
}
fn accumulate(
&self,
place: StateAddr,
col... | Rust | 0 |
import torch
dtype = torch.float16
device = 'cuda'
warmup_steps, active_steps = 5, 1000
start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)
attn_configs = {
#'yi-6B-tp1': {'num_heads': 32, 'num_kv_heads': 4, 'head_dim': 128},
#'yi-6B-tp2': {'num_heads': 16, 'num_kv_heads':... | Python | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020 Alibaba Group Holding Limited. 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... | Python | 1 |
QRResult<()>
where
W: Write,
{
while ds.bits_remaining() >= 4 {
let ty = ds.take_bits(4);
match ty {
0 => break,
1 => decode_numeric(meta, &mut ds, &mut writer),
2 => decode_alpha(meta, &mut ds, &mut writer),
3 => decode_structured(meta, &mut ds, &... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.