text
string
label_name
string
labels
int64
from flask import Flask, jsonify, request import pandas as pd app = Flask(__name__) # Read the CSV file into a pandas DataFrame my_books_df = pd.read_csv(r"F:\Full Stack Development\datasets\Bookss.csv") # Convert the DataFrame to a list of dictionaries books_dict = my_books_df.to_dict(orient='records') # Display t...
Python
1
id)}* """) # 保存到历史记录 save_to_history(query, result.answer, result.sources, generation_time) # 操作按钮 render_response_actions(result.answer, query) except Exception as e: st.error(f"生成失败: {str(e)}") def render_streaming_respon...
Python
1
d to generate tBUF and tSU:STA timings. // Sets TIMINGR reg, SCLL field. let scll = scll_val - 1; // SCL high period (master mode) // This field is used to generate the SCL high period in master mode. // tSCLH = (SCLH+1) x tPRESC // Note: SCLH is also used to generate tS...
Rust
0
_index``` function if algo == -1, the best algo will be chosen by CUDNN Returns ------- y: Tensor The result tensor """ oshape = conv2d_output_shape(tensor_format, pad_h, pad_w, stride...
Python
1
53 => EV1_SELR::AUX_TIMER1_EV, 52 => EV1_SELR::AUX_TIMER2_PULSE, 51 => EV1_SELR::AUX_TIMER2_EV3, 50 => EV1_SELR::AUX_TIMER2_EV2, 49 => EV1_SELR::AUX_TIMER2_EV1, 48 => EV1_SELR::AUX_TIMER2_EV0, 47 => EV1_SELR::AUX_COMPB, 46 => EV1_SELR::...
Rust
0
_key >= end_key { return Ok(()); } let handle = get_cf_handle(&self.0, cf)?; self.0 .delete_files_in_range_cf(handle, start_key, end_key, false)?; delete_all_in_range_cf( &self.0, cf, start_key, end_key, false, /* use_delete_range*/ ) } ...
Rust
0
""" ) with gr.Accordion("Similarity", open=False): gr.Markdown("""Discard images with low similarity or no faces :""") with gr.Row(): check_similarity = gr.Checkbox( False, placeholder="discard", ...
Python
1
r { left, right, op } => { match rename_expr_root_name(left, new_name.clone()) { Err(_) => rename_expr_root_name(right, new_name).map(|right| Expr::BinaryExpr { left: Box::new(*left.clone()), op: *op, right: Box::new(right), ...
Rust
0
.replace(&word, template); if result != word { return result.to_string(); } } return word; } } lazy_static! { static ref DEFAULT: Mutex<Pluralizer> = Mutex::new(Pluralizer::new()); } pub fn plural_of<S:Into<String>>(word:S, count:i32) -> String { r...
Rust
0
2_term: Array1<N> = p .quadpole_comp .iter() .map(|&i| eps_ij_t[[i, i]] * p.sigma[i].powi(4) * p.q2[i]) .collect(); // mean segment number let mut mdq1 = Array2::zeros((p.ndipole, p.nquadpole)); let mut mdq2 = Array2::zeros((p.ndipole, p.nquadpole)); let mut mdq...
Rust
0
new(fov: f32, znear: f32, zfar: f32, eye: Pnt3<f32>, at: Pnt3<f32>) -> InertialCamera { let mut fp = FirstPerson::new_with_frustrum(fov, znear, zfar, eye, at); fp.set_move_step(0.0); InertialCamera { cam: fp, acceleration: 200.0f32, deceleration: 0....
Rust
0
import molgraph from molgraph.chemistry import MolecularGraphEncoder from molgraph.chemistry import Featurizer from molgraph.chemistry import features # Define atomic encoders atom_encoder = Featurizer([ features.Symbol({'C', 'N', 'O'}, oov_size=1), features.Hybridization({'SP', 'SP2', 'SP3'}, oov_size=1), ...
Python
1
], config) messages = state["messages"] + [response] # Extract any tool calls from the response if hasattr(response, "tool_calls") and response.tool_calls and len(response.tool_calls) > 0: tool_call = response.tool_calls[0] # Handle tool_call as a dictionary rather than an object ...
Python
1
let mut batch = GeomBatch::new(); batch.extend(Color::RED.alpha(0.5), overlap); batch.upload(ctx) } // TODO OriginalRoad is dangerous, as this map changes. :\ fn find_short_roads(model: &Model) -> HashSet<OriginalRoad> { // Assume the full map has been built. We really care about short lanes there. ...
Rust
0
::new(1,2,3); /// let p = Point3i::from(c); /// assert_eq!(c.x , p.x()); /// assert_eq!(c.y , p.y()); /// assert_eq!(c.z , p.z()); /// let c = cgmath::Vector3::<f32>::new(1.0,2.0,3.0); /// let p = Point3f::from(c); /// assert_eq!(c.x , p.x()); /// assert_eq!(c.y , p.y()); /// assert_...
Rust
0
| str): identity of activity execution included in scenario depth: (int): specifies how many related entities will be traversed to create the response dataset_id (int | str): name of dataset Returns: Result of request as Scenario object """ raise Exception("...
Python
1
@p alpha and @p beta ignored"] #[doc = " - #dnnl_eltwise_sqrt: @p alpha and @p beta ignored"] #[doc = " - #dnnl_eltwise_linear: @p alpha -- scale, @p beta -- shift"] #[doc = " - #dnnl_eltwise_bounded_relu: @p alpha -- upper bound, @p beta ignored"] #[doc = " - #dnnl_eltwise_soft_relu: @p alpha and @...
Rust
0
e((2, 2))); assert_todo_lines!( lines, "pick aaa c1", "pick bbb c2", "pick ccc c3", "pick ddd c4", "pick eee c5" ); } #[test] fn undo_redo_add_range_start_index_at_top() { let mut history = History::new(10); history.record(HistoryItem::new_add(0, 1)); let mut lines = create_lines(); assert_eq!(histor...
Rust
0
epochs, train_accuracy, 'o-',color="b",label='Training Accuracy') plt.plot(epochs, val_accuracy, 'o-',color="green", label='Validation Accuracy') plt.title('Training and Validation Accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() #/////////////////////////////////////////////////////////...
Python
1
uchsia_io::OPEN_RIGHT_READABLE | fidl_fuchsia_io::OPEN_RIGHT_ADMIN, ) .or_else(|e| Err(format!("Could not get admin access {:?}", e)))?; let proxy = fidl_fuchsia_io::DirectoryAdminProxy::new( proxy.into_channel().or_else(|e| Err(format!("Could not extract channel {:?}", e)))?, ...
Rust
0
""" Safely decodes a encoded text stream back into a list of messages. If the encoded text stream contained an invalid hash or was in an invalid format, ``None`` is returned. """ if not data: return None bits = data.split('$', 1) if len(bits) == ...
Python
1
)); assert_ok!(VCU::destroy_oracle_account_minting_vcu( RawOrigin::Root.into(), 1, 1 )); }); } #[test] fn destroy_oracle_account_minting_vcu_not_work_for_non_existing_key() { new_test_ext().execute_with(|| { assert_noop!( VCU::destroy_orac...
Rust
0
#!/usr/bin/env python3 to_kv = __import__('7-to_kv').to_kv print(to_kv.__annotations__) print(to_kv("eggs", 3)) print(to_kv("school", 0.02))
Python
1
= 0) || (k == 0) || (i >= self.p_grid.grid_shape.0 - 1) || (j >= self.p_grid.grid_shape.1 - 1) || (k >= self.p_grid.grid_shape.2 - 1) } /// Returns weather velocity component c at position i, j, k is on or outside the boundary. pub fn is_boundary_velocity(&self, c: &Compon...
Rust
0
(VarEnv::Profile), Some(VarEnv::Dotfile) ]), name: ByteSpan::new(13usize, 20usize), } ); // invalid env / var_name assert!(parse_var("!FOO_BAR", 10).is_err()); // duplicate env assert!(parse_var("&&FOO_BAR", 0).is_err()); Ok(()) } #[test] fn parse_others() -> Result<()> { crate::tests::setup_test_...
Rust
0
from __future__ import annotations import pytest from great_expectations.compatibility.pyspark import types as pyspark_types from great_expectations.datasource.fluent.serializable_types.pyspark import ( SerializableStructType, ) @pytest.fixture def skip_if_spark_not_selected(test_backends) -> None: # NOTE: ...
Python
1
建省闽侯县"); map.insert("350122", "福建省连江县"); map.insert("350123", "福建省罗源县"); map.insert("350124", "福建省闽清县"); map.insert("350125", "福建省永泰县"); map.insert("350126", "福建省长乐县"); map.insert("350127", "福建省福清县"); map.insert("350128", "福建省平潭县"); map.insert("350181", "福...
Rust
0
eadMountedDevice for Headset<'context> { fn product_name(&self) -> &'static str { dispatch! { self => product_name() } } fn orientation(&self) -> math::Quaternion { dispatch! { self => orientation() } } fn button(&self, button: input::Button) -> input::ButtonState { dispatc...
Rust
0
import yaml def cargar_arbol(archivo): with open(archivo, "r", encoding="utf-8") as file: return yaml.safe_load(file) def normalizar_respuesta(respuesta): return respuesta.strip().lower() def adivinar_figura(arbol): while True: print("Piensa en una figura de la lista: cuadrado, rombo,...
Python
1
g.teams = teams config.team_spec = lambda x: teams[x] config.team_name = lambda x: teams[x] config.team_group = lambda x: x config.viewer = 'ascii' config.size = 'small' config.print = mock_print config.tournament_log_folder = None result = tournament.sta...
Python
1
#변수 : 값을 담는 상자(이름을 가진다) x= 4; y=5 print(x + y) #9 print(type(x)) x= x-1 print(x) #3
Python
1
AxisAlignedBoundingBox { pub x_min: f32, pub x_max: f32, pub y_min: f32, pub y_max: f32, pub z_min: f32, pub z_max: f32, } impl AxisAlignedBoundingBox { pub fn from_min_max(min: nalgebra_glm::Vec3, max: nalgebra_glm::Vec3) -> Self { Self { x_min: min.x, y_min: min.y, z_min: min.z, x_max: max.x, ...
Rust
0
chunk_size = fsize % chunk_size; } println!("seek: {}, chunk: {}", seek, chunk_size,); parts.push((seek, chunk_size)); seek += chunk_size; } let mut tasks = FuturesUnordered::new(); for (pos, part) in parts.iter().enumerate() { tasks.push(read_file(&file_path, ...
Rust
0
from fastapi import APIRouter, Depends, HTTPException, Query from typing import List, Optional from sqlite3 import Connection from models import Document from tools import get_db router = APIRouter() # Route pour créer un nouveau document @router.post("/", response_model=Document, tags=["Document"]) def create_docum...
Python
1
} #[test] fn test_color() { let s = "Hello world"; assert_eq!("\x1B[38;5;1mHello world\x1B[0m".to_owned(), s.color(Color::Red).to_string()); assert_eq!("\x1B[38;5;220mHello world\x1B[0m".to_owned(), s.color(Color::Red).color(Color::Gold1).to_string()); } #[test] fn test_bg_color() { let s = "Hello wo...
Rust
0
32_t, pub handle: uint32_t } // Defined in /usr/include/libdrm/drm.h as struct drm_clip_rect #[repr(C)] pub struct drmModeClip { pub x1: c_ushort, pub y1: c_ushort, pub x2: c_ushort, pub y2: c_ushort } #[repr(C)] pub struct drmModePropertyBlob { pub id: uint32_t, pub length: uint32_t, ...
Rust
0
x9d, 0xa8, 0x60, 0x8c, 0xad, 0xe9, 0x2d, 0xfb, 0x9a, 0xc0, 0xef, 0x90, 0x21, 0xba, 0x5d, 0x13, 0x3e, 0x58, 0x4b, 0xbc, 0x11, 0xd3, 0xdd, 0x2e, 0xe6, 0x89, 0x61, 0x87, 0x26, 0xd6, 0x88, 0xed, 0x40, 0xbd, 0x3, 0x5, 0xc9, 0x8a, 0x88, 0x44, 0x1f, 0x87, 0x86, 0x0, 0xcc, 0xb7, 0x4a, 0xf0, 0x98...
Rust
0
, 4, 5]; for i in data.iter() { ordered.push(*i); } println!("{}", ordered.get(0).unwrap()); //assert_eq!(*ordered.get(0).unwrap(), -2); assert_eq!(*(ordered.get(0).unwrap()), -2); assert_eq!(*(ordered.get(1).unwrap()), -1); assert_eq!(*(ordered.get(...
Rust
0
as _; impl<T: Config> ::frame_support::traits::GetPalletVersion for Module<T> { fn current_version() -> ::frame_support::traits::PalletVersion { frame_support::traits::PalletVersion { major: 3u16, minor: 0u8, patch: 0u8, } } fn storage_version() -> Option...
Rust
0
from skeleton import Joint import numpy as np def read_line(stream, idx): if idx >= len(stream): return None, idx line = stream[idx].strip().split() idx += 1 return line, idx def parse_asf(file_path): '''read joint data only''' with open(file_path) as f: content = f.read().splitlines() for id...
Python
1
pulation = new_population # Append values, show progress if not tune_mode: # Append the plot information best_fitnesses.append(np.max(fitnesses)) avg_fitnesses.append(np.mean(fitnesses)) worst_fitnesses.append(np.m...
Python
1
from __future__ import annotations from typing import TYPE_CHECKING import streamlit as st from .. import extra if TYPE_CHECKING: from streamlit.delta_generator import DeltaGenerator @extra def bottom() -> DeltaGenerator: """ Insert a multi-element container that sticks to the bottom of the app. ...
Python
1
t::contract_api::runtime; use types::ApiError; const ARG_NUMBER: &str = "number"; #[no_mangle] pub extern "C" fn call() { let number: u32 = runtime::get_named_arg(ARG_NUMBER); runtime::revert(ApiError::User(number as u16)); } <reponame>hawkw/mnemosyne<gh_stars>10-100 // // 0 1 0 Mnemosyne: a functional syste...
Rust
0
(BTreeSet<isize>, BTreeSet<isize>, BTreeSet<isize>)> = Vec::new(); for i in 0..commands.len() { let bbox = commands[i].1; coords.push(( BTreeSet::from([bbox.xmin, bbox.xmax]), BTreeSet::from([bbox.ymin, bbox.ymax]), BTreeSet::from([bbox.zmin, bbox.zmax]), ...
Rust
0
per(self.left_w_ratio), right_w_ratio: mapper(self.right_w_ratio), top_h_ratio: mapper(self.top_h_ratio), bottom_h_ratio: mapper(self.bottom_h_ratio), } } } /// if it is off the screen, scroll so it is inside an at least `char_dim` sized apron inside /// from the edge of...
Rust
0
fn try_enter_raffle( deps: DepsMut, info: MessageInfo, entering_address: &str, ) -> Result<Response, ContractError> { let validated = deps.api.addr_validate(entering_address)?; // admin can enter any address // info.sender can enter their own address let state = STATE.load(deps.storage)?; ...
Rust
0
} pub fn scaled(&self, other: &Scalar) -> Self { Self(other.0 * self.0) } pub fn generator() -> Self { Self(curve25519_dalek::constants::RISTRETTO_BASEPOINT_POINT) } } impl AsBase64 for CurveElem { type Error = CryptoError; fn as_base64(&self) -> String { bas...
Rust
0
from binance.um_futures import UMFutures import pandas as pd from time import sleep from time import time from binance.error import ClientError client = UMFutures() def get_tickers_usdt(): try: tickers = [] resp = client.ticker_price() for elem in resp: if 'USDT' in elem['symb...
Python
1
############################################################################### # # OpenEduCat Inc # Copyright (C) 2009-TODAY OpenEduCat Inc(<https://www.openeducat.org>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License a...
Python
1
_code == 401: sys.stdout.write('[+]code 401 : %s\n' % url) except: pass # 定义队列及放入URL def start(url, ext, count,ip): queue = Queue() f = open('%s.txt' % ext, 'r') for i in f: queue.put(url + i.rstrip('\n')) # 多线程 threads = [] thread_coun...
Python
1
ng(), input_string_language_1.to_string()) .with_query_param("input_string_language_2".to_string(), input_string_language_2.to_string()) .with_query_param("model".to_string(), model.to_string()) .execute(self.configuration.borrow()) } fn get_versions_text_text_word_alignment...
Rust
0
def find_blank(board): for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == '_': return i, j def is_valid_move(board, i, j): return 0 <= i < len(board) and 0 <= j < len(board[0]) def swap(board, i1, j1, i2, j2): board[i1][j1], board[i2][j2] = bo...
Python
1
P", *b"TWEER", *b"TWERK", *b"TWERP", *b"TWIER", *b"TWIGS", *b"TWILL", *b"TWILT", *b"TWINK", *b"TWINS", *b"TWINY", *b"TWIRE", *b"TWIRP", *b"TWITE", *b"TWITS", *b"TWOER", *b"TWYER", *b"TYEES", *b"TYERS", *b"TYIYN", *b"TYKES", *b"TYLER", *b"TYMPS", *b"TYNDE", *b"TYNED", *b...
Rust
0
[4., 16.] and the height is in the range [2., 16.]. If necessary, the default height is adjusted to ensure this. Parameters ---------- arg : float or 2D array If a float, this defines the aspect ratio (i.e. the ratio height / width). In case of an array the aspect ratio is numbe...
Python
1
lambda_x / lambda_y def ptransp_(self, x, y, u, c): lambda_x = self._lambda_x(x, c) lambda_y = self._lambda_x(y, c) return self._gyration(y, -x, u, c) * lambda_x / lambda_y def ptransp0(self, x, u, c): lambda_x = self._lambda_x(x, c) return 2 * u / lambda_x.clamp_min(se...
Python
1
# 配置日志 loguru.logger.add("scraper.log", rotation="10 MB") # 创建爬虫实例,headless=True表示无界面模式 scraper = PlaywrightScraper(headless=True) try: # 要爬取的网址 target_url = "https://blog.sciencenet.cn/blog-2089193-1469701.html" target_url = "https://blog.csdn.net/2401_85375151/article/deta...
Python
1
import brownie from brownie import ZERO_ADDRESS import pytest PRICE = 100 @pytest.mark.parametrize("price", [0, 100, 1e18]) def test_accept_buy_offer(market, token_id, token, alice, price, bob): bob_initial_balance = bob.balance() alice_initial_balance = alice.balance() expected_royalties = (price * toke...
Python
1
from __future__ import print_function import json import numpy as np from sklearn.metrics import accuracy_score from sklearn.linear_model import LogisticRegression from networkx.readwrite import json_graph def run_regression(train_embeds, train_labels, test_embeds, test_labels): log = LogisticRegression(so...
Python
1
fn new(hitable: Hitable<'a>, density: f32, albedo: &'a Texture<'a>) -> Self { let phase_function = isotropic(albedo); Self { hitable, phase_function, density, } } pub fn bounding_box(&self, t0: f32, t1: f32) -> Option<AABB> { self.hitable.bou...
Rust
0
import telebot import sqlite3 import qrcode from io import BytesIO import os from dotenv import load_dotenv load_dotenv() TOKEN = os.getenv("TOKEN") bot = telebot.TeleBot(TOKEN) # Создаем таблицу пользователей (если нет) def init_db(): with sqlite3.connect("users.db") as conn: conn.execute(''' ...
Python
1
def solve(grid): h, w = len(grid), len(grid[0]) bg = grid[0][0] axis = next(c for c in range(w) if len({grid[r][c] for r in range(h)}) == 1 and grid[0][c] != bg) out = [row[:] for row in grid] for r in range(h): for c in range(axis): v = grid[r][c] if v != bg: ...
Python
1
let msg = InstantiateMsg { post_count: 0 }; let info = mock_info("creator", &coins(2, "token")); let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); // Any address that isn't the contract owner is unauthorized to blacklist any user. let info = mock_info("anyone...
Rust
0
# Inference code generated from the JSON schema spec in @huggingface/tasks. # # See: # - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts # - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks. from dataclasses import d...
Python
1
println!("unknown") ; self.nl() } /// Logs a `unknown` end of analysis without any unknown properties. pub fn just_log_unknown(& self) { let pref = format!( "{} {}", self.fmt.ppre(), self.mk_sad( self.fmt.pref() ) ) ; println!( "{} {}", pref, self.mk_sad( "...
Rust
0
MDv0 { let raw: *mut u8 = transmute(&self._data_); transmute(raw.offset(0)) } } impl Clone for lcb_server_stats_cmd_st_u { fn clone(&self) -> Self { *self } } impl Default for lcb_server_stats_cmd_st_u { fn default() -> Self { unsafe { zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct lc...
Rust
0
next_page += f"&task_id={str(task_id)}" if model_id is not None: next_page += f"&model_id={str(model_id)}" response["next_page"] = next_page return response @staticmethod def video_prediction_properties_to_rest( video_prediction_properties: ...
Python
1
the License. use std::collections::{HashMap, HashSet}; use std::net::SocketAddr; use std::sync::{mpsc, Arc, RwLock}; use std::time::Duration; use std::boxed::FnBox; use grpc::EnvBuilder; use tempdir::TempDir; use super::cluster::{Cluster, Simulator}; use tikv::config::TiKvConfig; use tikv::server::{Server, ServerTr...
Rust
0
# main.py import config from dependency_manager import check_and_install_dependencies # Check and install dependencies before importing other modules check_and_install_dependencies() from json_processor import ( select_json_file, load_json_file, extract_content, save_output, update_data_structure...
Python
1
.170, 0.170, ]; #[cfg(test)] mod tests { use super::*; use super::CoefBlock; use descramble::{Bootstrap, descramble}; use params::BaseParams; use gain::Gains; #[test] fn verify_amps() { // Verify the constaints on J_i [p33]. for l in 9..=56 { let amps = &AM...
Rust
0
nd its difficulty's lower than ours, /// we're sure this peer is a stuck node, and we will kick out such kind of stuck peers. pub const STUCK_PEER_KICK_TIME: i64 = 2 * 3600 * 1000; /// If a peer's last seen time is 2 weeks ago we will forget such kind of defunct peers. const PEER_EXPIRATION_DAYS: i64 = 7 * 2; /// Con...
Rust
0
Pin}; // Modules // ---------------------------------------------------------------------------- #[cfg(doc)] #[doc = include_str!("../CHANGELOG.md")] pub mod _changelog_ {} #[cfg(feature = "alloc")] #[cfg_attr(feature = "doc_cfg", doc(cfg(feature = "alloc")))] pub mod arc; #[cfg(feature = "alloc")] #[cfg_attr(featur...
Rust
0
from aiofiles import open as aiopen from aiofiles.os import remove def filter_links(links_list: list, bulk_start: int, bulk_end: int) -> list: if bulk_start != 0 and bulk_end != 0: links_list = links_list[bulk_start:bulk_end] elif bulk_start != 0: links_list = links_list[bulk_start:] elif ...
Python
1
])) radar_right_index = np.argmax(radar_time >= (timestamp[1])) radar_right_index += 1 radar_data = frames[radar_left_index:radar_right_index] print(radar_data.shape, radar_time.shape) radar_image = np.zeros((timestamps.shape[0]-1,RBINS,ABINS_RADAR)) for i in range(timestamps.shape[0]-1): ...
Python
1
The starting 4D offset to copy from `src`. /// - `dst`: The destination slice. /// - `dst_shape`: A `Shape<4, Coord=u32>` for the entire `dst` slice. /// - `dst_start`: The starting 4D offset to copy into `dst`. #[inline] pub fn copy4<T, Src, Dst>( copy_shape: [u32; 4], src: &[T], src_shape: &Src, src_...
Rust
0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models from odoo.addons.stock_landed_costs.models.stock_landed_cost import SPLIT_METHOD from odoo.exceptions import UserError from odoo import _ class ProductTemplate(models.Model): _inheri...
Python
1
import os import torch import numpy as np from pynvml import * # GET [gpu_ids] OF ALL AVAILABLE GPUs def get_available_devices(): if torch.cuda.is_available(): # GET AVAILABLE GPUs RESOURCES gpu_ids = [] gpu_ids += [gpu_id for gpu_id in range(torch.cuda.device_count())] # RANK THO...
Python
1
# no.9 reverse the string a = input("Enter the string: ").split() for i in range(len(a)): a[i] = a[i][::-1] print(" ".join(a))
Python
1
"""ZigBee Scan command handler """ from prompt_toolkit import print_formatted_text, HTML from whad.cli.app import command from whad.dot15d4.address import Dot15d4Address from whad.zigbee.connector.enddevice import EndDevice @command('scan') def scan_handler(app, command_args): """scan for ZigBee networks <an...
Python
1
"""Grab the global logger instance.""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from __future__ import annotations import logging from typing import Any _logger: logging.Logger | logging.LoggerAdapter[Any] | None = None def get_logger() -> logging.Logger ...
Python
1
testname = test_get_name(filepath) if not os.path.exists(output_filepath) or os.path.getsize(output_filepath) == 0: errors.append("NO OUTPUT") print_message("No render result file found") print_message(testname, 'FAILURE', 'FAILED') ...
Python
1
#!/usr/bin/env python import sys import math import pandas as pd def vivado_timing_estimate_max_freq(summary_csv, intra_csv, output_csv): df_summary = pd.read_csv(summary_csv, index_col=0) df_intra = pd.read_csv(intra_csv, index_col=0) table = { "Clock": [], "Period(ns)": [], "F...
Python
1
::HcFmInterval); let frame_interval = fm_interval_val & 0x3FFF; // Perform a hardware reset (and get controller from the firmware) // SAFE: Read is safe let hc_control = io.read_reg(hw::Regs::HcControl); if hc_control & 0x100 != 0 { // SMM emulation currently controls the host // SAFE: No memory a...
Rust
0
'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | ((value as u32 & 0x01) << 1); self.w } } #[doc = "Field `cr_urx_en` reader - "] pub struct CR_URX_EN_R(crate::FieldReader<bool, bool>); impl CR_URX_EN_R { pub(crate) fn new(bits: bool) -> Self { CR_URX_EN_R(crate::FieldReader::new(b...
Rust
0
_put::<Arc<Node<u32, u32, u32>>>() .once() .withf(move |cacheable, _compression, txg| { let node_data = cacheable.0.try_read().unwrap(); let int_data = node_data.as_int(); int_data.children[0].key == 0 && !int_data.children[0].ptr.is_mem() && i...
Rust
0
Component>(&self, entity: Entity) -> Result<RefMut<'_, T>, QueryError> { let location = match self.world.get_entity_location(entity) { None => return Err(QueryError::ComponentError(ComponentError::NoSuchEntity)), Some(location) => location, }; if self .arche...
Rust
0
op.inputs.property_fields_container_element_types(my_property_fields_container_element_types) """ return self._property_fields_container_element_types class OutputsMapdlSplitToAcmoFacetIndices(_Outputs): """Intermediate class used to get outputs from mapdl_split_to_acmo_facet_indices operator....
Python
1
""" 代码中有从网络上参考或者直接复制过来的内容,对原作者致以谢意! 但因时间有些久了,来源无法一一追溯,故没有列出来源。报以歉意! """ # simtext相似度: # simtext可以计算两文档间四大文本相似性指标,分别为: # Sim_Cosine cosine相似性 # Sim_Jaccard Jaccard相似性 # Sim_MinEdit 最小编辑距离 # Sim_Simple 微软Word中的track changes # import sys import re import string from zhon.hanzi import punctuation as chinese...
Python
1
description("Invalid argument"), display("Invalid argument(s): {}", msg) } LockPoisoned(msg: String) { description("Lock poisoned"), display("Lock poisoned: {}", msg) } } foreign_links { Io(::std::io::Error) #[cfg(unix)]; Proto(::proto...
Rust
0
Mail # -------------------------------------------------- try: me = json.loads(requests.get("https://graph.microsoft.com/v1.0/me/memberOf", headers={ 'Content-Type': 'application/json', ...
Python
1
#[serde(alias = "nm")] name: String, } #[test] fn JSONを構造体にdeserialize() { let expected = Human { id: 1, name: "Ichiro".to_string(), }; assert_eq!( expected, serde_json::from_str(r#"{"id":1,"full_name":"Ichiro"}"#).unwrap(...
Rust
0
import re from src.model.item import Item class Parser: @staticmethod def parse(text: str): text = text.replace("\r\n", "\n").replace("\r", "\n") item = Item() sections = text.split("--------\n") # Base match = re.search(r'Item Class:\s*(.+)', sections[0]) ...
Python
1
from view import View v = View()
Python
1
# -*- coding=utf-8 -*- from unittest.mock import Mock from zettarepl.snapshot.task.nonintersecting_sets import tasks_intersect def test__tasks_intersect__same_dataset(): t1 = Mock(dataset="data/work") t2 = Mock(dataset="data/work") assert tasks_intersect(t1, t2) def test__tasks_intersect__different_dat...
Python
1
oint<T>) -> bool { self.0 == other.x && self.1 == other.y } } impl<T> PartialEq<Point<T>> for [T; 2] where T: PartialEq, { fn eq(&self, other: &Point<T>) -> bool { self[0] == other.x && self[1] == other.y } } impl<T, U> std::ops::Add<U> for Point<T> where T: std::ops::Add<T, Output...
Rust
0
= S7AreaMK. /// word_len = S7WLBytes. /// ``` /// /// **输入参数:** /// /// - start: 开始读取的字节索引 /// - size: 要读取的字节长度 /// - buff: 待写入数据缓冲区 /// /// **返回值:** /// /// - Ok: 操作成功 /// - Err: 操作失败 /// /// `注:如果你需要传输一个大的数据,你可以考虑使用异步的 as_mb_write()。` /// p...
Rust
0
2][1] &= v.z() <= v.w(); outside[0][0] &= v.x() < -v.w(); outside[1][0] &= v.y() < -v.w(); outside[2][0] &= v.z() < -v.w(); outside[0][1] &= v.x() > v.w(); outside[1][1] &= v.y() > v.w(); outside[2][1] &= v.z() > v.w(); } if outside.iter().any(|&x| x.iter().any...
Rust
0
".to_string()); assert_eq!(0, r6); let r7 = my_atoi("+1".to_string()); assert_eq!(1, r7); let r8 = my_atoi("+".to_string()); assert_eq!(0, r8); let r9 = my_atoi(" +0 123".to_string()); assert_eq!(0, r9); let r10 = my_atoi("-5-".to_string()); assert_eq!(-5, r10); let r11 = my_at...
Rust
0
^\x838\xf3\xc2\xb1\x87E\xc0\ \xe4\x81\x97P\xa6rJt\xfag\xfe!v\x9c;o\ \x96\x01\xa3\x8c\xd6p \x18\x96\xb7-\x5c\xbc\xea\x9d?\ \xfd\xe5&\xfb\xbd\x96\x0b\x98\x85\x87=\xd1\xf0\xa9\xfb\x1e\ \xc6bc\xb0\x84Af\x12\xb07\x0a\xa9\xe5P(r\ \xb5\xb9\xe7x\xf0\xba\x0f\xfe\x89\xbe\x8a n\xa5\xc1<\ \xb6i\xdd\xdc\xb9\xdf\xe8\xd3\x1c\xb1\xb1-...
Python
1
from score_models.sde import VESDE, VPSDE, TSVESDE import numpy as np import torch def get_trajectories(sde, B=10, N=100, x0=5): dt = 1/N t = torch.zeros(B) + sde.epsilon x0 = torch.ones(B) * x0 x = torch.clone(x0) trajectories = [x] marginal_samples = [x] for step in range(N): t +=...
Python
1
let instance = jvm.create_instance("java.lang.String", instantiation_args.as_ref()).unwrap(); let ref tid_from_java: String = jvm.to_rust(instance).unwrap(); assert!(&tid == tid_from_java); } { let jvm: Jvm = super::new_jvm(Vec::new(), ...
Rust
0