text string | label_name string | labels int64 |
|---|---|---|
CFString, CFStringRef, __CFString},
};
use libc::c_char;
use crate::{bootstrap, get_infos, provider::AccountViewData};
enum FFIStatus {
Success = 1,
// Refine this in a real project
Error = 2,
}
#[no_mangle]
pub unsafe extern "C" fn ffi_bootstrap() -> FFIVoidResult {
match bootstrap() {
Ok(_)... | Rust | 0 |
r this row
gates.push(CircuitGate::create_poseidon(wires, coeffs));
}
// final (zero) gate that contains the output of poseidon
gates.push(CircuitGate::zero(first_and_last_row[1]));
//
(gates, last_row)
}
/// Checks if a witness verifies a poseidon gate
... | Rust | 0 |
def _set_gradient_checkpointing_new(self, module, value=False):
if hasattr(module, 'gradient_checkpointing'):
module.gradient_checkpointing = value
modules_with_gc_enabled[module.__class__.__name__] = True
| Python | 1 |
ns[column_latter].width = width
fill_header_column(_SimpleDayPageColumn.time.value, "Время", 13)
fill_header_column(_SimpleDayPageColumn.name.value, "Наименование", 80)
fill_header_column(_SimpleDayPageColumn.tag.value, "Трек", 30)
fill_header_column(_SimpleDayPageColumn.talk_type.value... | Python | 1 |
n frame C
## Define forces on each point of the system
R_C_hat = Px*A.x + Py*A.y + Pz*A.z
R_Cs = -m*g*A.z
forces = [(pC_hat, R_C_hat), (pCs, R_Cs)]
## Define kinematic differential equations
# let ui = omega_C_A & bi (i = 1, 2, 3)
# u4 = qd4, u5 = qd5
u_expr = [C.ang_vel_in(A) & uv for... | Python | 1 |
acesso = '12qw'
chance = ''
while chance != acesso:
chance = input | Python | 1 |
#!/usr/bin/env python3
import hashlib
import hmac
from math import ceil
tek_val1 = [0x12,
0x34,
0x56,
0x67,
0x78,
0x9A,
0xBC,
0xDE,
0xF1,
0x23,
0x45,
0x67,
0x89,
0xAB,
0xCD,
0xEF]
tek_val1 = bytearray(tek_val1)
# The following code was taken and modified from
# https://en.wikipedia.org/... | Python | 1 |
from typing import Dict, Any, Tuple
import re
DEFAULT_TASK = ("browser_search", {"query": "qualgent test"})
def plan_from_prompt(prompt: str) -> Tuple[str, Dict[str, Any]]:
p = (prompt or "").lower()
if "search" in p or "browse" in p or "google" in p:
parts = p.split("search for ")
query = par... | Python | 1 |
from typing import List
def quickselect(nums: List[int], k: int) -> int:
"""
the quickselect algorithm enables you to determine
the kth largest / smallest element in a list without
having to sort the entire list.
:param nums: list of numbers to be sorted
:param k: integer which denotes k
:... | Python | 1 |
.com/lemonrock/ucx/master/COPYRIGHT.
#[repr(C)]
pub struct uct_iface_attr
{
pub cap: uct_iface_attr__bindgen_ty_1,
pub device_addr_len: usize,
pub iface_addr_len: usize,
pub ep_addr_len: usize,
pub max_conn_priv: usize,
pub overhead: f64,
pub bandwidth: f64,
pub latency: uct_linear_growth_t,
pub priority: u8... | Rust | 0 |
from sentence_transformers import SentenceTransformer, util
import json
import pandas as pd
from collections import defaultdict
import torch
from tqdm import tqdm
import argparse
import os
# 创建参数解析器并添加参数
parser = argparse.ArgumentParser()
parser.add_argument('--model_path', default=None, type=str, required=True, help=... | Python | 1 |
Operator::Eval,
_ => unreachable!(),
}))];
for elem in pair.into_inner() {
elements.push(
build_expression(elem.clone(), source.clone())?
.with_source(SourcePosition::from_pair(&elem, &source)),
);
... | Rust | 0 |
ctional Divider Control Register"]
pub mod pfd_480_clr;
#[doc = "480MHz Clock (PLL3) Phase Fractional Divider Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_z... | Rust | 0 |
fn compile(src: &str) -> CompilerResult {
thread_local! {
static GRAMMAR: Grammar = Grammar::new();
}
let mut src = String::from(src);
if !src.ends_with('\n') {
src += "\n";
}
CompilerResult(GRAMMAR.with(|grammar| {
grammar
.parse(&src[..])
.map_e... | Rust | 0 |
# Script para calcular el % de uso de cada lenguaje
import os
import operator
def scan_dir(dir_path, challenges={}, languages={}, total=0, challenge_name=None, path_name=None) -> tuple:
for path in os.scandir(dir_path):
if path.is_dir():
if "Reto #" in path.name and path.name not in challenge... | Python | 1 |
self.ea.evaluator.eval(self.problem, pop)
pop_X = np.array([p.X for p in pop])
top_k_idx = range(len(pop_X))
elites = pop_X
else:
raise ValueError(f"Invalid model manage strategy: {self.model_manage}")
self.elites_idx = top_k_idx
return elites
... | Python | 1 |
t_frame() {
// The first (context) frame gets extra long scans, this test checks that.
let mut f = TestFixture::new();
let mut stack = Section::new();
stack.start().set_const(0x80000000);
let return_address1 = 0x50000100u32;
let return_address2 = 0x50000900u32;
let frame1_sp = Label::new();... | Rust | 0 |
ub mod common;
mod endpointfilters;
mod error;
pub mod identity;
mod loading;
mod protocol;
pub mod services;
mod session;
#[cfg(feature = "stream")]
mod stream;
#[cfg(feature = "sync")]
pub mod sync;
mod url;
mod utils;
pub use crate::adapter::Adapter;
pub use crate::apiversion::ApiVersion;
pub use crate::auth::{Auth... | Rust | 0 |
, 1, texture::AaMode::Single),
&[&texels],
)
.unwrap();
let sinfo =
texture::SamplerInfo::new(texture::FilterMethod::Bilinear, texture::WrapMode::Clamp);
let proj = cgmath::perspective(Deg(45.0f32), WIDTH as f32 / HEIGHT as f32, 0.1, 100.0);
let view = Matrix4::look_at(... | Rust | 0 |
import MCRT
import os
__root_dir__ = os.path.dirname(__file__)
root_dataset = os.path.join(__root_dir__,"cifs","Triptycene","T2Acif")
log_dir = './logs/finetune/T2A'
downstream = "T2A_lattice_energy"
# kwargs (optional)
loss_names = {
"classification": 0,
"regression": 1,}
max_epochs = 50
batch_size =... | Python | 1 |
pk3 := ed25519.GenPrivKeyFromSecret([]byte{54, 253, 151, 16, 182, 114, 125, 12, 74, 101, 54, 253, 174, 153, 121, 74, 145, 180, 111, 16, 214, 48, 193, 109, 104, 134, 55, 162, 151, 16, 182, 114})
not_in_set := ed25519.GenPrivKeyFromSecret([]byte{121, 74, 145, 180, 111, 16, 214, 48, 193, 109, 35, 68,... | Rust | 0 |
te_input_dims(scores, labels).and_then(|()| {
let length = scores.len();
let x_mean = scores.iter().fold(T::zero(), |sum, &v| {sum + v}) / T::from_usize(length);
let y_mean = labels.iter().fold(T::zero(), |sum, &v| {sum + v}) / T::from_usize(length);
let mut sxx = T::zero();
let ... | Rust | 0 |
# Torndb is a very thin wrapper around MySQLdb that makes it even easier to use MySQL.
# Because it is very light, one can just go through the one-file python source
# to learn how to use it.
# Installation: pip install torndb
# Official doc: http://torndb.readthedocs.org/en/latest/
# Source: https://github.com/bdarne... | Python | 1 |
1, self.num_heads, self.head_dim)
value = self.value_fc(value).view(batch, -1, self.num_heads, self.head_dim)
query = query.permute(0, 2, 1, 3).contiguous().view(batch * self.num_heads, -1, self.head_dim)
key = key.permute(0, 2, 1, 3).contiguous().view(batch * self.num_heads, -1, self.head_dim)... | Python | 1 |
import streamlit as st
import matplotlib.pyplot as plt
from typing import List, Union
def show_bar_chart(values: List[Union[int, float]], labels: List[str], title: str) -> None:
"""
Display a bar chart in a Streamlit app using Matplotlib.
Args:
values (List[Union[int, float]]): List of numeric val... | Python | 1 |
_finalize_one(
self, agen: AsyncGeneratorType[object, NoReturn], name: object
) -> None:
try:
# This shield ensures that finalize_asyncgen never exits
# with an exception, not even a Cancelled. The inside
# is cancelled so there's no deadlock risk.
wit... | Python | 1 |
import os
import sys
import xarray as xr
import numpy as np
import s3fs
import caterva as cat
def open_zarr(year, month, datestart, dateend):
fs = s3fs.S3FileSystem(anon=True)
datestring = "era5-pds/zarr/{year}/{month:02d}/data/".format(year=year, month=month)
s3map = s3fs.S3Map(datestring + "snow_density... | Python | 1 |
laimed < _now {
let _cRewardRate = communityFundRewardRate.load(store).unwrap();
let _pending = (_now - _cLastClaimed) * _cRewardRate;
out = _pending;
}
return out;
}
fn _unclaimedDevFund(
store: & dyn Storage,
_env: Env,
) -> Uint128
{
let mut _now = Uint128::from(_env.block... | Rust | 0 |
import os
from conan import ConanFile
from conan.tools.build import can_run
from conan.tools.cmake import cmake_layout, CMake, CMakeDeps, CMakeToolchain
from conan.tools.env import VirtualRunEnv
from conan.tools.microsoft import msvc_runtime_flag
class TestPackageConan(ConanFile):
settings = "os", "arch", "compi... | Python | 1 |
e_samples,
"region": f"{chrom}:{split_start}-{split_end}",
"variant_type": variant_type,
"requested_granularity": requested_granularity,
}
payloads.append(payload)
# next split
split_start += SPLIT_SIZE
... | Python | 1 |
fusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler.add_noise
def add_noise(
self,
original_samples: torch.FloatTensor,
noise: torch.FloatTensor,
timesteps: torch.FloatTensor,
) -> torch.FloatTensor:
# Make sure sigmas and timesteps have the same device and... | Python | 1 |
*mut ::std::os::raw::c_void,
param: f64,
) -> msdfgen_Vector2;
}
extern "C" {
#[link_name = "\u{1}_ZNK7msdfgen12CubicSegment14signedDistanceENS_7Vector2ERd"]
pub fn msdfgen_CubicSegment_signedDistance(
this: *mut ::std::os::raw::c_void,
origin: msdfgen_Point2,
param: *mut f6... | Rust | 0 |
3 = layout.addPlot(row=2, col=0)
for plot, title in zip([p1, p2, p3], ['raw', '1-70Hz', '80-450Hz']):
plot.setTitle(
f"<span style='color: {colors['title_color']};font-family: {font_family};"
f" font-weight: bold; font-size: {text_size_str};'>{title}</span>")
p1.setXLink(p2) # 链... | Python | 1 |
<Path>,
I: IntoIterator<Item = T>,
T: AsRef<OsStr>,
{
Builder::new(rs_file, autocxx_incs)
.extra_clang_args(extra_clang_args)
.build()
}
#[deprecated]
/// Use [`Builder::new`] instead
pub fn expect_build<P1, I, T>(
rs_file: P1,
autocxx_incs: I,
extra_clang_args: &[&str],
) -> Bu... | Rust | 0 |
fn of(change: ComponentEvent) -> Self {
match change {
ComponentEvent::Inserted(_) => ChangeType::Inserted,
ComponentEvent::Modified(_) => ChangeType::Modified,
ComponentEvent::Removed(_) => ChangeType::Removed,
}
}
}
trait ComponentEventExt {
fn idx(sel... | Rust | 0 |
ence = F.softmax(confidence, dim=-1)
transfer_index = torch.multinomial(full_confidence, num_samples=number_transfer_tokens)
x_ = torch.zeros_like(x, device=self.device, dtype=torch.long) + mask_token_id
x_[mask_index] = x0.clone()
row_... | Python | 1 |
}
pub(crate) fn define(isas: &Vec<Isa>, shared_defs: &mut SharedDefinitions) -> Vec<TargetIsa> {
isas.iter()
.map(|isa| match isa {
Isa::Riscv => riscv::define(shared_defs),
Isa::X86 => x86::define(shared_defs),
Isa::Arm32 => arm32::define(shared_defs),
Isa:... | Rust | 0 |
col_type, loc, pairs, |ctx, w, Pair(v1, v2)| {
print_adata(ctx, w, v1)?;
print_adata(ctx, w, v2)
})
}
fn print_adata(ctx: &Context<'_>, w: &mut dyn Write, tv: &TypedValue<'_>) -> Result<()> {
match tv {
TypedValue::Uninit => w.write_all(b"uninit"),
TypedValue::Null => w.write_al... | Rust | 0 |
, Pool};
use structopt::StructOpt;
use total_recall::{
db::DBConnection,
graphql::{mutations::Mutation, query::Query, GQLContext, Schema},
service::{
endpoints::{graphiql, graphql, login},
AppState,
},
};
#[derive(Debug, StructOpt)]
#[structopt(name = "total_recall")]
struct Opt {
... | Rust | 0 |
ery backed: {}", self.is_battery_backed)
}
}
impl Cartridge {
pub fn load<R: Read>(r: &mut R) -> Result<Cartridge, LoadError> {
let magic = r.read_u32::<BigEndian>()?;
if magic != MAGIC_CONSTANT {
return Err(LoadError::FormatError(
"magic constant in header is incor... | Rust | 0 |
[repr(C)]
#[cfg(any(feature = "pa_v5", feature = "dox"))]
pub struct pa_card_profile_info2 {
/// Name of this profile.
pub name: *const c_char,
/// Description of this profile.
pub description: *const c_char,
/// Number of sinks this profile would create.
pub n_sinks: u32,
/// Number of sour... | Rust | 0 |
rue" />"#,
};
}
#[test]
fn triple_slash_reference_invalid() {
let (not_types_in_js_msg, not_types_in_js_hint) = {
let r = ReportKind::NotTypesInJs(swc_common::DUMMY_SP);
(r.as_message(), r.as_hint())
};
let (invalid_directive_msg, invalid_directive_hint) = {
let r = ReportKind::... | Rust | 0 |
None;
}
}
None
}
/// Get all the transitive callees inside a given caller,
/// including direct callees, callees of direct callees, etc.
pub fn gen_transitive(&self) -> HashMap<LocalDefId, HashSet<LocalDefId>> {
let mut transitive: HashMap<LocalDefId, HashSet<LocalD... | Rust | 0 |
f.trans_angle_slider.valueChanged.connect(self.trans_angle_spin.setValue)
self.trans_angle_spin.valueChanged.connect(self.trans_angle_slider.setValue)
return group
def _create_hydrophone_control(self):
"""创建水听器控制组"""
group = QGroupBox("水听器控制 (4自由度)")
layout = QV... | Python | 1 |
consecttive items that must be sampled")
.takes_value(true)
.required(true),
)
}
fn parse_arguments(arguments: &ArgMatches) -> SonarSweepArgs {
match arguments.subcommand_name() {
Some("part1") => SonarSweepArgs { sample_size: 1 },
Some("part2") => SonarSweepArgs { samp... | Rust | 0 |
ch2) module"]
pub type DMA_INFIFO_STATUS_CH2 = crate::Reg<u32, _DMA_INFIFO_STATUS_CH2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DMA_INFIFO_STATUS_CH2;
#[doc = "`read()` method returns [dma_infifo_status_ch2::R](dma_infifo_status_ch2::R) reader structure"]
impl crate::Readable for DMA_INFIFO_STATUS_CH2 {}
#[do... | Rust | 0 |
"""
Minimal reproduction of boolean validator bug with complex numbers
"""
import troposphere.validators
# Test cases showing the bug
test_cases = [
complex(0, 0), # 0j
complex(1, 0), # 1+0j
0j,
1+0j,
0.0+0j,
1.0+0j,
]
print("Boolean validator incorrectly accepts complex numbers:")
print("=... | Python | 1 |
_combinations()
.map(|(x, y)| distance(x, y))
.fold(T::zero(), |a, b| a.max(b.clone()))
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Hex8Element<T: Scalar> {
vertices: [Point3<T>; 8],
}
impl<T> Hex8Element<T>
where
T: Scalar,
{
pub fn from_vertices(vertices: [Poi... | Rust | 0 |
; sec_rsrc_psize as usize];
f.read_exact(&mut rsrc_section)?;
hexdump(&rsrc_section[0..256]);
// tree holds a tree view of the tables described by the starting offset
let mut tree = TreePool::new();
let parse = parse_resource_section(&mut tree, None, &rsrc_section, 0, 0);
... | Rust | 0 |
.map(|id| (Uuid::from_u128(id), FluctuatingSensor::default()))
.collect::<Vec<_>>();
let mut map = BTreeMap::new();
loop {
map.clear();
let now = Timestamp::now();
for (addr, sensor) in &mut sensors {
map.insert(*addr, SensorSta... | Rust | 0 |
endpoint_a(s: EndpointA) -> Result<(), Box<dyn Error>> {
offer_cancel_mpst!(s, recv_mpst_a_from_c, {
Branching0fromCtoA::Done(s) => {
close_mpst_multi(s)
},
Branching0fromCtoA::More(s) => {
let (_, s) = recv_mpst_a_from_c(s)?;
let s = send_mpst_a_to_c((),... | Rust | 0 |
import pytest
import httpx_auth
def test_header_value_must_contains_token():
with pytest.raises(Exception) as exception_info:
httpx_auth.WakaTimeAuthorizationCode(
"jPJQV0op6Pu3b66MWDi8b1wD",
"waka_sec_0c4MBGeR9LN74LzV5uelF9SgeQ32CqfeWpIuieneBbsL57dAAlqqJWDiVDJOlsSx61pVwHMKlsb3uMv... | Python | 1 |
"unadjusted")
np.testing.assert_allclose(ols.schwarz, 414.41095054038061, RTOL)
np.testing.assert_allclose(ols.sig2, 231.4568494392652, RTOL)
np.testing.assert_allclose(ols.sig2ML, 217.28602192257551, RTOL)
np.testing.assert_allclose(ols.sig2n, 217.28602192257551, RTOL)
np.testi... | Python | 1 |
angles_valid(
&ies.horizontal_angles().to_vec()
));
}
}
}
const KEYWORDS_TEST: &str = "[TEST] ABC1234
[TESTLAB] ABC Laboratories
[ISSUEDATE] 18-FEB-2001
[MANUFAC] Aardvark lighting Inc.
[LUMCAT] SKYVIEW 123-XYZ-abs-400
[LUMINAIRE] Wide beam flood to be used without tilt
[LAMP... | Rust | 0 |
_API_URL}/search"
params = {'query': query}
response = requests.get(url, params=params)
response.raise_for_status()
return response.json()
# Common currencies as fallback if API is unavailable
DEFAULT_CURRENCIES = ["usd", "eur", "gbp", "jpy", "aud", "cad", "chf", "cny", "inr", "btc", "eth"]
@cache.mem... | Python | 1 |
# dataset settings
_base_ = [
'../../_base_/datasets/sevir.py',
'../../_base_/default_runtime.py',
'../../_base_/models/mcvd.py',
'../../_base_/schedules/schedule_1e6i.py',
]
default_hooks = dict(
checkpoint=dict(type='CheckpointHook',
by_epoch=False, interval=int(1e4), max_keep_ckpts=1... | Python | 1 |
s `T` while `(T,)` is a tuple
macro_rules! impl_component_set {
($($i:tt, $xs:ident),+ $(,)?) => {
impl<$($xs),+> ComponentSet for ($($xs,)+)
where
$($xs: Component,)+
{
fn register(world: &mut World) {
$(
world.register::<$xs>();
... | Rust | 0 |
from __future__ import annotations
import time
import typing
import pandas as pd
from ..models import AbstractModel
from ._abstract_callback import AbstractCallback
if typing.TYPE_CHECKING:
# avoid circular import for type hints
from ..trainer import AbstractTrainer
class ExampleCallback(AbstractCallback)... | Python | 1 |
writeln!(
f,
"namespace {} {{",
result
.namespace
.iter()
.chain(std::iter::once(&result.name))
.cloned()
.collect::<Vec<_>>()
.join("::"),
)
.unwrap();
writeln!(f, "class Type {{").unwrap();
writeln!(f,... | Rust | 0 |
# GridCal
# Copyright (C) 2022 Santiago Peñate Vera
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3 of the License, or (at your option) any later version.
#
# This pr... | Python | 1 |
# visuals.py
import plotly.graph_objects as go
def create_radar_chart(stat_group_means, player_name, comparison_stats=None):
categories = list(stat_group_means.keys())
values = list(stat_group_means.values())
categories.append(categories[0])
values.append(values[0])
fig = go.Figure()
fig.add... | Python | 1 |
ch, opts='--inactivity-probe=1 --max-backoff=1' )
net = Mininet( topo=topo, switch=sw, controller=None,
waitConnected=True )
info( '* Adding Controllers to Data Network\n' )
for host in cnet.hosts:
if isinstance(host, Controller):
net.addController( host )
info( '*... | Python | 1 |
import json
from web3 import Web3
from datetime import datetime
from solidity_python_sdk.main import DigitalProductPassportSDK
# Initialize SDK
sdk = DigitalProductPassportSDK()
# Product details to deploy
product_details = {
"uid": "BRG-2023-001",
"gtin": "7894561230123",
"taricCode": "1905",
"manufa... | Python | 1 |
import pytest
import torch
from packaging import version
from colossalai._analyzer.fx import symbolic_trace
from colossalai.testing import clear_cache_before_run
from tests.kit.model_zoo import model_zoo
def trace_and_compare(model_cls, data, output_transform_fn, meta_args=None):
# trace
model = model_cls()
... | Python | 1 |
// deliver validator's chunk response
if num_commit < 20 {
let (chunk_response_recipient, _) = env.deliver_msg(fn_2_peer_id);
assert_eq!(chunk_response_recipient, fn_0_public_peer_id);
}
}
// bring back v again
env.send_peer_event(fn_0_vfn_peer_id, validator_... | Rust | 0 |
['C'] and i2 in K_dict['B']:
zq_1[i1,q] += w2_1 * x[q,i1,i2]
if 'C' in K and 'D' in K:
if i1 in K_dict['C'] and i2 in K_dict['D']:
zq_1[i1,q] += w2_1 * x[q,i1,i2]
if i1 in K_dict['D'] and i2 in K_dict['C']:
zq_1[i1,q] +=... | Python | 1 |
_cache").tempdir().unwrap();
BoxKeyPair::get_latest_pair_for("nope-nope", cache.path()).unwrap();
}
#[test]
fn get_public_key_path() {
let cache = Builder::new().prefix("key_cache").tempdir().unwrap();
fs::copy(fixture(&format!("keys/{}", VALID_PUB)),
cache.path().j... | Rust | 0 |
_into()
} else {
Err(AmphipodParseError::InvalidString(str.to_string()))
}
}
}
type Intermediate = HashSet<(Amphipod, SlotIdentifier)>;
#[inline]
fn is_blank_space(char: char) -> bool {
char == '.'
}
#[inline]
fn is_not_blank(char: char) -> bool {
!is_blank_space(char)
}
#[inline]
fn is_wall(char: char) -... | Rust | 0 |
, Choose<E, F>>>>>> {
#[must_use]
pub fn skip5(self) -> Chan<Z, F> {
self.sel2().sel2().sel2().sel2().sel2()
}
}
/// Convenience function.
impl<Z, A, B, C, D, E, F, G>
Chan<Z, Choose<A, Choose<B, Choose<C, Choose<D, Choose<E, Choose<F, G>>>>>>> {
#[must_use]
pub fn skip6(self) -> Chan<Z... | Rust | 0 |
return (comfy.samplers.KSampler.SAMPLERS[0],)
elif choice_type == "scheduler":
return (comfy.samplers.KSampler.SCHEDULERS[0],)
else:
choices = folder_paths.get_filename_list(choice_type)
if choices:
return (choices[... | Python | 1 |
self.read_register(Sensor::Accelerometer, register::AG::INT_GEN_CFG_XL.addr())?;
let mut data: u8 = reg_value & !XL_CFG_Bitmasks::ZHIE_XL; // clear the specific bit
data = match setting {
FLAG::Enabled => data | (1 << 5), // if Enabled, set bit
FLAG::Disabled => data, ... | Rust | 0 |
Kind::While);
keywords.insert("{", TokenKind::OpenCurly);
keywords.insert("|", TokenKind::Bar);
keywords.insert("||", TokenKind::Or);
keywords.insert("}", TokenKind::CloseCurly);
let mut tagged_iter = TaggedIter::new(file, contents);
let mut tokens = Vec::new();
let mut span = Span {
... | Rust | 0 |
import numpy as np
from PIL import Image
from tqdm import tqdm
import os
import sys
__dir__ = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(__dir__))
from wrappers import RealESRGANWrapper
class TileRealESRGAN(RealESRGANWrapper):
def __init__(self, device):
super(TileRealESR... | Python | 1 |
# coding: utf-8
"""
Graphiant APIs
**To use the APIs:** 1) Login using `/api/v1/auth/login` 2) Copy the value of \"token\" in the response 3) Click the \"Authorize\" button 4) In the \"Value\" text field enter: `Bearer <your token>` 5) Click \"Authorize\" 6) All requests are now authorized. **Toke... | Python | 1 |
from rest_framework import serializers
from django.contrib.auth import get_user_model
User = get_user_model()
class ResgisterSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'email','username','password','user_type']
def create(self, data):
user... | Python | 1 |
<u8>),
}
impl std::fmt::Debug for FileContents {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Text(text) => f.debug_tuple("Text").field(text).finish(),
Self::Binary(bytes) => f
.debug_tuple("Binar... | Rust | 0 |
import collections
import math
def solution(fees, records):
answer = []
in_time = collections.defaultdict(int)
park_time = collections.defaultdict(int)
for r in records:
time, number, status = r.split(" ")
number = int(number, 10)
if status == "IN":
hour = int(ti... | Python | 1 |
and order.get("order_type") == "sell"
]
if online_orders:
min_price = min(order.get("platinum", float("inf")) for order in online_orders)
return {
"mod_name": mod_url_name.replace("_", " ").title(),
... | Python | 1 |
def exec10():
soma_primeiro= 0
soma_segundo= 0
soma_igual= 0
for i in range (10,100):
primeiro = int(i/10)
segundo = int(i%10)
if primeiro>segundo:
soma_primeiro= soma_primeiro + 1
elif primeiro<segundo:
soma_segundo= soma_segundo + 1
else:
... | Python | 1 |
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1",
),
(
&[0xbd],
"68325720aabd7c82f30f554b313d0570c95accbb7dc4b5aae11204c08ffe732b",
),
(
&[0xc9, 0x8c, 0x8e, 0x55],
"7abc22c0ae5af26ce93dbb94433a0e0b2e119d014f8e... | Rust | 0 |
).assert_eq(other, ctx)
}
}
/// Slot types, used for variables and table values.
///
/// Externally this is rarely used separately because slot types need to be mutable;
/// the `Slot` container should be used instead in most cases.
pub struct S {
bits: AtomicUsize,
ty: RwLock<Ty>,
}
impl S {
pub fn n... | Rust | 0 |
cResponse {
pub id: u32,
#[serde(rename(serialize = "jsonrpc", deserialize = "jsonrpc"))]
pub jsonrpc_version: String,
pub result: Value,
}
//! Multicore support
// See [Chapter ?? Section ??](https://datasheets.raspberrypi.org/rp2040/rp2040_datasheet.pdf) for more details
use crate::pac;
#[cfg(featur... | Rust | 0 |
IFLA_BRPORT_FAST_LEAVE;
pub const IFLA_BRPORT_LEARNING: _bindgen_ty_7 = _bindgen_ty_7::IFLA_BRPORT_LEARNING;
pub const IFLA_BRPORT_UNICAST_FLOOD: _bindgen_ty_7 = _bindgen_ty_7::IFLA_BRPORT_UNICAST_FLOOD;
pub const IFLA_BRPORT_PROXYARP: _bindgen_ty_7 = _bindgen_ty_7::IFLA_BRPORT_PROXYARP;
pub const IFLA_BRPORT_LEARNING_... | Rust | 0 |
.histogram( b, bins = LAB_HISTOGRAM_NUM_BINS, range = ( 0, 255 ), density = True )
return ( r_hist, g_hist, b_hist )
def GetEdgeMapSlicedWasstersteinDistanceScore( edge_map_1: numpy.ndarray, edge_map_2: numpy.ndarray ):
# this is a fast alternate of a 2D wasserstein distance
def wassers... | Python | 1 |
64,device="cuda",dtype= torch.float16):
bool_matrix256 = torch.rand((1, total_length * 256),device = device,dtype = dtype) < sa16
bool_matrix1024 = torch.rand((1, total_length * 1024),device = device,dtype = dtype) < sa32
bool_matrix4096 = torch.rand((1, total_length * 4096),device = device,dtype = dtype) <... | Python | 1 |
pyop_frame = frame.get_pyop()
if not pyop_frame:
print('Unable to read information on python frame')
return
pyop_var, scope = pyop_frame.get_var_by_name(name)
if pyop_var:
print('%s %r = %s'
% (scope,
name,
... | Python | 1 |
doc = "* - SPINEL_STATUS_JOIN_NO_PEERS no joinable network was discovered."]
#[doc = "* - SPINEL_STATUS_JOIN_RSP_TIMEOUT if a response timed out."]
#[doc = "* - SPINEL_STATUS_JOIN_FAILURE join failure."]
#[doc = "*"]
#[doc = "* Frame format:"]
#[doc = "*"]
#[doc = "* `b` : Start or stop commissionin... | Rust | 0 |
(CURRENT_USER_STR));
Flash::success(Redirect::to(\"/\"), \"Successfully logout.\")
}
#[post(\"/register\", data = \"<user>\", format = \"application/x-www-form-urlencoded\")]
pub fn register(
user: LenientForm<Registration>,
db: ConnPool,
settings: State<Settings>,
) -> Result<Flash<Redirect>, Template... | Rust | 0 |
#!/usr/bin/python
# Author:
# Artem Kondratenko (@artkond)
import socket
import sys
from time import sleep
set_credless = True
if len(sys.argv) < 3:
print sys.argv[0] + ' [host] --set/--unset'
sys.exit()
elif sys.argv[2] == '--unset':
set_credless = False
elif sys.argv[2] == '--set':
pass
else:
print sys.argv[... | Python | 1 |
return __funcwrapper
class ImgUI:
"""
Stub out ImgUI so we don't get crashes
"""
GUI = None
def open(self):
def __funcwrapper(func):
def __inner(*args, **kwargs):
return func(*args, **kwargs)
return __inner
return __funcwrapper
... | Python | 1 |
fn recalculate_cached_matrices(&mut self) {
self.inverse_tf_matrix = self.tf_matrix.try_inverse().expect("Uninvertable Model View Matrix");
}
pub fn load_identity(&mut self) {
self.tf_matrix = Matrix4::identity();
self.inverse_tf_matrix = Matrix4::identity();
}
pub fn scale... | Rust | 0 |
_load_as_endpoints, eps_from_metadata):
plugin_cls = ep.load()
if not isinstance(plugin_cls, type):
click.echo(
click.style(
f"Plugins must be defined as references to classes with a "
f"nullary init function, but '{ep.value}' is "
... | 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Python | 1 |
not match expected loss."
expected_gradCenterVecs = [ [ 0., 0., 0. ],
[ 0., 0., 0. ],
[-6.42994865, -2.16396482, -1.89240934],
[ 0., 0., 0. ]... | Python | 1 |
None:
self.write(self.derive_context(frame))
def visit_Continue(self, node: nodes.Continue, frame: Frame) -> None:
self.writeline("continue", node)
def visit_Break(self, node: nodes.Break, frame: Frame) -> None:
self.writeline("break", node)
def visit_Scope(self, node: nodes.Scop... | Python | 1 |
16,
pub initial_max_data: u32,
pub initial_max_bidi_streams: u16,
pub initial_max_uni_streams: u16,
pub max_packet_size: u16,
pub ack_delay_exponent: u8,
pub disable_migration: bool,
pub initial_max_stream_data_bidi_local: u32,
pub initial_max_stream_data_bidi_remote: u32,
pub initia... | Rust | 0 |
}
/// Get a mutable reference to the inner sink.
pub fn get_mut(&mut self) -> &mut S {
&mut self.sink
}
/// Consumes this combinator, returning the underlying sink.
///
/// Note that this may discard intermediate state of this combinator, so
/// care should be taken to avoid losing... | Rust | 0 |
# Game Components
# • Game Window
# • Game Loop
# • Event Loop(Keyboard press, mouse movements, 'close' button, etc.)
import pygame
pygame.init() # initializes all the pygame sub-modules
screen = pygame.display.set_mode((800, 480)) # creating a game window
# set_mode() takes a tuple as an argument
running = True
w... | Python | 1 |
'_': 11, '`': 11, '{': 11, '|': 11, '}': 11, '~': 11},
20: {'0': 12, '1': 12, '2': 12, '3': 12, '4': 12, '5': 12, '6': 12, '7': 12, '8': 12, '9': 12, 'a': 12, 'b': 12, 'c': 12, 'd': 12, 'e': 12, 'f': 12, 'g': 12, 'h': 12, 'i': 12, 'j': 12, 'k': 12, 'l': 12, 'm': 12, 'n': 12, 'o': 12, 'p': 12, 'q': 12, 'r': 12, 's': 12... | Python | 1 |
_width: i64, tile_height: i64) ->HashMap<u32, Rectangle>{
let mut id = 0;
let x = i64::from(clip.height as i32) / tile_width;
let y = i64::from(clip.width as i32) / tile_height;
let mut tile_rectangles: HashMap<u32, Rectangle> = HashMap::with_capacity((x * y) as usize);
for i in 0..x{
for j ... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.