text string | label_name string | labels int64 |
|---|---|---|
::try_from(input).unwrap();
// let expect_uri = "http://";
// assert_eq!(&uri.normalize(), expect_uri);
// }
// //
// #[test]
// fn test_10() {
// let input = "http://[::]/";
// let uri: Uri = Uri::try_from(input).unwrap();
// let expect_uri = "http://[::]/";
// assert_eq!(&uri.normalize(), exp... | Rust | 0 |
x={self.v_max}")
print(f" time: nt={self.nt}, dt={self.dt:.4f}, T_total={self.T_total}")
print(f" dtype: {self.dtype}")
print(f" device: {self.device}")
#シミュレーションメソッド
def run_simulation(self):
self.Array_allocation()
self.set_initial_condition()
self.apply_bou... | Python | 1 |
e_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
html_domain_indices = False
# If false, no i... | Python | 1 |
rent_user.id}")
# Verify video exists and user owns it
result = await db.execute(
select(Video).where(Video.id == request.video_id)
)
video = result.scalar_one_or_none()
if not video:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail... | Python | 1 |
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _types as _cs
# End users want this...
from OpenGL.raw.GL._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant import Constant as _C
import ctypes
_... | Python | 1 |
Equal(len(message.parts), 0)
self.assertEqual(message.role, "user")
self.assertEqual(message.metadata["conversation_id"], self.conversation_id)
def test_adk_content_to_message_unknown_type(self):
"""Test handling unknown content type in ADK content."""
part = types.Part()
content = types.Content(... | Python | 1 |
get(&self, index: u64) -> LogArraySlice {
if index < 1 {
panic!("minimum index has to be 1");
}
let start = if index == 1 { 0 } else { self.bits.select(index-1)+1 };
let end = self.bits.select(index);
let length = end - start + 1;
self.nums.slice(start as u... | Rust | 0 |
def extract_timestamp(video_id: str):
try:
tagNo = int(video_id)
ts = tagNo >> 32
return ts
except:
return None
def deduplicate_videos(videos):
# TODO: compare against existing Supabase entries
return videos
| Python | 1 |
es[j_1+2],new_index_values[j_1+3]] , new_column_names[change_colums]] = combined_value #엑셀에서 사용할 셀의 위치
Four_cell_merge(j_1)
#관외 일반이용
if(df_data['시설명'] == desired_facility_list[change_colums]).any():
... | Python | 1 |
points2D = img_from_cam(intrinsics, points_cam, extra_params, default)
return points2D, points_cam
def img_from_cam(intrinsics, points_cam, extra_params=None, default=0.0):
"""
对给定的3D点应用内参和可选畸变。
参数:
intrinsics (torch.Tensor): 形状为Bx3x3的相机内参。
points_cam (torch.Tensor): 形状为Bx3xN的相机... | Python | 1 |
dir=str(working_directory),
logger=logger,
log_to_console=False)
logger.info("Copying the reference artn.in file to the working directory.")
shutil.copy(self._reference_artn_in_file_path, str(working_directory / "artn.in"))
logger.info("Write... | Python | 1 |
name="마스킹카드번호" value="0000-00**-****-0000">
</td><td class="t_left"><a href="#none" class="linkPoint2 letterType1" title="쿠팡(로켓와우월회비)" onclick="popSlsl('merchant id4' , 'base64 value','7', 'pg id3', '', '', '', '')">쿠팡(로켓와우월회비)</a>
</td><td>2,900원
</td><td>일시불
</td><td> ... | Rust | 0 |
hairs).
let window = dom::window().unwrap();
let document = window.document().unwrap();
container
.style()
.set_property("position", "relative")
.unwrap();
let chart_canvas = document
.create_element("canvas")
.unwrap()
.dyn_into::<dom::HtmlCanvasElement>()
.unwrap();
chart_canvas.style()... | Rust | 0 |
045123456Z`.
"""
return pulumi.get(self, "update_time")
@_builtins.property
@pulumi.getter(name="vlanId")
def vlan_id(self) -> pulumi.Output[_builtins.int]:
"""
VLAN ID for this subnetwork. If not specified, one is assigned automatically.
"""
return pulumi.ge... | Python | 1 |
ways)]
pub const fn ptr() -> *const wdt::RegisterBlock {
Self::PTR
}
}
impl Deref for WDT {
type Target = wdt::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for WDT {
fn fmt(&self, f: &mut core::fmt::Forma... | Rust | 0 |
e_exp3_sbox::<F, P>(input_var, composer),
}
}
}
// Allocate variables in circuit and enforce constraints when Sbox as cube
fn synthesize_exp3_sbox<F: PrimeField, P: TEModelParameters<BaseField = F>>(
input_var: &Variable,
composer: &mut StandardComposer<F, P>,
) -> Result<Variable, Error> {
let sqr =
composer.... | Rust | 0 |
set_path = idle_state.config.utxo_set_path.clone();
let network = idle_state.config.network;
let debug_level = idle_state.config.debug_level;
spawn(proc() {
// Lock the blockchain for reading while we are saving it.
{
let blockchain = bc_arc.read();
... | Rust | 0 |
mismatch_message(&mismatch)).to(be_equal_to(s!("Expected 'three' to be equal to 'four'")));
mismatches.clear();
match_xml(&expected.clone().into(), &actual.clone().into(), DiffConfig::NoUnexpectedKeys, &mut mismatches, &matchingrules!{
"body" => {
"$.foo" => [ MatchingRule::... | Rust | 0 |
#!/usr/bin/env python3
import numpy as np
import argparse
# Predefined RGB colors for each class (0–9).
CLASS_COLORS = np.array([
[135, 206, 235], # airplane
[255, 0, 0], # automobile
[ 0, 255, 0], # bird
[255, 160, 122], # cat
[139, 69, 19], # deer
[160, 82, 45], # dog
[ 3... | Python | 1 |
_utf8(output.stderr).unwrap_or(String::from(""))
);
} else {
let msg = format!(
"Failed to generate PlantUML diagrams, PlantUML exited with code {} ({}).",
output.status.code().unwrap_or(-9999),
String::from_utf8(output.stderr).unwrap_or(St... | Rust | 0 |
ideRegion;
use crate::profile::credentials::exec::named::NamedProviderFactory;
use crate::profile::credentials::exec::{ClientConfiguration, ProviderChain};
use crate::profile::parser::ProfileParseError;
use crate::provider_config::ProviderConfig;
use aws_smithy_client::erase::DynConnector;
mod exec;
mod repr;
impl Pr... | Rust | 0 |
and(2, 4, 38, 38)
>>> x = torch.rand(2, 10, 38)
>>> atomic_num_list = [6, 7, 8, 9, 15, 16, 17, 35, 53, 0]
>>> gen_mols = gen_mol_from_one_shot_tensor(adj, x, atomic_num_list)
>>> gen_mols
[<rdkit.Chem.rdchem.Mol>, <rdkit.Chem.rdchem.Mol>]
"""
x = x.permute(0, 2, 1)
adj = adj.cpu().detach... | Python | 1 |
efault=128, help='UCI Hash in MB')
parser.add_argument('--movetime-ms', type=int, default=None, help='Per-position movetime in ms (overrides depth)')
parser.add_argument('--ssl-tasks', nargs='+', default=['piece', 'threat', 'pin', 'fork', 'control'],
choices=['piece', 'threat', 'pin', 'fo... | Python | 1 |
this case relies on having single-precision floats; mixing half-precision
floats with fully-masked vectors will likely give you ``nans``.
If your logits are all extremely negative (i.e., the max value in your logit vector is -50 or
lower), the way we handle masking here could mess you up. But if you've got... | Python | 1 |
TXU_MASK_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 11"]
#[inline(always)]
pub fn cr_spi_sto_mask(&self) -> CR_SPI_STO_MASK_R {
CR_SPI_STO_MASK_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 10"]
#[inline(always)]
pub fn cr_spi_rxf_mask(&self) -> CR_SPI_RXF_MA... | Rust | 0 |
, B, Body = Mldv1Body<B>> + Mldv1MessageType + Debug,
>(
icmp: &IcmpPacket<Ipv6, B, M>,
max_resp_code: u16,
group_addr: Ipv6Addr,
) {
assert_eq!(icmp.message_body.reserved.get(), 0);
assert_eq!(icmp.message_body.max_response_delay.get(), max_resp_code);
assert_eq!... | Rust | 0 |
(Kind::_465, 1),
(Kind::_466, 1),
(Kind::_492, 1),
(Kind::_611, 2),
]
}
/// Returns the tiles that define the initial state of the map.
pub fn initial_tiles(hex: &Hex) -> Vec<Tile> {
use Location::*;
let city_tiles: Vec<Tile> = [
Anan, Nahari, Kubokawa, Sukumo, Matsuyama, S... | Rust | 0 |
#! /usr/bin/env python3
from matplotlib import pyplot as plt
import math
import os
import sys
def get_downloaded_ranges():
with open("zsync2_block_analysis.txt") as f:
total_size = int(f.readline().split(":")[1]) // 4096
data = []
line = f.readline()
while line:
pa... | Python | 1 |
ndex + 1, len(repeated_container) - 1)):
repeated_container[i].CopyFrom(repeated_container[i - 1])
repeated_container[index].CopyFrom(element)
def eliminate_const_nodes(model: onnx.ModelProto, const_nodes: List[onnx.NodeProto],
res: Tensors) -> onnx.ModelProto:
"""
:model... | Python | 1 |
# Copyright 2003-2008 by Leighton Pritchard. All rights reserved.
# Revisions copyright 2009 by Peter Cock.
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included ... | Python | 1 |
208, 157;
"欧碧", "oubi" => 192, 214, 149;
"苍葭", "cangjia" => 168, 191, 143;
"兰苕", "lanzhao" => 168, 183, 140;
"青玉案", "qingyuan" => 168, 176, 146;
"碧滋", "bizi" => 144, 160, 125;
"瓷秘", "cimi" => 191, 192, 150;
"... | Rust | 0 |
s not cached so be weary of losing links
search_page_completion = self.client.chat.completions.create(messages=[
{
"role": "system",
"content": self.system_prompt
},
{
"role": "user",
"content": f"Generate the se... | Python | 1 |
gb8::new(0x33, 0x33, 0x33),
SGray16::new(0x337F).convert(),
);
assert_eq!(SRgb8::new(0x40, 0x40, 0x40), SGray32::new(0.25).convert(),);
assert_eq!(
SRgb16::new(0x2929, 0x2929, 0x2929),
SGray8::new(0x29).convert(),
);
assert_eq!(
SRg... | Rust | 0 |
am {
type Item = ArrowResult<RecordBatch>;
fn poll_next(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
Poll::Pending
}
}
impl RecordBatchStream for BlockingStream {
fn schema(&self) -> SchemaRef {
Arc::clone(&self.schema)
}
}
/// ... | Rust | 0 |
zed virtio device: {:?}", device),
}
}
lazy_static! {
/// 用于放置给设备 DMA 所用的物理页([`FrameTracker`])
pub static ref TRACKERS: RwLock<BTreeMap<PhysicalAddress, FrameTracker>> =
RwLock::new(BTreeMap::new());
}
/// 为 DMA 操作申请连续 pages 个物理页(为 [`virtio_drivers`] 库提供)
///
/// 为什么要求连续的物理内存?设备的 DMA 操作只涉及到内存和对应设备... | Rust | 0 |
_get(uri: String) -> String {
let response = TodoRequest::parse(&uri, None)
.map(|request| request.process())
.unwrap_or_else(Response::Error);
serde_json::to_string(&response).unwrap_or_else(Response::json_error_from)
}
#[no_mangle]
pub unsafe extern "C" fn post(uri: WasmSlice, body: WasmSlice... | Rust | 0 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import lava.lib.dl.slayer as slayer
from lava.lib.dl.slayer.block.cuba import Conv as SpkConv
from lava.lib.dl.slayer.block.cuba import Dense as SpkDense
from .util import SpkDrop
class SNN(torch.nn.Module):
### Init ###
def __init__(self):
... | Python | 1 |
the heuristic for the potential relation
await rc_manager.update_heuristic(
relation_id=relation_id,
entity=entity,
entity_property_key=entity_property,
matched_entity=dm.matched_entit... | Python | 1 |
import subprocess
import logging
from urllib.parse import quote
import re
from abc import ABCMeta, abstractmethod
from minio import Minio
from os import name
from retrying import retry
from config import config
from tools import get_logger, ABSPATH, Database, bot, get_ddir
from users_map import user_map
class Uploa... | Python | 1 |
import os, sys
sys.path.append(os.path.abspath(os.path.join(os.getcwd(), "..")))
from commonsense_constraint import evaluation as commonsense_eval
from hard_constraint import evaluation as hard_eval
import json
from tqdm import tqdm
from datasets import load_dataset
import argparse
def load_line_json_data(filename):
... | Python | 1 |
: {}", inner);
// }
::std::process::exit(1);
}
}
fn run() -> Result<()> {
logger::init_logger();
let args = get_cli_args();
match args.subcommand {
NetmonSubcommand::Watch => watch::watch(&args),
NetmonSubcommand::Check => check::check(&args),
}
}
<gh_stars... | Rust | 0 |
"""
* Copyright 2020, Departamento de sistemas y Computación,
* Universidad de Los Andes
*
*
* Desarrolado para el curso ISIS1225 - Estructuras de Datos y Algoritmos
*
*
* 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... | Python | 1 |
: Encoding {
const INFINITY: Self;
const NEG_INFINITY: Self;
fn is_infinite(self) -> bool;
fn is_finite(self) -> bool;
}
/// Floating-point representations that expose `NaN`s.
pub trait Nan: Encoding {
/// A representation of `NaN`.
///
/// For primitive floating-point types, `NaN` is inco... | Rust | 0 |
::<B>(N);
let len_offset = E::inv((N as u64).into());
let mut result = unsafe { uninit_vector(values.len()) };
iter_mut!(result)
.zip(values)
.zip(inv_offsets)
.for_each(|((result, values), domain_offset)| {
// interpolate the values into a polynomial; this is similar to... | Rust | 0 |
::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("resource", resource);
if let Some(x_ms_client_request_id) = x_ms_client_request_id {
req_builder = req_builder.header("x-ms-client-request-id", x_ms_client_request_id);... | Rust | 0 |
fn query_token_info<S: ReadonlyStorage>(storage: &S) -> QueryResult {
let config = ReadonlyConfig::from_storage(storage);
let constants = config.constants()?;
let total_supply = if constants.total_supply_is_public {
Some(Uint128(config.total_supply()))
} else {
None
};
to_bina... | Rust | 0 |
Error> {
w.write_le(self.slot)?;
self.key_exchange.to_wire(w)?;
Ok(())
}
}
make_fuzz_safe! {
/// The [`GetDigests`] response.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct GetDigestsResponse<'wire> {
... | Rust | 0 |
in {}: {}",
message.author,
message.channel,
message.content);
let message = ffi::remove_color(&message);
let result = channel.discord.send_message(dest_chan, &message, "", false);
... | Rust | 0 |
await?;
println!("{}", id);
}
}
Ok(())
}
<filename>src/parser.rs
use crate::linereader::LineReader;
use crate::ParseError;
use crate::Section;
use std::io;
/// Parser for the text of an EditorConfig file.
///
/// This struct wraps any [std::io::BufRead].
/// It eagerly parses the prelude o... | Rust | 0 |
code.to_string().as_bytes())?;
return fmt_cmd.wait().map_err(|e| anyhow::Error::new(e));
}
<filename>bot_libs/nrs-qq/src/ext/common.rs
use alloc::sync::Arc;
use core::sync::atomic::Ordering;
use crate::provider::*;
use crate::Client;
pub async fn after_login<CP, OSCP, RP, MP, TP, TCP>(client: &Arc<Client<CP, OSCP... | Rust | 0 |
i64>, i64!(true));
named!(le_tsti64<i64>, i64!(false));
assert_eq!(be_tsti64(&[0x00, 0xFF, 0x60, 0x00, 0x12, 0x00, 0x80, 0x00]), Done(&b""[..], 71881672479506432_i64));
assert_eq!(le_tsti64(&[0x00, 0xFF, 0x60, 0x00, 0x12, 0x00, 0x80, 0x00]), Done(&b""[..], 36028874334732032_i64));
}
#[test]
fn manua... | Rust | 0 |
#Exercícios de Listas e Dicionários
import math
#Crie uma lista com os números de 1 a 10 e use um loop para imprimir cada número elevado ao quadrado.
numeros: list = [1,2,3,4,5,6,7,8,9,10]
for numero in numeros:
print(math.pow(numero,2))
#Dada a lista ["Python", "Java", "C++", "JavaScript"], remova o item "C++" e... | Python | 1 |
directory for the same
:param root: root under which other directories are re-based
:param isolated: equivalent to --no-user-cfg, i.e. do not consider
~/.pydistutils.cfg (posix) or ~/pydistutils.cfg (non-posix) for
scheme paths
:param prefix: indicates to use the "prefix" scheme and prov... | Python | 1 |
self._import_lib()
return self._cdll
@property
def task_handle(self) -> type:
return TaskHandle
@property
def cal_handle(self) -> type:
return CalHandle
@property
def encoding(self):
if self._encoding is None:
self._import_lib()
re... | Python | 1 |
use crate::serde::{packet_struct, serializable_enum};
serializable_enum! {
pub enum SpecialEffect: u8 {
SpawnSkeletron = 1,
CauseSoundAtPlayer = 2,
StartSundialing = 3,
BigMimicSpawnSmoke = 4,
}
}
packet_struct! {
/// Special NPC Effect.
///
/// Direction: Server <-... | Rust | 0 |
from opendevin.controller.agent import Agent
from .browsing_agent import BrowsingAgent
Agent.register('BrowsingAgent', BrowsingAgent)
| Python | 1 |
# Copyright 2020 Makani Technologies 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | Python | 1 |
Args:
wasSubstituted: True if the dispenser dispensed a different drug or
product from what was prescribed.
type: A code signifying whether a different drug was dispensed from
what was prescribed.
reason: Indicates the reason for the substitution of (or lack of
... | Python | 1 |
: &[u8] = b"operator";
let admin = 1;
let agent = 2;
let id = String::from(TEST_ORG_ID).into_bytes();
// Create org & admin agent
let _admin_role_id = store_admin_role();
store_test_org(id.clone(), String::from(TEST_ORG_NAME).into_bytes());
store_test_a... | Rust | 0 |
"zh ( e e e D ]| Z ee e j \ ZZZZ e
eez
e ez
eeez
e ez
cZZ e
ee eee cZZed z dz ek sed z dz e k r ed u ed ~ y)... | Python | 1 |
from aiogram.filters import Command
from aiogram.types.bot_command import BotCommand
START_COMMAND = Command('start')
FILMS_COMMAND = Command('films')
FILM_CREATE_COMMAND = Command("create_film")
FILM_SEARCH_COMMAND = Command("search_film")
FILM_FILTER_COMMAND = Command("filter_films")
FILM_RECOMMEND_COMMAND = Command... | Python | 1 |
pachoSolveFunctionBwdReturnType:
batch_size = grad_output.shape[0]
H = grad_output.clone()
H_double = H.double()
ctx.numeric_decomposition.solve(H_double) # solve in place
A_args = (
ctx.sparse_structure.num_cols,
ctx.A_row_ptr,
ctx.A_col_in... | Python | 1 |
# this is a Python ReaScript for use with the DAW Reaper
# it changes the number of channels for all selected tracks
# including their sends to a number given by the user
#
# this is very handy if you want to change ambisonic orders on the fly
# to save cpu processing (mainly channel copying/adding stuff)
# and chang... | Python | 1 |
"""Testing basic pipeline stages."""
import math
import pickle
import pandas as pd
from pdpipe.col_generation import Bin
from pdptestutil import random_pickle_path
def test_col_binner():
"""Testing the col binner helper class."""
binner = Bin._get_col_binner([0, 5])
assert binner(-math.inf) == "<0"
... | Python | 1 |
(v) => ReflectValueRef::F32(v),
ReflectValueRef::F64(v) => ReflectValueRef::F64(v),
ReflectValueRef::Enum(v) => ReflectValueRef::Enum(v),
ReflectValueRef::String(..)
| ReflectValueRef::Bytes(..)
| ReflectValueRef::Message(..) => unreachable!(),
}
}... | Rust | 0 |
E_PATH,
&["-e", "musl", "--color", "always", "--around", "0"],
env,
v.as_slice(),
);
assert_eq!(oup.stderr, "");
assert_eq!(
oup.stdout,
concat!(
"aarch64-unknown-linux-<S>musl<E> (installed)\n",
"arm-unk... | Rust | 0 |
def capitalize_first_letter(sentence):
result = ""
capitalize_next = True
for char in sentence:
if char == " ":
result += char
capitalize_next = True
elif capitalize_next:
result += chr(ord(char) - 32) if 'a' <= char <= 'z' else char
capitalize... | Python | 1 |
micAggregate::decode_from(peer, buf)?,
)),
7 => Ok(BgpAttrItem::AggregatorAS(BgpAggregatorAS::decode_from(
peer, buf,
)?)),
8 => Ok(BgpAttrItem::CommunityList(BgpCommunityList::decode_from(
buf,
)?)),
9 => Ok(BgpAttr... | Rust | 0 |
---------------------------------------------------------------------
#
def main():
os.putenv ( "GOMP_STACKSIZE", "2000000")
## os.putenv ( "LD_LIBRARY_PATH", "/opt64/lib:/progs/spd_20090409/src:/opt64/lib/python3.3/lib-dynload:/usr/lib" )
opts = optparse.OptionParser( version=get_geos__label )
opts.... | Python | 1 |
et("hold_days", 0) for t in trades if "hold_days" in t]
avg_trade_duration = np.mean(hold_days) if hold_days else 0
# 最大連續勝負次數
consecutive_stats = self._calculate_consecutive_stats(trades)
return {
"win_rate": win_rate,
"profit_ratio": profit_ratio,
... | Python | 1 |
&self.0
}
}
<reponame>joshmarinacci/idealos_schemas<filename>rust/idealos_schemas/src/menus.rs<gh_stars>0
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
pub enum node_type { }
pub const keystroke_obj_name: &str = "MAKE_keystroke_obj_name";
#[derive(Ser... | Rust | 0 |
tokens = line.split()
if len(tokens) != self.numAttributes:
print(f"Read {len(root.data)} data")
print(f"Last line read: {line}")
print(f"Expecting {self.numAttributes} attributes")
return 0
point = DataPoint(self.numAttri... | Python | 1 |
wal-sizes",
long,
help = "rocksdb max total WAL sizes"
)]
pub max_total_wal_size: Option<u64>,
#[serde(skip)]
#[structopt(skip)]
base: Option<Arc<BaseConfig>>,
}
impl StorageConfig {
fn base(&self) -> &BaseConfig {
self.base.as_ref().expect("Config should init.")
}
... | Rust | 0 |
import os
import csv
import json
# 配置存放csv和json文件的目录
path = "/Users/bytedance/Downloads/mockUser"
# 配置value列是csv文件中的第几列,下标从0开始
valueIndex = 1
def mockUserSort(i):
return i[1], int(i[0])
if __name__ == "__main__":
didMap = {}
csvList = []
jsonList = []
pathList = os.listdir(path)
for filena... | Python | 1 |
let mut path = root.clone();
for n in pkg.name.split('.') {
path.push(n);
}
path.set_extension("ya");
// First, get source cid from Package
let src_cid = match pkg.pos {
Pos::Some(p) => Some(p.input),
Pos::None => None,
};
let src_name = path.to_str().unwrap();
// Convert cid into Ipld obj... | Rust | 0 |
= 0;
// Assert all nodes are in non-voter state & have no entries.
router.wait_for_log(&btreeset![0, 1, 2], want, None, "empty").await?;
router.wait_for_state(&btreeset![0, 1, 2], State::NonVoter, None, "empty").await?;
router.assert_pristine_cluster().await;
// Initialize the cluster, then asser... | Rust | 0 |
idade = 51
if(idade <= 12):
print("criança")
elif (idade <=18):
print("adolecente")
elif(idade <50):
print("é adulto")
elif(idade > 50):
print("idoso") | Python | 1 |
fn le(&self, other: &Pin<Q>) -> bool {
P::Target::le(self, other)
}
fn gt(&self, other: &Pin<Q>) -> bool {
P::Target::gt(self, other)
}
fn ge(&self, other: &Pin<Q>) -> bool {
P::Target::ge(self, other)
}
}
#[stable(feature = "pin_trait_impls", since = "1.41.0")]
impl<P: De... | Rust | 0 |
.compress_append_to_vec(&mut buf, &mut name_refs)
.expect("failed to add F.ISI.ARPA");
Name::new_unchecked("BAR.F.ISI.ARPA")
.compress_append_to_vec(&mut buf, &mut name_refs)
.expect("failed to add F.ISI.ARPA");
let expected = b"\x03ISI\x04ARPA\x00\x01F\xc0\x00\... | Rust | 0 |
# Questão 95: Refaça o exercício 90, só que agora em forma de função Somador(), que vai
# receber dois parâmetros e vai retornar o resultado da soma entre eles para o
# programa principal.
def somador(num_a, num_b):
print(num_a + num_b)
print("="*15, "Somador", "="*15)
a = int(input("Primeiro valor: "))
b = int(... | Python | 1 |
parts.next().expect("missing repo name").to_string(),
);
let items = reco::get_indicated_items(&repo_id, indications);
match items {
Some(items) => Some(
items
.par_iter()
.map(|repo_id| config.get_repo_name(repo_id.to_string()))
.collect(),
),
None => None,
}
}
use st... | Rust | 0 |
import random
from typing import Optional
import numpy as np
import torch
def ensure_reproducibility(
seed: Optional[int] = None,
disable_cudnn_benchmark: bool = True,
avoid_non_deterministic_algorithms: bool = True,
) -> None:
"""
Sets seeds and configuration options to improve experiment reprod... | Python | 1 |
{
let mut varint: u64 = 0;
for index in 0..=9 {
if buf.is_empty() {
return Err(DecodeError::Eof);
}
let val = buf.get_u8();
// u64::MAX check
if index == 9 && val > 1 {
break;
}
varint += (val as u64 & !0x80) << (7 * index);
... | Rust | 0 |
"})
user = await repository_users.get_user_by_email(email, db)
if user is None:
logging.error(f"User not found with email: {email}")
raise credentials_exception
return user
def create_email_token(self, data: dict):
to_encode = data.copy()
expire = da... | Python | 1 |
Original
# ~~~~~~~~
#
plot_waveform(speech, sample_rate, title="Original")
plot_specgram(speech, sample_rate, title="Original")
Audio(speech, rate=sample_rate)
######################################################################
# RIR applied
# ~~~~~~~~~~~
#
plot_waveform(augmented, sample_rate, title="RIR Applie... | Python | 1 |
size)
.collect::<StdResult<Vec<_>>>()?;
if delegations_chunk.is_empty() {
break;
}
// append 0 byte to the last value to start with whatever is the next succeeding key
chunk_start = Some(
delegations_chunk
.last()
.unw... | Rust | 0 |
this works as expected: {}", word);
let string_slice = "This is of Type &str btw";
// Because it already is a string_slice we don't need the reference &
// already a slice
let result = best_signature(string_slice);
let string_result = best_signature(&s1[..]);
println!("Interesting:{} and from... | Rust | 0 |
or more.
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
pub struct ParMapBuilder<I> {
iter: I,
nb_threads: usize,
}
impl<I: Iterator> ParMapBuilder<I> {
/// As ParMap::par_map, but with a custom number of threads
/// # Example
///
/// ```
/// use par_map::ParMap;
... | Rust | 0 |
}, headers=headers, timeout=10)
response.raise_for_status()
data = response.json()
if data.get("response", {}).get("result") == "success":
logger.info(_("Conexão com Tautulli bem-sucedida."))
return {'success': True, 'message': _('Conexão com Tautulli ... | Python | 1 |
#!/usr/bin/env python3
# coding: utf-8
__author__ = "ChenyangGao <https://chenyanggao.github.io>"
__version__ = (0, 0, 3)
__all__ = ["encode_uri", "encode_uri_component", "encode_uri_component_loose"]
from urllib.parse import quote
translate = str.translate
TRANSTAB_ESCAPE2 = {c: f"%{c:02x}" for c in b'% '}
TRANSTA... | Python | 1 |
= "output file or directory")]
output: PathBuf,
#[options(short = "m", help = "dump mode (one of: 'ast', 'bytecode' or 'code')")]
mode: String,
#[options(short = "f", help = "split output into individual files")]
dump_files: bool,
#[options(short = "v", help = "verbose output (include implicit ... | Rust | 0 |
from deoplete.filter.matcher_fuzzy import Filter
def _ctx(complete_str, ignorecase=True, camelcase=True):
_candidates = [
{ 'word': 'foobar' },
{ 'word': 'afoobar' },
{ 'word': 'fooBar' },
{ 'word': 'afooBar' },
{ 'word': 'Foobar' },
{ 'word': 'aFoobar' },
{... | Python | 1 |
FIELDS, 63, &[]);
let testee = Ipv4Builder::new(*SRC, *DST, 28, &mut payload);
assert_eq!(8, testee.evenly_distributed_payload_per_fragment());
}
#[test]
fn evenly_distributed_payload_per_fragment_many_fragments_2() {
let mut payload = CustomPayload::with_packet_size(*FIELDS, 64, &[... | Rust | 0 |
import torch
def append_dims(x, target_dims):
return x[(...,) + (None,) * (target_dims - x.ndim)]
def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=1.0):
if guidance_rescale == 0:
return noise_cfg
std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=... | Python | 1 |
importance_analysis(self, features: Dict) -> Dict:
"""Analyze feature importance and correlations."""
# This would normally use the trained model to get feature importance
# For now, return a mock analysis
analysis = {
'high_importance': ['rsi_14', 'macd_str... | Python | 1 |
80 => Some(TAC_A::B80),
81 => Some(TAC_A::B81),
82 => Some(TAC_A::B82),
83 => Some(TAC_A::B83),
84 => Some(TAC_A::B84),
85 => Some(TAC_A::B85),
86 => Some(TAC_A::B86),
87 => Some(TAC_A::B87),
88 => Some(TAC_A::B... | Rust | 0 |
from pymongo import MongoClient
from datetime import datetime
class CurrencyConverter:
def __init__(self):
self.client = MongoClient("mongodb://localhost:27017/", serverSelectionTimeoutMS=5000)
self.db = self.client["currency_db"]
self.collection = self.db["rates"]
def close(self):
... | Python | 1 |
els[ax_idx] + ((" (makespan=%.1f)" % max_end ) if any(sched[m] for m in machines) else ""))
ax.set_xlabel("Time")
ax.set_yticks([i*10+5 for i in range(len(machines))])
ax.set_yticklabels(machines)
ax.set_xlim(0, max_end + 1)
ax.set_ylim(0, len(machines)*10)
ax.grid(True)... | Python | 1 |
#!/usr/bin/env python3
"""
TTML歌词生成器主程序
"""
from renderer import TTMLRenderer
from file_manager import FileManager
from clipboard.clipboard_manager import ClipboardManager
from convert.ttml_to_lrc import TTMLToLRC
from convert.lrc_to_ttml import LRCToTTML
def main():
# 示例歌词数据
lyrics_data = [
{"text": ... | Python | 1 |
nts",
Include::Series => "series",
Include::ISRCs => "isrcs",
}
}
}
pub(crate) enum BrowseBy {
Area,
Artist,
Recording,
Release,
ReleaseGroup,
Work,
Collection,
Place,
Label,
Track,
TrackArtist,
}
impl BrowseBy {
pub fn as_str(&self) ... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.