text string | label_name string | labels int64 |
|---|---|---|
Vec2::new(sx as f32, sy as f32)
}
}
pub trait CameraDraw
where
Self: graphics::Drawable,
{
fn draw_ex_camera(
&self,
camera: &Camera,
ctx: &mut ggez::Context,
p: ggez::graphics::DrawParam,
) -> GameResult<()> {
let dest = camera.calculate_dest_point(MintPo... | Rust | 0 |
import tkinter as tk
def tela_sobre():
root = tk.Toplevel()
root.title("Sobre")
root.geometry("400x300")
tk.Label(root, text="Sobre o Sistema", font=("Arial", 16)).pack(pady=20)
tk.Label(root, text="Sistema de gerenciamento para loja de roupas.").pack(pady=10)
tk.Label(root, text="Desenvolvedo... | Python | 1 |
// let ct = 1. as Float / (1. as Float + tan2_theta).sqrt();
// let st = (1. as Float - ct*ct).max(0. as Float).sqrt();
// let wh = Vector3f::new(st*phi.cos(), st*phi.sin(), ct);
// if wo.dot(wh) <= 0. as Float {
// -wh
// } else {
// wh
// }
let wo_stretched = Vector3f::new(... | Rust | 0 |
match iter {
Iteration::Inside { .. } => Color::new(0.0, 0.0, 0.0),
Iteration::Outside { .. } => Color::new(1.0, 1.0, 1.0),
}
}
}
#[derive(Debug, PartialEq)]
pub struct Gray {}
impl ColorScheme for Gray {
fn color(&self, iter: Iteration) -> Color {
match iter {
... | Rust | 0 |
let c = InPlaceOperations::create_instance(py, Cell::new(12)).unwrap();
py_run!(py, c, "d = c; c ^= 5; assert repr(c) == repr(d) == 'IPO(9)'");
}
py_class!(class ContextManager |py| {
data exit_called : Cell<bool>;
def __enter__(&self) -> PyResult<i32> {
Ok(42)
}
def __exit__(&self, ty: O... | Rust | 0 |
morse_code_dict = {
'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.',
'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---',
'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---',
'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-',
'U': '..-', 'V': '...-', 'W': '.--',... | Python | 1 |
//! Mbed Crypto provider
//!
//! This provider is a software based implementation of PSA Crypto, Mbed Crypto.
use super::Provide;
use crate::authenticators::ApplicationName;
use crate::key_info_managers::{self, KeyTriple, ManageKeyInfo};
use derivative::Derivative;
use log::{error, trace};
use parsec_interface::operati... | Rust | 0 |
the clock was changed to given frequency
pub fn emmc_set_clock2(&self, freq: u32) -> SdResult {
// A divisor of zero doesnt work. I think a divisor of 1 equates to half the base clock rate.
// TODO: need to find confirmation of the above.
assert!(freq < BASE_CLOCK as u32);
let mut... | Rust | 0 |
enum PunctKind {
/// `;`
Semicolon,
/// `,`
Comma,
/// `.`
Dot,
/// `@`
At,
/// `~`
Tilde,
/// `?`
Question,
/// `:`
Colon,
/// `$`
Dollar,
/// `=`
Eq,
/// `!`
Not,
/// `<`
Lt,
/// `>`
Gt,
/// `-`
Minus,
/// `&`... | Rust | 0 |
id: Option<i32>,
record_id: Option<i32>,
only_starred: bool,
limit: i64,
offset: i64,
) -> Result<Vec<RecordWithMeta>> {
let mut query = SqlBuilder::select_from("records as r");
query
.fields(&[
"r.id",
"r.title",
"r.source_record_id as guid",
... | Rust | 0 |
#[test]
fn test_run_script() {
let items = vec![
"tests/test_script_for_run.yaml",
"tests/test_script_for_run_silent.yaml",
"tests/test_script_for_run_interactive.yaml",
];
for item in items {
let script = Script::new(PathBuf::from(item));... | Rust | 0 |
::MAX, blue: 0x5a };
#[allow(dead_code)]
const ORANGE: Intensities = Intensities { red: u8::MAX, green: 0x7e, blue: 0 };
#[allow(dead_code)]
const WHITE: Intensities = Intensities { red: u8::MAX, green: u8::MAX, blue: u8::MAX };
impl<BUTTONS, RGB> trussed::platform::UserInterface for UserInterface<BUTTONS,RGB>
where
B... | Rust | 0 |
ack.format_exc()}")
return result
def main():
"""Main function to test YouTube transcript."""
# Test URLs - gunakan URL dari error log Anda
test_urls = [
"https://www.youtube.com/watch?v=Y681hXWwhQY", # URL dari error log
"https://www.youtube.com/watch?v=dQw4w9WgXcQ", # Rick... | Python | 1 |
import requests
# Consultando a un servidor RESTful
url = "http://localhost:8000/"
### Inciso a
# # GET para mostrar todas las carreras
ruta_get_carreras = url + "/carreras/"
get_response_carreras = requests.request(method="GET", url=ruta_get_carreras)
print(get_response_carreras.text)
### Inciso b
# # GET para mo... | Python | 1 |
allObjects {
id
}
}
"""
assert graphql_sync(schema, source) == (
{
"allObjects": [
{"id": "VXNlcjox"},
{"id": "VXNlcjoy"},
{"id": "UGhvdG86MQ=="},
{"id": "UGhvdG86... | Python | 1 |
from pymilvus import connections, FieldSchema, CollectionSchema, DataType, Collection
import random
# 1. Connect to Milvus
connections.connect("default", host="localhost", port="19530")
print("Connected to Milvus")
# 2. Define collection schema
fields = [
FieldSchema(name="id", dtype=DataType.INT64, is_primary=Tr... | Python | 1 |
pchainKHR,
///
/// 存储句柄
///
pub(crate) swap_chain_images: Vec<Image>,
///
/// 交换链格式化类型
///
pub(crate) swap_chain_image_format: Format,
///
/// 交换链大小
///
pub(crate) swap_chain_extent: Extent2D,
}
unsafe extern "system" fn debug_callback(
message_... | Rust | 0 |
) {
// `aes-128-ctr` is the name used in Ethereum keystores. A more appropriate name
// would be something like `aes-128-ctr/keccak256`, but the shorter one is used here
// for compatibility.
eraser
.add_cipher::<Self::Cipher>("aes-128-ctr")
.add_cipher::<Aes128Gc... | Rust | 0 |
etrics = {
"knn-t2.01@1": (1.0 + 0.0 + 1.0) / 3.0,
"knn-t2.01@1_cat": (1.0 + 1.0) / 2,
"knn-t2.01@1_dog": 0.0,
"knn-t2.01@1_avg_category": 0.5,
"knn-t2.01@2": (1.0 + 0.0 + 1.0) / 3.0,
"knn-t2.01@2_cat": (1.0 + 1.0) / 2,
"knn-t2.01@2_dog... | Python | 1 |
pe == object
with pytest.raises(TypeError) as excinfo:
m.f_simple_vectorized(s_array_object)
assert "incompatible function arguments" in str(excinfo.value)
# Explicitly convert to `np.array(..., dtype=simple_dtype)`
s_array = np.array([s.astuple()], dtype=simple_dtype)
np.testing.assert_arra... | Python | 1 |
posicionA = "X"
posicionB = ""
posicionC = ""
posicionD = ""
posicionE = "X"
posicionF = ""
posicionG = ""
posicionH = ""
posicionI = "X"
print("")
print("\t\t|\t\t |\t")
print("\tX\t|")
print("\t\t|\t\t |\t")
print("----------------------------------------------------")
print("\t\t|\t\t |\t")
print("\t\t|\tX\t |\t")
p... | Python | 1 |
g.
Args:
modules (torch.nn.Module): The modules for which the `BatchNorm` layer running statistics should be enabled.
Returns:
None
"""
if self.fts_handle.frozen_bn_track_running_stats:
rank_zero_debug("Since `frozen_bn_track_running_stats` is current... | Python | 1 |
_jl_usage(),
)
}
#[inline(never)]
fn get_matrix_usage(&self) -> usize {
self.levels.iter().fold(0, |acc, x| {
acc + x.reach.iter().fold(
std::mem::size_of::<Level>() - std::mem::size_of::<Vec<usize>>(),
|acc2, (_, y)| acc2 + y.get_memory_usage(),
... | Rust | 0 |
import pandas as pd
import gradio as gr
import joblib
import pickle
from sklearn.preprocessing import LabelEncoder
label_encoder = LabelEncoder()
loaded_model = joblib.load('decision_tree_model.joblib')
# try:
# with open('decision_tree_model.joblib', 'rb') as f:
# loaded_model = pickle.load(f)
# except Ex... | Python | 1 |
from lib.app import database
from databases.school_address_db import get_id_by_school_address
def create_new_student(
id_student: str,
name: str,
surname: str,
username: str,
age: int,
school_class: int,
school_address: str,
):
school_address_id = get_id_by_school_address(school_addres... | Python | 1 |
str = r#"
SELECT * FROM card
"#;
pub const FETCH_CARD_BY_ID_STMT: &str = r#"
SELECT * FROM card WHERE id = ?
"#;
pub const FETCH_CARD_BACK_FACE_BY_ID_STMT: &str = r#"
SELECT * FROM card_back_face WHERE id = ?
"#;
pub const FETCH_CARD_LEGALITIES_STMT: &str = r#"
SELECT format.name, legality.status
... | Rust | 0 |
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Test whether spec decoding handles the max model length properly."""
import pytest
from tests.utils import get_attn_backend_list_based_on_platform
from vllm import LLM, SamplingParams
from vllm.platforms impo... | Python | 1 |
ome(dir) = current_dir {
let manifest_path = dir.join(MANIFEST_FILENAME);
if manifest_path.exists() {
return Some(manifest_path);
}
current_dir = dir.parent();
}
None
}
/// Extract build options from the command line
fn extract_build_options(matches: &ArgMatches) -> ... | Rust | 0 |
Exponential {
attempts: u32,
max_attempts: u32,
min: u32,
max: u32,
mult: u32
}
}
impl ReconnectPolicy {
/// Reset the number of reconnection attempts. It's unlikely users will need to call this.
pub fn reset_attempts(&mut self) {
match *self {
ReconnectPolicy::Constant { ref mu... | Rust | 0 |
thus forbidden - inside unicode strings (should it be 1 byte? 1 code unit? 2 hex values? 4 hex values?)", s))?
} else if !byte && v > 0x7F {
Err(compile_error("this form of character escape may only be used with characters in the range [\\x00-\\x7f]", s))?
... | Rust | 0 |
}
#[doc = "Bloc is reset."]
#[inline(always)]
pub fn asserted(self) -> &'a mut W {
self.variant(MRT_RST_A::ASSERTED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inl... | Rust | 0 |
let wpk = handle_errors!(wpk_result);
// // Deserialize the merch close
// //let revoke_token: secp256k1::Signature = deserialize_object(ser_revoke_token);
// let merch_close_result: ResultSerdeType<zkproofs::ChannelcloseM> =
// deserialize_result_object(ser_merch_close);
// ... | Rust | 0 |
word: ~str, get: map_reduce::getter<int>) {
let mut count = 0;
loop { match get() { Some(_) => { count += 1; } None => { break; } } }
io::println(fmt!("%s\t%?", word, count));
}
struct box<T> {
mut contents: Option<T>,
fn swap(f: fn(+T) -> T) {
let mut tmp = None;
self.conten... | Rust | 0 |
# Copyright HeteroCL authors. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import heterocl as hcl
import numpy as np
def top_atax(M=38, N=42, dtype=hcl.Int(), target=None):
hcl.init(dtype)
A = hcl.placeholder((M, N), "A")
x = hcl.placeholder((N,), "x")
y = hcl.placeholder((N,), "y")
... | Python | 1 |
perate line.
#[test]
fn wrap_word_chinese() {
let glyphs = Layout::default().calculate_glyphs(
&*FONT_MAP,
&SectionGeometry {
bounds: (25.0, f32::INFINITY),
..<_>::default()
},
&[SectionText {
text: "提高代碼執行率"... | Rust | 0 |
, 12, 16, 16, 16)
guidance_r = self.guide_r(x[:, 0:1, :, :])
guidance_g = self.guide_g(x[:, 1:2, :, :])
guidance_b = self.guide_b(x[:, 2:3, :, :])
slice_coeffs_r = self.slice(coeff, guidance_r)
slice_coeffs_g = self.slice(coeff, guidance_g)
slice... | Python | 1 |
,
#[serde(rename = "DW1000c")]
Dw1000c,
#[serde(rename = "DW1500")]
Dw1500,
#[serde(rename = "DW1500c")]
Dw1500c,
#[serde(rename = "DW2000")]
Dw2000,
#[serde(rename = "DW2000c")]
Dw2000c,
#[serde(rename = "DW3000")]
Dw3000,
... | Rust | 0 |
#!/usr/bin/python
#
# knn_static.py
# Visualize the KNN classification result with static data
#
# Author : sosorry
# Date : 2017/01/12
# Origin : http://docs.opencv.org/2.4/modules/ml/doc/k_nearest_neighbors.html
# Usage : python knn_static.py
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Featur... | Python | 1 |
::unix::io::FromRawFd;
use std::os::unix::io::IntoRawFd;
use std::os::unix::io::RawFd;
use nix::errno::Errno;
use crate::event::buffer::EventBuffer;
use crate::event::events::Events;
use crate::fd::FD;
use crate::init;
use crate::init::Flags;
use crate::init::Init;
use crate::init::NotificationClass::Notify;
use crat... | Rust | 0 |
TokenType::End => {
reader.unexpected_end = true;
return Err(Error::new("Unexpected end of file.".to_string(), arg_info))
},
_ => return Err(Error::new("Unexpected token.".to_string(), arg_info)),
}
let comm... | Rust | 0 |
{
/// This method is expected to return the path of the API endpoint.
fn path(&self) -> Result<String, QueryError>;
/// This associated method is expected to return the result that was parsed from the JSON
/// response, or an error.
fn parse(string: &str) -> Result<T, QueryError>;
/// This as... | Rust | 0 |
("Must return error"),
Err(StdError::GenericErr { msg, .. }) => assert_eq!(msg, "Description too long"),
Err(_) => panic!("Unknown error"),
}
}
#[test]
fn fails_create_poll_invalid_link() {
let mut deps = mock_dependencies(20, &[]);
mock_init(&mut deps);
let msg = create_poll_msg(
... | Rust | 0 |
{
/// Handle to a spawned process, used to communicate with it
=0: CLASS_CORE_PROTOPROCESS = {
/// Give the process one of this process's objects
/// This method blocks if the child process hasn't popped the previous object
=0: CORE_PROTOPROCESS_SENDOBJ,
--
/// Start the process executing
=0: CORE_PROTOP... | Rust | 0 |
and early-returning with an error is very typical.
//! Unfortunately, the [`?`] operator doesn’t help us here because we want to early-return on a
//! boolean value, not an error value.
//!
//! A not very idiomatic and weird way to rewrite that:
//!
//! ```rust
//! fn foo(cond: bool) -> Option<i32> {
//! if cond { S... | Rust | 0 |
.
///
/// [See Heroku documentation for more information about this endpoint](https://devcenter.heroku.com/articles/platform-api-reference#space-network-address-translation-info)
///
/// # Example:
///
/// SpaceNATDetails takes one required parameter, space_id, and returns the [`SpaceNAT`][response].
/// ```rust
/// u... | Rust | 0 |
result = {
"status": "success",
"message": f"Campaign {campaign_id} has been deleted successfully",
"campaign_id": campaign_id,
"action": "deleted",
"warning": "This action is permanent. Campaign content and statistics have been removed."
}
... | Python | 1 |
{
*unique_ancestor_chain_found.borrow_mut() = true;
Ok(vec![])
} else {
Ok(r#box.input_quantifiers().map(|q| q.input_box).collect())
}
}
},
&mut |_, _| {
if !*unique_ancestor_chain_found.... | Rust | 0 |
# Time: O(k * n^2)
# Space: O(n^2)
class Solution(object):
def palindromePartition(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
# dp1[i][j]: minimum number of changes to make s[i, j] palindrome
dp1 = [[0]*len(s) for _ in xrange(len(s))]
... | Python | 1 |
x47\x4d\x7d\x17\x68\xa1\x11\x5d\x4c\x71\xc9\x41\x28\xc7\xb6\xa2\x4b\x97\xec\xc0\xaf\xfc\x2f\x3b\xbf\xe9\xf1\xb1\xfc\xf5\x01\xff\xa9\xfb\x49\x40\x0c\x63\x24\x98\xd7\x79\x2e\xa6\x55\xab\x16\xc6\xbe\x51\xd8\x71",
id: [ 0x51, 0xa3, 0xb0, 0xf5, 0xfd, 0x01, 0x79, 0x9c, 0x56, 0x6d, 0xb8, 0x37, 0x78, 0x8f, 0x0c, 0xa4, ... | Rust | 0 |
}
fn main() {
// This provides better error messages in debug mode.
// It's disabled in release mode so it doesn't bloat up the file size.
#[cfg(all(debug_assertions, target_arch = "wasm32"))]
console_error_panic_hook::set_once();
let el = EventLoop::new();
#[cfg(not(target_arch = "wasm32"))]... | Rust | 0 |
# SNMP MIB module (NORTEL-OPTICAL-GENERIC-MIB) expressed in pysnmp data model.
#
# This Python module is designed to be imported and executed by the
# pysnmp library.
#
# See https://www.pysnmp.com/pysnmp for further information.
#
# Notes
# -----
# ASN.1 source file://mibs\nortel\NORTEL-OPTICAL-GENERIC-MIB
# Produced ... | Python | 1 |
self.setupstat = None;
}
let dqh = self.get_dqh(ep_addr).ok_or(UsbError::InvalidEndpoint)?;
let ep_mask = util::epaddr2endptmask(ep_addr);
if let Some(setupstat) = setupstat {
// SETUP packets need special handling because no dTD is used
// see section 54.4.6.4.2... | Rust | 0 |
# -*- coding: utf-8 -*-
#############################################################################
#
# Cybrosys Technologies Pvt. Ltd.
#
# Copyright (C) 2019-TODAY Cybrosys Technologies(<https://www.cybrosys.com>)
# Author: Cybrosys Techno Solutions(<https://www.cybrosys.com>)
#
# You can modify it under... | Python | 1 |
/dzjy/dzjy_hygtj.html
:param symbol: choice of {'近一月', '近三月', '近六月', '近一年'}
:type symbol: str
:return: 活跃 A 股统计
:rtype: pandas.DataFrame
"""
period_map = {
"近一月": "1",
"近三月": "3",
"近六月": "6",
"近一年": "12",
}
url = "https://datacenter-web.eastmoney.com/api/d... | Python | 1 |
import os
import time
import json
import lzma
import httpx
from services.cache.loaders.loader import ensure_cache_directory, is_cache_valid
from terminal.cli import print_greyed_out
def load_nist_data(config):
cache_dir = config.get("cache_dir")
cache_file_compressed = os.path.join(cache_dir, 'CVE-all.json.xz... | Python | 1 |
mut u32, v: u32x4, l: usize);
#[link_name = "llvm.wasm.store64.lane"]
fn llvm_store64_lane(x: *mut u64, v: u64x2, l: usize);
#[link_name = "llvm.wasm.swizzle"]
fn llvm_swizzle(a: i8x16, b: i8x16) -> i8x16;
#[link_name = "llvm.wasm.eq"]
fn llvm_eq(a: i64x2, b: i64x2) -> i64x2;
#[link_name =... | Rust | 0 |
import os
from datetime import timedelta
from celery import Celery
REDIS_URL = os.getenv("CELERY_BROKER_URL", "redis://redis:6379/0")
celery_app = Celery(
"worker",
backend=REDIS_URL,
broker=REDIS_URL,
include=['app.tasks'],
)
celery_app.conf.update(
task_serializer='json',
accept_content=[... | Python | 1 |
= [
"<div>User Weekly Trend HTML</div>",
"<div>Final HTML with warning</div>",
]
with patch(
"insight.admin.user_weekly_trend_admin.from_dict"
) as mock_from_dict:
mock_insight = MagicMock()
mock_insight.... | Python | 1 |
nv,
parent: __wasi_cid_t,
keep_alive: __wasi_bool_t,
topic: WasmPtr<u8, M>,
topic_len: M::Offset,
format: __wasi_busdataformat_t,
buf: WasmPtr<u8, M>,
buf_len: M::Offset,
ret_cid: WasmPtr<__wasi_cid_t, M>,
) -> __bus_errno_t {
let bus = env.runtime.bus();
let memory = env.memory(... | Rust | 0 |
() {
let output = command_output("cargo", &["version"]).expect("must execute");
assert!(output.status.success());
let stderr = str::from_utf8(&output.stderr).unwrap();
assert!(stderr.is_empty());
let stdout = str::from_utf8(&output.stdout).unwrap();
assert_eq!(&stdout[0... | Rust | 0 |
601b4392a5_";
let expected = vec![
Entry::Dir("Q<KEY>D".into()),
Entry::Dir("QmdKuCuXDuVTsnG<KEY>LZhGHHHwWPQH28DeD/some".into()),
Entry::Dir("Q<KEY>8DeD/some/nested".into()),
Entry::Dir("QmdKuCuXDuVTsnG<KEY>LZhGHHHwWPQH28DeD/some/nested/dir".into()),
... | Rust | 0 |
import tkinter as tk
def paint(event):
"""Draw on the canvas."""
x1, y1 = (event.x - 1), (event.y - 1)
x2, y2 = (event.x + 1), (event.y + 1)
canvas.create_oval(x1, y1, x2, y2, fill="black", width=3)
def create_drawing_app():
"""Create a simple drawing app GUI."""
root = tk.Tk()
root.title(... | Python | 1 |
else:
x = blk(x, x_rpe)
if i in self.out_indices:
xp = self.norm(x[:, 1:, :]).permute(0, 2, 1).reshape(B, -1, Hp, Wp)
features.append(xp.contiguous())
time_backbone = time.time()
if self.with_fpn:
ops = [self.fpn1, s... | Python | 1 |
f03, 0xaf01, 0xffff, 0xffff]
);
assert_eq!(storage.write(StorageSlot::Custom(2), 10).is_ok(), true);
assert_eq!(
page2_slice,
[0x0fff, 0xffff, 0x5f0f, 0x3f04, 0x2f03, 0xaf01, 0x2f0a, 0xffff]
);
}
#[test]
fn successfully_rolls_over_to_first_page() {
... | Rust | 0 |
self.espooler_values.delta_movement = self.function.gcode_get_value(gcmd, "get_float", self.espooler_values.delta_movement,
"DELTA_MOVEMENT", self.lane_obj.fullname)
self.espooler_values.scaling = sel... | Python | 1 |
None
assert len(trainers) == 1 # one per model
trainer = trainers[0]
assert isinstance(trainer.logger.destinations, tuple)
assert len(trainer.logger.destinations) > 0
inmemorylogger = trainer.logger.destinations[
0] # pyright: ignore [reportGeneralTypeIssues]
assert isinstance(inmemo... | Python | 1 |
article details for {len(articles_to_process)} articles...")
for i, article in enumerate(articles_to_process):
print(f"Fetching details {i+1}/{len(articles_to_process)}: {article.get('title', '')[:50]}...")
self.debug_print(f"Before content fetching #{i+1}:", article)
... | Python | 1 |
DivFunction
where
T: num::Num + Copy + 'static,
{
fn apply(&self, input_elems: &[&T]) -> T {
let a = input_elems[0];
let b = input_elems[1];
*a / *b
}
fn grad(&self, inputs: &[&Tensor<T>]) -> HashMap<u128, Box<CalcGrad>>
{
let a = inputs[0].clone();
... | Rust | 0 |
d not be started
pub fn optimal_models(self) -> Result<OptimalModels<L, P, O, F, defaults::Non>, ClingoError> {
let mut handle = std::ptr::null_mut();
let event_handler = std::ptr::null_mut();
if !unsafe {
clingo_control_solve(
self.ctl.as_ptr(),
S... | Rust | 0 |
suffix: None,
index: None,
group: Some("[Unresolved]".to_string()),
});
} else if err.to_string() != "Error: Entry reserved!" {
view.push(Entry {
timestamp,
key: key.to... | Rust | 0 |
9` -> `2.0`
/// - `2.0` -> `2.0`
///
/// with `high = 2.0`
/// - `2.1` -> `2.0`
/// - `1.9` -> `1.9`
pub fn crop(&self, x: f64) -> f64 {
util::limit(self.low, self.high, x)
}
}
/// Calibration coefficients
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde... | Rust | 0 |
.tag),
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Config {
pub name: Option<String>,
pub version: Option<String>,
pub dependencies: Vec<Dependency>,
}
pub fn get_config_file<'a>(directory: PathBuf) -> Option<PathBuf> {
let config_file = directory.join(".scales.json");
... | Rust | 0 |
image file.");
});
}
fn closest_piet_colour(Rgb([r, g, b]): Rgb<u8>) -> Rgb<u8> {
*PIET_COLOURS
.iter()
.min_by_key(|rgb| {
let Rgb([ro, go, bo]) = rgb;
let rd = r as i32 - *ro as i32;
let gd = g as i32 - *go as i32;
let bd = b as i32 - *bo a... | Rust | 0 |
}
fn as_xy(&self) -> (i32, i32) {
let &Location(layer, rot) = self;
if layer == 0 {
return (0, 0);
}
let side_len = layer * 2;
let from_corner = (rot + 1) % side_len;
let half_side = side_len / 2;
let off_center = from_corner as i32 - half_side... | Rust | 0 |
where
S: Serializer,
{
serializer.serialize_str(&self.0.to_string())
}
}
impl<'de> Deserialize<'de> for PeerIdSerialized {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s: String = Deserialize::deserialize(deserializer... | Rust | 0 |
from django.utils import timezone
from grants.models import *
from grants.models import Contribution
from grants.utils import get_clr_rounds_metadata
# total stats
clr_rounds_metadata = get_clr_rounds_metadata()
round_start_date = clr_rounds_metadata['round_start_date']
round_end_date = clr_rounds_metadata['round_en... | Python | 1 |
import torch
import torch.nn as nn
from torch.autograd import Variable
import math
from args_params_hyperparams import parse_hyperparams, parse_args
args = parse_args()
hyperparams = parse_hyperparams()
def hard_sigmoid(x):
return torch.min(torch.max(x, torch.zeros_like(x)), torch.ones_like(x))
class _L0Norm(nn.... | Python | 1 |
lay.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, new)]
pub struct GameLoadingStatus {
/// Whether the map is loaded.
#[new(default)]
pub map_loaded: bool,
/// Whether characters are loaded.
#[new(default)]
pub character_augment_status: CharacterAugmentStatus,
}
impl GameLoadingStatus {... | Rust | 0 |
static str> {
Todo::get(id,get_conn(pool)?.deref())
.map_err(|_| "Error getting todo")
}
pub fn update(id: i32, todo_update: TodoUpdate, pool: &PgPool) -> Result<Todo, &'static str> {
Todo::update(id, todo_update,get_conn(pool)?.deref())
.map_err(|_| "Error getting todo")
}
pub fn de... | Rust | 0 |
def lunch(food):
if food == 'wings':
print(f"{food} is my favorite food")
elif food == 'pizza':
print(f"{food} is a pretty good lunch")
else:
print(f"{food} is just okay")
# lunch('wings')
# XOR
# print( True ^ False)
# print( False ^ False)
# print( True ^ True)
# print( False ^ T... | Python | 1 |
udio/aiff",
"audio/aac",
"audio/ogg",
"audio/flac",
]:
raise ValueError(
f"Unsupported audio media type: {audio_type}. "
... | Python | 1 |
geUnavailable(e.to_string()),
RelativePosition::Remote => Error::RemoteStorageUnavailable(e.to_string()),
})?;
backend_storage
.set(
libra_global_constants::WAYPOINT,
Value::String(waypoint.to_string()),
)
.map_err(... | Rust | 0 |
.transpose(dim0=2, dim1=3).contiguous().view(B, D, -1)
y_rb = ys[:, 0:2] + ys[:, 2:4].flip(dims=[-1]).view(B, 2, D, -1)
# 把竖向的部分转成横向,然后再相加,再转回最初是的矩阵形式
y_rb = y_rb[:, 0] + y_rb[:, 1].view(B, -1, W, H).transpose(dim0=2, dim1=3).contiguous().view(B, D, -1)
y_rb = y_rb.view(B, -1, H, W)
... | Python | 1 |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | Python | 1 |
new thread
pub fn new_boxed<S: Into<String>>(tid: ThreadID, name: S, process: Arc<Process>) -> ThreadPtr
{
let rv = box Thread {
cpu_state: process.empty_cpu_state(),
block: Arc::new(SharedBlock {
tid: tid,
name: name.into(),
process: process,
complete: crate::sync::EventChannel::new... | Rust | 0 |
persistent memory programming.
//!
//! Developers new to persistent memory probably want to start with this library.
//!
//! > This is **not** an official port of the NVM Library.
//! >
//! > The official **libpmemobj** documentation can be found at: [http://pmem.io/nvml/libpmemobj/](http://pmem.io/nvml/libpmemobj/)
e... | Rust | 0 |
import convokit
import numpy as np
import matplotlib.pyplot as plt
print("Loading corpus")
corpus = convokit.Corpus(filename=convokit.download("reddit-corpus-small"))
print("Computing hypergraph features")
hc = convokit.HyperConvo(prefix_len=10, include_root=False)
hc.fit_transform(corpus)
threads_feats = dict()
con... | Python | 1 |
# deadlock if the subprocess sends more than self.limit
# bytes. So just call self.read(self._limit) until EOF.
blocks = []
while True:
block = await self.read(self._limit)
if not block:
break
blocks.append(blo... | Python | 1 |
default::Default::default()
}
// repeated .CDeviceAuth_GetAuthorizedBorrowers_Response.Borrower borrowers = 1;
pub fn get_borrowers(&self) -> &[CDeviceAuth_GetAuthorizedBorrowers_Response_Borrower] {
&self.borrowers
}
pub fn clear_borrowers(&mut self) {
self.borrowers.clear();
... | Rust | 0 |
change_bit(&p.scgcacmp, 0, on) },
Domain::Eeprom => unsafe { bb::change_bit(&p.scgceeprom, 0, on) },
Domain::Pwm0 => unsafe { bb::change_bit(&p.scgcpwm, 0, on) },
Domain::Pwm1 => unsafe { bb::change_bit(&p.scgcpwm, 1, on) },
Domain::Emac0 => unsafe { bb::change_bit(&p.scgcemac, 0, on) },... | Rust | 0 |
import json
import csv
#inicio do código
def carregar_afd(arquivo):
with open(arquivo, 'r') as f:
dados = json.load(f)
inicial = dados["initial"]
finais = [0] * 100
for estado in dados["final"]:
finais[estado] = 1
transicoes = []
for t in dados["transitions"]:
... | Python | 1 |
import pdb
#####
#simple decorator
def one_adder(func):
def inner(a):
ret = func(a)
return ret + 1
return inner
@one_adder
def barney(a) :
return a * a
print barney(2)
#################################
# this is a little contrived
def span(func):
def inner(txt):
ret = fun... | Python | 1 |
anyhow::Result<()> {
//! # let mut config = Config::new();
//! # config.host("localhost");
//! # config.port(1433);
//! # config.authentication(AuthMethod::sql_server("SA", "<<PASSWORD>>"));
//! # config.trust_cert();
//! # let tcp = TcpStream::connect(config.get_addr()).await?;
//! # tcp.set_nodelay(true)?;
//! # let... | Rust | 0 |
Ntfs3 {
maximum_versions: u32,
version: u32,
class_id: u32,
owner_id: u32,
security_id: u32,
quota_charged: u64,
usn: u64,
}
/// Structure of a $STANDARD_INFORMATION attribute.
///
/// Among other things, this is the place where the file times and "File Attributes"
/// (Read-Only, Hidden, S... | Rust | 0 |
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York",
"occupation": "Engineer",
"hobby": "Painting"
}
my_dict["temp"]="value"
my_dict["name"]="Arin"
del my_dict["temp"]
print(my_dict) | Python | 1 |
_config[layer_name]["sym"] = layer_config[layer_name]["sym"]
elif layer_name in layer_names_in_block:
neq_keys = check_neq_config(
layer_config[layer_name],
data_type=quantization_config["data_type"],
bits=quantization_config["bits"],
g... | Python | 1 |
fer(&sender, &Self::account_id(), amount, AllowDeath)
.map_err(|_| dispatch::DispatchError::Other("Can't make donation"))?;
Ok(())
}
}
}
impl<T: Trait> Module<T> {
/// The account ID that holds the Charity's funds
pub fn account_id() -> T::AccountId {
PALLET_ID.into_account()
}
/// The Charity's balan... | Rust | 0 |
import pytest
import datetime
from tensorhive.models.RestrictionSchedule import RestrictionSchedule
from tensorhive.utils.Weekday import Weekday
def test_schedule_creation(tables):
schedule_expression = '12345'
starts_at = datetime.time(8, 0, 0)
ends_at = datetime.time(15, 0, 0)
schedule = Restrictio... | Python | 1 |
#!/usr/bin/env python3
import requests
import sys
import time
import lxml.html
from lxml.html.diff import htmldiff
from lxml.html.clean import Cleaner
url = sys.argv[1]
from helper import *
cleaner = Cleaner()
cleaner.javascript = True
cleaner.style = True
#cleaner.kill_tags = ['a', 'h1']
#cleaner.remove_tags = ['p'... | Python | 1 |
elation coefficient."""
y_pred_ranked = np.apply_along_axis(rankdata, 0, y_pred)
y_ranked = np.apply_along_axis(rankdata, 0, y)
return _weighted_pearson(y_pred_ranked, y_ranked, w)
def _mean_absolute_error(y, y_pred, w):
"""Calculate the mean absolute error."""
return np.average(np.abs(y_pred - y)... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.