text
string
label_name
string
labels
int64
pub sequence: Sequence, #[serde(default)] pub scene: SceneState, } impl ShouldResetPathTracer for PersistedState { fn should_reset_path_tracer(&self, other: &Self) -> bool { self.camera.should_reset_path_tracer(&other.camera) || self.exposure.should_reset_path_tracer(&other.exposure...
Rust
0
tensors="pt", padding=True, truncation=True ).to(self.model.device) if self.temperature == 0.0: generated_ids = self.model.generate(**inputs, max_new_tokens=self.max_tokens, do_sample=False) else: generated_ids = self.model.generate(**inputs, max_n...
Python
1
# mitre_mapping.py mitre_attack_mapping = { "ftp": { "id": "T1071.002", "technique": "Application Layer Protocol: File Transfer Protocols", "tactic": "Command and Control" }, "ssh": { "id": "T1021.004", "technique": "Remote Services: SSH", "tactic": "Lateral ...
Python
1
''' wlxsq决定制作一个Calc,该Calc具备求解一元一次方程的功能。 为了简化工作,拒绝花里胡哨。这个方程中,只有一个等号"=",零个或多个加号"+"、减号"-",一种小写字母表示未知数。当然,减号也可是负号 方程中并没有括号,也没有除号,方程中的字母表示未知数。 输入 仅一行,表示一个合法的方程,包含“+”、“-”、“=”、数字及小写字母。 输出 仅一行,表示答案,形式为“未知元=答案”。对答案保留3位小数,保证答案的绝对值不超过10000。 样例 2a=1 a=0.500 -5+2x=-10 x=-2.500 ''' s=input() x = '' for i in s: if 97<=ord(i...
Python
1
Clone, Copy, Debug, serde::Deserialize)] pub enum LogLevel { Error, Warn, Info, Debug, Trace, } impl FromStr for LogLevel { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let lower = s.to_lowercase(); match lower.as_str() { "error" => Ok(Lo...
Rust
0
; t!(s: "a/b/c", "a/b", true); t!(s: "a", ".", true); t!(s: ".", ".", false); t!(s: "/a", "/", true); t!(s: "/", "/", false); } #[test] fn test_root_path() { assert_eq!(Path::new(b!("a/b/c")).root_path(), None); assert_eq!(Path::new(b!("/a/b/c")).root...
Rust
0
# Copyright 2019 The Blueqat Developers # # 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 i...
Python
1
update(|f| Some(f + diff)).is_err() { return; } if !self.is_passed() { return; } let diff = self.current.load(); object.on_update(diff, container); self.reset(); } fn is_passed(&self) -> bool { self.current.load() >= self.inter...
Rust
0
import numpy as np from studies.modules.labeling_lib import calculate_labels_random def test_j_eq_i_single_up_is_valid_first_touch(): n = 5 close = np.zeros(n, dtype=np.float64) high = np.zeros(n, dtype=np.float64) low = np.zeros(n, dtype=np.float64) atr = np.ones(n, dtype=np.float64) label_m...
Python
1
""" Cache Services Module 提供缓存管理相关服务,包括: - 统一缓存系统 - 模板缓存 - 占位符缓存 - AI分析结果缓存 """ from .unified_cache_system import ( UnifiedCacheManager, UnifiedCacheEntry, CacheType, CacheLevel, initialize_cache_manager, get_cache_manager ) from .redis_cache_service import ( cache_service, get_cache_service, cach...
Python
1
# coding: utf8 from __future__ import unicode_literals from spacy.vocab import Vocab import spacy from spacy.lang.en import English from spacy.util import ensure_path from ..util import make_tempdir def test_issue4054(en_vocab): """Test that a new blank model can be made with a vocab from file, and that ser...
Python
1
1).unwrap_or_else(|| { eprintln!("Must provide path to write unicode tables to"); eprintln!( "e.g. {} library/core/unicode/unicode_data.rs", std::env::args().next().unwrap_or_default() ); std::process::exit(1); }); // Optional test path, which is a Rust s...
Rust
0
::Writer::new(&mut cursor); w.start_map()?; w.write_string(b"from")?; w.write_string(b"handler")?; w.write_string(b"id")?; w.write_string(id)?; w.write_string(b"seq")?; w.write_int(seq as isize)?; if ptype.is_empty() { w.write_string(b"con...
Rust
0
LinkParams { rate, prio }, body, ) => Envelope::Linked { node_uri: node, lane_uri: lane, rate, prio, body, }, ResponseEnvelope::Synced(RelativePath { node, lane }, body) => Envelope::Synce...
Rust
0
.is_locked()); assert!(!lock.is_locked_exclusive()); drop(read_guard); } { let write_guard = lock.write(); let write_result = lock.try_write(); assert!( write_result.is_none(), "try_write should fail while writ...
Rust
0
ew_product); registry.add_entry(new_entry)?; } Command::Migrate(MigrateCmd::Add(field_name, value)) => { registry .migrate_entries(::persistence::Migration::add_from_str(field_name, &value)?)?; } Command::Migrate(MigrateCmd::Remove(field_name)) => ...
Rust
0
th)) } pub fn retain(self, length: usize, attributes: Attributes) -> Self { self.push(DeltaOperation::insert(length).attrs(attributes)) } pub fn push(mut self, op: DeltaOperation) -> Self { self.ops.push(op); self } /// Returns a new Delta representing the concatenatio...
Rust
0
casy' (součet prosledovaných časů pro jednotlivé kanály),\n\t'divaci' (počet unikátních diváků pro jednotlivé kanály),\n\t'zatez' (maximální zátěž serveru)\n]") .to_string() .to_lowercase() .as_ref() { m @ "casy" | m @ "divaci" | m @ "zatez" => break m.to_string(), _ => (), } }; match op.as_...
Rust
0
} enum ConnectionInner { Established(EstablishedConnection), InProgress(TlsHandshakeMachine), } pub struct Connection { pub valid_until: ValidUntil, inner: ConnectionInner, } impl Connection { #[inline] pub fn new( opt_tls_acceptor: &Option<Arc<TlsAcceptor>>, valid_until: Vali...
Rust
0
l_hir_expr_while(expr, |e| match e.kind { ExprKind::AddrOf(ast::BorrowKind::Ref, _, e) if remaining != 0 => { remaining -= 1; Some(e) }, _ => None, }); (e, count - remaining) } /// Peels off all references on the expression. Returns the underlying expression and ...
Rust
0
_snake_case)] fn $test_name() { let db = common::load_rom(); match db.get_trainer_name(&$trainer_id) { Ok(trainer_name) => assert_eq!( trainer_name, TrainerName { name: ROMString::from($trainer_name) ...
Rust
0
from(res) << i*4; } out } fn permute(block: Secret<u32>) -> Secret<u32> { run_permutation(&tables::ROUND_PERMUTATION, Secret::<u64>::from(block), 32, 32).truncate() } #[cfg(test)] mod tests { extern crate test; extern crate rand; use super::{Des, key_schedule, initial_permute, final_permute, ...
Rust
0
::*; pub mod unloop_song; pub use unloop_song::*; pub mod is_looping; pub use is_looping::*; pub mod now_playing; pub use now_playing::*; pub mod queue; pub use queue::*; pub mod mute; pub use mute::*; pub mod unmute; pub use unmute::*; pub mod deafen; pub use deafen::*; pub mod undeafen; pub use undeafen::*; ...
Rust
0
def first_last6(nums): return True if nums[0] == 6 or nums[-1] == 6 else False
Python
1
import difflib import copy a = open("anytext.sh","r").read() b = open("shit.sh","r").read() #dir(difflib) #rnd = "round one. "*20 rnd = copy.copy(a) rnd = [x for x in rnd] # generate some function. this is it. whatever it means. x0 = [x for x in difflib.ndiff(a,b)] for xp in range(len(x0)): xf = ...
Python
1
#!/usr/bin/env python import netfilterqueue import scapy.all as scapy ack_list = [] def set_load(packet, load): packet[scapy.Raw].load = load del packet[scapy.IP].len del packet[scapy.IP].chksum del packet[scapy.TCP].chksum return packet def process_packet(packet): scapy_packet = scapy.IP(pac...
Python
1
WaitingNewCommandEndless } State::CheckBootloaderValidity => { blink_led(&mut p.0, 5); asm::delay(8_000_000); //State::Error State::WaitingNewCommandEndless } ...
Rust
0
use amethyst::utils::fps_counter::FPSCounter; use super::system_prelude::*; pub struct DebugSystem { last_fps_print: Instant, } const PRINT_FPS_EVERY_MS: u64 = 1000; impl<'a> System<'a> for DebugSystem { type SystemData = Read<'a, FPSCounter>; fn run(&mut self, fps_counter: Self::SystemData) { ...
Rust
0
ppend("-olas") elif sys.argv[out] == "laz": command.append("-olaz") elif sys.argv[out] == "bin": command.append("-obin") elif sys.argv[out] == "xyzc": command.append("-otxt") command.append("-oparse") command.append("xyzc") elif sys.argv[out] == "xyzci": c...
Python
1
-2b" # hook_layer = 20 # repo_id = "google/gemma-scope-2b-pt-res" # filename = f"layer_{hook_layer}/width_16k/average_l0_71/params.npz" # sae = jumprelu_sae.load_jumprelu_sae(repo_id, filename, hook_layer) # selected_saes = [(f"{repo_id}_{filename}_gemmascope_sae", sae)] # config = AutoInterpE...
Python
1
://snapshots01.mooc.fi/" ], "unlockables": [], "exercises": [ { "id": 81842, "name": "osa01-Osa01_01.Hiekkalaatikko", "locked": false, "deadline...
Rust
0
def lectura(): peso = float(input("Peso (kg): ")) altura = float(input("Altura (m): ")) grasa_corporal = float(input("Porcentaje de grasa corporal (%): ")) vo2_max = float(input("VO2 Máximo (mL/kg/min): ")) edad = int(input('Ingrese edad: ')) genero = input('0 para Masculino / 1 para Femenino: '...
Python
1
/MyLib.sol:MyLib:{:?}", Address::random())], ..Default::default() }; prj.write_config(config); prj.inner() .add_source( "LinkTest", r#" // SPDX-License-Identifier: MIT import "remapping/MyLib.sol"; contract LinkTest { function foo() public returns (uint256) { ...
Rust
0
(not isinstance(prompt, str) and not isinstance(prompt, list)): raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") if prompt_embeds is not None and prompt_attention_mask is None: raise ValueError("Must provide `prompt_attention_mask` when specifying `...
Python
1
# Copyright (c) 2023 Darren Erik Vengroff """Tests for the fetch implementation.""" import unittest import pandas as pd import censusdis.impl.fetch from censusdis import CensusApiException class ParseCensusJsonTestCase(unittest.TestCase): """Tests of parsing census JSON.""" def test_parse_json(self): ...
Python
1
import math def area_of_quadrilateral(X, Y, Z, T): d = math.sqrt(X**2 + Y**2) area_triangle1 = 0.5 * X * Y s = (Z + T + d) / 2 area_triangle2 = math.sqrt(s * (s - Z) * (s - T) * (s - d)) total_area = area_triangle1 + area_triangle2 return total_area def main(): X =...
Python
1
import cPickle as pickle import numpy as np import argparse from HICO_DET_utils import calc_ap, obj_range, rare def parse_args(): parser = argparse.ArgumentParser(description='Generate detection file') parser.add_argument('--file', dest='file', help='Detection file to evaluate', default...
Python
1
IVE: OpsLimit = OpsLimit($opslimit_sensitive as usize); /// `MemLimit` for highly sensitive data. pub const MEMLIMIT_SENSITIVE: MemLimit = MemLimit($memlimit_sensitive as usize); /// Variant id for the Argon2i13 algorithm pub const VARIANT: u32 = $variant; /// `OpsLimit` represents the maximum number of computations...
Rust
0
tinue 'targets_pass; } Err(other_error) => return Err(other_error), } } } if !infinite { break 'cycle; } } Ok(()) } <gh_stars>1-10 #[repr(C, align(16))] #[derive(Debug, PartialEq, Clone, Copy)] pub struct Co...
Rust
0
""" This is a Word Guesser type game called AHORCADO GAME. It can take a file with a single word for each row as a list of words for the game. Feel free to update the file variable with a .txt of your own! (Remember! Only a word for row!) """ import random # For randomize the choosen word import os # For using os.syst...
Python
1
import logging logger = logging.getLogger(__name__) class RequestLoggingMiddleware: def __init__(self,get_response): self.get_response = get_response def __call__(self,request): logger.info(f'Request:{request.method} {request.path}') response = self.get_response(request) logger...
Python
1
| kvs.get(MIME_TYPES).to_owned()); let mime_types = parse_compress_includes(&mime_types).map_err(|err| { anyhow::anyhow!( "{}: invalid HULK_COMPRESS_MIME_TYPES value '{}'", err, mime_types ) })?; Ok(Config { enabled, allow_encrypted, ...
Rust
0
# Copyright (c) 2013-2018 Steve Milner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # (1) Redistributions of source code must retain the above copyright # notice, this list of condi...
Python
1
val_net(batch_state).gather(2, batch_action) q_next = self.target_net(batch_next_state).detach() if self.args.double_dqn: q_target = batch_reward + self.args.gamma * q_next.gather(2, self.eval_net(batch_next_state).max(2)[1].unsqueeze(dim=2)) q_target = q_target.detach() ...
Python
1
from modules.extract.domain import ports as extract_ports from modules.extract.domain import value_objects as extract_value_objects class TestExtractUnitOfWork(extract_ports.AbstractExtractUnitOfWork): def __init__(self): self.file = TestFileDomainRepository() self.extract = TestExtractDomainRepos...
Python
1
(value) => self.insert(key, &value), None => self.remove(key), } } } pub mod internal { use super::Hamt; use std::rc::Rc; use std::sync::Arc; #[derive(Clone, Debug, PartialEq, Eq)] pub enum RcTrick<K, V> { RcTrick(Rc<Hamt<K, V, RcTrick<K, V>>>), } #[derive...
Rust
0
// so q is always defined let n = r - z * z0; (z0 - q * n) / (w0 * w - n.pow2()).sqrt() - cte } /// Computes the ratio (dX / dY) / (d^2X / dY^2) in the equatorial region #[inline] #[allow(clippy::many_single_char_names)] fn f_over_df_eqr(z: f64, z0: f64, w0: f64, cte: f64, r: f64) -> f64 { let w = 1.0 - z.pow2()...
Rust
0
e.html) implementation on this field. #[cfg(feature = "zeroize")] pub zeroize_fqs: ZeroizeFqs, } impl FieldAttr { /// Create [`FieldAttr`] from [`Attribute`]s. pub fn from_attrs( derive_wheres: &[DeriveWhere], skip_inner: &Skip, attrs: &[Attribute], ) -> Result<Self> { let mut self_ = FieldAttr::default()...
Rust
0
, 'de': 'Buch-Pahlavi', 'el': 'Επιγραφικό Παχλάβι', 'el-polyton': 'Επιγραφικό Παχλάβι', 'en': 'Inscriptional Pahlavi', 'en-Dsrt': '𐐆𐑌𐑅𐐿𐑉𐐮𐐹𐑇𐐲𐑌𐐲𐑊 𐐑𐐪𐑊𐐲𐑂𐐨', 'et': 'pahlavi raidkiri', 'eu': 'pahlavi inskripzioak', 'fa': 'پهلوی کتیبه\u200cای', 'ff-Adlm': '𞤄𞤭𞤲𞤣𞤭 𞤆𞤢𞤤𞤢𞤾𞤭', 'fi': 'piirtokirjoituspahl...
Python
1
ndow(0, 0, 10, 10, 0, X.CopyFromParent) def tearDown(self): self.win.destroy() self.dpy.close() def test_single_UTF8_STRING(self): props.change_prop(self.dpy, self.win, '_NET_WM_NAME', 'hey guy') val = props.get_prop(self.dpy, self.win, '_NET_WM_NAME') self.assertEqual(...
Python
1
import pyshark import json from pprint import pprint from datetime import datetime import matplotlib.pyplot as plt from dotenv import load_dotenv import os import sys load_dotenv() print(os.getenv("SSLKEYLOGFILE")) if len(sys.argv) != 2: print("Usage: python script.py [pcap file name]") sys.exit(1) # Exit th...
Python
1
s[cls] * conf except Exception as e: print(f"Error calculating distance: {str(e)}") continue # 考虑多人场景 if len(keypoints) > 1: person_violence = min(1.0, person_violence + 0...
Python
1
def _resnet_imagenet16(arch, pretrained=False, num_classes=16): if arch == 'resnet18': model = torchvision.models.resnet18(num_classes=num_classes) elif arch == 'resnet50': model = torchvision.models.resnet50(num_classes=num_classes) else: raise ValueError if pretrained: ...
Python
1
GameResult<()> { // いちいち書くのがだるいので、短縮ネームを変数束縛 let e_block = &core.game_state.actor.e_block; for li in e_block { let e_block_pos = Point2::new( li.x, li.y, ); graphics::draw(ctx, &core.assets.enemy_block, ...
Rust
0
# (c) 2012, Daniel Hokka Zakrisson <daniel@hozac.com> # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = r""" name: pipe author: Daniel Ho...
Python
1
mmy.make(get_user_model()) cls.profile = cls.user.profile cls.proposal_1 = mommy.make( 'deck.Proposal', author=cls.user, event__closing_date=tomorrow ) cls.proposal_2 = mommy.make( 'deck.Proposal', author=cls.user, e...
Python
1
#!/usr/bin/env python2 # # Print out a few IEEE double representations related to the Duktape fastint # number model. # import struct import math def isFastint(x): if math.floor(x) == x and \ x >= -(2**47) and \ x < (2**47) and \ (x != 0 or math.copysign(1.0, x) == 1.0): # Negative zero is...
Python
1
ok_list.append(h[j]) ok_list.append(h[j+1]) #print("OK:",ok_list) return ok_list tt = 1 break if tt == 1: break if tt == 1: break ...
Python
1
""" exposed URLS for cms app viewset : BlogViewSet """ from django.urls import path from app.cms.controllers.BlogViewSet import BlogViewSet blog_urlpatterns = [ path( "blog/get-blogs/", BlogViewSet.as_view({"get": "get_blogs"}), name="get-blogs", ), ]
Python
1
(), plugin_manager: PluginManager::new(), workers: HashMap::new(), job_handler: JobHandler::new(sender), receiver: Arc::new(Mutex::new(receiver)), shared_data: SharedDataRc::default(), global_messenger: MessengerRw::default(), } } } im...
Rust
0
isis/levels/level/link_state_database/lsp/tlvs/tlv/isis_alias_id/state/alias_id (oc-isis-types:system-id) If this variable is read-only (config: false) in the source YANG file, then _set_alias_id is considered as a private method. Backends looking to populate this variable should do so via calling thisO...
Python
1
] [-> PHYS_UNIT] (1.60 ..) [-> READ_WRITE] [-> REF_MEMORY_SEGMENT] [-> SYMBOL_LINK] (1.60 ..) [-> VIRTUAL] } /// describes the types of program segments /// /// Specification: 3.5.85 enum ProgType { PRG_CODE, PRG_DATA, PRG_RESERVED...
Rust
0
e.g., from /// `forall<T> { .. }`. Stands in as a representative of "some /// unknown type". Placeholder(PlaceholderIndex), /// A "dyn" type is a trait object type created via the "dyn Trait" syntax. /// In the chalk parser, the traits that the object represents is parsed as /// a QuantifiedIn...
Rust
0
("`validate_length` must be an integer") if validate_length < 1: raise ValueError("`validate_length` should be at least 1") else: validate_length = self.__validate_length if not normalize: normalize = self.__normalize return self.__get_in_memor...
Python
1
PendingRequests::Some(set) => set.contains(id), PendingRequests::All => true, } } fn is_empty(&self) -> bool { match self { PendingRequests::Some(set) => set.is_empty(), PendingRequests::All => false, } } } impl Default for PendingRequests { fn default() -> Self { PendingRequests::Some(HashSet::...
Rust
0
mut |op| { offset = op._store_val(txn, vars, offset, writer); }); vars.unmask_all(); offset } fn store_grad(&self, txn: TxnId, vars: &mut VarSet, mut offset: usize, writer: &mut Any) -> usize { let epoch = Epoch::new(self._id()); vars.unmask_all(); //writer.reset(); self._push(epo...
Rust
0
10000; let mut k = 10000; dbg!(find_kth_number(testcase2, k)); // => 9999 } <filename>src/const_assert.rs /// Asserts that constant expressions evaluate to `true`. /// /// Constant expressions can be ensured to have certain properties via this /// macro If the expression evaluates to `false`, the file will fai...
Rust
0
e updated assert updated_metadata["author"] == "New Author" assert updated_metadata["version"] == "2.0" def test_direct_hash_calculation_method( self, service, dummy_tensors, dummy_metadata, test_filepath ): """Test the _calculate_hash method directly.""" save_file(dummy...
Python
1
color='blue', facecolor='red', alpha=0.7, hatch='*') patch.set_clip_path(clip_path, ax2.transData) ax2.add_patch(patch) ax1.set_xlim([-3, 3]) ax1.set_ylim([-3, 3]) @cleanup def test_cull_markers(): x = np.random.random(20000) y = np.random.random(20000) fig...
Python
1
_ell_q1, f_xx_circ, decimal=8) npt.assert_almost_equal(f_xy_ell_q1, f_xy_circ, decimal=8) npt.assert_almost_equal(f_yx_ell_q1, f_yx_circ, decimal=8) npt.assert_almost_equal(f_yy_ell_q1, f_yy_circ, decimal=8) f_xx_circ, f_xy_circ, f_yx_circ, f_yy_circ = self.CircularMultipole.hessian( ...
Python
1
import matplotlib.pyplot as plt import numpy as np import csv # Function to read data from CSV file def read_csv(filename): models = [] original = [] onnx = [] gguf = [] with open(filename, 'r') as csvfile: csvreader = csv.DictReader(csvfile) for row in csvreader: m...
Python
1
clear() def get_balance(self, address: str): balance = 0 for block in self.blocks: for transaction in block.transactions: if transaction.sender == address: balance -= transaction.amount if transaction.receiver == address: ...
Python
1
print('=========== 3.1.1 if语句 ===========') age = 5 if age >= 3: # 判断变量age的值是否大于或等于3 print("可以上幼儿园了") print('=========== 3.1.2 if-else语句 ===========') u_name = input("请输入用户名:") pwd = input("请输入密码:") if u_name == "admin" and pwd == "123": print("登录成功!即将进入主界面。") else: print("您输入的用户名或密码错误,请重新输入。") p...
Python
1
# -*- coding: utf-8 -*- import numpy as np import geatpy as ea # 导入geatpy库 class soea_ES_miu_plus_lambda_templet(ea.SoeaAlgorithm): """ soea_ES_miu_plus_lambda_templet : class - (μ+λ)进化策略算法类. 算法描述: 本算法类实现的是(μ+λ)进化策略[1]。 参考文献: [1] Beyer H G , Schwefel H P . Evolution strategies – A ...
Python
1
) = conn_notifs_channel::new(); let hc_network_tx = HealthCheckerNetworkSender::new( PeerManagerRequestSender::new(peer_mgr_reqs_tx), ConnectionRequestSender::new(connection_reqs_tx), ); let hc_network_rx = HealthCheckerNetworkEvents::new(peer_mgr_notifs_rx, ...
Rust
0
from model.model_token_factored_alibi import FactoredTransformerModelALiBi as ModelALiBi model, tokenizer = ModelALiBi.load_from_checkpoint('output_alibi/alibi_model.pt',device='cuda')
Python
1
).y + 20)) patch_label.SetFont(gui_support.font_factory(13, wx.FONTWEIGHT_NORMAL)) patch_label.Centre(wx.HORIZONTAL) # Button: Start Root Patching start_button = wx.Button(frame, label="开始安装驱动补丁", pos=(10, patch_label.GetPosition().y + 25), size=(170, 30)) ...
Python
1
_IFINFO2 { let hdr = unsafe { let mut maybe_hdr = mem::MaybeUninit::<if_msghdr2>::uninit(); ptr::copy_nonoverlapping( data_ptr, maybe_hdr.as_mut_ptr() as *mut u8, mem::size_of::<if_msghdr2>(),...
Rust
0
# Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
Python
1
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By import time def cf_answer_submitter(contest_link, handle_or_email, password, prblm_no, language, code): driver = webdriver.Chrome() driver.get(contest_link) driver.find_element(By.LINK...
Python
1
\n" " if (max2 > max) {{ max = max2; {0} = argMax2; }}" " else if (max2 == max && argMax2 < {0}) {{ {0} = argMax2; }}", }, "argmin": { "inits": "int {0} = -1; float min = FLT_MAX;", "ops": "if ({1} < min) {{ min = {1}; {0} = i; }}", "shfl_red": "float min2 =...
Python
1
ions ligand_pdbqt_file_name_list = [None] * num_conformations ligand_dlg_file_name_list = [None] * num_conformations os.mkdir(ligand_name) os.chdir(ligand_name) os.system("ln -s ../protein*map* .") for conf_idx in range(num_conformations): ...
Python
1
for operation in operations: status = operation.get("detection_status", "unknown") rates[status] = rates.get(status, 0) + 1 return rates def _extract_key_findings(self, operations: List[Dict[str, Any]]) -> List[str]: """Extract key findings from...
Python
1
with gradio.Row(): model = gradio.Dropdown(models, label='Model', value='(base)', type='value') refreshM = ToolButton(value='\U0001f504') nouse0 = ToolButton(value="️|", variant='tertiary', tooltip='', interactive=False) CL = To...
Python
1
, use_byte_level: bool) -> Self { self.use_byte_level = use_byte_level; self } pub fn get_replacement(&self) -> char { self.replacement } pub fn set_replacement(&mut self, replacement: char) { self.replacement = replacement; self.str_rep = replacement.to_string(...
Rust
0
labels_folder, val_ratio=0.2): # Get list of files and sort numerically based on frame number image_files = sorted(glob(os.path.join(images_folder, "*.png")), key=lambda x: int(os.path.basename(x).split('_')[1].split('.')[0])) label_files = sorted(glob(os.path.join(labels_folder, "...
Python
1
else: dominated_level_elems = [level_elem for level_elem in new_levels[level_idx] if check_dominance( moving_set_elem, level_elem)] non_dominated_level_elems = [ level_elem for level_elem in new_levels[level_idx] if not check_dominance(...
Python
1
MonitoringType::BasicTh => write!(f, "Basic"), MonitoringType::BasicThGuSS => write!(f, "BasicGuard"), MonitoringType::BasicWithGuardDifferentSources => write!(f, "BasicGuard"), MonitoringType::BasicWithPersistenceOnGuard => write!(f, "BasicRETS"), MonitoringTy...
Rust
0
# https://github.com/comfyanonymous/ComfyUI/blob/master/nodes.py import torch import ldm_patched.modules.model_management import ldm_patched.modules.sample import ldm_patched.modules.samplers import ldm_patched.modules.utils class PerpNeg: @classmethod def INPUT_TYPES(s): return {"required": {"model...
Python
1
plugin().distro.lower() == json.get("plugin_distro").lower(): app.plugin_manager._add_plugin(plugin()) plugin_row = Plugins() plugin_row.name = plugin().name.lower() plugin_row.distro = plugin().distro ...
Python
1
ons can be used by third party tooling to determine node liveness. /// A value of 0 will disallow any liveness sessions. pub listener_liveness_max_sessions: usize, /// CIDR for addresses allowed to enter into liveness check mode on the listener. pub listener_liveness_allowlist_cidrs: StringList, ///...
Rust
0
# here we're going to use regular expressions to extract bits of text # regular expressions are a sort of "sub" language that's used within other programming languages to match patterns # the syntax looks a little obtuse at first, but they are an extremely powerful and useful tool # here's a reference about them http:/...
Python
1
class Solution: def numberOfArrays(self, differences: List[int], lower: int, upper: int) -> int: prefix = [0] + list(itertools.accumulate(differences)) return max(0, (upper - lower) - (max(prefix) - min(prefix)) + 1)
Python
1
, PartialEq, Clone, Serialize, Deserialize, Builder)] pub struct SlackSocketModeDebugInfo { pub host: String, pub started: Option<String>, pub build_number: Option<u64>, pub approximate_connection_time: Option<u64>, } #[skip_serializing_none] #[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Bu...
Rust
0
urn json.dumps(analysis, indent=2) if __name__ == "__main__": if len(sys.argv) < 2 or len(sys.argv) > 3: logger.error("Usage: python analyzer.py <path_to_python_file_or_project> [--json]") sys.exit(1) path = sys.argv[1] output_json = len(sys.argv) == 3 and sys.argv[2] == "--json" if ...
Python
1
an".to_owned(), )), }, _ => Err(CallError::ArgumentError("GFX_SYNC takes zero or one argument".to_owned())), } } } /// Adds all console-related commands for the given `console` to the `machine`. pub fn add_all(machine: &mut Machine, console: Rc<RefCell<dyn Console>>)...
Rust
0
. fn push_slice<T: Copy>( table: &mut KeyedMulti<T>, value: &[T] ) -> Id<[T]> { table.create(value.iter().cloned()).unwrap_or(Id::empty()) } } use serde::{Deserialize}; #[derive(Debug, Deserialize, Eq, PartialEq, Clone)] #[serde(untagged)] pub enum Multiformat { Stri...
Rust
0
nnURU[R"SS9S9nUSL$s snf)CCheck if all of the keys are immediately present (without waiting).r  microsecondsr[Nr$r4r=datetime timedelta)r'r`r0rarAs rcheckEtcdStore.check^?CDtKK$,,s"33tD  ...
Python
1
111) # 符号 key_dict['<`>'] = KeyCode.from_vk(192) key_dict['`'] = KeyCode.from_vk(192) key_dict['<~>'] = KeyCode.from_vk(192) key_dict['~'] = KeyCode.from_vk(192) key_dict['<!>'] = KeyCode.from_vk(49) key_dict['!'] = KeyCode.from_vk(49) key_dict['<@>'] = KeyCode.from_vk(50) key_dict['@'] = KeyCode.from_vk(50) key_dict['...
Python
1
{ result[i as usize].push_str(mappings.get(key).expect("couldn't fetch mapping")); } } if result[i as usize].is_empty() { result[i as usize] = (i + 1).to_string(); } } result } #[cfg(test)] mod tests { use super::*; use proptest::prelude...
Rust
0