text string | label_name string | labels int64 |
|---|---|---|
= maybe_effective_stake_ratio {
//?
let (integer, frac) = total_stake_limit_ratio(effective_stake_ratio);
return (integer.into(), frac);
}
return (0u128, Perbill::zero());
}
/// Insert new or update old stake limit
pub fn upsert_stake_limit(account_id: ... | Rust | 0 |
# src/main.py (agora focado apenas em DOWNLOAD)
import sys
import os
import json
import time
import traceback
script_dir = os.path.dirname(os.path.abspath(__file__))
if script_dir not in sys.path:
sys.path.insert(0, script_dir)
from config_mtr import CONFIG, log_message
from file_ops import (
carregar_planilh... | Python | 1 |
Pharmaceutical', 'shares': 833, 'price': 28.52}],
"date": "20231109"
}
portfolio_status9 = {
"cash": 21.36,
"stocks": [{'code': '600196.SH', 'name': 'Fosun Pharmaceutical', 'shares': 2239, 'price': 27.2}],
"date": "20231211"
}
portfolio_status10 = {
"cash": 594.36,
... | Python | 1 |
des.append(str(key))
structure.append([key, method.parent.label])
if str(key) == active_label:
colors.append([str(key), 'green'])
else:
colors.append([str(key), 'red'])
for j in range(len(self.con... | Python | 1 |
import torch
import torch.nn.functional as F
def normalize(v, eps=1e-6):
"""Normalize a batch of vectors to unit length."""
return v / (torch.norm(v, dim=-1, keepdim=True) + eps)
def sample_along_rays(rays_o, rays_d, num_samples=64, near=2.0, far=6.0):
"""
Uniformly samples 3D points along each ray.
... | Python | 1 |
grades = [ ["Алексей", 5, 4, 3], ["Мария", 4, 5, 5], ["Иван", 3, 2, 4], ["Елена", 5, 5, 5] ] #список
l = -1 #индекс вложенного списка
f = len(grades) # кол-во влаженных списков
g = len(grades[l]) # длинна вложенного списка
z = 0 #
x = {} #словарь
list_name = [] # список ключей
h = [[]for d in range(f)] #
b = [[] for r ... | Python | 1 |
) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
# [ doc = r" Proxy" ]
pub struct _EPERRINTSET9W<'a> {
w: &'a mut W,
}
impl<'a> _EPERRINTSET9W<'a> {
# [ doc = r" Sets the field bit" ]
pub fn set(self) -> &'a mut W {
... | Rust | 0 |
# Copyright (c) 2025 Microsoft Corporation.
"""LLM configuration module."""
import os
from enum import StrEnum
from typing import Any, Self
from pydantic import BaseModel, Field, SecretStr, model_validator
class LLMProvider(StrEnum):
"""Enum for the LLM provider."""
OpenAIChat = "openai.chat"
OpenAIEmb... | Python | 1 |
#!/usr/bin/python3
"""DOC"""
import requests
def number_of_subscribers(subreddit):
"""DOC"""
reddit_url = "https://www.reddit.com/r/{}/about.json" \
.format(subreddit)
header = {'User-agent': 'Mozilla/5.0'}
response = requests.get(reddit_url,
headers=header
... | Python | 1 |
t("-"))
# 提取这个区间的所有页面
for page_num in range(start_page, end_page + 1):
if page_num < len(book_toc):
text = str(book_toc[page_num])
# Apply line number trimming
... | Python | 1 |
.insert("revpos", 11)
.insert("stub", true)
.build();
let source = serde_json::to_string(&source).unwrap();
let got = serde_json::from_str(&source).unwrap();
assert_eq!(expected, got);
}
#[test]
fn saved_attachment_deserialize_ok_with_content_bod... | Rust | 0 |
e::try_new(batch.schema(), vec![vec![batch]])?;
let mut ctx = ExecutionContext::new();
ctx.register_table("test", Arc::new(table))?;
// Basic SELECT
let sql = "SELECT * FROM test";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec![
"+-------+",
"| d1 |... | Rust | 0 |
f64::cos(r.0 + t)),
ez: 0.0,
bx: 0.0,
by: 0.0,
bz: a0 * (f64::sin(r.0) * f64::sin(t) + 0.5 * (1.0 - R) * f64::cos(r.0 + t)),
};
} else if r.0 > 0.0 {
return EM {
ex: 0.0,
ey: a0 * (f64::cos(r.0) * f64::cos(t) - 0.5 * (1.0 - R) ... | Rust | 0 |
uantizedLinear.from_weight(
layer.qweight,
layer.scales,
layer.qzeros,
layer.qweight.size(0),
layer.ipex_output_size,
qconfig=qconfig,
bias=bias,
group_size=self.quant_config.group_size,
quant_method=IPEXConfig.I... | Python | 1 |
"Offset of field: ",
stringify!(QuESTEnv),
"::",
stringify!(numSeeds)
)
);
}
extern "C" {
#[doc = " Creates a state-vector Qureg object representing a set of qubits which will remain in a pure state."]
#[doc = ""]
#[doc = " Allocates space for a state-vector o... | Rust | 0 |
.watch(&tdir.mkpath("dir1"), RecursiveMode::Recursive)
.expect("failed to watch directory");
match watcher.unwatch(&tdir.mkpath("dir1")) {
Ok(_) => (),
Err(e) => panic!("{:?}", e),
}
}
#[test]
#[cfg_attr(target_os = "windows", ignore)]
fn unwatch_nonexisting() {
let tdir = tempfil... | Rust | 0 |
er pieces of
/// information to verify that the response is valid (i.e., the contents and signature match
/// what we expect).
pub fn new(
api_key: &[u8],
expected_otp: &Otp,
expected_nonce: &str,
response: Vec<u8>,
) -> Result<VerificationResult> {
let response =... | Rust | 0 |
min_chan: Sender<Sender<i32>>,
}
impl Service for Server {
type Request = Request;
type Response = Response;
type Error = io::Error;
type Future = Box<Future<Item=Response, Error=io::Error>>;
fn call(&self, req: Request) -> Self::Future {
let random_id = rand::thread_rng().gen_range(1, 5);... | Rust | 0 |
n_way,
"support_size": self.k_shot,
"query_size": self.q_query,
"unlabeled_size": 0,
"channels": support.size(1),
"height": support.size(2),
"width": support.size(3),
"support_set": support.view(self.k_shot, self.n_way, *support.shape[1... | Python | 1 |
from transformers import AutoModelForCausalLM, AutoTokenizer
SYSTEM_PROMPT_TEMPLATE = """A conversation between User and Assistant. The user asks a question, and the Assistant solves it. The assistant first thinks about the reasoning process in the mind and then provides the user with the answer. The reasoning process... | Python | 1 |
=OpenApiParameter.QUERY,
description="Parameter category to filter by"),
],
responses=ObservationRecordSerializer(many=True),
tags=["Observation Records"]
)
@api_view()
@permission_classes([HasAPIKeyOrIsAuthenticated])
def get_station_link_timeseries_data(request, station_link_id):
... | Python | 1 |
from typing import Callable
import polars as pl
from wimsey import tests
from wimsey.execution import test as _test # so pytest won't think this is test
def test_that_all_possible_tests_are_functions_that_return_partials() -> None:
for test_name, actual_test in tests._possible_tests.items():
assert isi... | Python | 1 |
import pandas as pd
from src.modules.schema_checker import check_schema_issues
from src.modules.duplicate_checker import find_duplicates
from src.modules.imbalance_checker import check_class_imbalance
from src.modules.bias_detector import detect_toxicity
from src.modules.similarity_checker import check_similarity
from ... | Python | 1 |
"""Logging configuration."""
import os
logs_folder = "logs"
log_file = os.path.join(logs_folder, "debug.log")
if not os.path.exists(logs_folder):
os.makedirs(logs_folder)
if not os.path.exists(log_file):
open(log_file, "a").close()
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"f... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 University of Dundee & Open Microscopy Environment.
# All Rights Reserved.
# Use is subject to license terms supplied in LICENSE.txt
#
"""
FOR TRAINING PURPOSES ONLY!
"""
from omero.gateway import BlitzGateway
from Parse_OMERO_Pr... | Python | 1 |
static h1_syscalls::dcrypto::DcryptoDriver<'static>,
nvcounter: &'static h1_syscalls::nvcounter_syscall::NvCounterSyscall<'static,
FlashCounter<'static, h1::hil::flash::virtual_flash::FlashUser<'static>>>,
uint_printer: h1_syscalls::debug_syscall::UintPrinter,
personality: &'static h1_syscalls::pers... | Rust | 0 |
= x - y;
assert_eq!(z.coeff, x.coeff - y.coeff * 10);
let z = y - x;
assert_eq!(z.coeff, y.coeff * 10 - x.coeff);
let z = x - Decimal::<3>::NEG_ONE;
assert_eq!(z.coeff, x.coeff * 10 + Decimal::<3>::ONE.coeff);
}
#[test]
#[should_panic]
fn test_sub_pos_overflow()... | Rust | 0 |
"""
Django settings for itshop project.
Generated by 'django-admin startproject' using Django 5.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/5.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.1/ref/settings/
"""
from pathlib ... | Python | 1 |
from __future__ import annotations
import os
from datetime import UTC, datetime
import pytest
from astroengine.chart import (
ChartLocation,
compute_composite_chart,
compute_harmonic_chart,
compute_natal_chart,
compute_return_chart,
compute_secondary_progressed_chart,
compute_solar_arc_ch... | Python | 1 |
import bisect
def binSearch(A, L, R, K):
while L <= R:
mid = (R + L) // 2
if A[mid] == K:
return mid, A[mid]
elif K >= A[mid]:
L = mid + 1
else:
R = mid - 1
return -1
a = [10, 20, 30, 40, 50, 60, 70, 80, 90]
x = binSearch(a, 0, len(a) - 1, ... | Python | 1 |
ert!(result.bitwise_eq(e_result.parse::<Single>().unwrap()));
}
}
#[test]
fn operator_overloads() {
// This is mostly testing that these operator overloads compile.
let one = "0x1p+0".parse::<Single>().unwrap();
let two = "0x2p+0".parse::<Single>().unwrap();
assert!(two.bitwise_eq((one + one).value... | Rust | 0 |
# -*- coding: utf-8 -*-
# Copyright 2024 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 |
import sys
import json
import requests
CKAN_API = "https://sdi.eea.europa.eu/catalogue/api/3/action/package_search"
def search_ckan(query: str, rows: int = 10):
try:
r = requests.get(CKAN_API, params={"q": query, "rows": rows}, timeout=30)
r.raise_for_status()
data = r.json()
ret... | Python | 1 |
# This file is distributed under the same license as the Django package.
#
# The *_FORMAT strings use the Django date format syntax,
# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = "d F Y"
TIME_FORMAT = "H:i"
DATETIME_FORMAT = "d F Y H:i"
YEAR_MONTH_FORMAT = "F Y"
MONTH_DAY_FORMAT... | Python | 1 |
if f_apb >= 0.0 {
Pr::new((-f_apb).exp() / (1.0 + (-f_apb).exp()))
} else {
Pr::new(1.0 / (1.0 + f_apb.exp()))
}
}
/// Run Newton's method to find optimal `A` and `B` values.
///
/// The optimization process happens in two steps, first the closed-form Hessian matrix and
/// gradient vectors are calculated; then,... | Rust | 0 |
tr, pub &'a TypeArgSlice);
pub struct TypeRefMut<'a>(pub &'a str, pub &'a mut TypeArgSlice);
/// Enum to hold type info
/// does it need to be an enum or could it be flattened
/// to look like this? Type(Canonical, Struple2<Type>)
#[derive(Clone)]
#[derive(PartialEq)]
#[derive(PartialOrd)]
#[derive(Eq)]
#[derive(Hash)... | Rust | 0 |
let mut launcher =
CoreBridgeLauncher::new_with_security(&mut self.bs, status, self.security.clone());
let mut engine = BibtexEngine::new();
engine.process(&mut launcher, &self.tex_aux_path, &self.unstables)
};
match result {
Ok(TexOutcome... | Rust | 0 |
target.clear_color(0., 0., 0., 0.0);
let (width, height) = target.get_dimensions();
let (src, facing_mat) = {
use cgmath::Matrix;
let src = Into::<[f32; 3]>::into(camera.pos);
let facing_mat = Into::<[[f32; 3]; 3]>::into(camera.facing.transpose());
... | Rust | 0 |
= ChartBuilder::on(&root_area)
.margin(20)
.set_label_area_size(LabelAreaPosition::Left, 40)
.set_label_area_size(LabelAreaPosition::Bottom, 40)
.caption(
"Probability distribution function of Normal distribution",
("Arial", 40),
)
.build_cartesia... | Rust | 0 |
if nb:
# 对应匹配到正样本的预测信息
ps = pi[b, a, gj, gi] # prediction subset corresponding to targets
# GIoU
pxy = ps[:, :2].sigmoid()
pwh = ps[:, 2:4].exp().clamp(max=1E3) * anchors[i]
pbox = torch.cat((pxy, pwh), 1) # predicted box
giou... | Python | 1 |
.
fn iter(&self) -> Box<dyn Iterator<Item = Result<(Height, Self::Header), Error>>>;
/// Return the number of headers in the store.
fn len(&self) -> Result<usize, Error>;
/// Return the store block height.
fn height(&self) -> Result<Height, Error>;
/// Check the store integrity.
fn check(&se... | Rust | 0 |
::super::credentials::WebAccount, view: &WebAccountClientView) -> Result<ComPtr<foundation::IAsyncAction>> { unsafe {
let mut out = null_mut();
let hr = ((*self.lpVtbl).SetViewAsync)(self as *const _ as *mut _, webAccount as *const _ as *mut _, view as *const _ as *mut _, &mut out);
if hr == S_... | Rust | 0 |
GL_FORWARD_COMPATIBLE: Int = 0x31B1;
pub const CONTEXT_OPENGL_ROBUST_ACCESS: Int = 0x31B2;
pub const OPENGL_ES3_BIT: Int = 0x00000040;
pub const CL_EVENT_HANDLE: Int = 0x309C;
pub const SYNC_CL_EVENT: Int = 0x30FE;
pub const SYNC_CL_EVENT_COMPLETE: Int = 0x30FF;
pub const SYNC_PRIOR_COMMANDS_COMPLETE: Int = 0x30F... | Rust | 0 |
, timestamp
/// format, destination.
#[serde(default, skip_serializing_if = "Logging::is_empty")]
logging: Logging,
/// Where to listen on.
///
/// This allows multiple listening ports at once, both over ordinary TCP and on unix domain
/// stream sockets.
listen: Vec<Server>,
/// T... | Rust | 0 |
_ => panic!("Not sure what to do with type: {:?}", ty),
}
}
/// Extracts the type ident string from a TypePath.
fn get_outer_type_without_generics(path: &syn::TypePath) -> String {
let segments: Vec<_> = path.path.segments.iter().map(|seg| seg.ident.to_string()).collect();
segments.join("::")
}
/... | Rust | 0 |
1 => BLANK,
2 | 3 => ONE_SUCCESS,
4 => TWO_SUCCESS,
5 | 6 => ONE_ADVANTAGE,
7 => ADVANTAGE_SUCCESS,
8 => TWO_ADVANTAGE,
_ => unreachable!(),
}
}
fn purple(gen: &mut PCG32) -> &'static [Symbol] {
match d8.sample(gen) {
1 => BLANK,
2 => ONE_FAILURE,
3 => TWO_FAILURE,
4 | ... | Rust | 0 |
c::Sender<()>,
mut stdout: ChildStdout,
child: &mut Child,
service_status: Arc<Mutex<ServiceStatus>>,
) -> (ChildAction, SmResult) {
loop {
match terminate_channel.try_recv() {
Ok(_) | Err(TryRecvError::Disconnected) => {
// terminating the thread is a best-effort, it... | Rust | 0 |
new(0, CalculatorFloat::from(0.0)).into()
);
}
/// Test get function
#[test]
fn get_op() {
let definition = Operation::from(DefinitionBit::new(String::from("ro"), 1, false));
let operation = Operation::from(PauliX::new(0));
let mut circuit = Circuit::new();
circuit.add_operation(definition.clone())... | Rust | 0 |
dBLL > -1 * max_dBLL:
fposN.write(mystr)
if event_type == 2:
if mass_gap + max_dBLL >= invariant_mass.s * -cut_sig and \
QQ + max_dBLL >= total_ke.s * -cut_sig and \
dBLL < max_dBLL:
fposN.write(mystr)
else:
if event_type == 0:... | Python | 1 |
(year: usize, month: usize, day: usize, hour: usize, minute: usize, second: usize, posneg: char, off_hour: usize, off_minute: usize) -> Result<Value<'a>, TOMLError> {
let y = format!("{:0>4}", year);
let m = format!("{:0>2}", month);
let d = format!("{:0>2}", day);
let h = format!("{:0>2}", hour);
l... | Rust | 0 |
import enum
class MQTTErrorCode(enum.IntEnum):
MQTT_ERR_AGAIN = -1
MQTT_ERR_SUCCESS = 0
MQTT_ERR_NOMEM = 1
MQTT_ERR_PROTOCOL = 2
MQTT_ERR_INVAL = 3
MQTT_ERR_NO_CONN = 4
MQTT_ERR_CONN_REFUSED = 5
MQTT_ERR_NOT_FOUND = 6
MQTT_ERR_CONN_LOST = 7
MQTT_ERR_TLS = 8
MQTT_ERR_PAYLOAD... | Python | 1 |
ata| &mut data.d);
//!
//! // ref1 and ref2 have different owners, erase ownwer types
//! let ref1: BoxRefAnyC<u64> = BoxRefC::into_any_owner(ref1);
//! let ref2: BoxRefAnyC<u64> = BoxRefC::into_any_owner(ref2);
//!
//! // so they can be stored in a vec
//! vec![ref1, ref2];
//! ```
mod arc_owned;
mod arc_ref;
mod box... | Rust | 0 |
# funcion decoradora que recibe otra funcion como parametro
def decorador(funcion):
# crear otra funcion
def f():
print('Antes de ejecutar la función') # hacer algo antes
funcion() # ejecutar la funcion recibida como argumento
print('Después de ejecutar la función') # hacer algo después
... | Python | 1 |
40.rs
//! NVMC (i.e. flash) driver for the nrf52840 board, written in pure-rust.
use core::{
ops::{Add, Sub},
usize,
};
use nrf52840_hal as hal;
use crate::FlashInterface;
use hal::pac::{Peripherals, NVMC};
use nrf52840_constants::*;
#[rustfmt::skip]
mod nrf52840_constants {
pub const FLASH_PAGE_SIZE :... | Rust | 0 |
V> \
<INFO num="{{VAL(number)}}" str="{{VAL(string)}}">Info</INFO> \
<FILE str="{{VAL(string)}}" strconv="{{VAL(string::World=big|Moon=small|Sun=huge)}}" num="{{VAL(number:5)}}" numfunc="{{EVAL(int({{VAL(number:5)}}/10))}}"> \
File{{COPY(DATA)}} \
</FI... | Python | 1 |
, buffer2);
for _ in 0..black_box(5) {
change_buffer.clear();
change_buffer.extend(
fresh
.as_raw_slice()
.iter()
.zip(stale.as_... | Rust | 0 |
kticks[For more information see `echo test`]' \
'--backslash[Avoid '\''\\n'\'']' \
'--brackets[List packages \[filter\]]' \
'--expansions[Execute the shell command with $SHELL]' \
'-h[Prints help information]' \
'--help[Prints help information]' \
'-V[Prints version information]' \
'--version[Prints version information... | Rust | 0 |
/");
test("https://foo.bar.ic0.app", "https://ic0.app/api/v2/");
test("https://ic0.app/foo/", "https://ic0.app/foo/api/v2/");
test("https://foo.ic0.app/foo/", "https://ic0.app/foo/api/v2/");
test("https://ic1.app", "https://ic1.app/api/v2/");
test("https://foo.ic1.app", "https:/... | Rust | 0 |
# Copyright (C) 2022-2025 Intel Corporation
# LIMITED EDGE SOFTWARE DISTRIBUTION LICENSE
import pytest
from iai_core.entities.metrics import (
AnomalyLocalizationPerformance,
ColorPalette,
CurveMetric,
LineChartInfo,
LineMetricsGroup,
Performance,
ScoreMetric,
)
@pytest.fixture()
def fxt... | Python | 1 |
d_temp};cmake {cmake_args} -DVIRTUAL_ENV={self.env} {ext.sourcedir};make -j8 install;pwd")
setup(
name='fastasr',
version='0.0.4',
python_requires='>=3.6',
install_requires=requirements,
description="FastASR",
long_description=get_readme(),
long_description_content_type='text/markdown',
... | Python | 1 |
# coding=utf-8
# Copyright (c) 2020 Alibaba PAI team.
#
# 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 ... | Python | 1 |
#!/usr/bin/env python
import rospy
from jsk_recognition_msgs.msg import DepthErrorResult, PlotData
import numpy as np
import csv
grid = 0.1 # 10 cm
bins = {}
data = PlotData()
def callback(msg):
bin_index = int(msg.true_depth / grid)
if bin_index not in bins:
bins[bin_index] = []... | Python | 1 |
# coding=utf-8
import ply.lex as lex
# List of token names.
reversed = (
# 基本操作
'LOAD', 'SAVE', 'TRAIN', 'RUN', 'OVERWRITE', 'CONNECT', 'SET',
# 数据源
'PARQUET', 'CSV', 'JSON', 'MLSQL',
# sklearn算法
'SKLEARN', 'KNN', 'LR',
# pandas and numpy
'PD', 'NP',
)
tokens = reversed + (
# Symb... | Python | 1 |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
import pytest
import torch
from fairscale.nn.misc import GradBucket
def test_grad_values_conserved():
with torch.... | Python | 1 |
Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
let strerror = |error| unsafe { wt_strerror(error) };
match self {
Error::System(i) => write!(f, "SYSTEM({}): {}", i, strerror(*i)),
Error::Rollback => write!(f, "{}", strerror(wiredtiger_sys::WT_ROLLBACK)),
... | Rust | 0 |
from PIL import Image, ImageFont, ImageDraw
import datetime as dt
target_img = Image.open("./src/그림3.jpg")
draw = ImageDraw.Draw(target_img,"RGBA")
box_coords = [(46, 56), (290, 150)] # 상자의 좌상단과 우하단 좌표
draw.rectangle(box_coords, fill=(255, 255, 255,128)) # 흰색 상자, 투명도 조정
font1 = ImageFont.truetype("./src/hy헤드라인m.t... | Python | 1 |
arse the MOPAC output file.")
gradient = data.pop("gradients")
output = input_model.dict()
output["provenance"] = {"creator": "mopac", "version": data.pop("mopac_version")}
output["properties"] = {}
output["properties"]["return_energy"] = data["heat_of_formation"]
out... | Python | 1 |
}
if let Some(v) = self.routing_id {
os.write_uint64(2, v)?;
}
os.write_unknown_fields(self.get_unknown_fields())?;
::std::result::Result::Ok(())
}
fn get_cached_size(&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields(&self) -> &::protobu... | Rust | 0 |
e),
MouseUp(MouseState),
MouseMove(ViewportPosition),
KeyUp(Key),
KeyDown(Key),
}
#[derive(Debug, Default)]
pub struct InputPreprocessor {
pub keyboard: KeyStates,
pub mouse: MouseState,
}
enum KeyPosition {
Pressed,
Released,
}
impl MessageHandler<InputPreprocessorMessage, ()> for InputPreprocessor {
fn pr... | Rust | 0 |
zw99vhjujn4 as jivc25ve5wm, tctb0ggr1tt
''.pg7l2kw5pkg: None = w5a23cieml0
assert equ0zkdw71_, 0j
import m8ln1_3ywm4, j8ygpky8ge5 as tbspzmo7f2_, rvwrae4yn7x as wd0yk5z0pas
raise oer_k61vqe6
'# strain_batteries_message -> battery_recipient_pole'
def dzwj28nfop1(v2mow9e48e_: fso7y_shqy2, d7fhgdxu8fw,... | Python | 1 |
ncBackupManager(vault_path)
backups = manager.list_backups()
if not backups:
print("📝 No backups found")
return
print(f"📋 Found {len(backups)} backup(s):")
for backup in backups:
print(f" • {backup.backup_id}")
print(f" Created: {backup.created_at.strftime... | Python | 1 |
ugin binary dependencies"
phelp = (
"Plugin name for which to remove the binary. "
+ "If no argument is given, all binaries are removed."
)
example_text = (
"examples:\n"
+ " imageio_remove_bin all\n"
+ " imageio_remove_bin freeimage\n"
)
parser = argparse.A... | Python | 1 |
(&self) -> String {
format!("input/day{:02}", self.get_day())
}
fn load_input<P: AsRef<Path>>(&self, p: P) -> io::Result<Self::Input> {
let f = File::open(p)?;
Ok(self.parse_input(f))
}
fn solve(&self) {
let input_file = self.input_file();
let input = self
... | Rust | 0 |
import numpy as np
import cv2
import os
from utils.misc import check_mkdir
img_path = './IMAGE/'
mask_path = './MASK/'
save_mask_path = './Image-mask_COLORED/'
img_list= [img_path + f for f in os.listdir(img_path) if
f.endswith('.jpg') or f.endswith('.png') or f.endswith('.bmp')]
gts_list = [mask_path + ... | Python | 1 |
"
fluidIds = ["Fluid"]
try:
mplugin.registerNode( SPHConfigurationNode.kPluginNodeTypeName, SPHConfigurationNode.kPluginNodeId, SPHConfigurationNode.creator, SPHConfigurationNode.initialize, OpenMayaMPx.MPxNode.kLocatorNode )
mplugin.registerNode( SPHFluidConfigurationNode.kPluginNodeTypeName, SPHFluidConfigur... | Python | 1 |
ll be set to the primary monitor's dimensions by the platform.
///
/// The default is `None`.
pub max_dimensions: Option<(u32, u32)>,
/// If `Some`, the window will be in fullscreen mode with the given monitor.
///
/// The default is `None`.
pub monitor: Option<platform::MonitorId>,
//... | Rust | 0 |
b"cbor_value_leave_container\x00",
)).as_ptr(),
b"src/cborparser.c\x00" as *const u8 as *const libc::c_char,
638i32,
b"cbor_value_is_container(it)\x00" as *const u8 as *const libc::c_char,
);
} else {
};
if 0 != !((*recursed).type_0 as libc::c_int == ... | Rust | 0 |
import uuid
from datetime import datetime, timezone
from typing import TYPE_CHECKING
from sqlalchemy import func, text
from sqlalchemy.dialects import postgresql as pg
from sqlmodel import Column, Field, Relationship
from backend.app.next_of_kin.schema import NextOfKinBaseSchema
if TYPE_CHECKING:
from backend.ap... | Python | 1 |
__all__ = ["router"]
from fastapi import APIRouter, Depends
from src.middleware.auth_guard import get_id
from src import repositories as reps
from src.utils import messages
import src.exceptions as exceptions
import src.schemas as schemas
router = APIRouter(
prefix="/match",
tags=["Matching"],
)
@router.pu... | Python | 1 |
from src.calculators.calculator_1 import Calculator1
def calculator_1_factory():
calc = Calculator1()
return calc | Python | 1 |
apost(
self,
url: str,
data: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None,
follow_redirects: bool = True,
) -> Response:
self._check_context_manager()
return await self._async_client.post(
url,
json=data,
... | Python | 1 |
eName
jiraBusinessLinePlatformDict["platformBusinessLine"] = platformBusinessLineName
return HttpResponse(ApiReturn(body=jiraBusinessLinePlatformDict).toJson())
def deleteJiraBusinessLinePlatform(request):
jiraBusinessLinePlatformId = request.POST.get("jiraBusinessLinePlatformId")
TbJiraBusinessLinePl... | Python | 1 |
::MessagePack, Some(&cipher))?;
let expected = rest::Message::from_encoded(item.encrypted.clone(), None)?;
assert_eq!(msg.data, expected.data);
assert_eq!(msg.encoding, expected.encoding);
}
Ok(())
}
#[tokio::test]
async fn encrypt_message_256() -> Result... | Rust | 0 |
count == |E|
// (I2) for each bucket: bucket.first / bucket.last together with
// all transitively reachable entries and their "hash_prev" /
// "hash_next" pointer form a valid doubly linked list
// (I3) "lru_first / lru_last" and the "lru_prev" / "lru_next"
// members of entries form a valid doubly lin... | Rust | 0 |
def get_vowels_number(message):
vowels = "AEIOUaeiou"
result = 0
for char in message:
if char in vowels:
result += 1
return result
message = "python is sweet"
result = get_vowels_number(message)
print(result)
| Python | 1 |
: u32 = 3;
pub const NLMSG_OVERRUN: u32 = 4;
pub const NLMSG_MIN_TYPE: u32 = 16;
pub const NETLINK_ADD_MEMBERSHIP: u32 = 1;
pub const NETLINK_DROP_MEMBERSHIP: u32 = 2;
pub const NETLINK_PKTINFO: u32 = 3;
pub const NETLINK_BROADCAST_ERROR: u32 = 4;
pub const NETLINK_NO_ENOBUFS: u32 = 5;
pub const NETLINK_RX_RING: u32 = ... | Rust | 0 |
from lib2to3.fixer_util import String
word = input("Enter the string :")
lowerCount = 0
upperCount = 0
for i in word:
if i.islower():
lowerCount += 1
else:
upperCount += 1
print("the number of lower character is : " , lowerCount )
print("the number of upper character is : " , upperCount ) | Python | 1 |
#!/usr/bin/python3
"""
This module contains a function that prints a name.
"""
def say_my_name(first_name, last_name=""):
"""
Prints "My name is <first name> <last name>"
Args:
first_name (str): First name
last_name (str, optional): Last name. Defaults to "".
Raises:
TypeError: If first_... | Python | 1 |
pub type OFFLINEFILES_ITEM_COPY = i32;
#[doc = "*Required features: `\"Win32_Storage_OfflineFiles\"`*"]
pub const OFFLINEFILES_ITEM_COPY_LOCAL: OFFLINEFILES_ITEM_COPY = 0i32;
#[doc = "*Required features: `\"Win32_Storage_OfflineFiles\"`*"]
pub const OFFLINEFILES_ITEM_COPY_REMOTE: OFFLINEFILES_ITEM_COPY = 1i32;
#[doc =... | Rust | 0 |
tus;
pub mod states;
pub fn shorten_string(s: &str) -> String {
let max_length = 50;
let mut s = s.to_string();
if s.len() > max_length {
s = s.replace("\n", " ");
s.truncate(max_length - 3);
s.push_str("...");
}
s
}
<reponame>registreerocks/tee_median_poc
extern crate data... | Rust | 0 |
: &HashMap<String, Option<&str>>,
) -> IndyResult<()> {
let captures = VALUE_TAG_MATCHER.captures(key).ok_or(IndyError::from_msg(
IndyErrorKind::InvalidState,
format!("Attribute name became unparseable"),
))?;
let attr_name = captures
.get(1)
... | Rust | 0 |
# 继承
class Car():
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
... | Python | 1 |
import calendar
from datetime import datetime
def imprimir_calendario(fecha_inicio, fecha_fin):
# Convertir las fechas de cadena a objeto datetime
fecha_inicio = datetime.strptime(fecha_inicio, "%Y-%m-%d")
fecha_fin = datetime.strptime(fecha_fin, "%Y-%m-%d")
# Iterar a través de los meses en el rango ... | Python | 1 |
"""
This script takes a pytest CSV file produced by pytest --csv foo.csv
and summarizes it into a more minimal CSV that is good for uploading
to Google Sheets. We have been using this with dynamic shapes to
understand how many tests fail when we turn on dynamic shapes. If
you have a test suite with a lot of skips or ... | Python | 1 |
(user_id=current_user.id).order_by(
Book.created_at.desc()
).limit(10).all()
# Get recent reading logs (last 10)
recent_logs = ReadingLog.query.filter_by(user_id=current_user.id).order_by(
ReadingLog.date.desc()
).limit(10).all()
return render_template('auth/my_activity.htm... | Python | 1 |
print(round(2.6657))
print(round(2.6657, 0))
print(round(2.45))
print(round(2.45, 0))
print(round(2, 0))
print(round(2,))
print(round(2.678))
print(round(7.5))#Nearest EVEN Integer **TIE BREAKING Scenario**
print(round(7.5,0))#Nearest EVEN Integer, but since the 1st argument is float and we provided the 2nd argument -... | Python | 1 |
tency check failed")
return False # 增加返回值表示聚合是否成功
# 计算权重
weights = {}
total_weight = 0.0
for station_id in updates.keys():
# 基于性能指标调整权重
base_weight = self.ground_stations[station_id]
metrics_factor = self._calculate_m... | Python | 1 |
FfiOptOwnedStr) {
ffi_boundary(move || {
let _ = string;
})
}
impl IntoFfi<FfiOptOwnedStr> for CString {
#[inline]
fn error_value() -> FfiOptOwnedStr {
FfiOptOwnedStr::null()
}
#[inline]
fn into_ffi(self) -> FfiOptOwnedStr {
FfiOwnedStr::from(self).into()
}
}
... | Rust | 0 |
32) };
const X0: f32 = V.0;
const X1: f32 = V.1;
const X2: f32 = V.2;
const Y0: f32 = unsafe { simd_extract(V, 0) };
const Y1: f32 = unsafe { simd_extract(V, 1) };
const Y2: f32 = unsafe { simd_extract(V, 2) };
assert_eq!(X0, 13.);
assert_eq!(X1, 42.);
... | Rust | 0 |
METHOD: &str = "inc";
#[no_mangle]
pub extern "C" fn call() {
let counter_uref = runtime::get_key(COUNTER_KEY).unwrap_or_revert_with(ApiError::GetKey);
let contract_ref = counter_uref
.to_contract_ref()
.unwrap_or_revert_with(ApiError::UnexpectedKeyVariant);
{
let args = (INC_METHO... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.