text string | label_name string | labels int64 |
|---|---|---|
ed city if relevant
if "flights" in response:
session["last_city"] = response["flights"]["destination"]
elif "tourism" in response:
session["last_city"] = response["tourism"]["city"]
elif "weather" in response:
session["last_city"] = response["weather"]["city"]
# Store conversat... | Python | 1 |
let visitor = visit::mk_vt(@visit::Visitor {
visit_fn: visit_fn,
visit_local: visit_local,
visit_expr: visit_expr,
visit_arm: visit_arm,
.. *visit::default_visitor()
});
let initial_maps = @mut IrMaps(tcx,
method_map,
... | Rust | 0 |
} else {
Some(account)
};
Ok(burned)
}
)?;
d.supply = d.supply.saturating_sub(burned);
Self::deposit_event(Event::<T>::Burned(id, who.clone(), burned));
Ok(().into())
})
}
/// Transfer asset balance to another account.
fn transfer(
id: Self::AssetId,
origin: &T::Account... | Rust | 0 |
r ator in porcos + passaros:
ator.status = DESTRUIDO
self.assertEqual(VITORIA, fase.status(),
'Sem porcos ativos o jogo deveria terminar com '
'vitória')
fase.adicionar_obstaculo(ObstaculoFake())
self.assertEqual(VITORIA, fase.status... | Python | 1 |
, target_width = target_size
pad_x = target_width - width
pad_y = target_height - height
padding = [0, 0, pad_x, pad_y]
return F.pad(inpt=image, padding=padding)
def _get_max_res_without_distortion(
image_size: Tuple[int, int],
target_size: Tuple[int, int],
) -> Tuple[int, int]:
"""
... | Python | 1 |
# Copyright (c) 2014-2017 Louisiana State University
# 2017-2025 Cardiff University
#
# This file is part of GWpy.
#
# GWpy is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the... | Python | 1 |
ops(
self,
torch.nn.AvgPool1d(3, stride=2),
device,
inp_dims=(8, 4, 16),
prec=0.05,
)
_test_bfloat16_ops(
self,
torch.nn.AvgPool2d(3, stride=2),
device,
inp_dims=(8, 4, 16, 16),
prec=0... | Python | 1 |
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from .serializer_registrar import SerializerRegistrar
class BaseSerializer(object):
"""
An abstract base class for serializers.
Each class extending BaseSerializer should serialize a single class,
wh... | Python | 1 |
14f863b8d5ab5a0d0c64d2e8a1e7d1457df2e5a3c51c73235be").unwrap();
let xpriv = DerivedXPriv::root_from_seed(&seed, Some(Hint::Legacy)).unwrap();
let descendants = [KeyDeriv {
path: &[0 + BIP32_HARDEN],
}];
for case in descendants.iter() {
validate_descendant(&case... | Rust | 0 |
from tkinter import *
from tkinter.ttk import *
root=Tk()
root.title("combobox")
root.geometry("200x100+50+30")
# combo=Combobox(root)
# combo['values']=(1,2,5,6,"hello","suuuu")
# combo.current(2)
# combo.grid(column=0,row=1)
chk=BooleanVar()
chk.set(True)
chk=Checkbutton(root,text="Select", var=chk)
chk.grid(column... | Python | 1 |
to()), 3);
assert_eq!(min_distance("intention".into(), "execution".into()), 5);
assert_eq!(
min_distance("zoologicoarchaeologist".into(), "zoopathologist".into()),
10
);
assert_eq!(
min_distance(
"pneumonoultramicroscopicsilicovolcanoconiosis".into(),
"ultramicroscopically".into()
),... | Rust | 0 |
SDM_DITHER_SEL_BLE_2470_R {
LO_SDM_DITHER_SEL_BLE_2470_R::new(((self.bits >> 4) & 0x03) as u8)
}
#[doc = "Bits 2:3"]
#[inline(always)]
pub fn lo_sdm_dither_sel_ble_2468(&self) -> LO_SDM_DITHER_SEL_BLE_2468_R {
LO_SDM_DITHER_SEL_BLE_2468_R::new(((self.bits >> 2) & 0x03) as u8)
}
#... | Rust | 0 |
number
%m mount point
%n file name
%N quoted file name with dereference if symbolic link
%o optimal I/O transfer size hint
%s total size, in bytes
%t major device type in hex, for character/block device special files
%T minor device type in hex, for character/block device special files
%u... | Rust | 0 |
ts: usize) -> Result<String, std::fmt::Error> {
let mut result = String::new();
write!(&mut result, "[")?;
for i in 0..nbits {
let byte = i / 8;
let bit = i % 8;
let num = if 0 != (data[byte] & (1 << bit)) { 1 } else { 0 };
write!(&mut result, "{}", num)?;
}
write!(&... | Rust | 0 |
a.axis_iter(Axis(0))
//! .into_par_iter()
//! .map(|row| row.sum())
//! .collect_into_vec(&mut sums);
//!
//! assert_eq!(sums, [120., 376., 632., 888.]);
//! }
//! ```
//!
//! ## Zip
//!
//! Use zip for lock step function application across several arrays
//!
//! ```
//! extern crate ndarray;
//! ext... | Rust | 0 |
st SIX: Polymino = Polymino {
cubes: [
((0, 0, 0), White),
((1, 0, 0), Black),
((2, 0, 0), White),
((0, 1, 0), Black),
((0, 0, 1), Black),
],
grain: Short,
};
pub const SEVEN: Polymino = Polymino {
cubes: [
((0, 0, 0), Black),
((0, 1, 0), White),
... | Rust | 0 |
save_configs(&configs)?;
}
let tm = ToolManager::new(&configs.working_directory, &configs.verbose_mode)?;
if run_tool {
if tool_name.is_empty() && keywords.len() > 0 {
tool_name = keywords[0].clone();
}
return tm.run_tool(tool_name, tool_args_vec);
} else if tool_hel... | Rust | 0 |
import jax
from ..llama import Llama, LlamaModel
from ..llama.attention import Attention
from ..llama.decoder import Decoder
from .shard_array import shard_array
sharding_mp = Llama(
model=LlamaModel(
embedding=...,
decoder=Decoder(
input_norm=...,
attention=Attention(q_pro... | Python | 1 |
) {
let id = meta.id.clone();
path2meta.insert(path, meta);
if ids.contains(&id) {
if let Some(nonempty) = collisions.get_mut(&id) {
*nonempty += 1;
} else {
collisions.insert(id, 2);
}
} else {
ids.insert(id.clone());
}
}
fn is_hidden(entry... | Rust | 0 |
#User function Template for python3
class Solution:
def sum_of_middle_elements(self, arr1, arr2):
# code here
result=sorted(arr1+arr2)
mid1=(len(result))//2-1
mid2=(len(result))//2
return result[mid1]+result[mid2]
| Python | 1 |
}
}
Ok(self.cached.is_some())
}
}
}
}
//! Supported devices.
use crate::{
crates,
probe::{Log, Probe},
utils::ser_to_string,
};
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::io::Write;
use termcolor::{ColorChoice, ColorSpec, ... | Rust | 0 |
>,
#[prost(string, tag = "3")]
pub cf: std::string::String,
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct RawDeleteResponse {
#[prost(message, optional, tag = "1")]
pub region_error: ::std::option::Option<super::errorpb::Error>,
#[prost(string, tag = "2")]
pub error: std::string::St... | Rust | 0 |
type {
FieldType::Boolean => DecodedData::Boolean(if field.field_data == "true" || field.field_data == "1" { true } else { false }),
FieldType::Float => DecodedData::Float(if let Ok(data) = field.field_data.parse::<f32>() { data } else { 0.... | Rust | 0 |
util.u('réveillé'): util.u('réveillé'),
"data": {"k1": util.u('drôle')}
},
self.datatype
)
])
eq_(
config.db.scalar(s),
{
util.u('réveillé'): util.u('réveillé'),
"data": {"k1": u... | Python | 1 |
ogit = masks[np.argmax(scores)], logits[np.argmax(scores), :, :]
# painted_image = mask_painter(image, mask.astype('uint8'), mask_color, mask_alpha, contour_color, contour_width)
# painted_image = point_painter(painted_image, np.squeeze(points[np.argwhere(labels>0)],axis = 1), point_color_ne, p... | Python | 1 |
"""Tests for the command line command matching code."""
##############################################################################
# Pytest imports.
from pytest import mark
##############################################################################
# Local imports.
from hike.widgets.command_line.base_command i... | Python | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
All pairs shortest paths by Floyd-Warshall
jill-jênn vie, christoph dürr et pascal ortiz - 2014-2019
"""
# snip{
def floyd_warshall(weight):
"""All pairs shortest paths by Floyd-Warshall
:param weight: edge weight matrix
:modifies: weight matrix to con... | Python | 1 |
d(list(set(support_levels)))[:5]
return {
'resistance': resistance_levels,
'support': support_levels
}
def trend_analysis(self, data: pd.DataFrame) -> Dict[str, any]:
close_prices = data['close']
# Calculate various moving averages
... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from typing import Dict, Any, Optional
from datetime import datetime
import uvicorn
from fastapi import FastAPI, HTTPException, BackgroundTasks
from pydantic import BaseModel, Field
from loguru import logger
from .. import T, __version__
from ..aipy.agent_taskmgr import... | Python | 1 |
number = int(input("give me a number: "))
for i in range(number):
for j in range(i + 1): #with i + 1 the need amount of stars will be typed
print('*', end=' ') #copied from the hints
print()
print("made by Seldi Hollidri") | Python | 1 |
# out['H'].shape)
# 結果の取得
p_ns = out['p_now'][0, :].cpu()
p_fs = out['p_future'][0, :].cpu()
vad_result = out['vad'][0, :].cpu()
# 最終フレームの結果を判定に利用
score_n = p_ns[-1].item()
score_f = p_fs[-1].item()
score_v = v... | Python | 1 |
Debug)]
struct User(usize);
#[rocket::async_trait]
impl<'a, 'r> FromRequest<'a, 'r> for User {
type Error = std::convert::Infallible;
async fn from_request(request: &'a Request<'r>) -> request::Outcome<User, Self::Error> {
request.cookies()
.get_private("user_id")
.and_then(|co... | Rust | 0 |
ffi.geometry = ffi::hsa_ext_image_geometry_t_HSA_EXT_IMAGE_GEOMETRY_2DADEPTH;
},
_ => { }
}
Ok(())
}
pub fn data_info(&self, agent: &Agent,
access: Access, layout: Layout)
-> Result<ImageDataInfo, Error>
{
let mut ffi = unsafe { MaybeUninit::zeroed().assume... | Rust | 0 |
from .data import (
BodyBatteryData,
DailyBodyBatteryStress,
HRVData,
SleepData,
WeightData,
)
from .http import Client, client
from .stats import (
DailyHRV,
DailyHydration,
DailyIntensityMinutes,
DailySleep,
DailySteps,
DailyStress,
WeeklyIntensityMinutes,
WeeklySte... | Python | 1 |
t self, constant: &EnumConstant) {}
fn visit_enum_attributes(&mut self, attributes: &[Attribute]) {
for attribute in attributes {
self.visit_enum_attribute(attribute);
}
}
fn visit_enum_attribute(&mut self, attribute: &Attribute) {}
}
// Copyright 2020-2021 <NAME>
// SPDX-Licen... | Rust | 0 |
Self::Full { .. } => "Full",
};
write!(f, "RequestMethod({})", desc)
}
}
/// A ledger transaction request which has been prepared for dispatch
#[derive(Debug)]
pub struct PreparedRequest {
/// The protocol version used in pool communication
pub protocol_version: ProtocolVersion,... | Rust | 0 |
#
# This file is part of the Chemical Data Processing Toolkit
#
# Copyright (C) Thomas Seidel <thomas.seidel@univie.ac.at>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# versi... | Python | 1 |
import pygame
from pygame import Surface
from pygame.time import Clock
import settings
from screens import Screen
from game_objects import Coin
from hooks import EventHook, StaticHook
from buttons import SkinButton, CheckButton, Button
class ShopScreen(Screen):
def __init__(self, surface: Surface, clock: Clock, ... | Python | 1 |
from ncatbot.plugin_system import NcatBotPlugin
from ncatbot.plugin_system import command_registry
from ncatbot.plugin_system import group_filter, private_filter, admin_filter
from ncatbot.core.event import BaseMessageEvent
class QSPermissionsPlugin(NcatBotPlugin):
name = "QSPermissionsPlugin"
version = "1.0.... | Python | 1 |
import os
os.system("uvicorn app.main:app --port 8000 --reload")
# To run this project
# Type 'py start.py' inside terminal
| Python | 1 |
#!/usr/bin/env python3
"""
创建测试音频文件进行ASR测试
"""
import wave
import numpy as np
import os
def create_test_audio():
"""创建一个简单的测试音频文件"""
# 参数设置
sample_rate = 16000 # 16kHz
duration = 2.0 # 2秒
frequency = 440 # A4音符
# 生成正弦波
t = np.linspace(0, duration, int(sample_rate * duratio... | Python | 1 |
_num(num: u128) {
println!("{}", num);
}
*/
<filename>archives/compiler/src/sem_analysis.rs
use super::ast::{ExprAst, StmtAst};
use super::ir::{Ir, IrInst};
use super::location::Locatable;
use super::term_color::red_bold;
use super::token::Identifier;
use once_cell::sync::Lazy;
use std::collections::HashMap;
/// セ... | Rust | 0 |
import sqlite3
# to work with SQLite we need to connect a database file with the program
conn = sqlite3.connect(":memory:")
# now have to put cursor to work with it
cur = conn.cursor()
"Creating Table in SQLite"
# now using cur.execute("") we can give SQLite command
cur.execute("CREATE TABLE students (Name TEXT, A... | Python | 1 |
{
let path = expand_expr(&ShorthandPath, token_nodes, context)?;
let start = path.span;
let expr = continue_expression(path, token_nodes, context);
let end = expr.span;
let block = hir::RawExpression::Block(vec![expr]).into_expr(start.until(end));
Ok(block)
}
}
///... | Rust | 0 |
&e)
}
}
}
Err(e) => {
display_error(&interp, &e);
}
}
interp.clear_codemap();
}
ReadResult::Signal(_) => {
prin... | Rust | 0 |
is_ok(),
error::UpateDatasetPermission {
role: session.user.id.to_string(),
dataset: permission.dataset,
permission: format!("{:?}", permission.permission),
}
);
let stmt = tx
.prepare(
"
SEL... | Rust | 0 |
"""HoloViz MCP Server.
This MCP server provides comprehensive tools, resources and prompts for working with the HoloViz ecosystem,
including Panel and hvPlot following best practices.
The server is composed of multiple sub-servers that provide various functionalities:
- Documentation: Search and access HoloViz docum... | Python | 1 |
report = self.folder_manager.get_status_report()
return {
'maintenance_active': self.running,
'config': self.config,
'folder_status': report,
'next_check_minutes': self.config['check_interval_minutes'] if self.running else None
}
# 全局实例
_a... | Python | 1 |
es(ValueError):
BBox.from_dict({"x1": 10, "y1": 20, "x2": 90}, title="Object")
def test_obbox():
obbox = OBBox(title="Object", coords=[10, 20, 30, 40, 50, 60, 70, 80])
assert obbox.model_dump() == {
"title": "Object",
"coords": [10, 20, 30, 40, 50, 60, 70, 80],
}
def test_obbox_d... | Python | 1 |
000_000;
let good_millis = dur.subsec_millis();
assert_eq!(bad_millis_1, good_millis);
assert_eq!(bad_millis_2, good_millis);
let bad_micros = dur.subsec_nanos() / 1_000;
let good_micros = dur.subsec_micros();
assert_eq!(bad_micros, good_micros);
// Handle refs
let _ = (&dur).subsec_na... | Rust | 0 |
ts(invalid_value, tz_arg):
"""do_timezone should return empty string for non-datetime inputs"""
result = tz_module.do_timezone(invalid_value, tz_arg)
# Should return empty string for non-datetime values
assert result == ""
# Test 7: Fragment key collision resistance
@given(
names=st.lists(st.text(... | Python | 1 |
xt(FSLCommand):
"""
Use FSL Vest2Text`https://web.mit.edu/fsl_v5.0.10/fsl/doc/wiki/GLM(2f)CreatingDesignMatricesByHand.html`_
to convert your design.mat design.con and design.fts files into plain text.
Examples
--------
>>> from nipype.interfaces.fsl import Vest2Text
>>> v2t = Vest2Text()
... | Python | 1 |
));
};
for v in &self.catch_probability_bonus {
try!(os.write_float(2, *v));
};
for v in &self.flee_probability_bonus {
try!(os.write_float(3, *v));
};
try!(os.write_unknown_fields(self.get_unknown_fields()));
::std::result::Result::Ok(())
... | Rust | 0 |
ue, {'from': bob})
with brownie.reverts():
merkle.proposewMerkleRoot(distribution2['merkleRoot'], {'from': alice})
chain.sleep(604801)
chain.mine()
merkle.proposewMerkleRoot(distribution3['merkleRoot'], {'from': alice})
merkle.reviewPendingMerkleRoot(True, {'from': bob})
for acct, claim ... | Python | 1 |
.y.start, other.y.start);
let start_z = max(self.z.start, other.z.start);
let end_x = min(self.x.end, other.x.end);
let end_y = min(self.y.end, other.y.end);
let end_z = min(self.z.end, other.z.end);
if start_x > end_x || start_y > end_y || start_z > end_z {
return No... | Rust | 0 |
# Ho va ten sinh vien: Nguyễn Thanh Xuân
# Ma so sinh vien: B2106825
# STT: 26
def Char2Num(c):
return ord(c)-65
def Num2Char(n):
return chr(n+65)
def encryptAF(txt,a,b,m):
r = ""
for c in txt:
e = (a*Char2Num(c)+b) % m
r = r+Num2Char(e)
return r
mahoa = encryptAF('HELLO', 5, 7,... | Python | 1 |
"邮政储蓄银行": {
"622150": "储蓄卡",
"622151": "储蓄卡",
"622188": "信用卡",
"622199": "信用卡"
},
"招商银行": {
"622662": "储蓄卡",
"622663": "储蓄卡",
"439225": "信用卡",
"518710": "信用卡"
... | Python | 1 |
#!/usr/bin/python3
test_source = [
"""
import brownie
import pytest
@pytest.fixture(scope="module")
def tester(BrownieTester, accounts):
tester = accounts[0].deploy(BrownieTester, True)
yield tester
def test_reverts_success(tester):
with brownie.reverts("zero"):
tester.revertStrings(0)
wi... | Python | 1 |
----------------------------------------
# 2) しきい値を変えたときの回収率と購入数をグラフ化
#-------------------------------------------------
pred_target_pairs = [
("P_top1", "T_top1"),
("P_top3", "T_top1"),
("P_top5", "T_top1"),
("P_pop1", "T_pop1"),
("P_pop3", "T_pop1"),
("P_pop... | Python | 1 |
soning_prompt = f"""
I'm having an issue with my Matplotlib animation code. Please explain what's wrong and how to fix it.
Error message:
{error_message}
Here's the code:
```python
{code}
```
Please explain the exact error and how I should fix it.
... | Python | 1 |
#!/usr/bin/env python3
import sys
import os
import cv2
from pyzbar.pyzbar import decode
def redirect_stderr(fd, to):
sys.stderr.close()
os.dup2(to.fileno(), fd)
sys.stderr = os.fdopen(fd, 'w')
def main(img):
qrcode_data = set()
fd = sys.stderr.fileno()
old_stderr = os.fdopen(os.dup(fd), 'w')
... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayOpenMiniMiniappFavoriteQueryModel(object):
def __init__(self):
self._designated_app_id = None
self._open_id = None
self._user_id = None
@property
def design... | Python | 1 |
ch",
arg,
None)
}
/// Get information about the current user's account.
pub fn get_current_account(
client: &impl crate::client_trait::UserAuthClient,
) -> crate::Result<Result<FullAccount, ()>> {
crate::client_helpers::request(
client,
crate::client_trait::Endpoint::Api,
... | Rust | 0 |
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
def load_data():
"""
加载清洗后的数据。
"""
# 从 data/processed/ 加载清洗后的数据
data = pd.read_csv('data/processed/cleaned_data.csv')
return data
def explore_data(data):
"""
数据探索:查看数据基本信息和统计信息。
"""
# 查看数据基本信息
print("... | Python | 1 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': "Sales - Service",
'summary': "Interaction between Sales and services apps (project and planning)",
'description': """
Allows to display sale information in the SOL services apps
====================... | Python | 1 |
on overflow.
///
/// See also
/// <code>FixedI32::[wrapping\_mul\_add][FixedI32::wrapping_mul_add]</code>
/// and
/// <code>FixedU32::[wrapping\_mul\_add][FixedU32::wrapping_mul_add]</code>.
#[must_use = "this returns the result of the operation, without modifying the original"]
fn wrapping... | Rust | 0 |
sender: SenderOnce<AppSum<Row, ReceiverF>>,
cont1: AppSum<Row, SessionF<C>>,
) where
C: Context,
Row: ElimSum,
Row: SplitRow,
Row: SumFunctorInject,
{
let res = lift_sum_inject(RunSession { ctx }, cont1);
let (receiver_sum, cont6) = Row::split_row(res);
sender.send(receiver_sum).unwrap();
Row::elim... | Rust | 0 |
kw super
kw crate
bt u32
lc x i32
fn quux(…) fn(i32)
ma m!(…) macro_rules! m
"#]],
);
check_empty(
r#"
macro_rules! m { ($e:expr) => { $e } }
fn quux(x: i32) {
let y = 92;
m!(x$0
}
"#,
expect![[r#... | Rust | 0 |
= f"{int(progress_bar.value * 100)}%"
page.update()
set_progress(False)
try:
print(f"[Rename] Completed. Renamed {renamed} of {total_to_process} files.", flush=True)
except Exception:
pass
# Close the app after confirming, regardless of rename co... | Python | 1 |
# -*- coding: utf-8 -*-
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"Li... | Python | 1 |
ae"
}
]
SbSysNetDrift["DokumentTypeOpslag"] = [
# Taken from the production environment
{
"ID": 0,
"Navn": "Uspecificeret",
"DefaultDokumentArtID": 6
},
{
"ID": 1,
"Navn": "Sbsys.Net dokument",
"DefaultDokumentArtID": 6
},
{
"ID": 2,
... | Python | 1 |
}
self.idx = start;
return Ok(QExpr {span, k: QExprKind::IdentApp(sp, args.into_boxed_slice())})
}
Err(ParseError::new(sp, format!("expecting prefix expression >= {}", p).into()))
}
fn lhs(&mut self, p: Prec, mut lhs: QExpr) -> Result<QExpr, ParseError> {
let mut tok_end = self.peek_token()... | Rust | 0 |
.successor_info_list)
delete_elem_list : List['NodeInfo'] = []
for idx in range(gval.SUCCESSOR_LIST_NORMAL_LEN, list_len):
# successor_info_listからエントリが削除された場合、rangeで得られる数字列全てに要素がない
# 状態が起こるため、最新のlengthでチェックし直す
if idx >= len(self... | Rust | 0 |
int(f"\n=== Revisions (Iteration {shared['iteration_count']}) ===")
# Handle test case revisions - map indices to actual test cases
if "test_cases" in exec_res:
current_tests = shared["test_cases"].copy()
print("Revising test cases:")
for index_str, revised_t... | Python | 1 |
# maximum number of optimizer iterations during training of the CRF (if set to None the optimizer
# will decide when to quit)
MAX_ITERATIONS = None
# Number of windows to use during training (offset is COUNT_WINDOWS_TEST, i.e. test windows will
# be loaded first)
COUNT_WINDOWS_TRAIN = 20000
# Number of windows to use... | Python | 1 |
# Copyright 2025 The Scenic 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 w... | Python | 1 |
e(
local_file_path
)
def _download_file(
self, local_file_path: Path, remote_file_key: str
) -> None:
r"""Download a file from the GCloud bucket to the local system.
Args:
local_file_path (Path): The path to the local file to be saved.
remote... | Python | 1 |
import pandas as pd
from tqdm import tqdm
# Enable tqdm for Pandas operations
tqdm.pandas()
# Load the English lyrics dataset and select 'id' and 'lyrics' columns with progress indicator
english_lyrics_path = "./datasets/songs_with_attributes_and_lyrics_english.csv"
print("Loading English lyrics dataset...")
english_... | Python | 1 |
should be a tensor")
# images = [t1, t2, ..., tN]
# Let's define paste_images as shifted list of input images
# paste_images = [t2, t3, ..., tN, t1]
# FYI: in TF they mix data on the dataset level
images_rolled = images[-1:] + images[:-1]
targets_rolled = targets[-1:] +... | Python | 1 |
Keycode::Down => self.down_pressed = false,
Keycode::Left => self.left_pressed = false,
Keycode::Right => self.right_pressed = false,
_ => (),
}
}
fn on_controller_button_down(&mut self, ctx: &mut Context, btn: Button, _ctrl_id: i32) {
match btn {
... | Rust | 0 |
(Debug, Clone, PartialEq)]
pub enum NumKind {
Integer(num_bigint::BigUint),
Float(f64),
Complex(f64),
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum Conversion {
Str,
Repr,
Ascii,
}
fn write_joined<I, T, S>(f: &mut fmt::Formatter<'_>, i: I, sep: S) -> fmt::Result
where
I: IntoIter... | Rust | 0 |
self.assertEqual(response.data["rendered_template_lines"], expected_response.split("\n"))
def test_render_jinja_template_failures(self):
"""
Test rendering invalid Jinja templates.
"""
test_data = [
{
"template_code": r"{% hello world %}",
... | Python | 1 |
# Ru
'を': 'z', # Wo
}
def decode_domain(domain: str):
try:
if domain.startswith('xn--'):
return idna.decode(domain)
return domain
except idna.IDNAError as e:
print(f"{type(e)}: IDNA decoding failed for domain: {domain}")
return domain
# Convert a punycode do... | Python | 1 |
Style::Bold, "等".into())]),
vec!["dang2".into()],
),
RubySegment::Punc("/".into()),
RubySegment::Word(
Word(vec![(TextStyle::Bold, "乙".into())]),
vec!["jyut6".into()],
),
RubySegment::Word(
Word(v... | Rust | 0 |
),
_pd: PhantomData,
}
}
}
impl<A: 'static> UIO<A> {
pub fn into_envio<R: 'static, E: 'static>(self) -> EnvIO<R, A, E> {
EnvIO {
instr: self.instr,
_pd: PhantomData,
}
}
}
impl<A: 'static, E: 'static> IO<A, E> {
pub fn with_env<R: 'sta... | Rust | 0 |
= torch.tensor(stack_u_c_1, device=self.device)
numerator_list = []
denominator_list = []
for idx, class_mean in enumerate(self.in_expert_distribution["class_mean"]):
denominator_list.append(torch.exp(torch.matmul(old_description_hidde... | Python | 1 |
from collections import deque
board = ["...D..R", ".D.G...", "....D.D", "D....D.", "..D...."]
n = len(board)
m = len(board[0])
answer = 0
# 4방향(좌 우 상 하)
dn, dm = [0, 0, -1, 1], [-1, 1, 0, 0]
start = [-1, -1]
visit = [[False] * m for _ in range(n)]
def move(i, j, dir):
global n, m
while True:
i += ... | Python | 1 |
(&addr_a).build().unwrap();
let lb_b = ScatterBuilder::new().bind(&addr_b).build().unwrap();
// Connected the worker to both load balancers.
let worker = GatherBuilder::new()
.connect(&[addr_a, addr_b])
.recv_high_water_mark(1)
.build()
.unwrap();... | Rust | 0 |
comp = prior_comps[k]
else:
comp = decoder_comps[k]
if isinstance(component, torch.nn.Module):
assert state_dicts_almost_equal(component.state_dict(), comp.state_dict())
elif hasattr(component, "config"):
assert dict(compon... | Python | 1 |
_שב", "_הפ", "_הו", "שמ", "מצרי",
"מצר", "מכ", "יציא", "יצי", "ים_ב", "וא_", "ה_ל", "דר_", "די_", "במ", "אחר",
"_ר", "_לה", "_הר", "רת", "סור", "סדר_", "סדר", "סד", "לכ", "לח", "ל_פ", "כל_",
"כה", "הפס", "בה", "ִ", "_מל", "ת_מצ", "ת_ח", "שנ", "שה", "רה", "סי",... | Rust | 0 |
list=stt.Type.List(
type=stt.Type(
string=stt.Type.String(nullability=NULLABILITY_NULLABLE)
),
nullability=NULLABILITY_NULLABLE,
)
),
... | Python | 1 |
PolylineViewBindGroup, SetPolylineBindGroup,
},
FRAG_SHADER_HANDLE, VERT_SHADER_HANDLE,
};
use bevy::{
core_pipeline::{AlphaMask3d, Opaque3d, Transparent3d},
ecs::system::{
lifetimeless::{Read, SQuery, SRes},
SystemParamItem,
},
prelude::*,
reflect::TypeUuid,
ren... | Rust | 0 |
のトークンです。
#[derive(Default)]
pub struct Diagram<T> {
entry_point: String,
node_map: HashMap<String, Node>,
fn_map: HashMap<String, Controller<T>>,
}
impl<T> Diagram<T> {
/// アプリケーション1つにつき、1つのフローチャートを共有します。
pub fn new() -> Diagram<T> {
Diagram {
node_map: HashMap::new(),
... | Rust | 0 |
# Copyright 2017-21 ForgeFlow (http://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import api, models
class StockBuffer(models.Model):
_inherit = "stock.buffer"
@api.model
def _exclude_past_moves_domain(self):
return [("exclude_from_adu", "="... | Python | 1 |
IFD.DateTimeOriginal,
self.raw_info, "exif", "originalTime", piexif.TYPES.Ascii):
self.coyp_DateTimeOriginal_from_uploadtime() # if originalTime is missing
# GPS #
if self.copy_exif("GPS", piexif.GPSIFD.GPSLongitude,
self.floatview_in... | Python | 1 |
ry:
if "model_file" in args: # 重新训练
model = PPO.load(args["model_file"], env=env, device="cpu", n_envs=n_envs, n_steps=n_steps_per_env, batch_size=minibatch_size, learning_rate=learning_rate)
else: # 训练新模型
model = PPO("MlpPolicy", env=env, verbose=1, n_steps=n_s... | Python | 1 |
tuning_args.plot_loss:
plot_loss(training_args.output_dir, keys=["loss", "eval_loss", "eval_accuracy"])
if training_args.predict_with_generate:
tokenizer.padding_side = "left" # use left-padding in generation
# Evaluation
if training_args.do_eval:
metrics = trainer.evaluate(me... | Python | 1 |
(&cx)
}
#[js_function(1)]
pub fn take_every(cx: CallContext) -> JsResult<JsExternal> {
let params = get_params(&cx)?;
let expr = params.get_external::<Expr>(&cx, "_expr")?;
let n = params.get_as::<usize>("n")?;
expr.clone()
.map(move |s: Series| Ok(s.take_every(n)), GetOutput::same_type())
... | Rust | 0 |
,
PageServerConf {
id: ZNodeId(10),
listen_pg_addr: "127.0.0.1:64000".to_string(),
listen_http_addr: "127.0.0.1:9898".to_string(),
checkpoint_distance: 111,
compaction_target_size: 111,
compaction_period: Duratio... | Rust | 0 |
]+" => |span, text, _| (span, Integer(text.parse().unwrap())),
r#""(.*)""# => |span, _, caps| (span, Text(caps[0].to_owned())),
r"->" => |span, _, _| (span, Arrow),
r"=" => |span, _, _| (span, Assign),
r"\(" ... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.