text string | label_name string | labels int64 |
|---|---|---|
else {
Err(PairingError::UnexpectedResponse)
}
}
status_code => {
let raw_response = response.text().await?;
Err(PairingError::ApiError(status_code, raw_response))
}
}
}
//! Errors that may occur in the compilation of Tortuga input.
pub ... | Rust | 0 |
ed_root5)
expected5 = [1, None, 2, None, 3]
print(f"Test Case 5 Input: [1, 2, null, 3]")
print(f"Test Case 5 Output: {output5}")
print(f"Test Case 5 Expected: {expected5}")
print(f"Test Case 5 Passed: {output5 == expected5}")
print("-" * 20)
# Custom Test Case: Tree with missing children
# Input: 4
# /
# ... | Python | 1 |
NUMPAD_ENTER = 335,
KB_NUMPAD_EQUAL = 336,
KB_LEFT_SHIFT = 340,
// KB_SHIFT = KB_LEFT_SHIFT,
KB_LEFT_CONTROL = 341,
// KB_CONTROL = KB_LEFT_CONTROL, KB_SHORTCUT = KB_CONTROL,
KB_LEFT_ALT = 342,
KB_LEFT_SUPER = 343,
KB_RIGHT_SHIFT = 344,
KB_RIGHT_CO... | Rust | 0 |
e generated for TOTP/HOTP
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Digits {
/// Six digits will be generated for the TOTP
Six = 6,
/// Eight digits will be generated for the TOTP
Eight = 8,
}
impl FromStr for Digits {
type Err = Error;
fn from_str(digits: &str) -> Result<Self, Self::Err... | Rust | 0 |
::Request::new(method, uri.unwrap());
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
let serialized = serde_json::to_string(&body).unwrap();
req.headers_mut().set(hyper::header::ContentType:... | Rust | 0 |
from pathlib import Path
import pytest
import requests
import responses
from poetrify.files import Pipfile
from poetrify.files import RequirementsTxt
@pytest.fixture()
def fixture():
return Path(__file__).parent / "fixtures" / "Pipfile"
@pytest.fixture()
def pypi_json():
return Path(__file__).parent / "fix... | Python | 1 |
te::Reg<ch_conf1::CH_CONF1_SPEC>,
#[doc = "0x9c - Current duty cycle for channel %s"]
pub ch7_duty_r: crate::Reg<ch_duty_r::CH_DUTY_R_SPEC>,
#[doc = "0xa0 - Timer %s configuration"]
pub timer0_conf: crate::Reg<timer_conf::TIMER_CONF_SPEC>,
#[doc = "0xa4 - Timer %s current counter value"]
pub tim... | Rust | 0 |
[0], a[1], c[1], a[2], b[2], c[2]]))
.map(|(cell, adjacent)| match cell {
b'*' => '*',
_ => match adjacent.iter().filter(|&&c| c == b'*').count() as u8 {
0 => ' ',
n => char::from(b'0' + n),
},
... | Rust | 0 |
_id: "robert_near".to_string(),
signer_account_pk: vec![0, 1, 2],
predecessor_account_id: "jane_near".to_string(),
input,
block_index: 0,
block_timestamp: 0,
epoch_height: 0,
account_balance: 0,
account_locked_balance: 0,
... | Rust | 0 |
rue
end_message_start_time = time.time()
# Update trail positions and colors with hue
trail_positions.append(tuple(ball_pos))
hue = (elapsed_time % 360) / 360.0
rgb_color = colorsys.hsv_to_rgb(hue, 1.0, 1.0)
color = (int(rgb_color[0] * 255), int(rgb_color[1] * 255), int(rgb_color[2] * 255))... | Python | 1 |
#!/usr/bin/env python3
"""
Clean up existing transcript files by extracting only the transcript text
This utility helps clean transcript files that contain API response metadata,
extracting only the actual transcript text for better readability.
Usage:
python clean_transcript.py input_file.txt
python clean_tr... | Python | 1 |
and_upper, f_out_lower_and_upper_x,
norm=c_norm, cmap='viridis'
)
check_array_z = np.zeros(len(zsamples_lower_and_upper))
check_array_y = np.zeros(len(ysamples_lower_and_upper))
for i in range(len(zsamples_lower_and_upper)):
check_array_z[... | Python | 1 |
ndpoint};
use std::mem;
use std::str;
use syscall::{Error as SyscallError, Result as SyscallResult};
use syscall;
use byteorder::{ByteOrder, NetworkEndian};
use device::NetworkDevice;
use port_set::PortSet;
use super::socket::{DupResult, SchemeFile, SchemeSocket, SocketFile, SocketScheme};
use super::{Smolnetd, Socket... | Rust | 0 |
Functio\
nDecl.OverloadR\toverloads\x1a\x89\x02\n\x08Overload\x12\x1f\n\x0boverlo\
ad_id\x18\x01\x20\x01(\tR\noverloadId\x126\n\x06params\x18\x02\x20\x03(\
\x0b2\x1e.google.api.expr.v1alpha1.TypeR\x06params\x12\x1f\n\x0btype_par\
ams\x18\x03\x20\x03(\tR\ntypeParams\x12?\n\x0bresult_type\x18\x04\x20\
... | Rust | 0 |
# Code generated by Lark OpenAPI.
import lark_oapi as lark
from lark_oapi.api.task.v2 import *
def main():
# 创建client
client = lark.Client.builder() \
.app_id(lark.APP_ID) \
.app_secret(lark.APP_SECRET) \
.log_level(lark.LogLevel.DEBUG) \
.build()
# 构造请求对象
request: Cr... | Python | 1 |
h.object(ProgressBarComponent, "_load_ui"):
with patch.object(ProgressBarComponent, "_load_stylesheet"):
component = ProgressBarComponent()
# Assert
assert hasattr(component, "progress_manager"), (
"Should have a progress manager"
... | Python | 1 |
"""
Конфигурация безопасности для системы аутентификации
"""
import os
import secrets
from typing import List, Dict, Any, Optional
from pydantic_settings import BaseSettings
from pydantic import field_validator, model_validator, ConfigDict
import logging
logger = logging.getLogger(__name__)
class SecuritySettings(Ba... | Python | 1 |
UES cases. If selectStmt is NULL, then the query"]
#[doc = " is INSERT ... DEFAULT VALUES."]
#[doc = ""]
#[repr(C)]
#[derive(Debug, Hash, PartialEq, Eq)]
pub struct InsertStmt {
pub type_: NodeTag,
pub relation: *mut RangeVar,
#[doc = " relation to insert into"]
pub cols: *mut List,
#[doc = " optio... | Rust | 0 |
right eye first).
SideBySideRightEyeFirst,
/// Anaglyph (green/magenta).
AnaglyphGreenMagenta,
/// Both eyes laced in one Block (left eye is first).
LacedLeftEyeFirst,
/// Both eyes laced in one Block (right eye is first).
LacedRightEyeFirst,
}
impl From<u64> for StereoMode {
fn from(d:... | Rust | 0 |
og_dir, gradients)
else:
basename = osp.basename(runner.work_dir.rstrip(osp.sep))
date = osp.basename(runner._log_dir.rstrip(osp.sep))
self.out_dir = osp.join(self.out_dir, basename, date, gradients)
save_dir = self.out_dir
... | Python | 1 |
}
}
}
}
<gh_stars>0
#![allow(unused)]
fn main() {
test_if_let();
stack_while_let();
for_pattern();
let_is_a_pattern();
let v = Vector { x: 10, y: 60, w: 6, z: 10 };
function_parameters_as_patterns(&v);
match_expression();
at_bindings();
}
fn at_bindings() {
enum... | Rust | 0 |
mut query_args: Vec<(String, String)> = Default::default();
if count > 0 {
query_args.push(("count".to_string(), count.to_string()));
}
if !exclude_fields.is_empty() {
query_args.push(("exclude_fields".to_string(), exclude_fields.join(" ")));
}
if !fields.... | Rust | 0 |
// For convenience, this represents both API errors as well as internal recoverable errors,
/// and maps them to appropriate status codes along with at least a minimally useful error
/// message in a plain text body, or a JSON body in the case of `UnprocessableEntity`.
#[derive(thiserror::Error, Debug)]
pub enum Error ... | Rust | 0 |
from cvzone.HandTrackingModule import HandDetector
import cv2
from HandTracking import lmList1, handType1, length
from ZoomGestureImage import tipOfFirstFinger
cap = cv2.VideoCapture(0)
cap.set(3, 1080)
cap.set(4, 720)
detector = HandDetector(maxHands=2, detectionCon=0.5, minTrackCon=0.5)
while True:
success, i... | Python | 1 |
f.head = node.next;
match self.head {
None => self.tail = None,
Some(mut head) => head.as_mut().prev = None,
}
node
})
}
#[inline]
fn push_back_node(&mut self, mut node: Box<Node<K, V>>) {
unsafe {
node.next =... | Rust | 0 |
form, ()),
"app_label": opts.app_label,
}
return self.render_add_type_form(request, context, form_url)
def render_add_type_form(self, request, context, form_url=""):
"""
Render the page type choice form.
"""
opts = self.model._meta
app_label = opt... | Python | 1 |
dden)]
pub struct _TCD7_SOFF;
#[doc = "`read()` method returns [tcd7_soff::R](tcd7_soff::R) reader structure"]
impl crate::Readable for TCD7_SOFF {}
#[doc = "`write(|w| ..)` method takes [tcd7_soff::W](tcd7_soff::W) writer structure"]
impl crate::Writable for TCD7_SOFF {}
#[doc = "TCD Signed Source Address Offset"]
pub... | Rust | 0 |
![
ActivityData::new(("job3", Some(3.), "delivery", Some((3., 8.)), Some((None, None)))),
ActivityData::new(("job2", Some(2.), "delivery", Some((9., 14.)), Some((Some((3., 1., 8., 9.)), None)))),
ActivityData::new(("job1", Some(1.), "delivery", Some((15., 20.)), Some((Some((2., 1., 14., 15... | Rust | 0 |
> { diff: -1, len: 5 });
test_splitable_methods_valid(Run2::<false> { diff: 1, len: 5 });
test_splitable_methods_valid(Run2::<false> { diff: 2, len: 5 });
test_splitable_methods_valid(Run2::<false> { diff: -1, len: 5 });
}
#[test]
fn alternate_assumes_positive_first() {
let... | Rust | 0 |
h = 6*dpi
# make a Path that spans the whole w-h rectangle
x = np.linspace(0, w, N)
y = np.ones(N) * h
y[::2] = 0
path = Path(np.vstack((x, y)).T)
# effectively disable path simplification (but leaving it "on")
path.simplify_threshold = 0
# setup the minimal GraphicsContext to dra... | Python | 1 |
#
# MIT No Attribution
#
# Copyright (C) 2010-2023 Joel Andersson, Joris Gillis, Moritz Diehl, KU Leuven.
#
# 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 restric... | Python | 1 |
x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'),
128, 64, framebuf.MONO_VLSB)
spi1 = SoftSPI(baudrate=100000, polarity = 0, phase = 0, sck = Pin(12), mosi = Pin(11), miso = Pin(8))
bme = BME280_SPI(spi1, 10)
spi2 = SoftSPI(baudrate=100000, polarity = 0, phase = 0, sck = Pin(27... | Python | 1 |
_data[index].1
})
.with_style(value_text_style)
.top_left_with_margins_on(
*container_line,
0.0,
ADVANCED_SETTINGS_LINE_VALUE_PADDING_LEFT,
)
.set(config.advanced_container_line_values[index], &mut master.ui);
}
}
fn form_settings<'a>(mast... | Rust | 0 |
))]
{
write!(f, "SimpleToken({:02X})", self.token)
}
}
}
#[derive(Copy, Clone)]
pub struct BS8 {
pub bytes: [u8; 8],
#[cfg(debug_assertions)]
name: &'static str,
}
impl BS8 {
pub fn new(bytes: [u8; 8], _debug_name: &'static str) -> Self {
Self {
byte... | Rust | 0 |
"""Generate the code reference pages."""
from pathlib import Path
import mkdocs_gen_files
nav = mkdocs_gen_files.Nav()
# Iterate through all Python files in src directory
for path in sorted(Path("src").rglob("*.py")):
module_path = path.relative_to("src").with_suffix("")
doc_path = path.relative_to("src").... | Python | 1 |
r#"
const a = () => ({
get this() { this;arguments },
set arguments(a = this) { this;arguments },
get [this]() { this;arguments },
})
"#,
r#"
var _this = this;
const a = function () {
return {
get this() {
this;
arguments;
},
set arguments(a = this) {
this;
arguments... | Rust | 0 |
());
/// assert!(writer.get_mut().is_empty());
/// ```
pub fn get_mut(&mut self) -> &mut W {
&mut self.inner
}
/// Unwraps and returns the underlying writer.
///
/// # Examples
///
/// ```
/// use noodles_vcf as vcf;
/// let writer = vcf::Writer::new(Vec::new());
... | Rust | 0 |
'''OpenGL extension EXT.abgr
This module customises the behaviour of the
OpenGL.raw.GL.EXT.abgr to provide a more
Python-friendly API
Overview (from the spec)
EXT_abgr extends the list of host-memory color formats. Specifically,
it provides a reverse-order alternative to image format RGBA. The ABGR
component... | Python | 1 |
false => RDMAS_A::_0,
true => RDMAS_A::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline(always)]
pub fn is_0(&self) -> bool {
*self == RDMAS_A::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline(always)]
pub fn is... | Rust | 0 |
"Response",
method=request.method,
uri=request.path,
status=response.status,
remote_addr=remote_addr,
took_seconds=round(took, 2),
),
exc_info=exc_info,
)
def maybe_commander(self, request: Request) -> t... | Python | 1 |
, high, false, &mut paths),
};
let iter = Iter {
paths,
frwrd: false,
};
Reverse {
range,
iter,
fin: false,
low: marker::PhantomData,
}
}
/// Return a random entry from this index.
pub fn random... | Rust | 0 |
weighted_sum += weight * metric.result()
return weighted_sum
def reset_states(self):
for metric in self._metrics:
metric.reset_states()
BinarySparseRecall = _get_binary_sparse_metric(tf.metrics.Recall)
BinarySparsePrecision = _get_binary_sparse_metric(tf.metrics.Precision)
BinarySparseRecallAtPreci... | Python | 1 |
ка:")
print(f" 📁 Всего категорий: {total_categories}")
print(f" 🏥 Всего услуг: {total_services}")
# Статистика по категориям
for cat_data in CATEGORIES_DATA:
count = db.query(Service).filter(Service.category_code == cat_data["code"]).count()
print(f" ... | Python | 1 |
ver timestamp values that meet the criteria
// of the bus with the highest bus `id`. For example, if the highest bus `id` is 900 and its
// associated delay is 10 minutes, the timestamps considered are 890, 1790, 2690, etc. This
// eliminates needing to loop over timestamps from 0-889, 891-1789, etc., that would be was... | Rust | 0 |
efault functions are
// parented to their trait to find the first private thing as the trait).
struct B;
trait A { fn foo(&self) {} }
impl A for B {}
mod tests {
use super::A;
fn foo() {
let a = super::B;
a.foo();
}
}
}
pub fn main() {}
// This... | Rust | 0 |
7];
cmp::min(key_max, n)
};
let gc_period = [0, 1, 16, 32, 256, 1024][rng.gen::<usize>() % 6];
let modul = key_max / n_threads;
println!(
"test_map seed:{} key_max:{} ops:{} threads:{} modul:{}",
seed, key_max, n_ops, n_threads, modul
);
let mut map: Map<Ky, u64> = {
... | Rust | 0 |
sthru_options!(inner);
send_desc_passthru_handler!(inner, R);
fn write_payload(
&self,
msg: &mut dyn MessageWrite,
_socket_addr: &IC::SocketAddr,
) -> Result<(), Error> {
(self.writer)(msg)
}
}
<gh_stars>10-100
//! Thread-local RNG based on SFMT
use super::SFMT;
use ra... | Rust | 0 |
nto_iter()
.filter_map(Result::ok)
.filter(|f| !f.file_type().is_dir())
.filter_map(|e| {
let p = e.into_path();
let count = count_linenumbers(&p);
if p.extension() == Some(OsStr::new("stderr")) && count > LENGTH_LIMIT {
Some((p, count))
... | Rust | 0 |
fruits="apple","banana","grapes","orange","papaya","tomato"
print(fruits[:3])
li=["apple","banana","grapes","orange","papaya","tomato"] | Python | 1 |
# -*- coding: utf-8 -*-
#
# Copyright 2018 Google 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 ... | Python | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
from ctypes.wintypes import DWORD, HRGN
from ctypes import windll, c_bool, c_int, POINTER, Structure
from ctypes import WINFUNCTYPE
from PyQt5.QtGui import QPainter, QPen
from PyQt5.QtWidgets import QApplication, QVBoxLayout, QPushButton
from Py... | Python | 1 |
..opts
};
let generator = Perlin::new();
let generator = generator.set_seed(opts.seed);
let generator = Turbulence::new(&generator);
let mut builder = Builder::new(&generator, &cave_opts);
builder.generate();
if opts.is_image {
use crate::image::BuilderWriter;
builder.w... | Rust | 0 |
'''zh-cn
数据生成器,(支持根据labelme格式的数据生成各种形变的表格,结果依旧是labelme的格式)
原始数据目录:
root_dir
├──dataset
│ ├── image.png|jpg
│ ├── image.json
│ ├── *.png|jpg
│ └── *.json
└──data_gen.py # 脚本文件
最后生成的目录结构:
root_dir
├──dataset
│ ├── image.png|jpg
│ ├── image.json
│ ├── *.png|jpg
│ └── *.json
├──output_dir
│ ├── image_... | Python | 1 |
: ::prost::alloc::vec::Vec<::prost_types::Any>,
}
#![deny(rust_2018_idioms, warnings)]
#![deny(clippy::all, clippy::pedantic)]
#![allow(
clippy::cognitive_complexity,
clippy::large_enum_variant,
clippy::similar_names,
clippy::module_name_repetitions,
clippy::use_self,
clippy::match_same_arms,
... | Rust | 0 |
5), 2)
# Show image
cv2.imshow("Hand and Finger Tracking", img)
# Handle key presses
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
elif key == ord('c'):
show_finger_count = not show_finger_count
elif key == ord('d'... | Python | 1 |
# coding: utf-8
# flake8: noqa
"""
Charity API
The Charity API allows third-party developers to search for and access details on supported charitable organizations. # noqa: E501
OpenAPI spec version: v1.2.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ i... | Python | 1 |
0,
)))
}
}
#[doc(alias = "gtk_tree_row_reference_get_path")]
#[doc(alias = "get_path")]
pub fn path(&self) -> Option<TreePath> {
unsafe {
from_glib_full(ffi::gtk_tree_row_reference_get_path(mut_override(
self.to_glib_none().0,
)))
... | Rust | 0 |
e_path = "RTL_dataset/saved/vericontaminated/verilogeval.json"
with open(source_path, "r") as f:
data = [json.loads(line) for line in f.readlines()]
json_data = []
for i, item in enumerate(data):
item_temp = {}
item_temp["Instruction"] = item["prompt"]
... | Python | 1 |
{ bits }
}
#[doc = "Bit 1 - Division factor for the main PLL (PLL) and audio PLL (PLLI2S) input clock"]
#[inline(always)]
pub fn pllm1(&self) -> Pllm1R {
let bits = {
const MASK: u8 = 1;
const OFFSET: u8 = 1;
((self.bits >> OFFSET) & MASK as u32) as u8
... | Rust | 0 |
std::io::Result;
use interface::Interface;
pub struct LoopbackInterface {
packets: Vec<Ipv4>
}
impl LoopbackInterface {
pub fn new() -> Self {
LoopbackInterface {
packets: Vec::new()
}
}
}
impl Interface for LoopbackInterface {
fn ip(&self) -> Ipv4Addr {
Ipv4Addr... | Rust | 0 |
doc = "Descriptor Address\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--writ... | Rust | 0 |
f.deserialize(resp)
self.assertEqual(len(datas), 0)
event = self._create_event(42, [BOService.PAAS], BOEvent.INCIDENT)
resp = self.api_client.get(url)
datas = self.deserialize(resp)
self.assertEqual(len(datas), 1)
event.end()
resp = self.api_client.get(url)
... | Python | 1 |
'a,'b> { }
// trait Bar1<'b,'c> { }
//
// Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
// The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
// reason is similar to the previous example: any impl of
// `T:Foo1<'x>` must show that `for<'b> T: ... | Rust | 0 |
@ NLS { newline, space }, after_r)| {
satisfy_map(get_sp_kind).or_not().map(move |kind| match kind {
None => Ok(nls),
Some(SpaceKind::NL(NLKind::CarriageReturn)) => Err((NLS { newline: newline + 1, space: 0 }, true)),
Some(SpaceKind::NL(NLKind::LineFeed)) => {
... | Rust | 0 |
size[1] / stride) # 640x640 GFLOPS
except (ImportError, Exception):
fs = ''
logger.info(f"Model Summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}")
def load_classifier(name='resnet101', n=2):
# Loads a pretrained model reshaped to n-class output
model = torc... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : HaiFeng
# @Email : 24918700@qq.com
# @Time : 2022/09/11
import os
import sys
import platform
import ctypes
import copy
from .struct import *
class Quote:
def __init__(self):
dllpath = os.path.join(os.path.abspath(os.path.dirname(__file__))... | Python | 1 |
_tiles(offset, 16 * 7, true);
let pokemon_logo = Img::new(&16, &7, &tiles)?;
Ok(pokemon_logo)
}
pub fn set_pokemon_logo_img(&self, pokemon_logo: &Img) -> Result<Patch> {
let old_pokemon_logo = self.get_pokemon_logo_img()?;
let old_pokemon_logo_data = old_pokemon_logo.to_2bpp()... | Rust | 0 |
import os
dirname = os.path.dirname(__file__)
import sys
sys.path.append(os.path.join(dirname, '../'))
from resnet import *
from resnet_masked import *
######## ResNet without any pruning
def ResNet18():
return ResNet(BasicBlock, [2,2,2,2], n_class=100)
def ResNet18_gn():
return ResNet(BasicBlock, [2,2,2,2... | Python | 1 |
import os
import re
import logging
from aiogram import Bot, Dispatcher, types
from aiogram.dispatcher.filters import Text
from aiogram.utils import executor
from pytube import YouTube
# Замените на ваш токен бота
API_TOKEN = 'TOKEN'
# Настройка логирования
logging.basicConfig(level=logging.INFO)
logger = logging.ge... | Python | 1 |
# If the schema of the statement does not exactly match the schema of the current entity,
# find a common parent schema.
elif current_schema.name != schema:
try:
current_schema = model.common_schema(current_schema, schema)
... | Python | 1 |
_Id = params.get("Id")
self._TemplateId = params.get("TemplateId")
if params.get("Notification") is not None:
self._Notification = PrometheusNotificationItem()
self._Notification._deserialize(params.get("Notification"))
self._UpdatedAt = params.get("UpdatedAt")
se... | Python | 1 |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2021 Fetch.AI Limited
#
# 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 ... | Python | 1 |
'query'] == filter['query'] and \
query_info['start_time'] == filter['start_time']:
db.session.delete(row)
else:
history.delete()
db.session.commit()
except Exception:
db.session.rollback()
# do ... | Python | 1 |
"""
import tkinter as tk
interfaz = tk.Tk()
interfaz.title("ARCHIVADOR 3.000")
interfaz.geometry("680x500")
# Hacemos que la raíz use grid y se expanda
interfaz.grid_rowconfigure(0, weight=1)
interfaz.grid_columnconfigure(0, weight=1)
pantalla_inicio = tk.Frame(interfaz)
pantalla_dos = tk.Frame(interfaz)
for f in (... | Python | 1 |
the subterms of an implicit conjunction. The
/// vector may be empty.
///
/// Note that if we do have to construct a remainder predicate, it must be
/// constructed afresh, since we can't modify the predicate we were handed.
/// Since we use `Box` and not `Rc` in our parse tree, this could end up copying
/// a lot if ... | Rust | 0 |
rior_idx with long tensor
# ensure every gt matches with its prior of max overlap
# 正解座標の物体数でループ
for j in range(best_prior_idx.size(0)):
best_truth_idx[best_prior_idx[j]] = j
# 8732個の各ボックスにマッチする正解座標をmatchesにセット
matches = truths[best_truth_idx] # Shape: [num_priors,4]
# 正解ラベルにクラス... | Python | 1 |
ool::new(4, 512);
let mut buf = bufs.pop();
loop {
match reader.read_event(&mut buf) {
Ok(XmlEvent::Start(ref e)) => match reader.decode(e.name())? {
"rss" => continue,
"channel" | "feed" | "rdf:RDF" => {
return Rss::from_xml(&bufs, &mut re... | Rust | 0 |
#-*-coding:utf-8-*-
"""
Copyright (c) 2012 wong2 <wonderfuly@gmail.com>
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
without limitation the rights to use, copy, ... | Python | 1 |
tracking_is_moving
def _updateUI(self):
new_transforms = self.client.get_current_transforms()
if new_transforms is None or self._check_still_moving(new_transforms):
self._widget.takeButton.setEnabled(False)
else:
self._widget.takeButton.setEnabled(True)
def han... | Python | 1 |
from rest_framework import serializers
from User.models import User
class UserProfileInfoSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ["username", "first_name", "last_name"] | Python | 1 |
d_expect_response(
&mut remote,
peer_enable_ind_reporting_cmd,
vec![at::Response::Ok],
)
.await;
let call_hold_info_cmd = at::Command::ChldTest {};
let expected6 = at::success(at::Success::Chld {
commands: vec![
"0".to_string(),
"1".to_string(),
... | Rust | 0 |
"""
Create Date: 2024-08-20 18:50:23.266628
"""
import textwrap
from alembic import op
from flask import current_app
revision = "0461_user_research_email"
down_revision = "0460_letter_rates_july_2024"
template_id = "55bcb671-4924-46c5-a00d-1a9d48458008"
template_content = textwrap.dedent(
"""
Hi ((name))
# How... | Python | 1 |
_response.is_success() {
Ok(crate::adapters::to_json(github_response)?)
} else {
match github_response.status_code() {
404 => Err(AppsListPlansError::Status404(crate::adapters::to_json(github_response)?)),
401 => Err(AppsListPlansError::Status401(crate::ad... | Rust | 0 |
import requests
from bs4 import BeautifulSoup
def get_image_url(URL):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36"
}
response = requests.get(URL, headers = headers)
soup = BeautifulSoup(response.te... | Python | 1 |
se_role.members.add(rando)
assert access.has_obj_m2m_access(config) # has access to both
def test_new_execution_environment_access(self, rando):
ee = ExecutionEnvironment.objects.create(name='test-ee', image='quay.io/foo/bar')
access = JobLaunchConfigAccess(rando)
assert access.ca... | Python | 1 |
Kana => VirtualKeyCode_::Kana,
Kanji => VirtualKeyCode_::Kanji,
LAlt => VirtualKeyCode_::LAlt,
LBracket => VirtualKeyCode_::LBracket,
LControl => VirtualKeyCode_::LControl,
LShift => VirtualKeyCode_::LShift,
LWin => VirtualKeyCode_::LWin,
Mail => VirtualKeyCode_::Mail,
MediaSelect => Vir... | Rust | 0 |
{} - points: {}",
points_winner.name, points_winner.travel_distance, points_winner.points
);
let distance_winner = deers
.iter()
.max_by(|a, b| a.travel_distance.cmp(&b.travel_distance))
.unwrap();
println!(
" Winning deer by distance = {} - traveled: {} - points: ... | Rust | 0 |
::*;
#[test]
fn test_overflow() {
assert_eq!(
overflow("I'm a pingoo with an apple", 15),
vec!["I'm a pingoo".to_string(), "with an apple".to_string()],
);
assert_eq!(
overflow("I'm a pingoo with an apple", 32),
vec!["I'm a pingoo with an ... | Rust | 0 |
'T1']
])
assert E | eo != 0
# Make a dcga translation rotor to move the ellipsoid
Tc1 = 1 - 0.5 * py * e2 * einf1
Tc2 = 1 - 0.5 * py * e7 * einf2
Tdcga = (Tc1 * Tc2).normal()
# Construct a rotation rotor
theta = np.pi / 2
RC1 = np.e ** (-0.5 * th... | Python | 1 |
on (32-bit) floating-point elements in a and b, alternatively subtract and add packed elements in c from/to the intermediate result, and store the results in dst using zeromask k (elements are zeroed out when the corresponding mask bit is not set).
///
/// Rounding is done according to the rounding\[3:0\] parameter, wh... | Rust | 0 |
: '',
'gulpfile.ls' : '',
'ini' : '',
'ledger' : '',
'package.json' : '',
'package-lock.json' : '',
'.ncmpcpp' : '',
'playlists' ... | Python | 1 |
Hash)]
#[allow(missing_docs)]
pub enum CapProp {
/// Current position of the video file in milliseconds or video capture
/// timestamp.
PosMsec = 0,
/// 0-based index of the frame to be decoded/captured next.
PosFrames = 1,
/// Relative position of the video file: 0 - start of the film, 1 - en... | Rust | 0 |
from microbit import i2c, sleep
def nastav_PWM_kanaly(kanal_on, kanal_off, rychlost):
# je nesmirne dulezite vzdy mit zapnuty jen jeden kanal,
# tedy tato funkce zarucuje, ze se druhy kanal vypne
i2c.write(0x70, kanal_off + bytes([0]))
i2c.write(0x70, kanal_on + bytes([rychlost]))
return 0
def jed... | Python | 1 |
config = {
# training
"batch_size": 24,
"learning_rate": 1e-4,
"weight_decay": 1e-5,
"lr_patience": 10,
"epochs": 150,
# dataset
"dataset_dir": "./MTAT/",
"filetype": "wav",
"items_per_track": 6,
"only_from_tag": 0, # 0 for all tracks
"tracks_per_genre": 0, # 0 for all ... | Python | 1 |
import asyncio
from pyrogram import *
from pyrogram import filters
from pyrogram.errors import YouBlockedUser
from pyrogram.types import *
from Zaid.modules.help import add_command_help
from Zaid.modules.basic.profile import extract_user
@Client.on_message(filters.command(["sg", "sa", "sangmata"], ".") & filters.me... | Python | 1 |
testtxt = document_text_list[2]
ra0, ra1 = make_anchor_range(highlighted_text, offset_begin, 2, document_text_list)
anc = make_anchor(highlighted_text, offset_begin, 2, document_text_list)
print anc
anc.support_anchor_list = []
## screw up the offset; this should break the quick... | Python | 1 |
. the amount of `=` characters in the boundary.
///
/// # Examples
///
/// ```
/// # use std::str::FromStr;
/// # use hrx::HrxArchive;
/// let arch_str = r#"<===> input.scss
/// ul {
/// margin-left: 1em;
/// li {
/// list-style-type: none;
/// }
/// }
/... | Rust | 0 |
from collections.abc import Sequence
import math
from thunder.core.proxies import TensorProxy
from thunder.torch import TensorLike
from thunder.executors.apexex import apex_ex
APEX_FUSED_NORMS_AVAILABLE = True
try:
# Fused layer norm is only importable if torch.distributed is available
# https://github.com/... | Python | 1 |
Err(Error::MalformedUtf8(StreamPosition::of_blc(1,1,2),1)),
Err(Error::MalformedUtf8(StreamPosition::of_blc(2,1,2),1)),
Ok(' '),
]);
test_buf_exp(b"Hello\nFun!\n123\xc0", &[
Ok('H'),Ok('e'),Ok('l'),Ok('l'),Ok('o'),Ok('\n'),
Ok('F'),Ok('u'),Ok('n'),Ok('!'),Ok('\n... | Rust | 0 |
d_incin! {
{ "[`Stack`]" }
pub SharedIncin<T> of OwnedAlloc<Node<T>>
}
impl<T> fmt::Debug for SharedIncin<T> {
fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result {
write!(fmtr, "SharedIncin {} inner: {:?} {}", '{', self.inner, '}')
}
}
#[derive(Debug)]
struct Node<T> {
val: ManuallyDr... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.