text string | label_name string | labels int64 |
|---|---|---|
import json
JFR = open("books.json", "r")
jsonFile = json.load(JFR)
# print(jsonFile)
for book in jsonFile['books']:
print(book['name'])
print("-" * len(book['name']))
for k, v in book.items():
print(k, "=>", v)
print("-" * 40)
print("-" * 60)
# data should be stored in single quotes (')
empd... | Python | 1 |
- - [28/Dec/2019:16:49:07 +0000] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:71.0) Gecko/20100101 Firefox/71.0""#,
}))
}
rfc5424 {
args: func_args![value: r#"<13>1 2020-03-13T20:45:38.119Z dynamicwireless.name non 2426 ID931 [exampleSDID@32473 iut="3" eventSource= "A... | Rust | 0 |
d2.get() as u64;
EMMC_CARD.card_capacity *= 512 * 1024; // Calculate Card capacity
}
} else {
// CSD VERSION 1.0
let csize = ((buffer[4] & 0x03) as u32) << 8;
csd.csd1.modify(CSIZE.val(csize));
csd.csd1
.modify(CSIZE.val... | Rust | 0 |
import matplotlib.pyplot as plt
def plot_digit(image_data):
image = image_data.reshape(28, 28)
plt.imshow(image, cmap="binary")
plt.axis("off") | Python | 1 |
import requests
import json
# Hugging Face API endpoint and token
API_URL = "https://api-inference.huggingface.co/models/meta-llama/Llama-2-7b-chat-hf"
HEADERS = {"Authorization": "Bearer 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"}
def get_ranked_menus_with_llama(input_data):
print("inside get_ranked_menus_with_llama... | Python | 1 |
else:
self._log("Could not find apply button", "error")
return False, self.logs
except Exception as e:
self._log(f"Error applying to job: {str(e)}", "error")
return False, self.logs
finally:
# Close the browser
... | Python | 1 |
"""
Write a python function to find a pair with highest product from a given array of integers.
assert max_Product([1,2,3,4,7,0,8,4]) == (7,8)
"""
def max_Product(arr):
max_product = 0
max_pair = []
for i in range(len(arr)):
for j in range(i+1, len(arr)):
if arr[i] * arr[j] > max_produc... | Python | 1 |
import re
import requests
import json
def parse_titles_and_fetch_details(text):
print(text)
titles = re.findall(r"\*\*(.*?)\*\*", text)
anime_doc = {}
for title in titles:
query = """
query ($search: String) {
Media(search: $search, type: ANIME) {
id
... | Python | 1 |
from numpy import arange
from mpl_toolkits.mplot3d import Axes3D # noqa
from mne import create_info, EvokedArray
from matplotlib.pyplot import savefig, close, gcf
from io import BytesIO
from utils.config import PSDEnum, ChannelEnum
from utils.edf import EdfUtil
def APSD(data, tmin, tmax, fb_idx, topo_signal=None): ... | Python | 1 |
U"]
DISABLED = 0,
#[doc = "1: Key slot ID successfully selected by KMU"]
ENABLED = 1,
}
impl From<SELECTED_A> for bool {
#[inline(always)]
fn from(variant: SELECTED_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `SELECTED` reader - Key slot ID successfully selected by the KMU"]
pub s... | Rust | 0 |
Compound.make_text(
"SHEET:", nominal_text_size / 3, align=(Align.MIN, Align.CENTER)
).wrapped
)
if sheet_number is not None:
labels += Pos(t_base_line3 @ (1 / 12)) * Sketch(
Compound.make_text(
str(sheet_number),
... | Python | 1 |
url = fetch_submit_url(&body);
assert_eq!("https://adfs.example.com:443/adfs/ls/IdpInitiatedSignOn.aspx?loginToRp=urn:amazon:webservices".to_owned(), submit_url);
Ok(())
}
#[test]
fn filters_input_params() -> Result<()> {
let response = r#"
<input name="AuthMethod" valu... | Rust | 0 |
i::airspy_set_mixer_gain(self.inner, adjust_gain(gain, 0, 15, 1)));
}
Ok(())
}
/// Set VGA (IF) gain: 0-15 db
/// If the specified gain falls outside of the valid range, the gain will be clamped.
pub fn set_vga_gain(&mut self, gain: u8) -> AirspyResult<()> {
unsafe {
... | Rust | 0 |
oc[key] = tomlkit.array()
doc[key].append(table)
toml_str = tomlkit.dumps(doc)
# Parse back
parsed = tomlkit.parse(toml_str)
# Convert to JSON and back
json_str = json.dumps(parsed, cls=yq.JSONDateTimeEncoder)
from_json = json.loads(json_str)
# Back to TOML
... | Python | 1 |
self.cursor.fetchone()
if talk_row:
talk_data = {
"text": talk_row[0],
"owner": {
"user_id": talk_row[1],
"name": talk_row[2],
"alias": talk_row[3],
"avatar... | Python | 1 |
eturn history, image_path, image_cnt
def chat_inner(self, message, dataset=None):
self.set_max_num(dataset)
kwargs_default = dict(do_sample=False, max_new_tokens=512, top_p=None, num_beams=1)
self.kwargs = kwargs_default
if len(message) > 1:
history, image_path, image_cn... | Python | 1 |
where
T: AsRef<[u8]> + Unpin,
{
type Output = Result<i32, ErrBox>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let inner = self.get_mut();
if inner.io_state == IoState::Done {
panic!("poll a Read after it's done");
}
if inner.io_state == IoState::Pending {
... | Rust | 0 |
-> fmt::Result {
f.write_str("platforms error")
}
}
#[cfg(feature = "std")]
impl std::error::Error for Error {}
// Copyright (c) 2021 The Lutino Projects
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.... | Rust | 0 |
time, screenshot_test_frame # 用于计算串流FPS
# 精确控制FPS
current_monoto_time = time.monotonic()
elapse_time = current_monoto_time - screenshot_last_limit_time
if elapse_time > 5: # 有切换,重置参数
wait_time = 0
elapse_time = 1.0 / config_obj.fps_var # 第一次不需要wait
# # 这段用于计算串流FPS,不需要可以注释掉(缩进... | Python | 1 |
79, 612121502, 660433863, 1066956358,
2410265369, 3691215764, 1134057558, 843539511, 694371854, 2599950644,
1558711302, 2053393907, 1148250800, 1108939089, 377893761, 1098804084,
1819782402, 3151682353, 3812854953, 1602843789, 369269593... | Rust | 0 |
er/nf-winuser-setwindowpos)
/// method.
pub fn SetWindowPos(self,
hwnd_insert_after: HwndPlace,
pos: POINT, size: SIZE, flags: co::SWP) -> WinResult<()>
{
bool_to_winresult(
unsafe {
user32::SetWindowPos(
self.ptr,
hwnd_insert_after.as_ptr(),
pos.x, pos.y,
size.cx, size.c... | Rust | 0 |
ation = *mut ::core::ffi::c_void;
pub type IMSMQEvent = *mut ::core::ffi::c_void;
pub type IMSMQEvent2 = *mut ::core::ffi::c_void;
pub type IMSMQEvent3 = *mut ::core::ffi::c_void;
pub type IMSMQManagement = *mut ::core::ffi::c_void;
pub type IMSMQMessage = *mut ::core::ffi::c_void;
pub type IMSMQMessage2 = *mut ::core:... | Rust | 0 |
{
do_encode_bench(b, 3 * 1024)
}
#[bench]
fn encode_3kib_display(b: &mut Bencher) {
do_encode_bench_display(b, 3 * 1024)
}
#[bench]
fn encode_3kib_reuse_buf(b: &mut Bencher) {
do_encode_bench_reuse_buf(b, 3 * 1024, STANDARD)
}
#[bench]
fn encode_3kib_slice(b: &mut Bencher) {
do_encode_bench_slice(b,... | Rust | 0 |
player.resume()
messages_queue.put("Play>True")
elif cmd == 'shuffle':
logging.info("cmd: shuffle")
appPlaylist.shuffle = not appPlaylist.shuffle
messages_queue.put(f"Shuffle>{'True' if appPlaylist.shuffle else 'False'}")
elif cmd == 'volume':
... | Python | 1 |
// We'll try to recover from the error.
MmuIss::SET_RESTARTABLE => panic!("restartable permission fault occurred accessing address {:#018x}: ISS = {:#010x}", fault_address, iss.bits()),
MmuIss::SET_UNCONTAINABLE => panic!("uncontainable permission fault occurred accessing address {:#018x}: ISS = {:#010... | Rust | 0 |
import random
import transformers
from lm_eval import evaluator, tasks
from lm_eval.api.model import LM
class DryrunLM(LM):
def __init__(self):
self.tokencost = 0
self.tokenizer = transformers.GPT2TokenizerFast.from_pretrained("gpt2")
self.tokenizer.pad_token = "<|endoftext|>"
@clas... | Python | 1 |
_ver) => {
write!(f,
"upgrading metadata version from '{}' to '{}'",
from_ver,
to_ver)
}
MetadataUpgradeNotNeeded(ver) => {
write!(f, "nothing to upgrade: metadata version is already '{}'", ver)
... | Rust | 0 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class yoloLoss(nn.Module):
'''
定义一个torch.nn中并未实现的网络层,以使得代码更加模块化
torch.nn.Modules相当于是对网络某种层的封装,包括网络结构以及网络参数,和其他有用的操作如输出参数
继承Modules类,需实现__init__()方法,以及forward()方法
'''
def __init__(self,S,B,l_co... | Python | 1 |
}
queue.push(new).unwrap();
}
queue
}
fn slab_push_only<T: Copy>(n: usize, m: usize, t: T) -> Slab<Slab<T>> {
let slab = Slab::new();
for _ in 0..n {
let new = Slab::new();
for _ in 0..m {
new.insert(t).unwrap()... | Rust | 0 |
set_fulfilled_at(stored_requests[1].id, Utc::now())
.await?;
ForcedExitRequestsSchema(&mut storage)
.set_fulfilled_at(stored_requests[2].id, Utc::now())
.await?;
let oldest_unfulfilled_request = ForcedExitRequestsSchema(&mut storage)
.get_oldest_unfulfilled_request()
.aw... | Rust | 0 |
tOr,
/// `a ^ b` - Bitwise xor
BitXor,
/// `a << b` - Bit-shift leftwards
BitShl,
/// `a >> b` - Bit-shift rightrights
BitShr
}
impl Show for BitOp {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{}", match *self {
BitAnd => "&",
BitOr => "|",
... | Rust | 0 |
import torch
from mmdet.models import DETECTORS
from third_party.bev_mmdet3d import BEVFormer
from third_party.bev_mmdet3d.core.bbox import bbox3d2result
@DETECTORS.register_module()
class BEVFormerTRT(BEVFormer):
def __init__(self, *args, **kwargs):
super(BEVFormerTRT, self).__init__(*args, **kwargs)
... | Python | 1 |
# the multilayer perceptron where I included bias
import tensorflow as tf
import numpy as np
from command_line_args import arg_parser
from data import data_from_args
from model_helpers import build_model, init_weights, set_seeds
args = arg_parser.parse_args()
data = data_from_args(args)
NUM_HIDDEN = args.num_hidden... | Python | 1 |
s.build(),
json!({
"ids": {
"trakt": 4834049
}
})
)
}
#[test]
fn list_selector_user() {
let s = ListSelector::default().user(|user| user.slug("lichthagel"));
assert_eq!(
s.build(),
... | Rust | 0 |
tagResources.append(tagResource)
if len(row[12]) >= 1:
tagResource = (getUUID(gmp, row[12]))
tagResources.append(tagResource)
comment = f"Created: {time.strftime('%Y/%m/%d-%H:%M:%S')}"
if tagType.upper() == "REPORT":
... | Python | 1 |
s *const Self)
}
/// Validates the given string.
fn validate(s: &str) -> Result<(), NameError> {
match Self::parse_as_possible(s) {
Ok(_) => Ok(()),
Err(e) => Err(NameError::new(
TargetNameType::Eqname,
e.map_or(0, |(_local_name_start, valid_u... | Rust | 0 |
ub subnet: Option<T>,
#[serde(rename = "IPRange")]
pub ip_range: Option<T>,
pub gateway: Option<T>,
pub aux_address: Option<HashMap<T, T>>,
}
/// Result type for the [Create Network API](../struct.Docker.html#method.create_network)
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "PascalCase")... | Rust | 0 |
fn is_escaped(data: &str, loc: usize) -> bool {
let mut i = loc;
while i >= 1 && data.as_bytes()[i - 1] == b'\\' {
i -= 1;
}
((loc - i) & 1) != 0
}
// Remove backslash escapes and resolve entities
pub fn unescape(input: &str) -> Cow<str> {
if input.find(|c| c == '\\' || c == '&' || c == '\r... | Rust | 0 |
ageOne.shape[3]), mode='bilinear', align_corners=False) # not ideal
tenUpsample = self.netDisparityFou(torch.cat([ tenImageOne, tenUpsample ], 1)); tenImageOne = None
tenRefine = self.netRefine(tenUpsample)
tenRefine *= tenStd[1] + 0.0000001
tenRefine += tenMean[1]
return torch.nn.functional.threshold(input... | Python | 1 |
Tasks.zero_shot_classification: [OutputKeys.SCORES, OutputKeys.LABELS],
# relation extraction result for a single sample
# {
# "uuid": "人生信息-1",
# "text": "《父老乡亲》是由是由由中国人民解放军海政文工团创作的军旅歌曲,石顺义作词,王锡仁作曲,范琳琳演唱",
# "spo_list": [{"subject": "石顺义", "predicate": "国籍", "object": "中国"}]
# }
... | Python | 1 |
from flask import Flask, request, jsonify
from face_detection import FaceDetection
import os
import cv2
from flask_cors import CORS, cross_origin
from PIL import Image, ExifTags
app = Flask(__name__)
CORS(app)
face_detector = FaceDetection()
# Endpoint to detect faces and return bounding boxes and probabilities
@a... | Python | 1 |
cryptid_account: account.info.key,
},
account.signer_nonce,
),
CryptidAccountAddress::Generative(account) => {
let seeder = CryptidSignerSeeder {
cryptid_account: account.key,
};
let n... | Rust | 0 |
n).
man_pages = [
(master_doc, 'grovepy', u'grove.py Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (sou... | Python | 1 |
self,
(mut doors, mut sprites, time, entities, mut main_resource): Self::SystemData,
) {
if main_resource.should_reset_plasma_timers {
self.sprite_changing_timer = TIMING_CHANGE_SPRITE;
self.door_timers = HashMap::new();
main_resource.should_reset_plasma_timers =... | Rust | 0 |
if avatar.size > 10 * 1024 * 1024:
return Response({'error':'图像过大'}, status=status.HTTP_400_BAD_REQUEST)
model_data['avatar'] = avatar
# 将模板传入
template = request.data.get('template')
if template:
try:
model_data['template... | Python | 1 |
SEL_A::OFF,
1 => EDSEL_A::POSEDGE,
2 => EDSEL_A::NEGEDGE,
3 => EDSEL_A::BOTHEDGES,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `OFF`"]
#[inline(always)]
pub fn is_off(&self) -> bool {
*self == EDSEL_A::OFF
}
... | Rust | 0 |
ubtract the two and then compare some small tolerance (e.g.
# 1e-12).
MinCovDet(random_state=rand_gen).fit(data)
def test_mcd_support_covariance_is_zero():
# Check that MCD returns a ValueError with informative message when the
# covariance of the support data is equal to 0.
X_1 = np.array([0.5, 0... | Python | 1 |
# Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
import pytest
import torch
import deepspeed
from deepspeed.accelerator import get_accelerator
from deepspeed.ops.op_builder import InferenceBuilder
from .inference_test_utils import allclose, get_dtypes
if not deepspeed.ops... | Python | 1 |
return parser
def main():
args = sanitize_help(get_parser()).parse_args()
graphbase = args.graphbase
# @RamRS: This might need some more work
infiles = [graphbase, graphbase + '.tagset']
if args.stoptags:
infiles.append(args.stoptags)
for _ in infiles:
check_input_files(_, ... | Python | 1 |
TXT(0x01, '改造·换钱\n'),
TXT(0x02, '购买道具\n'),
TXT(0x03, '离开\n'),
),
)
MenuEnd(0x0000)
ExecExpressionWithVar(
0x28,
(
(Expr.PushLong, 0xFFFF),
Expr.Nop,
Expr.Return,
),
)
OP_5F(0x0000)
FadeIn(30... | Python | 1 |
# 3 - Soma de Dígitos:
# Escreva um programa que solicite um número ao usuário e use
# um laço while para somar os dígitos do número até que a soma
# seja um único dígito.
soma = 0
n = int(input('Digite um numero: '))
while 0 <= n:
n -= 1
soma += n
print(n)
print(soma) | Python | 1 |
oi_4[2] and roi_4[1] <= y <= roi_4[3]:
return 'ROI 4'
return None
def main():
lidar = Lidar()
result = [0, 0, 0, 0] # Initialize the result array
try:
# Setup plot
img = np.zeros((640, 640, 3), dtype=np.uint8)
i = 0
while True:
data = lidar... | Python | 1 |
}
Ok(ret)
}
fn div(&mut self, x: &Self) -> Result<Self, String> {
// let ret = new_poly_div(&self, &x);
// return ret;
new_poly_div(self, x)
}
fn long_div(&mut self, x: &Self) -> Result<Self, String> {
poly_long_div(self, x)
}
fn fast_div(&mut self, x: &Self) -> Result<Self, String>{
... | Rust | 0 |
+ panic::UnwindSafe,
{
utils::set_network_environment("br");
let result = panic::catch_unwind(|| {
test();
});
utils::clear_network_environment();
assert!(result.is_ok())
}
mod components;
mod map;
mod player;
use components::{Position, Renderable};
use map::{create_map, draw_map};
use p... | Rust | 0 |
ed(ctx, Key::I) {
self.interactive_panel = true;
}
}
else if self.interactive_panel {
if input::is_key_pressed(ctx, Key::I) {
self.interactive_panel = false;
}
}
else if !self.player_turn {
puppet_master(&mu... | Rust | 0 |
continue
anchors_q_c3.append(np.array([x0, y0, x1, y1]))
x0, y0, x1, y1 = self.anchor_mapping((x0, y0, x1, y1), (l_q, t_q, r_q, b_q), (l_k, t_k, r_k, b_k))
if x0 == -1:
anchor_label = -1
x0 = y0 = 0 ... | Python | 1 |
._shape[1]
elif X._shape and not w._shape: w._shape = (1,X._shape[1])
elif w._shape and not X._shape: X._shape = (None,w._shape[1])
# Then set the shape of Z to match the shape of X
elemwise._calc_shapes(self,X,Z)
def _slice_inst(self,i):
self.w.fpval = self.w.fpval[0,i*sel... | Python | 1 |
import numpy as np
def gcc_phat(sig, refsig, fs=1, max_tau=None, interp=16):
# Compute cross-spectrum
n = sig.shape[0] + refsig.shape[0]
SIG = np.fft.rfft(sig, n=n)
REFSIG = np.fft.rfft(refsig, n=n)
R = SIG * np.conj(REFSIG)
cc = np.fft.irfft(R / (np.abs(R) + np.finfo(float).eps), n=(interp * n... | Python | 1 |
ad: M30SampleHeader = unsafe { mem::zeroed() };
let result = unsafe {
let mut hack = slice::from_raw_parts_mut(
&mut m30head as *mut M30SampleHeader as *mut u8,
mem::size_of::<M30SampleHeader>()
);
file.read(&mut hack)
};
l... | Rust | 0 |
page_index: params.page_index,
page_size: params.page_size,
data: service_vec,
}
}
/// query service usage statistics by provider
#[ink(message)]
pub fn query_by_provider(&self, provider: AccountId, params: PageParams) -> PageResult<UsageReco... | Rust | 0 |
"""
convenience printers for manual visual inspection of brainchop-cli output
"""
import hashlib
from typing import Any
from pathlib import Path
from brainchop.utils import load_models
from tinygrad.helpers import fetch, getenv
import subprocess
CACHEDIR = Path.home() / ".cache" / "brainchop" / "output"
CACHEDIR.mkdi... | Python | 1 |
# svd.py
import numpy as np
import torch
def nystrom_kernel_svd(samples, kernel_fn, k):
"""
Computes the SVD of the kernel matrix using the Nystrom method.
Args:
samples (np.ndarray): Data samples of shape (n_sample, H, W, C).
kernel_fn (callable): Kernel function from neural_tangents.
... | Python | 1 |
tr, Any]) -> bool:
"""辞書からデシリアライズ"""
try:
self._equipment_data = EquipmentData.from_dict(data)
self.initialized = self._equipment_data.initialized
self.set_data(self._equipment_data)
return True
except Exception as e:
logger.error(f"装備デ... | Python | 1 |
ethod(name = "__next__")]
fn next(&self, vm: &VirtualMachine) -> PyResult {
let predicate = &self.predicate;
let iterable = &self.iterable;
if !self.start_flag.get() {
loop {
let obj = call_next(vm, iterable)?;
let pred = predicate.clone();
... | Rust | 0 |
b(expr)`.
Simple {
dir: Spanned<PortDir>,
port: Vec<&'a ModportSimplePort<'a>>,
},
}
/// A single simple modport port.
///
/// For example the `a` or `.b(expr)` in `input a, .b(expr)`.
#[moore_derive::node]
#[indefinite("simple modport port")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct M... | Rust | 0 |
es! ident {
($t:tt) => {
Ident::new(stringify!($t), Span::call_site())
};
}
fn determine_endian(ident: &Ident) -> Result<Ident> {
match ident.to_string().as_str() {
"_" | "ne" | "native" => Ok(ident!(NativeEndian)),
"le" | "little" => Ok(ident!(LittleEndian)),
"be" | "big" =... | Rust | 0 |
1936*q^19
+ Order(q^20)
Sage example in ./combinat.tex, line 3185::
sage: n = 10
sage: V = range(1,n+1)
sage: F = Subsets(V, 2)
sage: S = SymmetricGroup(V)
sage: G = PermutationGroup([ on_pairs(sigma) for sigma in S.gens() ],
....: domain=F)
sage: q,t = QQ['q,t'].gens()
sage: Z... | Python | 1 |
import badger2040
import qrcode
import os
import badger_os
from widgets import draw_window, pprint, ptitle, plength, button, draw_ui
# Check that the qrcodes directory exists, if not, make it
try:
os.mkdir("qrcodes")
except OSError:
pass
# Load all available QR Code Files
try:
CODES = [f for f in os.listd... | Python | 1 |
1_33)]
pub use core::pin::Pin;
#[cfg(__standback_before_1_33)]
pub use crate::v1_33::Pin;
}
#[doc(hidden)]
pub mod task {
#[cfg(__standback_since_1_36)]
pub use core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
#[cfg(all(__standback_since_1_51, feature = "std"))]
pub use std::ta... | Rust | 0 |
t filter = future::block_on(PACKET_FILTER.lock());
if filter.update_warning_suppression(id, action == "suppress") {
display(
format!("Warnings for packet ID {:02X} {}ed", id, action),
Color::Green,
);
} else {
display(
"This packet ID is already handl... | Rust | 0 |
from __future__ import annotations
import jax.numpy as jnp
from jax.typing import ArrayLike
from matplotlib.axes import Axes
from .._checks import check_times
from .utils import colors, optional_ax
__all__ = ['pwc_pulse']
@optional_ax
def pwc_pulse(
times: ArrayLike,
values: ArrayLike,
*,
ax: Axes ... | Python | 1 |
"add a small description of the image inside the <img></img> tag; otherwise, add the image caption inside <img></img>. "
"Watermarks should be wrapped in brackets. Ex: <watermark>OFFICIAL COPY</watermark>. Page numbers should be wrapped in brackets. "
... | Python | 1 |
x13;
/// Device (host) features word selection.
const DEVICE_FEATURES_SEL: u64 = VIRTIO_BASE + 0x14;
const DEVICE_FEATURES_SEL_END: u64 = VIRTIO_BASE + 0x17;
/// Flags representing device features understood and activated by the driver. Access to this
/// register sets bits DriverFeaturesSel ∗ 32 to (DriverFeaturesSe... | Rust | 0 |
XEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OU... | Rust | 0 |
"""
Unit and regression test for the kaldo package.
"""
# Import package, test suite, and other packages as needed
from kaldo.forceconstants import ForceConstants
import numpy as np
from kaldo.phonons import Phonons
from kaldo.conductivity import Conductivity
import pytest
@pytest.fixture(scope="function")
def phono... | Python | 1 |
import inspect
def example_func(a, b, c=10, *args, **kwargs):
pass
params = inspect.signature(example_func).parameters
print(params)
def example_func(a, b, c=10, *args, **kwargs):
print(locals()) # Wyświetla słownik z wszystkimi argumentami i ich wartościami
example_func(1, 2, 3, 4, 5, key="value") | Python | 1 |
from pritunl.helpers import *
from pritunl import mongo
from pritunl import task
from pritunl import utils
from pritunl import settings
import datetime
class TaskCleanClientPool(task.Task):
type = 'clean_client_pool'
@cached_static_property
def pool_collection(cls):
return mongo.get_collection('c... | Python | 1 |
tor.reference_name)
# reference_thing_copy_loc = reference_mount if isinstance(reference_mount, bd.Location) else reference_mount.location
# motor.reference_thing.move(reference_thing_copy_loc.inverse())
# def export_urdf(self, joint_name:str, motor_name:str, parent_link_name: str, child_link_prefix:... | Python | 1 |
fn create_get_path_destroy() {
// just make sure all the functions are hooked up properly.
let devmgr = open_isolated_devmgr().expect("failed to open isolated devmgr");
let ramdisk = RamdiskClient::builder(512, 2048)
.dev_root(devmgr)
.build()
.expect("failed... | Rust | 0 |
IO_Object_ContentHandler(sax.handler.ContentHandler):
def __init__(self, item):
self.item = item
self._element = ""
def startDocument(self):
self._element = ""
def startElement(self, name, attrs):
self._element = ""
def endElement(self, name):
if name == "shor... | Python | 1 |
NonMinimalCborEncoding));
}
}
#[test]
fn test_read_negative() {
let cases = vec![
(-1, vec![0x20]),
(-24, vec![0x37]),
(-25, vec![0x38, 0x18]),
(-256, vec![0x38, 0xFF]),
(-1000, vec![0x39, 0x03, 0xE7]),
(-1000000, vec![... | Rust | 0 |
from fastapi import APIRouter , HTTPException | Python | 1 |
def nms_2d_faster(boxes, overlap_threshold, old_type=False):
x1 = boxes[:, 0]
y1 = boxes[:, 1]
x2 = boxes[:, 2]
y2 = boxes[:, 3]
score = boxes[:, 4]
area = (x2 - x1) * (y2 - y1)
I = np.argsort(score)
pick = []
while I.size != 0:
last = I.size
i = I[-1]
pick.ap... | Python | 1 |
from openai import OpenAI
from loguru import logger
import sys
from tenacity import (
retry,
stop_after_attempt,
wait_random_exponential,
) # for exponential backoff
from .save_image import save_generated_image
@retry(wait=wait_random_exponential(min=1, max=120), stop=stop_after_attempt(6))
def generat... | Python | 1 |
create_task(
self._upload_file_and_call_api(
"/file/upload",
file_name=filename,
file=file,
endpoint="/bot/send",
content_type="file",
buttons=buttons,
parent_id=pa... | Python | 1 |
,1], padding='VALID') + conv1_b
# layer_activations.append((conv1, 28*28*6))
# conv1 = tf.nn.relu(conv1)
# with tf.variable_scope('pool1'):
# pool_1 = tf.nn.max_pool(conv1, ksize=[1,2,2,1], strides=[1,2,2,1], padding='VALID')
# with tf.variable_scope('conv2')... | Python | 1 |
ber_of_words_per_batch)):
batch = ''
words_count = 0
while words_count < number_of_words_per_batch:
batch += raw_text[letter_id]
if raw_text[letter_id] == ' ':
words_count += 1
letter_id += 1
list_of_batc... | Python | 1 |
_Note: This conversion will lose precision due to the nature of floating point numbers._
pub fn as_secs_f64(&self) -> f64 {
self.seconds as f64 + self.subsecond_nanos as f64 / 1_000_000_000_f64
}
/// Creates a `DateTime` from an `f64` representing the number of seconds since the Unix epoch.
//... | Rust | 0 |
primitive_payload_value(&values, "null_field", false)
.expect_err("allow_missing=false: null value should return error");
super::get_primitive_payload_value(&values, "missing", false)
.expect_err("allow_missing=false: missing field should return error");
assert_eq!(
... | Rust | 0 |
from pydantic import BaseModel
from utils import Validation, get_app_logger, CmdExec
from functions import Functions
# Function Metadata
metadata = {
"name": "func_net_scan_nmap_ping_sweep",
"version": "1.0.0",
"description": "Perform a ping sweep using nmap on a specified network to identify live hosts."... | Python | 1 |
import pandas as pd
teams = ['Brazil', 'England', 'France', 'Italy', 'Spain', 'Uruguay', 'West Germany', 'Germany', 'Argentina']
wins = [5, 1, 2, 4, 1, 2, 3, 1, 3]
stats = list(zip(teams,wins))
df = pd.DataFrame(stats, columns=['Team', 'Wins'])
df.index.name = 'Index'
# Add a column for year of first win.
df['YearF... | Python | 1 |
> 7;
let x71 = x7 & U8(0x01u8);
let x711b = x71 * U8(0x1bu8);
x1 ^ x711b
}
fn mix_column(c: usize, state: Block) -> Block {
let i0 = 4 * c;
let s0 = state[i0];
let s1 = state[i0 + 1];
let s2 = state[i0 + 2];
let s3 = state[i0 + 3];
let mut st = state;
let tmp = s0 ^ s1 ^ s2 ^ s3... | Rust | 0 |
import torch
from .resnet18_32x32 import ResNet18_32x32
class ResNet18_256x256_Ensemble(torch.nn.Module):
def __init__(self, num_classes=10, num_models=5, discriminator_cls=None):
super(ResNet18_256x256_Ensemble, self).__init__()
self.nets = torch.nn.ModuleList([ResNet18_32x32(num_classes=num_clas... | Python | 1 |
import glob
from langchain_community.document_loaders import PyPDFLoader
"""Write code here to handle pdfs""" | Python | 1 |
self.i += 1;
self.inner.next()
}
}
impl<It: Iterator> ExactSizeIterator for PTIter<It> {}
<reponame>metajack/diem
use crate::stackless_bytecode::StacklessBytecode;
use vm::{
access::ModuleAccess,
file_format::{
Bytecode, CompiledModule, FieldDefinitionIndex, FunctionDefinition, Sign... | Rust | 0 |
Err(e) => {
Err(Error::custom(e.to_string()))
},
}
},
None => {
Err(Error::custom("missing \"admiral\" section".to_string()))
},
... | Rust | 0 |
_scopes).await
}
use sprout_therapy_assignment::config::routes::app_routes;
use sprout_therapy_assignment::schema::{Response, Request, LogicalPath};
use actix_web::{http::StatusCode, test, App};
use actix_service::Service;
use bytes::Bytes;
#[actix_rt::test]
async fn h_is_m() {
let mut app =
test::init_se... | Rust | 0 |
er {
u4::new(((encoded_instruction & 0x0000f000) >> 12) as u8)
}
const EQUAL_CONDITION: u8 = 0x0;
const NOT_EQUAL_CONDITION: u8 = 0x1;
const CARRY_SET_CONDITION: u8 = 0x2;
const CARRY_CLEAR_CONDITION: u8 = 0x3;
const NEGATIVE_CONDITION: u8 = 0x4;
const POSITIVE_CONDITION: u8 = 0x5;
const OVERFLOW_CONDITION: u8 = 0... | Rust | 0 |
import torch
from .rank_filter import rank_filter
def load_model_weight(model, checkpoint, logger):
state_dict = checkpoint['state_dict']
# strip prefix of state_dict
if list(state_dict.keys())[0].startswith('module.'):
state_dict = {k[7:]: v for k, v in checkpoint['state_dict'].items()}
model... | Python | 1 |
ngOrigin: FXMVECTOR,
ScalingOrientation: f32,
Scaling: FXMVECTOR,
RotationOrigin: FXMVECTOR,
Rotation: f32,
Translation: GXMVECTOR
) -> XMMATRIX
{
unsafe {
// M = Inverse(MScalingOrigin) * Transpose(MScalingOrientation) * MScaling * MScalingOrientation *
// MScalingOrigin... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.