text string | label_name string | labels int64 |
|---|---|---|
t processes this platform supports.
const NUM_PROCS: usize = 4;
// Actual memory for holding the active process structures.
static mut PROCESSES: [Option<&'static dyn kernel::process::Process>; NUM_PROCS] = [None; 4];
// Static reference to chip for panic dumps.
static mut CHIP: Option<&'static apollo3::chip::Apollo3... | Rust | 0 |
import subprocess
class PhoneDisplayHandler:
def __init__(self, speech_handler):
self.speech_handler = speech_handler
self.scrcpy_process = None
self.is_phone_displayed = False
async def display_phone(self):
if self.is_phone_displayed:
self.speech_handler.speak("You... | Python | 1 |
from contextlib import contextmanager
import json
import os
from typing import Any, Callable, Generator, Generic, Protocol, Type, TypeVar, overload
from enum import Enum
from dataclasses import is_dataclass
from src.util.log import LogLevel, log
from src.util.files import create_backup, read_from_file, write_to_file... | Python | 1 |
.
"type",
"state_key",
]
for k in immutable_fields:
if getattr(builder, k, None) != original_event.get(k):
raise Exception(
"Third party rules module created an invalid event: "
"cannot change field " + k
... | Python | 1 |
import datetime
from sqlalchemy import Integer, String, Float
from sqlalchemy.orm import Mapped, mapped_column, relationship, ForeignKey
from workout_api.generic.models import BaseModel
from workout_api.atleta.models import AtletaModel
class TrainingCenterModel(BaseModel):
__tablename__ = 'centros_treinamento'
... | Python | 1 |
new(s.as_str(), offset),
_ => LineBreakLeafIter::default()
};
LineBreakCursor {
inner: inner,
lb_iter: lb_iter,
last_byte: 0,
}
}
// position and whether break is hard; up to caller to stop calling after EOT
fn next(&mut self) -> (usiz... | Rust | 0 |
): Passengers.
seat ("economy" | "premium-economy" | "business" | "first"): Seat.
max_stops (int, optional): Maximum number of stops.
"""
trip_t = {
"round-trip": PB.Trip.ROUND_TRIP,
"one-way": PB.Trip.ONE_WAY,
"multi-city": PB.Trip.MULTI_CITY,... | Python | 1 |
assassin, virtual_target)
polygon.plot_hexagon_tiling(-5, n + 1, -5, n + 1)
for p, color in zip([assassin, target, virtual_target, final_position], "rgyc"):
plt.plot(
*p,
"o",
color=color,
markersize=5,
markeredgecolor="k",
label=(
... | Python | 1 |
ColorTarget::Stroke => self.stroke_color.to_rgba_components()
}
};
// Update the colour with Cairo
self.ctxt.set_source_rgba(r as f64, g as f64, b as f64, a as f64);
// Remember that this is the currently set colour
self.s... | Rust | 0 |
#[repr(align(16))]
pub struct CONTEXT {
pub P1Home: u64,
pub P2Home: u64,
pub P3Home: u64,
pub P4Home: u64,
pub P5Home: u64,
pub P6Home: u64,
pub ContextFlags: ::c_ulong,
pub MxCsr: ::c_ulong,
pub SegCs: ::c_ushort,
pub SegDs: ::c... | Rust | 0 |
, ui);
let button_size = 44.0;
let button_padding = 5.0;
// NOTE: This is very much a prototype. Please don't judge.
Button::new()
.w_h(button_size, button_size)
.mid_left_of(MASTER)
.rgb(0.4, 0.75, 0.6)
.label("Q")
.react(|| {
let mut n = input.clo... | Rust | 0 |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('get_video_info/', views.get_video_info, name='get_video_info'),
path('download_video/', views.download_video, name='download_video'),
path('get_progress/', views.get_progress, name='get_progress'... | Python | 1 |
1024, // 00: 4.096 KHz
1 => CPU_FREQ / 16, // 01: 262.144 Khz
2 => CPU_FREQ / 64, // 10: 65.536 KHz
3 => CPU_FREQ / 256, // 11: 16.384 KHz
_ => panic!("TODO"),
} as u16;
self.counter_lapsed += cycles as u16;
while... | Rust | 0 |
# app/api/endpoints/employees.py
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.db import repository, session
from app.schemas.employee import EmployeeCreate, EmployeeUpdate
from app.schemas.time_tracking import TimeTrackingCreate
from app.schemas.leave import LeaveCreate # Geändert... | Python | 1 |
ocDisabler = AllocDisabler;
#[derive(Clone, Debug)]
enum Field {
Unknown,
String,
Integer,
Float,
}
pub fn example_par_x(data: &PathBuf, capabilities: usize) -> Result<(), Box<dyn Error>> {
crossbeam::scope(|scope| {
let mut rdr = ReaderBuilder::new().quoting(false).from_path(data).unwrap(... | Rust | 0 |
import os
import logging
from binance_sdk_margin_trading.margin_trading import (
MarginTrading,
ConfigurationRestAPI,
MARGIN_TRADING_REST_API_PROD_URL,
)
from binance_sdk_margin_trading.rest_api.models import MarginAccountNewOcoSideEnum
# Configure logging
logging.basicConfig(level=logging.INFO)
# Creat... | Python | 1 |
from refined.utilities.numeric_handling.date_utils import Date
TEST_DATE_MENTIONS = {
# Just years
"2012": Date(year=2012),
"the start of 2012": Date(year=2012),
"the end of 2012": Date(year=2012),
"the year 1988": Date(year=1988),
"1945 to 1988": (Date(year=1945), Date(year=1988)),
# Ju... | Python | 1 |
"""
Copyright 2024 Samuel Davis
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
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
dist... | Python | 1 |
abel_set) = match emu.get_current_program() {
None => {
writeln!(stdout, "現在地点での変数の設定は行えません")?;
return Ok(());
}
Some((file, _, _)) => match emu.basic_info.get(file) {
Some((label, info)) => (file, label, &info.label_set),
... | Rust | 0 |
registers::addresses::DIV => memory.write(address, 0x00),
memory::registers::addresses::STAT => {
memory.write(address, data & !0b0000_0111);
}
_ => memory.write(address, data),
}
}
/// Read data at PC and increment PC by one.
#[inline]
pub fn... | Rust | 0 |
1 = f1
state = {
'model': model.state_dict(),
'best_acc1': best_acc,
'best_acc5': best_f1,
'epoch': epoch,
}
if not os.path.isdir('checkpoint'):
os.mkdir('checkpoint')
filename = "best_model"
... | Python | 1 |
new(Duration::from_secs(1));
// let display = Display10::new(fib);
// tokio::run(display);
// with combinators:
//
// tokio::run(
// fibonacci().take(10)
// .for_each(|num| {
// println!("{}", num);
// Ok(())
// })
// );
/... | Rust | 0 |
self.data["results"]["train_history"][state.global_step].update({
"loss": logs["loss"],
"lr": logs["learning_rate"],
"num_tokens": logs["num_tokens"],
"mean_token_accuracy": logs["mean_token_accuracy"]
})
... | Python | 1 |
parts.push(format!("<{}>", email));
}
}
parts.join(" ")
})
.collect(),
)
}
}
/// Transform fingerprints into GPGME keys.
///
/// Errors if a fingerprint does not match a public key.
fn fingerprints_to_... | Rust | 0 |
#coding:utf-8
import sys
sys.path.append('..')
from vg_node_port import NodeInput, NodeOutput
from vg_node import Node
from vg_dtypes import VGDtypes
from vg_env import register_node
from vg_config import NodeConfig
import math
NodeConfig.node_title_back_color['Num Action'] = '#66CDAA'
@register_node(name='+ (Int... | Python | 1 |
e', 1)
]),
test_count_letters_04: ("abcccd", vec![
('a', 1), ('b', 1), ('c', 3), ('d', 1)
]),
test_count_letters_05: ("aabcdd", vec![
('a', 2), ('b', 1), ('c', 1), ('d', 2)
]),
test_count_letters_06: ("abcdee", vec![
('a', 1), ('b', 1),... | Rust | 0 |
d_has_attentions
def test_sample_generate_dict_output(self):
# This model has a custom attention output shape AND config flags, let's skip those checks
old_has_attentions = self.has_attentions
self.has_attentions = False
super().test_sample_generate_dict_output()
self.has_at... | Python | 1 |
(|_| panic!("Error: could not coerce post-deployment script into valid utf-8"));
let exit_code = crate::post_deployment::run(&postd_script).exit_code();
println_with_time!("Finished executing post_deployment script. Now exiting with the script's exit code...");
std::proce... | Rust | 0 |
std::io::BufRead;
use std::io::BufReader;
use std::io::BufWriter;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::str::FromStr;
use anyhow::bail;
use anyhow::Context;
use anyhow::Result;
use clap::Arg;
use clap::Command;
#[derive(Debug)]
struct Node {
uid: usize,
cores: f32,
mem... | Rust | 0 |
l(x[2], _zero_aux_tensor):
# aux tensor isnot used, but will need grad in fuse net, so set a grad.
# backward base model will not use grad anymore, it is safe.
x[2].grad = _zero_aux_tensor
sum_embs = x[6]
sum_embs = torch.unsqueeze(sum_embs, dim=1)
eli... | Python | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
视频上传模块
功能:
1. 上传视频到YouTube
2. 自动生成视频标题、描述和标签
3. 设置视频缩略图
4. 批量上传管理
5. 上传进度监控
"""
import json
import logging
import os
import time
from pathlib import Path
from typing import Dict, List, Any, Optional
import google.auth
from google.auth.transport.requests import Reque... | Python | 1 |
Suffix 'b' is for blocking"
}
fn execute(&self, client: &mut ClientProxy, params: &[&str]) {
if params.len() < 3 {
println!("Invalid number of arguments for adding currency to account");
return;
}
println!(">> Adding zero balance in currency to account");
... | Rust | 0 |
(C)]
pub struct xcb_sync_alarm_iterator_t {
/// The value of the current iteration.
pub data: *mut xcb_sync_alarm_t,
/// The number of elements remaining including this one.
pub rem: c_int,
/// The offset of `data`, in bytes, from the start of the containing object.
pub index: c_int,
}
impl Def... | Rust | 0 |
fn(counter: *mut AtomicCounterO)>,
pub pin_thread_handle:
::std::option::Option<unsafe extern "C" fn(worker_thread_index: u32) -> u32>,
pub num_worker_threads: ::std::option::Option<unsafe extern "C" fn() -> u32>,
}
pub const TM_JSON_PARSE_EXT_ALLOW_UNQUOTED_KEYS: JsonParseExt = 1;
pub const TM_JSON_PA... | Rust | 0 |
(rest, (deku::ctx::Endian::Big, deku::ctx::Size::Bits(bits)))?;
Ok(op(rest, f32::from(value), modifier, modifier_op))
}
pub(crate) fn op(
rest: &BitSlice<Msb0, u8>,
value: f32,
modifier: f32,
modifier_op: Op,
) -> (&BitSlice<Msb0, u8>, f32) {
(rest, modifier_... | Rust | 0 |
e_quota_store()
return redirect("/dashboard")
def populate_quota_store():
allManagers = Employee.objects.filter(role=MGR).values_list('employeeID')
for manager in allManagers:
managerID = manager[0]
# Get number of employees under this manager
# based on the percentage calculate i... | Python | 1 |
]
#[doc(hidden)]
pub struct _CSPPROG_9;
#[doc = "`read()` method returns [cspprog_9::R](cspprog_9::R) reader structure"]
impl crate::Readable for CSPPROG_9 {}
#[doc = "`write(|w| ..)` method takes [cspprog_9::W](cspprog_9::W) writer structure"]
impl crate::Writable for CSPPROG_9 {}
#[doc = "CSP program"]
pub mod csppro... | Rust | 0 |
omeEnvironmentVar)?;
let home = volta_home()?;
debug!("Searching for profiles to update");
let env_profile = env::var("PROFILE");
let found_profile = PROFILES
.iter()
.chain(&env_profile.as_ref().map(String::as_str))
.fold(false, |prev, path| {
... | Rust | 0 |
from typing import List
class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
'''通过两个循环实现换位,matrix里面的数组逐个处理,能行,但效率低'''
n = len(matrix)
n2 = len(matrix[0])
rs = [[] for _ in range(n2)]
for i in range(0, n):
for j in range(0, n2):
... | Python | 1 |
iryTime=int.from_bytes(os.urandom(1024),'big')%P256.q
iv=Random.new().read(AES.block_size)
ECA_key=P256.G
def ECA_program():
Veh_socket = socket.socket() # get instance
host = '192.168.122.202'
port = 5000 # socket server port number
# look closely. The bind() function takes tuple as argument
Ve... | Python | 1 |
Elem {
pub name: String,
pub coef: u32,
pub pos: usize,
pub len: usize,
}
pub type Molecule = Vec<PerElem>;
/// Sorts the PerElems and groups those with the same name field.
///
/// Grouping of two (or more) PerElems means adding the coef field of the
/// duplicate to the one already found, and then t... | Rust | 0 |
]
formatted_response_text = "\n".join(formatted_response_data)
if (
total_tokens + num_tokens(formatted_response_text, self.token_encoder)
> self.max_data_tokens
):
break
data.append(formatted_response_text)
... | Python | 1 |
"""Keypoints primitive."""
# Copyright (C) 2025 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from typing import Union
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from .primitive import Primitive
class Keypoint(Primitive):
"""Keypoint primitive.
Args:
keypoints (np.nd... | Python | 1 |
is `:edb/cardinality :edb.cardinality/one`.
pub multival: bool,
/// `None` if this attribute is neither unique-value nor unique-causetIdity.
///
/// `Some(attribute::Unique::Value)` if this attribute is unique-value, i.e., it is `:edb/unique
/// :edb.unique/value`.
///
/// *Unique-value* m... | Rust | 0 |
t char_y_bounds:
paragraph.pdf_paragraph_composition = other_compositions
self.update_paragraph_data(paragraph)
return
para_y_min = min(b["y1"] for b in char_y_bounds)
para_y_max = max(b["y2"] for b in char_y_bounds)
# If the paragraph is vertically flat, tr... | Python | 1 |
all available SGD solvers.
/// [1]: ./enum.SGDKind.html
SGD(SGDKind),
}
impl SolverKind {
/// Create a Solver of the specified kind with the supplied SolverConfig.
pub fn with_config(&self, config: &SolverConfig) -> Box<ISolver> {
match *self {
SolverKind::SGD(sgd) => {
... | Rust | 0 |
_field_iid,
items,
}
}
_ => {
return Err(ParseDictionaryError::InvalidFormat);
}
};
let item = LayoutItemData { required, kind };
Ok(item)
}
fn import_category(
builder: &mut DictionaryBuilde... | Rust | 0 |
,
self.old_logp_a: batch['old_logp_actor'],
self.v_target: batch['v_target'],
self.adv: batch['adv'],
self.ep_reward: np.mean(reward_history[-10:]) if reward_history else 0.0,
})
self.wri... | Python | 1 |
mut voronoi_seeds : Vec<(usize, rltk::Point)> = Vec::new();
while voronoi_seeds.len() < self.n_seeds {
let vx = rng.roll_dice(1, build_data.map.width-1);
let vy = rng.roll_dice(1, build_data.map.height-1);
let vidx = build_data.map.xy_idx(vx, vy);
let candidate =... | Rust | 0 |
cess_id_word(self):
self.get_config.return_value = dedent(
"""\
router ospfv3 100
router-id 203.0.113.20
router ospfv3 TEST-1
router-id 198.51.100.1
""",
)
set_module_args(
dict(
config=dict(
... | Python | 1 |
ll() { [0u16; 2].bits_mut::<Lsb0>().store_be::<u16>(0); }
#[test]
#[should_panic]
fn bsl16_sb32_full() { [0u16; 3].bits_mut::<Lsb0>().store_be::<u32>(0); }
#[cfg(target_pointer_width = "64")]
#[test]
#[should_panic]
fn bsl16_sb64_full() { [0u16; 5].bits_mut::<Lsb0>().store_be::<u64>(0); }
#[test]
#[should_panic]
fn ... | Rust | 0 |
ChipDescMsg::ClearDesc);
GroupFldrMsgBus::dispatcher().send(GroupFldrAgentReq::UpdateFolder);
true
}
}
#[function_component(FolderTopRow)]
pub(crate) fn folder_top_row() -> Html {
html! {
<div class="chip-top-row">
<div class="chip-col-1 Chip nopadding">
{"#... | Rust | 0 |
Activities*
//! * creates [*Method Builders*](trait.MethodsBuilder.html) which in turn
//! allow access to individual [*Call Builders*](trait.CallBuilder.html)
//! * **[Resources](trait.Resource.html)**
//! * primary types that you can apply *Activities* to
//! * a collection of properties and *Parts*... | Rust | 0 |
from typing import List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.db.session import get_db
from app.models.player import Player
from app.schemas.player import PlayerCreate, PlayerUpdate, PlayerResponse
router = APIRouter()
@router.get("/", response_model=List[Pl... | Python | 1 |
from .. import IconBase
class IconCircleParkingOff(IconBase):
class_name = "lucide lucide-circle-parking-off"
svg_data = {
"attrs": {
"width": "24",
"height": "24",
"view_box": "0 0 24 24",
"fill": "none",
"stroke": "currentColor",
"stroke_width": "2",
... | Python | 1 |
- outcome: the outcome of the massage, one of 'success', 'exception' or 'timeout'.
- err_msg: error message if any, or None.
"""
queue = mp.Queue()
process = mp.Process(target=run_massage, args=(queue, task_id))
process.start()
process.join(timeout=timeout)
if process.is_alive():
... | Python | 1 |
# Ensure we have a QApplication
app = QApplication.instance()
if app is None:
app = QApplication(sys.argv)
logger.debug("Created new QApplication")
else:
logger.debug("Using existing QApplication")
# Create the window
window ... | Python | 1 |
let output = shell.edit("foo/bar");
assert_eq!(output, r#""$EDITOR" 'foo/bar'"#);
}
}
mod init {
use super::super::*;
use pretty_assertions::assert_eq;
#[test]
fn it_defaults() {
let shell = Bash {};
let output = shell.ini... | Rust | 0 |
rn contact
async def _insert(self, contact: Contact) -> Contact:
stmt = (
'''
INSERT INTO contact
(
company_id,
created_by_id,
user_id,
first_name,
surname,
patronymic,
... | Python | 1 |
to 10-tuple of `(u32, impl Strategy)` pairs where all
/// strategies ultimately produce the same value. Each `u32` indicates the
/// relative weight of its corresponding strategy.
/// You may use `W<S>` as an alias for `(u32, S)`.
///
/// Using this constructor directly is discouraged; prefer to us... | Rust | 0 |
ts.QFormLayout()
for label, widget in labels_and_widgets.values():
label_widget = QtWidgets.QLabel(label)
label_widget.setToolTip(widget.toolTip())
layout.addRow(label_widget, widget)
tab = QtWidgets.QWidget()
tab.setLayout(layout)
self._tabs.addTab(t... | Python | 1 |
import numpy as np
import pyloudnorm as pyln
import matplotlib.pyplot as plt
import traceback
from typing import Dict
from utility_functions import load_audio_stereo, extract_summary_statistics
def analyze_loudness(data: np.ndarray, sr: int = 44100, block_size: float = 0.4, plot_graph: bool = False) -> Dict:
if da... | Python | 1 |
ublic License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#![cfg_attr(not(feature = "std"), no_std)]
#![warn(missing_docs)]
//! This crate implements a simple binary Merkle Tree utilities required for inter-op with Ethereum
//! bridge & Solidity contract.
//!
//! The implementation is opt... | Rust | 0 |
def main():
name = input("what is your name? ")
hello(name)
def hello(to='world'):
print(f"Hello, {to}")
main() | Python | 1 |
"""
Pipeline validation CLI commands.
"""
import asyncio
import typer
from pipelex import log
from pipelex.pipe_works.pipe_dry import dry_run_all_pipes
from pipelex.pipelex import Pipelex
validation_app = typer.Typer(
name="validation",
help="Pipeline validation and setup commands",
add_completion=False,... | Python | 1 |
#!/usr/bin/env python3
"""Python Monograph: Remove Duplicates from a Sorted Array Solution 09
Copyright ©2024 Jerod Gawne <https://github.com/jerodg/>
This program is free software: you can redistribute it and/or modify
it under the terms of the Server Side Public License (SSPL) as
published by MongoDB, Inc., either ... | Python | 1 |
ansi::explain_ansi(&self.output, false)
} else {
ansi::strip_ansi_codes(&self.output)
}
}
}
pub fn run_delta(input: &str, config: &config::Config) -> String {
let mut writer: Vec<u8> = Vec::new();
delta(
ByteLines::new(BufReader::new(input.as_bytes())),
... | Rust | 0 |
re::header::{BlockNumber, Header, RawHeader, Seal};
use hash::blake2b;
use numext_fixed_hash::H256;
use serde_derive::Deserialize;
use std::any::Any;
use std::sync::Arc;
mod clicker;
mod cuckoo;
mod dummy;
pub use crate::clicker::Clicker;
pub use crate::cuckoo::{Cuckoo, CuckooEngine, CuckooParams};
pub use crate::dum... | Rust | 0 |
import os
from datetime import date, timedelta
import telebot
from celery import shared_task
from borrowing.models import Borrowing
bot = telebot.TeleBot(os.environ["TELEGRAM_BOT_TOKEN"])
CHAT_ID = os.environ["TELEGRAM_CHAT_ID"]
@shared_task
def notification_new_borrowing(borrowing_id):
"""
Send a notifica... | Python | 1 |
from pydantic import BaseSettings
from functools import lru_cache
class Settings(BaseSettings):
mongo_username: str
mongo_password: str
mongo_host: str
mongo_database: str
mongo_protocol: str
@property
def mongo_url(self):
return f"{self.mongo_protocol}://{self.mongo_username}:{s... | Python | 1 |
r"""
学习笔记
原始工程来源:
ShusenTang / Dive-into-DL-PyTorch
仓库地址:https://github.com/ShusenTang/Dive-into-DL-PyTorch
原始文献引用:
@book{zhang2019dive,
title={Dive into Deep Learning},
author={Aston Zhang and Zachary C. Lipton and Mu Li and Alexander J. Smola},
note={\url{http://www.d2l.ai}},
... | Python | 1 |
foo<T:fmt::Debug>(x: T) {
println!("{:?}", x);
}
use std::{
fs,
io::{self, prelude::*},
os::unix::io::RawFd,
path::PathBuf,
};
use crate::utils::consts::{MOSAIC_TMP_LOG_DIR, MOSAIC_TMP_LOG_FILE};
pub fn debug_log_to_file(message: String) -> io::Result<()> {
let mut file = fs::OpenOptions::new... | Rust | 0 |
within_area = within_x_range & within_z_range
case "+z" | "-z":
x_range = self.half_size[0] * (1 + within_area_margin)
y_range = self.half_size[1] * (1 + within_area_margin)
within_x_range = np.abs(points[:, 0]) <= x_range
... | Python | 1 |
from diet_module.service.abstract_service import AbstractDietService
from diet_module.repository.abstract_diet_repository import AbstractDietRepository
class DietService(AbstractDietService):
"""
Concrete implementation of the AbstractDietService that provides diet-related functionalities.
"""
def __... | Python | 1 |
lf.finish_home_complete
def wait_for_trigger(self, eventtime):
self.finish_home_complete.wait()
if self.multi == 'OFF':
self.raise_probe()
def probe_finish(self, hmove):
self.wait_trigger_complete.wait()
if self.multi == 'OFF':
self.verify_raise_probe()
... | Python | 1 |
4 => ( f(s+0) + f(s+1)) + (f(s+2) + f(s+3)),
5 => ( f(s+0) + f(s+1)) + (f(s+2) + f(s+3)) + f(s+4),
6 => ( f(s+0) + f(s+1)) + (f(s+2) + f(s+3)) + (f(s+4) + f(s+5)),
7 => (( f(s+0) + f(s+1)) + (f(s+2) + f(s+3))) + (f(s+4) ... | Rust | 0 |
>,
payload: JoinTeamRequest,
) -> anyhow::Result<()> {
self.tm.transaction(|td| {
let mut user = user_guard.user;
self.assert_user_can_join_team(&user)?;
let mut team_to_join = self.team_repo.find_by_join_code(&payload.join_code, &td)?;
user.team_id =... | Rust | 0 |
akes_value(false))
.arg(Arg::with_name("delete_system_cache")
.long("delete_system")
.help("Delete System cache, <Must be root>")
.takes_value(false))
.arg(Arg::with_name("delete_user_cache")
.long("delete_user")
.help("Delete user cache, If not running as root it ... | Rust | 0 |
from asyncio import sleep
async def repeat_until_success_async(func, *args, **kwargs):
err_counter = 0
while True:
try:
return await func(*args, **kwargs)
except Exception as e:
err_counter += 1
if err_counter > 5:
raise e
await sl... | Python | 1 |
watom.position = position
if velocities is not None:
velolist = np.array([v.value_in_unit(stku.nanometer/stku.femtosecond) for v in velocities]) * u.nm/u.fs
velolist = u.default.convert(velolist)
for newatom, velocity in zip(newatoms, velolist):
newatom.momentum = newatom.mass * ... | Python | 1 |
add_argument('-i', '--in-place', action='store_true',
help='Modify files in-place (creates .bak backups)')
parser.add_argument('--pattern', default='*.md',
help='File pattern to match (default: *.md)')
parser.add_argument('--contact', default='contact@example.com',
... | Python | 1 |
"""
=========================================================
K-means Clustering
=========================================================
The plot shows:
- top left: What a K-means algorithm would yield using 8 clusters.
- top right: What using three clusters would deliver.
- bottom left: What the effect of a bad ... | Python | 1 |
}
impl<T> core::ops::DerefMut for Mutex<T> {
fn deref_mut(&mut self) -> &mut spin::Mutex<T> {
&mut self.0
}
}
}
#[cfg(feature = "std")]
pub mod sync {
pub use std::sync::Arc;
pub use std::sync::{Mutex, RwLock};
}
/// std::task
#[cfg(feature = "std")]
pub use std::task;
... | Rust | 0 |
n unrealistic favourability towards
/// good luck typically.
///
/// When constrained in this way, this distribution is fairly accurate.
/// For this reason, I suggest that you feed in modified data rather than the exact run data from dream's streams.
/// I.E. I took all runs that made it beyond 10 ... | Rust | 0 |
<()>>();
}
}
<filename>examples/30_tcp_sofh/src/main.rs
use fesofh::SeqDecoder;
use std::io;
use std::net;
fn main() -> io::Result<()> {
let listener = net::TcpListener::bind("127.0.0.1:8080")?;
let reader = listener.accept()?.0;
let decoder = SeqDecoder::default();
let mut frames = decoder.read_fr... | Rust | 0 |
],
'layout': {
'title': 'Сравнение скорости ветра (км/ч)',
'yaxis': {'title': 'Скорость ветра (км/ч)'}
}
}
)
graphs.append(wind_graph)
# Г... | Python | 1 |
ase-Aware Speech Enhancement",
Yanxin Hu et al. https://arxiv.org/abs/2008.00264
"""
def __init__(
self, in_size, hid_size=128, rnn_type="LSTM", n_layers=2, norm_type=None, **rnn_kwargs
):
super().__init__()
self.rnn = complex_nn.ComplexSingleRNN(
rnn_type, in_s... | Python | 1 |
grade(&base),
})),
m_joint1: None,
}));
{
let mut self_ = result_ptr.borrow_mut();
{
let world = base.borrow().m_world.clone();
let mut world = world.borrow_mut();
world.set_destruction_listener(self_.destruction_listener.clone());
world.set_contact_listener(self_.contact_listener.clone... | Rust | 0 |
!(!s2.same_channel(&s3));
// assert!(!r.same_channel(&r3));
// assert!(!r2.same_channel(&r3));
// }
// #[test]
// fn different_flavors_same_channel() {
// let (s1, r1) = bounded::<usize>(0);
// let (s2, r2) = unbounded::<usize>();
// assert!(!s1.same_channel(&s2));
// assert!(!r1.same_channel(... | Rust | 0 |
>::new(
canvas_element.client_width(),
canvas_element.client_height(),
)
.max(&Size::default())
.cast::<u32>();
canvas_element.set_width(size.width);
canvas_element.set_height(size.height);
let size = size.cast::<f32... | Rust | 0 |
import datetime
from datetime import timezone
from glob import glob
import os
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--data_dir", default="adfa_verazuo", help="path to input files", type=str, choices=['adfa_verazuo'])
parser.add_argument("--sep_csv", default=";", help="separator for v... | Python | 1 |
BitcoinAddress {
pub private_key: PrivateKey,
pub public_key: PublicKey,
pub address: Address,
}
impl BitcoinAddress {
pub fn new(secp: &Secp256k1<impl Signing>, is_compressed: bool, is_bech32: bool) -> Self {
let random_bytes = get_random_bytes();
let secret_key =
SecretKe... | Rust | 0 |
ing requests and notifications.
pub request_channel_capacity: usize,
/// Backend channel for each unique subscription.
pub subscription_channel_capacity: usize,
/// Max request body size
pub max_request_body_size: usize,
/// Request timeout
pub request_timeout: Option<Duration>,
}
impl Default for WsConfig {
f... | Rust | 0 |
_bit_at(8, 3), true);
assert_eq!(get_bit_at(8, 0), false);
assert_eq!(get_bit_at(-1, 0), true);
}
}
#[cfg(test)]
mod test_bin_to_dec {
use steganography::bin_to_dec;
#[test]
fn test_bin_to_dec(){
assert_eq!(bin_to_dec(&[1,0,1]), 5);
assert_eq!(bin_to_dec(&[0,0,0]), 0);
... | Rust | 0 |
reamFixingDateBusinessDayConvention {
fn default() -> Self {
LegPaymentStreamFixingDateBusinessDayConvention::NotApplicable
}
}
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)]
pub enum LegPaymentStreamFixingDateOffsetUnit {
/// Day
#[serde(rename = "D")]
Day,
/// Week
#[serde(rename = "Wk")]
... | Rust | 0 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 1. simple plot with 4 numbers
plt.plot([1, 3, 2, 4])
plt.show()
# 2. points have x and y values; add title and axis labels
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.title('Test Plot', fontsize=8, color='g')
plt.xlabel('number n')
plt.ylabel('n^2... | Python | 1 |
min(carviz.maxEnergy, (carviz.energy + energy_share))
strongest_erbast.decrease_energy(100)
# if the erbast manages to survive he loses half his energy
else:
strongest_erbast.energy = strongest_erbast.energy // 2
def pride_cell_choice(cells_list, cella):
cell_list = []
... | Python | 1 |
from tesseract_env import Tess_Env
import numpy as np
def main():
#link and joint names in urdf
MA2010_link_names=["MA2010_base_link","MA2010_link_1_s","MA2010_link_2_l","MA2010_link_3_u","MA2010_link_4_r","MA2010_link_5_b","MA2010_link_6_t","MA2010_tool0"]
MA2010_joint_names=["MA2010_joint_1_s","MA2010_joint_2_l",... | Python | 1 |
lt<bool, SubmitError> {
Ok(true)
}
async fn validate_forced_exit(
&self,
_storage: &mut StorageProcessor<'_>,
_target_account_address: Address,
) -> Result<(), SubmitError> {
Ok(())
}
}
<filename>src/sql/query.rs
use std::collections::HashSet;
/// Data for `sele... | Rust | 0 |
crate_app || remove_crate_registry)
{
registry_crates_location.remove_crate(value);
size_cleaned += crate_detail.find_size_registry_all(value);
}
if list_crate.installed_git().contains(&value.to_string())
&& (remove_crate_app || remove_crate_git)
{
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.