text string | label_name string | labels int64 |
|---|---|---|
.0);
assert_relative_eq!(c2.z(), 0.0);
assert_relative_eq!(c2.Y(), 1.0);
}
#[test]
#[should_panic]
fn test_neg_set_panic() {
let mut c1 = XyY::new(0.2, 0.3, 0.9);
c1.set_y(-0.3);
}
#[test]
#[should_panic]
fn test_too_high_set_panic() {
let mut c1... | Rust | 0 |
height);
// let rgb = nannou::color::IntoLinSrgba::into_lin_srgba(spacebrush.col());
// float_delaunay.insert(Vertex {
// position: [spacebrush.pos.x, spacebrush.pos.y, 0.0],
// color: [rgb.red, rgb.blue, rgb.green, rgb.alpha],
// });
// th... | Rust | 0 |
one:
download_codeplug(dfu, firmware)
print('Write complete')
elif sys.argv[1] == 'sign':
filename = sys.argv[2]
f = open(filename, 'rb')
firmware = f.read()
f.close()
data = dfu_suffix... | Python | 1 |
9::ChannelSettings::CH4SET as u8,
ads1299::BIAS_DRN | ads1299::Gain::X1 as u8,
)
.map(map_status)?;
self.wreg(
ads1299::ChannelSettings::CH5SET as u8,
ads1299::BIAS_DRP | ads1299::Gain::X1 as u8,
)
.map(map_status)?;
self.wreg(
... | Rust | 0 |
from django.contrib import admin
from .models import NamesWoman, NamesMan
admin.site.register(NamesWoman)
admin.site.register(NamesMan)
| Python | 1 |
"""
INF601 - Advanced Programming in Python
Sam Boutros
Prof. Zeller
FHSU - Fall 2022
11/1/2022
https://samsclass.info/124/proj14/VP100.htm
"""
# Find the eight-character Unicode code point for a capital Sigma, covered by a green box in the image below.
"""
for x in range(0, 0xfff+1):
if chr(x).isprintable():
... | Python | 1 |
ml)** (from Google Research and the Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut."
l... | Python | 1 |
import numpy as np
from gym import spaces
from rl.utils.vec_env import VecEnvWrapper
class VecFrameStack(VecEnvWrapper):
"""
Frame stacking wrapper for vectorized environment
:param venv: (VecEnv) the vectorized environment to wrap
:param n_stack: (int) Number of frames to stack
"""
def... | Python | 1 |
128*self.wide_factor, 128*self.wide_factor, norm_fn=norm_fn, indice_key='res4'),
SparseBasicBlock(128*self.wide_factor, 128*self.wide_factor, norm_fn=norm_fn, indice_key='res4'),
SparseBasicBlock(128*self.wide_factor, 128*self.wide_factor, norm_fn=norm_fn, indice_key='res4'),
)
... | Python | 1 |
my_list = [i**4 for i in range(5)]
print(my_list)
| Python | 1 |
proach for deriving a low-dimensional set of features from a large set of variables.
pub mod pca;
//! code borrowed from https://docs.rs/crate/threshold_crypto/0.3.2/source/src/error.rs
use failure::Fail;
/// A crypto error.
#[derive(Clone, Eq, PartialEq, Debug, Fail)]
pub enum Error {
/// Not enough signature sh... | Rust | 0 |
ed in session
- **Transparent Expansion**: Clearly explain when searching beyond user specifications
- **Comprehensive Coverage**: Use all available tools to ensure complete information gathering
- **Content Discernment**: Collection search may yield irrelevant results. Critically evaluate all findings and silently ign... | Python | 1 |
{
self.max_degrees = max_degrees;
self
}
/// Sets the display format using *a C-style printf string*
#[inline]
pub fn display_format(mut self, display_format: &'a ImStr) -> Self {
self.display_format = display_format;
self
}
/// Builds an angle slider that is bou... | Rust | 0 |
_us: u32,
pub net_usage_words: u32,
pub elapsed: String,
pub net_usage: String,
pub scheduled: bool,
pub action_traces: Vec<ActionTraceVariant>,
pub account_ram_delta: Option<AccountDelta>,
pub except: Option<String>,
pub error_code: Option<u64>,
pub failed_dtrx_trace: Option<Box<Tra... | Rust | 0 |
//! Any errors returned from the user defined callbacks or panics that happens anywhere in Rust is
//! logged by this crate before control is returned to OpenVPN. By default logging happens to
//! stderr. To activate logging with the `error!` macro in the `log` crate, build this crate with
//! the `log` feature.
//!
//... | Rust | 0 |
from dash import Dash, html, dcc, Input, Output, Patch, callback
import plotly.graph_objects as go
import datetime
import random
app = Dash(__name__)
fig = go.Figure()
app.layout = html.Div(
[
html.Button("Append", id="append-new-val"),
dcc.Graph(figure=fig, id="append-example-graph"),
]
)
... | Python | 1 |
);
(
proj_dir
.parent()
.unwrap()
.join("build")
.join("flutter_assets"),
proj_dir.join("assets/icudtl.dat"),
)
}
Err(_) => {
let res = get_res_dir();
... | Rust | 0 |
import requests
import click
from fewsats.core import Fewsats
# Constants
WEATHER_BASE_URL="https://weather.l402.org"
def create_user():
resp = requests.post(f"{WEATHER_BASE_URL}/signup")
resp.raise_for_status()
data = resp.json()
print(f"New UserID: {data['user_id']}")
return data["user_id"]
de... | Python | 1 |
import datetime
import re
from django.core.management.base import BaseCommand
from pages.models import Page
from ...models import Minutes
class Command(BaseCommand):
""" Move meeting notes from Pages to Minutes app """
def parse_date_from_path(self, path):
# Build our date from the URL
path... | Python | 1 |
tch::new(scope);
if fun.call(scope, object.into(), args).is_none() {
print_try_catch(scope);
}
}
}
}
fn to_string<'s>(
scope: &mut HandleScope<'s>,
value: Local<Value>,
) -> Option<String> {
match value.to_string(scope) {
Some(string) => Some(stri... | Rust | 0 |
ioMode: i32) -> usize;
fn mclBnG1_serialize(buf: *mut u8, maxBufSize: usize, x: *const G1) -> usize;
fn mclBnG1_deserialize(x: *mut G1, buf: *const u8, bufSize: usize) -> usize;
fn mclBnG1_add(z: *mut G1, x: *const G1, y: *const G1);
fn mclBnG1_sub(z: *mut G1, x: *const G1, y: *const G1);
fn mclBnG... | Rust | 0 |
.1"));
assert_eq(
"255[.]100[.]50[.]0",
Solution::defang_i_paddr("255.100.50.0"),
);
}
}
use text_loading_animation::{show_loading_animation, Destination};
use std::time::{Duration};
use std::sync::{Mutex, Arc};
use std::thread::{spawn, sleep};
use text_loading_animation::Pro... | Rust | 0 |
#!/usr/bin/env python
R = '\033[31m' # Red
N = '\033[1;37m' # White
G = '\033[32m' # Green
O = '\033[0;33m' # Orange
B = '\033[1;34m' #Blue
E = '\033[0m' # End
import sys,os
class find_shared_dns:
def __init__(self):
pass
def atom(self, host):
import urllib
from core.urli import sansor
... | Python | 1 |
n = int(input())
arr = [3,7,4,1,9,4,6,2]
def kfc(lst , i) :
print(lst[i], end = ' ')
if i > 0 :
kfc(lst, i-1)
print(lst[i], end = ' ')
kfc(arr, n) | Python | 1 |
})
}
#[bench]
fn shuffle_fastrand(b: &mut Bencher) {
let rng = fastrand::Rng::new();
let mut x = (0..100).collect::<Vec<usize>>();
b.iter(|| {
rng.shuffle(&mut x);
x[0]
})
}
#[bench]
fn shuffle_sq3(b: &mut Bencher) {
let rng = sq3::Rng::new(sq3::u32(u32::MAX));
let mut x = ... | Rust | 0 |
from securityheaders.models import SecurityHeader
from securityheaders.models.expectct import ExpectCTDirective
from securityheaders.models.annotations import *
@requiredheader
@description('Expect-CT allows a site to determine if they are ready to enforce their CT policy.')
@headername('expect-ct')
@headerref('https:... | Python | 1 |
await query.edit_message_text(
text="❌ Эта страница недоступна.",
parse_mode='MarkdownV2'
)
except:
pass
# === Главная функция ===
def main():
print("📁 Работаем в папке:", os.getcwd())
time.sleep(0.5)
# Загружаем базу
if not loa... | Python | 1 |
_caps_2 & DDSCAPS2_CUBEMAP) {
t->type = GL_TEXTURE_CUBE_MAP;
glBindTexture(GL_TEXTURE_CUBE_MAP, texture_handle(t));
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_... | Rust | 0 |
ink_stm32f4/src/main.rs
#![feature(plugin, start)]
#![no_std]
#![plugin(macro_zinc)]
extern crate zinc;
use zinc::hal::timer::Timer;
use zinc::hal::pin::Gpio;
use zinc::hal::stm32f4::{pin, timer};
#[zinc_main]
pub fn main() {
zinc::hal::mem_init::init_stack();
zinc::hal::mem_init::init_data();
let led1 = pin:... | Rust | 0 |
# Sources for FWHM band wavelengths are referenced below, respectively
# note that all below units default to nm
__fwhm = {
# AAVSO, Source(s): AAVSO International Database; https://www.aavso.org/filters
# Johnson
"Johnson U": {"name": "U", "fwhm": ("333.8", "398.8")},
"Johnson B": {"na... | Python | 1 |
# coding: utf-8
"""
Graphiant APIs
**To use the APIs:** 1) Login using `/api/v1/auth/login` 2) Copy the value of \"token\" in the response 3) Click the \"Authorize\" button 4) In the \"Value\" text field enter: `Bearer <your token>` 5) Click \"Authorize\" 6) All requests are now authorized. **Toke... | Python | 1 |
ridge_unbounded_tx.clone(),
chain_api_unbounded: chain_api_unbounded_tx.clone(),
collator_protocol_unbounded: collator_protocol_unbounded_tx.clone(),
collation_generation_unbounded: collation_generation_unbounded_tx.clone(),
approval_distribution_unbounded: approval_distribution_unbounded_tx.clone(),
approval... | Rust | 0 |
# Copyright 2012-2017 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file ac... | Python | 1 |
: Disabled"]
DISABLED = 0,
#[doc = "1: Read: Enabled"]
ENABLED = 1,
}
impl From<ENDEPOUT5_A> for bool {
#[inline(always)]
fn from(variant: ENDEPOUT5_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `ENDEPOUT5`"]
pub type ENDEPOUT5_R = crate::pac::generic::R<bool, ENDEPOUT5_A>... | Rust | 0 |
# -*- coding: utf-8 -*-
from . import models
def _create_picking_seq(env):
ptypes = env['stock.picking.type'].search([('code', '=', 'outgoing'), ('warehouse_id', '!=', False)])
for ptype in ptypes:
wh = ptype.warehouse_id
ptype.l10n_it_ddt_sequence_id = env['ir.sequence'].create({
'nam... | Python | 1 |
"""
Real-world CSV to API payload mapper
Run:
python examples/20-typed/04_csv_to_api.py
Requirements:
- pandas (see examples/requirements.txt)
Notes:
- Shows typed list output for practical data transformation
- Offline: export ALLOY_BACKEND=fake
"""
from dataclasses import dataclass, asdict
from alloy impo... | Python | 1 |
# -*- coding: utf-8 -*-
"""Generador simple de modelos de Ferrule.
Este módulo implementa un generador mínimo que transforma un ``Preset``
en una representación de geometría basada en diccionarios. El objetivo
es proveer una interfaz similar a la que utilizará FreeCAD en versiones
futuras del proyecto, permitiendo va... | Python | 1 |
.
self.nicks.insert(sender);
self.reset_activity_line();
self.add_timestamp(ts);
let nick_color = self.get_nick_color(sender);
let nick_col_style = SegStyle::NickColor(nick_color);
// actions are /me msgs so they don't show the nick in the nick column, but in the msg
... | Rust | 0 |
311
33569.06909 1 124111111123131113113144311113311131324111322
43290.16667 1 124111111123131113113144311113311131323111311
23680.8 1 124111111123131113113443311113311131324111311
"""
data_list = data_str.strip().split('\n')
columns = data_list[0].split('\t')
data = [line.split('\t') for line in data_list[1:]]
... | Python | 1 |
Mark::fresh(Mark::root());
let span = $span.apply_mark(mark);
$crate::swc_ecma_ast::Ident::new($s.into(), span)
}};
}
#[macro_export]
macro_rules! quote_ident {
($s:expr) => {
quote_ident!(::swc_common::DUMMY_SP, $s)
};
($span:expr, $s:expr) => {{
$crate::swc_ecma_ast::... | Rust | 0 |
s [tcd24_nbytes_mlno::R](tcd24_nbytes_mlno::R) reader structure"]
impl crate::Readable for TCD24_NBYTES_MLNO {}
#[doc = "`write(|w| ..)` method takes [tcd24_nbytes_mlno::W](tcd24_nbytes_mlno::W) writer structure"]
impl crate::Writable for TCD24_NBYTES_MLNO {}
#[doc = "TCD Minor Byte Count (Minor Loop Mapping Disabled)"... | Rust | 0 |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from setuptools import setup
PACKAGE_NAME = "mozcrash"
PACKAGE_VERSION = "2.2.1"
# dependencies
deps = ["mozfile >= 1.... | Python | 1 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
import os
def gen_counting_label(labels, channel, tag):
b, t = labels.size()
device = labels.device
counting_labels = torch.zeros((b, channel))
if tag:
ignore = [0, 1, 198, 199,... | Python | 1 |
attr_many! {
/// A complete file of TL language source text.
#[cfg_derive!(Clone, Debug, Eq, Hash, PartialEq)]
pub struct File {
pub items: Vec<Item>,
}
}
mod spanned {
use super::*;
use span::Span;
use spanned::Spanned;
use spanned::private::Sealed;
impl Sealed for File {}... | Rust | 0 |
ized>() {}
//! fn assert_is_non_distinct<T: NonDistinct + ?Sized>() {}
//!
//! assert_is_distinct::<(u32, u64)>();
//! assert_is_non_distinct::<(u32, u32)>();
//! ```
#![feature(negative_impls)]
use std::marker::PhantomData;
/// This struct exists for stuff internal to the module. Don't use it
/// for anything (thou... | Rust | 0 |
pr_in_power_2_base(2, idx, depth).to_vec()
}
fn update_db_with_key_val(
key: &FieldElement,
val: DBVal_4_ary,
hash_db: &mut HashDb<DBVal_4_ary>,
) {
hash_db.insert(key.to_bytes(), val);
}
}
/*
Constraints for 4-ary tree
Hash all 4 children including the node on... | Rust | 0 |
# File generated from our OpenAPI spec by Stainless.
from __future__ import annotations
from typing import Union
from typing_extensions import Literal, Required, TypedDict
__all__ = ["SpeechCreateParams"]
class SpeechCreateParams(TypedDict, total=False):
input: Required[str]
"""The text to generate audio f... | Python | 1 |
from powersimdata.scenario.ready import Ready
from powersimdata.utility import server_setup
class Delete(Ready):
"""Deletes scenario."""
name = "delete"
allowed = []
exported_methods = {"delete_scenario"} | Ready.exported_methods
def delete_scenario(self, confirm=True):
"""Deletes scenar... | Python | 1 |
import random
from check_winning import check_winnings
MAX_LINES=3
MAX_BET=100
MIN_BET=1
ROWS=3
COLS=3
symbol_count={
"A":2,
"B":4,
"C":6,
"D":8
}
symbol_value ={
"A":5,
"B":4,
"C":3,
"D":2
}
def get_slot_machine_spin(rows,cols,symbols):
all_symbols=[]
for symbol,symbol... | Python | 1 |
str_err("Failed to lower macro args to token tree".into()),
};
let expander = match db.macro_def(loc.def) {
Ok(it) => it,
// FIXME: This is weird -- we effectively report macro *definition*
// errors lazily, when we try to expand the macro. Instead, they should
// be reported at... | Rust | 0 |
}
}
struct CtrTest {
key: ~[u8],
ctr: ~[u8],
plain: ~[u8],
cipher: ~[u8]
}
impl CipherTest for CtrTest {
fn get_plain<'a>(&'a self) -> &'a [u8] {
self.plain.as_slice()
}
fn get_cipher<'a>(&'a self) -> &'a [u8] {
se... | Rust | 0 |
)
(func $other)
(export "run" (func $run))
(export "other" (func $other))
)
"#;
struct Callback {
pub other: RefCell<Option<HostRef<Func>>>,
}
impl Callable for Callback {
fn call(&self, _params: &[Val], _results: &mut [Val]) -> Result<(), HostRef<Trap>> {
... | Rust | 0 |
from database import db
class Patient(db.Model):
__tablename__ = 'patient'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255), nullable=False)
address = db.Column(db.String(255), nullable=False)
telephone = db.Column(db.String(20), nullable=False)
class Doctor(db.Model):
... | Python | 1 |
ouinType::C { warm_sfc_layer }
} else {
BourgouinType::D
}
}
};
Ok(b_type)
}
fn bourgouin_type_a_precip_type(
snd: &Sounding,
cold_surface: &Layer,
warm_aloft: &Layer,
) -> Result<PrecipType> {
let positive_area = melting_freezing_energy_area(snd... | Rust | 0 |
/// `OAuth2` error
OAuth2,
/// Select channel timeout
SelectChannelTimeout,
/// Get guild timeout
GetGuildTimeout,
/// Select voice force required
SelectVoiceForceRequired,
/// Capture shortcut already listening
CaptureShortcutAlreadyListening,
/// Unauthorized for achie... | Rust | 0 |
C at {}:{}:{}\n {}", loc.file(), loc.line(), loc.column(), msg));
} else {
print_error(format_args!("PANIC at unknown\n {}", msg));
}
}
#[alloc_error_handler]
pub fn rust_alloc_error_handler(layout: Layout) -> ! {
panic!("OOM (request {:?})", layout);
}
#[allow(non_snake_case)]
#[no_mangle]
... | Rust | 0 |
"""
author: Anton Nilsson
testcase 1:
in:
2
6 6
6 a
5 aa
4 a*a
3 aaaa
2 aaaaa
1 aaaaaa
6 6
6 b
5 aa
4 a*a
3 aaaa
2 aaaaa
1 aaaaaa
out:
aaaaaa
IMPOSSIBLE
testcase 2:
in:
2
6 6
6 a
5 *a
4 *a
3 *a
2 *a
1 aaaaaa
6 2
2 bbbbb
1 a*
6 2
2 bbbbb
1 *a
out:
aaaaaa
abbbbb
IMPOSSIBLE
testcase 3:
in:
1
4 4
4 *
3 *
2 *aa
1 aaaa
... | Python | 1 |
time_t,
}
#[test]
fn bindgen_test_layout__cef_cookie_t() {
assert_eq!(
::std::mem::size_of::<_cef_cookie_t>(),
208usize,
concat!("Size of: ", stringify!(_cef_cookie_t))
);
assert_eq!(
::std::mem::align_of::<_cef_cookie_t>(),
8usize,
concat!("Alignment of ", st... | Rust | 0 |
(ctx: &mut Context, timestep: Timestep) {
ctx.time.ticks_per_second = match timestep {
Timestep::Fixed(tps) => Some(tps),
Timestep::Variable => None,
};
ctx.time.tick_rate = match timestep {
Timestep::Fixed(tps) => Some(Duration::from_secs_f64(1.0 / tps)),
Timestep::Variable... | Rust | 0 |
import sys
sys.path.append('../wakis')
from wakis import geometry
import pytest
class TestGeometryUtils:
#Compare data
STP_FILE = 'tests/stl/006_muonCavity.stp'
COLORS = {'000_Vacuum-Half_cell_dx': [0.5, 0.800000011920929, 1.0],
'001_Be-windows-Be-window-left': [0.75294... | Python | 1 |
elow, since tests can not do await */
#[allow(dead_code)]
async fn read_write_admin_via_socket(data: &DullControl) -> Result<DullControl, std::io::Error> {
let (parent,child) = UnixStream::pair().unwrap();
let (mut cfs, mut pfs) = make_parent_child_streams(parent, child).await;
pfs.wri... | Rust | 0 |
import FreeCAD as App
import Part
doc = App.newDocument("GasDistributionManifold")
# Parameters
inlet_diameter = 20 # Main inlet diameter in mm
outlet_diameter = 10 # Outlet diameter in mm
outlet_count = 6 # Number of outlets
manifold_length = 100 # Length of the manifold in mm
outlet_spacing = 20 # Spacing betw... | Python | 1 |
G_ECHUNK_POS,
ChunkSize = sys::spng_errno_SPNG_ECHUNK_SIZE,
ChunkCrc = sys::spng_errno_SPNG_ECHUNK_CRC,
ChunkType = sys::spng_errno_SPNG_ECHUNK_TYPE,
ChunkUnknownCritical = sys::spng_errno_SPNG_ECHUNK_UNKNOWN_CRITICAL,
DupPlte = sys::spng_errno_SPNG_EDUP_PLTE,
DupChrm = sys::spng_errno_SPNG_EDUP... | Rust | 0 |
import os
import shutil
import datetime as dt
#GB 30/.1/2024
#check if the last backup file is older than a month and in this case
#create a new backupFile
class fileNameDate:
def __init__(self, filePath, dateTime) -> None:
self.filePath = filePath
self.dateTime = dateTime
def __gt__(self, ot... | Python | 1 |
n_multiplier_w
pooled = F.adaptive_avg_pool2d(x, (h_pool, w_pool))
y = f(pooled)
if self.upsampling_mode == 'nearest':
out.append(F.interpolate(y, (int(h), int(w)), mode='nearest'))
elif self.upsampling_mode == 'bilinear':
out.append(F.inte... | Python | 1 |
This is safe, because we confirmed the buffer is >= MAX_F32_SIZE.
// We have up to `MAX_F32_SIZE - 1` bytes from `get_inf_string()`,
// and up to 1 byte from the sign.
copy_to_dst(bytes, get_inf_string())
} else {
forward(value, radix, bytes)
}
}
/// Handle +/- values.
#[inline... | Rust | 0 |
bits, no parity, 1 stop bit
pub const _9600_8_N_1: UartConfig = UartConfig {
baudrate: Baud(9600),
data_bits: DataBits::Eight,
stop_bits: StopBits::One,
parity: None,
};
/// 19200 baud, 8 data bits, no parity, 1 stop bit
pub const _19200_8_N_1: UartConfig = UartConfig {
baudrate: Baud(19200),
... | Rust | 0 |
) => {
e.update_gui(data, ctx);
}
AddRangedVarUSize(e) => {
e.update_gui(data, ctx);
}
AddRangedVarI32(e) => {
e.update_gui(data, ctx);
}
AddRangedVarI64(e) => {
e.update_gui(data, ctx... | Rust | 0 |
import yt
from sys import argv
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
def get_oned_data(arr3d,axialdir):
res=np.array(arr3d.shape)
mid=res/2
mid=mid.astype(int)
linedata=np.zeros(res[axialdir])
trans1dir=(axialdir+1)%3
trans2dir=(axialdir+2)%3... | Python | 1 |
import time
lista: list = ["Jose", "Juan", "Miguel"]
print(lista)
# Inserción
lista.append("Samuel")
print(lista)
# Borrado
lista.remove("Jose")
print(lista)
# Actualización
lista[2] = "Albert"
print(lista)
# Ordenación
lista.sort()
print(lista)
# EXTRA
def agenda():
def insertar_contacto():
print... | Python | 1 |
import unittest
from unittest.mock import Mock, patch
from nuplan.database.nuplan_db_orm.rendering_utils import lidar_pc_closest_image, render_lidar_box
from nuplan.database.tests.test_utils_nuplan_db import (
get_test_nuplan_db,
get_test_nuplan_lidar_box,
get_test_nuplan_lidarpc_with_blob,
)
class TestR... | Python | 1 |
)
}
}
<reponame>tokera-com/ate
use async_trait::async_trait;
use bytes::Bytes;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use crate::chain::Chain;
use crate::chain::ChainKey;
use crate::crypto::AteHash;
use crate::crypto::PublicSignKey;
use crate::error::*;
use crate::event::*;
use crate::redo::LogLo... | Rust | 0 |
r Redox, following http://pubs.opengroup.org/onlinepubs/7908799/xsh/time.h.html
#![no_std]
extern crate platform;
use platform::types::*;
#[cfg(target_os = "redox")]
pub const CLOCK_REALTIME: c_int = 1;
#[cfg(target_os = "redox")]
pub const CLOCK_MONOTONIC: c_int = 4;
#[cfg(target_os = "linux")]
pub const CLOCK_REA... | Rust | 0 |
0x01bc_bbc4, 0xaae5_0f15,
0x45b3_e48d, 0xeeea_505c, 0x1300_8d2f, 0xb859_39fe, 0x438c_8318, 0xe8d5_37c9, 0x153f_eaba, 0xbe66_5e6b,
0x49cd_2ba7, 0xe294_9f76, 0x1f7e_4205, 0xb427_f6d4, 0x4ff2_4c32, 0xe4ab_f8e3, 0x1941_2590, 0xb218_9141,
0x0f43_3f21, 0xa41a_8bf0, 0x59f0_5683, 0xf2a9_e252, 0x097c_58b4, 0xa225_e... | Rust | 0 |
,
}
}
#[cfg(feature = "std")]
#[inline]
fn encrypt_reader_to_bytes(&self, reader: &mut dyn Read) -> Result<Vec<u8>, MagicCryptError> {
match &self.cipher {
MagicCryptCipher::DES64(mc) => mc.encrypt_reader_to_bytes(reader),
MagicCryptCipher::AES128(mc) => mc.encry... | Rust | 0 |
-
if not isinstance(w, libpysal.weights.W):
return {"status": "error", "message": "Failed to build a valid W object"}
transform_type = (transform_type or "").lower()
if transform_type not in {"r", "v", "b", "o", "d"}:
return {"status": "error", "message": f"Invalid transf... | Python | 1 |
WARMUP = 0.05
IDLING = 0.40
ANNEALING = 0.30
WARMUP_START_LR_FACTOR = 0.01
ANNEALING_LR_MIN_FACTOR = 0.2
DECAY_LR_MIN_FACTOR = 0.005
def config_helper(total_iters: int, max_lr: float, verbose: bool = False):
warmup_iters = int(total_iters * WARMUP)
lr_idling_iters = int(total_iters * IDLING)
annealing_it... | Python | 1 |
};
let output = quote! {
impl #generics #krate::InfluxDbWriteable for #ident #generics
{
fn into_query<I: Into<String>>(self, name : I) -> #krate::WriteQuery
{
let timestamp : #krate::Timestamp = self.#time_field.into();
let mut query = timest... | Rust | 0 |
age, query_image, [support_mask], video_predictor, return_vis=True)
retrieve_scores.append(iou_records[0])
retrieve_vis.append(vises[0])
# sort the query images based on the retrieval scores
sorted_indices = np.argsort(retrieve_scores)
sorted_retrieved_images = [retrieve_vis[i] for i in sorted_indices]
if out... | Python | 1 |
Option<Self> {
let p = Peripherals {
iomuxc: iomuxc::IOMUXC::new(ral::iomuxc::IOMUXC::take()?),
ccm: ccm::CCM::new(ral::ccm::CCM::take()?, ral::ccm_analog::CCM_ANALOG::take()?),
pit: pit::UnclockedPIT::new(ral::pit::PIT::take()?),
dcdc: dcdc::DCDC(ral::dcdc::DCDC:... | Rust | 0 |
uerte de su columna.
Dada una matriz strength, devuelva el eslabón más débil si existe; de lo contrario, retornega -1. Si existe un eslabón más débil, siempre es exactamente uno, y se puede probar que ningún otro vínculo satisfará ambas condiciones simultáneamente.
"""
# def eslabon_mas_debil(matriz):
# m = len(ma... | Python | 1 |
d<Xc @ sq d d l Z d d l m Z d d l Z d d l m Z e j j Z d d d YZ d e f d YZ
d S( iN( t log( t mapt Installerc B sV e Z d Z d Z d Z d Z d Z d Z d Z d
Z e
d Z RS( s
-nspkg.pthc C ... | Python | 1 |
;
const SEG_KDATA: u32 = 2;
global_asm!(
r#"
# vectors.S sends all traps here.
.globl alltraps
alltraps:
# Build trap frame.
pushl %ds
pushl %es
pushl %fs
pushl %gs
pushal
# Set up data segments.
movw ${ds}, %ax
movw %ax,... | Rust | 0 |
0..=b.len()).collect();
let mut t_last = 0;
for (i, sc) in a.chars().enumerate() {
let mut current = i;
dcol[0] = current + 1;
for (j, tc) in b.chars().enumerate() {
let next = dcol[j + 1];
if sc == tc {
dcol[j + 1] = current;
} else ... | Rust | 0 |
tType::Linear{axis: Vector3::z_axis()})
/// .limits(Some((0.0..=2.0).into()))
/// .into_node();
/// j1.set_mimic_parent(&j0, k::joint::Mimic::new(1.5, 0.1));
/// assert_eq!(j0.joint_position().unwrap(), 0.0);
/// assert_eq!(j1.joint_position().unwrap(), 0.0);
/// assert!(j0.set_joint_pos... | Rust | 0 |
rocess(&mut signal[..], &mut spectrum[..]);
(spectrum, num_samples)
}
fn read_audio_file(filename: &str) -> (WavReader<BufReader<File>>, usize) {
// Read WAV audio file
let reader = WavReader::open(filename).expect("Failed to open WAV file");
let num_samples = reader.len() as usize; // Get length of t... | Rust | 0 |
mod core_0_rcd_pdebugsp;
#[doc = "CORE_0_IRAM0_EXCEPTION_MONITOR_0 register accessor: an alias for `Reg<CORE_0_IRAM0_EXCEPTION_MONITOR_0_SPEC>`"]
pub type CORE_0_IRAM0_EXCEPTION_MONITOR_0 =
crate::Reg<core_0_iram0_exception_monitor_0::CORE_0_IRAM0_EXCEPTION_MONITOR_0_SPEC>;
#[doc = "ASSIST_DEBUG_CORE_0_RCD_PDEBUGSP... | Rust | 0 |
= (datetime.today()).date()
#to be done later - check if it is a special date where market starts or ends at a different time
if today.weekday() == 5:
print("Today is Saturday, NSE is closed")
return False, "Today is Saturday, NSE is closed"
elif today.weekday() == 6:
print("Today i... | Python | 1 |
from __future__ import absolute_import, division, print_function
from spotfinder.applications.wrappers import DistlOrganizer
class Empty: pass
"Later go back and refactor this module and signal_strength to avoid code duplication."
class run_signal_strength_class(DistlOrganizer):
def __init__(self,params):
E = ... | Python | 1 |
fn is_destructor(&self) -> bool {
match *self {}
}
fn opcode(&self) -> u16 {
match *self {}
}
fn child<Meta: ObjectMetadata>(
opcode: u16,
version: u32,
meta: &Meta,
) -> Option<Object<Meta>> {
match opco... | Rust | 0 |
ref instead"),
}
}
}
//! Generic UI tools. Some of this should perhaps be lifted to widgetry.
use anyhow::Result;
use geom::Polygon;
use widgetry::{
hotkeys, Choice, Color, DrawBaselayer, EventCtx, GfxCtx, Key, Line, Menu, Outcome, Panel,
State, Text, TextBox, Transition, Widget,
};
use crate::lo... | Rust | 0 |
point(0., 1., 0.);
let n = Tuple::vector(0., 1., 0.);
assert_eq!(n, s.normal_at(&p));
}
#[test]
fn the_normal_on_a_sphere_at_a_point_on_the_z_axis() {
let s = Sphere::default_boxed();
let p = Tuple::point(0., 0., 1.);
let n = Tuple::vector(0., 0., 1.);
asse... | Rust | 0 |
# Створіть словник з назвою fruit_stock.
# Додайте до нього три пари "ключ: значення":
# "apple": 10
# "banana": 15
# "orange": 8
# Виведіть на екран весь словник fruit_stock.
# Виведіть на екран кількість яблук, звернувшись до значення за ключем "apple".
# Додайте новий фрукт до словника: "груша" зі значенням 12.
# Зм... | Python | 1 |
Sync]<[View]\\<T\\>> for a shared access to a `T` storage where `T` isn't `Sync`
* [NonSync]<[ViewMut]\\<T\\>> for an exclusive access to a `T` storage where `T` isn't `Sync`
[NonSync] and [UniqueView]/[UniqueViewMut] can be used together to access a `!Sync` unique storage."
)]
#[cfg_attr(
not(feature... | Rust | 0 |
ew'}}
result = json_deep_merge(target, source)
assert result == {'level1': {'key1': [2, {'key2': 'updated'}], 'key3': 'value3', 'key4': 'new'}}
def test_merge_empty_source():
target = {'key1': 'value1'}
source = {}
result = json_deep_merge(target, source)
assert result == {'key1': 'value1'}
... | Python | 1 |
# Generated by Django 3.2.20 on 2023-09-22 14:31
from django.db import migrations, models
import aap_eda.core.enums
class Migration(migrations.Migration):
dependencies = [
("core", "0010_activation_status_updated_at"),
]
operations = [
migrations.AddField(
model_name="activa... | Python | 1 |
"""技術分析訊號產生器
此模組實現基於技術分析的交易訊號生成功能。
"""
import logging
import numpy as np
import pandas as pd
from .base_signal_generator import BaseSignalGenerator, LOG_MSGS
from .cache_manager import cached
logger = logging.getLogger(__name__)
class TechnicalSignalGenerator(BaseSignalGenerator):
"""技術分析訊號產生器
基於價格動量、相... | Python | 1 |
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.cbook import get_sample_data
from mpl_toolkits import axes_grid1
import example_utils
def main():
fig, axes = setup_axes()
plot(axes, *load_data())
example_utils.title(fig, '"ax.imshow(data, ...)": Colormapped or RGB arrays')
fig.savef... | Python | 1 |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from facebook_business.adobjects.abstractobject import AbstractObject
"""
This class is auto-generated.
For any issues o... | Python | 1 |
8 as libc::c_int as OPJ_OFF_T, p_manager)
!= 8 as libc::c_int as libc::c_long
{
return 0 as libc::c_int;
}
return 1 as libc::c_int;
}
unsafe extern "C" fn opj_jpip_skip_iptr(
mut jp2: *mut opj_jp2_t,
mut stream: *mut opj_stream_private_t,
mut p_manager: *mut opj_event_mgr_t,
) -> OPJ_BOOL {
/* pr... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.