text
string
label_name
string
labels
int64
Some(ValType::Depth) => Token::Depth(val), Some(ValType::RangeWithEnd(end)) => Token::Range{ start: val, end: end + T::one() }, Some(ValType::RangeWithLen(len)) => Token::Range{ start: val, end: val + len + T::one()}, } } )(buf) } // Tokenize. // With 'nom', I don't know if i...
Rust
0
# pygame.math module, pygame.math.Vector2 object # https://www.pygame.org/docs/ref/math.html # # How to detect the collision of circles or balls in Pygame? # https://stackoverflow.com/questions/63145493/how-to-detect-the-collision-of-circles-or-balls-in-pygame # # GitHub - PyGameExamplesAndAnswers - Collision and Inter...
Python
1
support IPV6 sockets and actually has a quota on the # number of sockets that can be used, so just early out here instead of # creating a socket needlessly. # See https://github.com/urllib3/urllib3/issues/1446 if _appengine_environ.is_appengine_sandbox(): return False if socket.has_ipv6: ...
Python
1
{ ::std::mem::transmute(self._bitfield_1.get(40usize, 8u8) as u32) } } #[inline] pub fn set_src_pid(&mut self, val: u32) { unsafe { let val: u32 = ::std::mem::transmute(val); self._bitfield_1.set(40usize, 8u8, val as u64) } } #[inline] pub fn lbid(&self) -...
Rust
0
from datetime import datetime import flet as ft from icecream import ic from .database import get_bookings_from_user_id, get_profile_pic_and_name def gen_text(text, size, weight="normal"): return ft.Text( spans=[ ft.TextSpan( text, ft.TextStyle( ...
Python
1
} fn area(&self, a_on_d: f64, _a_on_c: f64, _c_on_b: f64, _a_on_r: f64) -> f64 { PI * a_on_d.powi(2) / 4.0 } } /// Semi-elliptical beta factor for an edge crack. /// Where *a* is the depth of crack, *2c* is the surface length of the crack, /// *`a_on_c` = a/c* and `phi` are the angle to a point o...
Rust
0
# -*- coding: utf-8 -*- # # Copyright 2017 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
def print_square_star_pattern(n): for i in range(n): for j in range(n): print("* ", end="") print() n = 4 print_square_star_pattern(n)
Python
1
, UnvalidatedBitField>); impl PartitionSectorMap { /// Records the given sectors at the given partition. pub fn add_values( &mut self, partition_idx: u64, sector_numbers: Vec<u64>, ) -> anyhow::Result<()> { self.add(partition_idx, BitField::try_from_bits(sector_numbers)?.int...
Rust
0
# # https://github.com/richardkiss/pycoinnet/ # # The MIT License (MIT) # # Copyright (c) 2014 Richard Kiss # # 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 wi...
Python
1
&self))?; let source_node: EndpointID = seq .next_element()? .ok_or_else(|| de::Error::invalid_length(2, &self))?; let timestamp: CreationTimestamp = seq .next_element()? .ok_or_else(|| de::Error::invalid_...
Rust
0
x = {'image0': torch_gray0, 'image1': torch_gray1} pred = pipeline_model(x) pred = batch_to_np(pred) kp0, kp1 = pred["keypoints0"], pred["keypoints1"] m0 = pred["matches0"] line_seg0, line_seg1 = pred["lines0"], pred["lines1"] line_matches = pred["line_matches0"] valid_matches = m0 != -...
Python
1
# run in windows command prompt: python -m streamlit run Start.py import streamlit as st st.set_page_config( page_title="Course Query Chatbot", page_icon="👋", ) st.write("# Welcome to Course Query Chatbot! 👋") st.text("by David Seow 15 Sep 2024") # st.sidebar.success("Select a demo above.") st.markdown( ...
Python
1
format!("/edit/tag/{}", tag_id.to_string()) } pub fn delete_path(tag_id: &picvudb::data::TagId) -> String { format!("/delete/tag/{}", tag_id.to_string()) } } impl PageResources for TagPages { fn page_resources(builder: &mut PageResourcesBuilder) { builder .rout...
Rust
0
from core.analysis.rules_engine import RulesEngine class Scorer: def __init__(self, report_text: str): self.report_text = report_text self.rules_engine = RulesEngine(report_text) def compute_score(self, findings: list, insights: list) -> float: """ Computes a simple compliance ...
Python
1
from .._tier0 import plugin_function from .._tier0 import Image from .._tier0 import push from .._tier1 import replace_intensities from .._tier1 import set_column @plugin_function(categories=['combine', 'label measurement', 'map', 'in assistant'], priority=-1) def label_minimum_intensity_map(intensity_image : Image, l...
Python
1
u8>) -> Vec<u8> { match usb_in.split_first() { Some((&OP_UNLOCK, b"")) => return api_unlock().await, Some((&OP_ATTESTATION, rest)) => return api_attestation(rest), _ => (), } // No other message than the attestation and unlock calls shall pass until the device is // unlocked or ...
Rust
0
f64(0.0) ); { let mut file = WhisperFile::open(&path)?; file.update_many( &[Point { interval: 0x5b171b01, value: 123.0, }], 0x5b171b04, )?; } assert_eq!( fs::read(&path)?, header .cl...
Rust
0
.get::<HttpStreamResource>(rid)?; let mut wr = RcRef::map(&stream, |r| &r.wr).borrow_mut().await; take(&mut *wr); Ok(()) } async fn op_http_read( state: Rc<RefCell<OpState>>, rid: ResourceId, mut buf: ZeroCopyBuf, ) -> Result<usize, AnyError> { let stream = state .borrow_mut() .resource_table ...
Rust
0
_id.typed_chain_id(); let tree_id_u32: u32 = match resource_id.target_system() { TargetSystem::TreeId(tree_id) => tree_id, _ => 0, }; let tree_id = TreeId::try_from(tree_id_u32).unwrap_or_default(); // returns the underlying chain id // the underlying chain id will be used to get the actual chain id(Substrat...
Rust
0
out = self.mask_head(body_feats, bbox, bbox_num, self.inputs) origin_shape = self.bbox_post_process.get_origin_shape() mask_pred = self.mask_post_process(mask_out, bbox_pred, bbox_num, origin_shape) return bbox_pred, bbox_num, mask_pred ...
Python
1
import json import fastapi from app.config import settings from app.core.calculate_repository import CalculateRepository, OptimizationStrategyType from app.models.calculator_input import Cluster, Model, OtherConfig from app.models.calculator_input import InputConfig from app.models.calculator_result import Parameter, ...
Python
1
.run_cycle(); assert!(test.v[0x1] == 0x11); } #[test] fn add_nn_to_vx() { // 0x7xNN let mut test = ::cpu::Cpu::new(); let rom = &[0x71, 0x11]; test.v[0x1] = 0x22; load_vec(&mut test, rom); test.run_cycle(); assert!(test.v[0x1] == 0x33); } #[test] fn set_vx_to_vy() { // 0x8xy0 let a = 5; le...
Rust
0
0, 0, 0, 0, 1, 0, 0, 0, 1, 1], to_bits((3003 as u16).fib_encode().unwrap()) ); } fn check_slice_u8(numbers: Vec<u8>) -> Vec<u8> { to_bits(numbers.fib_encode().unwrap()) } fn check_slice_u16(numbers: Vec<u16>) -> Vec<u8> { to_bits(numbers.fib_encode().unwrap()) } fn check_slice_u32(numbers: Vec<u32...
Rust
0
f64x2 = f64x2::new(1., 2.); let e: f64 = 2.; let r: f64 = transmute(vpmaxqd_f64(transmute(a))); assert_eq!(r, e); } #[simd_test(enable = "neon")] unsafe fn test_vmin_f64() { let a: f64 = 1.0; let b: f64 = 0.0; let e: f64 = 0.0; let r: f64 = transmute...
Rust
0
generation (default: {DEFAULT_DPI})") def main(filename: str, width: int, height: int, no_png: bool, dpi: int) -> None: """Generate ABI reference design for mugs. FILENAME is the output SVG file path (required). \\b Examples: # Generate default SV...
Python
1
).map(Box::new); } let raw = Box::into_raw(b); unsafe { let val = ptr::read(raw); // Box<T> -> Box<MaybeUninit<U>> let mut raw: Box<mem::MaybeUninit<U>> = Box::from_raw(raw.cast()); // If `map` panics or returns an error, `raw` will free the memory associated with `b`, but...
Rust
0
f:(non_ref_text_found() / ref_found()) { f } rule non_ref_text_found() -> UnitRefSearch = t:$((!logical_unit_ref() [_])+) { UnitRefSearch::Text(t.to_string()) } rule ref_found() -> UnitRefSearch = r:logical_unit_ref() { UnitRefSearch::Ref(r) } ...
Rust
0
SG_CTRL_DECRYPT_PARA_u>(), 8); assert_eq!(size_of::<CMSG_CTRL_DECRYPT_PARA>(), 24); assert_eq!(align_of::<CMSG_CTRL_DECRYPT_PARA>(), 8); assert_eq!(size_of::<CMSG_CTRL_KEY_TRANS_DECRYPT_PARA_u>(), 8); assert_eq!(align_of::<CMSG_CTRL_KEY_TRANS_DECRYPT_PARA_u>(), 8); assert_eq!(size_of::<CMSG_CTRL_KEY...
Rust
0
.join(dir_path))?; // Add linebreak at end of file fs::write(cwd.join(path), &(self.rendered_template.clone() + "\n"))?; Ok(()) } fn action_append(&self, location: ExtendLocation) -> RustgenResult<()> { match location { ExtendLocation::BeginOfFile => self.append_beg...
Rust
0
import math name=str(input("Enter your name to use this program.")) print("\n") print(f"Welcome, {name}") print("This program is designed to find the area of a circle.") print("\n") radius=float(input("Enter the value of radius: ")) print(f"You entered radius value: {radius} cm.") area=math.pi*pow(radius,2) print("\n"...
Python
1
return {"result": False, "message": e.message} return {"result": True} def list_tdsql_shards(self, ins_id): params = {"InstanceId": ins_id} resp_data, total, status = self._resource_list("dcdb_shard", params) if status: return {"result": True, "data": self.fo...
Python
1
= g1110 + g1000 + g0100 + g0010 - g0000 - g0111 - g1011 - g1101; let k12 = g1101 + g1000 + g0100 + g0001 - g0000 - g0111 - g1011 - g1110; let k13 = g1011 + g1000 + g0010 + g0001 - g0000 - g0111 - g1101 - g1110; let k14 = g0111 + g0100 + g0010 + g0001 - g0000 - g1011 - g1101 - g1110; let k15 = g1111 + g...
Rust
0
mut b = BytesMut::new(); b.extend_from_slice(buf); let id = YDigest64::from_bytes(b.get(0..64).unwrap())?; let version = YVersion::from_bytes(b.get(64..76).unwrap())?; let time = YTime::from_bytes(b.get(76..84).unwrap())?; let nonce = BigEndian::read_u32(b.get(84..88).unwrap());...
Rust
0
) } } impl uDebug for i32 { fn fmt<W>(&self, f: &mut Formatter<'_, W>) -> Result<(), W::Error> where W: uWrite + ?Sized, { if f.hex.is_some() { <u32 as uDebug>::fmt(&(*self as u32), f) } else { let mut buf: [u8; 21] = [0; 21]; f.write_str(isi...
Rust
0
event_input_pending(true) { // No data pending if helpers::poll(&mut poll_fds, -1) >= 0 { // Read from our "channel" whether we should stop the thread if poll_fds[0].revents & self::libc::POLLIN != 0 { let _res = unsafe { self::libc::read(poll...
Rust
0
# Copyright (c) 2020-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # NVIDIA CORPORATION, its affiliates and licensors retain all intellectual # property and proprietary rights in and to this material, related # documentation and any modifications thereto. Any use, reproduction, # disclosure or distribu...
Python
1
import modules.helper as h import re, os class command: def __init__(self): self.name = "upload" self.description = "upload file" self.usage = "Usage: upload path/to/localfile upload/path" def run(self,session,cmd_data): if not cmd_data['args']: print self.usage...
Python
1
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # ============================ # 1. Ler os dados # ============================ nascidos_vivos = pd.read_csv("nascidos_vivos.csv", index_col=0, sep=';') doses_aplicadas = pd.read_csv("doses_aplicadas_30dias.csv", index_col=0, sep=';') # Conver...
Python
1
# -*- coding: utf-8 -*- import os import pytest from renormalizer.cv import batch_run from renormalizer.cv.zerot import SpectraZtCV from renormalizer.cv.finitet import SpectraFtCV import numpy as np from renormalizer.tests.parameter import holstein_model, holstein_model4 from renormalizer.cv.tests import cur_dir from...
Python
1
-> Comment<'a> { Comment { span } } // GETTERS -----–-----–-----–-----–-----–-----–-----–-----–-----–-----–---- pub fn message(&self) -> &'a str { &self.span_content()[COMMENT_START_TOKEN.len()..] } // SETTERS -----–-----–-----–-----–-----–-----–-----–-----–-----–-----–---- ...
Rust
0
# Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
Python
1
html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://static.rust-lang.org/doc/master")] #![deny(deprecated_owned_vector)] #![feature(macro_registrar, managed_boxes)] extern crate syntax; use syntax::ast; use syntax::ast::Name; use syntax::codemap::{Span, mk_sp}; use syntax::e...
Rust
0
x.with_read(|guard| { if *guard > 0 { ready(Ok(*guard)) } else { ready(Err("Whoops!")) } }).await }); assert_eq!(r, Err("Whoops!")); } #[cfg(feature = "tokio")] #[test] fn with_read_ok() { let mtx = RwLock::<i32>::new(5); let r...
Rust
0
lables. - If we have a positive label, we represent it as `[0, 1]` - If we have a negative label, we represent it as `[1, 0]` """ # Load data from files positive_examples = list(open(positive_data_file, 'r', encoding='utf-8').readlines()) positive_examples = [s.strip() for s in p...
Python
1
'''MobileNetV2 in PyTorch. See the paper "Inverted Residuals and Linear Bottlenecks: Mobile Networks for Classification, Detection and Segmentation" for more details. ''' import torch import torch.nn as nn import torch.nn.functional as F from torchvision import models from torchvision.models import MobileNet_V2_Weight...
Python
1
2].into(); let data = data.try_mapped(|x| 100u8.checked_div(x).ok_or("error")); assert_eq!(data, Err("error")); } #[test] fn try_mapped_ref() { let data: BiBoundedVec<u8, 2, 8> = [1u8, 2].into(); let data = data.try_mapped_ref(|x| 100u8.checked_div(*x).ok_or("error")); assert_eq!(data, Ok([100u8, 50].int...
Rust
0
your message\r\n> ".to_string())); } clients.send(&replies)?; // finish up the tick incoming_messages.clear(); replies.clear(); finish_tick(&tick, &start); println!("--- )))"); } return Ok(()); } <gh_stars>1-10 use primitive_types::{H256, U256}; use evm...
Rust
0
import sys if sys.version_info >= (3, 12, 0): import six sys.modules['kafka.vendor.six.moves'] = six.moves import json from kafka import KafkaConsumer def json_deserializer(data): return json.loads(data.decode("utf-8")) consumer = KafkaConsumer( "test-topic", bootstrap_servers=["localhost:90...
Python
1
from pep600_compliance.images import base, package_manager class Mageia(base.Base): def __init__(self, image, eol, pkg_manager, packages, machines): _, version = image.split(":") self._packages = packages super().__init__(image, "mageia", version, eol, pkg_manager, machines) def insta...
Python
1
&'a mut T, mut b: &'a mut T) -> IOResult<bool> { cmp_read(&mut a, &mut b, 1) } /// Reads n bytes from reader pub fn read_n<T: Read>(mut input: &mut T, buf: &mut [u8], size: u32) -> IOResult<usize> { let mut taken = (&mut input).take(u64::from(size)); let mut read: usize = 0; let mut attempts = 0; while read < si...
Rust
0
pe; use crate::request::Request; use crate::utils::CommandExt as _; pub use info::JobOutputInfo; use jormungandr_integration_tests::common::jcli::JCli; use jortestkit::prelude::read_file; use jortestkit::prelude::ProcessOutput; use serde::{Deserialize, Serialize}; use std::io::Write; use std::path::{Path, PathBuf}; use...
Rust
0
""" 模型结构 如果想要修改网络结构的话在这个文件夹修改即可 """ import torch from torch import nn from classifier.conf.readConfig import Config config = Config().config class CNNBlock(nn.Module): def __init__(self, kernel_size, out_channels=config['hidden_layer']): super(CNNBlock, self).__init__() self.sequential = nn.Sequ...
Python
1
=> { // recover pack: add to new index in section packs let pack = pack.into_index_pack_with_time(self.time); indexer.write().await.add(pack).await?; } PackToDo::Delete => { // delete...
Rust
0
some() { non_blanket_impls.push(impl_def_id); } else { blanket_impls.push(impl_def_id); } } TraitImpls { blanket_impls: Rc::new(blanket_impls), non_blanket_impls: Rc::new(non_blanket_impls), } } // Query provider for `relevant_trait_impls_for`. pub(s...
Rust
0
collect::<Vec<String>>() .join("\t"), )?; let mut result = Ok(None); term::enable_raw_mode()?; let mut stdout = get_tty()?; // let mut stdout = stdout.lock(); execute!(stdout, term::EnterAlternateScreen)?; // let stdout = MouseTerminal::from(stdout); let backend = Crossterm...
Rust
0
2); let _elements = &a_elements | &b_elements; let mut a_f = replace_value(&apg1.lambda_upsilon, &prefix1); let b_f = replace_value(&apg2.lambda_upsilon, &prefix2); a_f.extend(b_f); let _new_name = prefix1.clone() + &prefix2; // APG::new(&new_name, elements, labels, a_f) unimplemented!() ...
Rust
0
from app import create_app from app.utils.celery_utils import celery # Create the Flask application (initializes Celery) app = create_app() if __name__ == '__main__': # Start the Celery worker with the Flask application context with app.app_context(): celery.worker_main(['worker', '--loglevel=info', '...
Python
1
from flask import request, jsonify from models.turma import Turma, adicionar_turma, listar_turmas, turma_por_id, atualizar_turma, excluir_turma, TurmaNaoEncontrada def create_turma(): data = request.get_json() adicionar_turma(data) return jsonify({'message': 'Turma criada com sucesso!'}), 201 def get_turm...
Python
1
} }; // Convert the given rusttype segment to a lyon path event. let segment_to_event = move |s: rusttype::Segment| -> lyon::path::PathEvent { match s { rusttype::Segment::Line(ref l) => { let line_seg = conv_line_segment(l); lyon::path::PathEvent::Line(...
Rust
0
import os import torch import torch.nn as nn import numpy as np from transformers import AutoModel class MedCPT(nn.Module): """ wrapper for a single text encoder, to allow text-text contrastive learning """ def __init__(self, cpt_checkpoint=None): super().__init__() self.model = AutoM...
Python
1
12: u32 = 55u32; #[doc = "*Required features: `\"Win32_NetworkManagement_IpHelper\"`*"] pub const IF_TYPE_IEEE802154: u32 = 259u32; #[doc = "*Required features: `\"Win32_NetworkManagement_IpHelper\"`*"] pub const IF_TYPE_IEEE80216_WMAN: u32 = 237u32; #[doc = "*Required features: `\"Win32_NetworkManagement_IpHelper\"`*"...
Rust
0
64> { self.exchange_filters .get("ExchangeMaxNumOrders")? .get_max_num_orders() } pub fn get_max_num_algo_orders(&self) -> Option<u64> { self.exchange_filters .get("ExchangeMaxNumAlgoOrders")? .get_max_num_algo_orders() } pub fn get_raw_r...
Rust
0
outine)?); // let hash = coroutine.hash(); // use_context() // .event_mgr() // .dispatcher() // .add_coroutine_listener_untyped(event.try_into()?, coroutine); // Ok(Some(hash)) // } // pub fn stop_coroutine(&self, hash: usize) { // use_contex...
Rust
0
h: replacement_for_cam_id = { "0": "eye0", "1": "eye1", "2": "world", None: "world", } replacement = replacement_for_cam_id[match.group("cam_id")] new_name = path.name.replace(match.group("prefix"), replaceme...
Python
1
import numpy as np from recommendation.model import Recommender from config import PARAM_DIR class popRec(Recommender): def __init__(self, DATA_NAME): super().__init__('popRec', DATA_NAME) def scoring(self, u, conditionItems): np.random.seed(0) s = np.random.rand(self.n_item)*...
Python
1
from typing import Annotated from annotated_types import MinLen, MaxLen from pydantic import BaseModel, EmailStr class UserBase(BaseModel): """Base model for user""" nickname: Annotated[str, MinLen(4), MaxLen(15)] email: EmailStr | None class UserIn(UserBase): """Model for creating a user""" ...
Python
1
: value['progress'], = reader.read_struct('<Q') result['value'] = value elif message_type == MessageType.ON_VOLUME_CHANGED: value['volume'], = reader.read_struct('<d') result['value'] = value elif message_type == MessageType.ON_AUDIO_DATA: value['data'] = _unpack_u8_vec(r...
Python
1
from .settings import * from decouple import config DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD': config('DB_PASSWORD'), 'HOST': config('DB_HOST'), 'PORT': config('DB_PORT'), ...
Python
1
.value_now .seti(io[IoTotals::ReadsCompleted as usize] as i64); self.stats[WhichStat::IoReadsMerged as usize] .value_now .seti(io[IoTotals::ReadsMerged as usize] as i64); self.stats[WhichStat::IoSectorsRead as usize] .va...
Rust
0
mat!( "1・1・0 = {}", reflexive_ordered3_i8(1,1,0) ) ); LOGGER.try_write().unwrap().writeln( &format!( "1・1・1 = {}", reflexive_ordered3_i8(1,1,1) ) ); LOGGER.try_write().unwrap().writeln( &format!( "1・1・2 = {}", reflexive_ordered3_i8(1,1,2) ) ); LOGGER.try_write().unwrap().writeln( &format!( "1・2・...
Rust
0
# -*- encoding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Fleet History', 'version': '1.0', 'category': 'Human Resources', 'summary': 'Get history of driven cars by employees', 'description': "", 'depends': ['hr', 'fleet'], 'data': [ ...
Python
1
3::{LdapConn, Scope}; /// # let mut ldap = LdapConn::new("ldapi://ldapi").unwrap(); /// let mut stream = ldap.streaming_search_with( /// EntriesOnly::new(), /// "", /// Scope::Base, /// "(objectClass=*)", /// vec!["+"] /// ); /// # let _ = stream; /// ``` #[derive(Clone, Debug)] pub struct EntriesOn...
Rust
0
retrieved. """ # Group remote users by destination, so we only send one request per remote # homeserver. by_destination: Dict[str, List[str]] = {} for user in remote_users: if user.domain not in by_destination: by_destination[user.domain] = [] ...
Python
1
UsbClass as _; use usb_device::device::UsbDeviceState; type UsbClass = keyberon::Class<'static, usb::UsbBusType, ()>; type UsbDevice = usb_device::device::UsbDevice<'static, usb::UsbBusType>; trait ResultExt<T> { fn get(self) -> T; } impl<T> ResultExt<T> for Result<T, Infallible> { fn get(self) -> T { ...
Rust
0
max_count) * canvas_height x0 = 130 + i * (bar_width + padding) y0 = 450 - bar_height x1 = x0 + bar_width y1 = 450 self.canvas.create_rectangle(x0, y0, x1, y1, fill="cyan") self.canvas.create_text((x0 + x1) / 2, 470, text=repr(char), fill="white"...
Python
1
#Chương trình minh họa sử dụng lệnh break #Duyệt qua tất cả các phần tử trong chuỗi for i in 'ngôn ngữ lập trình Python': print(i) if i == 'g': break print('Kết thúc!')
Python
1
{ return Default::default(); } let dict_data = data.as_hash().unwrap(); MachineConfig { ip: dict_data.get(&Yaml::from_str("ip")).and_then(|x| x.as_str()).map(String::from), port: dict_data.get(&Yaml::from_str("port")).and_then(|x| x.as_i64()).map(|x| x as u16), use...
Rust
0
playToolArgs { /// subnet_id: ClapSubnetId::from_str( /// "z4uqq-mbj6v-dxsuk-7a4wc-f6vta-cv7qg-25cqh-4jwi3-heaw3-l6b33-uae", /// ) /// .unwrap(), /// config: PathBuf::from("/path/to/ic.json5"), /// canister_caller_id: None, /// replay_until_height: None, /// subcmd: Some(SubCommand::...
Rust
0
1:{}/path", addr.port()); let res = http::Request::get(&uri) .timeout(Duration::from_millis(1000)) .call() .block(); let res = res?; // we do get a response, but reading the body times out. assert_eq!(res.status(), 200); let r = res.into_body().read_to_vec(1024).block(); ...
Rust
0
options) { Ok(result) => result, Err(error) => { println!("PNG Error: {}", error); return Ok(()); } } } else { println!("Not supported..."); return Ok(()); }; prin...
Rust
0
self.allows_enc } } const fn gen(bytes: &[u8]) -> Table { Table::gen(bytes) } /// ALPHA = A-Z / a-z pub const ALPHA: &Table = &gen(b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); /// DIGIT = 0-9 pub const DIGIT: &Table = &gen(b"0123456789"); /// HEXDIG = DIGIT / "A" / "B" / "C" / "D" / "E"...
Rust
0
}': () 29..36 'nope!()': {unknown} 47..93 'SizeSk...tail }': {unknown} 81..85 'true': bool 81..85 'true': bool 87..91 'tail': {unknown} 97..99 '{}': () "#]], ); } #[test] fn infer_std_crash_4() { // taken from rustc check_inf...
Rust
0
for profile in profile_list: profile_dict = {} name = profile.get('name') config = profile.get('config') pool = config.get('pool') size = config.get('size') stat...
Python
1
"""Helper functions to work with nested JSON structures.""" from collections.abc import Iterable from functools import reduce from typing import Callable, TypeVar, Union, overload _T = TypeVar("_T") _U = TypeVar("_U") JSONTree = Union[dict[str, "JSONTree[_T]"], list["JSONTree[_T]"], tuple["JSONTree[_...
Python
1
main_command_hint: str = \ """ Выберите пункт из меню: 1. Работа с калькулятором 2. Загрузить историю из файла 0. Выход """ local_command_hint: str = \ """ Выберите пункт из меню: 1. Вычисление (целые и дробные числа) 2. Отобразить историю 3. Очистить историю 0. Вернуться в главное меню """ calculator_instructions: s...
Python
1
# # 找到和样本j属于同一类的其他样本 # pos_samples_mask = (labels == i) & (labels != labels[j]) # pos_samples_indx[j][i] = np.random.choice(np.flatnonzero(pos_samples_mask), size=1)[0] ... # affinity_init = kneighbors_graph(z.detach().cpu().numpy(), n_neighbors=50, mode='di...
Python
1
j in range(len(conversations)): conversation = conversations[j] if conversation["from"] == "scorer": round_pattern = re.compile(r'\(round(\d+)\)') # 提取轮次 round_match = round_pattern.search(conversation["value"]) round_number = round_match.group(1) if rou...
Python
1
; mov [rdi + 0x30], rsi ; mov rsi, [rsp + 0x0] // access_addr ; mov [rdi + 0x88], rsi ; mov rsi, [rsp + 0x8] // true_rip ; mov [rdi + 0x90], rsi ; mov rsi, rdi // we want to save rdi, but we have to copy the address of self.regs into another register ...
Rust
0
#!/usr/bin/env python3 # Copyright (c) 2022 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test logic for setting -maxtipage on command line. Nodes don't consider themselves out of "initial block do...
Python
1
rt_eq!(output, Some(mem_thomas)); } /// Test for non-member detection #[test] fn parse_member_invalid_test() { let input = include_str!("../../tests/test_json_member_invalid.json"); let mut parsed = json::parse(input).unwrap(); let mut pmember = parsed["members"][0].take(); ...
Rust
0
ARAMETERS.name()); let has_nir = point_layout.has_attribute_with_name(attributes::NIR.name()); let mut format = Format::new(0).unwrap(); format.has_color = has_colors; format.has_gps_time = has_gps_time; format.has_nir = has_nir; format.has_waveform = has_any_waveform_attribute; if has_nir...
Rust
0
from __future__ import annotations from typing import Any import pandas as pd from pandas._libs.tslibs.parsing import DateParseError from sdgx.data_models.inspectors.base import Inspector from sdgx.data_models.inspectors.extension import hookimpl class BoolInspector(Inspector): def __init__(self, *args, **kwar...
Python
1
to_owned(), "serde_json" => "1.0".to_owned(), }, }; assert_eq!(actual, expected); } #[test] fn test_array() { // Copied from the TOML spec. let actual = toml! { [[fruit]] name = "apple" [fruit.physical] color = "red" shape = "round" ...
Rust
0
from __future__ import division import tushare as ts import time,re import pandas as pds import util.logout as log import util.TDX_OpenDataOutput as TDX_OpenDataOutput pro = ts.pro_api('XXX') ts.set_token('XXX') #早盘选股,选量比>25的,现量大于3000手,3日涨幅% <15%,流通盘小150亿 ###################sfile早盘竞价后导出EXCEL文件 def getstockopenamo(sfil...
Python
1
> srv_config_edit > cln_config_edit let html = extract_html(&srv_response); store_to_config_data(srv_response); // process with ConfigData let html_after_process = { let data = CONFIG_DATA.lock().unwrap(); tmplt::process_html(data.deref(), &html) }; w::set_inner_html("div_for_wa...
Rust
0
mtp_port); let security = ClientSecurity::None; let mut smtp_client = SmtpClient::new(addr, security)?; if self.smtp_username.is_some() && self.smtp_password.is_some() { let credentials = Credentials::new( self.smtp_username.as_ref().unwrap().to_owned(), ...
Rust
0
* // The Space Rust Library is distributed in the hope that it will be useful, * // but WITHOUT ANY WARRANTY; without even the implied warranty of * // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MIT License * // f...
Rust
0
_groups.push(rdep_group); in_progress.iter().for_each(|s| { trace!("Adding to satisfied deps: {}", s); satisfied_deps.insert(s.to_owned()); }); in_progress.clear(); group_num += 1; ...
Rust
0
X : {array-like, sparse matrix} of shape (n_samples, n_features) Array representing the data. y : array-like of shape (n_samples,) Array representing the labels. Returns ------- score : float Result of calling score on the `base_estimator`. ...
Python
1