text
string
label_name
string
labels
int64
rrogatepass') except ValueError as exc: if str(exc) == 'unsupported error handler': self.skipTest(f"{self.ENCODING!r} decoder doesn't support " f"surrogatepass error handler") else: raise self.check_decode_strings("su...
Python
1
#!/usr/bin/env python # -*- coding: utf-8 -*- import torch def point_to_plane_distance(points, plane_points, plane_normals): """ Calculate signed distance from points to planes. Args: points: (B, N, 3) or (N, 3) tensor of points plane_points: (B, M, 3) or (M, 3) tensor of points on planes...
Python
1
): if not os.path.exists(save_dir) and verbose: os.makedirs(save_dir) source_and_target_files = [('source', source), ('target', target)] # (1) 将 target image 和 source image 分别 crop, 并对齐, 得到 S 和T if only_target_crop: crops, orig_images, quads, inv_transforms = crop_and_a...
Python
1
, vector_store: VectorStoreModel, message: str, id: str, ephemeral: bool, str_ontology: str, updated_memory: str, ) -> None: relevant_memory = find_relevant_memories( data=data, vector_store=vector_store, message=message, id=id, ephemeral=ephemeral, ...
Python
1
_part2() { assert_eq!(part2(EX), 3); } } <filename>tss-esapi/src/structures/parameters.rs // Copyright 2021 Contributors to the Parsec project. // SPDX-License-Identifier: Apache-2.0 use crate::{ structures::{KeyedHashScheme, SymmetricDefinitionObject}, tss2_esys::{TPMS_KEYEDHASH_PARMS, TPMS_SYMCI...
Rust
0
from rest_framework_simplejwt.tokens import RefreshToken def create_token_response(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), }
Python
1
go_ast_binary_operator_or as isize, And = clingo_ast_binary_operator_clingo_ast_binary_operator_and as isize, Plus = clingo_ast_binary_operator_clingo_ast_binary_operator_plus as isize, Minus = clingo_ast_binary_operator_clingo_ast_binary_operator_minus as isize, Multiplication = clingo_ast_binary_opera...
Rust
0
#[serde(rename = "source")] Source, #[serde(rename = "test")] Test, #[serde(rename = "")] Noop, #[serde(other)] FallthroughString, } impl std::fmt::Display for CodeScanningAlertClassification { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &*sel...
Rust
0
rent displays. fig = plt.figure(figsize=(12, 4)) reflectivity_display = pyart.graph.RadarMapDisplay(radar_level3_reflectivity) ax = plt.subplot(121, projection=ccrs.PlateCarree()) reflectivity_display.plot_ppi_map( "reflectivity", ax=ax, colorbar_label="Equivalent Relectivity ($Z_{e}$) \n (dBZ)", vmi...
Python
1
ub type ImU32 = c_uint; /// Character for keyboard input/display pub type ImWchar = c_ushort; /// User data to identify a texture pub type ImTextureID = *mut c_void; /// Unique ID used by widgets (typically hashed from a stack of string) pub type ImGuiID = ImU32; /// A color identifier for styling #[repr(C)] #[deri...
Rust
0
ctor: &[u8]) -> Vec<$type> { let mut rdr = Cursor::new(vector); let mut values = Vec::with_capacity(vector.len() / std::mem::size_of::<$type>()); loop { let option = rdr.$read_func::<LittleEndian>(); match option { Ok(n) => values....
Rust
0
[getset(get = "pub")] master_key: MasterKey, /// The salt to derive the key to decrypt the in-memory encrypted master key. #[getset(get = "pub")] salt: Vec<u8>, /// The nonce used to decrypt the in-memory encrypted master key. #[getset(get = "pub")] nonce: Vec<u8>, /// The [`PathBuf`]...
Rust
0
febdGraph.meta_data['index_low'], febdGraph.meta_data['index_high'] ): veno_xs.append(x_fuse[low: high]) venoGraph.__setitem__('x_old', venoGraph.x.clone()) # 第二步修改,将图像特征加到oriGraph的节点上 oriGraph.x = self.oriNode(x + oriVF) veno_xs = torch.cat(veno_xs, dim...
Python
1
#Lists Challenge 8: Grocery List App import datetime #Create the datetime object and store the current date and time time = datetime.datetime.now() month = str(time.month) day = str(time.day) hour = str(time.hour) minute = str(time.minute) #Welcome message foods = ["Meat", "Cheese"] print("Welcome to the Grocery Lis...
Python
1
_COF: [Chunk; NLEN] = [0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]; pub const CRU: [Chunk; NLEN] = [ 0x7, 0x8000000, 0x6CD, 0x0, 0x24909, 0x4000000, 0x49B362, 0x0, 0x0, 0x0, ]; pub const CURVE_PXA: [Chunk; NLEN] = [ 0x803FB2B, 0xEE4224C, 0x8BF0D91, 0x8BBB489, 0xDB6A464, 0x7E8C61E, 0xFEB8D8C, 0x519EB62, ...
Rust
0
any pending loader callables if needed. """ return self.state.manager[self.key].__get__( self.state.obj(), self.state.class_) @property def history(self): """Return the current pre-flush change history for this attribute, via the :class:`.History` interface. ...
Python
1
ut or synced with upstream branch or remote; nothing left to update """ ) assert_success( ["traverse", "--sync-gitlab-mrs", "-Wy"], """ Fetching origin... Checking out the first root branch (develop) Checking for open GitLab MRs.....
Python
1
string()); let pkgfs = PkgfsInstance::new(blobfs_dir, system_image_merkle); Self { blobfs, pkgfs: Some(pkgfs) } } pub async fn serve(&self) { fx_log_info!("Preparing services via VFS"); let out_dir = pseudo_directory! { "blob" => remote_dir(self.blobfs.open_root_di...
Rust
0
67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10, ]; let mut subkey = [0u32; KEY_TABLE_LEN]; let plaintext = [ 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10, ]; let ciphertext = [ 0x67, 0x67, 0x31, 0x38, 0x54,...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # -------------------------------------------------------- # Descripttion: https://github.com/sxhxliang/detectron2_backbone # version: 0.0.1 # Author: Shihua Liang (sxhx.liang@gmail.com) # FilePath: /detectron2_backbone/setup.py # Create: 2020-03-26 22:13:49 # LastAuthor: S...
Python
1
verbose); let key = Key::new_generate().unwrap(); let mut node = Node::new(key.clone(), config); let tx_out = node.run(); node.add_tx(key.get_pub()); loop { let res = tx_out.recv(); println!("RESULT {:?}", res); } } <filename>research/gaia/gremlin/gremlin_core/src/bin/main.rs // //! Copyright ...
Rust
0
non_snake_case, )] pub mod tle; pub mod coordinates; use std::io::Write; macro_rules! println_stderr( ($($arg:tt)*) => { { let r = writeln!(&mut ::std::io::stderr(), $($arg)*); r.expect("failed printing to stderr"); } } ); /// $k_e = 7.43669161 \times 10\^{-2}$ Orbital constant for E...
Rust
0
is_unix_type(), false); } #[test] fn normal_directory_3() { let row = "08-22-18 02:05PM <DIR> 1.1 Header [13]"; let ftpentry = FtpEntry::try_from(row); assert!(ftpentry.is_ok()); let ftpentry = ftpentry.unwrap(); assert_eq!(ftpentry.kind(), FtpEntry...
Rust
0
ndering'] hitbox_enabled = settings['head_hitbox_rendering'] skeleton_enabled = settings['skeleton_rendering'] names_enabled = settings['show_names'] box_type = settings['box_type'] team_color_rgb = settings['team_color'] enemy_color_rgb = settings['enemy_color'] ...
Python
1
pub height: u32, } impl Viewport { pub fn clone_from_crtc_info(c: &CrtcInfo) -> Viewport { Viewport { x: c.x as u32, y: c.y as u32, width: c.width as u32, height: c.height as u32, } } pub fn without_strut( &self, screen_widt...
Rust
0
ConfigBootstrap, GlobalConfig, }; use tari_comms::{ peer_manager::PeerFeatures, tor::HiddenServiceControllerError, utils::multiaddr::multiaddr_to_socketaddr, NodeIdentity, }; use tari_core::chain_storage::ChainStorageError; #[cfg(all(unix, feature = "libtor"))] use tari_libtor::tor::Tor; use tari_sh...
Rust
0
from datetime import datetime, timedelta import pytest from redengine.core.time import ( TimeDelta ) @pytest.mark.parametrize( "dt,dt_ref,offset", [ # Regular pytest.param( datetime(2020, 1, 1, 10, 00), datetime(2020, 1, 1, 12, 00), "2:00:00", ...
Python
1
from . import specification_sheet from . import specification_method from . import specification_parameter from . import specification_template from . import specification_property from . import specification_storage_condition
Python
1
x, rect.position.y), size: half_size, }, Rect { position: rect.position + half_size, size: half_size, }, Rect { position: Vector2::new(rect.position.x, rect.position.y + half_size.y), size: half_size, }, ] } pub str...
Rust
0
pub fn is_aux_adc_done(&self) -> bool { *self == RTC_CH1_CAPT_EVR::AUX_ADC_DONE } #[doc = "Checks if the value of the field is `AUX_COMPB`"] #[inline] pub fn is_aux_compb(&self) -> bool { *self == RTC_CH1_CAPT_EVR::AUX_COMPB } #[doc = "Checks if the value of the field is `AUX...
Rust
0
from typing import Callable import inject from gi.repository import Adw, Gtk from cozy.control.artwork_cache import ArtworkCache from cozy.model.book import Book BOOK_ICON_SIZE = 52 class BookRow(Adw.ActionRow): _artwork_cache: ArtworkCache = inject.attr(ArtworkCache) def __init__( self, book: Boo...
Python
1
import pygame import time import random last_key = 5 BLUE1 = (0, 0, 255) pygame.init() pygame.display.set_caption('Sanke') display = pygame.display.set_mode((480, 600)) x = 0 y = 0 running = True while running: display.fill((0, 0, 0)) pygame.draw.rect(display, BLUE1, pygame.Rect(x, y, 20, 20)) x1 = random....
Python
1
from typing import Annotated from fastapi import APIRouter, Response from starlette import status from app.lib.auth_context import web_user from app.models.db.user import User from app.models.db.user_subscription import UserSubscriptionTarget from app.models.types import UserSubscriptionTargetId from app.services.use...
Python
1
.png")?; let mut game = Game::with_jokers(); game.add_player(graphics::Text::new(ctx, "Falch", &font)?); game.add_player(graphics::Text::new(ctx, "Dummer", &font)?); game.shuffle(); game.deal_to_all(5); Ok(MainState { cards, game }) }...
Rust
0
if !(workdir.exists()) { fs::create_dir_all(&workdir).unwrap(); } // Setting the directory as `pwd` env::set_current_dir(&workdir).unwrap(); let mut build: Instance; // Checking if the configuration file for a user already exists if !(Path::new(&format!("{}.json", env::var("...
Rust
0
1, 2, 4), output_dir: PathBuf::from("/tmp"), extra_args: vec!["--strict".to_string()], } ) } // Copyright 2020 <NAME> // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opens...
Rust
0
min_temp: None, max_temp: Some(20), other_checks: None, }; const LIGHT_JACKET: Gear = Gear { name: "a light jacket", min_temp: Some(21), max_temp: Some(35), other_checks: None, }; const VEST: Gear = Gear { name: "a vest", min_temp: Some(36), max_temp: Some(40), other_checks...
Rust
0
from .adv_control.nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS WEB_DIRECTORY = "./web" __all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS', "WEB_DIRECTORY"]
Python
1
#!/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 # ...
Python
1
![ 3.0_f64 / 4.0_f64, (13.0_f64.sqrt() + 1.0_f64) / 8.0_f64, -(13.0_f64.sqrt() - 1.0_f64) / 8.0_f64, ], rng: Xoshiro256StarStar::seed_from_u64(S), predict_distribution: Normal::new(0.0, SYSTEM_NOISE_VARIANCE.sqrt()).unwrap(), }; mpf.run_and_w...
Rust
0
cache); }); layer_cache } } } impl<TFile: FloFile+Send+'static> VectorLayer for SqliteVectorLayer<TFile> { fn active_brush(&self, when: Duration) -> Option<Arc<dyn Brush>> { let layer_id = self.layer_id; self.core.sync(|core| core.get_active_brush_for_layer(layer_id, when))...
Rust
0
$($elems,)* edn_internal!(@seq @set [$($inner_val)*]) , ] $($rest)*), ("(",")") => edn_internal!(@seq @$kind [ $($elems,)* edn_internal!(@seq @list [$($inner_val)*]) , ] $($rest)*), ("[","]") => edn_internal!(@seq @$kind [ $($elems,)* edn_internal!(@seq @vec [$($inner_val)*]) , ] $($rest)*), ...
Rust
0
s()); } } /// Add a string (as UTF-8 encoded byte-stream) to the end of the BLOB /// /// # Example /// /// ```rhai /// let b = blob(5, 0x42); /// /// b.append('!'); /// /// print(b); // prints "[424242424221]" /// ``` #[rhai_fn(name = "+=", name = "appen...
Rust
0
from telegram.ext import CallbackContext from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup from Help.Decorators import send_typing_action #command /help @send_typing_action def help(update:Update,context:CallbackContext): """Send a message when the command /help is issued.""" update.messa...
Python
1
import pandas as pd import numpy as np from sqlalchemy.orm import Session from ..models.medicine import Medicine from ..models.prediction import Prediction def _extract_forecast(model, steps: int): dates, values = None, None if hasattr(model, "get_forecast"): fc = model.get_forecast(steps=steps) ...
Python
1
records from a collection to skip. Default value is 0. */ pub async fn get( &self, fields: &[String], exclude_fields: &[String], count: i64, offset: i64, ) -> Result<crate::types::ConnectedSites> { let mut query_args: Vec<(String, String)> = Default::default(...
Rust
0
lta with v.T # Since we're tracing along the PT8AL21 phase boundary, which is a stoichiometric phase # The delta composition for PT8AL21 should be 0, but it can change for the liquid phase # But because the liquid phase is fixed at 0, the overall change in v.X('AL') should also be 0 T_deltas =...
Python
1
"""Tests examples/*: quickstart code and Jupyter notebook.""" import os import pathlib import subprocess import sys from typing import Iterable, Sequence import pytest import pytest_notebook as ptnb def _paths_to_strs(x: Iterable[pathlib.Path]) -> Sequence[str]: """Convert Path to str for nice Pytest `parameter...
Python
1
ct'): params['pay_amount'] = self.pay_amount.to_alipay_dict() else: params['pay_amount'] = self.pay_amount if self.pid: if hasattr(self.pid, 'to_alipay_dict'): params['pid'] = self.pid.to_alipay_dict() else: para...
Python
1
selected_move, best_value # --- Main move function implementing Iterative Deepening --- (Unchanged) def move(self, side, board): """ Calculates the best move using Iterative Deepening (Single-Threaded). """ self.start_time_for_move = time.time() self.calculation_time = 0 self....
Python
1
_key: String, } #[derive(Clone, Debug, Default)] pub struct BasicDeliverArgs { pub consumer_tag: String, pub delivery_tag: u64, pub redelivered: bool, pub exchange_name: String, pub routing_key: String, } #[derive(Clone, Debug, Default)] pub struct BasicAckArgs { pub delivery_tag: u64, pub...
Rust
0
_response_address(ut_.key_address_connect_address()); // // request.add_keys(key); // // // // Address rt_thread = get_routing_thread(); // // send_request<KeyAddressRequest>(request, socket_cache_[rt_thread]); // // } // // // // // // // KeyResponse generate_bad_response(const KeyRequest& req) { // //...
Rust
0
eq!( Font6x6::total_char_width('\u{A0}'), Font6x6::total_char_width(' ') ); } #[test] fn test_str_width() { let data: [(&str, u32); 4] = [("", 0), ("foo", 3), ("foo\rbar", 3), ("foo\rfoobar", 6)]; for (word, chars) in data.iter() { assert_eq!(char...
Rust
0
# Custom extensions for Griffe. from __future__ import annotations import ast from typing import Any import griffe _logger = griffe.get_logger("griffe_extensions") class CustomFields(griffe.Extension): """Support our custom dataclass fields.""" def on_attribute_instance( self, *, ...
Python
1
?; let array = pa.getattr("Array")?.call_method1( "_import_from_c", (array_pointer as uintptr_t, schema_pointer as uintptr_t), )?; Ok(array.to_object(py)) } fn to_py_batch<'a>( batch: &RecordBatch, py: Python, pyarrow: &'a PyModule, ) -> Result<PyObject, PyErr> { let mut py...
Rust
0
comment that cannot be forwarded as-is DocComment(Ident, String), /// Diagram start token DiagramStart(Ident), /// Diagram entry (line) DiagramEntry(Ident, String), /// Diagram end token DiagramEnd(Ident), } impl Attr { pub fn as_ident(&self) -> Option<&Ident> { match self { ...
Rust
0
Bit 31 - Set this bit to reset DMA TX AFIFO, which is used to send data out in SPI slave DMA controlled mode transfer."] #[inline(always)] pub fn dma_afifo_rst(&mut self) -> DMA_AFIFO_RST_W { DMA_AFIFO_RST_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub ...
Rust
0
20 = 2, Unknown = 99, } /// Converts enum into common encoded string impl Display for CryptoAlgorithm { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match self { CryptoAlgorithm::AesGcm => write!(f, "{}", AES_GCM_STR), CryptoAlgorithm::ChaCha20 => write!(f, "{}", CHA_CHA_20...
Rust
0
# MOJIZA/projectpapca/page_qrcode.py from engine.engine import PAGE, HTML from PyCSS.PyCSS import PyCSS import qrcode import io import base64 @PAGE(type="page", pagename="qrcode", route="/qrcode", methods=["GET", "POST"]) def qrcode_page(request, response): if request.method == "GET": # GET so'rovi uchun ...
Python
1
#[repr(transparent)] pub struct Proc { inner: ProcBuilder, } impl Proc { fn parent(&self) -> &SpinlockProtected<*const Proc> { // SAFETY: invariant unsafe { self.parent.assume_init_ref() } } /// Kill and wake the process up. pub fn kill(&self) { self.killed.store(true, Orde...
Rust
0
_name).canonicalize().unwrap(); let metadata = cargo_metadata::MetadataCommand::new() .no_deps() .other_options(["--all-features".to_string(), "--offline".to_string()]) .exec() .unwrap(); let workspace_members = metadata .workspace_members .iter() .map(|pkg_id| { metadata ...
Rust
0
Bearer {} impl Default for Bearer { fn default() -> Self { Bearer { bearer: None } } } impl Bearer { pub fn new<T: Into<String>>(bearer: T) -> Self { let bearer: String = bearer.into(); Bearer { bearer: Some(bearer.into()), } } } #[async_trait] impl Schem...
Rust
0
from __future__ import annotations import bs4 def get_first_deepest_tag(tag: bs4.Tag) -> bs4.Tag | None: """ Given a BeautifulSoup tag, returns the first deepest tag within it. For example, if we have the following HTML structure: <div><p>Test</p><span>Another Test</span></div> and we pass the '...
Python
1
lection_dict in change.new.items(): value = selection_dict["value"] store = selection_dict["store"] selection_type = self._selection_types[selection_name] if selection_type == "index": self.selections._set_value( selection_name, ...
Python
1
# -*- coding: utf-8 -*- # Copyright (c) 2009 - 2010 Detlev Offenbach <detlev@die-offenbachs.de> # """ Module implementing a dialog to enter the connection parameters. """ from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtSql import QSqlDatabase from KdeQt import KQFileDialog from E4Gui.E4Completers...
Python
1
s, }, unembed_error::UnembedError, }; use im::{ HashMap, HashSet, }; use std::fmt; #[derive(PartialEq, Clone, Debug)] pub struct Package { pub name: String, pub docs: String, pub source: Link, pub decls: Vec<Declaration>, } #[derive(PartialEq, Clone, Debug)] pub enum Declaration { Defn { name: Strin...
Rust
0
'), dpi=300, bbox_inches='tight') plt.close() def _print_sample_summary(self, result): """打印样本分析摘要""" sample_file = result['sample_file'] success = result['success'] computation_time = result['computation_time'] print(f" 分析状态...
Python
1
from CoreData import * from AppKit import * from Foundation import * import sys class ExamplePlugin (NSObject): def execute_(self, obj): try: movieArrayController = obj[0] movieArrayFilesController = obj[1] # access current movie m = movieArrayController.selection() print m if (m.valueForKey_...
Python
1
# https://leetcode.com/problems/roman-to-integer/description/ class Solution(object): def romanToInt(self, s): s += "O" d = {} d["O"] = 0 d["I"] = 1 d["V"] = 5 d["X"] = 10 d["L"] = 50 d["C"] = 100 d["D"] = 500 d["M"] = 1000 i = ...
Python
1
"""Collect available data from source(s). This module should: - collect data from different source like database, datalake or other - combine them into a single dataset - save the data locally for the rest of the data ingestion and versioning pipeline can work """ import os import requests from...
Python
1
#!/usr/bin/python # -*- coding: utf-8 -*- ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: ibm_is_dedicated_host_disks_info for_more_info: refer - https://registry.terraform.io/providers/IBM-Cloud...
Python
1
, /// The number of replicas needed to provide quorum pub quorum: u64, /// This is the time a backup waits before starting a view change. /// It is also used in other states as a timeout /// It should be smaller than primary_idle_timeout_ms; pub idle_timeout_ms: i64, /// This is the time ...
Rust
0
#!.venv/bin/python import gmsh mm = 1/1000 # FreeCAD (and ourselves) use mm, Elmer wants SI units (i.e. meters) gmsh.initialize() gmsh.model.add("coil") gmsh.option.setNumber("Geometry.OCCScaling", mm) # Coil (_, coil) = gmsh.model.occ.importShapes("coil.brep", highestDimOnly=True)[-1] # Core (_, core) = gmsh.mod...
Python
1
maxdisp // 4, refimg_fea.size()[2], refimg_fea.size()[3]).zero_()) for i in range(self.maxdisp // 4): if i > 0: cost[:, :refimg_fea.size()[1], i, :, i:] = refimg_fea[:, :, :, i:] cost[:, refimg_fea.size()[1]:, i, :, i:] = targetimg_fea[:...
Python
1
lf) } } impl<'a> Codegen<'a> for SimpleString<'a> { fn codegen(&self, state: &mut CodegenState<'a>) { self.parenthesize(state, |state| state.add_token(self.value)) } } #[derive(Debug, PartialEq, Eq, Clone, IntoPy)] pub struct FormattedStringText<'a> { pub value: &'a str, } impl<'a> Inflate<'a...
Rust
0
file."] #[doc = ""] #[doc = " @fields:"] #[doc = " num_faces ::"] #[doc = " The number of faces in the font file. Some font formats can have"] #[doc = " multiple faces in a single font file."] #[doc = ""] #[doc = " face_index ::"] #[doc = " This field holds two different values. Bits 0-15 are the ind...
Rust
0
) -> U, { type File = U; #[inline] fn open_path(&self, path: &Path) -> io::Result<Self::File> { match self.store.open_path(path) { Ok(file) => Ok((self.clo)(file)), Err(err) => Err(err), } } #[inline] fn entries_path(&self, path: &Path) -> io::Result<Entr...
Rust
0
ctorCriticRecurrent" init_noise_std: float = 1.0 actor_hidden_dims: list = [256, 256, 128] critic_hidden_dims: list = [256, 256, 128] activation: str = "elu" rnn_hidden_size: int = 256 rnn_num_layers: int = 1 rnn_type: str = "lstm" @configclass class AlgorithmCfg: class_name: str = "PP...
Python
1
_result = { "endpoint": url, "method": method, "error": str(e) } results["tests"].append(endpoint_result) # Remove duplicates from successful payloads results["successful_payloads"] = list(set(results["successful_payloads"])) ...
Python
1
import contextlib import pytest from pandas.compat import is_platform_windows from pandas import DataFrame import pandas._testing as tm from pandas.io.excel import ExcelWriter xlsxwriter = pytest.importorskip("xlsxwriter") if is_platform_windows(): pytestmark = pytest.mark.single_cpu @pytest.fixture def ext...
Python
1
c_api.request("dj_recommend_type", query) extra.append(extras.json(response, name="response")) assert (response["code"] == 200 or response["data"]["code"] == 200) def test_dj_sub(extra): """ 说明 : 登录后调用此接口 , 传入 """ example = [{"rid": "336355127", "t": "1"}, {"rid": "336355127", "t": "...
Python
1
txs, batch_id, vec![]); txs.push(variant); } else { for mempool_tx in group { let signed_tx = SignedZkSyncTx::try_from(mempool_tx)?; let variant = SignedTxVariant::Tx(signed_tx); txs.push(variant); }...
Rust
0
activation_fn=tf.nn.relu) pool6 = slim.max_pool2d(bn6, kernel_size=[2, 1], stride=[2, 1]) dropout7 = slim.dropout(pool6, keep_prob=1.0 - self.backbone_dropout, is_training=self.is_training) conv7 = slim.conv2d(dropout...
Python
1
(r.status)?; Ok(NewIface { id: iface_counter.next_iface_id() as u16, phy_ownership: device::PhyOwnership { phy_id, phy_assigned_id: r.iface_id }, mlme_channel, }) } fn get_client_sme( ifaces: &IfaceMap, iface_id: u16, endpoint: station::client::Endpoint, ) -> zx::Status { ...
Rust
0
import torch from .functional import * # noqa: F403 if torch.distributed.rpc.is_available(): from .api.remote_module import RemoteModule
Python
1
nsity_sets, theta_unit_label, intensity_unit_label, file_path, irrep_symbols=None, file_format='dat'): """ Save a set of calculated Raman intensities as a function of polarisation angle theta. Arguments: theta_vals -- values of theta. intensity_sets -- calculated band intensnties as...
Python
1
match from_utf8(&*actual.data) { Ok(a) => if re.is_match(a) { Ok(()) } else { Err(anyhow!("Expected binary file '{}' to match '{}'", actual.filename, regex)) }, Err(err) => Err(anyhow!("Expected binary file to match '{}' but...
Rust
0
from PyQt5.QtWidgets import QDialog, QLabel, QVBoxLayout, QApplication from PyQt5.QtCore import Qt, QTimer from PyQt5.QtGui import QPixmap, QPainter, QLinearGradient, QColor import os from PyQt5.QtWidgets import QMessageBox, QApplication import sys def show_notification(title, message): """ Hiển thị thông báo ...
Python
1
osure = Box::new(move |params| -> CallServiceResult { *arg_tetraplets_inner.borrow_mut() = params.tetraplets.clone(); closure(params) }); (host_function, arg_tetraplets) } <reponame>jakeswenson/tink-rust<gh_stars>10-100 // Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache Lic...
Rust
0
try point start_time = time.time() cfg = parser.parse_args() pprint(cfg) print(f"Simulation started at {datetime.now().isoformat()}") activity_model_id=watsonx_helper.activity_gen_model_id activity_model= activity_model_id.split("/")[1] strategy_model_id=watsonx_helper.strategy_gen_model_id ...
Python
1
ist[torch.Tensor] = [] uih_kjt_lengths: List[torch.Tensor] = [] for name, length in self._contextual_feature_to_max_length.items(): uih_kjt_values.append(data[name]) uih_kjt_lengths.append(length) uih_kjt_values.extend( video_history_u...
Python
1
_fs_type_UV_FS_MKDTEMP => FsType::MKDTEMP, uv::uv_fs_type_UV_FS_MKSTEMP => FsType::MKSTEMP, uv::uv_fs_type_UV_FS_OPEN => FsType::OPEN, uv::uv_fs_type_UV_FS_OPENDIR => FsType::OPENDIR, uv::uv_fs_type_UV_FS_READ => FsType::READ, uv::uv_fs_type_UV_FS_READDIR => F...
Rust
0
, ex: &Experiment) -> Result<HashMap<GitHubRepo, String>> { let path = self.shafile_path(ex); if !path.exists() { return Ok(HashMap::new()); } let data: Vec<(GitHubRepo, String)> = serde_json::from_str(&file::read_string(&path)?)?; Ok(data.into_iter().collect()) ...
Rust
0
''' Short Problem Definition: Marie invented a Time Machine and wants to test it by time-traveling to visit Russia on the Day of the Programmer (the 256th day of the year) during a year in the inclusive range from 1700 to 2700. Link Day of The Programmer ( https://www.hackerrank.com/challenges/day-of-the-programmer/pr...
Python
1
_out_mat.emission = Vec4::zero(); true } } //###################################################################### // Emissive //###################################################################### impl Emissive { pub fn new(r: f32, g: f32, b: f32) -> Material { Material::Emiss...
Rust
0
from math import dist def centroid(cluster): dists = [] for dot1 in cluster: sumd = 0 for dot2 in cluster: sumd += dist(dot1, dot2) dists.append([sumd, dot1]) return min(dists)[1] with open('txt/27_A_21599.txt') as file: cluster1 = [] cluster2 = [] cluster3 ...
Python
1
}) .collect() }) } #[cfg(test)] mod tests { use super::*; use crate::mock::{ message, run_test, Event as TestEvent, Origin, TestMessageDeliveryAndDispatchPayment, TestMessagesDeliveryProof, TestMessagesParameter, TestMessagesProof, TestPayload, TestRuntime, TokenConversionRate, PAYLOAD_REJECTED_BY_TARG...
Rust
0
p[1].y as i32), Point::new(self.p[2].x as i32, self.p[2].y as i32) ] } } struct Mesh { // mesh holds multiple triangles thus forming a object (3d model) tris: Vec<Triangle>, } impl Mesh { fn cube() -> Mesh { Mesh { tris: vec![ // south Tria...
Rust
0
import random as r import searchsort as s nums = [] while True: num = r.randint(1,50) if num not in nums: nums.append(num) else: pass if len(nums) == 50: break print(f'{nums}\n') s.merge_sort(nums, 0, len(nums)-1) print(nums)
Python
1
from extranjeria import * ruta = 'data\extranjeriaSevilla.csv' paises = ("ITALIA") pais=("MARRUECOS") lectura = lee_datos_extranjeria(ruta) nacionalidades = numero_nacionalidades_distintas(lectura) distritos_secciones = secciones_distritos_con_extranjeros_nacionalidades(lectura,paises) num_por_pais = extranjeros_por_p...
Python
1