text string | label_name string | labels int64 |
|---|---|---|
Var(Variable),
StackSlot(StackSlot),
}
impl Default for FinalValue {
fn default() -> Self {
Self::None
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum BTKind {
Int,
Uint,
Float(u8),
Bool,
}
impl BTKind {
pub fn of(tp: Ty) -> Self {
match EntityRef::index(tp)... | Rust | 0 |
uct SourceAnnotation {
// FIXME: These don't need to be pub crate
pub(crate) annotation: Annotation,
pub(crate) span: Span,
}
impl SourceAnnotation {
/// Gets the kind of annotation reported
pub fn kind(&self) -> AnnotateKind {
self.annotation.kind()
}
/// Gets the annotation's mes... | Rust | 0 |
false,
};
// if !res {
// tracing::trace!("Cannot merge: {}", dump(s));
// }
res
}
}
fn get_rightmost_alt_of_cond(e: &mut CondExpr) -> &mut Expr {
match &mut *e.alt {
Expr::Cond(alt) => get_rightmost_alt_of_cond(alt),
alt => alt,
}
}
fn count_l... | Rust | 0 |
ificationFailed)?;
// TODO: make sure air.lde_domain_size() == fri_verifier.domain_size()
// 5 ----- trace and constraint queries -------------------------------------------------------
// read proof-of-work nonce sent by the prover and update the public coin with it
let pow_nonce = channel.read_pow_no... | Rust | 0 |
#!/usr/bin/env pybricks-micropython
from pybricks.parameters import Port
from pybricks.tools import wait
import _thread
import time
from systems.LightSystem import LightSystem
from systems.LiftSystem import LiftSystem
from devices.SimpleUltraSonic import SimpleUltraSonic
from systems.DriveSystem import DriveSystem
fr... | Python | 1 |
xes `[0, 1, ..., seq_len - 1]`
seq_idx = torch.arange(seq_len, dtype=dtype, device=device)
# Calculate the product of position index and $\theta_i$
idx_theta = torch.outer(seq_idx, theta).float()
cache = torch.stack([torch.cos(idx_theta), torch.sin(idx_theta)], dim=-1)
# this is to mimic the beha... | Python | 1 |
t,
pub GuardBandTop: ::c_float,
pub GuardBandRight: ::c_float,
pub GuardBandBottom: ::c_float,
pub ExtentsAdjust: ::c_float,
pub StencilCaps: ::DWORD,
pub FVFCaps: ::DWORD,
pub TextureOpCaps: ::DWORD,
pub MaxTextureBlendStages: ::DWORD,
pub MaxSimultaneousTextures: ::DWORD,
pub V... | Rust | 0 |
: &str,
image_width: usize,
image_height: usize,
) -> String {
let plot_data = self.render_plot_data();
let plotly_js = PlotlyJs {}.render().unwrap();
let tmpl = PlotTemplate {
plot_data: plot_data.as_str(),
plotly_javascript: plotly_js.as_str(),
... | Rust | 0 |
"réng"),
('社', "shè"),
('礿', "yuè"),
('祀', "sì"),
('祁', "qí,zhǐ"),
('祂', "tā"),
('祃', "mà"),
('祄', "xiè"),
('祅', "yāo"),
('祆', "xiān"),
('祇', "qí,chí,zhī,zhǐ"),
('祈', "qí,guǐ"),
('祉', "zhǐ"),
('祊', "bēng,fāng"),
('祋', "duì"),
('祌', "zhòng,chōng"),
('祍', "... | Rust | 0 |
pub fn number_of_falses(mut self, input: i64) -> Self {
self.number_of_falses = Some(input);
self
}
pub fn set_number_of_falses(mut self, input: std::option::Option<i64>) -> Self {
self.number_of_falses = input;
self
}
/// <p>The nu... | Rust | 0 |
ey = self.selectedKey / 12 * 12
self.markSelectedKey()
def up(self):
self.smsChar = None
self.selectedKey -= 12
if self.selectedKey < 0:
self.selectedKey = self.max_key / 12 * 12 + self.selectedKey % 12
if self.selectedKey > self.max_key:
self.selectedKey -= 12
self.markSelectedKey()
def down(se... | Python | 1 |
self.ptr),
_marker:PhantomData,
}
}
}
/**
Clone is implemented for references and smart pointers,
using `GetPointerKind` to decide whether `P` is a smart pointer or a reference.
RObject does not implement Clone if P==`&mut ()` :
```compile_fail
use abi_stable::{
sabi_trait::{
doc... | Rust | 0 |
import mysql.connector
class DBConnection:
@staticmethod
def getConnection():
database = mysql.connector.connect(host="localhost", user="root", passwd="root", db='kmeans')
return database
if __name__=="__main__":
print(DBConnection.getConnection()) | Python | 1 |
-diag, -diag],
4 => [length, 0.0],
5 => [-length, 0.0],
6 => [ 0.0, length],
7 => [ 0.0, -length],
_ => unreachable!(),
}
}
#[inline(always)]
pub fn worley_3d<F>(
hasher: &dyn NoiseHasher,
distance_function: F,
return_type: ReturnType,
point: ... | Rust | 0 |
# -*- coding: utf-8 -*-
臺灣客家話拼音對照音值聲母表 = {
'b': 'p', 'p': 'pʰ', 'bb': 'b', 'm': 'm', 'f': 'f', 'v': 'v',
'd': 't', 't': 'tʰ', 'l': 'l', 'n': 'n', 'r': 'j',
'z': 'ts', 'c': 'tsʰ', 's': 's',
'j': 'tɕ', 'q': 'tɕʰ', 'x': 'ɕ',
'zh': 'tʃ', 'ch': 'tʃʰ', 'sh': 'ʃ', 'rh': 'ʒ',
'g': 'k', 'k': 'kʰ', 'ng':... | Python | 1 |
def is_dns_failure(event):
"""
Detects common DNS failure patterns in nslookup output
:param event: tuple of network events
:return: bool
"""
_id, tgt, method, res, latency, _ = event
if method != "nslookup" or not res:
return False
result = res.lower()
return any(term in r... | Python | 1 |
from . import benchmark
class PoolingBench(benchmark.Benchmark):
def __init__(self, case, mode, device, dtype, kernel_size, N, C, H, W):
super().__init__(mode, device)
self.case = case
self.kernel_size = kernel_size
self.N = N
self.C = C
self.H = H
self.W = ... | Python | 1 |
nt)
indices_at_axis = [
indices_at_axis,
]
indices_at_axis = indices_at_axis or [list(range(self._shape[ax])) for ax in axis]
reduced_shape = list(self._shape)
# the choices on the axis are reduced to 1, since it's determined by `indices_at_ax... | Python | 1 |
dex
.increment()
.map_err(|e| {
// FIXME: we should probably go back to 0 at this point.
BitcoindError::Custom(format!("Deriving next index: {}", e))
})?;
db_update_deposit_index(&revaultd.read().unwrap().db_file(), new_index)?;
revault... | Rust | 0 |
represent any JSON value.
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq, Hash, Default)]
pub struct Json<T>(pub T);
impl<T> Deref for Json<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> DerefMut for Json<T> {
fn deref_mut(&mut self) -> &mut Self::... | Rust | 0 |
unsafe { ::std::mem::zeroed() }
}
}
#[doc = " Listen Statement"]
#[doc = ""]
#[repr(C)]
#[derive(Debug, Hash, PartialEq, Eq)]
pub struct ListenStmt {
pub type_: NodeTag,
pub conditionname: *mut ::std::os::raw::c_char,
}
#[test]
fn bindgen_test_layout_ListenStmt() {
assert_eq!(
::std:... | Rust | 0 |
s'] = ffn1_biases
inputs['ffn2_weights'] = ffn2_weights
if ffn2_biases is not None:
inputs['ffn2_biases'] = ffn2_biases
# set attrs
attrs = {
'pre_layer_norm': pre_layer_norm,
'epsilon': epsilon,
'residual_alpha': residual_alpha,
... | Python | 1 |
iter::Iterator;
fn coords_iter<'a>(input: &'a str) -> impl Iterator<Item = (i32, i32)> + 'a {
use lazy_static::lazy_static;
use regex::Regex;
lazy_static! {
static ref PATTERN: Regex = Regex::new(r"(\d+),\s+(\d+)").unwrap();
}
PATTERN.captures_iter(input).filter_map(|caps| {
Some(... | Rust | 0 |
input_str = input("Enter comma-separated words: ")
words = input_str.split(',')
unique_sorted_words = sorted(set(words))
print("Processed words:")
print(' '.join(unique_sorted_words))
| Python | 1 |
import torch
from util.save_reference import save_reference
from typing import Tuple, List, Iterable
def create_squeeze(
shape: Tuple[int, ...] | List[int] | Iterable[int],
dtype: torch.dtype = torch.float32,
dir: str = "data",
name: str = "squeeze",
):
"""
Create a tensor of random values wit... | Python | 1 |
_15 = _bindgen_ty_15::IFLA_BOND_RESEND_IGMP;
pub const IFLA_BOND_NUM_PEER_NOTIF: _bindgen_ty_15 = _bindgen_ty_15::IFLA_BOND_NUM_PEER_NOTIF;
pub const IFLA_BOND_ALL_SLAVES_ACTIVE: _bindgen_ty_15 = _bindgen_ty_15::IFLA_BOND_ALL_SLAVES_ACTIVE;
pub const IFLA_BOND_MIN_LINKS: _bindgen_ty_15 = _bindgen_ty_15::IFLA_BOND_MIN_L... | Rust | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 1 14:56:28 2023
@author: jarn
"""
import tkinter as tk
def Interactivegraphplot(Graph):
'''
'''
pass
window = tk.Tk()
window.title("GraphVisualizer")
def handle_button_press(event):
window.destroy()
button = tk.Button(text="C... | Python | 1 |
center_y = reader.long()?;
let center_width = reader.dword()?;
let center_height = reader.dword()?;
Ok(Self {
center_x,
center_y,
center_width,
center_height,
})
}
}
/// A SliceOrigin describes the position of a [Slice] within the spr... | Rust | 0 |
test = {
'name': 'Higher Order Functions',
'points': 0,
'suites': [
{
'cases': [
{
'code': r"""
>>> # If Python displays <function...>, type Function, if it errors type Error, if it displays nothing type Nothing
>>> def cake():
... print('beets')
... | Python | 1 |
obj.name = object_name + "_imported" # Make the name unique
bpy.context.collection.objects.link(obj)
bpy.context.view_layer.objects.active = obj
obj.select_set(True)
cursor_location = bpy.context.scene.cursor.location
obj.location = cursor_location
... | Python | 1 |
(invocation) => {
server.process_invocation(&runtime, &invocation);
invocation.close(&runtime);
}
Err(OakError::OakStatus(OakStatus::ErrTerminated)) => {
break;
}
Err(error) => {
... | Rust | 0 |
ymin = int(xmin * width), int(ymin * height)
xmax, ymax = int(xmax * width), int(ymax * height)
words.append(word["value"])
words_bb.append([xmin, ymin, xmax, ymax])
# Process the boxes and get the referenc... | Python | 1 |
import os
import sys
import wintertools.circuitpython
import wintertools.fs
import wintertools.fw_fetch
import wintertools.jlink
import wintertools.uf2_to_bin
DEVICE_NAME = "winterbloom_big_honking_button"
USB_DEVICE_ID = "239A:6005"
JLINK_DEVICE = "ATSAMD21G18"
JLINK_SCRIPT = "scripts/flash.jlink"
ROOT_DIR = os.pat... | Python | 1 |
import os
import argparse
import numpy as np
from tqdm import tqdm
def split_npz(input_path, output_dir, chunk_size=10000):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
data = np.load(input_path)
img_emb = data['data'] # shape: (N, ...)
labels = data['label'] # shape: (... | Python | 1 |
mage_processor = self.default_image_processor
inputs = image_processor(
[np.zeros((3, 400, 333)), np.zeros((3, 400, 333))],
segmentation_maps=[np.zeros((384, 384)).astype(np.float32), np.zeros((384, 384)).astype(np.float32)],
return_tensors="pt",
)
inputs["p... | Python | 1 |
al_train_samples) * 100
MODEL.eval()
valid_loss = 0.0
correct = 0
total = 0
with torch.no_grad():
for images, rppgs, classes, labels in valid_loader:
images, rppgs, classes, labels = (
images.to(DEVICE),
rppgs.to(DEVICE),
classes.t... | Python | 1 |
const ERR_ELEMENT_SERIALIZATION: &str = "Cannot serialize element";
/// A non-iterable, lazily loaded storage map that stores its content directly on the storage trie.
///
/// This map stores the values under a hash of the map's `prefix` and [`BorshSerialize`] of the key
/// using the map's [`ToKey`] implementation.
/... | Rust | 0 |
r: colour.get_red() as f64 / 255.0,
g: colour.get_green() as f64 / 255.0,
b: colour.get_blue() as f64 / 255.0,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_contrast_ratio() {
let colour_black = Rgb::new(0, 0, 0);
let colour_blue = Rgb::new(0, 0, 25... | Rust | 0 |
_sh), dim=-1)
scales = 0.001 * F.softplus(scales)
scales = scales.clamp_max(0.3)
# Normalize the quaternion features to yield a valid quaternion.
rotations = rotations / (rotations.norm(dim=-1, keepdim=True) + eps)
sh = rearrange(sh, "... (xyz d_sh) -> ... | Python | 1 |
Ext('golang._os_test',
['golang/_os_test.pyx',
'golang/os_test.cpp']),
Ext('golang.os._signal',
['golang/os/_signal.pyx']),
Ext('golang._strconv',
['golang/_strco... | Python | 1 |
fw_ctx: &FwContext, message: &Message, args: &str) -> CommandResult {
message.reply(fw_ctx, args.to_string()).await?;
Ok(())
}
fn cmd<'a>(
fw_ctx: &'a FwContext,
message: &'a Arc<Message>,
args: &'a str,
) -> Pin<Box<dyn Future<Output = CommandResult> + Send + 'a>> {
Box::pin(command(fw_ctx, me... | Rust | 0 |
lf, do_resize):
userid = 'testuid'
size = '1g'
self.vmops.resize_memory(userid, size)
do_resize.assert_called_once_with(userid, size)
@mock.patch("zvmsdk.smtclient.SMTClient.live_migrate_move")
@mock.patch('zvmsdk.vmops.VMOps.get_power_state')
def test_live_migrate_vm(self, ... | Python | 1 |
0x00, // 0x1DD RESERVED
0x00, // 0x1DE RESERVED
0x00, // 0x1DF RESERVED
0x00, // 0x1E0 RESERVED
0x00, // 0x1E1 RESERVED
0x00, // 0x1E2 RESERVED
0x00, // 0x1E3 RESERVED
0x00, // 0x1E4 RESERVED
0x00, // 0x1E5 RESERVED
0x00, // 0x1E6 RESERVED
0x00, // 0x1E7 RESERVED
0x00, /... | Rust | 0 |
err) = err.error {
if let Some(clap_err) = err.downcast_ref::<clap::Error>() {
clap_err.exit()
}
}
let CliError {
error,
exit_code,
unknown,
} = err;
// `exit_code` of 0 means non-fatal error (e.g., docopt version info).
let fatal = exit_code != ... | Rust | 0 |
}
if account.access.contains("fleet-view") {
topics.push("fleet_comp".to_string());
}
Redirect::temporary(app.sse_client.events_url(&topics))
}
pub fn routes() -> Vec<rocket::Route> {
routes![stream,]
}
<reponame>shangsony/pea2pea
use bytes::Bytes;
use peak_alloc::PeakAlloc;
mod common;
us... | Rust | 0 |
# Copyright (c) 2025 Kodo Robotics
#
# 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 wri... | Python | 1 |
def demical_to_binary(n):
if n == 0:
return "0"
#создаем пустую строку для записи результата
binary = ""
while n>0:
#берем остаток от деления и добавляем его в строку binary
binary = str(n % 2) + binary
n = n//2
return binary
n = 12
print (demical_to_binary(n)) | Python | 1 |
workout_step::WorkoutStep::from_fields::<Order, Reader>(reader, fields)
.map(Message::WorkoutStep)
.map_err(|_e| "could not read message WorkoutStep".to_owned())
},
MesgNum::ZonesTarget => {
zones_target::ZonesTarget::from_fields::<Orde... | Rust | 0 |
(&self) -> usize {
unimplemented!();
}
}
pub fn range2idxs_1d<R>(r: R, size: usize) -> (usize, usize)
where R: RangeBounds<usize>,
{
let start_idx = match r.start_bound() {
Bound::Included(&x) => x,
Bound::Excluded(&x) => x + 1,
Bound::Unbounded => 0,
};
let end_idx = match r.end_bound() {
... | Rust | 0 |
def shape_list(x):
"""Deal with dynamic shape in tensorflow cleanly."""
static = x.shape.as_list()
dynamic = tf.shape(x)
return [(dynamic[i] if s is None else s) for i, s in enumerate(static)]
| Python | 1 |
;
fn foo() -> std::io::Result<()> {
let road_not_taken = b"I shall be telling this with a sigh
Somewhere ages and ages hence:
Two roads diverged in a wood, and I -
I took the one less traveled by,
And that has made all the difference.";
let file = try!(File::create("poem.txt"));
... | Rust | 0 |
ub use models::keys::keygen;
use models::topology::Topology;
use nymsphinx::addressing::clients::Recipient;
use nymsphinx::addressing::nodes::NymNodeRoutingAddress;
use nymsphinx::params::DEFAULT_NUM_MIX_HOPS;
use nymsphinx::Node as SphinxNode;
use nymsphinx::{delays, Destination, NodeAddressBytes, SphinxPacket};
use r... | Rust | 0 |
") # type: ignore[arg-type]
@pytest.mark.filterwarnings("ignore:.*backwards-compatibility:UserWarning")
def test_unique_none(constructor: Constructor) -> None:
if "duckdb" in str(constructor) and DUCKDB_VERSION < (1, 3):
pytest.skip()
df_raw = constructor(data)
df = nw.from_native(df_raw)
re... | Python | 1 |
#[test]
fn smoke() {
let cv = Condvar::new();
cv.notify_one();
cv.notify_all();
}
#[test]
fn notify_one() {
let mu = Arc::new(Mutex::new(()));
let cv = Arc::new(Condvar::new());
let mu2 = mu.clone();
let cv2 = cv.clone();
let guard = blo... | Rust | 0 |
t_P[valid_indices]
if len(lst_P) == 0:
return np.array([20, 20]), np.array([20, 20])
coeff_exp = np.polyfit(lst_bat, np.log(lst_P), 1)
coeff_pol = np.polyfit(lst_bat, lst_P, 2)
# y_pol = coeff_pol[0] * lst_bat**2 + coeff_pol[1] * lst_bat + coeff_pol[2]
# y_exp = np... | Python | 1 |
::new()?;
let version = Version::parse(env!("CARGO_PKG_VERSION")).unwrap();
let instance = Arc::new(Instance::new(
&CString::new("wosim").unwrap(),
version,
vec![],
)?);
let device = instance
.physical_devices()?
.into_iter()
... | Rust | 0 |
#!/bin/python3
# -*- coding: utf-8 -*-
# ##### BEGIN LICENSE BLOCK #####
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
... | Python | 1 |
, 4)));
pub fn trivial(self) -> SymbolicResult<Expr> {
match_term!(
self, {
Expr::Sym
| Expr::Cte [_] => Ok(self),
Expr::Num [n] => Ok(Expr::Num(n.trivial()?)),
Expr::Alg
| Expr::Fun
| Expr::Cal
//| Expr::Op
//| Expr::Sq
[e] => {
e.trivial... | Rust | 0 |
"""Test the Times of the Day integration."""
import pytest
from homeassistant.components.tod.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry
@pytest.mark.freeze_time("2022-03-16 17:37:00", tz_offset=-7... | Python | 1 |
# class - Classes são moldes para criar novos objetos
# As classes geram novos objetos (instâncias) que
# podem ter seus próprios atributos e métodos.
# Os objetos gerados pela classe podem usar seus dados
# internos para realizar várias ações.
# Por convenção, usamos PascalCase para nomes de
# classes.
# string = 'Lui... | Python | 1 |
maps_url = f"https://www.google.com/maps/search/?api=1&query={query}"
talk_print(f"{i}. {h} → {maps_url}")
if severity == "High":
talk_print("This seems serious. Please call emergency services immediately!")
talk_print(f"EMERGENCY ALERT! Call {emergency_numbers.get(c... | Python | 1 |
dir.join("sources"),
project_dir.join("examples"),
project_dir.join("scripts"),
project_dir.join("doc_templates"),
project_dir.join("tests"),
] {
ensure!(
path.exists(),
r#"Directory "{}" does not exist"#,
path.display()
);
}
... | Rust | 0 |
texture.render_to(&mut canvas, 0, 0, None);
// Update the screen
canvas.present();
}
}
<gh_stars>1-10
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use diem_transaction_builder::stdlib;
use diem_types::{account_config, vm_status::StatusCode};
use langua... | Rust | 0 |
MENT.html
//! [`CacheAligned`]: struct.CacheAligned.html
//! [`CStr`]: https://doc.rust-lang.org/std/ffi/struct.CStr.html
//! [`Deref`]: https://doc.rust-lang.org/std/ops/trait.Deref.html
//! [`DerefMut`]: https://doc.rust-lang.org/std/ops/trait.DerefMut.html
//! [`Drop`]: https://doc.rust-lang.org/std/ops/trait.Drop.h... | Rust | 0 |
groups=groups,
start_group=start_group,
group_count=group_count,
)
)
if offset != header.message_length:
raise comms.DecodeError(
f"AC Ability only decoded {offset} bytes out of {header.message_length}"
... | Python | 1 |
;
}
pub mod traits {
pub use super::handles::traits::*;
pub use super::msg_traits::*;
}
use syn::{
parse_macro_input,
LitStr,
parse::{Parse, ParseStream, Result},
};
use quote::quote;
use proc_macro::TokenStream;
struct ParseTarget(LitStr);
impl Parse for ParseTarget {
fn parse(input: ParseS... | Rust | 0 |
m plugins config.
QuayMetadataFetchPlugin::try_new(
settings.repository.clone(),
DEFAULT_QUAY_LABEL_FILTER.to_string(),
DEFAULT_QUAY_MANIFESTREF_KEY.to_string(),
None,
DEFAULT_API_BASE.to_string(),
... | Rust | 0 |
or p in properties:
type_ = UTIL.ofp_port_mod_prop_type_from_user(p['type'])
length = None
if type_ == ofp.OFPPDPT_ETHERNET:
advertise = UTIL.ofp_port_features_from_user(p['advertise'])
prop.append(
parser.OFPPortModPropEthernet(type_, length, advertise))
... | Python | 1 |
<'a> {
Iter(p.legal_noisy_iter().chain(p.legal_quiet_iter()))
}
pub fn noisy_iter<'a>(p: &'a Position) -> NoisyIter<'a> {
let mut temp = p.clone();
NoisyIter(Box::new(p.psudo_legal_noisy_iter().filter(move |x| is_legal(&mut temp, x))))
}
pub fn quiet_iter<'a>(p: &'a Position) -> QuietIter<'a> {
let mu... | Rust | 0 |
new_size)?;
self.range.resize_subrange(&mut domain.range, &options)
}
}
#[derive(Debug)]
pub struct VMDomain {
range: VMRange,
}
impl_vmrange_trait_for!(VMDomain, range);
impl VMDomain {
pub fn alloc_area(
&mut self,
options: &VMAllocOptions,
flags: VMAreaFlags,
) -> R... | Rust | 0 |
one()),
h_aux: Some(h_aux),
cred_metadata: Some(cred_metadata),
..fcr50::TryAuthParams::EMPTY
};
let response = self
.proxy
.try_auth(try_auth_params)
.await
.map_err(|_| CredentialError::InternalError)?
.map... | Rust | 0 |
ced with actual process end conditions
"""
return random.random() < 0.1
def run_q_learning(env, episodes=30, alpha=0.1, gamma=0.9, epsilon=0.1):
"""
Q-learning algorithm for process optimization
Parameters:
- env: ProcessEnv instance
- episodes: Number of training episodes
... | Python | 1 |
}\n", val).as_str());
}
}
}
accum
}
pub fn get_method_annotations(attrs: &ast::Attrs) -> (String, bool) {
let mut accum: Vec<String> = Vec::new();
let mut is_noreturn = false;
for attr in attrs.0.iter() {
if let "blocking" | "const" | "internal" | "noreturn" | "test_cate... | Rust | 0 |
#def radRGB()
#fast_with_aFewError
from math import exp,log
c2_div_STDcolorR=2.05539304255011812e+04
c2_div_STDcolorG=2.63463675111716257e+04
c2_div_STDcolorB=3.30145738821726118e+04
hexFF =2.55999999999999943e+02#256-1/(1<<44)
STD_T_D65 =6500 #D65标准色温
STDgamma =2.2 #标准gamma值
LmapFunc_gamma ="gamma"
LmapFunc_Xga... | Python | 1 |
from flask import Flask, jsonify, request
from flask_cors import CORS
import requests
app = Flask(__name__)
CORS(app)
# Definindo a URL base da API Fipe
URL_BASE_FIPE = "https://parallelum.com.br/fipe/api/v1/carros"
# Endpoint para listar todas as marcas
@app.route('/api/carros/marcas', methods=['GET'])
def listar_m... | Python | 1 |
Op| { &m.period },
|m: &mut TezosSignTx_TezosBallotOp| { &mut m.period },
));
fields.push(::protobuf::reflect::accessor::make_singular_field_accessor::<_, ::protobuf::types::ProtobufTypeBytes>(
"proposal",
|m: &TezosSignTx_TezosBallotOp| { &m.propo... | Rust | 0 |
}
/// MultiplexedSignalZeroA
///
/// - Min: 0
/// - Max: 3
/// - Unit: ""
/// - Receivers: Vector__XXX
#[inline(always)]
pub fn multiplexed_signal_zero_a(&self) -> f32 {
self.multiplexed_signal_zero_a_raw()
}
/// Get raw value of MultiplexedSignalZeroA
///
//... | Rust | 0 |
metadata = {"apiLevel": "2.15"}
requirements = {"apiLevel": "2.15"}
def run(protocol):
pass
| Python | 1 |
=====================================
# Due Report
@reportRouter.post('/due_report')
async def due_report(data:DueReport):
select = f"ifnull(b.cust_name,'NA')cust_name, a.phone_no, Sum(due_amt) - Sum(paid_amt)due_amt"
table_name = "td_recovery_new a,md_customer b"
where = f"a.comp_id = b.comp_id and a.phon... | Python | 1 |
of matched keys
#[structopt(name = "ls")]
Ls(FastPrint),
/// Print the list of matched keys with tags
#[structopt(name = "lstags")]
LsTags(ListTags),
/// Set the tags(overwrite) for the matched keys
#[structopt(name = "tags")]
Tags(SetTags),
/// Make the matched keys public avail... | Rust | 0 |
ert_eq!(a, 1);
assert_eq!(b, 2);
assert_eq!(c, 3);
assert_eq!(d, 4);
assert_eq!(e, 5);
assert_eq!(f, 6);
assert_eq!(g, 7);
assert_eq!(h, 8);
}
#[export_function]
pub fn floattypes(a: f32, b: f64) {
assert_eq!(a, 1.);
assert_eq!(b, 2.);... | Rust | 0 |
1_kind(OpKind::Register);
write_op1_reg!(instruction, decoder.state.rm + decoder.state.extra_base_register_base_evex + this.base_reg2 as u32);
if (decoder.state.flags & StateFlags::B) != 0 {
instruction.set_suppress_all_exceptions(true);
}
} else {
instruction.set_op1_kind(OpKind::Memory);
if (deco... | Rust | 0 |
_usage();
std::process::exit(1);
}
let linenum = args[2].parse::<usize>().unwrap();
let charnum = args[3].parse::<usize>().unwrap();
let fname = &args[4];
let fpath = Path::new(fname);
let src = racer::load_file(&fpath);
let pos = scopes::coords_to_point(&*src, linenum, charnum);
... | Rust | 0 |
, 48, 64, 96, 128, 256,
512, 1024, 2048, 4096
);
#[cfg(target_arch = "x86")]
unsafe impl Zeroable for x86::__m128i {}
#[cfg(target_arch = "x86")]
unsafe impl Zeroable for x86::__m128 {}
#[cfg(target_arch = "x86")]
unsafe impl Zeroable for x86::__m128d {}
#[cfg(target_arch = "x86")]
unsafe impl Zeroable for x86::__m2... | Rust | 0 |
op_bits
}
pub fn hd_op_bits(&self) -> &[E] {
&self.hd_op_bits
}
pub fn op_code(&self) -> E {
let mut result = self.ld_op_bits[0];
result += self.ld_op_bits[1] * E::from(2u32);
result += self.ld_op_bits[2] * E::from(4u32);
result += self.ld_op_bits[3] * E::from(8... | Rust | 0 |
inputs=[current_chat_id],
outputs=[faq_feedback_good, faq_feedback_bad]
)
for lang in langs:
make_language_tab(lang)
# === Chat History Interface ===
with gr.Tab(LABELS[DEFAULT_LANG]["chat_history"]): # Use default lang ... | Python | 1 |
_buf: [u8; 24] = [0; 24];
let mut input: [u8; 16] = [0; 16];
let mut rng = rand::rngs::SmallRng::from_entropy();
for elt in &mut input {
*elt = rng.gen();
}
assert_eq!(22, encode_config_slice(&input, STANDARD_NO_PAD, &mut buf));
let decoded = decode_config(&buf, STANDARD_NO_PAD).unwrap... | Rust | 0 |
the node's admin service
/// 5. Fetch the circuit that was abandoned in the previous step
/// 6. Validate the returned circuit has a `circuit_status` of `Abandoned`
#[test]
fn test_abandon_circuit() {
let store = setup_admin_service_store();
let event_store = store.clone_boxed();
... | Rust | 0 |
items.append({
'Item': menu['salad'],
'Quantity': f"{self.quantity_guide['salads'] * guests:.1f} kg",
'Category': 'Salad'
})
items.append({
'Item': menu['drink'],
'Quantity': f"{self.quantity_guide['drinks'] * guests:.0f} ... | Python | 1 |
crate::ui::Size;
use crate::{
components::{
popup_paragraph, visibility_blocking, CommandBlocking,
CommandInfo, Component, DrawableComponent,
},
keys::SharedKeyConfig,
strings,
ui::{self, style::SharedTheme},
};
use anyhow::Result;
use crossterm::event::{Event, KeyCode, KeyModifiers... | Rust | 0 |
import os
import requests
import time
import hmac
import hashlib
from telegram import Bot
# Leer variables de entorno
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
TELEGRAM_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID")
API_KEY = os.getenv("MEXC_API_KEY")
API_SECRET = os.getenv("MEXC_API_SECRET")
# Mostrar en logs si las var... | Python | 1 |
y, Debug, PartialEq)]
pub enum UCSTPIE_A {
#[doc = "0: Interrupt disabled"]
UCSTPIE_0 = 0,
#[doc = "1: Interrupt enabled"]
UCSTPIE_1 = 1,
}
impl From<UCSTPIE_A> for bool {
#[inline(always)]
fn from(variant: UCSTPIE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `UCSTPIE... | Rust | 0 |
rap();
tab.set_bounds(Bounds::Normal {
left: Some(0),
top: Some(0),
width: Some(1920),
height: Some(1080),
}).unwrap();
tab.navigate_to(start.as_str()).unwrap();
tab.wait_until_navigated().unwrap();
let png_data = tab.capture_screenshot(ScreenshotFormat::PNG, None, t... | Rust | 0 |
elf
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_NetworkManagement_QoS\"`*"]
pub struct IntServMainHdr {
pub ismh_version: u8,
pub ismh_unused: u8,
pub ismh_len32b: u16,
}
impl ::core::marker::Copy for IntServMainHdr {}
impl ::core::clone::Clone for IntServMainHdr {
fn clone(&self) -> Self {... | Rust | 0 |
impl SubscriptionManager {
pub fn subscribers(&self, ev: &WmEvent) -> Vec<&PluginId> {
let sub: SubscriptionEvent = ev.into();
self.subs
.get(&sub)
.map(|subs| {
subs.iter()
.filter(|(_, filters)| {
filters.iter().a... | Rust | 0 |
*, *num_labels*)
/// - `all_hidden_states` - `Option<Vec<Tensor>>` of length *num_hidden_layers* with shape (*batch size*, *sequence_length*, *hidden_size*)
/// - `all_attentions` - `Option<Vec<Vec<Tensor>>>` of length *num_hidden_layers* of nested length *inner_group_num* with shape (*batch size*, *sequenc... | Rust | 0 |
#Any pytest file should start with test so that it can execute it
#pytest method should start with test
#Any code should be wrapped in a method
#to execute in CLI - cd <path_of_the_tests>, py.test - to execute, -v to get more info
#-s to get console output - print statements = py.test -v -s (all tests in the given path... | Python | 1 |
field!(err, EditGroupMemberBuilderError, "access_level");
}
#[test]
fn sufficient_parameters() {
EditGroupMember::builder()
.group("group")
.user(1)
.access_level(AccessLevel::Developer)
.build()
.unwrap();
}
#[test]
fn endpoi... | Rust | 0 |
::Pid;
pub fn clone(cb: sched::CloneCb, clone_flags: sched::CloneFlags) -> Result<Pid> {
// unlike fork, clone requires the caller to allocate the stack. here, we use the default
// 4KB for stack size, consistant with the runc implementation.
const STACK_SIZE: usize = 4096;
let stack: &mut [u8; STACK_S... | Rust | 0 |
dataset = pd.read_csv(dataset_file)
perm_idxs = rng.permutation(len(dataset))
cutoff = int(len(dataset) * TRAIN_VAL_RATIO[0])
train_idxs = perm_idxs[:cutoff]
val_idxs = perm_idxs[cutoff:]
train_df = dataset.iloc[train_idxs]
val_df = dataset.iloc[val_idxs]
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.