text
string
label_name
string
labels
int64
decimal_num=int(input("Enter the Decimal NUmeber::")) binary_num=0 i=0 while(decimal_num!=0): reminder=decimal_num%2 binary_num=binary_num+reminder*(10**i) decimal_num=decimal_num/2 i=i+1 print(binary_num)
Python
1
nnull(&mut self) -> NonNull<T> { self.0.as_nonnull() } } impl<T> From<UniqueKernelPageRef<T>> for KernelPageRef<T> { fn from(that: UniqueKernelPageRef<T>) -> KernelPageRef<T> { that.0 } } impl<T> Deref for UniqueKernelPageRef<T> { type Target = T; fn deref(&self) -> &T { u...
Rust
0
# coding: utf-8 # In[1]: import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # In[2]: #载入数据集 mnist = input_data.read_data_sets("MNIST_data",one_hot=True) #每个批次的大小 batch_size = 100 #计算一共有多少个批次 n_batch = mnist.train.num_examples // batch_size #定义两个placeholder x = tf.placeholder(tf.f...
Python
1
sed_globals): """Method to update trust policy if not done already""" base36 = Base36() eks_client = EKS(self._session.create_client( 'eks', region_name=self._region, verify=parsed_globals.verify_ssl )) account_id = eks_client.get_account_i...
Python
1
getattr(oper, "reg", None) != None: # Adjust the size if needed if oper.tsize == 4: oper.reg += RMETA_LOW32 if prefixes & PREFIX_REX_B: oper.reg += REX_BUMP def ameth_e(self, bytes, offset, tsize, prefixes): osize, oper = e_i386.i386Disa...
Python
1
dClient> = vec![]; let mut r = self.redis_client.get_connection()?; let keys = r.keys::<&str, Vec<String>>(&self.redis_prefix)?; for key in keys { let clients_str = r.get::<String, String>(key)?; let stringfied_client = serde_json::from_str::<StringfiedEncodedClient>(&cli...
Rust
0
lags::RESTART, ], ), ]; let mut pwm = new(&trans); pwm.enable_restart_and_disable().unwrap(); let mut delay = DelayMock::new(); pwm.restart(&mut delay).unwrap(); destroy(pwm); } #[test] fn can_disable_then_restart_nonblocking() { let trans = [ I2cTrans::write( ...
Rust
0
saving = savings[i] if saving[1] in tour and saving[2] in tour: continue if saving[1] in tour: index = tour.index(saving[1]) if tour[index-1] == depot: tour.insert(index, saving[2]) elif tour[index+1] == depot: tour.insert(index+1, saving[2]) ...
Python
1
phia::try_from_canonical("magn|").unwrap(); assert_eq!("magn|", &og.s); // word ending let og = Orthographia::try_from_canonical("|us").unwrap(); assert_eq!("|us", &og.s); // word ending with additional separator let og = Orthographia::try_from_canonical("|eri|mus").unwrap(); assert_eq!("|...
Rust
0
ION_DEBUGMODE_ENABLED: u32 = 128u32; #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] pub const CODEINTEGRITY_OPTION_ENABLED: u32 = 1u32; #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] pub const CODEINTEGRITY_OPTION_FLIGHTING_ENABLED: u32 = 512u32; #[doc = "*Required features...
Rust
0
p(noise_pred, t, latents, **extra_step_kwargs).prev_sample # mask with inverted latents from appropriate timestep - use original image latent for last step latents = latents * mask_image + image_latents[i] * (1 - mask_image) # call the callback, if provided ...
Python
1
# coding: utf-8 """ NHL API Documenting the publicly accessible portions of the NHL API. The version of the OpenAPI document: 1.0.0 Generated by OpenAPI Generator (https://openapi-generator.tech) Do not edit the class manually. """ # noqa: E501 import unittest import datetime from openapi_cl...
Python
1
= status .set(DDS_INCONSISTENT_TOPIC_STATUS_ID) .set(DDS_OFFERED_DEADLINE_MISSED_STATUS_ID) .set(DDS_SUBSCRIPTION_MATCHED_STATUS_ID); assert_eq!(true, status.is_set(DDS_INCONSISTENT_TOPIC_STATUS_ID)); assert_eq!(true, status.is_set(DDS_OFFERED_DEADLINE_MISSED_STATUS_...
Rust
0
(np.arange(nr_boxes), np.arange(nr_boxes), indexing='ij') X,Y = X.reshape(-1), Y.reshape(-1) kl_div_s, kl_div_o = [], [] for i in range(N): logp_x = ent_cls[i,X,:num_ent_class].log() p_x = ent_cls[i,Y,:num_ent_class] #kl_s = F.kl_div(logp_x, p_x, reduction='none').sum(-1).view(nr_box...
Python
1
#!/usr/bin/env python # -*- coding: utf-8 -*- """Unprotect Malware - VT API - virusapi.py version 1.0 This module get VirusTotal report. """ import hashlib import json import requests def get_vt(api_key, filepe): hash_md5 = hashlib.md5() with open(filepe, "rb") as f: for chunk in iter(lambda: f.read...
Python
1
as_slice()[1..NIST_256_PUBKEY_X_LEN + 1] .try_into() .unwrap(); let pubkey_y: [u8; 32] = initiator_pk.to_bytes().as_slice()[NIST_256_PUBKEY_X_LEN + 1..] .try_into() .unwrap(); let hi = ECDSAHostId::get_host_id::<32>(&pubkey_x, &pubkey_y); let hit_bytes = HIT::compute_hit::<8...
Rust
0
import strawberry import strawberry_django from netbox_firmware.models import ( Firmware, FirmwareAssignment, Bios, BiosAssignment, ) from .types import ( FirmwareType, FirmwareAssignmentType, BiosType, BiosAssignmentType, ) @strawberry.type class FirmwareQuery: @strawberry.field ...
Python
1
_ => { count_to_param(&mut param); match oauth::get( "https://api.twitter.com/1.1/statuses/home_timeline.json", &consumer, Some(&access), Some(&param), ) { Ok(bytes) => { ...
Rust
0
_string()) .await .unwrap(); let msg_received = std::sync::Arc::new(atomic::AtomicBool::new(false)); sut.on_message({ let msg_received = msg_received.clone(); move |_| { msg_received.store(true, atomic::Ordering::Relaxed); } ...
Rust
0
batch)[:, 0:1, :, :] else: output = model(img_batch) # print(" eval output.shape", output.shape) loss = criterion(output, label_batch) iou, dice, SE, PC, F1, _, ACC = iou_score(output, label_batch) avg_meters['val_loss'...
Python
1
reat place to start your day.', rating=4), Review(user_id=12, shop_id=9, review='Fantastic coffee and great service.', rating=4), Review(user_id=13, shop_id=9, review='A bit crowded but worth it.', rating=3), # Shop 10: 6 reviews (46-51) Review(user_id=13, shop_id=10, review='The Daily ...
Python
1
# ______ Exercício 0093 ______ # Crie um programa que gerencie o aproveitamento de um jogador de futebol. O programa vai ler o nome do jogador e # quantas partidas ele jogou. Depois vai ler a quantidade de gols feitos em cada partida. No final, tudo isso será # guardado em um dicionário, incluindo o total de gols feit...
Python
1
> + 'static, E: 'static, CS: OutputPin + 'static, RESET: OutputPin + 'static, I: Wait + 'static, RFS: RadioSwitch + 'static, { radio: LoRa<SPI, CS, RESET>, rfs: RFS, irq: I, } #[derive(Debug, Copy, Clone)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum State { Idle, ...
Rust
0
mpared to the original GLM API. pub fn perspective_rh_no<N: RealField>(aspect: N, fovy: N, near: N, far: N) -> TMat4<N> { assert!( !relative_eq!(far - near, N::zero()), "The near-plane and far-plane must not be superimposed." ); assert!( !relative_eq!(aspect, N::zero()), "The...
Rust
0
self.hash_mask = (self.hash_mask << 1) + 1; let hash_mask = self.hash_mask; self.result.retain(|(_el, hash)| hash & hash_mask == 0); } // We need to recheck, since it may have change in the mean time if hash & self.hash_mask == 0 { ...
Rust
0
column will be sized to fit the cell contents. Otherwise, this can be one of the following: - ``"small"``: 75px wide - ``"medium"``: 200px wide - ``"large"``: 400px wide - An integer specifying the width in pixels help: str or None A tooltip that gets displ...
Python
1
class MouseEventArgs(EventArgs): """ Provides data for the System.Windows.Forms.Control.MouseUp,System.Windows.Forms.Control.MouseDown,and System.Windows.Forms.Control.MouseMove events. MouseEventArgs(button: MouseButtons,clicks: int,x: int,y: int,delta: int) """ @staticmethod def __new__(self,button,clicks,x...
Python
1
string = "python 3.0" string_tuple = tuple(string) print(string_tuple) print(type(string_tuple))
Python
1
ESSED: i32 = 0; // Compressed by computing the GCD pub const GCD_COMPRESSED: i32 = 1; // Compressed by giving IDs to unique values pub const TABLE_COMPRESSED: i32 = 2; // Compressed with monotonically increasing values pub const MONOTONIC_COMPRESSED: i32 = 3; // Compressed with pub constant ...
Rust
0
I) -> Result<Self, $crate::Error> where I: IntoIterator, I::Item: $crate::TryIntoInput, { static HELP: &$crate::Help = &$name::HELP; let mut it = $crate::helpers::Input::new(it.into_iter()); $($crate::__impl!(@init ...
Rust
0
) -> Result<(Vec<u8>, Vec<RawFd>)> { let mut msg_buf = vec![0; (message_length) as usize]; let received; let mut files: Vec<RawFd> = Vec::with_capacity(1); { let iov = [IoVec::from_mut_slice(&mut msg_buf)]; loop { match recvmsg(self.fd, &iov, ...
Rust
0
last.cleanup, names)); /// } /// days /// } /// /// // With a single crew working 8 hours a day: /// assert_eq!( /// assign_days(&tasks, 8), /// [ /// (7, vec!["Foundation"]), /// (8, vec!["Framing", "Plumbing"]), /// (7, vec!["Electrical", "Insulation"]), /// (5, vec!["...
Rust
0
index: usize, ) -> Option<Local<'s, Value>> { // Trying to access out-of-bounds internal fields makes V8 abort // in debug mode and access out-of-bounds memory in release mode. // The C++ API takes an i32 but doesn't check for indexes < 0, which // results in an out-of-bounds access in both debug and ...
Rust
0
import pandas as pd import matplotlib.pyplot as plt from statsmodels.graphics.tsaplots import plot_acf dataframe = pd.read_csv("../mcp_6months.csv") plot_acf(dataframe, lags=170) plt.xlabel("Lag") plt.ylabel("Auto correlation") plt.title("Auto correlation Function (ACF)") plt.grid(True) plt.show()
Python
1
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import torch # N is batch size; D_in is input dimension; # D_out is output dimension. N, D_in, D_out = 64, 1000, 10 # Create random Tensors to hold inputs and outputs. x1 = torch.randn(N, D_in).cuda().requires_grad_(True) y1 = torch.randn(N, D_...
Python
1
} <gh_stars>1-10 mod eco_863; mod ee_1045; mod ee_1071; mod ee_1103; mod ee_1119; mod ee_1120; mod ee_1129; mod ee_1152; mod ee_1160; mod ee_1163; mod ee_1174; mod ee_221; mod ee_401; mod ee_441; mod ee_460; mod ee_468; mod ee_470; mod ee_532; mod ee_536; mod ee_539; mod ee_549; mod ee_550; mod ee_572; mod ee_584; m...
Rust
0
etails(user_id).await?; if let Some(title) = user_details["user_title"]["value"].as_str() { user_details["user_title"]["value"] = JsonValue::String(title.to_uppercase()); } let user_group = user_details["user_group"]["value"].as_str().unwrap_or("").to_owned(); if let JsonValue::Array(user_statis...
Rust
0
it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see <http://www.gnu...
Rust
0
....#..#.", "..#.#...#.#", ".#...##..#.", "..#.##.....", ".#.#.#....#", ".#........#", "#.##...#...", "#...##....#", ".#..#...#.#", ]; #[test] fn test_example() { let example: Vec<String> = EXAMPLE.iter().map(std::string::ToString::to_...
Rust
0
# Author: Ben Brock # Created on May 03, 2023 #%% import qutip as qt import numpy as np import matplotlib.pyplot as plt N = 5 # number of transmon levels n_times = 101 t_duration = 40 q = qt.destroy(N) psi0 = qt.fock(N,0) # frequencies in GHz, times in ns kerr = -0.1 ts = np.linspace(-t_duration/2,t_duration/2,n_t...
Python
1
bit(false).unwrap(); w.write_bit(false).unwrap(); w.write_bit(true).unwrap(); w.write_bit(true).unwrap(); w.write_bit(false).unwrap(); w.write_bit(true).unwrap(); w.write_bit(true).unwrap(); w.write_bit(false).unwrap(); w.write_bit(true).unwrap(); w.write_bit(true).unwrap(); w.wr...
Rust
0
import sys # Token codes INT_LIT = 10 IDENT = 11 ASSIGN_OP = 20 ADD_OP = 21 SUB_OP = 22 MULT_OP = 23 DIV_OP = 24 LEFT_PAREN = 25 RIGHT_PAREN = 26 # Character classes LETTER = 0 DIGIT = 1 UNKNOWN = 99 # Global variables char_class = UNKNOWN lexeme = '' next_char = '' lex_len = 0 token = None next_token = None EOF = -...
Python
1
.run_until_stalled(&mut sender.send(request)).is_pending()); let _ = ex.run_until_stalled(&mut handler); let next_n = launcher.next_n(expected_urls.len()); pin_mut!(next_n); let source_components = unwrap_ready!(ex.run_until_stalled(&mut next_n)); assert_expected_components!(ex...
Rust
0
pcd_vertical_flip data = self.transforms(_results) aug_data.append(data) # list of dict to dict of list aug_data_dict = {key: [] for key in aug_data[0]} for data in aug_data: for key, val in data.items(): ...
Python
1
elayedTyping(tokio::sync::oneshot::Sender<()>); impl DelayedTyping { pub fn start( http: &std::sync::Arc<serenity::Http>, channel_id: serenity::ChannelId, delay: std::time::Duration, ) -> Self { let (sx, mut rx) = tokio::sync::oneshot::channel(); let http = std::sync::Ar...
Rust
0
ed.atoms[2])]); } else if pred.name == types::facts::PredicateType::RoleAllowsLogin as i32 { runtime.extend(&[RoleAllowsLogin(pred.atoms[0], pred.atoms[1])]); } else if pred.name == types::facts::PredicateType::RoleDeniesLogin as i32 { runtime.extend(&[RoleDeniesLogin(pred.atoms[...
Rust
0
rom_file(vocab_path.to_str().unwrap(), merges_path.to_str().unwrap(), true); let mut config = BertConfig::from_file(config_path); config.output_attentions = Some(true); config.output_hidden_states = Some(true); let roberta_model = RobertaForMultipleChoice::new(&vs.root(), &config); // Define input ...
Rust
0
, BigInt, Diagnostics, EnabledFeature, Import, Loc, Range, RpNumberKind, RpNumberType, RpStringType, RpStringValidate, Span, SymbolKind, WithSpan, }; use linked_hash_map::LinkedHashMap; use naming::{self, Naming}; use scope::Scope; use std::borrow::Cow; use std::collections::{hash_map, BTreeSet, HashMap}; use std::...
Rust
0
agent: &Agent, timeout: Duration, ) -> DfxResult { let assets_canister_info = info.as_info::<AssetsCanisterInfo>()?; let output_assets_path = assets_canister_info.get_output_assets_path(); let asset_locations: Vec<AssetLocation> = WalkDir::new(output_assets_path) .into_iter() .filte...
Rust
0
# Copyright (c) 2020 PaddlePaddle Authors. 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 by appli...
Python
1
import os import sys import torch import numpy as np import tempfile import json import time # 确保模块可被找到 sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # 确保导入路径正确 package_root = os.path.dirname(os.path.dirname(__file__)) if package_root not in sys.path: sys.path.append(package_root) ...
Python
1
# Generated by Django 5.2.4 on 2025-08-05 14:21 import django.utils.timezone from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='OwnTrackLog', fields=[ ...
Python
1
\d{2}:\d{2},\d{3})', time_line) if not time_match: continue start_time_str, end_time_str = time_match.groups() # 轉換時間格式 start_time = self._parse_srt_time(start_time_str) ...
Python
1
och_reward`](../consensus/struct.Consensus.html#structfield.initial_primary_epoch_reward) pub fn initial_primary_epoch_reward() -> Capacity { INITIAL_PRIMARY_EPOCH_REWARD } /// The default secondary_epoch_reward /// /// Apply to [`secondary_epoch_reward`](../consensus/struct.Consensus.html#...
Rust
0
.window.inner_size().height as f32, ); self.world_position = (self.screen_position - size / 2.0) * Vec2::new(1.0, -1.0) / camera.zoom + camera.pan; } pub fn tile(&self) -> IVec2 { self.world_position.floor().as_ivec2() } } pub struct Viewport { gfx: GraphicsContext,...
Rust
0
# Dictionary is a collection of key-value pairs. It is unordered, changeable and indexed. capital_cities = { "kenya": "Nairobi", "Uganda": "Kampala", "Tanzania": "Dodoma", "Rwanda": "Kigali", } print(capital_cities) # Outputs: {'kenya': 'Nairobi', 'Uganda': 'Kampala', 'Tanazania': 'Dodoma', 'Rwan...
Python
1
m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z assert point_o.pos_from(p1.point)-expr == 0 def test_validate_coordinates(): q1, q2, q3, u1, u2, u3 = dynamicsymbols('q1:4 u1:4') s1, s2, s3 = symbols('s1:4') # Test normal _validate_coordinates([q1, q2, q3], [u1, u2, u3]) #...
Python
1
fastest_step = torch.max( torch.cat(step_list, dim=1), dim=1, keepdim=True )[0] + 1 if "fastest_step" in incremental_state: incremental_state["fastest_step"] = torch.cat( [incremental_state["fastest_step"], fast...
Python
1
# Get thresholds for beginner mode def get_thresholds_beginner(): _ANGLE_ELBOW_SHOULDER_VERT= { 'NORMAL' : (180, 160), 'TRANS' : (155, 105), 'PASS' : (105, 80) } #ANKLE_KNEE_THRESH>170(kne...
Python
1
bined\0"); (*lmcf).combined_used = 1; } fmt = (*lmcf).formats.elts as *mut ngx_http_log_fmt_t; for i in 0..(*lmcf).formats.nelts { if (*fmt.offset(i as isize)).name.len == name.len && bindings::ngx_strcasecmp((*fmt.offset(i as isize)).name.data, name.data) == 0 { ...
Rust
0
) .expect("Resolve reverse failed"); assert_eq!(server_name, "server"); let bind_context_test = peer .bind_sync(server_id, iface_test_id, Duration::from_secs(5), None) .expect("bind_sync failed (test)"); // Send RPC calls. let params = TestHelloInParams { id: 0, ...
Rust
0
a separate mutex since `spawn` could be called from inside /// a future, which would mean the driver's mutex is already locked. spawn_queue: Mutex<Vec<TaskFuture>>, /// This is used to track when a future calls `wake` while we are within /// `hyper_executor::poll_next`. is_woken: Arc<ExecWaker>, }...
Rust
0
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # NO CHECKED-IN PROTOBUF GENCODE # source: channel.proto # Protobuf Python Version: 5.28.2 """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descri...
Python
1
y_min = max(0, center_y - margin) y_max = min(height, center_y + margin + 1) # 创建局部坐标网格 y_local, x_local = np.ogrid[y_min:y_max, x_min:x_max] # 计算到圆心的距离 distances = np.sqrt((x_local - center_x)**2 + (y_local - center_y)**2) # 创建圆圈掩码(圆环,厚度为1像素) circle_mask = ...
Python
1
def create_trigger_update_customer_rank(cursor): try: # Xóa trigger cũ nếu tồn tại drop_sql = "IF EXISTS (SELECT * FROM sys.triggers WHERE name = 'trg_UpdateCustomerRank') DROP TRIGGER trg_UpdateCustomerRank" cursor.execute(drop_sql) # Tạo trigger mới create_sql = """ ...
Python
1
.num_too_big => ('\u{fffd}', true), 0x00 | 0xD800..=0xDFFF => ('\u{fffd}', true), 0x80..=0x9F => match data::C1_REPLACEMENTS[(self.num - 0x80) as usize] { Some(c) => (c, true), None => (conv(self.num), true), }, 0x01..=0x08 | 0x0B | 0x0D....
Rust
0
erver, chat_id): self.wapi_functions.new_messages_observable.subscribe_live_location_updates(observer, chat_id) def unsubscribe_new_messages(self, observer): self.wapi_functions.new_messages_observable.unsubscribe_new_messages(observer) def unsubscribe_acks(self, observer): self.wapi_f...
Python
1
::stdin; use std::error::Error; use midir::{MidiInput, Ignore, MidiInputPort}; use std::{env, fs}; use csv::{Error as CsvError, StringRecord}; const MIDI_INPUT_NAME: &str = "kitara-midi-input"; // number of frets in each string: 22 + open string const NUM_FRETS: usize = 23; // number of strings: 6 const NUM_STRINGS...
Rust
0
IntegerWeight::new(21 + 18*55), /// ]); /// /// ``` pub fn shortest_distance<F: ExpandedFst>(fst: &F, reverse: bool) -> Fallible<Vec<<F as CoreFst>::W>> where <<F as CoreFst>::W as Semiring>::ReverseWeight: 'static, { if !reverse { _shortest_distance(fst) } else { let rfst: VectorFst<_> = ...
Rust
0
n("more warez", filtered_event2.unsigned) # Invite_room_state is allowed in events of type m.room.member self.assertIn("invite_room_state", filtered_event2.unsigned) self.assertEqual([], filtered_event2.unsigned["invite_room_state"]) def test_strip_event_removes_fields_based_on_event_type(s...
Python
1
def build_neck(neck_name, **kwargs): if neck_name not in NECK_MAP: raise ValueError( f'Neck {neck_name} not supported. Supported neck types: {NECK_MAP.keys()}' ) neck = NECK_MAP[neck_name](**kwargs) return neck
Python
1
#!/usr/bin/env python3 # Test whether a client sends a correct PUBLISH to a topic with QoS 2. # The client should connect to port 1888 with keepalive=60, clean session set, # and client id publish-qos2-test # The test will send a CONNACK message to the client with rc=0. Upon receiving # the CONNACK the client should ...
Python
1
_grads=True) assert gathered_tensor.shape == torch.Size([2, 2, 2]) return gathered_tensor.sum() model = TestModel() trainer = Trainer( default_root_dir=tmp_path, limit_train_batches=1, limit_val_batches=0, max_epochs=1, accelerator="gpu", ...
Python
1
from components.components import howest_container_primary, howest_container_secondary, powered_by_howest_footer from utils.utils import load_env, get_howest_logo, file_to_df from style import style import streamlit as st from PIL import Image import pandas as pd import time # Page configuration st.set_page_config("Ho...
Python
1
ne => { println!("No log streams found!"); Err(()) } } } <gh_stars>1-10 //! Tests for parsing RustSec advisories #![warn(rust_2018_idioms, unused_qualifications)] use rustsec::{advisory::Severity, database::Query, package}; /// Load example advisory from the filesystem fn load_ad...
Rust
0
Level_i32> for NcLogLevel { fn from(log_level: c_api::NcLogLevel_i32) -> Self { use {c_api::*, NcLogLevel::*}; match log_level { NCLOGLEVEL_SILENT => Silent, NCLOGLEVEL_PANIC => Panic, NCLOGLEVEL_FATAL => Fatal, NCLOGLEVEL_E...
Rust
0
""" Simple Travel Planner using OpenAI SDK with GitHub Models A basic script for travel planning assistance without classes. """ import os from openai import OpenAI from dotenv import load_dotenv # Load environment variables from .env file load_dotenv() GITHUB_TOKEN = os.getenv("GITHUB_TOKEN") # Initialize OpenAI cl...
Python
1
de; mod model; pub mod util; pub use self::model::*; <reponame>serzhiio/async-native-tls use std::future::Future; use std::io::{Read, Write}; use std::marker::Unpin; use std::pin::Pin; use std::ptr::null_mut; use std::task::{Context, Poll}; use native_tls::{Error, HandshakeError, MidHandshakeTlsStream}; use crate::...
Rust
0
from sympy.physics.wigner import wigner_3j import numpy as np lmax = 1 count = 0 nonzero_count = 0 # Count nonzero L triples. lcount = 0 for l1 in range(lmax + 1): for l2 in range(lmax + 1): for l3 in range(lmax + 1): if (np.abs(l1 - l2) <= l3) and (l3 <= l1 + l2): lcount += 1 ...
Python
1
't signed by the preceeding cert (or itself, if first), fail. cert.verify_signature(previous)?; // If the cert isn't valid (temporally), fail. if !cert.validity().is_valid() { return Err(ChainError::InvalidDate); } // Update state for the nex...
Rust
0
_provider(); let vp_iter = provider.vp_iter(); let mut vp_id = 0; let register_id = RegisterRawId { register_id_x86: RegisterIdx86::Ecx, }; assert_eq!(4, provider.vp_count().unwrap()); for vp in vp_iter { assert_eq!(vp_id, vp.id()); println!("Iterating in vp {}", vp_id)...
Rust
0
] pub struct MI_ConstStringAField { pub value: MI_ConstStringA, pub exists: u8, pub flags: u8, } impl ::core::marker::Copy for MI_ConstStringAField {} impl ::core::clone::Clone for MI_ConstStringAField { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: 'Win32_Syste...
Rust
0
es_grad_(True) with torch.enable_grad(): # Forward pass logits = self.model( inputs_embeds=input_embeds, past_key_values=self._get_batch_prefix_cache(len(input_embeds)), use_cache=True, ).logits # Compute loss and ...
Python
1
log messages, and /// when dumping paths. If `false`, the module name will be omitted. /// You may want to use `false` for `Project`s with only a single bitcode /// file, or if the LLVM module is clear from the function name. /// /// Default is `true`. pub print_module_name: bool, } #[derive(P...
Rust
0
from re import Match from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from aiogram.types import Message async def safe_delete_message(msg: 'Message') -> None: try: await msg.delete() except Exception: ... def split_list2chunks(lst: list[Any], chunk_size: i...
Python
1
Rgb(255, 0, 0); /// let cyan = genpdf::style::Color::Cmyk(255, 0, 0, 0); /// let grey = genpdf::style::Color::Greyscale(127); /// ``` #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Color { /// An RGB color with red, green and blue values between 0 and 255. Rgb(u8, u8, u8), /// An CMYK color with cyan...
Rust
0
y (simplified version) def detect_holidays(timestamps: List[datetime.datetime], country_code: str = 'DE') -> List[bool]: """ Detect holidays in timestamp list (simplified implementation) Args: timestamps: List of datetime objects country_code: Country code for holida...
Python
1
last paused media players.""" if match_result.is_match: # Save entity ids of paused media players self.last_paused.update( intent_obj.context, (s.entity_id for s in match_result.states) ) return await super().async_handle_states( intent_ob...
Python
1
as_raw_Layer(&self) -> *const c_void { self.inner_as_raw() } } impl crate::dnn::LayerTrait for PtrOfTanHLayer { #[inline] fn as_raw_mut_Layer(&mut self) -> *mut c_void { self.inner_as_raw_mut() } } pub type VectorOfMatShape = core::Vector<crate::dnn::MatShape>; impl VectorOfMatShape { pub fn as_raw_Vect...
Rust
0
# SPDX-FileCopyrightText: 2023 The Shadowserver Foundation # # SPDX-License-Identifier: AGPL-3.0-or-later # -*- coding: utf-8 -*- """ Created on Thu Jul 27 19:44:44 2023 """ import logging import unittest import unittest.mock as mock from intelmq.bots.parsers.shadowserver.parser import ShadowserverParserBot import i...
Python
1
: # pixel2style2pixel return latent_dict # Obtain the padding coefficient map, # currently shaped as [batch_size, 512, 32, 32] obtained by convolving # the 32x32 FPN feature map with the padding extractor (and modulation # head). padding_map = self.padding_extractor...
Python
1
Some(curr_block.exit[0]); } Branch => { let bool_args = get_args::<bool>(value_store, 1, args)?; check_num_labels(2, labels)?; let exit_idx = if bool_args[0] { 0 } else { 1 }; *next_block_idx = Some(curr_block.exit[exit_idx]); } Return => { out.flush().map_err(|e| InterpEr...
Rust
0
(&ident).unwrap(); if let Some(var) = instance.variables.get_mut(&indirvar.name) { Ok(ValueLoc::Mut(var)) } else { // fallback to instance functions let objspec = self.global.objects.get(&instance.objtype).ok_or_else(|| "internal error...
Rust
0
# Copyright 2021 Ecosoft Co., Ltd. (http://ecosoft.co.th) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models class ResPartner(models.Model): _inherit = "res.partner" pit_move_ids = fields.One2many( comodel_name="account.withholding.move", ...
Python
1
frac(2, 3), frac(1, 1), frac(3, 2), frac(2, 1), frac(3, 1) ] ); let sb30 = stern_brocot_sequence(20); for i in 1..sb30.len() { assert!(sb30[i - 1] < sb30[i]); } } } <reponame>timo-cmd2/Ecopay<gh...
Rust
0
self.make_this_hovered_status(ctx); } else { self.make_this_none_status(ctx); } } pub fn get_area(&self) -> numeric::Rect { self.texture.get_drawing_area() } } impl DrawableComponent for FramedButton { fn draw(&mut self, ctx: &mut ggez::Context) -> ggez...
Rust
0
cp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x562, &mut x563, x561, x540, 0xffffffff); let mut x564: u32 = 0; let mut x565: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x564, &mut x565, x563, x542, 0xffffffff); let mut x566: u32 = 0; let mut x567: fiat_secp256k1_u1 = 0; fiat_secp256k1_s...
Rust
0
import telebot from get_config import get_config import socket import socks import requests # 替换为您的 Telegram Bot Token bot_token = get_config()['mygptforbot'] # bot_token = get_config()['clsvipBot'] socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", 10808) socket.socket = socks.socksocket #使用socks建立连接 bot = telebot.T...
Python
1
ed" YARD_OUTLINED = "yard_outlined" YOUTUBE_SEARCHED_FOR = "youtube_searched_for" YOUTUBE_SEARCHED_FOR_SHARP = "youtube_searched_for_sharp" YOUTUBE_SEARCHED_FOR_ROUNDED = "youtube_searched_for_rounded" YOUTUBE_SEARCHED_FOR_OUTLINED = "youtube_searched_for_outlined" ZOOM_IN = "zoom_in" ZOOM_I...
Python
1
from os import kill from signal import SIGKILL from subprocess import PIPE, Popen from typing import Optional, Tuple # Indicate timeout with standard exit code E_TIMEOUT = -9 def _kill(proc_id, sudo_kill_delivery_fn): if sudo_kill_delivery_fn: sudo_kill_delivery_fn(proc_id) return...
Python
1