text string | label_name string | labels int64 |
|---|---|---|
):
return DFS_NAME
@classmethod
def metric_components(cls):
return [DFS_PRECISION_RETRIEVED, DFS_RECALL_RELEVANT, DFS_RELEVANT_RETRIEVED]
def __init__(self, collar=0.0, skip_overlap=False, beta=1.0, **kwargs):
super(DetectionPrecisionRecallFMeasure, self).__init__(**kwargs)
... | Python | 1 |
import os
from datetime import datetime
import requests
from bs4 import BeautifulSoup
from openpyxl import Workbook
from snownlp import SnowNLP
import jieba
from collections import Counter
import jieba.posseg as pseg
import json
import urllib.request
# 确定保存文本格式用的。
def get_formatted_time():
"""
获取格式化后的当前时间
... | Python | 1 |
async fn handle_describe_tenant(
&self,
req: DescribeTenantRequest,
) -> Result<DescribeTenantResponse> {
let db = self.master.tenant(&req.name).await?;
let desc = db.desc().await;
Ok(DescribeTenantResponse { desc: Some(desc) })
}
}
impl Server {
async fn handl... | Rust | 0 |
######################################################################
# BioSimSpace: Making biomolecular simulation a breeze!
#
# Copyright: 2017-2023
#
# Authors: Lester Hedges <lester.hedges@gmail.com>
#
# BioSimSpace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Pub... | Python | 1 |
wReqImpl> FwReqImplExt for T {
fn parent_responded(&self, req: &FwReq, rcode: FwRcode, frame: &[u8]) {
unsafe {
let data = T::type_data();
let parent_class = data.as_ref().parent_class() as *mut ffi::HinawaFwReqClass;
let f = (*parent_class)
.responded
... | Rust | 0 |
9, 20580, 1300, 25650, 45)
ChrSetPos(0x000A, 22800, 1300, 23640, 45)
ChrSetRGBAMask(0x0008, 255, 255, 255, 0, 0)
ChrSetRGBAMask(0x0009, 255, 255, 255, 0, 0)
ChrSetRGBAMask(0x000A, 255, 255, 255, 0, 0)
ChrClearFlags(0x0008, 0x0080)
ChrClearFlags(0x0009, 0x0080)
ChrClearFlags(0x000A, 0x0080)
... | Python | 1 |
from pyrogram import Client, filters
API_ID = "23472307"
API_HASH = "15311dad78288ffec031dc8b8b717c21"
BOT_TOKEN ="6946934155:AAFx4VojSkQyTf6sx8lvhbsC8U-2Wb_yEok"
Animelist = Client(
name="Aniume-bot",
api_id=API_ID,
api_hash=API_HASH,
bot_token=BOT_TOKEN
)
@Aniumelist.on_message(filters.comman... | Python | 1 |
acer, TracerProvider},
};
use serde_json::{json, Value};
use std::collections::{HashMap, HashSet};
use std::convert::Infallible;
use std::net::SocketAddr;
use std::path::Path;
use std::time::{Duration, SystemTime};
use tower::BoxError;
#[tokio::test(flavor = "multi_thread")]
async fn test_jaeger_tracing() -> Result<()... | Rust | 0 |
|i: &isize| *i >= 0,
OwnedNode::Decision(gt_zero_decision),
OwnedNode::Decision(lt_negative_10_decision),
));
tree_asserts(tree);
}
fn tree_asserts(tree: Decision<isize, TestAnswer>) {
assert!(matches!(tree.decide(&-50), TestAnswer::LessThanNegativeTen)... | Rust | 0 |
not skip next instruction if Vx == kk" {
let mut processor = Processor::new();
processor.V[0x1] = 0xAA;
processor.execute_opcode(0x41AA, &PRESSED_KEYCODES);
assert_eq!(processor.pc.get_current(), ADDRESS_NEXT);
}
test "5xy0 - skip next instruction if V... | Rust | 0 |
# Copyright 2023 Garena Online Private Limited
#
# 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 required by applicable law or agre... | Python | 1 |
import conftest
from PathPlanning.BezierPath import bezier_path as m
def test_1():
m.show_animation = False
m.main()
def test_2():
m.show_animation = False
m.main2()
if __name__ == '__main__':
conftest.run_this_test(__file__)
| Python | 1 |
arType::All)))
}
fn size(&self) -> io::Result<Rect> {
let (width, height) =
terminal::size().map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string()))?;
Ok(Rect::new(0, 0, width, height))
}
fn flush(&mut self) -> io::Result<()> {
self.buffer.flush()
}
}
... | Rust | 0 |
rmat="application/pdf",
source="RECAP",
creator=doc_court_name,
publisher="Free Law Project",
extra=doc_metadata,
)
# push to s3
document.to_s3()
# increm... | Python | 1 |
ck_max"] = True
refresh_track_max(obj[name])
else:
obj[name]["track_max"] = False
if track_str is not None:
if '.' not in track_str:
A = int(track_str)
rank = A
zb_str = "111111"
else:
A, B = track_str.sp... | Python | 1 |
# Launch the standalone instance manager as a separate process (hidden console)
subprocess.Popen([sys.executable, manager_path],
cwd=app_dir,
creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0,
stdout=s... | Python | 1 |
sae: i32,
) -> __mmask16 {
macro_rules! call {
($imm5:expr, $imm4:expr) => {
vcmpps(a.as_f32x16(), b.as_f32x16(), $imm5, m as i16, $imm4)
};
}
let r = constify_imm5_sae!(op, sae, call);
transmute(r)
}
/// Compare packed single-precision (32-bit) floating-point elements i... | Rust | 0 |
import pytest
import secp256k1
def test_schnorr_simple():
if not secp256k1.HAS_SCHNORR:
pytest.skip('secp256k1_schnorr not enabled, skipping')
return
inst = secp256k1.PrivateKey()
raw_sig = inst.schnorr_sign(b'hello')
assert inst.pubkey.schnorr_verify(b'hello', raw_sig)
key2 = se... | Python | 1 |
from policyengine_us.model_api import *
class mo_qualified_health_insurance_premiums(Variable):
value_type = float
entity = Person
label = "Missouri qualified healh insurance premiums"
unit = USD
definition_period = YEAR
reference = (
"https://dor.mo.gov/forms/5695.pdf", # MO Form 569... | Python | 1 |
-rfc5549"): {
"eos_data": [
{
"vrfs": {
"default": {
"peerList": [
{"peerAddress": "10.111.0.1", "ttl": 3, "maxTtlHops": 3},
{"peerAddress": "fe80::250:56ff:fe01:112%Vl4094", "ttl": 2,... | Python | 1 |
=> Ok(RelroLevel::None),
_ => Err(()),
}
}
}
impl ToJson for RelroLevel {
fn to_json(&self) -> Json {
match *self {
RelroLevel::Full => "full".to_json(),
RelroLevel::Partial => "partial".to_json(),
RelroLevel::Off => "off".to_json(),
... | Rust | 0 |
::model::*;
use crate::util::common::*;
use ActionType::*;
// [App]
pub struct EngineApp {
seed: u64,
mode: usize,
n_game: u32,
n_thread: u32,
write_to_file: bool,
gui_port: u32,
debug: bool,
names: [String; SEAT], // actor names
}
impl EngineApp {
pub fn new(args: Vec<String>) ->... | Rust | 0 |
er;
self.e[1] *= other;
self.e[2] *= other;
}
}
impl std::ops::DivAssign<Vec3> for Vec3 {
fn div_assign(&mut self, other: Vec3) {
self.e[0] /= other.e[0];
self.e[1] /= other.e[1];
self.e[2] /= other.e[2];
}
}
impl std::ops::DivAssign<f32> for Vec3 {
fn div_assig... | Rust | 0 |
xB0D0_B88A),
(r"textures\tx_secunda_one_wan.dds", 0x5806_062E, 0xB0D0_E08A),
(r"textures\tx_wicker_brown_02.dds", 0x5806_0A2A, 0x3162_1FAF),
(r"textures\tx_rock_cave_mo_01.dds", 0x5806_0C2F, 0x0EC9_463A),
(r"textures\tx_rock_diamond_01.dds", 0x5806_0C2F, 0x5F69_97DA),
(r"textures\tx_rock_cave_m... | Rust | 0 |
USER_PRIV_GUEST: DWORD = 0;
pub const USER_PRIV_USER: DWORD = 1;
pub const USER_PRIV_ADMIN: DWORD = 2;
pub const MAX_PASSWD_LEN: DWORD = PWLEN;
pub const DEF_MIN_PWLEN: DWORD = 6;
pub const DEF_PWUNIQUENESS: DWORD = 5;
pub const DEF_MAX_PWHIST: DWORD = 8;
pub const DEF_MAX_PWAGE: DWORD = TIMEQ_FOREVER;
pub const DEF_M... | Rust | 0 |
1# -*- coding: utf-8 -*-
import numpy as np
from sklearn import preprocessing
from scipy.linalg import qr
model_names = ['model/inception-v3/feat_v3_6crop2',
'model/21k/feat_21k_6',
'model/fb.resnet.torch/pretrained/features101',
'color',
'/mnt/disk/da... | Python | 1 |
(all_accuracies, axis=(1, 2))
std_accuracies = np.std(all_accuracies, axis=(1, 2))
mean_accuracies[0] = np.amax(mean_accuracies[0])
std_accuracies[0] = 0
mean_accuracies[1] = np.max(mean_accuracies[1])
std_accuracies[1] = 0
n_algo, n_runs, n_clients, n_rounds = all_accuracies.shape
x = np.arange(n_rounds)
cmap = plt... | Python | 1 |
OKE),
}
} else {
match kind {
UIPointType::GPHandle => (HANDLE_FILL, HANDLE_STROKE),
UIPointType::Point((GPHandle::At(_, _), GPHandle::Colocated))
| UIPointType::Point((GPHandle::Colocated, GPHandle::At(_, _))) => {
(POINT_ONE_FILL, POINT_ONE_STROK... | Rust | 0 |
caller, it would mean there's a bug in the framework resolution algorithm.
FrameworkCompatRetry = 0x8000809d, // -2147450723
/// Error reading the bundle footer metadata from a single-file `apphost`. This would mean a corrupted `apphost`.
AppHostExeNotBundle = 0x8000809e, // -2147450722
/// Error extra... | Rust | 0 |
"""
https://levelup.gitconnected.com/method-resolution-order-in-python-5afbaecc25e0 C3 mro algorithm
C3 MRO algorithm
MRO(A) = A + merge(L(Parent1), L(Parent2), ..., L(ParentN), Parent1, Parent2, ..., ParentN)
merge:
- Check HEAD of L(Parent1) - it would be Parent1
- IF HEAD doesn't appear in any tail of L(P... | Python | 1 |
(',').for_each(|p| {
let input = p.trim().split(' ').collect::<Vec<_>>();
let n = input[0].parse::<usize>().unwrap();
let input = input[1];
e.1.push((input, n));
});
});
g
}
fn part2(g: &Graph) -> usize {
const TOTAL: usize = 1000000000000;
let mu... | Rust | 0 |
out("r3") _,
options(nostack, preserves_flags),
)
}
#[repr(C)]
pub struct ObjAffineSetSrc {
/// 8-bit fraction
pub scale_ratio_x: i16,
/// 8-bit fraction
pub scale_ratio_y: i16,
/// 8-bit fraction, range 0 to u16::MAX
pub angle: u16,
}
/// (`swi 0x0F`) Calculates OBJ affine data.
///
/// Unlike with... | Rust | 0 |
ops::Add::add)
}
}
/// Implement arithmetic operations.
macro_rules! ops_impl {
($($t:ident, $meth:ident ;)*) => ($(
impl<T: Float> ops::$t for WrappedFloat<T> {
type Output = Self;
#[inline]
fn $meth(self, other: Self) -> Self::Output {
WrappedFloa... | Rust | 0 |
i32;
#[doc = "*Required features: `\"Win32_Security_Cryptography_Certificates\"`*"]
pub const XCN_OID_ENROLL_ATTESTATION_STATEMENT: CERTENROLL_OBJECTID = 436i32;
#[doc = "*Required features: `\"Win32_Security_Cryptography_Certificates\"`*"]
pub const XCN_OID_ENROLL_ENCRYPTION_ALGORITHM: CERTENROLL_OBJECTID = 437i32;
#[... | Rust | 0 |
= xrecover(y)
if x & 1 != bit(s, b - 1):
x = q - x
P = [x, y]
if not isoncurve(P):
raise Exception("decoding point that is not on curve")
return P
def checkvalid(s, m, pk):
if len(s) != b // 4:
raise Exception("signature length is wrong")
if len(pk) != b // 8:
... | Python | 1 |
(|s|
if s.status.success() {
let version = run_cmd.output().ok().and_then(|o| String::from_utf8(o.stdout).ok());
Ok(CargoCommandVersioned::new(
cargo_command,
version.unwrap_or_else(|| "unknown rustc version".into()),
))
} else {
match String::from_utf8(s.stderr) {
Ok(ref err) if er... | Rust | 0 |
4xx::gpioa::GPIOA;
#[cfg(feature = "stm32f4xx")]
use ili9486::io::stm32f4xx::gpiob::GPIOB;
#[cfg(feature = "stm32f4xx")]
use ili9486::io::stm32f4xx::gpioc::GPIOC;
use ili9486::{Command, Commands, ILI9486};
extern crate panic_semihosting;
use cortex_m_rt::entry;
#[cfg(feature = "stm32f4xx")]
use stm32f4xx_hal::{
... | Rust | 0 |
x = torch.cat([x1 * cos - x2 * sin, x2 * cos + x1 * sin], dim=1)
return x
def forward(self, length: int) -> torch.Tensor:
"""Compute rotary relative position bias.
Args:
length: Sequence length.
Returns:
bias: Rotary relative position bias. (L, L)
... | Python | 1 |
b_memory_usage/free'))
},
'temperature':
{
'gpu': create_value_and_unit(gpu_element.findtext('temperature/gpu_temp')),
'memory': create_value_and_unit(gpu_element.findtext('temperature/memory_temp'))
},
'utilization':
{
'gpu': create_value_and_unit(gpu_element.findtext('utilization/gpu_uti... | Python | 1 |
<i32> }
/// }
/// ```
///
/// ### Derive macro attributes
///
/// There are a number of field attributes available for use with `derive(Data)`.
///
/// - **`#[data(ignore)]`**
///
/// Skip this field when computing `same`ness.
///
/// If the type you are implementing `Data` on contains some fields that are
/// not rele... | Rust | 0 |
91cf9df6cfd8bd225fd3f46ba2f3f33809d0ee2e7ad338448b4ece7b4f622"),
);
// Invalidate witness
witness[5][0] += PallasField::one();
// gates[0] is RangeCheck0
assert_eq!(
cs.gates[0].verify_range_check(0, &witness, &cs),
Err(String::from(
"Inv... | Rust | 0 |
from fastapi import FastAPI
from api import login, attendance, gym
app = FastAPI()
app.include_router(login.router, prefix='/ch05')
app.include_router(attendance.router, prefix='/ch05')
app.include_router(gym.router, prefix='/ch05')
| Python | 1 |
::default(),
Shell::Unknown,
Target::Main,
child_dir_path.clone(),
child_dir_path,
);
assert_eq!(
find_rust_toolchain_file(&context),
Some("1.34.0".to_owned())
);
dir.close()?;
// `rust-toolcha... | Rust | 0 |
o
g
@ sL d dl mZmZ d dlmZ d dlmZ G dd deZG dd deZdS ) )IntegerAlias)Relation)Serialisablec @ s e Zd ZdZe Zdd ZdS )SheetBackgroundPicturepicturec C s
|| _ d S N)id)selfr r kC:\... | Python | 1 |
;
//const TEST_HEX_STRING: &str = "..#.#..#####.#.#.#.###.##.....###.##.#..###.####..#####..#....#..#..##..###..######.###...####..#..#####..##..#.#####...##.#.#..#.##..#.#......#.###.######.###.####...#.##.##..#..#..#####.....#.#....###..#.##......#.....#..#..#..##..#...##.######.####.####.#.#...#.......#..#.#.#...##... | Rust | 0 |
#!/usr/bin/env python
# Copyright (c) 2020 PaddlePaddle Authors. 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
#
# U... | Python | 1 |
class Solution:
# Constant space solution
def setZeroes(self, matrix):
first_row = reduce(lambda acc, i: acc or matrix[0][i] == 0, range(len(matrix[0])), False)
first_col = reduce(lambda acc, i: acc or matrix[i][0] == 0, range(len(matrix)), False)
for i in range(1, len(matrix)):
... | Python | 1 |
import sys
node = []
left = []
right = []
# simple funciton to display stacks side-by-side
def displayStacks():
maxLen = len(node)
if len(left) > maxLen: maxLen = len(left)
if len(right) > maxLen: maxLen = len(right)
print("# | N | L | R")
print("-------------")
for loop in range(... | Python | 1 |
(measurement, timestamp, tag, fields=['__value']*len(values), values=values)
def _write_point(self, measurement, timestamp, tag, fields, values):
point = self.Point(measurement)
if timestamp is not None:
if type(timestamp) in [ float, int ]:
... | Python | 1 |
42..43 'b': bool
42..48 'b = !b': ()
46..48 '!b': bool
47..48 'b': bool
"###);
}
#[test]
fn invalid_unary_ops() {
insta::assert_snapshot!(infer(
r#"
fn bar(a: f64, b: bool) {
a = !a; // mismatched type
b = -b; // mismatched type
}
"#),
@r###"
35..3... | Rust | 0 |
Returns:
list[Book]: A list of Book objects that are available.
"""
books = self.db.query(Book).filter(Book.available == True).offset(skip).limit(limit).all()
return books
def borrow_book(self, book_id: int, user_id: int):
"""
Marks a book as borrowed by a use... | Python | 1 |
},
],
})
}
pub fn get_spacex_launch_name_kvstore() -> KeyValueSource {
KeyValueSource::new(
"spacex_launch_name",
test_data_path("spacex_launches.json"),
"id",
"name",
)
}
use git2::{BranchType, Commit, Repository, Revwalk};
use std::error;
pub mod diffs;
p... | Rust | 0 |
always)]
pub fn ep_dma_dis11(&mut self) -> EP_DMA_DIS11_W {
EP_DMA_DIS11_W { w: self }
}
#[doc = "Bit 12 - Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx."]
#[inline(always)]
pub fn ep_dma_dis12(&mut self) -> EP_DMA_DIS12_W... | Rust | 0 |
}
#[doc = "Bits 9:10 - GPIO34 output configuration."]
#[inline(always)]
pub fn gpio34outcfg(&mut self) -> GPIO34OUTCFG_W {
GPIO34OUTCFG_W { w: self }
}
#[doc = "Bit 8 - GPIO34 input enable."]
#[inline(always)]
pub fn gpio34incfg(&mut self) -> GPIO34INCFG_W {
GPIO34INCFG_W... | Rust | 0 |
"total_time": total_time
})
return results
def icmp_traceroute(target_ip):
"""ICMP 跟踪路由(并行版本,主机名解析与下一跃点并行)"""
results = []
previous_ip = None
hostname_futures = {} # 存储主机名解析的futures
logger.debug(f"开始 ICMP 跟踪路由(并行版本): 目标={target_ip}")
with ThreadPoolExecutor() as hostname_executor... | Python | 1 |
decVal: Il2CppWin32Decimal,
_bindgen_union_align: [u64; 3usize],
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct Il2CppVariant__bindgen_ty_1___tagVARIANT {
pub type_: u16,
pub reserved1: u16,
pub reserved2: u16,
pub reserved3: u16,
pub n3: Il2CppVariant__bindgen_ty_1___tagVARIANT__bindgen_ty_1,
}... | Rust | 0 |
import json
import os
import pandas as pd
from src import DATA_FOLDER, UNZIPED_FOLDER_NAME
from src.io import CNAE_JSON_NAME, NATJU_JSON_NAME, QUAL_SOCIO_JSON_NAME, MOTIVOS_JSON_NAME, PAIS_JSON_NAME, \
MUNIC_JSON_NAME
from src.io.get_last_ref_date import main as get_last_ref_date
def main(ref_date=None):
re... | Python | 1 |
dim_in,
bbox_regr_dim * A,
3,
pad=1,
stride=1,
weight='retnet_bbox_pred_fpn{}_w'.format(k_min),
bias='retnet_bbox_pred_fpn{}_b'.format(k_min)
)
def add_fpn_retinanet_losses(model):
loss_gradients = ... | Python | 1 |
;
use amethyst_test::AmethystApplication;
use asset_model::{loaded::ItemId, play::ItemIdEvent};
use asset_play::ItemIdEventSystem;
#[test]
fn attaches_handle_and_sends_event_for_item_id_insertions() -> Result<(), Error> {
run_test(
|world| create_entity(world, None),
... | Rust | 0 |
Error> {
let auth = authenticate(id, server_config).await?;
match auth {
RoleGuard::Admin { user } | RoleGuard::Regular { user } => {
let code = data.code.clone();
info!("Creating link for: {}", &code);
let new_link = NewLink::from_link_delta(data, user.id);
... | Rust | 0 |
import os
import torch
import numpy as np
import json
def listify_matrix(matrix):
matrix_list = []
for row in matrix:
matrix_list.append(list(row))
return matrix_list
def convert_json(src_dir, src_json_name, dst_json_name, device='cpu'):
with open(os.path.join(src_dir, src_json_name)) as f:
... | Python | 1 |
s的所有权已经转移到了函数内部
// println!("s = {}", s); // ^ value borrowed here after move 这里不能再使用了
let s2 = takes_and_give_back(s);
println!("s2 ={}", s2);
let mut s = String::from("hello");
println!("s len = {}", cal_len(&s));
change(&mut s);
// 对于可变引用 在同一时间只能有一个对某一特定数据的可变引用。
// 这些尝试创建两个 s 的可变引用的... | Rust | 0 |
})", contextidr, vsvc_get_curpid_name());
}
println!("----");
println!("");
smmu_print_err();
}
pub fn print_exception(ec: u8, iss: u32, ctx: &[u64], ret_addr_in: u64) -> u64
{
let mut ec_unk = false;
let mut iss_unk = true;
let mut is_dabt = false;
let mut is_dabt_lower = tru... | Rust | 0 |
ode::SrcOut |
BlendMode::DestAtop |
BlendMode::Multiply |
BlendMode::Screen |
BlendMode::HardLight |
BlendMode::Overlay |
BlendMode::ColorDodge |
BlendMode::ColorBurn |
BlendMode::SoftLight |
BlendMode::Differenc... | Rust | 0 |
uid::Uuid;
use engine_lmdb::raw::{
PrimaryCausetNetworkOptions, DBEntryType, BlockPropertiesCollector, BlockPropertiesCollectorFactory,
};
use engine_lmdb::raw_util::{new_engine, CausetOptions};
use std::sync::Arc;
pub use engine_lmdb::LmdbEngine as TestEngine;
pub const PROP_TEST_MARKER_Causet_NAME: &[u8] = b"e... | Rust | 0 |
#!/usr/bin/env python
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
"""
Upload code coverage reports to codecov.io.
Multiple coverage files from multiple languages are accept... | Python | 1 |
from aws_cdk import aws_s3, RemovalPolicy, Tags, aws_kms
from constructs import Construct
class BaselineS3Bucket(aws_s3.Bucket):
def __init__(
self,
scope: Construct,
id: str,
access_control=aws_s3.BucketAccessControl.PRIVATE,
block_public_access=aws_s3.BlockPublicAccess.BL... | Python | 1 |
# Copyright The OpenTelemetry Authors
#
# 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 required by applicable law or agreed to in ... | Python | 1 |
print('*** Compresion de Listas ***')
# Una lista con el cuadrado de cada numero
numeros = [1, 2, 3, 4, 5]
cuadrados = [x**2 for x in numeros]
print(cuadrados)
# Lista de numeros pares
numeros = range(10+1)
pares = [x for x in numeros if x % 2 == 0]
print(pares)
# Lista saludando a cada nombre
nombres = ['Ana', 'Jer... | Python | 1 |
import ipaddress
from dataclasses import dataclass
@dataclass
class Address:
host: ipaddress.IPv4Address | ipaddress.IPv6Address
port: int
@property
def host_str(self):
return str(self.host)
@property
def tuple(self):
return self.host_str, self.port
@property
def con... | Python | 1 |
let u8_ptr = self.data.as_ptr() as *mut u8;
let u8_slice = unsafe {
std::slice::from_raw_parts(u8_ptr, slice_size)
};
self.webgl.buffer_sub_data_with_i32_and_u8_array(WebGl2RenderingContext::ARRAY_BUFFER, offset, u8_slice);
self.dirty_range = Range::empty();
}
... | Rust | 0 |
! 很多流行的程序库使用红黑树作为自平衡二叉搜索树的内部实现,例如STL,AVL树同样也可以直观、高效
//! 地解决平衡问题。
//!
//! 如下tree,是一棵正确的rb tree,而不是一棵正确的avl tree
//!
//! https://www.cs.usfca.edu/~galles/visualization/RedBlack.html
//!
//! 输入序列: [100, 150, 50, 125, 114, 107]
//!
//! B(100)
//! / \
//! B(50) R(125)
//! / \
//! B(114) B(150)
//! ... | Rust | 0 |
; CAN_FRAME_SIZE] = [ 3, 2, 1, 0, 7, 6, 5, 4 ];
#[derive(Copy,Clone)]
pub enum CanID {
One = 0,
Two = 1,
Three = 2,
}
pub enum CanReturn {
Success { ret: usize },
DataLost,
InvalidMsgBox,
WrongBufferSize,
PendingMessages,
}
macro_rules! valid_mbox {
($mbox: expr) => { $m... | Rust | 0 |
.style(match app.focused {
Widget::LogGroupsResults => Style::default().fg(Color::Yellow),
_ => Style::default(),
})
.borders(Borders::ALL)
.title("results"),
);
frame.render_widget(messages, chunks[1]);
status_bar::draw(app, f... | Rust | 0 |
import pandas as pd
msg = pd.read_csv('document.csv', names=['message', 'label'])
print("Total Instances of Dataset: ", msg.shape[0])
msg['labelnum'] = msg.label.map({'pos': 1, 'neg': 0})
X = msg.message
y = msg.labelnum
from sklearn.model_selection import train_test_split
Xtrain, Xtest, ytrain, ytest = train_test_spl... | Python | 1 |
dump for mismatched symbols")
parser.add_option('--out-orig', action='store',
help="result output file for original library", metavar="ORIGFILE")
parser.add_option('--out-new', action='store',
help="result output file for new library", metavar="NEWFILE")
parser.add_option('--dwarfdum... | Python | 1 |
#!/usr/bin/env python3
from roop import core
if __name__ == '__main__':
core.run()
| Python | 1 |
22\x22\x22\x22\x22\x22\x22\x22\x22\
\xca\x0ce\xf7\x05\x10\xd1\xe0XSW\xe7\xf1vu\x1d\
\x0c\x97k\x82\x05\x8c\xd3Z\x0fQ\x96U\x0ec\xca\x01\
\x94C)\x1f\xb4\xee\x02\xd0\x0a\x00P\xea=\x00o\x1b\
\xe0\x1d\x00[\x5c@\x12\xa9\xd4\xfah2\xd9b\xe3\x9f\
AD\x83\x84\x05\x00Q\x8eX_W7$\x9dJ\x1d\
\xa9\x80#\x8dR3a\xcc$\x00\xee\x01\xfe\xb3\x0... | Python | 1 |
());
(z * Funcs::legendre(z, i) - Funcs::legendre(z, i - 1)) * f
}
fn gamma(mut self) -> Self {
let ha = Self::from_f32(0.5).unwrap();
let on = Self::from_i8(1).unwrap();
let fh = Self::from_f32(7.5).unwrap();
let lan = Self::from_f64(2.5066282746310005024157652848110452... | Rust | 0 |
import os
import os.path as osp
import argparse
from tqdm import tqdm
from glob import glob
import skimage
import cv2
import numpy as np
from TorchTools.ArgsTools.base_args import BaseArgs
from TorchTools.Metrics import cal_ssim, cal_freqgain, cal_fsim, freqgain
def main():
gt_list = sorted(glob(osp.join(args.... | Python | 1 |
oc = "Bits 8:11 - ACD_C bias"]
#[inline(always)]
pub fn bias_7_iq_bb_1(&self) -> BIAS_7_IQ_BB_1_R {
BIAS_7_IQ_BB_1_R::new(((self.bits >> 8) & 0x0f) as u8)
}
#[doc = "Bits 4:7 - ACD_O bias"]
#[inline(always)]
pub fn bias_6_iq_bb_0(&self) -> BIAS_6_IQ_BB_0_R {
BIAS_6_IQ_BB_0_R::new... | Rust | 0 |
}
}
/*******************************************************************************
* DMA controller supplementary operations.
*/
impl Dma {
/// Clears a set of interrupt flags for a particular stream.
///
/// This winds up writing one of the two `ifcr` registers, but is more
/// convenient t... | Rust | 0 |
# coding: utf-8
"""
Brevo API
Brevo provide a RESTFul API that can be used with any languages. With this API, you will be able to : - Manage your campaigns and get the statistics - Manage your contacts - Send transactional Emails and SMS - and much more... You can download our wrappers at https://git... | Python | 1 |
# Basana
#
# Copyright 2022 Gabriel Martin Becedillas Ruiz
#
# 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 required by applicable l... | Python | 1 |
STOPPED(*status) {
exit_code = WSTOPSIG(*status) as usize;
break;
}
}
}
};
}
// TODO: Use the real exit code
ShellStatus::Run(exit_code)
}
<reponame>casey/fuchsia<filename>src/developer/fastboot/src/reply... | Rust | 0 |
from .observer import Observer
from .logging_observer import LoggingObserver
from .visualization_observer import VisualizationObserver
from .subject import Subject | Python | 1 |
import argparse
import xml.etree.ElementTree as ET
def build_hierarchy(node, path=""):
"""Recursively build the tag hierarchy."""
current_path = f"{path}/{node.tag}" if path else node.tag
hierarchy = {}
# Process all child nodes
for child in node:
child_tag = child.tag
if child... | Python | 1 |
# Copyright (c) 2020 Huawei Technologies Co.,Ltd.
#
# openGauss is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#
# http://license.coscl.org.cn/MulanPSL2
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS... | Python | 1 |
def merge_sort(arr_):
arr = arr_[:]
if len(arr) <= 1:
return arr
mid = len(arr) //2
left_half = arr[:mid]
right_half = arr[mid:]
return merge(merge_sort(left_half), merge_sort(right_half))
def merge(left, right):
merged = []
left_index = 0
right_index = 0
# Об'єдн... | Python | 1 |
import torch
import torch.nn as nn
import torch.nn.functional as F
class DoubleConv(nn.Sequential):
def __init__(self, in_channel, out_channel, mid_channel=None):
if mid_channel == None:
mid_channel =out_channel
super(DoubleConv, self).__init__(
nn.Conv2d(in_channels=in_chan... | Python | 1 |
import json
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.patches import FancyBboxPatch
import numpy as np
from datetime import datetime
import os
# 设置中文字体和学术风格
plt.rcParams['font.sans-serif'] = ['SimHei', 'Times New Roman']
plt.rcParams['axes.unicode_minus'] = False
plt.style.us... | Python | 1 |
s/{id}")
assert user_job["state"] == "finished"
assert "User deleted job" in user_job["status_info"].values()
def test_delete_api_endpoint(auth_client):
site = create_site(auth_client, name="polaris")
bjob = auth_client.post(
"/batch-jobs/",
site_id=site["id"],
project="datasci... | Python | 1 |
from django.core.management.base import BaseCommand
from optparse import make_option
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--addrport', action='store', dest='addrport',
type='string', default='',
help='port number or ipaddr:port to run t... | Python | 1 |
Err> {
match s {
"Monday" => Ok(Monday),
"Tuesday" => Ok(Tuesday),
"Wednesday" => Ok(Wednesday),
"Thursday" => Ok(Thursday),
"Friday" => Ok(Friday),
"Saturday" => Ok(Saturday),
"Sunday" => Ok(Sunday),
_ => Err(error:... | Rust | 0 |
e(13)));
let c = gr_inds.count();
assert_eq!(c, 4);
}
let e2 = gr_inds_iter.size_hint();
assert_eq!(e2, (0, Some(0)));
// make sure the reverse iterator does the right thing with "\n" at beginning of string
let s = "\n\r\n\r";
let gr = UnicodeSegmentation::graphemes(s, true)
... | Rust | 0 |
# main.py
import json
import psutil
from platform import uname
from flask import Blueprint, render_template
from flask_login import login_required, current_user
main = Blueprint('main', __name__)
@main.route('/')
def index():
return render_template('index.html')
@main.route('/profile')
@login_required
def profi... | Python | 1 |
: 1 }),
Poll::Pending,
Poll::Ready(VecDiff::Clear {}),
]);
let output = input.sum();
util::assert_signal_eq(output, vec![
Poll::Ready(Some(0)),
Poll::Ready(Some(15)),
Poll::Pending,
Poll::Ready(Some(28)),
Poll::Ready(Some(19)),
Poll::Pending,... | Rust | 0 |
from dataclasses import dataclass, field
from whad.hub.phy import Endianness
@dataclass
class FSKConfiguration:
"""
Configuration for FSK modulation.
:param deviation: select the modulation deviation (dev)
"""
deviation : int = 500000
@dataclass
class LoRaConfiguration:
"""
Configuration ... | Python | 1 |
a', 'el': 'Νότια Αλτάι', 'el-polyton': 'Νότια Αλτάι', 'en': 'Southern Altai', 'es': 'altái meridional', 'et': 'altai', 'eu': 'hegoaldeko altaiera', 'fa': 'آلتایی جنوبی', 'ff-Adlm': '𞤀𞤤𞤼𞤢𞤴𞤪𞤫 𞤙𞤢𞥄𞤥𞤲𞤢𞥄𞤲𞤺𞤫𞤲𞤳𞤮𞥅𞤪𞤫', 'fi': 'altai', 'fil': 'Southern Altai', 'fo': 'suður altai', 'fr': 'altaï du Sud', 'fy':... | Python | 1 |
let now = Instant::now();
let image = if settings.multithreading {
let image_ = Arc::new(Mutex::new(ImageBuffer::new(settings.image_width as u32, settings.image_height as u32)));
let world_ = Arc::new(world);
let camera_ = Arc::new(camera);
let settings_ = Arc::new(settings);
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.