text string | label_name string | labels int64 |
|---|---|---|
[doc(hidden)]
pub struct _AZ_OTP_RD_DATA;
#[doc = "`read()` method returns [az_otp_rd_data::R](az_otp_rd_data::R) reader structure"]
impl crate::Readable for AZ_OTP_RD_DATA {}
#[doc = "`write(|w| ..)` method takes [az_otp_rd_data::W](az_otp_rd_data::W) writer structure"]
impl crate::Writable for AZ_OTP_RD_DATA {}
#[doc... | Rust | 0 |
domain.count('.') == 1: # Simple domain
domain_name = most_common_domain.replace('.com', '').replace('.org', '').replace('.net', '')
domain_name = domain_name.replace('.co.uk', '').replace('.io', '')
# Clean up domain name properly
if len(domain_name) > 15: ... | Python | 1 |
tuples. (sample_index, label).
Returns:
images: a tensor [nExemplars, c, h, w]
labels: a tensor [nExemplars]
"""
images = []
labels = []
for (img_idx, label) in examples:
img = self.dataset[img_idx][0]
if self.load:
... | Python | 1 |
# Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
from pydantic import BaseModel
from graphrag.language_model.manager import ModelManager
from graphrag.language_model.protocol.base import ChatModel
def create_mock_llm(responses: list[str | BaseModel], name: str = "mock") -> ChatModel:
... | Python | 1 |
################################################################################
# Copyright (C) 2015 Jaakko Luttinen
#
# This file is licensed under the MIT License.
################################################################################
import numpy as np
from .expfamily import ExponentialFamily, useconst... | Python | 1 |
.as_r_rust()
.expect("my_nested_map (inner) as rust");
my_nested_map_row.insert(index, my_nested_map_inner_row);
}
assert_eq!(my_text_map_row, my_text_map);
assert_eq!(my_nested_map_row, my_nested_map);
}
}
#[test]
#[ignore]
#[cfg(feature = "v4")]
fn map_w... | Rust | 0 |
0.3257, 0.34148]),
measure_ss!("Sugar Powder", [0.00022272, 0.00025513, 0.000271], [0.012638, 0.031051, 0.050124]),
measure_ss!("Suisse Mocha Powder", [2.7979, 3.5452, 4.3365], [17.502, 27.004, 35.433]),
measure_ss!("Pacific Ocean Surface Water", [0.0001764, 0.00... | Rust | 0 |
#Pyref data goes here
data = """
commit: 3333bfdc16484100a91c682238f75c01b461b9cf - ref_type: ['Rename Method']|The method process_content from the module src/dom/service.py in class DomService is renamed to _process_content|Location: src/dom/service.py/DomService
commit: 4e8df47bab6647ac5664d071c580a990f9ebd1c5 - ref_... | Python | 1 |
fig = go.Figure()
fig.add_trace(go.Histogram(x=speeds, nbinsx=30, name="Simulated Speeds"))
x_range = np.linspace(mean_speed - 3*std_dev, mean_speed + 3*std_dev, 100)
fig.add_trace(go.Scatter(x=x_range,
y=stats.norm.pdf(x_range, mean_speed, std_dev) * le... | Python | 1 |
from typing import List
def compute_precision_at_k(r: List[int], k: int) -> float:
r_k = r[:k]
return sum(r_k) / k
def compute_recall_at_k(r: List[int], k: int) -> float:
r_k = r[:k]
total_relevant = sum(r)
return sum(r_k) / total_relevant if total_relevant else 0.0
def compute_average_precision(... | Python | 1 |
nder,
action_sender: ActionSender,
apiresp_watch_sender: tokio::sync::watch::Sender<crate::ApiResp>,
mut api_receiver: tokio::sync::mpsc::Receiver<crate::ApiChannelItem>,
bot_id: String,
) {
// 将 websocket 接收流与发送流分离
let (mut sink, mut stream) = socket.split();
// 接收消息
let another_event_s... | Rust | 0 |
self.test_room_2 = RoomSerializer(
Room.objects.create(**self.rooms["room_2"])
).data
def test_get_room_data(self):
# Asserting to get rooms data
url = reverse("room-list")
response = self.client.get(url, format="json")
self.assertEqual(response.status_cod... | Python | 1 |
}
#[inline]
fn is_remote_port(value: u32) -> bool {
value & MASK_HEADER == Self::TAG_EXTERN_PORT
}
#[inline]
fn is_local_reference(value: u32) -> bool {
value & MASK_HEADER == Self::TAG_REFERENCE
}
#[inline]
fn is_remote_reference(value: u32) -> bool {
value & ... | Rust | 0 |
urn micro_batch_id % (self.num_pipe_buffers() - 1)
class DPOInferenceSchedule(PipeSchedule):
def steps(self):
total_steps = self.micro_batches + self.stages - 1
for step_id in range(total_steps):
cmds = []
micro_batch_id = step_id - self.stage_id
# Alternate se... | Python | 1 |
expected_url, expected_cond = val
scheck(attr, "url", url, expected_url)
scheck(attr, "cond", cond, expected_cond)
scheck(attr, "the whole", values, expected_values)
check(
"https://example.org",
[
("https://example.org", None),
],
... | Python | 1 |
ank;
if last_accessed > dir.last_accessed {
dir.last_accessed = last_accessed;
}
})
.or_insert(Dir {
path: path.to_string().into(),
rank,
last_accessed,
});
}
db.dirs = DirLis... | Rust | 0 |
list
// TODO: Get an actual fix instead of this dirty manual hack
let flip = flip_fix_list.iter().any(|n| n == &id_name(&obj.name).unwrap());
// We want the rotation, but we've got multiple rotations, so combine them
let pre_rotation = Quaternion::from(Euler::new(
Deg(properties.pre_rotation[0... | Rust | 0 |
::unwrap)
.collect();
ret.sort_unstable(); //Now the list is in order
ret.push(ret.last().unwrap() + 3); //adding the laptop to the end
ret
}
<reponame>tarkah/rust-nhl-stats-api
/*
* NHL API
*
* Documenting the publicly accessible portions of the NHL API.
*
* The version of the OpenAPI document... | Rust | 0 |
heck_out:}|
/// |redis.cluster.pool.max_lifetime|false|${pool.max_lifetime:}|
/// |redis.cluster.pool.idle_timeout|false|${pool.idle_timeout:}|
/// |redis.cluster.pool.connection_timeout|false|${pool.connection_timeout:5s}|
/// |redis.cluster.pool.wait_for_init|false|${pool.wait_for_init:false}|
#[cfg_attr(docsrs, doc(... | Rust | 0 |
import customtkinter as ctk
def key_pressed(event):
print(f"Key pressed: {event.keysym}")
print(f"Widget with focus: {root.focus_get()}") # Add this line
root = ctk.CTk()
root.geometry("200x100")
frame = ctk.CTkFrame(root, width=100, height=50)
frame.pack(expand=True, fill="both")
# Set focus to the fram... | Python | 1 |
::Consumed, _), (new_ty, _)), DictEntry::Alias)) => {
is_index(new_ty, top_ctxt)
}
_ => false,
},
_ => false,
}
}
fn is_castable_integer(t: &BaseTyp) -> bool {
match t {
BaseTyp::UInt128 => true,
BaseTyp::Int128 => true,
BaseTyp::U... | Rust | 0 |
(Self::AR0_MS - ar_ms) / Self::AR_MS_STEP_1
} else {
5.0 + (Self::AR5_MS - ar_ms) / Self::AR_MS_STEP_2
};
// OD
let od = (self.od * multiplier).min(10.0);
// CS
let mut cs = self.cs;
if mods.hr() {
cs *= 1.3;
} else if mods.ez()... | Rust | 0 |
inputs[i : i + self.eval_args.batch_size], return_attention_mask=True, return_tensors="pt"
).to(self.model.device)
preds = self.batch_inference(batch_input)
outputs += preds
corrects = (np.array(outputs) == np.array(labels))
cat... | Python | 1 |
,
U16(u16s) => visitor.visit_u16_suffix(u16s),
U32(u32s) => visitor.visit_u32_suffix(u32s),
U64(u64s) => visitor.visit_u64_suffix(u64s),
Field(fs) => visitor.visit_field_suffix(fs),
}
}
pub fn walk_u8_suffix<'ast, Z: ZVisitorMut<'ast>>(
visitor: &mut Z,
u8s: &mut ast::U8Suff... | Rust | 0 |
s = itertools.chain(self.comments, (i[2] for i in out))
lines = ('%s\n' % l for l in lines)
with open(self.filename, 'wt') as f:
f.writelines(lines)
######################################################################
# Startup
############################################################... | Python | 1 |
pl From<DRAM2_POWER_A> for bool {
#[inline(always)]
fn from(variant: DRAM2_POWER_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `DRAM2_POWER`"]
pub type DRAM2_POWER_R = crate::R<bool, DRAM2_POWER_A>;
impl DRAM2_POWER_R {
#[doc = r"Get enumerated values variant"]
#[inline(always... | Rust | 0 |
_y: libc::c_int,
);
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct Fl_SVG_File_Surface {
_unused: [u8; 0],
}
extern "C" {
pub fn Fl_SVG_File_Surface_new(
width: libc::c_int,
height: libc::c_int,
file: *const libc::c_char,
) -> *mut Fl_SVG_File_Surface;
}
extern "C" {
p... | Rust | 0 |
let mut expected: Vec<usize> = Vec::new();
match i {
0 => {expected.extend([0, 1, 2, 3, 4, 5, 6, 7, 8].to_vec()); () },
8 => {expected.extend([72, 73, 74, 75, 76, 77, 78, 79, 80].to_vec()); () },
9 => {expected.extend([0, 9, 18, 27, 36, 45, 54, 63, 72].to_vec()); () },
... | Rust | 0 |
b mod instruction;
#[macro_use]
pub mod program;
<gh_stars>10-100
#![doc(html_root_url = "https://docs.rs/rustdx/0.2.5")]
#![cfg_attr(docsrs, feature(doc_cfg))]
// #![feature(test)]
// extern crate test;
pub mod bytes_helper;
#[cfg(feature = "file")]
#[cfg_attr(docsrs, doc(cfg(feature = "file")))]
pub mod file;
#[cf... | Rust | 0 |
;
for k in 0..N {
for i in 0..M {
dp[b[i]] = std::cmp::min(dp[b[i]], dp[a[i]] + (-c[i]))
}
}
for k in 0..N {
for i in 0..M {
if dp[a[i]] + (-c[i]) < dp[b[i]] {
dp[b[i]] = -INF;
}
}
}
let ans = if dp[N] <= -INF {
... | Rust | 0 |
src_id != !0, "Cannot set sources for tombstone source id");
if self.sources.len() > self.source_contents.len() {
self.source_contents.resize(self.sources.len(), None);
}
self.source_contents[src_id as usize] = contents.map(|x| x.to_string());
}
/// Returns the current sourc... | Rust | 0 |
kuka_iiwa/model.urdf", UrdfOptions::default())?;
// let kuka_id = p.load_urdf("kuka_lwr/kuka.urdf", UrdfOptions::default())?;
let num_joints = p.get_num_joints(kuka_id);
let kuka_end_effector_index = num_joints - 1;
set_joint_positions(&mut p, kuka_id, vec![0.1; num_joints].as_slice());
p.step_simu... | Rust | 0 |
;
#[doc = "*Required features: `\"Win32_System_Diagnostics_Debug\"`*"]
pub const SOURCETEXT_ATTR_HUMANTEXT: u32 = 32768u32;
#[doc = "*Required features: `\"Win32_System_Diagnostics_Debug\"`*"]
pub const SOURCETEXT_ATTR_IDENTIFIER: u32 = 256u32;
#[doc = "*Required features: `\"Win32_System_Diagnostics_Debug\"`*"]
pub co... | Rust | 0 |
sheet_name)
.ok_or(Error::Msg("Cannot read first sheet"))??;
Ok(range)
}
/**
* 解析一行生成一个hashmap对象
*/
fn parse_row(keys: &Vec<String>, range: &Range<DataType>) -> HashMap<String, String> {
let mut line: HashMap<String, String> = HashMap::new();
for n in 0..range.get_size().1 {
line.insert(k... | Rust | 0 |
tdata/big_buck_bunny_480p_h264.mov").unwrap()).unwrap();
let h264_track = f.tracks().iter().find_map(|t| {
if matches!(t.media_type(), Ok(mp4::MediaType::H264)) {
println!("sps: {:?}", t.sequence_parameter_set().unwrap().hex_dump());
println!("pps: {:?}", t.picture_pa... | Rust | 0 |
sage="Medicamento não encontrado", details=['path: PUT /meds_stock/<:id>'])), 404
connection.commit()
return jsonify(SuccessDTO(code=200, message="Medicamento atualizado")), 200
except SQLAlchemyError as e:
error = str(e.__dict__['orig'])
return jsonify({'error': e... | Python | 1 |
"""
Module materialsvalidation
Translated using PySD version 3.14.0
"""
@component.add(
name="Fe PRICE HISTORICAL 0",
units="$/t",
comp_type="Auxiliary",
comp_subtype="with Lookup",
depends_on={"time": 1},
)
def fe_price_historical_0():
"""
Iron and Steel Scrap Price in dollars per ton. Iro... | Python | 1 |
send(Query(statement)).await?;
let _: CopyResponse = conn
.stream
.recv_expect(MessageFormat::CopyOutResponse)
.await?;
let stream: TryAsyncStream<'c, Bytes> = try_stream! {
loop {
let msg = conn.stream.recv().await?;
match msg.format {
M... | Rust | 0 |
AVLTreeNode::is_balance(x.borrow().left.clone()) && AVLTreeNode::is_balance(x.borrow().right.clone())
}
}
}
}
/// `is_bst`: 验证`node`为根的二叉树是否是二分搜索树
///
/// leetcode [98. 验证二分搜索树](https:leetcode-cn.com/problems/validate-binary-search-tree)
///
pub f... | Rust | 0 |
#[inline]
pub fn new(source: Src) -> Self
where
Sbj: Default,
{
ConnectableObservable {
source,
subject: <_>::default(),
}
}
#[inline]
pub fn fork(&self) -> Sbj
where
Sbj: Clone,
{
self.subject.clone()
}
}
impl<'a, Src, Item, Err>
ConnectableObservable<Src, LocalSub... | Rust | 0 |
umn usage: {match.group(0)}")
return _replace_direct_last_active_date(extracted_sql)
else:
return _handle_last_active_clause(extracted_sql)
def ensure_trips_join(extracted_sql: str) -> str:
"""
Ensure trips table is included in the FROM clause if checking activity.
Args:
ex... | Python | 1 |
xon.start, ref_exon.end)
if len(matches) == 0: # likely due to very low coverage on transcript
return None
# check that all matches are adjacent (no splicing! this just one integral exon)
if (not intervals_adjacent) or c_branch.intervals_all_adjacent(matches):
# check if the ends differ a li... | Python | 1 |
import pandas as pd # type: ignore
# Utils
from src.utils.ytDownloader import search_youtube_url
from src.config import get_logger
logger = get_logger(__name__)
# --------------------------------------- get_youtube_urls ---------------------------------------
# - Get YouTube URLs from an Excel file containing son... | Python | 1 |
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
tokenizer.pad_token_id = tokenizer.eos_token_id
if tokenizer.bos_token is None:
tokenizer.add_special_tokens({"bos_token": tokenizer.eos_token})
tokenizer.bos_token_id = tokenizer.eos_token_id
if tokenize... | Python | 1 |
_state {
unsafe { AFL.unwrap() }
}
#[derive(Default, Debug)]
pub struct AFLCorpus {
entries: UnsafeCell<HashMap<usize, RefCell<Testcase<BytesInput>>>>,
}
impl Clone for AFLCorpus {
fn clone(&self) -> Self {
unsafe {
Self {
entries: UnsafeCell::new(self.entries.get().as_... | Rust | 0 |
which needs to be valid only for the call."]
#[doc = " \\param[in] defaultVal Specifes the value to return if the property couldn't be read."]
#[doc = " \\return Returns the string property if it exists. Otherwise returns defaultVal, which can be"]
#[doc = " specified as NULL. The return memory is ... | Rust | 0 |
#![warn(
missing_docs,
missing_debug_implementations,
missing_copy_implementations,
trivial_casts,
trivial_numeric_casts,
unsafe_code,
unstable_features,
unused_import_braces,
unused_qualifications
)]
use failure::Fail;
use cargo_inspect::{config, errors::InspectError, inspect};
u... | Rust | 0 |
mfd::FileSeal::SealWrite)?;
let r = unsafe { mmap::MmapOptions::new().map_copy_read_only(memfd.as_file()) }?;
Ok(r)
}
/// Creates a raw memory map of a memfd, suitable for IPC. It must be writable.
pub fn raw_memfd(memfd: &mfd::Memfd) -> Result<mmap::MmapRaw, Error> {
// The file can be truncated; no saf... | Rust | 0 |
system_transaction::transfer(&keypair, &keypair.pubkey(), 1, Hash::default()),
);
let txs: Vec<SanitizedTransaction> = (0..transaction_count)
.map(|_| transfer_tx.clone())
.collect();
let execute_units_adjustment = 10u64;
// assert only commited tx_costs are a... | Rust | 0 |
_v3_api_field_service.ratelimit.v3.RateLimitResponse.overall_code>`.
/// \[#not-implemented-hide:\]
#[prost(message, optional, tag = "5")]
pub quota: ::core::option::Option<Quota>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
#[repr(i32)... | Rust | 0 |
__main__":
import sys
sys.path.append("F://CPmod//ImportPluginGIT//i_scene_cp77_gltf//material_types")
sys.path.append("F://CPmod//ImportPluginGIT//i_scene_cp77_gltf//main")
import json
from common import *
filepath="F:\\CPmod\\bottles\\source\\raw\\base\\environment\\decoration\\food\\drinks\\d... | Python | 1 |
trano nelle viscere della terra. Cristalli magici illuminano le gallerie buie mentre echi misteriosi risuonano dalle profondità. Il Drago di Cristallo dorme su un tesoro di gemme preziose.",
"🌙 Cripta Maledetta": "Una cripta sotterranea piena di magia oscura. Qui riposano antichi stregoni. L'aria vibra di ... | Python | 1 |
ulkan"))
))]
use crate::empty::RafxFenceEmpty;
#[cfg(feature = "rafx-metal")]
use crate::metal::RafxFenceMetal;
#[cfg(feature = "rafx-vulkan")]
use crate::vulkan::RafxFenceVulkan;
use crate::{RafxFenceStatus, RafxResult};
/// A GPU -> CPU synchronization mechanism.
///
/// A fence can be in the following states:
/// ... | Rust | 0 |
.arg(tap_name)
.arg("address")
.arg(mac_addr)
.status()
.expect("Failed to execute ip link");
}
#[test]
fn test_write() {
// `fetch_add` adds to the current value, returning the previous value.
// reserve 2 IPs one for the tap and the other f... | Rust | 0 |
el_shift_range"]),
fill_mode=augmentation_parameters["fill_mode"],
cval=float(augmentation_parameters["cval"]),
horizontal_flip=get_boolean(augmentation_parameters["horizontal_flip"]),
... | Python | 1 |
middleware
let service = middleware::Timeout::new(
service, timer,
Duration::from_millis(200));
// Decorate the service with the Log middleware
let service = middleware::Log::new(service);
// Start the server
line::service::serve(&lp.handle(), addr, service).unwrap();
println... | Rust | 0 |
from PyQt6.QtWidgets import (QMainWindow, QWidget, QPushButton,
QVBoxLayout, QHBoxLayout, QLabel)
from PyQt6.QtCore import Qt, QEvent
import json, os
from .views.dash import DashView
from .views.config import ConfigView
from .components.screw_counter import ScrewCounter
from .units.state_... | Python | 1 |
it_tx` RPC method.
// External deps
use jsonrpc_core::types::{Failure, Output};
use num::BigUint;
// Workspace deps
use models::node::{
closest_packable_token_amount,
tx::{PackedEthSignature, Transfer, TxSignature},
Address, FranklinTx, TokenId,
};
use server::api_server::rpc_server::RpcErrorCodes;
use tes... | Rust | 0 |
::core::ffi::c_void,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for DHCP_CALLOUT_TABLE {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for DHCP_CALLOUT_TABLE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: 'Win32_NetworkManagement_Dhc... | Rust | 0 |
sum
}
}
fn main() {
// Set the value and quantity of each type of coin in the jar
let penny = Coins::get_coin("Penny".to_string(), 10).unwrap();
let nickel = Coins::get_coin("Nickel".to_string(), 10).unwrap();
let dime = Coins::get_coin("Dime".to_string(), 10).unwrap();
let quarter = Coins::get... | Rust | 0 |
!( once.state().done() );
```
*/
pub fn state(&self) -> ROnceState{
self.vtable().state()(&self.opaque_once)
}
/**
Runs an initialization function.
`f` will be run only if this is the first time this method has been called
on this ROnce.
Once this function returns it is guaranteed that some closure... | Rust | 0 |
import os
import numpy as np
import tensorflow as tf
from models import NAMAS
from utils import *
from utils import pp
flags = tf.app.flags
flags.DEFINE_integer("epoch", 25, "Epoch to train [25]")
flags.DEFINE_integer("word_embed_dim", 650, "The dimension of word embedding matrix [650]")
flags.DEFINE_integer("char_e... | Python | 1 |
# IODATA is an input and output module for quantum chemistry.
# Copyright (C) 2011-2019 The IODATA Development Team
#
# This file is part of IODATA.
#
# IODATA is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; e... | Python | 1 |
t=self.arabic_font, fg="white", bg="#3C1361",
selectcolor="#5A2A9C")
checkbox.pack(anchor="e", padx=10)
entries[f"موافقة_{term}"] = var
# التوقيعات
signatures_frame = tk.LabelFrame(scrollable_frame,
... | Python | 1 |
import os
from math import sqrt
import cv2
import numpy as np
from sim_model import normalize_vectors, derivative, SimulationModel
from sim_model import get_cloud_from_depth, get_camera_matrix
assets_path = os.path.dirname(os.path.abspath(__file__)) + '/../assets/'
def norm(v):
return sqrt(sum([c ** 2 for c in... | Python | 1 |
*u).is_ok() => Some(u.to_owned() as isize),
Edn::Double(d) => Some(d.to_owned().to_float().round() as isize),
Edn::Rational(r) => Some(rational_to_double(&r).unwrap_or(0f64).round() as isize),
_ => None,
}
}
/// Similar to `to_int` but returns an `Option<usize>`
... | Rust | 0 |
def main():
x=seconde()
print(x)
def seconde():
while True:
try:
x=int(input(" veuillez donner la veleur de x"))
except ValueError:
print("cette valeur est ivnvalide")
else:
return x
main()
from turtle import *
def triangle(ko... | Python | 1 |
ore::Semaphore;
mod fence;
mod semaphore;
<gh_stars>1-10
//! This is `dir-lock`, a library crate providing the type [`DirLock`], which is a simple file-system-based mutex.
//!
//! # Features
//!
//! The following feature is enabled by default:
//!
//! * `tokio`: Uses the [`tokio`](https://docs.rs/tokio) runtime for as... | Rust | 0 |
from typing import Any, Dict, List, Type, TypeVar
import attr
T = TypeVar("T", bound="ProjectCollectiongetResponseSchemaDataItemCustom")
@attr.s(auto_attribs=True)
class ProjectCollectiongetResponseSchemaDataItemCustom:
"""The object containing all custom defined fields."""
additional_properties: Dict[str,... | Python | 1 |
SingleColumnLayout(p)
l.append_layout_element(
SmartArt.vertical_bullet_list(
level_1_items=["Cherries", "Papaya", "Avocado"],
level_2_items=[
["Vitamin C", "Potassium"],
["Vitamin C", "Vitamin A"],
["Potassi... | Python | 1 |
27.into_floating_input().degrade();
let pins = twim::Pins { scl, sda };
let i2c = p.TWIM0.constrain(pins, twim::Frequency::K100);
let mut disp: GraphicsMode<_> = Builder::new().connect_i2c(i2c).into();
disp.init().expect("Display initialization");
disp.flush().expect("Cleans the display");
... | Rust | 0 |
'''
INPUT
ABC
OUTPUT
2
INPUT
CDF
OUTPUT
6
'''
a=input().lower()
s='bcdfghjklmnpqrstvwxyz'
c=0
for i in a:
if i in s:
c+=1
print(c)
abc
2
CDF
3
| Python | 1 |
ove |facing| facing * rot))
.collect()
}
pub fn parse(input: &str) -> Result<Vec<Scanner>> {
let mut scanners = Vec::new();
// go through and generate scanners without signatures
for line in input.lines() {
// skip blank lines
if line.trim().is_empty() {
continue;
... | Rust | 0 |
// Start timer.
let start = Instant::now();
// Run program.
app::run();
// Split timer.
let duration = start.elapsed();
println!("Time elapsed in expensive_function() is: {:?}", duration);
// Say goodbye / shudown program.
println!("Quitting program.");
process::exit(0);
}
... | Rust | 0 |
ernal.pack_start(label_note, False, False, 0)
def __toggled_system_font(self, widget, data=None):
"""Handle toggle of system font checkbox"""
self._parent.enable_save()
def _load_options(self):
"""Load terminal tab options"""
options = self._application.options.section('terminal')
self._checkbox_scrollba... | Python | 1 |
ern "C" fn __aeabi_memset4(dst: *mut u8, n: usize, c: i32) {
memset(dst, c, n);
}
#[no_mangle]
pub unsafe extern "C" fn __aeabi_memset8(dst: *mut u8, n: usize, c: i32) {
memset(dst, c, n);
}
#[no_mangle]
pub unsafe extern "C" fn __aeabi_memclr(dst: *mut u8, n: usize) {
__aeabi_memset(dst, n, 0);
}
#[no_m... | Rust | 0 |
rerun-if-changed={}", path.display());
if env.check(&path)? {
supports(name.to_str().expect("valid feature name"));
}
}
}
match env.target_os.as_str() {
"linux" => {
supports("gso");
supports("mtu_disc");
supports("pkti... | Rust | 0 |
// NOTE: Links to other types in rustdoc are not implemented
// yet,
// [see](https://internals.rust-lang.org/t/rustdoc-link-to-other-types-from-doc-comments/968).
/// Tries to connect on all available backends in order.
///
/// Possible errors:
///
/// - `ffi::enums::SioError::Invalid`
... | Rust | 0 |
import os
import argparse
import numpy as np
# Args
parser = argparse.ArgumentParser(description='lauch the sddmm benchmarks')
parser.add_argument('--start', type=int, default=0, help="the starting benchmark to run")
parser.add_argument('--end', type=int, default=1130, help="the ending benchmark to run")
parser.add_a... | Python | 1 |
"""Adapter implementations for external services - implements core interfaces."""
# src/adapters/llm_adapter.py
from typing import List
import httpx
import json
from src.core.models import SearchQuery, ILLMService
from src.utils.logger import setup_logger
logger = setup_logger(__name__)
class VLLMAdapter(ILLMServic... | Python | 1 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from allauth.socialaccount.tests import OAuth2TestsMixin
from allauth.tests import MockedResponse, TestCase
from .provider import StripeProvider
class StripeTests(OAuth2TestsMixin, TestCase):
provider_id = StripeProvider.id
def get_mocked_resp... | Python | 1 |
// right of `fby`).
//
// When calling another node, we borrow a mutable reference to the call memory field. This is
// possible because we have a mutable reference to our own memory. We provide this "sub-reference"
// to the callee.
use std::collections::HashMap;
use std::io::{Write, Result};
use crate::nast::*;
use... | Rust | 0 |
) -> ::aya_bpf_cty::c_int = ::core::mem::transmute(146usize);
fun(map, inode)
}
pub unsafe fn bpf_d_path(
path: *mut path,
buf: *mut ::aya_bpf_cty::c_char,
sz: __u32,
) -> ::aya_bpf_cty::c_long {
let fun: unsafe extern "C" fn(
path: *mut path,
buf: *mut ::aya_bpf_cty::c_char,
... | Rust | 0 |
from fontTools import ttLib
superclass = ttLib.getTableClass("hmtx")
class table__v_m_t_x(superclass):
headerTag = "vhea"
advanceName = "height"
sideBearingName = "tsb"
numberOfMetricsName = "numberOfVMetrics"
| Python | 1 |
were not found!'
'\'use_images\' switched off. Please check if parameter \'enable\' for analyzer'
'is set to True')
use_images = False
# Collect average embeddings
if isinstance(track.f_avg.avg, int):
contin... | Python | 1 |
,_cs.GLuint)
def glBindBufferBase(target,index,buffer):pass
@_f
@_p.types(None,_cs.GLenum,_cs.GLuint,_cs.GLuint,_cs.GLintptr,_cs.GLsizeiptr)
def glBindBufferRange(target,index,buffer,offset,size):pass
@_f
@_p.types(None,_cs.GLenum,_cs.GLenum,_cs.GLintptr,_cs.GLintptr,_cs.GLsizeiptr)
def glCopyBufferSubData(readTarget,w... | Python | 1 |
# faqat siz aytgan oqimga mos UZ matnlar
UZ = {
"choose_lang": "Iltimos, tilni tanlang:",
"hello": (
"👋 Salom! Men — MoliyaUz, sizning shaxsiy moliyaviy yordamchingizman.\n"
"Daromad va xarajatlaringizni hisoblashda, maqsadlar qo‘yishda va moliyangizni boshqarishda yordam beraman.\n\n"
... | Python | 1 |
anim_num = 5;
}
_ => {}
}
self.vel_y += 0x40;
self.vel_x = clamp(self.vel_x, -0x400, 0x400);
if self.vel_y > 0x5ff {
self.vel_y = 0x5ff;
}
self.x += self.vel_x;
self.y += self.vel_y;
if self.direction == Direction::... | Rust | 0 |
import html
import re
from collections import defaultdict
from typing import List, Any
from ..constants import MAX_INPUT_LENGTH, NUMBER_OF_SOURCES_DISPLAY
def sanitize_text(text: str) -> str:
"""
Sanitize user input or model output to prevent injection attacks or XSS.
- Escapes HTML characters to avoid ... | Python | 1 |
import xml.etree.ElementTree as ET
from .utils import shortNameFromPath
from systemFiles import ES_GAMES_METADATA
from utils.logger import get_logger
eslog = get_logger(__name__)
def getGamesMetaData(system, rom):
# load the database
tree = ET.parse(ES_GAMES_METADATA)
root = tree.getroot()
game = sho... | Python | 1 |
rmula2, data=data,
exposure=data['pyears'].values)
mod.fit()
constraints = 'C(smokes)[T.1]:C(agecat)[3] = C(smokes)[T.1]:C(agec`at)[4]'
mgr = FormulaManager()
lc = mgr.get_linear_constraints(mod.exog_names).linear_constraint(constraints)
R, q = lc.coefs, lc.constant... | Python | 1 |
"""
uritemplate
===========
URI templates implemented as close to :rfc:`6570` as possible
See http://uritemplate.rtfd.org/ for documentation
:copyright:
(c) 2013 Ian Stapleton Cordasco
:license:
Modified BSD Apache License (Version 2.0), see LICENSE for more details
and either LICENSE.BSD or LICENSE.APA... | Python | 1 |
,
CONVERT('TEXT', DATEADD('MONTH', -1, 981158400), '%Y-%m-%d'),
CONVERT('TEXT', DATEADD('MONTH', -13, 981158400), '%Y-%m-%d'),
CONVERT('TEXT', DATEADD('YEAR', -1, 981158400), '%Y-%m-%d')
)" => unnamed_0 = Str, unnamed_1 = Str, unnamed_2 = Str, unnamed_3 = Str, unnamed_4 = Str, unnamed_5 = Str, u... | Rust | 0 |
ent(_: HttpRequest) -> HttpResponse { HttpResponse::Ok().finish() }
absent(TestRequest::get().to_http_request()).await.expect_body_absent();
}
#[should_panic(expected = "expected no response body but a response body was present")]
#[actix_rt::test]
async fn result_expect_body_absent_should_fail... | Rust | 0 |
r_connection_failure[idx]
val_bit = a_bit * c_bit * conn_bit
val_actuator_bits.append(val_bit)
if sum(val_actuator_bits) > 0:
val_actuators.append(1)
else:
val_actuators.append(0)
# print("Val actuators: ", val_actuators)
... | Python | 1 |
!("article_{}", article_id)))
.collect();
let key_bytes: Vec<_> = keys.iter().map(|k| k.1.as_bytes()).collect();
let mut rows = 0;
let mut misses = Vec::with_capacity(ids.len());
let vals = self.mem.get_multi(&key_bytes[..]).unwrap();
for &(key, ref kstr) in &keys {
... | Rust | 0 |
"""Реализуйте класс DefaultObject. При создании экземпляра класс должен принимать один именованный аргумент default, имеющий значение по умолчанию None, а после произвольное количество именованных аргументов. Аргументы, передаваемые после default, должны устанавливаться создаваемому экземпляру в качестве атрибутов.
Пр... | Python | 1 |
reg(off.id.as_phys_reg());
let r4 = phys_reg_to_dynasm_reg(inst.operand[1].as_register().id.as_phys_reg());
match i2 {
4 => dynasm!(self.asm; add DWORD [Rq(r0) + m1 + 4*Rq(r3)], Rd(r4)),
_ => unimplemented!(),
}
}
... | Rust | 0 |
0 as u8; 128];
while !bela_app.should_stop() {
let event = monome.poll();
match event {
Some(e) => {
seq.input(e);
}
_ => {
println!("nothing.");
}
}
seq.main_thread_work();
seq.render(&mut grid)... | Rust | 0 |
_phantom: PhantomData,
}
}
}
use std::ffi::CString;
pub type MyCallback=extern fn(*const u8) -> i32;
#[repr(C)]
pub struct Fruit {
pub price:i64,
pub call_back: extern fn(*const u8) -> i32,
}
impl Fruit {
pub fn show(&mut self)
{
println!("fruit show {}", self.price);
}
}
#[n... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.