text string | label_name string | labels int64 |
|---|---|---|
Process(model_part,
# "smoothing_test_2D",
# KratosMultiphysics.Parameters("""
# {
# "result_file_configuration" : {
# "g... | Python | 1 |
import datetime
from requests_mock.mocker import Mocker
from uust_schedule import TZ_INFO, Event, Schedule, SemesterType
def test_get_start_datetime_of_academic_year() -> None:
assert datetime.datetime(2023, 8, 28, tzinfo=TZ_INFO) == Schedule.get_start_datetime_of_academic_year(2023)
def test_get_semester_type... | Python | 1 |
<[c @ sz d Z d d l m Z m Z m Z d d l Z e j e e d Z g e D]" Z e e rN e e d ^ qN Z d S( s0
This is the data downloader and loader module.
i( t dirnamet basenamet isfileNs /*.pyi(
t __doc__t os.pathR R R t globt __file... | Python | 1 |
"""Everything in this module is taken from the excellent trio project.
Having the public path in .__module__ attributes is important for:
- exception names in printed tracebacks
- ~sphinx :show-inheritance:~
- deprecation warnings
- pickle
- probably other stuff
"""
import os
def fixup_module_metadata(namespace):
... | Python | 1 |
is_null() {
App::error_message_box(&format!("CreateWindowExW failed: {}", std::io::Error::last_os_error()));
return;
}
unsafe {
ShowWindow(hwnd, SW_SHOW);
UpdateWindow(hwnd);
}
self.webview.initialize(hwnd, settings.get_url().clone(... | Rust | 0 |
from openai import OpenAI
def get_analysis(query, api_key):
client = OpenAI(api_key=api_key)
response = client.chat.completions.create(
model="gpt-4",
messages=[
{
"role": "system",
"content": "You turn sentiment analysis generated from an audio file into a helpful 3-5 sentence summ... | Python | 1 |
ble => false,
Self::DoubleFault => false,
#[allow(deprecated)]
Self::CoprocessorSegmentOverrun => false,
Self::InvalidTss => false,
Self::SegmentNotPresent => false,
Self::StackSegmentFault => false,
Self::GeneralProtectionFault => fals... | Rust | 0 |
(crate) struct Batch(Arc<BatchInner>);
unsafe impl Send for Batch {}
unsafe impl Sync for Batch {}
impl Batch {
pub(super) fn new(db: WeakDB, calls_len: usize, delay: Duration) -> Self {
let batch = Batch(Arc::new(BatchInner {
db,
calls_len,
ran: AtomicBool::new(false),... | Rust | 0 |
}
// Helper to check that fetching an invalid range returns a NotSatisfiable error.
pub(crate) async fn check_fetch_range_not_satisfiable(env: &impl TestEnv) {
for size in [20, CHUNK_SIZE - 1, CHUNK_SIZE, CHUNK_SIZE + 1, CHUNK_SIZE * 2 + 1] {
let path = format!("{}", size);
let body = (0..std::u8::... | Rust | 0 |
import logging
import re
from scrapy import signals, Spider
from quest.retail_quest_ids import RETAIL_QUEST_IDS
from quest.translations.quest_translation_formatter import QuestTranslationFormatter
from quest.translations.quest_translation_move_to_lookups import main as move_to_lookups
from supported_locales import LOCA... | Python | 1 |
"""
Complete the preOrder function in your editor below, which has parameter: a pointer to the root of a binary tree.
It must print the values in the tree's inorder traversal as a single line of space-separated values.
"""
from . import Node
class BinaryTreeNode(object):
def __init__(self, data=None, left=None, rig... | Python | 1 |
]
# 不足している列を空文字で埋める
while len(items) < self.model.columnCount():
items.append(QStandardItem(""))
self.model.appendRow(items)
"""既存のクラスに以下のメソッドを追加"""
def paste_youtube_chapters(self):
"""
クリップボードからYouTubeチャプター形式のデー... | Python | 1 |
ng: &str) -> String {
// arbitrary capacity
let cap = string.len() + string.len() / 3;
let mut res = String::with_capacity(cap);
let words = string.split_ascii_whitespace().collect::<Vec<_>>();
if let Some(x) = words.first() {
res.push_str(x);
} else {
return res;
}
fo... | Rust | 0 |
# System packages
import numpy as np
from numpy.typing import NDArray
# Local packages
def initial_guess_anisotropic() -> list[float]:
return np.squeeze(np.full((1,21), 1)).tolist()
def elastic_tensor_anisotropic(coefficients: list[float]) -> NDArray[np.float64]:
C11 = coefficients[0]
C12 = coefficients[... | Python | 1 |
w<'a>
where
's: 'a,
{
let mut fill =
Vec::with_capacity(self.offsets.len().max(inputs.len()) + self.templates.len());
let mut current = 0;
let mut offset_iter = self.offsets.iter().peekable();
let mut static_iter = self.templates.iter();
let mut inpu... | Rust | 0 |
e"]:
continue
if detected_label in ["orange", "sports ball", "sportsball", "sports_ball"]:
detected_label = "apple"
annotation_color = (0, 255, 0)
cv2.rectangle(base_frame, (x_val, y_val), (x_val + w_val, y_val + h_val), annotation_color, 2)
... | Python | 1 |
for port in 0..ports {
let arrival = self.clock + 1;
self.push_event(arrival, Event::Receive {
to: u16_to_socketaddr(port as u16),
env: env_with_return_address.clone(),
});
}
... | Rust | 0 |
Clone, Copy, Debug)]
pub struct Colour {
pub r: u8,
pub g: u8,
pub b: u8
}
impl Colour {
pub const fn new(r: u8, g: u8, b: u8) -> Self {
Colour {
r: r,
g: g,
b: b
}
}
pub const fn zero() -> Colour {
Colour {
r: 0,
... | Rust | 0 |
(feature = "bindgen"))]
mod bindings;
#[cfg(not(feature = "bindgen"))]
pub use bindings::*;
<filename>gensokyo-vulkan/src/pipeline/config.rs
use crate::types::format::Format;
pub struct PipelineConfig {
pub depth_stencil: DepthStencilConfig,
}
pub struct DepthStencilConfig {
/// The prefer format for depth... | Rust | 0 |
import numpy as np
from nsma.line_searches.armijo_type.als import ALS
from problems.extended_problem import ExtendedProblem
class MOALS(ALS):
def __init__(self, alpha_0: float, delta: float, beta: float, min_alpha: float):
ALS.__init__(self, alpha_0, delta, beta, min_alpha)
def search(self, proble... | Python | 1 |
revious_process() {
let mut selector = SortCriteriaSelector::default();
selector.next();
selector.previous();
assert_eq!(selector.selected(), PROCESS_ORDERING_CRITERIA[0]);
}
#[test]
fn should_not_apply_selection_by_default() {
let mut selector = SortCriteriaSelecto... | Rust | 0 |
compute_prepared_inputs(
program_id: &solana_program::pubkey::Pubkey,
signer_pubkey: &solana_program::pubkey::Pubkey,
signer_keypair: &solana_sdk::signature::Keypair,
tmp_storage_pda_pubkey: &solana_program::pubkey::Pubkey,
program_context: &mut ProgramTestContext,
accounts_vector: &mut std::ve... | Rust | 0 |
# Copyright 2021 The Magenta Authors.
#
# 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 or agreed to in ... | Python | 1 |
Real: From<C1>,
C3: 'a + Send + Sync,
C1: 'a + Send + Sync,
{
fn bsdf<'s>(&'s self, v: &TexturedVertex) -> BsdfRef<'s> {
let basecolor: Rgb<Real> = self.base_color.as_ref().sample(v.uv.x, v.uv.y).into();
let roughness: Real = self.roughness.as_ref().sample(v.uv.x, v.... | Rust | 0 |
elf.bst.put(60,'d')
self.bst.put(90,'e')
assert self.bst.root.key == 70
def testAuto3(self):
self.bst.put(40,'a')
self.bst.put(30,'b')
self.bst.put(50,'c')
self.bst.put(45,'d')
self.bst.put(60,'e')
self.bst.put(43,'f')
assert self.bst.root.key... | Python | 1 |
), h2:lang(mr), h3:lang(mr), h4:lang(mr), h5:lang(mr), h6:lang(mr), h2:lang(or), h3:lang(or), h4:lang(or), h5:lang(or), h6:lang(or), h2:lang(pa), h3:lang(pa), h4:lang(pa), h5:lang(pa), h6:lang(pa), h2:lang(sa), h3:lang(sa), h4:lang(sa), h5:lang(sa), h6:lang(sa), h2:lang(ta), h3:lang(ta), h4:lang(ta), h5:lang(ta), h6:la... | Rust | 0 |
Transformed::Replace(replacement) => Transformed::Replace(f(replacement)),
}
}
}
#![allow(dead_code, non_camel_case_types, non_upper_case_globals, non_snake_case)]
#[link(name = "nfc_sys", kind = "dylib")]
extern crate libc;
use self::libc::{uint8_t, uint32_t, size_t};
#[derive(Copy, Clone)... | Rust | 0 |
idl_mlme, MlmeEvent, MlmeEventStream, MlmeProxy};
use fidl_fuchsia_wlan_stats::IfaceStats;
use fuchsia_async as fasync;
use futures::channel::mpsc;
use futures::prelude::*;
use futures::select;
use log::warn;
use pin_utils::pin_mut;
use std::marker::Unpin;
use std::sync::{Arc, Mutex};
use void::Void;
use wlan_sme::{
... | Rust | 0 |
"fas fa-list-ol me-2"></i>Search Results:</h5>
<div id="results-container" class="border rounded p-3 bg-light" style="max-height: 400px; overflow-y: auto;">
</div>
</div>
</div>
</div>
</div>
... | Python | 1 |
log::error!("Bonding Information wasn't supplied, make sure to have the master initate bonding");
None
}
}
async fn remove_bonding_info(&self) {
use hci::le::privacy::remove_device_from_resolving_list::{send, Parameter};
use hci::le::privacy::PeerIdentityAddres... | Rust | 0 |
становки для не - Tropo Twitter поддержки!',
'unable to parse csv file': 'Невозможно проанализировать файл csv',
'uncheck all': 'Отменить все проверки',
'unidentified': 'Неидентифицирован',
'unknown': 'неизвестный',
'unspecified': 'неуточненный',
'unverified': 'Непроверенный',
'updated': 'обновлено',
'updates only': 'Т... | Python | 1 |
MapMemory`](https://www.khronos.org/registry/vulkan/specs/1.0-extensions/html/vkspec.html#vkMapMemory)
pub fn vkMapMemory(device: vk::VkDevice, memory: vk::VkDeviceMemory, offset: vk::VkDeviceSize, size: vk::VkDeviceSize, flags: vk::VkMemoryMapFlags, ppData: *mut *mut c_void) -> vk::VkResult; [pfn_vkMapMemory: ... | Rust | 0 |
future = {
let a = A;
a.f()
};
}
}
fn main() {}
use super::*;
use wasmer_derive::ValueType;
use crate::__wasi_option_timestamp_t;
pub type __wasi_socktype_t = u16;
pub const __WASI_SOCK_TYPE_DGRAM: __wasi_socktype_t = 0;
pub const __WASI_SOCK_TYPE_STREAM: __wasi_socktype_t = 1;
pu... | Rust | 0 |
ffi_catch_unwind!({
if pline.is_null() {
return 1;
}
area.write((*pline).0.area());
0
})
}
/// Wraps [Polyline::winding_number].
///
/// `winding_number` is used as the out parameter to hold the computed winding number.
///
/// ## Specific Error Codes
/// * 1 = `pli... | Rust | 0 |
'''
Created on 2024/09/03
@author: K.Takagi
'''
import numpy as np
from scipy.stats.stats import pearsonr
from datainout import getrandomsampling
def getpcor(p0,a0):
p=np.reshape(p0, (-1))
a=np.reshape(a0, (-1))
ret=pearsonr(p,a)[0]
return ret
def getpcorsamplingmax(nmax, p0,a0):
p=np.reshape(p0,... | Python | 1 |
pub const LINE_WIDTH: f32 = 2.0;
/// Size of the extra invisible space for hover interactions.
pub const HOVER_PADDING: f32 = 5.0;
// =============
// === Shape ===
// =============
/// Arrow shape that consists of a line and a triangle as arrow head.
pub mod arrow {
use super::*;
ensogl_core::define_shape_... | Rust | 0 |
import numpy as np
def read_nkpts_and_nbands(filename):
"""
Reads NKPTS and NBANDS from the BAND.dat file without using regular expressions.
Expecting the format: NKPTS & NBANDS: 400 64
Inputs: filename --> "BAND.dat"
Outputs: nkpts, nband
"""
with open(filename, 'r') as f:
for li... | Python | 1 |
de_str!("../templates/index.js.template"), &context)?;
Ok(())
}
fn render_template_to_file(file: &Path, template: &str, context: &Context) -> Result<(), Error> {
use std::fs;
use std::io::prelude::*;
let mut tt = TinyTemplate::new();
tt.set_default_formatter(&format_unescaped);
tt.add_templat... | Rust | 0 |
return FCMResponse(
success=False,
error=str(e)
)
async def send_multicast(
self,
device_tokens: List[str],
title: str,
body: str,
data: Optional[Dict[str, Any]] = None,
image: Optional[str] = None,
click_... | Python | 1 |
points = format!("{} {},{}", points, bounds.x + 15.0, bounds.y);
points = format!("{} {},{}", points, bounds.x + bounds.width, bounds.y);
points = format!("{} {},{}", points, bounds.x + bounds.width, bounds.y + bounds.height - 15.0);
points = format!("{} {},{}", points, bounds.x + bounds.width - 15.0, bounds.y + ... | Rust | 0 |
# -*- coding: utf-8 -*-
import math
from sklearn.metrics import f1_score
from sklearn.metrics import roc_auc_score
class Metrics(object):
"""根据不同的任务类型,选择合适的评估指标并计算。它可以支持多种任务类型:
分类任务:计算 top-k 准确率。
语言模型任务:计算困惑度。
神经机器翻译任务:计算困惑度和 top-1 准确率。
推荐系统任务:计算 AUC 和 F1 分数"""
def __init__(self, model, task="classificat... | Python | 1 |
uid: u32,
#[protocol(var)]
pub quantity: u32,
#[protocol(var)]
pub object_price: u64,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 164)]
pub struct ObjectItemToSellInBid<'a> {
pub base: ObjectItemToSell<'a>,
pub unsold_delay: u32,
}
#[derive(Clone, PartialEq, Debug, Enc... | Rust | 0 |
x_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "notify::use-underline",
transmute(notify_use_underline_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
}
}
}
unsafe extern "C" fn activate_trampoline<P>(this: *mut ffi::GtkExpander, f:... | Rust | 0 |
import frappe
from india_compliance.gst_india.setup import _create_hsn_codes
DOCTYPE = "GST HSN Code"
INCORRECT_HSN_CODE_LENGTHS = frozenset((3, 5, 7))
def execute():
if frappe.flags.hsn_codes_corrected:
return
used_hsn_codes = get_used_hsn_codes()
frappe.db.delete(DOCTYPE, {"name": ("not in", ... | Python | 1 |
unsafe { mem::transmute(data.as_mut_ptr()) }
}
pub fn any_from_slice<'a, T>(data: &'a [u8]) -> &'a T {
unsafe { mem::transmute(data.as_ptr()) }
}
}
pub mod math {
use core::ops::{Add, BitAnd, Not, Sub};
pub fn align_up<T>(value: T, alignment: T) -> T
where
T: BitAnd<Ou... | Rust | 0 |
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g = sorted(g)
s = sorted(s, reverse = True)
if not s: return 0
currcookie = s.pop()
total = 0
for child in g:
while child > currcookie:
try:
... | Python | 1 |
new_range = true;
ranges.push(curr_range);
log::debug!("RANGE {} {}", curr_range.0, curr_range.1);
curr_pos = curr_pos + cigar_len as i32;
// log::debug!("curr_pos: {}", curr_pos);
// log::debug!("len:{} + cigar_len:{} = {}", *ref_... | Rust | 0 |
def test_create_from_fparser2():
'''Test that the create_from_fparser2 method works as expected.'''
fortran_string = (
"type(REFERENCE_ELEMENT_DATA_TYPE) :: META_REFERENCE_ELEMENT(2) = "
"(/ &\n"
" reference_element_data_type(normals_to_horizontal_faces), &\n"
" reference_... | Python | 1 |
starts + 1
segment_signs = np.sign(arr[segment_starts])
adjusted_lengths = segment_lengths * segment_signs
return adjusted_lengths
def agg_interval(packets):
features = []
features.append([np.sum(packets>0), np.sum(packets<0)])
dirs = np.sign(packets)
assert not np.any(dir == 0), "Array c... | Python | 1 |
plit("/")[-1]
ext_tokenizer = WhisperTokenizerFast.from_pretrained(external_tokenizer)
ext_tokenizer.set_prefix_tokens(language=lang, task="transcribe")
elif external_tokenizer is None or len(external_tokenizer) == 0:
ext_tokenizer = None
else:
raise No... | Python | 1 |
# This Python file uses the following encoding: utf-8
import re
from os.path import join
from argparse import ArgumentParser
parser = ArgumentParser(description="Preprocess CMUdict and prepare input for GIZA++")
parser.add_argument("--input_name", type=str, required=True, help="Input file")
parser.add_argument("--ou... | Python | 1 |
from django.template import TemplateDoesNotExist, TemplateSyntaxError
from django.test import SimpleTestCase
from ..utils import setup
from .test_extends import inheritance_templates
class ExceptionsTests(SimpleTestCase):
@setup({"exception01": "{% extends 'nonexistent' %}"})
def test_exception01(self):
... | Python | 1 |
'''Modified slightly, the function greet_user() can not only tell the user Hello!
but also greet them by name. For the function to do this, you enter username
in the parentheses of the function’s definition at def greet_user(). By adding username here you allow the function to accept any value of username you
specify... | Python | 1 |
old) + 10 : #skip if that line is too small (10px)
continue
if start_y >= end_y: # Skip invalid or empty rows
print(f"Skipping invalid row: start_y={start_y}, end_y={end_y}")
continue
cv2.line(binary, (0, start_y), (binary.shape[1], start_y), (255, 0, 0), 2)
... | Python | 1 |
data_type: DataType,
) -> DictionaryArray<K> {
let child = DictionaryArray::<K>::get_child(&data_type);
let mut map = HashedMap::<u64, K>::default();
let extractor = build_extract(child);
let mut inner = vec![];
let keys = rows
.iter()
.map(|x| extractor(x.borrow()))
... | Rust | 0 |
in memory at once")
.default_value("30000000"));
//.arg(arg!(-e --expected-ori=[expected-ori] 'the expected orientation of alignments'")
// .default_value(fw"));
let quant_app = Command::new("quant")
.about("Quantify expression from a collated RAD file")
.version(version)
.author(... | Rust | 0 |
face;
#[cfg(target_os = "linux")]
use crate::linux::params::Params;
use crate::result::Result;
use async_std::fs::File;
use async_std::fs::OpenOptions;
use async_std::io::{BufReader, BufWriter};
#[cfg(target_family = "unix")]
use async_std::os::unix::io::{AsRawFd, RawFd};
use async_std::sync::Arc;
use mac_address::{mac... | Rust | 0 |
var_spans: DVec<span>;
values: Cell<~[ty::region]>;
constraints: hashmap<Constraint, span>;
lubs: CombineMap;
glbs: CombineMap;
// The undo log records actions that might later be undone.
//
// Note: when the undo_log is empty, we are not actively
// snapshotting. When the `start_snap... | Rust | 0 |
from k5test import *
import csv
from io import StringIO
def tab_csv(s):
io = StringIO(s)
return list(csv.DictReader(io, dialect=csv.excel_tab))
def getrows(dumptype):
out = realm.run([kdb5_util, 'tabdump', dumptype])
return tab_csv(out)
def checkkeys(rows, dumptype, names):
if sorted(rows[0].k... | Python | 1 |
import numpy as np
import sympy as sp
import matplotlib.pyplot as plt
import sys
import os
# Add the project root
sys.path.append(os.path.abspath('../../../'))
from src.openmm.simulated_tempering_module import generate_initial_trajectory
# For reproducibility
np.random.seed(0)
inp_dir = '../input/'
out_dir = 'outpu... | Python | 1 |
let path = http::uri::PathAndQuery::from_static(
"/google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseService/GetKey",
);
self.inner.unary(request.into_request(), path, codec).await
}
#[doc = " Updates the specified key."]
pub async fn upda... | Rust | 0 |
inkConfig {
path: template.clone().into(),
idle_timeout_secs: None,
encoding: Encoding::Text.into(),
};
let mut sink = FileSink::new(&config);
let (input, _) = random_lines_with_stream(100, 64);
let events = stream::iter(input.clone().into_iter().map... | Rust | 0 |
def test_shap_e(self):
expected_image = load_numpy(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/shap_e/test_shap_e_np_out.npy'
)
pipe = ShapEPipeline.from_pretrained('openai/shap-e')
pipe = pipe.to(torch_device)
pipe.set_progress_bar_config(disable=... | Python | 1 |
_quit: bool,
terminal: Terminal,
}
impl Editor {
pub fn run(&mut self) {
loop {
if let Err(error) = self.refresh_screen() {
die(error);
}
if self.should_quit {
break;
}
if let Err(error) = self.process_keypress(... | Rust | 0 |
-1-|---|---|---|- G#
")
),
case(
"Db",
indoc!("
[Db - Db major]
A ||---|---|---|-4-|- Db
E ||-1-|---|---|---|- F
C ||-1-|---|---|---|- Db
G ||-1-|---|---|---|- Ab
")
),
)]
fn test_chart(chord: &str, chart: &'sta... | Rust | 0 |
t Ranged<T, Min, Max> {
val: T,
_marker: PhantomData<(Min, Max)>,
}
pub trait RangedBuilder<Min, Max>
where Self: Sized
{
fn new(val: Self) -> Ranged<Self, Min, Max>;
}
use core::fmt;
impl<T, Min, Max> fmt::Display for Ranged<T, Min, Max>
where T: fmt::Display
{
fn fmt(&self, f: &mut fmt::Form... | Rust | 0 |
# In order for Panel to work in VS Code you would need the jupyter_bokeh package
# In order for this example to work your would need `panel jupyter_bokeh altair vega_datasets ipykernel`
import panel as pn
import altair as alt
import vega_datasets
pn.extension("vega", sizing_mode="stretch_width")
# Lets show some in... | Python | 1 |
the bounds. Otherise, two curves may be
/// interpolated to generate the result.
pub fn curve_at_x_with_continuation(&self, x: f32) -> IrregularDynamicCurve<f32, f32> {
assert!(self.curves.len() > 0, "Empty curve set");
if x <= self.min_x() {
let curve = &self.curves.first().unwrap(... | Rust | 0 |
b9a647305123b4f4d0741f296\n",
)
.add_file("zbi", "fake zbi");
env.run_system_updater(SystemUpdaterArgs {
initiator: "manual",
target: "m3rk13",
update: Some("fuchsia-pkg://fuchsia.com/another-update/4"),
reboot: None,
})
.await
.expect("run system_updater... | Rust | 0 |
ion_results).T
print("\nSample of detailed NDCI statistics:")
# Check which columns actually exist and display them
available_columns = df_results.columns.tolist()
print(f"Available columns: {available_columns}")
# Display relevant columns that exist
display_columns = []
for col in... | Python | 1 |
NameAttr::StreetName => AttributeTypeAndValue::new_street_name(value),
NameAttr::OrganisationName => AttributeTypeAndValue::new_organisation_name(value),
NameAttr::OrganisationalUnitName => AttributeTypeAndValue::new_organisational_unit_name(value),
};
((self.0).0)[0].0.p... | Rust | 0 |
@classmethod
def code(cls):
return 'ml-20m'
| Python | 1 |
HB8CFG_RDWSR::EPI_HB8CFG_RDWS_2 => 0,
EPI_HB8CFG_RDWSR::EPI_HB8CFG_RDWS_4 => 1,
EPI_HB8CFG_RDWSR::EPI_HB8CFG_RDWS_6 => 2,
EPI_HB8CFG_RDWSR::EPI_HB8CFG_RDWS_8 => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> EPI_H... | Rust | 0 |
if there is already a package version with the same id or the same
/// combination of package_type, namespace_id, package_name and version.
///
/// Returns an error if `package_version` does not have any valid signatures or if any of the valid
/// signatures are associated with a public key that does n... | Rust | 0 |
.2;
out.3 = a.3;
out.4 = a.4;
out.5 = a.5;
}
pub fn identity(out: &mut Matrix2d) {
out.0 = 1.;
out.1 = 0.;
out.2 = 0.;
out.3 = 1.;
out.4 = 0.;
out.5 = 0.;
}
pub fn fromValues(a: f32, b: f32, c: f32, d: f32, tx: f32, ty: f32) -> Ma... | Rust | 0 |
# Increase penalty if constraint violated, or if constraint
# term is NAN
if (try_constraint_val > self._max_constraint_val
or np.isnan(try_constraint_val)):
penalty_scale_factor = self._increase_penalty_factor
... | Python | 1 |
}
impl From<Vec<u8>> for ByteBuf {
fn from(bytes: Vec<u8>) -> Self {
ByteBuf {
blocks: vec![Block::from(bytes)],
idx: 0,
growth: 8 * 1024,
}
}
}
impl ByteBuf {
#[inline]
pub fn new() -> Self {
Self::with_growth(0)
}
#[inline]
pub... | Rust | 0 |
},
ColorSpace::Luv => match i {
0 | 1 => fastrand::u32(0..=100) as f64,
_ => fastrand::u32(0..=360) as f64,
},
ColorSpace::Lab if i == 0 => fastrand::u32(0..=100) as f64,
ColorSpace::HunterLab... | Rust | 0 |
pub tbitem: ItemTbItem,
pub tbitemfunc: ItemTbItemFunc,
pub tbitemextra: ItemTbItemExtra,
pub tbl10ndemo: L10nTbL10NDemo,
pub tbpatchdemo: L10nTbPatchDemo,
pub tbsystemmail: MailTbSystemMail,
pub tbglobalmail: MailTbGlobalMail,
pub tbrolelevelexpattr: RoleTbRoleLevelExpAttr,
... | Rust | 0 |
assert_eq!(6, total_bananas);
/// }
#[macro_export]
macro_rules! impl_op_ex_commutative {
// non-generic
($op:tt |$lhs_i:ident : &$lhs:path, $rhs_i:ident : &$rhs:path| -> $out:path $body:block) => (
$crate::impl_op_ex!($op |$lhs_i : &$lhs, $rhs_i : &$rhs| -> $out $body);
$crate::_parse_binar... | Rust | 0 |
F, E>
where
A: ServiceFactory,
F: Fn(A::Error) -> E + Clone,
{
a: A,
f: F,
e: PhantomData<E>,
}
impl<A, F, E> MapErrServiceFactory<A, F, E>
where
A: ServiceFactory,
F: Fn(A::Error) -> E + Clone,
{
/// Create new `MapErr` new service instance
pub(crate) fn new(a: A, f: F) -> Self {
... | Rust | 0 |
of test cases
safe_cases = [tc for tc in test_cases if tc['expected'] == "SAFE: true"]
unsafe_cases = [tc for tc in test_cases if tc['expected'] == "SAFE: false"]
# Ensure we have both safe and unsafe cases
assert len(safe_cases) > 0, "No safe test cases found"
assert len(unsafe_cases) > 0, "No... | Python | 1 |
_by_value > reference);
/// assert!(reference < gt_by_value);
/// assert!(gt_by_count > reference);
/// assert!(reference < gt_by_count);
/// assert_eq!(reference, equal);
/// assert_eq!(equal, reference);
/// ```
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord)]
pub struct Bin {
value: NotNan<f64>,
... | Rust | 0 |
# encoding: utf-8
"""
Serialization schemas for Team resources RESTful API
----------------------------------------------------
"""
from flask_marshmallow import base_fields
from flask_restplus_patched import ModelSchema
from app.modules.users.schemas import BaseUserSchema
from .models import Team, TeamMember
clas... | Python | 1 |
import networkx as nx
with open('input') as f:
data = list(f.read().strip())
dirs = {'N': 1j, 'S': -1j, 'E': 1, 'W': -1}
def parse(current, data, g, room_stack, end_stack, already_done):
if len(data) in already_done:
return
already_done.add(len(data))
while data:
s = data.pop(0)
... | Python | 1 |
scriptorAllocator::new(initializer);
let desc_index = descriptor_allocator.assign(descriptor_set_config);
let descriptor_distributor = descriptor_allocator.allocate()?;
let ubo_set = descriptor_distributor.acquire(desc_index);
let desc_storage = descriptor_distributor.into_repository()... | Rust | 0 |
device, image.block);
}
}
<gh_stars>1-10
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
anyhow::{anyhow, Context, Error},
fidl_fuchsia_space::{
ErrorCode as SpaceErrorCode, Man... | Rust | 0 |
Op::Gt => write!(f, ">"),
Op::Ba => write!(f, "&"),
Op::Bo => write!(f, "|"),
Op::Set => write!(f, "="),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
enum Variable {
Literal(Value),
Between(Value, Value),
AtLeast(Value),
}
impl Variable {
f... | Rust | 0 |
# Author: Liwei Wang
"""
This example intends to show users how to apply MyRungeKutta to define
own RungKutta solvers.
"""
from odespy import *
#import scitools.basics,easyviz as st
import scitools.std as st
import numpy as np
# arrays to test user-defined Runge-Kutta methods
bt = dict(
FehlBerg = dict(
tabl... | Python | 1 |
x0C => mmu.c += 1,
0x0D => mmu.c = alu::dec(mmu, c),
0x0E => mmu.c = mmu.get_next_byte(),
0x0F => {
mmu.a = rrc(mmu, mmu.a);
mmu.set_flag_z(false);
}
0x11 => {
let d16 = mmu.get_ne... | Rust | 0 |
#Tushar Borole
#Python 2.7
from flask_restful import Resource, Api, request
from package.model import conn
class Appointments(Resource):
"""This contain apis to carry out activity with all appiontments"""
def get(self):
"""Retrive all the appointment and return in form of json"""
appointme... | Python | 1 |
import cv2
import mediapipe as mp
# Initialize MediaPipe Pose
mp_pose = mp.solutions.pose
mp_drawing = mp.solutions.drawing_utils
pose = mp_pose.Pose()
# Load video
cap = cv2.VideoCapture("C:/Users/Lenovo/OneDrive/Desktop/intership project/pose video.mp4") # Replace with your video file
while cap.isOpened():
r... | Python | 1 |
h}, file not found'
ZipFile(path).extractall(path=path.parent) # unzip
dir = path.with_suffix('') # dataset directory == zip name
assert dir.is_dir(), f'Error unzipping {path}, {dir} not found. path/to/abc.zip MUST unzip to path/to/abc/'
return True, str(dir), self._find_yaml(dir) # z... | Python | 1 |
"""
NLP引擎基类
"""
from abc import ABC, abstractmethod
from typing import Optional
from ..context import DialogContext
from ...intent import Intent
class NLPEngine(ABC):
"""NLP引擎基类"""
@abstractmethod
async def initialize(self) -> bool:
"""
初始化引擎
Returns:
bool: 是否初始化成功
... | Python | 1 |
ot be supported soon")
import json
config = json.load(f)
else:
raise TypeError("Unsupported config file type")
logger = Logger(config)
if torch.cuda.is_available() and config.get("use_cuda", True):
device = torch.device("cuda")
logger.print("Using GP... | Python | 1 |
return None
if price is not None:
try:
price_val = float(price)
peak = peaks.get(sym)
if peak is None or price_val > peak:
peaks[sym] = price_val
except (TypeError, ValueError):
pass
action: Optional[str] = None
if change... | Python | 1 |
import torch
from misc.utils import spatial_replication
"""
Implementation of the loss functions defined in the paper at Appendix B.:
https://arxiv.org/pdf/2012.08261.pdf#page=10&zoom=100,66,560
"""
l1 = torch.nn.L1Loss()
bce = torch.nn.BCELoss()
def pixel_losses(real, fake):
"""
Returns the loss function for... | Python | 1 |
two ouf of three dims along which we bilineary interpolate.
inds = [h for h in range(3) if h != plane_idx]
for z in itertools.product(*corner_coords):
l = [None for _ in range(3)]
l[plane_idx] = jnp.zeros_like(x_grid[Ellipsis, 0])
for i, b in enumerate(z):
l[inds[i]] = x_ceil[Ellipsis... | Python | 1 |
lmbda = Sent["lmbda"]
rdm_A = Sent["DM_chain_subsys"]
rdm_B = Sent["DM_other_subsys"]
np.testing.assert_allclose(
p - lmbda**2, 0.0, atol=1e-5, err_msg="Failed lmbda^2 comparison!"
)
np.testing.assert_allclose(
p_rdm_A... | Python | 1 |
(|out_digit| *digits.iter().find(|(_, d)| ***d == *out_digit).unwrap().0)
.fold(0_u64, |tot, d| tot * 10 + d as u64)
})
.sum()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sample1() {
let input =
"be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb f... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.