text string | label_name string | labels int64 |
|---|---|---|
name("KEYPAIR")
.validator(is_valid_signer)
.takes_value(true)
.help("Filepath or URL to a keypair [default: client keypair]"),
)
.arg(
Arg::with_name("verbose")
.long("verbose")
.short("v")
.take... | Rust | 0 |
from turtle import *
from colorsys import *
tracer(10)
bgcolor("black")
pensize(2)
h =0
def draw(int, t):
circle(5+t, 90)
left(int)
circle(5+t, 60)
for i in range(200):
c = hsv_to_rgb(h, 1, 1)
h += 0.005
color(c)
up()
draw(90, i/50)
draw(180, i/4)
down()
fillcolor("black")
... | Python | 1 |
# TEST: Test connection for Cisco DNA Center
# Connect Plugin V1.6
"""
Copyright © 2020 Forescout Technologies, Inc.
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 Software without restriction, including... | Python | 1 |
o(self.device)
with torch.no_grad():
with torch.autocast(self.device.type):
_predictions = self.model(images)
predictions = {}
for key in _predictions.keys():
if isinstance(_predictions[key], torch.Tensor):
predictions[key] = (
... | Python | 1 |
alue associated with the given key from the slab.
pub(crate) fn remove(&self, idx: usize) {
// try to lock the slab so that we can use `remove_local`.
let lock = self.local.try_lock();
// if we were able to lock the slab, we are "local" and can use the fast
// path; otherwise, we wil... | Rust | 0 |
adding: u32,
npointers: u32,
fielddesc_type: u32,
) -> __BindgenBitfieldUnit<[u8; 4usize], u32> {
let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize], u32> =
Default::default();
__bindgen_bitfield_unit.set(0usize, 9u8, {
let alignment: u32 = un... | Rust | 0 |
self.sub(rhs)
}
}
impl Sub<Instant> for Instant {
type Output = Duration;
// TODO: For safety in production code, `sub` actually does saturating_sub.
// We should remove this operator from public scope.
fn sub(self, other: Instant) -> Duration {
self.saturating_duration_since(other)
}
... | Rust | 0 |
.version(clap::crate_version!())
.author("<NAME> <<EMAIL>>")
.about("Locate data by its hash.")
.setting(clap::AppSettings::SubcommandRequiredElseHelp)
.subcommand(
clap::SubCommand::with_name("scan")
.about("Update the location database")
... | Rust | 0 |
#!/usr/bin/env python3
"""
eBay API Deep Dive - FINAL SUMMARY & RECOMMENDATIONS
Major discovery: We can be 1000x more efficient with better APIs
"""
def show_final_api_recommendations():
"""Show final recommendations after deep dive"""
print("🎴 EBAY API DEEP DIVE - FINAL SUMMARY")
print("=" * 60)
... | Python | 1 |
_i16i64, i16, i64 }
test_impl_from! { test_i32i64, i32, i64 }
// Unsigned -> Signed
test_impl_from! { test_u8i16, u8, i16 }
test_impl_from! { test_u8i32, u8, i32 }
test_impl_from! { test_u8i64, u8, i64 }
test_impl_from! { test_u16i32, u16, i32 }
test_impl_from! { test_u16i64, u16, i64 }
test_impl_from! { test_u32i64, ... | Rust | 0 |
p }
}
}
impl<S> math::Transform<Point3<S>> for Transform<S>
where
S: BaseFloat,
{
fn one() -> Self {
let one = S::one();
let (x, y, z) = (one, one, one);
Transform {
scale: Vector3 { x, y, z },
rot: Euler {
x: Rad(x),
y: Rad(y)... | Rust | 0 |
g.num_labels == 1:
valid_mask = ((labels >= 0) & (labels != self.config.semantic_loss_ignore_index)).float()
loss_fct = BCEWithLogitsLoss(reduction="none")
loss = loss_fct(upsampled_logits.squeeze(1), labels.float())
loss = (loss * valid_mask).mean()
... | Python | 1 |
/// users.
MENTION_EVERYONE = 1 << 17;
/// Allows the usage of custom emojis from other guilds.
///
/// This does not dictate whether custom emojis in this guild can be
/// used in other guilds.
USE_EXTERNAL_EMOJIS = 1 << 18;
/// Allows for viewing guild ... | Rust | 0 |
source: error,
});
}
_ => panic!("Unexpected rendering error")
}
}
}
} else {
return Err(RenderError::InvalidPathCharacters {
path: self.to_p... | Rust | 0 |
# Problem link - https://www.naukri.com/code360/problems/target-sum_4127362?source=youtube&campaign=striver_dp_videos
# Solution - https://www.youtube.com/watch?v=b3GD8263-PQ&list=PLgUwDviBIf0qUlt5H_kiKYaNSqJ81PMMY&index=22
def recursive():
def solve(arr, index, target):
if target == 0:
return... | Python | 1 |
ime import datetime
loader.end_date = datetime.now().strftime("%Y-%m-%d")
elif source == "file":
from dataloader.file_loader import FileLoader
loader = FileLoader()
# 設置配置參數
file_config = config.get("file_config... | Python | 1 |
ElementIce = 5,
ElementDragon = 6,
ElementPoison = 7,
ElementSleep = 8,
ElementParalyze = 9,
ElementBomb = 10,
ElementNotEqualMain = 11,
ElementFirstGroup = 12,
CanEquipTargetBottle = 13,
Series064 = 14,
Series065 = 15,
}
}
rsz_enum! ... | Rust | 0 |
let p = get_empty_tmp_dir();
let store = JsonFaaSDataStore::from_path(p.join("doesntexist")).await;
assert!(store.is_ok());
assert_eq!(store.unwrap().len().await, 0);
}
#[async_std::test]
#[should_panic]
async fn test_from_path_invalid_paths_panic() {
let p = ge... | Rust | 0 |
y",
"items": {
"type": "object",
"properties": {
"path": {"type": "string"},
"num_repeats": {"type": "integer", "minimum": 1, "default": 10},
"resolutions": {
"type": "array",
"items": {"type": "i... | Python | 1 |
json.load(open(metadata_file))
valid_tracks = _get_musdb_valid()
if args.train_valid:
metadata_train = metadata
else:
metadata_train = {name: meta for name, meta in metadata.items() if name not in valid_tracks}
metadata_valid = {name: meta for name, meta in metadata.items() if name in v... | Python | 1 |
from customtkinter import *
import os
from tkinter import messagebox
# usando o from biblioteca e importando toda ela com o * e mais facil escrever os codigos
# fica mais simples e rapido
# cor da janela
set_appearance_mode("mode")
#set_default_color_theme("dark-blue")
# criando janela
janela = CTk()
janela.title("... | Python | 1 |
x47\x17\x67\x0F\x69\xA9\
\xBC\x76\x35\x91\xA4\xF0\x5C\x50\xD6\x88\x91\xA7\x44\xBC\xC6\xE7\
\xD6\xD5\xB5\xE8\x2C\x01\x8D\xA9\x99\xED\x35\xB0\xBB\x49\xC9\x67\
\x8E\x52\x6A\xBD\x8E\x85\xC1\x3E\xD2\x54\x02\x1D\xB9\xE7\x90\xCE\
";
let mut output = [0u8; 64];
let mut hasher = TupleHash::v2... | Rust | 0 |
ft += output_slices[slice_idx]
y = y.view_as(y_org)
def add_lora_logits(self,
y: torch.Tensor,
x: torch.Tensor,
lora_a_stacked: torch.Tensor,
lora_b_stacked: torch.Tensor,
scale,
... | Python | 1 |
# SPDX-FileCopyrightText: 2023-2025 Greenbone AG
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
from ...gmpv224.entities.report_formats import (
GmpCloneReportFormatTestMixin,
GmpDeleteReportFormatTestMixin,
GmpGetReportFormatsTestMixin,
GmpGetReportFormatTestMixin,
GmpImportReportFormatTestMixin,... | Python | 1 |
', \'samples\') is not correct'
)
self.assertTrue(
np.isclose(upper_cdf_samp, 0),
msg='CDFGroup derivative (\'ci_resid\', \'samples\') is not correct'
)
self.assertTrue(
np.isclose(lower_cdf_fci, 0),
msg='CDFGroup derivative (\'ci_resid\'... | Python | 1 |
# Problem link - https://www.naukri.com/code360/problems/count-square-submatrices-with-all-ones_3751502?source=youtube&campaign=striver_dp_videos
# Solution - https://www.youtube.com/watch?v=auS1fynpnjo&list=PLgUwDviBIf0qUlt5H_kiKYaNSqJ81PMMY&index=58
def count_square_sub_matrices(matrix):
"""
Overall tim... | Python | 1 |
from gurobipy import Model, GRB
def aircraft_landing(EarliestLanding, LatestLanding, TargetLanding, PenaltyAfterTarget, PenaltyBeforeTarget, SeparationTime):
"""
Args:
EarliestLanding: list of integers, earliest landing times for each aircraft.
LatestLanding: list of integers, latest landing ti... | Python | 1 |
width: &mut u16,
height: &mut u16,
reset: bgfx::ResetFlags)
-> bool {
let mut should_close = false;
while let Ok(result) = self.event_rx.try_recv() {
match result {
Event::Close =>... | Rust | 0 |
_of(INVOICE_DATE_MM)
.unwrap()
.to_string()
.parse::<u32>()
.unwrap(),
matches
.value_of(INVOICE_DATE_DD)
.unwrap()
.to_string()
.parse::<u32>()
.unwrap(),
)
.and_hms(23, 59, 59);
let invoice... | Rust | 0 |
at!("Not required."));
}
bar.set_message(format!("Success ({} files).", wrote));
bar.finish();
return Ok(wrote);
}
fn main() {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.optopt("b", "board", "target board", "<board>");
opts.optopt("i", "im... | Rust | 0 |
# Find Closest Number to Zero
# solution - 01
# Function to find the number closest to zero in a list
# Big O Analysis:
# Time Complexity: O(n) - We traverse the entire list once to find the closest number.
# Space Complexity: O(1) - Only a constant amount of space is used for the variable `lowest`.
def findClosestNu... | Python | 1 |
# zmq requires memoryviews to be contiguous
raise ValueError(
"Buffer %i (%r) is not contiguous" % (idx, buf)
)
except TypeError as e:
raise TypeError(
"Buffer objects must... | Python | 1 |
[-] 客户端: {self.client_address} 连接: {address,str(port)} 发生错误: {err}')
# 响应拒绝连接的错误
reply = self.ReplyFaild(address_type, 5)
self.connection.sendall(reply) # 发送回复包
# 建立连接成功,开始交换数据
if reply[1] == 0 and cmd == 1:
self.ExchangeData(self.connection, remote)
... | Python | 1 |
= 0.032;
let model_spec_0 = SpotLightModelSpec::new(
cutoff_0,
outer_cutoff_0,
ambient_0,
diffuse_0,
specular_0,
constant_0,
linear_0,
quadratic_0,
);
let attitude_spec_0 = LightAttitudeSpec::new(
position_0,
forward_0,
... | Rust | 0 |
def test_midpoint(self):
f, y0, t_points, sol = problems.construct_problem(TEST_DEVICE, reverse=True
)
y = torchdiffeq.odeint(f, y0, t_points[0:1], method='midpoint')
self.assertLess(max_abs(sol[0] - y), error_tol)
| Python | 1 |
_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 8)) | ((value as u32 & 0x03) << 8);
self.w
}
}
#[doc = "Transmitter narrow pulse\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debu... | Rust | 0 |
ncat2().from_err();
let decode_future = body_future
.and_then(|body| serde_json::from_slice(body.as_ref()).map_err(|err| err.into()));
decode_future
.and_then(|search_response: GithubSearchResponse| {
search_response
.it... | Rust | 0 |
# configuration file for xbee sensor lab SMS Text display
__version__ = "1.3.0"
from digi import cloud
REFRESH_RATE = 1800 # delay in seconds before reverting to phone number display
UPPERCASE = True # sets whether alphanumeric display is all uppercase or mixed case
USE_HTTP = False # sets whether to use an authenti... | Python | 1 |
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
RMDL: Random Multimodel Deep Learning for Classification
* Copyright (C) 2018 Kamran Kowsari <kk7nc@virginia.edu>
* Last Update: Oct 26, 2018
* This file is part of RMDL project, University of Virginia.
* Free to use, change, share and distribute source cod... | Python | 1 |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Aakvatech and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class NHIFScheme(Document):
pass
def add_scheme(id, name=None):
if frappe.db.exists("NH... | Python | 1 |
required. When you're
/// done with it, you can call `release(instance)` to return it.
///
/// `Instance` itself dereferences to a `RegisterBlock`, which
/// provides access to the peripheral's registers.
#[cfg(not(feature = "nosync"))]
#[inline]
pub fn take() -> Option<Instance> {
l... | Rust | 0 |
fs.symlink_metadata("sl").unwrap().0, Inode::new(0o777, Ftyp::Symlink, 5).view());
assert_eq!(fs.symlink_metadata("sl/sl").unwrap().0, Inode::new(0o777, Ftyp::Symlink, 6).view());
assert_eq!(fs.symlink_metadata("..").unwrap().0, Inode::new(0o300, Ftyp::Dir, DIRLEN).view());
assert_eq!(fs.symlink... | Rust | 0 |
tone::<i16>::_encode(mem::transmute(storage))
}
#[inline]
unsafe fn _decode(storage: &[u32], n_blks: usize, output: &mut [isize]) -> usize {
Monotone::<u16>::_decode(storage, n_blks, left, mem::transmute(output))
}
}
#[cfg(target_pointer_width = "32")]
impl EncodePrivate<isize> for Monotone<isize> {
#[i... | Rust | 0 |
)
# Don't apply audience if the credentials file passed from user.
if hasattr(credentials, "with_gdch_audience"):
credentials = credentials.with_gdch_audience(
api_audience if api_audience else host
)
# If the credentials are serv... | Python | 1 |
estoneRequest::size_range().contains(&5), false);
}
#[test]
fn size() {
let packet = MilestoneRequest::new(INDEX);
assert_eq!(packet.size(), CONSTANT_SIZE);
}
#[test]
fn into_from() {
let packet_from = MilestoneRequest::new(INDEX);
let mut bytes = vec![0u8; pac... | Rust | 0 |
# SPDX-FileCopyrightText: 2020 Dan Halbert for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
`adafruit_ble_adafruit.gyroscope_service`
================================================================================
BLE access to gyroscope data.
* Author(s): Dan Halbert
"""
__version__ = "1.2.3"
__repo__... | Python | 1 |
deploy_cfg (str | mmcv.Config): Input deployment config file or
Config object.
device (str): Device to input model.
Returns:
BaseBackendModel: Pose model for a configured backend.
"""
# load cfg if necessary
deploy_cfg, model_cfg = load_config(deploy_cfg, model_cfg)
... | Python | 1 |
_AT: typing.ClassVar[
danio.Field
] # "updated_at" timestamp without time zone NOT NULL
GENDER: typing.ClassVar[danio.Field] # "gender" int NOT NULL
USER_ID: typing.ClassVar[danio.Field] # "user_id" int NOT NULL
COINS: typing.ClassVar[danio.Field] # "coins" int NOT NU... | Python | 1 |
import json
import argparse
from typing import Any, Optional
def check_required_args(
parser: argparse.ArgumentParser,
namespace: argparse.Namespace,
*required_args,
arg_values: Optional[list[Any]] = None,
) -> None:
"""Check required arguments
Args:
parser (argparse.ArgumentParser): ... | Python | 1 |
}
// e > e4
0.0
}
<reponame>darosior/revault_tx<filename>src/txouts.rs
//! Revault txouts
//! Tiny newtype wrappers around bitcoin's TxOut to statically check Revault transaction
//! creation.
use bitcoin::TxOut;
use std::fmt;
/// A transaction output created by a Revault transaction.
pub trait RevaultTx... | Rust | 0 |
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../')))
import asyncio
from sphero_sdk import SpheroRvrAsync
from sphero_sdk import SerialAsyncDal
from sphero_sdk import DriveFlagsBitmask
loop = asyncio.get_event_loop()
rvr = SpheroRvrAsync(
dal=SerialAsyncDal... | Python | 1 |
esult: Result<BDAddr, _> = "2a00AabbCcdd".parse();
assert_eq!(result, Ok(addr));
let result: Result<BDAddr, _> = "2A:00:00".parse();
assert_eq!(result, Err(ParseBDAddrError::IncorrectByteCount));
let result: Result<BDAddr, _> = "2A:00:AA:BB:CC:ZZ".parse();
assert!(matches!(result... | Rust | 0 |
from itertools import zip_longest
names = ['Alice', 'Bob', 'Charlie', 'Dave']
ages = [24, 50, 18]
for name, age in zip_longest(names, ages):
print(name, age)
# Alice 24
# Bob 50
# Charlie 18
# Dave None
for name, age in zip_longest(names, ages, fillvalue=20):
print(name, age)
# Alice 24
# Bob 50
# Charlie 18... | Python | 1 |
ile):
print(f"Error: Configuration file '{config_file}' not found")
return
random_question = get_random_question(config_file)
if random_question:
questions.append(random_question)
# 处理直接指定的问题
elif args.question:
questions.append(args.question)... | Python | 1 |
rivilege.as_ref() {
query.push_str(" privilege=$");
query.push_str(index.to_string().as_str());
params.push(s as &(dyn ToSql + Sync));
index += 1;
}
if query.ends_with(',') {
query.pop();
query.push_str(" WHERE id=$");
} els... | Rust | 0 |
]);
}
#[test]
fn vram_writes_to_end_of_nametable_2_correctly_with_horizontal_mirroring() {
let mut vram = create_test_vram();
vram.write(0x2BFF, 0x12);
assert_eq!(0x12, vram.memory[0x07FF]);
}
#[test]
fn vram_reads_from_beginning_of_nametable_2_correctly_with_horizontal... | Rust | 0 |
sembled_image.len() + tiles[&ref_row[0].id].data.len() - 2,
vec![],
);
for tile_ref in ref_row {
let data = rotate_vec(
&flip_vec(&tiles[&tile_ref.id].data, tile_ref.flip),
tile_ref.rot,
);
for (dy, data_row) in data.iter().... | Rust | 0 |
data
/// * `len` - length that the `buf_ptr` can receives.
/// * `offset` - offset
/// * `index` - index
/// * `source` - source
pub fn load_cell_data_raw(
buf_ptr: *mut u8,
len: usize,
offset: usize,
index: usize,
source: Source,
) -> Result<usize, SysError> {
syscall_load(
buf_ptr,
... | Rust | 0 |
// Get step data from the configuration
let mut steps: Vec<Step> = Vec::new();
let mut next_id = StepId::first();
let mut step_fn_to_id: Vec<(_, StepId)> = Vec::new();
let start_id = next_id.take();
steps.push(Step {
id: start_id,
requires: HashSet::new(),
py_obj: None,
... | Rust | 0 |
Alignment of field: ",
stringify!(msghdr),
"::",
stringify!(msg_controllen)
)
);
assert_eq!(
unsafe { &(*(0 as *const msghdr)).msg_flags as *const _ as usize },
48usize,
concat!(
"Alignment of field: ",
stringify!(msghdr... | Rust | 0 |
h_name}{' ' * pad}{'-' * width_size}{' ' * pad}{'-' * width_date}"
print(header)
print(sep)
# Opcionalmente agrupar .hash/.sha256
rows = group_with_hashes(files) if group_hashes else sorted(files, key=lambda f: f.get('name', '').lower())
total_bytes = 0
for f in rows:
name = f.get("nam... | Python | 1 |
class Solution:
def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]:
heights = defaultdict(lambda:float("inf"))
queue = deque()
m, n = len(isWater), len(isWater[0])
for i in range(m):
for j in range(n):
if isWater[i][j] == 1:
... | Python | 1 |
essionType: DVSESSIONTYPE_PEER,
guidCT: PCM.guidType,
dwBufferQuality: DVBUFFERQUALITY_DEFAULT,
dwBufferAggressiveness: DVBUFFERAGGRESSIVENESS_DEFAULT,
};
DV_OK
}
unsafe fn GetClientConfig(&self, pClientConfig: *mut DVCLIENTCONFIG... | Rust | 0 |
from llama_index.core import VectorStoreIndex, StorageContext
from llama_index.core.schema import Document
from llama_index.core.node_parser import SimpleNodeParser
from llama_index.vector_stores.qdrant import QdrantVectorStore
from llama_index.embeddings.openai import OpenAIEmbedding
from qdrant_client import QdrantCl... | Python | 1 |
71 => CrunchExerciseName::SwissBallRussianTwist,
72 => CrunchExerciseName::WeightedSwissBallRussianTwist,
73 => CrunchExerciseName::SwissBallSideCrunch,
74 => CrunchExerciseName::WeightedSwissBallSideCrunch,
75 => CrunchExerciseName::ThoracicCrunchesOnFoamRol... | Rust | 0 |
j..i
}];
}
}
break;
}
let b = hv[i];
match b {
b';' => {
if p == 1 {
if let Some(mut e) = v.last_mut() {
e.1 = &hv[if hv[j] == b'"' && hv[i - 1] == b'"' {
... | Rust | 0 |
winuser::DrawMenuBar(*hwnd);
winuser::UnhookWindowsHookEx(event_hook);
}
Ok(())
}
unsafe fn on_win_msg(&mut self, msg: winuser::MSG) {
self.features.iter_mut().for_each(|f| f.win_msg(&msg));
if msg.message == winuser::WM_COMMAND {
let hig... | Rust | 0 |
, Version 2.0
//
// 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 writing, softwa... | Rust | 0 |
(always)]
pub fn is_pram2_overlay_enable(&self) -> bool {
*self == PRAM2_OVERLAY_CFG_A::PRAM2_OVERLAY_ENABLE
}
}
#[doc = "Write proxy for field `PRAM2_OVERLAY_CFG`"]
pub struct PRAM2_OVERLAY_CFG_W<'a> {
w: &'a mut W,
}
impl<'a> PRAM2_OVERLAY_CFG_W<'a> {
#[doc = r"Writes `variant` to the field"]
... | Rust | 0 |
use regex::Regex;
use sqlx::postgres::Postgres;
use sqlx::Transaction;
use std::sync::Arc;
use uuid::Uuid;
use crate::domain::profile::{Profile, ProfileRepository, ProfileService};
use crate::domain::secret::{SecretRepository, SecretService};
use crate::error::{Error, Result};
use crate::infrastructure::repository::b... | Rust | 0 |
import torch
import torch.nn as nn
from torchvision import models
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
vgg16 = models.vgg16(pretrained=True).to(device)
...... # 【此处为本例核心代码,已省略,完整代码见教材P134;建议读者手工输入核心代码并进行调试,这样方能领会其含义】
L = [conv2,conv3,conv5] #对这些网络层上的参数进行冻结
for layer in L:
for p... | Python | 1 |
telegram_bot_raw::UpdateKind::Message(msg) => {
if let Err(x) = handle_message(msg).await {
console_log!("Message handling error: {}", x);
}
}
telegram_bot_raw::UpdateKind::CallbackQuery(cb) => {
if le... | Rust | 0 |
== broadcast::TryRecvError::Empty => false,
_ => true,
}
}
}
impl<T> AsyncWrite for CommandPipelineInput<T>
where
T: Copy + fmt::Display + Unpin
{
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context,
buf: &[u8]
) -> Poll<io::Result<usize>> {
if ... | Rust | 0 |
m<E> for TransitionResult
where
E: Into<Error>,
{
fn from(e: E) -> Self {
TransitionResult::from_result(Err(e.into()))
}
}
impl<E> From<::std::result::Result<States, E>> for TransitionResult
where
E: Into<Error>,
{
fn from(res: ::std::result::Result<States, E>) -> Self {
TransitionR... | Rust | 0 |
logger.info(f"Endpoint name: {endpoint_name}")
# Test the deployed endpoint
logger.info("=" * 60)
logger.info("TESTING DEPLOYED ENDPOINT")
logger.info("=" * 60)
test_success = test_endpoint(endpoint_name)
i... | Python | 1 |
: 10.0,
target_frame_rate: 60.0,
frame_rate: 0.0,
frames_this_sec: 0.0,
this_sec: 0.0,
window: win,
window_size: math::Vec2i::zero(),
show_fps: true,
vsync: true,
};
console::Console::get().add_accessor("camera.fov", c as @console::Accessor);
console::Consol... | Rust | 0 |
r.organization
if channel not in organization.channels.all():
raise ValidationError('The channel does not belong to your organization.')
return data
class SubscribeSerializer(serializers.Serializer):
video_id = serializers.CharField()
endpoint_http = serializers.URLField()
... | Python | 1 |
zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [lmem_pcclcr](index.html) module"]
pub struct L... | Rust | 0 |
;
use std::io;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, ExitStatus, Stdio};
use std::{env, process};
use anyhow::{ensure, Context, Result};
use cargo_metadata::Message;
use log::{debug, error, warn};
use serde::Deserialize;
use structopt::StructOpt;
use self::cli::Opt;
use crate::firebird::s... | Rust | 0 |
]
.iter().cloned().collect();
TransactionTypeMap {
m: map,
}
}
}
impl TWHashMap for TransactionTypeMap {
fn get_value_from_key(&self, key: &str) -> Option<&u16> {
self.m.get(key)
}
fn get_key_from_value(&self, value: u16) -> Option<&'... | Rust | 0 |
e indicated the number described by `digits`.
/// Due to the exponential nature of Knuth's Yllion system, however, this
/// function may output yllion names that could not by outputted by any input to
/// the `full_name` function. Unfortunately, there are still some inputs too
/// large for this function to handle at t... | Rust | 0 |
fn from(args: (&str, &str, &str)) -> Self {
let (stype, sour, speer) = args;
let mut type_: [c_char; NG_TYPESIZ as usize] = [0; NG_TYPESIZ as usize];
let mut ourhook: [c_char; NG_HOOKSIZ as usize] = [0; NG_HOOKSIZ as usize];
let mut peerhook: [c_char; NG_HOOKSIZ as usize] = [0; ... | Rust | 0 |
x8C40`"]
#[doc = "* **Group:** InternalFormat"]
pub const GL_SRGB: GLenum = 0x8C40;
#[doc = "`GL_SRGB8: GLenum = 0x8C41`"]
#[doc = "* **Group:** InternalFormat"]
pub const GL_SRGB8: GLenum = 0x8C41;
#[doc = "`GL_SRGB8_ALPHA8: GLenum = 0x8C43`"]
#[doc = "* **Group:** InternalFormat"]
pub const GL_SRGB8_A... | Rust | 0 |
E: TypedCollection<Vec<u8>, String> = TypedCollection::new("table");
fn numeric_identity(k: &Vec<u8>) -> i64 {
i64::from_le_bytes(k.clone().try_into().unwrap())
}
fn uniqueness_violation(a: &String, b: &String) -> bool {
a == b
}
let collection = TABLE.get(stash)?;
fn commit(
... | Rust | 0 |
# This file is part of Supysonic.
# Supysonic is a Python implementation of the Subsonic server API.
#
# Copyright (C) 2021-2023 Alban 'spl0k' Féron
#
# Distributed under terms of the GNU AGPLv3 license.
from gunicorn.app.base import BaseApplication
from ._base import BaseServer
class GunicornApp(BaseApplication):
... | Python | 1 |
] = [
"CREATE TABLE repo (
url TEXT UNIQUE NOT NULL,
status TEXT NOT NULL,
reference_count INTEGER NOT NULL
)",
];
// Open a connection to the database.
pub fn open() -> Result<rusqlite::Connection> {
let conn = Connection::open("auto-clip... | Rust | 0 |
ll == "bash" || shell == "zsh" {
data = format!("export {}=\"{}\"", result.0, result.1);
} else if shell == "tcsh" || shell == "csh" {
data = format!("setenv {} \"{}\"", result.0, result.1);
} else if shell == "python" {
data = format!("os.environ[\"{}\"] = \"{}\";", ... | Rust | 0 |
from django import forms
from django_select2.forms import Select2Widget
from blog.models import Post, Category
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields=['title', 'content','author']
widgets={
'title': forms.TextInput(attrs={'class':'form-control',"place... | Python | 1 |
from unittest.mock import patch
from tests.config import INIT_RESP, NEXT_BOOT_PXE_BAD, NEXT_BOOT_PXE_OK
from tests.test_base import TestBase
class TestNextBootPxe(TestBase):
option_arg = "--pxe"
@patch("aiohttp.ClientSession.delete")
@patch("aiohttp.ClientSession.post")
@patch("aiohttp.ClientSession... | Python | 1 |
assert_eq!(original, decoded, "Invalid encoding/decoding");
});
}
#[test]
fn btree_map_test() {
executor::block_on(async {
let mut original = BTreeMap::new();
original.insert(1, "Hello".to_owned());
original.insert(2, "World".to_owned());
ori... | Rust | 0 |
ple:
//!
//! 1. Your crate creates a custom resource definition using the apiextensions v1 API. This API is only available in Kubernetes 1.16+,
//! so your crate would fail to compile if a lower feature was enabled.
//!
//! 1. Your crate creates a custom resource definition. If the `v1_16` or later feature is enable... | Rust | 0 |
Finish {B} descriptors spend {step_time:.4f}s')
desc = np.concatenate(desc_list, 0).reshape([B, desc_len])
return desc, keypoints, n
def calculate_M(source_desc, target_desc):
"""
Find the mutually closest point pairs in feature space.
source and target are descriptor for 2 point cloud key poi... | Python | 1 |
1, 0), (0, -1), (-1, 0))
skews = ((2, 2), (2, 1/10), (2, 1/100), (2, 1/1000))
for ax, (sx, sy) in zip(ax_arr.ravel(), skews):
k = 0
for prescale, centers in zip((1 - .0001, (1 - .0001) / np.sqrt(2)),
(on_axis_centers, diag_centers)):
for j, (x_... | Python | 1 |
4(socket_addr_v4) => Socks5Addr::V4(socket_addr_v4),
SocketAddr::V6(socket_addr_v6) => Socks5Addr::V6(socket_addr_v6),
};
let mut stream =
start_and_connect_to_server_remote(local_tcp_server_addr)?;
// Handshake.
stream.write_all(&[0x05, 0x01, 0x00])?;
le... | Rust | 0 |
reference_pointer4;
// let alias_2 = &mut var_reference_pointer4;
println!("{:p}", var_reference_pointer1);
// Dereference the Pointer using the * Dereferencing Operator to
// access the Value at the Memory Stack address that it points to
println!("{}", *var_reference_pointer1 + var_binding2);
... | Rust | 0 |
_KHR_debug"))))]
pub fn glGetDebugMessageLogKHR_is_loaded() -> bool {
!glGetDebugMessageLogKHR_p.load(RELAX).is_null()
}
/// [glGetError](http://docs.gl/es3/glGetError)()
/// * return value group: ErrorCode
#[cfg_attr(feature = "inline", inline)]
#[cfg_attr(feature = "inline_always", inline(always))]
... | Rust | 0 |
(b) => {
if b {
write!(f, "長南")
} else {
write!(f, "南")
}
}
SSE => write!(f, "南南東"),
SE(b) => {
if b {
write!(f, "長南東")
} else {
... | Rust | 0 |
}}
}
type Small = [u8; SMALL_STRUCT];
pub struct SmallStruct<T> {
storage: Small,
marker: PhantomData<T>,
}
impl<T> SmallStruct<T> {
pub fn new(elem: T) -> Self {
unsafe {
let mut ret = SmallStruct { storage: mem::uninitialized(), marker: PhantomData };
std::ptr::copy_no... | Rust | 0 |
if fixture_data['team_h'] == team_id:
# Team is playing at home
opponent = away_team
venue = 'H'
else:
# Team is playing away
opponent = home_team
venue = 'A'
result += f"- **GW{gw... | Python | 1 |
# Taken from https://github.com/osmr/imgclsmob/blob/master/pytorch/pytorchcv/models/shufflenet.py
import torch
import torch.nn as nn
from deeplite_torch_zoo.src.dnn_blocks.common import ConvBnAct, DWConv, get_activation
from deeplite_torch_zoo.src.dnn_blocks.pytorchcv.common import ChannelShuffle
class ShuffleUnit(... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.