text
string
label_name
string
labels
int64
if isinstance(model, nn.Module): # PyTorch model for x in 'model.args', 'model.model.args', 'model.model.model.args': with contextlib.suppress(Exception): return eval(x)['task'] for x in 'model.yaml', 'model.model.yaml', 'model.model.model.yaml': with contextl...
Python
1
-dx * value.sin() + dy * value.cos(), ) } 'F' => position = (x + dx * value, y + dy * value), _ => (), } } Ok((position.0.abs() + position.1.abs()).round()) } fn part2(input: &Vec<String>) -> Result<f64, &str> { let mut direction = (1.0, 0.0); ...
Rust
0
on=True) self.monitoring_thread.start() print(f"継続監視を開始しました(間隔: {interval}秒)") def stop_continuous_monitoring(self): """継続的な監視を停止""" self.monitoring_active = False if self.monitoring_thread: self.monitoring_thread.join(timeout=5) print("継続監視を停止しま...
Python
1
l s    rFcCs@|ddvr |dd}t|rdSt|rdSd|dS) Nr'"rr zkind(rA)rr real8pattern)r]r%r%r& _kind_func~ s     rKcCsLd|}|dkr dS|dkrdS...
Python
1
a::index::Error), #[error(transparent)] Json(#[from] JsonError), #[error("Protobuf decoding error")] #[serde(serialize_with = "crate::serialize_as_display")] ProtoDecode(#[from] prost::DecodeError), #[error("protocol error (invalid state or invocation)")] InvalidState, #[error(transparen...
Rust
0
SCALE_IDXR::_001, 2 => DCOC_ALPHAC_SCALE_IDXR::_010, 3 => DCOC_ALPHAC_SCALE_IDXR::_011, 4 => DCOC_ALPHAC_SCALE_IDXR::_100, 5 => DCOC_ALPHAC_SCALE_IDXR::_101, i => DCOC_ALPHAC_SCALE_IDXR::_Reserved(i), } } #[doc = "Checks if the value of the fie...
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
nce and base qualities are of different length.") } // TODO: Maybe printing one char at a time would be just as fast? for (base, qual) in seq.chars().zip(base_qualities.chars()) { // FIXME: We assume Sanger format base qualities here. output.push(if qual as u8 - 33u8 < min_baseq { 'N' } else { base }); }...
Rust
0
,"PinPcb"], [{y:-0.75,x:3.75,w:0.5,h:0.5},"PinPcb"], [{r:30,rx:5,ry:3.25,y:1,x:-1,sm:"cherry",a:7},"","",""], [{y:-0.8,x:-0.1,sm:"pinplate",a:4,w:0.5,h:0.5},"PPlate",{x:0.5,w:0.5,h:0.5},"PPlate"], [{r:90,rx:5.25,ry:1.2,y:-1.1,x:1.85,sm:"trrs",a:5,w:0.5},"trrs"] ]""" ) keyboard.meta.split = True return keybo...
Python
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 🤖 机器人轮询客户端 使用HTTP轮询方式与服务器通信 """ import requests import json import time import random from datetime import datetime class RobotPollingClient: """机器人轮询客户端""" def __init__(self, server_url, robot_id): self.server_url = server_url self.rob...
Python
1
"auth.check.url"), ("(gint) GST_RTSP_FILTER_KEEP", "1"), ("(gint) GST_RTSP_FILTER_REF", "2"), ("(gint) GST_RTSP_FILTER_REMOVE", "0"), ("(gint) GST_RTSP_MEDIA_STATUS_ERROR", "5"), ("(gint) GST_RTSP_MEDIA_STATUS_PREPARED", "3"), ("(gint) GST_RTSP_MEDIA_STATUS_PREPARING", "2"), ("(gint) GST_RTS...
Rust
0
# Using break inside for loop for s in "PYTHON LOOP": if s=='L': break print("current letter:",s)
Python
1
umstr, e).unwrap(); std::process::exit(1); } }; } else { return numstr.parse().unwrap(); } } fn parse_args() -> Args { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optopt("m", "memo...
Rust
0
""" This file is an example of how to manually register commands to prevent the worker thread rate limit problem. To run this example, first register the commands: $ python3 examples/multiworker/manual.py register Then, start the Gunicorn server (or whichever server you are using): $ gunicorn -w 4 examples.mu...
Python
1
ne(validator.validate("a-safe-password")) with self.assertRaises(ValidationError) as cm: validator.validate("from-my-custom-list") self.assertEqual(cm.exception.messages, [expected_error]) self.assertEqual(cm.exception.error_list[0].code, "password_too_common") def test_validat...
Python
1
mer when available.""" timer = get_global_timer() if timer is None: with nullcontext(): yield else: with timer.measure(category): yield def print_global_summary(title: str = "Timing Summary", show_counts: bool = True): timer = get_global_timer() if timer is n...
Python
1
# Copyright (c) ONNX Project Contributors # # SPDX-License-Identifier: Apache-2.0 import numpy as np import onnx from onnx.backend.test.case.base import Base from onnx.backend.test.case.node import expect class Equal(Base): @staticmethod def export() -> None: node = onnx.helper.make_node( ...
Python
1
frame as JPG _, buffer = cv2.imencode(".jpg", rgb_frame) # Convert to base64 string base64_frame = base64.b64encode(buffer.tobytes()).decode("utf-8") response[camera_id] = base64_frame except Exception as e: logger.error(f"Error processing frame fo...
Python
1
; use failure::Error; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; pub async fn get_store_from_settings(settings: &CisSettings) -> Result<SecretStore, Error> { let mut store = SecretStore::default(); store = match settings.sign_keys.source.as_str() { "none" => store, "fil...
Rust
0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from collections import defaultdict from operator import itemgetter from odoo import exceptions, fields, models from odoo.tools import groupby class MailMessage(models.Model): """ Override MailMessage class in ord...
Python
1
+1]); } else if j < n { assert!(*doc == ins_docs_tmp[1]); } else { assert!(*doc == ins_docs_tmp[j-n]); } if cursor.is_dead() { break; } j += 1; } } Err(e) => fail!("%s", e.to_str()), } // regular cursor again to check ...
Rust
0
rt.expect_validate_caller_type(vec![*INIT_ACTOR_CODE_ID]); let params = ConstructorParams { to: test_case.to_addr, from: test_case.from_addr }; expect_abort( &mut rt, METHOD_CONSTRUCTOR, &RawBytes::serialize(params).unwrap(), ...
Rust
0
ed_im_w, mask_threshold=0.5): """ Resize the output instances. The input images are often resized when entering an object detector. As a result, we often need the outputs of the detector in a different resolution from its inputs. This function will resize the raw outputs ...
Python
1
import discord from discord import app_commands from discord.ext import commands import random import time import json #* SALDOS def load_saldos(): try: with open("./dados/saldos.json", "r") as f: return json.load(f) except FileNotFoundError: return {} def save_saldos(saldos): w...
Python
1
ights_dir, 'loss_curve.png')) # if early_stopper(avg_val_loss,epoch=epoch+1): # print("[⛔] Early stopping triggered. Best val loss:", early_stopper.best_loss) # break if not (torch.isnan(torch.tensor(avg_val_loss)) or torch.isinf(torch.tensor(avg_val_loss))) and early_stopper(a...
Python
1
nism. // // This issue is tracking making some of this stuff public: // https://github.com/serde-rs/serde/issues/741 #![doc(hidden)] use core::cmp; use core::fmt; use core::marker::PhantomData; #[cfg(all(not(feature = "std"), feature = "collections"))] use collections::{String, Vec}; #[cfg(all(feature = "alloc", no...
Rust
0
no_vis, debug=not args.no_debug, terminal_debug=args.terminal_debug, vis_frequency=args.vis_frequency, create_gif=not args.no_gif, gif_fps=args.gif_fps, ) # Show paths to debug files if requested if args.show_debug_files: ...
Python
1
fier 4'), ('🏾', '🏾 Emoji Modifier 5'), ('🏿', '🏿 Emoji Modifier 6'), ('🤘', '🤘 Rock On'), ('📿', '📿 Prayer Beads'), ('🤖', '🤖 Robot'), ('🦁', '🦁 Lion'), ('🦄', '🦄 Unicorn'), ('🦃', '🦃 Turkey'), ('🦀', '🦀 Crab'), ('🦂', '🦂 Scorpion'), ('🧀', '🧀 Cheese'), ('🌭', '🌭 Hot Dog'), ('🌮', '🌮 Taco'), ('🌯', '🌯 Bu...
Python
1
ERTEXATTRIB2SVARBPROC; } pub type PFNGLVERTEXATTRIB3DARBPROC = ::std::option::Option< unsafe extern "C" fn(index: GLuint, x: GLdouble, y: GLdouble, z: GLdouble), >; extern "C" { pub static mut glad_glVertexAttrib3dARB: PFNGLVERTEXATTRIB3DARBPROC; } pub type PFNGLVERTEXATTRIB3DVARBPROC = ::std::option::Optio...
Rust
0
PRODUCT = 'MXF' PERIOD_30S = '30s' PERIOD_59S = '59s' PERIOD_1M = '1m' PERIOD_5M = '5m' PERIOD_15M = '15m' PERIOD_30M = '30m' MAX_CANDLE_AMOUNT = { PERIOD_30S: 2280, # 2280 / DAY PERIOD_59S: 1140, PERIOD_1M: 1140, # 1140 / DAY PERIOD_5M: 228, # 228 / Day PERIOD_15M: 76, # 76 / DAY PERI...
Python
1
import sys sys.path.append(r'D:\Dev\Source\Falcom\Decompiler2') from Falcom.ED62.Parser.scena_writer_helper import * try: import T4100_1_hook except ModuleNotFoundError: pass scena = createScenaWriter('T4100_1 ._SN') # id: 0xFFFF offset: 0x0 @scena.Header('Header') def Header(): header = ScenaHeader() ...
Python
1
r(dep_spec): spec_matched = True versions = set(match.group(1, 2)) - {None} match_version = cls.get_version_tuple(versions.pop()) if version[: len(match_version)] == match_version: return True return not spec_matched @classmethod def _get...
Python
1
} pub fn parse_instruction(bytecode: &[u8]) -> SizedInstruction { /* TODO: ** prefixes ** */ let sized_ins = prefix4bit(bytecode); sized_ins } // Catch immediate mov to reg fn prefix4bit(bytecode: &[u8]) -> SizedInstruction { let tentative_opcode = bytecode[0] >> 4; let opcode_byte = bytecode[0]; let make_imm_r...
Rust
0
# SPDX-FileCopyrightText: Copyright (c) 2021-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: LicenseRef-NvidiaProprietary # # NVIDIA CORPORATION, its affiliates and licensors retain all intellectual # property and proprietary rights in and to this material, related # documentation ...
Python
1
time.sleep(1) count += 1 command = 'ssh -i /home/ubuntu/zihengw.pem ubuntu@' + ip + ' "/home/ubuntu/.local/bin/ray stop"' os.system(command) process = multiprocessing.Process(target = killer) process.start() start = time.time() print(f()) end = time.time() pr...
Python
1
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. 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 # # ...
Python
1
29/9437410428_5f12f85913_z.jpg", ]; pub static ref DATA_DIR: PathBuf = { let data_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("test_data"); std::fs::create_dir_all(&data_dir).unwrap(); data_dir }; } #[cfg(feature = "full")] mod blocking_example { use super::*; use i...
Rust
0
assert results assert "trying fuzzy" in output assert "threshold=0.5" in output def test_fuzzy_match_verbose__debug_logging( fuzzy_context: FuzzyMatchContext, sample_name_cache: dict[str, dict[str, str]], debug_logger: logging.Logger, log_stream: StringIO, ) -> None: """Fuzzy match emits ve...
Python
1
# -*- coding: utf-8 -*- # # Copyright 2022 Google LLC. 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
idx: isize) -> Self { if idx < 0 { GridIndex::SubGrid(idx as usize) } else if idx > 0 { GridIndex::Cell(idx as usize) } else { GridIndex::Invalid } } } impl MeshData { pub fn new(verts: Vec<[f32; 3]>, indices: Vec<usize>) -> MeshData { ...
Rust
0
from copy import deepcopy from math import floor class Quarry: class Skills: class Skill: work_minutes = 0 work_time_str = "" mood = 100 def __init__(self, name: str = None, base_weight: float = 0, ...
Python
1
_") // ); // assert!(parse_snake_ident("Hello").is_err()); // assert!(parse_snake_ident("9Hey").is_err()); // } // #[test] // fn it_parses_camel_idents() { // // Starts with capital letter // assert_eq!( // parse_camel_ident(Span::new("Hello")).unwrap(), ...
Rust
0
: key, value = arg_pair.split('=', 1) # Clean up potential quotes around values args[key.strip()] = value.strip().strip('"\'') if func_name == "control_fan": tool_response = control_fan(**args) e...
Python
1
) .unwrap(), Fp::from_str( "7372230383134982628913227482618052530364724821976589156840317933676130378411", ) .unwrap(), ], vec![ Fp::from_str( "2020360675850121...
Rust
0
oggle-button-view-model/button/div[2]').text if likes_el[-1]=='K': likes_el = float(likes_el.replace('K','')) likes=int(likes_el*1000) elif likes_el[-1]=='M': likes_el = float(likes_el.replace('M','')) likes...
Python
1
"Given command is not associated with the handler !") } } #[derive(Debug)] pub struct NoCommandHandlerRegisterForGivenCommand {} impl Error for NoCommandHandlerRegisterForGivenCommand {} impl Display for NoCommandHandlerRegisterForGivenCommand { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { ...
Rust
0
02\x01\x03\x12\x03\x119B\n\x0b\n\x04\x06\0\x02\x02\ \x12\x03\x12\x042\n\x0c\n\x05\x06\0\x02\x02\x01\x12\x03\x12\x08\x11\n\ \x0c\n\x05\x06\0\x02\x02\x02\x12\x03\x12\x13\x1c\n\x0c\n\x05\x06\0\x02\ \x02\x03\x12\x03\x12'0b\x06proto3\ "; static mut file_descriptor_proto_lazy: ::protobuf::lazy::Lazy<::protobuf::...
Rust
0
js)) round_init_delta = round_init_adjs - test_adj_b logging.info(f"sample delta_norm_mean: {delta.norm(dim=[1, 2]).mean().item():.3e} " f"| init delta_norm_mean: {init_delta.norm(dim=[1, 2]).mean().item():.3e}" f"| round init delta_norm_mean: {round_init_delta.norm(dim=[1, 2])...
Python
1
amount: u64::from_le_bytes(*array_ref![buf, 72, 8]), signature: *array_ref![buf, 80, 96], }); ret.push(tx); } ret } } <reponame>ohadravid/nalgebra-numpy<filename>src/from_numpy.rs use nalgebra::base::{SliceStorage, SliceStorageMut}; use nalg...
Rust
0
) => panic!("Failed to change the socket name: {}", err) } drop(socket) } #[test] fn should_change_request_resend_interval() { let mut socket = match Socket::new(Req) { Ok(socket) => socket, Err(err) => panic!("{}", err) }; assert!(socket....
Rust
0
from packaging import version import google.protobuf if version.parse(google.protobuf.__version__).major == 5: from .v5 import ( auth_pb2, auth_pb2_grpc, chat_pb2, chat_pb2_grpc, collections_pb2, collections_pb2_grpc, deferred_pb2, deferred_pb2_grpc,...
Python
1
# 檢查各組件狀態並生成建議 if results.get('html_parser_test', {}).get('status') != 'passed': recommendations.append("增強HTML解析器需要進一步優化,建議檢查Selenium配置") if results.get('backup_manager_test', {}).get('status') != 'passed': recommendations.append("多層備援機制需要完善,建議增加更多備援數據源") ...
Python
1
import requests import pandas as pd import time def fetch_data_with_retry(url: str, params: dict, max_retries=5) -> requests.Response: for attempt in range(max_retries): response = requests.get(url, params=params) if response.status_code == 200: return response # Successfully got a res...
Python
1
for i in range(0, 2 * n): for j in range(0, 2 * m): dij = self.D(i, j) dkj = self.D(0, j) if dij < dkj: atBoundary0onBez1 = False dkj = self.D(2 * n, j) if dij < dkj: atBoundary1onBez1 ...
Python
1
egui::Color32::from_rgba_unmultiplied(50, 50, 50, 255); colors[ColorStyle::NodeBackgroundHovered as usize] = egui::Color32::from_rgba_unmultiplied(75, 75, 75, 255); colors[ColorStyle::NodeBackgroundSelected as usize] = egui::Color32::from_rgba_unmultiplied(75, 75, 75,...
Rust
0
import logging import os, types, importlib from contextlib import ContextDecorator # Set up logger logger = logging.getLogger(__name__) class NoCUDA(ContextDecorator): def __enter__(self): # # ---------- environment variable ------------------------------------- self._old_cuda_visible = os.environ...
Python
1
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # ht...
Python
1
pport both the `x86` and `x86_64` platforms, //! we only support 32-bit `x86` machines. SOS is a protected mode or //! long mode OS, and will not run on early x86 machines such as 286s. use util::{io, Void}; macro_rules! cpu_flag { ($doc:meta, $flag:ident, $get:ident, $set:ident) => { #[$doc] pub u...
Rust
0
: Matrix3x2<T>, b: Matrix3x2<T>) -> Matrix3x2<T> where T: Copy + Sub<T, Output = T> { [ vec2_sub(a[0], b[0]), vec2_sub(a[1], b[1]), vec2_sub(a[2], b[2]) ] } /// Subtracts 'b' from 'a'. #[inline(always)] pub fn mat3_sub<T>(a: Matrix3<T>, b: Matrix3<T>) -> Matrix3<T> where T: Copy...
Rust
0
test = { 'name': 'mul_interval', 'points': 1, 'suites': [ { 'cases': [ { 'code': r""" >>> str_interval(mul_interval(interval(-1, 2), interval(4, 8))) '-8 to 16' """, 'hidden': False, 'locked': False } ], 'scored': Tr...
Python
1
} #[repr(C)] #[doc = "*Required features: 'Win32_System_SystemServices'*"] pub struct DEV_BROADCAST_HANDLE64 { pub dbch_size: u32, pub dbch_devicetype: u32, pub dbch_reserved: u32, pub dbch_handle: u64, pub dbch_hdevnotify: u64, pub dbch_eventguid: ::windows_sys::core::GUID, pub dbch_nameof...
Rust
0
"content": [ {"type": "image_url", "image_url": {"url": image_url}}, {"type": "text", "text": user_question}, ], }, ] probability = 0.0 response_text = "" try: ...
Python
1
iberFeaturesAddAcknowledgeSubscriberReceived(builder, acknowledgeSubscriberReceived): builder.PrependBoolSlot(5, acknowledgeSubscriberReceived, 0) def AddAcknowledgeSubscriberReceived(builder, acknowledgeSubscriberReceived): return SubscriberFeaturesAddAcknowledgeSubscriberReceived(builder, acknowledgeSubscriberRec...
Python
1
#[allow(unused_mut)] let mut scope_203 = writer.prefix("Ipv6CidrBlock"); if let Some(var_204) = &input.ipv6_cidr_block { scope_203.string(var_204); } #[allow(unused_mut)] let mut scope_205 = writer.prefix("SubnetId"); if let Some(var_206) = &input.subnet_id { scope_205.string(var...
Rust
0
et options = SplineOpts::new() /// .tension(0.5) /// .num_of_segments(16); /// /// let calculated_points = prepared_points /// .calc_spline(&options) /// .expect("cant construct spline points"); /// /// assert_eq!(calculated_points.get_ref().len(), 33); /// ``` pub fn calc_spline(points: &Points, opts: &SplineO...
Rust
0
result } pub fn decrypt(text: &str, n: u32) -> String { let mut result = String::new(); for c in text.chars() { let is_upper = c.is_uppercase(); let deciphered = (util::alphabetize_char(c as u32, is_upper) - n) % 26; result += std::str::from_utf8(&[util::asciify_char(decipher...
Rust
0
oor.inherit_person("Idk"); PairOfWord::new("Effect", "Affect").log(); let pic = Camera::take_picture(); println!("{:?}", pic); // destructuring in rust // by redeclaring let Person { name: child_name, .. } = child; println!("child name is {}", child_name); // or by extracti...
Rust
0
$( $tail ),* ) { ( (ctx as &FnContext<$head>).extract(), $((ctx as &FnContext<$tail>).extract(),)* ) } } binder_impl!( $( $tail )* ); }; () => {} } macro_rules! tuple_args_impl { ...
Rust
0
", 1), Some((1, 4))); assert_eq!(re_bounds(&FLOAT_RE, "0_0.2", 0), Some((0, 5))); assert_eq!(re_bounds(&FLOAT_RE, "0__0.2", 0), Some((3, 6))); assert_eq!(re_bounds(&FLOAT_RE, "0.2 test", 0), Some((0, 3))); } #[test] fn test_raw_start_regex_search() { assert_eq!(re_bounds(&RA...
Rust
0
for j in (i + 1)..actual_k { let tri_tmp = Triangle3d { a: p, b: knn[i], c: knn[j], }; // Skip isosceles triangles as they could be ambiguous when matching if (...
Rust
0
; // get gamma challenge by appending 1 to the beta challenge and hash assembly { mstore(0x00, challenge) mstore8(0x20, 0x01) challenge := keccak256(0, 0x21) reduced_challenge := mod(challenge, p) } challenges.gamma = reduced_challenge; ...
Rust
0
-> pulumi.Output['outputs.RuntimeTemplateShieldedVmConfig']: """ Runtime Shielded VM spec. Structure is documented below. """ return pulumi.get(self, "shielded_vm_config") @_builtins.property @pulumi.getter(name="softwareConfig") def software_config(self) -> pulumi.O...
Python
1
AESV3" }); StdCF.set("AuthEvent", "DocOpen"); StdCF.set("Length", p.key_size as f64); CF.set("StdCF", StdCF); doc_encrypt.set("CF", CF); doc_encrypt.set("StmF", "StdCF"); doc_encrypt.set("StrF", "StdCF"); } doc_encrypt.set("R", p.R as f64); if p.V < 5 { ...
Rust
0
from lib.elasticsearch.query_utils import ( match_any_field, match_filters, highlight_fields, order_by_fields, combine_keyword_and_filter_query, ) def _data_doc_access_terms(user_id): return [ {"term": {"owner_uid": user_id}}, {"term": {"readable_user_ids": user_id}}, {...
Python
1
ys, key.to_string()); } } } return true; } // Table method!(pub table<TOMLParser<'a>, &'a str, Rc<TableType> >, mut self, alt!( complete!(call_m!(self.array_table)) | complete!(call_m!(self.std_table)) ) ); method!(table_subkeys<TOMLParser<'a>, &'a str, Vec<WSKeySep...
Rust
0
s()))[0] hdbg.dassert_in(prompt_tag, prompt_tags) python_cmd = f"{prompt_tag}()" ( system_prompt, pre_transforms, post_transforms, post_container_transforms, ) = eval(python_cmd) # Check return types. hdbg.dassert_isinstance(system_prompt, str) hdbg.dassert_is...
Python
1
ype(broker) in self.default_brokers: raise ValueError(f"Broker of type {type(broker)} is already set as default.") self.default_brokers[type(broker)] = broker def generate_op_path(self, op:str|Any): if isinstance(op, str): op_name = op elif isinstance(op, type): ...
Python
1
"""cat.py a version of unix cat, tweaked to show off runproc.py """ import sys data = sys.stdin.read(1) sys.stdout.write(data) sys.stdout.flush() while data: data = sys.stdin.read(1) sys.stdout.write(data) sys.stdout.flush() # Just here to have something to read from stderr. sys.stderr.write("Blah...") #...
Python
1
# fill small holes in the low-res masks up to `fill_hole_area` (before resizing them to the original video resolution) "++model.fill_hole_area=8", ] hydra_overrides.extend(hydra_overrides_extra) # Read config and init model cfg = compose(config_name=config_file, overrides=hydra_over...
Python
1
roString { #[inline] const unsafe fn new(s: String, real_str: &'static str) -> Self { Self { string: ManuallyDrop::new(s), real_str: ManuallyDrop::new(real_str), } } pub fn ident(i: &Ident) -> Self { Self::string(i.to_string()) } pub unsafe fn literal(s: String) -> Self { #[allow(unused_unsafe)] ...
Rust
0
.net/docs/vec4.js.html) pub fn floor(out: &mut Vec4, a: &Vec4) -> Vec4 { out[0] = f32::floor(a[0]); out[1] = f32::floor(a[1]); out[2] = f32::floor(a[2]); out[3] = f32::floor(a[3]); *out } /// Returns the minimum of two vec4's. /// /// [glMatrix Documentation](http://glmatrix.net/docs/vec4.js.html...
Rust
0
""" 💻 硬件性能实时监控系统 生产级硬件资源监控、优化和动态调节系统 支持20核CPU + RTX3060 + 128GB内存 + 1TB NVMe的极限性能释放 """ import asyncio import psutil import platform import threading import time import json import logging from datetime import datetime, timedelta from typing import Dict, Any, List, Optional, Tuple from dataclasses import dataclass, a...
Python
1
epin[i] .maxcnt .write(|w| w.bits(u32::from(self.bufs.in_lens[i]))); } } if out_enabled { unsafe { epout[i].ptr.write(|w| w.bits(self.bufs.out_bufs[i] as u32))...
Rust
0
# # python examples/example_matplotlib_figure.py # import typing as tp import numpy as np from matplotlib.axes import Axes from matplotlib.backend_bases import MouseEvent import edifice as ed from edifice.extra.matplotlib_figure import MatplotlibFigure @ed.component def Component(self): mouse_hover, mouse_hove...
Python
1
readProcessId(hwnd) if (pid == win_pid and win32gui.IsWindowVisible(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.GetClassName(hwnd).lower().startswith(app_name)): hwnds.append(hwnd) return True hwnds = [] win32gui.EnumWindows(find_chrome_windows, hwnds)...
Python
1
# How to generate a secret magic number # Multiply num by 64 # Bitwise XOR the number # Modulus the number by 16777216 # Divide num by 32 # Round down to nearest int (assume // does this, be careful if it doesn't) # Bitwise XOR and Modulus (16777216) the number # Multiply num by 2048 ...
Python
1
= tx.sort_key() nx = len(zx) liste_zy = [t.sort_key() for t in list_ty] for list_pos in product(range(nx), repeat=n): new_zx = tuple(zx) data = zip(list_pos, liste_zy) sorted_data = sorted(data, reverse=True) for pos_t in sorted_data: if labels: i...
Python
1
generar # respuestas más informadas y personalizadas. # -------------------------------------------------------------------------------- # ----------------------------- # Mostrar resultados # ----------------------------- # Se imprime la lista de resultados de forma legible para el usuario. pprint.pprint(results) # E...
Python
1
mance. Setting it /// manually using this function can expose a DoS attack vector. /// /// # Examples /// /// ``` /// use linked_hash_set::LinkedHashSet; /// use std::collections::hash_map::RandomState; /// /// let s = RandomState::new(); /// let mut set = LinkedHashSet::with_cap...
Rust
0
eships_unions' '# hatchet_canister_header -> machines_battleships_unions' global csrwxkrynln assert eea2ua02f94, aqn9v0e1_zj '# hatchet_canister_header -> machines_battleships_unions' None nonlocal ulg7jrvuw3z raise digbfz727uj @h595czw8c73 @ None @oqnbcxk8ru3 >= d9tpiwudi7z in 0 @(False for...
Python
1
import nose import requests import fixture @nose.with_setup(fixture.start_tangelo, fixture.stop_tangelo) def test_restful_service(): pos = ["one", "two", "three"] query = {"foo": "bar", "that": "telling"} url = fixture.url("restful", *pos, **query) expected = "%s: one two three {'foo': u'bar', 'that...
Python
1
m_yaml(str(path_yaml.resolve()), False) assert str(err_info.value) == err_msg_expected def test_validate(): test_config = DummyConfig() with ( patch.object(test_config, "are_all_required_fields_set", return_value=[]), patch.object(test_config, "are_all_fields_valid", return_value=[]), ...
Python
1
seek]; i += 1; handle.seek += 1; } Ok(i) } fn write(&self, id: usize, buffer: &[u8]) -> Result<usize> { let mut handles = self.handles.write(); let handle = handles.get_mut(&id).ok_or(Error::new(EBADF))?; let mut data = handle.data.write(); ...
Rust
0
# ЧТЕНИЕ ФАЙЛА def read_file_to_take_arguments(file): text = "" pattern = "" with open(file, "r") as file1: pattern = file1.readline()[:-1].lower() for line in file1: text += line.lower() return text, pattern # Определение номеров строк и слов def calculate_line_and_word_nu...
Python
1
fn size(&self) -> usize; fn offset(&self) -> usize; fn implicit_extend(&self) -> ImplicitRegisterExtend; } pub trait Register: Sized + Clone + Copy { type InfoType: RegisterInfo<RegType = Self>; fn name(&self) -> Cow<str>; fn info(&self) -> Self::InfoType; /// Unique identifier for this ...
Rust
0
ilder.body(req_body).map_err(list_by_environment::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(list_by_environment::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let ...
Rust
0
# -*- coding: utf-8 -*- """ Created on Thu Jul 24 16:26:38 2025 @author: Ville-Veikko Wettenhovi """ import numpy as np def padding(A: np.ndarray, sizeP, mode='symmetric'): """ Pads the input array symmetrically or with zeros. Parameters: A (np.ndarray): Input 2D or 3D array. sizeP (list...
Python
1
import os from unittest import skip from library.__main__ import library as lb from library.createdb.tube_add import tube_add from tests.utils import connect_db_args URL = "https://www.youtube.com/watch?v=W5ZLFBZkE34" STORAGE_PREFIX = "tests/data" dl_db = "tests/data/live.db" @skip("network") def test_live_skip():...
Python
1
hs, spembs = h.unsqueeze(0), spemb.unsqueeze(0) h = self._integrate_with_spk_embed(hs, spembs)[0] out, prob, att_w = self.dec.inference( h, trans_token, threshold=threshold, minlenratio=minlenratio, maxlenratio=maxlenratio, ...
Python
1
// or_insert inserts a new entry if no entry was found // if there's an entity, do nothing scores.entry("purple".to_string()).or_insert(100); scores.entry("purple".to_string()).or_insert(500); let score = scores.get("purple"); // println!("{:#?}", score); //? Hashmap example (word counter)...
Rust
0