text
string
label_name
string
labels
int64
td class=\"col2\">2</td></tr>\n<tr class=\"row3\"><td class=\"col1\">1</td><td class=\"col2\">2</td></tr>\n", "{% tablerow n in numbers cols:2%}{{tablerowloop.col}}{% endtablerow %}", v!({"numbers": [1, 2, 3, 4, 5, 6]})); } #[test] #[should_panic] // liquid-rust#282 fn test_quoted_fragment() { asse...
Rust
0
paces=True): # Preprocessing step to replace '_symmetry_space_group_name_H-M Pm' # with '_symmetry_space_group_name_H-M Pm_sg',to disambiguate from atom 'Pm', # or any space group symbol to avoid problematic cases, like 'P1' spacegroups = "|".join(SPACE_GROUPS) cif_string = re....
Python
1
components. #[derivative(Debug = "ignore")] pub health_pointses: ReadStorage<'s, HealthPoints>, /// `SkillPoints` components. #[derivative(Debug = "ignore")] pub skill_pointses: ReadStorage<'s, SkillPoints>, /// `ChargeTrackerClock` components. #[derivative(Debug = "ignore")] pub charge...
Rust
0
#How can you pick a random item from a list or tuple? import random l = [1, 2, 3, 4, 5, 6, 7, 8, 9,10] print(random.choice(l))
Python
1
ov = PI/3.0; // Construct world let mut world = World::new(); let mut shape_list = ShapeList::new(); let mut floor = Plane::new(&mut shape_list); floor.transform = scaling(10.0, 0.01, 10.0); let mut material = Material::new(); material.color = Color::from_hex("FFE2BA"); material.specul...
Rust
0
""" Wrapper around the game submodules. File information: - Author: Vincent Therrien (therrien.vincent.2@courrier.uqam.ca) - File creation date: January 2025 - License: MIT """ import auroral.game1.environment as env1 import auroral.game1.render as render1 from auroral.game1.game import frame as f...
Python
1
(self) -> f64 { self.numerator as f64 / self.denominator as f64 } } impl Debug for Fraction { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Fraction({}, {})", self.numerator, self.denominator) } } impl Display for Fraction { fn fmt(&self, f: &mut fmt::Formatter<...
Rust
0
changes_detected } fn relative_path(&self, path: &Path) -> PathBuf { let diff = if path.is_absolute() { pathdiff::diff_paths(path, &std::fs::canonicalize(&self.asset_path).unwrap()) } else { pathdiff::diff_paths(path, &self.asset_path) }; diff.unwrap_or_e...
Rust
0
x = self.stem(x) else: x = self.conv1(x) x = self.norm1(x) x = self.relu(x) x = self.maxpool(x) outs = [] for i, layer_name in enumerate(self.res_layers): res_layer = getattr(self, layer_name) x = res_layer(x) if...
Python
1
# This sample demonstrates the use of an interface node map. # Here we are going to use the interface node map of a Basler CXP interface # card to toggle 'Power Over CoaXPress' (PoCXP) between 'Auto' and 'Off'. from os import environ from pypylon import pylon # First check if GENICAM_GENTL64_PATH environment variable...
Python
1
from __future__ import annotations import json import asyncio from aiohttp import ClientSession, TCPConnector from urllib.parse import urlencode from ..typing import AsyncResult, Messages from .base_provider import AsyncGeneratorProvider, ProviderModelMixin from .helper import format_prompt class Feedough(AsyncGene...
Python
1
er_structs_with_options() { #[derive(Serialize, Deserialize, PartialEq, Debug)] struct Foo { a: Option<Box<Foo>>, b: Bar, } #[derive(Serialize, Deserialize, PartialEq, Debug)] struct Bar { a: String, b: f64, } let v = Foo { a: Some(Box::new(Foo { ...
Rust
0
from django.urls import path from . import views app_name = 'profiles' urlpatterns = [ path('accounts/login/',views.loginview,name='login'), path('accounts/logout/',views.logoutview,name='logout'), path('accounts/signup/',views.signupview,name='signup'), path('accounts/profile/',views....
Python
1
def scan_folder(self, subfolder): # Handle nested folders files = os.listdir(subfolder) if files and os.path.isdir(os.path.join(subfolder, files[0])): subfolder = os.path.join(subfolder, files[0]) # Check for archive files archive_files = ...
Python
1
# This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT. # See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details. # Author(s): Vincent Rouvreau # # Copyright (C) 2016 Inria # # Modification(s): # - 2025/03 Thibaud Kloczko: Use nanobind inst...
Python
1
Boolean(x(a)?.num() > x(b)?.num())), Progge::And([a, b]) => Some(Value::Boolean(x(a)?.bool() && x(b)?.bool())), Progge::Or([a, b]) => Some(Value::Boolean(x(a)?.bool() || x(b)?.bool())), Progge::Not(a) => Some(Value::Boolean(!x(a)?.bool())), _ => None, } } ...
Rust
0
: # OpenVINO requires ONNX f[2] = export_onnx(model, im, args.weights, args.opset, args.dynamic, args.half, args.simplify) # opset 12 if openvino: f[3] = export_openvino(args.weights, args.half) if tflite: export_tflite(f, False) # Finish f = [str(x) for x in f if x] # filter...
Python
1
_field_sqrt_unittest!(FieldElement); } mod gm { use super::super::Scalar; use crate::fiat_field_unittest; fiat_field_unittest!(Scalar); } } // Copyright (c) 2020-2022 <NAME> <<EMAIL>>, // <NAME> <<EMAIL>>, // <NAME> <<EMAIL>> // // L...
Rust
0
:\n{:#?}", stringify!( $src ), quote!{ #src2 }, $src ) }}; } /// /// Macro to generate syn error either with span of a syntax tree element or with default one `proc_macro2::Span::call_site()`. /// /// # Sample /// ``` /// # use wproc_macro::*; /// syn_err!( "No attr" ); /// # () /// ``` /// #[ macro_export ] macro...
Rust
0
inks: usize, n_steps: usize, b: &mut Bencher) { // Setup network let stepper = Sink::<usize>::new(); let sinks: Vec<_> = (0..n_sinks).map(|_| Sink::new()).collect(); let counters: Vec<_> = sinks .iter() .map(|sink| sink.stream().fold(0, |n, _| n + 1)) .collect(); let walker =...
Rust
0
. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. mod allocator; pub mod caching_object_handle; mod constants; pub mod crypt; pub mod data_buffer; pub mod directory; pub mod filesystem; pub mod fsck; mod graveyard; mod journal; mod merge; pub mod object_manager; ...
Rust
0
in range(start_index + seq_len, seq_max, seq_len): # if self.compare_seq(start_index, next_index, seq_len) is False: # break # seq_repeat += 1 # if seq_repeat > best_seq[2]: # best_seq = (start_index, seq_len, seq_repeat) # return ...
Python
1
ranspose(1, 2) h = F.avg_pool1d(h, h.shape[2]).squeeze(2) return h def prompt_encode(self, mol): h = self.language_model.encode(mol['instruction']) return h def prompt_encode_dy(self): self.prompts_tensors = self.prompts_tensor.to(self.config.device) h...
Python
1
lf` into a tripcode and appends it on a `String`. fn append(self, &mut String); /// Encodes `self` into a tripcode and writes it to a `Write`. fn write<W: Write>(self, &mut W) -> io::Result<()>; /// Decodes a Shift-JIS-encoded tripcode. fn decode_from_sjis(&[u8]) -> Option<Self>; /// Encodes ...
Rust
0
s, digits: Self::arg_bytes(), }; let voltage = voltage_fmt.parse(raw)?; Ok(Voltage(voltage)) } } impl From<f32> for Voltage { fn from(v: f32) -> Self { Voltage(v) } } #[cfg(test)] galvanic_test::test_suite! { name test; use super::*; use crate::{...
Rust
0
, Self::Error> { let item = try_ready!(self .fut .poll() .map_err(|e| (e.into(), self.req.take().unwrap()))); let req = self.req.take().unwrap(); let req = req.into_request(); Ok(Async::Ready((item, req))) } } /// FromRequest trait impl for tupl...
Rust
0
metersGadget<ConstraintF>, ConstraintF: PrimeField + SquareRootField> ToBytesGadget<ConstraintF> for CubicExtFieldGadget<P, ConstraintF> { fn to_bytes<CS: ConstraintSystemAbstract<ConstraintF>>( &self, mut cs: CS, ) -> Result<Vec<UInt8>, SynthesisError> { let mut c0 = self.c0.to_byte...
Rust
0
''' Takes numbers from the user and performs arithmetic operations. Writes results with timestamp into a file. Repeats until user exits. ''' from datetime import datetime filename = "math_results.txt" while True: choice = input("Do you want to continue? (yes/no): ").lower() if choice != 'yes': break...
Python
1
fn test_reflect() { assert_eq!(Point::new(0, 0), Point::new(0, 14).fold_y(7)); assert_eq!(Point::new(0, 1), Point::new(0, 13).fold_y(7)); assert_eq!(Point::new(3, 6), Point::new(3, 8).fold_y(7)); assert_eq!(Point::new(4, 0), Point::new(6, 0).fold_x(5)); } #[test] fn test...
Rust
0
from smqtk.representation import ( DetectionElement, SmqtkRepresentation, ) from smqtk.utils.configuration import ( cls_conf_from_config_dict, cls_conf_to_config_dict, make_default_config, ) from smqtk.utils.dict import merge_dict class DetectionElementFactory (SmqtkRepresentation): """ Fa...
Python
1
class Solution: # preSum, O(n) def minimumDeletions(self, s: str) -> int: totalA,totalB = 0,0 n = len(s) for c in s: if c == 'a': totalA += 1 else: totalB += 1 ans = totalA curA,curB = 0,0 for i in range(n): ...
Python
1
from rest_framework import serializers from .models import * class HostSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = HostsLists fields = ('url', 'id', 'hostname', 'ip', 'ansible_user', 'ansilbe_key') class ProjectGroupsSerializer(serializers.HyperlinkedModelSerializer)...
Python
1
test_text_arg_deserialize_borrowed() { let m = "23[\"test\",\"hello\",{\"key\":\"value\"}]"; let packet = deserialize(EngineMessage::Text(m.to_string().into())) .unwrap() .packet() .unwrap(); let args = match packet.data() { Data::Event { args, .....
Rust
0
import os import logging from binance_sdk_derivatives_trading_usds_futures.derivatives_trading_usds_futures import ( DerivativesTradingUsdsFutures, ConfigurationRestAPI, DERIVATIVES_TRADING_USDS_FUTURES_REST_API_PROD_URL, ) # Configure logging logging.basicConfig(level=logging.INFO) # Create configurati...
Python
1
import subprocess import win32gui import time import win32process proc = subprocess.Popen(["notepad.exe"],shell=False) # lets wait a bit to app to start time.sleep(3) target = proc.pid def enumWindowFunc(hwnd, windowList): """ win32gui.EnumWindows() callback """ # text = win32gui.GetWindowText(hwnd) # class...
Python
1
get_bedrock_llm(model_name=model_name, max_tokens=1024) # Update global settings instead of using ServiceContext Settings.embed_model = embed_model Settings.llm = llm # Create table node mapping and schema objects table_node_mapping = SQLTableNodeMapping(sql_database) table_schema_objs = [] ...
Python
1
files", "notes.txt").unwrap() ); } } use std::path::{Path, PathBuf}; use chrono::Local; use egui::ScrollArea; use crate::{ config::get_backups_flder, steam::{get_shortcuts_paths, SteamSettings}, }; use super::MyEguiApp; #[derive(Default)] pub struct BackupState { pub available_backups: Optio...
Rust
0
endFactor::OneMinusDestinationAlpha, ConstColor => MTLBlendFactor::BlendColor, OneMinusConstColor => MTLBlendFactor::OneMinusBlendColor, ConstAlpha => MTLBlendFactor::BlendAlpha, OneMinusConstAlpha => MTLBlendFactor::OneMinusBlendAlpha, SrcAlphaSaturate => MTLBlendFactor::SourceA...
Rust
0
"""API package for SlideForge backend.""" from .v1 import router as v1_router __all__ = ["v1_router"]
Python
1
pub(crate) fn new(bits: u8) -> Self { TMX_BM_CAS_BULK_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for TMX_BM_CAS_BULK_R { type Target = crate::FieldReader<u8, u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `tmx_bm_cas_bulk` wri...
Rust
0
OUR]) } #[test] fn five_books_return_price_with_five_books_discount() { assert_correct_price(8.0 * 5.0 * 0.80, vec![Book::ONE, Book::TWO, Book::THREE, Book::FOUR, Book::FIVE]) } #[test] fn six_books_return_price_with_six_books_discount() { assert_correct_price(8.0 * 6.0 * 0.70, vec![Book::ONE, Book::TWO, Book...
Rust
0
from keras_cv_attention_models.fastervit.fastervit import ( FasterViT, FasterViT0, FasterViT1, FasterViT2, FasterViT3, FasterViT4, FasterViT5, FasterViT6, switch_to_deploy, ) __head_doc__ = """ Keras implementation of [Github NVlabs/FasterViT](https://github.com/NVlabs/FasterViT). P...
Python
1
+ ";FOLD_CHANGE_LOG=" + consecutive_dups["log2_m"].astype(str) + ";PROBES=" + consecutive_dups["counts"].astype(str) consecutive_dups.loc[((consecutive_dups['call'] == 0)|(consecutive_dups['call'] == 1)), 'FORMAT'] = "GT:GQ" consecutive_dups.loc[((consecutive_dups['call'] == 3)|(consecutive_dups...
Python
1
t]: try: if isinstance(value, str): # Handle score format like "75/100" if "/" in value: numerator = float(value.split("/")[0]) cleaned_data[field] = numera...
Python
1
erscripts. /// /// The parameter `script` accepts values `None` for ASCII numbers, /// `Some(true)` for subscripts, and `Some(false)` for superscripts. /// /// The coefficients of 1 are dropped by default and can only be kept for ASCII /// numbers by specifying the "#" flag in the formatter. /// /// Non-positive coeffi...
Rust
0
d[x][y] == player && board[x-1][y-1] == player && board[x-2][y-2] == player && board[x-3][y-3] == player { return true; } } } return false; } pub fn add_stone(board: &mut [[u8; 6]; 7], column: u...
Rust
0
let d = unsafe { let r: raw::TraitObject = mem::transmute(a); r.data }; assert_eq!(b, d); assert_eq!(c, d as usize); } <gh_stars>0 use crate::dynamics::joint::{JointAxesMask, JointData}; use crate::dynamics::{JointAxis, MotorModel}; use crate::math::{Point, Real}; #[cfg_attr(feature ...
Rust
0
06<'a> { pub fn new( i2c: &'a dyn i2c::I2CDevice, interrupt_pin: &'a dyn gpio::InterruptPin<'a>, buffer: &'static mut [u8], events: &'static mut [TouchEvent], ) -> Ft6x06<'a> { // setup and return struct interrupt_pin.enable_interrupts(gpio::InterruptEdge::Falling...
Rust
0
indentMismatch { display("Unindent doesn't match any outer indentation level") } AmbigueColon { display("Either add a space after colon or quote the colon") } UnexpectedDirective { display("Directive must start at start of line") } BadChars { display("Characte...
Rust
0
# 声明:本代码仅供学习和研究目的使用。使用者应遵守以下原则: # 1. 不得用于任何商业用途。 # 2. 使用时应遵守目标平台的使用条款和robots.txt规则。 # 3. 不得进行大规模爬取或对平台造成运营干扰。 # 4. 应合理控制请求频率,避免给目标平台带来不必要的负担。 # 5. 不得用于任何非法或不当的用途。 # # 详细许可条款请参阅项目根目录下的LICENSE文件。 # 使用本代码即表示您同意遵守上述原则和LICENSE中的所有条款。 import random import time from model.m_xiaohongshu import NoteUrlInfo, CreatorUrlInfo fr...
Python
1
>no111u3/automatic<filename>src/interactive_list.rs //! Interactive run items, it aborts if one fail start or fail exit //! //! # Example //!``` //!use automatic::interactive_list::InteractiveList; //!use automatic::runitem::RunItem; //!use automatic::run::Run; //!let items = vec![ //! RunItem::new("true".to_string(...
Rust
0
from __future__ import annotations import polars as pl from . import load_reth_data def compute_bytes_per_contract( contracts: pl.DataFrame, reth_db_path: str, ) -> None: bytes_per_code_hash = compute_bytes_per_code_hash(contracts=contracts) bytecode_inflation_factor = get_bytecode_inflation_factor( ...
Python
1
er" { // Right now, the player is the only object that can equip. game.inv.iter() .filter(|item| { item.equipment.map_or(false, |e| e.equipped) }) .map(|item| item.equipment.unwrap()) .collect() } else { ...
Rust
0
_4 => JNIVersion::V4, JNI_VERSION_1_6 => JNIVersion::V6, JNI_VERSION_1_8 => JNIVersion::V8, v => JNIVersion::Invalid(v), } } } impl From<JNIVersion> for i32 { fn from(other: JNIVersion) -> Self { match other { JNIVersion::V1 => JNI_VERSION_1_1, ...
Rust
0
import re from typing import Dict, List import rich from rich.markup import escape # 回复解析器 class ResponseExtractor: # 多行文本数字匹配格式 # 目前有两个匹配组,第一个为标准数字序号部分,第二个为可能出现的多余引号组(常见于deepseek-v3) multiline_number_prefix = r'(\d+\.\d+\.)(")?[,,\s]?(?(2)"|)?' # 多行文本段结束后缀 multiline_quote_suffix = r'(?:\n["“”][...
Python
1
, 3.0, 4.0, 5.0 - If the business meets or exceeds expectations in key areas, consider giving a 5-star rating - If the business fails significantly in key areas, consider giving a 1-star rating - Review text should be 2-4 sentences, focusing on your personal experience and emotional ...
Python
1
1 E 7 A, 1 E => 1 FUEL ", "31", None, ), ( " 9 ORE => 2 A 8 ORE => 3 B 7 ORE => 5 C 3 A, 4 B => 1 AB 5 B, 7 C => 1 BC 4 C, 1 A => 1 CA 2 AB...
Rust
0
# Ultralytics YOLO 🚀, AGPL-3.0 license """ YOLO-NAS model interface. Example: ```python from ultralytics import NAS model = NAS('yolo_nas_s') results = model.predict('ultralytics/assets/bus.jpg') ``` """ from pathlib import Path import torch from ultralytics.engine.model import Model from ultr...
Python
1
import shutil from multiprocessing import Queue from pathlib import Path from typing import Dict, Any, List import time import ujson TABLE_NAMES = [ 'labels', 'descriptions', 'aliases', 'external_ids', 'entity_values', 'qualifiers', 'wikipedia_links', 'entity_rels' ] class Table: def __init__(self, path: Pat...
Python
1
})); } let access_token = access_token.unwrap(); if !access_token .claims .token_type .eq_ignore_ascii_case("access_token") { return ready(Err(AuthError { reason: "Invalid access token".to_string(), ...
Rust
0
pts) midpoint_lon = dataset.createDimension('midpoint_lon',numpts) unit_area_patch = dataset.createDimension('unit_area_patch',numpts) # Create variables midpoint_lats = dataset.createVariable('midpoint_lat',float,('midpoint_lat',)) midpoint_lons = dataset.createVariable('midpoint_lon',float,('midp...
Python
1
{ use interface_with_fragment_query::*; let response_data: ResponseData = serde_json::from_str(RESPONSE_FRAGMENT).expect("RESPONSE_FRAGMENT did not deserialize"); assert_eq!( response_data, ResponseData { everything: Some(vec![ InterfaceWithFragmentQuery...
Rust
0
whence.clone(), fun: Arc::clone(&self.fun), }) } } } } impl<S : ValueTree, F : Fn (&S::Value) -> bool> Filter<S, F> { fn ensure_acceptable(&mut self) { while !(self.fun)(&self.source.current()) { if !self.source.complicate() { ...
Rust
0
o crop moving volume ' + str(crop2End - crop2Start) + ' seconds') # initialize the registration if timing: initTransformStart = time.time() tx = sitk.VersorRigid3DTransform() tx.SetCenter(fixedPoint) tx.SetTranslation(np.array(movingPoint) - np.array(fixedPoint)) if timing: initTransformEnd = t...
Python
1
dlValue::Base10(value); } } if let Some(children) = node.children_mut() { normalize_numbers(children); } } } fn normalize_strings(doc: &mut KdlDocument) { for node in doc.nodes_mut() { for entry in node.entries_mut() { if let Some(value) = ent...
Rust
0
100 use rocket::response::Redirect; use rocket_contrib::templates::{tera::Context, Template}; use crate::models::User; use crate::utils::Either::{self, A, B}; #[get("/")] pub fn index(user: Option<User>) -> Either<Redirect, Template> { let ctx = Context::new(); if let Some(_) = user { return A(Redirec...
Rust
0
assert_eq!( ::std::mem::align_of::<CreateSeqStmt>(), 8usize, concat!("Alignment of ", stringify!(CreateSeqStmt)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<CreateSeqStmt>())).type_ as *const _ as usize }, 0usize, concat!( "Offset of field: ", ...
Rust
0
this_ as "chrono::ChLinkMarkers*"] -> *const Marker as "const chrono::ChMarker*" { return this_->GetMarker1(); }) }; if ptr.is_null() { None } else { Some(unsafe { &*ptr }) } } pub fn marker_2(&self) -> Option<&Marker> { ...
Rust
0
reconstructed = self.decode(z) return reconstructed, x, z, mean, log_var FEATURE_MAP= {} SAMPLE_FEATURES = {} class FinalLayerNormV2(torch.nn.Module): def __init__(self, final_layernorm, vae): super(FinalLayerNormV2, self).__init__() self.ori_layernorm = final_layernorm self.vae ...
Python
1
ws => s, let_rule[i] => i, func[f] => f, control_flow[c] => c, => Ok(ExprS(Expr::Nop, Span::new(Pos::new(1,1), Pos::new(1,1)))), } stmt2: Res<ExprS> { set_rule[i] => i, stmt3[s] ws => s, stmt3[s] ws Amp => Ok(ExprS(Expr::Background(Box::new(s?)), span!()...
Rust
0
TxtCtl.Enter, TxtCtl.Clear, '#0010260437V#1019F说话太任性\n', '让大家为难可不行啊。', TxtCtl.Enter, ), ) CloseMessageWindow() ChrTalk( 0x0010, ( '#0640260438V#226F#6P别、别随便\n', '乱叫什么公爵先生!', TxtCtl.Enter,...
Python
1
"service": "dashscope", "details": { "api_accessible": True, "settings_configured": True } } mock_service.health_check.return_value = mock_health response = client.get("/dashscope/health") assert response.status_code == 200 ...
Python
1
Attack at dawn", output: vec![ 0x45, 0xa0, 0x1f, 0x64, 0x5f, 0xc3, 0x5b, 0x38, 0x35, 0x52, 0x54, 0x4b, 0x9b, 0xf5, ], }, ] } #[test] fn test_crypt() { for t in wikipedia_tests().iter() { let mut rc4 = Rc4::new(t.key...
Rust
0
ain_from_position_and_id(main_position, main_chain_ref); BTCRelay::set_block_chain_from_id(main_chain_ref, &main); // insert the fork chain in Chains and ChainsIndex let fork_chain_ref: u32 = 4; let fork_start_height: u32 = 20; let fork_block_height: u32 = 100; let fork_...
Rust
0
import pytest # fmt: off TESTCASES = [ # Punctuation tests ("আমি বাংলায় গান গাই!", ["আমি", "বাংলায়", "গান", "গাই", "!"]), ("আমি বাংলায় কথা কই।", ["আমি", "বাংলায়", "কথা", "কই", "।"]), ("বসুন্ধরা জনসম্মুখে দোষ স্বীকার করলো না?", ["বসুন্ধরা", "জনসম্মুখে", "দোষ", "স্বীকার", "করলো", "না", "?"]), ("ট...
Python
1
_, actual)) => match_file(&key, &value, actual, mismatches, matchers), None => { debug!("MIME multipart '{}' is missing in the actual body", key); mismatches.push(Mismatch::BodyMismatch { path: s!("$"), expected: Some(key.clone().into_bytes()), actual: None, mismatch:...
Rust
0
def find_peak_element(nums): """ 寻找数组中的峰值元素 峰值元素是指大于左右相邻值的元素 :param nums: List[int],输入数组 :return: int,任一峰值元素的索引 """ if not nums: return -1 left, right = 0, len(nums) - 1 while left + 1 < right: mid = (left + right) // 2 # 如果中间元素小于其右邻居,峰值...
Python
1
let baseline_valid = !no_tools || !extract_test_directives(path, "// no-boogie-test")?.is_empty(); if no_tools { options.prover.generate_only = true; if NOT_CONFIGURED_WARNED .compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed) .is_ok() { ...
Rust
0
import torch from loguru import logger class NodeDecoder(torch.nn.Module): def __init__(self, emb_dim, decoder_dim, num_label, device): """ Parameters ---------- emb_dim dimension size of the model's output embedding feature decoder_dim hidden classif...
Python
1
self.begin & ~1)) _append_comment( self.handler, '__finally {{ here }} // __try {{ {:08X}-{:08X} }}'.format( self.begin & ~1, self.end & ~1)) def _append_comment(address, comment): old_comment = Comment(address & ~1) if old_comment == comm...
Python
1
determinants _ => { let slater_matrix: SMatrix<f64, N, N> = self.slater_matrix(particles)?; let slater_det = det(Some(&slater_matrix), None).unwrap(); let jastrow = if self.jastrow_on { self.evaluate_jastrow(particles) } else { 0. }; Ok(slater...
Rust
0
#!/usr/bin/python3 import sys from mnemonic import Mnemonic # display config script info if len(sys.argv) <= 1 or sys.argv[1] == "-h" or sys.argv[1] == "help": print("tool for seed words") print("blitz.mnemonic.py generate") print("blitz.mnemonic.py add6x4 \"[SEEDWORDS-SPACE-SEPERATED]\"") print("blit...
Python
1
} impl fmt::Display for OptimizationLevel { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Self::NoOptimizations => write!(f, "0"), Self::BasicOptimizations => write!(f, "1"), Self::SomeOptimizations => write!(f, "2"), Self:...
Rust
0
{ let n_vecs = cursor.read_i32::<LittleEndian>()?; let sz_vecs = cursor.read_i32::<LittleEndian>()?; let mut vecs = Vec::new(); for _ in 0..(n_vecs * sz_vecs) { let v = cursor.read_u8()?; vecs.push(v); } let vis_data = VisData { n_vecs: n_vecs, sz_vecs : sz_vecs,...
Rust
0
m3u8Url = item[1] # return m3u8Url # return None def getM3U8MasterUrl(self): self.__checkRequests() allM3U8Url = [] for item in self.__requests: if ".m3u8" in item[1]: allM3U8Url.append((item[1], Network.downloadM3U8(item[1]))) ...
Python
1
Clone>(S); impl<S> ::copra::service::Service for Wrapper<S> where S: DemoService + Clone, { type Request = (super::demo::GreetMessage, ::copra::controller::Controller); type Response = (super::demo::GreetMessage, ::copra::controller::...
Rust
0
self._LinkStatus = None self._LinkMaterialInfo = None self._LinkClassInfo = None @property def LinkType(self): return self._LinkType @LinkType.setter def LinkType(self, LinkType): self._LinkType = LinkType @property def LinkStatus(self): return s...
Python
1
"""Tests for RBTools setup-completion command. Version Added: 5.0 """ from rbtools.commands.setup_completion import SetupCompletion from rbtools.testing import CommandTestsMixin, TestCase class SetupCompletionTest(CommandTestsMixin[SetupCompletion], TestCase): """Tests for rbt setup-completion command. ...
Python
1
def convert_features_to_descriptors(features): descriptors = [] # Valence valence = features.get("valence") if valence is not None: if valence < 0.3: descriptors.append("melancholic") elif valence < 0.7: descriptors.append("neutral") else: des...
Python
1
# Import your functions from func_engine here.. from func_engine.remove import remove_action from func_engine.add import add_action from func_engine.update import update_action from func_engine.describe_routes import describe_routes def main( route: str, payload: list, ): # Add your function to the map in...
Python
1
import os import csv import pandas as pd import json import chardet def get_statistic(df_examples): types = [ "IP", "E", "TC", "TR", "C", "total", "traj", ] df_st = pd.DataFrame(columns=["type", "num"]) for type_now in types: df_subset = d...
Python
1
dded in Android API 21+ (according to #227), // so if we can dynamically detect an appropriately configured C compiler for // that then let's enable the `dl_iterate_phdr` API, otherwise Android just // won't have any information. fn maybe_enable_dl_iterate_phdr_android(build: &mut cc::Build) { let expansion = cc::B...
Rust
0
ML format. """ import re # Check if response contains XML tags tool_pattern = r'<tool_(\w+)>\s*({.*?})\s*</tool_\1>' final_answer_pattern = r'<final_answer>\s*(.*?)\s*</final_answer>' # Try to match tool usage tool_match = re.search(tool_pattern, response, re.DO...
Python
1
the surface. On the contrary, if the border condition is a cavity, then a value of $`T_{pane} U_{cavity}`$ /// should be added. $`T_{pane}`$ is the temperature of the surface before or after. /// pub fn get_k_q( &self, ini: usize, fin: usize, temperatures: &Matrix, ...
Rust
0
rc(Term::builtin_rc(BuiltinType::Add, vec![]), Term::var_rc(Variable::new("a"))), Term::num_lit_rc(12)))), ("(a) false", Some(Term::appl_rc(Term::var_rc(Variable::new("a")), Term::bool_lit_rc(false...
Rust
0
import numpy as np import pandas as pd import plotly.express as px # Given data frequency = 60 # Hz Vrms = 1.0 # Root Mean Square voltage # Calculate time periods T = 1 / frequency t_values = np.linspace(0, 2*T, 1000) # Time values for two periods # Instantaneous voltage functions voltage = lambda t: Vrms * n...
Python
1
deadMiner = 44, Tim = 45, Bunny = 46, CorruptBunny = 47, Harpy = 48, CaveBat = 49, KingSlime = 50, JungleBat = 51, DoctorBones = 52, TheGroom = 53, Clothier = 54, Goldfish = 55, Snatcher = 56, CorruptGoldfish = 57, Piranha = 58, LavaSlime = 59, Hellbat = 60, Vulture = 61, Demon = 62,...
Rust
0
class Solution: def getEncryptedString(self, s: str, k: int) -> str: idx = k % len(s) return s[idx:] + s[:idx]
Python
1
ernal(Re_Dext, Pr_air) k_ext = calculate_external_surface_heat_transfer_coefficient(Nu_Dext, lambda_air, D_ext) results.append({ "time": i * dt, "P1": P1, "T1": T1, "m": m, "rho1": rho1, "u2": u2, "D3_nozzle": D...
Python
1
ScreenExclusiveModeEXT = unsafe extern "system" fn(_device: Device, _swapchain: SwapchainKHR) -> Result; /// <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/vkAcquireNextImage2KHR.html> pub type PFN_vkAcquireNextImage2KHR = unsafe extern "system" fn( _device: Device, _acquire_info: *...
Rust
0