text
string
label_name
string
labels
int64
(all_lines) if len(all_lines) != 0 else 1 ), "source_file": source_file_name, "raw_path": file_2_changed_lines[source_file_name][ "raw_path"...
Python
1
import os from dotenv import load_dotenv from openai import AzureOpenAI def setup_clients(): """Set up and return Azure OpenAI clients and model deployment names for all models.""" load_dotenv() # GPT-4o client setup gpt4o_endpoint = os.getenv("AZURE_GPT_4o_OPENAI_ENDPOINT") gpt4o_api_key = os...
Python
1
import streamlit as st def get_best_flight_options(origin, destination): """ Retorna as melhores opções de emissão de passagens com base nos programas de milhas. """ recommendations = { # Europa ("São Paulo", "Madrid"): [ {"Cia": "Latam", "Programa": "Latam Pass", "Melhor Ro...
Python
1
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of condit...
Python
1
ys)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | ((value as u32 & 0x01) << 1); self.w } } #[doc = "Pull Enable for Port E Bit 2\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PTEPE2_A { #[doc = "0: Pullup is disabled for...
Rust
0
.is_ascii_digit() || *c == '-') .collect::<String>() .parse::<i32>() .ok() .ok_or_else(error)?; Ok(SplitResponse(token, channel, prefix, value)) } #[cfg(test)] mod tests { use super::*; #[test] fn test_split_response() { assert_eq!( split_response(b...
Rust
0
.is_empty() || !state.constants.is_empty()) && state.startup_function.is_none() { drop(state); let parsed = syn::parse2(quote! { fn php_module_startup() {} }) .map_err(|_| anyhow!("Unable to generate PHP module startup function."))?; let startup = startup...
Rust
0
Graph, SavedModelBundle, SessionOptions, SessionRunArgs, Tensor}; fn main() { //Sigmatures declared when we saved the model let train_input_parameter_input_name = "training_input"; let train_input_parameter_target_name = "training_target"; let pred_input_parameter_name = "inputs"; //Names of outpu...
Rust
0
raise NotImplementedError() elif featureJob.sp.feature_type == "sample" and featureJob.sp.sample_type == "ogbn": feature_generation.ogbn_generate_split( job, splitJob, feature_graph_name, feature_graph_files) else: raise ValueError() # @...
Python
1
import os import sys from pyspark.sql import SparkSession from pyspark.sql.functions import from_json, col, when, to_timestamp from pyspark.sql.types import ( StructType, StructField, StringType, IntegerType, TimestampType, ArrayType ) from pyspark.ml import PipelineModel from dotenv import load_dotenv def main()...
Python
1
s the task-local logger with the specified logger, returning the old /// logger. pub fn set_logger(logger: ~Logger) -> Option<~Logger> { let mut task = Local::borrow(None::<Task>); util::replace(&mut task.get().logger, Some(logger)) } <reponame>lord/tide //! HTTP cookies. mod middleware; pub(crate) use middle...
Rust
0
ionVQCausalConv3d(config.embed_dim, config.z_channels) self.spatial_scale_factor = 2 ** (len(config.ch_mult) - 1) # self.post_init() def encode(self, x: paddle.Tensor): ndim = x.ndim if ndim == 4: t = self.config.temporal_downsample_factor b, c, h, w = tuple(...
Python
1
<I>, params: &Parameters) -> ESParseResult<I, ClassBody> { ensure_params!(params; "class_body"; Parameter::Yield); class_element_list(i, params).map(ClassBody) } // ClassElementList struct ClassElementList(ClassElement, Vec<ClassElementListRest>); impl ClassElementList { fn new(rhs_val: ClassElement) -...
Rust
0
EncryptMode::EncryptWithRngKey => { // Create cipher with randomly generated key let mut rng = rand::thread_rng(); let key_rng_bytes = rng.gen::<[u8; 32]>(); let cipher = Aes256Gcm::new(Key::from_slice(&key_rng_bytes)); (Some(cipher), Some(key_rng_byt...
Rust
0
cls=common_toggle_cls)(theme_item("bg-[#ecedef]", "bg-white", "bg-[#ecedef]")), A(id="theme-toggle-dark", cls=f"{common_toggle_cls} bg-popover")(theme_item("bg-slate-950", "bg-slate-800", "bg-slate-400")), cols_max=2,cls=('max-w-md','gap-8'))), Button('Update preferences', cl...
Python
1
, f: glib_ffi::gpointer) where P: IsA<PlacesSidebar> { let f: &&(Fn(&P, &gio::File, PlacesOpenFlags) + 'static) = transmute(f); f(&PlacesSidebar::from_glib_borrow(this).downcast_unchecked(), &from_glib_borrow(location), from_glib(open_flags)) } unsafe extern "C" fn show_connect_to_server_trampoline<P>(this: *m...
Rust
0
UCHAR, s_b3: UCHAR, s_b4: UCHAR, }} STRUCT! {struct in_addr_S_un_w { s_w1: USHORT, s_w2: USHORT, }} UNION! {union in_addr_S_un { [u32; 1], S_un_b S_un_b_mut: in_addr_S_un_b, S_un_w S_un_w_mut: in_addr_S_un_w, S_addr S_addr_mut: ULONG, }} STRUCT! {struct in_addr { S_un: in_addr_S_un,...
Rust
0
compute_tm(gt_coords, pred_coords) best_lddt = compute_lddt(gt_coords, pred_coords) best_gdt_ts, best_gdt_ha = compute_gdt(gt_coords, pred_coords) return { "rmsd": float(best_rmsd), "tm": float(best_tm), "lddt": float(best_lddt), "gdt_ts": float(best_gdt_ts), "gdt_ha"...
Python
1
from store.models import Customer from djoser.serializers import UserSerializer as BaseUserSerializer, UserCreateSerializer as BaseUserCreateSerializer class UserCreateSerializer(BaseUserCreateSerializer): class Meta(BaseUserCreateSerializer.Meta): fields = ['id', 'username', 'password', ...
Python
1
import numpy as np import torch def get_human_readable_count(number: int) -> str: """Return human_readable_count Originated from: https://github.com/PyTorchLightning/pytorch-lightning/blob/master/pytorch_lightning/core/memory.py Abbreviates an integer number with K, M, B, T for thousands, millions, ...
Python
1
(|a| a.to_str()); match name { Some("elan") => elan_mode::main(), Some(n) if n.starts_with("elan-setup") || n.starts_with("elan-init") => { // NB: The above check is only for the prefix of the file // name. Browsers rename duplicates to // e.g. elan-setup(2), and...
Rust
0
ction(LookupExtraction): lookup_type = "map" def __init__(self, mapping, **kwargs): super(MapLookupExtraction, self).__init__(**kwargs) self._mapping = mapping def build_lookup(self): lookup = super(MapLookupExtraction, self).build_lookup() lookup["map"] = self._mapping ...
Python
1
s, rangs): if self.opt['final_mean'] > 1: if len(dists) < self.opt['final_mean']: return list(), list() half = self.opt['final_mean'] // 2 from scipy.ndimage import uniform_filter if len(dists[0].shape) > 0: dists = np.nanmax(dists...
Python
1
""" Line Chart with datum --------------------------------- An example of using ``datum`` to highlight certain values, including a ``DateTime`` value. This is adapted from two corresponding Vega-Lite Examples: `Highlight a Specific Value <https://vega.github.io/vega-lite/docs/datum.html#highlight-a-specific-data-value>...
Python
1
import discord from discord.ext import commands from discord import app_commands class Nickname(commands.Cog): def __init__(self, bot): self.bot = bot @app_commands.command(name="nickname", description="Changes a user's nickname.") @app_commands.describe( member="The user whose nickname to...
Python
1
ftmart::update_token_royalty_beneficiary( Origin::signed(BOB), CLASS_ID, TOKEN_ID, ALICE )); assert_ok!(Nftmart::update_token_royalty_beneficiary( Origin::signed(ALICE), CLASS_ID, TOKEN_ID, BOB )); }); } #[test] fn create_class_should_work() { ExtBuilder::default().build().execute_with(...
Rust
0
i] + max_t[which_plane] * dir[i]; if coord[i] < bound.min[i] || coord[i] > bound.max[i] { return None; } } else { coord[i] = candidate_plane[i]; } } Some(coord) } pub fn trace_ray<F, R>(world: &world::World, max: f64, s: cgmath::Vector3<f64>, ...
Rust
0
"""The LCSCBarcodePlugin is meant to integrate the LCSC API into InvenTree. This plugin can currently only match LCSC barcodes to supplier parts. """ import re from django.utils.translation import gettext_lazy as _ from plugin import InvenTreePlugin from plugin.mixins import SettingsMixin, SupplierBarcodeMixin cl...
Python
1
fashion. Fields: item: A WrrPolicyItem attribute. """ item = _messages.MessageField('WrrPolicyItem', 1, repeated=True) class WrrPolicyItem(_messages.Message): r"""A routing block which contains the routing information for one WRR item. Fields: healthCheckedTargets: Endpoints that are health ch...
Python
1
nums = [12,34,65,42,65,12,79,97,75,23,90,99,10,18] n = int(input("Enter a num you want to find: ")) i = 0 while i <= len(nums) : if(nums[i] == n ): print("Found at index" , i) break else: print("Finding........") i+=1 print("End of the Program")
Python
1
, ref a2, ref b2)| { mult_add::<Dist, Mult>(r, a1, b1, s, frag); mult_add::<Dist, Mult>(r, a2, b2, s, frag); }); } } mult_add::<Dist, Mult>(&mut result.content, &a.content, &b.content, a.size, Frag::USIZE); result } macro_rules! op { ($res: expr => $...
Rust
0
() as u32; } (sum & 0xff) == 0 } /// Per-CPU state #[repr(C)] pub(crate) struct CpuInfo { pub(crate) cpu_id: u8, cpu_status: CpuStatus, cpu_env: *mut Env, cpu_ts: TaskState, } impl CpuInfo { const fn empty() -> CpuInfo { CpuInfo { cpu_id: 0, cpu_status: Cpu...
Rust
0
l::ml::DirectLookup::new( self.class_labels.clone(), Tensor::zero_dt(self.class_labels.datum_type(), &[])?.into_arc_tensor(), )?, &casted, )?[0]; Ok(tvec!(labels, scores[0])) } fn nboutputs(&self) -> TractResult<usize> { Ok(2) ...
Rust
0
def point_sample_fine_grained_features(features_list, feature_scales, boxes, point_coords): """ Get features from feature maps in `features_list` that correspond to specific point coordinates inside each bounding box from `boxes`. Args: features_list (list[Tensor]): A list of feature ma...
Python
1
_free(RAX) { None } else { dynasm!(self.asm ; push rax ); self.block_state.depth.reserve(1); // DON'T FREE THIS REGISTER HERE - since we don't // remove it from the stack freeing the register // here will cause `...
Rust
0
if let Some(min_difficulty_gap) = NetworkUpgrade::minimum_difficulty_spacing_for_height(network, block_height) { block_time_gap > min_difficulty_gap } else { false } } /// Returns the averaging window timespan for the network upgrade. /// ...
Rust
0
turned by the given function, which is passed the raw asyncio driver connection. This is used to invoke awaitable-only methods on the driver connection within the context of a "synchronous" method, like a connection pool event handler. E.g.:: engine = create_async_...
Python
1
bail!(v, "may not be used on enums with variants with multiple fields"); } match &v.fields { Fields::Unnamed(f) => { field_types.push(f.unnamed.iter().next().unwrap().ty.clone()); Ok(field_types) ...
Rust
0
#!/usr/bin/env python3 # Copyright 2012-2023, Andrey Kislyuk and argcomplete contributors. # Licensed under the Apache License. See https://github.com/kislyuk/argcomplete for more info. """ This script is part of the Python argcomplete package (https://github.com/kislyuk/argcomplete). It is used to check if an EASY-I...
Python
1
self.service .battery_level_notify(&c, analog.battery) .unwrap(); } if self.notifications.button_a { self.service.button_a_notify(&c, button_a_presses)....
Rust
0
r_on_lan(8000).await; match &orchestrator_ip { Some(ip) => { info!("Orchestrator detected at {}", ip); } None => { error!("No orchestrator on port 8000 detected on this LAN"); } }; Ok(()) } //! ABY pub mod assignment; pub mod trans; pub mod utils; //...
Rust
0
ld process `bash` to execute `{command}`")] pub struct BashSpawnError { command: String, #[source] source: anyhow::Error, } impl BashSpawnError { pub fn new<SourceError>(command: impl Into<String>, source: SourceError) -> Self where SourceError: std::error::Error + Sync + Send + 'static, ...
Rust
0
fn test_geocentric_longitude() { let l_deg = 90.; assert_eq!(270., spa::geocentric_longitude(&l_deg)); let l_deg = 350.; assert_eq!(170.00000000000003, spa::geocentric_longitude(&l_deg)); } #[test] fn test_geocentric_latitude() { let b_deg = 90.; assert_e...
Rust
0
""" logger package """ from GHEtool.logger.ghe_logger import ghe_logger
Python
1
pallets/refresh-seeds/src/tests.rs<gh_stars>1-10 // Copyright 2021 ZeroDAO // // 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 // // Unles...
Rust
0
accountbool == 'update': update_account(cluster, headers_inc) if accountbool == 'delete': delete_account(cluster, headers_inc) def main() -> None: """Main function""" arguments = [ Argument("-c", "--cluster", "API server IP:port details")] args = parse_args( "Demonstr...
Python
1
niform_data; mod nalgebra_vertex_data; //! A map based on a patricia tree. use crate::node::Node; use crate::tree::{self, PatriciaTree}; use std::fmt; use std::iter::FromIterator; /// A map based on a patricia tree. #[derive(Clone)] pub struct PatriciaMap<V> { tree: PatriciaTree<V>, } impl<V> PatriciaMap<V> { ...
Rust
0
# Binary Analysis Next Generation (BANG!) # # This file is part of BANG. # # This program 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 License, or # (at your option) any later versio...
Python
1
uilder; use clap::Parser; #[derive(Parser)] struct Opts { file: PathBuf, } fn main() { let opts = Opts::parse(); let cwd = std::env::current_dir().unwrap(); std::env::set_current_dir(opts.file).unwrap(); let data_builder = CookerDataBuilder::new(); data_builder.parse_base_configuration().unw...
Rust
0
ec<u8>> for ContractCode { type Target = Vec<u8>; const COL: usize = super::db::COL_CONTRACT_CODE; fn key(&self) -> Self::Target { self.0.as_bytes().to_vec() } fn value(val: &Vec<u8>) -> Cow<[u8]> { Cow::Borrowed(val) } fn parse_value(raw: &[u8]) -> Vec<u8> { raw.t...
Rust
0
= cat_boxes([gt_bboxes_, priors], dim=0) assign_result.add_gt_(gt_labels) gt_ones = priors.new_ones(gt_bboxes_.shape[0], dtype=torch.uint8) gt_flags = torch.cat([gt_ones, gt_flags]) num_expected_pos = int(self.num * self.pos_fraction) pos_inds = self.pos_sampler._sam...
Python
1
f"Python路径: {sys.executable}") # 选择评估方法 evaluation_method = select_evaluation_method(task) add_evaluation_log(task_id, f"选择的评估方法: {evaluation_method}") # 确保数据集已下载 add_evaluation_log(task_id, f"检查{evaluation_method}数据集...") success, message = download_da...
Python
1
let lookups = inner.lookups.into_iter() .map(SubstLookup::parse) .collect(); Self { inner, lookups} } } #[derive(Clone)] pub struct SubstLookup<'a> { pub subtables: Vec<SubstitutionSubtable<'a>>, pub coverage: GlyphSet, pub reverse: bool, pub props: u32, } impl<...
Rust
0
import pytest pytest.importorskip("jax") def test_imports(): from rockpool.nn.modules import SoftmaxJax, LogSoftmaxJax def test_SoftmaxJax(): from rockpool.nn.modules import SoftmaxJax import numpy as np import jax import jax.numpy as jnp Nin = 3 Nout = 5 T = 10 # - Test modu...
Python
1
if "additionalProperties" in input_schema: result.extend( _extract_properties_keys( input_schema["additionalProperties"], prefix, ) ) # If dictionary has "items" key: recurse into it if "items" in input_schema: result.extend( ...
Python
1
ame>zhenkyle/lpc11xx #[doc = "Reader of register GPREG4"] pub type R = crate::R<u32, super::GPREG4>; #[doc = "Writer for register GPREG4"] pub type W = crate::W<u32, super::GPREG4>; #[doc = "Register GPREG4 `reset()`'s with value 0"] impl crate::ResetValue for super::GPREG4 { type Type = u32; #[inline(always)] ...
Rust
0
-721 respecting smart contracts. #[ink::trait_definition] pub trait IErc721 { /// Creates a new ERC-721 token contract. #[ink(constructor)] fn new() -> Self; /// Returns the balance of the owner. /// /// This represents the amount of unique tokens the owner has. ...
Rust
0
data) } pub fn debug_wabt_validate_ffi(data: &[u8]) -> bool { wabt_ffi::fuzz_wabt_validate_ffi(&data) } pub fn debug_wabt_wat2wasm_ffi(data: &[u8]) -> bool { wabt_ffi::fuzz_wabt_wat2wasm_ffi(&data) } mod wasm3; pub fn fuzz_wasm3_parser_ffi(data: &[u8]) { let _ = wasm3::fuzz_wasm3_parser_ffi(&data); } pub f...
Rust
0
Module<T: Trait> as Test { NoDefault: Option<NoDef>; JustVec: Vec<u32>; JustVecWithDefault: Vec<u32> = vec![6, 9]; OptionVec: Option<Vec<u32>>; MapVec: map hasher(blake2_128_concat) u32 => Vec<u32>; MapVecWithDefault: map hasher(blake2_128_concat) u32 => Vec<u32> = vec![6, 9]; OptionMapVec: map ...
Rust
0
match self.inner.next()? { Ok(e) => self.current = Some((self.f)(e).into_iter()), Err(error) => return Some(Err(error)), } } } } trait Accumulator<I: StrId> { fn add(&mut self, element: Option<EncodedTerm<I>>); fn state(&self) -> Option<EncodedTe...
Rust
0
MATERIAL CRÍTICO', width='small'), 'pde_description': st.column_config.Column('PDE DESCRIPCIÓN', width='small'), 'pde_actualizado': st.column_config.DatetimeColumn('PDE ACTUALIZACIÓN', format="YYYY-MM-DD", width='small'), 'pde_usuario': st.column_config.Column('PDE USUARI...
Python
1
Some(msg) => FutureResult::RtmpWatchNotificationReceived(stream_id, msg, receiver), None => FutureResult::RtmpWatchChannelGone(stream_id), }; Box::new(result) } async fn wait_for_publish_notification( stream_id: StreamId, mut receiver: UnboundedReceiver<RtmpEndpointPublisherMessage>, )...
Rust
0
])); // define data. let batch1 = RecordBatch::try_new( schema1.clone(), vec![ Arc::new(StringArray::from(vec!["a", "b", "c", "d"])), Arc::new(Int32Array::from(vec![1, 10, 10, 100])), ], )?; // define data. let batch2 = RecordBatch::try_new( ...
Rust
0
tx, graphics::DrawMode::Fill, graphics::Rect::new( pos.x * ::GLOBAL_SCALE, pos.y * ::GLOBAL_SCALE, size.x * ::GLOBAL_SCALE, size.y * ::GLOBAL_SCALE, ), )?; graphics::set_color(ctx, graphics::Color::new(1.0, 1.0, 1.0, 1.0))?; Ok(()) } ...
Rust
0
Sync, RigidBodyType, }, }; use clap::{arg_enum, value_t}; use rand::Rng; // Take a look at example_utils/utils.rs for details! #[path = "../example_utils/utils.rs"] mod utils; use utils::*; arg_enum! { #[derive(PartialEq, Debug)] pub enum ControllerType { DynamicImpulse, DynamicForce, ...
Rust
0
s = Rect::from((PathComponent::Move(PathPoint::new(30.0, 30.0)), PathComponent::Line(PathPoint::new(60.0, 20.0)))); assert!(bounds.x1 == 30.0); assert!(bounds.y1 == 20.0); assert!(bounds.x2 == 60.0); assert!(bounds.y2 == 30.0); } #[test] fn can_get_bounding_box_for_line_pat...
Rust
0
missing_format() { let mut cmd = Command::cargo_bin("opml").unwrap(); let assert = cmd.args(&["--file", SAMPLE]).assert(); assert .failure() .code(1) .stderr(read_to_string("tests/snapshots/missing-format.txt").unwrap()); } <filename>pallets/liquidity-mining/src/tests/test_ext.rs // This file is part...
Rust
0
r.reset() # Check for detected warning #if not warning_flag and detector.warning: # print(f"Warning detected at step {i}") # warning_flag = True false_alarm_rate = (false_alarms / (first_point-len(train))) if detected_drifts else 0 ...
Python
1
der>(&self, r: R) -> anyhow::Result<()> { let prepared = self.session.prepare(r.render()).await?; self.session.execute(&prepared, ()).await?; Ok(()) } pub async fn prepare_execute<A>( &mut self, statement: String, items: Vec<A>, ) -> anyhow::Result<()> wh...
Rust
0
current += self.speed * dt; } fn get(&self) -> Frame { self.frames[self.current as usize % self.frames.len()] } } /* * Midgard Public API * * The Midgard Public API queries THORChain and any chains linked via the Bifröst and prepares information about the network to be readily available for publ...
Rust
0
reference = db.query(UserLLMPreference).filter( UserLLMPreference.user_id == current_user.id ).first() if period == "daily": token_limit = preference.daily_token_quota if preference else 50000 cost_limit = preference.monthly_cost_limit / 30 if preference else...
Python
1
init_start = init_shard_idx_start * init_nshard s = max(start - init_start, 0) if len(init_weight.shape) == 2: new_weight = init_weight[:, s:] else: new_weight = init_weight[s:] e = end - (init_shard_...
Python
1
ree.iter(), prev: None, done: false, } } } impl<K: fmt::Debug, V: fmt::Debug, C: Slab<Node<AnyRange<K>, V>>> fmt::Debug for RangeMap<K, V, C> where for<'r> C::ItemRef<'r>: Into<&'r Node<AnyRange<K>, V>>, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{{")?; for (range, value) in se...
Rust
0
# define enumerations using the Enum base class from enum import Enum, unique, auto @unique class Fruit(Enum): APPLE = 1 BANANA = 2 ORANGE = 3 TOMATO = 4 PEAR = auto() def main(): pass # TODO: enums have human-readable values and types print(Fruit.APPLE) print(type(Fruit.APPLE)) ...
Python
1
P::Point: Debug + Send + Sync + 'static, <P::Point as EuclideanSpace>::Scalar: Send + Sync + 'static, <P::Point as EuclideanSpace>::Diff: Debug + Send + Sync + 'static, T: Component + Transform<P::Point> + Send + Sync + Clone + 'static, Y: Default + Send + Sync + 'static, B: Bound<Point = P::Po...
Rust
0
\left(\sum_{\lambda_k > 0} 1, \sum_{\lambda_k > 0.}1 - \sum_{\lambda_k < 0.} 1\right) A system is degenerate if it has a zero eigenvalue and consequently, it's critical point is said to be "catastrophe". It returns a warning in this case. """ if np.any(np.abs(self.eigenvalues) < sel...
Python
1
se std::rc::Rc; pub const A0: [f64; 7] = [ 0.91056314451539, 0.63612814494991, 2.68613478913903, -26.5473624914884, 97.7592087835073, -159.591540865600, 91.2977740839123, ]; pub const A1: [f64; 7] = [ -0.30840169182720, 0.18605311591713, -2.50300472586548, 21.4197936296668, ...
Rust
0
txid_be, ChannelStatus::PendingOpen); assert!(rc.is_ok()); let rc = mpc::customer_mark_open_channel(&mut cust_state); assert!(rc.is_ok()); let rc = mpc::merchant_mark_open_channel(channel_token.escrow_txid.0.clone(), &mut merch_state); assert!(rc.is_ok()); ...
Rust
0
"""Configures pytest for all tests, providing various fixtures""" from unittest.mock import patch from aiohttp import ClientSession import pytest from pytest_httpserver import HTTPServer from tests.core_test_object import CoreTestObject from tests.test_data import CONFIG_RETURN_VALUE from tests.test_data import LOGIN...
Python
1
filtered( TeeReader::new(&mut input, tempfile.as_mut().unwrap()), &filter, ) .context("reading/copying input initrd")?, }; if base_initrd.get(INITRD_LIVE_STAMP_PATH).is_none() { bail!("not a CoreOS live initramfs image"); } if base_initrd.get(INITRD_IGNITI...
Rust
0
import socket from .utils import set_ttl from .log import logger from . import remote from .config import config import time import threading # 实现lock,使得最多同时运行k个 transmitfile_semaphore = threading.Semaphore(config["TransmitFile_Limit"]) logger = logger.getChild("fake_desync") try: import platform system = pl...
Python
1
source(&full_route, |r| r.f(listing::file_handler)) } } // Copyright (c) 2017, <NAME> <<EMAIL>> // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies...
Rust
0
import pandas as pd def load_test_data_from_csv(file_path): df = pd.read_csv(f"test_data/{file_path}") return [tuple(row) for row in df.itertuples(index=False, name=None)], df.columns.tolist()
Python
1
#!/usr/bin/env python # # ----------------------------------------------------- # Exploit id: FSE:016 # # Author: Federico Fazzi # Contact: federico@autistici.org # Date: 09/06/2006, 13:58 # Sinthesis: 0verkill 0.16, Remote integer overflow # Product: http://artax.karlin.mff.cuni.cz/~brain/0verkill/ # --...
Python
1
e Error = VarIntBoundsExceeded; /// Succeeds iff `x` < 2^62 fn try_from(x: u128) -> Result<Self, VarIntBoundsExceeded> { VarInt::from_u64(x.try_into().map_err(|_| VarIntBoundsExceeded)?) } } impl std::convert::TryFrom<usize> for VarInt { type Error = VarIntBoundsExceeded; /// Succeeds iff `...
Rust
0
arsho_config_file_path, "r", encoding="utf-8") as f: old_config = yaml_2.load(f) with StringIO(dump_config_to_yaml(ConfigModel())) as f2: new_config = yaml_2.load(f2) merged_config = merge_configs(old_config, new_config) with open(destination_file, ...
Python
1
number is multiplied with. /// *`variance` - The standard deviation of the normal distribution the random number is drawn from. /// /// # Example /// ``` /// use roqoqo::prelude::*; /// use roqoqo::operations::RotateZ; /// /// let gate = RotateZ::new(0, 1.0.into()); /// let overrota...
Rust
0
pretrained=self.configer.get('network', 'pretrained'), network="dcnet") return model def deepbase_dcn_resnet101(self, **kwargs): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-t...
Python
1
fn part1(&self) -> String { bfs( self.start_pos, self.end_pos, &self.passage, &self.teleports, 0, ) .to_string() } fn part2(&self) -> String { bfs( self.start_pos, self.end_pos, &self...
Rust
0
&work_item]).unwrap(); // Notify list item that it needs to update as well ctx.submit_command(ITEM_CHANGED.with(data.id).to(ITEM_LIST_WIDGET_ID)); ctx.request_update(); }), )) } fn build_detail_view_title() -> impl Widget<UiWorkItem>...
Rust
0
print(f" Z轴: {base_ang_vel[2]:+8.4f}") print(f" 模长: {np.linalg.norm(base_ang_vel):8.4f}") print() # 显示投影重力 print("🌍 投影重力向量 (projected_gravity):") print(f" X轴: {projected_gravity[0]:+8.4f}") print(f" Y轴: {projected_gravity[1]:+8.4f}") print(f" ...
Python
1
@REMOVELAST $( [$first_index:tt AND $first_type_parameter:ident], )+ @SEPARATOR [$index:tt AND $type_parameter:ident], $( [$nth_index:tt AND $nth_type_parameter:ident], )+ ) => { impl_axes!(@REMOVELAST $([$first_index AND $first_type_parameter],)* [$index AND $type_parameter], @SEPARATOR $([$nth_index AND $nth_...
Rust
0
# coding: utf-8 # Copyright (C) 2022, [Breezedeus](https://github.com/breezedeus). # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this f...
Python
1
import mysql.connector def get_mysql_connection(): connection = mysql.connector.connect( host="localhost", user="root", password="", database="youtube_project", ssl_disabled=True ) return connection # def get_mysql_connection(): # connection = mysql.connector.co...
Python
1
(&mut out, "CreateDBInstance", "2014-10-31"); #[allow(unused_mut)] let mut scope_263 = writer.prefix("DBName"); if let Some(var_264) = &input.db_name { scope_263.string(var_264); } #[allow(unused_mut)] let mut scope_265 = writer.prefix("DBInstanceIdentifier"); if let Some(var_266) = ...
Rust
0
", e))?; Ok(()) } /// The included mutable vec is the data that is going to be mutated. This should be /// the entire file data of the compiled file. After writing to this vec, you can /// save it out to a file pub fn write_to_included_section( included: &mut Vec<u8>, mut write_data: Vec<DataToWrite>, ) ->...
Rust
0
oader(val_dataset, batch_size=batch_size, shuffle=False, num_workers=nw, pin_memory=True, ...
Python
1
we just store the bytes with the decoded data? // the decoded data is useful for queries, the encoded data is needed for transfers, signing // and ordering. self.to_bytes().cmp(&other.to_bytes()) } } #[cfg(test)] mod tests { use std::net::Ipv4Addr; use std::net::Ipv6Addr; use ...
Rust
0
import json import os def convert_jsonl_for_pyserini(input_file, output_file): """Convert JSONL data to Pyserini-compatible format with a structured 'contents' field""" docs = [] with open(input_file, "r", encoding="utf-8") as f: for line in f: data = json.loads(line.strip()) ...
Python
1
>10-100 mod cli; mod config; mod exec; mod mask; use std::io::Read; use anyhow::*; use exec::CommandExecExt; use serde::Serialize; #[derive(Serialize)] struct KeyValue<'a> { key: &'a str, value: &'a str, } impl<'a, K, V> From<&'a (K, V)> for KeyValue<'a> where K: AsRef<str>, V: AsRef<str>, { fn ...
Rust
0