text
string
label_name
string
labels
int64
import matplotlib.pyplot as plt import numpy as np import pybullet as p import pybullet_data import time import math import transforms3d # Connect to PyBullet in GUI mode p.connect(p.GUI) # Set the search path for URDF files p.setAdditionalSearchPath(pybullet_data.getDataPath()) # Load the ground plane and your rob...
Python
1
in images Used by the video processing page """ if 'image' not in request.files: return jsonify({ 'success': False, 'message': 'No image file provided' }) file = request.files['image'] if file.filename == '': return jsonify({ 'success...
Python
1
import my import tp # # This is an internal only object to fire lasers from staffs # def tp_init(name, text_long_name, text_short_name): self = tp.Tp(name, text_long_name, text_short_name) # begin sort marker my.gfx_ascii_shown(self, True) my.gfx_targeted_laser(self, "laser_discord") my.is_able_to...
Python
1
# FIXME support nD if self.keep_spatial: x = torch.cat([x, emb.unsqueeze(0).expand(batch_expand).permute(0, 3, 1, 2)], dim=1) else: x = torch.cat([x.permute(0, 2, 3, 1), emb.unsqueeze(0).expand(batch_expand)], dim=-1) x = x.reshape(B, feat_shape.numel(), -1) ...
Python
1
expected; let diff_norm = diff.opnorm_fro().unwrap(); diff_norm / denominator } pub fn are_equal_matrices_to_within(one : ArrayView2<f32>, two : ArrayView2<f32>, within : f32, print : bool) -> bool { let diff = &one - &two; let frob_norm = diff.opnorm_fro().unwrap(); if (frob_norm > within) { ...
Rust
0
::protobuf::types::ProtobufTypeUint64, >( "percentile_values_ns", |m: &MeasureCommandGetSummaryResponse_Histogram| &m.percentile_values_ns, |m: &mut MeasureCommandGetSummaryResponse_Histogram| &mut m.percentile_values_ns, )); ::prot...
Rust
0
+ 'static> Endpoint<State> for StaticFiles { type Fut = BoxFuture<'static, Response>; fn call(&self, ctx: Context<State>) -> Self::Fut { let served = self.path.clone(); let path = ctx.param::<PathBuf>("path").unwrap(); let future = async move { let path = served.join(path)....
Rust
0
c with automatic retries on specific errors. """ while True: success = await main(target, port, command, username, debug) if success: break print(f"{Fore.YELLOW}[WARNING] Reconnecting...") await asyncio.sleep(0.5) if __name__ == "__main__": parser = argparse.Arg...
Python
1
n torch.nn.functional.sigmoid( self.beta * (torch.log(value) - torch.log(1 - value)) - torch.log(self.alpha) ) def _q_bar_prob(self, value: torch.Tensor) -> torch.Tensor: r""" Computes the probability of the q_bar function. Args: value (torch.Ten...
Python
1
l Future<Output = Result<(), BoxError>> + Send + 'static) { self.0.push(check.boxed()); } /// Push a set of checks into the set. /// /// This method can be daisy-chained. pub fn and(mut self, checks: AsyncChecks) -> Self { self.0.extend(checks.0); self } /// Wait un...
Rust
0
from django.core.urlresolvers import RegexURLPattern, RegexURLResolver from django.core.exceptions import ImproperlyConfigured __all__ = ['handler404', 'handler500', 'include', 'patterns', 'url'] handler404 = 'django.views.defaults.page_not_found' handler500 = 'django.views.defaults.server_error' def include(arg, na...
Python
1
import torch class WarmupScheduler: def __init__(self, scheduler, lr_min, warmup): self.scheduler = scheduler self.warmup = warmup self.lr_min = lr_min self.warmup_scheduler = torch.optim.lr_scheduler.LambdaLR(scheduler.optimizer, ...
Python
1
internal_path = 0 depth=0 class TreeNode: def __init__(self, key): self.left = None self.right = None self.val = key def insert(root, key): if root is None: return TreeNode(key) else: if root.val < key: root.right = insert(root.right, key) else: ...
Python
1
= i2c.read_i2c_block_data(SW_ADDR, 0x00, 26) GPIO.setup(SW_XFER_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) if data[3] == 0x15 and data[4] == id: print_hex(data) return True return False reset() # Size Flags Seq ...
Python
1
#!/usr/bin/env python # SMTP transmission with manual EHLO - Chapter 13 - ehlo.py import sys, smtplib, socket if len(sys.argv) < 4: print "usage: %s server fromaddr toaddr [toaddr...]" % sys.argv[0] sys.exit(2) server, fromaddr, toaddrs = sys.argv[1], sys.argv[2], sys.argv[3:] message = """To: %s From: %s S...
Python
1
def slider_event_cb(evt): slider = evt.get_target() # Refresh the text label.set_text(str(slider.get_value())) # # Create a slider and write its value on a label. # # Create a slider in the center of the display slider = lv.slider(lv.scr_act()) slider.set_width(200) ...
Python
1
| |------------------|--------------------|--------------------| |Predicted Normal | {test_confm[0][0]} | {test_confm[1][0]} | |Predicted Failure | {test_confm[0][1]} | {test_confm[1][1]} | ## Metrics and Limitations **When component 7 is under service** **Faulty input data** """ model_card = ModelCard(...
Python
1
s): print(f"\nProcessing {symbol} ({i+1}/{len(Stock_Symbols)})") tensor_data = datagenerator( stock_symbol=symbol, stock_name=Stock_Names[i], stock_industry=Stock_Industries[i], stock_sector=Stock_Sectors[i], bertopic_model=topic_model...
Python
1
= np.array(camera["R"]), np.array(camera['t'])[:, np.newaxis] extrinsic_matrix = np.concatenate([R, T], axis=1) keypoint3d_camera = np.matmul(extrinsic_matrix, np.hstack( (keypoint3d, np.ones((keypoint3d.shape[0], 1)))).T) # (3 x NUM_KEYPOINTS) Z_c = ...
Python
1
訂單已完成或已取消,無法撤單" ) # 模擬撤單邏輯 success = await _cancel_order_with_broker(request.order_id, session_id) if success: # 更新訂單狀態 order["status"] = OrderStatus.CANCELLED order["updated_at"] = datetime.now() logger.i...
Python
1
""" Plugin for ResolveURL Copyright (C) 2024 gujal This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ...
Python
1
import os from newsapi import NewsApiClient from dotenv import load_dotenv load_dotenv() def get_news(query, language='en', page_size=100): """ Obtiene noticias utilizando la API de NewsAPI. Args: query (str): La palabra clave para buscar. language (str, optional): El idioma de las notici...
Python
1
q.iter()); for (i, (ps, qs)) in it.into_iter().enumerate() { let mut cs = cs.ns(|| format!("Pair_{}", i)); let mut f = Self::GTGadget::one(cs.ns(|| "f"))?; let mut idx: usize = 0; for (j, &n) in P::WNAF.iter().rev().enumerate() { let mut cs =...
Rust
0
clone(); let field = FieldRef::new("users.address.postcode".to_string()).unwrap(); assert!(ns.contains(&field)); ns.delete(field.clone()).unwrap(); assert!(!ns.contains(&field)); } #[test] fn delete_top_level_is_err() { let mut ns = USER_NAMESPACE.clone(); le...
Rust
0
pub const VSS_E_AUTORECOVERY_FAILED: HRESULT = 0x800423FB; pub const VSS_E_DYNAMIC_DISK_ERROR: HRESULT = 0x800423FC; pub const VSS_E_NONTRANSPORTABLE_BCD: HRESULT = 0x800423FD; pub const VSS_E_CANNOT_REVERT_DISKID: HRESULT = 0x800423FE; pub const VSS_E_RESYNC_IN_PROGRESS: HRESULT = 0x800423FF; pub const VSS_E_CLUSTER_E...
Rust
0
} } pub mod rotate_key_command { use super::*; command!(CommandMetadata::build("rotate-key", "Rotate keys for active did") .add_optional_deferred_param("seed", "If not provide then a random one will be created (UTF-8, base64 or hex)") .add_optional_param("fees_inputs","The...
Rust
0
ies.dispatch(query) def paginate(self, paginated_query: PaginatedQueryDTO[Any]) -> PagedResult[Any]: result = self.queries.dispatch(paginated_query) if not isinstance(result, PagedResult): raise TypeError(f"Esperado PagedResult, obteve {type(result).__name__}") return result cl...
Python
1
>() .once() .in_sequence(&mut seq) .with(eq(ReadPhysical::new(key3, PHYSICAL_PAGE_SZ as u64))) .returning(move |_| { let mut v = vec![0u8; PHYSICAL_PAGE_SZ]; for (i, elt) in v .iter_mut() .enumerate() .take(sz - spli...
Rust
0
rogenitor_support::encode_path(&client_id.to_string()), ); self.client .put(&url, Some(reqwest::Body::from(serde_json::to_vec(body)?))) .await } /** * Get-or-create an authorization for a specific app and fingerprint. * * This function performs a `PUT` to...
Rust
0
"order": "sorted" }, "action": { "type": "ContinuousAction" } } env_config = default_env_config gym_env.configure(env_config) gym_env.reset() # currently flatten the observations, will support other ways later gym_env = Flat...
Python
1
(*) as total_records FROM historical_indices GROUP BY category ORDER BY category """).fetchall() for row in result: print(f"\nCategory: {row[0]}") print(f"Number of Indices: {row[1]}") print(f"Date Range: {row[2]} to {row[3...
Python
1
s, GuestMemory, GuestMemoryRegion}; use crate::kvm::memory; pub const CMDLINE_MAX_SIZE: usize = 0x10000; #[derive(Debug, PartialEq)] pub enum Error { InitrdAddress, ZeroPageSetup, E820Configuration, } pub type Result<T> = std::result::Result<T, Error>; pub const PAGE_SIZE: usize = 4096; pub fn initrd_lo...
Rust
0
# -*- coding: utf-8 -*- # Copyright (C) 2024 BIRU # # This file is part of Tenzu. # # Tenzu 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 Software Foundation, either version 3 of the License, or (at your option) any later...
Python
1
_score(all_labels, all_preds) * 100 f1 = f1_score(all_labels, all_preds, average='weighted', zero_division=0) * 100 precision = precision_score(all_labels, all_preds, average='weighted', zero_division=0) * 100 recall = recall_score(all_labels, all_preds, average='weighted', zero_division=0) * 100 cm = c...
Python
1
#!/usr/bin/env python3 # Copyright (C) 2019 Checkmk GmbH - License: GNU General Public License v2 # This file is part of Checkmk (https://checkmk.com). It is subject to the terms and # conditions defined in the file COPYING, which is part of this source code package. # mypy: disable-error-code="no-untyped-def" from ...
Python
1
#!/usr/bin/env python3 # # Copyright 2020-2022 Fraunhofer Institute for Software and Systems Engineering # # 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/...
Python
1
lue); props[prop_index(prop3_name)] = Some(prop3_value); AuntRecord { number, props } } fn get_value(&self, prop: &usize) -> Option<i32> { self.props[*prop] } } enum Reading { Equal(i32), Greater(i32), Less(i32), } impl Reading { fn is_valid(&self, value: &i32) -> ...
Rust
0
", 0x5865_635D, 0x691D_4E3E), (r"textures\tx_mural1_00.dds", 0x5865_635D, 0x691D_4E9E), (r"textures\tx_guar_lip.dds", 0x5865_635D, 0x6920_46AE), (r"textures\tx_wood_dark.dds", 0x5865_635D, 0x6F37_F7DA), (r"textures\tx_wethwood.dds", 0x5865_635D, 0x749E_51E6), (r"textures\tx_sky_clear.dds", 0x58...
Rust
0
Other: Sized + SignedDistanceFunction2d<T>, { SdfUnion { left: self, right: other, } } } pub trait BoundedSdf<T>: SignedDistanceFunction2d<T> + BoundedGeometry<T, Dimension = U2> where T: Scalar, { } impl<X, T> BoundedSdf<T> for X where T: Scalar, X: SignedD...
Rust
0
() { // There is no piece on the source square let board = Board::new(); let src = Square::from_pos(Rank::C, File::First); let dst = Square::from_pos(Rank::D, File::First); assert_eq!(false, board.is_valid_move(ChessMove::new(src, dst))); } #[test] fn is_valid_move_dst_own_piece() { // Tries to...
Rust
0
user, pos_item) return self.loss_fct(ones, score_pos) + self.loss_fct(-1 * ones, score_neg) else: # randomly train i-i relation and u-u relation with u-i relation if random.random() < 0.5: # noqa: PLR2004 score_neg = self.forward(user, neg_item) ...
Python
1
Height(1), Round(1), &empty_hash(), Round(1), sandbox.s(ValidatorId(2)), )); sandbox.add_time(Duration::from_millis(sandbox.current_round_timeout() - 1)); sandbox.send( sandbox.p(ValidatorId(2)), &sandbox.create_propose_request( &sandbox.p...
Rust
0
[test] fn test() { let (res1, res2) = Solver::run_on_input(); assert_eq!(res1, 18227); assert_eq!(res2, 2355350878831); } #[test] fn test_pt1() { assert_eq!( 71, run1(&Solver::parse_input( " class: 1-3 or 5-7 ...
Rust
0
o.it/viaggiatrenonew/resteasy/viaggiatreno/soluzioniViaggioNew/{}/{}/{}", from.short_id().unwrap(), to.short_id().unwrap(), when.format("%FT%T") ); if cfg!(debug_assertions) { println!("{}", url); } let body: mapping::VTJourneySearchResult ...
Rust
0
# Copyright 2019 Google LLC # # 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
E: Trait; existential type F: Trait; const AnotherConst: i32 = 100; const SomeConst: i32 = 100; // comment on foo() fn foo() { println!("hello, world"); } fn foo1() { println!("hello, world"); } fn foo2() { println!("hello, world"); } fn foo3() {...
Rust
0
); assert_eq!(children.len(), 1); let floating_children = tree.floating_children(root_c); assert_eq!(floating_children.len(), 0); } } <gh_stars>1-10 use nom::{self, IResult, Err, Needed}; use frame::{self, ChannelAssignment}; use subframe::{self, Subframe, CodingMethod, PartitionedRiceConte...
Rust
0
# coding:utf-8 import sys from PySide6.QtCore import QPoint, Qt from PySide6.QtWidgets import QApplication, QWidget, QHBoxLayout from qfluentwidgets import InfoBarIcon, InfoBar, PushButton, setTheme, Theme, FluentIcon, InfoBarPosition, InfoBarManager @InfoBarManager.register('Custom') class CustomInfoBarManager(Info...
Python
1
ack(); if let AstNode::Constant(T![nil]) = rhs { out_str.push(']'); break; } else { out_str.push_str(", "); } top = self.peek_stack(); } Ok(out_str) } else { ...
Rust
0
try_from_peekable!(bytes, CPY); try_from_peekable!(bytes, DEC); try_from_peekable!(bytes, DEX); try_from_peekable!(bytes, DEY); try_from_peekable!(bytes, EOR); try_from_peekable!(bytes, INC); try_from_peekable!(bytes, INX); try_from_peekable!(bytes, INY); ...
Rust
0
# Generated by Django 5.1.2 on 2024-11-29 20:58 import django.utils.timezone from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0018_community_community_picture'), ] operations = [ migrations.AddField( model_name='post',...
Python
1
, // deprecated and ignored } } // ex: noet ts=4 filetype=rust use thiserror::Error; #[derive(Clone, Copy, Debug, Eq, Error, Hash, Ord, PartialEq, PartialOrd)] #[error("`Task` was cancelled")] pub struct Cancelled; // Make sure #1399 stays fixed fn foo() -> fn@() -> int { let k = ~22; let _u = {a: k}; ...
Rust
0
_from_ds.dim(), 1); assert_abs_diff_eq!(abs_err_from_arr1, 0.15, epsilon = 1e-5); assert_abs_diff_eq!(abs_err_from_arr1, abs_err_from_ds[0]); // odd length absolute errors let records = array![[0.0, 0.0], [0.1, 0.1], [0.2, 0.2], [0.3, 0.3], [0.4, 0.4]]; let targets = array![0.0,...
Rust
0
et mut v = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]; smul(&mut v, &[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], 1); assert!(v == [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); } <filename>src/pedigree.rs //! I/O for pedigree files. use std::fs::File; use csv; use super::errors::*; /// Sex o...
Rust
0
self.create(user_id, &self.users[user_id], channel, timestamp)? } } (Some(&"update"), 2) => { if self.check_host_name(user_id, channel, timestamp, splitted_messages.last())? { self.update(user_id, &self.users[user_id], channel, timestam...
Rust
0
{ info!("Running."); while let Some(TransactionSolidifierWorkerEvent(hash, index)) = self.receiver.next().await { self.solidify(hash, index); } info!("Stopped."); Ok(()) } } #[cfg(test)] mod tests {} <filename>src/outline/currency_bangladeshi.rs use seed::{pr...
Rust
0
var_tree = tree.tree_.impurity[tree.apply(Xstar)] var_tree = np.clip(var_tree, eps, np.inf) mean_tree = tree.predict(Xstar) std += var_tree + mean_tree ** 2 std /= len(trees) std -= ymean ** 2 std = np.sqrt(np.clip(std, eps, np.inf...
Python
1
lab-runner-rs mod request; pub(crate) use request::*; mod update; pub(crate) use update::*; mod trace; pub(crate) use trace::*; mod artifacts; pub(crate) use artifacts::*; use bech32::{u5, Bech32, FromBase32, ToBase32}; use chain_crypto::{ AsymmetricKey, AsymmetricPublicKey, Curve25519_2HashDH, Ed25519, Ed25519B...
Rust
0
, B) A2 = np.transpose(np.dot(c*R, np.transpose(A))) + t return A2 def euler2mat(theta, to_4x4=False): assert theta.shape[-1] == 3 original_shape = list(theta.shape) original_shape.append(3) theta = theta.view(-1, 3) theta_x = theta[:, 0:1] theta_y = theta[:, 1:2] theta_z = theta...
Python
1
import traceback import demistomock as demisto # noqa: F401 from CommonServerPython import * # noqa: F401 """ STANDALONE FUNCTION """ # Get Incident Details. def get_incident_sta(): return demisto.incidents()[0] # Check if user is a member of Unusual Activity Group. def check_user_exist_group_sta(field: Dic...
Python
1
# Title: Print the Sum of a Current Number and a Previous number # Statement: Write a Python code to iterate the first 10 numbers, and in each iteration, print the sum of the current and previous number. ''' Expected Output: Printing current and previous number sum in a range(10) Current Number 0 Previou...
Python
1
# number of anchors no = na * (nc + 5) # number of outputs = anchors * (classes + 5) layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args m = eval(m) if isinstance(m, str) else m # eval strings ...
Python
1
285 => Ok(258), _ => Err(Error::new(ErrorKind::InvalidData, "Invalid length symbol!")), } } /// Decodes the repetition distance from the distance symbol. /// RFC 3.2.5. fn decode_huffman_distance(&mut self, sym: u16) -> Result<usize> { const OFFSETS: [usize; 26] = [ ...
Rust
0
bject) -> EasyMod """ 添加服务端初始化调用方法 """ REG_SERVER_INIT_CALL(callFunc) return self def addClientInitCallFunc(self, callFunc=lambda: None): # type: (object) -> EasyMod """ 添加客户端初始化调用方法 """ REG_CLIENT_INIT_CALL(callFunc) return self def regNativePyClien...
Python
1
pub struct NullActionHandler; impl ActionHandler for NullActionHandler { fn do_action(&self, _request: ActionRequest) {} } pub fn test_tree() -> Arc<crate::tree::Tree> { let root = Node { children: vec![ PARAGRAPH_0_ID, PARAGRAPH_1_IGNORED_ID, ...
Rust
0
} #[test] fn it_correctly_converts_to_string_for_complex_cases() { let location = Regex::new(r",\slocation:\s(-)?[\d]+").unwrap(); let tests = [ include_str!("data/sql/table_1.sql"), include_str!("data/sql/view_1.sql"), include_str!("data/sql/func_1.sql"), include_str!("data/sq...
Rust
0
); keysyms.insert("Georgian_ghan", 0x10010e6); keysyms.insert("Georgian_qar", 0x10010e7); keysyms.insert("Georgian_shin", 0x10010e8); keysyms.insert("Georgian_chin", 0x10010e9); keysyms.insert("Georgian_can", 0x10010ea); keysyms.insert("Georgian_jil", 0x10010eb); keysyms.insert("Georgian_cil", 0x10010ec);...
Rust
0
yFromIntContext.fail(); } let mut output = [0u8; $ii]; let bytes = x.to_be_bytes(); let start = std::mem::size_of::<$ty>() - $ii; output.copy_from_slice(&bytes[start..]); Ok(Imm::Constant(output)) } } ...
Rust
0
efore - num_after))) }, QuitAndSave, "Finish editing component" => { components[index] = component; return Ok(Some("Finished editing component".to_string())); }, QuitWithoutSaving, "Abort editing and discard changes" => { return Ok(Some("Discarding c...
Rust
0
" => { let h = Hnsw::<f32, DistJeffreys>::new(max_nb_conn, 10000, 16, ef_const, DistJeffreys{}); let api = HnswApif32{opaque: Box::new(h)}; return Box::into_raw(Box::new(api)); } _ => { log::warn!("init_hnsw_f32 received unknow distance {:?} ", dname); let p = ...
Rust
0
.created, 'YYYY-MM-DD\THH24:MI:SS.US') AS day, COUNT("user".id) AS day_users FROM "user" WHERE TO_DATE("user".created, 'YYYY-MM-DD\THH24:MI:SS.US') >= ...
Python
1
_size#(32,32) h, w = grid_size epsilon =1e-5 # 正则化Sigma Sigma_reg = torch.from_numpy(gmm_simga).to(device) + epsilon * torch.eye(gmm_simga.shape[1], device=device).unsqueeze(0) # 批量计算差值 diff = (torch.from_numpy(features_pca).to(device...
Python
1
import numpy as np from collections import Counter import torch.nn as nn from torch.nn import functional as F import torch from math import isnan from .vocab import PAD_ID, EOS_ID def to_bow(sentence, vocab_size): ''' Convert a sentence into a bag of words representation Args - sentence: a list of to...
Python
1
import pytest from apps.diplomas.models import Diploma, Languages pytestmark = [ pytest.mark.django_db, ] @pytest.fixture(autouse=True) def diploma(mixer, order): return mixer.blend("diplomas.Diploma", study=order.study, language=Languages.RU) @pytest.fixture def query(): return lambda: Diploma.object...
Python
1
import matplotlib.pyplot as plt import numpy as np # 示例数据 x = np.arange(1, 31) # 横轴:进化代数,范围是1到30 y_1 = [ 8.958310e+10, 8.545415e+10, 6.570399e+10, 5.647282e+10, 5.623002e+10, 5.121097e+10, 4.998651e+10, 4.676474e+10, 4.612247e+10, 4.548019e+10, 4.419565e+10, 4.217306e+1...
Python
1
", font=("Arial", 20, "bold"), fg="#FFD700", bg="#2D0A4D") title_label.pack(pady=15) # إطار التحكم control_frame = tk.Frame(manager_window, bg="#3C1361") control_frame.pack(fill=tk.X, padx=20,...
Python
1
.as_bytes() } } /// "Decode" a scalar from a 32-byte array. /// /// By "decode" here, what is really meant is applying key clamping by twiddling /// some bits. /// /// # Returns /// /// A `Scalar`. fn clamp_scalar(mut scalar: [u8; 32]) -> Scalar { scalar[0] &= 248; scalar[31] &= 127; scalar[31] |= 64; ...
Rust
0
""" 集成测试:章节创建流程(按已实现端点对齐)。 """ import sys from pathlib import Path from fastapi.testclient import TestClient sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src")) from main import app client = TestClient(app) class TestChapterCreationWorkflow: def test_complete_chapter_creation_workflow(self): ...
Python
1
.time() self.LIMIT = limit url = self.BASE_URL + "/top100" return await self.parser_result(start_time, url, session) async def recent(self, category, page, limit): async with aiohttp.ClientSession() as session: start_time = time.time() self.LIMIT ...
Python
1
{args}") # If DROP_CLIENT_UNKNOWN is enabled, check if the client identified # by calling server.version previously. If not, disconnect the session if self.env.drop_client_unknown and method != "server.version" and self.client == "unknown": self.logger.info("disconnecting because c...
Python
1
[`gaps`]: RangeMap::gaps pub struct Gaps<'a, K, V> { outer_range: &'a Range<K>, keys: core::iter::Peekable<alloc::collections::btree_map::Keys<'a, RangeStartWrapper<K>, V>>, candidate_start: &'a K, } // `Gaps` is always fused. (See definition of `next` below.) impl<'a, K, V> core::iter::FusedIterator for ...
Rust
0
Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn...
Rust
0
import torchvision.models as models # for timm models we don't have such files, since it provides a simple wrapper timm.create_model. Check tools.models.py BACKBONES = { "alexnet": models.alexnet, "resnet18": models.resnet18, "resnet34": models.resnet34, "resnet50": models.resnet50, "resnet101": mo...
Python
1
# 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
invert_bounds(bounds.clone()); let source_slice_shape = source_bounds.to_shape(self.source.shape())?; let expand_axis = self.rebase.expand_axis(); let source_expand_axis = if bounds[expand_axis].is_index() { // in this case the expanded dimension is elided None }...
Rust
0
name()), _ => Some(i.name()) }, _ => Some(i.name()), }, RSASTItem::Variant(v, _) => Some(v.name()), RSASTItem::Field(f) => match f.ident { Some(ref id) => Some(id...
Rust
0
me.page_num + 1, tuples: page_data, }; create_page(&page, scheme.table_name.clone()); } pub fn read_table(&self, table_name: impl ToString + Hash) -> (&Scheme, Vec<PageAuxiliar>) { let mut scheme = { let table_id = gen_hash(&table_name); self.catalog....
Rust
0
pub fn datatype(def: DefId, scope: ScopeId, ty: VTy) -> Val { Val::App( Var::Type(def, scope), Box::new(ty), Vec::new(), Glued::new(), ) } pub fn boolean(b: bool) -> Val { match b { true => Val::builtin(Builtin::True, Val::buil...
Rust
0
c2(neighbor) { Some(_) => { if !self.visited.contains_key(&neighbor) { self.queue .push_back(SearchPath::new(neighbor, candidate.pos)) } {} } None => continue, ...
Rust
0
from flask import Flask, request, jsonify from flask_sqlalchemy import SQLAlchemy from flask_restful import Api, Resource from http import HTTPStatus import uuid # Assuming appropriate imports for services and exceptions # from your_service import EhrService, CompositionService # from your_exception import ObjectNotFo...
Python
1
#----------------------------------------------------------------------------- # Copyright (c) 2005-2023, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License (version 2 # or later) with exception for distributing the bootloader. # # The full license is in the file COPYING.txt...
Python
1
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class DeviceContent(object): def __init__(self): self._content_list = None self._device_sn = None @property def content_list(self): return self._content_list @cont...
Python
1
e = "GL_KHR_debug"))))] pub unsafe fn glGetObjectPtrLabelKHR_load_with_dyn( get_proc_address: &mut dyn FnMut(*const c_char) -> *mut c_void, ) -> bool { load_dyn_name_atomic_ptr( get_proc_address, b"glGetObjectPtrLabelKHR\0", &glGetObjectPtrLabelKHR_p, ) } /// Checks if the pointer ...
Rust
0
let mut file = tokio::fs::File::create(&tar_path).await.unwrap(); let r = reqwest::get(download_url).await.unwrap(); file.write_all(&r.bytes().await.unwrap()).await.expect("Could not write to file."); } let zipped_path = format!("/tmp/scales-pypi-{}-{}.tar.gz", dependency.name, dependency...
Rust
0
d: self.offload_model_to_cpu(self.model) self.ae.decoder.to(x.device) x = unpack(x.float(), height, width) x = self.ae.decode(x) self.offload_model_to_cpu(self.ae.decoder) x1 = x.clamp(-1, 1) x1 = rearrange(x1[-1], "c h w -> h w c") ...
Python
1
''' Crie um programa que calcule o IMC do usuário. O programa irá informar o valor do IMC e informar o diagnóstico (consultar tabela do IMC na internet). ''' # Criando as variáveis para o cálculo do IMC # Entrada de dados peso = float(input("Informe seu peso em Kg: ").replace(",",".")) altura = float(input("Informe su...
Python
1
def partition(array, low, high): pivot = array[high] i = low - 1
Python
1
#!/usr/bin/env python # coding: utf-8 # To run this, press "*Runtime*" and press "*Run all*" on your A100 Google Colab Pro instance! # <div class="align-center"> # <a href="https://unsloth.ai/"><img src="https://github.com/unslothai/unsloth/raw/main/images/unsloth%20new%20logo.png" width="115"></a> # <a href="https://...
Python
1
# On importe les bibliothèques nécessaires import pandas as pd import numpy as np import os from pydub import AudioSegment import sys def _calculate_loudness(audio_file_path, start, end): # Vérifier si le chemin du fichier est NaN ou inexistant if pd.isna(audio_file_path) or not os.path.isfile(audio_file_path)...
Python
1
macro_rules! js_into { ($arg:expr, $type:ty) => {{ let res: Result<$type, JsValue> = match $arg.into_serde() { Ok(ok) => Ok(ok), Err(e) => Err(js_error!("{}", &e.to_string())), }; res }}; } pub type JsReturn<T = JsValue> = Result<T, JsValue>; <filename>tests/try_build/do_not_hold_ctx_throu...
Rust
0