text
string
label_name
string
labels
int64
# -*- coding: utf-8 -*- #https://developers.google.com/gmail/api/quickstart/python(参考) from datetime import datetime import os from apiclient.discovery import build from httplib2 import Http import oauth2client from oauth2client import client from oauth2client import tools try: import argparse flags = argpar...
Python
1
to update host stats host_ids = db.session.query( VulnerabilityGeneric.host_id, VulnerabilityGeneric.service_id ) by_severity = kwargs.get('by', None) == 'severity' if by_severity: for severity in values: if severity not in Vulnerabili...
Python
1
import os import math import re # clear terminal def clear(): os.system('cls' if os.name == 'nt' else 'clear') clear() # point class class Point: def __init__(self, x, y): self.id = str(x) + '_' + str(y) self.x = x self.y = y def __str__(self): return f'({self.x}, {sel...
Python
1
import numpy as np import scipy.optimize from CoolProp.CoolProp import PropsSI as prop from data import nodes, blocks from modules import Node, comp, turb,heat_source,heat_exch,split,mix from scipy.optimize import root_scalar,root,minimize global data data = open("res.txt", "a") def Sensitivity(inp): P1 = inp[0]...
Python
1
RDY pin will be set high and it will be kept so until the //! measurement is read or an appropriate SMBus alert response is sent by //! the master. //! //! ```no_run //! use linux_embedded_hal::I2cdev; //! use ads1x1x::{ //! Ads1x1x, SlaveAddr, ComparatorQueue, ComparatorPolarity, //! ComparatorMode, Comparator...
Rust
0
4:-64, 64:-64] # GTB[count,:] = M1['labels'] # # df[count, 0] = count # df[count, 1] = i # df[count, 2] = j # # count = count + 1 # #NE = NE/np.max(NE) # #img_size = (Npix, Npix) ##img_size = resize_size_Big # #N_pixels = img_size ##N_pixels_orgn = origin_size # #if K.image_da...
Python
1
!apt-get install -y xvfb python-opengl ffmpeg > /dev/null 2>&1 !pip install pyvirtualdisplay > /dev/null 2>&1 !pip install piglet > /dev/null 2>&1 from tkinter import * from pyvirtualdisplay import Display !pip install tkinter # ***** IMPORTS ***** import tkinter as tk # ***** VARIABLES ***** # ...
Python
1
ers. Args: tag_world_corners (np.ndarray): World coordinates of the tag corners. tag_image_corners (np.ndarray): Image coordinates of the tag corners. Returns: tuple: Camera position and Euler angles. """ success, rvec, tvec = cv2.solvePnP(tag_world_...
Python
1
# 3 tanks of oxygen and 3 tanks of hydrogen are good for 8 days, scaling with power output def lb_to_kg(lb: float) -> float: """ Convert pounds to kilograms. Args: lb: mass in pounds Returns: value in kilograms """ return lb * 0.45359237 def power_plant_mass(average_p...
Python
1
from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def home(): return render_template("index.html") @app.route("/login", methods=["POST"]) def receive_data(): name = request.form["username"] password = request.form["password"] return f"<h1>Name: {name}, Password:...
Python
1
user_input=input("how many cookies do you have ?") user_cookies=int(user_input) cookies_eaten=0 while user_cookies > 0 : user_cookies=user_cookies - 1 cookies_eaten=cookies_eaten+1 print ("Eating a cookie") print(cookies_eaten) print ("I ate all the cookies.")
Python
1
f.flush() test_file_path = Path(f.name) try: # Should load only valid messages, skipping malformed ones messages = load_transcript(test_file_path) # Should have loaded 2 valid messages, skipped 2 malformed ones assert len(messages) == 2 ...
Python
1
#!/usr/bin/env python # -*- coding:utf-8 -*- """ @Description: 人脸裁剪处理器 @Author: Kermit @Date: 2024-02-18 15:51:15 """ import asyncio import logging import time import numpy as np from event_bus.event_bus_processor import BaseEventBusProcessor from event_bus.message_body.asd_message_body import AsdMessageBody from ev...
Python
1
# SPDX-License-Identifier: CC-BY-NC-4.0 # SPDX-FileCopyrightText: © 2022- twinify Developers and their Assignees import jax.numpy as np import numpyro.distributions as dist from numpyro.primitives import sample, plate from twinify.dpvi.modelling import slice_feature, NAModel def preprocess(df): """ Args: ...
Python
1
jrS\ \ \ 4S\4SjrSrg)_DNSCacheTableNttlrec,0Ul0UlXlg)N _addrs_rr _timestamps_ttl)rgrs rhri_DNSCacheTable.__init__UW9; rlhostcXR;$)Nr)rgr...
Python
1
''' Created on April 26, 2013 @package: livedesk @copyright: 2013 Sourcefabric o.p.s. @license: http://www.gnu.org/licenses/gpl-3.0.txt @author: Mugur Rus API implementation for liveblog sync. ''' from sqlalchemy.schema import Column, ForeignKey, UniqueConstraint from livedesk.meta.blog import BlogMapped from sqlalch...
Python
1
help='Specify GPU number', default='0') parser.add_argument('--local_rank', type=int, default=-1) return parser import sys if sys.argv[0].endswith('color_texture_branch/scripts.py'): parser = get_basic_arg_parser() args = parser.parse_args() cfg = get_config(configs, args.config) os.environ[...
Python
1
_input_allow_device_events_checked) } /// Sends a `Input::AllowDeviceEvents` request (unchecked). #[inline] pub unsafe fn xcb_input_allow_device_events( &self, c: *mut xcb_connection_t, time: xcb_timestamp_t, mode: u8, device_id: u8, ) -> xcb_void_cookie_t { ...
Rust
0
ets data_val_normal = data_val[target_val==opt.normal_digit] target_val_normal = target_val[target_val==opt.normal_digit] data_val_abnormal = data_val[target_val!=opt.normal_digit] target_val_abnormal = target_val[target_val!=opt.normal_digit] randIdx_normal = np.arange(data_val_normal.shape[0]...
Python
1
# -*- coding: utf-8 -*- # # RERO ILS # Copyright (C) 2019 RERO # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, version 3 of the License. # # This program is distributed in the hope that...
Python
1
.bits = bits; self } #[doc = "Bit 0 - Ones written to this address clear bits in the IENR, thus disabling the interrupts. Bit n clears bit n in the IENR register. 0 = No operation. 1 = Disable rising edge or level interrupt."] #[inline] pub fn cenrl0(&mut self) -> _CENRL0W { _CENRL0W { w...
Rust
0
.Tensor: if waveform.ndim == 3: waveform = waveform.squeeze(1) with torch.no_grad(): outputs = self.encoder(waveform, output_hidden_states=False, return_dict=True) features = outputs.last_hidden_state # (B, T, D) features = self.sequence_model(features) ...
Python
1
_spectral_beams, use_dask): hdu = pyfits.open(data_5_spectral_beams) spec = OneDSpectrum.from_hdu(hdu) np.testing.assert_almost_equal(spec, np.arange(5, dtype='float')) assert isinstance(spec, VaryingResolutionOneDSpectrum) assert hasattr(spec, 'beams') assert len(spec.beams) == 5 hdu.close...
Python
1
> = points.iter().collect(); // Compare with those values generated by OpenCV assert_abs_diff_eq!(moments.get::<0, 0>(), 703.0); assert_abs_diff_eq!(moments.get::<1, 0>(), 52175.166666666664); assert_abs_diff_eq!(moments.get::<0, 1>(), 25661.5); assert_abs_diff_eq!(moments.get::<2, 0>(), 4084450.66...
Rust
0
<T: Data> Harness<'_, T> { /// Create a new `Harness` with the given data and a root widget, /// and provide that harness to the passed in function. /// /// For lifetime reasons™, we cannot just make a harness. It's complicated. /// I tried my best. /// /// This function is a subset of [crea...
Rust
0
import json import random # file_path = 'data/plots.json' # with open(file_path, 'r', encoding='utf-8') as f: data = json.load(f) # def random_mineral(): elements = [ "Hydrogen", "Helium", "Lithium", "Beryllium", "Boron", "Carbon", "Nitrogen", "Oxygen", "Fluorine", "Neon", "Sodium", "Magn...
Python
1
-> &'a mut W { self.variant(BB_LDO_HF_TRIMW::_5) } #[doc = "1.50 V"] #[inline] pub fn _6(self) -> &'a mut W { self.variant(BB_LDO_HF_TRIMW::_6) } #[doc = "1.66 V"] #[inline] pub fn _7(self) -> &'a mut W { self.variant(BB_LDO_HF_TRIMW::_7) } #[doc = r" Wri...
Rust
0
'scenes':scenes2[60:90]}) p8 = multiprocessing.Process(target = dat2npy, kwargs = {'shuffle':shuffle, 'categ':categ2, 'scenes':scenes2[90:]}) p1.start() ...
Python
1
(input)?; log::info!("some_strings = {:?}", some_strings); (input, Some(some_strings)) } else { (input, None) }; let (input, _something) = if maybe_flags & 2 == 2 { let (input, lod_count) = le_u8(input)?; let (input, something) = take(...
Rust
0
gb( r as f64 / 255.0, g as f64 / 255.0, b as f64 / 255.0 )) } _ => Err(s), } } struct Struct { layers: Vec<Rc<Layer>>, name: Box<str>, boundaries: Vec<Boundary>, extents: Extents, } #[derive(Debug, Clone, Copy)] struct Point { x: f64, y: f64, } impl std::ops::Sub for Point { type Output =...
Rust
0
let move_message: [u8; 14] = [ 0x2, 0xa, 0x67, 0xe, 0x0, 0x0, 0x0, 0x3, 0x0, 0x0, 0x0, 0x1, 0x0, 0x9c, ]; let pilot_state = js::PilotState { flag: true, speed: 0, turn: -100, }; let move_frame = Frame { frame_type: Typ...
Rust
0
or2::new(0.0, 0.0), view_angles_delta: Vector2::new(0.0, 0.0), keyboard_state: Default::default(), } } pub fn new(context: Arc<Context>, frame: Arc<InputFrame>) -> InputFrame { let ic = &context.input; let mut keyboard_state = frame.keyboard_state.clone(); let mut mouse_movement = Vector2::new(0f32...
Rust
0
INT_STATUS_SPEC>; #[doc = "PG External Interrupt Status Register"] pub mod pg_eint_status; #[doc = "pg_eint_deb register accessor: an alias for `Reg<PG_EINT_DEB_SPEC>`"] pub type PG_EINT_DEB = crate::Reg<pg_eint_deb::PG_EINT_DEB_SPEC>; #[doc = "PG External Interrupt Debounce Register"] pub mod pg_eint_deb; #[doc = "pio...
Rust
0
ce = device try: self.model = VitPoseForPoseEstimation.from_pretrained("usyd-community/vitpose-base-simple").to(device).eval() print("PoseEstimator: VitPoseForPoseEstimation model loaded successfully.") except Exception as e: raise RuntimeError(f"An error occurred whi...
Python
1
bg_wall_fov_true: (154, 38, 84, 255), world_fg_wall_fov_true: (206, 82, 126, 255), world_bg_floor_fov_false: (80, 25, 35, 255), world_fg_floor_fov_false: (80, 25, 35, 255), world_bg_floor_fov_true: (124, 18, 54, 255), world_fg_floor_fov_true: (206, 82, 126, 255), // entity colors entity_pla...
Rust
0
ackForest { FOO => println!("hi"), GOO => println!("meh"), WORKS => println!("möp"), _ => println!("bye"), } } #![warn(clippy)] #![warn(if_let_redundant_pattern_matching)] fn main() { if let Ok(_) = Ok::<i32, i32>(42) {} if let Err(_) = Err::<i32, i32>(42) { } ...
Rust
0
import numpy as np import matplotlib.pyplot as plt import grid_plot as gp #----------------------------------------------------------------------------- nzones = 8 # data that lives on the grid #a = np.array([0.3, 1.0, 0.9, 0.8, 0.25, 0.15, 0.5, 0.55]) a = np.array([0.3, 1.0, 1.0, 0.8, 0.2, 0.15, 0.5, 0.55]) gr = ...
Python
1
COSE Key can be found in the //! IANA "COSE Key Common Parameters" registry (Section 16.5). //! //! https://www.iana.org/assignments/cose/cose.xhtml#key-common-parameters //! //! Additional parameters defined for specific key types can be found in //! the IANA "COSE Key Type Parameters" registry (Section 16.6). //! //...
Rust
0
# Copyright (c) 2010-2024 openpyxl from openpyxl.descriptors.serialisable import Serialisable from openpyxl.descriptors.excel import Relation class Related(Serialisable): id = Relation() def __init__(self, id=None): self.id = id def to_tree(self, tagname, idx=None): return super().to...
Python
1
me_iter): """Check resume states and pretrain_network paths. Args: opt (dict): Options. resume_iter (int): Resume iteration. """ if opt["path"]["resume_state"]: # set pretrained model paths name = "pretrain_network_dc" basename = "dc" if opt["path"].get("...
Python
1
at_flag: "abcd \t e fghi 😀 jk😀lm 🈎_🇧🇷 no🇧🇷pq", within_flag: "abcd \t e fghi 😀 jk😀lm 🇧🈎_🇷 no🇧🇷pq", after_flag: "abcd \t e fghi 😀 jk😀lm 🇧🇷🈎_ no🇧🇷pq", until_flag: "abcd \t e fghi 😀 jk😀lm 🇧🇷 🈎_no🇧🇷pq", ...
Rust
0
Depends(get_db), current_user: User = Depends(get_current_user) ): if user_id == current_user.userId: raise HTTPException(status_code=400, detail="You cannot follow yourself.") follow = await add_follow(db, follower_id=current_user.userId, following_id=user_id) return {"message": "Fol...
Python
1
1])); assert_eq!( Capture::from_slice(&[v1, v2]), Capture::from_slice(&[v1, v2]) ); } #[test] fn conversion() { let v1 = Variable::fresh(); let v2 = Variable::fresh(); assert_eq!( Fact::from_slice(&[v1, v2]), Fact::from_record(Capture::from_slice(&[v1, v2])) ); ...
Rust
0
#[structopt(short, long, case_insensitive = true, default_value = "INFO")] log_level: LevelFilter, /// Twitch credential files. #[structopt(short, long, default_value = "twixelbox-bot.toml")] config_file: String, } struct Canvas { frame_side_len: u32, } impl Canvas { fn add_cube( &mut...
Rust
0
4722222 9 17 0.052955953013333334 22 18 0.02199033287288889 12 19 0.052955953013333334 23 20 0.016911101656944448 2 21 0.052955953013333334 16 22 0.026477976506666667 11 23 0.011488453117388888 6 24 0.011640164641972222 1 25 0.052955953013333334 32 26 0.052955953013333334 10 27 0.015782488811222226 5 28 0.0529559530133...
Rust
0
ax.plot_surface(t, f, z, rcount=len(t), ccount=len(f), cmap='magma', antialiased=True, vmin=z_min, vmax=0) # Z axis ax.set_zlim([z_min, 0]) ax.zaxis.set_major_locator(LinearLocator(10)) ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) # X axis ax.set_x...
Python
1
"left".to_owned(), "right".to_owned()], Type::PointerType(PointerType( Type::TypeName(TypeName::Identifier("TreeNode".to_owned())) .into() )) .into(...
Rust
0
concat!("Size of: ", stringify!(Dwfl_Callbacks)) ); assert_eq!( ::std::mem::align_of::<Dwfl_Callbacks>(), 4usize, concat!("Alignment of ", stringify!(Dwfl_Callbacks)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<Dwfl_Callbacks>())).find_elf as *const _ as usize...
Rust
0
okens), 1) assert j_uk_uk.shape[1] < max_len j_uk_uk = nn.functional.pad( j_uk_uk, (0, max_len - j_uk_uk.shape[1]), 'constant', 50256 ) samples.append(( j_us_us, # 0 j_us_uk, # 1 j_uk_us, # 2 j_uk_uk, # 3 (us_us_head_limit, us_us_target_limit, us_us_full_limit), (u...
Python
1
from tests.workflows.basic_node_mocking.workflow import MockedNodeWorkflow, StartNode def test_workflow__happy_path(): # GIVEN a workflow with a node that needs to be mocked to succeed workflow = MockedNodeWorkflow() # WHEN we run the workflow with a mock defined final_event = workflow.run( n...
Python
1
); assert_eq!(row_ids.to_vec(), vec![1, 6, 13]); let row_ids = v.row_ids_filter_range( (10, &Operator::LT), (-100, &Operator::GT), RowIDs::new_vector(), ); assert_eq!(row_ids.to_vec(), vec![11, 14, 15]); let row_ids = v.row_ids_filter_range( ...
Rust
0
with open(DEST / "docs" / path.name.replace(".md", ".html"), "w") as f: f.write(template) for path in CONTENT.glob("*.md"): template = template_from_markdown(path, template=CHANGELOG_HTML_TEMPLATE) with open(DEST / path.name.replace(".md", ".html"), "w") as f: f.write(temp...
Python
1
from ...urtps import EventPubNode class NeoPixel(EventPubNode): """ Represents a NeoPixel object that controls a strip of individually addressable RGB LEDs. Args: num_pixels (int): The number of pixels in the NeoPixel strip. brightness (float, optional): The brightness of the NeoPixel...
Python
1
Config(input_dim=(1, 28, 28))) def test_create_log_file( self, tmpdir, model_sample, train_dataset, training_config ): dir_log_path = os.path.join(tmpdir, "dummy_folder") trainer = CoupledOptimizerAdversarialTrainer( model=model_sample, train_dataset=train_datas...
Python
1
OutputVisitor { pub(crate) fn new(scope: Scope) -> Self { FnOutputVisitor { scope, ty: None, is_async: false, } } } impl<'ast> visit::Visitor<'ast> for FnOutputVisitor { fn visit_fn(&mut self, kind: visit::FnKind<'_>, _: source_map::Span, _: ast::NodeId) ...
Rust
0
pub scs: SCS, _reserved8: [u8; 4usize], # [ doc = "0x1a8 - Peripheral Clock Selection register 0." ] pub pclksel0: PCLKSEL0, # [ doc = "0x1ac - Peripheral Clock Selection register 1." ] pub pclksel1: PCLKSEL1, _reserved9: [u8; 16usize], # [ doc = "0x1c0 - USB Interrupt Status" ] pub ...
Rust
0
self.insert_adjacent_html(InsertPosition::BeforeEnd, html) } /// Insert nodes from HTML fragment after element. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML) fn insert_html_after( &self, html: &str ) -> Result<(), InsertAdjacentError...
Rust
0
m.insert("space", ("\u{2423}", true)); m.insert("plus", ("+", false)); m.insert("minus", ("-", false)); m.insert("less", ("<", false)); m.insert("greater", (">", false)); m.insert("equal", ("=", false)); m.insert("semicolon", (";", false)); m.insert("apostrophe",...
Rust
0
r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub...
Rust
0
h I think you're nominated'", said Dappy."And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations."The band have two sho...
Python
1
(|_| ()) })?; Ok(status_handle) } pub fn run_as_console() -> Result<(), Error> { let settings = app::init()?; let main = super::Main::<ModuleRuntime>::new(settings); main.run_until(signal::shutdown)?; Ok(()) } pub fn run() -> Result<(), Error> { // start app as a console app if an envir...
Rust
0
# # Copyright (c) 2012+ Anton Tyurin <noxiouz@yandex.ru> # Copyright (c) 2013+ Evgeny Safronov <division494@gmail.com> # Copyright (c) 2011-2014 Other contributors as noted in the AUTHORS file. # # This file is part of Cocaine. # # Cocaine is free software; you can redistribute it and/or modify # it u...
Python
1
:5433", TlsMode::None, )); let trans = or_panic!(conn.transaction()); let stmt = or_panic!(trans.prepare("SELECT 1")); or_panic!(trans.finish()); let result = or_panic!(stmt.query(&[])); assert_eq!(1i32, result.iter().next().unwrap().get::<_, i32>(0)); } #[test] fn test_stmt_finish() { ...
Rust
0
select, stream::{FuturesUnordered, Stream, StreamExt, TryStreamExt}, }, log::{error, info}, parking_lot::Mutex, std::{marker::Unpin, sync::Arc}, void::Void, wlan_inspect, wlan_sme::{self, clone_utils}, }; use crate::{ device_watch::{self, NewIfaceDevice}, mlme_query_proxy::M...
Rust
0
as_ptr() as *const _, $crate::translate::ToGlibPtr::<*const std::os::raw::c_char>::to_glib_none( &w.into_string() ).0, ); } } }}; } // rustdoc-stripper-ignore-next /// Macro used to log using GLib logging system. It...
Rust
0
]); assert_eq!(iovecs[2][..], b""[..]); assert_eq!(iovecs[3][..], b""[..]); } buf.advance(2); { let b1: &[u8] = &mut []; let b2: &[u8] = &mut []; let b3: &[u8] = &mut []; let b4: &[u8] = &mut []; let mut iovecs = [ IoSlice::new(b1), ...
Rust
0
import json from typing import Dict from fastapi import WebSocket class ConnectionManager: def __init__(self): self.active_connections: Dict[str, WebSocket] = {} async def connect(self, websocket: WebSocket, client_id: str): await websocket.accept() self.active_connections[client_id]...
Python
1
#-*- coding: utf-8 -*- import pandas as pd inputfile = '../tmp/data1_GM11.xls' # 灰色预测后保存的路径 outputfile = '../data/revenue.xls' # 神经网络预测后保存的结果 modelfile = '../tmp/1-net.model' # 模型保存路径 data = pd.read_excel(inputfile) # 读取数据 feature = ['x1', 'x2', 'x3', 'x4', 'x5', 'x7'] # 特征所在列 data_train = data.loc[range(1994, 20...
Python
1
h = words.next().unwrap(); input.insert(layer.parse()?, depth.parse()?); } } Ok(input) } /// Improved version that uses iterators to express intent of search better than /// previous convoluted for-loops. fn run() -> Result<(), Error> { let layers = read_input()?; let delay = (0..s...
Rust
0
# Copyright 2022 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
Python
1
# Create your views here. from django.db.models import F from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.shortcuts import get_object_or_404, render from django.urls import reverse from django.views import generic from django.utils import timezone from .models import Question, Choice cl...
Python
1
{ Dependency::GivenVariant(dep) if dep > 0.0 => { // calc s = sum 1 / i let mut s = 0.0; for m in 1..samples.len() * ploidy + 1 { s += 1.0 / m as f64; } // het becomes mixture (by dep) of (het' such that Pr(...
Rust
0
fn drop(&mut self) { self.device.destroy_pipeline(self.pipeline); } } //! # Examples //! //! How to monitor if there's a new update and install it. //! Only available for Flatpak applications. //! //! ```no_run //! use ashpd::flatpak::update_monitor::{ //! UpdateInfo, UpdateMonitorProxy, UpdateOpti...
Rust
0
d set of group of observations in pair-wise comparison. :return: p-values """ pvals = np.tile(np.NaN, [len(idx0), len(idx1), self.model_estim.x.shape[1]]) for i, xi in enumerate(idx0): for j, xj in enumerate(idx1): if i != j: pvals[i, j, :]...
Python
1
BlackHole OE1.6 elif os.path.exists("/etc/CurrentDelCamName"): try: camdlist = open("/etc/CurrentDelCamName", "r") except: return None # Pure2 elif os.path.exists("/etc/clist.list") and not os.path.exists("/usr/...
Python
1
:Increment(index) => *index, Token::Inline(index) => *index, Token::Int(index) => *index, Token::LessEqThan(index) => *index, Token::LessThan(index) => *index, Token::Long(index) => *index, Token::Macro(..) => panic!("Macro token found: {:?}", token), Token::Macro...
Rust
0
#!/usr/bin/env python3 """ 测试F9键停止功能的修复 """ import logging import time import sys import os # 添加项目根目录到Python路径 sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # 配置日志 logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) def tes...
Python
1
le: *const Bundle<Authorized, Amount>, ) -> bool { let bundle = unsafe { bundle.as_ref() }; bundle.map(|b| b.flags().outputs_enabled()).unwrap_or(false) } #[no_mangle] pub extern "C" fn orchard_bundle_spends_enabled(bundle: *const Bundle<Authorized, Amount>) -> bool { let bundle = unsafe { bundle.as_ref() ...
Rust
0
scene.frame_end = 1 scene.render.image_settings.file_format = 'PNG' scene.render.filepath = filepath scene.update() data_context = {"blend_data": bpy.context.blend_data, "scene": scene} bpy.ops.render.render(data_context, write_still=True) # cleanup bpy.data.scenes.remove(scene, do_unlin...
Python
1
let gq_tmp = rgoth_square.phi_q_to_the_minus_1(&pk.q).reduce(); let gq = gq_tmp.exp(&pk.q); match gq == pk.gq { true => Ok(()), false => Err(ErrorReason::SetupError), } } pub fn encrypt(pk: &PK, m: &BigInt) -> Ciphertext { unsafe { pari_init(10000000, 2)...
Rust
0
&dst_bin).map_err(|err| error!(err, "error replacing `{}` with `{}`: {}", dst_bin.display(), src_bin.display(), err))?; if !quiet { statusln!("Replaced", "`{}` with `{}`", dst_bin.display(), src_bin.display()) } } Ok(()) } } struct Ignore { /// ASCII prefix pre: &'static str...
Rust
0
""" from itertools import combinations import itertools def read_file(filename): alphabet = [] with open(filename, 'r') as f: lines = f.read().split('\n') alphabet = lines[0].split() n = int(lines[1]) return alphabet, n def product(alphabet, n): result = [] ...
Python
1
) array_contains, sdb_array_contains = register('sdb_array_contains','c_void_p, c_char_p, c_char_p, POINTER(c_uint)','c_bool') num_exists, sdb_num_exists = register('sdb_num_exists','c_void_p, c_char_p','c_bool') num_set, sdb_num_set = register('sdb_num_set','c_void_p, c_char_p, c_ulonglong, c_uint','c_bool') num_g...
Python
1
; //! - **Easy to use**: the user interface is nice, with human-oriented input //! files; //! - **Stable**: it will never crash on a good input, and provides helpful //! error messages. /// The full version of the crate, containing git state if available pub static VERSION: &str = env!("LUMOL_FULL_GIT_VERSION"); ...
Rust
0
return (4, num1, num2, '') # 4 - тип размера # Все остальное - в конец return (9, 0, 0, size_str) # Создаем ключ сортировки # Применяем ключ к колонке 'Размер', обрабатывая возможные ошибки df_results['sort_key'] = df_results['Размер'].apply(lambda x: sorta...
Python
1
) } pub fn e() -> Number { Number::Float(2.7182818284590452353602874713527) } } // This file is part of Substrate. // Copyright (C) 2017-2021 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use...
Rust
0
ters::prelude::*; // let root = // BitMapBackend::new("layout.png", (1920, 1080)).into_drawing_area(); // root.fill(&WHITE).unwrap(); // let root = root // .titled("Exe Circuit Layout", ("sans-serif", 60)) // .unwrap(); // halo2_proofs::dev::CircuitLa...
Rust
0
crate goji; extern crate serde_json; use goji::sprints::*; #[test] fn deserialise_sprint() { let sprint_str = r#"{ "id": 72, "self": "http://www.example.com/jira/rest/agile/1.0/sprint/73", "name": "sprint 2" }"#; let sprint: Sprint = serde_json::from_str(sprint_str).unwrap(); ...
Rust
0
# Desafio 02 """ Para este desafio, quero que você declare duas variáveis: uma chamada 'nome', que deve guardar o seu primeiro nome como uma string, e outra chamada 'idade', que deve guardar a sua idade como um número inteiro. Depois disso, eu quero que você imprima na tela uma frase que diga "Olá, meu nome é [nom...
Python
1
self.avail += units; } fn try_wake_one(&mut self) -> Option<Waker> { let id = *self.list.front()?; let waiterset_entry = match self.waiterset.entry(id) { Entry::Occupied(entry) => entry, Entry::Vacant(_) => unreachable!(), }; let units = waiterset_entry.g...
Rust
0
ction receiver buffer overflow"; /// HTTP protocol over TLS/SSL const HTTPS_PORT: u16 = 443; pub(crate) enum MaybeTlsListener { PlainText(TcpListener), Tls(TlsListener), } impl Listener for MaybeTlsListener { type Socket = Either<TcpStream, TlsStream>; type AcceptStream = Fuse<EitherStream>; fn ...
Rust
0
import os # Etiket klasörlerinin yolları label_dirs = [ r"C:/Users/ASAF/Desktop/plane_faraway/test/labels", r"C:/Users/ASAF/Desktop/plane_faraway/train/labels", r"C:/Users/ASAF/Desktop/plane_faraway/val/labels", ] def convert_class_ids(folder_path, from_id='0', to_id='2'): print(f"\nİşleniyor: {folder_...
Python
1
ype: Sized { fn extract(value: &Tagged<Value>) -> Result<Self, ShellError>; } impl<T: ExtractType> ExtractType for Tagged<T> { fn extract(value: &Tagged<Value>) -> Result<Tagged<T>, ShellError> { let name = std::any::type_name::<T>(); trace!("<Tagged> Extracting {:?} for Tagged<{}>", value, nam...
Rust
0
, 'Israele', 'Italia', 'Giamaica', 'Giappone', 'Jersey', 'Giordania', 'Kazakhstan', 'Kenya', 'Kiribati', 'Korea', 'Kuwait', 'Republicca Kirgiza', 'Repubblica del Laos', 'Latvia', 'Libano', 'Lesotho', 'Liberia', 'Libyan Arab Jamahiriya', 'Liechtenstein', 'Lituania', 'Lussemburgo', ...
Python
1
# Copyright 2017-present Adtran, Inc. # # 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 law or agreed to in writ...
Python
1
import asyncio import click from nest.core.pynest_container import PyNestContainer from nest.core.pynest_factory import AbstractPyNestFactory, ModuleType class CLIAppFactory(AbstractPyNestFactory): def __init__(self): super().__init__() def create(self, app_module: ModuleType, **kwargs): co...
Python
1
StatEntry = HashMap<String, (StatsPrinter, i32)>; pub type StatsCollection = (Instant, HashMap<String, StatEntry>); pub fn print(data: &StatsCollection) { println!("Stats:"); println!( " over the last {:.02}ms", (Instant::now() - data.0).as_millis() ); f...
Rust
0
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from contextlib import asynccontextmanager import uvicorn import os from app.database import init_db from app.api.routes import router from app.services.stock_price import start_price_updater # --------------------------------------------...
Python
1
AratakiIttoRoleEnum; #[cfg(not(target_family = "wasm"))] const SKILL_MAP: CharacterSkillMap = CharacterSkillMap { skill1: Some(&[ CharacterSkillMapItem { index: AratakiIttoDamageEnum::Normal1 as usize, chs: "一段伤害" }, CharacterSkillMapItem { index: AratakiIttoDamageEnum::Normal2...
Rust
0
write!( f, "[{},{},{}]", self.role, self.network_id.as_str(), self.peer_id.short_str(), ) } } impl NetworkContext { pub fn new(role: RoleType, network_id: NetworkId, peer_id: PeerId) -> NetworkContext { NetworkContext { ...
Rust
0