text string | label_name string | labels int64 |
|---|---|---|
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import edward as ed
import numpy as np
import tensorflow as tf
import os
from edward.models import Bernoulli, Normal
from edward.util import Progbar
from keras.layers import *
from keras ... | Python | 1 |
from datadog import initialize, api
import re
import csv
options = {
'api_key': 'YOUR_API_Key',
'app_key': 'YOUR_APP_Key'
}
initialize(**options)
monitors = api.Monitor.get_all()
bp_tag_pattern = re.compile(r"BigPandaTags:\s*\[(.*?)\]", re.DOTALL)
filtered_monitors = []
for monitor in monitors:
... | Python | 1 |
pts(&anime));
// finished airing recently
anime.end_date = (Utc::now() - Duration::weeks(threshold / 2)).timestamp();
assert!(strategy.accepts(&anime));
// finished airing long ago
anime.end_date = (Utc::now() - Duration::weeks(threshold)).timestamp();
assert!(!strategy... | Rust | 0 |
import jmbitcoin as btc
import pytest
def test_address_descriptors():
assert(btc.get_address_descriptor("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i") ==
"addr(1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i)#ns3f5w84")
assert(btc.get_address_from_descriptor("addr(1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i)#ns3f5w84") ==
"... | Python | 1 |
cond=RCOND):
'''Compute the inverse, or pseudo-inverse as fallback, of a matrix.'''
try:
# Faster version first, with is_singular() test...
return invert_caution(mat)
except Exception:
# ... so mat is probably singular:
system.warn("ILL-CONDITION: invert() may outp... | Python | 1 |
ONFIG", OCICRYPT_CONFIG_PATH);
}
let status: ExitStatus = pull_command.status()?;
if !status.success() {
let mut error_message = format!("failed to pull image: {:?}", status);
if let Err(e) = fs::remove_dir_all(&tmp_cid_path) {
error_message.push_str(&f... | Rust | 0 |
self) -> Ipv6State<Instant, D> {
let Ipv6StateBuilder { icmp } = self;
Ipv6State {
inner: IpStateInner {
table: ForwardingTable::default(),
fragment_cache: IpPacketFragmentCache::default(),
pmtu_cache: PmtuCache::default(),
},
... | Rust | 0 |
"""Utilities for parsing EPUB table of contents (TOC)."""
from __future__ import annotations
from epub_io.reader import EpubReader
def parse_toc_to_dict(reader: EpubReader) -> dict[str, str]:
"""Extract TOC titles mapped by document href.
Parses the EPUB's table of contents and creates a mapping from
d... | Python | 1 |
ursor::new(tar!("link.tar"));
let mut ar = Archive::new(rdr);
ar.set_overwrite(true);
t!(ar.unpack(td.path()));
}
#[test]
#[cfg(all(unix, feature = "xattr"))]
fn xattrs() {
// If /tmp is a tmpfs, xattr will fail
// The xattr crate's unit tests also use /var/tmp for this reason
let td = t!(TempB... | Rust | 0 |
zorder=10,
)
axs[0].set_xlabel("$Re(\lambda)$")
axs[0].set_ylabel("$Im(\lambda)$")
axs[1].set_xlabel("time in s")
axs[1].set_ylabel(r"$\bm{q}$")
axs[2].set_xlabel("time in s")
axs[2].set_ylabel("rel RMS error")
# Create custom legend
custom_lines = [
L... | Python | 1 |
b use self::enums::InputSource;
pub use self::enums::KeyMatch;
pub use self::enums::MemoryFormat;
pub use self::enums::NotifyType;
pub use self::enums::ScrollDirection;
pub use self::enums::SubpixelLayout;
pub use self::enums::SurfaceEdge;
pub use self::enums::TouchpadGesturePhase;
pub use self::enums::VulkanError;
mo... | Rust | 0 |
ance')
plt.plot(range(1000),dpplml_sub_rel_wcv[sub_sample_idx],color="red",label='ProtoQuery variance')
plt.xlabel('Samples')
plt.ylabel('Variance of Subject and Predicate Features Within the Same Sample')
plt.legend()
plt.savefig(f'{save_path}/sub_rel_var.png')
plt.clf()
plt.plot(range(... | Python | 1 |
== "predicate":
formatted = [f"'{x}'" for x in edge_filters["predicate"]]
value = f"type({variable}) IN [{', '.join(formatted)}]"
elif key in knowledge_provenance_properties:
formatted = [
f"'{x}' IN {variable}{prefix}{... | Python | 1 |
tarted etcd process %d" % (self.pid))
wait_time = 60 + random.randint(0,10)
while False: #not self.is_endpoint_healthy(wait_time):
if restartCount > 0:
self.shutdown_server()
cfg.fix... | Python | 1 |
_with_h_priority_return_valid_addcommand() {
parse_command_with_x_priority_return_valid_addcommand(Priority::High, "h");
}
}<reponame>narpfel/rust-clippy<gh_stars>1000+
#![warn(clippy::needless_continue)]
macro_rules! zero {
($x:expr) => {
$x == 0
};
}
macro_rules! nonzero {
($x:expr) ... | Rust | 0 |
roundtrip(i64::MAX);
test_i64_encoding_roundtrip(0);
test_i64_encoding_roundtrip(41262);
test_i64_encoding_roundtrip(-98793);
}
#[test]
fn test_f64_lex_order() {
let mut nan_buf = Vec::new();
let mut zero_buf = Vec::new();
let mut pos_buf = Vec::new();
... | Rust | 0 |
kind.iter() {
let (subdir, cargo_build_debug) = match kind.as_str() {
"example" => ("examples/", format!("cargo build --package {} --example {}", package.name, target.name)),
"bin" => ("", format!("cargo build --package {} --bin {}", package.name,... | Rust | 0 |
]
# start iina
print("iina starting")
cherrypy.engine.publish('mpv_start')
self.iina = subprocess.Popen(
params,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
env=Setting.get_system_env())
def st... | Python | 1 |
= Square(21);
/// The C6 square on the chess board
///
/// ```
/// use chess::{Square, Rank, File};
///
/// assert_eq!(Square::C6, Square::make_square(Rank::Sixth, File::C));
/// ```
pub const C6: Square = Square(22);
/// The D6 square on the chess board
///
/// ```
///... | Rust | 0 |
0174}',
'ꊿ', 'ﶲ', '𓎜', '𑛉', 'ὑ', '𛰍', 'ⓖ', 'Ҝ', '\u{2df2}', 'ﰗ', 'ᙖ', 'ᕂ',
'𞋟', '𑐫', '𖡞', 'ᘝ', 'Ե', 'ᴙ', 'ㄘ', '善', 'ꌉ', '𐳐', 'ﮟ', '𐳀',
'𛄢', '🏹', '╆', 'ᚡ', '𑴆', '𝤫', '\u{a94b}', 'ŕ', '\u{1acc}', 'ꏆ', '𐠨',
'🌦', '𐠪', '𞠀', '𐂆', 'Ḗ', '\u{fe21}', '🢗', 'ᕆ', '𖬸', '𑣔', '𛀂',
'隣', '𞺵', 'ଶ... | Rust | 0 |
ER_2D_SHADOW_ARB: c_uint = 0x8B62;
pub const SAMPLER_3D: c_uint = 0x8B5F;
pub const SAMPLER_3D_ARB: c_uint = 0x8B5F;
pub const SAMPLER_BINDING: c_uint = 0x8919;
pub const SAMPLER_BUFFER: c_uint = 0x8DC2;
pub const SAMPLER_BUFFER_AMD: c_uint = 0x9001;
pub const SAMPLER_BUFFER_EXT: c_uint = 0x8DC2... | Rust | 0 |
, num_tokens]
for (bsz, num_tokens) in fixed_shapes
]
)
try:
num_tokens_vec = self.num_tokens_vec(indices).astype("int64")
except NotImplementedError:
num_tokens_vec = None
return data_utils.batch_by_size(
indi... | Python | 1 |
rHandRank,
meta::Meta,
tests::{FiveCardHand, RepresentativeHand, SevenCardHand, SixCardHand},
utils,
},
};
#[test]
fn test_all_five_card_combos() {
let gen = utils::combinations_generator(Card::generate_deck(), 5);
let evals = gen.fold(HashSet::wi... | Rust | 0 |
#!/usr/bin/env python
"""
vtkEnSightWriter test for writing VTK_CONVEX_POINT_SET cell
vtkEnSightWriter should write VTK_CONVEX_POINT_SET as "nfaced" element
and vtkEnSightGoldBinaryReader will read it back as VTK_POLYHEDRON.
"""
import vtk
from vtk.util.misc import vtkGetDataRoot, vtkGetTempDir
import os.path
VTK_DA... | Python | 1 |
"""Top-level package for Chess Tuning Tools."""
try:
from importlib.metadata import version
except ImportError:
from importlib_metadata import version
__author__ = """Karlson Pfannschmidt"""
__email__ = "kiudee@mail.upb.de"
__version__ = version("chess-tuning-tools")
from tune.io import InitStrings, load_tuni... | Python | 1 |
N;
}
self.x.$f()
}
};
}
impl DecInterval {
impl_dec!(inf);
impl_dec!(mag);
impl_dec!(mid);
impl_dec!(mig);
impl_dec!(rad);
impl_dec!(sup);
impl_dec!(wid);
}
#[cfg(test)]
mod tests {
use crate::*;
#[test]
fn inf() {
assert!(const_int... | Rust | 0 |
"""Monitor CPU RAM and GPU VRAM usage to prevent out of memory errors."""
import logging
from typing import Optional
import psutil
import torch
logger = logging.getLogger(__name__)
class OutOfMemoryError(Exception):
"""Custom exception for GPU or RAM out of memory."""
def __init__(self, message: str, devi... | Python | 1 |
+ f"{data.get('truckPlacement', {}).get('coordinateY'):.0f}"
)
text += (
", "
+ f"{data.get('truckPlacement', {}).get('coordinateZ'):.0f}"
)
Text(
text,
... | Python | 1 |
{course['course_number']} (min grade: {course['minimum_grade']})")
if logic == "AND":
return " AND ".join(course_summaries)
elif logic == "OR":
return " OR ".join(course_summaries)
else:
return f"Complex requirements: {', '.join(course_summaries)}"
if __name__ == "__main__":
... | Python | 1 |
uper::GlusterError> {
let op_ret = data.read_i32::<BigEndian>()?;
let op_errno = data.read_i32::<BigEndian>()?;
let size = data.read_u32::<BigEndian>()?;
let mut s = unpack_dict_bytes(data, size)?;
let mut cursor = Cursor::new(&mut s[..]);
let friends = deserialize_dict(... | Rust | 0 |
"step": 1}),
"downscale_mode": ("BOOLEAN", {"default": True, "label_on": "max", "label_off": "min"}),
"compress_level": ("INT", {"default": 0, "min": 0, "max": 9, "step": 1}),
},
"hidden": {"prompt": "PROMPT", "extra... | Python | 1 |
members in the Ordered Set 'btu_scheduler:task_execution_times'
// are not just Task Schedule ID's. The Unix Time is a suffix. Removing members now requires some "starts_with" logic.
// First, list all the keys using 'zrange btu_scheduler:task_execution_times 0 -1'
let mut redis_conn = rq::get_redis_connection(a... | Rust | 0 |
([0; N])
}
}
impl AsMut<[u8]> for RandomSeed {
fn as_mut(&mut self) -> &mut [u8] {
&mut self.0
}
}
impl SeedableRng for Random {
type Seed = RandomSeed;
fn from_seed(seed: RandomSeed) -> Random {
Random {
seed: seed.clone(),
rng: SeedableRng::from_seed(seed... | Rust | 0 |
"image dimensions: {}, given upper-left: {})"
.format((im_width, im_height), (ul_x, ul_y)))
in_bounds = False
if not ((0 <= lr_x <= im_width) and (0 <= lr_y <= im_height)):
log.warning("Lower-right coordinate outside image bounds "
"([w, h] image dimensions... | Python | 1 |
impl Default for AmbientLight {
fn default() -> Self {
Self {
color: Vector3::zero(),
}
}
}
impl AmbientLight {
pub fn new(color: Vector3<f64>) -> Self {
Self { color }
}
pub fn get_color(&self) -> Vector3<f64> {
self.color
}
}
<filename>src/view.r... | Rust | 0 |
();
let config: Config = serde_yaml::from_str(&config_file).unwrap();
println!("using zoom binary path: {}", config.zoom_bin_path);
rocket::ignite()
.manage(config)
.mount("/", routes![meeting])
.launch();
}
use indexmap::map::IndexMap;
use proc_macro2::TokenStream;
use quote::{quo... | Rust | 0 |
assert!(n > der, "number of nodes must be greater than der!");
let nf = n as f64;
// Grid points
let x = 2.0 * PI * Array::range(0., nf, 1.0) / nf;
// grid spacing
let dx = 2.0 * PI / nf;
// Indices for flipping trick
let nn1 = ((nf - 1.0) / 2.0).floor() as usize;
let nn2 = ((nf - 1.0) ... | Rust | 0 |
from botocore.credentials import Credentials
from aiodynamo.credentials import Key
from aiodynamo.sign import make_default_endpoint
KEY = Key("AKIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY")
CREDENTIALS = Credentials(KEY.id, KEY.secret)
SERVICE_NAME = "dynamodb"
REGION = "us-east-1"
URL = make_defa... | Python | 1 |
}
// Now start incorporating past history
// FIXME: gotta sort out swaps in polarity between time-points
// FIXME: this isnt quite right as we move from OP into first TRAN point. hacking that for now
let cgs2 = if self.op.cgs == 0.0 {
// This is the fake initial-time ... | Rust | 0 |
.ticks(), 10_000);
let d: Duration<u32, 1, 10_000> = z + 1.minutes();
assert_eq!(d.ticks(), 600_000);
let d: Duration<u32, 1, 10_000> = z + 1.hours();
assert_eq!(d.ticks(), 36_000_000);
}
#[test]
fn duration_shorthands_u64() {
let z = Duration::<u64, 1, 10_000>::fr... | Rust | 0 |
::Deref for E1AS_R {
type Target = crate::FieldReader<bool, E1AS_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Event 2 Detection Status\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum E2AS_A {
#[doc = "0: Event 2 not detected"]
VAL... | Rust | 0 |
from pydantic import BaseModel
from typing import Optional, List, Dict, Any
class GenerateRequest(BaseModel):
"""Request model for generating a response"""
system_prompt: str
user_prompt: str
role_id: Optional[str] = None
provider_name: Optional[str] = None
class StreamGenerateRequest(BaseModel)... | Python | 1 |
_eq!(options.binary_prefix(), "0b");
assert_eq!(options.binary_suffix(), "");
assert_eq!(options.binary_digit_group_size(), 4);
assert_eq!(options.digit_separator(), "");
assert!(!options.leading_zeroes());
assert!(options.uppercase_hex());
assert!(options.small_hex_numbers_in_decimal());
assert!(options.add_lea... | Rust | 0 |
N_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
SESSION_ENGINE = "django.contrib.sessions.backends.cached_db"
SECRET_KEY = os.environ["SECRET_KEY"]
EMAIL_HOST = os.environ["EMAIL_HOST"]
EMAIL_PORT = int(os.environ["EMAIL_PORT"])
EMAIL_HOST_USER = os.environ["EMAIL_HOST_USER"]
EMAIL_HOST_PASSWORD = os.environ["... | Python | 1 |
=> Some(Int64),
(Utf8, _) => Some(Utf8),
(_, Utf8) => Some(Utf8),
(Boolean, Boolean) => Some(Boolean),
(Boolean, Int8) => Some(Int8),
(Boolean, Int16) => Some(Int16),
(Boolean, Int32) => Some(Int32),
(Boolean, Int64) => Some(Int64),
(Boolean, UInt8) => ... | Rust | 0 |
None]+1e-8)
pred_all += pred
pred = pred_all / len(test_transform_set)
loss = criterion(pred, torch.LongTensor(label).cuda(non_blocking=True)) # for reference
pred = pred.max(1)[1].data.cpu().numpy()
# calculation 1: add per room predictions
interse... | Python | 1 |
raise ValueError('Servo indices do not match.')
# Create new times values. # TODO: what about time = 0.5
new_times: list[float] = [0.5*time for time in self._times]
new_times += [0.5 + 0.5*time for time in other._times]
# Combine angle values
new_an... | Python | 1 |
"""
测试 match_word_list_by_priority 函数的各种场景
"""
import pytest
from unittest.mock import patch
from one_dragon.base.matcher.match_result import MatchResult, MatchResultList
from one_dragon.base.matcher.ocr.ocr_utils import match_word_list_by_priority
class TestMatchWordListByPriority:
@pytest.fixture
def samp... | Python | 1 |
self.iterator = iterator.map(str::to_string);
}
pub fn stoken(&mut self, stoken: Option<&str>) {
self.stoken = stoken.map(str::to_string);
}
pub fn to_fetch_options<'a>(&'a self) -> etebase::FetchOptions<'a> {
let mut ret = etebase::FetchOptions::new();
if let Some(limit)... | Rust | 0 |
: 5 + ChallengeManager::<Test>::get_raising_period_Length(),
raised_group: vec![
(ACCOUNT_ID_2, 2_000_000_000_000),
(ACCOUNT_ID_2, 3_000_000_000_000),
(ACCOUNT_ID_3, 1_000_000_000_000),
]
}
);
let check_perval = vec![
(ACCOUNT_ID_2, Perbill::from_rational(2_000_000_000_000u64, 6_000_00... | Rust | 0 |
import statsmodels.api as sm
from pyspark.sql.types import *
from pyspark.sql import functions as F
__all__ = [
'StatsLogit',
'NumRange',
'mode',
'Div',
]
def StatsLogit(X, y, intercept=True):
"""
描述: statsmodels 逻辑回归
:param X:
:param y:
:param intercept:
:return:
"""
... | Python | 1 |
"Cherry:4:4:good:Oct\n",
"Kiwi:1111:1.1.11:good:Jun\n",
"Orange:222:1.1.2:good:Jan\n",
)
);
assert_eq!(r.is_ok(), true);
}
//
#[test]
fn test_uniq_color() {
let env = env_1!();
let in_w = super::IN_DAT_FRUIT.to_string() + super:... | Rust | 0 |
id.to_string()),
]);
handle_as_json_with_status::<RemovePlaceResponse>(req).await?;
Ok(())
}
pub async fn create_experience(
&self,
group_id: Option<AssetId>,
) -> RobloxApiResult<CreateExperienceResponse> {
let req = self
.client
... | Rust | 0 |
String {
todo!()
}
}
fn match_kind<'tree>(
kind: &'static str,
candidate: &'tree Node,
) -> Option<(TNode<'tree>, Env<'tree>)> {
let mut env = HashMap::new();
let candidate = candidate.inner;
let node = match_single_kind(kind, candidate, &mut env)?;
Some((node, env))
}
fn match_no... | Rust | 0 |
#Kategorisanje studenata po broju položenih predmeta i prosjeku koji su ostvarili kad su prvi put bili prva godina
#Prvo sam podatke preuzeo i pripremio za obradu koristeći Excel file. Nakon pripreme, otkucao sam Python kod
#kako bih dobio kategorije studenata u ispisu
import pandas as pd
from datetime import datetime
... | Python | 1 |
uired features: 'Win32_Media_Audio'*"]
pub union AUDIOCLIENT_ACTIVATION_PARAMS_0 {
pub ProcessLoopbackParams: AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS,
}
impl ::core::marker::Copy for AUDIOCLIENT_ACTIVATION_PARAMS_0 {}
impl ::core::clone::Clone for AUDIOCLIENT_ACTIVATION_PARAMS_0 {
fn clone(&self) -> Self {
... | Rust | 0 |
description=f"Successfully sent the file: {filename}",
color=0x00ff00
)
else:
embed = discord.Embed(
title="❌ File Send Error",
description=f"File not found: {filename} in {current_directory}",
color=0xff0000
)
... | Python | 1 |
"2")]
HalfDay,
/// Morning
#[serde(rename = "3")]
Morning,
/// Afternoon
#[serde(rename = "4")]
Afternoon,
/// Evening
#[serde(rename = "5")]
Evening,
/// After-hours
#[serde(rename = "6")]
AfterHours,
/// Holiday
#[serde(rename = "7")]
Holiday,
}
impl Default for TradingSessionID {
fn default() -> S... | Rust | 0 |
# Copyright 2017 Insurance Australia Group Limited
#
# 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 ag... | Python | 1 |
: &MessageSender) -> Option<u32>;
#[wasm_bindgen(method, getter)]
pub fn id(this: &MessageSender) -> Option<String>;
#[wasm_bindgen(method, getter)]
pub fn url(this: &MessageSender) -> Option<String>;
#[wasm_bindgen(method, getter, js_name = tlsChannelId)]
pub fn tls_channel_id(this: &Message... | Rust | 0 |
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
import requests
TOKEN = "7648014049:AAHRVap0OpFaP39tlG-LxjC1NOnTkoNbCWc"
URL = "https://brsapi.ir/Api/Market/Gold_Currency.php?key=FreeuaqGvMDvclRinL2Fy4Rzdb0jxcES"
headers = {
"User-Agent": "Moz... | Python | 1 |
}
KeyCode::Fullstop => {
if modifiers.is_shifted() {
DecodedKey::Unicode(':')
} else {
DecodedKey::Unicode('.')
}
}
KeyCode::Slash => {
if modifiers.is_shifted() {
... | Rust | 0 |
_base_ = [
'../../model/swin_pretrained.py',
'../../data/phase2/bepn14_ros50.py',
'../../schedule/sgd_decr.py',
'../../runtime/default.py'
]
load_from = None
resume = False
| Python | 1 |
ing service, send request using zmq socket"""
images, bbox = socket.recv_pyobj()
start_time = time.time()
sam2.init_state(images)
cur_bbox = bbox
sam2.add_bbox(cur_bbox)
new_bbox = sam2.track()
# sam2.vis() # debug
socket.send_pyobj(new_bbox)
# Debug code... | Python | 1 |
();
//! ```
#![cfg_attr(all(not(test), not(feature = "mock")), no_std)]
#![cfg_attr(feature = "strict", deny(warnings))]
extern crate alloc;
extern crate core;
/// # Redis command abstractions
///
/// This crates includes abstractions for some Redis commands like
/// [AUTH](crate::commands::auth),
/// [HELLO](crate::... | Rust | 0 |
let mut values: Vec<Value> = Vec::with_capacity(length);
for _ in 0..length {
values.push(c.v.clone());
}
CollKind::WrappedColl {
elem_tpe: c.tpe,
items: values,
}
}),
... | Rust | 0 |
let mut v: Vec<isize> = vec![1, 2, 3];
takes_imm_elt(&v[0], || {})
}
fn has_mut_vec_but_tries_to_change_it() {
let mut v: Vec<isize> = vec![1, 2, 3];
takes_imm_elt(
&v[0],
|| { //~ ERROR cannot borrow `v` as mutable
v[1] = 4;
})
}
fn main() {
}
// message files will inc... | Rust | 0 |
from . import _base
from ._axes import Axes
# Backcompat.
Subplot = Axes
class _SubplotBaseMeta(type):
def __instancecheck__(self, obj):
return (isinstance(obj, _base._AxesBase)
and obj.get_subplotspec() is not None)
class SubplotBase(metaclass=_SubplotBaseMeta):
pass
def subplot_... | Python | 1 |
import torch
import torch.nn as nn
import torch.distributed as dist
import torch.multiprocessing as mp
import os
def setup(rank, world_size):
"""初始化每个进程的分布式环境"""
os.environ["MASTER_ADDR"] = "localhost"
os.environ["MASTER_PORT"] = "29500"
dist.init_process_group("gloo", rank=rank, world_size=world_size)... | Python | 1 |
ort matplotlib.pyplot as plt
augmentations = Compose([Scale(512), RandomRotate(10), RandomHorizontallyFlip()])
local_path = "/home/meet/datasets/NYUv2/"
dst = NYUv2Loader(local_path, is_transform=True, augmentations=augmentations)
bs = 4
trainloader = data.DataLoader(dst, batch_size=bs, num_worker... | Python | 1 |
class Solution:
def minOperations(self, nums: List[int], k: int) -> int:
heap = nums
heapify(heap)
count = 0
while len(heap) >= 2 :
x, y = heappop(heap), heappop(heap)
if x >= k and y >= k:
return count
else:
... | Python | 1 |
from subprocess import DEVNULL, STDOUT, Popen, getoutput, check_output, check_call, PIPE, call, run as _run
from traceback import TracebackException
def printEx(e):
print("".join(TracebackException.from_exception(e).format()))
def run(command, **kawrgs):
return _run(command, **kawrgs)
def returnCode(command,... | Python | 1 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': "Subcontract with Barcode",
'summary': "Allows the subcontracting process with the barcode views",
'category': 'Hidden',
'version': '1.0',
'description': """
This bridge module is auto-insta... | Python | 1 |
&ResourceRecordType::Owned)
}
pub fn is_expired(&self) -> bool {
match self {
ResourceRecordType::Owned => false,
ResourceRecordType::Expirable(exp_info) => exp_info.expire_at < Instant::now(),
}
}
pub fn should_refresh(&self) -> bool {
match self {
... | Rust | 0 |
f to_arrow(self: Self) -> Any:
return self._native_frame
def sample(
self: Self,
n: int | None = None,
*,
fraction: float | None = None,
with_replacement: bool = False,
seed: int | None = None,
) -> Self:
import numpy as np # ignore-banned-import... | Python | 1 |
#-----------------------------------------------------------------------------
# Demonstrate the use of the code generator
from crcmod import Crc
g8 = 0x185
g16 = 0x11021
g24 = 0x15D6DCB
g32 = 0x104C11DB7
def polyFromBits(bits):
p = 0
for n in bits:
p = p | (1 << n)
return p
# The following is fr... | Python | 1 |
from ipaddress import ip_address, ip_network
for a in range(256):
net = ip_network(f'192.214.{a}.184/255.255.255.224', False)
cnt = 0
for ip in net:
ip = f'{int(ip):032b}'
if ip.count('1') > 15:
cnt += 1
if cnt == net.num_addresses:
print(a)
break
| Python | 1 |
# -*- coding: utf-8 -*-
#
# @File: distributed.py
# @Author: NVIDIA
# @Date: 2023-04-29 11:50:12
# @Last Modified by: Haozhe Xie
# @Last Modified at: 2023-04-29 12:18:02
# @Email: root@haozhexie.com
# @Ref: https://github.com/NVlabs/imaginaire
import ctypes
import math
import os
import pynvml
import torch
import ... | Python | 1 |
from compas.geometry import Point
__all__ = [
"Inertia",
]
class Inertia:
"""The moments of inertia represent the spatial distribution of mass in a rigid body.
It depends on the mass, size, and shape of a rigid body with units of
[mass * m**2]. The moments of inertia can be expressed as the componen... | Python | 1 |
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GLES2 import _types as _cs
# End users want this...
from OpenGL.raw.GLES2._types import *
from OpenGL.raw.GLES2 import _errors
from OpenGL.constant import Constant as _C
import... | Python | 1 |
# Copyright 2025 © BeeAI a Series of LF Projects, LLC
# SPDX-License-Identifier: Apache-2.0
import logging
from uuid import UUID
from kink import inject
from beeai_server.domain.models.user import User
from beeai_server.domain.models.user_feedback import UserFeedback
from beeai_server.service_layer.unit_of_work impo... | Python | 1 |
ource: True
>>> p4 = plot_implicit(
... Eq(x**2 + y**2, 5), (x, -5, 5), (y, -2, 2),
... adaptive=False)
Using mesh grid without using adaptive meshing with number of points
specified:
.. plot::
:context: close-figs
:format: doctest
:include-source: ... | Python | 1 |
t mut stmts = ~[];
for b.stmts.iter().advance |stmt| {
match fld.fold_stmt(*stmt) {
None => {}
Some(stmt) => stmts.push(stmt)
}
}
ast::blk_ {
view_items: view_items,
stmts: stmts,
expr: b.expr.map(|x| fld.fold_expr(*x)),
id: fld.new_id(... | Rust | 0 |
age name.
"""
output_dir = self.config['testing']['output_dir']
ignore_dir = self.config['testing'].get('filename_ignore_dir', True)
filename_replace_source = self.config['testing'].get('filename_replace_source', None)
filename_replace_target = self.config['testing'].get('filena... | Python | 1 |
[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _MonoReflectionMethodBody {
_unused: [u8; 0],
}
pub type MonoReflectionMethodBody = _MonoReflectionMethodBody;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _MonoAppContext {
_unused: [u8; 0],
}
pub type MonoAppContext = _MonoAppContext;
#[repr(C)]
#[deri... | Rust | 0 |
######## PROTEIN ########
protein_atom_mapping = {"H": 0, "C": 1, "N": 2, "O": 3, "S": 4, "Se": 5}
######## LIGAND ########
ligand_atom_mapping = {'C': 0, 'N': 1, 'O': 2, 'S': 3, 'B': 4, 'Br': 5, 'Cl': 6, 'P': 7, 'I': 8, 'F': 9, 'NH': 10, 'N+': 11, 'O-': 12,}
ligand_atom_mapping_ev = ligand_atom_mapping.copy()
ligand_... | Python | 1 |
# modules/syntax.py
import re
def validate_record_syntax(record, record_type):
"""Validate the syntax of a DNS record (SPF or DMARC)."""
if record_type == "SPF":
mechanism_patterns = {
"all": r"^all$",
"include": r"^include:[\w\.\-]+\.[a-zA-Z]{2,}$",
"a": r"^a(:[\w... | Python | 1 |
se_error_from_http_status(self, response):
return {
'Error': {
'Code': str(response['status_code']),
'Message': http.client.responses.get(
response['status_code'], ''
),
},
'ResponseMetadata': {
... | Python | 1 |
s(env.cc_cfg.obs_coord)
wbpos = env.get_wbody_pos()
wbquat = env.get_wbody_quat()
ee_wpos = env.get_ee_pos(None)
bquat = env.get_body_quat() # current pose (body) in quaternion
com = env.get_com()
head_pose = env.get_head().copy()
body_com = env.get_body_com()
... | Python | 1 |
of consolidated_xx.pth",
)
parser.add_argument(
"--special_tokens",
default=None,
type=List[str],
help="The list of special tokens that should be added to the model.",
)
parser.add_argument(
"--instruct",
action="store_true",
default=False,
... | Python | 1 |
import sys
from bigO import BigO
from wrapper import * # Importa os wrappers
from functions import * # Importa as funções originais
# Inicializa o analisador de complexidade
tester = BigO()
# Lista de funções para análise
functions = [
binary_search_wrapper, # Wrapper para O(log n)
linear_search_w... | Python | 1 |
th load_pem_patch as load_pem:
with pytest.raises(ValueError):
_python_rsa.RSAVerifier.from_string(cert_bytes)
load_pem.assert_called_once_with(cert_bytes, "CERTIFICATE")
class TestRSASigner(object):
def test_from_string_pkcs1(self):
signer = _python_rsa.RSASigner.f... | Python | 1 |
= rec.map_err(|e| match e {
sqlx::Error::RowNotFound => Error::NamespaceNotFound {
name: name.to_string(),
},
_ => Error::SqlxError { source: e },
})?;
Ok(namespace)
}
}
#[async_trait]
impl TableRepo for PostgresTxn {
async fn create_or_get(... | Rust | 0 |
from rest_framework import serializers
from api.models.vitalsign import VitalSign
class VitalSignSerializer(serializers.ModelSerializer):
class Meta:
model = VitalSign
fields = [
'id', 'patient', 'recorded_by_nurse', 'recorded_by_doctor', 'date',
'blood_pressure', 'heart_rat... | Python | 1 |
Constant,
"one-minus-constant" => wgpu_types::BlendFactor::OneMinusConstant,
_ => unreachable!(),
}
}
fn serialize_blend_state(state: GpuBlendState) -> wgpu_types::BlendState {
wgpu_types::BlendState {
alpha: serialize_blend_component(state.alpha),
color: serialize_blend_component(state.color),
}... | Rust | 0 |
_size_valid(leafs, U::to_usize()));
let test_name = "test_levelcache_direct_build_from_slice";
let replica = format!("{}-{}-{}-{}-replica", test_name, leafs, len, row_count);
let lc_name = format!("{}-{}-{}-{}", test_name, leafs, len, row_count);
let temp_dir = tempdir::TempDir::new(&test_name).unwrap(... | Rust | 0 |
import torch
from torch import mean, nn
from collections import OrderedDict
from torch.nn import functional as F
import numpy as np
from numpy import random
def setup_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudn... | Python | 1 |
def f(nums, spot, idx):
nums.insert(spot, idx)
return nums | Python | 1 |
ailed) > 0:
print("\n---------------------------------------------")
print(f"The following use cases failed ({len(failed)})")
for item in failed:
print(f"[ FAILED ] : {item[0]} : {item[1]}")
total = len(passed) + len(failed)
pass_percent = len(passed) / total
print("\n-... | Python | 1 |
);
mat_submatrix!(Mat3x3, Mat2x2, 3);
macro_rules! mat_cofactor {
($V:ident, $N:expr) => {
impl<T> $V<T>
where
T: Copy + Num + Signed,
{
pub fn cofactor(self, x: usize, y: usize) -> T {
(if (x + y) % 2 == 0 {
T::one()
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.