text string | label_name string | labels int64 |
|---|---|---|
import sys
import os
import traceback
import binding
def test():
# cross_assign
assert binding.attr == 1234
assert binding.attr2 == 1234
# c_function_callback
def myfunc(val):
return val
binding.func_1(1, myfunc)
binding.func_4(1,2,2,2,myfunc, 3,3)
# array
A = binding.A
... | Python | 1 |
oup(0), '')
m = re.search(r'\(([^()]+)\)', matched, re.U)
if m:
aclass = m.group(1)
matched = matched.replace(m.group(0), '')
m = re.search(r'([(]+)', matched)
if m:
style.append("padding-left:{0}em".format(len(m.group(1))))
matched = matched.replace(m.group(0), '')
... | Python | 1 |
value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Reader of field `GPIO_FUNC57_IN_INV_SEL`"]
pub type GPIO_FUNC57_IN_INV_SEL_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `GPIO_FUNC57_IN_INV_SEL`"]
pub struct GPIO_FUNC57_IN_INV_SEL_W<'a> {
w: &'a mut W,
}
impl<'a> GPIO_FUNC57_IN_INV_SEL_W<'a> ... | Rust | 0 |
match &variant.fields {
Fields::Unnamed(_) => {
// println!("unamed");
variant_expr.push(quote! {
#name::#id(val) => val.write_size(version),
});
},
_ => {},
}
}
if variant_ex... | Rust | 0 |
[0] <= pair[1])
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn has_double_digits() {
assert!(122345usize.has_double_digits());
}
#[test]
fn misses_double_digits() {
assert!(!123456usize.has_double_digits());
}
#[test]
fn is_six_digits_long() {
as... | Rust | 0 |
!")
}
assert_eq!(*role, "camera".to_string());
},
_ => panic!("Member was not expected Member-variant")
}
match osm.relations[&77994].members[1] {
osm::Member::Node(ref ref_id, ref role) => {
match *ref_id {
osm::UnresolvedReference::N... | Rust | 0 |
cb(img, keys, FSCB_LEN_PAGES=2):
global SYSTEM_BASIS
fscb = None
fscb_count = 0
if SYSTEM_BASIS in keys:
key = keys[SYSTEM_BASIS]
pages = [img[i:i+4096] for i in range(0, len(img), 4096)]
space_update = []
fscb_start = None
pg = 0
for page in pages:
... | Python | 1 |
path, error));
}
// Wait for a connection on the unix socket (connection from zxdb).
let (socket, _) = listener.accept().await?;
let (mut zxdb_rx, mut zxdb_tx) = socket.split();
let mut debug_agent_rx = rx.borrow_mut();
let mut debug_agent_tx = tx.borrow_mut();
// Reading from zxdb (using... | Rust | 0 |
\u{13b}"),
("midot;", "\u{13f}"),
("strok;", "\u{141}"),
("Jcy;", "\u{409}"),
("ang;", "\u{27ea}"),
("arr;", "\u{219e}"),
("opf;", "\u{1d543}"),
("scr;", "\u{2112}"),
... | Rust | 0 |
"""RetinaFPN in PyTorch."""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models.resnet import *
class FPN(nn.Module):
def __init__(self, resnet_size: int):
super().__init__()
self.resnet_size = resnet_size
assert self.resnet_size in [18, 34, 50, 101... | Python | 1 |
utimensat(AT_FDCWD, to.as_ptr(), × as *const timespec, 0)
};
if ret == -1 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
#[cfg(unix)]
pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
let n = fs::copy(from, to)?;
copy_timestamps(from, to)?;
Ok(n)
}
///... | Rust | 0 |
A reference to the [`VirtualMachine`]'s [`Stack`].
pub(crate) fn stack(&self) -> &Stack {
&self.stack
}
pub(crate) fn modules(&self) -> &[Gc<Module>] {
&self.modules
}
/// The base pointer, or the value which indicates where in the stack values
/// pertaining to the currently ... | Rust | 0 |
y_like + opt_out
array_like += opt_out
with assert_raises(TypeError):
array_like - opt_out
with assert_raises(TypeError):
opt_out - array_like
def test_subclass(self):
class SubArrayLike(ArrayLike):
"""Should take precedence over ArrayLike.""... | Python | 1 |
assert_eq!(v[1], 0x3FFFF);
assert_eq!(v[2], 0);
assert_eq!(v[3], 0);
assert_eq!(v[4], 0);
assert_eq!(v[5], 0);
assert_eq!(v[6], 0);
assert_eq!(v[7], 0);
}
}
<filename>atuin-server/src/handlers/history.rs
use warp::{http::StatusCode, Reply};
use crate::databa... | Rust | 0 |
lue of the field is `FWMDE0_0`"]
#[inline(always)]
pub fn is_fwmde0_0(&self) -> bool {
**self == FWMDE0_A::FWMDE0_0
}
#[doc = "Checks if the value of the field is `FWMDE0_1`"]
#[inline(always)]
pub fn is_fwmde0_1(&self) -> bool {
**self == FWMDE0_A::FWMDE0_1
}
}
impl core::op... | Rust | 0 |
#!/usr/bin/env python3
"""
X Bookmarks to Obsidian 설치 스크립트
"""
import os
import sys
import subprocess
import json
from pathlib import Path
def install_requirements():
"""필요한 패키지 설치"""
print("필요한 Python 패키지를 설치합니다...")
try:
subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", "requi... | Python | 1 |
named_file.as_path().to_str().unwrap(),
1,
);
assert!(result.is_err());
assert!(format!("{:?}", result).contains("CgroupInheritFromParent"));
let child_file = dir2.as_path().join(named_file.as_path().to_str().unwrap());
// 3. If parent file exists and is not empty... | Rust | 0 |
: ArrowJson = serde_json::from_str(&s).unwrap();
arrow_json
}
#[test]
fn track_union_nested_dict() {
let inner: DictionaryArray<Int32Type> = vec!["a", "b", "a"].into_iter().collect();
let array = Arc::new(inner) as ArrayRef;
// Dict field with id 2
let dctfield =
... | Rust | 0 |
/// Err(Error::RequiredFileFromSubsystemNonexistant {
/// subsys: "init",
/// fname: "$TEMP/ops-add_feeds-verify-1/tokens.toml".to_string(),
/// }));
/// ```
pub fn verify(config_dir: &(String, PathBuf)) -> Result<(PathBuf, PathBuf), Error> {
let token... | Rust | 0 |
sparse image block dimensions for non-tail mip levels."]
pub const ALIGNED_MIP_SIZE: Self = Self(0b10);
#[doc = "Image uses a non-standard sparse image block dimensions"]
pub const NONSTANDARD_BLOCK_SIZE: Self = Self(0b100);
}
#[repr(transparent)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)... | Rust | 0 |
# Code generated by Lark OpenAPI.
from typing import Any, Optional, Union, Dict, List, Set, IO, Callable, Type
from lark_oapi.core.construct import init
class RejectApprovalTaskRequestBody(object):
_types = {
"user_id": str,
"opinion": str,
}
def __init__(self, d=None):
self.user... | Python | 1 |
get better error messages if our code ever panics.
//
// For more details see
// https://github.com/rustwasm/console_error_panic_hook#readme
console_error_panic_hook::set_once();
}
// A macro to provide `println!(..)`-style syntax for `console.log` logging.
#[cfg(target_arch = "wasm32")]
#[macro_export... | Rust | 0 |
SIGTTOU, SigHandler::SigIgn).unwrap();
// Ignoring sigchild will mess up waitpid and cause Command::spawn to panic under some conditions.
//signal::signal(Signal::SIGCHLD, SigHandler::SigIgn).unwrap();
}
}
pub fn test_clear_sigint() -> bool {
SIG_INT.swap(false, Ordering::Relaxed)
}
<filename>p... | Rust | 0 |
extents, eps) {
return false;
}
true
}
}
pub fn create_property_set<'a, I>(polylines: I, invert_area: bool) -> Vec<PlineProperties>
where
I: IntoIterator<Item = &'a Polyline>,
{
polylines
.into_iter()
.map(|pl| PlineProperties::from_pline(pl, invert_area))
... | Rust | 0 |
(AtomicUsize::new(0));
let inner = Arc::new(TestWake(test.clone()));
let waker = to_waker(inner.clone());
assert_eq!(Arc::strong_count(&inner), 2);
assert_eq!(test.load(SeqCst), 0);
let other = waker.clone();
assert_eq!(Arc::strong_count(&inner), 3);
drop(waker);
... | Rust | 0 |
type PCDAccumulator = DLogItemAccumulator<G, D>;
type PCDVerifierKey = SimpleMarlinPCDVerifierKey<'a, G, D>;
fn succinct_verify(
&self,
vk: &Self::PCDVerifierKey,
) -> Result<<Self::PCDAccumulator as ItemAccumulator>::Item, PCDError> {
let succinct_time = start_timer!(|| "Marlin s... | Rust | 0 |
# Copyright (C) 2008-today The SG++ project
# This file is part of the SG++ project. For conditions of distribution and
# use, please see the copyright notice provided with SG++ or at
# sgpp.sparsegrids.org
import numpy as np
from pysgpp import HashGridPoint
from pysgpp.extensions.datadriven.uq.operations import crea... | Python | 1 |
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | Python | 1 |
label = batch.y[batch.room_mask], batch.y[batch.object_mask]
mask = (
batch[mask_name][batch.room_mask],
batch[mask_name][batch.object_mask],
)
else:
if self... | Python | 1 |
sh)
fnmr = 1.0 * (num_query - num_acc) / num_query
if fmr == 1e-3:
sym = ' ' if thresh >= 0 else ''
line = 'FNMR = {:.10f} : FMR = {:.10f} : THRESHOLD = {}{:.10f}'.format(fnmr, fmr, sym, thresh)
print(line)
fnmrs_list.append(fn... | Python | 1 |
street: String,
/// Postalcode input column (0-indexed or header name)
///
/// Postal code (input) column in the CSV file, specified either as 0-indexed number or as the text of the column header
#[structopt(short, long, display_order(51))]
postalcode: String,
/// City input column (0-index... | Rust | 0 |
Vector2::new(0.2, 0.2),
Vector2::new(0.6, 0.6),
1,
)
.unwrap();
let rect_1_intersector = rect_1.intersector();
let rect_2_intersector = rect_2.intersector();
let rect_3_intersector = rect_3.intersector();
assert_eq!(
rect_1_inter... | Rust | 0 |
import numpy as np
from nlaugmenter.interfaces.SentenceOperation import SentenceAndTargetOperation
from nlaugmenter.tasks.TaskTypes import TaskType
"""
Adds a positive labelled emoji as well as a positive emoteicon for positive sentences and vice versa.
And neutral smiley for unlabelled and neutral sentences.
Since I... | Python | 1 |
ities, &'static str> {
let mut res = AsyncExternalities { extensions: Default::default() };
let mut ext = &mut res as &mut dyn Externalities;
ext.register_extension::<TaskExecutorExt>(TaskExecutorExt(scheduler.clone()))
.map_err(|_| "Failed to register task executor extension.")?;
Ok(res)
}
impl AsyncExternalit... | Rust | 0 |
"""
Set of general purpose utility functions for easier interfacing with Python API
"""
import inspect
from copy import deepcopy
def get_class_init_kwargs(cls):
"""
Helper function to return a list of all valid keyword arguments (excluding "self") for the given @cls class.
Args:
cls (object): Cla... | Python | 1 |
pe_blend::Data<R>>,
}
pub struct Pipelines<R> where R : gfx::Resources {
pub opaque: OpaquePipeline<R>,
pub blend: BlendPipeline<R>,
}
pub struct Renderer<R, C, F, D> where R : gfx::Resources,
C : gfx::CommandBuffer<R>,
F : gfx::Facto... | Rust | 0 |
Ident;
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::TokenStreamExt;
use core_extensions::{IteratorExt, SelfOps};
#[doc(hidden)]
pub mod reflection;
mod attribute_parsing;
mod common_tokens;
mod generic_params;
mod nonexhaustive;
mod prefix_types;
mod repr_attrs;
mod tl_function;
mod tl_f... | Rust | 0 |
var("MGIT_PARALLEL") {
Ok(val) => val.parse().unwrap_or(4),
Err(_) => num_cpus::get() * 8,
};
let (tx, rx) = channel();
fork(pool_size, &tx).unwrap();
drop(tx);
join(rx).unwrap()
}
fn fork(pool_size: usize, tx: &Sender<(PathBuf, GitStatus, String)>) -> Result<(), Error> {
let m... | Rust | 0 |
info.inet_server_addr).as_str(),
);
span.record("net.peer.port", &info.inet_server_port);
Ok(InstrumentedPgConnection { inner: conn, info })
}
#[doc(hidden)]
#[instrument(
fields(
db.name=%self.info.current_database,
db.system="postgresql",
... | Rust | 0 |
Difficulty(difficulty.as_u64()),
MmrNodeCount(node_count) => ProtoNodeCommsResponse::MmrNodeCount(node_count),
MmrNodes(added, deleted) => ProtoNodeCommsResponse::MmrNodes(ProtoMmrNodes { added, deleted }),
}
}
}
//---------------------------------- Collection impls ----------------... | Rust | 0 |
from src.model import drone_dynamics
import matplotlib.pyplot as plt
import numpy as np
# define simulation parameters
dt = 0.1
t_final = 20.0 # seconds
time_steps = int(t_final / dt)
time = np.linspace(0, t_final, time_steps)
Q = np.eye(12)
parms = {"Q": Q, "R": np.eye(4), "N": 10, "Qf": Q, "dynamic": True}
drone_m... | Python | 1 |
that is called in this transaction.
pub callee: AccountId,
/// The selector bytes that identifies the function of the callee that should be called.
pub selector: [u8; 4],
/// The SCALE encoded parameters that are passed to the called function.
pub input: Vec<u8>,
/// The amount of chain balance ... | Rust | 0 |
:load_kernel(hello world)", |b| {
b.iter(|| unsafe {
vm.load_kernel().unwrap();
})
});
}
criterion_group!(load_kernel_benchmark_group, load_vm_hello_world);
<gh_stars>10-100
use std::env::args;
use std::time::Instant;
fn main() {
let now = Instant::now();
let output = run(&args().nth(1).expect("Please... | Rust | 0 |
n null() -> Self {
Self(0)
}
pub const unsafe fn from_raw(i: isize) -> Self {
Self(i)
}
pub const fn into_inner(self) -> isize {
self.0
}
pub fn is_null(self) -> bool {
self.0 == 0
}
}
unsafe impl Send for $name {}
unsafe impl Sync fo... | Rust | 0 |
eate_attestation(
provider: AttestationProvider | None,
entra_resource: str | None = None,
token: str | None = None,
) -> WorkloadIdentityAttestation:
"""Entry point to create an attestation using the given provider.
If the provider is None, this will try to auto-detect a credential from the runtim... | Python | 1 |
,
AttributePlace::Function => !0,
}
}
}
/// Matches lumen::Attribute::AttrKind in Attributes.cpp
/// Semantically a subset of the C++ enum llvm::Attribute::AttrKind,
/// though it is not ABI compatible (since it's a C++ enum)
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub enum Attribute {
Alw... | Rust | 0 |
while words.peek().is_some() {
if words.peek() == Some(&"no") { break; }
contain.push((
words.next().map(|x| x.parse::<i32>().expect("invalid number")).unwrap(),
format!("{} {}", words.next().unwrap(), words.next().unwrap()),
));
... | Rust | 0 |
ew(family: __u8, protocol: __u8) -> Result<Self, Error> {
let socket = socket(AF_NETLINK as i32, SOCK_DGRAM, NETLINK_INET_DIAG);
send_diag_msg(socket, family, protocol)?;
Ok(NetlinkIterator {
protocol,
socket,
recv_buf: [0u8; SOCKET_BUFFER_SIZE as usize],
... | Rust | 0 |
lOrder.PostOrder))
# Set current_match of Dictation expansions in the given expansion to
# current_match values of their respective counterparts in the sequence.
for e1, e2 in zip(dictation_in_seq, dictation_in_exp):
assert isinstance(e1, Dictation) and isinstance(e2, Dictation)
... | Python | 1 |
}
}
}
impl std::fmt::Display for Value {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Value::Null => write!(f, "NULL"),
Value::Int(x) => write!(f, "{}", x),
Value::Float(x) => write!(f, "{:.2}", x.0),
Value::Bool... | Rust | 0 |
d_x = workgroup_id % num_workgroup_x;
let workgroup_id_y = (workgroup_id / num_workgroup_x) % num_workgroup_y;
let workgroup_id_z =
(workgroup_id / (num_workgroup_x * num_workgroup_y)) % num_workgroup_z;
let mut setup_data = vec![];
fo... | Rust | 0 |
non-normalized scalar value computed from a fieldValue tuple.
vec2 texCoord; // Used for color lookup.
eyeNormal = normalize(vertexNormalMC); // Perspective transform requires re-normalization.
lightVector = normalize(LightVector0);
// Debug: color by normal vector (offset to avoid black):
// vec3 tn = 0.2... | Python | 1 |
contacts = {
"dad" : "9815272626",
"mom":"9872758318",
"japjot" : "8437941646",
"tusit" : "9779715342",
"Tapu" : "9458904471",
"shubham":"8847535118",
"rohan":"8847565660",
"mridul":"6284056155",
"maanit":"9729881170",
"krish":"7717613669",
"khatri":"7976284317",
"jasvir":"8146561629",
"jaivee... | Python | 1 |
# Author: Mark Blakeney, Feb 2024.
"Uninstall one, or more, or all applications."
from __future__ import annotations
from argparse import ArgumentParser, Namespace
from .. import utils
aliases = ['remove']
def _uninstall(args: Namespace, pkgname: str) -> str | None:
"Uninstall given package"
pkgname, vdir... | Python | 1 |
struct DataStructField {
pub info: DataStructFieldInfo,
pub name: InternedString,
pub value: Item,
}
impl DataStructField {
pub fn new(info: DataStructFieldInfo, name: InternedString, value: Item) -> Self {
DataStructField { info, name, value }
}
}
#[derive(Debug, Clone, Serialize, Deseria... | Rust | 0 |
_first_block_lect_normal(&mut testkit);
let funding_tx = FundingTx::from_hex(
"0200000001a4f68040d03b137746fd10351c163ed4e826fd70d3db9c6\
457c63a5e8571a47c010000006a47304402202d09a52acc5b9a40c1d8\
9dc39c877c394b7b6804cda2bd6549bb7c66b9a1b73b02206b8a9d2ff\
830c639050b96f97461d0f83... | Rust | 0 |
metrics_cli: MetricsEnabled,
) -> Result<Option<Vec<FrameSummary>>, CliError> {
let y4m_details = source.input.get_video_details();
let mut frame_summaries = Vec::new();
let mut pass1file = pass1file;
let mut pass2file = pass2file;
// Submit first pass data to pass 2.
if let Some(passfile) = pass2file.a... | Rust | 0 |
ative_data_set = topology_data_set.clone();
let mut timestamp_interval = TimestampInterval::new(interval_duration);
let mut output = RecordingWriter::new(output_writer);
while let Some(data_set) = dsr.read_data_set()? {
let timestamp = data_set.timestamp;
let local_timestamp = timestamp.w... | Rust | 0 |
// ___12.34
println!("{}", format!("{:>08}", 12.34)); // 00012.34
println!("{}", format!("{:>8}", -12.34)); // __-12.34
println!("{}", format!("{:>08}", -12.34)); // -0012.34
println!("{}", format!("{:.2}", 12.34567)); // 12.35
}
<reponame>niwis/snitch
// Copyright 2020 ETH Zurich and University of Bo... | Rust | 0 |
o_button, redo_button=self._redo_button))
def _create_clip_launch(self):
self._clip_launch = ClipLaunchComponent(name=u'Clip_Launch', is_enabled=False, layer=Layer(clip_launch_button=self._clip_launch_button, track_stop_button=self._track_stop_button))
def _create_clip_launch_background(self):
... | Python | 1 |
\xd5\xdb\xe7\xaf\xa4\xb5P\x83|\xb6\xd3\xa6\xb6z\xef\
\xe4\x96\x9b>\xc6\xefQ\xb9\xba\x0a\xf7\x17\x122\xa0m\
\xfb\xa48 e\x9b\xe5a\x93\x83\x80@'\xdb\x18\xc8\
\xe7'\xd5\xa1d\x94\x07\x05\x80?(b\x1f\xeb\xce\xd3\
\xf9\xf1\xc69\xc0\x03!.5+\xd4\xfd\xd22\xa1P\
\x09\x19#i\xc9\x0cF\x00Q\xc1,288 \x8c\
\x80\xba\x0e\x84\xba\x9e\xa8\x... | Python | 1 |
tch1:
line_number = int(match1.group(1))
result = str(line_number)
app_route_name = "Line "+result
else:
origin_app_route_name = re.sub(r'\(.*?\)', '', origin_app_route_name)
... | Python | 1 |
}
);
}
}
<filename>contract/app-nft/tests/sim/main.rs
use near_sdk_sim::{call, view, deploy, init_simulator, ContractAccount, UserAccount, to_yocto, DEFAULT_GAS};
use near_contract_standards::non_fungible_token::metadata::TokenMetadata;
use near_contract_standards::non_fungible_token::NonFungibleToken... | Rust | 0 |
"""Test Problem Report Message."""
from unittest import TestCase, mock
import pytest
from ......messaging.models.base import BaseModelError
from .. import problem_report as test_module
from ..problem_report import (
OOBProblemReport,
OOBProblemReportSchema,
ProblemReportReason,
ValidationError,
)
c... | Python | 1 |
import numpy as np
import pint
ureg = pint.UnitRegistry()
Q_ = ureg.Quantity
# -------------------- thermal expansion tolerance --------------------
# inputs
diameter_chamber_with_ribs = Q_(0.0315, 'meter').magnitude
coefficient_of_thermal_expansion = Q_(24.0*(10**-6), '1/kelvin').magnitude
throat_inner_wall_temp = Q... | Python | 1 |
# Light наследява Device, има private атрибут __brightness с @property и @setter
from device import Device
class Light(Device):
def __init__(self, status=bool, brightness=int):
super().__init__(status)
self.__brightness = brightness
@property
def brightness(self):
ret... | Python | 1 |
import torch
import pytest
from acetn.ipeps import Ipeps
from acetn.renormalization.ctmrg import ctmrg
@pytest.fixture
def ipeps():
dims = {'phys': 2, 'bond': 3, 'chi': 9}
dtype = torch.float64
device = torch.device('cpu')
ipeps_config = {
'dtype': dtype,
'device': device,
'TN'... | Python | 1 |
EX_Vpmovq2m_kr_zmm
0x00,// Invalid
// 58 = 0x3A
0x08,// MandatoryPrefix2
0x00,// Invalid
0x09,// VectorLength
0x29,// VkHW_3
0x4D,// XMM0
0x8D, 0x17,// EVEX_Vpminuw_xmm_k1z_xmm_xmmm128
0x04,// N16
0x29,// VkHW_3
0x6D,// YMM0
0x8E, 0x17,// EVEX_Vpminuw_ymm_k1z_ymm_ymmm256
0x05,// N... | Rust | 0 |
em(for_each)]
pub fn animate_entities(
anim: &mut Animate,
body_handle: &DefaultBodyHandle,
#[resource] time: &mut DeltaTime,
#[resource] bodies: &mut DefaultBodySet<f32>,
) {
let refresh_rate = 7.5;
let frame_length = Duration::from_secs_f32(1.0 / refresh_rate);
if time.instant.elapsed() >... | Rust | 0 |
)
_create_event(
event="step three",
distinct_id="user b",
team=self.team,
timestamp="2021-06-09 13:39:00",
)
_create_event(
event="step one",
distinct_id="user c",
team=self.team,
timestamp="2021-0... | Python | 1 |
#!/usr/bin/python3
"""
fuction used to add integers
"""
def add_integer(a, b=98):
"""
adds integers
Parameters:
a (int or float): first number
b (int or float): second number
Returns:
int: sum of a and b
Raises:
TypeError: if a or b are neither int nor float
... | Python | 1 |
include_bytes!("fontawesome/webfonts/fa-brands-400.woff");
pub static FONT_AWESOME_WOFF2_BRANDS: &[u8] =
include_bytes!("fontawesome/webfonts/fa-brands-400.woff2");
pub static FONT_AWESOME_EOT_900: &[u8] = include_bytes!("fontawesome/webfonts/fa-solid-900.eot");
pub static FONT_AWESOME_SVG_900: &[u8] = include_byt... | Rust | 0 |
from keras.models import Sequential, Model
from keras.layers import Dense, Dropout, Flatten, Reshape, Input
from keras.layers import Conv2D, MaxPooling2D, Activation, concatenate
from keras import applications
class Network:
def __init__(self, stride_scale = 0):
# if stride_scale == 0:
# self.... | Python | 1 |
#!/usr/bin/env python3
"""
Phoenix Prompt Management - Full Integration Test
Tests Phoenix PromptVersion creation, retrieval, and observability features.
"""
import sys
import os
from pathlib import Path
# Add src to path
src_path = Path(__file__).parent.parent / "src"
sys.path.insert(0, str(src_path))
from rag_sear... | Python | 1 |
format!("{}.{}.{}.{}", major, minor, patch, build));
}
}
}
}
}
JsValue::NULL
}
use crate::cx::*;
#[derive(Clone)]
pub struct Blit {
pub shader: Shader,
pub min_x: f32,
pub min_y: f32,
pub max_x: f32,
pub max_y: f32,
pub alpha: f32... | Rust | 0 |
parse
pub fn parse_iter<'a, 'r>(&'r self, text: &'a str) -> ParseIter<'a, 'r> {
ParseIter::new(text, self.version.as_ref(), self.prefix.as_ref())
}
}
/// An iterator over release notes.
///
/// This type is returned by [`parse_iter`] function or [`Parser::parse_iter`] method.
#[allow(missing_debug_impl... | Rust | 0 |
table.add_row(item["timestamp"], item["message"], ", ".join(item["files"]))
console.print(table)
else:
console.print("[green]No queued commits[/green]")
def check_push_status(repo):
origin = repo.remote(name="origin")
try:
repo.git.fetch()
except:
console.print("[red]... | Python | 1 |
}
}
use std::collections::HashSet;
use std::hash::{BuildHasher, Hash};
use std::pin::Pin;
use crate::prelude::*;
use crate::stream::{self, IntoStream};
impl<T, H> stream::Extend<T> for HashSet<T, H>
where
T: Eq + Hash,
H: BuildHasher + Default,
{
fn extend<'a, S: IntoStream<Item = T> + 'a>(
... | Rust | 0 |
mi_mut: MOUSEINPUT,
ki ki_mut: KEYBDINPUT,
hi hi_mut: HARDWAREINPUT,
}}
STRUCT!{struct INPUT {
type_: DWORD,
u: INPUT_u,
}}
pub type PINPUT = *mut INPUT;
pub type LPINPUT = *mut INPUT;
extern "system" {
pub fn SendInput(
cInputs: UINT,
pInputs: LPINPUT,
cbSize: c_int,
) ... | Rust | 0 |
pub where_clauses: Vec<QuantifiedWhereClause>,
pub assoc_ty_values: Vec<AssocTyValue>,
pub impl_type: ImplType,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum ImplType {
Local,
External,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct AssocTyValue {
pub name: Identifier,
pub variabl... | Rust | 0 |
n_cutout.{}", ext));
set.insert(format!("gbuffers_terrain_cutout_mip.{}", ext));
set.insert(format!("gbuffers_terrain_solid.{}", ext));
set.insert(format!("gbuffers_textured.{}", ext));
set.insert(format!("gbuffers_textured_lit.{}", ext));
set.insert(format!("... | Rust | 0 |
ool,
}
impl<T: ?Sized> fmt::Debug for Context<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Context").finish()
}
}
impl<'cx, T: ?Sized> Context<'cx, T> {
pub(crate) fn new(header: &'cx fuse_in_header, io: &'cx mut T) -> Self {
Self {
header... | Rust | 0 |
{
Delay::Unknown
}
}
impl Delay {
pub fn map<T, F>(self, func: F) -> Option<T>
where
F: FnOnce(Duration) -> T,
{
if let Delay::Some(d) = self {
Some(func(d))
} else {
None
}
}
}
impl From<Option<Duration>> for Delay {
fn from(d: ... | Rust | 0 |
if key == 'y':
cy += posy
elif key == 'top':
cy += posy - h
elif key == 'center_y':
cy += posy - (h / 2.)
yield len_children - i - 1, x, cy, w, h
x += w + spacin... | Python | 1 |
# /208. Implement Trie (Prefix Tree)
class TrieNode:
def __init__(self):
self.childrens = {}
self.endOfWord = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
cur = self.root
for c in word:
if c... | Python | 1 |
e
},
28usize,
concat!(
"Offset of field: ",
stringify!(cudnnConvolutionBwdDataAlgoPerf_t),
"::",
stringify!(mathType)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<cudnnConvolutionBwdDataAlgoPerf_t>())).reserv... | Rust | 0 |
pattern::key_service_authenticate(driver, audit, &auth)
.map_err(GrpcMethodError::Unauthorised)?;
// Unsafely decode token to get user identifier, used to read key for safe token decode.
let (user_id, token_type) = Jwt::decode_unsafe_user(&req.token, service.id)
... | Rust | 0 |
[cfg(feature = "dim2")]
{
if nonlinear_strain {
let j = grad_tr + Matrix::identity();
let jjt = j * j.transpose();
let stress01 =
c_top_left * Vector::new(jjt.m11 - N::one(), jjt.m22 ... | Rust | 0 |
::Reference;
use crate::models::r5::ResourceList::ResourceList;
use serde_json::json;
use serde_json::value::Value;
use std::borrow::Cow;
/// Information about a medication that is used to support knowledge.
#[derive(Debug)]
pub struct MedicationKnowledge<'a> {
pub(crate) value: Cow<'a, Value>,
}
impl Medication... | Rust | 0 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: object_detection/protos/box_coder.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor... | Python | 1 |
pub trait DecodeBuffer<T> {
fn get_msg(&self, id: u32, buf: &[u8]) -> Result<T, String>;
fn get_signature(&self) -> u16;
}
pub struct Buffer<T: Clone> {
buffer: Vec<u8>,
queue: Vec<IncomeMessage<T>>,
}
#[allow(clippy::len_without_is_empty)]
#[allow(clippy::new_without_default)]
impl<T: Clone> Buffer<T... | Rust | 0 |
"""Base classes for all metrics"""
from abc import ABC, abstractmethod
from synthesis.synthesizers.utils import astype_categorical
COLOR_PALETTE = ['#393e46', '#ff5722', '#d72323']
class BaseMetric(ABC):
def __init__(self, labels=None, exclude_columns=None, astype_cat=True):
self.labels = labels or ['or... | Python | 1 |
matplotlib.pyplot as plt
def plot_with_labels(low_dim_embs, labels, figsize=(18, 18), second=5, saveable=True, name='tsne', fig_idx=9862):
assert low_dim_embs.shape[0] >= len(labels), "More labels than embeddings"
if saveable is False:
plt.ion()
plt.figure(fig_idx)
p... | Python | 1 |
), Some(unit_v2)) = (
v1.try_normalize(S::zero()),
v2.try_normalize(S::zero()))
{
let cross = unit_v1.cross(&unit_v2);
if let Some(axis) = Unit::try_from_value(cross, S::default_epsilon()) {
return Some(
Self::from_axis_angle... | Rust | 0 |
lb {
Invalidate,
NoInvalidate,
}
pub struct Mapper {
p4: Unique<PageTable<Level4>>,
}
impl Mapper {
const unsafe fn new() -> Self {
// The address points to the recursively mapped entry (511) in the P4 table, which we can
// use to access the P4 table itself.
// ... | Rust | 0 |
@property
def task_type_map(self):
return self._task_type_map
| Python | 1 |
import matplotlib.pyplot as plt
# Tentativa 1
def show_matriz(matriz):
for i in range(len(matriz)):
print(matriz[i])
print()
return
def plotar_matriz(matriz):
plt.imshow(matriz)
plt.colorbar()
plt.show()
# Exercício 1 e 2
def build_matriz(linhas, colunas):
matriz = []
for i in... | Python | 1 |
nTextType::Str => dna_decode_string(v),
PlainTextType::Int => dna_decode_integer(v).to_string(),
// _ => { panic! ("[!] Unexpected error matching intype")}
}
}
fn dna_decode_integer(input: Vec<u8>) -> u32 {
let mut out = 0 as u32;
let base: u32 = 4;
for (i, bit) in input.iter().enumera... | Rust | 0 |
let result1: HashSet<Vec<&usize>> = all_combinations::combinations_iter(&input).collect();
let mut result2: HashSet<Vec<&usize>> = HashSet::new();
for v in all_combinations::combinations_borrow(&input, Vec::new()) {
result2.insert(v);
}
assert_eq!(result1.len(), result2.len()); //65375
... | Rust | 0 |
]
impl ::core::clone::Clone for D3D11_VIDEO_DECODER_DESC {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Graphics_Direct3D11\"`*"]
pub struct D3D11_VIDEO_DECODER_EXTENSION {
pub Function: u32,
pub pPrivateInputData: *mut ::core::ffi::c_void,
pub Private... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.