text
string
label_name
string
labels
int64
or c in text.chars() { if is_meta_character(c) { buf.push('\\'); } buf.push(c); } } /// Returns true if the give character has significance in a regex. /// /// These are the only characters that are allowed to be escaped, with one /// exception: an ASCII space character may be e...
Rust
0
_xfeatures2d"); println!("cargo:rustc-link-lib=opencv_highgui"); //println!("cargo:rustc-link-lib=opencv_img_hash"); println!("cargo:rustc-link-lib=opencv_imgcodecs"); println!("cargo:rustc-link-lib=opencv_imgproc"); println!("cargo:rustc-link-lib=opencv_objdetect"); // p...
Rust
0
transform = T.NormalizeFeatures() if name == 'amazon-photo': torch_dataset = Amazon(root=f'{data_dir}Amazon', name='Photo', transform=transform) elif name == 'amazon-computer': torch_dataset = Amazon(root=f'{data_dir}Amazon', name...
Python
1
#[inline(always)] pub fn lpsc(&self) -> LPSC_R { LPSC_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 17 - OverCurrentIndicatorChange This bit is set by hardware when a change has occurred to the OCI field of this register."] #[inline(always)] pub fn ocic(&self) -> OCIC_R { OC...
Rust
0
from __future__ import annotations import os from argparse import Namespace from uuid import uuid4 import numpy as np import rerun as rr import rerun.blueprint as rrb README = """\ # Entity drag-and-drop The goal of this test is to check the behavior of views when entities are dragged-and-dropped over them. The dra...
Python
1
Some(v) => format!( "{}/api/v4/groups/{}/{}?per_page={}", host.unwrap_or(&"https://gitlab.com".to_string()), v, domain, per_page ), None => match user { Some(u) => format!( "{}/api/v4/users/{}/{}?per_page={}", host.unwrap_or(&"...
Rust
0
ok', interval=1, img_shape=(256, 256, 3))) log_processor = dict(type='LogProcessor', window_size=50, by_epoch=True) ############################### running schedule ################################# # model settings norm_cfg = dict(type='SyncBN', requires_grad=True) data_preprocessor = dict...
Python
1
for fullClass in failures: testcase = fullClass[(fullClass.rindex(".") + 1) :] if failures[fullClass] == config.testIters: tests[testcase] = re.sub(reTestsSeed, "", oldTests[testcase]) if len(tests) > 0: print("\n[repro] Re-testing 100%% failures at the tip of ...
Python
1
bindgen output"); let out_dir = std::env::var("OUT_DIR").expect("build out dir"); bindings .write_to_file(PathBuf::from(out_dir).join("kcp.rs")) .expect("writing bindings"); } fn main() { build_enet( format!("{}/third_party/enet", env!("CARGO_MANIFEST_DIR")).into(), ); bui...
Rust
0
pedIndex, { _marker: PhantomData<K>, slice: [V], } impl<K, V> SliceMap<K, V> where K: TypedIndex, { /// Gets a reference to the value at the given index. pub fn get(&self, index: K) -> Option<&V> { self.slice.get(index.index()) } /// Gets a mutable reference to the value at the giv...
Rust
0
# Copyright 2016 Bridgewater Associates # # 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 appli...
Python
1
_highlighted_people(); let mut batch = GeomBatch::new(); let mut quadtree = QuadTree::default(app.map().get_bounds().as_bbox()); // It's quite silly to produce triangles for the same circle over and over again. ;) let car_circle = Circle::new( Pt2D::new(0...
Rust
0
} if value in timezone_map: value = timezone_map[value] else: value = None # set to None if it doesn't pass the validation try: if model_instance: value = fie...
Python
1
_encrypted) = match encode_encrypt(cli, to) { Ok((encoded, encrypted)) => (encoded, encrypted), Err(e) => panic!("{}", e), }; // compose the extrinsic let xt: UncheckedExtrinsicV4<([u8; 2], Vec<u8>, u128, H256)> = compose_extrinsic!(chain_api, TEEREX, "shield_funds", to_encrypted, *amount, shard); let tx_has...
Rust
0
Debug; use traits::Weight; impl<T> Weight for Ratio<T> where T: Clone + Integer + Debug, i64: Into<T>, { #[inline] fn from_i64(n: i64) -> Ratio<T> { Ratio::from_integer(n.into()) } } // 能被并发读写,内部可变性 // TODO: 传入所有权, 返回所有权 #![no_std] use rkalloc::*; use core::sync::atomic::{AtomicU32, Order...
Rust
0
ile() snowboydecoder.play_audio_file() # 关闭snowboy功能 self.detector.terminate() # 开启语音识别 ## 这里放唤醒后要执行的函数 self.mainSpeechFunc() # 打开snowboy功能 self.waitUntilAwakened() # wake_up —> monitor —> wake_up 递归调用 # 热词唤醒(snowboy目前暂不支持Windows) def waitUntilA...
Python
1
b::{HttpResponse, ResponseError, Result, Scope, web::{Data, Query, get, scope}}; use actix_web::body::BoxBody; use serde::Serialize; use crate::app::config::SpotifyConfig; use crate::app::models::spotify::{AuthResponse, RequestAttributes, SpotifyAuthorization, SpotifySignin, SpotifySigninError}; #[derive(Debug, Seria...
Rust
0
0[row..]); ntt(&mut w); poly_mul(&mut w,&c); intt(&mut w); poly_negate(&mut r,&w); if infinity_norm(&r) >= GAMMA2 { badone=true; break; } poly_sub(&mut ay[row..],&r); poly_soft_reduce(&mut a...
Rust
0
utils::BytesWriter::new(); for cook in jar.delta() { let name = utf8_percent_encode(cook.name(), USER_INFO_ENCODE_SET); let value = utf8_percent_encode(cook.value(), USER_INFO_ENCODE_SET); let _ = write!(&mut buffer, "; {}={}", name, value); } ...
Rust
0
""" Asynchronous socket implementation - same functionality but with asynchronous flavour! """ # Allow forward references in type hints (Python>=3.7) from __future__ import annotations import select import typing as T import socket from future import Future Data = bytes class AsyncSocket: def __init__(self, so...
Python
1
index: 0 }; let tmp = miller_loop(&mut adder); MillerLoopResult(tmp) } /// Invoke the pairing function without the use of precomputation and other optimizations. #[cfg_attr(docsrs, doc(cfg(feature = "pairings")))] pub fn pairing(p: &G1Affine, q: &G2Affine) -> Gt { struct Adder { cur: G2Projectiv...
Rust
0
LinePos(MovePosition::Beginning), 0) ), ( CMAP, "<C-C>", command_unfocus!() ), ( CMAP, "<C-D>", unmapped!() ), ( CMAP, "<C-E>", edit!(EditAction::Motion, MoveType::LinePos(MovePosition::End), 0) ), ( CMAP, "<C-G>", unmapped!() ), ( CMAP, "<C-L>", unmapped!() ), ( CMAP, "<...
Rust
0
ork": { //! "city": "Anytown", //! "country": "USA", //! "state": "New York", //! "street": "101 Main Street" //! } //! */ //! }, //! //! // Consider adding a note field to the `other` contact option //! contact_options: [ //! { //! work: { //! ...
Rust
0
import pytest from src.api.base_api import ApiClient from src.api.files_api import FilesApi from src.api.store_api import StoreApi from src.api.pet_api import PetApi from src.factories.order_factory import OrderFactory from src.factories.pet_factory import PetFactory from utils.logger import Logger @pytest.fixture(s...
Python
1
# Copyright The Caikit 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 writing...
Python
1
currency_manager.global_min_lock_ts(), None); let ts_seqs = vec![ vec![20, 30, 40], vec![40, 30, 20], vec![20, 40, 30], vec![30, 20, 40], ]; let keys: Vec<_> = vec![<KEY>"] .into_iter() .map(|k| Key::from_raw(k)) ...
Rust
0
0xFB, 0x98), PALETURQUOISE: rgb(0xAF, 0xEE, 0xEE), PALEVIOLETRED: rgb(0xDB, 0x70, 0x93), PAPAYAWHIP: rgb(0xFF, 0xEF, 0xD5), PEACHPUFF: rgb(0xFF, 0xDA, 0xB9), PERU: rgb(0xCD, 0x85, 0x3F), PINK: rgb(0xFF, 0xC0, 0xCB), PLUM: rgb(0xDD, 0xA0, 0xDD), POWDERBLUE: rgb(0xB0, 0xE0, 0xE6), PURP...
Python
1
] key = cls._get_tex_source(tex, fontsize), dpi alpha = cls._grey_arrayd.get(key) if alpha is None: pngfile = cls.make_png(tex, fontsize, dpi) rgba = mpl.image.imread(os.path.join(cls._texcache, pngfile)) cls._grey_arrayd[key] = alpha = rgba[:, :, -1] ...
Python
1
# Copyright (C) 2014 Anaconda, Inc # SPDX-License-Identifier: BSD-3-Clause import logging import sys from os.path import abspath, expanduser from .. import api from ..conda_interface import ArgumentParser from ..deprecations import deprecated logging.basicConfig(level=logging.INFO) epilog = """ Tool to convert pack...
Python
1
terner` uses an `Arc<ThreadedRodeo>` and thus /// can be cloned to create more references. #[derive(Debug, Clone)] pub struct StringInterner { rodeo: Arc<ThreadedRodeo>, } impl StringInterner { /// Creates a new string interner. pub fn new() -> Self { Self { rodeo: Arc::new(ThreadedRode...
Rust
0
::min_value().into() && val <= u8::max_value().into() ); *pixel = T::cast_from(val); } } for (i, row) in rec_plane.data.chunks_mut(rec_plane.cfg.stride).enumerate() { for (j, pixel) in row.iter_mut().enumerate() { let val = (j as i32 - i as i32 - xpad_off) & 255i32; ...
Rust
0
, 1, 3, 3)); } #[test] fn test_approx_equal() { assert!(approx_equal(0., 0., 0.)); assert!(approx_equal(1., 0., 1.)); assert!(approx_equal(-0.1, -0.2, 0.3)); assert!(!approx_equal(1., 0., 0.5)); assert!(!approx_equal(-1., 1., 1.)); } // #[test] fn test_ch...
Rust
0
ro_rules! external_name { ("typeof") => { "_typeof" }; ("instanceof") => { "_instanceof" }; ("throw") => { "_throw" }; ($s:literal) => { $s }; } macro_rules! helper { ($field_name:ident, $s:tt) => {{ helper!(::swc_common::DUMMY_SP, $field_name...
Rust
0
Texture, pub white_planet: Texture, pub blue_planet: Texture, pub red_ring: Texture, pub white_ring: Texture, pub blue_ring: Texture, pub dead_planet: Texture, pub star: AnimationData, pub explosion: AnimationData, pub enemy: AnimationData, } impl WorldAssets { pub fn new<L: R...
Rust
0
let zeros = self.bb.0.trailing_zeros(); self.c = self.c << zeros; self.bb = self.bb >> zeros; let ret = Some(self.c); self.c = self.c << 1u32; self.bb = self.bb >> 1u32; ret } } } // u64 with exactly 1 bit filled, represent...
Rust
0
#! /usr/bin/env python import openturns as ot ot.TESTPREAMBLE() # DEFAULT CONSTRUCTOR AND STRING CONVERTER print("test : default constructor and string converter") # Default constructor triangularMatrix0 = ot.TriangularMatrix() # String converter print("triangularMatrix0 = ", repr(triangularMatrix0)) # CONSTRUCT...
Python
1
if history.len() > 1 { let vertices = history .iter() .map(|v| pt2(v.x, v.y)) .enumerate() .map(|(_, p)| { let rgba = srgba(0.0, 0.0, 0.0, 1.0); (p, rgba) }); draw.polyline().weight(1.0).colored_points(vertic...
Rust
0
write!(f, "FIELD"), DirectiveLocation::FragmentDefinition => write!(f, "FRAGMENT_DEFINITION"), DirectiveLocation::FragmentSpread => write!(f, "FRAGMENT_SPREAD"), DirectiveLocation::InlineFragment => write!(f, "INLINE_FRAGMENT"), DirectiveLocation::Schema => write!(f, "SC...
Rust
0
e020100300506032b65700422042017ed9c73e9db649ec189a612831c5fc5 70238207c1aa9dfbd2c53e3ff5e5ea85" ); /// Ciphertext of Ed25519 PKCS#8 private key when encrypted using /// PBKDF2-SHA256 as the KDF. /// /// Extracted with: /// $ openssl asn1parse -inform der -in pkcs8/tests/examples/ed25519-encpriv-aes256-pbkdf2-sha2...
Rust
0
{ let mut dev = FTx232H::init_chan($vendor, $product, $channel).unwrap(); dev.loopback(true).unwrap(); assert_eq!(dev.is_loopback(), true); let mut spidev = dev.spi(SpiSpeed::CLK_AUTO).unwrap(); // loopback: 1-byte messages ...
Rust
0
_minute = Duration::from_secs(60); assert_eq!(format_duration(&single_minute), String::from("01:00")); } #[test] fn test_seconds() { let seconds = Duration::from_secs_f32(1.12); assert_eq!(format_duration(&seconds), "00:01.12"); let seconds_leftover = Duration::from_secs_f3...
Rust
0
---' if F>best_f1: best_f1=F best_e=0 saver.save(sess,checkpoints_model) else: best_e+=1 test_pred = [] for i in range(0, len(x_test), config.batch_size): input_x = x_test[slice(i, i + confi...
Python
1
use try_zip::{try_zip, TryZip}; mod race; pub use race::{race, Race}; mod race_ok; pub use race_ok::{race_ok, RaceOk}; // // Copyright (C) 2019 Swift Navigation Inc. // Contact: https://support.swiftnav.com // // This source is subject to the license found in the file 'LICENSE' which must // be be distributed togethe...
Rust
0
link, instrument, channel_title, views, duration, published_date, likes, comments, description, tags, thumbnail_url, category_id, live_broadcast_content, default_audio_language, licensed_content, definition, caption_status) ) conn.commit() except HttpError as e: print(f"An HTTP error oc...
Python
1
auses, exclude=True).apply( expr ) if not self._pagination_query_required(): expr = LimitQuery(limit_count=self.limit_count).apply(expr) expr = OffsetQuery(query_offset=self.query_offset).apply(expr) expr = OrderQuery(sorted_orders=self.sorted_orders).apply(ex...
Python
1
lue2), chunk.get_constant(index2)); assert_eq!(Some(&value3), chunk.get_constant(index3)); } <reponame>CleverCloud/clevercloud-sdk-rust<filename>examples/cleverctl/src/cmd/addon/config_provider/environment.rs use std::{path::PathBuf, sync::Arc}; use clevercloud_sdk::{ oauth10a::{ proxy::{self, ProxyConne...
Rust
0
from __future__ import annotations import re import typing from typing import Any, Callable, TypeVar import numpy as np import pytest import matplotlib as mpl from matplotlib import _api if typing.TYPE_CHECKING: from typing_extensions import Self T = TypeVar('T') @pytest.mark.parametrize('target,shape_repr,...
Python
1
arity) } /// Defines a method for `name` on `self` that calls `f` when invoked. /// /// **Note:** This method can be unwieldy to use and so it is recommended to /// instead call the convenience macro [`def_method!`]. /// /// # About `MethodFn` /// /// - The first argument is _alway...
Rust
0
import numpy as np import pandas as pd def create_negative_samples(ratings_df, n_negatives=5, random_seed=42): """ Create negative samples for each user by sampling from items they haven't interacted with. Args: ratings_df: DataFrame containing user-item interactions n_negatives: Numbe...
Python
1
.7/0 V", _ => "", } } fn analog_display_type(features: u8) -> &'static str { match features & 0x18 { 0x0 => "Monochrome or grayscale", 0x8 => "RGB color", 0x10 => "Non-RGB color", _ => "Undefined", } } fn supported(v: bool) -> &'static str { match v { tr...
Rust
0
} } } } } } } use flo_ui::*; use objc::*; use objc::rc::*; use objc::runtime::*; use cocoa::base::*; use std::ops::Deref; const UTF8_ENCODING: usize = 4; /// /// Wrapper for the FloProperty bridging class /// pub struct FloProperty ...
Rust
0
hasta que el usuario escriba 'salir' while True: # Pedimos al usuario que escriba una opción: documento, 'imprimir' o 'salir' opcion = input("Añade un documento o selecciona imprimir/salir: ") # Si el usuario escribe 'salir' (ignorando mayúsculas/minúsculas) if opcion.lower() == "s...
Python
1
pin_num in 0u32..16 { let pin_name = format!("P{}{}", port_letter, pin_num); pins_table.push(vec![ pin_name, p.name.to_string(), port_num.to_string(), pin_num.to_string(), ...
Rust
0
Some(type_params) = &node.type_params { items.extend(parse_node(type_params.into(), context)); } items.push_condition(conditions::if_above_width_or( context.config.indent_width, if use_space { Signal::SpaceOrNewLine } else { Signal::PossibleNewLine }.into(), if use_space { " ".into() } els...
Rust
0
0, shrinkB=sqrt(kwargs['node_size']) / 2.0, connectionstyle="arc3,rad=0.08", # rad control angle )) nx.draw_networkx_nodes(G, pos, node_color=node_colors, **kwargs) # define node labels if self.molecule: if nolabel: node_labels = {n: f'{self.t...
Python
1
end(case) with open(os.path.join(self.checkpoint_dir, phase + '_eval.csv'), 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=list(content[0].keys())) writer.writeheader() for case in content: writer.writerow(case) # log validation metrics...
Python
1
from locations.categories import Categories, apply_category from locations.storefinders.yext import YextSpider class BuildersFirstsourceUSSpider(YextSpider): name = "builders_firstsource_us" item_attributes = {"brand": "Builders FirstSource", "brand_wikidata": "Q27686100"} api_key = "75d03100e13baa02575a0...
Python
1
enrolled result = f.searchTemplate() positionNumber = result[0] if ( positionNumber >= 0 ): mylcd.lcd_clear() mylcd.lcd_display_string('Template already',1) mylcd.lcd_display_string('exists at ',2) mylcd.lcd_display_string('position # ',3) mylcd.lcd_display_string(str(positionNum...
Python
1
#!/usr/bin/python3 from db_ingest import DBIngest from db_query import DBQuery from signal import signal, SIGTERM from rec2db import Rec2DB from runva import RunVA from language import text from threading import Event from configuration import env import traceback office = list(map(float, env["OFFICE"].split(","))) d...
Python
1
# Copyright 2022 Cartesi Pte. Ltd. # # SPDX-License-Identifier: Apache-2.0 # 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 appl...
Python
1
with PdfPages(filtered_pdf_file_name) as pdf: with PdfPages(edge_detection_pdf_file_name) as pdf2: # Apply the filteron all the noisy images: for noisy_image, title, noise_type, noise_level, original in images: apply_all_filters_and_save(original, noisy_image, title, nois...
Python
1
def get_price_prediction_answer(card_id): answers = { "10964": "1158000", "10962": "13000", "10963": "41000", "10965": "63000", "10967": "32000", "10966": "3539000", "10968": "19000", "10969": "13000", "10970": "18000", "10971": "16000" } return answers.get(str(card_id),...
Python
1
pub generator: Box<Generator>, } impl Generator for Many { fn generate(&self) -> Vec<u8> { trace!("generate Many"); let num = thread_rng().gen_range(0, MANY_MAX); (0..num).flat_map(|_| self.generator.generate()).collect() } fn negate(&self) -> Vec<u8> { trace!("negate ...
Rust
0
_off, sparse_df) sparse_df.drop(columns=rare_codes + pointless_codes, inplace=True) sparse_df.rename(columns=words_dict, inplace=True) #sparse_df = add_apache_diag(sparse_df, eICU_path, cut_off) print('==> Keeping ' + str(sparse_df.shape[1]) + ' diagnoses which have a prevalence of more than ' + str(cut...
Python
1
tleReasonHwPowerBrakeSlowdown: u32 = 128; pub const nvmlClocksThrottleReasonDisplayClockSetting: u32 = 256; pub const nvmlClocksThrottleReasonNone: u32 = 0; pub const nvmlClocksThrottleReasonAll: u32 = 511; pub const NVML_NVFBC_SESSION_FLAG_DIFFMAP_ENABLED: u32 = 1; pub const NVML_NVFBC_SESSION_FLAG_CLASSIFICATIONMAP_E...
Rust
0
.addSortMethod(Handle, xbmcplugin.SORT_METHOD_VIDEO_RUNTIME) break if ContentType == 'Season': xbmcplugin.addSortMethod(Handle, xbmcplugin.SORT_METHOD_VIDEO_SORT_TITLE) xbmcplugin.addSortMethod(Handle, xbmcplugin.SORT_METHOD_VIDEO_YEAR) xbmcplugin.addSortMethod(H...
Python
1
ds.hash(state); self.mc_err.hash(state); self.mc_rip.hash(state); self.mc_cs.hash(state); self.mc_rflags.hash(state); self.mc_rsp.hash(state); self.mc_ss.hash(state); self.mc_len.hash(state); ...
Rust
0
f()) .next(); if let Some(use_return_for_result) = use_return_for_result { if typ == Default::default() { error!("Function \"{}\": use_return_for_result set to true, but function has no return value", func_name); return false; } return *use_return_for_result; ...
Rust
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ ═══════════════════════════════════════════════════════════════════ CCMP4 视频合成模块 第三阶段:最终视频重建和音视频合成 ═══════════════════════════════════════════════════════════════════ 功能概述: - 高质量视频处理 - 音视频精确同步 - 智能编码优化 - 多格式输出支持 作者:CCMP4 开发团队 版本:3.0.0 (第三阶段) """ import os import te...
Python
1
PositionRef, contributions: contributions::velocity::Collection<N, D>, ) -> Self { #[allow(clippy::cast_precision_loss)] Self { v, sampling_position, contributions: contributions.generalize(), } } pub(in crate::integration_step) fn abstra...
Rust
0
here the keys are memory region names and the values are arrays of initialization data. :return: An array of measurement results (0 or 1) of shape (trials, len(qubits)) """ if qubits is None: qubits = sorted(cast(set[int], quil_program.get_qubits(indices=Tr...
Python
1
if property_name in memeber_set: memeber_set.remove(property_name) if len(memeber_set) > 0: warnings.warn("%s fileds are useless." % ",".join(memeber_set)) class CreateBlockIgnoreRuleNewResponse(AbstractModel): r"""CreateBlockIgnoreRuleNew返回参数结构体 """ ...
Python
1
resource.authenticated); ``` ##### > Serialize and de-serialize a `Keypair`, `SecretKey` and `PublicKey` As `Keypair`, `SecretKey` and `PublicKey` are reflected from [ed25519_dalek](https://docs.rs/ed25519-dalek/latest/ed25519_dalek/), you could refer to their docs to read further about them. These are needed for any...
Rust
0
_low_t = 128; /// The `xkb::VModsLow::6` enum variant. /// /// This is a variant of [`xcb_xkb_v_mods_low_t`]. pub const XCB_XKB_V_MODS_LOW_6: xcb_xkb_v_mods_low_t = 64; /// The `xkb::VModsLow::5` enum variant. /// /// This is a variant of [`xcb_xkb_v_mods_low_t`]. pub const XCB_XKB_V_MODS_LOW_5: xcb_xkb_v_mods_low_t = ...
Rust
0
(Event::Nomatch { parent: parent, location: loc.to_string() }) ) ) ); #[cfg(test)] mod tests { use super::*; #[test] fn test_notify() { let txt = "!system=USB subsystem=INTERFACE type=ATTACH ugen=ugen0.2 vendor=0x1050 sernum=\"\" mode=host\n"; let res = event(txt); le...
Rust
0
367544c494011e3317dbf9a509cb1e5dc1e85a941bbee3d7f2afbc9b1" }, Test { input: "The quick brown fox jumps over the lazy dog.", output_str: "ed892481d8272ca6df370bf706e4d7bc1b5739fa2177aae6c50e946678718fc67a7af2819a021c2fc34e91bdb63409d7" }, ]; ...
Rust
0
ignoring it", s)); loop; } } let dir = LogDirective {name: name, level: log_level}; dirs.push(dir); } return dirs; } /// Set the log level of an entry in the crate map depending on the vector /// of log directives fn update_entry(dirs...
Rust
0
when the fixed proposer is down. Rotating proposers /// won't gather quorum certificates to machine loss/byzantine behavior on f/n rounds. pub struct RotatingProposer<T, P> { // Ordering of proposers to rotate through (all honest replicas must agree on this) proposers: Vec<P>, // Number of contiguous round...
Rust
0
_tys, ret_tys, fun, } = host_fn; let ty_idx = module.add_type(wasm::FunctionType::new(arg_tys, ret_tys)); let fun_addr = self.store.allocate_host_fun(module_addr, ty_idx, fun); let fun_idx = module.add_fun(fun_addr); module.add...
Rust
0
("(a b)", list!(sym!("a"), sym!("b"))); compare_fmt("(a . b)", cons(sym!("a"), sym!("b"))); } #[test] fn test_iter() { let list: Datum<()> = Datum::Cons( Rc::new(RefCell::new(Datum::Num(1))), Rc::new(RefCell::new(Datum::Cons( Rc::new(RefCell::new(Datu...
Rust
0
des, hessian, cart_local_modes, optimize="greedy" ) lmlm = np.einsum("im,ij,jm->m", L, hessian, L, optimize="greedy") # Eq. (27) in [2] # S has shape (nlocalmodes, nnormalmodes) S = anlm**2 / anan[:, None] / lmlm[None, :] # Eq. (30) in [2] C = S / S.sum(axis=0)[None, :] return S, C @...
Python
1
4_: 16275721671749807405u64, }; pub const TM_TT_TYPE_HASH__NETWORK_SETTINGS: StrhashT = StrhashT { u64_: 4133456848111380615u64, }; pub const TM_TT_TYPE_HASH__LOCALIZATION_SETTINGS: StrhashT = StrhashT { u64_: 12227184065019180970u64, }; pub const TM_TT_TYPE_HASH__TRANSLATION: StrhashT = StrhashT { u64_: 16...
Rust
0
u32, 7u32, 7u32, 8u32, 8u32, 9u32, 9u32, 10u32, 10u32, 11u32, 11u32, 12u32, 12u32, 13u32, 13u32, 14u32, 14u32, 15u32, 15u32, 16u32, 16u32, 17u32, 17u32, 18u32, 18u32, 19u32, 19u32, 20u32, 20u32, 21u32, 21u32, 22u32, 22u32, 23u32, 23u32, 24u32, 24u32]; static kInsertOffset: [u32; 24] = [0u32, 1u32, 2u32, 3u3...
Rust
0
# -*- coding: utf-8 -*- """ Created on Fri Nov 10 14:17:58 2017 @author: Balázs Hidasi """ import theano from theano import tensor as T import numpy as np import custom_theano_ops as cto disable_custom_op = False def gpu_diag_wide(X, keepdims=False): E = T.eye(*X.shape) return T.sum(X*E, axis=1, keepdims=ke...
Python
1
mod task_node_test; use std::fs::read_to_string; use std::process; pub struct Fasta { pub sequence : Vec<String>, pub title : Vec<String>, } impl Fasta { pub fn new( arg : &String ) -> Fasta { let fin = read_to_string( ( *arg ).as_str() ).expect( "FAILED to open input file" ); let mut seq_list : Vec<St...
Rust
0
PIO1_PIN17_SEC_MASK_A { #[doc = "0: Pin state is blocked to non-secure world."] BLOCKED = 0, #[doc = "1: Pin state is readable by non-secure world."] READABLE = 1, } impl From<PIO1_PIN17_SEC_MASK_A> for bool { #[inline(always)] fn from(variant: PIO1_PIN17_SEC_MASK_A) -> Self { variant a...
Rust
0
, message: _, } => { browser.log(format!("Sending message {}", message_id)).await; } _ => (), }; } }; let result = send_message( ton.clone(), ParamsOfSendMessage { message: fix...
Rust
0
import numpy as np def rollout_policy_fn(board): """A random and fast version of policy function used in rollout phase(also called default policy). Rollout phase(default policy) means we play randomly until the game terminated and get the final result. We then back-propagate this result to all...
Python
1
# Generated by Django 5.0.4 on 2024-10-20 03:42 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('DetectorApp', '0001_initial'), ] operations = [ migrations.AddField( model_name='userimage', name='was_processed', ...
Python
1
ks = [ executor.submit( process_sample, full_paths[idx*2], full_paths[idx*2+1], processor ) for idx in range(n_samples) ] # 收集线程任务结果 for future in as_completed...
Python
1
/* TODO: Update let fragment = gfx::ShaderSource { glsl_120: Some(FRAGMENT_SRC[0]), glsl_150: Some(FRAGMENT_SRC[1]), .. gfx::ShaderSource::empty() }; */ let set = factory.create_shader_set(&VERTEX_SRC[1], &FRAGMENT_SRC[1]).unwrap(); let vertex...
Rust
0
(&self, bufs: &[&[u8]]) -> Result<usize> { apply_fn_on_any_socket!(&self.socket, |socket| { socket.writev(bufs).await }) } pub fn access_mode(&self) -> AccessMode { // We consider all sockets both readable and writable AccessMode::O_RDWR } pub fn status_flags(&self) -> StatusFl...
Rust
0
ORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: model = TrajectoryTransformerModel.from_pretrained(model_name) self.assertIsNotNone(model) @require_torch class TrajectoryTransformerModelIntegrationTest(unittest.TestCase): @slow def test_prediction(self): batch_size = 1 config...
Python
1
), blurry, 3hands,4fingers,3arms, bad anatomy, missing fingers, extra digit, fewer digits, cropped, jpeg artifacts,poorly drawn face,mutation,deformed", "sampler_name": "DPM++ SDE Karras", "steps": 20, # 25 "cfg_scale": 8, "width": 512, "height": 768, "seed": -1, } ...
Python
1
"starship_preexec" && "$dbg_trap" != "starship_preexec_all" ]]; then function starship_preexec_all(){ $dbg_trap; starship_preexec; }; trap starship_preexec_all DEBUG; fi; PROMPT_COMMAND=starship_precmd; STARSHIP_START_TIME=$(date +%s); fi; "##; /* For zsh: preexec_funct...
Rust
0
f.count_spin.value() a = (mat.get("buy_price", 0) + mat.get("fee", 0)) * cnt b = self.sale_price.value() * cnt unit_profit = self.sale_price.value() - (mat.get("buy_price", 0) + mat.get("fee", 0)) total_profit = b - a self.result.setText( f"개당 이익: {unit_profit} ({'이익'...
Python
1
p_client.status.success()); let remote_inspect = wash() .args(&["par", "inspect", HTTP_FAKE_OCI, "-o", "json"]) .output() .expect("failed to inspect remote cached registry"); assert!(remote_inspect.status.success()); let remote_inspect_output = output_to_string(remote_inspect); ...
Rust
0
umpy.linspace(0, 15.8, 80): xaxisthetis1.append(i) if conservative: baththetis1.append(-solver_obj.fields.bathymetry_2d.at([i, 0.55])) else: baththetis1.append(-solver_obj.fields.bathymetry_2d.at([i, 0.55])) if os.getenv('THETIS_REGRESSION_TEST') is None: # Compare model and experimenta...
Python
1
_triple( offset_u64, offset_u64 + 1, |(a, b, c): (&mut u64, &u64, &u64)| { *a = (*b >> $bits) | (*c << (64 - $bits)); }, ) }; } macro_rules! shift_branched_triples { ...
Rust
0
assert_eq!(rr.committed_value, change); assert_eq!(&rr.proof_message, proof_message); let full_rewind_result = tx.body.outputs()[0] .full_rewind_range_proof(&factories.range_proof, &rewind_key, &rewind_blinding_key) .unwrap(); ...
Rust
0