text string | label_name string | labels int64 |
|---|---|---|
r("message/rfc822").unwrap()));
let body = format!("From:{}\nTo:{}\nSubject:{}\n\n{}\n",
from,
to,
subject,
body);
let client = Client::new();
let res = try!(client.post(url)
.... | Rust | 0 |
"""
文件名: Code/Chapter03/C13_RegMetircs.py
创建时间: 2023/2/4 5:30 下午
作 者: @空字符
公众号: @月来客栈
知 乎: @月来客栈 https://www.zhihu.com/people/the_lastest
"""
import numpy as np
def MAE(y, y_pre):
return np.mean(np.abs(y - y_pre))
def MSE(y, y_pre):
return np.mean((y - y_pre) ** 2)
def RMSE(y, y_pre):
return np.sqrt(... | Python | 1 |
imer};
use futures::future::{poll_fn, Either};
use futures::lock::{Mutex, MutexGuard, MutexLockFuture};
use futures::ready;
use rand::Rng;
use std::collections::BTreeMap;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll, Waker};
use std::time::{Duration, Instant};
const MAX_FRAME_SIZE: usize = 4096... | Rust | 0 |
n_eoa2seq_in, dean_eoa2seq_out = load_data(dean_f_in, dean_f_out)
if FLAGS.dup:
dean_eoa2seq_agg = seq_duplicate(dean_eoa2seq_in, dean_eoa2seq_out)
else:
dean_eoa2seq_agg = seq_generation(dean_eoa2seq_in, dean_eoa2seq_out)
eoa2seq_agg.update(dean_eoa2seq_agg)
if FL... | Python | 1 |
extern "C" {
pub fn BODY(x: SEXP) -> SEXP;
}
extern "C" {
pub fn CLOENV(x: SEXP) -> SEXP;
}
extern "C" {
pub fn RDEBUG(x: SEXP) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn RSTEP(x: SEXP) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn RTRACE(x: SEXP) -> ::std::os::raw::c_int;
}
extern "C" {
... | Rust | 0 |
wrap();
let closure = Closure::once(move || paint_and_schedule(&runner_ref, panicked));
window.request_animation_frame(closure.as_ref().unchecked_ref())?;
closure.forget(); // We must forget it, or else the callback is canceled on drop
Ok(())
}
// Only paint and schedule if ther... | Rust | 0 |
from typing import Dict
from fastapi import APIRouter, status
from app.schemas.text2motion import TextPrompt
from app.services.motion2mp4 import amass_motion2mp4_service
from app.services.text2motion import text2motion_generation_service
text2motion_router = APIRouter(prefix="")
@text2motion_router.post(
"/tex... | Python | 1 |
tions_class = detections_class[conf_sort_index]
# 进行非极大抑制
max_detections = []
while np.shape(detections_class)[0]:
# 取出这一类置信度最高的,一步一步往下判断,判断重合程度是否大于nms_thres,如果是则去除掉
max_detections.append(detections_class[0:1])
... | Python | 1 |
e('${FILENAME}', x) for x in source_include_list])
)
)
for enum in enums:
f.write(enum_util_conversion_begin.replace('${ENUM_NAME}', enum.name))
for value in enum.values:
f.write(enum_util_switch.replace('${ENUM_MEMBER}', value.name).replace('${ENUM_N... | Python | 1 |
ngle Redis Set, called `subjects`, exists to
//! track the complete set of known subject strings. This
//! facilitates discovery of the different subsets of the audit
//! log.
//!
//! Here is some pseudocode for the insertion logic of the
//! `LOG(e)` operation, where `e` is an object:
//!
//! ```redis-pseudo-code
//!... | Rust | 0 |
$crate::vector::Vector::<_, vector!(@count $($elem),*)>::new([ $($elem),* ])
};
}
/// Creates a [`Matrix`] from given elements.
///
/// # Example
///
/// ```rust
/// # #[macro_use] extern crate rowcol;
/// # use rowcol::prelude::*;
/// # fn main() {
/// let m1 = matrix![[1, 2], [3, 4]];
/// assert_eq!(m1 ... | Rust | 0 |
("UnvaultEmergency tx '{}' is still unconfirmed", unemer_txid);
}
}
Ok(())
}
fn maybe_confirm_emer(
db_path: &Path,
bitcoind: &BitcoinD,
db_vault: &DbVault,
emer_txid: &Txid,
) -> Result<bool, BitcoindError> {
if let (_, Some(height), _) = bitcoind.get_wallet_transaction(emer_txid)... | Rust | 0 |
hat order
//! * Job merging: merge identical / similar jobs in the queue to reduce workload
//! * Parallel execution: run jobs on multiple threads and lock jobs which should be run exclusively, they remain in the queue and don't occupy other resources
//! * Concurrent exclusion: key-based locking to avoid jobs running ... | Rust | 0 |
)
# Warn user if all samples have been filtered for a given test_case
all_filtered_test_cases: list[str] = []
for test_case, sizes in test_case_to_filtered_sizes.items():
for size in sizes:
if size == 0:
all_filtered_test_cases.append(test_case)
if all_filtered_test... | Python | 1 |
len(clean_client_idx), len(poison_client_idx)))
# 初始化local_list
node_list = []
for i in range(args.client_num):
# total_steps = int(len(subset_idx_list[i])/args.batch_size *
# args.epochs * args.round / args.client_num*args.select_num)
total_steps = args.round * ar... | Python | 1 |
) {
if let Some(var_100) = &input.compute_environment {
object.key("computeEnvironment").string(var_100);
}
if let Some(var_101) = &input.compute_resources {
let mut object_102 = object.key("computeResources").start_object();
crate::json_ser::serialize_structure_compute_resource_upd... | Rust | 0 |
24 24" height="24" viewBox="0 0 24 24" width="24"><g><rect fill="none" height="24" width="24"/><rect fill="none" height="24" width="24"/></g><g><g><g><path d="M16.7,5.3l1.44-1.44c0.32-0.32,0.09-0.85-0.35-0.85H11.5c-0.28,0-0.5,0.22-0.5,0.5V9.8c0,0.45,0.54,0.67,0.85,0.35 l1.45-1.45c1.97,1.46,3.25,3.78,3.25,6.42c0,0.66-0... | Rust | 0 |
"""Removes the cost_model field from Incident. Adds the cost_model field to IncidentType.
Revision ID: 50e99c66e72f
Revises: 3a33bc153e7e
Create Date: 2024-04-22 14:19:18.388675
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "50e99c66e72f"
down_revision = "3a33... | Python | 1 |
ccess_chain<'fx, 'a>(
fx: &mut FunctionCx<'fx, 'a, 'tcx>,
lvalue: &mir::Place<'tcx>,
) -> Variable<'tcx> {
use rustc_data_structures::indexed_vec::Idx;
fn access_chain_indices<'r, 'tcx>(
lvalue: &'r mir::Place<'tcx>,
mut indices: Vec<usize>,
) -> (&'r ... | Rust | 0 |
blow up. It did if the
# platform pow() was buggy, and Python didn't worm around it.
eq = self.assertEqual
a = -1.0
# The next two tests can still fail if the platform floor()
# function doesn't treat all large inputs as integers
# test_math should also fail if that is h... | Python | 1 |
one:
_addConsoleHandler(logger=logger, level=level, fmt=fmt)
if levelFile is not None:
# If not disabled, use patterned log-file: main-%03d.log
_addFileHandler(logger=logger, level=levelFile, fmt=fmt,
outDir=outDir, subDir=appId, filename="main.log",
... | Python | 1 |
.div_ip2();
}
if ecp::SEXTIC_TWIST == SexticTwist::M_TYPE {
zz.mul_ip();
zz.dbl();
yz.mul_ip();
yz.norm();
}
zz.norm(); // 3b.Z^2
yy.dbl();
zz.sub(&yy);
zz.norm(); // 3b.Z^2-Y^2
a.copy(&FP4::new_fp2s(&yz, &zz)); // -2YZ.Ys | 3b.Z^2-Y^2 | 3X^2.Xs
if ... | Rust | 0 |
the kernel.
#[allow(unused)]
pub unsafe fn as_pslice(&self) -> &'static [u8] {
core::slice::from_raw_parts(self.binary_paddr.0 as *const u8, self.size())
}
}
impl core::fmt::Debug for Module {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
let mut w = f.debug_struct(... | Rust | 0 |
(),
})
})
.map_err(|e| eprintln!("health server error: {}", e)),
);
})
.join()
.unwrap();
sync_status.join().expect("status syncer crashed");
component_watch.join().expect("component watcher crashed");
configuration_watch.join().unwrap(... | Rust | 0 |
, Ev>(&mut self, index: I, value: V)
where I: for<'r> PushOne<&'r mut LuaTable<L>, Err = Ei>,
V: for<'r, 's> PushOne<&'r mut PushGuard<&'s mut LuaTable<L>>, Err = Ev>,
Ei: Into<Void>,
Ev: Into<Void>,
{
match self.checked_set(index, value) {
Ok(()... | Rust | 0 |
};
ONER { bits }
}
}
<gh_stars>10-100
/*extern crate piston;
extern crate graphics;
extern crate glutin_window;
extern crate glium_graphics;
extern crate time;
use std::cell::RefCell;
use std::rc::Rc;
use std::path::Path;
use piston::window::{ WindowSettings, Size };
use piston::event::*;
use glium... | Rust | 0 |
Arc<Mutex<InnerThrottleTimeObserver<O, Item>>>,
);
impl<O, Item, Err> Observer<Item, Err> for ThrottleTimeObserver<O, Item>
where
O: Observer<Item, Err> + Send + 'static,
Item: Clone + Send + 'static,
{
fn next(&mut self, value: Item) {
let mut inner = self.0.lock().unwrap();
if inner.edge == ThrottleEdg... | Rust | 0 |
if obj_name in name_dict.keys():
# name_dict[obj_name].append(file.name)
# else:
# name_dict[obj_name] = [file.name]
# name_dict = dict(sorted(name_dict.items(), key=lambda item: len(item[1]), reverse=True))
# # write_to_json('./name_dict.json', name_dict)... | Python | 1 |
g `self`,
/// and discarding the success value, if any.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let x: Result<u32, &str> = Ok(2);
/// assert_eq!(x.err(), None);
///
/// let x: Result<u32, &str> = Err("Nothing here");
/// assert_eq!(x.err(), Some("Nothing h... | Rust | 0 |
"""
Model data imported from outside of Kanji Time.
Internal Dependencies
---------------------
The Python code modules in :mod:`external_data` depend on each other per the below diagram.
.. mermaid::
:caption: external_data - Internal Module Dependencies
---
config:
layout: elk
look: ha... | Python | 1 |
# Task 1
# Write a Python program to detect the number of local variables declared in a function.
def number_local_variables(a, b):
sum = a + b
print(f"{a} + {b} = {sum}")
print(number_local_variables.__code__.co_nlocals)
| Python | 1 |
(false)
.default_value(default_light_x).help("光源X坐标, 取值范围: [0, 1)"),
)
.arg(
Arg::with_name("lighty")
.short("y")
.required(false)
.default_value(default_light_y).help("光源Y坐标, 取值范围: [0, 1)"),
)
.arg(
... | Rust | 0 |
ccountId, Balance = Balance>;
/// The currency mechanism.
type Currency: ReservableCurrency<Self::AccountId>;
/// The Category ID type
type CategoryId: Parameter + Member + AtLeast32BitUnsigned + Default + Copy + MaybeSerializeDeserialize + Bounded + FullCodec;
}
#[pallet::error]
pub enum Error<T> {
///... | Rust | 0 |
use curve25519_dalek::{ristretto, ristretto::RistrettoPoint, scalar::Scalar};
use wedpr_l_crypto_zkp_utils;
use wedpr_l_utils::error::WedprError;
/// Converts RistrettoPoint into String.
pub fn point_to_string(point: &RistrettoPoint) -> String {
crate::bytes_to_string(&wedpr_l_crypto_zkp_utils::point_to_bytes(&p... | Rust | 0 |
tile_row(tile),
}
}
/// Renvoie les coordonnées de la tuile dans le monde.
///
/// Attention, ces coordonnées sont relatives à la position de la map dans le
/// monde et représente le centre de la tuile.
#[inline]
pub fn world_coords(&self, tile: u16) -> Point2<f32> {
self.t... | Rust | 0 |
> {
let mut handle = curl::easy::Easy::new();
let proxy_url = "https://fwdproxy";
let proxy_port = 8082;
let cainfo = "/var/credentials/root/ca.pem";
let sslcert = "/var/credentials/user/x509.pem";
let sslkey = "/var/credentials/user/x509.pem";
handle.connect_timeout(std::time::Duration::f... | Rust | 0 |
rt_eq!(meta("date: 2017123T12:34:56-13:30").date(),
Some(Utc.ymd(2017, 5, 4).and_hms(2, 4, 56)));
}
#[test]
fn parents_single() {
assert_eq!(meta("parent: hello-world").parents(), vec!["hello-world"]);
}
#[test]
fn parents_single_array() {
assert_eq!(meta("parent:\n... | Rust | 0 |
serde::de::Error::custom),
None => Err(serde::de::Error::custom("Invalid prefix")),
}
}
}
mod dynamodb_fin_ts {
use chrono::{DateTime, Utc};
use serde::{Deserialize, Deserializer, Serializer};
pub fn serialize<S>(timestamp: &DateTime<Utc>, serializer: S) -> Result<S::Ok, S::Error>
... | Rust | 0 |
global_momentum[key] = torch.zeros_like(global_momentum[key])
self.global_delta = global_delta
self.global_momentum = global_momentum
def aggregate(self, local_weights, local_deltas, client_ids, model_dict, current_lr):
C = len(client_ids)
for param_key in self.global_momentum:
... | Python | 1 |
# Example file for Advanced Python: Hands On by Joe Marini
# Arrange data into groups
import json
from collections import defaultdict
import pprint
from itertools import groupby
# open the sample weather data file and use the json module to load and parse it
with open("../../sample-weather-history.json", "r") as weat... | Python | 1 |
.5))
predicted = numpy.array(predicted)
# In[ ]:
print "Accuracy: ", accuracy_score(test_labels, predicted)
print "Recall: ", recall_score(test_labels, predicted)
print "Precision: ", precision_score(test_labels, predicted)
# In[ ]:
step = numpy.arange(0, len(test_labels))
plt.subplot(211)
plt.xlim(-1, len(test_l... | Python | 1 |
mpl From<TicksTime> for f64 {
fn from(item: TicksTime) -> Self {
item.0 as f64
}
}
impl From<TicksTime> for u64 {
fn from(item: TicksTime) -> Self {
item.0 as u64
}
}
#[cfg(test)]
mod test {
use super::{clock, Signature, Tempo, TicksTime};
use std::cmp::Ordering;
#[test]
pub fn new() {
l... | Rust | 0 |
connect_bad_hostname<C: TlsConnector>() -> tls_api::Error {
t!(Runtime::new()).block_on(connect_bad_hostname_impl::<C>())
}
async fn connect_bad_hostname_ignored_impl<C: TlsConnector>() {
drop(env_logger::try_init());
// First up, resolve google.com
let addr = t!("google.com:443".to_socket_addrs()).n... | Rust | 0 |
contains(TileFlags::BLOCKS_VISION)
{
return false;
}
}
previous = Some((x, y));
if tile.contains(TileFlags::BLOCKS_VISION) {
return false;
}
}
}
... | Rust | 0 |
# Generated by Django 2.2.11 on 2020-08-18 22:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0117_v400_remove_cloudforms_inventory'),
]
operations = [
migrations.AlterField(
model_name='project',
name=... | Python | 1 |
class Animals:
pass
class Pets(Animals):
pass
class Dog(Pets):
@staticmethod
def bark():
print("Bow Bow!")
d = Dog()
d.bark() | Python | 1 |
izationError, expected):
next(serializers.deserialize("jsonl", test_string, ignore=False))
class JsonSerializerTransactionTestCase(
SerializersTransactionTestBase, TransactionTestCase
):
serializer_name = "jsonl"
fwd_ref_str = [
"""{
"pk": 1,
"model": "serialize... | Python | 1 |
#!/usr/bin/env python
# usage: ./ssl_server.py <port> <cert_file> <Client certificate authentication>
# Start the server with or without client certificate authentication
import ssl
import sys
import flask
app1 = flask.Flask("SSL Server")
@app1.route("/hello")
def hello():
return "Hello World!"
def start_serv... | Python | 1 |
6_pd);
qc!(MASK_OUT_Y, OP_LSL_16_DI, qc_lsl_16_di);
qc!(MASK_OUT_Y, OP_LSL_16_IX, qc_lsl_16_ix);
qc!(MASK_EXACT, OP_LSL_16_AW, qc_lsl_16_aw);
qc!(MASK_EXACT, OP_LSL_16_AL, qc_lsl_16_al);
qc!(MASK_OUT_Y, OP_LSR_16_AI, qc_lsr_16_ai);
qc!(MASK_OUT_Y, OP_LSR_16_PI, qc_lsr_16_pi);
qc!(MASK_OUT_Y... | Rust | 0 |
# Created by UPO-JZSB on Jan/17/2021
# Released Under GPL-v3.0 License
# Version 0.1 is released on Jan/17/2021
# Implementation of wigb
# Version 0.2 is released on Jan/19/2021
# Add parameter direction - decide the plot direction
# Version 0.3 is released on Jan/20/2021
# Replace `plot' by `fill_between' function ... | Python | 1 |
import re
from .. import Provider as AutomotiveProvider
class Provider(AutomotiveProvider):
"""Implement automotive provider for ``el_GR`` locale."""
uppercase_letters = "ABEZHIKMNOPTYX"
license_formats = (
"??? ####",
"?? ####",
)
def license_plate(self) -> str:
"""Gen... | Python | 1 |
c_node1.clone(),
sender_2,
DummyNetworkService::default(),
15,
)?;
let join_handle = node2.process_block_connect_event(receiver).await;
let branch = sync_task.await?;
let node2 = join_handle.await;
let current_block_header = node2.chain().current_header();
assert_eq!(bran... | Rust | 0 |
if inject.checkBooleanExpression("'utf8'=(SELECT CHARSET(CURRENT_USER()))"):
Backend.setVersion("= 4.1.0")
else:
Backend.setVersionList([">= 4.0.6", "< 4.1.0"])
else:
Backend.setVersionList([">= 4.0.0", "< 4.0... | Python | 1 |
(),
MenuState::WarpMenu => warp_menu::transition_into(),
MenuState::FlagMenu => flag_menu::transition_into(),
MenuState::InventoryMenu => inventory_menu::transition_into(),
MenuState::CheatMenu => cheat_menu::transition_into(),
MenuState::SpawnMenu => spawn_menu::transition_into(... | Rust | 0 |
x0 = self.branch0(x)
x1 = self.branch1(x)
x2 = self.branch2(x)
x3 = self.branch3(x)
out = torch.cat((x0, x1, x2, x3), 1)
return out
class Mixed_5c(nn.Module):
def __init__(self):
super(Mixed_5c, self).__init__()
self.branch0 = nn.Sequential(
... | Python | 1 |
from Base import PowerMartingale
from Dataset.heigh_weight import HeightWeightDataset
from Threshold import MartingaleThreshold
from p_values import PValueCalculator
from blackwater.estimation.distance.local_outlier_factor import LocalOutlierFactor
dataset = HeightWeightDataset()
model = LocalOutlierFactor(100, 10)
... | Python | 1 |
if "stdout" in sys.argv[i]:
self.stdout = sys.argv[i]
self.stdout = self.stdout.replace("stdout=", "")
print("stdout = " + self.stdout)
sys.stdout = open(self.stdout, "a")
if "storage" in sys.argv[i]:
self.storage = sys.... | Python | 1 |
t.key.as_ptr()) };
assert_eq!(portable64, expected);
let portable128 = PortableHash::new(key).hash128(data);
let portable256 = PortableHash::new(key).hash256(data);
let builder64 = HighwayHasher::new(key).hash64(data);
let builder128 = HighwayHasher::new(key).hash128(data);
... | Rust | 0 |
(&Path::new("test/root-ca.pem")) {
Ok(_) => {}
Err(err) => panic!("Unexpected error {:?}", err),
}
// Now connect to the socket and make sure the protocol negotiation works...
let stream = TcpStream::connect(localhost).unwrap();
let mut stream = match Ssl::new(&ctx.build()).unwrap().conn... | Rust | 0 |
nt, bool),
#[serde(deserialize_with = "biguint_with_sign_from_hex_string")]
pub x: (BigUint, bool),
#[serde(deserialize_with = "biguint_with_sign_from_hex_string")]
pub exp_w0: (BigUint, bool),
#[serde(deserialize_with = "biguint_from_hex_string")]
pub exp_w1: BigUint,
#[serde(deserializ... | Rust | 0 |
fn test_selectors() {
let (_env, app) = utils::start_basic_component("selectors-test").await.expect("create comp 1");
let (_env2, app2) =
utils::start_basic_component("selectors-test2").await.expect("create comp 2");
let (_env3, app3) =
utils::start_test_component("selectors-test3").await.e... | Rust | 0 |
from App import db
from App.livro.models import Livro
def cadastrar_livro(livro):
livro_bd = Livro(
titulo=livro.titulo,
autor=livro.autor,
isbn = livro.isbn,
preco = livro.preco,
estoque = livro.estoque
)
db.session.add(livro_bd)
db.session.commit()
return T... | Python | 1 |
]
pub enum ModuleName<'a> {
Anonymous,
Simple(String),
Qualified(String, Vec<&'a str>),
}
#[derive(Debug, Clone)]
pub(crate) struct ModuleAst<'a> {
name: ModuleName<'a>,
pub(crate) exposing: Option<Exposing<'a>>,
imports: Option<Vec<Import<'a>>>,
externs: Option<Extern<'a>>,
pub(crate) ... | Rust | 0 |
_layers_cnt_minus_1 = br.f::<u8>(2)?; // f(2)
ss.spatial_layer_dimensions_present_flag = br.f::<bool>(1)?; // f(1)
ss.spatial_layer_description_present_flag = br.f::<bool>(1)?; // f(1)
ss.temporal_group_description_present_flag = br.f::<bool>(1)?; // f(1)
ss.scalability_structure_reserved_3bits = br.f::... | Rust | 0 |
import logging
from typing import Optional
import requests
from open_webui.retrieval.web.main import SearchResult, get_filtered_results
from open_webui.env import SRC_LOG_LEVELS
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["RAG"])
def search_serpstack(
api_key: str,
query: str,
count: i... | Python | 1 |
"""
Écrire un programme Python pour vérifier si une valeur donnée est présente ou non dans un ensemble.
"""
# Création d'un ensemble avec quelques éléments
ensemble = {1, 2, 3, 4, 5}
# Vérification de la présence d'une valeur dans l'ensemble
valeur_a_verifier = 3
est_present = valeur_a_verifier in ensemble
# Affich... | Python | 1 |
("No result found!");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part1_example1() {
let input = read_input("input1.txt");
assert_eq!(part1(&input), 514579);
}
#[test]
fn test_part2_example1() {
let input = read_input("input1.txt");
assert_eq!(part... | Rust | 0 |
from mage_ai.api.operations.constants import META_KEY_LIMIT, META_KEY_OFFSET
from mage_ai.api.presenters.BasePresenter import BasePresenter
from mage_ai.orchestration.backfills.service import preview_run_dates
class BackfillPresenter(BasePresenter):
default_attributes = [
'block_uuid',
'completed_... | Python | 1 |
"date": df.index[-1].date(),
"netliq": df["NetLiq"].iloc[-1],
"walcl": df["WALCL_b"].iloc[-1],
"rrp": df["RRP_b"].iloc[-1],
"tga": df["TGA_b"].iloc[-1],
"effr": df["EFFR"].iloc[-1],
}
m1, m2, m3, m4, m5 = st.columns(5)
m1.metric("Net Liquidity", fmt_b(latest["netliq"]), help="WALCL - RRP - TGA... | Python | 1 |
from custom_distribution import CustomDistribution
from dicetypes import DiceType, IntType
import math
import random
class DiscreteDistribution(CustomDistribution):
NAME = "discrete"
ARG_TYPES = (list[float],)
# These can be int, float, list[int], or list[float]
def __init__(self, probs: list[float]):... | Python | 1 |
ce 2^{}", log2_size),
|b| {
b.iter(|| {
let r = bitmap.clone().slice(offset, len);
assert!(r.null_count() > 0);
})
},
);
let offset = ((size as f64) * 0.2) as usize;
let len = ((size as f64) * 0.51) ... | Rust | 0 |
from __future__ import absolute_import
from __future__ import print_function
import tarfile, inspect, os
from six.moves.urllib.request import FancyURLopener
from ..utils.generic_utils import Progbar
class ParanoidURLopener(FancyURLopener):
def http_error_default(self, url, fp, errcode, errmsg, headers):
raise ... | Python | 1 |
fn main() {
let input = fs::read_to_string("input.txt").expect("Error reading input.txt");
let mut spinlock = Spinlock::from_str(&input.trim(), 2017);
println!(
"What is the value after 2017…? {}",
spinlock.get_value_after_last_inserted(),
);
let mut spinlock = Spinlock::from_str(&... | Rust | 0 |
import numpy as np
import torch
from ultralytics.yolo.engine.predictor import BasePredictor
from ultralytics.yolo.engine.results import Results
from ultralytics.yolo.utils.torch_utils import select_device
from .modules.mask_generator import SamAutomaticMaskGenerator
class Predictor(BasePredictor):
def preproce... | Python | 1 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/empty.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from googl... | Python | 1 |
##########################################################################
# Copyright (c) 2009, 2010, ETH Zurich.
# All rights reserved.
#
# This file is distributed under the terms in the attached LICENSE file.
# If you do not find this file, copies can be found by writing to:
# ETH Zurich D-INFK, Haldeneggsteig 4, C... | Python | 1 |
n::bitand_assign));
}
}
#![allow(dead_code, non_camel_case_types, non_snake_case)]
use std::os::raw::{c_int, c_char, c_void, c_ulong, c_double, c_long, c_ushort};
#[cfg(test)]
use std::mem;
pub type EM_BOOL = c_int;
pub type EM_UTF8 = c_char;
pub type EMSCRIPTEN_RESULT = c_int;
pub const EM_TRUE: EM_BOOL = 1;
pu... | Rust | 0 |
import cv2
import os
import numpy as np
import json
from tqdm import trange
def create_video(images_folder, output_video, fps, font_scale, text_color, text_position):
images = [img for img in os.listdir(os.path.join(images_folder, 'rgb_front')) if img.endswith(".jpg") or img.endswith(".png")]
images.sort()
... | Python | 1 |
import ljd.ast.nodes as nodes
import ljd.ast.traverse as traverse
def insert_table_record(constructor, key, value):
array = constructor.array.contents
records = constructor.records.contents
if isinstance(key, nodes.MULTRES):
assert len(records) == 0 \
or isinstance(records[-1], nodes.TableRecord)
records.... | Python | 1 |
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
import re
import json
from tqdm import tqdm
import argparse
import os
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--dataset", type=str, default="mscoco")... | Python | 1 |
es=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs):
input_shape = input_ids.shape
# if model is used as a dec... | Python | 1 |
-46 standard
pub fn with<C: secp256k1::Signing>(
secp: &Secp256k1<C>,
channel_source: KeySource,
channel_xpriv: ExtendedPrivKey,
shutdown_scriptpubkey: Option<PubkeyScript>,
) -> Self {
let fingerpint = channel_source.0;
let keys = (0u16..=6)
.into_it... | Rust | 0 |
new(
OpdsLinkType::Image,
OpdsLinkRel::Thumbnail,
format!("{}/thumbnail", base_url),
),
OpdsLink::new(
OpdsLinkType::Image,
OpdsLinkRel::Image,
format!("{}/pages/1", base_url),
),
... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
name: 票友机票预订系统6处SQL注入2(绕过)
referer: http://www.wooyun.org/bugs/wooyun-2015-0116851
author: Lucifer
description: multi sqli。
'''
import sys
import requests
class piaoyou_six2_sqli_BaseVerify:
def __init__(self, url):
self.url = url
def run(self):
... | Python | 1 |
header("x-ua-compatible", "IE=edge, Chrome=1")
.body("Resource not found")
}
}
}
async fn echo() -> impl Responder {
"It works"
}
fn generate_db(b: bool) -> Box<dyn Database> {
match b {
false => Box::new(DatabaseMySql::try_new(env::var("DB_URL").unwrap_or_else(
... | Rust | 0 |
# Enviar um email com os detalhes da compra online (Maximo 3 tentativas) para compras confirmadas.
compra_confirmada = False
dados_compra = 'Compra no valor de R$12.50 e entrega confirmada.'
for enviar in range(3):
if compra_confirmada:
print(dados_compra)
print('Detalhes enviado para o seu email'... | Python | 1 |
import pytest
pytest.register_assert_rewrite('tests.utils')
| Python | 1 |
Identifier: Apache-2.0
// (Re-)generated by schema tool
// >>>> DO NOT CHANGE THIS FILE! <<<<
// Change the json schema instead
// @formatter:off
#![allow(dead_code)]
use wasmlib::*;
pub const SC_NAME: &str = "fairroulette";
pub const HSC_NAME: ScHname = ScHname(0xdf79d138);
pub const PARAM_NUMBER: &str = "... | Rust | 0 |
u32x2::new(0, 0);
simd_eq(a, transmute(b))
}
/// Unsigned compare bitwise equal to zero
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(test, assert_instr(cmeq))]
#[stable(feature = "neon_intrinsics", since = "1.59.0")]
pub unsafe fn vceqzq_u32(a: uint32x4_t) -> uint32x4_t {
let b: u32x4 = u32x4::new(... | Rust | 0 |
t)]
mod tests {
use super::*;
use serde_xml::de::from_iter;
use std::fs::File;
use std::io::Read;
#[test]
fn it_can_parse() -> () {
let test_file = File::open("test_files/cumulative.xml").unwrap();
let deserialized: Result<CliOutput,_> = from_iter(test_file.bytes());
pri... | Rust | 0 |
use uuid::Uuid;
use wiremock::{
http::HeaderValue,
matchers::{method, path},
Mock, MockServer, ResponseTemplate,
};
#[tokio::test]
async fn test_canister_http_server() {
// Setup local mock server.
let mock_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/hello... | Rust | 0 |
::new();
assert_eq!(tester.len(), 0);
assert_eq!(tester.front(), None);
for case in 0..(1 << len) {
assert_eq!(tester.len(), 0);
for bit in 0..len {
if case & (1 << bit) != 0 {
tester.push_front(());
} else {
... | Rust | 0 |
.75 }, PointF64 { x: 529.57, y: 127.86 },
PointF64 { x: 539.27, y: 147.24 }, PointF64 { x: 617.74, y: 159.86 }, PointF64 { x: 629.55, y: 194.60 }, PointF64 { x: 671.55, y: 222.55 },
PointF64 { x: 727.81, y: 213.36 }, PointF64 { x: 739.94, y: 204.77 }, PointF64 { x: 769.98, y: 208.42 }, PointF64 ... | Rust | 0 |
ity.p12");
let builder = TlsAcceptorBuilder::from_pkcs12(pkcs12, "mypass").unwrap();
builder.build().unwrap()
}
fn test_tls_connector() -> TlsConnector {
let root_ca = include_bytes!("root-ca.der");
let root_ca = Certificate::from_der(root_ca.to_vec());
let mut builder = TlsConnector::builder().un... | Rust | 0 |
ore()
.internal(),
swapchain_count: 1,
p_swapchains: self.swapchain.internal(),
p_image_indices: &present_index,
..Default::default()
};
unsafe {
match self
.swapchain
.swapchain_loader()
.queue_present(self.device.present_queue(), &present_info)
... | Rust | 0 |
"""
Displaying an image in a scene
==============================
Displaying an image can be done in two different ways based the details
of the information you are trying to communicate.
We consider a color image with shape (height, width, 3). In PyGFX, this is
descried as a texture.
A gfx.Image will display the tex... | Python | 1 |
assert_eq!(v.load(Relaxed), 10.0);
///
/// assert_eq!(v.compare_exchange(6.0, 12.0, SeqCst, Relaxed), Err(10.0));
/// assert_eq!(v.load(Relaxed), 10.0);
/// ```
#[inline]
pub fn compare_exchange(
&self,
current: f64,
new: f64,
success: Ordering,
failure: ... | Rust | 0 |
ition=meaning,
is_in_target_language=is_in_target_language,
),
],
)
assert _define_word(
my_course, word, is_in_target_language=is_in_target_language
) == {"word": word, "definition": meaning}
def test_skips_empty_definition():
word = fakes.fake_string()
... | Python | 1 |
from datetime import *
from urllib.parse import urlparse
from dateutil.parser import isoparse
from ics import *
def test_issue_269_missing_alarms():
c = Calendar()
e = Event()
e.begin = e.dtstamp = isoparse("2021-01-01 11:00:00")
e.duration = timedelta(minutes=30)
# TODO get rid of all the urlpa... | Python | 1 |
::ser::{VHSerializer};
use flate2::{read::GzDecoder, write::GzEncoder, Compression};
#[derive(PartialEq, Debug, Serialize, Deserialize, Clone)]
pub struct CompressedWrapper<T> {
inner: Vec<u8>,
_phantom: PhantomData<T>,
}
#[derive(PartialEq, Debug, Serialize, Deserialize, Clone)]
#[serde(from = "Compressed... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.