text
string
label_name
string
labels
int64
def get_distance_from_start(gt_translation): distances = np.diff(gt_translation[:, 0:3], axis=0) distances = np.sqrt(np.sum(np.multiply(distances, distances), 1)) distances = np.cumsum(distances) distances = np.concatenate(([0], distances)) return distances
Python
1
f the Resistance won. @param spies List of only the spies in the game. """ for i,votes in enumerate(self.gameState.votes): votedTeam=self.gameState.selectedTeams[i] spiesInTeam=len([s for s in votedTeam if s in spies]) for j,vote i...
Python
1
import insightconnect_plugin_runtime from insightconnect_plugin_runtime.exceptions import PluginException from .schema import ExportRulesInput, ExportRulesOutput, Input, Output, Component # Custom imports below import requests import base64 class ExportRules(insightconnect_plugin_runtime.Action): def __init__(s...
Python
1
while self.notebook.GetPageCount()>0: self.notebook.DeletePage(0) event.Skip() if __name__=='__main__': from skimage.data import camera, astronaut from skimage.io import imread app = wx.App() cf = CanvasFrame(None, autofit=False) cf.set_imgs([astronaut(), 255-astr...
Python
1
nst Motion_Est_ID_ME_EPZS: Motion_Est_ID = 5; #[doc = "< reserved for experiments"] pub const Motion_Est_ID_ME_X1: Motion_Est_ID = 6; #[doc = "< hexagon based search"] pub const Motion_Est_ID_ME_HEX: Motion_Est_ID = 7; #[doc = "< uneven multi-hexagon search"] pub const Motion_Est_ID_ME_UMH: Motion_Est_ID = 8; #[doc = "...
Rust
0
} } } extern crate ndarray; use ndarray_ext::NdArray; use op; use op::Op; use ops; use std::cell::Cell; use std::fmt; use std::mem; use std::ops::{Deref, DerefMut}; use std::rc::Rc; /// Symbolic multi-dimensional array. pub struct Tensor(pub Rc<TensorCore>); pub struct TensorCore { /// Operation of this ...
Rust
0
from endersgame.riverstats.fewvar import FEWVar def finite_sample_fewvar(xs, fading_factor=0.1): # Initialize variables to calculate EWA and EWVar x_sum = 0 x_square_sum = 0 weight_sum = 0 weight = 1.0 # Calculate weighted mean and variance for x in reversed(xs): x_sum += weight ...
Python
1
kip_serializing_if = "Option::is_none")] pub broker_assignment: Option<BrokerAssignment>, #[serde(rename = "is_controlled", skip_serializing_if = "Option::is_none")] pub is_controlled: Option<bool>, #[serde(rename = "is_active", skip_serializing_if = "Option::is_none")] pub is_active: Option<bool>, ...
Rust
0
from django.conf import settings from elasticsearch_dsl import DocType, Date, String, Nested, Object, Index, \ MetaField, analyzer, FacetedSearch, Q, TermsFacet, DateHistogramFacet, SF # user is repeated in several places, reuse a field definition user_field = Object(properties={ 'display_name': String(fields...
Python
1
from dataclasses import dataclass from src import domain from src.application.base.commands import BaseCommand, CommandHandler from src.application.base.interface.request import RequestProtocol from src.application.base.security import BaseJWTManager from src.application.cqrs.helpers import authorization_required from...
Python
1
sts = [ ( "#####\n# #\n# # #\n# #\n#####", PartOfSpeech::ParticleCollate, ), ( "#####\n # #\n# #\n# # \n#####", PartOfSpeech::Noun { islands: 2, depth: 0, }, ), ( ...
Rust
0
configservice = self._find_storage_hardwareid_service( storage_system) if configservice is None: exception_msg = (_("Error finding Storage Hardware ID Service.")) LOG.error(exception_msg) raise exception.VolumeBackendAPIException(data=exception_msg) hardw...
Python
1
::<Box<SelectBox>>()); } use std::any::{Any, TypeId}; // see: https://blog.csdn.net/K_Ohaha/article/details/105421601 // see: https://bbs.csdn.net/topics/392031097?locationNum=6&fps=1 // see: https://rustcc.gitbooks.io/rustprimer/content/trait/trait-object.html fn print_any_draw(any: &Any) { // 向下转型 if let So...
Rust
0
For example: ```python @reactive.effect @reactive.event(input.show_tab) def _(): ui.update_nav_panel("tabset_id", target="Foo", method="show") ui.update_navset("tabset_id", selected="Foo") ``` See Also -------- ~shiny.ui.insert_nav_panel ~shiny.ui.remove_nav_panel ...
Python
1
r#" (for ~name in (rni ~..rest) ~..body) "# )) } fn break_(result: Option<Val>) -> Val { match result { Some(result) => backquote!("(finish-block LOOP ~result)"), None => backquote!("(finish-block LOOP)"), } } fn continue_() -> Val { backquote!("(restart-bl...
Rust
0
&mut [u8], direction: Direction, _todo: cpu::Features, ) -> Tag { let chacha20_key = match key { aead::KeyInner::ChaCha20Poly1305(key) => key, _ => unreachable!(), }; let mut counter = Counter::zero(nonce); let mut ctx = { let key = derive_poly1305_key(chacha20_key, coun...
Rust
0
// C.6.2. Second Request { let mut block = track_try_unwrap!(encoder.enter_header_block(Vec::new())); track_try_unwrap!(block.encode_field( LiteralHeaderField::with_indexed_name(StaticEntry::Status, b"307") .with_indexing() .with_huffman_encoded_value(), ...
Rust
0
, 'b, 'c, F: Write + Seek> { opt: &'a mut RawOptionWriter<'b, 'c, F>, } pub struct ShbOptionWriter<'a, F: Write + Seek> { block: RawBlockWriter<'a, F>, finished: bool, } pub struct IdbOptionWriter<'a, F: Write + Seek> { block: RawBlockWriter<'a, F>, finished: bool, } pub struct FilterOptionWriter...
Rust
0
import pytest import time from multiprocessing import Process from seleniumbase import BaseCase from app import app # Import your FAB app instance import json import os from dotenv import set_key, load_dotenv load_dotenv() user = os.getenv("USER") password = os.getenv("PASSWORD") def run_fab(): """Run the Flask ...
Python
1
: "x"(*rkey) : : "intel", "alignstack" ); } } macro_rules! aeskeygenassist { ($src:ident, $i:expr) => {{ let mut dst = mem::MaybeUninit::<u64x2>::uninit(); unsafe { llvm_asm!("aeskeygenassist $0, $1, $2" : "+x"(*dst.as_mut...
Rust
0
import re from collections.abc import Callable from dataclasses import dataclass from typing import Literal, Optional from posthog.schema import DatabaseSchemaManagedViewTableKind, RevenueAnalyticsEventItem from posthog.hogql import ast from posthog.models.team.team import Team from posthog.warehouse.models.external...
Python
1
it supports the /// target chains). pub chain_hash: Slice32, /// Channel id used by the channel; first temporary and later final. /// /// The temporary_channel_id is used to identify this channel on a per-peer /// basis until the funding transaction is established, at which point it /// is...
Rust
0
from abc import ABC, abstractmethod from typing import Tuple import torch from torch.distributions import Normal, Independent from torch.distributions import Distribution from torch import Tensor class SDE(ABC): """ Abstract class for some SDE info important for the score models """ def __init__(self,...
Python
1
rors /// /// `index` must be a valid position. pub fn get_char_pos(&self, index: usize) -> Result<usize> { if index == 0 { Ok(0) } else { match self.str_to_char_pos.get(index) { Some(index) if *index != 0 => Ok(*index), _ => Err(anyhow!...
Rust
0
} })?; let device_type = DeviceType::from_ffi(info.type_); let model = try_c_char_ptr_to_str(info.model) .map_err(|e| CueDeviceInfoFromFfiError::StringConversionError { field: "model".to_string(), error: e, })? .ok_or_else(|| ...
Rust
0
ne)] pub struct Fork<S, D> { shared: RefCell<ForkShared<S, D>>, } #[derive(Clone)] struct ForkShared<S, D> { signal: S, ring_buffer: ring_buffer::Bounded<D>, pending: bool, } impl<S, D> Fork<S, D> { const A: bool = true; const B: bool = false; /// Consumes the `Fork` and returns two branc...
Rust
0
_submission_{metric}_{now_date_time}.json", args) with open(path, "w", encoding="utf-8") as f: json.dump(output_dict, f, indent=4, ensure_ascii=False) # print(f"Submission file saved to {path}") eval_logger.info(f"Submission file saved to {path}") return mean_score def vcr_aggregate_exact_matc...
Python
1
&device_extra.unwrap(), &device_diags.unwrap(), ) .await .err() { println!("\terror: {}", e); } } println!(); } ...
Rust
0
import asyncio import os from aiogram import Bot, Dispatcher, types from aiogram.filters import BaseFilter from aiogram.fsm.strategy import FSMStrategy from dotenv import load_dotenv from models.user import RoleEnum from services.auth import get_user_role from controllers import admin, master, client, base from models....
Python
1
watch() sys.exit(0) # test train_collector and start filling replay buffer train_collector.reset() train_collector.collect(n_step=args.batch_size * args.training_num) # trainer result = OffpolicyTrainer( policy=policy, train_collector=train_collector, test_co...
Python
1
// `fill_bytes` is faster than many `gen::<u32>` calls self.fill_bytes(data[..].as_byte_slice_mut()); // Swap bytes per the `Rng::fill` source. This might be // unnecessary if reproducibility across architectures is not // desired. data.to_le(); if rem > 0 { ...
Rust
0
client_ch).poll(), Some(Event::ConnectionLost { reason: ConnectionError::ConnectionClosed(frame::ConnectionClose { error_code: TransportErrorCode::CONNECTION_REFUSED, .. }), }) ); assert_eq!(pair.server.connections.len(), 0); assert_eq!...
Rust
0
_pos.get_mut(); match e { OfferFocus => return Accept, MouseButton { state, .. } if focused && state.released() => return DropFocus, MouseButton { .. } if focused => *click = mouse_pos.sub(*p), MouseMove { at, .. } if focused => *p = at.sub(*click), _ => (), } Reject }, id, ...
Rust
0
amount: Uint256, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct BalanceOfResponse { pub amount: Uint256, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct IsWhitelistedResponse { pub whitelisted: bool, } #[derive(Serialize, Deserialize, C...
Rust
0
::std::result::Result::Ok(()) } // Compute sizes of nested messages #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; for value in &self.packages { let len = value.compute_size(); my_size += 1 + ::protobuf::rt::compute_raw_varint32_...
Rust
0
# debug_vision.py import cv2 from djitellopy import Tello # Importa os módulos que já criamos import config import vision_module as vision import display_module as display def main(): """ Script de depuração para testar a detecção de QR codes sem executar a lógica de voo. O drone permanecerá parado (no c...
Python
1
eceive); super::reg_json_async(rt, "op_datagram_send", op_datagram_send); } #[derive(Deserialize)] pub(crate) struct AcceptArgs { pub rid: i32, pub transport: String, } async fn accept_tcp( state: Rc<RefCell<OpState>>, args: AcceptArgs, _zero_copy: BufVec, ) -> Result<Value, AnyError> { let rid = args.r...
Rust
0
Chunk::Slice{ key_count: read_dword(&raw[0..]), flags: read_dword(&raw[4..]), name: name, // TODO (erik): Parse keys. keys: Vec::new(), } } pub fn new(header: &Header, raw: &[u8]) -> (Chunk, u32) { let size = read_dword(&raw[0...
Rust
0
from solution import * def test_is_automorphic_number(): assert is_automorphic_number(76) == True assert is_automorphic_number(25) == True assert is_automorphic_number(9376) == True assert is_automorphic_number(7) == False assert is_automorphic_number(-25) == False try: is_automorphic_n...
Python
1
10, 0x08, 0x04, 0x02, 0x00, 0x00, // / 0x1C, 0x3E, 0x61, 0x41, 0x43, 0x3E, 0x1C, // 0 0x40, 0x42, 0x7F, 0x7F, 0x40, 0x40, 0x00, // 1 0x62, 0x73, 0x79, 0x59, 0x5D, 0x4F, 0x46, // 2 0x20, 0x61, 0x49, 0x4D, 0x4F, 0x7B, 0x31, // 3 0x18, 0x1C, 0x16, 0x13, 0x7F, 0x7F, 0x10, // 4 ...
Rust
0
SSAGE_TERMINATE: INSTALLMESSAGE = 218103808i32; #[doc = "*Required features: 'Win32_System_ApplicationInstallationAndServicing'*"] pub const INSTALLMESSAGE_SHOWDIALOG: INSTALLMESSAGE = 234881024i32; #[doc = "*Required features: 'Win32_System_ApplicationInstallationAndServicing'*"] pub const INSTALLMESSAGE_PERFORMANCE: ...
Rust
0
buf) return api_def_proto def get_op_def(self, op_name): if op_name in self._op_per_name: return self._op_per_name[op_name] raise ValueError("No entry found for " + op_name + ".") def op_names(self): return self._op_per_name.keys() @tf_contextlib.contextmanager def tf_buffer(data=None): ...
Python
1
0x00,// No flags set 0x8C, 0x0B,// 1420 = "tileloadd" // VEX_Tdpbf16ps_tmm_tmm_tmm 0x00,// No flags set 0x8D, 0x0B,// 1421 = "tdpbf16ps" // VEX_Tdpbuud_tmm_tmm_tmm 0x00,// No flags set 0x8E, 0x0B,// 1422 = "tdpbuud" // VEX_Tdpbusd_tmm_tmm_tmm 0x00,// No flags set 0x8F, 0x0B,// 1423 = "tdpbusd" // VEX_Td...
Rust
0
role="user", content=prompt_config.post.format(question=session.question), ), ] post = await llm_model.call_single( messages=messages, callbacks=callbacks, name="post", ...
Python
1
..width { let off = y_off + x * x_stride; if y == 0 { for c in 0..x_stride { target[off + c] = target[off + c - x_stride] + padded[off + c] as u32; } } else { for c in 0..x_stride { target[off + c...
Rust
0
# coding=utf-8 from __future__ import division from datetime import date import jieba import requests from bs4 import BeautifulSoup from slack_bot.ext import cache from utils import check_cache description = """ 获取以下网站的活动列表: http://segmentfault.com/events http://huiyi.csdn.net/activity/home http://www.chekucafe.com/...
Python
1
he License for the specific language governing permissions and // limitations under the License. //! `log_graph_args` accepts a list of commits in a repository, and computes //! inclusions and exclusions to pass to `git log --graph` to show the //! relationships between the given commits. mod internal; /// A list of...
Rust
0
::ScopedFd, session::{ address_space::{ address_space::{AddressSpace, AddressSpaceSharedPtr, AddressSpaceSharedWeakPtr}, BreakpointType, WatchConfig, }, task::{ task_inner::{CapturedState, TrapReasons}, Task, TaskSharedP...
Rust
0
targets = train_data.targets() if args.dataset_type == 'regression': targets = scaler.inverse_transform(targets) selected_indices = np.argsort(np.abs(np.array(targets).squeeze() - np.array(preds).squeeze()))[-expand_size:] train_pool = tra...
Python
1
import os import torch import json from poselib.retarget.amass_loader import AMASSLoader from poselib.retarget.retargeting_processor import RetargetingProcessor from poselib.skeleton.skeleton3d import SkeletonTree, SkeletonState, SkeletonMotion from poselib.visualization.common import plot_skeleton_state, plot_skeleton...
Python
1
from .kxsts import KXsts
Python
1
# Python Tkinter GUI based "LOVE CALCULATOR" # import tkinter from tkinter import * # import random module import random # Creating GUI window root = Tk() # Defining the container size, width=400, height=240 root.geometry('400x250') # Title of the container root.title('Love Calculator????') # Function to calculate lo...
Python
1
( self, messages: Optional[List[Dict[str, str]]] = None, stream: bool = True, user_query: str = None, on_token=None, mcp_enabled: bool = False ) -> Iterator[str]: """ 调用对话API(集成记忆检索,仅流式返回) Args: messages: 消息列表,如果为None则使用历...
Python
1
}); } #new_complete_method #read_to_type_method } impl Event<#type_name> for #event_name { fn is_guaranteed(&self) -> bool { #event_name::is_guaranteed() } #event_write_method fn get_type...
Rust
0
# encoding: utf-8 """ Utilities for version comparison It is a bit ridiculous that we need these. """ #----------------------------------------------------------------------------- # Copyright (C) 2013 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the f...
Python
1
nf = nf[nf.index.isin(tnf.index)] nf = nf.reset_index('pdate') ##财报数据发布后,剔除分红 dividend = dividend['dividend'].reindex(nf.index.union(dividend.index)).fillna(0) nf = nf.drop(['pdate'],axis=1) ##日度对齐 nf = nf.unstack() nf = nf.r...
Python
1
impl$(<$($ilf: lifetime,)* $($ig: ident),*>)? $($t: ident)::+ $(<$($lf: lifetime,)* $($g: ty),*>)?; type Unsub = $u: ty; macro method($($args:tt)*) $body:tt $(where $($b:tt)+)? )=>{ impl$(<$($ilf,)* $($ig),*>)? SharedObservable for $($t)::+ $(<$($lf,)* $($g,)*>)? $(where $($b)+)? ...
Rust
0
from textual import on from textual.app import App, ComposeResult from textual.widgets import Header, Input, Footer, Static, Markdown from textual.containers import VerticalScroll from textual.timer import Timer from fetch_api import send_prompt import os class Prompt(Static): def __init__(self, message: str) -> N...
Python
1
} <filename>runtime/src/kitties.rs use crate::nfts; use parity_codec::Encode; use rstd::result; use runtime_io::blake2_256; use support::{decl_event, decl_module, decl_storage, ensure, traits::Currency, StorageMap}; use system::ensure_signed; pub trait Trait: nfts::Trait { type Event: From<Event<Self>> + Into<<Sel...
Rust
0
} fn gates_table() -> HashMap<&'static str, QCircuit> { use jp_quantum::gates::*; let mut table = HashMap::new(); table.insert("id", id()); table.insert("h", h()); table.insert("x", x()); table.insert("y", y()); table.insert("z", z()); table.insert("cz", cz()); table.insert("ccz",...
Rust
0
tTaskCompleteResponse>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCode...
Rust
0
########################################################################################## # # # Copyright (C) 2018-2022 Simon O'Meara : simon.omeara@manchester.ac.uk # # ...
Python
1
Tracked { /// Event channel tracking modified/inserted/removed components. fn channel(&self) -> &EventChannel<ComponentEvent>; /// Mutable event channel tracking modified/inserted/removed components. fn channel_mut(&mut self) -> &mut EventChannel<ComponentEvent>; } #[derive(Debug, Copy, Clone)] /// Co...
Rust
0
_CLASS_MENUITEM", "menuitem"), ("GTK_STYLE_CLASS_MESSAGE_DIALOG", "message-dialog"), ("GTK_STYLE_CLASS_MONOSPACE", "monospace"), ("GTK_STYLE_CLASS_NEEDS_ATTENTION", "needs-attention"), ("GTK_STYLE_CLASS_NOTEBOOK", "notebook"), ("GTK_STYLE_CLASS_OSD", "osd"), ("GTK_STYLE_CLASS_OVERSHOOT", "oversh...
Rust
0
is_processors, _ = load_model_and_preprocess( name=args.model_name, model_type=args.model_type, is_eval=True, device=device, ) vis_processors = ds['val'].vis_processor print('Loading model done!') def inference(image, prompt, min_len=1, max_len=250, beam_size=5, len_penalty=-1, repetition_penalty=1, ...
Python
1
) with open(f'config/downloader.json', 'r', encoding='utf8') as file: json_data = json.loads(file.read()) # if live if is_checking_live: # self.get_live_status() if 'liveID' not in json_data[self.ch_name] or self.new_video_id != json_data[self.ch_name]['live...
Python
1
, pub timestamp: i64, pub expiration_hours: u16, pub email: String, pub amount: u64, } // Sizing consts const DISCRIMINATOR_LENGTH: usize = 8; const PAYER_PUBLIC_KEY_LENGTH: usize = 32; const RECIPIENT_PUBLIC_KEY_LENGTH: usize = 32; const TIMESTAMP_LENGTH: usize = 8; const EXPIRATION_HOURS_LENGTH: usiz...
Rust
0
eval_decimal("255.0_u8"), Ok((KNumber::UNN(255), KNumberTy::U8)) ); // 2^53-1 (= max safe-integer) assert_eq!( eval_decimal("9007199254740991.0_u64"), Ok((KNumber::UNN(9007199254740991), KNumberTy::U64)) ); } #[test] fn test_e...
Rust
0
import sqlite3 # Crea una conexión a la base de datos SQLite def create_connection(db_name: str): connection = None try: connection = sqlite3.connect(db_name) connection.execute("PRAGMA foreign_keys = ON;") # Activa las claves foráneas print(f"Conexión exitosa a {db_name}") ex...
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
, 0, 0, 0, 0, 1]); let frame = GoawayFrame::from_raw(&raw).expect("Expected successful parse"); assert_eq!(frame.error_code(), ErrorCode::ProtocolError); assert_eq!(frame.last_stream_id(), 0); assert_eq!(frame.debug_data(), &Bytes::new()); } #[test] fn test_parse_valid_no_de...
Rust
0
DiagnosticBuilder, ErrorGuaranteed, fluent}; use rustc_macros::{SessionDiagnostic, SessionSubdiagnostic}; use rustc_session::{parse::ParseSess, SessionDiagnostic}; use rustc_span::Span; #[derive(SessionDiagnostic)] #[error(slug = "parser-expect-path")] struct DeriveSessionDiagnostic { #[primary_span] span: Sp...
Rust
0
extend(labels) val_preds.extend(preds) print(f"val loss: {val_loss}") # get overall performance val_acc, val_prec, val_recall, val_f1 = overall_performance(val_labels, val_preds) return val_acc, val_prec, val_recall, val_f1 def set_random_seeds(seed): """ set random seed """ ...
Python
1
(window.google && (window.google.sn", "__webpack_require", "e={Vue:null", "_PostRPC()", ".password-toggler-button-parent", "allowAdblock()", ".topbanneradvertise", ".wrcx {display:none}", "rw_sendSocketMessage(aData)", "window[\"_gaUserPrefs\"]", "function n(){!function(){functio...
Rust
0
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. """ Commands to communicat...
Python
1
import matplotlib.pyplot as plt import numpy as np def pie_chart(labels, values, colors): fig, ax = plt.subplots() ax.pie( values, labels=labels, colors=colors, wedgeprops=dict(width=0.5), autopct='%1.0f%%' ) plt.show() def donut_chart(recipe, data, colors, title, filename): fig, a...
Python
1
ab.get::<u64>(ChannelScrape::VT_SCRAPE_TIMESTAMP, Some(0)).unwrap() } #[inline] pub fn state(&self) -> Option<ChannelState<'a>> { self._tab.get::<flatbuffers::ForwardsUOffset<ChannelState>>(ChannelScrape::VT_STATE, None) } } impl flatbuffers::Verifiable for ChannelScrape<'_> { #[inline] fn run_verifier...
Rust
0
#!/usr/bin/env python3 ''' 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"...
Python
1
def load_model_hook(models, input_dir): while len(models) > 0: model = models.pop() sub_dir = 'unet' if isinstance(model.base_model.model, type( accelerator.unwrap_model(unet).base_model.model) ) else 'text_encoder' model_cls = UNet2DConditionModel if isinstance(model...
Python
1
ub async fn unload(&self, persist: bool) -> Result<()> { Context::unload(&self.path, persist).await } pub async fn save(&self) -> Result<()> { Context::save(&self.path).await } } <filename>src/lib.rs //! This crate provides a simple interface to liblzma. LZMA is more commonly known as XZ or 7zip, //! (a...
Rust
0
from Node import Node class Arbre: def __init__(self): self.codes = {} def build_tree(self, freq_dict): nodes = [Node(char, freq) for char, freq in freq_dict.items()] while len(nodes) > 1: nodes = sorted(nodes, key=lambda x: x.freq) left = nodes.pop(0) ...
Python
1
cel(self): """Cancel selecting/creating path. Works by clearing the path selection, which causes no path to be returned. The 'cancelled' attribute is also set to True, to indicate the user cancelled providing path(s). The 'running' attribute is also set to False, which...
Python
1
import os import cv2 import argparse from ultralytics import YOLO import supervision as sv import numpy as np def parse_arguments() -> argparse.Namespace: parser = argparse.ArgumentParser(description="YOLOv8 live") parser.add_argument( "--webcam-resolution", default=[1280,720], nargs=2...
Python
1
cell::VolatileCell<u32>, } #[doc = "LENIENCY MSB"] pub mod leniency_msb; #[doc = "PART ID"] pub struct PART_ID { register: ::vcell::VolatileCell<u32>, } #[doc = "PART ID"] pub mod part_id; #[doc = "Packet Buffer TX"] pub struct PKT_BUFFER_TX0 { register: ::vcell::VolatileCell<u16>, } #[doc = "Packet Buffer TX"]...
Rust
0
nZeroI8); impl CommonCoord for Coord { fn raw(&self) -> i8 { self.0.get() } } #[derive(Debug, Clone)] pub enum CoordFromStrError { CharacterCount, InvalidLetter, InvalidNumber, } impl std::fmt::Display for CoordFromStrError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Res...
Rust
0
"""Block a user on Mastodon.""" import argparse from dotenv import find_dotenv, load_dotenv from mastodon_sim.logging_config import logger from mastodon_sim.mastodon_ops.get_client import get_client from mastodon_sim.mastodon_ops.login import login def block_user(login_user: str, target_user: str) -> None: """...
Python
1
# non-project-specific task; ignore (TODO) continue project = t['kwargs']['project'] if not project in self.messages: self.messages[project] = {} if not taskID in self.messages[project]: ...
Python
1
ght"].set_visible(False) ax1.text(-0.025,label_y_position, 'a', transform=ax1.transAxes, fontsize=label_size, fontweight='bold', va='top', ha='right') ax1.text(0.9, 0.55, '', transform=ax1.transAxes, fontsize=inset_size, va='top', ha='right') #Histogram out-degree ax2 = plt.subplot(...
Python
1
of alternatives which can easily be converted /// from a string (`--chain=...`) into a `ChainSpec`. #[derive(Clone, Debug)] pub enum Alternative { /// Whatever the current runtime is, with just Alice as an auth. Development, /// Whatever the current runtime is, with simple Alice/Bob auths. LocalTestnet...
Rust
0
import requests from bs4 import BeautifulSoup li = [] data = requests.get("https://rahulshettyacademy.com/AutomationPractice/") soup = BeautifulSoup(data.content,'html.parser') #print(soup.prettify()) appium = soup.find('a',string='Appium') print(appium['href'])
Python
1
empty() { namespace_label.push_str("_"); } namespace_label.push_str(&*class_symbol.name.clone()); let mut static_memory_label = namespace_label.clone(); static_memory_label.push_str("_static"); let mut static_init_label = static_memory_label.to_string(); static_init_label.push_str("_init"); l...
Rust
0
# Copyright 2021-present, the Recognai S.L. 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 la...
Python
1
b3) + np.cross(b1_ref, b3_dot)) / np.linalg.norm(np.cross(b1_ref, b3))), b2) # b1_dot = np.cross(b3_dot, b2) + np.cross(b3, b2_dot) # # # Calculate R_c_dot # Rc_dot = np.vstack((b1_dot, b2_dot, b3_dot)).T # wc_hat = np.matmul(Rc.T, Rc_dot) # wc = np.array([wc_hat[2, 1], w...
Python
1
p is not None: pass return primal_out, tangent_out def _eval_gto_jvp_r0(cell, cell_t, eval_name, coords, comp, kpts, kpt, shls_slice, non0tab, ao_loc): if 'ip' in eval_name: raise NotImplementedError('Please use GTOval_cart_deriv1 or \ GTO...
Python
1
sleep_records=sleep_records, activity_records=minimal_activity_records, heart_records=[], start_date=test_date, end_date=test_date.replace(day=26), ) # Check results for feature_set in features: seoul_features = feature_set.seoul_...
Python
1
CategoryPeriodPollRankings { maxPollNumberBytes, numPollsInPeriod, voteCountsByCategoryIndex: Vec::with_capacity(numCategoriesInPeriod), } } } /** * Random access data structure needed for initial lookup of a Location+Category poll rankings. * Contains time period spe...
Rust
0
o é reservado e varia entre as aplicações. let header_metadata: u32 = u32::from_be_bytes([content[0x06], content[0x07], content[0x08], content[0x09]]); // Offset de onde os dados da imagem começam. let header_offset: u32 = u32::from_le_bytes([content[0x0A], content[0x0B], content[0x0C], con...
Rust
0
let err = server_future.await.expect_err("Server terminated in error"); assert_eq!(ErrorKind::Interrupted, err.kind(), "Unexpected error when the server exits"); client_cancelation_token.cancel(); let err = client_future.await.expect_err("Client terminated without error"); ass...
Rust
0
(pattern)] #![feature(placement_in)] #![feature(placement_in_syntax)] #![feature(placement_new_protocol)] #![feature(shared)] #![feature(slice_get_slice)] #![feature(slice_patterns)] #![cfg_attr(not(test), feature(sort_unstable))] #![feature(specialization)] #![feature(staged_api)] #![feature(str_internals)] #![feature...
Rust
0
&mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "WebKitFindControllerPrivate @ {:?}", self as *const _) } } #[repr(C)] pub struct WebKitFormSubmissionRequestClass { pub parent_class: gobject::GObjectClass, pub _webkit_reserved0: Option<unsafe extern "C" fn()>, pub _webkit_reserve...
Rust
0