text string | label_name string | labels int64 |
|---|---|---|
_x, axis=-1, keepdims = True)
kps_xz = key2eye - camera_y* np.sum(key2eye*camera_y, axis=-1, keepdims = True)
cos_y_z = np.sum(kps_yz*camera_z, axis=-1)
cos_x_z = np.sum(kps_xz*camera_z, axis=-1)
cos_fov = np.cos(camera_fov*0.5/180 * math.pi)
bone_mask = (cos_y_z >= cos_fov*np.... | Python | 1 |
.16.58.3 is multicast
/// assert!(ip.is_multicast());
/// // 240.0.0.0 is not multicast
/// assert!(! (ip + 1).is_multicast());
/// # }
/// ```
pub fn is_multicast(self) -> bool {
(self.0 & 0xf000_0000) == 0xe000_0000
}
/// Return the address as an `u32`
///
///
/// ... | Rust | 0 |
ws = news_links.first
# Получаем текст ссылки (заголовок новости)
title = first_news.inner_text()
print(f"Открываем новость: {title}")
# Открываем новость в новой вкладке, удерживая клавишу Ctrl
# context.expect_page() создает объект ожидания для новой вкладки
# Внутри ... | Python | 1 |
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import poisson
def plot_poisson_distribution(lambda_val, k_range, title, xlabel, ylabel, filename):
poisson_pmf = poisson.pmf(k_range, lambda_val)
plt.figure()
plt.bar(k_range, poisson_pmf, edgecolor='k', alpha=0.7)
plt.title(title)
... | Python | 1 |
atch.FAST_InputFile = path_params['FAST_InputFile']
fastBatch.channels = channels
fastBatch.FAST_runDirectory = run_dir
fastBatch.case_list = case_list
fastBatch.case_name_list = case_name_list
fastBatch.debug_level = 2
fastBatch.FAST_exe = 'openfast'
fastBatch.run_serial(... | Python | 1 |
._channel_order_gci),
map_gci_list_to_names(band_ci_to_idx),
map_gci_list_to_names(gci_diff)))
# Initialize a matrix to read band image data into
# TODO: Handle when there are no bands?
band_dtype = gdal_arra... | Python | 1 |
# Conditional statements in python are used in a way like any other programming language.
# In general, there are three conditional statements in python if, elif, and else.
# if statement is the most widely used conditional statement.
# There could be one or more than one elif depending on the requirements. elif is use... | Python | 1 |
##################################################################
# For this example, ensure you have a valid GitHub PAT token set
# in the environment variables.
##################################################################
import os
from railtracks import MCPHttpParams, connect_mcp
import asyncio
import railtr... | Python | 1 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import transformers
class DefaultModel(nn.Module):
def __init__(self, plm_name, add_special_token):
super().__init__()
self.plm_name = plm_name
self.plm = transformers.AutoModelForSequenceClassification.from_pretrained(
... | Python | 1 |
es = []
val_losses = []
val_lev_distances = []
best_val_lev = float('inf')
epochs_no_improve = 0
model_name_tag = f"morse_cnn_se_proj_gru_mha_h{config.RNN_HIDDEN_SIZE}_refactored"
best_model_path = os.path.join(output_dir, f"best_{model_name_tag}_model.pth")
print(f"\n--- Starting Training:... | Python | 1 |
let path = entry.unwrap().path();
if path.is_dir() {
depth = max(depth, find_max_depth(&path) + 1);
}
}
depth
}
fn count_num_files(dir: &Path) -> usize {
let mut num_files = 0;
let mut queue = VecDeque::from([dir.to_path_buf()]);
while let Some(path) = queue.pop_... | Rust | 0 |
) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `MSM`"]
pub enum MSMW {
#[doc = "No action"]
NOSYNC,
#[doc = "The effect of an event on the trigger input (TRGI) is delayed to allow a perfect synchronization betwe... | Rust | 0 |
.org/registry/vulkan/specs/1.0-extensions/html/vkspec.html#VkDescriptorUpdateTemplateCreateInfoKHR)
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct VkDescriptorUpdateTemplateCreateInfoKHR {
pub sType: vk::VkStructureType,
pub pNext: *mut c_void,
pub flags: VkDescriptorUpdateTemplateCreateFlagsKHR,
p... | Rust | 0 |
s).unwrap();
let url = format!("/gifs/search?{}", query_);
self.client.get(&url, None).await
}
/**
* Translate phrase to GIF.
*
* This function performs a `GET` to the `/gifs/translate` endpoint.
*
* The translate API draws on search, but uses the GIPHY `special sauce`... | Rust | 0 |
h:
if tile <= 100 or tile is None:
tile = 0
print(f'img: {img}. version: {version}. scale: {scale}. face_enhance: {face_enhance}. tile: {tile}.')
try:
extension = os.path.splitext(os.path.basename(str(img)))[1]
img = cv2.imread(str(img), cv2.IMREAD_UNCHANGED)
... | Python | 1 |
model = models.ModifyNetworkAclQuintupleEntriesResponse()
model._deserialize(response["Response"])
return model
except Exception as e:
if isinstance(e, TencentCloudSDKException):
raise
else:
raise TencentCloudSDKException(t... | Python | 1 |
from django.shortcuts import render, get_object_or_404
from django.http import Http404
from django.views.generic import ListView, DetailView
from .models import Post
class PostsView(ListView):
queryset=Post.objects.all()
template_name='blog/posts.html'
context_object_name='posts'
class SinglePostView(D... | Python | 1 |
mean(e2test))
Etest.append(np.mean(e3test))
Etest.append(np.mean(e4test))
# plot the bias-variance trade-off graph
plt.figure(figsize=(8, 4))
plt.plot(com,Etest,label="Variance")
plt.plot(com,Etrain,label="Bias")
plt.xlabel('Complexity')
plt.ylabel('Error')
plt.title("Bias Variance TradeOff")
plt.figtext(0.5, 0.01, "T... | Python | 1 |
location(ecs, position.single_position(), attack.source, attack.damage);
ecs.delete_entity(entity).unwrap();
}
pub fn begin_charge(ecs: &mut World, entity: Entity, target: Point, damage: Damage, kind: WeaponKind) {
let initial_position = ecs.get_position(entity);
// This code does not correctly handle wide... | Rust | 0 |
_write
pub extern "C" fn ClosingSigned_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ClosingSignedDecodeErrorZ {
let res = crate::c_types::deserialize_obj(ser);
let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::ClosingSigned { inner: ... | Rust | 0 |
mut [u8]) -> io::Result<usize> {
self.get(queue)
.ok_or_else(|| Error::from(queue).into_io())?
.recv(datagram)
}
}
impl IntoIterator for Tun {
type Item = Queue;
type IntoIter = IntoIter<Queue>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.queues.in... | Rust | 0 |
_batches(
&self,
service_id: Option<&str>,
offset: i64,
limit: i64,
) -> Result<MfgBatchList, MfgBatchStoreError> {
MfgBatchStoreOperations::new(self.connection).list_mfg_batches(service_id, offset, limit)
}
fn update_mfg_batch(
&self,
mfg_batch_id: &... | Rust | 0 |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Kyoto University (Hirofumi Inaguma)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Map transcription to phone sequence with a lexicon."""
import argparse
import codecs
from distutils.util import strtobool
import re
from tqdm import tqdm... | Python | 1 |
ssert_eq!(ctx.counts["AADAT"], 1);
assert_eq!(ctx.no_feature, 1);
assert_eq!(ctx.ambiguous, 1);
assert_eq!(ctx.low_quality, 1);
assert_eq!(ctx.unmapped, 1);
assert_eq!(ctx.nonunique, 1);
}
}
<reponame>hgallagher1993/futures-rs
use {Async, Future, Poll};
use stream::Stream;
... | Rust | 0 |
from Tarefas.gerenciador_tarefas import GerenciadorTarefas
from Utils.utils import Utils
class Inicializar:
def __init__(self):
self.gerenciador = GerenciadorTarefas()
self.utils = Utils()
def exibir_menu(self):
while True:
print("\nGerenciador de Tarefas")
prin... | Python | 1 |
pl {
fn inner_ptr(&self) -> *mut FaissVectorTransform {
self.inner
}
}
pub type CenteringTransform = CenteringTransformImpl;
pub struct CenteringTransformImpl {
inner: *mut FaissCenteringTransform,
}
unsafe impl Send for CenteringTransformImpl {}
unsafe impl Sync for CenteringTransformImpl {}
im... | Rust | 0 |
binary=binary,
stochastic=stochastic,
H=H,
W_LR_scale=W_LR_scale,
nonlinearity=lasagne.nonlinearities.identity,
num_units=10)
mlp = lasagne.layers.BatchNormLayer(
mlp,
epsilon=epsilon,
... | Python | 1 |
#[fail(display = "Unable to get platform id list after {} seconds of waiting.", _0)]
GetPlatformIdsPlatformListUnavailable(u64),
#[fail(display = "`devices_max` can not be zero.")]
GetDeviceIdsDevicesMaxZero,
#[fail(display = "No devices specified.")]
CreateContextNoDevicesSpecified,
#[fail(... | Rust | 0 |
assert_eq!(process_int_code_with_input(&mut v, 8), Some(1));
}
#[test]
fn input_not_equal_to_8_immediate_mode() {
let mut v = vec![3, 3, 1108, -1, 8, 3, 4, 3, 99, -1, 8];
assert_eq!(process_int_code_with_input(&mut v, 9), Some(0));
}
#[test]
fn input_less_than_to_8_immedi... | Rust | 0 |
self, spi_baud_rate: u32, spi_mode: SpiMode, spi_lsb_first: bool) {
self.spi.rcc_busenr_spien.set_bit(); // SPI clock enable
self.spi.spi_cr2.store_reg(|r, v| {
r.errie().set(v); // error interrupt is enabled
r.frf().clear(v); // SPI Motorola mode
r.txdmaen().set(v); ... | Rust | 0 |
import numpy as np
import pytest
import psi4
pytestmark = [pytest.mark.psi, pytest.mark.api, pytest.mark.quick]
@pytest.fixture
def spaces():
h2o = psi4.geometry("""
O
H 1 1.0
H 1 1.0 2 101.5
symmetry c1
""")
rhf_e, wfn = psi4.energy('SCF/cc-pVDZ-f12', molecule=h2o, retur... | Python | 1 |
def direc_distan(direc,distan):
if direc == 1 : # 북
return [1,0,distan]
elif direc == 2 : # 남
return [2,sero,distan]
elif direc == 3 : # 서
return [3,distan,0]
elif direc == 4 : # 동
return [4,distan,garo]
garo, sero = map(int,input().split())
sto... | Python | 1 |
import os
import sys
import tkinter as tk
from PIL import Image, ImageTk
def load_asset(path):
base = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
assets = os.path.join(base, "assets")
return os.path.join(assets, path)
def load_image(path):
img = Image.open(path).convert("RGBA"... | Python | 1 |
expect_boolean("1 !=2", true);
expect_boolean("1< 2", true);
expect_boolean("1 >2", false);
expect_boolean("1 >2", false);
expect_boolean("1<2", true);
expect_boolean("1 >= 2", false);
expect_boolean("2 >=1", true);
expect_boolean("2>= 2", true);
expect_boolean("1 <= 2", true);
... | Rust | 0 |
import torch
from torch import nn
from einops import rearrange
from einops.layers.torch import Rearrange
def posemb_sincos_1d(patches, temperature=10000, dtype=torch.float32):
_, n, dim, device, dtype = *patches.shape, patches.device, patches.dtype
n = torch.arange(n, device=device)
assert (dim % 2) == ... | Python | 1 |
line: CcT,
pub c_cc: [CcT; NCCS],
pub c_ispeed: SpeedT,
pub c_ospeed: SpeedT,
}
<filename>examples/gtk-demo/src/main.rs
use std::env::args;
use gio::prelude::*;
use gtk::prelude::*;
use gtk::DrawingArea;
use cairo::Context;
use plotters::prelude::*;
fn build_ui(app: >k::Application) {
drawable(app,... | Rust | 0 |
imple-http-server. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/simple-http-server/master/COPYRIGHT. No part of simple-http-server, including this file, may be copied, modified, propagated, or distribute... | Rust | 0 |
rk_cell_bits!(wam.machine_st.heap[1]), pstr_loc_as_cell!(2));
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), pstr_offset_as_cell!(0));
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), fixnum_as_cell!(Fixnum::build_with(3)));
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), list_... | Rust | 0 |
import os
import multiprocessing
import tensorflow as tf
from absl import logging
def setup_gpu_threadpool(num_gpus):
cpu_count = multiprocessing.cpu_count()
logging.info('Logical CPU cores: %d' % cpu_count)
# Sets up thread pool for each GPU.
per_gpu_thread_count = 1
total_gpu_thread_count = pe... | Python | 1 |
self, resource: str) -> None:
# Load the worker from the same path as this file
resource_path = os.path.join(os.path.dirname(__file__), "pdf_js", resource)
with open(resource_path, "r") as f:
workerjs = f.read()
js_content = f"""
var PDFJS = window['pdfjs-dist/bu... | Python | 1 |
::new(0),
last_user_registration: Cell::new(0),
}
}
}
/// Implementation of Logger for LogPrinter.
///
/// You can implement any trait (even from other crates) on your types,
/// or your traits on any type from other crates.
impl Logger for LogPrinter {
fn log (&self, message: LogMessage) {... | Rust | 0 |
tend(positions.map(crate::Position));
mesh_builder.vertex(&scratch.positions);
}
if let Some(tex_coords) = reader.read_tex_coords(0) {
scratch.tex_coords.clear();
scratch
.tex_coords
.extend(tex_coords.into_u16().map(crate::TexCoords));
mesh_builder.verte... | Rust | 0 |
Buffer already exists use `get_buffer` or use a different key."
);
}
self.buffers.insert(name, buffer);
}
pub fn get_buffer<T: Into<String>>(&self, name: T) -> &wgpu::Buffer {
self.buffers.get(&name.into()).unwrap()
}
}
// Copyright (c) The Starcoin Core Contributors
// ... | Rust | 0 |
assert!(ip != Ipv4Addr::new(127, 0, 0, 1));
}
#[tokio::test]
async fn cloudflare_test() {
// Heads up: this test requires internet connectivity
let resolver = DnsResolver::create_cloudflare().await.unwrap();
let ip = resolver.ipv4_lookup("example.com.").await.unwrap();
... | Rust | 0 |
import os.path as osp
import zipfile
import pandas as pd
import torch_frame
class Dota2(torch_frame.data.Dataset):
r"""The `Dota2 Game Results
<https://archive.ics.uci.edu/dataset/367/dota2+games+results>`_
dataset. Dota2 is a popular moba game with two teams of 5 players.
At start of the game, each... | Python | 1 |
not create websocket" );
assert_eq!( URL, ws.url() );
Ok(())
}.boxed_local().compat()
}
// Verify protocols.
//
#[ wasm_bindgen_test(async) ]
//
pub fn no_protocols() -> impl Future01<Item = (), Error = JsValue>
{
let _ = console_log::init_with_level( Level::Trace );
info!( "starting test: no_protocols"... | Rust | 0 |
from openpyxl import Workbook
from datetime import datetime
# ایجاد یک شیء Workbook
wb = Workbook()
# انتخاب برگه فعال
ws = wb.active
ws.title = "تاریخ تولد"
# وارد کردن نام افراد و تاریخ تولد آنها
people = [
("علی", "2005-02-10"),
("سارا", "2000-05-22"),
("محمد", "2010-11-15"),
("مریم", "2003-09-03"... | Python | 1 |
l test
#[cfg(not(target_os = "macos"))]
#[cfg(test)]
mod association_test;
mod association_internal;
mod association_stats;
use crate::chunk::chunk_abort::ChunkAbort;
use crate::chunk::chunk_cookie_ack::ChunkCookieAck;
use crate::chunk::chunk_cookie_echo::ChunkCookieEcho;
use crate::chunk::chunk_error::ChunkError;
us... | Rust | 0 |
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
// nibble * 0 1 00 01 10 11 000 001 010 011 100 101 110 111 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111 x
// nibble len offset 0 1 2 3 ... | Rust | 0 |
import numpy as np
import PYME.Analysis._fithelpers as fh
def get_offtime_cdf(frame_num, envelope='upper'):
ts = np.sort(frame_num)
#find the gap lengths. -1 as otherwise two consecutive frames would give a gap length of 1
dt = np.diff(ts) - 1
#just take the non-zero gaps and sort to give x v... | Python | 1 |
ttern
content: str
@field_validator("pattern", mode="before")
@classmethod
def _coerce_content(cls, v: Any) -> StringPattern | RegexPattern | dict:
return coerce_string_regex_pattern(v)
class StripDecoder(BaseModel):
"""
A Strip decoder strips characters from the input text.
This... | Python | 1 |
(start_position: &Position, end_position: &Position) -> (i32, i32, i32, i32) {
let (start_x, start_y, end_x, end_y) = get_valid_rectangle(start_position, end_position);
(start_x as i32, start_y as i32, end_x as i32, end_y as i32)
}
pub fn get_transformed_mouse_position(window: &mut dyn EditorWindow, transform:... | Rust | 0 |
_base_ = './queryinst_r50_fpn_ms-480-800-3x_coco.py'
model = dict(
backbone=dict(
depth=101,
init_cfg=dict(type='Pretrained',
checkpoint='torchvision://resnet101')))
| Python | 1 |
replace_string(keyboard(kb_name) / 'keyboard.json', 'LAYOUT_ortho_4x4', 'LAYOUT')
replace_string(keymaps_path / 'default/keymap.c', 'LAYOUT_ortho_4x4', 'LAYOUT')
cli.log.info(f'{{fg_green}}Created a new keyboard called {{fg_cyan}}{kb_name}{{fg_green}}.{{fg_reset}}')
cli.log.info(f"Build Command:... | Python | 1 |
-> vec4 {
let df = Df::viewport(pos * rect_size);
df.box(vec2(0.), rect_size, border_radius);
if prev_w > 0. {
df.box(vec2(prev_x, -rect_size.y), vec2(prev_w, rect_size.y), border_radius);
df.gloop(gloopiness);
}
... | Rust | 0 |
"min": 0,
"max": 100,
"tooltip": "Amount of compression to apply on image.",
},
),
}
}
FUNCTION = "preprocess"
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("output_image",)
CATEGORY = "image"
... | Python | 1 |
import atexit
import colorama
import sys
import time
try:
from msvcrt import getch
except ImportError:
import tty
import termios
def getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin... | Python | 1 |
t!(parts, line));
let algorithm = opts.algorithm;
let tx = tx.clone();
pool.execute(move || {
tx.send(verify_checksum(&path, &checksum, algorithm)).expect("Internal error.");
});
count += 1;
}
for _ in 0..count {
m... | Rust | 0 |
#!/usr/bin/python
# Copyright 2015 Huawei Devices USA Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... | Python | 1 |
from humanprompt.components.extract.extract_regex_batch import QABatchExtract_new
class BatchInferenceSVAMPExtract_new(QABatchExtract_new):
pass
| Python | 1 |
总的代币池;
// 1. 挑战费用 = 基因价格 × 挑战费系数
// challenger 发起挑战的吞噬者者,
// facer 应战的吞噬者
// 吞噬挑战
// 吞噬者可以向其他吞噬者发起挑战,从而获得其基因;
// 发起挑战,需要支付代币,所有代币将投放进入总的代币池;
// 挑战费用 = 基因价格 × 挑战费系数
#[pallet::weight(T::SwallowerWeightInfo::make_battle())]
pub fn make_battle(
origin: OriginFor<T>,
challenger: T::Hash,
facer... | Rust | 0 |
rm) in any
# way that is inconsistent with the permitted uses described
# herein. You agree not to use any name or emblem of Harvard, Toronto
# or Sherbrooke, or any of their subdivisions for any purpose, or to
# falsely suggest any relationship between End User (or its
# Institution) and Harvard, Toronto and/or Sherbr... | Python | 1 |
xc2\
\xee\xf9\xad\xcb2\xfb|\xb9\xae\xa2\xff\x00\xc2\xfa6\xa9\
*y\xban\x9bq\xb7\x1bZ[uv\xfc\x09\x15V\
\xc3Y\xd0mu\xef\xec\x1b\x0b\xcb\x0b}J$\xf3~\
\xc2\x8c\x12L\x1er\x14riJ\xdaw\x1c\xbd\x94\xd6\
\x89\xdc\xe0\xf5\x9f\x8f\xbe\x03\xd1\xbcQk\xa4\xea\x9e(\
\xd2\xf4\xddF\xff\x00\xfdM\xad\xe3y20\xce>\xeb\
\x0c\xf5\xad\x8b\xaf\... | Python | 1 |
f/data/lcls/ds/prj/prjs2e21/results/COOKIE_ML_Output/denoising/run_07282024_multiPulse/autoencoder_best_model.pth"
best_autoencoder_model_path = "/sdf/data/lcls/ds/prj/prjs2e21/results/COOKIE_ML_Output/denoising/run_09042024_multiPulse_final/autoencoder_6_best_model.pth"
best_model_zero_mask_path = "/sdf/data/l... | Python | 1 |
class Game:
def __init__(self, name, developer, year, price):
self.name = name
self.developer = developer
self.year = year
self.price = price
def price_in_pounds(self):
return self.price * 15.6
game_one = Game("Ys", "Falcom", 2010, 50)
print(f"Game Name Is \"{game_one.name}\", ", end="")
prin... | Python | 1 |
ok_or(SerdeError::invalid_value(Unexpected::Signed(v), &self))
}
}
#[cfg(test)]
mod test_i64 {
use super::*;
use serde::Deserialize;
#[derive(Deserialize, Debug)]
struct Item {
#[serde(deserialize_with = "ToNum::<i64>::deserialize")]
value: i64,
}
#[test]
fn i64_deseri... | Rust | 0 |
t schedulers depending on the
# platform. One might prefer patching `sys.platform` for a more direct test, but that
# causes problems in other libraries.
def check_default_scheduler(module, collection, expected, emscripten):
from contextlib import nullcontext
from unittest import mock
from dask.local impor... | Python | 1 |
"""Defines constants for core."""
# HTTP Header key and value
from __future__ import annotations
HEADER_APIKEY = "simcloud-api-key"
HEADER_VERSION = "tidy3d-python-version"
HEADER_SOURCE = "source"
HEADER_SOURCE_VALUE = "Python"
HEADER_USER_AGENT = "User-Agent"
HEADER_APPLICATION = "Application"
HEADER_APPLICATION_VA... | Python | 1 |
(contexto_clase.clone(), id_valor.to_owned()) {
Ok((_, _, var)) => return var,
Err(_err) => {
// println!("{:?}", _err);
}
};
}
} else {
match tabla_funciones.buscar_variable(contexto_funcion.clone(), id_valor.to_owned()) {
Ok((_, _, var)) => return var,
Err... | Rust | 0 |
) {
attenuation * ray_color(rng, &ray, objects, depth - 1)
} else {
BLACK
}
} else {
ray.background()
}
}
#[derive(Debug, Clone)]
pub struct Object {
sphere: Sphere,
material: Material,
}
fn random_scene<R: Rng>(rng: &mut R) -> Vec<Object> {
let mut ... | Rust | 0 |
K, V, S, LEN>
where
K: Eq + Hash,
V: PartialEq,
S: BuildHasher,
{
fn eq(&self, other: &Self) -> bool {
self.iter()
.all(|(k, v)| other.get(k).map_or(false, |v2| v == v2))
}
}
impl<K, V, S, const LEN: usize> Eq for HashMap<K, V, S, LEN>
where
K: Eq + Hash,
V: Eq,
S: B... | Rust | 0 |
raw_zhangsan)
def test_covert_with_invalid_enum(self, bare_local_data_source, tenant_user_custom_fields, logger):
raw_zhangsan = RawDataSourceUser(
code="zhangsan",
properties={
"username": "zhangsan",
"full_name": "张三",
"email": "zhan... | Python | 1 |
arches: Vec<String> = Vec::new();
for route in self.routes.iter() {
if route.branch != branch {
continue;
}
if !arches.contains(&route.arch) {
arches.push(route.arch.clone());
}
}
arches
}
pub fn versions(&m... | Rust | 0 |
= '\w+|$[\d\.]+|\S+') for x in sentence]
freq = nltk.FreqDist(itertools.chain(*self.tokenize_sent))
print('found ',len(freq),' unique words')
vocab = freq.most_common(vocab_size - 1)
self.index_to_word = [x[0] for x in vocab]
self.index_to_word.append(unk... | Python | 1 |
}
pub async fn serve(
self,
addr: std::net::SocketAddr,
shutdown: impl std::future::Future<Output = ()>,
) -> hyper::Result<()> {
let svc = InboundServerPoliciesServer::new(self);
hyper::Server::bind(&addr)
.http2_only(true)
.tcp_nodelay(true)... | Rust | 0 |
.nn.functional.softmax(
outputs, dim=-1).topk(1)
results = []
for i, sample_labels in enumerate(metadata["class_labels"]):
correct_indices = [
class_labels.index(c.strip()) for c in sample_labels.split(",")
]
is_correct_top5 = len(set(correct_indices) &
... | Python | 1 |
import addressbook_pb2 as addressbook
import os
print = lambda *x: x
def writeAddressBook():
addressBook = addressbook.AddressBook()
alice = addressBook.person.add()
alice.id = 123
alice.name = "Alice"
alice.email = "alice@example.com"
alicePhones = [alice.phone.add()]
alicePhones[0].num... | Python | 1 |
mut scope_5208 = writer.prefix("ConnectionNotificationArn");
if let Some(var_5209) = &input.connection_notification_arn {
scope_5208.string(var_5209);
}
#[allow(unused_mut)]
let mut scope_5210 = writer.prefix("ConnectionEvents");
if let Some(var_5211) = &input.connection_events {
le... | Rust | 0 |
# Copyright 2024 Bytedance Ltd. and/or its affiliates
#
# 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 required by applicable law ... | Python | 1 |
ASN1_T61STRING: c_int = 20;
pub const V_ASN1_TELETEXSTRING: c_int = 20; // alias
pub const V_ASN1_VIDEOTEXSTRING: c_int = 21;
pub const V_ASN1_IA5STRING: c_int = 22;
pub const V_ASN1_UTCTIME: c_int = 23;
pub const V_ASN1_GENERALIZEDTIME: c_int = 24;
pub const V_ASN1_GRAPHICSTRING: c_int = 25;
pub const V_ASN1_ISO64STRI... | Rust | 0 |
-> bool>(&mut self, mut f: F) -> &'a str {
let n = self
.iter()
.position(|&b| !(b as char).is_ascii() || !f(b as char))
.unwrap_or(self.len());
unsafe { self.consume_str_n(n) }
}
}
#[cfg(test)]
mod test {
use super::*;
static HELLO: &'static [u8] = b"he... | Rust | 0 |
?;
let typ = tuple(elems.iter().map(|e| e.typ()).collect());
Ok(TypedExpr::Tuple { meta, elems, typ })
}
fn infer_var(name: String, meta: Meta, level: usize, env: &mut Env) -> Result<TypedExpr, Error> {
let constructor = infer_value_constructor(&name, level, &meta, env)?;
Ok(TypedExpr::Var {
con... | Rust | 0 |
P2::Err, (P2::Res, P1::Err)>;
fn parse(&self, s: S) -> Result<S, Self::Res, Self::Err> {
(&self.precedator, &self.parser).parse(s)
.map(|((_, r), s, p)| (r, s, p))
}
}
/// Precedes given parser with another.
///
/// # Examples
/// ```rust
/// use parsco::{Parser, preceded, tag, take};
/// ... | Rust | 0 |
fse");
const SYNTH_REPL08: &[u8] = include_bytes!("../../data/synth/repl08.lzfse");
const SYNTH_REPL09: &[u8] = include_bytes!("../../data/synth/repl09.lzfse");
const SYNTH_REPL10: &[u8] = include_bytes!("../../data/synth/repl10.lzfse");
const SYNTH_REPL11: &[u8] = include_bytes!("../../data/synth/repl11.lzfse");
const... | Rust | 0 |
// the Program Counter) will match the intended location of .start. We
// don't have an easy way to signal an error, so for now we just yield
// if the location is wrong.
sub r4, pc, #4 // r4 = pc
ldr r5, =.start // r5 = address of .start
cmp r4, r5
beq .Lsta... | Rust | 0 |
s"
for p in plants:
open[p].ScenNObj = fixedCosts[p] * 0.95
# Scenario 4: Combine scenario 1 and scenario 3
m.Params.ScenarioNumber = 4
m.ScenNName = "Increased warehouse demands and decreased plant fixed costs"
for w in warehouses:
demandConstr[w].ScenNRhs = demand[w] * 1.1
for p in plants:
open[p].ScenNO... | Python | 1 |
tart_date, today)
if df is None or df.empty:
print("未能获取有效数据,退出分析")
return
# 准备特征
df_features = prepare_features(df)
print("特征准备完成")
# 创建标签
df_labeled = create_labels(df_features)
print("标签创建完成")
# 删除含有NaN的行
df_clean = df_labeled.dropna()
if len(df_... | Python | 1 |
endpoint and
/// the time at which it will reset.
///
/// After each HTTP API call and in order to not reach the
/// rate-limit set by Discord, the library keeps a hashmap
/// associating the routes to their bucket. However, when
/// these buckets reset, it is not necessary to keep them
///... | Rust | 0 |
/{1:02}/collision/em{0:03}_{1:02}_colliders.rcol",
id, sub_id
)
}
fn gen_ems_collider_path(id: u32, sub_id: u32) -> String {
format!(
"enemy/ems{0:03}/{1:02}/collision/ems{0:03}_{1:02}_colliders.rcol",
id, sub_id
)
}
pub fn gen_collider_mapping(rcol: Rcol) -> Result<ColliderMapping... | Rust | 0 |
};
let fold_id = e_cxt.coll_handlers()[c_idx].folder().id();
doc! {
"Initializes the accumulator used to fold over [`{}::{}`]'s {}.",
e_cxt.e_id(), variant.v_id(), data_name;
newline
"This initializer is called whenever the zipper reaches a [`{}... | Rust | 0 |
async
{
increment_clone( 4, Arc::new( exec.clone() ), tx );
rx.next().await.expect( "Some" )
});
assert_eq!( 5u8, res );
}
// pass a GlommioCt to a function that takes exec: `impl SpawnHandle`
//
#[ test ]
//
fn spawn_handle()
{
let builder = LocalExecutorBuilder::new();
let exec = GlommioCt:... | Rust | 0 |
#!/usr/bin/env python3
import subprocess
import json
import argparse
import sys
from datetime import datetime
from typing import Dict, List
def get_user_contributions(username: str, year: int = None) -> Dict:
"""
指定したユーザーのコントリビューションデータを取得
"""
print(f"Fetching contribution data for user: {username}")
... | Python | 1 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created by PyCharm.
File Name: LinuxBashShellScriptForOps:python-dateutil-examples-01.py
Version: 0.0.1
Author: dgden
Author Email: dgdenterprise@gmail.com
URL: https://github.com/DingGuodong/LinuxBash... | Python | 1 |
true => P3_A::VALUE2,
}
}
#[doc = "Checks if the value of the field is `VALUE1`"]
#[inline(always)]
pub fn is_value1(&self) -> bool {
*self == P3_A::VALUE1
}
#[doc = "Checks if the value of the field is `VALUE2`"]
#[inline(always)]
pub fn is_value2(&self) -> bool... | Rust | 0 |
import openai
import os
# from langchain.llms import OpenAI
from langchain_openai import OpenAI
from langchain.agents import load_tools
from langchain.agents import initialize_agent,create_react_agent
from dotenv import load_dotenv
from langchain_core.tools import tool
load_dotenv()
@tool
def get_current_weather(locat... | Python | 1 |
},
"_mm256_avg_epu16" => Intrinsic {
inputs: { static INPUTS: [&'static Type; 2] = [&::U16x16, &::U16x16]; &INPUTS },
output: &::U16x16,
definition: Named("llvm.x86.avx2.pavg.w")
},
"_mm256_hadd_epi16" => Intrinsic {
inputs: { static INPUT... | Rust | 0 |
assert_eq!(s!(a - c * b), op::scalar_sub(&a, &op::scalar_mul(&c, &b)));
assert_eq!(
s!(a - c * b - a),
op::scalar_sub(&op::scalar_sub(&a, &op::scalar_mul(&c, &b)), &a)
);
assert_eq!(
s!(a - c * b + a),
op::scalar_add(&op::scalar_sub(&a, &op::scalar_mul(&c, &b)), &a)
... | Rust | 0 |
le::create(&output).unwrap_or_else(|_| {
println!(
"{}: {}",
style("couldn't create output file").red(),
output.display()
);
std::process::exit(-1);
});
let count = if source.is_dir() {
println!(
"{} {}counting contents of {}…",
... | Rust | 0 |
x="Hello World" | Python | 1 |
_DATA */
const EI_DATA: usize = 5;
const ELFDATANONE: EIDENT = 0; /* Invalid data encoding */
const ELFDATA2LSB: EIDENT = 1; /* 2's complement, little endian */
const ELFDATA2MSB: EIDENT = 2; /* 2's complement, big endian */
const ELFDATANUM: EIDENT = 3;
/* EI_VERSION */
const EI_VERSION: usize = 6;
const EV_CURRENT: ... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.