text string | label_name string | labels int64 |
|---|---|---|
def spherical_dist_loss(x, y):
x = F.normalize(x, dim=-1)
y = F.normalize(y, dim=-1)
return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2)
| Python | 1 |
termination of a running job.
Termination = 2,
/// Registers a new executor at the coordinator.
AddExecutor = 3,
/// Registers a spawned job worker group.
AddWorkerGroup = 4,
/// Subscribes to an topic in the catalog.
Subscribe = 5,
/// Unsubscribes from a topic.
Unsubscribe = 6,
... | Rust | 0 |
b = matrix_b.unwrap();
debug_message(&format!("End parse matrix: {:?}", SECOND_MATRIX));
if matrix_a[0].len() != matrix_b.len() {
debug_message(&format!("matrices can't be multiplied"));
return FUNCTION_ERROR;
}
let mut matrix_c:Vec<Vec<f64>> = Vec::new();
debug_message(&format!("... | Rust | 0 |
_next: bool,
_current: FileId,
_path_index: PathIndex,
) -> Option<BufferData> {
None
}
fn get_id(&mut self, _path: &PathBuf) -> FileId {
FileId(0)
}
fn get_path(&self, _id: FileId) -> PathBuf {
PathBuf::from("")
}
fn set_source(&mut self, _sourc... | Rust | 0 |
ockIter<U>) -> bool {
cmp_block_iter(self, other) == Ordering::Equal
}
}
impl<T: Bits> Eq for BlockIter<T> {}
impl<T, U> PartialOrd<BlockIter<U>> for BlockIter<T>
where T: Bits,
U: Bits<Block = T::Block> {
fn partial_cmp(&self, other: &BlockIter<U>) -> Option<Ordering> {
Some(cm... | Rust | 0 |
set = (offset as i64).wrapping_add(cst as i64);
if low32_will_sign_extend_to_64(final_offset as u64) {
let base = put_input_in_reg(ctx, add_inputs[1 - i]);
return Amode::imm_reg(final_offset as u32, base).with_flags(flags);
}
... | Rust | 0 |
=> it.skip(cnt),
}
}
}
<reponame>amethyst/naia
use std::{net::SocketAddr, time::Duration};
use naia_shared::{LinkConditionerConfig, SharedConfig};
use super::protocol::Protocol;
pub fn get_server_address() -> SocketAddr {
return "127.0.0.1:14191"
.parse()
.expect("could not parse soc... | Rust | 0 |
":2,"d":3,"e":4}
"#
);
test!(
destructing_alt2,
r#"
.[] as {$a, $b, c: {$d}} ?// {$a, $b, c: [{$e}]} | {$a, $b, $d, $e}
"#,
r#"
[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]
"#,
r#"
{"a":1,"b":2,"d":3,"e":null}
{"a":1,"b":2,"d":null,"e"... | Rust | 0 |
"""
Armando entorno virtuales
"""
print("Hello world") | Python | 1 |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# Set the style
sns.set_style("white")
# Create a figure
plt.figure(figsize=(10, 10))
# Create grid points
x = np.linspace(-4, 4, 15)
y = np.linspace(-4, 4, 15)
X, Y = np.meshgrid(x, y)
# Calculate radius at each point
R = np.clip(np.sqrt(X**2... | Python | 1 |
(state.fs.fd_map.get(&from).ok_or(__WASI_EBADF));
state.fs.fd_map.insert(
to,
Fd {
// TODO: verify this is correct
rights: fd_entry.rights_inheriting,
..*fd_entry
},
);
__WASI_ESUCCESS
}
/// ### `fd_seek()`
/// Update file descriptor offset
/// I... | Rust | 0 |
yncConfig | SQLAlchemyAsyncConfig,
capfd: CaptureFixture[str],
tmp_project_dir: Path,
) -> None:
from sqlalchemy.orm import DeclarativeBase
from advanced_alchemy import base, mixins
class _UUIDAuditBase(base.CommonTableAttributes, mixins.UUIDPrimaryKey, DeclarativeBase):
registry = base.cr... | Python | 1 |
# Main files
import gradio as gr
from agent import run_nutritionist_pipeline
import os
import re
def process_meal(username, meal_desc, dietary_preference):
"""
Process a meal through the nutritionist pipeline.
Args:
username (str): Name of the user
meal_desc (str): Description of the m... | Python | 1 |
}/>
</>
}
}
fn create(_ctx: &Context<Self>) -> Self {
Self {}
}
fn update(&mut self, _ctx: &Context<Self>, _msg: Self::Message) -> bool {
false
}
}
<gh_stars>0
use grid::Grid;
use regex::Regex;
use std::cmp::max;
use std::cmp::min;
use std::fs::File;
use std::io... | Rust | 0 |
to_string()],
);
assert_eq!(
get_values(&tags, &vec!["Env".to_string(), "Name".to_string()]),
vec!["staging".to_string(), "api".to_string()]
);
assert_eq!(get_values(&tags, &vec!["env".to_string()]), vec![""]);
assert_eq!(
get_values(&tags, &vec!["ignore-monitor".to_string()]... | Rust | 0 |
# -*- coding: utf-8 -*-
# Copyright 2025 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 or... | Python | 1 |
= " upon successful return"]
#[doc = " @param timeout Maximum time in milliseconds to wait for data."]
#[doc = ""]
#[doc = " @return WEBINSPECTOR_E_SUCCESS on success,"]
#[doc = " WEBINSPECTOR_E_INVALID_ARG when client or *plist is NULL,"]
#[doc = " WEBINSPECTOR_E_PLIST_ERROR when the... | Rust | 0 |
oot.into(), 0, BOND_AMOUNT, RewardDestination::Staked).unwrap();
LiquidStaking::<T>::notification_received(
pallet_xcm::Origin::Response(MultiLocation::parent()).into(),
0u64,
Response::ExecutionResult(None)
).unwrap();
}: _(SystemOrigin::Root, 0, vec![val1.clone(... | Rust | 0 |
assert_eq!(0x5, vm.regs.v[vx as usize]);
assert_carry(&vm);
assert_eq!(initial_vy_val, vm.regs.v[vy as usize]);
}
#[test]
fn exec_instruction_subn_vx_vy_with_borrow() {
let vx: u8 = 2;
let vy: u8 = 3;
let initial_vx_val = 0x3;
let initial_vy_val = 0x2;
... | Rust | 0 |
ve(Serialize, Deserialize)]
pub struct BackupConfigSerialized {
backup_folder: String,
world_folder: String,
incremental_freq_hours: u64,
full_backup_every: u32,
keep_full_backup: u32,
rclone_path: Option<String>,
flush_on_save: bool,
silent: bool,
}
#[derive(Serialize, Deserialize)]
pu... | Rust | 0 |
64, 64, winuser::LR_LOADFROMFILE
) as HICON;
}
if hicon == null_mut() as HICON {
Err(unsafe { get_err("Error loading image") })
} else {
let mut nid = get_nid_struct(&self.window.info.hwnd);
nid.uFlags = NIF_ICON;
nid.hIcon = hicon;
unsafe {
if shellapi::Shell_No... | Rust | 0 |
nnexb"],
VideoFormat::HEVC =>
&["libx265", "-preset", "ultrafast"],
VideoFormat::VP8 => &["vp8"],
VideoFormat::Other(ref s) =>
unreachable!("Unknown codec {:?} should never be used as a target.", s),
}
}
}
#[derive(Debug)]
pub struct Format {
container: ContainerFormat,
audio: Option<AudioFormat>... | Rust | 0 |
/// after reaching the `ASYNC_FLUSH_QD_LINES_THRESHOLD`, log lines are still
/// coming in faster than they can actually be flushed, when we reach this limit
/// we'll pause and let it finish flushing rather than letting the queue
/// continue growing.
const SYNC_FLUSH_QD_LINES_THRESHOLD: usize = 10 * ASYNC_FLUSH_QD_L... | Rust | 0 |
from django.conf import settings
from redis import Redis
from datetime import datetime, timezone
class RedisTokenRepository:
def __init__(self):
self.redis = Redis(
host=getattr(settings, "REDIS_HOST", "localhost"),
port=6379,
db=0,
username=getattr(settings... | Python | 1 |
# Copyright 2022 The Music Spectrogram Diffusion Authors.
# Copyright 2024 The HuggingFace Team. 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... | Python | 1 |
,
0,
preimage_hash.clone()
));
assert_eq!(
last_event(),
Event::Governance(crate::Event::PreimageInvalid(BOB_COUNTRY_ID, preimage_hash.clone(), 0))
);
});
}
#[test]
fn unlocking_balance_after_removing_vote_works() {
ExtBuilder::default().build().execute_with(|| {
let origin = Origin::signed(ALICE... | Rust | 0 |
result
} else {
panic!("Can't return a value for method `{}` with no matching expectations.", self.sig.name);
}
}
// For Testing
#[allow(dead_code)]
fn id_count(&self) -> usize {
self.ids.len()
}
}
#[cfg(test)]
mod store_tests {
use super::*;
use constra... | Rust | 0 |
c learning rate.")
w -= learning_rate * gradients
print("✅ Huấn luyện hoàn tất!")
print(f"Trọng số cuối cùng: {w.flatten()}")
return w
def training(data, target_col):
st.write("## 📊 Chia dữ liệu (Training - Validation - Testing)")
# Kiểm tra nếu `target_column` chưa tồn tại
# if "... | Python | 1 |
rim::u128::u128;
///
/// assert_eq!(u128::new(6).wrapping_mul(u128::new(9)), u128::new(54));
///
/// let a = u128::max_value() - u128::new(2);
/// let b = u128::max_value() - u128::new(4);
/// assert_eq!(a.wrapping_mul(b), u128::new(15));
/// ```
pub fn wrapping_mul(self, other: u128) ->... | Rust | 0 |
a 8bit model from the Hub works as expected
"""
from bitsandbytes.nn import Int8Params
model_id = "ybelkada/gpt2-xl-8bit"
model = AutoModelForCausalLM.from_pretrained(model_id)
linear = get_some_linear_layer(model)
self.assertTrue(linear.weight.__class__ == Int8Params... | Python | 1 |
listener_modes: Vec<ListenerMode>,
}
impl JmuxProxyArgs {
fn parse(c: &Context) -> anyhow::Result<Self> {
let common = CommonArgs::parse(JMUX_PROXY_SUBCOMMAND, c)?;
let arg_pipe = c.args.get(0).context("<PIPE> is missing")?.clone();
let pipe_mode = parse_pipe_mode(arg_pipe).context("B... | Rust | 0 |
::util::paths::resolve_executable;
use cargo::Config;
use flate2::read::GzDecoder;
use std::ffi::OsString;
use std::io::Read;
use std::io::Write;
use std::path::Path;
const COMPRESSED_MAN: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/man.tgz"));
/// Checks if the `help` command is being issued.
///
/// This runs... | Rust | 0 |
new(nonce_seed: [u8; 8]) -> CountingNonceSequence {
let mut buff = [0 as u8; 12];
buff[..8].copy_from_slice(&nonce_seed[..]);
CountingNonceSequence {
count: 0,
buff: buff
}
}
}
impl NonceSequence for CountingNonceSequence {
fn advance(&mut self) -> Res... | Rust | 0 |
unused_mut)]
let mut entry_2118 = list_2117.entry();
entry_2118.string(item_2116);
}
list_2117.finish();
}
#[allow(unused_mut)]
let mut scope_2119 = writer.prefix("DryRun");
if let Some(var_2120) = &input.dry_run {
scope_2119.boolean(*var_2120);
}
... | Rust | 0 |
def leftRightArrowsPattern(rows):
r, r1, c, row1 = None, None, None, None
row1 = rows
rows = rows * 4
print ("\n----Panah Ke Kanan-----\n")
for r in range (1, rows):
# to print the left arrow
if r <= row1:
for c in range (1, (row1 - r) + 1):
print (end=" ... | Python | 1 |
"""
All function in this module take and return :class:`bytes`
""" | Python | 1 |
8311],
[-0.44411578327900214],
[-0.30198985650876464],
[-0.15278551580218513],
[6.661338147750939e-16],
[0.1527855158021858],
[0.30198985650876564],
[0.4441157832790025],
[0.5758319602618311],
[0.6940510260622235],
[0.7960019260777125],
... | Rust | 0 |
UKTeaspoons,
}
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
pub enum Unit {
Angle(AngleUnit),
Area(AreaUnit),
Distance(DistanceUnit),
Energy(EnergyUnit),
Force(ForceUnit),
Mass(MassUnit),
Power(PowerUnit),
Pressure(PressureUnit),
Temperature(TemperatureUnit),
Time(TimeUnit),
Volume(VolumeUnit),
}
... | Rust | 0 |
from dash import Dash, html, dcc, Input, Output
import dash_daq as daq
import plotly.express as px
import dash_bootstrap_components as dbc
import pandas as pd
df = px.data.tips()
app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
gauge = html.Div(
[
daq.Gauge(
label="Party Size... | Python | 1 |
t' % i)
train_writer.flush()
print(loss)
train_writer.flush()
self.sess.close()
def train_exe(self):
"""
进行一轮训练
:return:
"""
start = time.time()
time_all = 0.0
start_c = 0
for sentence_index, (sentence, tags) in enumerate(zip(self.words_batch, self.tags_batch)):
... | Python | 1 |
t"]):
new_cid = None
for i, (cid, data) in enumerate(cid2chapter_list):
if data.text == "[CHAPTER_ROOT]":
continue
if context_idx < data.context_id:
new_cid = cid2chapter_list[i - 1][0]
break
... | Python | 1 |
class DrawingData:
def __init__(self, labels, data1, data2, data1_label, data2_label, title):
self.labels = labels
self.data1 = data1
self.data2 = data2
self.data1_label = data1_label
self.data2_label = data2_label
self.title = title #
def get_all_data(self):
... | Python | 1 |
from discretehelpers.a import int_to_perm
from discretehelpers.boolf import Boolf
from discretehelpers.boolf.examples import tatami, fusuma, geloba
def test_faction():
tatami_faction = tatami.ec_faction()
assert tatami_faction.block_labels == {
(0, 1): Boolf('1111 1000'),
(2, 3): Boolf('1110 ... | Python | 1 |
task::AtomicWaker,
};
pub mod uart_16550;
static SERIAL_QUEUE: OnceCell<ArrayQueue<u8>> = OnceCell::uninit();
static WAKER: AtomicWaker = AtomicWaker::new();
pub struct SerialStream {
_private: (),
}
impl SerialStream {
pub fn new() -> Self {
SERIAL_QUEUE
.try_init_once(|| ArrayQueue::ne... | Rust | 0 |
tored and proved. They are only appended to the tree but
//! never deleted or updated.
//!
//! # Internal Nodes
//! A non-leaf node carries the hash value derived from both its left and right children.
//!
//! # Placeholder Nodes
//! To make sure each Leaf node has a Merkle Proof towards the root, placeholder nodes are... | Rust | 0 |
_builtin_HEXAGON_M2_mmpyuh_rs0",
"llvm.hexagon.M2.mmpyuh.rs1" => "__builtin_HEXAGON_M2_mmpyuh_rs1",
"llvm.hexagon.M2.mmpyuh.s0" => "__builtin_HEXAGON_M2_mmpyuh_s0",
"llvm.hexagon.M2.mmpyuh.s1" => "__builtin_HEXAGON_M2_mmpyuh_s1",
"llvm.hexagon.M2.mmpyul.rs0" => "__builtin_HEXAGON_M2_mmpyul_rs0",
"ll... | Rust | 0 |
- Late frame synchronization detection interrupt enable"]
pub struct LFSDETIE_W<'a> {
w: &'a mut W,
}
impl<'a> LFSDETIE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LFSDETIE_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Interru... | Rust | 0 |
:
print(f"명령어 검색 오류: {e}")
return []
finally:
session.close()
@classmethod
def cosine_search(cls,
query: str,
top_k: int = 5) -> List[Dict[str, Any]]:
"""
하이브리드 검색 (키워드 + 벡터 검색)
Args... | Python | 1 |
aginator::items)
pub struct ListHarvestJobsPaginatorItems<
C = aws_smithy_client::erase::DynConnector,
M = crate::middleware::DefaultMiddleware,
R = aws_smithy_client::retry::Standard,
>(ListHarvestJobsPaginator<C, M, R>);
impl<C, M, R> ListHarvestJobsPaginatorItems<C, M, R>
where
C: aws_smithy_client:... | Rust | 0 |
# !usr/bin/env python
# -*- coding:utf-8 -*-
# Author:LiuQian,time:2018/12/18
# DDQN + 高斯马尔科夫移动模型 + 用户关联(A1, A1)15*25个动作 + 用户速度、角度随机,移动模型中有高斯变量(初始位置变化) + 用户公平性 + 约束无人机最后一点尽可能的近一点
# 改变用户密度-12个用户
import numpy as np
import tkinter as tk
import time
import tensorflow as tf
import math
UNIT = 40
MAZE_H = 15
MAZE_W = 25
... | Python | 1 |
_on_copy)]
#![deny(clippy::fallible_impl_from)]
#![deny(clippy::implicit_clone)]
#![deny(clippy::large_stack_arrays)]
#![warn(clippy::manual_ok_or)]
#![deny(clippy::missing_docs_in_private_items)]
#![deny(clippy::missing_panics_doc)]
#![warn(clippy::needless_borrow)]
#![warn(clippy::needless_pass_by_value)]
#![warn(cli... | Rust | 0 |
( $( $thing:expr ),+ ) => { macro_seqc_expr!(1, $($thing),*) };
( $( $thing:pat ),+ ) => { macro_seqc_pat!(1, $($thing),*) };
() => { 0 };
}
/**
* Helper for macro_seqc!
*/
#[macro_export]
macro_rules! macro_seqc_expr {
( $id:expr, $head:expr, $( $tail:expr ),* ) => ({
macro_seqc_expr!( $id + 1... | Rust | 0 |
"""A test for GW job maker."""
import pytest
from jobflow import run_locally
from pymatgen.io.aims.sets.bs import GWSetGenerator
from atomate2.aims.jobs.core import GWMaker
from atomate2.aims.schemas.task import AimsTaskDoc
def test_gw_maker_molecule(tmp_dir, species_dir, mock_aims, o2):
# mapping from job name... | Python | 1 |
d_data(mech_sel, fp_path, lbl_path)
X_train, X_test, y_train, y_test = train_test_split(
X_all, y_all, test_size=0.3, stratify=y_all, random_state=RANDOM_STATE
)
sampler = SMOTE(random_state=RANDOM_STATE) if resample_method == 'smote' else RandomUnder... | Python | 1 |
# Group: 24
# Names: Divy, Elio, Kelvin, Matthew
import board
import digitalio
import time
"""
Keypad code for our second Pico board. Reads input from the keypad
and prints the corresponding number to the serial console which is
read by the connected computer (see serial_keypad.py).
"""
# Keypad pin declarations
pRo... | Python | 1 |
import subprocess
import time
import os
import glob
import threading
import xml.etree.ElementTree as ET
from collections import namedtuple, deque
import argparse
COMMAND_TEMPLATE = """
CUDA_VISIBLE_DEVICES={gpu_ids} python auto_eval_logits.py \
--model_name "{model_model}" \
--model_path "{model_path}" \
-... | Python | 1 |
nt: 0,
}
}
fn value(&self) -> Option<Arc<HandlerObj>> {
match &self.value {
None => None,
Some(v) => Some(v.clone()),
}
}
fn set_value(&mut self, value: HandlerObj) {
self.value = Some(Arc::new(value));
}
fn add_child(&mut self, child_id: NodeId) {
if self.children_count == MAX_CHILDREN {
pa... | Rust | 0 |
spellcheck::*;
//!
//! let mut cities = CityData::new();
//! cities
//! .populate_from_file("data/cities_canada-usa-filtered.csv")
//! .unwrap();
//! let london = Coordinate::new(42.98339, -81.23304);
//!
//! let results = cities.search("London", Some(london));
//! assert_eq!(
//! format!("{:?}", resul... | Rust | 0 |
data": None}
return err_po_num_empty
def err_po_num():
err_po_num = {"code": "1061", "msg": "订单已经存在", "data": None}
return err_po_num
def err_po_qty_type():
err_po_qty_type = {"code": "1062", "msg": "数量必须是数字", "data": None}
return err_po_qty_type
def err_po_qty():
... | Python | 1 |
"""
La libreria `pyttsx3` in Python è utilizzata per la sintesi vocale, permettendo di convertire il testo in parlato.
È un'interfaccia offline che supporta vari motori di sintesi vocale come SAPI5 su Windows, NSSpeechSynthesizer su MacOS
e espeak su Unix.
Ecco alcuni degli utilizzi più comuni della libreria `pyttsx... | Python | 1 |
(0, 255)
slider.valueChanged.connect(self._on_rgb_slider_changed)
value_label = QLabel("0")
value_label.setMinimumWidth(35)
value_label.setAlignment(Qt.AlignmentFlag.AlignRight)
rgb_layout.addWidget(label, i, 0)
rgb_layout.addWidget(s... | Python | 1 |
for j in range(n_factories):
model.addCons(tram_service[j] <= self.max_tram_cost_budget, f"TramCostBudget_{j}")
# Constraints: annual transport plan
total_transport = np.sum(transportation_demands)
model.addCons(quicksum(depot_capacities[j] * factory_depot[j] for j in ra... | Python | 1 |
rkServer>, net_event_handler: Arc<T>, non_blocking: bool)
where
T: NetEvents + 'static + Sync + Send + Sized,
{
for conn_handler in network_server.conn_handlers.iter() {
let ev = net_event_handler.clone(); //kanudo.network_controller.clone();
let c = conn_handler.... | Rust | 0 |
, drops, AmountType::Fee)
}
#[inline(always)]
fn encode_account_src(buf_out: &mut [u8], account_id: &Buffer<ACC_ID_LEN>) {
encode_account(buf_out, account_id, AccountType::Account)
}
#[inline(always)]
fn encode_account_dst(buf_out: &mut [u8], account_id: &Buffer<ACC_ID_LEN>) {
encode_account(buf_out, account_... | Rust | 0 |
0A,// VectorLength_er
0x39,// VkW_er_5
0x4D,// XMM0
0x4D,// XMM0
0xF5, 0x0D,// EVEX_Vcvttpd2qq_xmm_k1z_xmmm128b64
0x0B,// N16b8
0x01,// true
0x39,// VkW_er_5
0x6D,// YMM0
0x6D,// YMM0
0xF6, 0x0D,// EVEX_Vcvttpd2qq_ymm_k1z_ymmm256b64
0x0C,// N32b8
0x01,// true
... | Rust | 0 |
}
def __iter__(self):
for idx in range(len(self)):
yield self[idx]
if __name__ == "__main__":
rot_vec = np.array([1, 0.0, 0.0]) * 90.0
Rmat = R.from_rotvec(rot_vec, degrees=True).as_matrix()
# Rmat = None
video1 = "/media/test/T7/video_test.mp4"
video2 = "/med... | Python | 1 |
{
Open(tok::DotDotDot),
Inclusive(tok::DotDotEq, Box<Pat>),
Exclusive(tok::DotDot, Box<Pat>),
}
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct PatGroup {
pub lparen_tok: tok::LParen,
pub tys: Punctuated<Pat, tok::Comma>,
pub rparen_tok: tok::RParen,
}
#[derive(Debug, PartialEq, Eq, Hash)]
p... | Rust | 0 |
if snip.as_slice().contains("/") {
try!(write!(out, "<span class='comment'>{}</span>",
Escape(snip.as_slice())));
} else {
try!(write!(out, "{}", Escape(snip.as_slice())));
}
}
last = next.sp.hi;
i... | Rust | 0 |
import logging
class CheesyVM:
def __init__(self, code):
self.MAX_OPS = 3000
self.optimized_code = ''.join(filter(lambda x: x in ['.', ',', '[', ']', '<', '>', '+', '-'], code))
self.code = code
stack, self.jumps = [], {}
for position, command in enumerate(code):
... | Python | 1 |
If the matrix is not symmetric or positive definite, None is returned.
//
// Solve L one row at a time from row 1 to row n:
// A = L * L'
//
// a11 a12 .. .. a1n L11 0 .. .. 0 L11 L21 .. .. Ln1
// a21 a22 .. .. a2n L21 L22 .. .. 0 0 L22 .. .. Ln2
// .. .. .. .. .. = .. .. .. .. 0 * ..... | Rust | 0 |
by the arguments specified
sys.exit(launch.run(args))
if __name__ == "__main__":
# Set up a logger for the console messages. Initially configure the console handler to report
# debug messages until a file logger can be established to handle the debug messages. After
# which the console logger will be ... | Python | 1 |
#
# Elliptic Curve Equation
#
# y^2 = x^3 + A*x + B (mod P)
#
from .math import Math
from .point import Point
class CurveFp:
def __init__(self, A, B, P, N, Gx, Gy, name, oid, nistName=None):
self.A = A
self.B = B
self.P = P
self.N = N
self.G = Point(Gx, Gy)
self.na... | Python | 1 |
y_slug(conn, Some(user_id), to_delete)?;
diesel::delete(articles)
.filter(id.eq(art_id))
.execute(conn)
.map_err(Into::<Error>::into)?;
Ok(artcl)
}
use schema::articles;
#[derive(AsChangeset)]
#[table_name = "articles"]
struct ChangeArticle {
slug: Option<String>,
title: Option<... | Rust | 0 |
e': 'Мелодрамы',
'Sci-Fi': 'Фантастика',
'Short': 'Короткометражки',
'Sport': 'Спортивные',
'Thriller': 'Триллеры',
'War': 'Военные',
'Western': 'Вестерны',
'[B]by Site[/B]': '[B]по Сайту[/B]',
'Cartoons Series': 'Мультсериа... | Python | 1 |
let eps = 1e-100;
let result = find_zeros(
f,
&Float::with_val(prec, 0.0f64),
&Float::with_val(prec, 1.0f64),
prec,
eps,
eps,
1000,
);
// let solution = 0.5f64.powf(1.0 / 3.0);
let value = f(&result.unwra... | Rust | 0 |
future::ready, TryStreamExt};
use redust_resp::{from_data, Data};
use tracing::instrument;
use crate::{model::pubsub::Response, Connection, Result};
use super::Command;
/// Unsubscribe from all channels and return this connection to normal mode.
#[derive(Debug)]
pub struct Unsubscribe;
#[async_trait]
impl Command f... | Rust | 0 |
CenterPos: DVector,
r: f64,
DivNum: i32,
DifColor: u32,
SpcColor: u32,
FillFlag: i32,
) -> i32;
pub fn dx_DrawCapsule3D(
Pos1: Vector,
Pos2: Vector,
r: f32,
DivNum: i32,
DifColor: u32,
SpcColor: u32,
FillFlag... | Rust | 0 |
figuration.kwargs.get("value_set", [])
}
observed_values = (
(name, schema)
for name, schema in renderer_configuration.params
if name.startswith(ov_param_prefix)
)
expected_values = (
(name, schema)
for name, schema in rendere... | Python | 1 |
import numpy as np
import matplotlib.pyplot as matplt
def generate_utility_function(resolution=100, min_val=0, max_val=1,):
No_U_Curve = True
No_Clip_Curve = False
while True:
# random select point between low and high, and build the function
fx = np.array([min_val,np.random.uniform(min_val... | Python | 1 |
name','date','time'))
tv.column('#0',width=82)
tv.column('name',width=130)
tv.column('date',width=133)
tv.column('time',width=133)
tv.grid(row=2,column=0,padx=(0,0),pady=(150,0),columnspan=4)
tv.heading('#0',text ='ID')
tv.heading('name',text ='NAME')
tv.heading('date',text ='DATE')
tv.heading('time',text ='TIME')
###... | Python | 1 |
}
}
}
impl Clone for Stream {
fn clone(&self) -> Self {
Stream {
endpoint: self.endpoint.as_new(),
encoding: self.encoding.clone(),
suspend_sender: None,
}
}
}
/// A collection of streams that can be indexed by their EndpointId to their
/// endpoint and ... | Rust | 0 |
import re
from faker.utils.decorators import slugify_domain
from .. import Provider as InternetProvider
class Provider(InternetProvider):
free_email_domains = (
"hol.gr",
"gmail.com",
"hotmail.gr",
"yahoo.gr",
"googlemail.gr",
"otenet.gr",
"forthnet.gr",
... | Python | 1 |
x=sampled_dets,
nbinsx=50,
name='Sampled Points',
opacity=0.7,
marker_color='blue'
),
row=2, col=1
)
grid_dets_flat = grid_Z.flatten()
fig.add_trace(
go.Histogram(
x... | Python | 1 |
) -> tuple[int, list[tuple[VlobID, int]]] | VlobPollChangesAsUserBadOutcome:
try:
org = self._data.organizations[organization_id]
except KeyError:
return VlobPollChangesAsUserBadOutcome.ORGANIZATION_NOT_FOUND
if org.is_expired:
return VlobPollChangesAsUser... | Python | 1 |
, &bytes)?;
// ideally would pattern match (or just recurse) on the identifier here but we're
// only supporting elf
let elf = goblin::elf::Elf::parse(&bytes)?;
let mut bytes = Cursor::new(bytes);
return elf.analyze(&mut bytes, config);
... | Rust | 0 |
1.");
assert_eq!(vec![expected_transport1_address.clone()], urls);
transport2.process().unwrap();
let _ = t2_endpoint.process(&mut ());
assert_eq!(
transport2.bound_url(),
Some(expected_transport2_address.clone())
);
// After transport2 bind proc... | Rust | 0 |
");
}
}
}
Ok(())
}
}
use crate::errors::Context;
use crate::journal::Change;
use crate::journal::ChangeFilter;
use crate::journal::Journal;
use log::info;
use rand::Rng;
use std::collections::HashSet;
use std::fs;
use std::io;
use std::path::Path;
use std::path::PathBuf;
... | Rust | 0 |
.await
.context("adding routing table entry for weave tun")?;
// routing rules for wpan
let () = add_route_table_entry(
fidl_ip!("fdce:da10:7616:6::"),
fidl_ip!("ffff:ffff:ffff:ffff::"),
wpan_if_id,
&route_proxy,
)
.await
.context("adding routing table entry for ... | Rust | 0 |
0000:00:01.0"
"#;
let config: RuntimeConfig = toml::from_str(CONFIG)?;
assert_eq!(false, config.secondary);
assert_eq!(None, config.app_group);
assert_eq!(None, config.data_dir);
assert_eq!(None, config.dpdk_args);
assert_eq!(default_capacity(), config.mempool.c... | Rust | 0 |
0 .. 1;
let max_pages = ImportedMemory::max::<T>().max_pages;
let mut sbox = Sandbox::from(&WasmModule::<T>::from(ModuleDefinition {
memory: Some(ImportedMemory {
min_pages: 0,
max_pages,
}),
call_body: Some(body::repeated(r * max_pages, &[
Instruction::I32Const(1),
Instruction::GrowMemory... | Rust | 0 |
os.path.join(gt_dir, gt_pan_seq_name),
os.path.join(gt_dir, gt_dep_seq_name) if gt_dep_seq_name is not None else None,
dstq_obj,
seq_id
)
result = dstq_obj.result()
print(result)
if __name__ == '__main__':
args = parse_args()
result_... | Python | 1 |
,
events_list=context.decoded_events,
)
return EvmDecodingOutput(process_swaps=True)
def addresses_to_decoders(self) -> dict[ChecksumEvmAddress, tuple[Any, ...]]:
return {self.router_address: (self._decode_swapped,)}
@staticmethod
def counterparties() -> tuple[Counterpa... | Python | 1 |
the global context.
fn fetch_import<'cx>(
env: &mut ImportEnv<'cx>,
import_id: ImportId<'cx>,
) -> Result<ImportResultId<'cx>, Error> {
let cx = env.cx();
let import = &cx[import_id].import;
let span = cx[import_id].span.clone();
let location = cx[import_id].base_location.chain(import)?;
/... | Rust | 0 |
from time import sleep
from CodingDrone.drone import *
from CodingDrone.protocol import *
def eventMotion(motion):
print("eventMotion()")
print("- Accel: {0:5}, {1:5}, {2:5}".format(motion.accelX, motion.accelY, motion.accelZ))
print("- Gyro: {0:5}, {1:5}, {2:5}".format(motion.gyroRoll, motion.gyroPitch... | Python | 1 |
let mut my_size = 0;
if let Some(ref v) = self.namedObject.as_ref() {
let len = v.compute_size();
my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len;
}
if !self.mRID.is_empty() {
my_size += ::protobuf::rt::string_size(2, &self.mRID);
... | Rust | 0 |
print('Sw = ', sw)
return sw
def Awl(area):
awl = -1*area[2]
print('Awl = ', awl)
return awl
def Centros(pain):
Cx1, Cy1, Cz1 = pain[0]
Cx2, Cy2, Cz2 = pain[2]
Cx = (Cx1+Cx2)/2
Cy = (Cy1+Cy2)/2
Cz = (Cz1+Cz2)/2
centro = [Cx, Cy, Cz]
print('Coord do Centro do paine... | Python | 1 |
ng_variance#Two-pass_algorithm
pub fn variance<T: ToReal<R>, R: Real>(data: &[T]) -> R {
match data.len() {
1 => R::zero(),
n => {
let mu = data.iter().fold(R::zero(), |sum, x| sum + x.to_real()) / R::from_natural(n);
let (mut sum1, mut sum2) = (R::zero(), R::zero());
... | Rust | 0 |
def main():
# Create and print a list named fruit.
fruit_list = ["pear", "banana", "apple", "mango"]
print(f"original: {fruit_list}")
# Add code to reverse and print fruit_list.
fruit_list.reverse()
print(f"reversed: {fruit_list}")
# Add code to append "orange" to the end of fruit_list and p... | Python | 1 |
vote amount
assert_ok!(Call::Democracy(DemocracyCall::vote {
ref_index: index,
vote: Vote {
aye: true,
balance: 20_000_000,
}
})
.dispatch(origin_of(account_of(ALICE))));
assert!(
matches!(DemocracyPallet::r... | Rust | 0 |
from optparse import make_option
from django.core.management.base import NoArgsCommand
from ._utils import get_or_create_common_template
class Command(NoArgsCommand):
help = """Syncs file system templates and themes
with the database bidirectionally.
based on dbtemplates.sync_templates"... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.