text string | label_name string | labels int64 |
|---|---|---|
LibRaw_decoder_flags = 128;
pub const LibRaw_decoder_flags_LIBRAW_DECODER_FIXEDMAXC: LibRaw_decoder_flags = 256;
pub const LibRaw_decoder_flags_LIBRAW_DECODER_ADOBECOPYPIXEL: LibRaw_decoder_flags = 512;
pub const LibRaw_decoder_flags_LIBRAW_DECODER_LEGACY_WITH_MARGINS: LibRaw_decoder_flags = 1024;
pub const LibRaw_dec... | Rust | 0 |
from ops.data import OpsClass, OpsField, DszObject, DszCommandObject, cmd_definitions
import dsz
if ('portmap' not in cmd_definitions):
dszportmap = OpsClass('process', {'id': OpsField('id', dsz.TYPE_INT), 'name': OpsField('name', dsz.TYPE_STRING), 'port': OpsClass('port', {'sourceport': OpsField('sourceport', dsz... | Python | 1 |
#[inline(always)]
pub fn hcdma_buffermode_mut(&self) -> &mut HCDMA_BUFFERMODE {
unsafe { &mut *(((self as *const Self) as *mut u8).add(20usize) as *mut HCDMA_BUFFERMODE) }
}
}
#[doc = "Host Channel Characteristics Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::ge... | Rust | 0 |
nd buffers to submit.
pub command_buffers: Ic,
/// Semaphores to wait being signalled before submission.
pub wait_semaphores: Iw,
/// Semaphores to signal after all command buffers in the submission have finished execution.
pub signal_semaphores: Is,
}
/// Abstraction for an internal GPU execution ... | Rust | 0 |
sigma * &sigma * &sigma * &epsilon_k)
* 1e-19
* (JOULE / KELVIN / KB).into_value().unwrap();
let q2 = &q * &q / (&m * &sigma.mapv(|s| s.powi(5)) * &epsilon_k)
* 1e-19
* (JOULE / KELVIN / KB).into_value().unwrap();
let dipole_comp: Array1<usize> = mu2
... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
.. codeauthor:: Kevin A.G. Smet (ksmet1977 at gmail.com)
"""
import numpy as np
from pathlib import Path
from itertools import islice
space = ' '
branch = '│ '
tee = '├── '
last = '└── '
def tree(dir_path: Path, level: int=-1, limit_to_directories: bool=False,
length_li... | Python | 1 |
Arc::new(Hle::new())
}
fn do_stuff_with_value(value: &Self::TestType, times: usize) {
let borrowed = &*value;
for _ in 0..times {
let _ = borrowed.lock();
// do nothing
}
}
}
fn main() {
let phantom: PhantomData<MyTestCase> = PhantomData;
Crite... | Rust | 0 |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import astropy.units as u
from gammapy.astro.darkmatter import (
DarkMatterAnnihilationSpectralModel,
DarkMatterDecaySpectralModel,
JFactory,
profiles,
)
from gammapy.maps import WcsGeom
from gammapy.utils.testing import asser... | Python | 1 |
# -*- coding: utf-8 -*- #
# Copyright 2021 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 |
_str(),
}
}
}
impl fmt::Display for MediaType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl std::str::FromStr for MediaType {
type Err = HeaderParseError;
fn from_str(s: &str) -> Result<Self, HeaderParseError> {
match s {
... | Rust | 0 |
LineEdit.setPlaceholderText(_translate("MainWindow", "请输入检测编号"))
self.label_9.setText(_translate("MainWindow", "结束:"))
self.label_3.setText(_translate("MainWindow", "开始:"))
item = self.qTableWidget_1.verticalHeaderItem(0)
item.setText(_translate("MainWindow", "新建行"))
item = self.... | Python | 1 |
# SPDX-FileCopyrightText: 2023 Martin Stephens
#
# SPDX-License-Identifier: MIT
"""Makes a debug message function available to all modules."""
try:
from typing import TYPE_CHECKING, Union
if TYPE_CHECKING:
from adafruit_wiznet5k.adafruit_wiznet5k import WIZNET5K
except ImportError:
pass
import g... | Python | 1 |
from datetime import datetime
from unittest.mock import Mock
from together.types.chat_completions import ChatCompletionChunk as TogetherChatCompletionChunk
from any_llm.providers.together.utils import _create_openai_chunk_from_together_chunk
from any_llm.types.completion import ChatCompletionChunk
def test_create_o... | Python | 1 |
der_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
loc: Optional[torch.FloatTensor] = None
scale: Optional[torch.FloatTensor] = None
static_features: Optional[torch.FloatTensor] = None
@dataclass
class SampleTSPredictionOutput(Mod... | Python | 1 |
),
Constraint::Percentage(50),
Constraint::Percentage(30),
Constraint::Percentage(70),
]
.as_ref(),
)
.split(t.size());
//parent pane
let parent_ls = Command::new("ls").arg("..").output(... | Rust | 0 |
ig.rs
//! Settings for tweaking completion.
//!
//! The fun thing here is `SnippetCap` -- this type can only be created in this
//! module, and we use to statically check that we only produce snippet
//! completions if we are allowed to.
use ide_db::helpers::{insert_use::InsertUseConfig, SnippetCap};
#[derive(Clone, ... | Rust | 0 |
Parameters {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.basis)
}
}
static PARAMETERS: [Parameters; 4] = [
Parameters { basis: "a b c" },
Parameters {
basis: "a b c d e f g h",
},
Parameters {
basis: "a b ccccccccccccccccccccccccccccccccc... | Rust | 0 |
16,
}
impl Default for Type {
fn default() -> Self {
Type::UNKNOWN
}
}
impl From<i32> for Type {
fn from(i: i32) -> Self {
match i {
0 => Type::UNKNOWN,
1 => Type::RLMT_AS,
2 => Type::RLMT_CORE,
3 => Type::RLMT_CPU,
4 => Type::RL... | Rust | 0 |
shared::Shared;
use scene_graph::{Entity, Component, ComponentManager, Id};
use geometry::Geometry;
use material::Material;
use mesh_manager::MeshManager;
struct MeshData {
entity: Option<Entity>,
geometry: Geometry,
material: Material,
}
#[derive(Clone)]
pub struct Mesh {
data: Shared<MeshData>,
... | Rust | 0 |
bounded.value()
}
}
};
}
impl_from_bounded_for_internal_value! { i8 }
impl_from_bounded_for_internal_value! { i16 }
impl_from_bounded_for_internal_value! { i32 }
impl_from_bounded_for_internal_value! { i64 }
impl_from_bounded_for_internal_value! { isize }
impl_from_bounded_for_i... | Rust | 0 |
ner_name}]: {line}")
except kr8s.ServerError as e:
logs_container.add_stdout(f"[{container_name}]: Log streaming ended: {e}")
except Exception as e:
logs_container.add_stdout(f"[{container_name}]: Unexpected error during streaming: ... | Python | 1 |
# The asyncio module in Python is designed to handle asynchronous programming.
# allowing you to run tasks concurrently without needing multiple threads or processes.
# It is particularly well-suited for I/O-bound tasks like web scraping, network operations, or reading/writing files.
# Key Concepts of asyncio:
... | Python | 1 |
import os
import argparse
import numpy as np
import optas
from optas.visualize import Visualizer
from utils_viz import (
get_urdf_path,
convert_aligned_to_gripper_pose,
)
def show_frame(vis, RT, alpha: float = 1.0, line_width: float = 1.0):
origin = RT[:3, 3]
frame = np.eye(3)
frame_new = RT[:3,... | Python | 1 |
"""SCons.Tool.mwld
Tool-specific initialization for the Metrowerks CodeWarrior linker.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2... | Python | 1 |
vec![]));
let result = test_interpret(plan, ());
assert_eq!(Err("No alternatives to interpret further".into()), result);
}
#[test]
fn test_alternatives_plan_single_alternative() {
let plan = AlternativeInterpretationsPlan::new(sym!("Test"),
vec![Box::new(StepResult::re... | Rust | 0 |
tion(status_code=401, detail="Invalid or expired access token.")
else:
# Other AWS service errors
logging.error(f"ClientError in delete_user: {e}")
raise HTTPException(status_code=400, detail=f"Failed to delete user account: {error_code}")
except BotoCoreError as e:
... | Python | 1 |
"""
Tiny ImageNet: Loss Functions
"""
import tensorflow as tf
def softmax_ce_loss(logits, labels):
"""Softmax + cross-entropy loss
Args:
logits: logits (N, C) C = number of classes
labels: tf.uint8 labels {0 .. 199}
Returns:
losses: mean cross entropy loss
"""
labels = tf.cast(labels, tf.int3... | Python | 1 |
# -*- coding: utf-8 -*-
#
# This file is part of Flask-CeleryExt
# Copyright (C) 2015 CERN.
# Copyright (C) 2022 Graz University of Technology.
#
# Flask-CeleryExt is free software; you can redistribute it and/or modify it
# under the terms of the Revised BSD License; see LICENSE file for more
# details.
"""Flask exte... | Python | 1 |
mestamp::duration_to_seconds(self.started_at.elapsed());
self.metrics
.load_log_prefix_duration_seconds
.observe(elapsed);
return Ok(Async::Ready(None));
}
Phase::A(Some(index)) => {
... | Rust | 0 |
progress_str = "[{0}{1}]\nProgress: {2}%\n".format(
"".join(["█" for i in range(math.floor(percentage / 5))]),
"".join(["░" for i in range(20 - math.floor(percentage / 5))]),
round(percentage, 2),
)
current_message = (
f"Upload... | Python | 1 |
ions, N=5):
"""Если кол-во рекоммендаций < N, то дополняем их топ-популярными"""
if len(recommendations) < N:
recommendations.extend(self.overall_top_purchases[:N])
recommendations = recommendations[:N]
return recommendations
def _get_recommendations(self, user, mo... | Python | 1 |
from . import project_budget_project_type
from . import project_budget_acceptance_flow
from . import project_budget_cash_flow
from . import project_budget_cost_flow
from . import project_budget_project
from . import project_budget_technological_direction
from . import project_budget_project_member
from . import project... | Python | 1 |
e::ffi::c_void;
pub type TensorUInt32Bit = *mut ::core::ffi::c_void;
pub type TensorUInt64Bit = *mut ::core::ffi::c_void;
pub type TensorUInt8Bit = *mut ::core::ffi::c_void;
use walle_core::app::StandardOneBot;
use walle_core::config::AppConfig;
use walle_core::DefaultHandler;
#[tokio::main]
async fn main() {
trac... | Rust | 0 |
elif div.div:
abstract = div.div.text.strip()
else:
abstract = div.text.strip()
else:
if div.h3:
title = div.h3.text.s... | Python | 1 |
is not None:
vocoder_conf.update(model.feats_extract.get_parameters())
if (
"n_fft" in vocoder_conf
and "n_shift" in vocoder_conf
and "fs" in vocoder_conf
):
return Spectrogram2Waveform(**vocoder_conf)
el... | Python | 1 |
t_serialize(IntValue::from_bigint(&[0xFF, 0xFF]), &[0xFF]);
assert_serialize(IntValue::from_bigint(&[0x00, 0xFF]), &[0x00, 0xFF]);
}
// TODO: update tests
/*
#[test]
fn test_64() {
assert_eq!(Int::from(5u64).get_i64(), Some(5));
assert_eq!(Int::from(5i64).get_i64(), Some(5));
assert_eq!(Int::from(5u16).get_i64(),... | Rust | 0 |
color: CDF,
strength: f32,
angular_diameter: f32,
sun_direction: Vec3,
},
}
impl EnvironmentMap {
// pub const fn new(color: SPD, strength: f32) -> Self {
// EnvironmentMap { color, strength }
// }
// currently unused
// sample the spectral distribution at a env... | Rust | 0 |
import pytest
from datasets import DatasetDict # type: ignore
from pathlib import Path
from artifex.core import ValidationError
from artifex.models.classification_model import ClassificationModel
@pytest.mark.unit
@pytest.mark.parametrize(
"synthetic_dataset_path",
[ (1,) ] # wrong type, should be a string
)... | Python | 1 |
import os
from langchain.llms.bedrock import Bedrock
from langchain.prompts import PromptTemplate
def get_llm():
model_kwargs = { #AI21
"maxTokens": 1024,
"temperature": 0,
"topP": 0.5,
"stopSequences": [],
"countPenalty": {"scale": 0 },
"presencePenalty":... | Python | 1 |
isk_final_agreement = sum(1 for ra, fa in zip(metrics['risk_actions'], metrics['final_actions']) if ra == fa)
risk_final_rate = risk_final_agreement / len(metrics['final_actions']) * 100
return_final_agreement = sum(1 for rta, fa in zip(metrics['return_actions'], metrics['final_actions']) if rta == fa)
... | Python | 1 |
project_data_scorer= {
"founder": {
"prior_web3_experience": "Senior role in successful Web3 project",
"technical_expertise": "Strong technical team with Rust/Solana experience",
"team_completeness": "Full team covering tech, product, business, community",
},
"github": {
"tec... | Python | 1 |
aliased access
events.
The `BitAccess` trait provides capabilities to access bits in memory elements
through shared references, and its implementations are responsible for
coördinating synchronization and contention as needed.
!*/
use crate::{
index::{
BitIdx,
BitMask,
BitRegister,
},
order::BitOrder,
};
us... | Rust | 0 |
Zero-sized type used to mark things that "act like" they own a `T`.
///
/// Adding a `PhantomData<T>` field to your type tells the compiler that your
/// type acts as though it stores a value of type `T`, even though it doesn't
/// really. This information is used when computing certain safety properties.
///
/// For ... | Rust | 0 |
f"../../logs/pickup_temporal/{model_name}/{combination_name}/seed{seed}/mode_{mode}/normal/trajectory.pkl"
agent_id = 0
label_encoder = sklearn.preprocessing.LabelEncoder()
# Load log data
data = load_trajectory(log_file_path)
messages, attributes_dict = extract_message(data)
label_dict = extra... | Python | 1 |
B: Format<Chan = H>,
Self::Chan: From<H>,
H: Channel,
H: From<Self::Chan>;
/// Blend pixel on top of another, using "over".
fn over<B, H>(dst: Self, src: B) -> Self
where
B: Format<Chan = H>,
Self::Chan: From<H>,
H: Channel,
H: From<Self::Cha... | Rust | 0 |
rn "C" fn init(render_quantum_samples: i32, mode: i32) -> *mut Bitcrusher {
Box::into_raw(Box::new(Bitcrusher::new(
render_quantum_samples as usize,
CrushMode::from_i32(mode),
)))
}
#[no_mangle]
pub unsafe extern "C" fn process_quantum(
me: *mut Bitcrusher,
input_length: usize,
bit_depth_length: usize,
) -> *... | Rust | 0 |
// Increment the value read from storage; will error in the event of overflow.
let new = old.checked_add(1).ok_or(Error::<T>::StorageOverflow)?;
// Update the value in storage with the incremented result.
<Something<T>>::put(new);
Ok(())
},
}
}
}
}
pub mod constants;
pub mod entry_po... | Rust | 0 |
#
# Apapted from code in LALSimInpspiralTaylorF2.c
#
# Copyright (C) 2007 Jolien Creighton, B.S. Sathyaprakash, Thomas Cokelaer
# Copyright (C) 2012 Leo Singer, Alex Nitz
# Adapted from code found in:
# - LALSimInspiralTaylorF2.c
#
# This program is free software; you can redistribute it and/or modify
# it und... | Python | 1 |
except (ValueError, TypeError):
int_suffix = False
while fpath.exists():
fsint += 1
if int_suffix:
fpath = Path(f"{fstem}.{fsint:03d}")
else:
if '_' in fstem:
w = fstem.split('_')
try:
... | Python | 1 |
import pandas as pd
import torch
import json
import faiss
import requests
from io import BytesIO
from PIL import Image
from tqdm import tqdm
from transformers import CLIPProcessor, CLIPModel
# ---------- CONFIG ----------
CSV_PATH = "marketing_sample_for_amazon_com-ecommerce__20200101_20200131__10k_data.csv"
FAISS_IND... | Python | 1 |
zane"#,
))
.stdout(predicate::str::contains("[D] Skalowany Gauss"))
.stdout(predicate::str::contains("[E] Metoda SOR"))
.stdout(predicate::str::contains("4334"))
.stdout(predicate::str::contains("4328"))
.stdout(predicate::str::contains("4326"))
.stdout(predicate:... | Rust | 0 |
().unwrap();
assert_eq!(origin.scheme(), "http");
assert_eq!(origin.hostname(), "web-platform.test");
assert_eq!(origin.port(), Some(8000));
}
let headers = test_encode(allow_origin);
assert_eq!(headers["access-control-allow-origin"], s);
}
#[test]
... | Rust | 0 |
#!/usr/bin/python
# encoding: utf-8
# -*- coding: utf-8 -*-
"""
Created by PyCharm.
File Name: LinuxBashShellScriptForOps:rsa-encrypt-decrypt.py
Version: 0.0.2
Author: Guodong
Author Email: dgdenterprise@gmail.com
URL: https://github.com/DingGuodo... | Python | 1 |
ea, "Enter end address for selection:")
finally:
idaapi.jumpto(start_ea)
if end_ea and end_ea <= start_ea:
idaapi.msg(
f"Error: End address 0x{end_ea:X} must be greater than start address 0x{start_ea:X}."
)
end_ea = None
if end_ea ... | Python | 1 |
ms():
try: df[field_name] = df.eval(formula)
except Exception: pass
st.markdown("### 1. (선택) 계산된 필드 생성")
with st.expander("새로운 필드를 계산하여 추가하기"):
new_field_name = st.text_input("새 필드 이름 (예: ROI)")
formula = st.text_input("계산 공식 (예: 월급여 / 총경력)", help... | Python | 1 |
dhms) / 1_000_000_000
*seconds = seconds.checked_add(t_f_ns / 1_000_000_000).ok_or_else(|| {
ValueError(format!(
"INTERVAL '{}' overflows maximum seconds; \
cannot exceed {} seconds",
self.value,
... | Rust | 0 |
"""
Задача №3.
В некоторой школе решили набрать три новых математических класса
и оборудовать кабинеты для них новыми партами.
За каждой партой может сидеть два учащихся.
Известно количество учащихся в каждом из трех классов.
Выведите наименьшее число парт, которое нужно приобрести для них.
Input: 20 21 22(ввод чи... | Python | 1 |
*world
.insert(
(),
vec![(Translation::new(1.0, 0.0, 0.0), LocalToWorld::identity())],
)
.first()
.unwrap();
let children = world.insert(
(),
vec![
(
Translation::new(0.0... | Rust | 0 |
er(entry_2962, item_2960)?;
}
list_2961.finish();
}
#[allow(unused_mut)]
let mut scope_2963 = writer.prefix("MaxResults");
if let Some(var_2964) = &input.max_results {
scope_2963.number(
#[allow(clippy::useless_conversion)]
aws_smithy_types::Number::NegInt... | Rust | 0 |
name: value.name,
auto_restart: value.auto_restart,
server_folder,
server_jar,
backups,
rcon_password: value.rcon_password,
rcon_port: value.rcon_port,
java: value.java,
java_args: value.java_args,
m... | Rust | 0 |
len: libc::c_int,
mut cp: caddr_t,
) {
while off > 0i32 {
if off < (*m).m_hdr.mh_len {
break;
}
off -= (*m).m_hdr.mh_len;
m = (*m).m_hdr.mh_next
}
while len > 0i32 {
let mut count = 0;
count = if (*m).m_hdr.mh_len - off > len {
len... | Rust | 0 |
let (value, check) = DropTest::new();
values.push(value);
checks.push(check);
}
(values, checks)
}
}
impl Drop for DropTest {
fn drop(&mut self) {
let _ = self.0.fetch_add(1, Ordering::AcqRel);
}
}
/// Type that checks if `DropTest` is actually droppe... | Rust | 0 |
impl Display for IOError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
Debug::fmt(self, f)
}
}
impl Error for IOError {}
use structopt::StructOpt;
#[derive(StructOpt, Debug)]
#[structopt(name = "todo", about = "A simple command line todo app")]
/// A simple command line todo app
p... | Rust | 0 |
grid = grid.copy().apply_function(
lambda x: x + np.array([0.5 * x[1], 0.5 * x[0], 0])
)
self.play(Transform(grid, warped_grid), run_time=3)
self.wait(2)
def benamou_breniers_symphony(self):
# Create symbolic representations instead of SVG files
violin = Circle(c... | Python | 1 |
# coding: utf-8
from mhw_armor_edit import ftypes as ft
from mhw_armor_edit.ftypes import StructFile, Struct
class WpDatGEntry(Struct):
STRUCT_SIZE = 69
id: ft.uint()
unk1: ft.ushort()
base_model_id: ft.short()
part1_id: ft.short()
part2_id: ft.short()
unk7: ft.ubyte()
color: ft.ubyte... | Python | 1 |
edges = [
[1, 3],
[2, 3, 4],
[0],
[],
[2, 5],
[],
]
# O(v+e) time | O(v) space
def cycleInGraph(edges):
"""Function takes in a non-empty two-dimensional list representing outgoing edges
in a unweighted, directed graph and returns True if the input list contains cycles
otherwise F... | Python | 1 |
# coding: utf-8
"""
Slurm REST API
API to access and control Slurm
The version of the OpenAPI document: Slurm-24.11.5&openapi/slurmdbd&openapi/slurmctld
Contact: sales@schedmd.com
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E50... | Python | 1 |
t CANONICALIZED_PATHS = 0x10;
const OPLOCK = 0x20;
const OPBATCH = 0x40;
const REPLY = 0x80;
}
}
bitflags! {
pub struct Flags2: u16 {
const LONG_NAMES = 0x01;
const EAS = 0x02;
const SMB_SECURITY_SIGNATURE = 0x04;
const IS_LONG_NAME = 0x40;
const DFS... | Rust | 0 |
import collections
import copy
import dataclasses
import datetime
import enum
import json
import udmi.schema.util
from typing import Any, List
@dataclasses.dataclass
class Status:
category: str
level: int
message: str
timestamp: datetime.datetime = dataclasses.field(
default_factory=datetime.datetime.no... | Python | 1 |
"istr" => Type::IStr,
"__internal_Debug" => Type::Debug,
"__internal_Display" => Type::Display,
"[u8]" => Type::U8Slice,
"?" => Type::Format,
"[?]" => Type::FormatSlice,
"char" => Type::Char,
_ => return Err(()),
})
... | Rust | 0 |
]
outputs = self.model(batch)
response = outputs[0]['output']
return response
def generate_summary_batch(self, video_paths: list[str], audio_paths: list[str], questions: list[str], tasks: list[str]) -> list[str]:
# Read all data, this should be done with a dataloader for... | Python | 1 |
') and hasattr(view.get_serializer().Meta, 'model'):
model = view.get_serializer().Meta.model
if model:
return getattr(model, '_meta').verbose_name
else:
model = queryset.model._meta.verbose_name
except Exception as e:
pass
return model if model else "... | Python | 1 |
turn cx.type_i1();
}
let offset =
if index == 0 {
Size::ZERO
}
else {
a.value.size(cx).align_to(b.value.align(cx).abi)
};
self.scalar_gcc_type_at(cx, scalar, offset)
}
fn gcc_field_index(&self, index: usize... | Rust | 0 |
derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ModuleDraftQuery {
/// The query string.
#[serde(flatten)]
pub parent_id: AssetId,
}
/// Response for successfully finding a module
#[derive(Serialize, Deserialize, Debug)]
pub struct ModuleResponse {
/// The mo... | Rust | 0 |
r);
// # CONSOLE
// Create a shared UART channel for the consoles and for kernel debug.
sam4l::usart::USART3.set_mode(sam4l::usart::UsartMode::Uart);
let uart_mux =
UartMuxComponent::new(&sam4l::usart::USART3, 115200, dynamic_deferred_caller).finalize(());
let pconsole = ProcessConsoleComp... | Rust | 0 |
)
//! .await;
//!
//! match challenger_league_entries_request {
//! Ok(challenger_league_entries) => println!("{:#?}", challenger_league_entries),
//! Err(error) => println!("Oh no! An error occurred! Error: {:#?}", error),
//! }
//!
//! Ok(())
//! }
//! ```
mod client;
pub mod enum... | Rust | 0 |
]{Colors.END} {url} ({size} bytes)")
if len(directories) > 10:
print(f" ... and {len(directories) - 10} more directories/files found")
# SSL Information
ssl_info = web_vulns.get('ssl')
if ssl_info:
Log... | Python | 1 |
to describe a LOVE release.
#[derive(Hash,Eq,PartialEq,Serialize,Deserialize,SmartHash)]
pub struct Release {
pub version : Version,
pub platform: Platform,
pub link : String,
}
impl fmt::Display for Release {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,"{}-{}",self.platfor... | Rust | 0 |
ug, Clone, PartialEq)]
pub enum AccessControlAllowHeaders {
/// Specific headers
Only(Vec<String>),
/// Any header
Any,
}
/// CORS response headers
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AllowCors<T> {
/// CORS header was not required. Origin is not present in the request.
NotRequired,
/// CORS header ... | Rust | 0 |
# streamlit_app.py
import streamlit as st
from streamlit_tags import st_tags_sidebar
import pandas as pd
import json
import re
import sys
import asyncio
# ---local imports---
from scraper import scrape_urls
from pagination import paginate_urls
from markdown import fetch_and_store_markdowns
from assets import MODELS_US... | Python | 1 |
);
parse_files(&files);
return;
} else {
let files = macos_fseventsd::parser::get_fseventsd();
parse_files(&files);
}
}
fn parse_files(files: &Result<Vec<String>, std::io::Error>) {
match files {
Ok(results) => {
println!("Going to parse {} files", result... | Rust | 0 |
import unittest
from pyats.topology import loader
from genie.libs.sdk.apis.iosxe.SoftwareFedIpv6MldSnoopingGroups.verify import verify_Software_Fed_Ipv6_Mld_Snooping_Groups
class TestVerifySoftwareFedIpv6MldSnoopingGroups(unittest.TestCase):
@classmethod
def setUpClass(self):
testbed = """
de... | Python | 1 |
::from_str(&fix_pos_str3).unwrap();
assert!(similar(from_fix_pos_str3, fix_pos, max_diff));
let from_fix_neg_str3 = I15F17::from_str(&fix_neg_str3).unwrap();
assert!(similar(from_fix_neg_str3, fix_neg, max_diff));
let fix_str9 = format!("{:.9}", fix);
let fix... | Rust | 0 |
# Run the Agent
from langchain_core.messages import HumanMessage
from graph_builder import build_agent_graph
app = build_agent_graph()
# query = "What is refund pol
# ?"
# query = "raise a ticket for this issue"
# query = "Raise a ticket with id 3526"
# query = "order the product with given product id 2"
query ... | Python | 1 |
n_for_hit(HITId=hit_id, ExpireAt=past_time)
def setup_sns_topic(task_name, server_url, task_group_id):
# Create the topic and subscribe to it so that our server receives notifs
client = boto3.client('sns', region_name='us-east-1')
pattern = re.compile('[^a-zA-Z0-9_-]+')
filtered_task_name = pattern.su... | Python | 1 |
import torch
import numpy as np
from torch import nn
def get_params_size(params_list):
params_size = sum([np.prod(list(p.size())) for p in params_list]) * 4 / 1024
return "{:.0f}KB".format(params_size)
def clip_by_tensor(t, t_min, t_max):
"""
clip_by_tensor
--------------------
param ... | Python | 1 |
/ Chapter 3 Matrices
// Page 36
#[test]
#[rustfmt::skip]
fn calculating_a_cofactor_of_a_3x3_matrix() {
let a = [
[3.0, 5.0, 0.0, 0.0],
[2.0, -1.0, -7.0, 0.0],
[6.0, -1.0, 5.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
];
assert_eq!(Matrix::... | Rust | 0 |
s.append(cur_ep_len)
cur_ep_ret = 0
cur_ep_true_ret = 0
cur_ep_len = 0
if not isinstance(env, VecEnv):
observation = env.reset()
step += 1
def add_vtarg_and_adv(seg, gamma, lam):
"""
Compute target value using TD(lambda) estimator, and ad... | Python | 1 |
cationWarningRuntimeWarningFileIOisattyDEFAULT_BUFFER_SIZEfstatfileno
st_blksizeOSErrorAttributeErrorBufferedRandomBufferedWriterBufferedReader
TextIOWrappermodeclose)filer4 bufferingencodingerrorsnewlineclosefdr ZmodesZcreatingreadingwritingZ appendingZupdatingtextbinaryr$ rawresult... | Python | 1 |
from pydantic.type_adapter import TypeAdapter
from features.feature_health.models import (
FeatureHealthEventType,
FeatureHealthProviderName,
)
from features.feature_health.providers.sample.types import (
SampleEvent,
SampleEventStatus,
)
from features.feature_health.types import (
FeatureHealthEve... | Python | 1 |
e plot
# fig = px.line(filtered_df, x='year', y='value', line_dash='sector', color='fuel', facet_col='end_use', facet_col_wrap=3)
fig = px.area(filtered_df, x='year', y='end_use_energy_use_PJ', color='end_use', facet_col='sub2sectors', facet_col_wrap=2)
fig.update_yaxes(matches=None, showticklabels=True)
... | Python | 1 |
, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, ... | Rust | 0 |
w Request.
///
/// # Examples
///
/// # extern crate jrpc;
///
/// ```rust
/// # extern crate jrpc;
/// extern crate serde_json;
/// use jrpc::{Id, Request};
///
/// # fn main() {
/// let value: Vec<u32> = vec![1, 2, 3];
/// let request = Request::new(
/// Id:... | Rust | 0 |
from datetime import datetime
import marshmallow
from marshmallow import post_load
import typing
class WopiPutHeadersSchema(marshmallow.Schema):
wopi_lool_timestamp = marshmallow.fields.DateTime(
required=False,
load_from="X-LOOL-WOPI-Timestamp",
dump_to="X-LOOL-WOPI-Timestamp",
)
... | Python | 1 |
och_transactions(1, Some(&txn));
assert!(!query[0].is_inherent());
assert_eq!(query[0].block_number, 1);
assert_eq!(query[0].unwrap_basic().value, Coin::from_u64_unchecked(3));
assert!(query[1].is_inherent());
assert_eq!(query[1].block_number, 1);
assert_eq!(
... | Rust | 0 |
# module = a file containing python code . May contain functions, classes, etc.
# used with modular programing, which is to separate a program into parts
# to see the availibale modules type
help("modules") | Python | 1 |
(NonZeroU32::new(1).unwrap()), // daily
size_limit: MemorySize::Bytes(NonZeroU64::new(1_048_576).unwrap()), // 1 MiB
},
}
}
pub fn default_config() -> Config {
Config {
default_storage: default_storage_config(),
register_groups: Default::default(),
}
}
#[derive(Debug, C... | Rust | 0 |
{asp}.npy')
deepfeature = np.load("/mnt/sdb/cxh/liwen/EAT_code/demo/video_processed/obama/deepfeature32/obama.npy")
print(deepfeature.shape)
driving_latent = np.load(latent_path_driving[:-4]+'.npy', allow_pickle=True)
he_driving = driving_latent[1]
valid_scope = deepfea... | Python | 1 |
import instructor
from pydantic import BaseModel, Field
class Parameters(BaseModel):
board_name: float = Field(description="FPGA board name")
max_DSP: float = Field(description="Maximum DSP resource counts for the given board")
max_FF: float = Field(description="Maximum FF resource counts for the given b... | Python | 1 |
from typing import List, Optional
def isValid(s: str) -> bool:
"""
有效的括号
问题:判断字符串中的括号是否有效(匹配且顺序正确)
思路:
1. 使用栈来匹配括号
2. 遇到左括号时入栈
3. 遇到右括号时,检查栈顶是否匹配的左括号
4. 如果匹配,弹出栈顶;如果不匹配,返回 False
5. 最后检查栈是否为空
栈的应用:
- 后进先出(LIFO)特性完美匹配括号的嵌套结构
- 时间复杂度 O(n),空间复杂度 O(n)
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.