text string | label_name string | labels int64 |
|---|---|---|
ha': 0.1,\n"
"```\n"
"\n"
"**Hyperparameter Grid:**\n"
"```python\n"
"'alpha': [0.01, 0.1, 1.0],\n"
"```"
)
assert ridge_wrapper.to_markdown() == expected_ridge_md
expected_mlp_md = (
"### MLP (`mlp`)\n"
... | Python | 1 |
str().unwrap(),
web::post().to(serve_upload)
)
// serve uploaded image files from `uploaded_files` as `directed_to`
// for example, `./tmp/*.png` will be accessed from `https://web.site/img/*.png`
.service(
Files::new(
&format!(
... | Rust | 0 |
number of queries, the current memory consumption is evaluated, before further processing occurs.
/// Queries are accelerated with a default Multi-Metric potential which is updated after 50000 queries each
///
/// Additional parameters: <path_to_graph> <path_to_queries> <query_breakpoints, comma-separated> <buckets = ... | Rust | 0 |
ONTIGUOUS'] for arr in arrays)
C_order = all(arr.flags['C_CONTIGUOUS'] for arr in arrays)
order = 'F' if F_order and not C_order else 'C'
result = _nx.empty(shape=shape, dtype=dtype, order=order)
# Note: In a c implementation, the function
# PyArray_CreateMultiSortedStridePerm could be used for more... | Python | 1 |
KindInner::PtrValue(inner) => inner.$func($($arg_name)*),
ValueKindInner::VmaValue(inner) => inner.$func($($arg_name)*),
ValueKindInner::DataValue(inner) => inner.$func($($arg_name)*),
ValueKindInner::GroupValue(inner) => inner.$func($($arg_name)*),
... | Rust | 0 |
from eth.vm.forks.byzantium.computation import (
BYZANTIUM_PRECOMPILES,
ByzantiumComputation,
)
from eth.vm.gas_meter import (
GasMeter,
allow_negative_refund_strategy,
)
from .opcodes import (
CONSTANTINOPLE_OPCODES,
)
CONSTANTINOPLE_PRECOMPILES = BYZANTIUM_PRECOMPILES
class ConstantinopleCompu... | Python | 1 |
{tags}
</div>
}
}
#[derive(Clone, Debug, PartialEq, Properties)]
pub struct ShowDetailProps {
pub post_id: u64,
}
#[function_component(ShowDetail)]
fn app(ShowDetailProps { post_id }: &ShowDetailProps) -> Html {
let detail_url = format!("/post/show/{}", post_id);
let post_detail = use_stat... | Rust | 0 |
ORIGINAL, &mut receptor_3, None).await;
}
/// Verifies delivery statuses are properly relayed back to the original sender.
#[fuchsia_async::run_singlethreaded(test)]
async fn test_delivery_status() {
let hub = MessageHub::<TestMessage, TestAddress>::create();
let known_receiver_address = TestAddress::Foo(2);
... | Rust | 0 |
patch_size: Size of the patches.
Returns:
A tensor of shape (B, N, C, patch_size, patch_size), where N is the
number of patches.
"""
B, _, H, W = x.shape
assert (
H % patch_size == 0 and W % patch_size == 0
), "Image dimensions must be divisible by patch size."
x = ein... | Python | 1 |
}
}
net.sf.jasperreports.engine.query.QueryClauseFunctionBundle
mod _inner;
pub mod quads;
pub mod triples;
#[cfg(test)]
mod test_data {
//! These test data snippets are copied from sophia tests
//!
pub static TESTS_NQUADS: &[&str] = &[
r#"<http://champin.net/#pa> <http://www.w3.org/1999/02/2... | Rust | 0 |
Dark pool analysis and inference tool. | Python | 1 |
scaled_loss = info_dict['loss_dict']['loss'] / info_dict['accum_grad']
scaled_loss.backward()
info_dict['loss_dict']['loss'] = scaled_loss
return info_dict
def update_parameter_and_lr(model, optimizer, scheduler, info_dict):
grad_norm = 0.0
if info_dict['train_engine'] == "deepspeed":... | Python | 1 |
case were we considered an i8 as an u8 and still get the right x - max.
let safe_u8 = if src_is_signed { |x: &u8| x.wrapping_add(128) } else { |x: &u8| *x };
let max = view.iter().map(|it| safe_u8(it)).max().unwrap();
view.iter().zip(buffer.iter_mut()).for_each(|(x, exp)| {
let input_diff = safe_u... | Rust | 0 |
#!/usr/bin/python3
""" 16-main """
from models.rectangle import Rectangle
if __name__ == "__main__":
list_input = [
{'id': 89, 'width': 10, 'height': 4},
{'id': 7, 'width': 1, 'height': 7}
]
json_list_input = Rectangle.to_json_string(list_input)
list_output = Rectangle.from_json_strin... | Python | 1 |
b fn ExecMaterializeSlot(slot: *mut TupleTableSlot) -> HeapTuple;
}
#[pg_guard]
extern "C" {
pub fn ExecPartitionCheck(
resultRelInfo: *mut ResultRelInfo,
slot: *mut TupleTableSlot,
estate: *mut EState,
emitError: bool,
) -> bool;
}
#[pg_guard]
extern "C" {
pub fn ExecPartiti... | Rust | 0 |
<h2>Login Form </h2>
<form class="myForm" method="get" enctype="application/x-www-form-urlencoded" action="/html/codes/html_form_handler.cfm">
<label class="aud
ioOnly" for="user_email">Email</label>
<input type="email" name="user_email" required placeholder="Email">
<label class="audioOnly" for="user_pwd">Passwo... | Python | 1 |
#
# Copyright © 2025 Agora
# This file is part of TEN Framework, an open source project.
# Licensed under the Apache License, Version 2.0, with certain conditions.
# Refer to the "LICENSE" file in the root directory for more information.
#
from enum import IntEnum
from typing import TypeVar, cast
from libten_runtime_p... | Python | 1 |
k: u32,
pub compressed_length: u32, // 32000 if not compressed
pub uncompressed_length: u32,
}
pub struct SqPackRawFile {
pub uncompressed_size: u32,
pub header: Bytes,
pub blocks: Vec<Bytes>,
}
impl SqPackRawFile {
pub fn from_blocks(uncompressed_size: u32, header: Bytes, blocks: Vec<Bytes>) ... | Rust | 0 |
清除失败, {exec_shell[1]}")
server.log(f"[清理缓存] {exec_shell[0]}")
return public.returnMsg(True, "清除成功")
def server_status(self, args):
server = alidrive_server()
return {
"status": server.server_status(),
"core_status": server.alidrive_status(),
}
de... | Python | 1 |
use consensus::{ConsensusParams, ConsensusFork, BitcoinCashConsensusParams, SegWit2xConsensusParams};
pub use deployments::Deployment;
pub use network::{Magic, Network};
<gh_stars>0
/// Represents a vowel in the Japanese language.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Vowel {
A,
I,
U,... | Rust | 0 |
from django import template
register = template.Library()
@register.filter
def dict_key(d, key):
if isinstance(d, dict):
return d.get(key)
return None
| Python | 1 |
relude::*;
type TensorType = Vec<Vec<f32>>;
type EError = EncephalonError;
pub struct LinearRegressor {
input_size: usize,
weights: Tensor,
}
impl LinearRegressor {
pub fn new(input_size: usize) -> Result<Self, EError> {
if input_size == 0 {
return Err(EError::new("Linear Regression n... | Rust | 0 |
ind_community_item<'a>(&'a self) -> BTreeSet<BgpCommunity> {
let mut ret: BTreeSet<BgpCommunity> = BTreeSet::new();
for i in self.terms.iter() {
if i.predicate==FilterItemMatchResult::No {
continue
};
match &i.item {
FilterItem::Community... | Rust | 0 |
from ir_measures import measures
class _SetP(measures.Measure):
"""
The Set Precision (SetP); i.e., the number of relevant docs divided by the total number retrieved
"""
__name__ = 'SetP'
NAME = __name__
PRETTY_NAME = 'Set Precision'
SHORT_DESC = 'The precision among all returned documents... | Python | 1 |
l_todos_from_source_code_files(&source_files);
let github_issues = api.get_closed_issues();
if let Some(issues) = github_issues {
let compared_todos_and_issues = compare_todos_and_issues(&source_code_todos, &issues);
if compared_todos_and_issues.is_empty() {
println!("No unreported ... | Rust | 0 |
ublished'].unique())
data['status_type'].unique()
len(data['status_type'].unique())
# Data preprocessing For model fitting
data.drop(['status_id', 'status_published'], axis=1, inplace=True)
data.info()
data.head()
# Feature vector and Targtet Variable
X = data
y = data['status_type']
# Convert Categorical variable ... | Python | 1 |
U3-13S2M returns values in kelvins.
if *self.temperature_abs_supported.as_ref().unwrap() {
let mut val_out = std::mem::MaybeUninit::uninit();
if dc1394error_t::DC1394_SUCCESS != unsafe { dc1394_feature_get_absolute_value(
cam, dc1394feature_t::DC1394_FEATURE_TEMPERATURE,... | Rust | 0 |
from .loader import LTRLoader | Python | 1 |
ow<'a, str>>,
#[serde(borrow, default)]
changes: Vec<Cow<'a, str>>,
}
pub fn read_game_version(assets_dir: &Path) -> AnyResult<RcString> {
let abs_changelog_path = assets_dir.join(*CHANGELOG_FILE_PATH);
let mut changelog_bytes = Vec::new();
let changelog_data: ChangelogFileRef =
utils::json::read_file(&... | Rust | 0 |
("enum def should point to EnumDef node");
let variants = if let Some(vl) = enum_def.variant_list() {
vl.variants()
.filter_map(|variant_def| {
let name = variant_def.name().map(|n| n.as_name());
name.map(|n| {
let def_... | Rust | 0 |
# Copyright 2017, Google, Inc.
# 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 |
ystick
}
fn watchdog(&self) -> &Self::WatchDog {
&()
}
fn context_switch_callback(&self) -> &Self::ContextSwitchCallback {
&()
}
}
/// Main function.
///
/// This is called after RAM initialization is complete.
#[no_mangle]
pub unsafe fn main() {
apollo3::init();
let periph... | Rust | 0 |
_args(&method);
let arg_names = compute_arg_identifiers(&args).unwrap();
let returns = match compute_returns(method) {
Ok(r) => r,
Err(e) => panic!(e)
};
if arg_names.len() < 2 {
panic!("network R... | Rust | 0 |
#[doc = "`read()` method returns [pwm_fsr::R](pwm_fsr::R) reader structure"]
impl crate::Readable for PWM_FSR {}
#[doc = "PWM Fault Status Register"]
pub mod pwm_fsr;
#[doc = "PWM Fault Clear Register\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_ze... | Rust | 0 |
ap::with_capacity(size * 2))),
tx_map: DashMap::new(),
flush_lock: Arc::new(Mutex::new(())),
};
let co_queue = Arc::clone(&pool.co_queue);
let real_queue = Arc::clone(&pool.real_queue);
let flush_lock = Arc::clone(&pool.flush_lock);
tokio::sp... | Rust | 0 |
})
.collect()
}
///
/// Find the entrypoint in this RuleGraph for the given product and params.
///
pub fn find_root<I: IntoIterator<Item = R::TypeId>>(
&self,
param_inputs: I,
product: R::TypeId,
) -> Result<(EntryWithDeps<R>, RuleEdges<R>), String> {
let params: ParamTypes<_> = para... | Rust | 0 |
# Variáveis são usadas para salvar algo na memória do computador.
# PEP8: inicie variáveis com letras minúsculas, pode usar
# números e underline _.
# O sinal de = é o operador de atribuição. Ele é usado para
# atribuir um valor a um nome (variável).
# Uso: nome_variável = expressão
nome_completo = "Bruno Batista"
soma... | Python | 1 |
(always)]
pub fn hctsiz_scatgather(&self) -> &crate::Reg<hctsiz_scatgather::HCTSIZ_SCATGATHER_SPEC> {
unsafe { &*(((self as *const Self) as *const u8).add(16usize) as *const crate::Reg<hctsiz_scatgather::HCTSIZ_SCATGATHER_SPEC>) }
}
#[doc = "0x10 - Host Channel Transfer Size Register \\[BUFFERMODE\\... | Rust | 0 |
let token = init(&mock_ref);
let tx1 = token
.call("isMinter")
.as_caller(&OWNER)
.with_arg(OWNER.to_vec()) // account
.exec(&mock_ref);
assert_eq!(tx1.ok(), true);
assert_eq!(
tx1.result_values[0],
true_result!(),
"owner should be a minter after... | Rust | 0 |
_num!(),
y1: parse_num!(),
x2: parse_num!(),
y2: parse_num!(),
x: parse_num!(),
y: parse_num!(),
}
}
b's' => {
Token::SmoothCurveTo {
abs: abs... | Rust | 0 |
import numpy as np
import matplotlib.pyplot as plt
def caffery_toa_localization(anchors, distances):
"""
anchors: N×2 array, anchor positions
distances: N array, measured distances (TOA*c)
"""
a1 = anchors[0]
d1 = distances[0]
A, b = [], []
for i in range(1, len(anchors)):
xi, y... | Python | 1 |
obal key store object.
static ref KEY_STORE: Mutex<KeyStore> = Mutex::new(KeyStore::new());
}
impl KeyStore {
const MAX_KEY_SIZE: usize = 128;
fn new() -> Self {
KeyStore {
keys: HashMap::new(),
}
}
/// Get global key store instance.
///
/// Calling this method... | Rust | 0 |
impl AsRef<UpdateChatDraftMessage> for UpdateChatDraftMessage {
fn as_ref(&self) -> &UpdateChatDraftMessage { self }
}
impl AsRef<UpdateChatDraftMessage> for RTDUpdateChatDraftMessageBuilder {
fn as_ref(&self) -> &UpdateChatDraftMessage { &self.inner }
}
/// The list of chat filters or a chat filter has ch... | Rust | 0 |
matrix[y]
for index in range(len(target_row)):
target_row[index] = 0
for index, _ in enumerate(matrix):
matrix[index][x] = 0
return matrix
# 1.9
# String Rotation:Assumeyou have a method isSubstringwhich checks if oneword is a substring of another.
# Given two strings, sl a... | Python | 1 |
{
ResumableUpload {
dest: to,
cl: cl,
max_chunksize: max_chunksize,
_resp: Default::default(),
}
}
pub fn set_max_chunksize(&mut self, size: usize) -> Result<&mut Self> {
if size % (1024 * 256) != 0 {
Err(ApiError::InputDataErro... | Rust | 0 |
dimension when feed into tf placeholder
s = observation[np.newaxis, :]
if np.random.uniform() < self.epsilon:
# forward feed the observation and get q value for every actions
actions_value = self.sess.run(self.q, feed_dict={self.tfs: s})
action = np.argmax(actions_v... | Python | 1 |
print("🩸 Stage 5: Analyzing devourers and anticoherence fields...")
def anticoherence_functional(psi_params):
"""
Anticoherence: 𝒜(ψ) = ∫₀^∞ ||R^t ψ - ψ||² dt
Measures recursive instability and divergence from self-similarity.
"""
recursion_dep... | Python | 1 |
len());
debug_assert!(i2 < HALFRATE[0].len());
debug_assert!(i3 < HALFRATE[0][0].len());
2 * HALFRATE[i1][i2][i3] as u32
}
pub fn hdr_sample_rate_hz(h: &[u8]) -> u32 {
static G_HZ: [u32; 3] = [44100, 48000, 32000];
G_HZ[(h[2] as (i32) >> 2 & 3) as usize]
>> (h[1] as (i32) & 0x8 == 0) as (i... | Rust | 0 |
ImutExprInt::InvokeAggr(e) => e.mid(),
ImutExprInt::List(e) => e.mid(),
ImutExprInt::Literal(e) => e.mid(),
ImutExprInt::Match(e) => e.mid(),
ImutExprInt::Merge(e) => e.mid(),
ImutExprInt::Patch(e) => e.mid(),
ImutExprInt::Path(e) => e.... | Rust | 0 |
) {
if let Some(dispatcher) = self.core_dispatcher.take() {
dispatcher.dispose(world);
}
self.dispatchers.drain().for_each(|(_name, dispatcher)| {
dispatcher.dispose(world);
})
}
}
<filename>src/y21/d17.rs<gh_stars>1-10
use crate::io::read_lines;
use itertools... | Rust | 0 |
true)
.help("Read input from FILE instead of stdin")
.takes_value(true),
)
.arg(
Arg::with_name("format")
.short("f")
.long("format")
.value_name("FORMAT")
.help("Input file format")
.takes_value(true)
.possible_values(format_ids.as_slice()),
)
.arg(
Arg::with_name("query")... | Rust | 0 |
>src/encoder/async_encoder.rs
use borrow::Cow;
use tokio::io::{AsyncRead, AsyncWrite};
use ops::{Deref, DerefMut};
use std::{borrow, error, fmt, io, mem, ops, result};
use crc32fast::Hasher as Crc32;
use deflate::write::ZlibEncoder;
use crate::chunk::{self, ChunkType};
use crate::common::{
AnimationControl, BitDe... | Rust | 0 |
::eq),
(F32, Op::Ne) => operate_f32(lhs, rhs, f32::ne),
(F64, Op::Ne) => operate_f64(lhs, rhs, f64::ne),
(F32, Op::Le) => operate_f32(lhs, rhs, f32::le),
(F64, Op::Le) => operate_f64(lhs, rhs, f64::le),
(F32, Op::Lt) => operate_f32(lhs, rhs, f32::lt),
... | Rust | 0 |
sLikeC",
"humidity",
"weatherDesc",
"observation_time",
],
}
resp = requests.get(f"https://wttr.in/{city_name}?format=j1")
resp.raise_for_status()
resp = resp.json()
ret = {k: {_v: resp[k][0][_v] for _v in v} for k, v in... | Python | 1 |
i32, ordinal: u16) -> Result<Self, ComponentRangeError> {
ensure_value_in_range!(year in MIN_YEAR => MAX_YEAR);
ensure_value_in_range!(ordinal in 1 => days_in_year(year), given year);
Ok(Self { year, ordinal })
}
/// Create a `Date` from the ISO year, week, and weekday.
///
///... | Rust | 0 |
e: (batch_size, num_tags)
next_score, indices = next_score.max(dim=1)
# Set score to the next score if this timestep is valid (mask == 1)
# and save the index that produces the next score
# shape: (batch_size, num_tags)
score = torch.where(mask[i].unsqueeze(1... | Python | 1 |
) => e.fmt(f),
DeserializeFailure::DefiniteLenMismatch(found, expected) => {
write!(f, "Definite length mismatch: found {}", found)?;
if let Some(expected_elems) = expected {
write!(f, ", expected: {}", expected_elems)?;
}
O... | Rust | 0 |
py)]
pub struct RolloverMsg3;
impl From<CfdTransactions> for RolloverMsg1 {
fn from(txs: CfdTransactions) -> Self {
let cets = txs
.cets
.into_iter()
.map(|grouped_cets| {
(
grouped_cets.event.id,
grouped_cets
... | Rust | 0 |
self.as_raw_fd(), remaining_buf, cur_offset as libc::off_t)
.map_err(map_nix_error)
)?;
total_bytes_read += bytes_read;
if bytes_read == 0 {
break;
}
}
if total_bytes_read < buf.len() {
return Err(io... | Rust | 0 |
sub(filter_paeth(0, previous[i], 0));
}
}
}
}
#[test]
fn learn_str() {
// 新建空字符串
let mut s1 = String::new();
// 从字符串字面值创建字符串
let data = "initial contents";
let s2 = data.to_string();
// 该方法用于任何实现了Display trait 的类
// 也可以作用与字符串字面量
let _s3 = "initial contents".to_s... | Rust | 0 |
#include <iostream>
#include <string>
#include <bitset>
using namespace std;
int main(int argc, char** argv)
{
int test_case;
int T;
cin>>T;
for(test_case = 1; test_case <= T; ++test_case)
{
int N,M;
cin >> N >> M;
string ans;
/*
cpp에서는
&& : 논리AND
& : 비트AN... | Python | 1 |
objs:
totalobjs.remove(obj)
try:
del pathfinder
except:
""
PicoBoy.Fill_Screen((0,0,0))
for pos in positions:
PicoBoy.Render_Sprite(badsprt,pos[0]*16,pos[1]*16)
... | Python | 1 |
from typing import Dict, Any
from reinvent_scoring.scoring.enums.container_type_enum import ContainerType
from reinvent_scoring.scoring.enums.component_specific_parameters_enum import ComponentSpecificParametersEnum
from reinvent_scoring.scoring.predictive_model.base_model_container import BaseModelContainer
from rei... | Python | 1 |
import whisper
import re
def generate_timed_captions(audio_filename, model_size="small"):
transcript = whisper.load_model(model_size).transcribe(word_timestamps=True, audio=audio_filename, condition_on_previous_text = False)
return getCaptionsWithTime(transcript)
def splitWordsBySize(words, maxCaptionSize)... | Python | 1 |
:W<u32, super::DMAR>;
#[doc = "Register DMAR `reset()`'s with value 0"]
impl crate::ResetValue for super::DMAR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `DMAR`"]
pub type DMAR_R = crate::R<u16, u16>;
#[doc = "Write proxy for field `DMAR`... | Rust | 0 |
Spec::k(0),
non_linear: std::ptr::null(),
});
assert_eq!(err, 0);
assert!(v.iter().all(|&a| a.is_zero()));
}
pub fn return_c<K, TA, TB, TC, TI>()
where
K: MatMatMulKer<TA, TB, TC, TI>,
TA: Copy,
TB: Copy,
TC: Copy + 'static + PartialEq,
... | Rust | 0 |
let hide = Material::plastic([0.84, 0.6, 0.53], [0.3, 0.3, 0.3], 0.2);
// Meshes
let planemesh = scene.load_obj(meshes::path("plane").as_path()).unwrap();
let buckyballmesh = scene.load_obj(meshes::path("buckyball").as_path()).unwrap();
// The Floor
let mut plane = Aggregate::new();
plane... | Rust | 0 |
0x4a, 0x6d, 0x79, 0x2d, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x61, 0x09, 0x6d, 0x79,
0x2d, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x61, 0x4a, 0x6d, 0x79, 0x2d, 0x68, 0x65, 0x61,
0x64, 0x65, 0x72, 0x62, 0x09, 0x6d, 0x79, 0x2d, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x62,
];
let mut decoder = conne... | Rust | 0 |
import os, shutil
from ..input import input_vasp_potcar, get_info, input_vasp_kpoints
from ..shell_scripts import job
from ase.io import read
from .. import __shell__, __python__, run_vasp
from . import vasp_incar
def gen_INCAR(encut, spin, fermiDirac, fun, u, fElectron, **kwargs):
incar_elf=f"""# INCAR for elf
I... | Python | 1 |
Some(dp), Some(_cp)) = (
pac::Peripherals::take(),
cortex_m::peripheral::Peripherals::take(),
) {
let gpiob = dp.GPIOB.split();
let mut blue = gpiob.pb7.into_push_pull_output();
// Set up the system clock. We want to run at 16MHz for this one.
let rcc = dp.RCC.constr... | Rust | 0 |
V, roughness[0,...,None],reflectance[0,...,None])
kS = F[None,:,:,0]
kD = 1.0*(1-self.metalness)
irradiance =dr.texture(self.diffuse[None, ...], normal[None].contiguous(), filter_mode='linear', boundary_mode='cube')[0].permute(2,0,1)
miplevel = self.get_mip(roughness)
sp... | Python | 1 |
} else {
get_integer(data, endptr);
}
}
if status == 2i32 {
status = 0i32
} else if status == 3i32 && *data < endptr {
warn!("{}: Garbage after endchar.", "Type2 Charstring Parser");
} else if status < 0i32 {
/* error */
panic!(
"{}: Parsin... | Rust | 0 |
a=int(input())
if(a%2==0):
print(-1)
else:
g=a-2
s=a//2
for x in range(1,a+1,2):
print(' '*(s),'*'*x,sep='')
s=s-1
s=1
for i in range(1,a,2):
print(' '*s,'*'*g,sep='')
g=g-2
s=s+1 | Python | 1 |
#!/usr/bin/python
#python version:2.7.2
# Reg exercise01
import re
print '--------------------------------------------------'
pattern = re.compile('hello')
match1 = pattern.match('hello world!')
match2 = pattern.match('helloo world!')
match3 = pattern.match('helllo world!')
if match1:
print match1.group()
else:... | Python | 1 |
from django.contrib import admin
from django.contrib.contenttypes.admin import GenericTabularInline
from permissions import models
class ObjectMembershipInline(GenericTabularInline):
"""
Inline admin interface for ObjectMembership.
Allows managing ObjectMembership instances within the parent model's admi... | Python | 1 |
BE(SmallIntCarrierBE),
//SmallLE(SmallIntCarrierLE),
Big(BitSlice<Vec<u8>>),
}
impl BitCarrier for IntegerBits {
type T = u8;
fn bit_len(&self) -> usize {
match self {
//Self::SmallBE(si) => si.bit_len(),
//Self::SmallLE(si) => si.bit_len(),
Self::Big(bi) => ... | Rust | 0 |
DISABLE_R::new(((self.bits >> 18) & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 0:1"]
#[inline(always)]
pub fn usb_vrefh(&mut self) -> USB_VREFH_W {
USB_VREFH_W { w: self }
}
#[doc = "Bits 2:3"]
#[inline(always)]
pub fn usb_vrefl(&mut self) -> USB_VREFL_W {
USB_VREFL_W { w: se... | Rust | 0 |
os::raw::c_int,
pub buffer: *mut ::std::os::raw::c_uchar,
pub num_grays: ::std::os::raw::c_ushort,
pub pixel_mode: ::std::os::raw::c_uchar,
pub palette_mode: ::std::os::raw::c_uchar,
pub palette: *mut ::std::os::raw::c_void,
}
pub type FT_Bitmap = FT_Bitmap_;
#[repr(C)]
#[derive(Debug, Copy, Clone)]... | Rust | 0 |
::with_capacity(16);
for i in 0..16 {
mem[ByteAt(i)] = (i as u8).into();
}
for i in 1..8 {
assert_eq!(mem[ OctaAt( 0)], mem[ OctaAt( i)]);
assert_eq!(mem[ OctaAt( 8)], mem[ OctaAt( 8 + i)]);
}
for i in 1..4 {
assert_eq!(mem[T... | Rust | 0 |
OXY_BYPASS_LIST_TOO_LARGE: DWORD = 0x80200019;
pub const BG_S_UNABLE_TO_DELETE_FILES: DWORD = 0x0020001A;
pub const BG_E_INVALID_SERVER_RESPONSE: DWORD = 0x8020001B;
pub const BG_E_TOO_MANY_FILES: DWORD = 0x8020001C;
pub const BG_E_LOCAL_FILE_CHANGED: DWORD = 0x8020001D;
pub const BG_E_ERROR_CONTEXT_REMOTE_APPLICATION:... | Rust | 0 |
nt for Enable {
fn prettify<'a>(&self, arena: &'a bumpalo::Bump) -> RcDoc<'a, ColorSpec> {
self.comp.prettify(&arena).append(RcDoc::text(";"))
}
}
impl PrettyPrint for Empty {
fn prettify<'a>(&self, _arena: &'a bumpalo::Bump) -> RcDoc<'a, ColorSpec> {
RcDoc::nil()
}
}
impl PrettyPrint ... | Rust | 0 |
cols) = covariances.dim();
let (l_matrix_len, l_matrix_rows, l_matrix_cols) = l_matrices.dim();
if kalman_gain_len != covariances_len || covariances_len != l_matrix_len {
return Result::Err(MatrixOperationError::UnequalNumberOfInputsError);
}
if kalman_gain_cols != l_matrix_cols {
retur... | Rust | 0 |
s {
match new_bin_file_path.file_name() {
Some(new_bin_filename) => {
log::debug!("Creating a hardlink for {:?}", new_bin_file_path);
let new_bin_path = shim_dir.join(new_bin_filename);
utils::create_hard_link(&executable_path, new_bin_path)?;
... | Rust | 0 |
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, (nn.BatchNorm2d, nn.InstanceNorm2d, nn.GroupNorm)):
if m.weight is not None:
nn.init.constant_(m.weight, 1)
if m.bias is not None:
nn.init... | Python | 1 |
per_host.
let resp = match result {
Err(e) => return Err(e),
Ok(resp) => resp,
};
// release the response
Ok(resp)
}
/// Connect the socket, either by using the pool or grab a new one.
fn connect_socket(unit: &Unit, hostname: &str) -> Result<Stream, Error> {
match unit.url.scheme()... | Rust | 0 |
llis() as i64
}
pub fn decode_hexstr(hex_str: &str) -> Result<Vec<u8>> {
Ok(hex::decode(hex_str).map_err(|_| ProtocolError("Could not decode hex string"))?)
}
// FIXME: this is super ugly
/// Pad numerical string with zeros to the desired precision. Required for Nash Me backend
pub fn pad_zeros(str_num: &str, pre... | Rust | 0 |
for id in postorder.iter() {
doms.insert(*id, None);
}
doms.insert(func.entry_point_id(), Some(func.entry_point_id()));
let mut changed = true;
while changed {
changed = false;
for (b_idx, b) in postorder.iter().enumerate().rev().skip(1) {
let preds = get_predecessors(func, *b);
// Make sure ... | Rust | 0 |
1", as_str);
extract_regex!(T, GAPDH, T::SV_INDEX, "3", as_str);
// extract (no gene name)
static ENH1: &'static str = ">sp|Q9N2K0|ENH1_HUMAN HERV-H_2q24.3 provirus ancestral Env polyprotein OS=Homo sapiens OX=9606 PE=2 SV=1";
extract_regex!(T, ENH1, 1, ENH1, as_str);
extract_re... | Rust | 0 |
True
if self.mode == "main":
continue_running = self.handle_main_input(key)
elif self.mode == "add_rule":
self.handle_add_rule_input(key)
elif self.mode == "edit_rule":
self.handle_edit_rule_input(key)
elif self.mode == "ad... | Python | 1 |
file."""
os.makedirs(os.path.dirname(output_file), exist_ok=True)
with open(output_file, 'w') as f:
json.dump(certificate, f, indent=2, default=str)
def main():
"""Main critical line verification workflow."""
parser = setup_arguments()
args = parser.parse_args()
print("🎯 CRI... | Python | 1 |
_static/cvxlogo-transparent.png"
html_favicon = "_static/favicon.ico"
# autodoc options for napoleon
napoleon_google_docstring = False
napoleon_numpy_docstring = True
napoleon_include_init_with_doc = False
napoleon_include_private_with_doc = True
napoleon_include_special_with_doc = True
napoleon_use_admonition_for_exa... | Python | 1 |
# Copyright 2022-2024 The University of Arizona and other Hatchet Project
# Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: MIT
import os
import json
import glob
import pytest
from hatchet import GraphFrame
from hatchet.util.logger import Logger
def test_no_logging_by_default(ca... | Python | 1 |
resuming.
Args:
epoch (int): Current epoch.
current_iter (int): Current iteration.
"""
if current_iter != -1:
state = {'epoch': epoch, 'iter': current_iter, 'optimizers': [], 'schedulers': []}
for o in self.optimizers:
state['opti... | Python | 1 |
Key::Char('7') => Command::Coord(6),
Key::Char('8') => Command::Coord(7),
Key::Char('9') => Command::Coord(8),
Key::Char('0') => Command::Coord(9),
Key::Char('e') | Key::Char('E') => Command::AutoEx... | Rust | 0 |
raw::c_uint;
pub const __NL80211_NAN_SRF_INVALID: nl80211_nan_srf_attributes = 0;
pub const NL80211_NAN_SRF_INCLUDE: nl80211_nan_srf_attributes = 1;
pub const NL80211_NAN_SRF_BF: nl80211_nan_srf_attributes = 2;
pub const NL80211_NAN_SRF_BF_IDX: nl80211_nan_srf_attributes = 3;
pub const NL80211_NAN_SRF_MAC_ADDRS: nl8021... | Rust | 0 |
(204, 101, 245)] # husl
def draw_keypoints(image, keypoints, gt_keypoints=None):
'''
:param image:
:param keypoints: [[x, y, v], ...]
:return:
'''
alpha = 0.8
color1 = (0, 255, 0)
color2 = (0, 0, 255)
thick = 2
l = 5
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale ... | Python | 1 |
t("State: 5/5 - 定义DLX类完成")
def main():
print("State: Final Stage - 开始求解")
# 计算所有放置和矩阵行
global pieces, GRID_WIDTH, GRID_HEIGHT
matrix_rows, piece_info = build_matrix_and_placements(pieces, GRID_WIDTH, GRID_HEIGHT)
# 计算总列数
num_cell_cols = GRID_WIDTH * GRID_HEIGHT
num_piece_cols = sum(piece.... | Python | 1 |
#Blender python file
#Print animation info for objects named *axis asumed to be a line object
import bpy
for col in bpy.data.collections:
for obj in col.objects:
if obj.name.endswith("axis"):
name=obj.name
v0=obj.matrix_world @ obj.data.vertices[0].co
v1=obj.matrix_world @ o... | Python | 1 |
32> {
self.x.iter().map(|a| a.0)
}
//~^^ ERROR cannot infer an appropriate lifetime
}
fn main() {}
/// See https://github.com/awslabs/aws-lambda-rust-runtime for more info on Rust runtime for AWS Lambda
use lambda_runtime::{handler_fn, Error};
use log::LevelFilter;
use serde::{Deserialize, Serialize};
... | Rust | 0 |
marker: PhantomData<*const ()>,
}
unsafe impl Send for P0 {}
impl P0 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const p0::RegisterBlock = 0x5000_0000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const p0::RegisterBlock {
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.