text string | label_name string | labels int64 |
|---|---|---|
super().__init__()
self.blocks = nn.ModuleList([
GPTLayer(
dim=dim,
num_heads=num_heads,
mlp_ratio=mlp_ratio,
attention_dropout=attention_dropout,
dropout=dropout,
dtype=dtype,
) for _ in ran... | Python | 1 |
beef() {
println!("Is this accessible?");
}
}
fn main() {
foo::beef::qux();
foo::deadbeef();
let guess = Guess::new(99);
println!("{}", guess.value());
}
use crate::instructions::calc_rarity_points;
use anchor_lang::prelude::*;
use anchor_spl::{
associated_token::AssociatedToken,
... | Rust | 0 |
m the
/// input pointer).
const NoAlpha = 1;
/// ColorEdit: disable picker when clicking on colored square.
const NoPicker = 1 << 2;
/// ColorEdit: disable toggling options menu when right-clicking on inputs/small preview.
const NoOptions = 1 << 3;
/// ColorEdit, ... | Rust | 0 |
import os
def gltf_pipeline(input_path, out_path, is_binary=True):
command = 'gltf-pipeline -i "' + input_path + '" -o "' + out_path + '" -d'
if is_binary:
command += ' -b'
else:
command += ' -s'
print("gltf pipeline command:", command)
os.system(command)
# exists mains success... | Python | 1 |
unction_name).expect("Invalid string"),
}),
is: is.map(|(module, entry_function_name)| ProgramGroupModule {
module,
entry_function_name: CString::new(entry_function_name).expect("Invalid string"),
}),
}
}
}
/// A group of programs to be as... | Rust | 0 |
import pyodbc
def test_pyodbc_connection():
try:
connection = pyodbc.connect(
"DRIVER={ODBC Driver 18 for SQL Server};"
"SERVER=iush-proyecto-aula.database.windows.net,1433;"
"DATABASE=omega-ubuntu;"
"UID=admin-aula;"
"PWD=Sistemas$1234;"
... | Python | 1 |
decode(reader: &mut impl Read, _state: ()) -> eyre::Result<Self> {
let bounds = BoundingBox::decode(reader, ())?;
let flags = u32::decode(reader, ())?;
let is_leaf = bool::decode(reader, ())?;
if is_leaf {
let leaf_index = u32::decode(reader, ())?;
Ok(SectorOct... | Rust | 0 |
Self {
Self {
kind: (),
name: name.into(),
namespace: None,
}
}
pub fn within(mut self, namespace: &str) -> Self {
self.namespace = Some(namespace.to_string());
self
}
#[must_use]
pub fn from_obj(obj: &K) -> Self {
Self {... | Rust | 0 |
let max_path_len = files.iter().fold(0, |acc, info| {
cmp::max(acc, info.path.to_string_lossy().len())
});
Ok(files
.iter()
.map(|info| {
let path = info.path.to_string_lossy();
format!(
"{size}\t\t{mime_type}\t{path}{path_space}",
... | Rust | 0 |
(i as isize);
}
fn add_inout<'ast>(name: &'ast str, i: usize, map: &mut AliasInfoMap<'ast>) {
map.entry(name.as_ref()).or_default().add_inout(i as isize);
}
fn add_use<'ast>(name: &'ast str, map: &mut AliasInfoMap<'ast>) {
map.entry(name.as_ref()).or_default().add_use();
}
// ... | Rust | 0 |
55 push %rbp
// 1: 48 89 e5 mov %rsp,%rbp
// 4: 48 8b 05 00 00 00 00 mov 0x0(%rip),%rax # b <deadbeef+0xb>
// 7: R_X86_64_GOTPCREL DEADBEEF-0x4
// b: 8b 08 mov (%rax),%ecx
// d: 83 c1 01 add $0x1,%ecx
... | Rust | 0 |
#!/usr/bin/env python
#-*- coding: UTF-8 -*-
"""
This module uses the sample.py script to load all test models it finds.
Note: this is not an exhaustive test suite, it does not check the
data structures in detail. It just verifies whether basic
loading and querying of 3d models using pyassimp works.
"""
import os
im... | Python | 1 |
#Faça um programa que leia um nome de usuário e a sua senha e não aceite a
# senha igual ao nome do usuário, mostrando uma mensagem de erro e voltando a pedir as informações.
while True:
nome = str(input('Informe seu nome: ')).strip().lower().split()
senha = str(input('Digite sua senha: ')).strip().lower()
... | Python | 1 |
t dag = yatima_core::dag::DAG::from_term(&def.to_owned().term);
dag.norm(&defs, false);
println!("{}", dag);
Ok(())
}
}
}
// for valgrind testing
// Command::Test => {
// use im::HashMap;
// use yatima::{
// core::dag::DAG,
// parse::span::Span,
// };
// pub fn parse(
// i: &str,
/... | Rust | 0 |
}
}
}
#[derive(Debug, Clone)]
pub struct InputMisMatchError {
pub(crate) base: BaseRecognitionError,
}
impl InputMisMatchError {
pub fn new(recognizer: &mut dyn Parser) -> InputMisMatchError {
InputMisMatchError {
base: BaseRecognitionError::new(recognizer),
}
}
... | Rust | 0 |
iveDate::from_ymd(x.year(), month, 1)
}
Period::Month => NaiveDate::from_ymd(x.year(), x.month(), 1),
Period::Week => {
NaiveDate::from_isoywd(x.iso_week().year(), x.iso_week().week(), Weekday::Mon)
}
}
}
pub fn eop(x: &NaiveDate, p: Period) -> NaiveDate {
match p {
... | Rust | 0 |
grad[:5, :3])
# print("v2 v.grad[:5, :3, :5]: ", v.grad[:5, :3, :5])
# print("v2 table.grad[:5, :3, :5, :2]: ", table.grad[:5, :3, :5, :2])
# # input()
print("((output-output_v2)**2).max(): ", ((output-output_v2)**2).max())
print("((attn_grad-attn.grad)**2).max(): ", ((attn_grad-attn.grad)**2).max())
print("((v_grad... | Python | 1 |
from ..base import FFmpegCommandBuilder
class MP4CommandBuilder(FFmpegCommandBuilder):
def build_command(self) -> list[str]:
command = self._get_basic_ffmpeg_command()
if self.segment_record:
additional_commands = [
"-c:v", "copy",
"-c:a", "aac",
... | Python | 1 |
from telegram import ReplyKeyboardMarkup, Update
from telegram.ext import CallbackContext
from users.models import Profile
from . import constants
from .constants import START
from .permissions import restricted
from .utils import get_botmessage_by_keyword
@restricted
async def start(update: Update, context: Callba... | Python | 1 |
Ok((r, m)) = c_style_comment(rest) {
rest = r;
mid_size += m.len()
} else if let Ok((r, u)) = tag::<&str, &str, nom::error::Error<&str>>("*/")(rest) {
rest = r;
mid_size += u.len();
break;
} else {
// eat an asterisk or single slas... | Rust | 0 |
# -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
from gunicorn.http.message import Request
from gunicorn.http.unreader import SocketUnreader, IterUnreader
class Parser(object):
mesg_class = None
def __init__(self, cfg, source, so... | 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 |
ering task
timer.tasks_start.write(|w| w.tasks_start().set_bit());
compiler_fence(SeqCst);
}
/// Resets the timer.
#[inline]
fn reset(&mut self) {
//rprintln!("Resetting interval timer");
// Variable to make the code a bit less verbose.
let timer = &mut self.tim... | Rust | 0 |
+", Color::Red, true),
("Grn+", Color::Green, true),
("Ylw+", Color::Yellow, true),
("Blu+", Color::Blue, true),
("Mgn+", Color::Magenta, true),
("Cyn+", Color::Cyan, true),
("Wht+", Color::White, true),
];
println!("usual+bold");
print!(" ");
for &(ref... | Rust | 0 |
path=node.original_file_path,
original_file_path=node.original_file_path,
insight=self._build_failure_result(
node_id,
not missing_model_documentation,
... | Python | 1 |
text = f"<|audio|>{voice_id}: {text}<|eot_id|><custom_token_4>"
try:
token_gen = self._llm(
text,
max_tokens=options.get("max_tokens", 2_048),
stream=True,
temperature=options.get("temperature", 0.8),
top_p=... | Python | 1 |
g!')
box_pos = box.xyxy[0]
center_x = (box_pos[0] + box_pos[2]) / 2
center_y = (box_pos[1] + box_pos[3]) / 2
click(center_x, center_y)
print('clicked bag')
time.sleep(1)
... | Python | 1 |
texture_coordinates: [f32; 2],
}
unsafe impl bytemuck::Pod for BlockVertex {}
unsafe impl bytemuck::Zeroable for BlockVertex {}
impl Vertex for BlockVertex {
fn desc<'a>() -> wgpu::VertexBufferLayout<'a> {
use std::mem;
wgpu::VertexBufferLayout {
array_stride: mem::size_of::<BlockVerte... | Rust | 0 |
import cv2 as cv
video_file = '../data/PETS09-S2L1-raw.webm'
# Read the given video file
video = cv.VideoCapture(video_file)
assert video.isOpened(), 'Cannot read the given video, ' + video_file
# Get FPS and calculate the waiting time in millisecond
fps = video.get(cv.CAP_PROP_FPS)
wait_msec = int(1 / fps * 1000)
... | Python | 1 |
.header(Header::new("X-Forwarded-Host", "foo.example.com"));
let mut response = req.dispatch();
assert_eq!(response.status(), Status::Ok);
assert!(response.body().is_some());
}
#[test]
fn test_allowed_hosts_with_host_proxy_header_allowed_proxy() {
static ALLOWED_HOSTS: &[&str] = &["example.com"... | Rust | 0 |
es_per_material: Vec<Vec<u32>>,
}
<filename>rust/nodebridge/src/ckb/mod.rs
use std::time::{Duration, Instant};
use std::{str, thread};
use chrono::prelude::*;
use ckb_jsonrpc_types::BlockTemplate;
use ckb_types::prelude::{Builder, Entity, Pack};
use ckb_types::{H256};
use failure::Error;
use futures::future::{loop_fn,... | Rust | 0 |
- result[2]) <= result[0] && result[0] <= 1.0)
);
assert_approx_eq!(result[1], 1.0 - result[0] - result[2]);
assert!(result[2] >= 0.0 && result[2] <= 1.0);
}
}
#[test]
fn uf10_optimum() {
let mut rng = weak_rng();
for d in 5..31 {
le... | Rust | 0 |
pub trait PartialSessionWitness<C, A, K>: HasPartialSession<C, A>
{
fn with_partial_session(
self: Box<Self>,
cont: Box<dyn NeedPartialSession<C, A, K>>,
) -> K;
}
extern crate proc_macro;
mod serde_diff;
/// # Examples
///
/// Minimal example of implementing diff support for a struct
/// ```rust
/// use... | Rust | 0 |
"""Tests for the Straight-Through Estimator (STE)."""
import chex
import jax
import jax.numpy as jnp
from prxteinmpnn.model.ste import ste_loss, straight_through_estimator
def test_straight_through_estimator():
"""Test the Straight-Through Estimator implementation.
Raises:
AssertionError: If the output do... | Python | 1 |
Device Type Register"]
pub devtype: crate::Reg<devtype::DEVTYPE_SPEC>,
#[doc = "0xfd0 - ETM Peripheral Identification Register #4"]
pub pidr4: crate::Reg<pidr4::PIDR4_SPEC>,
#[doc = "0xfd4 - ETM Peripheral Identification Register #5"]
pub pidr5: crate::Reg<pidr5::PIDR5_SPEC>,
#[doc = "0xfd8 - E... | Rust | 0 |
}
}
}
false
}
fn demolish_if_possible(
board: &mut Board,
stashes: &mut Stashes,
dealing_stuff: Option<(&mut Vec<Card>, &mut Vec<Card>, &mut StdRng, u8)>,
hand: &mut Vec<Card>,
mut selected_indicies: Vec<usize>,
target: (i8, i8),
piece_index: usize,
) -> bool {
/... | Rust | 0 |
from unittest.mock import patch
from tests.providers.gcp.gcp_fixtures import (
GCP_PROJECT_ID,
mock_api_client,
mock_is_api_active,
set_mocked_gcp_provider,
)
class TestDataprocService:
def test_service(self):
with patch(
"prowler.providers.gcp.lib.service.service.GCPService._... | Python | 1 |
m.shape[:-1],
dtype=m.dtype,
device=m.device,
).detach()
# [*, N_res, N_seq, C_in]
m = m.transpose(-2, -3)
mask = mask.transpose(-1, -2)
if chunk_size is not None:
m = self._chunk(m, mask, chunk_size, use_lma=use_lma)
e... | Python | 1 |
import os
import re
import sys
import json
import platform
import tempfile
import shutil
import subprocess
import datetime
def write_json(path, data, encoding="utf8"):
"""写入json"""
with open(path, "w", encoding=encoding) as f:
json.dump(data, f, ensure_ascii=False, indent=4)
def read_json(path, defa... | Python | 1 |
name = name.into();
if let Some(passphrase) = passphrase {
let state_store = StateStore::open_with_passphrase(name.clone(), passphrase).await?;
let crypto_store = CryptoStore::open_with_passphrase(name, passphrase).await?;
Ok((Box::new(state_store), Box::new(crypto_store)))
} else {
... | Rust | 0 |
;
lastB = b;
}
if j > area - 3 {
continue;
}
print!("{}", background_rgb(lastR, lastG, lastB, &foreground_rgb(r, g, b, printChar)));
}
print!("{esc}[1;1H", esc = 27 as char);
frame += 1;
}
}
fn foreground_rgb(r: u8, g: u8, b: u8, text: &str) -> String {
forma... | Rust | 0 |
import cv2
import IpCameraList
from threading import Thread
from pygrabber.dshow_graph import FilterGraph
class WebcamStream :
def __init__(self, stream_id):
self.stream_id = stream_id
self.vcap = cv2.VideoCapture(self.stream_id)
if self.vcap.isOpened() is False :
print("[... | Python | 1 |
#!/usr/bin/env python
#
# Copyright 2016 Google Inc. 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 |
_links(leg_fk_bone_name).get(ankle_bone_name))
# ひざ
knee_fk_bone = leg_fk_links.to_links(leg_fk_bone_name).get(knee_bone_name).copy()
knee_fk_bone.ik_limit_min = MVector3D(0, -180, 0)
knee_fk_bone.ik_limit_max = MVector3D(0, 10, 0)
leg_fk2... | Python | 1 |
ce_root.resolve()).encode()).hexdigest()[
:8
]
workspace_dir = get_data_dir() / "workspaces" / workspace_id / workspace_label
workspace_dir.mkdir(parents=True, exist_ok=True)
return workspace_dir / repo_name / label
def get_workspace_session_name(workspace_root: Path, workspace_label: str) -> ... | Python | 1 |
)
}
pub fn leaves_indices_count_mismatch(indices_len: usize, leaves_len: usize) -> Self {
Self::new(
ErrorKind::LeavesIndicesCountMismatch,
format!(
"leaves indices count doesn't match leaves count: {} and {}",
indices_len, leaves_len
... | Rust | 0 |
OutputWindow: hwnd,
Windowed: TRUE,
SwapEffect: DXGI_SWAP_EFFECT_DISCARD,
Flags: DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH,
};
let _hr = unsafe { dxgi_factory.Create... | Rust | 0 |
onfig.sector_size);
let tree_leafs =
get_tree_leafs::<<DefaultTreeHasher as Hasher>::Domain>(post_config.sector_size);
let mut proofs = Vec::with_capacity(winners.len());
let inputs: Vec<_> = winners
.par_iter()
.map(|winner| {
let replica = replicas
.ge... | Rust | 0 |
use nfuint_tests::props;
use proptest::prelude::any;
macro_rules! std_ops_shift {
($opr:tt, $bits:expr, $name:ident) => {
proptest! {
#[test]
fn $name(ref le in any::<props::U256LeBytes>()) {
let expected: props::U256LeBytes = {
let val: etypes::... | Rust | 0 |
ype GlibType = ffi::ALSASeqPortCapFlag;
fn into_glib(self) -> ffi::ALSASeqPortCapFlag {
self.bits()
}
}
#[doc(hidden)]
impl FromGlib<ffi::ALSASeqPortCapFlag> for PortCapFlag {
unsafe fn from_glib(value: ffi::ALSASeqPortCapFlag) -> Self {
Self::from_bits_truncate(value)
}
}
impl Static... | Rust | 0 |
expect("stdlib module failed to compile");
let verified_module =
VerifiedModule::new(compiled_module).expect("stdlib module failed to verify");
let verification_errors = verify_module_dependencies(&verified_module, &stdlib_modules);
// Fail if the module doesn't verify
for e... | Rust | 0 |
189),
("CSPR", 190),
("ARK", 191),
("NU", 192),
("MTL", 193),
("REQ", 194),
("TOMO", 195),
("SYS", 196),
("STEEM", 197),
("PHA", 198),
("ANT", 199),
("BTCST", 200),
("HEX", 20... | Rust | 0 |
}
impl PinweaverGetLog {
pub fn new(
root: [u8; HASH_SIZE as usize],
) -> Result<PinweaverRequest<PinweaverGetLog, PinweaverGetLogResponse>, PinWeaverError> {
Ok(PinweaverRequest::new(PinweaverMessageType::GetLog, PinweaverGetLog { root }))
}
}
impl Serializable for PinweaverGetLog {
/... | Rust | 0 |
ArithmeticBase::Column(ref col) => write!(f, "{}", col),
ArithmeticBase::Scalar(ref lit) => write!(f, "{}", lit.to_string()),
ArithmeticBase::Bracketed(ref ari) => write!(f, "({})", ari),
}
}
}
impl fmt::Display for ArithmeticItem {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::... | Rust | 0 |
cd_dict.values()]))
logging.info(f"Average: {mean_mcd:.4f} ± {std_mcd:.4f}")
# write results
if args.outdir is None:
if os.path.isdir(args.gen_wavdir_or_wavscp):
args.outdir = args.gen_wavdir_or_wavscp
else:
args.outdir = os.path.dirname(args.gen_wavdir_or_wavscp... | Python | 1 |
from matplotlib import pyplot as plt
import numpy as np
def plotPositions(txPosition, rxPosition, txNormal, rxNormal):
fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
# plot positions
ax.plot(*txPosition, 'r*')
ax.plot(*rxPosition, 'bx')
# plot pointing vectors
# looks like: ax.quive... | Python | 1 |
# Copyright 2024 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Python | 1 |
r(torch.randn(embedding_size) * scale, requires_grad=False)
self.weight = self.W
def forward(self, x):
if self.log:
x = torch.log(x)
x_proj = x[:, None] * self.weight[None, :] * 2 * np.pi
if self.flip_sin_to_cos:
out = torch.cat([torch.cos(x_proj), tor... | Python | 1 |
rT z8Caught subprocess termination from unknown pid: %d -> %d)r| rA rV rB rC rY r3 r@ rN r[ rZ r r r
r r )r! rs rD rt rH rI r r r rL s:
"z FastChildWatcher._do_waitpid_all)r r r r r r' r... | Python | 1 |
.zip(self.key_states.iter_mut())
{
next_state.reset_action();
next_state.set_down(cur_state.is_down());
}
}
fn as_input_engine(&self) -> Rc<RefCell<dyn InputEngine>> {
self.input_engine.upgrade().unwrap()
}
}
<filename>src/boot/vspace.rs
//! Defi... | Rust | 0 |
&Option<LambdaAST> {
match self {
VariableWithLambda::Scalar(scalar) => &scalar.lambda,
VariableWithLambda::Stream(stream) => &stream.lambda,
}
}
// This function is unsafe and lambda must be non-empty, although it's used only for tests
#[allow(dead_code)]
pub(cr... | Rust | 0 |
import os, sys
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
extra = {}
try:
from setuptools import setup
has_setuptools = True
extra['test_suite'] = 'tests.runtests'
except ImportError:
from distutils.core import setup
has_setuptools = False
if sys.version_info >= (3, ):
if ... | Python | 1 |
ndexSet::<Self>::default();
let mut ids = HashMap::<Id, Id>::default();
let mut todo = self.children().to_vec();
while let Some(id) = todo.last().copied() {
if ids.contains_key(&id) {
todo.pop();
continue;
}
let node = get_nod... | Rust | 0 |
a> {
fn set_meta(&mut self, meta: Meta<'a>) {
self.meta = meta;
}
}
impl BaseTypeSchemaBuilder for TUnicode<'_> {
fn build_schema<B>(builder: &mut B) -> TStruct<'static>
where
B: SchemaBuilder<'static>,
{
let range_element = builder.add_unwrap(
"unicode_length_el... | Rust | 0 |
ls_b: ls,
};
data.compute(self.coords_count() - 1, ls.coords_count() - 1)
} else {
T::zero()
}
}
}
struct Data<'a, T>
where
T: Float + FromPrimitive,
{
cache: Vec<Vec<T>>,
ls_a: &'a LineString<T>,
ls_b: &'a LineString<T>,
}
impl<... | Rust | 0 |
@classmethod
def from_unet(cls, unet: UNet2DConditionModel,
controlnet_conditioning_channel_order: str='rgb',
conditioning_embedding_out_channels: Optional[Tuple[int]]=(16, 32, 96,
256), load_weights_from_unet: bool=True):
"""
Instantiate Controlnet class from UNet2DConditionModel.
Par... | Python | 1 |
await self._action_scale_up(state)
elif action == "investigate":
await self._action_investigate(state)
async def _action_monitor(self, state: dict[str, Any]):
"""Monitor action - just observe and log."""
metrics = state.get("metrics", {})
print(f"📊 Monitoring: CPU={... | Python | 1 |
teAgentDeployScriptDetails.
:type: str
"""
allowed_values = ["LINUX", "WINDOWS", "MACOS", "UNKNOWN"]
if not value_allowed_none_or_none_sentinel(os_family, allowed_values):
raise ValueError(
f"Invalid value for `os_family`, must be None or one of {allowed_value... | Python | 1 |
.pattern).await?;
let names: Vec<String> = files.iter().map(|file| file.path.clone()).collect();
let sizes: Vec<u64> = files.iter().map(|file| file.size).collect();
let md5s: Vec<Option<Vec<u8>>> = files
.iter()
.map(|file| file.md5.as_ref().map(|f| f.to_string().into_by... | Rust | 0 |
NAME, PASSWORD)
print("✅ Successfully logged into Instagram!")
return cl
except exceptions.BadPassword:
print("❌ Incorrect password. Check credentials.")
return None
except exceptions.LoginRequired:
print("⚠️ Login required. Retrying...")
... | Python | 1 |
ces: VkAccelerationStructureGeometryInstancesDataKHR,
}
}
unionize! {
/// [VkDeviceOrHostAddressConstKHR](https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VkDeviceOrHostAddressConstKHR.html)
VkDeviceOrHostAddressConstKHR {
/// * **No Auto-validity:** true
deviceAddress: VkDeviceAddre... | Rust | 0 |
),
(
"dl_src~=00:11:22:33:44:66",
OFPFlow(
"n_bytes=100 priority=100,dl_src=00:11:22:33:44:55/ff:ff:ff:ff:ff:00,nw_src=192.168.1.0/24,tcp_dst=80 actions=2" # noqa: E501
),
True,
["dl_src"],
),
(
"dl_src~=00... | Python | 1 |
importlib.import_module(target_module)
# Successfully imported all modules, we can return
return
except (ImportError, ModuleNotFoundError) as e:
pass
# If we reach here, it means that at least one of the modules is not installed
logger.info(
f"The extra packages... | Python | 1 |
# Copyright (C) 2015-2017 Free Software Foundation, Inc.
# 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 version.
#
# This progr... | Python | 1 |
from datetime import datetime
from videogame import Videogame
v1 = Videogame()
v1.marca = "Sony"
v1.modelo = "Playstation 5"
v1.data = datetime.now()
print("V1=",v1)
v2 = Videogame(datetime.now())
print("V2=",v2)
v3 = Videogame(datetime.now(), "Nintendo", "Switch")
print("V3=",v3)
v3.anos_garantia = 10
v3.jogos_insta... | Python | 1 |
m(script);
utxo.into_iter().map(move |utxo| Funds {
outpoint: *utxo.outpoint(),
terminal: vec![case, index],
script_pubkey: script_pubkey.clone(),
amount: utxo.amount().as_sat(),
... | Rust | 0 |
# Copyright 2024 NXP
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import random
from gvgen import GvGen
from torch.export import ExportedProgram
def exported_program_to_dot( # noqa C901
exported_program: ExportedProgram, dot... | Python | 1 |
from pep600_compliance.images import base, package_manager
class AnolisOS(base.Base):
def __init__(self, image, eol, pkg_manager, packages, machines, python="python3"):
_, version = image.split(":")
self._packages = packages
super().__init__(
image,
"anolisos",
... | Python | 1 |
eSheet("background-color: #25222A; border-radius: 5px; margin: 1px")
def addPage(self, widget: SiGraphicWrapperWidget, name: str = "新页面") -> None:
self._no_page_label.hide()
self._no_button_label.hide()
new_button = SiFlatButtonWithIndicator(self)
new_button.setText(name)
n... | Python | 1 |
#!/usr/bin/env python3
"""
Example of how to run LLMEO project from the framework.
"""
import sys
import os
# Add project root to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../.."))
def run_llmeo_example():
"""Run a simple LLMEO example."""
print("🧪 Running LLMEO Example")
print(... | Python | 1 |
.len())
/// }
/// fn flush(&mut self) -> std::io::Result<()> {
/// Ok(())
/// }
/// }
///
/// let jws = "eyJhbGciOiJ0ZXN0X2FsZ29yaXRobSIsImN1c3RvbSI6ImN1c3RvbV92YWx1ZSJ9..ZXlKaGJHY2lPaUowWlhOMFgyRnNaMjl5YVhSb2JTSXNJbU4xYzNSdmJTSTZJbU4xYzNSdmJWOTJZV3gxWlNKOS5BQUVDQXdRRkJn".as_bytes();
///
/// let mut... | Rust | 0 |
}
}
pub fn push(&mut self, value: bool) {
let idx = self.length >> 3;
if idx >= self.data.len() {
self.data.push(0);
}
self.length += 1;
self.replace(self.length - 1, value);
}
pub fn replace(&mut self, idx: usize, value: bool) {
asse... | Rust | 0 |
a = [5, 10, 20, 15, 7, 25, 30, 10]
for i in range(1,len(a)-1):
if a[i]>a[i-1] and a[i]>a[i+1]:
print(i)
else:
pass
| Python | 1 |
E$-GI-H dD)II-J 5t,KI-L %eD$&7MI-N -eD$.?OI-P tT!2QI-R eD$'SI-T 5t,UI-V "5t#4WI-X dD)YI-Z .uT4/@[I-\ %d+]I-^ E$%_I-`
eD$aI-b eD$/cI-d uT40eI-f dD)gI-h $U4%6iI-j eD$/kI-l 5t$mI-n... | Python | 1 |
;
min = cards;
if val >= best {
best = cards;
best_model = Some(model);
}
} else {
//println!("Impossible!");
max = val;
}
}
let mut models = Vec::new();
if let Some((mut model, mut encoder)) = best... | Rust | 0 |
}
<gh_stars>1-10
use std::fmt::{self, Display, Formatter};
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub enum Rcst {
EqualsSign, // =
Comma, // ,
Colon, // :
OpeningParenthesis, // (
ClosingParenthesis, // )
OpeningBracket, // [
ClosingBracket, ... | Rust | 0 |
D8 OSAGE SMALL LETTER A .. U+104FB OSAGE SMALL LETTER ZHA
// U+10CC0 OLD HUNGARIAN SMALL LETTER A .. U+10CF2 OLD HUNGARIAN SMALL LETTER US
// U+118C0 WARANG CITI SMALL LETTER NGAA .. U+118DF WARANG CITI SMALL LETTER VIYO
// U+16E60 MEDEFAIDRIN SMALL LETTER M .. U+16E7F MEDEFAIDRIN SMALL LETTER Y... | Rust | 0 |
tem in enumerate(sorted_items)}
print(base_model_ranking)
base_model_list = sorted(base_model_ranking, key=elo_rating_style.get, reverse=True)
print(base_model_list)
# 判断是否继续进行bubble window
new_model_rank = base_model_list.index(new_model)+1
model_num = len(base_model_lis... | Python | 1 |
ng_tx = pending_tx_result.unwrap();
pending_txs.push(pending_tx);
}
join_all(pending_txs).await;
}
pub fn get_user_key() -> BridgeUserKey {
let mut rng = rand::thread_rng();
let secret: [u8; 32] = rng.gen();
// the starting location of the funds
let eth_key = SigningKey::from_bytes(&sec... | Rust | 0 |
return ve!(Self, TotalSizeNotMatch, Self::TOTAL_SIZE, slice_len);
}
Ok(())
}
}
#[derive(Debug, Default)]
pub struct WithdrawalLockArgsBuilder {
pub(crate) deposition_block_hash: Byte32,
pub(crate) deposition_block_number: Uint64,
pub(crate) withdrawal_block_hash: Byte32,
pub(c... | Rust | 0 |
# Group Anagrams
# method1: sort 每一个单词,将结果作为 hash key,将单词作为 hash list value,最终将hash value 转换为 list
# method2: 相同的字符出现的次数一定是一致的,生成一个26个字母的数组 key_list = [0] # 26, 通过 ord(ch) - ord("a")
# 获取每个字符在26个字母中顺序的整形,作为 index 对多次出现在 key_list中的结果 +1,将key转换为 string,作为 hash的key,
# 将单词作为 hash list value的值,即可得到最终结果
class Solution(objec... | Python | 1 |
.rstrip())
line_height = font.get_height() + 2
for i, line in enumerate(lines):
if (i + 1) * line_height > text_rect.height:
break
line_surface = font.render(line, True, self.text_color)
screen.blit(line_surface, (text_rect.left, text_rect.top + i * li... | Python | 1 |
def Args(parser):
flags.AddQueueResourceArg(parser, 'to create')
flags.AddLocationFlag(parser)
flags.AddCreatePushQueueFlags(parser, release_track=base.ReleaseTrack.BETA)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class AlphaCreate(Create):
"""Create a Cloud Tasks queue.
The flags available to thi... | Python | 1 |
CUDNN_POINTWISE_LOGICAL_OR,
PointwiseMode::Max => Self::CUDNN_POINTWISE_MAX,
PointwiseMode::Min => Self::CUDNN_POINTWISE_MIN,
PointwiseMode::Mod => Self::CUDNN_POINTWISE_MOD,
PointwiseMode::Mul => Self::CUDNN_POINTWISE_MUL,
PointwiseMode::Neg => Self::CUDNN_PO... | Rust | 0 |
fn resumeen(&mut self) -> RESUMEEN_W {
RESUMEEN_W { w: self }
}
#[doc = "Bit 7 - STALL Interrupt Enable"]
#[inline(always)]
pub fn stallen(&mut self) -> STALLEN_W {
STALLEN_W { w: self }
}
}
<reponame>matix522/uranos
use alloc::alloc::*;
unsafe impl Sync for TaskStack {}
#[derive(Debug)]
pub struct... | Rust | 0 |
mponent.
#[inline]
pub fn time(&self) -> NaiveTime {
self.time
}
/// Returns the number of non-leap seconds since January 1, 1970 0:00:00 UTC
/// (aka "UNIX timestamp").
/// Note that this does *not* account for the timezone!
#[inline]
pub fn timestamp(&self) -> i64 {
le... | Rust | 0 |
self.0.to_owned().into()
}
}
<gh_stars>0
use super::require_identity_on_endpoint::NewRequireIdentity;
use super::Endpoint;
use crate::tcp;
use linkerd2_app_core::{
classify,
config::ConnectConfig,
metrics,
opencensus::proto::trace::v1 as oc,
proxy::{http, tap},
reconnect,
spans::Spa... | Rust | 0 |
OCATION_PER_2X1_PIXELS_NV : i32 = 6;
pub const SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_1X2_PIXELS_NV : i32 = 7;
pub const SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X2_PIXELS_NV : i32 = 8;
pub const SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_4X2_PIXELS_NV : i32 = 9;
pub const SHADING_RATE_PALETTE_ENTRY_1_INVOCAT... | Rust | 0 |
import scapy.all as scapy
import argparse
def network_sniffer(interface):
try:
# Start sniffing packets on the specified interface
scapy.sniff(iface=interface, store=False, prn=lambda x: x.show())
except Exception as e:
print('An error occurred: %s' % e)
def main():
parser = argpa... | Python | 1 |
import pandas as pd
import numpy as np
from statsmodels.tsa.arima.model import ARIMA # type: ignore
from sklearn.metrics import mean_squared_error
from math import sqrt
import matplotlib.pyplot as plt
# Load the data
file_path = r"C:\Users\adira\OneDrive\Desktop\Alcohol_Sales.csv"
alcohol_sales_df = pd.read_csv(file_p... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.