text
string
label_name
string
labels
int64
let j = $i + $n0.measure(); // if $func(j) { // $node($func, $i, $n0) // } else { // lookup!($node, $func, j ; $($n),*) // } // }}; // } pub fn lookup<T,M,P>(pred: P, i: M, digit: &Digit<T,M>) -> (&T,M) where T: Measure<M> + 'static, ...
Rust
0
ep": end_at_step, "denoise": 1.0, "add_noise": add_noise, "force_full_denoise": force_full_denoise } } del pipe return {"ui": {"value": [seed]}, "result": (new_pipe,)} # 预采样设置(噪声注入) class samplerSettingsNoiseIn: def __init__(sel...
Python
1
import django import sys,os rootpath = os.path.dirname(os.path.realpath(__file__)).replace("\\","/") rootpath = rootpath.split("/apps")[0] # print(rootpath) syspath=sys.path sys.path=[] sys.path.append(rootpath) #指定搜索路径绝对目录 sys.path.extend([rootpath+i for i in os.listdir(rootpath) if i[0]!="."])#将工程目录下的一级目录添加到python搜索路...
Python
1
fn deref(&self) -> &<Self as Deref>::Target { &self.state } } pub struct StateWrapper(State); impl Deref for StateWrapper { type Target = State; fn deref(&self) -> &<Self as Deref>::Target { &self.0 } } impl StateWrapper { pub fn add_image(&mut self, image_url: &str) { se...
Rust
0
pe, tokens::space)(input) } fn pipe(input: &str) -> IResult<&str, Expr> { let pipe = pair(char('|'), tokens::space); let expr = pair(chain, many0(preceded(pipe, chain))); map(expr, |(first, rest)| { rest.into_iter().fold(first, |lhs, rhs| { Expr::Binary(BinaryOp::Pipe, Box::new(lhs), Bo...
Rust
0
is_rxne() {} spi.read().unwrap() // 読む } fn lps25hb_send_buf(spi: &mut Spi<SPI1, (PA5<Alternate<AF5>>, PA6<Alternate<AF5>>, PA7<Alternate<AF5>>)>, data: &mut [u8]) { spi.transfer(data).unwrap(); // 送って読む } struct DigitalOut { // GPIO出力用の構造体 pin: PA4<Output<PushPull>> } impl DigitalOut { ...
Rust
0
import numpy as np from sklearn.preprocessing import MinMaxScaler, StandardScaler import pandas as pd from statsmodels.stats.outliers_influence import variance_inflation_factor import matplotlib.pyplot as plt from sklearn.decomposition import PCA import seaborn as sns from sklearn.model_selection import KFold from xgbo...
Python
1
p(i + 1).unwrap_or_else(|| { radeco_err!("parse error"); String::new() }); worklist.push((replace_root, i as u8, p)); } while let Some((parent, edge_idx, subexpr)) = worklist.pop() { let pt = if let Some(tk) = self.seen.get(&subexpr).c...
Rust
0
how!("u64 can not be generated from {}", value.wrapped)) }, _ => Err(anyhow!("u64 can not be generated from {}", value.wrapped)) } } } impl TryFrom<DataValue> for i64 { type Error = anyhow::Error; fn try_from(value: DataValue) -> Result<Self, Self::Error> { match &value.wrapped { Value...
Rust
0
import json, time, random, os import numpy as np import dataclasses from torch.nn import functional as F from typing import List, Dict from PIL import Image from io import BytesIO import base64 import matplotlib.pyplot as plt time_slot = {} time_ref = time.time_ns() def record_time(name): if name not in time_slot...
Python
1
c APIs // to destructure an event and rebuild it let wanna_be_expected = fixtures::v10::full_json_data(); let data: serde_json::Value = wanna_be_expected .data() .cloned() .unwrap() .try_into() .unwrap(); let bytes = serde_json:...
Rust
0
ok(workbook, filename): """Save the given workbook on the filesystem under the name filename. :param workbook: the workbook to save :type workbook: :class:`openpyxl.workbook.Workbook` :param filename: the path to which save the workbook :type filename: string :rtype: bool """ archive...
Python
1
program.dispatch(Msg::EditorMsg(editor::Msg::SetMeasurement( measurements.clone(), ))) }) .no_render() } } /* #[cfg(target_arch = "wasm32")] #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; */ ...
Rust
0
nal_method) async def attack(self): """Perform the attack logic based on the current round.""" if self.engine.round not in range(self.round_start_attack, self.round_stop_attack + 1): pass elif self.engine.round == self.round_stop_attack: logging.info(f"[{self.__class...
Python
1
=memory_2048_368.x"); println!("cargo:rerun-if-changed=memory_512_176.x"); println!("cargo:rerun-if-changed=memory_64_176.x"); println!("cargo:rerun-if-changed=memory_64_240.x"); Ok(()) } #[derive(Clone, Copy)] struct Target { sub_family: SubFamily, } impl Target { fn read() -> Self { ...
Rust
0
_str().unwrap_or("").is_empty(){ path.set_extension("bbscript"); println!("EXTRACT SCRIPT CALLED\npath: {:?}\nindex: {}", path, script_index); if let Err(e) = save_script(path, script_index, scripts_ref.clone()) { alert(300, 300, format!("Could not save file! Error: ...
Rust
0
set(ids.canvas, ui); // Instantiate the `ListSelect` widget. let num_items = list_items.len(); let item_h = 30.0; let font_size = item_h as carbide_core::FontSize / 2; let (mut events, scrollbar) = widget::ListSelect::multiple(num_items) .flow...
Rust
0
and_zs_ids_chunks[1]] = generate_cat_err_sig(zs[rand_zs_ids_chunks[1]], break_rfs[1], break_catas[1], cat_photo_z_sigma) final_phot_zs[rand_zs_ids_chunks[2]] = generate_cat_err_sig(zs[rand_zs_ids_chunks[2]], break_catas[0], ...
Python
1
#!/usr/bin/python # -*- coding: utf-8 -*- """ [env] # Conda Environment conda create --name llm_query_poc python=3.9.13 conda info --envs source activate llm_query_poc conda deactivate # if needed to remove conda env remove -n [NAME_OF_THE_CONDA_ENVIRONMENT] conda env remove -n llm_query_poc # update conda conda up...
Python
1
import warnings warnings.warn("sympy_compat module is deprecated. Use `import symengine` instead", DeprecationWarning, stacklevel=2) from symengine import *
Python
1
import pyautogui # implimindo o pyautogui no programa for i in range(10): pyautogui.moveTo(100 +10 * i, 100 +10 * i, duration=0.5) pyautogui.moveTo(200 +10 * i, 100+ 10 *i, duration=0.5) pyautogui.moveTo(200 +10 * i, 20 + 10 *i, duration=0.5) pyautogui.moveTo(100 +10 * i, 100 +10 * i, duration=0.5)
Python
1
empty(py).into()")] #[pyi(default = "[]", python_type = "list[int]")] pub vertex_indices: PyObject, #[pyo3(get, set)] #[pyinit(default = "PyList::empty(py).into()")] #[pyi(default = "[]", python_type = "list[AttributeData]")] pub positions: Py<PyList>, #[pyo3(get, set)] #[pyinit(defaul...
Rust
0
unsafe { let module_def: ModuleDef = ModuleDef::new(NAME, DOC, ModuleInitializer(init)); assert_eq!((*module_def.ffi_def.get()).m_name, NAME.as_ptr() as _); assert_eq!((*module_def.ffi_def.get()).m_doc, DOC.as_ptr() as _); Python::with_gil(|py| { ...
Rust
0
::FightCommonInformations; use protocol_derive::{Decode, Encode}; #[derive(Clone, PartialEq, Debug, Encode, Decode)] #[protocol(id = 6073)] pub struct GameRolePlayAggressionMessage<'a> { #[protocol(var)] pub attacker_id: u64, #[protocol(var)] pub defender_id: u64, pub _phantom: std::marker::Phantom...
Rust
0
), 1); let outer_div_2 = root.find("#nested").find("div ~ .inner-div-2-2"); assert_eq!(outer_div_2.length(), 1); // unique selector let div = root.find("div"); let inner_div_2_2 = div.find(".inner-div-2-2"); assert_eq!(inner_div_2_2.length(), 1); let firsts = div.find(":nth-child(1)"); assert_eq!(firsts.length(...
Rust
0
) @staticmethod def _draw_lane_central(lane, ax, color_val): """draw boundary""" for curve in lane.central_curve.segment: if curve.HasField('line_segment'): px = [] py = [] for p in curve.line_segment.point: px.appe...
Python
1
end(transition) state = next_state score += reward if done: break self.memory.add(seq_data) experience = self.memory.sample(on_policy=True) self.learner.update_model(experience) ...
Python
1
0(&children[0], &children[1], &children[2], parse_tree), 35 => self.equality_list_1(parse_tree), 36 => self.relational(&children[0], &children[1], parse_tree), 37 => self.relational_list_0(&children[0], &children[1], &children[2], parse_tree), 38 => self.relational_list_1...
Rust
0
Key Takeaways Summarize the key concepts learned in this tutorial. """ console.print("\n[bold yellow]🎓 Tutorial Wrap-Up[/bold yellow]") console.print("[italic]Key Takeaways:[/italic]\n") console.print("- **Configurations:** Use the type-params pattern to define settings flexibly.") consol...
Python
1
$NetBSD$ Python 3 compatability. --- pystatsd/daemon.py.orig 2013-06-14 19:27:00.000000000 +0000 +++ pystatsd/daemon.py @@ -27,7 +27,7 @@ class Daemon(object): if pid > 0: # First parent; exit. sys.exit(0) - except OSError, e: + except OSError as e: ...
Python
1
TEXT; quote! { map(choices::warp::reply) .map(move |reply| { use choices::warp::{reply::{with_header, with_status}, http::StatusCode}; match #access_pattern { Ok(config) => with_status( with_header( config.#field_ide...
Rust
0
&[])?; let record: Record<(i32, Record<(i32, i32)>)> = row.get(0); assert_eq!(record, Record((1, Record((2, 3))))); let row = client.query_one("SELECT (1, 'a')", &[])?; let record: Record<(i32, String)> = row.get(0); assert_eq!(record, Record((1, "a".into()))); Ok(()) } fn pg_test_inner(dir: ...
Rust
0
let a = Library::new("a.dll").unwrap(); /// a.get::<extern "C" fn()>("increment").unwrap()(); /// /// let b = Library::new("b.dll").unwrap(); /// b.get::<extern "C" fn()>("increment").unwrap()(); /// /// println!("Success"); /// } /// ``` macro_rules! crossdylib { { $($(#[$attr:meta])* $vis:vis static $ident:iden...
Rust
0
: play_twice(b) with program() as prog: b.run() job = simulate_program_and_return(cfg, prog, 200) samples = job.get_simulated_samples() tstamp = int(job.simulated_analog_waveforms()["controllers"]["con1"]["ports"]["1"][0]["timestamp"]) assert all( samples.con1.analog["1"][t...
Python
1
let mut set = BitSet::new(); // Write 0xFEFF07 set.remove(0); for i in 1..19 { set.insert(i); } // Set bit 70 set.insert(70); return set; } #[test] fn it_can_correctly_serialize() { let set = sample_bitset(); let bin = set.serialize_to_vec(); assert_eq!(hex::decode("0200...
Rust
0
TransferUpload { fn drop(&mut self) { log::trace!("destroying RafxUpload"); // If the transfer is in flight, wait for it to complete self.upload.wait_for_idle().unwrap(); self.wait_for_idle().unwrap(); log::trace!("destroyed RafxUpload"); } } /* * <NAME> * * Jenkins...
Rust
0
eam_info', ['POST']) @validate(json=UpdateExtraTeamInfoParam) @wish_response @wish_checker(['user_is_staff']) async def update_extra_team_info( req: Request, body: UpdateExtraTeamInfoParam, worker: Worker, user: User | None ) -> dict[str, Any]: assert user is not None if user.model.user_info.ban_list.ban_s...
Python
1
if brand: md += f"**Brand:** {brand}\n\n" if recommended_uses: md += f"**Recommended Uses:** {recommended_uses}\n\n" st.markdown(md) else: if image_url: st.image(image_url, width=200) st.markdown(f'<d...
Python
1
super().stop() # Clean up device resources del self._device def start_impedance_check(self) -> None: """Start electrode impedance monitoring in background thread. Initiates continuous impedance measurement for all electrodes. Provides real-time feedback on electrode cont...
Python
1
mask |= mask >> 16; // Let's not care about the unbounded execution time :) let mut value = self.next() & mask; while value >= len { value = self.next() & mask; } value + range.start } } #[test] fn create() { for i in 1..100 { println!("new...
Rust
0
import sqlite3 from datetime import datetime # Define the Business class to model a business entity class Business: def __init__(self, business_name, address, phone, email, website, rating, lat, lng, business_type): self.business_name = business_name self.address = address self.phone = phon...
Python
1
(192,) ), pool_type='max' ) l = nn.layers.GlobalPoolLayer(l, name='gp') l = nn.layers.DropoutLayer(l, name='gpdrop', p=0.8) l = nn.layers.DenseLayer(l, name='out', num_units=n_classes, nonlinearity=nn.nonlinearities.softmax) net = NeuralNet( layers=l, regression=False, use_label_encode...
Python
1
Value::Integer(integer) => Self::integer_to(integer, val_type), Value::Color(r, g, b) => Self::color_to((r, g, b), val_type), Value::Char(character) => Self::char_to(character, val_type), } } fn address_to(addr: Address, val_type: &Type) -> Value { match *val_typ...
Rust
0
m) main_frame.pack(fill="both", expand=True) # Configure grid columns for main_frame (make column 1 expandable) main_frame.columnconfigure(1, weight=1) # --- Widgets --- # Row 0: Story Name story_name_label = ttk.Label(main_frame, text="故事名称:") story_na...
Python
1
leaf: Element, asset: CurrencyId) -> Result<(), dispatch::DispatchError>; /// Withdraw from the mixer fn withdraw( id: TreeId, proof_bytes: &[u8], root: Element, nullifier_hash: Element, recipient: AccountId, relayer: AccountId, fee: Balance, refund: Balance, asset: CurrencyId, ) -> Result<(), dis...
Rust
0
import matplotlib.pyplot as plt import time import numpy as np from scipy.interpolate import make_interp_spline, BSpline from matplotlib import rc idx = [] stiffnessLeft, stiffnessRight = [],[] stiffnessNeutral = [] minLimitX = 0 maxLimitX = 12.5 minLimitY = 0 maxLimitY = 1.1 with open("plot-stiffness-faster-01.txt"...
Python
1
[FUNCTIONS[current]] = code self.changed.emit() def set_function_text(self, current=None): if current is None: current = self.ui.cfg_functionMode.currentText() self.ui.run_label.setVisible(current == FuncTypes.open) self.ui.function_send_mode.setVisible(current == FuncT...
Python
1
cmd_args_parser.add_argument("--data_root", type=str, help="Root directory for the data.") cmd_args_parser.add_argument( "--number_of_runs", type=int, default=3, help="Number of runs for evaluating the model (default: 3).", ) cmd_args_parser.add_argument( "--check...
Python
1
ion.block_dims(), args); let thread_sizes = get_sizes(self.function.thread_dims().iter().rev(), args); let mut tmp_arrays = vec![]; let params = self .function .device_code_args() .map(|x| match *x { ParamVal::External(p, _) => ThunkArg::ArgRef...
Rust
0
""" FEniCS tutorial demo program: Nonlinear Poisson equation. -div(q(u)*grad(u)) = f in the unit square. u = u_D on the boundary. """ from __future__ import print_function # Warning: from fenics import * will import both `sym` and # `q` from FEniCS. We therefore import FEniCS first and then # ...
Python
1
final text in a path") .span_note(span, "trailing param is here") .emit(); return false; } // Check if this is a dynamic param. If so, check it's well-formedness. if segment.starts_with("<") && segment.ends_with(">") { let mut param = &seg...
Rust
0
# Copyright 2015 Google 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 by applicable law or ag...
Python
1
from __future__ import annotations from pathlib import Path GRAMMAR_DIR = Path(__file__).parent GRAMMAR_PEP_508_CONSTRAINTS = GRAMMAR_DIR / "pep508.lark" GRAMMAR_PEP_508_MARKERS = GRAMMAR_DIR / "markers.lark"
Python
1
'username']] = entry assert 'u1' in by_username assert len(by_username['u1']['summary_fields']['direct_access']) == 1 assert len(by_username['u1']['summary_fields']['indirect_access']) == 0 access_entry = by_username['u1']['summary_fields']['direct_access'][0] assert sorted(access_entry['descendant...
Python
1
return True def validate_date_format(date_str: str, format_str: str = '%Y-%m-%dT%H:%M:%S') -> bool: """ Validate a date string against a format. Args: date_str: The date string to validate. format_str: The expected format of the date string. Returns: bool: True if the date string matches the form...
Python
1
for ii in range(len(sampling)): dt[ii, ...] *= sampling[ii] numpy.multiply(dt, dt, dt) if dt_inplace: dt = numpy.add.reduce(dt, axis=0) if distances.shape != dt.shape: raise RuntimeError('distances array has wrong shape') if ...
Python
1
import sys from pathlib import Path # ensure project root is on the path sys.path.append(str(Path(__file__).resolve().parents[1])) from .helpers import _parse_table, assert_readme_equivalent def test_parse_table_strips_abbr(): table = ( '| Rank | <abbr title="Overall">📊</abbr> Overall | Repo |\n' ...
Python
1
s.sat.add_clause(vec![!short_up, dx. lt_const(2)]); s.sat.add_clause(vec![!short_down, dx. lt_const(2)]); s.sat.add_clause(vec![short_down, short_up, both_straight, dx.gte_const(2)]); edge_shapes.push((e_begin,e_end)); } let print = |m:&SATDiffModel| { ...
Rust
0
# Code generated by Lark OpenAPI. from typing import Any, Optional, Union, Dict, List, Set, IO, Callable, Type from lark_oapi.core.construct import init from .property import Property class CopyFileRequestBody(object): _types = { "name": str, "type": str, "folder_token": str, "ext...
Python
1
, R> where R: Rng, { /// Create a shuffler with the given capacity. pub fn with_capacity(capacity: usize, rng: R) -> Self { RandomRemoveVec { inner: Vec::with_capacity(capacity + 1), rng, } } /// Check whether the shuffler is empty. pub fn is_empty(&self)...
Rust
0
tr, keys: &str, body: &str, answer_is_expected: bool ) -> Result<(), String> { if conf.no_answer { send_with_body(conf.clone(), wallet, depool, value, keys, body).await } else { call_contract_and_get_answer( conf.clone(), wallet, depool, ...
Rust
0
Builder::new() .with_proposals(vec![proposal]) .build() .expect("Failed to build proposal list") } fn make_agent(public_key: &str) -> Agent { AgentBuilder::new() .with_org_id("test_org".to_string()) .with_public_key(public_key.to_string()) ...
Rust
0
ethod: Methods::ToPrecision, }; } // Non-engine initialized errors return Error::FishNetOne { help: "".to_string(), }; } use std::net::IpAddr; fn unwrap_ip_address() { // We can see that 127.0.0.1 is a valid IP address, so it’s acceptable to use unwrap here. let home: IpAddr =...
Rust
0
] #[allow(non_snake_case)] pub struct Peripherals { pub IWDG: iwdg::Instance, pub WWDG: wwdg::Instance, pub FLASH: flash::Instance, pub RCC: rcc::Instance, pub PWR: pwr::Instance, pub DMA: dma::Instance, pub DMAMUX: dmamux::Instance, pub GPIOA: gpio::Instance, pub GPIOB: gpio::Instan...
Rust
0
rive::GoogleDrive; use hubcaps::Github; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use sheets::Sheets; use tracing::{event, instrument, span, Level}; use tracing_subscriber::prelude::*; use cio_api::applicants::{email_send_new_applicant_notification, get_role_from_sheet_id}; use cio_api::db::Databa...
Rust
0
tent.split('\n')) nodes = len(re.findall(r'[A-Z]+\[', content)) stats_table.add_row( title[:40] + "..." if len(title) > 40 else title, diagram_type, str(lines), str(nodes) ) total_lines += lines total_nodes += node...
Python
1
rmat", "-i", file, ], check=True, ) def parse_args(): """Setup argparse.""" parser = argparse.ArgumentParser() parser.add_argument( "certs_and_keys_header", help="output header file for test certificates and keys", ) return parser.parse_a...
Python
1
<Body>) -> FutureResponse { let sess: String = match get_session(&req) { Some(s) => s.to_string(), None => return self.respond(invalid_session()), }; if self.sessions.is_valid_session(&sess) { self.respond_with(StatusCode::OK, "") } else { ...
Rust
0
"data_quality": "high" } } } } engine.update_from_task_result("VALIDATE_DATA", result_1) # Test second task that depends on first task's result task_2 = { "task_id": "PROCESS_DATA", "when": "VALIDATE_D...
Python
1
} ), creator=collector_config.created_by, ) except Exception as e: # pylint: disable=broad-except logger.warning( f"collector_config->({collector_config.collector_config_id}) grant creator action failed, reason: {e}" ) def...
Python
1
} } else if reverse { Some((format!("key_{:03}", limit), format!("value_{:03}", limit / 2))) } else { None }; if reverse { assert_seek!(cursor, reverse_seek, seek_key, exp_kv); assert_seek!(near...
Rust
0
class Solution: def maxSum(self, grid: List[List[int]]) -> int: max_sum = 0 for row in range(len(grid)-2): for col in range(len(grid[0])-2): # top, middle, and bottom top = grid[row][col] + grid[row][col+1] + grid[row][col+2] middle = grid[...
Python
1
self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28); self.w } } #[doc = "1 Milli-Second timer interrupt Enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MSE_A { #[doc = "0: Disable"] _0, #[doc = "1: Enable"] _1, } impl From<MSE_A> for bool { #[in...
Rust
0
_td = AssertUnwindSafe(td); let future = catch_unwind(move || AssertUnwindSafe(unwind_async_fn.0(unwind_td.0))); let ret = match future { Ok(fut) => CatchUnwind::new(AssertUnwindSafe(fut)).await, Err(panic) => Err(panic), }; ...
Rust
0
potify.get_authorize_url(false).unwrap_throw())?; Response::redirect_with_status(url, 301) } <filename>src/libcore/task/poll.rs #![stable(feature = "futures_api", since = "1.36.0")] use crate::ops::Try; use crate::result::Result; /// Indicates whether a value is available or if the current task has been /// sched...
Rust
0
, /// Error value error: E, }, } impl<T, B, E> Frame<T, B, E> { /// Return the request ID associated with the frame. pub fn channel_id(&self) -> RequestId { match *self { Frame::Message { id, .. } => id, Frame::Body { id, .. } => id, Frame::Error ...
Rust
0
alues(true) .value_names(&["LOWER", "UPPER"]) .help( "Limits for the z-coordinates of the regular grid to resample to\n\ [default: same as original]", ) .takes_value(true), ) .subcommand(create_weigh...
Rust
0
import random # Hàm tạo bộ bài def create_deck(): suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades'] ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace'] deck = [(rank, suit) for suit in suits for rank in ranks] random.shuffle(deck) return deck # Hàm tính điểm của ...
Python
1
width as usize, sp.height as usize, ), }); } else { panic!("Unknown console type."); } } } } fn rebuild_consoles(bterm: &mut BTerm) { let be = BACKEND.lock().unwrap(); let gl = be.gl.as_ref().unwrap(...
Rust
0
_bytes")] code: Vec<u8>, ty_args: Vec<TypeTag>, args: Vec<TransactionArgument>, } impl Script { pub fn new(code: Vec<u8>, ty_args: Vec<TypeTag>, args: Vec<TransactionArgument>) -> Self { Script { code, ty_args, args, } } pub fn code(&self) ->...
Rust
0
t(params.keys()) for name, value in vars(self).items(): property_name = name[1:] if property_name in memeber_set: memeber_set.remove(property_name) if len(memeber_set) > 0: warnings.warn("%s fileds are useless." % ",".join(memeber_set)) clas...
Python
1
// created to serve different requests from a single client. pub trait Node { /// The implementation of the block service. type BlockService: block::BlockService; /// The implementation of the content service. type ContentService: content::ContentService; /// The implementation of the gossip servi...
Rust
0
}); last_set_bit + 1 } pub fn ecmult_wnaf_const(wnaf: &mut [i32], a: &Scalar, w: usize) -> i32 { let mut s = a.clone(); let mut word = 0; /* Note that we cannot handle even numbers by negating them to be * odd, as is done in other implementations, since if our scalars * were specified to...
Rust
0
in self.converters: return self.converters[name] return None def get_burner(self): """ returns a class for the desired burner, or the most priviledged if the desired is not installed """ if (self.config.burner is None) or (self.config.burner not in self.burners): re...
Python
1
(self, img_size, text_polys): """Generate text center region mask and geometry attribute maps. Args: img_size (tuple): The image size (height, width). text_polys (list[list[ndarray]]): The list of text polygons. Returns: text_region_mask (ndarray): The text ...
Python
1
ow_graph(self): r = gf.Flow("root") customer = test_utils.ProvidesRequiresTask("customer", provides=['dog'], requires=[]) customer2 = test_utils.ProvidesRequiresTask("customer2", ...
Python
1
; pub mod gameshark; mod left_value; mod typ; pub use decomp_data::DecompData; use lazy_static::lazy_static; lazy_static! { /// A pre-compiled `DecompData` /// /// This is compiled into the crate and is automatically deserialized from /// bincode on the first access. pub static ref DECOMP_DATA_ST...
Rust
0
from pydantic import BaseModel from typing import Optional, Dict, List class Config(BaseModel): oneapi_key: Optional[str] = "" # OneAPI KEY oneapi_url: Optional[str] = "" # API地址 oneapi_model: Optional[str] = "deepseek-chat" # 使用的语言大模型,建议使用ds-v3模型兼顾质量和成本 gemini_model: Optional[str] = "gemini-2.0-fla...
Python
1
# Analisar dados externos if hasattr(book, 'external_data') and book.external_data: self.stdout.write(' Dados Externos: Presentes') try: external_data = json.loads(book.external_data) # Verificar estrutura dos dados externos if 'volumeInf...
Python
1
ome(level) = s.parse::<u8>().ok() { Ok(NumericalLogLevel(level)) } else { match s.parse::<NamedLogLevel>() { Ok(level) => Ok(NumericalLogLevel(level as u8)), Err(_) => Err(anyhow::anyhow!(format!("Invalid level value: '{}'", s))), } } ...
Rust
0
ass>(), }, ), ( "WebKitWebPage", Layout { size: size_of::<WebKitWebPage>(), alignment: align_of::<WebKitWebPage>(), }, ), ( "WebKitWebPageClass", Layout { size: size_of::<WebKitWebPageClass>(), alignment: ali...
Rust
0
# RegularExpressionEx19.py # Program for searching for all space characters. import re sp="[abc]" matres=re.finditer(r"\S" , "CHa1b2c 3e@ u#uTrRrS") print("*"*50) for i in matres: print("\t Start Inadex:{} End Index:{} Value:{}".format(i.start(),i.end(),i.group)) print("*"*50)
Python
1
motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) del motorcycles[1] print(motorcycles)
Python
1
ghtnessDown = KEY_BRIGHTNESSDOWN, BrightnessUp = KEY_BRIGHTNESSUP, Media = KEY_MEDIA, SwitchVideoMode = KEY_SWITCHVIDEOMODE, /* Cycle between available video outputs (Monitor/LCD/TV-out/etc) */ KBDIllumToggle = KEY_KBDILLUMTOGGLE, KBDIllumDown = KEY_KBDILLUMDOWN, KBDIllumUp = KEY_KBDILLUM...
Rust
0
"); let r2 = String::from("r2"); let r3 = String::from("r3"); let r4 = String::from("r4"); let spus = DefaultSpuStore::quick(vec![ (0, true, Some(r1.clone())), (1, true, Some(r1.clone())), (2, true, Some(r1.clone())), (3, true, Some(r2.clo...
Rust
0
a4: [147, 193, 230, 137, 95, 111, 229, 172] }; pub const TaskScheduler: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 260519583, data2: 42213, data3: 19708, data4: [189, 62, 115, 230, 21, 69, 114, 221] }; #[repr(C)] #[doc = "*Required features: `\"Win32_System_TaskScheduler\"`*"] pub struct WEEKLY { ...
Rust
0
### Regular Expressions ### import re # match my_string = "Esta es la lección número 7: Lección llamada Expresiones Regulares" my_other_string = "Esta no es la lección número 6: Manejo de ficheros" match = re.match("Esta es la lección", my_string, re.I) print(match) start, end = match.span() print(my_string[start:e...
Python
1
_t1ce_node = Tensor(t1_t1ce_node, mstype.float32) flair_t2_score, t1_t1ce_score = model.predict(flair_t2_node, t1_t1ce_node) t1_t1ce_score = t1_t1ce_score.asnumpy() t1_t1ce_score = np.transpose(t1_t1ce_score, axes=[0, 2, 3, 4, 1]) ...
Python
1
=> impl_py_getter_def(name, doc, getter, &impl_wrap_getter(cls, name)), FnType::Setter(ref setter) => impl_py_setter_def(name, doc, setter, &impl_wrap_setter(cls, name, &spec)), } } fn check_generic(name: &syn::Ident, sig: &syn::MethodSig) { if !sig.generics.ty_params.is_empty...
Rust
0
.find_cost_map()[0][0] - 1; println!("Part 2 = {}", part2); } #[derive(Debug)] struct RiskMap { risk: Vec<Vec<u64>>, expected_risk: Vec<Vec<Option<u64>>>, } impl RiskMap { fn min_expected_risk(&self, pos: (usize, usize)) -> Option<u64> { let r = self.risk[pos.0][pos.1]; ...
Rust
0