text string | label_name string | labels int64 |
|---|---|---|
ed_imports)]
use $crate::private::{AdhocKind, TraitKind};
let error = $err;
(&error).anyhow_kind().new(error)
});
($fmt:expr, $($arg:tt)*) => {
$crate::private::new_adhoc(format!($fmt, $($arg)*))
};
}
<gh_stars>1-10
use std::fmt;
use std::time::Duration;
use number_prefix::{... | Rust | 0 |
"""
Rollback management utilities for undoing changes
"""
import asyncio
import logging
import time
import json
from typing import Any, Dict, List, Optional, Callable, Union
from dataclasses import dataclass, field
from enum import Enum
from datetime import datetime
class RollbackType(Enum):
"""Типы отката"""
... | Python | 1 |
# PYTHONPATH=. python scripts/examples/ed.py
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
from src.inference_time_alignment.decoder import EFTPosthocGenerationMixin
from src.inference_time_alignment.model import PrefixPreTrainedWrapper
from src.inference_time_alignment.... | Python | 1 |
.filter(|&y| self.at_coords(level + 1, 0, y))
.count() as u32;
}
if level < deep && index == ABOVE {
adj += (0..WIDTH)
.filter(|&x| self.at_coords(level + 1, x, 0))
.count() as u32;
}
if level < deep && index == RIGHT {
... | Rust | 0 |
,
},
error_handlers::{ErrorHandler, LoggingErrorHandler},
};
use futures::{stream::FuturesUnordered, Future, StreamExt};
use teloxide_core::{
requests::Requester,
types::{
AllowedUpdate, CallbackQuery, ChatMemberUpdated, ChosenInlineResult, InlineQuery, Message,
Poll, PollAnswer, PreChe... | Rust | 0 |
StrAtom(String),
}
// None if there was no specific matching
// (so an untagged call should be used.)
pub fn match_syntax(expr: Expr) -> Matching {
match expr {
Expr::List(list) => {
if let Some((ec, et, ef)) = matches_if_expr(&list) {
Matching::If(ec, et, ef)
} else if let Som... | Rust | 0 |
// NOTE: Since disallowed_but_legal_combinations is empty, this message
// will never actually be emitted.
allowed_combinations_message:
r#"Unaligned requires either a) repr "C" or "transparent" with all fields implementing Unaligned or, b) repr "packed""#,
derive_unaligned: true... | Rust | 0 |
///
/// Gets a copy of the `Reactor` in order to do anything it likes there.
fn finish(&mut self, msg: RelayMsg, reactor: &mut Reactor) -> Result<()>;
}
/// An object that can extend a circuit by one hop, using the `MetaCellHandler` trait.
///
/// Yes, I know having trait bounds on structs is bad, but in th... | Rust | 0 |
s_order(generate_cross_sell(trade_id), False, verbose)
treat_trades(trades, side)
if neworder:
sells[neworder['order_id']]=neworder
buys = {}
sells = {}
order_book = OrderBook()
# nb buys and sells to prefill orderbook
prefill(10)
#print(order_book)
#usage:
# 1/ trade_id
#... | Python | 1 |
point_cloud(smooth_opc, calc_normals=False)
tri_norms = pick_valid_normals(tri_map, opc_normals)
opc_normals_cp = MatrixDouble(tri_norms, copy=True) # copy here!!!!!
# plot_triangle_normals(np.asarray(tri_mesh.triangle_normals), opc_normals)
tri_mesh.set_triangle_normals(opc_normals_cp) # copy again her... | Python | 1 |
x<$data_type>) -> Complex<$data_type>,
{
let mut array = self.to_complex_array();
for n in &mut array[0..Self::LEN / 2] {
*n = op(*n);
}
Self::from_complex_array(array)
}
#[inline]
fn arr... | Rust | 0 |
None,
};
// CCMP-128 is better than TKIP
let pairwise_cipher_suites =
vec![match self.pairwise_cipher_suites.iter().max_by_key(|cipher_suite| {
match **cipher_suite {
CIPHER_CCMP_128 => 1,
_ => 0,
}
... | Rust | 0 |
the 'leaf' until suspend_end.
fn suspend_leaf(
origin,
admins: MerkleRoot<T::AccountId, T::TreeHashOut>,
leaf: Hashed<Document, T::TreeHashOut>,
proof: Vec<ProofElement<T::TreeHashOut>>,
suspend_end: UnixTimeSeconds,
) -> DispatchResult {
... | Rust | 0 |
32> for DescriptorType {
fn from(f: u32) -> DescriptorType {
DescriptorType::from_u32(f).unwrap()
}
}
#[repr(i32)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Primitive, Hash)]
pub enum AttachmentLoadOp {
Load = vks::VK_ATTACHMENT_LOAD_OP_LOAD as i32,
Clear = vks::VK_ATTACHMENT_LOAD_OP_CLEAR a... | Rust | 0 |
import multiprocessing
import socketserver
from PIL import Image
import io
import logging
import signal
import sys
import socket
logging.basicConfig(level=logging.INFO)
class ImageScalingHandler(socketserver.BaseRequestHandler):
def handle(self):
logging.info("Received connection")
scale_factor = ... | Python | 1 |
!("#icon-1739-{}-nodesc", COLOR_DEAD) }
"Done-Unknown" => { format!("#icon-1739-{}-nodesc", COLOR_UNKNOWN) }
_ => { format!("#icon-1899-{}", COLOR_UNKNOWN) } // Matches every string value
}
}
fn inv_to_kml(invader: InvaderSpotter, icon: &str, (mut lat, mut long): (f32, f32)) -> String {
if invader.coor... | Rust | 0 |
m_data.get("confidence"),
meta=item_data.get("meta")
))
stats_data = scan_result.get("stats", {})
stats = PlaceholderStats(
total=stats_data.get("total", 0),
need_reanalysis=stats_data.get("need_reanalysis", 0),
by_kind=stats_data.get("by_... | Python | 1 |
clone();
let __end0 = __0.0.clone();
let __temp0 = __action15(&__start0, &__end0);
let __temp0 = (__start0, __temp0, __end0);
__action8(__temp0, __0, __1)
}
fn __action23<'input>(
__0: (usize, crate::ast::List<'input>, usize),
__1: (usize, usize, usize),
) -> crate::ast::Item<'input> {
let ... | Rust | 0 |
file.read_to_end(&mut buffer)?;
// NB not padding buffer to 4 bytes so will not always replicate CryptoJS javascript implementation
println!("{} {} bytes", filename, buffer.len());
let hash = hash256(&buffer);
println!("hash: {}", hex::encode(&hash));
//let pubkey = PubKey::from_pem_file(&args[1])?;
l... | Rust | 0 |
nfo!("received {:#?} from peer {}", peer_msg, uuid);
if peer_msg.is_err() {
break Err(peer_msg.unwrap_err());
}
match peer_msg.unwrap() {
PeerMessage::Signal(signal) => room_handle.send(rooms::Message::Signal { peer: uuid, signal ... | Rust | 0 |
provider.clone(), redeem_ids[2]),
)
.await;
// now move from mempool into chain and await the remaining redeem
btc_rpc.flush_mempool().await;
assert_redeem_event(TIMEOUT, user_provider, redeem_ids[1]).await;
}
async fn assert_redeem_event(
duration: Duration,
provider: Arc<PolkaBtcProvider... | Rust | 0 |
# Tuplas
tuplas_num = [1,2,3.3,7,27,"python"]
tuplas_num.pop()
#acessos
print("Para acessar por posição ex: tuplas_num[0] ",tuplas_num[0])
print(tuplas_num[-1])
print(tuplas_num[:4])
print(tuplas_num[3:])
print(tuplas_num[2:6:2])
print("\n---------------\n")
#desenpacotamento
curso = ["python","Felipe", 10.00, 2024... | Python | 1 |
15} {:<15}".format("Metric", "Isolation Forest", "Random Forest", "Notes"))
print("-" * 70)
print("{:<25} {:<15.2f} {:<15.2f} {}".format("Precision", avg_precision, rf_precision, "Higher = fewer false alarms"))
print("{:<25} {:<15.2f} {:<15.2f} {}".format("Recall", avg_recall, rf_recall, "Higher = catches more attacks"... | Python | 1 |
urn any programs to be installed in the datapath
let mut h = HashMap::default();
h.insert(
"TestBasicSerialize",
"
(def (Report.acked 0) (Control.num_invoked 0) (Report.cwnd 0) (Report.rate 0))
(when true
(:= Report.acked (+ Report.acked Ac... | Rust | 0 |
VSQRTSD = 1474,
XED_ICLASS_VSQRTSS = 1475,
XED_ICLASS_VSTMXCSR = 1476,
XED_ICLASS_VSUBPD = 1477,
XED_ICLASS_VSUBPS = 1478,
XED_ICLASS_VSUBSD = 1479,
XED_ICLASS_VSUBSS = 1480,
XED_ICLASS_VTESTPD = 1481,
XED_ICLASS_VTESTPS = 1482,
XED_ICLASS_VUCOMISD = 1483,
XED_ICLASS_VUCOMISS = 1... | Rust | 0 |
{
text.size.x += speed;
text.position.x -= speed / 2.0;
let mut instructions = instructions.single_mut();
instructions.content = String::from(INSTRUCTIONS);
instructions
.content
.push_str(&format!("\nSize: {}", text.size.x));
}
for mut sprite i... | Rust | 0 |
#!/usr/bin/env python
#-*- coding:utf-8 _*-
import tqdm
import json
import warnings
warnings.filterwarnings('ignore')
import numpy as np
from scipy.interpolate import interp2d,RegularGridInterpolator
from scipy.sparse import diags,csr_matrix, csc_matrix
from scipy.sparse.linalg import spsolve, gmres, eigs
# from ... | Python | 1 |
import numpy as np
import matplotlib.pyplot as plt
import cv2
import os
from frame_seq_data import FrameSeqData, K_from_frame
import core_3dv.camera_operator as cam_opt
import torch
import banet_track.ba_module as module
from core_io.depth_io import load_depth_from_png
import core_math.transfom as trans
from visualizer... | Python | 1 |
_secs(10))
.use_rustls_tls()
.trust_dns(true)
.build()?;
Ok(ApiClient {
project: project.clone(),
account: account.clone(),
access_key_id: access_key_id.clone(),
secret_access_key: secret_access_key.into(),
cloud_en... | Rust | 0 |
won't work with btreeset, and dedup has weird lifetime errors
.collect::<Vec<_>>();
resolve_logins_to_users(&members)
}
/// Return a list of all known team members.
fn all_team_members() -> DashResult<Vec<GitHubUser>> { specific_subteam_members(|_| true) }
/// Check if an issue comment is written by a me... | Rust | 0 |
_http_log_msec(
mut r: *mut bindings::ngx_http_request_t,
mut buf: *mut bindings::u_char,
mut op: *mut ngx_http_log_op_t,
) -> *mut bindings::u_char {
let mut tp: *mut bindings::ngx_time_t = ptr::null_mut();
tp = ngx_timeofday!();
return bindings::ngx_sprintf(
buf,
b"%T.%03M\x00"... | Rust | 0 |
if await page.is_visible('button[text="Confirm"]'):
confirm_button = page.get_by_role("button", name="Confirm")
if confirm_button is not None:
await confirm_button.click()
if await page.title() == "Confirm ... | Python | 1 |
me.now.return_value = fixed_now
# Mock a queryset-like behavior
mock_task = MagicMock()
mock_task.get_data_object.return_value = "Mocked Task"
mock_queryset = MagicMock()
mock_queryset.order_by.return_value = [mock_task]
# Ensure filter returns a queryset-like object fo... | Python | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
LRMM の設定値を計算するツール
"""
import os
import sys
import math
def extract_msx_logo():
"""LRMM の設定値を計算するツール"""
output_file = "rotate.txt"
try:
# 回転中心
ox = 104
oy = 39
with open(output_file, "w") as f:
for theta in range( 0, 128 ):
vx = math.cos( theta *... | Python | 1 |
Result<Vec<stmt::Stmt>> {
use {lexer::scan, parser::parse};
scan(s.as_ref()).and_then(|t| parse(&t))
}
use std::fmt::Write;
use super::is_set;
/// Formats `bytes` taking into account an offset and length of the form
pub fn fmt(
bytes: &[u8],
offset: usize,
length: usize,
f: &mut std::fmt::Form... | Rust | 0 |
implementation of PL011.
ILPR [
UNUSED OFFSET(0) NUMBITS(32) []
],
/// Integer Baud rate divisor
IBRD [
/// Integer Baud rate divisor
IBRD OFFSET(0) NUMBITS(16) []
],
/// Fractional Baud rate divisor
FBRD [
/// Fractional Baud rate divisor
FBRD OFFSET(0) NUMBITS(6) []
... | Rust | 0 |
# Copyright (c) 2021, Hitachi America Ltd. All rights reserved.
#
# 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 appli... | Python | 1 |
option::Option<__jni_bindgen::Local<'env, crate::android::os::PersistableBundle>>, __jni_bindgen::Local<'env, crate::java::lang::Throwable>> {
// class.path == "android/media/MediaRecorder", java.flags == PUBLIC, .name == "getMetrics", .descriptor == "()Landroid/os/PersistableBundle;"
unsafe {
... | Rust | 0 |
ory(traj_file, "w", atoms)
if not np.isnan(t_schedule).any():
MaxwellBoltzmannDistribution(
atoms=atoms,
temperature_K=t_schedule[last_step],
rng=np.random.default_rng(seed=velocity_seed),
)
if zero_lin... | Python | 1 |
text = "Python123"
print(text.isalpha())
print(text.isdigit())
print(text.isalnum())
print(text.isspace())
| Python | 1 |
import argparse
import os
import subprocess
import tempfile
from glob import glob
from threading import Thread
import yaml
SERVER_CONFIG = {"protocols": ["tcp"], "paths": {"all": {"source": "publisher"}}}
BASE_STREAM_URL = "rtsp://localhost:8554/live"
def main(video_directory: str, number_of_streams: int) -> None:
... | Python | 1 |
om_request(Method::Get, download_url.to_owned(), None, None) {
Ok(response) => Box::new(response),
Err(err) => return Error::io_result(IoError::new(IoErrorKind::NotConnected, err))
};
Ok(Content {
reader: Some(reader),
writer: None,
})
})
}
/// Create the new instance of `Content`... | Rust | 0 |
035d05038119035a05038119035b0503"),
("0024", "81190361050381190362050381191000"),
# ("0027", "0503811910010503811910020503811910030503"),
# ("0027", "8119100505038119100405038119100605038119"),
# ("0027", "100705038119102c050381191029050381190ffd"),
# ("0027",... | Python | 1 |
write_float::<_, DECIMAL>(2013265900.0f32, &options, "2013265900.0");
write_float::<_, DECIMAL>(2080374800.0f32, &options, "2080374800.0");
write_float::<_, DECIMAL>(2113929200.0f32, &options, "2113929200.0");
write_float::<_, DECIMAL>(2130706400.0f32, &options, "2130706400.0");
write_float::<_, DECIMAL... | Rust | 0 |
right device
model.to(device)
# construct an optimizer
params = [p for p in model.parameters() if p.requires_grad]
optimizer = torch.optim.SGD(
params,
lr=0.005,
momentum=0.9,
weight_decay=0.0005
)
# and a learning rate scheduler
lr_scheduler = torch.optim.lr_scheduler.StepLR(
optimizer,
step... | Python | 1 |
ed.dtype
assert res_lowered.dtype == exp_lowered.dtype
assert res_swapped.dtype == exp_swapped.dtype
assert res_titled.dtype == exp_titled.dtype
assert res_uppered.dtype == exp_uppered.dtype
assert_equal(res_capitalized, exp_capitalized)
assert_equal(res_lowered, exp_lowered)
assert_equal(r... | Python | 1 |
# Only log the last (biggest) cfg metrics in the progress bar
val_logs = {
"parts_chamfer_distance": parts_chamfer_distances.mean().item(),
"parts_f_score": parts_f_scores.mean().item(),
}
val_progress_bar.set_postfix(**val_logs)
logger.info(
... | Python | 1 |
"es": {"english_name": "Spanish", "chinese_name": "西班牙语"},
"ta": {"english_name": "Tamil", "chinese_name": "泰米尔语"},
"te": {"english_name": "Telugu", "chinese_name": "泰卢固语"},
"th": {"english_name": "Thai", ... | Python | 1 |
Literal::Int(i)),
&src::Literal::UInt(i) => Ok(dst::Literal::UInt(i)),
&src::Literal::Long(i) => Ok(dst::Literal::Long(i)),
&src::Literal::Half(f) => Ok(dst::Literal::Half(f)),
&src::Literal::Float(f) => Ok(dst::Literal::Float(f)),
&src::Literal::Double(f) => Ok(dst::Literal::Dou... | Rust | 0 |
time.sleep(0.5)
input_element.send_keys(address)
time.sleep(1)
# 针对邮编库网站的查询按钮选择器
button_selectors = [
"#search_btn", # 邮编库的搜索按钮ID
"input[type='submit']",
"button[type='submit']",
"button:cont... | Python | 1 |
"""
認証関連のAPIエンドポイントのテスト
"""
import pytest
import json
from http import HTTPStatus
from datetime import datetime
from app import create_app, db
from app.infrastructure.database.models import UserModel
from app.domain.value_objects.role import RoleType
# テストデータ
TEST_EMAIL = "test@example.com"
TEST_PASSWORD = "Password12... | Python | 1 |
let Some(id_val) = params_map.get(ID_KEY) {
print_url(&format_url(id_val));
Ok(())
} else {
Err(From::from(format!("Expected url to have param key: {}.", ID_KEY)))
}
}
fn main() {
if let Err(err) = run() {
println!("{}", err);
process::exit(1);
}
}
<reponame>Elin... | Rust | 0 |
==Search Path with RRT====
obstacle_list = [
(-0.25, -0.90, -0.20, -0.60),
( 0.20, -0.90, 0.25, -0.60),
(-0.25, -0.45, -0.20, 0.10),
( 0.20, -0.45, 0.25, 0.10),
(-0.80, 0.10, -0.60, 0.15),
(-0.45, 0.10, -0.20, 0.15),
( 0.60, 0.10, 0.80, 0.15),
... | Python | 1 |
# ------------------------------------------------------------------------------
# Copyright (c) Facebook, Inc. and its affiliates.
# To view a copy of this license, visit
# https://github.com/facebookresearch/detectron2/blob/main/LICENSE
# ------------------------------------------------------------------------------
... | Python | 1 |
poses, true_poses = rescore_docked_costructures(
engine, model, target_id, baseline_id, alt_struct_id
)
rescore_metrics = get_docking_metrics(pred_poses, true_poses)
for key, val in rescore_metrics.items():
ret[f"{baseline}_{key}"] = val
if not CONFIG.eval.docking.only_rescore:
... | Python | 1 |
super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.hidden_act = hi... | Python | 1 |
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import lfilter, sawtooth
def computeValues(R, S=False):
if not S:
m = np.arange(0, R)
s = 2 * m * (0.9 ** m)
else:
m = np.arange(0, R, 0.001)
s = 2 * sawtooth(3 * np.pi * m + np.pi/6)
d = np.random.rand... | Python | 1 |
"""
视觉语言操作
机器人根据指令人的指令调节空调,自主探索环境导航到目标点,通过手臂的运动规划能力操作空调,比如开关按钮、调温按钮、显示面板
"""
import time
from robowaiter.scene.scene import Scene
class SceneVLM(Scene):
def __init__(self, robot):
super().__init__(robot)
# 在这里加入场景中发生的事件, (事件发生的时间,事件函数)
self.signal_event_list = [
(3, self.add_wa... | Python | 1 |
.len();
let ncol = rows[0].len();
let mut data = vec![vec![0; ncol + 4]; nrow + 4];
for i in 0..nrow {
for j in 0..ncol {
if &rows[i][j..j + 1] == "#" {
data[i + 2][j + 2] = 1;
}
}
}
let mut img = Image::new(data, algorithm);
for _ in 0..5... | Rust | 0 |
criteria passing BLAST hits
"""
if not sequences:
sequences = helpers.get_sequences(query_file, query_ids)
hits = []
for line in handle:
qid, sid, pident, *_, qstart, qend, _, _, evalue, score, _ = line.split("\t")
# Manually calculate query coverage
coverage = (int(qe... | Python | 1 |
);
rust!(this.out, "}}");
rust!(this.out, "pub mod {}parse_table {{", this.prefix);
try!(super::parse_table::compile(this.grammar,
this.user_start_symbol,
this.start_symbol,
... | Rust | 0 |
15\xfb\
\xa6\xa7)'\x16\xa9\xc5\xa8\xce)(8\xb5\xcc\x9d\xee\
\x97,W\xbc\x97-\x96\xbcj?\x15\xdb\x8d\x92j\xd7\
\xbf{5{m{\xaf\xc4\xf2\x9bo\x1bhvC\xc6\
\x1e*\xf0F\x97}\xaaxoP\xf1\xce\xb5a\xe2\xc8\
4\xff\x00\x07\xf8\x8bM\xf0\xa6\x9dkk\xa6Yh\xde\
!\x1a\x95\xec\x96\x0c\xda\xa5\xe0\x1a\xf3x\xbek\xa35\
\xbc-\x7fj4Y\xfc2\xcf>\x9f\... | Python | 1 |
JWE pretty easily:
//! ````
//! "<protected_value>.<encrypted_key_value>.<iv_value>.<ciphertext_value>.<tag_value>"
//! ````
//! Streaming to a password protected JWK (JWE) simply requires adding the `--outpass`
//! argument:
//!
//! ````bash
//! > pkcs_jwk --in <mypkcs8.pem> --inpass file:password.txt --outpass file... | Rust | 0 |
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
from typing import List, Optional
from typing_extensions import Literal
from ..._models import BaseModel
__all__ = ["TranscriptionTextDoneEvent", "Logprob"]
class Logprob(BaseModel):
token: Optional[str] = None
"""The tok... | Python | 1 |
_3 => 3,
OCMW_A::OCMW_4 => 4,
OCMW_A::OCMW_5 => 5,
}
}
}
#[doc = "Reader of field `OCMW`"]
pub type OCMW_R = crate::R<u8, OCMW_A>;
impl OCMW_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, OCMW_A> {
use crate::Variant::*;
match ... | Rust | 0 |
RLIMIT_FSIZE on the shell via export did not trigger
/// the exception, only with the explicit `setrlimit` call within the
/// script is the error triggered. Also writing to a file as the solution
/// in https://github.com/x746e/apue/blob/master/ch10/ex11-xfsz/mycat.c does
/// did not solve the issue
/// - som... | Rust | 0 |
et.
pub fn parse_icmp_packet<
I: IcmpIpExt,
C,
M: for<'a> IcmpMessage<I, &'a [u8], Code = C>,
F: for<'a> FnOnce(&IcmpPacket<I, &'a [u8], M>),
>(
mut buf: &[u8],
src_ip: I::Addr,
dst_ip: I::Addr,
f: F,
) -> ParseResult<(M, C)>
where
for<'a> IcmpPacket<I, &'a [u8], M>:
Parsable... | Rust | 0 |
_ptr() as _);
}
}
/// decodes the k -byte encoded input message storing the result in the n -byte output.
/// The function returns a 1 if the internal CRC passed and a 0 if it failed.
/// If no CRC was specified (e.g. LIQUID_CRC_NONE ) then a 1 is always returned.
pub fn decode(&self, pckt:... | Rust | 0 |
def find_peak_element(nums):
n = len(nums)
if n == 0:
return -1
if n == 1 or nums[0] > nums[1]:
return 0
if nums[n - 1] > nums[n - 2]:
return n - 1
for i in range(1, n - 1):
if nums[i] > nums[i - 1] and nums[i] > nums[i + 1]:
return i
return -1
nums = ... | Python | 1 |
import torch
import matplotlib.pyplot as plt
from torch.nn import functional as F
import numpy as np
import math
def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999):
""" beta schedule
Create a beta schedule that discretizes the given alpha_t_bar function,
which defines the cumulati... | Python | 1 |
variant of the algorithm.
use crate::geometry::primitives::{cross_product, FPCoordinate};
pub fn monotone_chain(input_coordinates: &[FPCoordinate]) -> Vec<FPCoordinate> {
let n = input_coordinates.len();
if n <= 3 {
return input_coordinates.into();
}
// TODO: Implement heuristic by Akl-Toussa... | Rust | 0 |
array
#[test]
fn test2_35() {
assert_eq!(search_insert(vec![1, 3, 5, 6], 5), 2);
assert_eq!(search_insert(vec![1, 3, 5, 6], 2), 1);
assert_eq!(search_insert(vec![1, 3, 5, 6], 7), 4);
assert_eq!(search_insert(vec![1, 3, 5, 6], 0), 0);
}
<filename>src/low_loader/context.rs
//! LLVM Context Wrapper
//!
//!... | Rust | 0 |
+ 1, mode2),
self.operand(sp + 2, mode3),
)
}
fn run(&mut self, input: &Vec<i32>) -> Result<Vec<i32>, Box<dyn Error>> {
let mut output: Vec<i32> = Vec::new();
let mut inputp = 0;
let mut ip = 0;
loop {
let opcode: Opcode = self.0[ip].try_into()?;... | Rust | 0 |
ids.append(int(graph_otl))
obj["res"] = ids
except Exception as e:
ret_code = CommonResponseStatus.SERVER_ERROR.value
err = repr(e)
error_log = log_oper.get_error_log(err, sys._getframe(), traceback.format_exc())
Logger.log_error(error_log)
... | Python | 1 |
required(true)
.help("URL for Tabasco server"),
)
.arg(
Arg::with_name("debug")
.long("debug")
.takes_value(false)
.help("Enables debug mode in the enclave"),
)
.get_matches();
let tabasco_url = matches.value... | Rust | 0 |
e_shadowed_locals_with_multi_descope() {
test_rant_file!(
"sources/access/override_shadowed_locals_with_multi_descope.rant",
"foo bar baz"
);
}
#[test]
fn empty_def() {
test_rant_file!("sources/access/empty-def.rant");
}
#[test]
fn multi_accessor_defs() {
test_rant!(r#"<$foo=8; $bar=2; $baz=[sub:<foo>... | Rust | 0 |
l=None)
self._forward_backward(data_batch=data_batch,
out_grads=[neg_advs, v_grads])
self._update_params()
def _discount(self, x, gamma):
return scipy.signal.lfilter([1], [1, -gamma], x[::-1], axis=0)[::-1]
def _forward_backward(self, data_batch, out_gra... | Python | 1 |
t(siz) => {
// Ok(CBqlType(CBqlTypeBase::Int as u8, siz as u16))
// }
// BqlType::DateTime => Ok(CBqlType(CBqlTypeBase::UInt as u8, 32)),
// _ => Err(MetaError::UnknownCBqlTypeConversionError),
// }
// }
// }
// #[repr(C)]
// pub enum CBqlTypeBase {
// ... | Rust | 0 |
str))]
archive: PathBuf,
/// Dir with files to process.
/// Renames files inside this dir.
/// Automatically creates a 'deduposaur.process_metadata.json' file and
/// deletes it when all files are processed.
/// When using this option, run the command one last time
/// so it can record delet... | Rust | 0 |
spacer_line = '/~~~~~~~~\\'
def print_logo():
'''Prints two copies of each figure, alternating figures
(dog, monkey, dog, monkey) and prints the following spacer
line with no leading space: /~~~~~~~~\ before the first figure,
between figures and after the last figure.
'''
print(spacer_line)
... | Python | 1 |
c == '\n' {
buf_to_read = buf_to_read.split_off(idx + s as usize);
buf.append(&mut buf_to_read);
return Ok(result);
}
result.push(c);
skip_count = s - 1;
} else if let Err((msg, count)) = next_char_result {
//printl... | Rust | 0 |
let rest =
&inner[1..];
fnn(self, env, &rest)
}
_ => bail!("only built-in functions can ba called"),
}
}
},
Ast::Square(inner) => {
... | Rust | 0 |
tCreateDatabaseW(sesid: super::StructuredStorage::JET_SESID, szfilename: *const u16, szconnect: *const u16, pdbid: *mut u32, grbit: u32) -> i32;
#[doc = "*Required features: 'Win32_Storage_Jet', 'Win32_Foundation', 'Win32_Storage_StructuredStorage'*"]
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Sto... | Rust | 0 |
print("Welcome to the Underwater World")
choice = input("Do you want to 'dive deeper' or 'surface'? ")
if choice == "dive deeper":
action = input("Do you want to 'search for pearls' or 'chase the fish'? ")
if action == "search for pearls":
print("You found a rare pearl. You Win!")
elif action == "ch... | Python | 1 |
def dispersion_relation_2D(p, theta, C):
arg = C*sqrt(sin(p*cos(theta))**2 +
sin(p*sin(theta))**2)
c_frac = 2./(C*p)*arcsin(arg)
return c_frac
import numpy as np
from numpy import \
cos, sin, arcsin, sqrt, pi # for nicer math formulas
r = p = np.linspace(0.001, pi/2, 101)
theta = n... | Python | 1 |
yload_len = self.mac_commands_bytes.len();
securityhelpers::encrypt_frm_data_payload(
&self.data[..],
&self.mac_commands_bytes[..],
self.fcnt,
nwk_skey,
)?
} else {
securityhelpers::encrypt_frm_data_payload(
... | Rust | 0 |
# SPDX-License-Identifier: Apache-2.0
# Copyright 2013-2019 The Meson development team
from __future__ import annotations
import functools
import typing as T
from .base import DependencyMethods, detect_compiler, SystemDependency
from .cmake import CMakeDependency
from .detect import packages
from .pkgconfig import P... | Python | 1 |
status_t_CERT_STATUS_VALIDITY_TOO_LONG: cef_cert_status_t = 32768;
pub const cef_cert_status_t_CERT_STATUS_IS_EV: cef_cert_status_t = 65536;
pub const cef_cert_status_t_CERT_STATUS_REV_CHECKING_ENABLED: cef_cert_status_t = 131072;
pub const cef_cert_status_t_CERT_STATUS_SHA1_SIGNATURE_PRESENT: cef_cert_status_t = 52428... | Rust | 0 |
urn self.guard_source() != GuardSource.SYNTHETIC_LOCAL
# Subclasses can be found in torch/_dynamo/source.py
@dataclasses.dataclass(frozen=True)
class ChainedSource(Source):
base: Source
def is_dict_key(self):
# Recurse until you either hit a ConstDictKey or a Source
return self.base.is_dict_k... | Python | 1 |
raise ValueError(msg)
@register_class('ScratchData', CORE_NAMESPACE)
class ScratchData(NWBData):
__nwbfields__ = ('description', )
@docval({'name': 'name', 'type': str, 'doc': 'the name of this container'},
{'name': 'data', 'type': ('scalar_data', 'array_data', 'data', Data), 'doc': 'the source ... | Python | 1 |
1)
def forward(
self, psd_in: ComplexTensor, ilens: torch.LongTensor, scaling: float = 2.0
) -> Tuple[torch.Tensor, torch.LongTensor]:
"""The forward function
Args:
psd_in (ComplexTensor): (B, F, C, C)
ilens (torch.Tensor): (B,)
scaling (float):
... | Python | 1 |
def test_large_model_pt(self):
vqa_pipeline = pipeline("visual-question-answering", model="dandelin/vilt-b32-finetuned-vqa")
image = "./tests/fixtures/tests_samples/COCO/000000039769.png"
question = "How many cats are there?"
outputs = vqa_pipeline(image=image, question=question, to... | Python | 1 |
EditorState, settings::Value as SettingValue};
/// type
pub type OwnedLayoutEditorState = Box<LayoutEditorState>;
/// type
pub type NullableOwnedLayoutEditorState = Option<OwnedLayoutEditorState>;
/// drop
#[no_mangle]
pub extern "C" fn LayoutEditorState_drop(this: OwnedLayoutEditorState) {
drop(this);
}
/// Ret... | Rust | 0 |
sitions,
scaled_words: &ScaledWords,
) -> InlineTextLayout {
use azul_core::ui_solver::InlineTextLine;
let font_size_px = word_positions.text_layout_options.font_size_px;
let space_advance = scaled_words.space_advance_px;
let line_height_px = space_advance
* word_positions
.text... | Rust | 0 |
xprs2J\
2Z1vjsMVW97rsKOs8lo+qxPGfni27udledH2ZQABGZHOgZsChj59Xb3oVAA8/V3rjt5Un7gsz2AHQ6aY6o\
ky59Rsg/CpB8gP7szjK/wrCclA==\"";
fn private_key_1() -> PrivateKey {
let pem = include_str!("../../../test_assets/private_keys/rsa-2048-pk_1.key")
.parse::<Pem>()
.expect("pem 1");
PrivateKey::f... | Rust | 0 |
#
import sys, os
#
from quspin.operators import hamiltonian # Hamiltonians and operators
from quspin.basis import boson_basis_1d # Hilbert space spin basis
from quspin.tools.evolution import evolve # ODE evolve tool
from quspin.tools.Floquet import Floquet_t_vec # stroboscopic time vector
import numpy as np # ge... | Python | 1 |
StartQuoteType::Quote),
'“' => CharType::StartQuote(StartQuoteType::SlantQuote),
'«' => CharType::StartQuote(StartQuoteType::LeftBracket),
'»' => CharType::StartQuote(StartQuoteType::RightBracket),
' '|'\t'|'\r'|'\n' => CharType::Whitespace,
'('|'['|'{' => CharType::Paren(true),
')'|']'|'}' => CharType::Par... | Rust | 0 |
if nums[*back] < nums[i] {
deque.pop_back().unwrap();
} else {
break;
}
}
deque.push_back(i);
if i>=k-1 {
res.push(nums[*deque.front().unwrap()]);
}
};
res
... | Rust | 0 |
lse:
return self._get_non_stacked_location(location)
@staticmethod
def _get_non_stacked_location(
location: Union[
DeckSlotName,
StagingSlotName,
ModuleCore,
NonConnectedModuleCore,
OffDeckType,
WasteChute,
... | Python | 1 |
': '{}'", cancel_txid, e),
}
// Still re-insert it, even if it'll be removed at the next `listunspent` poll
unvaults_cache.insert(
unvault_outpoint,
UtxoInfo {
txo,
is_confirmed: false,
},
);
}
Ok(())
}
// Rew... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.