text
string
label_name
string
labels
int64
molecule_sets = [ 'melatonin-and-metabolites', 'clinical-melatonin-receptor-agonists', 'enamine-melatonin-realspace-analogues', 'covid_submissions_03_26_2020', ] # Read ligands def read_molecules(filename): """Read molecules from the specified path Parameters ---------- filename : str ...
Python
1
import os directory = "" albedo = ['albedo','basecolor'] metal = ['metalness', 'metallic'] rough = ['roughness'] normal = ['normal'] height = ['height'] list_albedo = [] list_metal = [] list_rough = [] list_normal = [] list_height = [] # for each file in the directory and subdirectory check if it has the word albe...
Python
1
-3)] class LogoGenerationFivefold(LogoGenerationTemplate): def construct(self): logo = self.logo iris, spike_layers, pupil = logo name = OldTexText("3Blue1Brown") name.scale(2.5) name.next_to(logo, DOWN, buff=MED_LARGE_BUFF) name.set_gloss(0.2) self.add(i...
Python
1
maintaining the total weight of connected components. //! //! **Balanced binary search trees**: A [balanced binary search tree][3] organizes search keys and //! their associated payload in a way such that the resulting binary tree has a minimal height, //! given the number of items stored, resulting in query and updat...
Rust
0
self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `NSCN`"] pub enum NSCNW { #[doc = "Once per electrode"] _00000, #[doc = "Twice per electrode"] _00001, #[doc = "3 time...
Rust
0
= if self.radix == 10 { match (self.value.is_negative(), new_value.is_negative()) { (true, false) => old_length - 1, (false, true) => old_length + 1, _ => old_text.len(), } } else { old_text.len() - 2 } - separator_rtl_...
Rust
0
} #[simd_test(enable = "neon")] unsafe fn test_vmax_s8() { let a: i8x8 = i8x8::new(1, 2, 3, 4, 5, 6, 7, 8); let b: i8x8 = i8x8::new(16, 15, 14, 13, 12, 11, 10, 9); let e: i8x8 = i8x8::new(16, 15, 14, 13, 12, 11, 10, 9); let r: i8x8 = transmute(vmax_s8(transmute(a), transmute(b)...
Rust
0
# The following meta-model has an inheritance relation: mm_cs = """ MyAbstractClass:Class { abstract = True; } MyConcreteClass:Class :Inheritance (MyConcreteClass -> MyAbstractClass) Z:Class myZ:Association (MyAbstractClass -> Z) { target_lower_cardinality = 1; } """ #...
Python
1
u16, name: name.detach_small(start), public1: p1, public2: p2, }, }) } } // ExternalID ::= 'SYSTEM' S SystemLiteral | 'PUBLIC' S PubidLiteral S SystemLiteral fn parse_external_id(s: &mut Stream<'a>, start: usiz...
Rust
0
file.to_string(), result); } else { println!("{}", &result); } } use super::*; mod link; pub use self::link::Link; mod link_markers; pub use self::link_markers::LinkMarkers; mod link_lock; pub use self::link_lock::LinkLock; mod link_lock_lock { use super::*; #[repr(C)] pub struct LinkLo...
Rust
0
pid=APP_PID, tid=SECOND_APP_TID) # JIT compilation slices trace.add_atrace_begin( ts=150, pid=APP_PID, tid=JIT_TID, buf='JIT compiling something') trace.add_atrace_end(ts=160, pid=APP_PID, tid=JIT_TID) trace.add_sched(ts=155, prev_pid=0, next_pid=JIT_TID) trace.add_sched(ts=165, prev_pid=JIT_TID, next_pid=0) tra...
Python
1
#! usr/bin/python3.9 """ Module initially auto generated using V5Automation files from CATIA V5 R28 on 2020-06-11 12:40:47.360445 .. warning:: The notes denoted "CAA V5 Visual Basic Help" are to be used as reference only. They are there as a guide as to how the visual basic / catscript function...
Python
1
# -*- coding: utf-8 -*- """ Created on Tue Nov 13 14:25:26 2018 @author: ilys """ import numpy as np import pickle import os import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import myutulities as mu from os import listdir from os.path import isfile, join from scipy.interpolate import interp1d...
Python
1
sns.heatmap(label_v1_mask, annot=True, cmap='coolwarm') # annot=True显示数值,cmap='coolwarm'指定颜色映射 # plt.title('Heatmap of the Matrix') # 添加标题 # plt.show() # plt.savefig(f'/home/fsj/projects/HEAL_FSJ/img_save_encoder/{cav_id}_label_v1_mask.png',...
Python
1
pports partial ordering. However, we know // the day fraction is not NaN (see DateDayFraction::new) // so we can just panic if the order does not exist. match self.partial_cmp(&other) { Some(order) => order, None => panic!("DateDayFraction contains NaN day-fraction") ...
Rust
0
km } else { KeyMap::Action(action) } } }; *self = new_map; } pub fn match_keys(&self, keys: &[Key]) -> KeyMatch { match *self { KeyMap::Node(ref km) => { match keys.len() { ...
Rust
0
ntry>) -> AsleepPlan { let mut plan = AsleepPlan::new(); if log.len() == 0 { return plan; } let mut id = 0; let mut last_time = log[0].time; let mut asleep = true; for &LogEntry {time, event} in log.iter() { match event { Event::Begin(x) => { id...
Rust
0
defined insta::assert_snapshot!( run_query!(&runner, r#"{ findManyTestModel( where: { AND: [ { b: { isSet: true } }, { b: { isNot: { b_field: "b_1" } } }, ] } ) { id } }"#), @r###"{"data":{"findMany...
Rust
0
├─ Timeout: ", end="") ASCIIColors.yellow(f"{args.timeout if args.timeout else 'None (infinite)'}") ASCIIColors.white(" ├─ LLM Cache Enabled: ", end="") ASCIIColors.yellow(f"{args.enable_llm_cache}") ASCIIColors.white(" └─ LLM Cache for Extraction Enabled: ", end="") ASCIIColors.yellow(f"{a...
Python
1
#!/usr/bin/env python3 import argparse from dataclasses import dataclass import jinja2 def get_args(): parser = argparse.ArgumentParser() parser.add_argument( "--total", type=int, default=1, help="Number of runners", ) parser.add_argument( "--index", t...
Python
1
{ match Self::from(&cipherSuiteName) { Some(cipherSuite) => Ok(cipherSuite), None => Err(CipherSuiteParseError::Unknown(s.to_owned())), } }, } } } impl CipherSuite { const NoCipherSuiteId: c_int = 0; #[inline] fn nulTerminatedCipherSuiteListSize(list: *const c_int) -> usize { const i...
Rust
0
def start_train(): logits = inference() loss = losses(logits, Y) train_op = train_step(loss) accuracy = evaluation(logits, Y) saver = tf.train.Saver(max_to_keep=2) with tf.Session() as sess: merged = tf.summary.merge_all() summary = tf.summary.FileWriter("logs", sess.graph) ...
Python
1
from tests.runtime_aggtest.aggtst_base import TstView class aggtst_array_every(TstView): def __init__(self): # Validated on Postgres self.data = [{"c1": False, "c2": False}] self.sql = """CREATE MATERIALIZED VIEW array_every AS SELECT EVERY(c1 > c2) AS c1, EVERY(c2 > ...
Python
1
Clone)] pub struct growbuf { pub pt: *mut ::std::os::raw::c_uchar, pub base: *mut ::std::os::raw::c_uchar, pub end: *mut ::std::os::raw::c_uchar, } #[test] fn bindgen_test_layout_growbuf() { assert_eq!( ::std::mem::size_of::<growbuf>(), 24usize, concat!("Size of: ", stringify!(gr...
Rust
0
base1.clone(), result2: result2.clone(), base2: base2.clone(), blinded_base1, blinded_base2, r } } pub fn verify(&self) -> bool { let c = Self::challenge(&self.base1, &self.base2, &self.result1, &self.result2, &self.blinded_base1, &se...
Rust
0
`y_pred` will be used. include_values : bool, default=True Includes values in confusion matrix. xticks_rotation : {'vertical', 'horizontal'} or float, \ default='horizontal' Rotation of xtick labels. values_format : str, default=None ...
Python
1
turn value, transfered bytes pub ret: i32, } impl UhyveWrite { pub fn new(data: usize, len: usize) -> Self { UhyveWrite { data: data, len: len, ret: 0, } } pub fn ret(&self) -> i32 { unsafe { read_volatile(&self.ret) } } pub fn len(&self) -> usize { unsafe { read_volatile(&self.len) } } } pu...
Rust
0
#!/usr/bin/env python # encoding: utf-8 # Carlos Rafael Giani, 2007 (dv) # Thomas Nagy, 2008-2010 (ita) import sys from waflib.Tools import ar, d from waflib.Configure import conf @conf def find_dmd(conf): """ Find the program *dmd*, *dmd2*, or *ldc* and set the variable *D* """ conf.find_program(['dmd', 'dmd2', ...
Python
1
import os, shutil from update import Update import subprocess, zipfile from bz2 import BZ2File def test_delta_exists(env): for de in env.get_deltaZipPaths(): assert os.path.exists(de) for dm in env.get_deltaManifestPaths(): assert os.path.exists(dm) def test_delta_manifest_parse(env): for dm in env.get...
Python
1
m() si(torch.cat( [torch.cat([x, x_s, x_adv_diff_region, x_adv_diff_p_region, mask], -1), 10*torch.cat([x-x, x_s-x, x_adv_diff_region-x_s, x_adv_diff_p_region-x_adv_diff_region, mask], -1) ],-2) , save_path + f'/{exp_name}_final{y_final}.png') for exp_name in ['tr...
Python
1
import heapq def shortest_path(matrix): rows, cols = len(matrix), len(matrix[0]) start, end = (3, 12), (7, 3) graph = {(i, j): [] for i in range(rows) for j in range(cols) if matrix[i][j] != 'x'} for i in range(rows): for j in range(cols): if matrix[i][j] != 'x': fo...
Python
1
num_pos() g.graph["num_gates"] = self.num_gates() if levels: g.graph["levels"] = depth_aig.num_levels() + 1 # + 1 for the PO level if graph_tts: g.graph["function"] = graph_funcs # Iterate over all nodes in the AIG, plus synthetic PO nodes for node in self.nodes() + [self.po_index(...
Python
1
import os import matplotlib.pyplot as plt import numpy as np import pandas as pd mesh = np.load('mesh.npy', allow_pickle=True).flat[0] offset = 0.88 auc_grid = mesh['auc_grid']-offset aupr_grid = mesh['aupr_grid']-offset auc_grid[auc_grid<0]=0 aupr_grid[aupr_grid<0]=0 print(auc_grid) print(aupr_grid) # auc_grid ...
Python
1
//! let height: u8 = 2; //! let width: u8 = 16; //! let lcd = components::hd44780::HD44780Component::new(mux_alarm, width, height).finalize( //! components::hd44780_component_helper!( //! stm32f429zi::tim2::Tim2, //! // rs pin //! gpio_ports.pins[5][13].as_ref().unwrap(), //! // en ...
Rust
0
from .common import InfoExtractor class MuseScoreIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?musescore\.com/(?:user/\d+|[^/]+)(?:/scores)?/(?P<id>[^#&?]+)' _TESTS = [{ 'url': 'https://musescore.com/user/73797/scores/142975', 'info_dict': { 'id': '142975', 'ext'...
Python
1
from enum import Enum from typing import Optional, Dict, Any from datetime import datetime from fastapi import HTTPException, status from pydantic import BaseModel class ErrorType(str, Enum): VALIDATION = "validation" AUTH = "auth" NOT_FOUND = "not_found" CONFLICT = "conflict" INTERNAL = "internal...
Python
1
save_path = os.path.join( hparams["save_folder"], "baseline_audio_results" ) save_path_enhanced = os.path.join(save_path, "enhanced_testclips") if not os.path.exists(save_path_enhanced): os.makedirs(save_path_enhanced) # Estimated source signal = predict...
Python
1
dinary => oref.to_s(), ObjKind::Regexp(rref) => format!("({})", rref.as_str()), _ => format!("{:?}", self_val), }, _ => unreachable!(), }; Ok(Value::string(s)) } fn inspect(vm: &mut VM, self_val: Value, _: &Args) -> VMResult { match self_val.as_rvalue() { So...
Rust
0
} #[allow(unused_mut)] let mut scope_3622 = writer.prefix("DryRun"); if let Some(var_3623) = &input.dry_run { scope_3622.boolean(*var_3623); } writer.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_describe_transit_gateway_multicast_d...
Rust
0
attn_weights: Optional[Tensor] = None if need_weights and isinstance(unnormalized_attn_weights, Tensor): wsz = src_len if self.slide_mode == "stride" and not self.sample_attn_swz == "global": wsz = self.sample_attn_swz + 1 attn_weights = unnormalized_...
Python
1
character in line.clone() { if closers.contains(&character) { let ind = closers.iter().position(|&x| x == character).unwrap(); if str_vec[str_vec.len() - 1] != beginners[ind] { incomplete = false; break 'outer; } else {...
Rust
0
], remappings=[ ('/image_raw', '/camera/image_raw'), ('/camera_info', '/camera/camera_info') ] ) return LaunchDescription([ LogInfo(msg="Starting control_node..."), RegisterEventHandler( event_handler=OnProcessStart( target_a...
Python
1
let f: &F = &*(f as *const F); f( &WebView::from_glib_borrow(this).unsafe_cast(), &from_glib_borrow(request), ) .to_glib() } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.a...
Rust
0
#!/usr/bin/python # -*- coding: utf-8 -*- DATA=[ 0x08,0x02,22,97,38,15,0x00,40,0x00,75,0x04,0x05,0x07,78,52,12,50,77,91,0x08, 49,49,99,40,17,81,18,57,60,87,17,40,98,43,69,48,0x04,56,62,0x00, 81,49,31,73,55,79,14,29,93,71,40,67,53,88,30,0x03,49,13,36,65, 52,70,95,23,0x04,60,11,42,69,24,68,56,0x01,32,56,71,37,0x02,36,91...
Python
1
sys::webkit_hit_test_result_get_link_uri(self.as_ref().to_glib_none().0)) } } fn get_media_uri(&self) -> Option<GString> { unsafe { from_glib_none(webkit2_sys::webkit_hit_test_result_get_media_uri(self.as_ref().to_glib_none().0)) } } } impl fmt::Display for HitTestResul...
Rust
0
Request) -> Option<&ChangePeerRequest> { if !msg.has_admin_request() { return None; } let req = msg.get_admin_request(); if !req.has_change_peer() { return None; } Some(req.get_change_peer()) } fn check_sst_for_ingestion(sst: &SSTMeta, region: &Region) -> Result<()> { let u...
Rust
0
* `b` - value multiplied by the imaginary number `j` in `q = ai + bj + ck + r` /// * `c` - value multiplied by the imaginary number `k` in `q = ai + bj + ck + r` /// * `r` - The real number denoted `r` in `q = ai + bj + ck + r` pub fn new(a: T, b: T, c: T, r: T) -> Self { Quaternion(a, b, c, r)...
Rust
0
ion_key.as_mut().unwrap() } // Take field pub fn take_encryption_key(&mut self) -> ::std::vec::Vec<u8> { self.encryption_key.take().unwrap_or_else(|| ::std::vec::Vec::new()) } } impl ::protobuf::Message for CVideo_UnlockedH264_Notification { fn is_initialized(&self) -> bool { true ...
Rust
0
2_unsafe(SafeUMx::min_value()) == (usize::min_value() as u32)); assert!(to_u64_unsafe(SafeUMx::min_value()) == (usize::min_value() as u64)); assert!(to_umx_unsafe(SafeUMx::min_value()) == (usize::min_value() as usize)); } #[test] fn convert_from_raw_umx_to_unsafe() { assert!(to_u8_u...
Rust
0
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from .predict import OBBPredictor from .train import OBBTrainer from .val import OBBValidator __all__ = "OBBPredictor", "OBBTrainer", "OBBValidator"
Python
1
.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &::std::any::Any { self as &::std::any::Any } fn as_any_mut(&mut self) -> &mut ::std::any::Any { self as &mut ::std::any::Any } ...
Rust
0
push(0x90), 2 => { patch_bytes.push(0x66); patch_bytes.push(0x90); } 3 => { patch_bytes.push(0x0f); patch_bytes.push(0x1f); patch_bytes.push(0x00); } 4 => { patch_bytes.push(0x0f); patch_bytes.pus...
Rust
0
), pc(1, 1, 0) )).await; } #[tokio::test] async fn test_div_max_price_2() { test_instr(instruction::divide( pc(i64::MAX, 1, 0), pc(i64::MAX, 1, 0) )).await; } #[tokio::test] async fn test_mul_max_price() { test_instr(instruction::multiply( pc(i64::MAX, 1, 2), pc...
Rust
0
h); assert!( res.is_ok(), "failed to call C_WrapKey({}, {:?}, {}, {}) without parameter: {}", sh, &mechanism, wrapOh, secOh, res.unwrap_err() ); let wrappedKey = res.unwrap(); println!( "Wrapped Key Bytes (Total of {} bytes): {:?}", wrappedKey.len(), wrappedKey ); } #[...
Rust
0
int(c) # 2,求矩阵的秩 u,v=np.linalg.eig(b) # u为特征值 print(u) print(v) # 矩阵分解 # Cholesky分解并重建 d = np.array([ [2, 1], [1, 2] ]) l = np.linalg.cholesky(d) print(l) # 得到下三角矩阵 e=np.dot(l, l.T) print(e) # 重建得到矩阵d # 对不正定矩阵,进行SVD分解并重建 U, s, V = np.linalg.svd(d) S = np.array([ [s[0], 0], [0, s[1]]...
Python
1
""" Performance benchmark tests for KuzuMemory. Tests performance characteristics and ensures operations meet required thresholds. """
Python
1
destructive of the stylesheet. pub fn from_document<'a>( d: Rc<dyn Document>, resultdoc: &'a dyn Document, sc: &StaticContext ) -> Result<DynamicContext<'a>, Error> { let mut dc = DynamicContext::new(Some(resultdoc)); // Check that this is a valid XSLT stylesheet let root = match d.get_root_element(...
Rust
0
#[cfg_attr(feature = "inline", inline)] #[cfg_attr(feature = "inline_always", inline(always))] pub unsafe fn glFinish() { #[cfg(all(debug_assertions, feature = "debug_trace_calls"))] { trace!("calling glFinish();",); } let out = call_atomic_ptr_0arg("glFinish", &glFinish_p); #[cfg(all(debu...
Rust
0
csv = self.mimeview.convert_content(self.req, 'trac.ticket.Ticket', ticket, 'tab') content = ('\ufeff' 'id\tsummary\treporter\towner\tdescription\tstatus\t' 'keywords\tcc\r\n' '1\tFoo\tsanta@…\tjoe@…\tBar\tnew\...
Python
1
(*atom.read(urids.float).unwrap(), second_value); } } } #![no_main] #[macro_use] extern crate libfuzzer_sys; extern crate ethereum_types; extern crate ssz; use ethereum_types::H256; use ssz::{DecodeError, Decodable}; // Fuzz ssz_decode() fuzz_target!(|data: &[u8]| { let result: Result<(H256, usize), D...
Rust
0
rent_step', return_value=True) as mock_validate, \ patch.object(panel, '_complete_wizard') as mock_complete: WizardServicePanel.next_step(panel) # データ収集と検証が呼ばれる mock_collect.assert_called_once() mock_validate.assert_called_once() ...
Python
1
agementService, > { management_service_server::ManagementServiceServer::new(ManagementService { application, server, }) } use serde::{Deserialize, Serialize}; #[derive(Debug, Eq, PartialEq, Serialize, Deserialize, Clone)] pub struct Author { name: String, email: String, #[serde(skip...
Rust
0
DDx  =h) mm$OPPP`mmo%%//# # #sEDDTCPm-"--(STTTzmmo%%//# # #sEDDXk&u5#"*--0["\\\"Fmmo%%//# # #sEDDDhm-&"--(STTTZmmo%%//# # #sEDDV!%%&FGT&mmis",=>>>T ...
Python
1
); assert_eq!( generate_ts(1705, 2, 10, 20, 40, 50, 56789).last_day_of_month(), generate_ts(1705, 2, 28, 20, 40, 50, 56789) ); assert_eq!( generate_ts(1, 1, 1, 0, 0, 0, 0).last_day_of_month(), generate_ts(1, 1, 31, 0, 0, 0, 0) ); ...
Rust
0
bitstruct_class.__str__ = def_inst.__class__.__dict__['__str__'] # Return an instance of the new BitStruct class bitstruct_inst = bitstruct_class( nbits ) # TODO: hack for verilog translation! bitstruct_inst._module = def_inst.__class__.__module__ bitstruct_inst._classname = def_inst.__cla...
Python
1
[cfg(test)] mod tests { use super::*; extern crate libtransport; use libtransport::generic_test as lits; #[test] fn common() -> Result<()> { let a: Vec<String> = vec![ String::from("127.0.0.1:9000"), String::from("127.0.0.1:9001"), String::from("127.0.0.1...
Rust
0
; fn main() { App::build() .insert_resource(WindowDescriptor{ title: "Snake 2D".to_string(), width: 500.0, height: 500.0, ..Default::default() }) .insert_resource(ClearColor(Color::rgb(0.04, 0.04, 0.04))) .insert_resource(SnakeSegments...
Rust
0
f = open("Day1/input.txt") l1 = [] l2 = [] for line in f: line = line[:-1] temp = line.split(" ") l1.append(int(temp[0])) l2.append(int(temp[-1])) l1.sort() l2.sort() total = 0 for i in range(len(l1)): total += abs(l1[i] - l2[i]) print(total) counts = {} for i in l2: if i not in counts: ...
Python
1
import argparse import os import subprocess def main(): # parse arguments parser = argparse.ArgumentParser(description="Process some folders.") parser.add_argument("--output_dir", type=str, help="output folder for the model") parser.add_argument("--ps1", type=str, help = "path to ps = 1 model") par...
Python
1
c.sz%8 != 0 { return nil, fmt.Errorf("barf: section size %% 8 != 0: sz %d ", sec.sz) } blob, err := f.Read(sec.off, sec.sz) if err != nil { return nil, err } arr := make([]uint64, 0, len(blob)/8) for len(blob) > 0 { arr = append(arr, binary.BigEndian.Uint64(blob)) blob = blob[8:] } return arr, nil } fu...
Rust
0
> log::LevelFilter::Info, "warn" => log::LevelFilter::Warn, "error" => log::LevelFilter::Error, _ => log::LevelFilter::Off } } else { log::LevelFilter::Off }; let pid = unsafe { libc::getpid() }; if let Ok( value ) = env::var( "MEMORY_PROFILER_LOGFIL...
Rust
0
y and absolute indexed should take an * extra cycle for page crosses or not. Nestest does not verify this. */ macro_rules! combine { ($modify:ident, $read:ident, $addressing:ident) => {{ self.$addressing(pinout).await; self.operand.set(self.read(pin...
Rust
0
Params<F>, state: &mut [F], ) { for r in 0..SC::PERM_HALF_ROUNDS_FULL { for (i, x) in params.round_constants[r].iter().enumerate() { state[i].add_assign(x); } for state_i in state.iter_mut() { *state_i = sbox::<F, SC>(*state_i); } apply_m...
Rust
0
.body("ready\n".into()) .expect("builder with known status code must not fail") } else { Response::builder() .status(StatusCode::SERVICE_UNAVAILABLE) .body("not ready\n".into()) .expect("builder with known status code mu...
Rust
0
import os import json import datetime from dotenv import load_dotenv from groq import Groq # Load environment variables from .env file load_dotenv() # Get API key from env api_key = os.getenv("GroqAPIKey") # Function to fetch Username and Assistant name from env def get_env_values(): username = os.getenv("USERNA...
Python
1
process_running; use interfaces::game_events::*; use interfaces::{GameAnalyzer, GameTrait}; pub const GAME_NAME: &str = "LEAGUE_OF_STEEL"; pub const GAME_EXE: &str = "League of Legends.exe"; pub struct LolLib {} impl LolLib { pub fn new() -> Self { Self {} } } impl GameTrait for LolLib { fn get_...
Rust
0
import heapq def solution(scoville, k): answer = 0 heapq.heapify(scoville) while scoville[0] < k: mix = heapq.heappop(scoville) + (heapq.heappop(scovile) * 2) heapq.heappush(scoville, mix) answer += 1 if len(scoville) == 1 and scoville[0] < k: return -1 ...
Python
1
plt.plot(hull.points[simplex, 0], hull.points[simplex, 1], 'g-') # Hull edges plt.plot(node[0], node[1], 'ro') # Plot node plt.show() return not np.all(hull.equations @ np.append(node, 1) <= 0) # <= 0 if inside the convex hull except: return True # Default to ...
Python
1
/// Returns a tuple where the first number is the number of bytes /// read from the stream, and the second number is the number of /// bytes additionally read. Any of the numbers might be zero. /// It can also return an error. /// /// A type implementing this trait, will typically also implemen...
Rust
0
de código:") response = await agent.generate_code( "função para calcular fatorial", language="python" ) if response["success"]: print(f" ✅ Código gerado:") print(response['code'][:300]) else: print(f" ❌ Erro: {response['error...
Python
1
: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("parse BindRecItemVisitor error") } fn visit_map<A>(self,mut map: A) -> Result<Self::Value, A::Error> where A: MapAccess<'a>, { let mut ann = None; let mut ident = ""; let mut expr = None; loop { mat...
Rust
0
fn = "/apdcephfs/share_916081/effidit_shared_data/hilllzhang/llm_hallucination/LLaMA-Factory/data/halueval_dialog_10k.json" convert_dialog_halueval(dialog_data, output_fn) bio_data = "/apdcephfs/share_916081/effidit_shared_data/hilllzhang/llm_hallucination/hallucination_correct/my_cd/src/utils/bio_hallu_ll...
Python
1
EmptyStack)?; stack.push(a); stack.push(b); } Opcode::NewArray | Opcode::NewInit => { stack.push(JSValue::Object(Rc::new(RefCell::new(Object::new())))); } Opcode::String => { stack.push(JSValue::String(imm...
Rust
0
Size; use notation_model::prelude::{LaneKind, PlayingState, Semitones, TrackKind, Tab, Note}; use serde::{Deserialize, Serialize}; #[cfg(feature = "inspector")] use bevy_inspector_egui::Inspectable; use crate::prelude::NotationSettings; #[derive(Copy, Clone, PartialEq, Serialize, Deserialize, Debug)] #[cfg_attr(feat...
Rust
0
rd getters /// Gets the minimum surface gravity for a planet. pub fn get_min_gravity(&self) -> f64 { self.min_gravity } /// Gets the maximum surface gravity for a planet. pub fn get_max_gravity(&self) -> f64 { self.max_gravity } /// Gets the minimum surface temperature for...
Rust
0
or> { WinShape::try_from(val.as_str()) } } /// WinClass provides a easy way to identify the different window class types #[allow(dead_code)] #[derive(Debug, Clone, PartialEq)] pub enum WinClass { CopyFromParent, InputOnly, InputOutput, } // Convert from u32 to Class impl WinClass { pub...
Rust
0
# Copyright (C) 2025 Robotec.AI # # 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 wr...
Python
1
ll receive the best * length to reach this byte from a previous byte. * returns the cost that was, according to the costmodel, needed to get to the end. */ fn get_best_lengths(s: &mut BlockState, in_: &[u8], instart: usize, inend: usize, ...
Rust
0
='', swap=''), 58: dict( name='face-58', id=58, color=[255, 255, 255], type='', swap='face-56'), 59: dict( name='face-59', id=59, color=[255, 255, 255], type='', swap='...
Python
1
"""Helper script to update currency list from the official source.""" from pathlib import Path from bs4 import BeautifulSoup import requests from .hassfest.serializer import format_python_namespace req = requests.get( "https://www.six-group.com/dam/download/financial-information/data-center/iso-currrency/lists/l...
Python
1
p = p.transpose(1, 2) # (batch, head, time1, d_k) # (batch, head, time1, d_k) q_with_bias_u = (q + self.pos_bias_u).transpose(1, 2) # (batch, head, time1, d_k) q_with_bias_v = (q + self.pos_bias_v).transpose(1, 2) # compute attention score # ...
Python
1
_ty_2 { pub map_fd: __u32, pub key: __u64, pub __bindgen_anon_1: bpf_attr__bindgen_ty_2__bindgen_ty_1, pub flags: __u64, } #[repr(C)] #[derive(Copy, Clone)] pub union bpf_attr__bindgen_ty_2__bindgen_ty_1 { pub value: __u64, pub next_key: __u64, _bindgen_union_align: u64, } impl Default for b...
Rust
0
obj/struct.LatexObj.html extern crate sdl2; extern crate tempfile; use std::fs::{create_dir, remove_dir_all, File}; use std::io::{Error, ErrorKind, Result as IResult, Write}; use std::mem::drop; use std::path::Path; use std::process::{exit, Command}; use std::sync::Mutex; use std::time::Instant; use image::PngImage;...
Rust
0
remaining attempts. return Err(err); } attempt += 1; } } } } } /// Dummy progress callback function. If you don't want to report progress on /// for each retry, use this function. pub fn progress_dummy<E>( _re...
Rust
0
nds=['send_media']) async def add_schedule_job(message: types.Message): if message.from_user.id in pending_schedule and pending_schedule[message.from_user.id]["time"]: scheduled_time = pending_schedule[message.from_user.id]["time"] job_scheduler.add_job(schedule_media_sending, 'date', run_date=sched...
Python
1
from enum import Enum class ExtendAPITools(Enum): GET_VIRTUAL_CARDS = "get_virtual_cards" GET_VIRTUAL_CARD_DETAIL = "get_virtual_card_detail" CANCEL_VIRTUAL_CARD = "cancel_virtual_card" CLOSE_VIRTUAL_CARD = "close_virtual_card" GET_CREDIT_CARDS = "get_credit_cards" GET_CREDIT_CARD_DETAIL = "ge...
Python
1
e_map.insert(WallType::MushroomUnsafe, GUN_POWDER); walltype_map.insert(WallType::CrimsonGrassUnsafe, BUCCANEER); walltype_map.insert(WallType::DiscWall, METALLIC_BRONZE); walltype_map.insert(WallType::CrimstoneUnsafe, JON); walltype_map.insert(WallType::IceBrick, BLUE_DIANNE); walltype_map.insert(W...
Rust
0
} let resend = match packet.mode { SendMode::TimeSensitive => false, SendMode::Unreliable => false, SendMode::Persistent => true, SendMode::Reliable => true, }; return Some((pending_packet_clone, resend));...
Rust
0
# # Copyright (C) [2020] Futurewei Technologies, Inc. # # FORCE-RISCV is 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 # # THIS SOFTWARE IS PR...
Python
1
# app/scripts/add_planned_date.py import os import sqlite3 DB_PATH = "clinic.db" if not os.path.exists(DB_PATH): print("❌ База данных clinic.db не найдена") exit(1) db = sqlite3.connect(DB_PATH) cur = db.cursor() # Получаем все колонки таблицы visits cur.execute("PRAGMA table_info(visits);") columns = [col...
Python
1