text string | label_name string | labels int64 |
|---|---|---|
maskmovq mm0, mm1");
test_invalid(&[0x0f, 0xf7, 0x01]);
test_display(&[0x4f, 0x0f, 0xe7, 0x03], "movntq qword [r11], mm0");
test_display(&[0x0f, 0xe7, 0x03], "movntq qword [rbx], mm0");
test_invalid(&[0x0f, 0xe7, 0xc3]);
test_display(&[0x4f, 0x0f, 0xc3, 0x03], "movnti qword [r11], r8");
test_i... | Rust | 0 |
# convert char to pinyin
def convert_char_to_pinyin(text_list, polyphone=True):
if jieba.dt.initialized is False:
jieba.default_logger.setLevel(50) # CRITICAL
jieba.initialize()
final_text_list = []
custom_trans = str.maketrans(
{";": ",", "“": '"', "”": '"', "‘": "'", "’": "'"}... | Python | 1 |
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.triggers.cron import CronTrigger
from shared.settings import settings
from shared.shared_logger import get_shared_logger
from shared.helpers import sessionMaker
logger = ge... | Python | 1 |
::mem::size_of::<m_hdr>() as libc::c_ulong)
as libc::c_int
};
(*m).m_hdr.mh_next = n
}
m = (*m).m_hdr.mh_next
}
}
_ => {}
}
m = m0;
if (*m).m_hdr.mh_flags & 0x2i32 != 0 && (*m).M_d... | Rust | 0 |
=> assert_eq!(e.to_string(), "Backend unavailble: PerfPT"),
}
}
// Ensure we can share `Tracer`s between threads.
#[test]
fn test_shared_tracers_betwen_threads() {
use std::sync::Arc;
use std::thread;
let arc1 = Arc::new(TracerBuilder::new().build().unwrap());
l... | Rust | 0 |
import torch
import triton
import triton.language as tl
import triton_runner
@triton.jit
def matmul_kernel(a_ptr, b_ptr, c_ptr, M, N, K, stride_am, stride_an, stride_bn, stride_bk, stride_cm, stride_ck,
BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, BLOCK_SIZE_K: tl.constexpr):
pid_k ... | Python | 1 |
import os
# Set up environment variables for application configuration
# Default port is 8000 unless specified in the environment
PORT = int(os.environ.get("PORT", 8000))
# Default PostgreSQL username is "admin" unless specified in the environment
POSTGRES_USER = os.environ.get("POSTGRES_USER", "admin")
# Default P... | Python | 1 |
05/31/how-to-execute-a-sql-query-only-if-another-sql-query-has-no-results/
"-- EXPLAIN ANALYZE
WITH ta AS (
INSERT INTO fileinfo(filehash, hashtype, filesize)
VALUES($2, $3, $4)
ON CONFLICT (filehash) DO UPDATE SET filesize = NULL WHERE FALSE
... | Rust | 0 |
###
### crawler.py
###
###
from webcorpus import WebCorpus
from getpage import get_page
from bs4 import BeautifulSoup
def get_all_links(page):
soup = BeautifulSoup(page)
links = []
for link in soup.find_all('a'):
links.append(link.get('href'))
return links
def add_page_to_index(index, url, co... | Python | 1 |
import sys
from scapy.all import *
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
def analyze_port(host, port, verbose_level):
print("[+] Scanning port %s" % port)
packet = IP(dst=host)/TCP(dport=port,flags="S")
response = sr1(packet,timeout=0.5,verbose=verbose_level)
if response is not... | Python | 1 |
req",
|m: &ApplyReq| { &m.put_req },
|m: &mut ApplyReq| { &mut m.put_req },
));
fields.push(::protobuf::reflect::accessor::make_singular_ptr_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<DeleteReq>>(
"delete_req",
... | Rust | 0 |
t of the label for the line edit (QString)
@param slist list of strings to select from (QStringList)
@param current number of item, that should be selected as a default (integer)
@param editable indicates whether the user can input their own text (boolean)
@param f window flags for the dialog (Qt.Window... | Python | 1 |
t = line_numbers_data.line_number[Left];
let nr_right = line_numbers_data.line_number[Right];
let (minus_style, zero_style, plus_style) = (
config.line_numbers_style_minusplus[Minus],
config.line_numbers_zero_style,
config.line_numbers_style_minusplus[Plus],
);
let ((minus_number... | Rust | 0 |
header::LOCATION;
use actix_web::http::uri::{Authority, InvalidUriParts, Scheme, Uri};
use actix_web::{body::EitherBody, Error, HttpResponse};
use bool_ext::BoolExt;
use futures::future::{ok, Either, FutureExt, LocalBoxFuture, Ready};
use std::convert::TryFrom;
// ------ Redirect ------
#[derive(Copy, Clone)]
pub str... | Rust | 0 |
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
"""Simple test script for Adafruit 2.9" 296x128 tri-color display
Supported products:
* Adafruit 2.9" Tri-Color Display Breakout
* https://www.adafruit.com/product/1028
"""
import time
import board
import displayio
from... | Python | 1 |
"""
Module made by t.me/ZrekryuDev
Date: Fri, Dec 15 2023
Supoort chat at t.me/KangersChat
"""
import asyncio
import os
import uuid
import httpx
from pyrogram.enums import MessageMediaType
from pyrogram.types import (
Message,
InlineKeyboardButton,
InlineKeyboardMarkup
)
from pyrogram import Client, f... | Python | 1 |
0], num_classes, kernel_size=1)
def upsample(self, inputs, target):
return F.interpolate(inputs, size=target.shape[2:], mode='trilinear', align_corners=False)
def forward(self, x):
size = x.shape[2:]
x0, x1, x2, x3, x4 = self.backbone(x)
x3_1 = self.conv3_1(torch.cat([x3, self... | Python | 1 |
row_1=['🦚','🦚','🦚']
row_2=['🦚','🦚','🦚']
row_3=['🦚','🦚','🦚']
nested_list=[row_1,row_2,row_3]
position=input("enter the position you want to put money:")
row_number=int(position[0])
column_number=int(position[1])
row_selected=nested_list[row_number-1]
row_selected[column_number-1]="Likki"
print(f"{row_1} \n {row... | Python | 1 |
)
else:
users.append(f"• {mention_html(user.id, html.escape(user.first_name))}")
message = "<b>ʙʟᴀᴄᴋʟɪsᴛᴇᴅ ᴜsᴇʀs</b>\n" + (
"\n".join(users) if users else "ɴᴏɴᴇ ɪs ʙᴇɪɴɢ ɪɢɴᴏʀᴇᴅ ᴀs ᴏғ ʏᴇᴛ."
)
update.effective_message.reply_text(message, parse_mode=ParseMode.HTML)
def __us... | Python | 1 |
(&self) {}
}
}
fn main() {}
use crate::console;
use crate::compiler::compile_app;
use colored::Colorize;
use once_cell::sync::Lazy;
use std::env;
pub static WORKDIR: Lazy<String> = Lazy::new(|| {
let out = env::var("WORKDIR").unwrap_or(
env::var("PWD").expect("Please provide a WORKDIR"),
);
... | Rust | 0 |
n new_secp() -> Secp256k1 {
secp::Secp256k1::with_caps(secp::ContextFlag::Commit)
}
// utility to create a block without worrying about the key or previous header
fn new_block(txs: Vec<&mut Transaction>, secp: &Secp256k1) -> Block {
let mut rng = OsRng::new().unwrap();
let skey = SecretKey::new(secp, &mut rng... | Rust | 0 |
import os
import json
import time
from dotenv import load_dotenv
from spider import HyperliquidSpider
from data_processor import DataProcessor
from notification import NotificationManager
from storage import Storage
# 加载环境变量
load_dotenv()
def main():
print("=== 测试总仓位价值变化异常检测 ===")
# 初始化组件
spider = H... | Python | 1 |
tr>) -> ParseResult<Self>
where
Self: Sized;
}
/// Represents a type that can parsing from multipart.
#[poem::async_trait]
pub trait ParseFromMultipartField: Type {
/// Parse from multipart field.
async fn parse_from_multipart(field: Option<PoemField>) -> ParseResult<Self>
where
Self: S... | Rust | 0 |
):
# y from cnn!!
test_outy = restorecnn( pathdat, pathexe, restorefile, inputfile2, data_x_acc )
seq_data = ssad.irssfp_arrayin_data( Nexample, Nk ).set( test_outy ) #intial sequence
# sequence simulation, y->x_hat
seq_data = ssad.irssfp_arrayin_data( Nexamp... | Python | 1 |
t (wallet_handle, wallet_config) = utils::setup_with_wallet("indy_key_for_did_works_for_their_did");
did::store_their_did_from_parts(wallet_handle, DID, VERKEY).unwrap();
let received_verkey = did::key_for_did(-1, wallet_handle, DID).unwrap();
assert_eq!(VERKEY, received_verkey);
... | 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 |
import jittor as jt
from jittor import nn
from jdet.utils.registry import LOSSES
def l1_loss(pred,target,weight=None,avg_factor=None,reduction="mean"):
loss = jt.abs(pred-target)
if weight is not None:
loss *= weight
if avg_factor is None:
avg_factor = max(loss.shape[0],1)
if reduc... | Python | 1 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('gui', '0001_initial'),
('vms', '0001_initial'),
('auth', '0006_require_contenttypes_0002'),
... | Python | 1 |
Player,
moved_piece_source: Square,
moved_piece_destination: Square,
},
/// Signal that a new player is now playing. The boar is the
/// most recent one which can also be retreived by requesting a
/// `ChessUpdate::Board` response.
PlayerSwitch {
player: Player,
fen: ... | Rust | 0 |
pos, 0.0, 1.0);
}
";
const FRAGMENT_SHADER: &str = "
#version 150
in vec2 v_uv;
in vec4 v_color;
uniform sampler2D u_texture;
out vec4 o_color;
void main() {
o_color = texture(u_texture, v_uv) * v_color;
}
";
pub struct DrawParams {
color: Color,
origin: Vec2,
scale: Vec2,
rotation: f32,
}
im... | Rust | 0 |
tence contains an explicit discourse marker
4. Ensure sentence length follows a wave pattern (short → medium → long → medium → short)
5. Transform {passive_pct}% of passive constructions to active and vice versa
6. MAINTAIN EXACT MEANING while restructuring the discourse""",
# Prompt 5: Multi-Relation Tran... | Python | 1 |
fn mem_size(&self) -> usize {
match self {
AtomType::Bool => 1,
AtomType::U8 | AtomType::I8 => 1,
AtomType::U16 | AtomType::I16 => 2,
AtomType::U32 | AtomType::I32 | AtomType::F32 => 4,
AtomType::U64 | AtomType::I64 | AtomType::F64 => 8,
}... | Rust | 0 |
# Create sample entities
entities = [
Entity(name="Quantum Mechanics", type=EntityType.CONCEPT),
Entity(name="Warp Drive", type=EntityType.TECHNOLOGY),
Entity(name="Random Entity", type=EntityType.ORGANIZATION)
]
# Calculate precision
precisio... | Python | 1 |
pes(
self, recipes: List[Recipe], page: int = 1, page_size: int = 10
) -> PaginatedResult:
"""对菜谱列表进行分页,返回仅包含名称和描述的数据.
Args:
recipes: 菜谱列表
page: 页码(从1开始)
page_size: 每页大小
Returns:
分页结果
"""
total_records = len(recipes)
... | Python | 1 |
#!/usr/bin/python3
"""
Contains the class definition of a State and
an instance Base = declarative_base()
"""
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class State(Base):
"""The class State for MySQL database defined"""
... | Python | 1 |
ed_boxes_y, pred_boxes_w, pred_boxes_h], dim = -1)
for b in range(bs):
#-------------------------------------------------------#
# 将预测结果转换一个形式
# pred_boxes_for_ignore num_anchors, 4
#-------------------------------------------------------#
... | Python | 1 |
#What are functions: is the group of statement in program to perform a specific task
#user define function
#Sythex function in python
def sumf(arg1,arg2):
print(arg1 + arg2)
sumf(10,30)
#parameters, Arguments, Return
def sumf(name, age):
print(name)
print(age)
sumf("Dakalo", 26)
#How to return a v... | Python | 1 |
clone();
let exec = ctx.exec.clone();
match &mut result {
Err(status) => {
let status_code = status.status_code;
let message = if status.expose {
status.message.clone()
} else {
// set expose to true; then root status_handler won't log... | Rust | 0 |
import json
import os
voc2007_train = json.load(open('/nobackup-slow/dataset/my_xfdu/VOCdevkit/VOC2007_converted_ID/train_coco_format.json'))
voc2007_test = json.load(open('/nobackup-slow/dataset/my_xfdu/VOCdevkit/VOC2007_converted_ID/val_coco_format.json'))
voc2012_train = json.load(open('/nobackup-slow/dataset/my_x... | Python | 1 |
th, BitDepth::Eight);
remove_file(output).ok();
}
#[test]
fn issue_52_01() {
test_it_converts(
"tests/files/issue-52-01.png",
None,
ColorType::RGBA,
BitDepth::Eight,
ColorType::Indexed,
BitDepth::Eight,
);
}
#[test]
fn issue_52_02() {
test_it_converts(
... | Rust | 0 |
输出:", e.stdout)
if e.stderr:
print("错误:", e.stderr)
def main():
"""主函数"""
print("🚀 开始配置Azure Speech Services...")
# 检查依赖
try:
result = subprocess.run(
["pip", "show", "azure-cognitiveservices-speech"],
capture_output=True,
text=True,
... | Python | 1 |
open(gt_file).read().splitlines()
except Exception, e:
util.print_error('unable to load ' + gt_file + ': ' + str(e))
for line in lines:
parts = line.split(' ')
if len(parts) != 2 or not util.represents_int(parts[1]):
util.print_error('Ground truth file must have lines of for... | Python | 1 |
from typing import Dict, List, Union
from ..base_transform import LabelTransform
class Mapping(LabelTransform):
r'''
Mapping the label according to a certain dictionary.
.. code-block:: python
from torcheeg import transforms
t = Mapping({
'left_hand': 0,
'ri... | Python | 1 |
_loss_node, pixel_loss_node, deep_loss_node],
{target_node: target_imgs, truncation_node: 1.0})
print(i, total_loss_val, pixel_loss_val, deep_loss_val, reg_loss_val)
# Write out the final images / seeds with appropriate names
[output_images, latents,... | Python | 1 |
fn new(
uart_tx: &'static UTx,
uart_rx: &'static URx,
tx_buf: &'static mut [u8],
rx_buf: &'static mut [u8],
) -> UartEcho<UTx, URx> {
assert!(
tx_buf.len() > rx_buf.len(),
"UartEcho has improperly sized buffers"
);
UartEcho {
... | Rust | 0 |
import re
import subprocess
from cvescan.errors import PkgCountError
INSTALLED_REGEX = re.compile(r"^[uihrp]i")
def get_installed_pkgs_from_manifest(manifest):
installed_pkgs = {}
for pkg in manifest.splitlines():
(pkg, version) = pkg.split("\t")
pkg = _strip_architecture_extension(pkg)
... | Python | 1 |
il import dumps, loads
# @roficial.get("/prueba")
# def prueba():
# resultado = dbcon.srit.oficiales.find({}).sort({"idof": -1 }).limit(1)
# if resultado != None:
# print(resultado)
# ll = resultado.next()
# print("Resultado", int(ll["idof"]))
# gdata = int(ll["idof"])
# ... | Python | 1 |
[error("block time {candidate_time:?} is greater than the median-time-past for the block plus 90 minutes {block_time_max:?}")]
#[non_exhaustive]
TimeTooLate {
candidate_time: DateTime<Utc>,
block_time_max: DateTime<Utc>,
},
#[error("block difficulty threshold {difficulty_threshold:?} is... | Rust | 0 |
-1].content
except Exception as e:
logger.error(f"Error processing query: {e}")
raise HTTPException(status_code=500, detail=f"Error processing query: {str(e)}")
@app.post("/query", response_model=QueryResponse)
async def query_endpoint(request: QueryRequest):
"""Endpoint to process queries thr... | Python | 1 |
<S: Into<String>>(
&mut self,
sheet_id: S,
sheet_title: S,
) -> &mut Worksheet {
let mut worksheet = Worksheet::default();
worksheet.set_sheet_id(sheet_id);
worksheet.set_name(sheet_title.into());
self.work_sheet_collection.push(worksheet);
self.work_s... | Rust | 0 |
import codecs
class Codec(codecs.Codec):
def encode(self, input, errors='strict'):
return codecs.charmap_encode(input, errors, encoding_map)
def decode(self, input, errors='strict'):
return codecs.charmap_decode(input, errors, decoding_table)
class IncrementalEncoder(codecs.IncrementalEncoder... | Python | 1 |
from .base import VoiceAssistant
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
import transformers
import torch
import io
import base64
from openai import OpenAI
import soundfile as sf
class GPT4oAssistant(VoiceAssistant):
def __init__(self):
self.client = OpenAI()
se... | Python | 1 |
# coding: utf-8
# Copyright (c) 2012, Machinalis S.R.L.
# This file is part of quepy and is distributed under the Modified BSD License.
# You should have received a copy of license in the LICENSE file.
#
# Authors: Rafael Carrascosa <rcarrascosa@machinalis.com>
# Gonzalo Garcia Berrotaran <ggarcia@machinalis.... | Python | 1 |
todo {} as done", id)?;
if todo_repo.complete_todo(id).await? {
writeln!(writer, "Todo {} is marked as done", id)?;
} else {
writeln!(writer, "Invalid id {}", id)?;
}
}
None => {
writeln!(writer, "Printing list of all todos... | Rust | 0 |
what exactly happened.
//! // You can also just use its `Debug`, `Display` or `Error` traits
//! Error::HttpError(_)
//! |Error::MissingAPIKey
//! |Error::MissingToken(_)
//! |Error::Cancelled
//! |Error::UploadSizeLimitExceeded(_, _)
//! |Error::Failure(_)
//! ... | Rust | 0 |
self._cells[i][j].draw_move(self._cells[i][j-1], True)
if j < self._num_rows - 1 and not self._cells[i][j + 1].visited and not self._cells[i][j].has_bottom_wall:
self._cells[i][j].draw_move(self._cells[i][j+1])
if self._solve_dfs(i, j + 1):
return True
... | Python | 1 |
ds."
max_seq_len = max_num_blocks_per_seq * block_size
dtype = torch.float16
device = get_current_device()
alibi_slopes = None
if use_alibi_slopes:
alibi_slopes = get_alibi_slopes(num_attn_heads, device)
if same_context_len:
context_lengths = torch.tensor([max_seq_len for _ in ... | Python | 1 |
&data.website_title,
)
}
}
}
}
}
}
}
}
}
<filename>goko/src/plugins/discrete/categorical.rs
//! # Categorical Distribution... | Rust | 0 |
marks b");
if term.len() > 0 {
select_string.push_str(&format!(", tags t, tags_bookmarks tb
WHERE t.id = tb.tag_id AND b.id = tb.bookmark_id AND t.tag LIKE \"%{}%\" OR b.url LIKE \"%{}%\"", term, term));
}
let mut stmt = conn.prepare(&select_string)?;
let mut rows = stmt.query([])?;
let m... | Rust | 0 |
class Solution(object):
def similarPairs(self, words):
"""
:type words: List[str]
:rtype: int
"""
count = 0
for i in range(len(words)):
for j in range(i+1, len(words)):
if set(words[j]) == set(words[i]):
count += 1
... | Python | 1 |
ind_skip`]:
/// use the match-like syntax, running the branch of the first pattern that matches.
/// [example](#find-example)
///
/// - [`strip_prefix`] and [`strip_suffix`]:
/// use the match-like syntax, running the branch of the first pattern that matches.
/// [example](#parsing-enum-example)
///
/// - [`trim_start_... | Rust | 0 |
from unittest import TestCase
from custom_data_structures.min_stack.min_stack import MinStack
class MinStackTestCase(TestCase):
def test_pop_empty(self):
# Given
min_stack = MinStack()
# When
actual = min_stack.pop()
# Then
expected = None
self.assertEqual... | Python | 1 |
import streamlit as st # type: ignore
def tela_apresentacao():
st.markdown(
"""
<div style='text-align: center; padding: 50px 20px;'>
<h1 style='font-size: 42px;'>Análise de Acidentes de Trânsito no Brasil</h1>
<h3>Período: 2021 a 2025</h3>
<p style='font-size:... | Python | 1 |
import pytest
import pandas as pd
import pickle
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
import mlflow
# Set your remote tracking URI
mlflow.set_tracking_uri("http://ec2-54-196-109-131.compute-1.amazonaws.com:5000/")
@pytest.mark.parametrize("model_name, stage, holdout_data_... | Python | 1 |
# -*- coding: utf-8 -*-
import sys
import os
import torch
# import important files
root_path = os.path.abspath('.')
sys.path.append(root_path)
from architecture.rrdb import RRDBNet
from architecture.discriminator import UNetDiscriminatorSN
from train_code.train_master import train_master
class train_esrgan(train_... | Python | 1 |
inverse().map_vec(v))).sqrlen() < 1e-8);
};
}
#[test]
fn affine_inverse() {
affine_inverse_test!(Affine2, Mat2, Vec2);
affine_inverse_test!(Affine3, Mat3, Vec3);
affine_inverse_test!(Affine4, Mat4, Vec4);
}
macro_rules! affine_map_vec_test {
($Map:ident, $Mat:ident, $Vec:ident) => {
let m ... | Rust | 0 |
Node, pos: Array);
#[wasm_bindgen(method, js_name="addTo", js_class=Edge)]
pub fn add_edge_to_graph(this: &Edge, graph: &Graph);
#[wasm_bindgen(method, js_name="renderIn", js_class=Graph)]
pub fn render_in_element(this: &Graph, element: &str);
#[wasm_bindgen(method, structural, indexing_getter)]
... | Rust | 0 |
# encoding=utf-8
import time
import os
import glob
import torch
import operator
import scipy.optimize as opt
from lapjv import lapjv
from src.utils import *
from scipy.stats import spearmanr, kendalltau
tm = 0
types_aids = [
'O', 'S', 'C', 'N', 'Cl', 'Br', 'B', 'Si', 'Hg', 'I', 'Bi', 'P', 'F',
'Cu', 'Ho', 'Pd... | Python | 1 |
import daft
import pandas as pd
import pendulum as lu
from cuallee import Check
def test_positive(check: Check):
check.is_on_monday("id")
pd_df = pd.DataFrame(
{"id": pd.Series([lu.now().next(lu.MONDAY).date()], dtype="datetime64[ns]")}
)
df = daft.from_pandas(pd_df)
result = check.valida... | Python | 1 |
, b: &Self::Solution) -> Ordering {
if a.0 < b.0 && a.1 <= b.1 {
Ordering::Less
} else if a.0 <= b.0 && a.1 < b.1 {
Ordering::Less
} else if a.0 > b.0 && a.1 >= b.1 {
Ordering::Greater
} else if a.0 >= b.0 && a.1 > b.1 {
Ordering::Greater
... | Rust | 0 |
# Generated by Django 3.0.8 on 2021-12-11 17:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("contenttypes", "0002_remove_content_type_name"),
("wagtailredirects", "0006_redirect_increase_max_length"),
]
operations = [
migrati... | Python | 1 |
fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self {
Self { props, link }
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Message::Action(e) => {
self.props.action.emit(e);
}
}
false
}
... | Rust | 0 |
# Copyright (c) 2016 Intel Corp
#
# Authors: Prudhvi Rao Shedimbi <prudhvi.rao.shedimbi@intel.com>
#
# 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... | Python | 1 |
ace().collect();
let action = parts[0];
if action == "mask" {
let mut set_bits = 0;
let mut clear_bits = 0;
let mut float_bits = 0;
// Parse the mask
for (i, bit) in rev(parts[2].chars()).enumerate() {
let bitmask = 1 << i;
... | Rust | 0 |
import unittest
import torch
import torch.nn as nn
from parameterized import parameterized
from torch.testing._internal.common_utils import run_tests
from torch_tensorrt.fx.tools.common_fx2trt import DispatchTestCase, InputTensorSpec
class TestFlattenConverter(DispatchTestCase):
@parameterized.expand(
[
... | Python | 1 |
import numpy as np
from qmsolve import Hamiltonian, SingleParticle, TimeSimulation, init_visualization, femtoseconds, m_e, Å
#interaction potential
def potential_barrier(particle):
#This wavefunction correspond to a gaussian wavepacket with a mean X momentum equal to p_x0
V0 = 2
a = 1 * Å
x0 = 4 * Å... | Python | 1 |
l, json=init_notification)
print("\nSent initialized notification")
# 3. List tools request
list_tools_request = {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}
print("\nSending tools/list request...")
tools_result = await send_reques... | Python | 1 |
a new Rectangle with its top-left corner at the origin and with the provided Size.
///
/// Arguments
/// ---------
/// size : Size
/// Size of the new Rectangle
///
/// Returns
/// -------
/// Rectangle
/// The new Rectangle.
#[staticmethod]
fn with_size(size: &W... | Rust | 0 |
= Gpt2Vocab::unknown_value();
// When
let gpt2_vocab = Gpt2Vocab {
values,
indices,
unknown_value,
special_indices,
special_values,
};
// Then
assert_eq!(gpt2_vocab.unknown_value, "");
assert_eq!(Gpt2Vocab::bos_... | Rust | 0 |
return 1
subprocess.run(
[pip_path, "install", "-r", tmp_path],
check=True,
capture_output=True,
text=True
)
mostrar_info(_("Dependencias instaladas en el entorno virtual"))
r... | Python | 1 |
rors
)
def test_will_not_unmount_filesystem_on_partition(self):
node = factory.make_Node()
partition = factory.make_Partition(node=node)
filesystem = factory.make_Filesystem(
mount_point=factory.make_absolute_path(), partition=partition
)
form = UnmountNo... | Python | 1 |
await self._send_error(error_msg)
except Exception as e:
logger.exception(f"[RealTimeVoiceHandler:Logic] 处理用户回答失败: {e}")
await self._send_error(f"处理回答失败: {str(e)}")
async def _speak_question(self, question: str):
"""播放问题语音"""
try:
... | Python | 1 |
)
.await
.unwrap();
let gas_price = web3.eth().gas_price().await.unwrap();
let gas_price = gas_price + gas_price / 2;
let mut options = Options::default();
options.gas_price = Some(gas_price);
options.gas = Some(gas_limit / gas_price);
options.nonce = Some(nonce);
let ke... | Rust | 0 |
converted into a zero-valued tag with the method
/// `Tag::from(v: u8)`. For example:
///
/// ```
/// let tag = Tag::Array(7, 5); // an u32 array with 7 values
/// if let Tag::Array(_, ut) = tag {
/// assert_eq!(Tag::U32(0), Tag::from(ut));
/// }
/// ```
///
/// After the tag, the content of the array is encoded in... | Rust | 0 |
EBands) as isize) =
if -9.0f32 > *old_ebands.offset((i + c * (*m).nbEBands) as isize) {
-9.0f32
} else {
*old_ebands.offset((i + c * (*m).nbEBands) as isize)
};
tmp =
coef * *old_ebands.offset((i + c * (*m).nbEBands) as isize) + prev[c as usize] + q;
*old_ebands.offset((i + c * (*m).nbEB... | Rust | 0 |
ApicId::X2Apic(x2apic.apic_id),
}
}
}
/// Represents an SMT thread in the system.
#[derive(Ord, PartialOrd)]
pub struct Thread {
/// ID the thread, global within a system.
pub id: GlobalThreadId,
/// ID of the NUMA node (system global)
pub node_id: Option<NodeId>,
/// ID of the package... | Rust | 0 |
_number), Some(port_number)) = (module_name, module_number, port_number) {
//if let Some(module_name) = module_name {
//let command = get_module_command(&module_name, &cmd.clone().string().unwrap());
let command = get_module_command(&module_name, &path[2]);
println!("command = {:?}", command... | Rust | 0 |
mbah key-termux' + me + ':\n' + pu + '[' + i + '+' + pu + ']' + i + ' tombol kanan,kiri,HOME,PGUP,PGDN? ' + pu + '[' + i + 'y' + cy + '/' + me + 'n' + pu + ']' + me + ': ' + cy)
if key == 'y' or key == 'Y':
os.system('rm -rf $HOME/.termux')
os.system('mkdir .termux')
os.system('cd .termux')
... | Python | 1 |
activated: `HtmlHrElement`*"]
pub fn color(this: &HtmlHrElement) -> String;
# [wasm_bindgen (structural , method , setter , js_class = "HTMLHRElement" , js_name = color)]
#[doc = "Setter for the `color` field of this object."]
#[doc = ""]
#[doc = "[MDN Documentation](https://developer.mozilla.org/e... | Rust | 0 |
sources_response(&payment_method, &res).wait().unwrap();
let res_parsed: Vec<serde_json::Value> = serde_json::from_str(&res).unwrap();
assert_eq!(res_parsed.len(), 1);
let utxo = res_parsed.get(0).unwrap().as_object().unwrap();
assert_eq!(utxo.get("paymentAddress").unwrap().as_str().unwrap(), payment_a... | Rust | 0 |
| vec![Fp::zero(); n]);
testing::fill_in_witness(0, &mut witness, &[]);
// make sure we're done filling the witness correctly
cs.verify(&witness, &[]).unwrap();
// generate witness polynomials
let witness_evals: [Evaluations<Fp, D<Fp>>; COLUMNS] =
array_init(|col| E... | Rust | 0 |
m-bindgen
#![allow(unused_imports)]
use super::*;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "wasm-bindgen" {
# [wasm_bindgen (extends = :: js_sys :: Object , js_name = CSSRule , typescript_type = "CSSRule")]
#[derive(Debug, Clone, PartialEq, Eq)]
#[doc = "The `CssRule` class."]
#[doc = ""]
... | Rust | 0 |
accum.append(rest)
return
if p > 0:
accum.append(rest[:p])
rest = rest[p:]
# p is no longer used
c = rest[1:2]
if c == "%":
accum.append("%")
rest = rest[2:]
elif c =... | Python | 1 |
*Required features: `\"Win32_NetworkManagement_MobileBroadband\"`*"]
pub type MBN_CONNECTION_MODE = i32;
#[doc = "*Required features: `\"Win32_NetworkManagement_MobileBroadband\"`*"]
pub const MBN_CONNECTION_MODE_PROFILE: MBN_CONNECTION_MODE = 0i32;
#[doc = "*Required features: `\"Win32_NetworkManagement_MobileBroadban... | Rust | 0 |
ep(0.001)
# close out the stream gracefully
except trio.ClosedResourceError:
print('transport closed on streamer side!')
assert stream.closed
break
else:
raise RuntimeError(
'Streamer not cancelled before finish... | Python | 1 |
requestedDate=request.requestedDate,
totalStudents=request.totalStudents,
totalTeachers=request.totalTeachers,
comment=request.comment,
offerContactEmail=request.collectiveOfferTemplate.contactEmail,
offerContactPhoneNumber=request.collectiveOfferTemplate.contactPhone,
... | Python | 1 |
#!/usr/bin/env python3
""" task_wait_n """
import asyncio
import random
from typing import List
task_wait_random = __import__('3-tasks').task_wait_random
async def task_wait_n(n: int, max_delay: int) -> List[float]:
""" task_wait_n """
coroutines = []
for _ in range(n):
coroutines.append(task_w... | Python | 1 |
}
/// balances are state of the erc20 tokens
pub fn legacy_holders(storage: &mut dyn Storage) -> Bucket<Holder> {
bucket(storage, PREFIX_HOLDERS)
}
/// balances are state of the erc20 tokens (read-only version for queries)
pub fn legacy_holders_read(storage: &dyn Storage) -> ReadonlyBucket... | Rust | 0 |
ode ***')
print('Sleeping for 2 seconds...')
time.sleep(2)
# A process returns its result to the caller as an event.
result = 42
LaunchProcess.post_event(reply_token,DataEvent(result)) # source must be None for pickling
LaunchProcess.post_event(reply_token,CompletionEve... | Python | 1 |
commendation = RecommendationType.SELL
# Extract confidence
confidence = 0.5 # Default medium confidence
if 'high confidence' in analysis_lower or 'strong' in analysis_lower:
confidence = 0.8
elif 'low confidence' in analysis_lower or 'weak' ... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.