text
string
label_name
string
labels
int64
# Merge Sort implementation in Python with in depth comments # # Author: BedirT # Merge Sort is a divide and conquer algorithm that divides the input array into two halves, # calls itself for the two halves, and then merges the two sorted halves. The merge() # function is used for merging two halves. The merge(arr, ...
Python
1
o, no], [no, no, no, no, no, no, 31, no, no, no, no], [no, no, no, no, no, 28, 38, 47, no, no, no], [no, no, no, no, 26, 35, 44, 52, 60, 68, no], [no, no, no, 24, 32, 41, 49, 58, 66, 76, no], [no, no, no, 29, 39, 47, 55, 63, 73, no, no], [no, no, 2...
Python
1
} use crate::Bit; impl PartialEq for Bit { fn eq(&self, other: &Self) -> bool { match (self, other) { (Bit::Zero, Bit::Zero) => true, (Bit::One, Bit::One) => true, _ => false } } } impl Eq for Bit {}<gh_stars>1-10 use nom::character::is_digit; use crate...
Rust
0
+ ESCAPE i = i + 2 elif i + 2 < n and ishex(line[i + 1]) and ishex(line[i + 2]): new = new + chr(unhex(line[i + 1:i + 3])) i = i + 3 else: new = new + c i = i + 1 if not part...
Python
1
rgs, "share_all_embeddings", False) args.no_token_positional_embeddings = getattr( args, "no_token_positional_embeddings", False ) args.adaptive_input = getattr(args, "adaptive_input", False) args.apply_bert_init = getattr(args, "apply_bert_init", False) args.decoder_output_dim = getattr( ...
Python
1
url = self.config.update_task_video_edit_update() print(f"🤖 [API-UPDATE] 使用数字人专用接口: {url}") else: url = self.config.update_task_status() print(f"📝 [API-UPDATE] 使用通用接口: {url}") headers = self.config.get_headers(tenant_id) ...
Python
1
"""Tests that simulations of reference metalenses give expected results. Copyright (c) 2023 The INVRS-IO authors. """ import dataclasses import pathlib import unittest import jax import numpy as onp import pytest from parameterized import parameterized from invrs_gym.challenges.metalens import challenge as metalens...
Python
1
from setuptools import setup, find_packages import sys setup(name="qtodotxt", version="1.9.0", description="Cross Platform todo.txt GUI", author="QTT Development Team", author_email="qtodotxt@googlegroups.com", url='https://github.com/QTodoTxt/QTodoTxt', packages=find_packages(in...
Python
1
form!(Form::Month(_))), integer_check_by_range!(1, 31), |month, integer| month.value().intersect(&helpers::day_of_month(integer.value().value as u32)?) ); b.rule_3("el <day-of-week> <day-of-month>", b.reg(r#"el"#)?, datetime_check!(form!(Form::DayOfWeek{..})),...
Rust
0
llee: Pollee::new(init_events), is_semaphore, flags: Atomic::new(flags), }) } } impl File for EventFile { fn write(&self, buf: &[u8]) -> Result<usize> { let new_val = slice_to_u64(buf)?; if new_val == u64::max_value() { return_errno!(EINVAL, "the valu...
Rust
0
/// • If such a VM exit occurs and this control is 0, the interrupt is not acknowledged and /// the VM-exit interruption-information field is marked invalid. const ACKNOWLEDGE_INTERRUPT = 1 << 15; /// This control determines whether the IA32_PAT MSR is saved on VM exit. const...
Rust
0
position( INITIAL_TERM_ID, initial_term_offset, *POSITION_BITS_TO_SHIFT, INITIAL_TERM_ID, ); image_test.subscriber_position.set(initial_position); let mut image = Image::create( SESSION_ID, CORRELATION_ID, SUBSC...
Rust
0
def calculate_price(total_people, is_agreement_customer=False, is_remote_market=False, is_hotel_package=False, is_tourism_employee=False, elderly_ratio=0.0, student_ratio=0.0): """ 计算七里扬帆三江口游线的总价格 参数: total_people (int): 总人数 is_agreement_customer (bool...
Python
1
'1,0', '1,1', '1,2', '1,3', '2,0', '2,1', '2,2', '2,3']) all_cons = ['u', 'v', 'r', 'indifference'] for cons in all_cons: constraint_data = [cons] for x in info[cons]: constraint_data.append(str(x)) ...
Python
1
import json from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async class ChatCunsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name ...
Python
1
class Solution: def minimumMoney(self, transactions: List[List[int]]) -> int: ans = 0 losses = 0 # Before picking the final transaction, perform any transaction that raises # the required money for cost, cashback in transactions: losses += max(0, cost - cashback) # Now, pick a transact...
Python
1
/Monthly/{month_abbr}01" monthly_bc_fcst_dir = f"{forcedir}/bcsd/Monthly/{month_abbr}01" outdir = f"{forcedir}/bcsd/6-Hourly/{month_abbr}01" if not os.path.exists(outdir): os.makedirs(outdir) print("[INFO] Processing temporal disaggregation of CFSv2 variables") for year in range(int(fcst_...
Python
1
import asyncio import discord from discord.ext import commands import os from config import TOKEN, PREFIX intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix=PREFIX, intents=intents) @bot.event async def on_ready(): print(f"Bot is online as {bot.user}") # Dynam...
Python
1
{ [1, 2] => 2.5e+1 }); exec!(map! {[1, 2] => [1, 2]}, { [1, 2] => [1, 2] }); exec!(map! {[1, 2] => map! {1=>2,3=>4}}, { [1, 2] => {1=>2,3=>4} }); exec!(map! {map! {1=>2,3=>4} => Null}, { {1=>2,3=>4} => null }); exec!(map! {map! {1=>2,3=>4} => true}, { {1=>2,3=>4} => true }); exec!(map! {map! {1=>2,3...
Rust
0
latility and volatility > 0: # Reduce size for high volatility volatility_adjustment = min(0.02 / volatility, 2.0) # Target 2% volatility base_size = int(base_size * volatility_adjustment) # Minimum viable size min_size = max(1, int(1000 / price)) # At leas...
Python
1
from(input: &str, separator: &str) -> Self { let mut named_columns = 0usize; let title_line = list_items(&list_clean_input(input)) .map(|name| format!("{}\x1B[0m", name)) .filter(|_| { named_columns += 1; true }) .intersper...
Rust
0
"""empty message Revision ID: 79c4ba20f308 Revises: 7307319a0b91 Create Date: 2024-09-15 10:53:37.911502 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '79c4ba20f308' down_revision = '7307319a0b91' branch_labels = None depends_on = None def upgrade(): # ...
Python
1
ng(), market_type, symbol, pair, msg_type: MessageType::L2Event, timestamp: timestamp.expect("Coinbase level2 snapshot messages don't have timestamp"), asks: orderbook_snapshot.asks.iter().map(parse_order).collect(), bids: orderbook_sna...
Rust
0
ра author_name = message.text.strip() # Сбрасываем состояние (выходим из режима ожидания ввода) await state.clear() conn = sqlite3.connect('quotes.db') cursor = conn.cursor() # Ищем автора в базе данных (используем LIKE для частичного совпадения) cursor.execute('SELECT COUNT(*...
Python
1
range(num_process): gpu_ids.put(next(gpu_id_cycle_iterator)) process_pool = Pool(processes=num_process, initializer=init_worker, initargs=(gpu_ids, _cfg, )) start_time = time.time() pool_output = list(tqdm.tqdm(process_pool.imap_unordered(\ process_input_by_worker_...
Python
1
emBC[planeInc+j*edgeElems] |= XI_M_SYMM ; self.elemBC[planeInc+j*edgeElems+edgeElems-1] |= XI_P_FREE ; self.elemBC[planeInc+j] |= ETA_M_SYMM ; self.elemBC[planeInc+j+edgeElems*edgeElems-edgeElems] |= ETA_P_FREE ; self.elemBC[rowInc+j] |= ZETA_M_SYMM ; ...
Rust
0
_none()) } { *state = Some(T::init(&self.params)); } state.as_mut().unwrap() } } /// A low-level dynamic collection of `T` values. /// /// `TypedArray` uses mmap for memory allocation. This means that memory consumption from a /// `TypedArray` is lazy: the pages are only backed by phys...
Rust
0
CsMatView::new_view(CompressedStorage::CSC, (5, 5), indptr, indices, data).unwrap(); let vector = vec![0.1, 0.2, -0.1, 0.3, 0.9]; let mut res_vec = vec![0.; 5]; mat.mul_vec(&vector, &mut res_vec); let expected_output = vec![0., 0.26439869, -0.01803924, 0.75120319, 0.11616419]...
Rust
0
use Error::*; let message = match &self { PathNotExist(path) => format!("Can't open file at {}.", path.to_str().unwrap()), LoopTarget(path) => format!("A node in file {} has target to the file itself.", path.to_str().unwrap()), LayoutNotFound(name) => format!("Can't fin...
Rust
0
( wasm_binary: &[u8], initial_authorities: Vec<( AccountId, AccountId, GrandpaId, BabeId, ImOnlineId, AuthorityDiscoveryId, )>, root_key: AccountId, endowed_accounts: Option<Vec<AccountId>>, ethereum_accounts: Option<Vec<AccountId>>, _enable_pr...
Rust
0
''' Atividade: Um trabalhador mora a 2,4 km de distância do seu emprego. Ele tem que decidir entre duas opções de transporte para chegar ao trabalho: de ônibus, cuja velocidade média em sua região é de 18 km/h, ou de bicicleta, com a qual ele é capaz de desenvolver uma velocidade média de 8 m/s. Considerando que ...
Python
1
service logging Now just disable some logs Args: exclude_paths (List[str]): The paths to disable log """ if not exclude_paths: # Not show heartbeat log exclude_paths = ["/api/controller/heartbeat"] uvicorn_logger = logging.getLogger("uvicorn.access") if uvicorn_logger:...
Python
1
""" Main script for training agents with SampleFactory. """ import sys from sample_factory.cfg.arguments import parse_full_cfg, parse_sf_args from sample_factory.envs.env_utils import register_env from sample_factory.train import run_rl from megaverse_rl.megaverse_params import add_megaverse_args, megaverse_override...
Python
1
_verify_vaa(&deps.storage, data, env.block.time)?; vaa_archive_add(&mut deps.storage, vaa.hash.as_slice())?; if state.gov_chain == vaa.emitter_chain && state.gov_address == vaa.emitter_address { if state.guardian_set_index != vaa.guardian_set_index { return Err(StdError::generic_err( ...
Rust
0
::from_str(&jstr).expect("Failed to parse item_presets.json") } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct ItemPresetsValue { pub(crate) id: String, pub(crate) name: String, #[serde(rename = "appendName")] pub(crate) append_name: String, #[serde(rename = "default")] pub(crate) i...
Rust
0
t(host) .and_then(move |stream| { let (host_reader, host_writer) = stream.split(); let sending = copy(server_reader, host_writer); let receiving = copy(host_reader, server_writer); let proxy = sending.select(receiving).map(drop).map_err(|(err, _)| { ...
Rust
0
点的的节点 pub fn find_max_children(&self) -> Option<Node> { self.find_max(&|node: &Node| node.children.len()) } /// 获取h1 pub fn find_all_h1(&self) -> Vec<Node> { self.find_all(&mut |node| node.name == "h1") } /// 遍历节点 pub fn walk<F>(&self, fun: &mut F) -> bool where ...
Rust
0
ping=retarget_data["joint_mapping"], source_tpose=source_tpose, target_tpose=target_tpose, rotation_to_target_skeleton=rotation_to_target_skeleton, scale_to_target_skeleton=retarget_data["scale"] ) # keep frames between [trim_frame_beg, trim_frame_end - 1] frame_beg = retarget_data[...
Python
1
[(Minus N), Undefined] => Undefined } forall (M: Int, N: Int) { [(Zero M), (Zero N)] => (@Unique (Zero (# M N))) [(Zero M), (Plus N)] => (Minus (# M N)) [(Zero M), (Minus N)] => (Plus (# M N)) [(Plus M), (Zero N)] => (Plus (# M N)) [(Plus M), ...
Rust
0
ict.update({"Ig_avg_data": Ig_avg_q2}) save_data_dict.update({"Qg_avg_data": Qg_avg_q2}) save_data_dict.update({"Ie_avg_data": Ie_avg_q2}) save_data_dict.update({"Qe_avg_data": Qe_avg_q2}) save_data_dict.update({"Ig_var_data": Ig_var_q2}) save_data_dict.update({"Qg_var_data": Qg_var_q2}) save_da...
Python
1
LOB: &str = "/hub-v2/children/core/children/session-manager/children/\ session:session/exec/expose/fuchsia.modular.internal.BasemgrDebug"; // Glob pattern for the path to the Launcher service exposed by basemgr when running as a v2 session. const SESSION_LAUNCHER_GLOB: &str = "/hub-v2/children/core/children/sessio...
Rust
0
at: uint16 length: uint32 numVarSelectorRecords: uint32 varSelector: Array[VariationSelector] = arrayEntry("numVarSelectorRecords") # Even though they aren't contiguous the varSelector array gives all the info needed to load the UVS tables. defaultUVS: Array[DefaultUVS] = dynamicEntry( deriv...
Python
1
ed[1:] if aggressive: datasets = [self.extract_base(x) for x in datasets] result.extend(datasets) else: if aggressive: splitted = [self.extract_base(x) for x in splitted] # ...
Python
1
import os.path as osp import os os.environ['CUDA_VISIBLE_DEVICES'] = '6, 7' import sys os.chdir(sys.path[0]) sys.path.append(osp.abspath(osp.join(os.getcwd(),'..'))) # For import model import torch import quiver from torch_geometric.datasets import Reddit import torch.multiprocessing as mp from model import SAGE if ...
Python
1
import unittest from app.modules import SiteAutoTag from app.services import auto_tag from app.services.fetchSite import fetch_site class TestCDNName(unittest.TestCase): def test_302_1(self): item = { "site": "https://www.qq.com", "title": "", "status": 302, ...
Python
1
rr(ZipError::FileNotFound); }, }; self.by_index(index) } /// Get a contained file by index pub fn by_index<'a>(&'a mut self, file_number: usize) -> ZipResult<ZipFile<'a>> { if file_number >= self.files.len() { return Err(ZipError::FileNotFound); } let ref data = self.fil...
Rust
0
dom_vec(Some(peers.other()), 5); #[cfg(feature = "telemetry")] stats.val().resent.fetch_add(neighbours.len() as u64, Ordering::Relaxed); // Transit broadcasts will be traced untagged overlay_shard.distribute_broadcast( &TaggedByteSlice { ...
Rust
0
", feature = "interpreter"))] { match Engine::from_source(&line) { Ok(result) => println!("{}", result), Err(e) => eprintln!("{}", e), }; } else if #[cfg(feature = "vm")] { ...
Rust
0
import torch import torch.optim as optim def create_optimizer(cfg, parameters): if cfg.name == "sgd": return optim.SGD( parameters, lr=cfg.lr, weight_decay=cfg.weight_decay, momentum=cfg.momentum ) elif cfg.name == "adamw": return optim.AdamW( parameters, ...
Python
1
lval[1][lval[2]] = rval; return ## def XATS000_ftset(tpl0, idx1, rval): tpl1 = tpl0.copy(); tpl1[idx1] = rval; return tpl1 ## ########################################################################. class X2PYExcptn(Exception): pass ## end of [class X2PYExcptn] ###################################################...
Python
1
, source, sc) } fn trivia_lexer<'a>( arena: &'a Bump, source_text: &'a SourceText<'a>, offset: usize, ) -> Lexer<'a, TokenFactoryFullTrivia<'a>> { Lexer::make_at(source_text, offset, TokenFactoryFullTrivia::new(arena)) } pub fn scan_leading_xhp_trivia<'a>( arena: &'a Bump, source_text: &'a Sou...
Rust
0
n, m = map(int, input().split()) res = [] def ndm(idx, depth): if depth == m: print(*res) return for i in range(1, n+1): res.append(i) if i >= res[idx-1]: idx += 1 ndm(idx, depth+1) idx -= 1 else: pass res.pop() n...
Python
1
re::u64::MAX, // Important: check func_env } } /// Creates a new table element. pub fn new(address: VirtAddr, sig_idx: SignatureIndex) -> Self { Self { address, sig_idx: sig_idx.as_u32() as u64, } } } impl VmContext { /// Heap offset in the context. ...
Rust
0
#!/usr/bin/env python """ Simple converted to convert text string into indices Used for text-to-speech synthesis Based on https://github.com/fatchord/WaveRNN """ import os import sys import re import numpy as np from core_scripts.other_tools import display as nii_warn from core_scripts.data_io.text_process import to...
Python
1
s(old_installer_contents.as_bytes()) .ok_or_else(|| anyhow!("Could not find $package_version in windows/install.ps1"))? .get(1) .ok_or_else(|| { anyhow!("Could not find the version capture group in windows/install.ps1") })? .as_bytes(), ) ...
Rust
0
e", "Makefile"), ("use.stable.mask", "Text"), (".gemrc", "YAML"), ("use.mask", "Text"), ("Jenkinsfile", "Groovy"), ("Makefile.PL", "Perl"), (".curlrc", "cURL Config"), ("zlogin", "Shell"), ("Modulefile", "Puppet"), ("gitignore-global", "Ignore List...
Rust
0
hautfarbe:', 'es': ':hombre_corriendo_tono_de_piel_claro_medio:', 'fr': ':homme_qui_court_peau_moyennement_claire:', 'ja': ':走る男_やや薄い肌色:', 'ko': ':뛰는_남자_연한_갈색_피부:', 'pt': ':homem_correndo_pele_morena_clara:', 'it': ':uomo_che_corre_carnagione_abbastanza_chiara:', ...
Python
1
import os from pdb import pm from miasm.analysis.sandbox import Sandbox_Win_x86_32 from miasm.core.locationdb import LocationDB from miasm.os_dep import win_api_x86_32_seh from miasm.jitter.csts import * def deal_exception_access_violation(jitter): jitter.pc = win_api_x86_32_seh.fake_seh_handler(jitter, win_api_x8...
Python
1
ernel.shape assert in_length == (kernel_length * hop_size), "length of (x, kernel) is not matched" padding = dilation * int((kernel_size - 1) / 2) x = F.pad(x, (padding, padding), "constant", 0) # (batch, in_channels, in_length + 2*padding) x = x.unfold(2, hop_size + 2 * padding, hop_s...
Python
1
from __future__ import annotations import os import aiohttp import voluptuous as vol from homeassistant.core import HomeAssistant, ServiceCall from homeassistant.exceptions import ServiceValidationError from .const import ( DOMAIN, LOGGER, ZHIPUAI_IMAGE_GEN_URL, IMAGE_SIZES, DEFAULT_IMAGE_SIZE, ) ...
Python
1
other: &Self) -> Ordering { self.partial_cmp(other).unwrap() } } //! @ The |eq_define| and |eq_word_define| routines take care of local definitions. //! @^global definitions@> //! Global definitions are done in almost the same way, but there is no need //! to save old values, and the new value is associate...
Rust
0
self.frontiter.as_mut().and_then(|it| it.next_back()), next => self.backiter = next.map(IntoIterator::into_iter), } } } #[inline] fn try_rfold<Acc, Fold, R>(&mut self, mut init: Acc, mut fold: Fold) -> R where Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: T...
Rust
0
from manim import RED, MarkupText, Text, VMobject __module_test__ = "text" def test_Text2Color(): txt = Text( "this is a text with spaces!", t2c={"spaces": RED}, stroke_width=1, disable_ligatures=True, ) assert len(txt.submobjects) == 29 assert all(char.fill_color.to...
Python
1
.iter() .find_map(|(template, pin)| { if template.alias() == *alias { Some(pin) } else { None } }) .unwrap(); let png = folder.child(forma...
Rust
0
# Copyright (c) 2025 Arne Deutsch, itemis AG, MIT License import json import subprocess import sys from pathlib import Path import pytest from hippo_eval.eval.score import em_norm, normalize from hippo_mem.testing import FAKE_MODEL_ID def test_normalize_and_em() -> None: assert normalize("The, apple!") == "appl...
Python
1
------------------------------------------- trigger2 = triangle.period_start_marker() # ----------------------------------------------------------------------- assert trigger2 == trigger assert qdac.get_recorded_scpi_commands() == [ f'sour1:tri:mark:pstart {trigger.value}' ] def test_trian...
Python
1
Flask # COMMAND ---------- from flask import Flask, jsonify, request app = Flask("llama2-13b-chat") @app.route('/', methods=['POST']) def serve_falcon_7b_instruct(): resp = gen_text_for_serving(**request.json) return jsonify(resp) # COMMAND ---------- from dbruntime.databricks_repl_context import get_context...
Python
1
let t = thread::current(); if let Some(name) = t.name() { write!( buf, "{}{} {} {}] {}{}", prefix, chrono::Local::now().format(TIME_FORMAT), name, record.metadata().target(), record.args()...
Rust
0
jiang Anji Saianfu Biotech Co., Ltd, AndLucky COVID-19 Antigen Rapid Test"), "1304" => Cow::Borrowed("AMEDA Labordiagnostik GmbH, AMP Rapid Test SARS-CoV-2 Ag"), "1319" => Cow::Borrowed("SGA Medikal, V-Chek SARS-CoV-2 Ag Rapid Test Kit (Colloidal Gold)"), "1331" => Cow::Borrowed("Beijing Lepu Me...
Rust
0
from diffsynth import save_video, SDXLImagePipeline, ModelManager, SVDVideoPipeline from diffsynth import ModelManager import torch # Download models # `models/stable_diffusion_xl/sd_xl_base_1.0.safetensors`: [link](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/sd_xl_base_1.0.safetensor...
Python
1
ant C represents the average day light with a CCT of /// 6774 K Uses the CIE 1932 2° Standard Observer #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct C; impl<T: FromF64> WhitePoint<T> for C { #[inline] fn get_xyz() -> Xyz<Any, T> { Xyz::new(from_f64(0.98074), from_f64(1.0), from_f64(1.18232)) ...
Rust
0
t = await resp.text() assert isinstance(result, str) if rule.contains and result.find(rule.contains) < 0: raise ValidationFailException() rules[rule.key] = True except Exception: rules[rule.key] = False ...
Python
1
e('"', '').replace("'", "").strip() logger.info(f"✅ 뉴스 생성 완료: {news_content}") return f"{stock_display} 관련 최신 뉴스: '{news_content}' 입니다." except Exception as openai_error: logger.error(f"❌ OpenAI API 오류: {openai_error}") logge...
Python
1
from core.praser import init_obj def create_model(**cfg_model): """ create_model """ opt = cfg_model['opt'] logger = cfg_model['logger'] model_opt = opt['model']['which_model'] model_opt['args'].update(cfg_model) model = init_obj(model_opt, logger, default_file_name='models.model', init_type='...
Python
1
"""Implementation of mathematical domains. """ __all__ = [ 'Domain', 'FiniteField', 'IntegerRing', 'RationalField', 'RealField', 'ComplexField', 'AlgebraicField', 'PolynomialRing', 'FractionField', 'ExpressionDomain', 'PythonRational', 'GF', 'FF', 'ZZ', 'QQ', 'ZZ_I', 'QQ_I', 'RR', 'CC', 'EX', 'EXRAW',...
Python
1
&ctx.context).context("handle_github_webhook() failed") { Ok(value) => value, Err(err) => { return Err(pyo3::exceptions::PyOSError::new_err(format!("{:?}", err))); } }; Ok(yattag::PyDoc { doc }) } pub fn register_python_symbols(module: &PyModule) -> PyR...
Rust
0
.with_context(|| format!("Producing download URL for binary dep {}", package.name))?, ); } Ok(SourceDetails { git_data, download_url, }) } fn produce_download_url( crates_io_template: &str, source: &Source, package_name: &str, package_version: &semver::Versi...
Rust
0
) -> DCINSS0_W { DCINSS0_W { w: self } } #[doc = "Bit 17 - Digital Comparator Interrupt Status on SS1"] #[inline(always)] pub fn dcinss1(&mut self) -> DCINSS1_W { DCINSS1_W { w: self } } #[doc = "Bit 18 - Digital Comparator Interrupt Status on SS2"] #[inline(always)] pub ...
Rust
0
""" ========= Spy Demos ========= Plot the sparsity pattern of arrays. """ import matplotlib.pyplot as plt import numpy as np # Fixing random state for reproducibility np.random.seed(19680801) fig, axs = plt.subplots(2, 2) ax1 = axs[0, 0] ax2 = axs[0, 1] ax3 = axs[1, 0] ax4 = axs[1, 1] x = np.random.randn(20, 20) ...
Python
1
= dim.target_range.start; steps[dim.target_dim] = dim.target_range.step; match dim.target_range.end { Some(v) => { if v < 0 { upperbounds[dim.target_dim] = 0; // random number as it doesn't matter neg_upperbounds[dim.target_dim] = -v as usize; unknown_u...
Rust
0
CENTRAL_LESC_BONDING_PKE_PD_MSC}"] #[doc = " @mmsc{@ref BLE_GAP_CENTRAL_LESC_BONDING_PKE_CD_MSC}"] #[doc = " @mmsc{@ref BLE_GAP_CENTRAL_LESC_BONDING_OOB_MSC}"] #[doc = " @endmscs"] #[doc = ""] #[doc = " @param[in] conn_handle Connection handle."] #[doc = " @param[in] p_sec_params Pointer to the @ref ble_gap_sec_params_...
Rust
0
: ClassId, instance_id: InstanceId, price: Option<BalanceOf<T>>, ) -> DispatchResult { let who = ensure_signed(origin)?; let owner = Self::owner(&class_id, &instance_id)?; ensure!(owner == who, Error::<T>::MustBeCardOwner); Self::set_price(&class_id, &instance_id, &price)?; ...
Rust
0
age.as_bytes()).unwrap(); assert_eq!(bytes, message.as_bytes().len()); remote_thread.join().unwrap(); } fn start_udp_proxy() -> Child { let proxy = binary() .arg("--verbose") .arg("--udp") .arg("--server") .arg("localhost") .arg("--server-port") .arg("44310"...
Rust
0
-> LPTM_R { LPTM_R::new(((self.bits >> 16) & 0x7f) as u8) } } #[doc = "Error and Status 2 register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [esr2](index.html) module"] pub struct ...
Rust
0
import numpy as np import pytest from numpy.testing import assert_almost_equal from sklearn.metrics.pairwise import pairwise_kernels from ...tools import linear, power from .. import Hsic class TestHsicStat: @pytest.mark.parametrize("n, obs_stat", [(100, 1.0), (200, 1.0)]) @pytest.mark.parametrize("obs_pvalu...
Python
1
ex] if self.noise_magnitude > 0: for key in self.need_add_noise_keys: if key in result_dict.keys(): result_dict[key] = (result_dict[key] + self.noise_magnitude * np.random.randn(*result_dict[key].shape).astype(result_dict[key]...
Python
1
B cv0FzDB5lcjDBNz7zDBZQVjDBZQrzDBBWXjDB cCB8xDBO0gjDBGZgyDBx1hjDBKceyDBIFkjDB cgVDxDBf/ZiDBepqxDBwKfjDBJbNxDBZQ4iDB ccS6wDBEtPgDBXP5wDBHv7hDBfU0wDBlDzgDB ciWUxDB/puaDBZQAxDBEtYfDBJGKxDBdT2bDB cqGkxDBW58TDB6mexDBf/mZDB2jkxDBFuEVDB c8nOxDBfUYQDB9ojxDBnE1SDBDXcxDBNeNRDB cVjxwDBXP4ODBtdAxDBV...
Rust
0
import argparse from konoha import SentenceTokenizer from konoha import WordTokenizer if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--endpoint", type=str, default=None) args = parser.parse_args() sentence_tokenizer = SentenceTokenizer() tokenizers = ["MeCab",...
Python
1
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from __future__ import print_function import logging from .main_view import Win from threading import RLock from doubanfm.colorset.colors import color_func # colors from doubanfm.dal.dal_lrc import LrcDal logger = logging.getLogger('doubanfm') mutex = RLock() class Lr...
Python
1
args["page_wise"] is True return mock_layout_analysis monkeypatch.setattr( "layout_analysis.LayoutAnalysis", mock_layout_analysis_constructor ) result = await process_layout_analysis(record, page_wise=True) # Verify analyse was called mock_layout_analysis.analyse.assert_called_onc...
Python
1
lon, -g) kp_inc_mask = kp_inc.abs().max(dim=-1)[0] <= 0.5 return kp_inc, kp_singularity_mask, kp_inc_mask """ Legacy code """ def iterative_nms(score, nms_size): prev_nms_mask = nms(score, nms_size, True) prev_nms_box_mask = apply_box_filter(prev_nms_mask.float(), nms_size) > 0 while True: ...
Python
1
": [Interval(Integral, 0, None, closed="left")], "alpha": [Interval(Real, 0, None, closed="left")], "warm_start": ["boolean"], "fit_intercept": ["boolean"], "tol": [Interval(Real, 0.0, None, closed="left")], } def __init__( self, *, epsilon=1.35, ...
Python
1
#[test] fn serialize_tx_with_sigs() { let minter = crypto::KeyPair::gen(); let wallet = crypto::KeyPair::gen(); let mut owner_tx = TxVariant::V0(TxVariantV0::OwnerTx(OwnerTx { base: Tx { timestamp: 1230, fee: get_asset("123.00000 MARK"), ...
Rust
0
UINT = 128; pub const D3D12_IA_DEFAULT_INDEX_BUFFER_OFFSET_IN_BYTES: UINT = 0; pub const D3D12_IA_DEFAULT_PRIMITIVE_TOPOLOGY: UINT = 0; pub const D3D12_IA_DEFAULT_VERTEX_BUFFER_OFFSET_IN_BYTES: UINT = 0; pub const D3D12_IA_INDEX_INPUT_RESOURCE_SLOT_COUNT: UINT = 1; pub const D3D12_IA_INSTANCE_ID_BIT_COUNT: UINT = 32; p...
Rust
0
Ok((self.env.number_elements, self.env.cumulative_size)) } fn clock_res_get(&self, id: types::Clockid) -> Result<types::Timestamp> { let resolution = clock::res_get(id)?; Ok(resolution) } fn clock_time_get( &self, id: types::Clockid, _precision: types::Timestamp...
Rust
0
nst REQUEST_BYTE: u8 = b'\x06'; const PIECE_BYTE: u8 = b'\x07'; const CANCEL_BYTE: u8 = b'\x08'; const PORT_BYTE: u8 = b'\x09'; pub fn deserialize(from: &mut BytesMut) -> IResult<Message<'static>, MagnetiteError> { if from.len() < 4 { return IResult::ReadMore(4 - from.len()); } let size = BigEndian...
Rust
0
index=data_point['index'], input=data_point['input'], outputs=data_point['outputs'], others=data_point.get('others', {}), truncation=data_point.get('truncation', -1), length=data_point.get('length', -1), ...
Python
1
class Solution: def minimumEffortPath(self, heights: List[List[int]]) -> int: left = 0 right = max(max(row) for row in heights) m,n = len(heights),len(heights[0]) dirs = [[0,1],[1,0],[-1,0],[0,-1]] # can we complete the journey with effort x def journey(row,col,effort...
Python
1
equirementBuilder { pub fn build(&self) -> DataRequirement { DataRequirement { value: Cow::Owned(self.value.clone()), } } pub fn with(existing: DataRequirement) -> DataRequirementBuilder { DataRequirementBuilder { value: (*existing.value).clone(), } ...
Rust
0
if self.training: goals = self.mask_cond(goals) # we want to use unconditional sampling during clasisfier free guidance if uncond: goals = torch.zeros_like(goals).to(self.device) goal_embed = self.tok_emb(goals) # embed them into lin...
Python
1