text
string
label_name
string
labels
int64
new(head)] }$(.min($tail))*).into_expr() } }; } /// /// Fold left with `max` all given expression. /// /// This marco uses `partial_cmp` inside the expanded codes. /// Panics if and only if `partial_cmp` returns `None`. /// /// # Examples /// /// ``` /// # #[macro_use] extern crate cherries; /// # use cher...
Rust
0
sSdkAppid: 短信SdkAppid在 [短信控制台](https://console.cloud.tencent.com/smsv2) 添加应用后生成的实际SdkAppid,例如1400006666。 :type SmsSdkAppid: str :param _EndDateTime: 拉取截止时间,UNIX 时间戳(时间:秒)。 :type EndDateTime: int """ self._SendDateTime = None self._Offset = None self._Limit = None ...
Python
1
a_base() { bail!("Repo URI was not recognized"); } // Enforce https let _ = parsed.set_scheme("https"); match parsed.host_str() { Some("gitlab.com") => Ok(gitlab::fetch_project(&parsed, password).await?), Some("github.com") => Ok(github::fetch_project(&parsed, username, passwor...
Rust
0
AmlValue::DebugObject => match *self { AmlValue::DebugObject => Ok(self.clone()), _ => Err(AmlError::AmlValueError) }, AmlValue::Device(_) => Ok(AmlValue::Device(self.get_as_device()?)), AmlValue::Event(_) => Ok(AmlValue::Event(self.get_as_...
Rust
0
|&Vec3 { x, y, z }| Vec3::new(z, -y, x), |&Vec3 { x, y, z }| Vec3::new(y, z, x), |&Vec3 { x, y, z }| Vec3::new(-z, y, x), |&Vec3 { x, y, z }| Vec3::new(-y, -z, x), ]; type FingerprintSouce = HashMap<i32, Vec<Vec3>>; #[derive(Debug, Clone)] struct Scanner { position: Vec3, fingerprints: HashSet<i32...
Rust
0
image = path.join(utils.module_path(), "images/storage_default_16.png") else: image = path.join(utils.module_path(), "images/storage_shaped_16.png") list_r...
Python
1
return image def latents_kl_divergence(x0, x1): EPSILON = 1e-6 x0 = x0.view(x0.shape[0], x0.shape[1], -1) x1 = x1.view(x1.shape[0], x1.shape[1], -1) mu0 = x0.mean(dim=-1) mu1 = x1.mean(dim=-1) var0 = x0.var(dim=-1) var1 = x1.var(dim=-1) kl = ( torch.log((var1 + EPSILON) /...
Python
1
import os from pathlib import Path import hydra import pandas as pd import wandb from omegaconf import OmegaConf from transformers import set_seed from mtd.eval.generate_toxic_sentences import generate_toxic_continuation # You have to define the all model path you want to make generations for in the config file. @h...
Python
1
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8 # # MDAnalysis --- https://www.mdanalysis.org # Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors # (see the file AUTHORS for the full list of names) #...
Python
1
pub branch_color: String, pub commit_color: String, pub git_clean_color: String, pub git_wt_modified_color: String, pub git_index_modified_color: String, pub git_clean: String, pub git_wt_modified: String, pub git_index_modified: String, pub add_new_line: bool, pub git_arrow_up_c...
Rust
0
"hh3cTISessionEntry": hh3cTISessionEntry, "hh3cTISessionId": hh3cTISessionId, "hh3cTISessionConnectionCount": hh3cTISessionConnectionCount, "hh3cTISessionInitiatorName": hh3cTISessionInitiatorName, "hh3cSanClientResource": hh3cSanClientResource, "hh3cSanClientCreateIndex": hh3cSanCli...
Python
1
from joblib import numpy_pickle_utils from joblib.compressor import BinaryZlibFile from joblib.testing import parametrize @parametrize('filename', ['test', u'test']) # testing str and unicode names def test_binary_zlib_file(tmpdir, filename): """Testing creation of files depending on the type of the filenames.""...
Python
1
""" @Author : Ailitonia @Date : 2024/8/10 下午2:05 @FileName : danbooru @Project : nonebot2_miya @Description : booru 系列适配 @GitHub : https://github.com/Ailitonia @Software : PyCharm """ from typing import TYPE_CHECKING from src.service.artwork_proxy import ( BehoimiAr...
Python
1
] fn strcmp(_: *const i8, _: *const i8) -> i32; #[no_mangle] fn strlen(_: *const i8) -> u64; /* The internal, C/C++ interface: */ #[no_mangle] fn _tt_abort(format: *const i8, _: ...) -> !; #[no_mangle] fn ttstub_input_open( path: *const i8, format: tt_input_format_type, ...
Rust
0
# Simple Python script to download a file. Used as a fallback # when other more reliable methods fail. # from __future__ import print_function import sys try: from requests import get except ImportError: try: from urllib.request import urlretrieve USING = "urllib.request.urlretrieve" except...
Python
1
hould not use additional parameters not used by LanguageIDModel.run()") tracker.add_points(2) # Partial credit for passing sanity checks model.train(dataset) test_predicted_probs, test_predicted, test_correct = dataset._predict('test') test_accuracy = np.mean(test_predicted == test_correct) accur...
Python
1
the first number (if it exists) enum_parts = [p.strip() for p in enum_parts if p.strip()] if len(enum_parts) > 1: return enum_parts # If no clear sub-queries found, return original as single query if not sub_queries: sub_queries = [query] ...
Python
1
, // Spawn needs to happen before transform in order for the global // to be corrrectly rendered. // But it also must happen after transform to // start from the correct position. // Compromise: update renderer position manually. global_transform: ...
Rust
0
ix(key)] = results[key] elif key in self.SEG_KEYS: gt_pts_seg[self._remove_prefix(key)] = results[key] else: raise NotImplementedError(f'Please modified ' f'`Pack3DDetInputs` ' ...
Python
1
# Authors: # Endi S. Dewata <edewata@redhat.com> # # 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; version 2 of the License. # # This program is distributed in the hope that it will be usefu...
Python
1
um_datetime( record["ApproximateArrivalTimestamp"] ), "partition": record["PartitionKey"], "stream_name": stream_name, }, "_kinesis_msg_id": digest128(shard_id + sequence_number), ...
Python
1
create_resources, create_unused_resource_channels, ResourceControllers, UnusedResourceConsumers, }, Backend, DefaultBackend, Renderer, RendererShared, }, command::{producer::CommandProducer, ClockCommand, Command, MixerCommand, SoundCommand}, error::{AddClockError, AddSubTrackError, PlaySoundError}, }; ///...
Rust
0
lval_eval::lval_eval(lenv.unwrap(), &mut lval.lval_pop_with_index(1)) } else { lval_eval::lval_eval(lenv.unwrap(), &mut lval.lval_pop_with_index(2)) } } t => Lval::lval_err(Lerror::FirstArgumentDoesNotEvalTo { expect: LvalTypeMeta::LvalBoo...
Rust
0
anger_env_sh_target), not_if=format("test -f {setup_ranger_env_sh_target}"), sudo=True ) File(params.setup_ranger_env_sh_target, owner = params.kafka_user, group = params.user_group, mode = 0o755 ) if params.stack_supports_core_site_for_ranger_plugin and par...
Python
1
z, axis=1) feature_mapping = { str(code): category for category, code in mappings[dataset_name].items() } fig = viz.plot_categorical_feature_importance( diffs, cat_list[i], cat_names[i], feature_mapping ) fig_path = str(output_path / f"feat_importance_{dat...
Python
1
def jaccard_similarity(list1, list2, print_intersection=False): ''' Calculates Jaccard Index between two lists of words ''' intersection = len(list(set(list1).intersection(list2))) if print_intersection: print(list(set(list1).intersection(list2))) union = (len(list1) + len(list2)) - inte...
Python
1
); let chunk3_string_to_sign = create_chunk_string_to_sign(&date, region, &chunk2_signature, &[]); assert_eq!( chunk3_string_to_sign, concat!( "AWS4-HMAC-SHA256-PAYLOAD\n", "20130524T000000Z\n", "20130524/us-east-1/...
Rust
0
div![ C!["pt-5"], h1!["Navbars"], hr![], ExampleBox::new("Basic example") .content(div![ NavBar::new(plain!("Navbar"), "#") .fixed_top(false) .update_toggle(|toggle| toggle.add_on_click(|_| Msg::ToggleNavbar)) ...
Rust
0
protobuf::parse_from_bytes(&init_server_packet[4..]).unwrap(); protobuf_bind!(response, { challenge => { login_crypto_challenge.diffie_hellman => { gs: remote_key, } } }); let shared_keys = keys.add_remote_key(rem...
Rust
0
@pytest.mark.parametrize( "env, expected", ( ({}, True), ({"REQUESTS_CA_BUNDLE": "/some/path"}, "/some/path"), ({"REQUESTS_CA_BUNDLE": ""}, True), ({"CURL_CA_BUNDLE": "/some/path"}, "/some/path"), ({"CURL_CA_BUNDLE": ""}, True), ({"...
Python
1
r, file=sys.stderr) # noqa: T201 FirstSeenWithDistsPair = Tuple[Distribution, Distribution] def render_duplicated_dist_metadata_text( first_seen_to_already_seen_dists_dict: dict[Distribution, list[Distribution]], ) -> None: entries_to_pairs_dict: dict[str, list[FirstSeenWithDistsPair]] = {} for first_s...
Python
1
e MQTT worker so they are removed together. // However, topic handlers are shutdown as soon as the signal is received, causing this send to potentially // fail and spam the output. The return is then ignored as not being essential. let _ = tx.send((*event).clone()); }); } <reponame>tomcummin...
Rust
0
e, but that's somewhat unclear. Its also not clear what happens if an /// `RST` is executed, since that's a 1 byte jump. Does overwritting the `PC` avert the bug? /// Note that with any normal `CALL`, `JP`, or `JR`, the repeat byte would be used as the /// jump target or offset instead.) /// ...
Rust
0
_pid) = other.pid { return s_pid.cmp(&o_pid); } } // If both have pgid set, compare that if let Some(s_pgid) = self.pgid { if let Some(o_pgid) = other.pgid { return s_pgid.cmp(&o_pgid); } } // If either has pid...
Rust
0
_CONFIGURATION_PATH.as_path(), ) .unwrap(); } } use hyper::Method; use serde::Serialize; use crate::{ methods::builders::SendDiceBuilder, methods::Request, types::{ChatId, DiceEmoji, Message, ReplyMarkup}, }; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)] pub ...
Rust
0
LIGHTNING_ASSUME(blockDim.y == 16); LIGHTNING_ASSUME(threadIdx.y < 16); LIGHTNING_ASSUME(blockDim.z == 4); LIGHTNING_ASSUME(threadIdx.z < 4); dim3 virtual_block_index( block_offset_x + blockIdx.x, block_offset_y + blockIdx.y, block_offset_z + blockIdx.z ); ::lightnin...
Rust
0
turesType, TargetsType], List[Optional[CacheMetadataEntry]]]: """ Compute all features/targets from builders for scenario :param scenario: for which features should be computed :param builders: to use for feature computation :return: computed features/targets and the metadata ent...
Python
1
timeout('select timed out') continue except OpenSSL.SSL.Error as e: raise ssl.SSLError('bad handshake: %r' % e) break return WrappedSocket(cnx, sock) def _verify_callback(cnx, x509, err_no, err_depth, return_code): return err_no == 0 def ssl_wrap...
Python
1
self.parallelism -= 1; } if self.parallelism == 0 { self.tx.take(); } Some(ret) } None => None, } } } #[tokio::main(flavor = "current_thread")] async fn main() { // let result_folder = std::env::...
Rust
0
if hasattr(os, 'link') and os.path.exists(dest): # unlink and re-copy, since it might be hard-linked, and # we don't want to change the source version os.unlink(dest) self.copy_file('setup.cfg', dest) self.get_finalized_command('egg_info').save_version_info(des...
Python
1
Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1 * * Generated by: https://openapi-generator.tech */ /// ScaledJobJobTargetRefTemplateSpecProjectedSources : Projection that may be projected along with other supported volume types #[derive(Clone, Debug, P...
Rust
0
parray expected = np.array([0, 3, 2, 3]) tm.assert_numpy_array_equal(ndarray, expected) def test_sparray_inplace(): sparray = SparseArray([0, 2, 0, 0]) ndarray = np.array([0, 1, 2, 3]) sparray += ndarray expected = SparseArray([0, 3, 2, 3], fill_value=0) tm.assert_sp_array_equal(sparray, e...
Python
1
83602432e+10 mem_used{host="myhostname"} 3.4635874304e+10 mem_used_percent{host="myhostname"} 50.40183067321777 mem_free{host="myhostname"} 1.190197248e+10"##.lines(); let ip_address = IpAddr::V4(Ipv4Addr::new(1, 2, 3, 4)); let print_opts = options::Print { logs: false, headers:...
Rust
0
import allure from selenium.webdriver.common.by import By from pages.base_page import BasePage class HeaderPage(BasePage): @allure.step('Получение текущей валюты') def get_now_currency(self, timeout): return self.get_element((By.XPATH,'//strong'), timeout).text @allure.step('Переключение валюты...
Python
1
heads/master")); // `master` should NOT point at `b`, but instead to a direct reference assert_ne!(repo.read_ref(symbolic!("master"))?, symbolic_ref!("refs/heads/b")); assert!(repo.read_ref(symbolic!("master"))?.is_direct()); Ok(()) }) } #[test] fn test_simple_soft_reset() -> BitRes...
Rust
0
def somme_varargs(*args): return sum(args) print(somme_varargs(1, 2, 3)) print(somme_varargs(10, 20, 30, 40)) print(somme_varargs())
Python
1
import boto3 from botocore.exceptions import ClientError def create_s3_bucket(bucket_name, region='us-west-1'): s3_client = boto3.client('s3', region_name=region) try: # Check if the bucket already exists s3_client.head_bucket(Bucket=bucket_name) print(f"Bucket '{bucket_name}' alre...
Python
1
class Gift: def __init__(self): self.TIKTOK_GIFTS = [{'name': '小心心', 'coin': 1}, {'name': '玫瑰', 'coin': 1}, {'name': '玫瑰花', 'coin': 1}, {'name': '抖音', 'coin': 1}, {'name': '人气TOP1', 'coin': 1}, {'name': '小皇冠', 'coin': 10}, {'name': '人气票', 'coin': 1},...
Python
1
hits = filtered[:k] ctx_blocks = build_context_blocks(hits) context = truncate_tokens("\n\n".join(ctx_blocks)) llm = get_llm(temp) prompt = ( f"{SYSTEM_PROMPT}\n\n" f"Question: {q}\n\n" f"Context:\n{context}\n\n" f"Instructions: cite sources in-line using the IDs in brac...
Python
1
name_to_pos_entry in &field_name_to_pos { if field_name_to_pos_entry.1.len() > 1 { still_some_left = true; } } } let ticket_values: Vec<i32> = ticket_raw .lines() .map(|s| s.trim()) .filter(|s| !s.is_empty()) .filter(|s| &s[0..2] !...
Rust
0
import django_filters as filters from django import forms from django.db.models import ( Value, Q, ) from django.db.models.functions import Concat from account.models import User from quiz.models import ( QuizResult, Quiz, ) class QuizResultFilter(filters.FilterSet): """ Filter the Main quiz r...
Python
1
) } } pub mod operators; pub mod population; pub mod terminator;<reponame>TianyiShi2001/kodama use num_traits::Float; use crate::condensed::CondensedMatrix; use crate::dendrogram::Dendrogram; use crate::method; use crate::{LinkageState, Method}; /// Perform hierarchical clustering using the minimum spanning t...
Rust
0
/// fn do_the_thing( /// client: Arc<dyn MyService + Send + Sync + 'static>, /// ) -> impl Future<Item = Out> {...} /// # }; /// ``` pub mod mock { pub struct NestedContainers<'mock> { pub mapList: r#impl::nested_containers::mapList<'mock>, pub mapSet: r#impl::nested_containers::mapSet<'mock>, ...
Rust
0
labels_df = pd.read_csv(task_file, sep='\t') labels_set = set(labels_df[label_header].values.tolist()) labels_dict = {lab: i for i, lab in enumerate(list(labels_set))} train_labels_df = pd.read_csv(train_file, sep='\t') train_idx, train_y = [], [] for nod, lab in zip(train_label...
Python
1
phase: winit::event::TouchPhase, ) -> bool { true } /// A mouse button press has been received. #[allow(unused_variables)] fn on_window_mouse_input( &self, device_id: winit::event::DeviceId, state: winit::event::ElementState, button: winit::event::MouseBu...
Rust
0
ng(), Box::new(Node::CallFunction( "TheOdds".to_string(), vec![Node::Float(52.0)], )), vec![], ), Node::Print(Box::new(Node::Variable("survive".to_string()))), ]), ...
Rust
0
*const F); f(&Connection::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"changed\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C...
Rust
0
self.head += reader.pointer - head_start; // reset pointer reader.jump_async(&top).await?; // return item Ok(Some(item)) } pub async fn next_async<R: AsyncRead + AsyncSeek + Unpin + Send>(&mut self, reader: &mut PartialReader<R>) -> TychoResult<Option<T::ItemType>> { s...
Rust
0
[allow(unused_imports)] use std::borrow::Borrow; #[allow(unused_imports)] use super::*; #[derive(Debug, Default, Serialize, Deserialize, PartialEq)] pub struct r#User { #[serde(rename = "_embedded", skip_serializing_if = "Option::is_none")] r#embedded: Option<Value>, #[serde(rename = "_links", skip_serial...
Rust
0
llvm_asm!("cli" : : : : "intel", "volatile"); } } /// Enable interrupts #[inline(always)] pub fn enable() { unsafe { llvm_asm!("sti; nop" : : : : "intel", "volatile"); } } /// Enable interrupts #[inline(always)] pub fn enable_and_hlt() { x86_64::instructions::interrupts::enable_interrupts_and_...
Rust
0
fmt::Debug for GtkCellViewClass { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { f.debug_struct(&format!("GtkCellViewClass @ {:?}", self as *const _)) .field("parent_class", &self.parent_class) .field("_gtk_reserved1", &self._gtk_reserved1) .field("_gtk_reser...
Rust
0
assert connect_response.status_code == 404 assert verify_response.status_code == 404 class TestStripePermissions: """Test permission system for Stripe endpoints.""" @pytest.fixture def organization_with_different_owner(self, organization_staff_user: RevelUser) -> Organization: """O...
Python
1
# Fast api from fastapi import FastAPI, Depends, HTTPException from sqlalchemy.orm import Session import models, schemas from database import engine, SessionLocal # Create tables models.Base.metadata.create_all(bind=engine) app = FastAPI(title="Toy store API", version="2.0") # Dependency: get DB Session def get_db(...
Python
1
R1CSEvalsParameters, R1CSEvalsProof, R1CSSatProof, R1CSSatisfiedParameters, SNARKProof, SnarkParameters, SumCheckCommitmentParameters, SumCheckEvalProof, SumCheckProof, }, inner_product::bullet_inner_product_proof, polynomial::{ bound_poly_var_bot, combine_with_n, combine_with_r, ev...
Rust
0
tree!("D") ] ); let tree_2_root_node = tree!("X"); let tree_1 = Tree::new(&tree_1_root_node); let tree_2 = Tree::new(&tree_2_root_node); // distance between a tree and itself should always be zero assert_eq!(0, tree_1.tree_edit_distance(...
Rust
0
str(s: &str) -> Result<Self, Self::Err> { match s { "AL" => Ok(Country::Albania), "AD" => Ok(Country::Andorra), "AT" => Ok(Country::Austria), "AZ" => Ok(Country::Azerbaijan), "BH" => Ok(Country::Bahrain), "BY" => Ok(Country::Belarus), ...
Rust
0
let archive = args.value_of("archive").unwrap(); let format = ArchiveFormat::get_format(archive)?; match format { ArchiveFormat::Zip => { // TODO unimplemented!() } ArchiveFormat::Tar => { // TODO unimplemented!() } } } fn ...
Rust
0
#!/usr/bin/env python from vtkmodules.vtkFiltersModeling import ( vtkSpherePuzzle, vtkSpherePuzzleArrows, ) from vtkmodules.vtkRenderingCore import ( vtkActor, vtkPolyDataMapper, vtkRenderWindow, vtkRenderWindowInteractor, vtkRenderer, ) import vtkmodules.vtkInteractionStyle import vtkmodule...
Python
1
from django.template import Library, Node register = Library() class CountRenderNode(Node): count = 0 def render(self, context): self.count += 1 for v in context.flatten().values(): try: str(v) except AttributeError: pass return...
Python
1
or.execute(sql, adr) # myresult = mycursor.fetchall() # for x in myresult: # print(x) # sql = "SELECT * FROM customers ORDER BY name" #sort the result alphabetically by name # mycursor.execute(sql) # myresult = mycursor.fetchall() # for x in myresult: # print(x) # sql = "SELECT * FROM customers ORDER BY name ...
Python
1
/ spec.whistleblower_reward_quotient; let proposer_reward = whistleblower_reward / spec.proposer_reward_quotient; safe_add_assign!(state.balances[proposer_index], proposer_reward); safe_add_assign!( state.balances[whistleblower_index], whistleblower_reward.saturating_sub(proposer_reward) ...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2014 <+YOU OR YOUR COMPANY+>. # # This 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, or (at your option) # any later version. #...
Python
1
leap year second approximation, Gregorian - y/100 // leap year third approximation, Gregorian + y/400; } // revert back to january 1 basis (we were at march 1st, we need to move ahead) Ok(day - 306) } /// Converts a day number which counts t...
Rust
0
.build()? .send_local(InsertWorker::boxed( keyspace.clone(), sync_key, synced_record, retries_per_query, )); Ok(()) } async fn finish_log_file(log_file: &mut LogFile, dir_path: &PathBuf) -> anyhow::Result...
Rust
0
from typing import TYPE_CHECKING, TypeVar, cast from airda.framework import log from airda.framework.agent import AgentModuleKeys from airda.framework.module.keys import Keys from airda.framework.obj.object import Object if TYPE_CHECKING: from airda.framework.agent.module.assistant_manager.assistant.assistant imp...
Python
1
pki")] mod verify; // TODO: Fix `ring` crate to build for ARM embedded targets #[cfg(not(feature = "webpki"))] mod verify { pub(crate) fn verify_signature<'a, CipherSuite>( config: &crate::config::TlsConfig<'a, CipherSuite>, _message: &[u8], _certificate: crate::handshake::certificate::Cert...
Rust
0
from datetime import datetime, timedelta, date from .db.models import Frequency def create_schedule(tasks, day_of_week, preferences): today_date = date.today() schedule = [] for task in tasks: if task.frequency == Frequency.WEEKLY and task.day_of_week != day_of_week: continue if...
Python
1
# The MIT License (MIT) # Copyright (c) 2021-present foxwhite25 # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, ...
Python
1
#[doc = "*Required features: 'Win32_Networking_WinInet'*"] pub const INTERNET_OPTION_ALTER_IDENTITY: u32 = 80u32; #[doc = "*Required features: 'Win32_Networking_WinInet'*"] pub const INTERNET_OPTION_APP_CACHE: u32 = 130u32; #[doc = "*Required features: 'Win32_Networking_WinInet'*"] pub const INTERNET_OPTION_ASYNC: u32...
Rust
0
ed to the length specified in the header. //! //! # Transfer-Encoding: chunked //! //! Dechunking is a response body is done automatically if the response headers contains //! a `Transfer-Encoding` header. //! //! Sending a chunked request body is done by setting the header prior to sending a body. //! //! ``` //! let ...
Rust
0
CString::new(name); let infolist_time = weechat.get().infolist_time.unwrap(); let time = unsafe { infolist_time(self.ptr, name.as_ptr()) }; let unix = SystemTime::UNIX_EPOCH; let duration = Duration::from_secs(time as u64); unix.checked_add(duration) } /// Get a vari...
Rust
0
tage(5i16)), ("v-11", Voltage(-11i16)), ("%23", Percentage(23i8)), ("%-55", Percentage(-55i8)), ]; let must_err = [ ("%22.15", InvalidValue), (" v2", InvalidValue), ("", MissingValue), ]; for (s, e) in must_ok { assert_eq!(AdjRequest::parse(s.as_...
Rust
0
.shape, trues.shape) # 计算并打印指标 mae, mse, rmse, mape, mspe = metric(preds, trues) print(f"mse:{mse:.6f}, mae:{mae:.6f}, mape:{mape:.6f}, mspe:{mspe:.6f}") # 保存结果 if self.args.save: folder = os.path.join('./results', setting) os.makedirs(folder, exist_ok=T...
Python
1
words = [ "MAISON", "POMMES", "SOLEIL", "PLUIES", "CHANTE", "MANGER", "DORMIR", "PARLER", "ECRIRE", "COURIR", "DONNER", "VENDRE", "PORTER", "PENSER", "CROIRE", "SAVOIR", "DEVOIR", "VALOIR", "SORTIR", "PARTIR", "MONTER", "ENTRER", ...
Python
1
rse().unwrap(); assert!(i < 10); } for r in flatfs.values() { let value = r.unwrap(); assert_eq!(value.len(), 128); } } } use chrono::prelude::*; use std::io::Write; use thin_edge_json::{json::ThinEdgeJsonError, measurement::GroupedMeasurementVisitor}; p...
Rust
0
import board from kmk.kmk_keyboard import KMKKeyboard as _KMKKeyboard from kmk.quickpin.pro_micro.avr_promicro import translate as avr from kmk.quickpin.pro_micro.boardsource_blok import pinout as pins from kmk.scanners import DiodeOrientation from kmk.scanners.keypad import MatrixScanner # from kmk.scanners.encoder ...
Python
1
h = needle_image.shape[:2] haystack_image = _load_cv2(haystack_image, grayscale) if region: haystack_image = haystack_image[ region[1]:region[1] + region[3], region[0]:region[0] + region[2] ] else: region = (0, 0) #...
Python
1
# Natural Language Toolkit: Stemmer Interface # # Copyright (C) 2001-2024 NLTK Project # Author: Trevor Cohn <tacohn@cs.mu.oz.au> # Edward Loper <edloper@gmail.com> # Steven Bird <stevenbird1@gmail.com> # URL: <https://www.nltk.org/> # For license information, see LICENSE.TXT from abc import ABCMeta, a...
Python
1
self_vec.drain(self.start..self.end); } } } } impl core::fmt::Debug for DrainUtf32<'_> { #[inline] fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { core::fmt::Debug::fmt(&self.iter, f) } } impl core::fmt::Display for DrainUtf32<'_> { #[...
Rust
0
_prefixlenToNetmask(prefixlen, version): """Return a mask of n bits as a long integer. From 'IP address conversion functions with the builtin socket module' by Alex Martelli http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66517 """ if prefixlen == 0: return 0 elif prefixlen...
Python
1
import pytest class TestCorsPreflight: def test_cors_preflight(self, app): # Simulate a CORS preflight request made by the browser from a client # hosted on a domain other than the one the service is running on. # # Note that no `Authorization` header is set. origin = "http...
Python
1
from flask import Flask, render_template import subprocess import threading import os app = Flask(__name__) # Define your commands with descriptive names COMMANDS = { 'Reload Page': 'python press_ctrl_r.py', 'Page Down': 'python press_pgdn.py', } # Global variable to track auto-shift status auto_shift_active...
Python
1
provide a 'Thought:' sequence, and a 'Code:\n```py' sequence ending with '```<end_action>' sequence, else you will fail. 2. Use only variables that you have defined! 3. Always use the right arguments for the tools. DO NOT pass the arguments as a dict as in 'answer = ask_search_agent({'query': "What is the place where ...
Python
1
"""Hupu Live: Proudly presented by Hupu JRs. Usage: hupu -l | --list hupu -s | --shedule hupu -w | --watch <gameNumber> hupu -d | --data <gameNumber> hupu -n | --news <gameNumber> hupu -h | --help hupu -v | --version Tips: Please hit Ctrl-C on the keyborad when you want to inter...
Python
1
::VmarFlags, ) -> Result<usize, zx::Status>; } impl Mapper for zx::Vmar { fn map( &self, vmar_offset: usize, vmo: &zx::Vmo, vmo_offset: u64, length: usize, flags: zx::VmarFlags, ) -> Result<usize, zx::Status> { Self::map(self, vmar_offset, vmo, vmo_of...
Rust
0
[0], dec_channels[0]), PointBatchNorm(dec_channels[0]), nn.ReLU(inplace=True), nn.Linear(dec_channels[0], num_classes), ) if num_classes > 0 else nn.Identity() ) def forward(self, data_dict): coord = data_dict["coor...
Python
1
acientes = lab.medico_con_mas_pacientes() if medico_mas_pacientes: print("Médico con más pacientes:", medico_mas_pacientes.nombres, medico_mas_pacientes.apellidos) else: print("No se encontró ningún médico con pacientes registrados.") # Consultar ingresos por tipo de paciente ingresos_por_tipo_paciente = lab.c...
Python
1
ined(env: NapiEnv) -> Result<NapiValue> { unsafe { let mut napi_val: NapiValue = mem::uninitialized(); let status = napi_get_undefined(env, &mut napi_val); napi_either(env, status, napi_val) } } pub fn get_null(env: NapiEnv) -> Result<NapiValue> { unsafe { let mut napi_val: ...
Rust
0
Mnemonic::Sed, AddressingMode::Implied) => Ok(InstructionVariant::SedImplied), (Mnemonic::Sei, AddressingMode::Implied) => Ok(InstructionVariant::SeiImplied), (Mnemonic::Tax, AddressingMode::Implied) => Ok(InstructionVariant::TaxImplied), (Mnemonic::Tay, AddressingMode::Implied) => O...
Rust
0
from rest_framework import serializers class TaskSerializer(serializers.Serializer): id = serializers.UUIDField(source="uuid", read_only=True) uuid = serializers.UUIDField(read_only=True) short_id = serializers.IntegerField(source="id", read_only=True) status = serializers.CharField(required=False) ...
Python
1