text string | label_name string | labels int64 |
|---|---|---|
ype == DistributedType.DEEPSPEED:
self._model = accelerator.prepare(self.model)
else:
self._model = accelerator.prepare_model(self.model, evaluation_mode=True)
self.accelerator = accelerator
if self.accelerator.is_local_main_process:
lo... | Python | 1 |
from django.apps import AppConfig
class OrcamentosConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'Orcamentos'
| Python | 1 |
ase letters a-z, aa-zz, etc."""
assert value > 0
result: List[str] = []
while value != 0:
value, remainder = divmod(value - 1, len(string.ascii_lowercase))
result.append(string.ascii_lowercase[remainder])
result.reverse()
return "".join(result)
def unpad_aes(padded: bytes) -> byt... | Python | 1 |
#!/usr/bin/env python3
# Python Kubernetes client example
# This script demonstrates how to use the Python Kubernetes client library
from kubernetes import client, config
import sys
import urllib3
# Disable SSL warnings for this example
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
def main():... | Python | 1 |
ref mut size) => { *size += len; }
Node::NewlineIndentQuestionSpace (ref mut size) => { *size += len; }
Node::QuestionNewlineIndent (ref mut size) => { *size += len; }
Node::ColonNewlineIndent (ref mut size) => { *size += len; }
_ => ()
}
}
pub fn is_newl... | Rust | 0 |
///
/// # futures::executor::block_on(async {
/// # let homeserver = url::Url::parse("http://localhost:8080")?;
/// # let mut client = matrix_sdk::Client::new(homeserver)?;
/// # let room_id = matrix_sdk::ruma::room_id!("!test:localhost");
/// let content = json!({
/// "avatar_url": "mx... | Rust | 0 |
="咨询标题")
answer = models.CharField(max_length=1000, verbose_name="咨询回答")
time = models.DateTimeField(max_length=255, verbose_name="咨询回答")
course_name = models.CharField(max_length=255, verbose_name="课程名字")
class Meta:
verbose_name = '用户咨询'
verbose_name_plural = verbose_name
class User... | Python | 1 |
))) or ""}'])
env['CCCOMFLAGS'] = '$CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c $SOURCES /Fo$TARGET $CCPCHFLAGS $CCPDBFLAGS'
env['CC'] = 'cl'
env['CCFLAGS'] = SCons.Util.CLVar('/nologo')
env['CCCOM'] = '$CC $CCFLAGS $CCCOMFLAGS'
env['SHCC'] = '$CC'
env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS')
env['SHCC... | Python | 1 |
en we're trying to apply our ``tipping_ctrl``
for Travis at the cafe because the inputs would be different.
"""
tipping = ctrl.ControlSystemSimulation(tipping_ctrl)
"""
We can now simulate our control system by simply specifying the inputs
and calling the ``compute`` method. Suppose we rated the quality 6.5 out of 1... | Python | 1 |
/
pub fn render_unreleased_entry_from_template(
config: &Config,
path: &Path,
section: &str,
component: Option<String>,
id: &str,
platform_id: PlatformId,
message: &str,
) -> Result<String> {
let project_url = config
.maybe_project_url
... | Rust | 0 |
dé
Voir également setParamShapeFissure, paramètres rayonPipe et lenSegPipe.
nbSegRad = nombre de couronnes
nbSegCercle = nombre de secteurs
areteFaceFissure = taille cible de l'arête des triangles en face de fissure.
"""
self.maillageFissureParams = dict(nomRep = os.curdir, \
... | Python | 1 |
# 这个文档演示格式化输出
# 格式化方式一: 占位符
name = "zhangsan"
age = 8
price = 3.8
print("%s今年%d岁了,可以去小卖部买东西了,购买了一个包烟花了%f元" % (name, age, price))
"""
我们可以使用辅助符号"m.n"来控制数据的宽度和精度
m,控制宽度,要求是数字(很少使用),设置的宽度小于数字自身,不生效
.n,控制小数点精度,要求是数字,会进行小数的四舍五入
示例:
%3d:表示将整数的宽度控制在3位,如数字11,被设置为3d,就会变成:[空格]11,用1个空格补足宽度。
%8.2f:表示将宽度控制为8,将小数点精度设置为2
小数点和小... | Python | 1 |
let mut sogi = SOGI {
// TODO
u: [0.0; 3],
osg_u: [0.0; 3],
osg_qu: [0.0; 3],
u_q: [0.0; 2],
u_d: [0.0; 2],
ylf: [0.0; 2],
fo: 0.0,
fnom: fnom,
theta: [0.0; 2],
cos: 0.0,
sin... | Rust | 0 |
cav_hparams=None,
overwrite=False,
verbose=False):
"""Gets, creating and training if necessary, the specified CAV.
Assumes the activations already exists.
Args:
concepts: set of concepts used for CAV
Note: if there are two concepts, provide ... | Python | 1 |
1 (3)
//! [4] 0 (4) 2 1 3
//! [5] 0 4 2 (5) 1 3
//! [6] 0 4 2 5 1 (6) 3
//! [7] 0 4 2 5 1 6 3 (7)
//! [8] 0 (8) 4 2 5 1 6 3 7
//! [9] 0 8 4 (9) 2 5 1 6 3 7
//! [1] 0 8 4 9 2(10) 5 1 6 3 7
//! [2] 0 8 4 9 2 10 5(11) 1 6 3 7
//! [3] 0 8 4 9 2 10 5 11 1(12) 6 3... | Rust | 0 |
ColorStateDescriptor, ColorWrite, ComputePipelineDescriptor, CullMode, Fence, FrontFace, IndexFormat,
InputStepMode, LoadOp, PipelineLayoutDescriptor, PipelineStageDescriptor, PolygonMode, PrimitiveTopology,
RasterizationStateDescriptor, RenderPassColorAttachmentDescriptor, RenderPassDescriptor, RenderPipel... | Rust | 0 |
, n5) =
part1(carry + limbs[5] + m(n1, l[4]) + m(n2, l[3]) + m(n3, l[2]) + m(n4, l[1]));
let (carry, n6) =
part1(carry + limbs[6] + m(n2, l[4]) + m(n3, l[3]) + m(n4, l[2]) + m(n5, l[1]));
let (carry, n7) =
part1(carry + limbs[7] + m(n3, l[4]) + m(n4, l[3]) + m(n5, l[2... | Rust | 0 |
t cpu);
assert_ne!(cpu.registers.pc, 0xBEEF);
assert_eq!(cpu.machine_cycles, 0);
}
}
// https://leetcode.com/problems/longest-continuous-increasing-subsequence/
// 3 ms, 2.2 MB
impl Solution {
pub fn find_length_of_lcis(nums: Vec<i32>) -> i32 {
let mut maxCnt = 1;
let mut cnt = ... | Rust | 0 |
!status.success() {
fail(&format!("command did not execute successfully, got: {}", status));
}
}
fn prepend(var: &str, val: PathBuf) {
let prefix = env::var(var).unwrap_or(String::new());
let mut v = vec![val];
v.extend(env::split_paths(&prefix));
env::set_var(var, &env::join_paths(v).unwr... | Rust | 0 |
ref()),
("timeAssigned", &goal.time_assigned),
(
"achieved",
if goal.time_achieved.is_some() {
"1"
} else {
"0"
},
),
("rate", &format!("{}", goal.rate)),
("wife", &format!("{}", goal.wifescore)),
(
"timeAchieved",
goal.time_achieved
... | Rust | 0 |
let mut i = 0;
while !found_dist.contains(blocks) {
found_dist.insert(blocks.to_vec());
do_redistribute(blocks);
i += 1;
}
i
}
fn main() {
println!("Please enter the blocks separated by a tab:");
let mut val = String::new();
io::stdin().read_line(&mut val).expect("Fa... | Rust | 0 |
from sympy.core.numbers import Integer
from sympy.matrices.dense import (eye, zeros)
i3 = Integer(3)
M = eye(100)
def timeit_Matrix__getitem_ii():
M[3, 3]
def timeit_Matrix__getitem_II():
M[i3, i3]
def timeit_Matrix__getslice():
M[:, :]
def timeit_Matrix_zeronm():
zeros(100, 100)
| Python | 1 |
rom . import matrixlib as _mat
from .matrixlib import *
from .compat import long
# Make these accessible from numpy name-space
# but not imported in from numpy import *
if sys.version_info[0] >= 3:
from builtins import bool, int, float, complex, object, str
unicode = str
else:
... | Python | 1 |
pe should not have changed.
assert_eq!(*entry.addr_sub(), slaac_addr_sub);
assert_eq!(entry.state, AddressState::Assigned);
assert_eq!(entry.config_type(), AddrConfigType::Slaac);
// Address invalidation timers were added.
assert_eq!(ctx.dispatcher.timer_events().count(), 2);
... | Rust | 0 |
ause the token to be
/// reinitialized.
pub const CKF_TOKEN_INITIALIZED: CK_FLAGS = 0x400;
/// Secondary authentication.
///
/// If it is true, the token supports secondary authentication for private
/// key objects.
pub const CKF_SECONDARY_AUTHENTICATION: CK_FLAGS = 0x800;
/// User PIN count low.
///
/// If it is tr... | Rust | 0 |
Info, ctrlInfo, newCInfo, cbf_obs, cbf_agent,reached_targets = reset_state()
dis = 2.6
iterations += 1
break
if all(reached_targets):
print(f'dis: {dis}')
success = True
break
elif i == info.maxStep:
... | Python | 1 |
: String) -> Token {
Token { kind, len, raw }
}
}
/// Enum representing common lexeme types.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum TokenKind {
/// Any whitespace characters sequence.
Whitespace,
Literal {
kind: LiteralKind,
},
/// Keywords such a... | Rust | 0 |
Ok(hm)
}
FromConfigFile(ref config_file) => {
let filepath = Path::new(&config_file[..]);
let mut file_content = String::new();
File::open(filepath)
.and_then(|mut f| f.read_to_string(&mut file_content))
.map_err(|_| {
... | Rust | 0 |
)
}
/// The second collider involved in this contact pair.
pub fn collider2(&self) -> Entity {
self.context.collider_entity(self.raw.collider2).unwrap()
}
/// The number of contact manifolds detected for this contact pair.
pub fn manifolds_len(&self) -> usize {
self.raw.manifol... | Rust | 0 |
r HuyaUser {
fn _decode_from(decoder: &mut TarsDecoder) -> Result<Self, DecodeErr> {
let uid = decoder.read_int64(0, false, -1)?;
let imid = decoder.read_int64(1, false, -1)?;
let name = decoder.read_string(2, false, "".to_string())?;
let gender = decoder.read_int32(3, false, -1)?;
... | Rust | 0 |
{
fn description(&self) -> &str {
match *self {
StartSpeechSynthesisTaskError::InvalidS3Bucket(ref cause) => cause,
StartSpeechSynthesisTaskError::InvalidS3Key(ref cause) => cause,
StartSpeechSynthesisTaskError::InvalidSampleRate(ref cause) => cause,
StartSpe... | Rust | 0 |
e_and_be_called() {
// Arrange
let mut bus = SimpleEventBus::new();
let action_id = "test";
let received = Arc::new(Mutex::new(String::from("")));
let clone = received.clone();
bus.subscribe_to_action(
action_id,
Box::new(move |message: Action| {
... | Rust | 0 |
/// let res = Custom(status, format!("404: {}", req.uri()));
/// Box::pin(async move { res.respond_to(req) })
/// }
///
/// fn handle_500<'r>(_: Status, req: &'r Request<'_>) -> ErrorHandlerFuture<'r> {
/// Box::pin(async move{ "Whoops, we messed up!".respond_to(req) })
/// }
/... | Rust | 0 |
let path = pb.finish().unwrap();
let mut pixmap = Pixmap::new(100, 100).unwrap();
pixmap.fill_path(&path, &paint, FillRule::Winding, Transform::identity(), None);
let expected = Pixmap::load_png("tests/images/fill/winding-star.png").unwrap();
assert_eq!(pixmap, expected);
}
#[test]
fn even_odd_star()... | Rust | 0 |
}
}
use crate::scanner::Token;
/// Get unary precedence of token.
pub fn get_unary_precedence(token: &Token) -> u8 {
get_operator_precedence(token).0
}
/// Get binary precedence of token.
pub fn get_binary_precedence(token: &Token) -> u8 {
get_operator_precedence(token).1
}
/// Return true if the token rep... | Rust | 0 |
/ draws_actual
logger.info(f"📊 Draw Stats: {draws_predicted} predicted, {draws_actual} actual")
logger.info(f"📊 Draw Recall: {draw_recall:.1%}")
print(f"\n📊 Cascade Model (thresh={draw_threshold}) Classification Report:")
print(classification_report(data['y_test_3class'], y_pred_cascade,
... | Python | 1 |
chist_shifted <= cref)])
cref = np.min(chist_shifted[np.logical_and(fhist < fref, phi <= phimin)])
fref = np.min(fhist[chist_shifted <= cref])
# Can't use argmin here because using it with a mask throws off the index
kopt = np.ma.array(chist, mask=(fhist > fref)).argmin()
#========... | Python | 1 |
e.sleep(0.1)
count += 1
print("end of armijoMin algorithm")
time.sleep(1)
return alpha
def firstStep(iteration, initGuess, preX=float('inf')):
"""first step initialization"""
if iteration == 1:
x = initGuess
return x
else:
x = preX
return x
... | Python | 1 |
"resnet50_l2_eps5"]
VISION_TRANSFORMER_MODELS = ["vit_small_patch16_224", "vit_base_patch16_224",
"vit_large_patch16_224"]
BIT_M_MODELS = ["BiTM_resnetv2_50x1", "BiTM_resnetv2_50x3", "BiTM_resnetv2_101x1",
"BiTM_resnetv2_101x3", "BiTM_resnetv2_152x2", "BiTM_resnetv2_... | Python | 1 |
earning/nand2tetris/projects/07/MemoryAccess/BasicTest/BasicTest.vm".to_string();
let simple_add_test = "/Users/julian/Experiments/coursera_learning/nand2tetris/projects/07/StackArithmetic/SimpleAdd/SimpleAdd.vm".to_string();
let stack_test = "/Users/julian/Experiments/coursera_learning/nand2tetris/projects/0... | Rust | 0 |
# Demonstrate how to customize logging output
import logging
# TODO: add another function to log from
# set the output file and debug level, and
# TODO: use a custom formatting specification
logging.basicConfig(filename="output.log",
level=logging.DEBUG)
logging.info("This is an info-level log ... | Python | 1 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from pathlib import Path
import importlib
# automatically import any Python files in the criterions/ directory
for file in sorted(Path(__file__).parent.glob("*.py")):
if not file.name.startswith("_"):
importlib.import_module("graphor... | Python | 1 |
#!/usr/bin/env python3
from typing import Optional
import torch as th
import torch.nn.functional as F
from diffusers import DDIMScheduler
def diffusion_loss(preds: th.Tensor,
trajs: th.Tensor,
noise: th.Tensor,
noisy_trajs: th.Tensor,
steps:... | Python | 1 |
for_bytearray {
($($wrapper:ident, $size:ident;)*) => {$(
impl $crate::traits::FromBase64 for $wrapper {
type Error = $crate::traits::EncodingError;
fn from_base64(s: &str) -> core::result::Result<Self, $crate::traits::EncodingError> {
if s.len() % 4 != 0 {
... | Rust | 0 |
pose = None
self.scratch.refinenet1 = _make_fusion_block(features, use_bn)
self.scratch.refinenet2 = _make_fusion_block(features, use_bn)
self.scratch.refinenet3 = _make_fusion_block(features, use_bn)
self.scratch.refinenet4 = _make_fusion_block(features, use_bn)
head_features_... | Python | 1 |
ey.lower()][1]
def __len__(self):
return len(self._store)
def __eq__(self, other):
return isinstance(other, Mapping) and {
k.lower(): v for k, v in self.items()
} == {k.lower(): v for k, v in other.items()}
def __iter__(self):
return (original_key for original_... | Python | 1 |
ead::spawn(move || {
helper::continuous_read(id, clk_time, seconds, flg1);
});
let flg2 = Arc::clone(&flag);
let data = Arc::new(Mutex::new(Vec::<RawDataset>::with_capacity(DATA_SIZE)));
let data_cln = Arc::clone(&data);
let job_runner = thread::spawn(move || {
helper::get_data(id,... | Rust | 0 |
)
def test_model_forward_not_implemented(self):
"""Test not overriding forward() causes TypeError."""
model_name = "NSS"
model_version = "4"
with self.assertRaisesRegex(TypeError, r"must override forward\(\)"):
@register_model(model_name, model_version)
... | Python | 1 |
'''Определите площадь получившейся фигуры в квадратных единицах.
'''
from turtle import*
tracer(0)
lt(90)
screensize(10000,10000)
r=20
for i in range(8):
for k in range(4):
fd(5*r)
rt(30)
fd(6*r)
rt(150)
rt(60)
up()
for x in range(-50,50):
for y in range(-50,50):
go... | Python | 1 |
[]
nback_labels = []
with torch.no_grad():
for actions, targets in loader:
if len(all_hidden_states) >= max_samples:
break
actions, targets = actions.to(DEVICE), targets.to(DEVICE)
_, hidden_states = model(actions, return_hidden=True)
... | Python | 1 |
print(f"Fold {fold + 1}/{FOLD} - Test Accuracy: {test_accuracy:.4f}, Test F1 Score: {test_f1:.4f}, Test Precision Score: {test_precision:.4f}\nTest F1_All: {test_f1_all}\n\n")
acc_mean, acc_std = compute_mean_std(test_ACC)
f1_mean, f1_std = compute_mean_std(test_F1)
pre_mean, pre_std = compute_me... | Python | 1 |
r#"{"value":1.0}"#);
check_deserialization(
Structf64Flexible { value: half_second },
r#"{"value":"0.5"}"#,
);
check_deserialization(Structf64Flexible { value: one_second }, r#"{"value":"1"}"#);
check_deserialization(Structf64Flexible { value: zero }, r#"{"value":"0"}"#);
check_erro... | Rust | 0 |
///
/// use bollard::volume::CreateVolumeOptions;
///
/// use std::default::Default;
///
/// let config = CreateVolumeOptions {
/// name: "certs",
/// ..Default::default()
/// };
///
/// docker.create_volume(config);
/// ```
pub async fn create_volume<T>(&self, co... | Rust | 0 |
Vec<Range> {
let (doc, line_index) = match self.files.get(uri) {
Some((doc, line_index)) => (doc, line_index),
None => return selections.to_vec(),
};
let mut res = Vec::new();
for &sel in selections.iter() {
let sel = from_vs_range(sel, line_index);
... | Rust | 0 |
from typing import List
def solve(grid: List[List[int]]) -> List[List[int]]:
h = len(grid)
w = len(grid[0])
res = [row[:] for row in grid]
for i in range(1, h-1):
for j in range(1, w-1):
if grid[i][j] == 0 and grid[i-1][j] == 0 and grid[i+1][j] == 0 and grid[i][j-1] == 0 and grid[i]... | Python | 1 |
cost': 900,
'max_connection_cost': 937,
'min_hub_capacity': 100,
'max_hub_capacity': 3000,
'min_maintenance_cost': 75,
'max_maintenance_cost': 2500,
'max_zones': 45,
'min_maintenance': 50,
'max_maintenance': 500,
'min_utility_cost': 100,
'm... | Python | 1 |
"#;
const MD_INSTALL_DONE: &str = r#"
The **br** function has been installed.
You may have to restart your shell or source your shell init files.
Afterwards, you should start broot with `br` in order to use its full power.
"#;
const REFUSED_FILE_CONTENT: &str = r#"
This file tells broot you refused the installation o... | Rust | 0 |
_path()
test_alter_layout_lrn()
test_alter_layout_resnet()
test_alter_layout_broadcast_op()
test_alter_layout_broadcast_scalar_op()
test_alter_layout_scalar()
test_alter_layout_concatenate()
test_alter_layout_nchw_upsamping_op()
test_alter_layout_strided_slice()
test_alter_layout_dep... | Python | 1 |
ndError::from(e)),
};
let inset_url: Option<String> = match get_character_media(
&realm_name,
character_name,
&access_token,
Some(character.race.id),
Some(&character.gender.t),
)
.await
{
Ok(media) => media.assets.and_then(|assets| {
asset... | Rust | 0 |
nums = []
def add(nums_list):
result = 0
for num in nums_list:
result += num
return result
def subtract(nums_list):
result = nums_list[0]
nums_list.pop(0)
for num in nums_list:
result -= num
return result
def multiply(nums_list):
result = nums_list[0]
nums_list.pop... | Python | 1 |
import os
import numpy as np
from setuptools import Extension
REPROJECT_ROOT = os.path.relpath(os.path.dirname(__file__))
def get_extensions():
libraries = []
sources = []
sources.append(os.path.join(REPROJECT_ROOT, "_overlap.pyx"))
sources.append(os.path.join(REPROJECT_ROOT, "overlapArea.c"))
... | Python | 1 |
z2 = x + "a"
"#,
err: "error @2:17-2:18: undefined identifier y",
}
}
#[test]
#[ignore]
fn error_types_do_not_suppress_additional_actual_errors() {
test_error_msg! {
src: r#"
x = y - 1
z = x + ""
"#,
// Should get an int != string error here, b... | Rust | 0 |
en compared
against the media-ranges in ranges. For example:
>>> quality('text/html','text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5')
0.7
"""
parsed_ranges = map(parse_media_range, ranges.split(','))
return quality_parsed(mime_type, parsed_ranges)
def be... | Python | 1 |
multi_line_1.chart_prop.set_legend_values(vec![
String::from("Location 1"),
String::from("Location 2"),
String::from("Location 3"),
]);
multi_line_1.draw();
let mut multi_line_3 = chart_builder::LineChart::new(
String::from("Test Line Chart 6"),
data_1.clone(),
... | Rust | 0 |
a firewall alias")
async def delete_from_alias(ctx: Context, alias_name: str, address: str) -> str:
"""Delete an entry from a firewall alias.
Args:
ctx: MCP context
alias_name: Name of the alias
address: IP address, network, or hostname to delete
Returns:
JSON string with ... | Python | 1 |
# Copyright (C) 2022-2025 Intel Corporation
# LIMITED EDGE SOFTWARE DISTRIBUTION LICENSE
"""Implementation of VideoFrameReader"""
import logging
import os
import time
from collections.abc import Callable
import numpy as np
from media_utils.video_decoder import VideoDecoder, VideoFrameReadingError
NUM_VIDEO_FRAME_D... | Python | 1 |
# ------------------------------------------------------
# -------------------- mplwidget.py --------------------
# ------------------------------------------------------
# from PySide2.QtCore import Qt
# from PySide2.QtWidgets import QWidget, QVBoxLayout
# IMPORT PACKAGES AND MODULES
# ///////////////////////////////... | Python | 1 |
node
numcheck += 1
if time.time()-starttime >= maxtime and numcheck >= mincheck:
break
globals.flags.pop("train_mode")
# No errors? Then simply return
if len(failures) == 0:
logging.info("gradient check PASSED")
return
msg = "...gradie... | Python | 1 |
: 'cent', # Align with center
'full' : 'full', # Align with both left and right margins
}
_Enum_styl = {
'plain' : 'plan', # Plain
'bold' : 'bold', # Bold
'italic' : 'ital', # Italic
'outline' : 'outl', # Outline
'shadow' : 'shad', # Shadow
'underline' : 'undl', # Underlin... | Python | 1 |
en),
}
.ok_or_else(|| error(self, slot))
}
pub(crate) fn get_slot_local(
&self,
slot: LocalSlotId,
name: &str,
) -> anyhow::Result<Value<'v>> {
// Make sure the error-path doesn't get inlined into the normal-path execution
#[inline(never)]
fn ... | Rust | 0 |
st_hiragana_n() -> Result<(), kanabake::error::Error> {
assert_eq!(kanabake::to_hiragana("n")?, "ん");
assert_eq!(kanabake::to_hiragana("nna")?, "んな");
assert_eq!(kanabake::to_hiragana("nnn")?, "んんん");
Ok(())
}
#[test]
fn test_hiragana_variants() -> Result<(), kanabake::error::Error> {
assert_eq!(ka... | Rust | 0 |
i16, BigEndian, 5>>::SIZE
);
}
#[test]
fn test_i32_littleendian() {
let mut storage = vec![0; 1024];
type Field1 = WrappedField<i32, Wrapped<i32>, PrimitiveField<i32, LittleEndian, 5>>;
type Field2 = WrappedField<i32, Wrapped<i32>, PrimitiveField<i32, LittleEndian, 20>>;
... | Rust | 0 |
import pytest
from tests.conftest import DATADIR, TABLES, create_dummy_config_file
from suzieq.sqobjects import get_sqobject
@ pytest.mark.schema
@ pytest.mark.parametrize('table',
[pytest.param(x,
marks=getattr(pytest.mark, x))
... | Python | 1 |
import os
from typing import TYPE_CHECKING, Any, Callable
if TYPE_CHECKING:
# PyTorch
CUDA_VISIBLE_DEVICES: list[int]
# All environment variables with their type parsers
_ENV_PARSERS: dict[str, Callable[[str], Any]] = {
"CUDA_VISIBLE_DEVICES": lambda x: list(map(int, x.split(","))),
}
# Subset of enviro... | Python | 1 |
wrap_or_else(|_| DEFAULT_GRID_STATE_DIR.to_string())
}
#[cfg(any(
feature = "purchase-order",
feature = "product",
feature = "xsd-downloader"
))]
fn get_grid_xsd_dir() -> PathBuf {
PathBuf::from(get_grid_state_dir()).join("xsd")
}
<filename>leetcode/src/d1/_199_binary_tree_right_side_view.rs<gh_stars>1... | Rust | 0 |
default_initial_settings = {
"name": "Signal Pro 300 v2",
"manufacturer": "ATMAT sp. z o.o.",
"start_gcode": "G21 ; set units to millimeters\nG90 ; use absolute positioning\nM82 ; absolute extrusion mode\nG28 ; home all without mesh bed level\nM420 S1\nG92 E0.0 ; reset extruder distance position\nG1 Z0.25\n... | Python | 1 |
ndar::rule::Rule;
use calendar::rule_item::RuleItem;
use calendar::offset_kind::OffsetKind;
use calendar::repetition_kind::RepetitionKind;
use calendar::time_interval::TimeInterval;
use chrono::{Duration};
#[test]
fn rule_works() {
// the work day starts at 9:15am with duration 8h 45min (ends at 6:00pm)
let ... | Rust | 0 |
Arc::new(tesseract::monitor::Monitor::new()),
));
}
}
<filename>src/main.rs<gh_stars>1-10
#![no_std]
#![no_main]
extern crate panic_halt;
use cortex_m_rt::entry;
use stm32f4xx_hal as _;
#[entry]
fn main() -> ! {
loop {}
}
<filename>tinfoil-macros/src/implementation.rs
use darling::FromField;
use quo... | Rust | 0 |
pub fn generationnumber_getvalue(&self) -> String {
self.generationnumber.get_value()
}
pub fn generationnumber_setvalue(&mut self, number: char) {
self.generationnumber.set_value(number);
}
/******************* GRID NAME ***********************/
pub fn gridname_getcursor(&self) -> (u16,... | Rust | 0 |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
CamemBERT: a Tasty French Language Model
"""
from fairseq.models import register_model
from .hub_interface import RobertaHubInterface
fro... | Python | 1 |
[derive(Accounts)]
pub struct CreateCounter<'info> {
#[account(mut)]
pub user: Signer<'info>,
// Space Reference: https://book.anchor-lang.com/chapter_5/space.html
// space: 8 discriminator + 1 bump + 1 count
#[account(
init, payer = user, space = 8 + 1 + 1,
seeds = [b"counter", user... | Rust | 0 |
_node);
self.perms.proof_insert(self.ptrs.len() - 2, penult_perm);
}
self.ptrs = self.ptrs.drop_last();
assert(self.wf_head());
assert(self.wf_tail());
if self.ptrs.len() > 0 {
/*#[spec] let i = self.ptrs.len() - 1;
assert(self.ptrs.len() ==... | Rust | 0 |
Http11;
let given = create_via_header(None, &version);
assert_eq!(Via("1.1 weldr".to_owned()), given);
let given = create_via_header(Some(&via), &version);
assert_eq!(Via("1.0 proxy, 1.1 weldr".to_owned()), given);
}
#[test]
/// Per RFC 2616 Section 13.5.1 - MUST remove ... | Rust | 0 |
(1, 1, 0),
(1, 1, 1),
(1, 2, 1),
(2, 1, 1),
(2, 1, 2),
(0, 1, 1),
(0, 0, 2),
(1, 2, 2),
(2, 0, 2),
(0, 0, 0),
(0, 2, 0),
(0, 2, 0),
];
static LINE_EVAL_VALUES: [u8; 50] = [
1, 5, 5, 0, 0, 1, 1, 5, 5, 5, 1, 1, 1, 0, 1... | Rust | 0 |
Routes::Index => index::view(),
Routes::Grades => grades::view(model),
Routes::Subjects => subjects::view(model),
Routes::Teachers => teachers::view(model),
Routes::Admin => admin::view(model),
}
}
],
]
}
#[wasm_bindgen(start)]
pub fn render() {
App::builder(update, view)
.after_mount... | Rust | 0 |
erence.setdefault("framework", "vllm")
config.inference.setdefault("max_new_tokens", None)
# Evaluation
config = _validate_and_fill_eval_config(config)
return config
def _validate_and_fill_eval_config(config: DictConfig) -> DictConfig:
provider = config.evaluation.provider.lower()
... | Python | 1 |
})
}
use crate::articles::article::Article;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Serialize, Deserialize, Debug)]
pub struct Inventory {
pub articles: HashMap<String, Article>,
}
impl Inventory {
pub fn new() -> Self {
Self {
articles: HashMap::new... | Rust | 0 |
ount = sum(1 for idx in ring if mol.GetAtomWithIdx(idx).GetSymbol() == "N")
if n_count != 2:
continue
# Additionally, verify that at least one ring atom (or its immediate neighbor outside the ring)
# carries a carbonyl (C=O). Look over all bonds around ring atoms.
ca... | Python | 1 |
en(dat)-8):
x = u64(dat[i:i+8])
if x & 0xfff == 0x67e:
binary_addrs[x] += 1
if (x >> 40) == 0x7f and (u64(dat[i+8:i+16]) >> 40) == 0x7f and not libc:
# found arena pointer pair
libc = x - 0x1dd000 - (x&0xfff)
if dat[i:i+4] == 'AAAA' and dat[i+0x50:i+0x54] == 'AAAA':
cooki... | Python | 1 |
de='I'):
"""returns the list of defined MAP application-contexts that include the MAP
operation(s) for the given opcode
mode: 'I' for Initiator or 'R' for Responder
"""
ret = {}
key = ('Symmetric', 'InitiatorConsumerOf') if mode in ('I', 'i') else ('Symmetric', 'ResponderConsumerOf')
... | Python | 1 |
1\\\"\" ]\n \
2 [ label = \"\\\"0.1.1\\\"\" ]\n \
3 [ label = \"\\\"0.1\\\"\" ]\n \
0 -> 1 [ label = \"\\\"RoleC?RoleA: Update\\\"\" ]\n \
1 -> 2 [ label = \"\\\"RoleC!RoleA: Okay\\\"\" ]\n \
2 -> 0 [ label = \"\\\"µ\\\"\" ]\n \
0... | Rust | 0 |
L: LockManager, F: KvFormat>(
storage: &Storage<E, L, F>,
requests: Vec<u64>,
gets: Vec<GetRequest>,
tx: Sender<MeasuredSingleResponse>,
begin_instant: tikv_util::time::Instant,
) {
REQUEST_BATCH_SIZE_HISTOGRAM_VEC
.kv_get
.observe(gets.len() as f64);
let ids = requests.clone... | Rust | 0 |
remark: str):
"""
:param flag: 请求ID
:param approve: 是否同意
:param remark: 备注
:return: 设置好友请求
"""
return (
"/set_friend_add_request",
{"flag": flag, "approve": approve, "remark": remark},
)
async def set_self_long_nick(self, longn... | Python | 1 |
'''
The compiler is not implemented in the simulator. This module provides a stub
to allow tests to import successfully.
'''
compile = None
compile_for_current_device = None
compile_ptx = None
compile_ptx_for_current_device = None
| Python | 1 |
import json
# paths
COCO_SEG_CONFIG_PTH = "./imports/pointrend/config/pointrend_rcnn_R_50_FPN_3x_coco.yaml"
COCO_SEG_WEIGHTS_PTH = "./imports/pointrend/weights/model_final_edd263.pkl"
COCO_THING_CLASSES_PTH = "constants/coco_thing_classes.json"
LVIS_SEG_CONFIG_PTH = "LVISv0.5-InstanceSegmentation/mask_rcnn_X_101_32x8... | Python | 1 |
= sum([volume.volume_unpaid_cost_estimate for volume in final_catalog_list])
# 如果本书所有章节都是不需要积分查看的 => 直接起飞
if quote == 0:
# 1
self.logger.info("当前所有卷都是免费积分或你已经购买,直接执行下载。")
return new_novel, final_catalog_list, 'NOT_NEED_RESET_SESSION'
else:
# 2
... | Python | 1 |
ign! {
//! /// Factory for terms. Uses the standard library's "SipHash".
//! let factory = consign(37, RandomState::new()) for ActualSum;
//! }
//!
//! fn main() {
//! // Map from terms. Uses the standard library's "SipHash".
//! let map = HConMap::<Sum, usize, RandomState>::with_hasher(RandomState::new... | Rust | 0 |
:.3f}GB\\\\')
print('--------------')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--batch_size', type=int,
help='Batch size',
default=1,
)
parser.add_argument(
'--prefill_seq_len', type=int,
help='Size of ... | Python | 1 |
Debug, Clone)]
pub struct Edge_label_holdout_Params {
pub train_size : f64,
pub use_stratification : bool,
pub random_state : EdgeT,
}
#[derive(Arbitrary, Debug, Clone)]
pub struct Random_subgraph_Params {
pub random_state : usize,
pub nodes_number : NodeT,
pub verbose : bool,
}
#[derive(Arbitrary, Debug, Clone)... | Rust | 0 |
::Something] => Some(()),
//! [@] => None
//! }
//! }
//! # }
//! ```
//!
//! Everything seems familiar except `[@]`. What is that?
//! Grammars have the concept of an 'empty token'. It's usually called `epsilon` and that's how
//! we'll call it as well. It's used to match the empty string `""` or in our ca... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.