text
string
label_name
string
labels
int64
": False, }, } def test_prepare_database_dict_prod() -> None: secrets_accessor = DummySecretsAccessor.create_rotatable() db_secret = { "engine": "postgres", "host": "marge", "port": 7727, "user": "midsize", "password": "the-holding", "set_role": "sta...
Python
1
import torch from torch import Tensor def robust_l1_loss(pred_mean: Tensor, pred_log_std: Tensor, target: Tensor) -> Tensor: """Robust L1 loss using a Lorentzian prior. Trains the model to learn to predict aleatoric (i.e. per-sample) uncertainty. Args: pred_mean (Tensor): Tensor of predicted mean...
Python
1
l": {"url": icon}} if cover: kwargs["cover"] = {"type": "external", "external": {"url": cover}} page = self.client.pages.create(**kwargs) logger.info(f"Created new page: {page['url']}") return { "id": page["id"], "title": report.title, ...
Python
1
import json import boto3 import logging import csv logger = logging.getLogger() logger.setLevel(logging.INFO) s3_client = boto3.client('s3') def lambda_handler(event, context): # Log the received event logger.info("Received event: " + json.dumps(event, indent=2)) # Extract bucket name and file key (obje...
Python
1
bar::bars(sheet, tpb)); Ok(Self { player, response: receiver, config, }) } } use crate::core::transport::auth::Digest; use crate::core::transport::crypto::{AssociatedData, Nonce}; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug, Clone, Copy)] pub(crate) enum PacketEncryption...
Rust
0
ans("","", string.punctuation)).replace(' ', '')}'; ''') phrase_to_modif = phrase print("la phrase a bien été modifiée") ans = input("Voulez vous modifier la commande ? (yes) : ") if ans == "yes": cmd_list = [] print("Donnez nous la nouvelle...
Python
1
onfigurado e conectado") return config except Exception as e: if debug_db: print(f"❌ Falha na conexão com MySQL: {e}") print(f"🔄 Fazendo fallback para SQLite...") # Fallback explícito para SQLite engine = 'sqlite' # Fallback p...
Python
1
if matches.is_present("daemonize") { let stdout = File::create("/tmp/gejji.out").unwrap(); let stderr = File::create("/tmp/gejji.err").unwrap(); let daemonize = Daemonize::new() .pid_file("/tmp/test.pid") .chown_pid_file(true) .working_directory("/tmp") ...
Rust
0
s3 upload_part err: {}", err)))?; let part_e_tag = part_res .e_tag() .ok_or_else(|| Error::from("s3 upload part missing e_tag"))?; parts.push( CompletedPart::builder() .e_tag(part_e_tag) .part_number(part_num...
Rust
0
go_metadata.status.success() { panic!("cargo metadata failed"); } let metadata: Metadata = serde_json::from_slice(cargo_metadata.stdout.as_ref()).unwrap(); let workspace_packages = metadata .packages .iter() .filter(|package| metadata.workspace_members.contains(&package.id)...
Rust
0
substrate_subxt/struct.Client.html) parameterised to `MyRuntime`, you have access to /// two new methods: `fun_stuff()` and `fun_stuff_and_watch()` by way of the derived `FunStuffExt` /// trait. The `_and_watch` variant makes the call and waits for the result. The fields of the /// input struct become argum...
Rust
0
s.current_mp - mp_cost) # 魔法効果を適用 result = self._apply_spell_effect(spell_id, attacker, target, context) else: result = ActionResult(success=False, message="魔法IDが指定されていません") return result def _get_spell_mp_cost(self, spell_id: str) -> in...
Python
1
import torch.nn as nn import torch import pandas as pd class NN_BN_Model(nn.Module): def __init__(self,hidden_layer=64): super(NN_BN_Model, self).__init__() self.inp = nn.Linear(5, hidden_layer) self.BN_inp = nn.BatchNorm1d(hidden_layer) self.linear = nn.Linear(hidden_layer,hidden_l...
Python
1
use the /// ccommon debug logger once that is set up. pub fn init() -> Result<(), SetLoggerError> { use log::LevelFilter; // TODO: dynamically set this based on dlog? log::set_max_level(LevelFilter::Trace); log::set_logger(&LOGGER) } /// Set the global panic handler to one which logs the /// panic at...
Rust
0
ue of the field is `RF_GPIO5_SRC_DIO_12`"] #[inline(always)] pub fn is_rf_gpio5_src_dio_12(&self) -> bool { *self == GPIO5_A::RF_GPIO5_SRC_DIO_12 } #[doc = "Checks if the value of the field is `RF_GPIO5_SRC_DIO_13`"] #[inline(always)] pub fn is_rf_gpio5_src_dio_13(&self) -> bool { ...
Rust
0
from engine import * class Zephyra(PokemonBase): _species='Zephyra' _types=['Flying'] _gender='Mele' _ability=['Speedy Recovery'] _move_1=('Brave Bird',120,100,'Physical','Flying',0,['contact']) _move_2=('Steel Wing',70,90,'Physical','Steel',0,['contact']) def __init__(self): super...
Python
1
) points_=embed_fn(points) cam_input = torch.cat([points_, out_dirs_,normals], dim=-1) Radiance=[] for pos,outd in zip(torch.split(points_,1000),torch.split(out_dirs_,1000)): radiance=renderer(pos,outd,uni_in_dirs_).unsqueeze(0)/100 #1*N*M*3 ...
Python
1
# Bonsai - OpenBIM Blender Add-on # Copyright (C) 2023 Dion Moult <dion@thinkmoult.com> # # This file is part of Bonsai. # # Bonsai is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Licen...
Python
1
from odoo import fields, models class ResPartner(models.Model): _inherit = 'res.partner' l10n_br_indicador_ie_dest = fields.Selection( [('1', '1 - Contribuinte ICMS'), ('2', '2 - Contribuinte isento de Inscrição no cadastro de \ Contribuintes do ICMS'), ('9', '9 - Nã...
Python
1
#----------------------------------------------------------------- # Benchmarking utility for internal use. # # Use with Python 3.6+ # # Eli Bendersky [https://eli.thegreenplace.net/] # License: BSD #----------------------------------------------------------------- import os import statistics import sys import time sy...
Python
1
ord) .await?; let token: Token = match login_response.status() { StatusCode::OK => login_response.json().await?, StatusCode::BAD_REQUEST => { let body = login_response.body().await?; let body_value: serde_json::Value = serde_json::from_slice(&body)?; let ...
Rust
0
import os import pygame from tkinter import * class MusicPlayer: def __init__(self, root): self.root = root self.root.title("Music Player") self.root.geometry("1000x200+200+200") pygame.init() pygame.mixer.init() self.track = StringVar() self.status = StringV...
Python
1
import numpy import pytest from thinc.layers import premap_ids, remap_ids, remap_ids_v2 @pytest.fixture def keys(): return numpy.array([4, 2, 6, 1, 8, 7, 9, 3, 30]) @pytest.fixture def mapper(keys): return {int(k): int(v) for v, k in enumerate(keys)} def test_premap(keys, mapper): premap = premap_ids...
Python
1
#!/usr/bin/python3 def simple_delete(my_dict, key=""): my_dict.pop(key, None) return my_dict
Python
1
!(server.read_to_end(&mut received)); iotry!(server.close()); })); }); } #[bench] fn bench_transfer_one_packet(b: &mut Bencher) { let len = 1024; let server_addr = next_test_ip4(); let data = (0..len).map(|x| x as u8).collect::<Vec<u8>>(); let data_arc = Arc::new(data); b.i...
Rust
0
0, 57.0), 0.185259) print("==================================================") # ((-63.0, -45.0), 1.0) assert find_region_max_value(RAMA_ILE_VAL, -60, -40) == ((-63.0, -45.0), 1.0) assert find_region_max_value(RAMA_ILE_VAL, -120, -60) == ((-63.0, -45.0), 1.0) assert find_region_max_value(RAMA_ILE_VAL, -120,...
Python
1
{agent_scratchpad}""" # Set up a prompt template class CustomPromptTemplate(StringPromptTemplate): # The template to use template: str # The list of tools available tools: List[BaseTool] def format(self, **kwargs) -> str: # Get the intermediate steps (AgentAction, Observation tuples) ...
Python
1
#!/usr/bin/env python3 # Google API for "commentThreads": # https://developers.google.com/youtube/v3/docs/commentThreads/list # # Example video on YouTube video to get comments: # https://www.youtube.com/watch?v=oVp1vrfL_w4&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M # # Python module for Google API (not used in exa...
Python
1
e in ['CGC 10', 'CGC 9.5', 'CGC 9']: if grade in title: return grade return None def _extract_card_name(self, title: str) -> Optional[str]: """Extract card name from graded card title""" # Simplified extraction - in production would be more sophistic...
Python
1
# Code generated by Lark OpenAPI. from typing import Any, Optional, Union, Dict, List, Set, IO, Callable, Type from lark_oapi.core.construct import init class InterviewMeetingRoom(object): _types = { "room_id": str, "room_name": str, "building_name": str, "reserved_status": int, ...
Python
1
Pos { fn eq(&self, other: &CloseChunkPos) -> bool { self.square_dist == other.square_dist } } impl PartialOrd for CloseChunkPos { fn partial_cmp(&self, other: &CloseChunkPos) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl Eq for CloseChunkPos {} impl Ord for CloseChunkP...
Rust
0
CROSS_INPUT_RESET: u32 = 0; pub const SIO_INTERP0_CTRL_LANE0_CROSS_INPUT_BITS: u32 = 65536; pub const SIO_INTERP0_CTRL_LANE0_CROSS_INPUT_MSB: u32 = 16; pub const SIO_INTERP0_CTRL_LANE0_CROSS_INPUT_LSB: u32 = 16; pub const SIO_INTERP0_CTRL_LANE0_CROSS_INPUT_ACCESS: &'static [u8; 3usize] = b"RW\0"; pub const SIO_INTERP0_...
Rust
0
rue, false, false, None, true); assert_eq!(command, expect); } #[test] fn test_current_branch() { let command = current_branch(); assert_eq!(command.raw, "git branch"); assert!(command.dir.is_empty()); assert!(!command.show); assert!(command.silent); assert!(command.pipe); assert!(comm...
Rust
0
(self.X, new_coefs) + residues * new_coefs[0] / coefs[0]).T def emsc(spectra: np.ndarray, wavenumbers: np.ndarray, order: int = 2, reference: np.ndarray = None, constituents: np.ndarray = None, return_coefs: bool = False) -> U[np.ndarray, T[np.ndarray, np.ndarray]]: """ Preprocess all...
Python
1
let x = f32::from(measure.x) * SENSITIVITY; // let y = f32::from(measure.y) * SENSITIVITY; // let z = f32::from(measure.z) * SENSITIVITY; // iprintln!(&mut itm.stim[0], "{:?}", (x, y, z)); match instant { None => { // If acceleration goes above a th...
Rust
0
none(), true); assert_eq!(list.back().is_none(), true); assert_eq!(list.size(), 0); list.push_back(7); list.push_back(4); list.push_back(1); assert_eq!(*list.front().unwrap(), 7); assert_eq!(*list.back().unwrap(), 1); assert_eq!(list.size(), 3); ...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' FISCO BCOS/Python-SDK is a python client for FISCO BCOS2.0 (https://github.com/FISCO-BCOS/) FISCO BCOS/Python-SDK is free software: you can redistribute it and/or modify it under the terms of the MIT License as published by the Free Software Foundation. This proje...
Python
1
reation let queue_family = physical .queue_families() .find(|&q| q.supports_graphics()) .expect("couldn't find a graphical queue family"); let (device, mut queues) = { Device::new( physical, &Features::none(), &DeviceExtensions::none(), ...
Rust
0
_op_ex!(+ |a: &Int, b: &Int| -> Int { Int { value: a.value.clone() + b.value.clone() } }); impl_op_ex_commutative!(+ |a: &Int, b: &i8| -> Int { op_other!(+, a, b) }); impl_op_ex_commutative!(+ |a: &Int, b: &u8| -> Int { op_other!(+, a, b) }); impl_op_ex_commutative!(+ |a: &Int, b: &i16| -> Int { op_other!(+, a, b) }); ...
Rust
0
import jax import jax.numpy as jnp import pytest from dynamiqs.method import Tsit5 from ..order import TEST_LONG from .floquet_qubit import FloquetQubit @pytest.mark.run(order=TEST_LONG) class TestFloquet: @pytest.mark.parametrize('omega', 2.0 * jnp.pi * jnp.array([1.0, 2.5])) @pytest.mark.parametrize('amp'...
Python
1
Response, Error> for PowerDescriptorResponse { fn pack(&self, data: &mut [u8]) -> Result<usize, Error> { let size = if self.status == Status::Success { 5 } else { 3 }; if data.len() != size { return Err(Error::WrongNumberOfBytes); } data[0] = u8::from(self.status); ...
Rust
0
set a dummy string if it's None. # This still makes sense when using vLLM because it doesn't care about the API key. client_sync = OpenAI( api_key=openai_client.api_key or "EMPTY", base_url=openai_client.base_url ) models = client_sync.models.list() if len(models.data) != 1: raise V...
Python
1
int transmit FIFO size register"] pub mod otg_hs_dieptxf2; #[doc = "OTG_HS device IN endpoint transmit FIFO size register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero),...
Rust
0
r { fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> { self.expr } fn make_items(self: Box<Self>) -> Option<SmallVector<P<ast::Item>>> { self.items } fn make_impl_items(self: Box<Self>) -> Option<SmallVector<ast::ImplItem>> { self.impl_items } fn make_trait_it...
Rust
0
import typer import logging import asyncio from arxivllm import find as find_arxiv_papers, present app = typer.Typer() def setup_logging(debug: bool = False): app_level = logging.DEBUG if debug else logging.INFO logging.basicConfig( level=app_level, # Set default level based on debug flag for...
Python
1
Some(payload) } else { None } } } impl<R: radio::PhyRxTx + Timings, const N: usize> Shared<R, N> { pub fn new( radio: R, credentials: Option<Credentials>, region: region::Configuration, mac: Mac, get_random: fn() -> u32, ) -> S...
Rust
0
n(dean_eoa2seq_in, dean_eoa2seq_out) eoa2seq_agg.update(dean_eoa2seq_agg) if args.tornado: print("Add tornado...") tornado_in = open(os.path.join(args.data_dir, "tornado_trans_in_removed.csv"), "r") tornado_out = open(os.path.join(args.data_dir, "tornado_trans_out_removed.csv"), "r"...
Python
1
} /// Infallible sorted insertion /// caller must verify !self.nominators.contains(nominator.owner) before /// call pub fn add_top_nominator(&mut self, nominator: Bond<A, B>) { match self.top_nominators.binary_search_by(|x| nominator.amount.cmp(&x.amount)) { Ok(i) => self.top_nominators.insert(i, nom...
Rust
0
)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `SCANDV` reader - Scan Data Valid"] pub struct SCANDV_R(crate::FieldReader<bool, bool>); impl SCANDV_R { pub(crate) fn new(bits: bool) -> Self { SCANDV_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for SCANDV_R...
Rust
0
assert_eq!(from_rows, Matrix::from(2, 4, &[1.0, 2.0, 1.0, -1.0, 4.0, 4.0, 3.0, 4.0,])); } #[test] fn test_get_columns() { let mat = Matrix::from(4, 4, &DATA); let from_cols = mat.get_columns(&[0, 2]); assert_eq!(from_cols, Matrix::from(4, 2, &[1.0, 1.0, 3.0, 4.0, 4.0, 3.0, 2.0, 1.0...
Rust
0
iter().enumerate().advance |(i, filename)| { let contents = vec::from_fn(3, |j| fmt!("%u %u", i, j + 1)); make_file(filename.get_ref(), contents); } let in = FileInput::from_vec(filenames); // read once from 0 assert_eq!(in.read_line(), ~"0 1"); ...
Rust
0
# Magnetic field of a toroid, using Biot-Savart law # Ruth Chabay, Carnegie Mellon University, 2000-05-30 from visual import * scene.width=800 scene.height=800 scene.title="Magnetic Field of a Toroid" scene.minscale=.95 bigradius = 0.25 smallradius=0.03 I=1. muthing=1e-7 nturns=75. # number of loops in helix nsteps...
Python
1
esInRange_withBytes_length_((item, 1), b"", 0) def nsmutabledata__iadd__(self, iterable_of_ints): view = memoryview(iterable_of_ints) self.appendData_(view) return self def nsmutabledata_extend(self, iterable_of_ints): try: view = memoryview(iterable_of_ints) except TypeError: s...
Python
1
box_coder.decode_export(batch_priors, batch_mlvl_bboxes_pred, max_shape=img_shape) if with_score_factors: batch_score_factors = torch.cat(mlvl_score_factors, dim=1) if not self.use_sigmoid_cls: batch_scores = batch_scores[..., : self.num_classes] if with_score_factors:...
Python
1
, data: Message::default(), } } } impl From<ForeignEnvelope> for Envelope { fn from(other: ForeignEnvelope) -> Self { Self { reverse_path: other.reverse_path, forward_paths: other .forward_paths .into_iter() .map(|fpath| fpath.into()) .collect(), data: other.data, } } } use desktop...
Rust
0
ry2_result, default=str) # make sure the query log populates run_query("SYSTEM FLUSH LOGS") benchmarking_result = [] i = 0 while len(benchmarking_result) == 0 and i < 10: benchmarking_result = run_query( BENCHMARKING_SQL, p...
Python
1
all_SSIM_gcess.append(SSIM_gcess.cpu().detach().numpy()) print('test_gcess---------', " [RLNE: %f] : [PSNR: %f/%f] " % (RLNE_gcess, PSNR_gcess, PSNR1)) rec_label_data.append(label_data.cpu().detach().numpy()) torch.cuda.empty_cache() all_PSNR_gcess = np.array(al...
Python
1
ss\";\ \n\ \nfoo {\ \n blah: blah;\ \n goo {\ \n blee: blee;\ \n @import \"../14_imports/b.scss\";\ \n hello: world;\ \n }\ \n @import \"sub/c.scss\";\ \n}" ) .unwrap(), ...
Rust
0
import numpy as np import cv2 import glob from tqdm import tqdm import os import json square_size = 16 criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 50, 0.0001) checkerboard_size_row = 41 checkerboard_size_col = 64 x, y = np.mgrid[0:checkerboard_size_col, 0:checkerboard_size_row] objp = np.zeros((che...
Python
1
fn weak_portal(&self) -> WeakPortal<T> { Portal::downgrade(&self.portal()) } } impl<'a, T: ?Sized> RwAnchor<'a, T> { #[inline] pub fn new(reference: &'a mut T) -> Self { Self { reference: ManuallyDrop::new(Arc::new(RwLock::new(reference.into()))), _phantom: PhantomDa...
Rust
0
import pytest import pygame import numpy as np from sim_env.renderer import meters_to_pixels from sim_env.parameters import Config from sim_env.car import Car def test_initialize_window(renderer): """Test if the window initializes correctly.""" renderer.initialize_window() assert renderer.window is not No...
Python
1
j + 1, col=i + 1, ) fig.update_yaxes(row=j + 1, col=i + 1, range=[-2, 105]) fig.update_yaxes(title_text="Accuracy", row=1, col=1) margin = 20 fig.update_annotations(font_size=22) fig.update_layout( width=600, height=400, margin=dict(l=margin * 4, r=margin, b=margin * 3.5, t=margi...
Python
1
lysis = { "dir_score": dir_score, "total_problems": total, "level_distribution": level_counts, "level_percentages": { level: (count / total * 100) if total > 0 else 0 for level, count in level_counts.items() }, "comp...
Python
1
ize=args.cp_size, sequence_parallel=args.sequence_parallel, ), log_every_n_steps=1, limit_val_batches=0.0, num_sanity_val_steps=0, accumulate_grad_batches=1, gradient_clip_val=grad_clip, u...
Python
1
arr.set(0, "string"); var x = arr[1]; var y = arr.get(0); "#; let (stmts, mut inter) = get_stmts(input); assert_eq!(Ok(()), inter.interpret(&stmts)); assert_eq!(Ok(10.into()), env_get(&inter, "x")); assert_eq!(Ok("string".into()), env_get(&inter, "y")); } #[test] fn test_array_push() { ...
Rust
0
algorithm_id: AlgorithmId, message: Vec<u8>, key_id: KeyId, ) -> Result<CspSignature, CspThresholdSignError>; // Corresponds to `ThresholdSignatureCspVault.threshold_keygen_for_test()`. async fn threshold_keygen_for_test( algorithm_id: AlgorithmId, threshold: NumberO...
Rust
0
# -*- coding: utf-8 -*- # # Copyright 2017 Google LLC. 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 requir...
Python
1
######################################################################################## # # # LEDAW - LED Analysis Wizard # # Ledip Module ...
Python
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 设备配置文件 管理 FunASR 的 GPU/CPU 设置 """ import logging import os logger = logging.getLogger(__name__) # 设备配置 DEVICE_CONFIG = { # 强制使用特定设备 ("auto", "cpu", "cuda") "force_device": "auto", # GPU 相关设置 "gpu_settings": { "preferred_gpu_id": 0, # 优先...
Python
1
= est.predict(Xt) assert np.isnan(p[0]) and np.isnan(p[1]) expected = np.array([np.nan, np.nan, 1, 2, 3, 5, 11, 12]) np.testing.assert_allclose(p, expected, atol=0.5) def test_groupby_smoother_cb_weights(): xone = np.ones(4) weights = [0, 0, 0, 1] X = np.c_[[0, 0, 1, 1], [0, 0, 0, 0], [0, 1, ...
Python
1
ive(Debug, PartialEq, Eq, Clone, Hash, Serialize)] #[must_use] pub struct Fresh { thumb_url: String, #[serde(rename = "photo_url")] url: String, #[serde(skip_serializing_if = "Option::is_none", rename = "photo_width")] width: Option<usize>, #[serde(skip_serializing_if = "Option::is_none", rename...
Rust
0
Europa', 'no': 'Europa', 'nqo': 'ߋߙߐߔߎ߬', 'or': 'ୟୁରୋପ୍', 'os': 'Европӕ', 'pa': 'ਯੂਰਪ', 'pa-Guru': 'ਯੂਰਪ', 'pcm': 'Yúrop', 'pl': 'Europa', 'ps': 'اروپا', 'pt': 'Europa', 'qu': 'Europa', 'rm': 'Europa', 'ro': 'Europa', 'ru': 'Европа', 'sc': 'Europa', 'sd': 'يورپ', 'sd-Arab': 'يورپ', 'se': 'Eurohpá', 'si': 'යුරෝපය', 'sk'...
Python
1
Type; macro_rules! diagnostics { ($($diag:ident,)*) => { pub enum AnyDiagnostic {$( $diag(Box<$diag>), )*} $( impl From<$diag> for AnyDiagnostic { fn from(d: $diag) -> AnyDiagnostic { AnyDiagnostic::$diag(Box::new(d)) ...
Rust
0
let request = get_emote_sets::GetEmoteSetsRequest::builder() //! .emote_set_id(vec!["1234".into()]) //! .build(); //! ``` //! //! ## Response: [Emote] //! //! Send the request to receive the response with [`HelixClient::req_get()`](helix::HelixClient::req_get). //! //! ```rust, no_run //! use twitch_api2::heli...
Rust
0
_DR3_VAC_ages_v1.fits') def galahDynamicsPath(dr=3): if dr == 3 or dr == '3': return os.path.join(_GAIA_TOOLS_DATA,'galah','DR%i' % int(dr), 'GALAH_DR3_VAC_dynamics_v1.fits') def lamostPath(dr=2,cat='all'): if cat.lower() == 'all': filename= 'dr2.fits' elif cat....
Python
1
_strings(s: &str) -> bool { s.contains("ab") | s.contains("cd") | s.contains("pq") | s.contains("xy") } fn is_nice_part1(s: &str) -> bool { has_three_vowels(s) & has_repeated_char(s) & !has_illegal_strings(s) } fn solve_part1(strings: &str) -> usize { strings.lines().filter(|s| is_nice_part1(s)).count() }...
Rust
0
let keys = "GT:GQ".parse()?; /// /// assert_eq!( /// Genotype::from_str_format("0|0:13", &keys), /// Ok(Genotype::try_from(vec![ /// Field::new(Key::Genotype, Some(Value::String(String::from("0|0")))), /// Field::new(Key::ConditionalGenotypeQuality, Some(Value::Integer(1...
Rust
0
ia reference. pub fn build_mapped_parameters( param_file_path: PathBuf, checked: bool, ) -> io::Result<MappedParameters<E>> { let mut offset: usize = 0; let param_file = File::open(&param_file_path)?; let params = unsafe { MmapOptions::new().map(&param_file)? }; ...
Rust
0
import pytest from salesman.checkout.payment import PaymentMethod, payment_methods_pool def test_base_payment_method(): method = PaymentMethod() assert method.get_urls() == [] with pytest.raises(NotImplementedError): method.basket_payment(None, None) with pytest.raises(NotImplementedError): ...
Python
1
ret_opacity = customization.get_opacity() return ret_name, ret_color, ret_scale, ret_opacity def _get_icon_path(name: str) -> str: """ Get the SVG path for the icon's MDI name. """ if "mdi:" in name: name = name.replace("mdi:", const.EMPTY_STRING) return MDI_ICONS.get(name, co...
Python
1
hon program given by pyfile. Alternatively, an executable module or package to debug can be specified using the -m switch. Initial commands are read from .pdbrc files in your home directory and in the current directory, if they exist. Commands supplied with -c are executed after commands from .pdbrc files. To let th...
Python
1
`uninit` lives long enough, // so it has to be in the same scope as `$name`. That's why // `let_base_ptr` declares a variable (several, actually) // instead of returning one. let uninit = $crate::__priv::mem::MaybeUninit::<$type>::uninit(); let $name: *const $type = uninit.as_pt...
Rust
0
tile_map_dimensions = Vec2::new(1., 1.); let tile_map = TileMap::new( tile_map_dimensions, chunk_dimensions, tile_dimensions, atlas_handle, ); let tile_map_components = TileMapComponents { tile_map, transform: Default::def...
Rust
0
ap_null(); /// Tries to load [`glViewport`], returns if a non-null pointer was obtained. #[doc(hidden)] pub unsafe fn glViewport_load_with_dyn( get_proc_address: &mut dyn FnMut(*const c_char) -> *mut c_void, ) -> bool { load_dyn_name_atomic_ptr(get_proc_address, b"glViewport\0", &glViewport_p) } ///...
Rust
0
ing, } /// The Tool implementation for fetching and installing 3rd-party packages #[derive(Debug)] pub struct Package { pub(crate) name: String, pub(crate) details: PackageDetails, } impl Package { pub fn new(name: String, details: PackageDetails) -> Self { Package { name, details } } fn ...
Rust
0
# Install PyWake if needed import py_wake import numpy as np import matplotlib.pyplot as plt import random as rnd #importing the properties of Hornsrev1, which are already stored in PyWake from py_wake.examples.data.hornsrev1 import V80 from py_wake.examples.data.hornsrev1 import Hornsrev1Site from py_wake.examples.d...
Python
1
_eq!( aggs, vec![ AggregateVec::Count(vec![Some(3)]), AggregateVec::MinString(vec![Some("Orange Crush".to_owned())]), AggregateVec::MaxString(vec![Some("Stand".to_owned())]), ] ); // bytes let arr = vec![ ...
Rust
0
ode(&self) -> &crate::Reg<grxstsp_devicemode::GRXSTSP_DEVICEMODE_SPEC> { unsafe { &*(((self as *const Self) as *const u8).add(32usize) as *const crate::Reg<grxstsp_devicemode::GRXSTSP_DEVICEMODE_SPEC>) } } #[doc = "0x20 - Receive Status Read and Pop Register \\[HOSTMODE\\]"] #[inline(always)] pu...
Rust
0
ve_all_credentialsz WebDriver.remove_all_credentialsYs$ W336GI_I_5`ar)verifiedc^|jtj|j|dy)zSets whether the authenticator will simulate success or fail on user verification. ver...
Python
1
ytes(); let alpha = components[3]; let res: [u8; 4] = [ mul_div_255(components[0], alpha), mul_div_255(components[1], alpha), mul_div_255(components[2], alpha), alpha, ]; *dst_pixel = u32::from_le_bytes(res); } } #[inline(always)] pub(...
Rust
0
last_tracks_render = rendering(renderer, last_tracks, K, resolution).rgb last_tracks_render = cv2.cvtColor(last_tracks_render, cv2.COLOR_BGR2RGB) all_tracks.append(last_tracks) else: all_tracks.append({}) if last_img is not None and last_cosy...
Python
1
'cps': f"{calculate_rate(start_cemented, end_cemented, duration):.2f}", 'count_init': start_count, 'count_final': end_count, 'cemented_init': start_cemented, 'cemented_final': end_cemented } async def get_block_counts(rpc): result = await rpc.block_count() return result['...
Python
1
os]) < self.eMarks[ from_pos ]: break except IndexError: from_pos += 1 break from_pos += 1 return from_pos def skipSpaces(self, pos: int) -> int: """Skip spaces from given position.""" ...
Python
1
Some(socket) } } /// Get dialer that created the pipe. See [nng_pipe_dialer](https://nng.nanomsg.org/man/v1.2.2/nng_pipe_dialer.3). pub unsafe fn dialer(&self) -> Option<UnsafeDialer> { let dialer = UnsafeDialer::new(nng_pipe_dialer(self.pipe)); if dialer.id() == -1 { ...
Rust
0
coming_auth_token".to_string())), ilp_over_http_outgoing_token: Some(SecretString::new("outgoing_auth_token".to_string())), ilp_over_btp_url: Some("btp+ws://example.com/accounts/bob/ilp/btp".to_string()), ilp_over_btp_incoming_token: Some(SecretString::new("incoming_btp_token".to_string())), ...
Rust
0
ool = False) -> None: """Setup logging configuration.""" level = logging.DEBUG if verbose else logging.INFO # Create formatter formatter = logging.Formatter( '%(asctime)s [%(levelname)s] %(message)s', datefmt='%H:%M:%S' ) # Setup console handler with Windows-compatible encoding...
Python
1
# exception handling try: app = int(input("enter a number")) print(app) except ValueError: print("invalid input") finally: print("CLEANING ") a = [2, 13, 5, 6, 7] for i in a: print("x"*i) for j in a: output = "" for count in range(j): output += "x" print(output) max = a[0] for ...
Python
1
, create one let interval = if let Some(x) = state .intervals .iter_mut() .find(|interval| interval.name == name) { x } else if state .intervals .try_push(IntervalRecord { name, samples: Stati...
Rust
0
impl Trace for Chunk { fn trace(&self) { self.constants.iter().for_each(|constant| constant.trace()); } fn trace_debug(&self, log: &mut dyn std::io::Write) { self .constants .iter() .for_each(|constant| constant.trace_debug(log)); } } #[cfg(test)] mod test { use super::*; struct ...
Rust
0
import requests import json from datetime import datetime GRAPHQL_URL = "https://www.heb.com/graphql" HEADERS = { "Content-Type": "application/json", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36", "Accept-Language": "en-US,e...
Python
1