text
string
label_name
string
labels
int64
# coding: utf-8 """ Dhan Trading API Comprehensive API documentation for Dhan Trading Platform, covering order management, market data, portfolio, and utilities. The version of the OpenAPI document: 1.0.0 Generated by OpenAPI Generator (https://openapi-generator.tech) Do not edit the class manua...
Python
1
""" ckwg +31 Copyright 2015-2016 by Kitware, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and...
Python
1
from enum import StrEnum class ModelNames(StrEnum): """ This class contains the names of the diffusion models that are used for training and inference. """ DDPM = "ddpm_35m" DDPMwithEMA = "ddpm_ema" DDPMwithPowerLawEMA = "ddpm_power_law_ema" CFG_DDPM = "cfg_ddpm" CFG_DDPM_EMA = "...
Python
1
only list offers matching list of OfferIds #[api(type = 1106)] #[display("offer_list({0})", alt = "{0:#}")] #[from] OfferList(List<PublicOffer<BtcXmr>>), // #[api(type = 1107)] // #[display("offer_list({0})", alt = "{0:#}")] // #[from] // OfferIdList(List<PublicOfferId>), // #[api(...
Rust
0
#!/usr/bin/env python3 """ 覆蓋率測試運行腳本 運行測試並生成覆蓋率報告 """ import subprocess import sys import os def run_coverage(): """運行覆蓋率測試""" print("正在運行覆蓋率測試...") # 運行 pytest 並生成覆蓋率報告 cmd = [ sys.executable, "-m", "pytest", "tests/", "--cov=project", "--cov-report=xml", ...
Python
1
pub mod errors; pub mod request; #[derive(Debug, Clone)] pub struct Infinispan { base_url: String, http_client: reqwest::Client, basic_auth_encoded_val: String, } impl Infinispan { pub fn new( base_url: impl Into<String>, username: impl AsRef<str>, password: impl AsRef<str>, ...
Rust
0
import runpy from setuptools import setup, find_packages __version__ = runpy.run_path("elf/__version__.py")["__version__"] requires = [ "numpy", "imageio", "scikit-image", "scikit-learn", "skan" ] # optional dependencies for setuptools extras = { "hdf5": "h5py", "zarr": "zarr", "n5":...
Python
1
::Specified) } #[doc(hidden)] fn __private_visit_untagged_option<D>(self, deserializer: D) -> Result<Self::Value, ()> where D: Deserializer<'de>, { Ok(match T::deserialize(deserializer) { Ok(v) => RemovableValue::Specified(v), _ => RemovableValue::Remove, ...
Rust
0
ors.RingCount, 'max_abs_partial_charge': Descriptors.MaxAbsPartialCharge, 'max_partial_charge': Descriptors.MaxPartialCharge, 'min_abs_partial_charge': Descriptors.MinAbsPartialCharge, 'min_partial_charge': Descriptors.MinPartialCharge, 'num_NHOH': Descriptors.NHOHCount, ...
Python
1
{ return Err(WrongArity); } let condition = self.eval_expr(tail.get(0).unwrap().clone())?; if condition.is_truthy() { self.eval_expr(tail.get(1).unwrap().clone()) } else { self.eval_expr(tail.get(2).unwrap().clone()) } } pub fn eval_call_special_quote( &mut self, ta...
Rust
0
RE_STEP, } else: config[CONF_VISUAL] = { CONF_MIN_TEMPERATURE: PROTOCOL_MIN_TEMPERATURE, CONF_MAX_TEMPERATURE: PROTOCOL_MAX_TEMPERATURE, CONF_TEMPERATURE_STEP: { CONF_TARGET_TEMPERATURE: PROTOCOL_TARGET_TEMPERATURE_STEP, CONF_CU...
Python
1
2); assert_eq!(nrem, 3); assert_eq!(quot, [DecimalDigit(748_731_383), DecimalDigit(35_706), DecimalDigit(0)]); assert_eq!(num[..nrem], [DecimalDigit(612_453_958), DecimalDigit(628_288_073), DecimalDigit(241_893_843)]); let mut num = [ DecimalDigit(2_827_928_982_748_837_756_...
Rust
0
impl timeval_t { pub fn new(sec: time_t, usec: suseconds_t) -> Self { let time = Self { sec, usec }; time.validate().unwrap(); time } pub fn validate(&self) -> Result<()> { if self.sec >= 0 && self.usec >= 0 && self.usec < 1_000_000 { Ok(()) } else { ...
Rust
0
ObjectDeliveryMethod or INVENTORY if the value could not be translated. :rtype: CommonObjectDeliveryMethod """ if value is None or value == CommonObjectDeliveryMethod.NONE: return PickerInteractionDeliveryMethod.INVENTORY if isinstance(value, PickerInteractionDeliveryMethod):...
Python
1
form!(Form::TimeOfDay(TimeOfDayForm::Hour {.. }))), relative_minute_check!(), |datetime, relative_minutes| { if relative_minutes.value().value < 10 && !relative_minutes.value().prefixed { return Err(RuleError::Invalid.into()) }...
Rust
0
local_constraint References ---------- .. [1] Burt, Ronald S. "Structural holes and good ideas". American Journal of Sociology (110): 349–399. """ # Check if scipy is available try: # Needed for errstate import numpy as np # make sure nx.adjacenc...
Python
1
doc = "i2s_fifo_wdata register accessor: an alias for `Reg<I2S_FIFO_WDATA_SPEC>`"] pub type I2S_FIFO_WDATA = crate::Reg<i2s_fifo_wdata::I2S_FIFO_WDATA_SPEC>; #[doc = "i2s_fifo_wdata."] pub mod i2s_fifo_wdata; #[doc = "i2s_fifo_rdata register accessor: an alias for `Reg<I2S_FIFO_RDATA_SPEC>`"] pub type I2S_FIFO_RDATA = ...
Rust
0
q/K1SZFPTOtr/KBHBeksoGMGw==".to_string()), ); // Build the `Accessor`. let accessor: Arc<dyn Accessor> = builder.finish().await?; // `Accessor` provides the low level APIs, we will use `Operator` normally. let op: Operator = Operator::new(accessor); let path = uuid::Uuid::new_v4().to_string();...
Rust
0
e": return db.session.query(ProcessRule).filter( ProcessRule.id == self.process_rule_id, ).one_or_none() @property def segment_count(self) -> int: return db.session.query(func.count(Segment.id)).filter( Segment.document_id == self.id, ).scalar() @pro...
Python
1
shutil.move(str(file_path), str(dest_path)) logging.info(f"Moved {file_path.name} to {folder_name}/") except Exception as e: logging.error(f"Error moving {file_path.name}: {str(e)}") ...
Python
1
e(old_embeddings, nn.Embedding): raise TypeError( f"Old embeddings are of type {type(old_embeddings)}, which is not an instance of {nn.Embedding}. You" " should make sure that `old_embeddings` are an instance of" f" {nn.Embedding}." ) old_...
Python
1
erMethod == 'contains': users = users.filter(username__icontains=username) elif userMethod == 'starts': users = users.filter(username__istartswith=username) elif userMethod == 'is': users = users.filter(username__iexact=username) else: ...
Python
1
32_handle_properties { Some(v) => v, None => Default::default(), }; let _return = _function(self.handle, handle_type as _, handle, &mut memory_win32_handle_properties); crate::utils::VulkanResult::new(_return, memory_win32_handle_properties) } } <reponame>nebelgrau77/...
Rust
0
!("Events: {:?}", res); self.pending.extend(res); // FIXME: May result in infinite scan loop? self.state = WatcherState::Fresh(latest_version); Ok(Async::Ready(())) } fn maybe_watch(&mut self) -> Poll<(), Error> { trace!("maybe_watch? {:?}", self.state); let ve...
Rust
0
))); } Ok(cert) } } impl Body for Certs { fn into_message(self) -> ChanMsg { ChanMsg::Certs(self) } fn write_body_onto<W: Writer + ?Sized>(self, w: &mut W) { let n_certs: u8 = self .certs .len() .try_into() .expect("Too ma...
Rust
0
Attachment( name="Deleting multiple content", multiple_content=[b"Content 1", b"Content 2", b"Content 3"], ) ) session.commit() attachment = session.execute( select(Attachment).where(Attachment.name ...
Python
1
(False) fig.subplots_adjust(hspace=2, left=0.05, right=0.95, bottom=0.1, top=0.95) return fig @figure_test def test_tickable_gridlines(): wcs = WCS( { "naxis": 2, "naxis1": 360, "naxis2": 180, "crpix1": 180.5, "crpix2": 90.5, ...
Python
1
if let Some(mat) = IDENT.find(&s[pos..]) { tokens.push(Token::Ident(&s[pos+mat.start()..pos+mat.end()])); pos += mat.end(); } else if let Some(mat) = NUM.find(&s[pos..]) { tokens.push(Token::Num(s[pos+mat.start()..pos+mat.end()].parse().unwrap())); pos += mat.end(); } else if let Some(mat) = INT...
Rust
0
from pydantic import BaseModel class Token(BaseModel): access_token: str refresh_token: str | None = None token_type: str class TokenRefreshData(BaseModel): refresh_token: str = None class TokenData(BaseModel): username: str | None = None scopes: list[str] = [] class Login(BaseModel): ...
Python
1
nza\ny quema los escudos en el fuego.") }, PsalmVerse { number: 11, a: String::from("\"Estén, pues, quietos, y sepan que yo soy Dios; *"), b: String::from("he de ser ensalzado entre las naciones,\nensalzado seré en la tierra\".") }, PsalmVerse { number: 12, a: String::f...
Rust
0
] total_unread += result['unread'] else: failed_accounts.append({ 'account': result['account'], 'error': result['error'] }) exc...
Python
1
error::ExpressionTooLarge { value, spec: Specifier::from(buf.len() as u8), } .fail() } else { let start = buf.len() - bytes.len(); buf[start..].copy_from_slice(&bytes); Ok(Op::$op(buf)) } }}; } macro_rul...
Rust
0
) //! .nodes() //! .h(&["ip", "port", "heapPercent", "name"]) //! .send() //! .await?; //! //! let response_body = response.read_body::<String>().await?; //! # Ok(()) //! # } //! ``` //! //! pub use super::generated::namespace_clients::cat::*; <reponame>brunobell/aoc-2019 use std::error::Error; use std...
Rust
0
pub struct arm_biquad_casd_df1_inst_f32 { #[doc = "< number of 2nd order stages in the filter. Overall order is 2*numStages."] pub numStages: u32, #[doc = "< Points to the array of state coefficients. The array is of length 4*numStages."] pub pState: *mut float32_t, #[doc = "< Points to the array ...
Rust
0
import os,sys import importlib import options from utils import log import warnings warnings.filterwarnings("ignore") os.environ['WANDB_IGNORE_GLOBS'] = '*.pth' os.environ['WANDB_MODE'] = 'dryrun' def main(): log.process(os.getpid()) log.title("[{}] (PyTorch code for testing Sat2Density and debug".format(sys.a...
Python
1
LOG_ALL").is_ok(); let level = if bypass { LevelFilter::Trace } else { LevelFilter::Info }; log::set_boxed_logger(Box::new(Logger { bypass, out: io::stdout(), level, }))?; log::set_max_level(level); Ok(()) } pub struct Logger { bypass: bool, ...
Rust
0
32); map.insert("keys", VM::core_keys as fn(&mut VM, &Chunk, usize) -> i32); map.insert("values", VM::core_values as fn(&mut VM, &Chunk, usize) -> i32); map.insert("each", VM::core_each as fn(&mut VM, &Chunk, usize) -> i32); map.insert("from-json", VM::core_from_json as fn(&mut VM, &Chun...
Rust
0
amColorMarker, { pub entity: Entity, pub closest: &'w ClosestPlayer, pub team: &'w T, pub name: &'w Name, } #[derive(Debug, Default, Component, Inspectable)] #[component(storage = "SparseSet")] pub struct ControllingPlayer; #[derive(WorldQuery)] #[world_query(derive(Debug))] pub struct ControllingPlay...
Rust
0
import sys import numpy as np import pandas as pd import tensorflow as tf from tensorflow.keras.models import load_model import autokeras as ak from tensorflow.python.ops import image_ops from tensorflow.python.ops import io_ops """ keras模型预测 0~1 0 1~2 122 2~3 913 3~4 763 4~5 235 不均匀数据集导致回归预测高分区不准确 """ directory = "/o...
Python
1
"value": "one", }, ], [ { "node_name": "test1", "input": "in1", "value": 2, }, { "node_name": "...
Python
1
mix_identity: IdentityKeyRef<'a>, amount: &Coin, ) -> Result<ExecuteResult, NymdError> { let fee = self.operation_fee(Operation::DelegateToMixnode); let req = VestingExecuteMsg::DelegateToMixnode { mix_identity: mix_identity.into(), }; self.client ...
Rust
0
).register(world.clone()).unwrap(); }; // Scenario: [01D3PSPCNHH6CSW08RTFKZZ8SP] Find metric descriptors matching a filter when regex "01D3PSPCNHH6CSW08RTFKZZ8SP" | world, _matches, _step| { let desc_names: HashSet<_> = world.desc().iter().map(|desc| desc.fq_name.as_str()).collect(); world....
Rust
0
crate::diagnostics::{Diagnostic, Level}; use crate::diff::{parse_diff, FileChanges}; use crate::intervals::intersect_intervals; use crate::reporters::{report_diagnostic, OutputKind}; use anyhow::{bail, Context, Result}; use clap::{crate_authors, crate_description, crate_version, value_t, App, AppSettings, Arg}; use st...
Rust
0
stHeader> <ProtocolVersion> <ProtocolVersionMajor type="Integer" value="1"/> <ProtocolVersionMinor type="Integer" value="4"/> </ProtocolVersion> <BatchCount type="Integer" value="1"/> </RequestHeader> <BatchItem> <Operation type="Enumeration" value="Destroy"/> <RequestPayload> ...
Rust
0
# Copyright 2022 The HuggingFace Team and Brian Chao. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
Python
1
d list of json files from the stdin and generates the JSON Schema which is written to the stdout") .get_matches(); } const AUTHORS: &str = "Created and maintained by: <NAME> <<EMAIL>>, <NAME> <<EMAIL>>, <NAME> <<EMAIL>, <NAME>, <NAME>, <NAME>"; #[doc = "Reader of register GPIO_FUNC0_IN_...
Rust
0
{ let len = try!(self.read_u32()); f(self, len as usize) } fn read_seq_elt<T, F>(&mut self, _: usize, f: F) -> DecodingResult<T> where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult<T> { f(self) } fn read_map<T, F>(&mut self, f: F) -> DecodingResult<T> ...
Rust
0
struct AsyncAwaitRemoval; impl AsyncAwaitRemoval { pub fn remove_async_await(&mut self, item: TokenStream2) -> TokenStream2 { let mut syntax_tree: File = syn::parse(item.into()).unwrap(); self.visit_file_mut(&mut syntax_tree); quote!(#syntax_tree) } } impl VisitMut for AsyncAwaitRemov...
Rust
0
er_Path = Folder_Path SaveFile_Path = SaveFile_Path SaveFile_Name = SaveFile_Name # # 修改当前工作目录 # os.chdir(Folder_Path) # 将该文件夹下的所有文件名存入一个列表 file_list = os.listdir(Folder_Path) df_list = [] # 读取第一个CSV文件并包含表头 df = pd.read_excel(Folder_Path + '\\' + file_list[0]) # 编码默认UTF-8,若乱码自行更改 ...
Python
1
<bool, E>, { // TODO migrate use of Result<(), Option<E>> to ControlFlow when it's no longer unstable fn check<T, E>( mut f: impl FnMut(T) -> Result<bool, E>, ) -> impl FnMut((), T) -> Result<(), Option<E>> { move |(), x| match f(x) { Ok(true) => Ok(()...
Rust
0
brc = Birch(n_clusters=3, branching_factor=branching_factor, threshold=0.01) brc.fit(X) check_branching_factor(brc.root_, branching_factor) # Raises error when branching_factor is set to one. brc = Birch(n_clusters=None, branching_factor=1, threshold=0.01) with pytest.raises(Value...
Python
1
Capabilities::find_duplicates(&get_connection()); } pub fn hash(root_directory: &str) { println!("Hashing..."); Capabilities::start_hashing(&root_directory, &get_connection()); } pub fn orphans() { println!("Removing orphans from database..."); Capabilities::delet...
Rust
0
import numpy as np import PIL import pytest from laia.data import ImageDataset def test_image_dataset_empty(): dataset = ImageDataset([]) assert len(dataset) == 0 @pytest.mark.parametrize("transform", [None, lambda x: 1]) def test_image_dataset(monkeypatch, transform): expected_image = np.array([[1, 2]...
Python
1
Record> { let payload_len = if self.data.len() <= 0x100 { (self.data.len() - 1) as u8 } else { // Length (excluding length/checksum bytes) must fit in a single byte return Err(Error::RecordLengthOutOfBounds); }; let mut dat...
Rust
0
from .node import create_gather_visualizations_node __all__ = ["create_gather_visualizations_node"]
Python
1
cfg(test)] #[allow(unused_mut)] mod chanmon_update_fail_tests; #[cfg(test)] #[allow(unused_mut)] mod reorg_tests; #[cfg(test)] #[allow(unused_mut)] mod onion_route_tests; #[cfg(test)] #[allow(unused_mut)] mod monitor_tests; #[cfg(test)] #[allow(unused_mut)] mod shutdown_tests; pub use self::peer_channel_encryptor::LN_...
Rust
0
continue anns.append( Bbox( x=x1, y=y1, w=x2 - x1, h=y2 - y1, id=line_idx, attributes=attributes, labe...
Python
1
test_vector=embeddings, name_role=name_role, thresh=thresh) if person_name == 'Unknown': color =(0,0,255) # bgr else: color...
Python
1
"""Base class for Wallet Portfolio tools.""" from typing import List, Optional, Type from langchain.tools.base import ToolException from pydantic import BaseModel, Field from intentkit.abstracts.skill import SkillStoreABC from intentkit.skills.base import IntentKitSkill # Chain ID to chain name mapping for EVM chai...
Python
1
Determina o diretório de configuração do Earth Engine com base no SO. if system == "Windows": config_dir = os.path.join( os.environ["USERPROFILE"], ".config", "earthengine" ) elif system in ["Linux", "Darwin"]: # Linux or MacOS (Darwin) config_dir = os.path.join(os.environ[...
Python
1
行读取图中的节点个数和边的个数 let mut header = String::new(); let _ = reader.read_line(&mut header); let (v, e) = parse_line(header); assert_eq!(v, graph.v()); // 读取每一条边的信息 for _ in 0..e { let mut line = String::new(); let _ = reader.read_line(&mut line); let (v1, v2, weight) = pars...
Rust
0
pointing_device.pointing_type = "Track Point".to_string(); }, "6" => { pointing_device.pointing_type = "Glide Point".to_string(); }, "7" => { ...
Rust
0
bUtils.has_update("metric_graph", reset=True): logger.info("new data") dbUtils._subscribers["metric_graph"] = False is_new_data = True if is_new_data: print("New data") if options == "" or options is None: return [], style, old_children, old_tag_selec...
Python
1
mut factor = UnivarPolynomial::new(1); factor[0] = f[j].clone(); factor[1] = u_raised_to_powers_of_2[j].clone(); poly_i = UnivarPolynomial::multiply(&poly_i, &factor); } else { // If MSB of i is 0, multiply by X ...
Rust
0
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
Python
1
: IOCFG13, #[doc = "0x38 - Configuration of DIO14"] pub iocfg14: IOCFG14, #[doc = "0x3c - Configuration of DIO15"] pub iocfg15: IOCFG15, #[doc = "0x40 - Configuration of DIO16"] pub iocfg16: IOCFG16, #[doc = "0x44 - Configuration of DIO17"] pub iocfg17: IOCFG17, #[doc = "0x48 - Confi...
Rust
0
nome = 'erik' idade = 20 print(f"nome: {nome}, idade: {idade}") if idade < 18: print("menor de idade") else: print("maior de idade")
Python
1
} /// This is used to provide access to el_ws while recursively appending children to it. pub fn quick_clone(&self) -> Self { Self { tag: self.tag.clone(), attrs: Attrs::empty(), style: Style::empty(), text: None, children: Vec::new(), ...
Rust
0
"gameId": game_id}) async def fetch_game_playbyplay(self, game_id: str) -> Any: """Fetch play-by-play data for a specific game.""" return await self._get_json("wnbaplay", params={"gameId": game_id}) async def fetch_box_score(self, game_id: str) -> Any: """Fetch box score data for a spe...
Python
1
ribosome, } = args; if workspace.source_chain.has_genesis() { return Ok(()); } let result = ribosome.run_genesis_self_check( GenesisSelfCheckHostAccess, GenesisSelfCheckInvocation { payload: GenesisSelfCheckData { dna_def: dna_file.dna_def()...
Rust
0
= if let Some(id_type) = id_type { Some(quote! {#id_type}) } else if let (Some(ctx), Some(id)) = (input.ctx.as_ref(), input.id.as_ref()) { Some(gen_type_from_ctx_id(ctx, id).ok_or_else(|| { syn::Error::new(id.span(), "DekuRead: cannot determine `id` type from `ctx`") })?) } ...
Rust
0
img_coords[i, 1]), img_orig_width=img_orig_width, img_orig_height=img_orig_height, img_new_size=img_new_size, pad=True, ) embd_coords_xy.append([x_new, y_new]) embd_coords_xy_torch = torch.tensor(embd_coords_xy) return embd_coords_xy_torch def tr...
Python
1
from __future__ import annotations from typing import Any, Generator, Tuple, TypeVar import numpy as np from numpy.typing import NDArray _T = TypeVar("_T", bound=Any) def groupby_array( *arrays: NDArray[_T], by: NDArray[Any] ) -> Generator[Tuple[NDArray[_T], ...], None, None]: """Group arrays by a given ar...
Python
1
ion { assert!(hunk.process().is_ok()) } } } #[test] fn deserialize_too_many_fields() { init_log(); helper::load::<NewgroundsSong>(CREO_DUNE_DATA_TOO_MANY_FIELDS); helper::load::<Creator>(CREATOR_REGISTERED_DATA_TOO_MANY_FIELDS); } #[test] fn deserialize_level() { init_log(); ...
Rust
0
bject. Fields: pageSize: The maximum number of ReplayResult objects to return. Defaults to 5000. The maximum value is 5000; values above 5000 are rounded down to 5000. pageToken: A page token, received from a previous Simulator.ListReplayResults call. Provide this token to retrieve the ...
Python
1
ute is set up:")] /// ``` /// use actix_web::{web, App, HttpResponse}; /// /// let app = App::new().service( /// web::resource("/{project_id}") #[doc = concat!(" .route(web::", stringify!($method_fn), "().to(|| HttpResponse::Ok()))")] /// /// )...
Rust
0
CRYPTNET_PRE_FETCH_MIN_MAX_AGE_SECONDS_DEFAULT: DWORD = 1 * 60 * 60; pub const CRYPTNET_PRE_FETCH_MAX_MAX_AGE_SECONDS_VALUE_NAME: &'static str = "CryptnetPreFetchMaxMaxAgeSeconds"; pub const CRYPTNET_PRE_FETCH_MAX_MAX_AGE_SECONDS_DEFAULT: DWORD = 14 * 24 * 60 * 60; pub const CRYPTNET_PRE_FETCH_MIN_OCSP_VALIDITY_PE...
Rust
0
Some(v) => v, None => return Err("Failed to determine glob value".to_string()), }; let glob_matches = glob(glob_value).map_err(|e| e.to_string())?; for path in glob_matches { match path { Ok(p) => { if let Some(ext) = p.extension() { if...
Rust
0
# -*- coding: utf-8 -*- # # OpenCraft -- tools to aid developing and hosting free software projects # Copyright (C) 2015-2019 OpenCraft <xavier@opencraft.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free...
Python
1
rgar_articulos() if not articulos: print("\nNo hay artículos registrados.\n") return try: id_buscar = int(input("Ingrese el ID del artículo a eliminar: ")) except ValueError: print("ID inválido.") return articulo = next((art for art in articulos if art["id"] == id...
Python
1
from PyObjCTools.TestSupport import TestCase, min_os_level import NetworkExtension class TestNEAppProxyFlow(TestCase): def test_enum_types(self): self.assertIsEnumType(NetworkExtension.NETunnelProviderError) self.assertIsEnumType(NetworkExtension.NETunnelProviderRoutingMethod) @min_os_level("...
Python
1
"); None } } fn deserialize_contact_info(p: &PathBuf, f: &mut File) -> Option<ipc::CallMe> { let mut buf = String::new(); match f.read_to_string(&mut buf) { Ok(_) => match toml::from_str::<ipc::CallMe>(&buf) { Ok(config) => Some(config), Err(e) => { p...
Rust
0
from unittest.mock import patch from corehq.apps.accounting.models import Subscription, SubscriptionType from corehq.apps.groups.models import Group from ..views import NotificationsServiceRMIView def test_should_hide_feature_notifs_for_pro_with_groups(): with case_sharing_groups_patch(['agroupid']): hi...
Python
1
fading=self.fading.to_proto() if self.fading else None, ) @dataclass(frozen=True) class MoveNodesRequest: session_id: int node_id: int source: str = field(compare=False, default=None) position: Position = field(compare=False, default=None) geo: Geo = field(compare=False, default=No...
Python
1
0.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5...
Python
1
d}") MYLOGGER.info(f"---- USER {username}: model usage of GPU: {(before - after):2f} MB") return loaded_model def load_and_generate_image(user_data, loaded_model): """Generate images from loaded model based on user input Args: loaded_model: gr.State(StableDiffusionPipeline) Returns: ...
Python
1
r member in group_members] friends=[friend for friend in friends if friend not in group_members_nicknames] if not friends: print(f'待邀请好友已均位于{group_name}中,无法邀请至群聊中!') if friends: add=group_chat_settings_window.child_window(title='',control_type="Button",found_index=1) Approval_window=...
Python
1
rap(); for p in 0..5 { let f = do_hswitch(HDMIInput::try_from(p).unwrap()); assert_eq!(rt.block_on(f).unwrap(), format!("port{}R", p).as_bytes()); } } async fn do_tvswitch(input: TVInput, expected_size: usize) -> Result<Vec<u8>, Error> { let (mut s1, s2) = Serial...
Rust
0
from typing import List class DisjointSet: def __init__(self): self.par: List[int] = [i for i in range(26)] def find(self, num: int) -> int: par_num = num while par_num != self.par[par_num]: par_num = self.par[par_num] self.par[num] = par_num return par_...
Python
1
d, #[doc = "The mobile network resource identifier"] #[serde(rename = "serviceKey", default, skip_serializing_if = "Option::is_none")] pub service_key: Option<String>, } impl MobileNetworkPropertiesFormat { pub fn new(public_land_mobile_network_identifier: PlmnId) -> Self { Self { pr...
Rust
0
ectedComponents(bw) for label in range(1, num_labels): mask = (label_map == label) ys, xs = np.where(mask) if ys.size == 0: continue path_mm: List[Tuple[float,float]] = [] min_y, max_y = ys.min(), ys.max() ...
Python
1
from __future__ import print_function import errno import os import numpy as np # import cPickle # python2 import pickle as cPickle # python3 def assert_eq(real, expected): assert real == expected, '%s (true) vs %s (expected)' % (real, expected) def create_dir(path): if not os.path.exists(path): try...
Python
1
\ latest:{}, \ genesis:{}, \ snapshot:{:?}, \ private_tx_enabled:{})", peer_id, peer.protocol_version, peer.network_id, peer.difficulty, peer.latest_hash, peer.genesis, peer.snapshot_number, peer.private_tx_enabled ); if io.is_expired() { trace!(target: "sync", "Status packet...
Rust
0
rted. """ lineno = node.get_lineno() self.log_message('Line %d: %s' % (lineno, reason)) def start_tree(self, tree, filename): """Some fixers need to maintain tree-wide state. This method is called once, at the start of tree fix-up. tree - the root node of th...
Python
1
# outdated pomegranate code """from model import model # Observed data observations = [ "umbrella", "umbrella", "no umbrella", "umbrella", "umbrella", "umbrella", "umbrella", "no umbrella", "no umbrella" ] # Predict underlying states predictions = model.predict(observations) for pr...
Python
1
0008, 0x02) TerminateThread(0x0009, 0x02) Sleep(400) ChrTalk( 0x0103, ( '#0030020915V#025F#6P将军有没有想过\n', '我们特地从洛连特\n', '赶过来这里的原因啊?', TxtCtl.Enter, ), ) CloseMessageWindow() Sleep(400) ChrTalk( 0x0103, ...
Python
1
#[test] fn test_uint64_pre_encode() { let mut state = State::new(); (u64::MAX - 2).pre_encode(&mut state); assert_eq!( state, State { start: 0, end: 9, buffer: None, } ); } #[test] fn te...
Rust
0
rns - median)) modified_zscore = 0.6745 * np.abs(returns - median) / mad return modified_zscore > threshold elif method == 'iqr': # Interquartile Range returns = data['Close'].pct_change() Q1 = returns.quantile(0.25) Q3 = returns.quantile(0.75) IQR = Q3 - Q1 ...
Python
1
; const VK_DISCARD_RECTANGLE_MODE_EXCLUSIVE_EXT: VkDiscardRectangleModeEXT = 1; const VK_DISCARD_RECTANGLE_MODE_MAX_ENUM_EXT: VkDiscardRectangleModeEXT = u32::MAX; #[repr(C)] pub struct VkXYColorEXT { pub x: f32, pub y: f32, } #[repr(C)] pub struct VkHdrMetadataEXT { pub ty: VkStructureType, pub next:...
Rust
0
返回: int: 已读取的记录总数 """ return self._current_position def process_knapsack(s1, idx_knapsack, dst_dir): """ 处理单个 packing 数据 参数: s1: 当前处理组的索引 idx_knapsack: 背包中包含的索引列表 dst_dir: 目标目录路径 """ # global BASE_NAMES packed_imgs, packed_caps...
Python
1