text string | label_name string | labels int64 |
|---|---|---|
: 项目ID过滤
creator_id (Optional[int]): 创建者ID过滤
assignee_id (Optional[int]): 指派人ID过滤
severity (Optional[str]): 严重程度过滤
status (Optional[str]): 状态过滤
page (int): 页码
page_size (int): 每页数量
db (Session): 数据库会话
current_user (User): 当前用户
Returns:
... | Python | 1 |
plugins: {{
legend: {{
position: 'right',
}}
}}
}}
}});
// Gráfico de severidade
const severityCtx = document.getElementById('severityChart').getContext('2d... | Python | 1 |
#(#attrs)* #vis #sig {
::profiling_futures::FutureWrapper::new(async move #block).await
}
};
res.into()
}
<gh_stars>1-10
extern crate clap;
use self::clap::{App, Arg};
const NAME: &'static str = env!("CARGO_PKG_NAME");
const AUTHOR: &'static str = env!("CARGO_PKG_AUTHORS");
const VER... | Rust | 0 |
r.callback_query(F.data == 'no')
async def reg_repeat(call: CallbackQuery, bot: Bot, state: FSMContext):
category = (await state.get_data())["category"]
await state.clear()
# проверка админ или нет для правильного заполнения роли, иначе без этого выдает ошибку
if category == 'admin':
await state... | Python | 1 |
) # 移除多余参数
training_args_dict.pop("use_kd", None) # 移除多余参数
training_args_dict.pop("kd_loss_scale", None) # 移除多余参数
training_args_dict.pop("lmbda", None) # 移除多余参数
training_args_dict.pop("beta", None) # 移除多余参数
training_args_dict.pop("seq_kd", None) # 移除多余参数
trainer = ... | Python | 1 |
import unittest
from unittests import wtc
import wx
#---------------------------------------------------------------------------
class spinbutt_Tests(wtc.WidgetTestCase):
def test_spinbuttCtor(self):
sb = wx.SpinButton(self.frame)
def test_spinbuttDefaultCtor(self):
sb = wx.SpinButton()
... | Python | 1 |
ask<'a> {
pub asset_filter: fn(&Asset) -> bool,
pub command: &'a str,
pub repo: (&'a str, &'a str),
pub trim_version: fn(String) -> String,
pub version_arg: &'a str,
}
impl<'a> GHRATask<'a> {
pub fn sync(&mut self) -> task::Result {
if self.exists() {
return Ok(Status::Skipp... | Rust | 0 |
from sql_embedder import SQLEmbeddingComparer
if __name__ == "__main__":
sql1 = """SELECT employees.name, employees.department_name
FROM employees
"""
sql2 = """SELECT name,
FROM cofee
"""
embedding_comparer = SQLEmbeddingComparer(trust_r... | Python | 1 |
parser = argparse.ArgumentParser()
parser.add_argument('--configs', default='configs/cityscapes/H_48_D_4.json', type=str,
dest='configs', help='The file of the hyper parameters.')
parser.add_argument('--phase', default='train', type=str,
dest='phase', help='The p... | Python | 1 |
3,
9 => 4,
10 => 4,
11 => 4,
12 => 4,
13 => 4,
14 => 4,
15 => 4,
16 => 4,
17 => 5,
18 => 5,
19 => 5,
20 => 5,
21 => 5,
22 => 5,
23 => 5,
... | Rust | 0 |
|-- 'W' [Underline]
|-- 'elt' []
");
}
#[test]
fn format_test_complex_2() {
let mut tree = Tree::new("Hallo Welt", None);
tree.set(6, "Hallo Welt".len(), FontStyle::Bold);
tree.set(0, "Hallo Welt".len(), FontStyle::Italic);
tree.set(4, 7, FontStyle::Underline);
... | Rust | 0 |
"cargo:rerun-if-changed=crates/records/records.witx");
}
use crate::fields::FieldContent;
use serde::Serialize;
#[derive(Clone, Copy, Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum AntNetwork {
Antfs,
Antplus,
Private,
Public,
UnknownValue(u64),
}
impl From<FieldContent> for AntNe... | Rust | 0 |
self.logger.info(f"🎉 Joined new guild: {guild.name} (ID: {guild.id})")
# Find a suitable channel to send welcome message
for channel in guild.text_channels:
if channel.permissions_for(guild.me).send_messages:
embed = discord.Embed(
title="👋... | Python | 1 |
unsafe { libc::telldir(dir.0) }
}
pub fn dirfd(dir: &mut DirectoryStream) -> nix::Result<RawFd> {
let res = unsafe { libc::dirfd(dir.0) };
Errno::result(res)
}
<gh_stars>1-10
use std::process;
#[cfg(unix)]
use nix::sys::signal::{raise, signal, SigHandler, Signal};
#[derive(Debug, Clone, Copy, PartialEq)]... | Rust | 0 |
key:
print(f"API Key Error: Please make sure ANTHROPIC_API_KEY is set in your .env file.")
raise ValueError("Anthropic API key not found. Please make sure ANTHROPIC_API_KEY is set in your .env file.")
return ChatAnthropic(model=model_name, api_key=api_key)
elif model_provider == Mod... | Python | 1 |
,
} => {
write!(f, " {} : {}", property_name, pattern)?;
if let Some(ref init) = default_init {
write!(f, " = {}", init)?;
}
}
}
Ok(())
}
}
/// BindingPatternTypeArray represents the different types of bindi... | Rust | 0 |
from typing import Dict, NamedTuple
from eth_utils import decode_hex
DEPOSIT_CLI_VERSION = '2.7.0'
class BaseChainSetting(NamedTuple):
NETWORK_NAME: str
GENESIS_FORK_VERSION: bytes
GENESIS_VALIDATORS_ROOT: bytes
MAINNET = 'mainnet'
GOERLI = 'goerli'
PRATER = 'prater'
SEPOLIA = 'sepolia'
ZHEJIANG = 'zhe... | Python | 1 |
.RelativeName()
pc_client = private_connections.PrivateConnectionsClient(
release_track=self.ReleaseTrack())
result_operation = pc_client.Create(
parent_ref, private_connection_ref.privateConnectionsId, args)
client = api_util.GetClientInstance(self.ReleaseTrack())
messages = api_util.... | Python | 1 |
import os
import time
from typing import Union
from .merge_hdf5 import merge_hdf5_files
def merge_seed_logs(
merged_path: str,
experiment_dir: str,
num_logs: Union[int, None] = None,
delete_files: bool = True,
) -> None:
"""Merge all .hdf5 files for different seeds into single log."""
# Collec... | Python | 1 |
: A_BS_UE_test,
y_ue: Y_UE_test / Z_UE_test}) * Z_UE_test
Y_BS_pred_test = np.reshape(Y_BS_pred_test, [N_TEST, -1])
Y_BS_pred_test = power_nomalize(Y_BS_pred_test, X_BS_test1[:, :, 0], nUE_BS)
nnrate, _ = cal_sum_rate1(A_BS_... | Python | 1 |
a.chip.skill().cmp(&b.chip.skill()).then_with(||a.chip.name.cmp(&b.chip.name))
});
}
ChipSortOptions::Range => {
folder.sort_by(|a, b| {
a.chip.range.cmp(&b.chip.range).then_with(||a.chip.name.cmp(&b.chip.name))
});
... | Rust | 0 |
, derive(PartialEq))]
pub struct TokenMetadata {
pub line: usize,
pub chars: Range<usize>,
}
<filename>terraria-protocol/src/packets/update_tile_entity.rs
use crate::packets::PacketBody;
use crate::SliceCursor;
/// Update Tile Entity.
///
/// Direction: Server -> Client.
#[derive(Debug)]
pub struct UpdateTileE... | Rust | 0 |
import os
import sys
import cfg
import pygame
from modules import *
'''游戏主程序'''
def main():
pygame.init()
screen = pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption('Gemgem —— 九歌')
# 加载背景音乐
pygame.mixer.init()
pygame.mixer.music.load(os.path.join(cfg.ROOTDIR, "resources/audios... | Python | 1 |
let mut v = Vec::new();
for (label, (point_label, point)) in query_set {
let poly = polys
.get(label)
.expect("polynomial in evaluated lc is not found");
let eval = poly.evaluate(*point);
v.push(((label.clone(), point_label.clone()), eval));
}
v
}
/// Gen... | Rust | 0 |
(encoding: tk::tokenizer::Encoding) -> Self {
Encoding { encoding }
}
}
#[pyproto]
impl PyObjectProtocol for Encoding {
fn __repr__(&self) -> PyResult<String> {
Ok(format!(
"Encoding(num_tokens={}, attributes=[ids, type_ids, tokens, offsets, \
attention_mask, special_to... | Rust | 0 |
struct InitSystem {}
impl <'a>System<'a> for InitSystem {
type SystemData = (
Entities<'a>,
Read<'a, LazyUpdate>,
// Phyisics
Write<'a, RigidBodyContainer>,
Write<'a, ColliderContainer>,
);
fn run(&mut self, data: Self::SystemData) {
let (entities, lazy, mut... | Rust | 0 |
#ranking_quality_metrics.py
#!/usr/bin/env python3
import sys
import os
import time
import numpy as np
import pandas as pd
# ─ Add project root so we can import core.py ─────────────────────────────────
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from core import load_model, load_s... | Python | 1 |
"*Required features: `\"Win32_Graphics_Direct3D12\"`*"]
pub const D3D12_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR: D3D12_FILTER = 129i32;
#[doc = "*Required features: `\"Win32_Graphics_Direct3D12\"`*"]
pub const D3D12_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT: D3D12_FILTER = 132i32;
#[doc = "*Required features... | Rust | 0 |
is set to HIGH."]
#[inline(always)]
pub fn pinval4(&self) -> PINVAL4_R {
PINVAL4_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - Fast GPIO output value Set bits. Bit 0 in PINx corresponds to pin Px\\[0\\], bit 31 in PINx corresponds to pin Px\\[31\\]. 0 = Controlled pin output is set ... | Rust | 0 |
}
#[test]
fn eq_if_all_match_but_state() {
let a = NodeData {state: Rc::new('a'), lp_from_top: 42, flags: NodeFlags::new_exact(), my_id: NodeIndex(0), inbound: None, best_parent: None, lp_from_bot: -1};
let b = NodeData {state: Rc::new('b'), lp_from_top: 42, flags: NodeFlags::new_exact(), ... | Rust | 0 |
MatplotlibExporter.register()
class MatplotlibWindow(QtGui.QMainWindow):
def __init__(self):
from ..widgets import MatplotlibWidget
QtGui.QMainWindow.__init__(self)
self.mpl = MatplotlibWidget.MatplotlibWidget()
self.setCentralWidget(self.mpl)
... | Python | 1 |
nviron['HTTP_AUTHORIZATION'] = 'Bearer 1/accesstoken'
else:
self.testbed.setup_env(
overwrite=True,
user_email=email,
user_id=user_id,
user_organization=organization,
user_is_admin=('1' if is_admin else '0'),
)
def Logout(self):
"""Logs the user o... | Python | 1 |
ty::NoMax {
None
} else {
Some(quote! {
if (#incr_condition).intersects(incr) { counter_val.max #op_eq #value_max; }
})
};
quote! {
let value = #value_getter;
let incr = #incr_getter;
#update_max
if (#incr_condition).contains(incr) { counte... | Rust | 0 |
attr.parse_args::<CaseValues>()
.map(|val| SifAttribute::Case(val.into_enfold(nth)))
} else if attr.path.is_ident("rename") {
attr.parse_args::<RenameNextValue>()
.map(|val| SifAttribute::RenameNext(val.into_enfold(nth))... | Rust | 0 |
revents the NotImplementedError
pylab.get_current_fig_manager().canvas.flush_events()
monitors[0].contained_objects.append(refresh_raster_plot)
def raster_plot_spiketimes(spiketimes, **plotoptions):
"""
Raster plot of a list of spike times
"""
m = Monitor()
m.so... | Python | 1 |
from the reference position.
Returns:
- Set[Point2]: A set containing the eight adjacent positions.
"""
p = position
d = distance
# Get the four direct neighbors (top, bottom, left, right)
direct_neighbors = self.neighbors4(position, distance)
# Get the f... | Python | 1 |
channels=asset_channels, run=run.id_, limit=10
# )
#
# # Verify we get a dictionary
# assert isinstance(data, dict)
class TestChannelsAPISync:
"""Test suite for the synchronous Channels API functionality.
Only includes a s... | Python | 1 |
": "rw",
"type": "VALUE",
},
{
"id": "211",
"name": "自动投放-洗衣液",
"code": "detergent_set",
"mode": "rw",
"type": "BOOL",
},
{
"id": "212",
"name": "自动投放-柔顺剂",
"code": "softener_set",... | Python | 1 |
>
where
T: ServicePair,
U: std::io::Read,
{
let fields = decode(&mut stream)?;
if fields.get("callerid").is_none() {
bail!(ErrorKind::HeaderMissingField("callerid".into()));
}
Ok(())
}
fn exchange_headers<T, U>(stream: &mut U, caller_id: &str, service: &str) -> Result<()>
where
T: S... | Rust | 0 |
)
.subcommand(
SubCommand::with_name("restore")
.about("Restore a container from a previous checkpoint (not supported)")
.version(crate_version!()),
);
parse_matches(app.clone());
}
use crate::keywords::schema::keyword;
#[derive(Insertable)]
#[table_name = "keyword"]
pub struct Keyword<'a> {
pu... | Rust | 0 |
= None
)
tokenized_test.set_format("torch")
tokenizer.padding_side = "right"
# only select 100 samples to test on
if len(tokenized_test) > 100:
tokenized_test = tokenized_test.select(range(100))
if attack:
if attack_size < len(tokenized_train):
tokenized_train = tok... | Python | 1 |
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
raise ZeroDivisionError("Syntax Error..!")
return x / y
def calculator():
while True:
print("=== Menu ===")
print("1. Add")
print("2. Subtrac... | Python | 1 |
assert_eq!(
Lint::UnevenPieceLength,
"uneven-piece-length".parse().unwrap()
);
}
#[test]
fn convert() {
fn case(text: &str, value: Lint) {
assert_eq!(value, text.parse().unwrap());
assert_eq!(value.name(), text);
assert_eq!(value.to_string(), value.name());
}
case("... | Rust | 0 |
"""Provides a radio button widget."""
from __future__ import annotations
from textual.widgets._toggle_button import ToggleButton
class RadioButton(ToggleButton):
"""A radio button widget that represents a boolean value.
Note:
A `RadioButton` is best used within a [RadioSet][textual.widgets.RadioSet... | Python | 1 |
meter_types! {
pub const PunishmentSlots: u32 = 1;
pub const MaxGroupSize: u32 = 100;
}
impl swork::Config for Test {
type Currency = Balances;
type Event = ();
type PunishmentSlots = PunishmentSlots;
type Works = ();
type MarketInterface = Market;
type MaxGroupSize = MaxGroupSize;
... | Rust | 0 |
pub fn priorities(&self) -> &[f32] {
self.priorities.as_slice()
}
pub fn reserved_queues(&self) -> u32 {
self.reserved_queues
}
}
#[derive(Debug)]
pub struct RendererQueues {
graphics_queues: Vec<OperationQueue>,
transfer_queues: Vec<OperationQueue>,
sparse_queues: Vec<Operation... | Rust | 0 |
#!/usr/bin/python
import sys
import os
import cv2 as cv
import numpy as np
print('\ntextdetection.py')
print(' A demo script of the Extremal Region Filter algorithm described in:')
print(' Neumann L., Matas J.: Real-Time Scene Text Localization and Recognition, CVPR 2012\n')
if (len(sys.argv) < 2):
p... | Python | 1 |
# Copyright (c) OpenMMLab. All rights reserved.
from typing import Dict, Optional, Tuple, Union
import torch.nn as nn
from mmcv.cnn import ConvModule
from mmrazor.registry import MODELS
@MODELS.register_module()
class ConvBNReLU(nn.Module):
def __init__(
self,
in_channel: int,
out_chann... | Python | 1 |
le(to_ptr(self.gicd_base, crate::GICD_ICFGR + (n << 2)), val) };
}
fn gicd_write_ctlr(&self, val: GicdCtlrS) {
unsafe { write_volatile(to_ptr(self.gicd_base, crate::GICD_CTLR), val) };
}
// ------------------------------------------------------------------------
// GICD's API
fn gicd_... | Rust | 0 |
(Ora) not implemented!");
// Ok(())
}
}
/// OraIndY: ORA indirect, indexed by Y
pub struct OraIndY { }
impl Instruction for OraIndY {
fn opcode (&self) -> &'static str { "ORA"}
fn hexcode(&self) -> Byte { 0x11 }
fn execute(&self, _cpu: &mut dyn VirtualCpu) -> std::io::Result<()> {
pan... | Rust | 0 |
Type::Bcd,
"F" => TokenType::Sprite,
_ => TokenType::Label(text),
};
self.add_token(token);
}
}
<gh_stars>1000+
// run-pass
#![feature(rustc_private)]
extern crate rustc_macros;
extern crate rustc_serialize;
mod submod {
use rustc_macros::{Decodable, Encodable};
/... | Rust | 0 |
import logging
from collections.abc import Generator
from typing import Any, Dict
import json
from dify_plugin import Tool
from dify_plugin.entities.tool import ToolInvokeMessage
from utils.rongcloud import RongCloudAPI
logger = logging.getLogger(__name__)
class GetUserInfoTool(Tool):
"""Get RongCloud user info ... | Python | 1 |
el=DIP(sigmoid_output=False,
lr=DIP_lr,
epoch_steps=num_DIP_steps)
if condition is not None and self.type == 'DIP':
targets = [output.unsqueeze(0), condition.unsqueeze(0)]
masks = [mask, torch.ones_like(mask)]
... | Python | 1 |
ain[batch_idx, :]
# Encode labeled data
x_batch = encoder.predict(x_batch)
# Select a batch of unlabeled data
batch_u_idx = np.random.permutation(len(x_unlab[:, 0]))[:batch_size]
xu_batch_ori = x_unlab[batch_u_idx, :]
# Augment unlabeled data
xu_batch = list()
f... | Python | 1 |
let bare_entry = emit.here();
(new_stackmap_with_frame_descr(frame_descr), bare_entry)
}
fn emit_epilogue(emit: &mut Emit, want_ret: bool) {
emit.mov(rsp, rbp)
.pop(rbp);
if want_ret {
emit.ret();
}
}
fn new_stackmap_with_frame_descr(frame: &FrameDescr) -> StackMap {
let mut... | Rust | 0 |
type1>($property1)?;
let prop2 = params.get_as::<$type2>($property2)?;
ca.$method_name(prop1, prop2)
.map_err(JsPolarsEr::from)?
.into_series()
.try_into_js(&cx)
}
};
}
impl_str_method_with_err!(str_contains, contains, &str, "pat");
im... | Rust | 0 |
pub fn rows(&self) -> usize {
self.grid.rows()
}
pub fn col(&self) -> usize {
self.col
}
pub fn into_iter(self) -> impl Iterator<Item = &'g T> + 'g {
(0..self.grid.rows()).map(move |y| &self.grid[y][self.col])
}
}
impl<'g, T> Index<usize> for Col<'g, T> {
type Outp... | Rust | 0 |
```python
target = syscall.get_target()
# Returns: "storage"
```
"""
return self.target
def set_source(self, source: str) -> None:
"""
Set the source of the system call.
Example:
```python
syscall.set... | Python | 1 |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Basic example which allows local human keyboard input to talk to a trained model.
Note: this is identical to example... | Python | 1 |
# -*- coding: utf-8 -*-
"""
Helper functions for image processing.
"""
import numpy as np
from scipy import fftpack as sfft
def sliding_window(arr, window):
if arr.ndim != 3:
raise ValueError('The input array needs to be 3-D - (h,w,c)!')
n_windows = (arr.shape[0] // window) * (arr.shape[1] // window)
... | Python | 1 |
return False
def _is_equal_with_tolerance(self, a: Any, b: Any) -> bool:
r"""Compares two Python objects for equality with optional float
tolerance.
This method recursively compares nested structures (lists, tuples,
sets, and dictionaries) and applies floating point toleranc... | Python | 1 |
{
unsafe {
let original: $fn_type = ::std::mem::transmute(self.trampoline());
original($($nm),*)
}
}
}
};
(@impl_core ($($nm:ident : $ty:ident),*) ($fn_type:ty)) => {
unsafe impl<Ret: 'static, $($ty: 'static),*... | Rust | 0 |
import torch
from collections import OrderedDict
from tinymm.MLM.dataset import ENWikiList, ENWikiDataset
from tinymm.MLM.model import MLM
from tinymm.GPT.model import GPTConfig
class MLMProvider:
def __init__(self, config):
self.config = config
@staticmethod
def get_datasets(config):
# ... | Python | 1 |
from __future__ import annotations
from typing import TYPE_CHECKING
from sec_parser.processing_steps.abstract_classes.abstract_elementwise_processing_step import (
AbstractElementwiseProcessingStep,
ElementProcessingContext,
)
from sec_parser.semantic_elements.semantic_elements import EmptyElement
if TYPE_CH... | Python | 1 |
if system_arch == "amd64":
if package_installer == "rpm":
qq_download_url = f"{base_url}_x86_64.rpm"
elif package_installer == "dpkg":
qq_download_url = f"{base_url}_amd64.deb"
elif system_arch == "arm64":
if package_installer == "rpm":
qq_download_ur... | Python | 1 |
orch.LongTensor([hps.data.spk2id[sid]]).to(device)
audio = (
net_g.infer(
x_tst,
x_tst_lengths,
speakers,
tones,
lang_ids,
bert,
ja_bert,
sdp_ratio=sdp_ratio,
... | Python | 1 |
flat)
}
}
#[cfg(test)]
mod tests {
use super::*;
use super::super::{test_decode, test_encode};
#[test]
fn iter() {
let expose_headers = test_decode::<AccessControlExposeHeaders>(
&["foo, bar"]
).unwrap();
let as_vec = expose_headers.iter().collect::<Vec<_>>();
... | Rust | 0 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from frontera.utils.fingerprint import hostname_local_fingerprint, sha1, md5
from w3lib.util import to_bytes
url1 = u"https://news.yandex.ru/yandsearch?cl4url=top.rbc.ru/politics/14/07/2015/55a50b509a79473f583e104c&lang=ru&lr=54#fragment"
url2 = u"TestStr... | Python | 1 |
ble to load font data");
let parser = Processor::new();
let cell_size = Size::new(14.0, 22.0);
let term = Term::new(
&Config::default(),
SizeInfo {
width: 0.0,
height: 0.0,
cell_width: cell_size.width,
cell_h... | Rust | 0 |
exEntryListBuildError {
fn description(&self) -> &str {
match *self {
AlternateIdIndexEntryListBuildError::MissingField(ref msg) => msg,
}
}
fn cause(&self) -> Option<&dyn StdError> {
match *self {
AlternateIdIndexEntryListBuildError::MissingField(_) => None,... | Rust | 0 |
# Центрируем диалог на экране, если нет родительского окна
if not self.parent():
self.center_on_screen()
def center_on_screen(self):
"""Центрирует диалог на экране"""
try:
from qgis.PyQt.QtWidgets import QApplication
screen = QApplica... | Python | 1 |
#######
optimizerD.clear_grad()
real_img = data
bs_size = real_img.shape[0]
label = paddle.full((bs_size, 1, 1, 1), real_label, dtype='float32')
real_out = netD(real_img)
errD_real = loss(real_out, label)
errD_real.backward()
noise = paddle.randn([bs_siz... | Python | 1 |
pr=[
".*_wrist_.*",
],
effort_limit_sim={
".*_wrist_yaw_joint": 5.0,
".*_wrist_roll_joint": 25.0,
".*_wrist_pitch_joint": 5.0,
},
velocity_limit_sim={
".*_wrist_yaw_joint": 22.0,
... | Python | 1 |
ersion_mask(m),
InputSetting::Delay((ch, del)) => lc.set_delay(ch, del),
InputSetting::Threshold((ch, th)) => lc.set_input_threshold(ch, th),
InputSetting::Window(w) => match args.window {
// Allow window... | Rust | 0 |
}
#[test]
fn test_event_schedule_now() {
let test_event_schedule = EventSchedule {
name: "Reoccurring event",
offset: NaiveTime::from_hms(1, 45, 0),
frequency: Duration::hours(3),
length: Duration::minutes(30),
};
let now = test_even... | Rust | 0 |
CallBuilder {
pub fn new(call: Call, request: Data) -> CallBuilder {
CallBuilder {
call: Some(call),
request,
}
}
}
impl CallBuilder {
/// Upon receiving a particular message from the service that is
/// invoked this callback will take some action
pub fn cal... | Rust | 0 |
#[rstest]
fn rollback_after_clear_instance(repo_object: RepoObject) -> anyhow::Result<()> {
let RepoObject {
mut repo,
mut object,
key,
} = repo_object;
object.write_all(b"test data")?;
object.commit()?;
drop(object);
repo.commit()?;
repo.clear_instance();
repo... | Rust | 0 |
_out)
dec_out[:, i] = dec_out_temp[:, i]
if i+1 < self.pred_len:
dec_in[:, i+1] = dec_out[:, i]
else:
# Using teacher-forcing for parallel training
dec_in = self.dec_x_embedding(dec_in[:, :-1]) if self.dec_x_embedding is not None else d... | Python | 1 |
cy = responses[1]
all_policies.extend(org_policies)
if edge_policy:
all_policies.append(edge_policy)
if backend_policy:
all_policies.append(backend_policy)
if args.IsSpecified('format') and args.format == 'json':
return (
client.messages.BackendServicesGetEffectiveSecurityP... | Python | 1 |
_A::SIRCDIV1_1,
2 => SIRCDIV1_A::SIRCDIV1_2,
3 => SIRCDIV1_A::SIRCDIV1_3,
4 => SIRCDIV1_A::SIRCDIV1_4,
5 => SIRCDIV1_A::SIRCDIV1_5,
6 => SIRCDIV1_A::SIRCDIV1_6,
7 => SIRCDIV1_A::SIRCDIV1_7,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `SIRCDIV1_... | Rust | 0 |
: T) -> Self {
Self::Deserialize(msg.to_string())
}
}
<gh_stars>100-1000
#[macro_use]
extern crate diesel;
mod data_object;
mod endpoints;
pub mod models;
pub mod schema;
use diesel::prelude::*;
use diesel::sqlite::SqliteConnection;
use roa_diesel::{make_pool, Pool};
#[derive(Clone)]
pub struct State(pub... | Rust | 0 |
'''
PiCamera Camera: Implement CameraBase with PiCamera
'''
#
# TODO: make usage of thread or multiprocess
#
__all__ = ('CameraPiCamera', )
from math import ceil
from kivy.logger import Logger
from kivy.clock import Clock
from kivy.graphics.texture import Texture
from kivy.core.camera import CameraBase
from picame... | Python | 1 |
6, 92, 118, 92, 102, 92, 110]
// ```
let pattern = [92, 116, 92, 118, 92, 102, 92, 110];
let debug = Debug {
source: &pattern,
options: "",
encoding: "",
};
let mut s = String::new();
debug.fmt_into(&mut s).unwrap();
assert_eq!(... | Rust | 0 |
buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.0.flush()
}
}
impl<S: io::Read + io::Write + fmt::Debug + Send + Sync + 'static> tls_api::TlsStreamImpl<S>
for TlsStream<S>
{
fn shutdown(&mut self) -> io::Result<()> {
matc... | Rust | 0 |
Debug)]
pub struct DBError {
pub message: String,
}
impl DBError {
pub fn new(message: String) -> Self {
Self { message }
}
}
use std::io::{self, Write};
use std::time::{Duration, Instant};
use kolben::rlercobs;
fn main() {
let mut dgs_port = None;
let ports = serialport::available_ports()... | Rust | 0 |
checks.append({
"date": match.group(1),
"status": "completed",
"duration": int(match.group(2))
})
for match in aborted_matches:
checks.append({
"date": match.group(1),
"status": "aborted",
"duration": int(match.group(2))
... | Python | 1 |
h_hint(
anyhow!("did not find expected <document start> at line 2 column 1\n\nCaused by:\n did not find expected <document start> at line 2 column 1"),
with_current_source_dir("testdata/isobin_configs/default_load.toml"),
ErrorHint::new(2,1,include_str!("testdata/isobi... | Rust | 0 |
components.spiderchart.SpiderPlot
<gh_stars>0
use std::{default::Default, fmt, path::PathBuf, sync::Arc};
use anyhow::Error;
use log::{debug, error, trace};
use regex::Regex;
use crate::utils::lines::LinesReader;
extern "C" {
fn memmem(
haystack: *const u8,
hlen: libc::size_t,
needle: *co... | Rust | 0 |
"""
Plots the real space representation of the monolayer unit cel
"""
import numpy as np
import matplotlib.pyplot as plt
# Define real space vectors
r1 = 1/2 * np.array([np.sqrt(3),1])
r2 = 1/2 * np.array([np.sqrt(3),-1])
r3 = np.array([0,1])
r4 = r2-r3
r5 = r1+r3
r6 = r1+r2
# Define point coordinates
origin = [0,0]... | Python | 1 |
= phonetic_type_list[phonetic_index][1]
# phonetic group
count = 1
index = phonetic_index + 1
# middle.comment
# 예외로 처음부터 일치하지 않다면
# 묵음 혹은 자음첨가 일 수 있다
if phonetic_index == 0 and type != word_type_list[index - 1][1]:
if... | Python | 1 |
eg<u32, _IRQ_SETUP_1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _IRQ_SETUP_1;
#[doc = "`read()` method returns [irq_setup_1::R](irq_setup_1::R) reader structure"]
impl crate::Readable for IRQ_SETUP_1 {}
#[doc = "`write(|w| ..)` method takes [irq_setup_1::W](irq_setup_1::W) writer structure"]
impl crate::Writabl... | Rust | 0 |
>(Suspect::VT_NAME, None)
}
#[inline]
pub fn age(&self) -> u32 {
self._tab.get::<u32>(Suspect::VT_AGE, Some(0)).unwrap()
}
#[inline]
pub fn face_img(&self) -> Option<&'a str> {
self._tab
.get::<flatbuffers::ForwardsUOffset<&str>>(Suspect::VT_FACE_IMG, None)
}
... | Rust | 0 |
x = float(input("Ingresa el valor para x: "))
y = 1./(x + 1./(x + 1./(x + 1./x)))
print("y =", y)
| Python | 1 |
# Description: A* algorithm implementation
import heapq
import numpy as np
from typing import Tuple
import matplotlib.pyplot as plt
from utils import calc_time
import config
class Node:
def __init__(self, x:int, y:int, parent=None, target=None):
self.x = x
self.y = y
# the cost of the path... | Python | 1 |
from datetime import date
from django.db import models
from archives.models import Especialidad, Datos, Direccion
# Create your models here.
class TipoUsuario(models.Model):
id_usuario = models.AutoField(primary_key=True, verbose_name="ID del usuario")
rol = models.CharField(max_length=20, verbose_name="Rol"... | Python | 1 |
::mem::size_of::<Mask8>(), 1);
assert_eq!(std::mem::size_of::<Mask16>(), 2);
assert_eq!(std::mem::size_of::<Mask32>(), 4);
}
}
<reponame>beltram/stubr<gh_stars>10-100
use asserhttp::*;
use surf::get;
#[async_std::test]
#[stubr::mock("req/headers/equal/string.json")]
async fn should_default_to_case_... | Rust | 0 |
$NetBSD: patch-setup.py,v 1.1 2015/12/11 21:40:50 riz Exp $
Rearrange installation dirs for pkgsrc, and don't install redhat files
--- setup.py.orig 2019-08-05 15:57:03.615377427 +0000
+++ setup.py
@@ -58,21 +58,13 @@ else:
setup_kwargs = dict()
-storage_dirs = [ ('storage/ceres/dummy.txt', []), ('storage/whis... | Python | 1 |
}
}
// Linking object files with different code models is undefined behavior
// because the compiler would have to generate additional code (to span
// longer jumps) if a larger code model is used with a smaller one.
//
// See https://reviews.llvm.org/D52322 and https://reviews.llvm.org/D52323.... | Rust | 0 |
elf.scaler.transform(X_test)
logger.info(f"Тестовые данные нормализованы: {X_test.shape[0]} образцов")
return X_train_scaled, X_test_scaled
def split_data(self, df: pd.DataFrame) -> Tuple[pd.DataFrame, pd.DataFrame, pd.Series, pd.Series]:
"""
Разделяет данные на обучающую и тестовую выборки.
Args:
df: DataFrame с по... | Python | 1 |
ocksSrgb.mat'))
val_data_gt = val_data_dict['ValidationGtBlocksSrgb']
self.num_img, self.num_block, h_, w_, c_ = val_data_gt.shape
self.val_data_noisy = np.reshape(val_data_noisy, (-1, h_, w_, c_))
self.val_data_gt = np.reshape(val_data_gt, (-1, h_, w_, c_))
def __len__(self):
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.