text
string
label_name
string
labels
int64
est_case::test_case; use super::*; const A: &str = "a"; const AX: &str = "a/b/.."; const B: &str = "a/b"; const C: &str = "a/b/c"; const CX: &str = "./a/b/c"; #[test] fn from_config() { assert_eq!( LocalGenerator::new(12, 34)...
Rust
0
class Solution: def minCost(self, basket1: List[int], basket2: List[int]) -> int: swapped = [] count = collections.Counter(basket1) count.subtract(collections.Counter(basket2)) for num, freq in count.items(): if freq % 2 != 0: return -1 swapped += [num] * abs(freq // 2) ...
Python
1
iled to swap slots %i and %i' % (a, b)) def transfer_slots(self, source_slots, target_slots): for slot in source_slots: if slot.is_empty: continue item_id_empty = constants.INV_ITEMID_EMPTY target = self.inventory.find_slot(item_id_empty, target_slots) ...
Python
1
ase)] #[no_mangle] pub unsafe extern "C" fn Java_io_emurgo_rnhaskellshelley_Native_transactionBuilderAddChangeIfNeeded( env: JNIEnv, _: JObject, tx_builder: JRPtr, address: JRPtr ) -> jobject { handle_exception_result(|| { let tx_builder = tx_builder.rptr(&env)?; let address = address.rptr(&env)?; tx_bu...
Rust
0
frame. let (_output, paint_commands) = self.platform.end_frame(); let paint_jobs = self.platform.context().tessellate(paint_commands); // Upload all resources for the GPU. let screen_descriptor = egui_wgpu_backend::ScreenDescriptor { physical_width: window.inner_size().width...
Rust
0
ight (c) 2020 Huawei Technologies Co.,Ltd. All rights reserved. // // StratoVirt is licensed under Mulan PSL v2. // You can use this software according to the terms and conditions of the Mulan // PSL v2. // You may obtain a copy of Mulan PSL v2 at: // http://license.coscl.org.cn/MulanPSL2 // THIS SOFTWARE IS PR...
Rust
0
models provide a ``ToolMenu`` instance for easy access to their tools. .. note:: Use shift key when right clicking to display the native context menu. """) #----------------------------------------------------------------------------- # Private API #-----------------------------------------------...
Python
1
ed Position Report #[serde(rename = "BL")] AdjustedPositionReport, /// Allocation Instruction Alert #[serde(rename = "BM")] AllocationInstructionAlert, /// Execution Acknowledgement #[serde(rename = "BN")] ExecutionAcknowledgement, /// Contrary Intention Report #[serde(rename = "BO")] ContraryIntentionReport...
Rust
0
name\":\"<NAME>\"},{\"name\":\"<NAME>\"}]}\n", ); assert_cmd.assert().success().stdout("3\n"); } #[test] fn should_print_out_count_when_count_flag_is_specified() { let mut cmd = Command::main_binary().unwrap(); cmd.arg("--count"); let mut stdin_cmd = cmd.with_stdi...
Rust
0
# -*- coding: utf-8 -*- """High level wrapper for TCPIP resources. This file is part of PyVISA. :copyright: 2014-2024 by PyVISA Authors, see AUTHORS for more details. :license: MIT, see LICENSE for more details. """ from .. import constants from .messagebased import ControlRenMixin, MessageBasedResource from .resou...
Python
1
dist = np.sqrt((point_x - robot_x) ** 2 + (point_y - robot_y) ** 2) # Calculate the absolute angle difference between robot heading and base2point_yaw angle_diff = abs(robot_heading - base2point_yaw) angle_diff = min(angle_diff, 2 * np.pi - angle_diff) # Normalize angle to be within [0, π]...
Python
1
F_TYPE_HARDWARE; attr.config = match event { BackendStalls => sys::perf_hw_id_PERF_COUNT_HW_STALLED_CYCLES_BACKEND, BranchInstructions => sys::perf_hw_id_PERF_COUNT_HW_BRANCH_INSTRUCTIONS, BranchMisses => sys::perf_hw_id_PERF_COUNT_HW_BRANCH_MISSES, BusCycles => s...
Rust
0
pub_date": "2020-06-25T14:14:19Z", "signature": "{}", "url": "{}", "with_elevated_task": "{}" }} "#, version, public_signature, download_url, with_elevated_task ) } fn generate_sample_bad_json() -> String { r#"{ "version": "v0.0.3", "notes": "Bl...
Rust
0
# FIXME: Try to respect vocab_dir somehow? vocab = load_vocab(args.vocab_dir or args.model, args.vocabtype) special_vocab = gguf.SpecialVocab(model_plus.paths[0].parent, load_merges = args.vocabtype == 'bpe') outfile = args.outfile OutputFile.write_vocab_only(outfile, params, vo...
Python
1
<&str>= inDefine.trim().split(" ").into_iter().collect(); for i in 0..splits.len() { symTable.Symbols.insert(format!("v{}", i), splits[i].trim().to_string()); } } if it.get(2).is_some() { let inDefine...
Rust
0
_buffer_count); write_bits!(24, 27, bits_1, receive_buffer_count); write_bits!(28, 31, bits_1, exchange_buffer_count); let mut bits_2: u32 = 0; write_bits!(0, 9, bits_2, data_word_count); write_bits!(10, 13, bits_2, Self::encode_receive_static_type(receive_static_count)); ...
Rust
0
=> None, } } #[test] fn test_linearise() { let context = PyContext::new(); let object: PyClassRef = FromPyObjectRef::from_pyobj(&context.object); let type_type = &context.type_type; let a = new(type_type.clone(), "A", vec![object.clone()], HashMap::new()).unwrap();...
Rust
0
0, 2), cf(0, 3)), Vector4::new(cf(1, 0), cf(1, 1), cf(1, 2), cf(1, 3)), Vector4::new(cf(2, 0), cf(2, 1), cf(2, 2), cf(2, 3)), Vector4::new(cf(3, 0), cf(3, 1), cf(3, 2), cf(3, 3)) ); Some(m) } } } #[cfg(test)] mod test { use basenu...
Rust
0
combined_nms.""" boxes = tf.constant([[[[0, 0, 0.1, 0.1], [0, 0, 0.1, 0.1]], [[0, 0.01, 1, 0.11], [0, 0.6, 0.1, 0.7]], [[0, -0.01, 0.1, 0.09], [0, -0.1, 0.1, 0.09]], [[0, 0.11, 0.1, 0.2], [0, 0.11, 0.1, 0.2]]], [[...
Python
1
ercase() .split(",") .map(|filter| match filter.trim() { "new" => FmtSpan::NEW, "enter" => FmtSpan::ENTER, "exit" => FmtSpan::EXIT, "close" => FmtSpan::CLOSE, "active" => FmtSpan::ACTIVE, "full" =...
Rust
0
""" #07 PILAS Y COLAS """ from collections import deque from queue import Queue # ------------- PILAS ------------- # Sin collections deque pila = [] # Con append agregamos un elemento a la lista (PUSH) pila.append("hola") # con pop, eliminamos el ultimo elemento y este lo retorna (POP) pila.pop() # print(pila) pi...
Python
1
()); } #[test] fn can_convert_to_and_from() { let f = StatusFlags { carry: true, decimal: true, sign: true, overflow: true, interrupt_disabled: false, ..Default::default() }; let byte = f.to_u8(); let r...
Rust
0
#!/usr/bin/env python3 # SPDX-FileCopyrightText: (C) 2022 - 2025 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import os from tests.ui.browser import Browser import tests.ui.common_ui_test_utils as common def test_delete_sensor_main(params, record_xml_attribute): """! Checks that sensors can be deleted f...
Python
1
d finally D. This part of the code is // hideous. // A “face buffer” used to copy parts of the original image into a buffer that will be passed to // luminance to upload to a cubemap face. By the way, you might be wondering what THE FUCK are all // those “* 3” below -> RGB textures. let face_size_bytes = (si...
Rust
0
proc_macro; mod rust; mod rustfmt; pub mod shell; mod toolchain; mod workspace; // We need to prepend " " to `long_help`s. // https://github.com/BurntSushi/ripgrep/blob/9eddb71b8e86a04d7048b920b9b50a2e97068d03/crates/core/app.rs#L533-L539 #[derive(StructOpt, Debug)] #[structopt( author("<NAME> <<EMAIL>>"), about("Ple...
Rust
0
class Employee: def __init__(self, name, id, dept): self.name = name self.id = id self.dept = dept self.salary = 30000 def workDistribution(self, dept): if dept == "Human Resource": print("Collect work distribution details from the manager.") else: ...
Python
1
ursive::new((self.0,self.1,self.2,self.3,self.4,self.5,self.6).into_recursive(), self.7) } } // TODO more /*macro_rules! impl_into_tuple_for_recursive_type { ( $($types: ident),* => => $nested_type:ty => $($accessors:expr),* => /*empty $acessor_prefix:expr*/ ) => { impl< $($types),* > IntoTuple<( $($typ...
Rust
0
SwapKind::Buy { Q.clone() + quantity } else { Q.clone() - quantity }; let two_times_PC_S_times_PC_R = balance!(2) * PC_S * PC_R; let to = (Q_prime.clone() / two_times_PC_S_times_PC_R.clone() + P_I) * Q_prime; let from = (Q.clone() / two_times_PC_S_times_P...
Rust
0
al_lookup_gt_dists = all_gt_dists[0] for i in range(0, size, update_batch_size): update_plan = [] for j in range(update_batch_size): delete_id = i + j insert_id = delete_id + size update_plan.append((0, insert_id)) update_plan.append((2, delete_id)) ...
Python
1
n_display, scene_counter, scene_save_path ] ) prev_scene_btn.click( fn=navigate_to_previous_scene, inputs=[current_scene_index], outputs=[current_scene_index] ).then( fn=update_scene_display, ...
Python
1
) + (x2478 as u64)); let mut x2519: u64 = 0; let mut x2520: fiat_bls381_u1 = 0; fiat_bls381_subborrowx_u64(&mut x2519, &mut x2520, 0x0, x2506, 0xb9feffffffffaaab); let mut x2521: u64 = 0; let mut x2522: fiat_bls381_u1 = 0; fiat_bls381_subborrowx_u64(&mut x2521, &mut x2522, x2520, x2508, 0x1eabfffeb153ffff);...
Rust
0
closest_opponent_to_ball=frame["closest_opponent_to_ball"], a_target_goal=frame["a_target_goal"], b_target_goal=frame["b_target_goal"], distance_from_target_goal=frame["distance_from_target_goal"], possession_target_end=frame["possession_target_end"], ...
Python
1
unt.fetch_add(1, Ordering::Relaxed); pb.inc(1); for output in &mut outputs { output.write_host(&line).expect("failed to write host into output"); } } for output in outputs { output.finalise().expect("failed to finalise output"); }...
Rust
0
# ------------------------------------------------------ # 📚 Topic: Finding the Ones Digit of a Number # 👨‍💻 Author: Muhammad Hammad Zubair # 📅 Date: May 2025 # 📘 Description: # This program prints the ones digit of a given number. # ------------------------------------------------------ # -------------------...
Python
1
import torch import torch.nn as nn from torch.utils.data import Dataset, TensorDataset from torch.utils.data import random_split class Discriminator(nn.Module): def __init__(self, input_dim, hidden_dim=100): super(Discriminator, self).__init__() self.dense0 = nn.Linear(input_dim, hidden_dim) ...
Python
1
ml-sax-InputSource" #[cfg(any(feature = "all", all(feature = "org-xml-sax-InputSource")))] #[deprecated] pub fn parse_InputSource<'env>(&'env self, arg0: impl __jni_bindgen::std::convert::Into<__jni_bindgen::std::option::Option<&'env crate::org::xml::sax::InputSource>>) -> __jni_bindgen::std::result::Re...
Rust
0
self.accept_input_unique(KbgpInput::MouseWheelDown); } } if horizontal { if 0.0 < event.x { self.accept_input_unique(KbgpInput::MouseWheelRight); } else if event.x < 0.0 { self.accept_input_unique(KbgpInput::MouseWheelL...
Rust
0
yIntoRaw, TryIntoString}; <filename>src/day2/mod.rs use crate::common::*; pub enum Command { Forward(isize), Up(isize), Down(isize) } impl Solution<Day2> for AdventOfCode2021 { type Part1Out = isize; type Part2Out = isize; fn part1(input: &Vec<Command>) -> Self::Part1Out { let (hor, d...
Rust
0
<usize> { let buf_len = buf.len(); let start_ptr = buf.as_ptr(); let mut buf_ptr = unsafe { start_ptr.add(buf_len-1) }; while buf_ptr >= start_ptr { let aa = unsafe { *buf_ptr }; if aa == c { return Some(plus_offset_from(buf_ptr, start_ptr)); } buf_ptr = unsaf...
Rust
0
obalLeftRelease, GlobalRightRelease, GlobalMiddleRelease, } #[derive(Debug, Clone, Copy, PartialEq)] pub enum KeyCode { NoKey, AnyKey, Character(char), Left, Right, Up, Down, Enter, Escape, Space, Shift, Control, Alt, Backspace, Tab, Home, End, Delete, Insert, PageUp, Page...
Rust
0
#!/usr/bin/env python3 # # Copyright (C) 2019-2021 checkra1n team # This file is part of pongoOS. # # 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 without li...
Python
1
def bytes(self): b, f = self.bytesFlops() return b
Python
1
] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] pub enum CreditLevel { Zero, One, Two, Three, Four, Five, Six, Seven, Eight, } impl Default for CreditLevel { fn default() -> Self { CreditLevel::Zero } } /// Each campaign_id represents a DPR Proof-of-C...
Rust
0
s = <[String; $n]>::deserialize(deserializer)?; Ok($name(make_pai_array_from_string_array!(s, $($index),*))) } } }; } build_consumed_struct!(Consumed2; 2; 0, 1); build_consumed_struct!(Consumed3; 3; 0, 1, 2); build_consumed_struct!(Consumed4; 4; 0, 1, 2, 3); fn deseria...
Rust
0
|| coord.x() < self.min_x() || coord.y() < self.min_y() { Err(ErrorKind::OutOfBounds.into()) } else { Ok(()) } } /// Checks if an index is valid and inbounds. fn check_index(&self, idx: usize) -> DimensionResult<()> { // NOTE:...
Rust
0
unread: item.classList.contains('unread') }); } } } else { // 테이블 구조 시도 const rows = document.querySelectorAll('tr'); for (let row of rows) { c...
Python
1
: {:?}", err))?; } let new_events = batch.commit(); serde_json::to_string(&new_events) .map_err(|err| JsValue::from(format!("new events could not be serialized: {:?}", err))) } use{ crate::histogram::*, num_traits::{ ops::{ checked::*, wrapping::* }, ...
Rust
0
fidl_fuchsia_net_ext::{IntoExt as _, NetTypesIpAddressExt}; use fidl_fuchsia_net_interfaces_admin as finterfaces_admin; use fidl_fuchsia_net_stack as fnet_stack; use fidl_fuchsia_net_stack_ext::{exec_fidl, FidlReturn as _}; use fidl_fuchsia_netemul as fnetemul; use fuchsia_async::{DurationExt as _, TimeoutExt as _}; u...
Rust
0
\x9f\xFF\x8d\x58\x08\x04\x25\xA3\x01\x2d\x05\xC8"; let keypair = KeyPair::from_bip39_phrase(phrase).unwrap(); assert_eq!(keypair.address(), expected_address); } #[test] fn test_parity_phrase() { let phrase = "this is sparta"; let expected_address = b"\x00\x6E\x27\xB6\xA7\x2E\x1f\x34\xC6\x26\x76\x2F\x3C...
Rust
0
pub type JobIndex = HashMap<String, CoreJob>; /// Gets job index from core problem definition. pub fn get_job_index(problem: &CoreProblem) -> &JobIndex { problem .extras .get("job_index") .and_then(|s| s.downcast_ref::<JobIndex>()) .unwrap_or_else(|| panic!("cannot get job index!")...
Rust
0
let rsa = Rsa::private_key_from_pem(private_key.as_bytes())?; let keypair = PKey::from_rsa(rsa)?; let mut signer = Signer::new(MessageDigest::sha1(), &keypair)?; signer.update(policy.as_bytes())?; Ok(openssl::base64::encode_block(&signer.sign_to_vec()?)) } /// Create a URL safe Base64 encoded stri...
Rust
0
from sqlmodel import SQLModel, Field from typing import Optional from datetime import date class Student(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) instructor_id: int = Field(foreign_key="user.id") name: str email: str = Field(index=True) rut: str = Field(index...
Python
1
te.side_effect = [ # For delete network self._get_mock_response(200, response={}), # For controller leave network self._get_mock_response(200, response={}), ] vpn.delete() self.assertEqual(Vpn.objects.count(), 0) ...
Python
1
name = "Harry is a good boy and who is real goat" print(name.replace("good","bad")) print(name) #Strings are immutable which means that you cannot change them by running functions on them
Python
1
in lines.iter().skip(25).copied() { let is_valid = (|| { for (iidx, i) in window.iter().enumerate() { for (jidx, j) in window.iter().enumerate() { if i != j && iidx != jidx && i + j == curr { return true; } ...
Rust
0
onesync_enabled_and_disabled( self, cli_arguments, kube_apis, ingress_controller_prerequisites, ingress_controller, ingress_controller_endpoint, ): """ Test: 1. NIC starts without zone-sync configured in the `nginx-config` 2. Apply conf...
Python
1
eturned. pub fn list_fonts<'c, 'input, Conn>(conn: &'c Conn, max_names: u16, pattern: &'input [u8]) -> Result<Cookie<'c, Conn, ListFontsReply>, ConnectionError> where Conn: RequestConnection + ?Sized, { let request0 = ListFontsRequest { max_names, pattern: Cow::Borrowed(pattern), }; requ...
Rust
0
103, InvalidItemType = 104, IPBanned = 105, GSLTExpired = 106, InsufficientFunds = 107, TooManyPending = 108, NoSiteLicensesFound = 109, WGNetworkSendExceeded = 110, AccountNotFriends = 111, LimitedUserAccount = 112, }use std::{io, num::NonZeroU64, path::Path}; use crate::{ buffer_usage_data::BufferUsage...
Rust
0
ption_greed_ending: location.access_rule = lambda state, items_needed=lock.items_needed: ( has_perk_count(state, world.player, items_needed//2) ) elif victory_condition == VictoryCondition.option_pure_ending: location.access_rule = lambda state, items_needed=l...
Python
1
impl From<&ApiCall<'_, '_, '_, '_, '_, '_>> for HTTPRequest<String> { fn from(i: &ApiCall) -> Self { Request::from(i).into() } } use super::SetupRequest; use crate::Never; impl SetupRequest<'_, Never, HTTPRequest<String>> for Builder { fn setup_request(&mut self, r: Request, _params: Never) -> HT...
Rust
0
# Copyright 2013 IBM Corp. # # 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 t...
Python
1
"] if len(parameters) != len(image_relative_fp_list): # Create some dummy names for missing images image_relative_fp_list = ( Open3DFileHandler._create_dummy_fp_list(len(parameters)) ) for pinhole_camera_parameter, image_relat...
Python
1
mplegui.KEY_MAP["down"] and key == simplegui.KEY_MAP["up"]: pass def keyup(key): global paddle1_vel, paddle2_vel # palyer 1 if key == simplegui.KEY_MAP["w"]: paddle1_vel = 0 if key == simplegui.KEY_MAP["s"]: paddle1_vel = 0 if key == simplegui.KEY_MAP["w...
Python
1
ueue: Option<serde_json::Value>, scan_status: Option<serde_json::Value>, } impl Response { /// Extracts the internal value of the response. /// /// # Errors /// /// This method will error if the response contained an error (as defined by /// the [Subsonic API]). /// /// [Subsonic AP...
Rust
0
node_id: [reference NODE] = 0i32, light1_id: [reference LIGHT] = 0i32, light2_id: [reference LIGHT] = 0i32, nodes: [dynamic array [u32] [reference NODE] 0i32] = Vec::new(), unk3: [dynamic array [u32] [u32] 0u32] = Vec::new(), }, NodeDataSkin: T_...
Rust
0
from twisted.internet import reactor from twisted.internet.defer import Deferred from twisted.internet.protocol import Protocol from twisted.web.client import Agent from twisted.web.http_headers import Headers import twisted.internet.defer class ResponsePrinter(Protocol): def __init__(self, finished): self...
Python
1
xp(self.subdeconvolver.b_vals[0]).item())), torch.exp(self.subdeconvolver.b_vals[-1]).item(), self.subdeconvolver.b_vals.numel()).to(self.device).reshape(-1,1) def get_pdf(self, values = None,log_prob=False): if values is...
Python
1
cess_tac_message(encoded_message) # May succeed with warnings or fail depending on implementation # At minimum should not crash self.assertIsInstance(result, dict) self.assertIn("valid", result) self.assertIn("errors", result) asyncio.run(run_test())...
Python
1
import plotly.graph_objects as go from plotly.subplots import make_subplots from src.utils import PATH def plot_layer(x, lev, num_channels=6, titles=None, save=False, x_range=[None, None]): """ Shape: [batch_size, channels, altitude, latitude, longitude] """ rows = (num_channels + 1) // 2 if title...
Python
1
and_high_index]) # Calculate max/mean power ratio stationary_wavelet_transform_features['template_swt_d_' + str(level+1) + '_low_power_ratio'] = \ max_power_low / mean_power_low stationary_wavelet_transform_features['template_swt_d_' + str(level+1) + '_med_power_rati...
Python
1
from argparse import RawTextHelpFormatter from fa import context, utils try: import ida_search import idc except ImportError: pass DESCRIPTION = '''expands the result-set with the occurrences of the given immediate in "ida immediate syntax" EXAMPLE: 0x00000000: ldr r0, =0x1234 0x00000004: add r0...
Python
1
rmissionOverwriteType::Role, }])), position: Some(0), rate_limit_per_user: None, recipients: None, rtc_region: None, thread_metadata: None, topic: None, user_limit: None, video_quality_mode: None, } }...
Rust
0
irect()).location(); thread::spawn(move || { // Initialize thread-local variable with thread let thread = init_current_thread(thread); thread_main(thread, location); deinit_current_thread(); }); } fn thread_main(thread: &DoraThread, location: Address) { use crate::compiler;...
Rust
0
r("부통령 선거일")), 1952: ( # City/Town/Township-level Local Elections. (APR, 25, local_election_day), # Provincial-level Local Elections. (MAY, 10, local_election_day), # 2nd Presidential Election/3rd Vice President Election. (AUG, 5, president...
Python
1
from aws_cdk import ( aws_ec2 as ec2, aws_batch as batch, aws_ecs as ecs, App, Stack, CfnOutput, Size ) from constructs import Construct class BatchEC2Stack(Stack): def __init__(self, scope: Construct, id: st...
Python
1
.string_field(4) machine_names: list[str] = betterproto.string_field(5) app_buildid_hwm: int = betterproto.uint64_field(6) class AppSessionSuspendRequest(UnifiedMessage, um_name="Cloud.SuspendAppSession"): appid: int = betterproto.uint32_field(1) client_id: int = betterproto.uint64_field(2) machin...
Python
1
/// You **should not** normally use this, because it doesn't allow you to pick /// advanced pixel formats. It's provided just for dummy window creation during /// WGL initialization. /// /// See [`ChoosePixelFormat`](https://docs.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-choosepixelformat) #[cfg_attr(feat...
Rust
0
/// - [`Input::FeedbackClass::Integer`](XCB_INPUT_FEEDBACK_CLASS_INTEGER) /// - [`Input::FeedbackClass::Led`](XCB_INPUT_FEEDBACK_CLASS_LED) /// - [`Input::FeedbackClass::Bell`](XCB_INPUT_FEEDBACK_CLASS_BELL) pub type xcb_input_feedback_class_t = u32; /// The `Input::FeedbackClass::Keyboard` enum variant. /// /// This i...
Rust
0
p(|m| WildMatch::new(m)).collect(); MATCHES.write().unwrap().append(&mut list); } #[derive(Clone, Default)] pub struct MitmFilter; impl MitmFilter { pub async fn filter(_ctx: &HttpContext, req: &Request<Body>) -> bool { let host = req.uri().host().unwrap_or_default(); let list = MATCHES.read()...
Rust
0
example = example[: self.max_words] labels = copy.deepcopy(example) labels[: len(prompt)] = -1 example_mask = example.ge(0) label_mask = labels.ge(0) example[~example_mask] = 0 labels[~label_mask] = IGNORE_INDEX example_mask = example_mask.float() ...
Python
1
output.push(prefix.clone()); }); } } fn preserve<'a>(s: &mut Vec<&'a str>, op: impl FnOnce(&mut Vec<&'a str>)) { let len = s.len(); op(s); s.truncate(len); } crate trait Atom: Copy + From<usize> + Into<usize> { fn table(intern: &InternerTables) -> &Interner<Self>; } impl Atom for Region {...
Rust
0
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.llms.cloudflare_workersai import CloudflareWorkersAI # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising deprecation warnings and # handling op...
Python
1
igo', label_style=ft.TextStyle(color=color, size=12), on_change=checkbox_change, value=condition ) ) index = i[1].index('http') search_list_row.controls.append(ft.TextButton( ...
Python
1
ptions.output_file_name); } eprintln!(); } command.status() }, Phase::Assemble => { //clang {opt_level} -o {output_file} --target={target_triple} {.c, .ll, .bc, and .s files} -c -x ir - let mut command = Command::new("clang"); command .arg(options.opt_level.to_clang_arg_str()) .arg(fo...
Rust
0
""" Classifies: CHEBI:36233 disaccharide """ from rdkit import Chem def is_disaccharide(smiles: str): """ Determines if a molecule is a disaccharide based on its SMILES string. A disaccharide is two monosaccharides joined by a glycosidic bond. Args: smiles (str): SMILES string of the molecule ...
Python
1
from microcontroller import nvm as microcontroller_nvm from . import AbstractAction class Action(AbstractAction): def __init__(self, nvm_method: str, nvm_data: str, app_data: dict): super().__init__('nvm', nvm_method, app_data) self.nvm_data = nvm_data def erase(self) -> None: nvm_...
Python
1
import FWCore.ParameterSet.VarParsing as VarParsing options = VarParsing.VarParsing() options.register('runNumber', 1, VarParsing.VarParsing.multiplicity.singleton, VarParsing.VarParsing.varType.int, "the run number to be uploaded.") options.register('des...
Python
1
w(Box::new(move |cc| Box::new(root_fn(cc)))); // inner box = fat pointer, outer box = winapi compatible thin pointer let hInstance = unsafe { GetModuleHandleW(null_mut()) }; let hwnd = unsafe { CreateWindowExW( 0, wch_c!("ForecastleD3D9").as_ptr(), title.as_ptr(), STYLE | WS_VISIBLE, CW_USEDEF...
Rust
0
xis is None: x_axis = legend[0] elif x_axis not in legend: raise RequiredChoiceError( f"Unknown x-axis '{x_axis}'.", choices=legend ) # Print legend and exit if requested if legend_only or not functions: import rich.table ...
Python
1
if current_history and 0 <= row_index < len(current_history): # 获取选中行的数据 selected_row = current_history[row_index] # 检查是否点击的是第5列(点击加载数据列) if col_index == 4 and len(selected_row) > 4 and selected_r...
Python
1
uardado.") display(df) # COMMAND ---------- # MAGIC %md # MAGIC ##convertir columna a datatime y guardarlo, solo tomando la fecha # COMMAND ---------- import pandas as pd #leer el archivo CSV df = pd.read_csv("/dbfs/mnt/PagWeb/Extract/Separados/separados_web_romanosConvertidos.csv") #convertir la columna 'created...
Python
1
/// Print the machine hardware name. pub machine: bool, /// Print the processor type (non-portable). pub processor: bool, /// Print the hardware platform (non-portable). pub hardware_platform: bool, /// Print the operating system. pub operating_system: bool, } impl Default for Option...
Rust
0
KLENB : usize; fn bytes_ref_keb(&'a self) -> Self::Bytes; fn kelem_eq_keb(&self, other: &Self) -> bool; } // TODO test without HRTB : put pub struct SimpleDHTElemBytes<KEB>(pub KEB, pub BitVec) where for<'a> KEB: DHTElemBytes<'a>; impl<KEB> SimpleDHTElemBytes<KEB> where for<'a> KEB: DHTEl...
Rust
0
let n = a.len(); let mut i: usize = 0; let mut line: u32 = 0; let mut col: u32 = 0; while i<n { let c = a[i]; if c.is_ascii_alphabetic() { let j = i; let col0 = col; while i<n && a[i].is_ascii_alphabetic() { i+=1; col+=1; } ...
Rust
0
irit { #[inline] fn can_from(value: &Spirit) -> bool { <LivingSpirit as CanFrom<Spirit>>::can_from(value) && <FriendlySpirit as CanFrom<Spirit>>::can_from(value) } } try_can_from!(impl TryFrom<Spirit>, Error = Spirit for LivingFriendlySpirit); impl AsRef<Spirit> for LivingFriendlySpiri...
Rust
0
pub(crate) fn generate_shared_secrets<ESK, H>( circuit_pub_keys: &[<ESK as DiffieHellman>::PK], mut session_key: ESK, ) -> Result<Vec<<ESK as DiffieHellman>::SSK>, SfynxError> where ESK: SecretKey + DiffieHellman + Blind + ToVec, <ESK as SecretKey>::PK: ToVec, ESK::SSK: ToVec, H: Hash, { if ...
Rust
0
ption: "cert not found".to_owned(), })?; Ok(cert) } fn get_key_by_hash(&self, hash: &str) -> Result<Vec<u8>, StorageError> { let key = self .keys .get_collection() .get(hash) .cloned() .ok_or_else(|| MemoryStorageError::Oth...
Rust
0
from typing import Optional, Union, List from phi.k8s.app.superset.base import SupersetBase class SupersetWebserver(SupersetBase): # -*- App Name name: str = "superset-ws" # Command for the container command: Optional[Union[str, List[str]]] = "webserver" # -*- App Ports # Open a container p...
Python
1
* * Generated by: https://github.com/swagger-api/swagger-codegen.git */ /// GetCharactersCharacterIdContactsLabels200Ok : 200 ok object #[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct GetCharactersCharacterIdContactsLabels200Ok { /// label_id integer #[serd...
Rust
0
assert_eq!(lapper.seek(i.start, i.stop, &mut cursor).count(), 1); /// } /// ``` #[inline] pub fn seek<'a>(&'a self, start: I, stop: I, cursor: &mut usize) -> IterFind<'a, I, T> { if *cursor == 0 || (*cursor < self.intervals.len() && self.intervals[*cursor].start > start) { ...
Rust
0