text
string
label_name
string
labels
int64
from azure.identity import AzureAuthorityHosts AZURE_CHINA_CLOUD = "https://management.chinacloudapi.cn" AZURE_US_GOV_CLOUD = "https://management.usgovcloudapi.net" AZURE_GERMAN_CLOUD = "https://management.microsoftazure.de" AZURE_GENERIC_CLOUD = "https://management.azure.com" def get_regions_config(region): all...
Python
1
# # Copyright (C) 2021 - 2024 Satoru SATOH <satoru.satoh gmail.com> # SPDX-License-Identifier: MIT # # pylint: disable=missing-docstring, unused-import """Test cases for anyconfig.api.single_load to load primitive types.""" from __future__ import annotations import typing import pytest import anyconfig.api._load as ...
Python
1
y<Rc<FontTexture>> { if persistent.is_none() { let text_display = TextDisplay::new(text_system, font, text); *persistent = Some(text_display); } return persistent.as_ref().unwrap(); } pub fn draw_text<'a>( persistent: &'a mut Option<TextDisplay<Rc<FontTexture>>>, text_system: &TextS...
Rust
0
from typing import Tuple import gradio as gr from .. import files def create_output_column(disable_local_saving: bool = False) -> Tuple[gr.Column, dict]: """Create the output column with audio player and file list.""" with gr.Column(scale=1) as col: gr.Markdown("### Latest Output") audio_out...
Python
1
let i: &[u8] = b"/http://user:pass@www.example.com:1234/path1/path2?a=b&c=d#frag"; assert!(!scheme()(i).is_ok()); } #[test] fn ParseCredentials_1() { let i: &[u8] = b"//user:pass@www.example.com:1234/path1/path2?a=b&c=d#frag"; let o: &[u8] = b"www.example.com:1234/path1/path2?a=b&c=d#frag"; let u: &[...
Rust
0
pub enum CHK_CHRG_B_A { #[doc = "0: Check whether a charger (either a dedicated charger or a host charger) is connected to USB port."] CHECK = 0, #[doc = "1: Do not check whether a charger is connected to the USB port."] NO_CHECK = 1, } impl From<CHK_CHRG_B_A> for bool { #[inline(always)] fn fr...
Rust
0
from typing import List import torch def batch_to_multihot(label: List[List[int]], num_labels: int) -> torch.tensor: """Converts label to multihot format. Args: label: [batch size, *] num_labels: total number of labels Returns: multihot: [batch size, num_labels] """ mult...
Python
1
35 [RS :wax[U5(aUR S 5 [R"5(d=[R"5S :XaUR S 5 U$UR S5 U$)NO...
Python
1
assert dr.allclose(spec, [0.6 * (1 - 0.04) / 1.5**2] * 3) assert dr.allclose(bs.pdf, 1.0) assert dr.allclose(bs.eta, 1.5) assert dr.allclose(bs.wo, [0, 0, -1]) assert bs.sampled_component == 1 assert bs.sampled_type == +mi.BSDFFlags.Del...
Python
1
X_TKN2_SHARE_ID), (ALICE, 6, 486, 0, BSX_TKN1_LIQ_POOL_ID, BSX_TKN1_SHARE_ID), ]; for (caller, nft_id_index, withdrawn_shares, deposits_left, liq_pool_farm_id, lp_token) in test_data { let bsx_tkn1_pallet_amm_shares_balance = Tokens::free_balance(BSX_TKN1_SHARE_ID, &pallet_account); let bsx_tkn2_pallet_am...
Rust
0
te::custom::resolve_styles; use crate::styling::style_to_ansi; use lazy_static::lazy_static; use regex::{Captures, Regex}; lazy_static! { static ref PARSER: Regex = Regex::new(r"(?i)(?:\{(?P<styleSingle>[^\{\}]+)\})|(?:\{\{(?P<styleDouble>[^\{\}]+)\}\})").unwrap(); static ref SPLITTER: Regex = Regex::new(r"[\|...
Rust
0
tp://web.mit.edu/xcrysden_v1.5.60/www/XCRYSDEN/doc/XSF.html Attributes: wf_list : a list of MLWFs to plot supercell : a supercell used for plotting ''' grid = np.asarray(grid) origin = np.asarray([-grid[i]*(supercell[i]//2)/grid[i] for i in range(3)])....
Python
1
"""JSON file settings source.""" from __future__ import annotations as _annotations import json from pathlib import Path from typing import ( TYPE_CHECKING, Any, ) from ..base import ConfigFileSourceMixin, InitSettingsSource from ..types import DEFAULT_PATH, PathType if TYPE_CHECKING: from pydantic_sett...
Python
1
(shop_config_dict, product_row, collection_minimum_price, discount, max_variants_count=100) # variants_live_list = json.loads(product_row['variants_live']) # options_live_list = json.loads(product_row['options_live']) # if product_row['vendor_name'].lower() == "Shoplazza".lower(): # df_variants_new...
Python
1
Iterator<Item=u32> { self.x.iter().map(|a| a.0) //~ ERROR E0759 } } fn main() {} //! De/Serialization for Rust's builtin and std types use crate::Separator; use serde::{ de::{Deserialize, DeserializeOwned, Deserializer, Error, MapAccess, SeqAccess, Visitor}, ser::{Serialize, SerializeMap, Seriali...
Rust
0
ents_num)) def _top_k_leaves_idxs_set(self, k, t, removed_point_idx, da): tree = self.trees[t] leaf_das = [ np.sum(np.abs(da[list(tree._document_idxs_for_leaves[leaf_idx])])) for leaf_idx in xrange(len(tree.leaf_values)) ] leaf_idxs_to_update = np.argsort(lea...
Python
1
""" Censor 2 ----> CENSOR 1 Designed to be run by the evaluator. TCP Censor that synchronizes on first SYN only, works 100% of the time, sends 5 RSTs to client. """ import layers.packet import logging logging.getLogger("scapy.runtime").setLevel(logging.ERROR) from scapy.all import IP, TCP from censors.censor impor...
Python
1
#!/usr/bin/env python3 import uuid from datetime import datetime import json from models import storage """ class BaseModel that defines all common attributes/methods for other classes """ class BaseModel: """ Acts as the base class """ def __init__(self, *args, **kwargs): """ used for...
Python
1
MeshRiggingGroup>> { let mut rigging_buffers = Vec::new(); for mesh_object in object_data { // TODO: unk1 is sometimes set to 0 for singlebound mesh objects, which isn't currently preserved. let flags = RiggingFlags { max_influences: calculate_max_influences(&mesh_object.bone_influe...
Rust
0
import matplotlib.pyplot as plt # Measurements from throughput.data # Measurements from latency.data def do_plot(): f, ax = plt.subplots(2,1, figsize=(6,5)) replicaNo = [4, 8, 16, 32] xticks = [0,4, 8, 16, 32, 40] xticks_label = ["","4", "8", "16", "32", "64", ""] thru = [ ('HotStuff',[ ...
Python
1
rate: CrateOwned, ) -> impl StdFuture<Item = String, Error = Error> + Send { let resolver = self.clone(); futures::future::lazy(|| { let registry_dl_url = resolver.get_registry_dl_url().map_err(|_| ()); registry_dl_url .and_then(move |registry_dl_url| { ...
Rust
0
def word_bank(): words = [] while True: word = input("Enter a word: ") words.append(word) try_again = input("Do you want to enter another word? (Y/y for Yes, N/n for No): ") if try_again.lower() == 'n': break elif try_again.lower() !=...
Python
1
""" Challenge: Emoji Enhancer for Messages Create a Python script that takes a message and adds emojis after specific keywords to make it more expressive. Your program should: 1. Ask the user to input a message. 2. Add emojis after certain keywords (like "happy", "love", "code", "tea", etc.). 3. Print the updated me...
Python
1
CKET_POKER_SHOWDOWN] = PacketPokerShowdown ######################################## PACKET_POKER_CLIENT_PLAYER_CHIPS = 205 # 0xcd # %SEQ% PacketNames[PACKET_POKER_CLIENT_PLAYER_CHIPS] = "POKER_CLIENT_PLAYER_CHIPS" class PacketPokerClientPlayerChips(Packet): type = PACKET_POKER_CLIENT_PLAYER_CHIPS def __init...
Python
1
state.acquire_permit(Uuid::new_v4()).await.unwrap(); } assert_eq!(state.available_permits(), 0); } #[tokio::test] async fn return_permits() { let id = Uuid::new_v4(); let state = ProvisioningState::new(1); state.acquire_permit(id).await.unwrap(); asse...
Rust
0
#00 SINTAXIS, VARIABLES, TIPOS DE DATOS Y HOLA MUNDO # Sitio Oficial Python https://www.python.org/ # Sintaxis para realizar comentarios en Python # Para una sola línea se usa el simbolo numeral '#' ''' Para comentarios de varias líneas se usa: (') Comilla sensilla, como se esta usando en este ejemplo ''' """ o ...
Python
1
# 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, software # distributed under t...
Python
1
tem in res: print('%s & %s & %.2f & %.2f & %.2f & %.2f & %.2f & %.2f & %.2f & %.2f & %.2f \\\\' % item) def get_data(function): res = dict() x = list() y = list() with open(DATA_ROOT + function) as f: for line in f: if not line.startswith('GO:'): continue ...
Python
1
_base_ = '../grounding_dino_swin-t_pretrain_obj365_goldg_cap4m.py' data_root = 'data/d3/' test_pipeline = [ dict( type='LoadImageFromFile', backend_args=None, imdecode_backend='pillow'), dict( type='FixScaleResize', scale=(800, 1333), keep_ratio=True, backend='p...
Python
1
o use AWS authentication" ) parser.add_argument("--region", type=str, default="us-east-1", help="AWS region") parser.add_argument( "--query_type", type=str, default="neural_sparse", help="Query type" ) args = parser.parse_args() print(args) try: # Initialize OpenSearch clien...
Python
1
("b").peek_active() ); assert!(hint_set .sub_hints("a") .sub_hints("b") .sub_hints("c") .is_active()); assert_eq!( None, hint_set .sub_hints("a") .sub_hints("b") .sub_hints("...
Rust
0
(self.loss_constraint * self.weight_loss_constraint).backward() for i, x in enumerate(self.parameters_all): for psf_order in range(len(PSF)): x.grad = x.grad + torch.sum(PSF[psf_order].grad / self.train_rate * d_PSF[psf_order][:, :, i, :, :]) # 计算梯度 # Adam方法进行梯度更新 ...
Python
1
orker = thread()(f) return worker return inner def select_runner(name): """ Return runner based on name ( worker or timer ) and settings.TASK_RUNNER. """ mapper = { 'block': {'worker': b_worker, 'timer': b_timer}, 'uwsgi': {'worker': u_worker, 'timer': u_timer}, 'c...
Python
1
from pydantic import BaseModel, Field from datetime import datetime from typing import List from models.layer import Layer class NeuralNetworkMetadata(BaseModel): id: str name: str description: str url: str createdAt: datetime lastUpdated: datetime class NeuralNetwork(NeuralNetworkMetadata): ...
Python
1
# Copyright (c) 2025, NVIDIA CORPORATION. import pandas as pd import pytest import cudf from cudf.testing import assert_eq from cudf.testing._utils import ( assert_column_memory_eq, assert_column_memory_ne, ) @pytest.mark.parametrize( "data", [ range(1, 5), [1, 2, 3, 4], pd.D...
Python
1
self.inner_as_raw_mut() } } impl core::AlgorithmTraitConst for PtrOfRadialVarianceHash { #[inline] fn as_raw_Algorithm(&self) -> *const c_void { self.inner_as_raw() } } impl core::AlgorithmTrait for PtrOfRadialVarianceHash { #[inline] fn as_raw_mut_Algorithm(&mut self) -> *mut c_void { self.inner_as_raw_mu...
Rust
0
of_messages() { let user1 = Principal::from_text("yy53y-szfmc-h2gyu-zlind-wzikf-6zuqh-i4x6u-fvado-rvydl-qxwlz-oqe").unwrap(); let user2 = Principal::from_text("ups66-6ukpx-mitsu-vhso3-ixjld-5p3m5-fbq6p-bbbma-oyzvm-mjr2w-qae").unwrap(); let mut chat = Chat::new(user1.clone(), user2.clone()); ...
Rust
0
import json def jsonl_to_json(input_file_path, output_file_path): """ 将JSONL文件转换为JSON数组文件。 :param input_file_path: 输入的JSONL文件路径 :param output_file_path: 输出的JSON文件路径 """ # 用于存放所有解析后的JSON对象 data_list = [] # 打开JSONL文件并逐行读取 with open(input_file_path, 'r', encoding='utf-8') as ...
Python
1
partial_prod = prime_field::fmul( partial_prod.clone(), denominator.clone() ); // Calculate the denominator for the composition polynomial columns: x - z^2. denominator = shifted_eval_point.clone() + minus_point_pow.clone(); batch_inverse_vec[products_idx + 82] = partial_prod.clone(); batch_inverse_ve...
Rust
0
milvusService = MilvusKBService(knowledge_base_name) # 添加文档到 milvus 服务 await milvusService.do_add_doc(docs=detail_results) search_retriever = await milvusService.search_docs(query, top_k=retrival_top_k) context = "\n".join([doc[0].page_content for doc in search_...
Python
1
import hashlib import os import requests import time import sys import json import csv # 显示某等级地区的小计 def show_level_count(x_list): j = 0 for i in range(len(x_list)): j += len(x_list[i]["communitys"]) print(j) return j def writer_to_csv(risk_txt): risk_json = json.loads(risk_txt) so_f...
Python
1
############################################################################### # This file is part of SWIFT. # Copyright (c) 2017 Bert Vandenbroucke (bert.vandenbroucke@gmail.com) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as p...
Python
1
return Some(offs); } } None } fn next_item(&mut self) -> Option<(usize, Fixed, Fixed)> { let d = &self.data; let point_index = self.pts.next()?; if self.xrun.0 >= self.xrun.1 { let control = d.read::<u8>(self.xs)?; self...
Rust
0
"exti2_intn": 8, "exti3_intn": 9, "exti4_intn": 10, "exti9_5_intn": 23, "exti15_10_intn": 40, } }, "GPIOA": { "type": "peripheral", "base": 0x40010800, "struct": "STM32F1xxGpio" }, "GPIOB": { "type": "pe...
Python
1
048, 2048), data, label: Some("background".into()), mip_count: rend3::types::MipmapCount::ONE, mip_source: rend3::types::MipmapSource::Uploaded, }); lock(skybox_routine).set_background_texture(Some(handle)); Ok(()) } #[cfg(not(target_arch = "wasm32"))] pub fn spawn<Fut>(fu...
Rust
0
[error("Max token error: max_token: {max_token}, tokens_required: {tokens_required}")] MaxTokenError { max_token: Uint128, tokens_required: Uint128, }, #[error("Insufficient liquidity error: requested: {requested}, available: {available}")] InsufficientLiquidityError { requested...
Rust
0
import flet as ft import webbrowser class SideMenu(ft.Container): """ 应用程序的侧边菜单组件 """ def __init__(self, page: ft.Page, on_page_change=None, on_toggle_menu=None): """ 初始化侧边菜单 Args: page: Flet页面对象 on_page_change: 页面切换回调函数,接收页面名称作为参数 on...
Python
1
# -*- coding: utf-8 -*- ############################################################################### # # OpenEduCat Inc # Copyright (C) 2009-TODAY OpenEduCat Inc(<http://www.openeducat.org>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser G...
Python
1
_speaker_handle: GuildSpeakerHandle { guild_id: self.guild_id, songbird: self.songbird.clone(), guild_speaker: self.guild_speaker.clone(), current_call: self.songbird.get(self.guild_id), }, } } } pub struct GuildSpeakerEndedHandle ...
Rust
0
version, the value is (MAJOR*100*100 + MINOR*100 + RELEASE)."] pub fn ZSTD_versionNumber() -> libc::c_uint; } extern "C" { #[doc = " ZSTD_versionString() :"] #[doc = " Return runtime library version, like \"1.4.5\". Requires v1.3.0+."] pub fn ZSTD_versionString() -> *const libc::c_char; } extern "C" { ...
Rust
0
eInterface set_HardwareInterface[0..1], FilterInterface set_FilterInterface[1..2], ConnectorPresent set_ConnectorPresent[2..3], NotAuthenticated set_NotAuthenticated[3..4], NotMediaConnected set_NotMediaConnected[4..5], Paused set_Paused[5..6], LowPower set_LowPower[6..7], EndPointInterface ...
Rust
0
::RespValue, resp_array}; #[derive(Debug)] pub enum ClusterSetSlot { Importing { slot: u16, source_node_id: String }, Migrating { slot: u16, dest_node_id: String }, Stable { slot: u16 }, Node { slot: u16, node_id: String }, } pub fn importing(slot: u16, source_node_id: String) -> ClusterSetSlot { ...
Rust
0
]}], ['30~90日', None, {'type': 'time_delta', 'definition': 'blur', 'time': [{'day': 30.0}, {'day': 90.0}]}], # 时间段转时间点 ['20天以后', _ts_1, {'type': 'time_span', 'definition': 'blur', 'time': ['2021-07-04 00:00:00', 'inf']}], ['20天后', _ts_1, {'type': 'time_point...
Python
1
STARTTLS ([RFC 2487](https://tools.ietf.org/html/rfc2487)) //! //! #### SMTP Transport //! //! This transport uses the SMTP protocol to send emails over the network (locally or remotely). //! //! It is designed to be: //! //! * Secured: connections are encrypted by default //! * Modern: unicode support for email conte...
Rust
0
not in ( 0, fun_type_2, fun_type_4) or step2_ not in (0, fun_type_3, fun_type_5): return fail_api("参数异常") if list_ is None: return fail_api("请上传图片") type_ = 3 terrain_classification(model_path, up_dir, generate_dir, list_,...
Python
1
ub fn into_builder(self) -> CustomFormatBuilder { self.into() } /// Returns this format's representation of decimal points. pub fn decimal(&self) -> char { self.dec } /// Returns this format's [`Grouping`], which governs how digits are separated (see [`Grouping`]). /// /// ...
Rust
0
Eq for Popularimeter { fn eq(&self, other: &Self) -> bool { self.email == other.email } } impl Hash for Popularimeter { fn hash<H: Hasher>(&self, state: &mut H) { self.email.hash(state); } } #[cfg(test)] mod tests { use crate::id3::v2::items::popularimeter::Popularimeter; fn test_popm(popm: &Popularimeter)...
Rust
0
SELECT * FROM unnest($1, $2, {}) as U ON CONFLICT (device_id, time) DO UPDATE SET {}", insert_cols, unnest_cols, conflict_cols ); // When using unnest each column is an array let mut col_types = vec![Type::TIMESTAMP_ARRAY, Type::OID_ARRAY]; col_types....
Rust
0
ome(controller) = &iface.controller { match controller_subordinates.get_mut(controller) { Some(subordinates) => subordinates.push(iface.name.clone()), None => { let mut new_subordinates: Vec<String> = Vec::new(); new...
Rust
0
import heapq dy = [-1,1,0,0] dx = [0,0,-1,1] inf = 21e8 def dijkstra(): dists = [[inf] * n for _ in range(n)] dists[0][0] = 0 heap = [(0, 0, 0)] # 깊이, y, x while heap: ky_cost, kyi, kyj = heapq.heappop(heap) if dists[kyi][kyj] < ky_cost: continue for i in range...
Python
1
. Returns: The full_thread flag """ return self._full_thread @property def trace_reports(self): """Set of trace reports for this message. Returns: The trace reports that have been logged on this message/thread so far. (Only for tar...
Python
1
# -*- coding: utf-8 -*- import torch import torch.nn as nn import torch.nn.functional as F from transformers import BertModel,AutoModel,RoFormerModel import math from ban16 import BANLayer from torch.nn.utils.weight_norm import weight_norm import numpy as np class BERTBinding_AbDab_cnn(nn.Module): def __init__(se...
Python
1
tart immediately with your reasoning, and keep it concise. Respond in this format: <think> [One or two decisive sentences] </think> Then write your answer in this format: The answer is [(choice)] [choice content]. ''' choice_str = f"(a) {choices[0]} (b) {choices[1]} (c) {choices[2]} (d) {choices[3]}" retu...
Python
1
# Copyright 2021-present, the Recognai S.L. team. # # 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 la...
Python
1
b = _generate_bernoulli(key2, mean, p=p) bz = jax.tree_util.tree_map(lambda x, y: x * y - (1 - x) * y, b, z) return jax.tree_util.tree_map( lambda a, b: a + b, mean, metric.scale(mean, bz, inv=False, trans=False) ) def _log1pexp(a): return jnp.log1p(jnp.exp(a)) def _barker_logpdf(x, mean,...
Python
1
) -> Self::IntoIter { self.iter() } } impl<L: Language> IntoIterator for SyntaxList<L> { type Item = SyntaxSlot<L>; type IntoIter = SyntaxSlots<L>; fn into_iter(self) -> Self::IntoIter { self.iter() } } #[cfg(test)] mod tests { use text_size::TextRange; use crate::raw_lan...
Rust
0
center; } h2 { display: block; width: 70%; margin: -0.2em auto 0; font-family: 'Fira Sans', sans-serif; font-weight: 300; font-size: 1.2em; color: #5b5b5b; text-align: center; } .coming-soon { display: block; width: 40%; margin: 2.5em auto...
Rust
0
parens $($tt:tt)+ ) => ( $($tt)+ ); (@parens ) => ( () ); } pub fn future_unreachable<T, E> () -> ::tokio::prelude::future::FutureResult<T, E> { unreachable!() } pub mod generic; pub type Position = generic::Position<usize>; pub type DeltaPos = generic::DeltaPos<usize>...
Rust
0
# -*- coding: utf-8 -*- import unittest from unittest.mock import patch from src.IntuneCD.backup.Intune.EnrollmentConfigurations import ( EnrollmentConfigurationsBackupModule, ) class TestEnrollmentConfigurationsBackupModule(unittest.TestCase): """Tests for the EnrollmentConfigurationsBackupModule class.""" ...
Python
1
def min_landlock_flips(grid): """ Returns the minimum number of 0s that need to be flipped to make at least one landlocked area non-landlocked. If it's impossible, returns -1. """ if not grid or not grid[0]: return -1 m, n = len(grid), len(grid[0]) directions = [(0, 1), (1, 0), ...
Python
1
= SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_2020; pub type SamplerYcbcrRange = i32; pub const SAMPLER_YCBCR_RANGE_ITU_FULL: i32 = 0; // Luma 0..1 maps to 0..255, chroma -0.5..0.5 to 1..255 (clamped) pub const SAMPLER_YCBCR_RANGE_ITU_NARROW: i32 = 1; // Luma 0..1 maps to 16..235, chroma -0.5..0.5 to 16..240 pub const SAMPL...
Rust
0
distributed_reward, }); Ok(()) } /// Add liquidity pool to farm and allow yield farming for given `asset_pair` amm. /// /// Only farm owner can perform this action. /// /// Only AMMs with `asset_pair` with `incentivized_asset` can be added into the farm. AMM /// for `asset_pair` has to exist to ...
Rust
0
: could try again but we're can't be sure if the file // descriptor was closed or not, so to be safe we don't // close it again. let err = io::Error::last_os_error(); error!("error closing Signals: {}", err); } } } //! An `unsegen` widget for...
Rust
0
class Expense: def __init__(self, name, category, amount): self.name = name self.category = category self.amount = amount
Python
1
#!/usr/bin/python # # (IDA Pro Only) Shows SEH chains (stack and handlers) for all threads. # # Author: Satoshi Tanda # ################################################################################ # The MIT License (MIT) # # Copyright (c) 2013 tandasat # # Permission is hereby granted, free of charge, to any pers...
Python
1
#[doc = "< Registered surface will be used for output of H.264 ME only mode."] #[doc = "This buffer usage type is not supported for HEVC ME only mode."] NV_ENC_OUTPUT_MOTION_VECTOR = 1, #[doc = "< Registered surface will be used for output bitstream in encoding"] NV_ENC_OUTPUT_BITSTREAM = 2, } #[doc = "...
Rust
0
}) .unwrap_or(RegisterRule::Undefined) } fn set(&mut self, register: Register, rule: RegisterRule<R>) -> Result<()> { if !rule.is_defined() { let idx = self .rules() .iter() .enumerate() .find(|&(_, r)| r.0 == regis...
Rust
0
iWidget> { if self.show_encoding { Some(&mut self.encoding_view) } else { None } } } impl UiWidget for GamePlayUI { fn print(&mut self, ui: &mut UiContext) -> std::io::Result<()> { if let Some(popup) = self.get_popup_mut() { popup.print(ui)?; ...
Rust
0
rn False # except Exception as e: # logger.error(f"[-] {target} 连接失败: {e}") # return False # # # if __name__ == '__main__': # main() import sys import argparse import requests import logging import json from multiprocessing.dummy import Pool requests.packages.urllib3.disable_warnings() # 设置日志...
Python
1
lines() { let test = "Aqui ((hay espacios) estes) o no estes".to_string(); let actual = add_new_lines(test, 2, false); assert_eq!(actual, "Aqui (\n(hay espacios) estes) o no estes") } #[test] fn onelevel_new_lines() { let test = "(Aqui ((())) ((())) estes o no estes)".to_string(); let actual = add...
Rust
0
b'0' <= b && b <= b'9') || !buf[i+1..].iter().all(|&b| b'0' <= b && b <= b'9') { return None; } let year_short: i32 = ((buf[0] - b'0') as i32) * 10 + ((buf[1] - b'0') as i32); let year = if year_short < 50 { year_short + 2000 } els...
Rust
0
fn(host: *const clap_host), pub request_jump: unsafe extern "C" fn(host: *const clap_host, position: clap_beattime), pub request_loop_region: unsafe extern "C" fn(host: *const clap_host, start: clap_beattime, duration: clap_beattime), pub request_toggle_loop: unsafe extern "C" fn(host: *const clap_...
Rust
0
{ port: 0x0C, payload: Payload::SlotTime(42) } )), frame_content(data) ); let data = &[0xF0 | FrameType::TXTail as u8, 42]; assert_eq!( Ok(( EMPTY, Frame { ...
Rust
0
: None })) } fn d_parse_double(input: &[u8]) -> IResult<&[u8], Frame, RedisParseError<&[u8]>> { let (input, data) = nom_map_res(d_read_to_crlf_s, to_f64)(input)?; Ok((input, Frame::Double { data, attributes: None })) } fn d_parse_boolean(input: &[u8]) -> IResult<&[u8], Frame, RedisParseError<&[u8]>> { let (inp...
Rust
0
(blank=True, max_length=500)), ('period_start', models.DateField()), ('period_end', models.DateField()), ('created_at', models.DateTimeField(auto_now_add=True)), ('generated_by', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AU...
Python
1
import numpy as np import pytest from rocketpy.tools import ( calculate_cubic_hermite_coefficients, euler313_to_quaternions, find_roots_cubic_function, haversine, tuple_handler, ) @pytest.mark.parametrize( "angles, expected_quaternions", [((0, 0, 0), (1, 0, 0, 0)), ((90, 90, 90), (0, 0.70...
Python
1
Reads coordinate pairs from a file into an array fn load_data( source: &str, xcol: usize, ycol: usize, size: (u32, u32), ) -> Result<Vec<u64>, Box<dyn std::error::Error>> { let mut v = vec![0u64; size.0 as usize * size.1 as usize]; // Calculate bin sizes for x and y, based on the pixel size of...
Rust
0
d_response: u8, f: f32, q: f32, p: f32, } impl UserRAPPOR { fn new(actual_response: u8, f: f32, q: f32, p: f32) -> Self { let mut rng = rand::thread_rng(); let rand = rng.gen_range(0.0..1.0); let mem_rep; if rand < f * 0.5 { mem_rep = 1; } else if rand >= f * 0.5 && rand < f { ...
Rust
0
pub fn set_remote_description( peer_id: u64, kind: SdpType, sdp: String, ) -> anyhow::Result<()> { WEBRTC .lock() .unwrap() .set_remote_description(peer_id, kind.into(), sdp) } /// Creates a new [`RtcRtpTransceiver`] and adds it to the set of transceivers /// of the specified [...
Rust
0
nscript::new(b"doctest example"); /// assert_eq!( /// proof.rewind_single_get_commitment_data( /// &bp_gens, /// &pc_gens, /// &mut rewind_transcript, /// &committed_value, /// 32, /// &rewind_nonce_1, /// &rewind_nonce_2, ...
Rust
0
::game::Game; use crate::protocol::*; use crate::server::callback::*; use crate::utils::Uptime; use super::games::Games; enum Event { Add(Client), #[allow(dead_code)] Halt, } pub struct Server { /// The port that is listening for attempting new TCP connections. port: u16, /// List of all game...
Rust
0
(config.network,config.dataset.den_factor,config.train.route_size,device) # dump_input = torch.rand( # (1, 3, config.TRAIN.IMAGE_SIZE[1], config.TRAIN.IMAGE_SIZE[0]) # ) # logger.info(get_model_summary(model.cuda(), dump_input.cuda())) if config.test.model_file: model_state_file = conf...
Python
1
match stream.read_cstring(16) { Ok(s) if s == "PING" => { if let Err(_) = PONG.send(&mut stream) { continue 'listen; } break; } _ => { continue 'listen; ...
Rust
0
import pytest from hwpx_mcp_server.core.plan import PlanManager, PipelineError def make_manager(paragraphs): manager = PlanManager() doc_id = "doc" manager.register_document(doc_id, "\n".join(paragraphs)) return manager, doc_id def make_operation(match, replacement="UPDATED", *, section=0, paragrap...
Python
1
2'), ] starting_ce_count = get_table('Collectingevent').objects.count() starting_co_count = get_table('Collectionobject').objects.count() results = do_upload(self.collection, data, plan, self.agent.id) for r, expected in zip(results, [Matched, NoMatch, Matched, NoMatch]): ...
Python
1
#Partial code from bs4 import BeautifulSoup import requests import pandas as pd #Scrapping all teams an his historical data in american cup since 1916 to 2021 to export in a two df historical and fixture. years = ['1916','1917','1919','1920','1921','1922','1923','1924','1925','1926','1927','1929','1935','1937','1939...
Python
1
pot: &Spot, time: f64) -> Self { let max_radius = spot.radius; // TODO: Dubiously physical spot growth code let radius = match spot.mortality { Mortality::Immortal => spot.radius, Mortality::Mortal(lifetime) => { let growth_time = 0.1 * (lifetime.upper - l...
Rust
0
from opencompass.multimodal.models import (MiniGPT4ScienceQAPromptConstructor, MiniGPT4ScienceQAPostProcessor) # dataloader settings val_pipeline = [ dict(type='mmpretrain.LoadImageFromFile'), dict(type='mmpretrain.ToPIL', to_rgb=True), dict(type='mmpretrain.torch...
Python
1
test] fn test_fixed_size() { // from playground serialize_and_deserialize_uper( 8 * 9, &[0x08, 0x65, 0x78, 0x61, 0x63, 0x74, 0x6C, 0x79, 0x38], &BasicConstrained { abc: "exactly8".to_string(), }, ); } #[test] fn test_fixed_size_extensible_smaller() { // from ...
Rust
0
reason fn calculate_bounds(&mut self) -> Bounds { if self.is_empty() { return Bounds::empty(); } let mut min_x = i32::max_value(); let mut min_y = i32::max_value(); // get new top/left for t in self.all_iter() { if t.pos.x < min_x { ...
Rust
0