text
string
label_name
string
labels
int64
import shutil import zipfile from pathlib import Path import numpy as np from data.utils import read_mask_to_numpy def convert_mask(mask_folder): mask_files = sorted(list(Path(mask_folder).iterdir())) for file in mask_files: mask = read_mask_to_numpy(file) file.unlink() save_path = f...
Python
1
"""Amorphous silica surface.""" import mbuild as mb class AmorphousSilicaSurface(mb.Compound): """Amorphous silica surface.""" def __init__(self, surface_roughness=1.0): super(AmorphousSilicaSurface, self).__init__() if surface_roughness == 1.0: mb.load( "amorpho...
Python
1
@property def extra_keys(self): extra = [] for k in self.state_keys: if k.startswith('encoder_l') or k.startswith('decoder_l') or k in [ CONFIG_KEY, 'Wemb', 'Wpos', 'decoder_ff_logit_out_b']: continue else: extra.append(k) return extra
Python
1
let arg_target: &str = command.value_of("url").unwrap(); let opt_no_css: bool = command.is_present("no-css"); let opt_no_frames: bool = command.is_present("no-frames"); let opt_no_images: bool = command.is_present("no-images"); let opt_no_js: bool = command.is_present("no-js"); let opt_insecure:...
Rust
0
if header.number != 0 && header.extra_data.len() as u64 > config.maximum_extra_data_size { return Err(Error::ExtraDataOutOfBounds); } // we can't detect if block is from future in runtime // => let's only do an overflow check if header.timestamp > i32::max_value() as u64 { return Err(Error::TimestampOverflow)...
Rust
0
16>>(&self, index: I) -> ::bobbin_bits::U1 { let index: usize = index.into().value() as usize; let shift: usize = 0 + index; unsafe { ::core::mem::transmute(((self.0 >> shift) & 0x1) as u8) } // [0] } #[doc="Returns true if HRS != 0"] #[inline] pub fn test_hrs<I: Into<::bobbin_bits:...
Rust
0
let len = serde_for_commands!(@len $($field),*); let mut s = serializer.serialize_struct(stringify!($ty), std::cmp::max(len, 1))?; s.serialize_field("raw", raw)?; $( s.serialize_field(stringify!($field), &self.$field)?; )* s.end(...
Rust
0
Biased Sampling to determine whether data is distinct. /// Past work for data deduplication include Stable Bloom Filters, but it suffers from a high /// false negative rate and slow convergence rate. /// /// # Examples /// /// ``` /// use probabilistic_collections::bloom::BSBloomFilter; /// /// let mut filter = BSBloo...
Rust
0
# Copyright (c) Facebook, Inc. and its affiliates. # # 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 ...
Python
1
casl2::Register::Gr3)); self.code(value_labels.ld_len(casl2::Register::Gr4)); self.code(format!(r#" CALL {copy}"#, copy = partialcopy)); self.code(recovers); self.set_register_idle(length_reg); self.set_register_idle(offset_reg); self.return_temp...
Rust
0
# test_solar_nadiation.py # # Created: Emilio Botero, Sep 2014 #---------------------------------------------------------------------- # Imports # ---------------------------------------------------------------------- import SUAVE from SUAVE.Core import Units from SUAVE.Core import ( Data, Container, ) import n...
Python
1
let mut ex = Command::new(command); ex.arg(path).status().map_err(MyError::IoError) } None => { let mut ex = Command::new(&self.default); ex.arg(path).status().map_err(MyError::IoError) ...
Rust
0
def _scale_acceleration(self, value): # The measurements are 12 bits left justified to preserve the sign bit # so we'll shift them back to get the real value right_justified = value >> 4 lsb_value = self._range_class.lsb[self._cached_accel_range] return right_justified * lsb_...
Python
1
__jni_args = []; // let __jni_env = __jni_bindgen::Env::from_ptr(self.0.env); // let (__jni_class, __jni_method) = __jni_env.require_class_method("android/app/backup/BackupDataOutput\0", "finalize\0", "()V\0"); // __jni_env.call_void_method_a(self.0.object, __jni_method,...
Rust
0
rror(msg) => { write!(f, "malformed stream: {}", msg) }, Error::SeekError(ref kind) => { write!(f, "seek error: {}", kind.as_str()) } Error::Unsupported(feature) => { write!(f, "unsupported feature: {}", feature) ...
Rust
0
(PluginType::Waveshaper, PluginType::Distortion), (PluginType::Amplifier, PluginType::Dynamics), (PluginType::Compressor, PluginType::Dynamics), (PluginType::Envelope, PluginType::Dynamics), (PluginType::Expander, PluginType::Dynamics), (PluginType...
Rust
0
); test_cs!(hline_to_with_two_coords, &[ CFFInt(10), CFFInt(20), UInt8(operator::MOVE_TO), CFFInt(30), CFFInt(40), UInt8(operator::HORIZONTAL_LINE_TO), UInt8(operator::ENDCHAR), ], "M 10 20 L 40 20 L 40 60 Z ", rect(10, 20, 40, 60) ); test_cs!(hline_to_with_three_coords, &[ CFFInt(10), CFFInt(20),...
Rust
0
} 1 } /// Converts an `NSTDUInt32` to an `NSTDUnichar`. /// /// # Note /// /// This function does not check the validity of `num`. /// /// # Parameters /// /// - `const NSTDUInt32 num` - The u32. /// /// # Returns /// /// `NSTDUnichar chr` - `num` interpreted as a numerical character, � on error. #[inline] #[...
Rust
0
overflow"); } /* * We always write three octal digits. Optimization only gives few Kb * smaller size for most documents when zlib compressed. */ if (ch as i32) < 32i32 || ch as i32 > 126i32 { let fresh4 = result; /* Shouldn't use format_buffer[]. */ ...
Rust
0
# Import Modules from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QVBoxLayout, QHBoxLayout from random import choice # Main App object and settings app = QApplication([]) main_window = QWidget() main_window.setWindowTitle('Ruffy Random Word Maker') main_window.resize(...
Python
1
from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from .models import User from django.utils.translation import gettext_lazy as _ @admin.register(User) class UserAdmin(BaseUserAdmin): model = User list_display = ("email", "is_active", "is_staff", "trade_mode", "...
Python
1
from concurrent.futures import ThreadPoolExecutor class WorkerPool: def __init__(self, settings): self.settings = settings self._executors = { 'worker': ThreadPoolExecutor( max_workers=self.settings.MAX_WORKER_THREADS, thread_name_prefix='LonaWorker', ...
Python
1
rvar_min=rvarmin) msg_hdl1 = vp.estim.MsgHdlSimp(shape=zshape1,damp=damp,\ damp_var=damp_var,alpha_max=alpha_max,rep_axes=(0,),\ rvar_min=rvarmin) msg_hdl_list.append(msg_hdl0) msg_hdl_list.append(msg_hdl1) ...
Python
1
# Copyright 2023 The TensorFlow Authors. 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 required by applica...
Python
1
faces_array_byte_size = (mesh_info.faces.len() * std::mem::size_of::<GLuint>()) as isize; gl::BufferData(gl::ELEMENT_ARRAY_BUFFER, faces_array_byte_size, mesh_info.faces.as_ptr() as *const GLvoid, gl::STATIC_DRAW); let size_of_vec3_i32 = std::mem::size_of::<glm::Vec3>() as i32; gl:...
Rust
0
xmap = QPixmap(f":/fish_0.png").transformed( QTransform().scale(cos(pi / 4), cos(pi / 4)).shear(-sin(pi / 4), sin(pi / 4))) painter.drawPixmap(100, 260, pixmap) pixmap = QPixmap(f":/fish_0.png").transformed( QTransform().shear(-sin(pi / 3), sin(pi / 3)).scale(cos(pi / 3), cos(pi ...
Python
1
mod bt_bullet_dynamics_common; #[cfg(target_arch = "x86_64")] pub use bt_bullet_dynamics_common::*; <gh_stars>10-100 use dependencies::hex; use dependencies::secp256k1; use dependencies::bytes; use secp256k1::{Secp256k1, SecretKey, PublicKey}; use std::error::Error; use std::collections::HashMap; use super::handshake...
Rust
0
ckage_group") @patch("airflow.providers.amazon.aws.hooks.sagemaker.SageMakerHook.conn", new_callable=mock.PropertyMock) def test_group_deleted_if_error_when_adding_model(self, conn_mock, create_group_mock, group_created): group = "group-name" op = SageMakerRegisterModelVersionOperator( ...
Python
1
; } else { eprintln!("bad implicit batch id {}", &batch_id); } } //////////////////////////////////////////////////////////////////////////////////////////////////// } //////////////////////////////////////////////////////////////////////////////////////////////////// pub type AbsolutePathPattern = S...
Rust
0
return Ok(()); } else if opt == PullOpts::Append { let mut file = File::open(&path).with_context(|| "Failed to open file")?; file.read_to_string(&mut contents) .with_context(|| "Failed to read file")?; } } if ...
Rust
0
[Fiat-Shamir heuristic]. /// /// For signature types that implement this trait, when the `derive-preview` /// Cargo feature is enabled a custom derive for [`Signer`] is available for any /// types that impl [`DigestSigner`], and likewise for deriving [`Verifier`] for /// types which impl [`DigestVerifier`]. /// /// [F...
Rust
0
from ..schemas import order_fields def build_prompt(text=None) -> str: if text is not None: text = f"""请从以下文本内容中提取结构化信息: 【文本内容】 {text} """ else: text = "" """构建结构化提取提示语""" fields_desc = "\n".join( [f"- {k}: {v}" for k, v in order_fields.items()]) return f""" {text} 【提...
Python
1
nt::solana_sdk::{pubkey::Pubkey, sysvar::rent}; use fixed::types::I80F48; use serde::{Deserialize, Serialize}; use std::{collections::HashMap, str::FromStr}; use zo_abi as zo; fn div_to_float<T: Into<i128>, U: Into<u32>>(n: T, p: U) -> f64 { let n: i128 = n.into(); let p = 10i128.pow(p.into()); let (q, r) ...
Rust
0
pub fn set_internal_node_num_keys(&mut self, num_keys: usize) { unsafe { *(self.index(INTERNAL_NODE_NUM_KEYS_OFFSET) as *mut usize) = num_keys; } } pub fn get_internal_node_num_keys(&self) -> usize { unsafe { *(self.index(INTERNAL_NODE_NUM_KEYS_OFFSET) as *cons...
Rust
0
Conforms to \"ACPI Low Power Idle Table (LPIT)\" July 2014."] #[doc = ""] pub type ACPI_TABLE_LPIT = acpi_table_lpit; #[repr(C, packed)] #[derive(Debug, Copy, Clone)] pub struct acpi_lpit_header { pub Type: UINT32, pub Length: UINT32, pub UniqueId: UINT16, pub Reserved: UINT16, pub Flags: UINT32, }...
Rust
0
5bsoh0cn, phaodqw8z_h: qqqq_ne4dbb): xwptciupbvd -= ygj1gajzcuj import nnnbu9sdb2t pgway5mpkpm: '' = b4nur41jjjr c26lycru1eq = u49urshbgkk = gf7_mk268u3 = grxe9lsk3w7 = svi71v73l04 = qa7_m416ren = j1uk2pugd0b = a3vlszju30_ = fxi79u8qw51 return 0 nonlocal a0wxeejpuf4 '# jackboxes_alkalinity_p...
Python
1
_f32_image_as_png(&data, level_size, format!( "tests/images/out/{} ({}) {}.{}x{}.png", layer_index, layer_name, channel.name, level_size.width(), level_size.height(), )) } } } /// Save raw float data to a PNG file, ...
Rust
0
n # optimizer = Adam(sam2_model.mask_decoder.parameters(), lr=1e-5, weight_decay=0) optimizer=torch.optim.AdamW(params=predictor.model.parameters(),lr=0.0001,weight_decay=1e-4) #1e-5, weight_decay = 4e-5 ########################### ここ変えてしまった ########################### #Try DiceFocalLoss, FocalLoss, Di...
Python
1
#========================================================================= # Prob06p05_comb_codes_penc_4to2_test #========================================================================= # SPDX-License-Identifier: MIT # Author : Christopher Batten, NVIDIA # Date : May 20, 2024 from pyhdl_eval.cfg import Config, In...
Python
1
to its binary representation. /// /// In `GF(2^x)`, coefficients in the extension polynomial may only take /// values of `0` or `1`. As a result, there is a natural mapping of values /// in `GF(2^x)` to bits. `0b1011` maps to `x^3 + x^1 + 1`, for example. /// The greatest degree that can be encoded...
Rust
0
from sqlalchemy import Column, Integer, String from sqlalchemy.orm import relationship from db.models.base import Base class TypeFournisseur(Base): __tablename__ = "types_fournisseur" __table_args__ = {"extend_existing": True} id = Column(Integer, primary_key=True) nom = Column(String(100), unique=Tru...
Python
1
(); let sgx_ret = unsafe { ocall_get_nonce( &mut retval as *mut _, self.id, acc_address.as_bytes().as_ptr(), nonce.as_mut_ptr() as *mut _, ) }; ensure!( sgx_ret == sgx_status_t::SGX_SUCCESS, ...
Rust
0
import saw_client as saw from saw_client.crucible import cry, cry_f from saw_client.llvm import Contract, CryptolTerm, void, i32, GhostVariable import unittest from pathlib import Path def pre_counter(contract: Contract, counter: GhostVariable): n = contract.fresh_var(i32, "n") contract.precondition_f("{n} < ...
Python
1
t one = E256( E128(0xe2aaa5a70e8d29d2b12f7788023e73f4), E128(0x00000000000923b301f281f891d2d8b6), ); let two = E256( E128(0x75bc106493590c971d17f2885f4f575d), E128(0x0000000000000d7d0080fc6291ec2141), ); c.bench_function("u256_wrapping_rem_u", |b| b.iter(|| black_box(one....
Rust
0
# 米游社的Salt # java提取,会跟随版本更新 mihoyobbs_salt = "idMMaGYmVgPzh3wxmWudUXKUPGidO7GM" mihoyobbs_salt_web = "G1ktdwFL4IyGkHuuWSmz0wUe9Db9scyK" # so提取 一般不会变 mihoyobbs_salt_x4 = "xV8v4Qu54lUKrEYFZkJhB8cuOh9Asafs" mihoyobbs_salt_x6 = "t0qEgfub6cvueAPgR5m9aQWWVciEer7v" # 部分接口要带 mihoyobbs_verify_key = "bll8iq97cem8" # 米游社的版本 mihoy...
Python
1
""" LLM settings, used for both the interface and summarizer bots. """ from typing import Any, Dict from litellm import get_model_info, get_supported_openai_params from pydantic import model_validator from pydantic_settings import BaseSettings class BotModelSettings(BaseSettings): """ LLM settings, used for ...
Python
1
information to allow for /// repeated queries, at the cost of *O(limit)* memory use. /// /// This uses *O(sqrt(limit))* memory, and is designed to be as /// cache-friendly as possible. `StreamingSieve` should be used for /// one-off calls, or simple linear iteration. /// /// The design is *heavily* inspired/adopted fr...
Rust
0
# Importing libs from colorama import init, Fore, Style import pyfiglet import subprocess as sp import os # Setupping 0 to plugin name, and theme name vars plname = 0 thname = 0 # Initing colorama with autoreset init(autoreset=True) def cls(): os.system("cls") # Printing menu def menu(): try: os.system...
Python
1
; run_main( &context, &cli::Args::ExecutableMock { executable_mock_path: executable_mock.path(), }, )?; assert_eq!(context.get_captured_stdout(), "foo"); Ok(()) } } pub fn run_scriptkeeper(context: &Context, script: &Path) -> R<Exi...
Rust
0
= crate::fmath::acos(source.direction().dot(&diff) / dist); let d = S::directivity(theta); let r = source.amp() * d * (-dist * self.attens[idx]).exp() / dist; let phi = source.phase() + self.wavenums[idx] * dist; Complex::from_polar(r, phi) } fn propagate_all(&self, target: Vec...
Rust
0
rde(rename = "bars", skip_serializing_if = "Option::is_none")] pub bars: Option<crate::models::HistoryResultBars>, } impl HistoryResult { pub fn new() -> HistoryResult { HistoryResult { bars: None, } } } //! The Gilbert–Johnson–Keerthi distance algorithm. use alga::general::...
Rust
0
new().build(Vec::new())?; let mut from = 0; loop { let to = ::std::cmp::min(from + LZ4_BUFFER_SIZE, input_buf.len()); encoder.write_all(&input_buf[from..to])?; from += LZ4_BUFFER_SIZE; if from >= input_buf.len() { break; } } let (v, result) = encoder.finish(); m...
Rust
0
import rospy from std_srvs.srv import Trigger, TriggerRequest, TriggerResponse from sensor_msgs.msg import Image from open_vocab_vision_ros.detection_node import decode_img_msg from open_vocab_vision_ros.srv import Query, QueryRequest, QueryResponse from open_vocab_vision_ros.vlm.vlm import VLMWrapper class VLMInf...
Python
1
Signature.std_err())?; let id = RecoverableId::new(data.get_u8(pos + 1 + 64)) .or(ContractError::CannotDecodeSignature.std_err())?; let recoverable_signature = RecoverableSignature::new(&signature, id) .or(ContractError::CannotDecodeSignature.std_err())?; let verify_key ...
Rust
0
EMAC_TX_CLK, EMAC_RXD2, EMAC_TX_ER, EMAC_RX_CLK, EMAC_RX_ER, EMAC_RXD3, EMAC_RXD0, EMAC_RXD1, EMAC_RX_DV, MTDI, MTCK, MTMS, } /// Peripheral output signals for the GPIO mux #[allow(non_camel_case_types)] #[derive(PartialEq, Copy, Clone)] pub enum OutputSignal { SPICLK...
Rust
0
# Copyright 2014-2017 The ODL contributors # # This file is part of ODL. # # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at https://mozilla.org/MPL/2.0/. from __future__ import division import pytes...
Python
1
""" [Amun - low interaction honeypot] Copyright (C) [2014] [Jan Goebel] 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 2 of the License, or (at your option) any later version. This ...
Python
1
# Generated by Django 3.2 on 2021-06-10 15:10 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('employee', '0018_auto_20210610_2108'), ] operations = [ migrations.RemoveField( ...
Python
1
import os from typing import Callable, Dict from mage_ai.shared.hash import get_json_value, merge_dict def get_template_vars(include_python_libraries: Dict = None) -> Dict[str, Callable]: from mage_ai.data_preparation.shared.secrets import get_secret_value no_db_kwargs = get_template_vars_no_db(include_pytho...
Python
1
import streamlit as st # importing streamlit libarary for creating web app import random # importing random libarary for generating random characters import string # importing string libarary for string operations # Function to generate a password based on user preferences def generate_password (length, use_digits,...
Python
1
"""Beartype configuration to prevent NumPy contamination. This module configures beartype (used by coredis) to disable automatic NumPy integration which causes system-wide dependency contamination during import. Must be imported before any coredis/beartype usage to be effective. """ import logging import os logger ...
Python
1
model: Modello PyTorch. val_loader: DataLoader per il validation set. device: Dispositivo per l'addestramento (default: "cpu"). Returns: val_accuracy: Accuratezza sul validation set. """ model.eval() # Modalità di valutazione val_correct = 0 val_total = 0 with torch.no...
Python
1
False otherwise. """ return self.account.edit_account_info(short_name, author_name, author_url) def _md_to_dom(self, content: str) -> List[Dict[str, Any]]: """Converts Markdown content to Telegraph DOM format. This is an internal helper method and should not be called ...
Python
1
>> for f64 { type Error = TryFromDecimalError; fn try_from(n: Decimal<N>) -> Result<f64, Self::Error> { let mut cx = Context::<Decimal<N>>::default(); cx.try_into_f64(n) } } impl<const N: usize> From<f32> for Decimal<N> { fn from(n: f32) -> Decimal<N> { let mut cx = Context::<De...
Rust
0
from io import StringIO import os import pytest import astropy.units as u import numpy as np from pint.models import get_model from pint import toa import pint.residuals from pinttestdata import datadir par_nowave = """ PSRJ J0835-4510 RAJ 08:35:20.61149 DECJ -45:10:34.8751...
Python
1
pub fn bit(&self) -> bool { match *self { EPDR::DISABLE_PULL_DOWN => false, EPDR::ENABLE_PULL_DOWN => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> EPDR { match value { false => EPDR::DISABLE_PULL_DO...
Rust
0
import pytest import boa code = """ @external def identity(a: uint256) -> uint256: return a @external def sometimes_raises(a: uint256) -> uint256: assert a % 2 == 0 return a @external def overloaded(a: uint256, b: bool = True) -> uint256: assert b return a """ @pytest.fixture(scope="module") d...
Python
1
# cam9.py # # Description: # Here's a concise summary of the code: # Camera Setup: Configures the Raspberry Pi camera with 720x480 resolution and 180-degree rotation, allowing 2 seconds for stabilization. # GPIO Configuration: Sets up GPIO pins for the PIR sensor and LED, initially turning off the LED. # Motion Detecti...
Python
1
tags_metadata = [ { "name": "GPT", "description": "GPT related Operations", } ]
Python
1
ourt(output_video_frames) output_video_frames = mini_court.draw_points_on_mini_court(output_video_frames, player_mini_court_detections) output_video_frames = mini_court.draw_points_on_mini_court(output_video_frames, ball_mini_court_detections, color...
Python
1
) ) conditions.append( ( ((( (dataframe['rsi'] > self.rsi_high.value) | # upper = basis + dev # lower = basis - dev # disp_down = basis - ((upper - lower) * for_sigma) // Минимально-допустим...
Python
1
_index])], }.assimilate_storage(&mut t).unwrap(); let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(50)); ext }#[derive(Clone, Copy, Debug)] pub struct Rectangle([f64; 4]); impl Rectangle { #[inline] pub fn new(pos: [f64; 2], size: [f64; 2]) -> Recta...
Rust
0
#open file nov = open('371.txt','r+') #Messege construct for analitics messege = list(range(0,370)) idd =100 # Количество обрабатываемых строк for i in range(0, idd): messege[i] = nov.readline() #print(messege[i]) nov.close #ФАйл Qcode nov = open('Qtwo.txt','r+') #Messege construct for analitics Qtwo = list(r...
Python
1
self.index_after_last += 1; } pub fn pop(&mut self) -> T { self.index_after_last -= 1; unsafe { *self.items.get_unchecked(self.index_after_last) } } } /// A simple function for testing performance of BDD traversal. pub fn dfs_node_count(bdd: &Bdd) -> u...
Rust
0
mock_ssh_client2 = mock.MagicMock(spec=paramiko.SSHClient) conn_tuple1 = (mock_ssh_client1, mock_sftp_client1) conn_tuple2 = (mock_ssh_client2, mock_sftp_client2) sftp_manager.connections[host1] = conn_tuple1 sftp_manager.connections[host2] = conn_tuple2 # Mock _resolve_path_for_operation to r...
Python
1
from entities.entity import Entity import pygame class Player(Entity): def __init__(self, screen_width, screen_height): super().__init__("ASETS/AVATARS/CROQUI/5C.png", 150, 150, x=screen_width // 2, y=screen_height - 170) self.speed = 8 self.screen_width = screen_wi...
Python
1
olemized end points in the `from_region` // and make sure they are included in the `to_region`. // for region_decl in self.infcx.tcx.tables.borrow().free_region_map() { // // FIXME(nashenas88) figure out skolemized_end points // let block = self.en...
Rust
0
imd_ge(a, transmute(b)) } /// Compare signed greater than or equal to zero #[inline] #[target_feature(enable = "neon")] #[cfg_attr(test, assert_instr(cmge))] #[stable(feature = "neon_intrinsics", since = "1.59.0")] pub unsafe fn vcgez_s32(a: int32x2_t) -> uint32x2_t { let b: i32x2 = i32x2::new(0, 0); simd_ge(a...
Rust
0
out.push_str(&info); } } } (result_stdout, result_stderr) } fn report_all(for_hard: bool) -> (String, String) { let mut result_stderr = String::new(); let mut result_stdout = String::new(); let (_out, _err) = get_limit("open_files", false, for_hard); if !_out.is_empty() { ...
Rust
0
def ElevenPointInterpolatedAP(rec: Any, prec: Any) ->list[Any]: """Calculate 11-point interpolated average precision. Args: rec (np.ndarray[np.float64]): recall array prec (np.ndarray[np.float64]): precision array Returns: Interp_ap_info (list[Any]): List containing information nec...
Python
1
_POLICY_ARG = None NAME_ARG = None _support_rpc_status = False @classmethod def Args(cls, parser): UpdateHelper.Args( parser, support_rpc_status=cls._support_rpc_status, ) def Run(self, args): return UpdateHelper.Run( self.ReleaseTrack(), args, self._supp...
Python
1
#!/usr/bin/python3 import psycopg2, sys, json, datetime def Update_Config(): try: print(str(datetime.datetime.now()) + " Updating config.json file.") File = open("config.json", "r") JSON_Data = json.load(File) JSON_Data["core"]["organisation"] = {"name": "", "website": "", "domain"...
Python
1
Adam(net.parameters()) criterion = torch.nn.MSELoss() def inference(): for i, batch in zip(range(args.num_iterations_per_trial), train_dl): inp, tgt = batch # Move to gpu and add channel dimension inp, tgt = inp.cuda()[:, None, ...], tgt.cuda()[:, None, ...] ...
Python
1
ROOT = BASE_DIR / 'staticfiles' # Media files MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' # AWS S3 Configuration AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') AWS_S3_REGION_NAME = o...
Python
1
import torch import torchaudio import random import itertools import numpy as np from tools.mix import mix import librosa def normalize_wav(waveform): waveform = waveform - torch.mean(waveform) waveform = waveform / (torch.max(torch.abs(waveform)) + 1e-8) return waveform def pad_wav(waveform, segment_le...
Python
1
# coding=utf-8 # Copyright 2023 The HuggingFace Inc. 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...
Python
1
import random # Define race settings is_race_on = False colors = ["red", "orange", "yellow", "green", "blue", "purple"] y_positions = [-70, -40, -10, 20, 50, 80] all_turtles = {color: 0 for color in colors} # Track each turtle's position # Get user's bet user_bet = input("Which turtle will win the race? Enter a colo...
Python
1
IGN_RIGHT) position = Point(SCREEN_WIDTH - HUD_MARGIN, HUD_MARGIN) label = Label(text, position) cast.add_actor(LIVES_GROUP, label) def _add_score(self, cast): cast.clear_actors(SCORE_GROUP) text = Text(SCORE_FORMAT, FONT_FILE, FONT_SMALL, ALIGN_CENTER) position = Po...
Python
1
# -*- coding: utf-8 -*- from odoo import models, registry from odoo.api import Environment from odoo.fields import Datetime from odoo.http import request from odoo.addons.bus.websocket import wsrequest class IrWebsocket(models.AbstractModel): _inherit = 'ir.websocket' def _update_bus_presence(self, inactivit...
Python
1
INED, key=Component.UNDEFINED, height=Component.UNDEFINED, width=Component.UNDEFINED, accessKey=Component.UNDEFINED, className=Component.UNDEFINED, contentEditable=Component.UNDEFINED, contextMenu=Component.UNDEFINED, dir=Component.UNDEFINED, dragg...
Python
1
rmat::WireTypeVarint); }; for value in &self.trainer_slots { my_size += ::protobuf::rt::value_size(3, *value, ::protobuf::wire_format::WireTypeVarint); }; for value in &self.search_roll_bonus { my_size += ::protobuf::rt::value_size(4, *value, ::protobuf::wire_form...
Rust
0
from django.core.management.base import BaseCommand from squad.core.models import Group from squad.core.notification import send_status_notification class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( '--dry-run', '-d', action='store_true', ...
Python
1
# Copyright 2022 The HuggingFace 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 # # Unless required by applicabl...
Python
1
# Generated by Django 5.1.6 on 2025-06-22 18:24 import django.db.models.deletion from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("account", "0004_auditlog"), migrations.swappable_dependency(settings.AUTH_USER_MODE...
Python
1
nect the device to a host machine's USB port and run this //! program. //! //! The expected output of this program (after listing USB devices) is: //! //! Received [10, 11, 12] //! Wrote [13, 14, 15] //! //! The program exits with status `0` if the above interactions occur //! correctly. extern crate libusb; ...
Rust
0
draw_areas(frame, self.areas) # 画区域 draw_detections(frame,warn_msg['detection_object']) # cv2.imshow("warn fig",frame) # cv2.waitKey(0) # cv2.destroyAllWindows() msg = ResultProcess.mechine_result_process(warn_msg,fr...
Python
1
''' Module of Windows API for plyer.email. ''' import os try: from urllib.parse import quote except ImportError: from urllib import quote from plyer.facades import Email class WindowsEmail(Email): ''' Implementation of Windows email API. ''' def _send(self, **kwargs): recipient = kwa...
Python
1
from __future__ import unicode_literals import commandLineParser import common import os import fileVersionManagement import gameScanner import installConfiguration import logger #do install given a installer config object def main(conf): # type: (installConfiguration.FullInstallConfiguration) -> None logger.getGl...
Python
1
data A dictionary containing the model input data. batch: A dictionary containing the input mini-batch data. We need to use the keys with the model prefix to index required data. keys: A dictionary containing the model arguments and corresponding batch key...
Python
1
"#, bg = channel.color.to_owned() )}> <i class={channel.icon} aria-hidden="true"></i> <span class={css!( r#" padding-left: 5px; "#, ...
Rust
0