text string | label_name string | labels int64 |
|---|---|---|
from unittest.mock import patch
from corehq.apps.es.transient_util import doc_adapter_from_index_name
from corehq.util.es.elasticsearch import TransportError
from pillowtop.checkpoints.manager import PillowCheckpoint
from pillowtop.pillow import interface
TEST_ES_MAPPING = {
'_meta': {
'comment': 'You k... | Python | 1 |
= cls_name.split(" - ")[0]
manu_idx = manufacturer_to_idx[manu]
target_tensor[cls_idx].copy_(manufacturer_prompts[manu_idx])
else:
target_tensor.copy_(source_tensor)
print("Turning off gradients in both the image and the text encoder")
name_t... | Python | 1 |
.x, bbox.min.y + scale.1 as i32).map(|x| x as u32);
let padding = self.padding;
let mut cache = FontCache::new(scale.1);
glyph.draw(|x, y, alpha| {
let (x, y) = (x, y).add(offset).sub(start_t);
let alpha = trunca... | Rust | 0 |
void main(void) {
vec2 texcoord = f_texcoord;
float KX[9];
KX[0] = 1.0; KX[1] = 0.0; KX[2] = -1.0;
KX[3] = 2.0; KX[4] = 0.0; KX[5] = -2.0;
KX[6] = 1.0; KX[7] = 0.0; KX[8] = -1.0;
float gx = 0.0;
for (int i = -1; i < 2; ++i) {
for (int j = -1; j < 2... | Rust | 0 |
# Copyright 2016 Julien Danjou
# Copyright 2016 Joshua Harlow
# Copyright 2013-2014 Ray Holder
#
# 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
#... | Python | 1 |
'mutex, T>, TimedOut)
{
let timed_out = self.inner().wait_timeout(guard.0.mutex.get(), duration);
(guard, timed_out)
}
/// Wakes up one blocked thread on this condition variable.
///
/// If there is a blocked thread on this condition variable, then it will
/// be woken up from its call to [`wait`] ... | Rust | 0 |
details = [
{"name": "Anirudh", "age": 98, "gender": "Male"}, # <--x | x["age"]
{"name": "Pratik", "age": 18, "gender": "Male"},
{"name": "Muskan", "age": 32, "gender": "Female"},
{"name": "Nihar", "age": 54, "gender": "Male"},
]
"""
Name = Anirudh, Age = 98, Gender = Male
"""
new_Details = sorted(deta... | Python | 1 |
counts = {} # create new empty dict
with open("../DATA/breakfast.txt") as breakfast_in:
for line in breakfast_in:
breakfast_item = line.rstrip()
if breakfast_item in counts: # check to see if current item in dict
counts[breakfast_item] = counts[breakfast_item] + 1 # if so, incremen... | Python | 1 |
lf, &x, &y)
}
})
}
num_ops! {"int", op_int, isize, Int, |x, y| x == y}
num_ops! {"real", op_real, f64, Real, |x: f64, y: f64| (x - y).abs() < f64::EPSILON }
fn op_bool(&self, x: bool, y: bool) -> Value {
use Op::*;
use Value::*;
match self {
Or ... | Rust | 0 |
_eq!(v.as_ref(), Some(expected_v));
}
// Make sure that merged overlay iterator works.
let it = overlay.iter(Context::background());
test_iterator_with(&items, it, &tests);
// Commit the overlay.
overlay.commit(Context::background()).unwrap();
// Test that all ... | Rust | 0 |
te, goal, gt_crystals, ganon_crystals);
if dungeon_items != "Standard " {
game_string.push_str(dungeon_items);
}
if shuffle != "Vanilla Shuffle " {
game_string.push_str(shuffle);
}
if logic != "No Glitches " {
game_string.push_str(logic);
... | Rust | 0 |
pub fn set_message(&mut self, message: Message<'m>) {
self.message = message;
}
pub fn current_handler_key(&self) -> &'c str {
if let Some(handler_key) = self.current_handler {
handler_key
} else {
panic!("Calls to handler_key are only allowed within a runn... | Rust | 0 |
-child option').dblclick()
expect(select_right.locator('optgroup')).to_have_count(1)
expect(select_right.locator('option')).to_have_count(5)
expected = [select_right.locator(f'optgroup option:nth-child({i})').get_attribute('value') for i in range(1, 6)]
assert selector.evaluate('elem => Array.from(elem.... | Python | 1 |
&self,
request: &AstroEventRequest,
) -> Result<Result<AstronomyResponse, ApiError>, Error> {
self.call::<AstroEventService>(request).await
}
#[maybe_async]
/// The *Astro Position* service can be used to retrieve the altitude, azimuth and distance to
/// the Moon and the Su... | Rust | 0 |
is [***separator***](https://w3c.github.io/aria/#separator).
///
/// Other permitted roles are [***presentation***](https://w3c.github.io/aria/#presentation)
/// and [***none***](https://w3c.github.io/aria/#none).
///
/// # Styling
///
/// Browsers will likely still display an unspecified line by d... | Rust | 0 |
message = render_system_message()
human_message = render_human_message(info)
history = ''
trajectories.append((step, human_message, ''))
history += human_message + '\n'
reward_seq.append(env.info['all_reward'])
score_seq.append(env.info['score'])
logger.info(syste... | Python | 1 |
pe[-2:]
skip_connections = []
for i, layer in enumerate(self.base):
x = layer(x)
if i in self.shortcut_layers:
skip_connections.append(x)
out = x
for i in range(self.n_blocks):
skip = skip_connections.pop()
out = F.interpo... | Python | 1 |
g" in out) == show_msg
assert ("bye" in err) == show_msg
def test_hy2py_stdin():
out, _ = run_cmd("hy2py", "(+ 482 223)")
assert "482 + 223" in out
assert "705" not in out
def test_hy2py_compile_only(monkeypatch):
def check(args):
output, _ = run_cmd(f"hy2py {args}")
asse... | Python | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import rospy
from std_msgs.msg import Float64
from sensor_msgs.msg import Image
import numpy as np
import cv2
from cv_bridge import CvBridge
class DepthSubscriber:
def __init__(self):
rospy.init_node('depth_subscriber', anonymous=True)
self.bridge = Cv... | Python | 1 |
tually usable as AF_INET so must be unknown type".to_string()));
}
},
AF_INET6 => match addr.as_inet6() {
Some(a) => {
socket
.join_multicast_v6(a.ip(), 0)
.chain_err(|| "Failed to join IPv6 multicast")?;
}
... | Rust | 0 |
import os
from dotenv import load_dotenv
import streamlit as st
from groq import Groq
# Load environment variables from .env file
load_dotenv()
model="gemma2-9b-it"
#"llama-3.1-8b-instant", "llama-3.1-70b-versatile", "gemma-7b-it", "gemma2-9b-it"
# Get the API key from environment variables
GROQ_API_KEY = os.getenv(... | Python | 1 |
_ROM_BASE + 2 - 0x03);
}
#[test]
fn instruction_cmp() {
// Immediate, Flag behavior
let (mut cpu, mut nes) = new_test_cpu(vec![0xC9, 0x03]);
cpu.a = 4;
assert_eq!(cpu.execute_instruction(&mut nes), 2);
assert_eq!(cpu.read_flag(Flag::Carry), true);
assert_eq!(... | Rust | 0 |
import matplotlib.pyplot as plt
import numpy as np
# Helper functions
def get_colors(inp, colormap="viridis", normalize=True, vmin=None, vmax=None):
colormap = plt.cm.get_cmap(colormap)
if normalize:
vmin = np.min(inp)
vmax = np.max(inp)
norm = plt.Normalize(vmin, vmax)
return colorma... | Python | 1 |
// // what is stored there is depending on what will be written to BMP180_REGISTER_CTL
// // before reading common 0xf6 register
// // testing with I2C Mockup requires some trickery :)
// // test values are taken from BMP180 datasheet page 15 (Figure 4)
// fn make_dev(mut i2cdev: MockI2CDevice) -> B... | Rust | 0 |
# flake8: noqa
# To add a new coin
# 1. define a class in networks.py
# 2. add it to SUPPORTED
from .networks import *
SUPPORTED = {
'bitcoin_main': BitcoinMain,
'bitcoin_test': BitcoinTest,
'bitcoin_reg': BitcoinRegtest,
'litecoin_main': LitecoinMain,
'litecoin_test': LitecoinTest,
'litecoi... | Python | 1 |
import json
import bottle
@bottle.get("/text")
def text():
return "Returning text"
@bottle.get("/data/get")
def get_data():
try:
position = bottle.request.params["position"]
except:
return {
"result": "error-bad-data"
}
return {
"result": "",
"d... | Python | 1 |
sistant, entity_id, "should_expose", should_expose
)
@callback
def async_should_expose(hass: HomeAssistant, assistant: str, entity_id: str) -> bool:
"""Return True if an entity should be exposed to an assistant."""
exposed_entities: ExposedEntities = hass.data[DATA_EXPOSED_ENTITIES]
return exposed_ent... | Python | 1 |
"""
Tests the spatial transformer network code
"""
from __future__ import print_function
import torch
import numpy as np
import torch.nn as nn
from torch.autograd import Variable
import utils
import time
from modules.stn import STN
from modules.gridgen import AffineGridGen, CylinderGridGen, CylinderGridGenV2, Dens... | Python | 1 |
src.clone());
let vec_of_vec_clone = vec_of_vec.clone();
assert_eq!(21., vec_of_vec.get(1)?.get(0)?.y);
assert_eq!(21., vec_of_vec_clone.get(1)?.get(0)?.y);
vec_of_vec.set(1, VectorOfPoint2f::from_iter(vec![Point2f::new(40., 41.), Point2f::new(42., 43.)]));
assert_eq!(41., vec_of_vec.get(1)?.get(0)?.y);
ass... | Rust | 0 |
import tkinter as tk
def calculate():
try:
result = eval(display.get())
display.delete(0, tk.END)
display.insert(tk.END, result)
except Exception as e:
display.delete(0, tk.END)
display.insert(tk.END, "Error")
def clear():
display.delete(0, tk.END)
root = tk.Tk()
r... | Python | 1 |
!(payload.user_id, 0);
assert_eq!(payload.algorithm, "HMAC-SHA256");
assert_eq!(payload.issued_at.timestamp(), 1634206592);
}
Err(err) => panic!("{}", err),
}
}
}
/*
* Copyright (c) 2021 Works Applications Co., Ltd.
*
* Licensed under the Apache Lic... | Rust | 0 |
ot::init::PropertyUsage::DEFAULT,
});
builder.add_property(godot::init::Property {
name: "test/test_flags",
default: 0,
hint: godot::init::PropertyHint::Flags {
values: &["A", "B", "C", "D"],
},
getter: |_: &RustTest| 0,
setter: (),
usage: godo... | Rust | 0 |
.post_mean_std_1d.
Args:
input_filemask (str): glob filemask of posterior mean and standard deviation output by
run_likelihoods.max_like_1d.
save_path (str, optional): Path to save figure to, if supplied. If not supplied, figure is displayed.
"""
# Load and co... | Python | 1 |
def deepview_model_provider():
args = get_args()
vocab_size = 32317
model_config = {'hidden_size': args.hidden_size, 'num_layers': args.
num_layers, 'dropout': args.dropout, 'batch_first': False,
'share_embedding': args.share_embedding}
model = GNMTWithLoss(GNMT(vocab_size=vocab_size, **... | Python | 1 |
time: float = 0.0
k1: float = 0.700000000000000
k2: float = 0.500000000000000
k3: float = 1.00000000000000
C: float = 1.00000000000000
S2: float = 0.0
S1: float = 0.00100000000000000
S3: float = 0.0
S4: float = 0.0
# Initial assignments
S1_conc = S1 / C
S2_conc = S2 / C
S3_conc = S3 / C
S4_conc = S4 / C
reaction1 = S1... | Python | 1 |
Failed to read line");
let num: usize = match num.trim().parse() {
Ok(num) => num,
Err(_) => panic!("Enter a number"),
};
let mut mythos = Mythos::init(num);
mythos.generate();
mythos
}
fn main() {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());
if a... | Rust | 0 |
and a merge are happening concurrently, access to this
// needs to be synchronized using `mutex` above.
data_file_id_gen: Arc<Mutex<util::FileIDGen>>,
clock: Arc<Mutex<ClockT>>,
merge_thread: Option<std::thread::JoinHandle<()>>,
merge_stopchan: Option<chan::Sender<()>>,
}
fn setup_bitrust(config: &Config) -... | Rust | 0 |
for_this_expr<'a>(node: &ThisExpr<'a>, parent: Node<'a>) {
unsafe {
let node_ptr = node as *const ThisExpr<'a> as *mut ThisExpr<'a>;
(*node_ptr).parent.replace(parent);
}
}
#[derive(Clone)]
pub struct ThrowStmt<'a> {
parent: Option<Node<'a>>,
pub inner: &'a swc_ast::ThrowStmt,
pub arg: Expr<'a>,
}
i... | Rust | 0 |
"""
wrapper implementation for schtasks.exe, windows task scheduler
docs: https://learn.microsoft.com/en-us/windows/win32/taskschd/schtasks
"""
import os.path
import subprocess
def create_task(name, frequency, command):
"""
Creates a TaskScheduler task with the given parameters.
:param name:
:param f... | Python | 1 |
E
pub const NARROW_ASCII_LATIN_UPPER_CASE_E: u32 = 0x0045;
/// 半角 ASCII文字 アルファベット大文字 F
pub const NARROW_ASCII_LATIN_UPPER_CASE_F: u32 = 0x0046;
/// 半角 ASCII文字 アルファベット大文字 G
pub const NARROW_ASCII_LATIN_UPPER_CASE_G: u32 = 0x0047;
/// 半角 ASCII文字 アルファベット大文字 H
pub const NARROW_ASCII_LATIN_UPPER_CASE_H: u32 = 0x0048;... | Rust | 0 |
);
}
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_dinic() {
let mut graph = Dinic::new(5, 5);
graph.add_edge(0, 1, 3);
graph.add_edge(1, 2, 2);
graph.add_edge(1, 3, 2);
graph.add_edge(2, 4, 2);
graph.add_edge(3, 4, 2);
... | Rust | 0 |
from collections.abc import Callable, Generator
from typing import Any
from unittest.mock import AsyncMock, Mock
import pytest
from faker import Faker
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import sessionmaker
f... | Python | 1 |
from __future__ import annotations
def check_polygon(nums: list[float]) -> bool:
"""
Takes list of possible side lengths and determines whether a
two-dimensional polygon with such side lengths can exist.
Returns a boolean value for the < comparison
of the largest side length with sum of the rest.... | Python | 1 |
# Filter by team context if specified and deduplicate
filtered_docs = []
seen_content = set()
for doc in docs:
if (team_context is None or doc.metadata.get('team_context') == team_context) and doc.page_content not in seen_content:
filtered_docs.append({
... | Python | 1 |
import torch
import torch.nn as nn
class Conv(nn.Module):
"""Standard convolution layer."""
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, groups=1):
super(Conv, self).__init__()
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding=kernel_size... | Python | 1 |
[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
SLV_RX_SEG_TRANS_CLR_EN_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for SLV_RX_SEG_TRANS_CLR_EN_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}... | Rust | 0 |
reader.read(count).unwrap();
}
fn read_performance_custom_format(buffer: &mut dyn PointBufferWriteable, path: &str) {
buffer.clear();
let mut reader = LASReader::from_path(path).unwrap();
let count = reader.remaining_points();
reader.read_into(buffer, count).unwrap();
}
fn write_performance(points... | Rust | 0 |
mm_xmm_xmmm128
0x03,// HasVPrefix, SameAsPrev
// VEX_Vaesdec_ymm_ymm_ymmm256
0x03,// HasVPrefix, SameAsPrev
// EVEX_Vaesdec_xmm_xmm_xmmm128
0x03,// HasVPrefix, SameAsPrev
// EVEX_Vaesdec_ymm_ymm_ymmm256
0x03,// HasVPrefix, SameAsPrev
// EVEX_Vaesdec_zmm_zmm_zmmm512
0x03,// HasVPrefix, SameAsPrev
// Aesde... | Rust | 0 |
#!/usr/bin/python
"""Generate Abseil compile compile option configs.
Usage: <path_to_absl>/copts/generate_copts.py
The configs are generated from copts.py.
"""
from os import path
import sys
from copts import COPT_VARS
# Helper functions
def file_header_lines():
return [
"GENERATED! DO NOT MANUALLY EDIT TH... | Python | 1 |
import jax
import jax.numpy as jnp
from exceptions.invalid_argument_exception import InvalidArgumentException
from functions.abstracts.compilable_function import CompilableFunction
class NewtonInterpolant(CompilableFunction):
"""
TODO
"""
###############################
### Attributes of instance... | Python | 1 |
(self, self.move_id.currency_id)
valuation_price_unit = valuation_price_unit_total / valuation_total_qty
valuation_price_unit = self.product_id.uom_id._compute_price(valuation_price_unit, self.product_uom_id)
else:
# Valuation_price unit is always expressed in invoice currenc... | Python | 1 |
"""This client shows workbench extacting files from a zip file."""
import zerorpc
import os
import pprint
import client_helper
def run():
"""This client shows workbench extacting files from a zip file."""
# Grab server args
args = client_helper.grab_server_args()
# Start up workbench connection
... | Python | 1 |
test(), reason="Skip because BNNS codegen is not available")
def test_conv2d_dw():
if skip_runtime_test():
return
np.random.seed(0)
shape = [4, 5, 5]
for batch in [1, 2]:
mod, params = _get_model(shape=(batch, *shape), groups=shape[0])
compare_inference_with_ref(mod, params)
... | Python | 1 |
nNode;
impl PlanNode {
pub fn display_indent_format(&self) -> impl fmt::Display + '_ {
PlanNodeIndentFormatDisplay::create(0, self, false)
}
pub fn display_graphviz(&self) -> impl fmt::Display + '_ {
struct Wrapper<'a>(&'a PlanNode);
impl<'a> fmt::Display for Wrapper<'a> {
... | Rust | 0 |
import os
import subprocess
from urllib.parse import urlparse
# Configuration
domain = "api.deriv.com"
output_dir = "output"
threads = "10"
# Ensure the output directory exists
os.makedirs(output_dir, exist_ok=True)
def run_subdomain_enumeration():
command = f"subfinder -d {domain} -o {os.path.join(output_dir, '... | Python | 1 |
s a compiler intrinsic function.
Intrinsic(Intrinsic),
}
/// A function / procedure / builtin operator, which is called with function call style.
#[derive(Clone, Debug, DeepSizeOf)]
#[allow(variant_size_differences)]
pub enum Operator {
/// A user procedure, with a link to the procedure definition and the typechec... | Rust | 0 |
"""Let's see the following example. We have a list of guests, we want to extract each guest's name from a new row."""
mehmonlar = ['Ali','Vali','Hasan', 'Husan','Olim']
for mehmon in mehmonlar:
print(mehmon)
"""For method is help to us write code more easier and fast """
mehmonlar = ['Ali','Vali','Hasan', 'Husa... | Python | 1 |
evice)
y_pred = torch.empty(0).to(device)
with torch.no_grad():
for i, data in enumerate(dloader, 0):
x_categ, x_cont, y_gts, cat_mask, con_mask = data[0].to(device), data[1].to(device),data[2].to(device),data[3].to(device),data[4].to(device)
_ , x_categ_enc, x_cont_enc = embed_d... | Python | 1 |
#!/usr/bin/python3
for c in range(97, 123):
print("{}".format(chr(c)), end='')
| Python | 1 |
render_dot_texinfo(self, node, dotcode, {}, 'inheritance')
raise nodes.SkipNode
def skip(self: nodes.NodeVisitor, node: inheritance_diagram) -> None:
raise nodes.SkipNode
def setup(app: Sphinx) -> ExtensionMetadata:
app.setup_extension('sphinx.ext.graphviz')
app.add_node(
inheritance_diagr... | Python | 1 |
let edges = vec_vec_i32![[0, 1], [0, 2], [1, 4], [1, 5], [2, 3], [2, 6]];
let has_apple = vec![false, false, true, false, false, true, false];
let res = 6;
assert_eq!(Solution::min_time(n, edges, has_apple), res);
let n = 7;
let edges = vec_vec_i32![[0, 1], [0, 2], [1, 4], [1, 5], [2, 3], [2, 6]... | Rust | 0 |
", hash);
let to_hash = format!("{:?}{:?}", hash, register.row.unwrap());
println!("{:?}", &to_hash.clone());
hash = seahash::hash(to_hash.as_bytes());
println!("{:0x}", hash);
let to_hash = format!("{:?}{:?}", hash, register.column.unwrap());
println!("{:?}", &to_hash.clone());
hash = seahash::hash(to_... | Rust | 0 |
::None,
};
let is_japanese = data[0x4a] == 0;
let old_licensee_code = data[0x4b];
let mask_rom_version_number = data[0x4c];
let header_checksum = data[0x4d];
let mut checksum: usize = 0;
for b in data[0x34..0x4d].iter() {
checksum = checksum.wrappin... | Rust | 0 |
end_ts: req.get_end_version().into(),
backend: req.get_storage_backend().clone(),
limiter,
cancel: cancel.clone(),
is_raw_kv: req.get_is_raw_kv(),
cf,
compression_type: req.get_compression_type(),
compression... | Rust | 0 |
ion')
H = np.array([[np.cos(theta), -np.sin(theta), tx ],
[np.sin(theta), np.cos(theta), ty ],
[0.0, 0.0, 1.0]])
# print(H)
verts_list = ibs.get_annot_rotated_verts(aid_list)
... | Python | 1 |
(Debug, thiserror::Error)]
pub enum Error {
#[error(transparent)]
Io(#[from] std::io::Error),
}
impl Serialize for Error {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.to_string().as_ref())
}
}
#[derive(Serialize... | Rust | 0 |
ory[expected.txn_hash]
assert actual.txn_hash == expected.txn_hash
assert actual.sender == expected.sender
assert actual.receiver == expected.receiver
def test_history_getitem_account(chain, vyper_contract_instance, owner):
actual = chain.history[owner.address]
assert isinstance(actual, AccountHis... | Python | 1 |
nt_number + 1 {
break;
}
match c.block_header(BlockId::Hash(last_parent_hash)) {
None => {
return Err(BlockError::UnknownParent(last_parent_hash))?;
}
Some(next) => {
chain.push_front(next.decode()?);
}
}
}
// Get the state for last checkpoint.
let... | Rust | 0 |
V4, // [Ⲽ]
N_PARTITIONS,
}
#[derive(Copy, Clone, Debug, PartialEq, FromPrimitive)]
#[repr(C)]
pub enum BlockSize {
BS_128x128,
BS_128x64,
BS_64x128,
BS_64x64,
BS_64x32,
BS_64x16,
BS_32x64,
BS_32x32,
BS_32x16,
BS_32x8,
BS_16x64,
BS_16x32,
BS_16x16,
... | Rust | 0 |
// impl Actor for MyActor {
// type Context = Context<Self>;
// fn started(&mut self, _ctx: &mut Context<Self>) {
// println!("Actor is alive");
// }
// fn stopped(&mut self, _ctx: &mut Context<Self>) {
// println!("Actor is stopped");
// }
// }
// /// Define handler for `Message... | Rust | 0 |
ng value for connection_type!")
if (
flash_options.flash_method == FlashMethod.SD_CARD
and not flash_options.selected_board
):
raise Exception("Missing value for selected_board!")
if flash_options.flash_method is FlashMethod.REGULAR:
cmd = [
... | Python | 1 |
#[cfg(feature = "thread_safe")] std::sync::Mutex<T>,
#[cfg(not(feature = "thread_safe"))] std::cell::RefCell<T>,
);
struct LockGuard<'a, T>(
#[cfg(feature = "thread_safe")] std::sync::MutexGuard<'a, T>,
#[cfg(not(feature = "thread_safe"))] std::cell::Ref<'a, T>,
);
impl<'a, T> Deref for LockGuard<'a, T> ... | Rust | 0 |
navigation documents...")
# processed_nav_docs = []
# for doc in nav_docs:
# processed_doc = self.document_processor.process_document(doc)
# processed_nav_docs.append(processed_doc)
# stats['processed_nav_docs'] = len(processed_nav_docs)
... | Python | 1 |
in valid points that have all-zero coordinates
pcd: open3d pcd objective
"""
pcd_np = np.asarray(pcd.points) # <Nx3>
non_zero_coord = np.abs(pcd_np) > 1e-6 # <Nx3>
valid_ind = np.sum(non_zero_coord,axis=-1)>0 #<N>
valid_ind = list(np.nonzero(valid_ind)[0])
valid_pcd = o3d.geometry.select_dow... | Python | 1 |
Option<u64>,
) -> Result<()> {
let mut should_loop = false;
for dir in dirs {
if dir.url.is_some() {
should_loop = true;
break;
}
}
if !should_loop {
debug!("not syncing as SyncDirs do not have remote URLs");
return Ok(());
}
let delay_sec... | Rust | 0 |
1Cm1bb6uZsjfKNlJgRlXAXYaItKlcqVr71SUgp1AR-fPAF2yBudTCstlywGlR4ySwk-rg0A")#sua chave de API
# 2. ID do seu assistente
assistant_id = "asst_2p6V02GJAdCt" #seu assistente
# --- Input para o conteúdo da mensagem com as informações para o agente fazer as buscas ---
user_question = input("Por favor, digite a sua pergunta p... | Python | 1 |
r) = row {
if r != other.row {
row = None;
}
}
if let Some(c) = col {
if c != other.col {
col = None;
}
}
}
if let Some(... | Rust | 0 |
_by(32) {
// byte shift left 1
state = _mm256_add_epi8(state, state);
let input = _mm256_loadu_si256(input.as_ptr().add(i).cast());
let input = _mm256_xor_si256(
input,
_mm256_and_si256(_mm256_srli_si256(input, 5), shift_mask),
... | Rust | 0 |
es | QMessageBox.StandardButton.No,
QMessageBox.StandardButton.No
)
if reply == QMessageBox.StandardButton.Yes:
# 从后往前删除,避免索引变化
for row in sorted(selected_rows, reverse=True):
self.rules_table.removeRow(row)
# 更新预览
... | Python | 1 |
"),
("(guint) GST_PAD_PROBE_TYPE_PULL", "8192"),
("(guint) GST_PAD_PROBE_TYPE_PUSH", "4096"),
("(guint) GST_PAD_PROBE_TYPE_QUERY_BOTH", "1536"),
("(guint) GST_PAD_PROBE_TYPE_QUERY_DOWNSTREAM", "512"),
("(guint) GST_PAD_PROBE_TYPE_QUERY_UPSTREAM", "1024"),
("(guint) GST_PAD_PROBE_TYPE_SCHEDULING"... | Rust | 0 |
"""
Monkey-patch for DSPy's sync_send_to_stream function.
The original DSPy implementation blocks the event loop with future.result(),
causing deadlocks when using MCP tools with dashboard streaming.
This patch replaces it with a non-blocking fire-and-forget approach.
"""
import asyncio
import logging
logger = log... | Python | 1 |
o
cg: @ s d dl mZ ejZdS ) )zosN)compilers.Cr CompilerzOSCCompiler r r qC:\Users\devid\Desktop\Daily-Practice\Attendance App\venv\lib\site-packages\setuptools\_distutils\zosccompiler.py<module> s
| Python | 1 |
ss}} *
Dummy${sim_object}Shunt<${{sim_object.cxx_class}}>::Params::create() const
{
return Dummy${sim_object}Shunt<${{sim_object.cxx_class}}>::create(*this);
}
} // namespace gem5
"""
)
if not sim_object.override_create:
code(
"""
namespace gem5
{
namespace ${{sim_obje... | Python | 1 |
lu1, kernel=(3, 3), stride=(2, 2), pool_type='max', \
pooling_convention='full', name='pool1')
conv2 = mx.sym.Convolution(data=pool1, kernel=(3, 3), num_filter=100, num_group=5, name='conv2')
prelu2 = mx.sym.LeakyReLU(data=conv2, act_type='prelu', name='prelu2')
pool2 = mx.sym.Poo... | Python | 1 |
_access_token,
spotify_ids,
|res: SpotifyBatchArtistsResponse| Ok(res.artists),
)
.await?;
for artist in &mut entities {
if let Some(images) = artist.images.as_mut() {
while images.len() > 1 {
images.pop();
}
}
}
Ok(entities)
... | Rust | 0 |
_ => env.type_error("Type error in m[key]: m is not a map.")
}
}
enum Space {
None, Left(usize), Center(usize), Right(usize)
}
struct Float {
fmt: char,
precision: Option<usize>
}
enum FmtType {
None, Int(char), Float(Float)
}
struct Fmt {
space: Space, fmt_type: FmtType, sign: bool, fill: c... | Rust | 0 |
--
# SAMPLING
# -------------------------------------------------------------------------------------------------
@pytest.mark.flaky(max_runs=3, min_passes=1)
def test_sample_normal_spherical():
mean = torch.tensor([1.5, 3.5])
covar = torch.tensor(4.0)
target_covar = torch.tensor([[4.0, 0.0], [0.0, 4.0]])... | Python | 1 |
let mut buffer = Vec::new();
let encoder = TextEncoder::new();
// Gather the metrics.
let metric_families = prometheus::gather();
// Encode them to send.
encoder.encode(&metric_families, &mut buffer).unwrap();
Bytes::from(buffer)
}
fn main() -> std::io::Result<()> {
// Read sensor eagerly... | Rust | 0 |
L\x19\xe5 \xf8')\x8f\xef\xb3\
\x94\x15\xc0\xff\x97\xf2\xd8\x98\xc28\xab9\xf8\x9ey\x9d\
t\xf3v\xe7\x99\xc6\x02v-\xbb\xd7\xcf\xddy\xcf*\
\xe3~\xfd<\xce\xb8\xeb\x07\x1ew\x94y\xbd\xb1\x05h\
\x9bES\x98\x86EJ\x13\xeb\x5c\xb4\x1a\xf6'\xc3\xea\
\x16\x5c\xb4|\x7f\xd7)\xdd\xb3\x7fM\x09\xd7\xa6\xe4~\
\xf0\x7f\x91\xf2\xef\xb4!\xcd... | Python | 1 |
: "Player".to_string(),
holdable: false,
color: "green".to_string(),
print_colored: '@'.to_string().color("green"),
paired_item: "".to_string(),
score: 0,
id: 20,
};
// Repositioning
player.reposition_item(2, 2);
as... | Rust | 0 |
0], gt_mask[0]
intersection = np.sum(pred_mask * gt_mask)
pred_sum = np.sum(pred_mask)
gt_sum = np.sum(gt_mask)
# 计算 Dice 系数
if pred_sum + gt_sum == 0:
return 1.0
return 2.0 * intersection / (pred_sum + gt_sum)
def compute_mean_dice(pred_masks, gt_masks):
# 计算预测掩码和真实掩码之间的平均 Dice ... | Python | 1 |
"resume_cron": self._resume_cron,
"op_site_ids": self._op_site_ids,
"exclude_dirs": self._exclude_dirs,
}
)
# 启动任务
if self._scheduler.get_jobs():
self._scheduler.print_jobs()
s... | Python | 1 |
ub fn init() {
sodiumoxide::init().unwrap();
}
pub fn base_path() -> std::path::PathBuf {
std::env::var("DATGRUNCH2_DIR")
.unwrap_or_else(|_| ".".to_string())
.into()
}
pub fn prepare_base_path(base_path: &Path) -> io::Result<()> {
fn create_dir2e(path: &Path) -> io::Result<()> {
s... | Rust | 0 |
nit)
Ux = math_ops.matmul(inputs, U)
U_cx, U_rx, U_gx = array_ops.split(Ux, 3, axis=1)
W_r = vs.get_variable(
"W_r", [self._hidden_size, self._hidden_size], dtype=tf.float32, initializer=U_init)
W_g = vs.get_variable(
"W_g", [self._hidden_... | Python | 1 |
_axes.len()];
for cube in new_data.iter_mut() {
self.get_src_pos(&dest_pos, &mut src_pos);
self.get_range(&dest_pos, &mut start, &mut end);
let (current_cube, active_count) =
self.check_neighbors(&src_pos, &start, &end, &mut scratch_pos);
*cube ... | Rust | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 28 00:25:58 2021
@author: A.Goumilevski
"""
import os
working_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),"../../.."))
os.chdir(working_dir)
#from snowdrop.src.utils.util import simulationRange
ESTIMATE = False
if __name__ == '_... | Python | 1 |
let receiver_ephemeral_keys = (0..num_receivers.get())
.map(|dealer_index| {
Some(ephemeral_key_set_from_tuple(create_ephemeral(
&mut rng,
dkg_id,
&dealer_index.to_be_bytes()[..],
)))
})
.... | Rust | 0 |
.minimize(), $b.minimize()));
}
macro_rules! assert_not_equiv {
($a: expr, $b: expr) => (assert!(!$a.equiv(&$b)));
}
#[test]
fn test_dfa_minimize() {
assert_eq!(dfa! {
9;
0, 'a', 2;
0, 'b', 3;
0;
1, 'a', 1;
1, 'b', 1;
2, 'a', 4;
2, 'b', 5;
... | Rust | 0 |
return GenericFeatures.collectFeatures(vcfname, tag, features, processor=StrelkaAdmixIndelFeatures.processValue)
FeatureSet.register("hcc.varscan2.indel", Varscan2HCCIndelFeatures)
class PiscesHCCSNVFeatures(StrelkaAdmixSNVFeatures):
""" Collect SNV features from Pisces-to-HCC truthset comparison """
d... | Python | 1 |
in_program, FLAGS):
"""
init model params in run_server: pserver
#worker no need init params
"""
return
def train(self, FLAGS, net_output):
"""
start training
"""
fleet.init_worker()
super(PaddleCloudFleetTrainer, self).train(... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.