text string | label_name string | labels int64 |
|---|---|---|
expected_output = {
"vlanid":{
101:{
"received":{
"arp":{
"REQ":357478,
"REP":937
}
},
"received_broadcast_multicast":{
"arp":{
"REQ":19
}
... | Python | 1 |
import boto3
from logging_config import logger
from state_manager import StateManager
state_manager = StateManager()
def cleanup_spot_requests():
ec2_client = boto3.client('ec2')
response = ec2_client.describe_spot_instance_requests(Filters=[{'Name': 'state', 'Values': ['open', 'active']}])
requ... | Python | 1 |
if isinstance(value, int):
self.floors += value
return self
# Пример использования
h1 = House('ЖК Эльбрус', 10)
h2 = House('ЖК Акация', 20)
print(h1) # Название: ЖК Эльбрус, кол-во этажей: 10
print(h2) # Название: ЖК Акация, кол-во этажей: 20
# Сравнение
print(h1 == h2) # False
# Увелич... | Python | 1 |
#!/usr/bin/env python3
""" Module imports task 3 to perform more tasks """
import asyncio
import random
from typing import List
task_wait_random = __import__("3-tasks").task_wait_random
async def task_wait_n(n: int, max_delay: int) -> List[float]:
""" displays function"""
delays = []
tasks = [task_wait_... | Python | 1 |
a scope with the given name and push it onto the stack of scopes. It will be manually assigned as a child of the given parent scope.
pub fn enter_with_parent(&mut self, name: &'static str, parent: &ScopeId) -> (Guard, ScopeId) {
let id = self.new_id(name, Some(parent));
self.enter_with_id(name, id)... | Rust | 0 |
full of source code.
// #[allow(clippy::case_sensitive_file_extension_comparisons)]
// #[allow(dead_code)]
// fn is_immediate(&self, file_path: &Path) -> bool {
// file_path
// .file_name()
// .unwrap()
// .to_str()
// ... | Rust | 0 |
_NAME, MarketType::InverseFuture, raw_msg, None).unwrap()[0];
assert_eq!(orderbook.asks.len(), 3);
assert_eq!(orderbook.bids.len(), 3);
assert!(orderbook.snapshot);
assert_eq!(orderbook.timestamp, 1646480395477);
assert_eq!(orderbook.seq_id, Some(21312965));
crate::util... | Rust | 0 |
{
$scorer(&line).map(|(score, indices)| (line.into(), score, indices))
})
})
};
}
// Generate an filtered iterator from Source::List(list).
macro_rules! source_iter_list {
( $scorer:ident, $list:ident ) => {
$list.filter_map(|line| $scorer(&line).map(|(s... | Rust | 0 |
natives::None,
"CSS" => TagAlternatives::Css,
tags => TagAlternatives::Tags(
tags.split(" or ").map(|v|
v.trim()
.trim_start_matches('<')
.trim_end_matches('>')
.to_string()
... | Rust | 0 |
G16F,
R16G16B16_SFLOAT = __gl::RGB16F,
R16G16B16A16_SFLOAT = __gl::RGBA16F,
R32_SFLOAT = __gl::R32F,
R32G32_SFLOAT = __gl::RG32F,
R32G32B32_SFLOAT = __gl::RGB32F,
R32G32B32A32_SFLOAT = __gl::RGBA32F,
// signed integer formats
R8_SINT = __gl::R8I,
R8G8_SINT = __gl::RG8I,
R8G8B8_... | Rust | 0 |
le {}
impl Pack for UniswapOracle {
const LEN: usize = 139;
fn unpack_from_slice(src: &[u8]) -> Result<Self, ProgramError> {
let src = array_ref![src, 0, 139];
let (is_initialized, authority, token0, decimal0, amount0, token1, decimal1, amount1) =
array_refs![src, 1, 32, 20, 1, 32, 2... | Rust | 0 |
se),
weight=default_weight_observer)
else:
qconfig = default_qconfig
return qconfig
def get_default_qat_qconfig(backend='fbgemm'):
# Histogram observer is too slow for quantization aware training
if backend == 'fbgemm':
qconfig = QConfig(activation=FakeQuantize... | Python | 1 |
n = int(input())
x, y = 1, 1
plans = input().split()
dx = [0, 0, -1, 1]
dy = [-1, 1, 0, 0]
direction = ['L', 'R', 'U', 'D']
for plan in plans:
for i in range(len(direction)):
if plan == direction[i]:
nx = x + dx[i]
ny = y + dy[i]
if nx > n or ny > n or nx < 1 or ny < 1:... | Python | 1 |
,').collect();
for column in 0..size_x {
let position = tiles[column].parse::<i32>().unwrap();
let y = position / 10;
let x = position % 10;
map.push(Tile {
texture_sheet: "assets/terrain_ss.png",
... | Rust | 0 |
.id))
.ok().expect("error retaining event");
}
Event{ id: self.id }
}
}
use clap::{Command, IntoApp, Parser, Subcommand};
use clap_complete::{generate, Generator, Shell};
use imgurs::ImgurClient;
use std::io::{self, stdout};
use crate::cli::{credits::*, delete_image::*, info_image:... | Rust | 0 |
import asyncio
import socket
from typing import Any, Callable, Optional
import pycares
class DNSResolver:
def __init__(self, loop: Optional[asyncio.AbstractEventLoop] = None) -> None:
# Use event_thread=True for automatic event handling in a separate thread
self._channel = pycares.Channel(event_t... | Python | 1 |
if event.type == meteor_spawn:
Meteor((meteor_sprites, all_sprites), meteor_surface)
if event.type == death_event.type:
AnimatedExplosion(all_sprites,explosion_surfaces,player.rect.center)
explosion_sound.play()
player.death()
pygame.time.set_timer(py... | Python | 1 |
}
Ok(())
}
async fn launch_container(engine: &mut LxdSandboxEngine) -> Result<()> {
trace!(".. launching new container");
engine.client.launch(&engine.config.image, &engine.config.container).await?;
Ok(())
}
async fn forward_ssh_agent(engine: &mut LxdSandboxEngine) -> Result<()> {
trace!("... | Rust | 0 |
placa = str(input("Placa do veículo: "))
nome = str(input("Nome do motorista: "))
vm = int(input("Velocidade registrada: "))
vmp = int(input("Velocidade máxima permitida: "))
multa = input("O motorista ja foi multado antes? (Sim/Não): ").lower()
pm = input("Deseja pagar a multa agora? (Sim/Não): ").lower()
if(vm <= vm... | Python | 1 |
from .mtv import MTVServicesInfoExtractor
class ComedyCentralIE(MTVServicesInfoExtractor):
_VALID_URL = r'https?://(?:www\.)?cc\.com/(?:episodes|video(?:-clips)?|collection-playlist|movies)/(?P<id>[0-9a-z]{6})'
_FEED_URL = 'http://comedycentral.com/feeds/mrss/'
_TESTS = [{
'url': 'http://www.cc.c... | Python | 1 |
import numpy as np
from typing import Any
def PLA(X: np.ndarray[Any, Any], y: np.ndarray[int], w0: np.ndarray[Any], epoch_num: int, lr=0.1) -> np.ndarray[Any]:
# augmentation
X = np.insert(X, 0, 1, axis=1)
assert len(X[0]) == len(w0), "Dimension Mismatch!"
for epoch in range(epoch_num):
if_wro... | Python | 1 |
"""
https://github.com/wandergis/coordTransform_py/blob/master/coordTransform_utils.py
"""
import math
from math import pi
a = 6378245.0 # 长半轴
ee = 0.00669342162296594323 # 偏心率平方
x_pi = pi * 3000.0 / 180.0
def wgs84_to_gcj02(lng, lat):
"""
WGS84转GCJ02(火星坐标系)
:param lng:WGS84坐标系的经度
:param lat:WGS84坐... | Python | 1 |
);
f(&mut w);
self.register.write(w.bits);
}
}
# [ derive ( Clone , Copy ) ]
# [ repr ( C ) ]
pub struct S4ndtrR {
bits: u32,
}
impl S4ndtrR {
# [ doc = "Bits 0:15 - Number of data items to transfer" ]
pub fn ndt(&self) -> u16 {
const MASK: u32 = 65535;
const OFFSET: u8... | Rust | 0 |
from django.shortcuts import render
from sistema.models import Usuario
def listarUsuarios(request):
usuarios = Usuario.objects.all()
context = {
'usuarios': usuarios,
}
return render(
request,
'usuarios/listar.html',
context,
) | Python | 1 |
找到。
INVALIDPARAMETERVALUE_LAUNCHTEMPLATENOTFOUND = 'InvalidParameterValue.LaunchTemplateNotFound'
# 无效的实例启动模板版本号。
INVALIDPARAMETERVALUE_LAUNCHTEMPLATEVERSION = 'InvalidParameterValue.LaunchTemplateVersion'
# 参数值数量超过限制。
INVALIDPARAMETERVALUE_LIMITEXCEEDED = 'InvalidParameterValue.LimitExceeded'
# 本地盘的限制范围。
INVALIDPAR... | Python | 1 |
OCI_TYPEMETHOD_PIPELINED = 32768,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum OCITypeParamMode {
OCI_TYPEPARAM_IN = 0,
OCI_TYPEPARAM_OUT = 1,
OCI_TYPEPARAM_INOUT = 2,
OCI_TYPEPARAM_BYREF = 3,
OCI_TYPEPARAM_OUTNCPY = 4,
OCI_TYPEPARAM_INOUTNCPY = 5,
}
#[repr(C)]
#[de... | Rust | 0 |
static ref IBM_13125_P100_1997: Encoding = parse_ucm(&request_mapping_file("ibm-13125_P100-1997").unwrap()).unwrap();
}
lazy_static! {
pub static ref IBM_13140_P101_2000: Encoding = parse_ucm(&request_mapping_file("ibm-13140_P101-2000").unwrap()).unwrap();
}
lazy_static! {
pub static ref IBM_13143_P101_2000: E... | Rust | 0 |
e(1)
CMD_HELP.update(
{
"kingmemes": "⚡𝘾𝙈𝘿⚡`.eye`\
\nUsage: Lihat Sendiri.\
\n\n⚡𝘾𝙈𝘿⚡`.earth`\
\nusage: Memutar Bumi 🌎🌎\
\n\n⚡𝘾𝙈𝘿⚡`.bombs`\
\nUsage: Bom Telegram🤣🤣\
\n\n⚡𝘾𝙈𝘿⚡`.think`\
\nUsage: hmmm berpikir\
\n\n⚡𝘾𝙈𝘿⚡`.gotm` atau ⚡𝘾𝙈𝘿⚡`.gott`\
\nUsage: dapatkan sucks🤣\
\n\n⚡𝘾𝙈𝘿⚡`... | Python | 1 |
er() == symbol.upper():
asset_quote = quote_data[key]
symbol = key # Update symbol to the matched key
break
if not asset_quote:
logger.warning(colored(f"No quote data found for {symbol}", "yellow"))
ret... | Python | 1 |
one)]
pub union pthread_mutex_t {
pub __data: __pthread_mutex_s,
pub __size: [::std::os::raw::c_char; 40usize],
pub __align: ::std::os::raw::c_long,
_bindgen_union_align: [u64; 5usize],
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union pthread_cond_t {
pub __data: __pthread_cond_s,
pub __size: [::st... | Rust | 0 |
;
// Check the proof for every element.
for &(idx, value) in &test_vector[..] {
let merkle_proof = tree.merkle_path(idx);
let hasher = TestHasher::default();
// To check the proof, we fold it starting from the hash of the value
// and updating with the ... | Rust | 0 |
#!/usr/bin/env python3
from markdown import Markdown
import unittest
class MathTestCase(unittest.TestCase):
def verify(self, mkd_name, html_name, config=None):
config = config or dict()
md = Markdown(extensions=['mdx_math'], extension_configs={'mdx_math': config})
with open('test_data/%s.m... | Python | 1 |
# Code generated by Lark OpenAPI.
from typing import Any, Optional, Union, Dict, List, Set, IO, Callable, Type
from lark_oapi.core.construct import init
class BatchCreateAuthorizationApplicationRecordPermissionMemberRequestBody(object):
_types = {
"user_ids": List[str],
}
def __init__(self, d=No... | Python | 1 |
, msg: untrusted::Input,
signature: untrusted::Input,
) -> Result<(), Error> {
let spki = parse_spki_value(spki_value)?;
if !signature_alg
.public_key_alg_id
.matches_algorithm_id_value(spki.algorithm_id_value)
{
return Err(Error::UnsupportedSignatureAlgorithmForPublicKey);
}... | Rust | 0 |
修改FSINFO
self.fsinfo
.write_free_clusters(free_clusters - num, self.block_device.clone());
// 写入分配的最后一个簇
self.fsinfo
.write_first_free_cluster(current_cluster, self.block_device.clone());
self.cache_write_back();
Some(first_cluster)
}
pub fn deal... | Rust | 0 |
int ('Press Q to quit')
status_keys = [key[0] for key in status.keys()]
print ('%-8s%-8s%-8s%s' % ('Mode', 'value', 'step', 'message'))
print_status(status)
publish_status(node, broadcaster, status)
while True:
kk = getch()
status['message'] = ''
try:
key_idx = s... | Python | 1 |
me'].str.contains(r'\d', regex=True, na=False)]
all_sections_df = expand_sections(all_sections_df)
all_sections_df = get_course_code(all_sections_df, tfm_courses_df)
parent_product_df = get_course_parent(all_sections_df, config, headers_365)
# Recuperamos los ids de los tutores para cad... | Python | 1 |
import pytest
from src.tg_client import TgClient
from src.tg_websocket import TgServer
import time
@pytest.fixture
async def websocket_server():
print("start...........aflk;a;jdf;alkdjfa;lkj")
server = TgServer(8080)
print("HELLLLLLLLLLLLOOOOOOOOOOOOOOOOOOOOOOOO")
await server.start()
yield server
... | Python | 1 |
d
should NOT have any embedded variables expanded, nor should it
have complete graphite URLs in the queries.
"""
dashboard = database.DashboardRecord.query.get_or_404(id)
# Validate the payload
definition = DashboardDefinition.from_json(json.loads(request.data.decode('utf-8')))
if dashboa... | Python | 1 |
t MESH_GROUP_KNIGHT: MeshGroup = MeshGroup(&[
Entry(GlobalMesh::Knight1, -0.2, 0., 0.9, 0.2, 0.2, 0.2),
Entry(GlobalMesh::Knight2, -0.2, 0., 0.9, 0.2, 0.2, 0.2),
]);
const MESH_GROUP_ROOK: MeshGroup =
MeshGroup(&[Entry(GlobalMesh::Rook, -0.1, 0., 1.8, 0.2, 0.2, 0.2)]);
const MESH_GROUP_PAWN: MeshGroup =
... | Rust | 0 |
{
static mut EVERY_10:u32 = 0;
let go = unsafe {EVERY_10==9};
unsafe {EVERY_10+=1};
if go {
let future = future.join(sync::now(device.clone()));
state_ignore.previous_frame_end = Some(future.... | Rust | 0 |
% 4 == 0 {
cards_each = i;
break;
}
}
for suit in &suits {
for i in 0..(discard / 4) {
deck.remove(
deck.iter()
.position(|(s, n)| (s, n) == (suit, &(i as i32)))
.... | Rust | 0 |
_>) -> core::fmt::Result {
formatter.write_str("field identifier")
}
fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
match value {
0u64 => Ok(Field::Ids),
... | Rust | 0 |
################################################################################
# The Neural Network (NN) based Speech Synthesis System
# https://svn.ecdf.ed.ac.uk/repo/inf/dnn_tts/
#
# Centre for Speech Technology Research
# ... | Python | 1 |
$super:ident, no) => {
pub fn add_to_subset(fun: &mut super::Function, id: Id) -> bool {
let obj = fun.$super[&id].clone();
fun.$name.insert(id, obj).is_none()
}
define_ir!(@create_def struct $name, @, $super, no);
};
(@create_def type $name:ident, $param:ident,... | Rust | 0 |
B) -> Acc,
) -> impl FnMut(Acc, T) -> Acc {
move |acc, elt| g(acc, f(elt))
}
impl<'f, R, I, F> Iterator for MapProducer<'f, I, F>
where
I: Iterator,
F: Fn(I::Item) -> R,
{
type Item = R;
fn size_hint(&self) -> (usize, Option<usize>) {
self.base.size_hint()
}
fn next(&mut self) -> O... | Rust | 0 |
t self.items:
return
message = {
"type":"item",
"refresh": True,
"diff": diff,
"items": [],
}
items = self.items
if diff:
items = [item for item in items if item.diff != 0]
if not items:
return
... | Python | 1 |
pub struct Set<'a> {
pred: Box<Fn(f64) -> bool + 'a>
}
impl<'a> Set<'a> {
pub fn new<P>(pred: P) -> Set<'a>
where P: Fn(f64) -> bool + 'a {
Set {
pred: Box::new(pred)
}
}
pub fn contains(&self, el: f64) -> bool {
(self.pred)(el)
}
pub fn union(first: &... | Rust | 0 |
ive()
elif choice == "3":
run_enhanced_component_test()
elif choice == "4":
show_window_troubleshooting()
elif choice == "5":
install_simulation_deps()
elif choice == "6":
print("\n👋 Thank you for using Enha... | Python | 1 |
.try_for_each(|it| output_sender.send(it))
.unwrap()
},
)
}
// Copyright 2018 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the S... | Rust | 0 |
vice logical block size, the smallest unit the device can address.
///
/// This is usually 512
pub fn logical_block_size(&self) -> Result<u64> {
fs::read_to_string(self.path.join("queue/logical_block_size"))?
.trim()
.parse::<u64>()
.map_err(|_| Error::Invalid)
... | Rust | 0 |
PhantomData<B>,
}
}
impl<S, B> Future for CompressResponse<S, B>
where
B: MessageBody,
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
{
type Output = Result<ServiceResponse<EitherBody<Encoder<B>>>, Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self... | Rust | 0 |
"""
Aggregate per‑split TSVs
"""
from pathlib import Path
import pandas as pd, numpy as np, re, sys, os, shutil
out_generic = Path(snakemake.output.summary)
out_tagged = Path(snakemake.output.tagged)
in_fps = [Path(p) for p in snakemake.input]
frames = []
rx = re.compile(r"metrics_k(\d+)\.tsv$")
for fp in in_fp... | Python | 1 |
from app.account_generator import generate_account_json, remove_sec_ch_ua
from app.proxy_changer import update_proxy_settings
from app.proxy_checker import check_proxies_menu
from app.utils import print_title, print_error, custom_style, print_banner, initialize_files, clear_screen
import questionary
import sys
def mai... | Python | 1 |
)
}
}
impl<T, F> ArrayGenerate<F> for [T; $n]
where F: $fn_trait() -> T
{
fn generate(mut f: F) -> Self {
[$(replace_ident!($i => f()),)*]
}
}
impl<T> ArrayRepeat<T> for [T; $n... | Rust | 0 |
oop::ClassKind::TypeArray(_) => unimplemented!(),
}
}
ValueType::VOID => unreachable!(),
}
name
}
use itertools::Itertools;
use std::collections::HashMap;
use std::io::Read;
use std::path::PathBuf;
use walkdir::WalkDir;
pub(crate) fn filter_path(path: impl AsRef<st... | Rust | 0 |
ual(len(maxs), len(maps))
for map_, max_, min_ in zip(maps, maxs, mins):
assert_allclose(map_["data"].max(), max_, rtol=5e-2)
assert_allclose(map_["data"].min(), min_, rtol=5e-2)
# calculated from correct looking mapping on 2015/12/26
assert_allclose(
np.sqrt(np.sum(maps[0]["data"] *... | Python | 1 |
from abc import abstractmethod
from confluent_kafka import Consumer
import sys
from confluent_kafka.error import KafkaError, KafkaException
class DefaultConsumer():
def __init__(self, conf: dict, subscriptions: list):
self.conf = conf
self.consumer = self.build_consumer()
self.running = Tru... | Python | 1 |
on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use std::ffi::CString;
use crate::command::flyweight::Flyweight;
use crate::concurrent::atomic_buffer::AtomicBu... | Rust | 0 |
an.bold()),
LsColors::parse_style("36;01"));
assert_eq!(Some(Colour::Red.normal()),
LsColors::parse_style("31;00"));
}
#[test]
fn test_parse_256() {
assert_eq!(Some(Colour::Fixed(115).normal()),
LsColors::parse_style("38;5;115"));
assert_eq!(Some(Colour::Fixed... | Rust | 0 |
drawer
.draw_windows(&*self.window_map.borrow(), self.compositor_token, &self.logger);
}
fn error(&mut self, _device: &mut DrmDevice<Card>, error: DrmError) {
panic!("{:?}", error);
}
}
<gh_stars>0
// Copyright 2020-2021 <NAME>
// SPDX-License-Identifier: Apache-2.0
// #![deny(missing_... | Rust | 0 |
> Self {
GAIN_CTRL7_GC_RBB1_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for GAIN_CTRL7_GC_RBB1_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `gain_ctrl7_gc_rbb1` writer - "]
pub struct GAIN... | Rust | 0 |
B_I;
let mut t0 = self.getpx();
t0.mul(&Q.x); // x.Q.x
let mut t1 = self.getpy();
t1.mul(&Q.y); // y.Q.y
let mut t2 = self.getpz();
t2.mul(&Q.z);
let mut t3 = self.getpx();
t3.add(&self.y);
t3.norm(); //t3=X1+Y1
let mut t4 = Q.getpx();
... | Rust | 0 |
import random
class RockPaperScissors:
def __init__(self):
self.choices = ["rock", "paper", "scissors"]
self.player_score = 0
self.computer_score = 0
def play(self, player_choice):
# Randomly select the computer's choice
computer_choice = random.choice(self.choices)
... | Python | 1 |
import json
from typing import Iterable
import jsonlines
import os
def read_jsonl(path):
content = []
with jsonlines.open(path, "r") as json_file:
for obj in json_file.iter(type=dict, skip_invalid=True):
content.append(obj)
return content
def save_answers(
queries: Iterable, ... | Python | 1 |
#-----------------------------------------------------------------------------
# Copyright (c) 2021-2023, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License (version 2
# or later) with exception for distributing the bootloader.
#
# The full license is in the file COPYING.txt... | Python | 1 |
JPNL",
"JPNS",
"JPW",
"LXFT",
"NSTG",
"CDW",
"MWRX",
"PETX",
"SAMG",
"TRMR",
"BXSpA.CL",
"DXJS",
"DXPS",
"FULLL",
"IDOG",
"KCGw",
"NDLS",
"OXLCO",
"RNA",
"TRBC",
"EMDG",
"FOXA",
"ORAN",
"ORM",
"CLACW",
"OUTR",
"TRCB",
"VNRAP",
"BACpJ.CL",
"CLAC",
"S.WD",
"ON... | Rust | 0 |
essarily the preferred granularity. In IOMMUs which make use of page tables, it may be
//! possible to share a set of page tables between different groups, reducing the overhead both to
//! the platform (reduced TLB thrashing, reduced duplicate page tables), and to the user
//! (programming only a single set of transla... | Rust | 0 |
c_uint = 0x8E8C;
pub const COMPRESSED_RGBA_BPTC_UNORM_ARB: c_uint = 0x8E8C;
pub const COMPRESSED_RGBA_FXT1_3DFX: c_uint = 0x86B1;
pub const COMPRESSED_RGBA_S3TC_DXT1_EXT: c_uint = 0x83F1;
pub const COMPRESSED_RGBA_S3TC_DXT3_EXT: c_uint = 0x83F2;
pub const COMPRESSED_RGBA_S3TC_DXT5_EXT: c_uint = 0x8... | Rust | 0 |
[np.array([1, 0, 0]), np.array([0, 1, 0]), np.array([0, 0, 1])]]
for rv in np.transpose(rot_vectors):
coords.append(rotate_coord(coords[0], rv))
return coords
def rotate_coord(coord0, rotation_vector):
coord = []
for c0 in coord0:
coord.append(quat.rotate_vectors(quat.from_rotation_ve... | Python | 1 |
if not os.path.exists(data_file):
print(f"Error: File not found: {data_file}")
sys.exit(1)
try:
with open(data_file, 'r') as f:
data = f.read()
except Exception as e:
print(f"Error reading file: {e}")
sys.exit(1)
# Get database path ... | Python | 1 |
re(figsize=(12, 8))
# Calculate number of ingredients for each recipe
n_ingredients = df['ingredients'].apply(len)
# Create scatter plot
colors = df['cuisine'].astype('category').cat.codes
plt.scatter(df['prep_time'], n_ingredients, c=colors, alpha=0.6)
plt.xlabel('Preparation Tim... | Python | 1 |
# -*- coding: utf-8 -*- #
# Copyright 2019 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 |
import pandas as pd
data = {
"Name":['Ram',None,'Dhansyam','Aditi','Jagdish','Raj','Simran','Aman'],
"Age":[28,None,22,30,29,40,25,32],
"Salary":[50000,None,45000,52000,49000,70000,48000,58000],
"Performance_score":[85,None,89,78,88,92,90,88]
}
df = pd.DataFrame(data)
print(df)
df.interpolate(method=... | Python | 1 |
ub.com/NixOS/patchelf/blob/7ec8edbe094ee13c91dadca191f92b9dfac8c0f9/src/patchelf.cc#L1331-L1332
result.push("$ORIGIN/../lib:");
result.push(zlib);
result
};
eprintln!(
r#"patch options:
patchelf = {:?}
linker = {:?}
rpath = {:?}"#,
patchelf, linker, rpath
... | Rust | 0 |
, Surface Temperature, `ts` and Adibat `ad`
pub fn new<KT: Into<Kelvin<f64>>>(ad: Adiabat, kappa: ThermalDiffusivity<f64>, ts: KT, age: Second<f64>) -> Self {
OceanicGeotherm { ad, kappa, ts: ts.into(), age }
}
/// Create a new Oceanic Geotherm from a Mantle Potential Temperature `tp`
/// and an... | Rust | 0 |
map: &mut Array2D<Tile>,
point1: &Location,
point2: &Location,
bridge_y: i32,
) {
for y in point1.1..=bridge_y {
map.set(y as usize, point1.0 as usize, Tile::Ground);
}
for y in bridge_y..=point2.1 {
map.set(y as usize, point2.0 as usize, Tile::Ground);
}
if point1.0... | Rust | 0 |
nfinity": chebyshev_grad,
"linfty": chebyshev_grad,
"linf": chebyshev_grad,
"minkowski": minkowski_grad,
# Standardised/weighted distances
"seuclidean": standardised_euclidean_grad,
"standardised_euclidean": standardised_euclidean_grad,
"wminkowski": weighted_minkowski_grad,
"weighted_mi... | Python | 1 |
ts[0]
else:
best_artist = artist
t5 = time.time()
top_tracks = get_artist_top_tracks(best_artist, top_n=len(scenes))
t6 = time.time()
top_track_names = [track[1] for track in top_tracks]
top_track_lyrics = []
for track in top_tracks:
lyri... | Python | 1 |
5535
pe: id1
pf: NodePtr {file: 1, level: 0, index: 1}
fn f1(a1) {let x = 1} "SA:[local], EA:[local], pa:[local], pb:[local], pc:[local], pd:[local], pe:[local], pf:[local]"
r1: [1, 2, 3]
o1: {x: 1, 1.0: 2}
C2: Component {
a1: [1, 2... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: wyn
# Time: 2024-08-17 17:37:24
from flask import Blueprint
from flask import request, redirect, url_for
from model.conf import conf
base_blueprint = Blueprint('base', __name__, url_prefix='/base')
def get_base(conf) -> dict:
baseconf = {}
for key in (... | Python | 1 |
mut map)?;
}
"AwsServices" => {
aws_services = ::serde::de::MapAccess::next_value(&mut map)?;
}
_ => {}
}
}
Ok(... | Rust | 0 |
import openai
from ..common.debug import dprint
from ..common.templates import PromptTemplates
from ..types.goal import AgentGoal
from ..types.environment import ExecutionEnvironment
from ..types.plan import AgentPlan, AgentPlanFormat
from ..types.step import AgentStep
def generate_plan(
goal: AgentGoal,
en... | Python | 1 |
"""
The matcher subsystem needs a function called "confirm_top", which
takes the data passed to a top file environment and determines if that
data matches this minion.
"""
import logging
import salt.loader
log = logging.getLogger(__file__)
def confirm_top(match, data, nodegroups=None):
"""
Takes the data p... | Python | 1 |
# bar_chart_stacked.py
from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference
def create_excel_data(sheet):
data_rows = [
('Number', 'Batch 1', 'Batch 2'),
(2, 10, 30),
(3, 40, 60),
(4, 50, 70),
(5, 20, 10),
(6, 10, 40),
(7, 50, 30),
... | Python | 1 |
"image": {
"newsUrl": "https://www.goodhousekeeping.com/life/money/a31404597/pi-day-deals-2020/",
"source": "GoodHousekeeping.com",
"imageUrl": "https://t2.gstatic.com/... | Rust | 0 |
Tuple::point(0.0, 0.0, -5.0),
direction: Tuple::vector(0.0, 0.0, 1.0),
};
let x = w.intersect(&r);
assert_eq!(x[0].t, 4.0);
assert_eq!(x[0].point, Tuple::point(0.0, 0.0, -1.0));
assert_eq!(x[0].eyev, Tuple::vector(0.0, 0.0, -1.0));
assert_eq!(x[0].normalv, Tu... | Rust | 0 |
//! 123 -> x
//! 456 -> y
//! x AND y -> d
//! x OR y -> e
//! x LSHIFT 2 -> f
//! y RSHIFT 2 -> g
//! NOT x -> h
//! NOT y -> i
//! ```
//!
//! After it is run, these are the signals on the wires:
//!
//! ```plain
//! d: 72
//! e: 507
//! f: 492
//! g: 114
//! h: 65412
//! i: 65079
//! x: 123
//! y: 456
/... | Rust | 0 |
Instant::<u64, 1, 1_000>::from_ticks(10) - Duration::<u64, 1, 1_000>::from_ticks(1);
assert_eq!(diff, Instant::<u64, 1, 1_000>::from_ticks(9));
// Instant - Duration, Different base
let sum: Instant<u64, 1, 10_000> =
Instant::<u64, 1, 10_000>::from_ticks(10) + Duration:... | Rust | 0 |
core::mem::transmute::<
*const (),
extern "C" fn(
*mut SPI_Flash_Cfg_Type,
SF_Ctrl_IO_Type,
u8,
u32,
*mut u8,
u32,
) -> BL_Err_Type,
>(rom_lookup(RomIndex::SFlash_Read))
... | Rust | 0 |
argument('-r', '--rotate', action='store_true',
help='Rotate video by 90 degrees.')
parser.add_argument('-s', '--size', metavar='WIDTHxHEIGHT',
help='Frame size to use instead of the device '
'screen size.')
parser.add_argument('host_file', narg... | Python | 1 |
able_code)]
unreachable!()
}
}
}
}
pub trait EscalateResult {
type Output;
fn escalate(self) -> Self::Output;
}
impl<Ok, E: Escalate> EscalateResult for Result<Ok, E> {
type Output = Result<Ok, E::Output>;
fn escalate(self) -> Self::Output {
self.map_err(|e| e.escalate())
}
}
/// A caught [`Escalati... | Rust | 0 |
await client.get_installed_modules()
# Convert to more structured format for better readability
response = {
"modules": modules,
"moduleCount": len(modules),
"retrievedAt": f"{datetime.now().isoformat()}Z",
}
return [TextC... | Python | 1 |
dim"]) -> Float[Tensor, "*bs out_dim"]:
"""
Process input with a multilayer perceptron.
Args:
inputs: Network input
Returns:
MLP network output
"""
activation_fn = activation_dict[self.activation]
x = inputs
self.initialize_weights... | Python | 1 |
GapAlignmentSide::Right => 0,
};
// fill scores with alignment scores
// if the colon marks the position in the sequence before rPos,qPos
// R: ...ACT:X
// Q: ...ACT:Y
// 1) if X and Y are bases they either match or mismatch. shift doesn't change, rPos and qPos advance
// -> right horizontal step ... | Rust | 0 |
lf, plugin_name: str) -> bool:
plugin_dir = conf.PLUGIN_HOME / plugin_name
if not plugin_dir.is_dir():
logger.warning(f"插件目录 {plugin_dir} 不存在,无法删除。")
return False
widgets_to_remove = []
if widgets_to_remove:
try:
widget_config_path = CO... | Python | 1 |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Jordan Borean <jborean93@gmail.com>
# 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
from __future__ import absolute_import, division, print_function
__metaclass_... | Python | 1 |
#[macro_use] extern crate log;
extern crate irq_safety;
extern crate atomic_linked_list;
extern crate task;
#[cfg(single_simd_task_optimization)]
extern crate single_simd_task_optimization;
use alloc::collections::VecDeque;
use irq_safety::RwLockIrqSafe;
use atomic_linked_list::atomic_map::AtomicMap;
use task::TaskRe... | Rust | 0 |
ces_colorvar[(self, i)] = (var, cbname)
cnf[i] = var.get()
return fn(self, cnf, None)
return _patch
def _create(self, itemType, args, kw):
"""Internal function."""
args = tkinter._flatten(args)
cnf = args[-1]
if isinstance(cnf, (dict, tuple)):
args = args[:-1]
e... | Python | 1 |
= Vec<&'static str>;
// This looks an awful lot like doing permutations of a list.
// Because of that, this came in handy! https://github.com/Dual-Iron/wykraken/blob/master/src/main.rs
fn map() -> Map {
let mut ret = HashMap::new();
for line in crate::input!(12).lines() {
let mut split = line.split('... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.