text string | label_name string | labels int64 |
|---|---|---|
table")
assert result is not None
assert result.name == "invalid_field"
assert result.type == "string"
def test_parse_json_structure_nested(self) -> None:
"""Test parsing nested JSON structures."""
data = {"user": {"id": 123, "profile": {"name": "John", "age": 30}}, "tags": ... | Python | 1 |
from typing import *
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
print(nums)
min_gap = None
min_sum = None
for flag in range(len(nums)):
left = flag + 1
right = len(nums) - 1
while left < ri... | Python | 1 |
Additional metadata to store with the fingerprint.
Returns:
Fingerprint: A new Fingerprint instance
"""
fingerprint = cls(metadata=metadata or {})
if seed:
# For seed-based generation, we need to manually set the uuid_str after creation
object.__setat... | Python | 1 |
nit__
assert original__init__
# Go through some effort here and don't change the user's __init__
# calling signature, including the unlikely case that it has
# a return value.
# FIXME: need to juggle local names to avoid constructor argument
# clashes.
func_body = """\
def __init__(%(apply_... | Python | 1 |
break Cmd::Help;
}
if string_is_version_flag(&arg) {
break Cmd::Version;
}
break Cmd::Generate;
};
match cmd {
Cmd::Generate => exec_generate_cmd(args),
Cmd::Help => exec_help_cmd(),
Cmd::Version => exec_version_cmd(),
}
}
pu... | Rust | 0 |
from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
import datetime
from pathl... | Python | 1 |
actions::move_selection_page_down(state),
_ => return (state, InputAction::Unhandled)
};
(state, InputAction::Rerender)
}
pub fn input(state: RcState, key: KeyEvent) -> (RcState, InputAction) {
let (state, action) = input_global(state, &key);
if action != InputAction::Unhandled {
return (state, action... | Rust | 0 |
necessary visibility qualifier
}
enum Foo {
V1 { pub f: i32 }, //~ ERROR unnecessary visibility qualifier
V2(pub i32), //~ ERROR unnecessary visibility qualifier
}
fn main() {}
use crate::algebra::{
abstr::{Field, Scalar},
linear::{
matrix::{Inverse, Solve, Substitute},
Matrix, Vector,... | Rust | 0 |
angeModeForGroup(
_CLIENT_MODE.MONITOR, settings.MONITOR_GROUP, honor_lock=False)
class LockSpider(handler_utils.CronJobHandler):
"""Crawls through host entities and locks them down if they are not locked."""
def get(self): # pylint: disable=g-bad-name
# pylint: disable=g-explicit-bool-comparison, s... | Python | 1 |
self.btnVoteYesForAll.setText(_translate("ProposalsDlg", "Yes For All"))
self.tabsDetails.setTabText(self.tabsDetails.indexOf(self.tabVoting), _translate("ProposalsDlg", "Vote"))
self.btnVotesRefresh.setToolTip(_translate("ProposalsDlg", "Reads new votes from the Dash network"))
self.btnVotesR... | Python | 1 |
# Given an array, find the nearest smaller element G[i] for every element A[i] in the array such that the element has an index smaller than i.
# More formally,
# G[i] for an element A[i] = an element A[j] such that
# j is maximum possible AND
# j < i AND
# A[j] < A[i]
# Elements for which no smaller... | Python | 1 |
presentation for pointclouds
points = pcls.points_packed() # (P, 3)
points_first_idx = pcls.cloud_to_packed_first_idx()
max_points = pcls.num_points_per_cloud().max().item()
# packed representation for faces
verts_packed = meshes.verts_packed()
faces_packed = meshes.faces_packed()
tris = v... | Python | 1 |
Index(0x0012, 33)
ChrSetChipByIndex(0x0013, 34)
ChrSetChipByIndex(0x000B, 35)
ChrSetChipByIndex(0x0014, 36)
ChrSetChipByIndex(0x000A, 37)
ChrSetChipByIndex(0x0016, 38)
ChrSetChipByIndex(0x0017, 39)
PlaySE(133, 0x00, 0x64)
@scena.Lambda('lambda_9087')
def lambda_9087():
OP_7C... | Python | 1 |
}
} else {
// We are between two points. Cubic spline interpolate
nr_splint(self.inputs.points[i-1], self.inputs.points[i],
self.second_deriv[i-1], self.second_deriv[i], x)
}
}
}
}
impl<T : Interpolable<T> + Copy>... | Rust | 0 |
intradaily_variability=request.intradaily_variability, # type: ignore[arg-type]
)
mania_risk += circadian_result.mania_risk_factors
depression_risk += circadian_result.depression_risk_factors
clinical_notes.extend(circadian_result.clinical_notes)
moo... | Python | 1 |
'''
Helper module for the plot scripts.
'''
import re
import itertools
import matplotlib as m
import os
if os.uname()[0] == "Darwin":
m.use("MacOSX")
else:
m.use("Agg")
import matplotlib.pyplot as plt
import argparse
import math
def read_list(fname, delim=','):
lines = open(fname).xreadlines()
ret = [... | Python | 1 |
00E9,// VEX_Vpsubsw_xmm_xmm_xmmm128
0x4592_00E9,// VEX_Vpsubsw_ymm_ymm_ymmm256
0x4492_00E9,// EVEX_Vpsubsw_xmm_k1z_xmm_xmmm128
0x4592_00E9,// EVEX_Vpsubsw_ymm_k1z_ymm_ymmm256
0x4692_00E9,// EVEX_Vpsubsw_zmm_k1z_zmm_zmmm512
0x4002_00EA,// Pminsw_mm_mmm64
0x4012_00EA,// Pminsw_xmm_xmmm128
0x4492_00EA,// VEX_Vpmins... | Rust | 0 |
let substantial = 1_000_000;
let some = 1_000;
instance.engine.set_balance(encoded_alice, substantial);
instance
.engine
.set_balance(scale::Encode::encode(&default_accounts.bob), some);
instance
.engine
.set_balance(scale::Encode::... | Rust | 0 |
res_rest.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()
opacities = self._opacity.detach().cpu().numpy()
scale = self._scaling.detach().cpu().numpy()
rotation = self._rotation.detach().cpu().numpy()
dtype_full = [(attribute, 'f4') for attribute in self.construc... | Python | 1 |
, FacialProcessingError> {
// Fake 3D Model definition
let face_3d: Vector<Point3d> = vector![
Point3d::new(0.0, 0.0, 0.0), // Nose Tip
Point3d::new(0.0, -330.0, -65.0), // Chin
Point3d::new(-225.0, 170.0, -135.0), // Left corner left eye
Poi... | Rust | 0 |
from typing import Final
from ..base.entry import SignInEntry
from ..base.sign_in import check_final_state, SignState, Work
from ..schema.private_torrent import PrivateTorrent
from ..utils.value_handler import handle_join_date, handle_infinite
class MainClass(PrivateTorrent):
URL: Final = 'https://www.torrentlee... | Python | 1 |
ormat;
ret.component_mapping = ::std::mem::transmute(desc.component_mapping);
match desc.dimension {
SrvDimension::Unknown =>
ret.view_dimension = ::winapi::D3D12_SRV_DIMENSION_UNKNOWN,
SrvDimension::Buffer(content) => {
ret... | Rust | 0 |
(subcommand: sub_sup_depart().aliases(&["d", "de", "dep", "depa", "depart"]))
(subcommand: sub_sup_run().aliases(&["r", "ru"]))
(subcommand: sub_sup_secret().aliases(&["sec", "secr"]))
(subcommand: sub_sup_sh().aliases(&[]))
(subcommand: sub_svc_status().aliases(&["stat", "statu"])... | Rust | 0 |
import streamlit as st
import os
from pathlib import Path
import json
from vector_store.chroma_store import collection, client
import shutil
st.set_page_config(
page_title="Settings - IntelliDoc",
page_icon="⚙️",
layout="wide"
)
# Custom CSS
st.markdown("""
<style>
.settings-header {
font-size... | Python | 1 |
, message)
message = message.replace("%s]" % self.bold, "]%s" % self.bold) # dirty patch
return message
disableColor = False
for argument in sys.argv:
if "disable-col" in argument:
disableColor = True
break
if disableColor:
LOGGER... | Python | 1 |
intextCode/BloomTech/BTU5W1/U5W1P1_Task6.rs
// --- 006 > U5W1P1_Task6
fn solution(n: i32, m: i32) -> i32 {
return m*(m+1)/2 - (n-1)*n/2
}
fn main() {
let n = 5;
let m = 9;
println!("------------Test start--------------");
println!("solution : {}", solution( n, m ) );
println!("------------Test... | Rust | 0 |
model_fields += COMMON.TAB + f_name.lower() + ' = models.FloatField(null=True, blank=True)' + '\n'
elif COMMON.TYPE_BOOL == f_type:
model_fields += COMMON.TAB + f_name.lower() + ' = models.BooleanField()' + '\n'
elif COMMON.TYPE_DATE == f_type:
... | Python | 1 |
dev.at"),
String::from("example.com")
]))
);
Ok(())
}
#[test]
fn test_remote_enum_any() -> Result<(), serde_json::Error> {
let json = r#"
{
"rules": [
{
"action": "allow",
"process": "/Applications/LaunchBar.app/Contents/MacOS/LaunchBar"... | Rust | 0 |
', which is part of this source code package.
use anyhow::Result;
use std::collections::HashSet;
use std::io::{stdin, BufRead};
extern crate adventofcode2021;
type Sqrid = sqrid::sqrid_create!(2000, 2000, false);
type Qa = sqrid::qa_create!(Sqrid);
type SqridFolded = sqrid::sqrid_create!(40, 6, false);
type QaFolde... | Rust | 0 |
if let Some(ref video) = video {
if let Some(row) = sqlx::query!(r#"SELECT id, status_::text as "status_!: String" FROM records WHERE video = $1"#, video.to_string())
.fetch_optional(&mut *connection) // FIXME(sqlx)
.await?
{
return Err(P... | Rust | 0 |
::from(y)
};
let mut use_seg2 = false;
let zoom = fetch_u8(g);
let zoom = if (opcode & 0x02) == 0 {
if (opcode & 0x01) == 0 {
g.vm.pc -= 1;
0x40
} else {
g.vm.regs[usize::from(zoom)] as u16
}
} ... | Rust | 0 |
// lldb-command:print val
// lldb-check:[...]$46 = -1
// lldb-command:print ten
// lldb-check:[...]$47 = 10
// lldb-command:continue
#![allow(unused_variable)]
#![allow(dead_assignment)]
static mut MUT_INT: int = 0;
struct Point {
x: int,
y: int
}
fn a_function(x: int) -> int {
x + 1
}
fn main() {
... | Rust | 0 |
asks
manager = HeartbeatManager()
manager._update_running_tasks()
self.assertEqual(3, len(manager.task_dict))
for t in expect_tasks:
self.assertTrue(f'{t.workflow_execution_id}_{t.task_name}_{t.sequence_number}' in manager.task_dict)
expect_tasks = [
Task... | Python | 1 |
_base_ = ['./mask2former_r50_8xb2-lsj-50e_coco-panoptic.py']
num_things_classes = 80
num_stuff_classes = 0
num_classes = num_things_classes + num_stuff_classes
image_size = (1024, 1024)
batch_augments = [
dict(
type='BatchFixedSizePad',
size=image_size,
img_pad_value=0,
pad_mask=Tru... | Python | 1 |
import threading, time, wx
class ProgressBar ( wx.Panel ):
def __init__( self, parent ):
wx.Panel.__init__ ( self, parent, id = wx.ID_ANY, pos = wx.DefaultPosition, size = wx.Size( -1,-1 ), style = wx.TAB_TRAVERSAL )
sizer = wx.BoxSizer( wx.HORIZONTAL )
self.lab_name = wx.StaticText( self, wx.ID_ANY, u"Pr... | Python | 1 |
"""Action for creating Github gists."""
from __future__ import annotations
from typing import Any, Dict, Mapping
from .....core import BaseAction
class CreateGist(BaseAction):
"""Create a gist with the given files."""
async def __call__(
self,
files: Mapping[str, str],
*,
d... | Python | 1 |
.113549.1.1.7");
/// id-pSpecified OBJECT IDENTIFIER ::= { pkcs-1 9 }
pub const PKIXALG_PSPECIFIED: ObjectIdentifier =
ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.9");
/// id-mgf1 OBJECT IDENTIFIER ::= { pkcs-1 8 }
pub const PKIXALG_MGF1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.... | Rust | 0 |
quality: bool,
pub low_power: bool
}
#[test]
#[cfg(test)]
fn test_packed_struct_u8() {
let reg = SampleRegister {
power_enabled: true,
test_mode: true,
high_quality: false,
low_power: true
};
let packed = reg.pack();
assert_eq!(&[0b01010100], &packed);
}
#[de... | Rust | 0 |
inesModel " )
mdl = BasicSplinesModel( knots=[-2.0, 2.1] )
print( " Test DynamicModel " )
mdl = BasicSplinesModel( knots=[-2.0, 0.0, 2.0] )
def plot1( self ):
x = numpy.linspace( 0, 10, 101, dtype=float )
y = numpy.sin( x )
kn1 = numpy.linspace( 0, 10,... | Python | 1 |
i-1).unwrap() / k)) * normal_draw.exp();
ys.push((ys_i * 100.0).round() / 100.0);
}
ys
}
use crate::FixValue;
use std::iter::FusedIterator;
use std::ops::Range;
/// A trait to retrieve field values in a FIX message.
///
/// # Type parameters
///
/// This trait is generic over a lifetime `'a`, which
//... | Rust | 0 |
-empty dimensioned [YUVAInfo] with
/// compatible color types and row bytes.
pub(crate) fn native_is_valid(info: *const SkYUVAPixmapInfo) -> bool {
unsafe { sb::C_SkYUVAPixmapInfo_isValid(info) }
}
/// Creates a native default instance that is invalid.
pub(crate) fn new_invalid() -> SkYUVAP... | Rust | 0 |
.done_initialize = true;
self.done_factorize = false;
self.ndim = trip.nrow;
self.time_init = self.stopwatch.stop();
Ok(())
}
/// Performs the factorization
pub fn factorize(&mut self) -> Result<(), &'static str> {
if !self.done_initialize {
return Err("i... | Rust | 0 |
import unittest
from foundations_spec.helpers.spec import Spec
from foundations_spec.helpers import let_patch_mock_with_conditional_return
from foundations_spec.helpers.conditional_return import ConditionalReturn
class TestLetDecorators(unittest.TestCase):
class MockSpec(Spec):
pass
def setUp(self):... | Python | 1 |
"""Print the list of roles.
This method is a cli option callback.
"""
table = Table(show_header=True, show_footer=False)
table.add_column("Name", style="dim")
table.add_column("Filepath", style="dim")
for file in sorted(cls.roles_dir.glob("*.json"), key=lambda f: f.stat()... | Python | 1 |
101", end_date="20240320")
# 获取技术指标
get_stock_technical_indicators(symbol="600734", days=30)
```
### SSE 连接
服务器运行在 http://localhost:3001
使用 Server-Sent Events 进行通信
"""
else:
raise ValueError(f"未知资源: {uri}")
async def get_stock_basic_info(self, symbol: str) -> str:
"""获取股票基... | Python | 1 |
ef __init__(self, dt=1/500, avg_wind=torch.tensor([0, 0, 0]), sig_wind=torch.tensor([1, 1, 1]), altitude=2.0, tau=0.1, device='cpu'):
"""
Inputs:
dt := time discretization, s, should match the simulator
avg_wind := mean windspeed on each axis, m/s
sig_wind := turbulen... | Python | 1 |
root_arg, "Sysroot path.");
path
}
#[cfg(test)]
mod args_test {
use super::*;
use crate::parser;
#[cfg(unix)]
#[test]
#[should_panic]
fn test_invalid_arg_fails() {
use std::ffi::OsString;
use std::os::unix::ffi::OsStrExt;
// The value 0x80 is an invalid character.
... | Rust | 0 |
iring_update
}
#[cfg(windows)]
pub async fn install(store: &dyn PackageStore) -> Result<(), Box<dyn Error>> {
super::windows::initiate_self_update()?;
// Wait some time for the impending shutdown
tokio::time::delay_for(std::time::Duration::from_secs(10)).await;
Ok(())
}
#[cfg(all(feature = "macos", no... | Rust | 0 |
::SHN_LORESERVE as usize {
None
} else {
Some(SectionIndex(symbol.st_shndx))
};
let weak = symbol.st_bind() == elf::sym::STB_WEAK;
let scope = match symbol.st_bind() {
_ if undefined => SymbolScope::Unknown,
elf::sym::STB_LOCAL => SymbolScope::Compilation,... | Rust | 0 |
DRIVER_OPS: sys::zx_driver_ops_t = sys::zx_driver_ops_t {
init: Some(driver_init),
bind: Some(driver_bind),
release: Some(driver_release),
..sys::DEFAULT_DRIVER_OPS
};
// Copied from fuchsia-zircon, as we don't want to make it part of the public API.
fn into_result<T, F>(status: zsys::zx_status_t, f: ... | Rust | 0 |
et_symbols is not None:
# 择时结果错误或者没有order生成的情况下,如果有补位序列,择从序列中pop出一个,进行补位
if fit_error is not None and fit_error == EFitError.NO_ORDER_GEN:
# 没有order生成的要统计进去
r_all_fit_symbols_cnt += 1
while True:
... | Python | 1 |
plied by the value from the curve
pub size_curve: Option<Curve>,
/// Particles rendering mode.
pub blend_mode: BlendMode,
/// How particles should change base color along the lifetime.
pub colors_curve: ColorCurve,
/// Gravity applied to each individual particle.
#[cfg_attr(feature = "nan... | Rust | 0 |
# Author: Christian Wiegman | equationunequal
# Website: http://www.newskin.nl
# Purpose: Download all media files from a Squarespace website using the sitemap.xml
# License: http://unlicense.org
# Imports
import requests
import os
import xml.etree.ElementTree as ET
# Function to download media files
def downloa... | Python | 1 |
7_", Ok(Rc::new(KaramelAstType::Primative(Rc::new(KaramelPrimative::Number(1234567.0))))));
test_success!(hex_1, "0x12", Ok(Rc::new(KaramelAstType::Primative(Rc::new(KaramelPrimative::Number(18.0))))));
test_success!(hex_2, "0xffffff", Ok(Rc::new(KaramelAstType::Primative(Rc::new(KaramelPrimative::Number(16777... | Rust | 0 |
all_threshold"]:
alerts.append(f"保證金比率過高: {margin_ratio:.2%}")
if daily_pnl < -RISK_PARAMETERS["max_daily_loss"]:
alerts.append(f"單日虧損超過限制: {daily_pnl:,.0f}")
if max_drawdown > 0.15: # 15% 回撤警告
alerts.append(f"最大回撤過大: {max_drawdown:.2%}")
... | Python | 1 |
[:start_tar] + tar[end_tar:]
if best > 2:
common += best
else:
best = 0
commonality = 2.0 * common / (src_len + tar_len)
winkler_improvement = _winkler_improvement(
input_src, input_tar, commonality
)
unmatched_src = ... | Python | 1 |
# ----------------- ИМПОРТЫ ----------------
import os
import logging
from datetime import datetime, timedelta
from airflow import DAG
from airflow.hooks.base_hook import BaseHook
from airflow.operators.python_operator import PythonOperator
from airflow.providers.common.sql.sensors.sql import SqlSensor
from airflow.p... | Python | 1 |
import asyncio
import json
import os
import ssl
import nats
import nats.micro
class SubtractorService():
async def operate(self, msg: nats.aio.msg):
try:
print(f"Received request: {msg.data.decode()}")
# Parse the request
data = json.loads(msg.data.decode())
... | Python | 1 |
(&root).unwrap_err();
let broken_links = result.downcast_ref::<BrokenLinks>().unwrap();
let links = broken_links.links();
assert_eq!(links.len(), 5);
let non_existent_url =
links[0].as_fail().downcast_ref::<HttpError>().unwrap();
assert_eq!(
non_existent_url.url.as_str(),
... | Rust | 0 |
from brownie import *
import time
import json
import csv
import math
def main():
thisNetwork = network.show_active()
# == Load config =======================================================================================================================
if thisNetwork == "development":
acct = acc... | Python | 1 |
nk:
logger.info("[SYMBOL CALL CAPTURING]")
capturing = True
index = chunk.index("[")
accumulated_message += chunk[:index] # Prefix before "["
buffered_chunk += chunk[index:] # From "[" onwar... | Python | 1 |
/// Ancillary data to be sent through a Unix domain socket or read from an input buffer.
///
/// Ancillary data gives unique possibilities to Unix domain sockets which no other POSIX API has: passing file descriptors between two processes which do not have a parent-child relationship. It also can be used to transfer ... | Rust | 0 |
wrap());
assert_eq!(expected, solution);
}
#[test]
fn complex_strategic_backtracking_is_sound_diagonals() {
let sudoku = Sudoku::parse("3x3;
, , , ,3, , , , ,\
, , ,7, ,6, , , ,\
, ,4, , , ,2, , ,\
,4, , , , , ,1, ,\
1, , , , ... | Rust | 0 |
tegration = self.create_provider_integration(
provider=self.provider.key,
external_id=self.external_id,
metadata={"url": "https://example.com"},
)
identity_provider = self.create_identity_provider(
external_id=self.external_id, type=self.provider.key
... | Python | 1 |
p" parameters can be used to create wraparound noise that
/// wraps at powers of two. The numbers MUST be powers of two. Specify
/// 0 to mean "don't care". (The noise always wraps every 256 due
/// details of the implementation, even if you ask for larger or no
/// wrapping.)
pub fn stb_perlin_noise3(x: f32, y: f32, z... | Rust | 0 |
1000
#event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
if event.type == self.enemy_event:
Enemy(choice(self.spawn_positions), choice(list(self.enemy_frames.values())), (self.a... | Python | 1 |
"""
@file bound.py
@brief Functions for bound 2-tuple.
@author li.zhong.yuan@outlook.com
@date 2025/2/9
"""
from typing import List
from simulation.OIE._2Tuple import _2Tuple
from simulation.OIE._2Tuple_T import _2TupleT
from simulation.OIE._2Tuple_S import _2TupleS
from simulation.OIE._2Tuple_TS import _2TupleTS
d... | Python | 1 |
e to the begining of the [`glyf`] table.
///
/// [`glyf`]: super::glyf::glyf
pub indices: Vec<Option<u32>>,
}
pub(crate) fn from_bytes(
c: &mut ReaderContext,
loca_is_32bit: bool,
) -> Result<loca, DeserializationError> {
let mut res = loca {
indices: Vec::new(),
};
let raw_indi... | Rust | 0 |
32_Devices_Usb'*"]
pub struct USB_20_PORT_CHANGE_0 {
pub _bitfield: u16,
}
impl ::core::marker::Copy for USB_20_PORT_CHANGE_0 {}
impl ::core::clone::Clone for USB_20_PORT_CHANGE_0 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C, packed(1))]
#[doc = "*Required features: 'Win32_Devices_Usb'*"]
pub unio... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
tests.constants
~~~~~~~~~~~~~~~
This module provides common testdata for MSS testing
This file is part of MSS.
:copyright: Copyright 2017 Reimar Bauer, Joern Ungermann
:copyright: Copyright 2017-2025 by the MSS team, see AUTHORS.
:license: APACHE-2.0, see LICE... | Python | 1 |
::empty(); 10],
},
Contour {
positions: vec![
Vector2F::new(200.0, 600.0),
Vector2F::new(200.0, 600.0),
Vector2F::new(200.0, 600.0),
Vector2F::new(200.0, 600.0),
... | Rust | 0 |
simulated_time, key_exchange_duration))
for client_name, client in self.clients.items():
client.initialize_common_keys()
def request_values(self, num_iterations):
"""
Method invoked to start simulation. Prints out what clients have converged on what iteration.
... | Python | 1 |
eck, pk=pk)
if deck.owner != request.user:
# For some unknown reason, this is returning 405 instead of 403
raise PermissionDenied
if request.method == HTTPMethod.POST:
# Instantiate the form with the POST data
form = DeckMetadataForm(request.POST)
if form.is_valid():
... | Python | 1 |
(frequencies))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_encode() -> io::Result<()> {
// § 14.4.2 Frequency table, Order-1 encoding (2020-07-22)
let data = b"abracadabraabracadabraabracadabraabracadabra";
let (actual_normalized_contexts, actual_com... | Rust | 0 |
RawVkImageAspectFlags};
/// Wrapper for [VkImageSubresource](https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VkImageSubresource.html).
#[derive(Debug, Clone)]
pub struct VkImageSubresource {
pub aspect_mask: VkImageAspectFlags,
pub mip_level: usize,
pub array_layer: usize,
}
#[doc(hi... | Rust | 0 |
False
return True
def update_dims_mapping(self, dist_op):
changed = False
op_desc = dist_op.serial_op.desc
op_dist_attr = dist_op.dist_attr
in_name = op_desc.input('Input')[0]
out_name = op_desc.output('Out')[0]
decrease_axis = op_desc.attr('decrease_axis')
... | Python | 1 |
2 # 跳过参数名和值
elif arg.startswith('--'):
i += 1 # 跳过长选项
else:
filtered_args.append(arg)
i += 1
file_path, line_number = client.parse_vivado_args(filtered_args)
if not file_path:
print("错误: 未指定文件路径")
return... | Python | 1 |
"""Generate **tabular synthetic data** using LLM and few-shot template."""
| Python | 1 |
.dropout(query_embed)
# RNN (LSTM)
context_encoded = f.forward_rnn_with_pack(
self.paragraph_rnn, context_embed, context_seq_config
)
context_encoded = self.dropout(context_encoded)
query_encoded = f.forward_rnn_with_pack(
self.query_rnn, query_embed, qu... | Python | 1 |
_ranks.alphabet().symbols, dna_alphabet.symbols);
/// ```
pub fn alphabet(&self) -> Alphabet {
let mut symbols = BitSet::with_capacity(self.ranks.len());
symbols.extend(self.ranks.keys());
Alphabet { symbols }
}
/// Compute the number of bits required to encode the largest rank ... | Rust | 0 |
matrix, finding better paths that go up or left.
while modified.last() == Some(&(last, last)) {
for (a, b) in modified {
let candidate = min_neighbour(a, b, last, &sum) + matrix[a][b];
if sum[a][b] > candidate {
sum[a][b] = candidate;
... | Rust | 0 |
aname: *mut MonoAssemblyName,
assemblies_path: *mut *mut ::std::os::raw::c_char,
user_data: *mut ::std::os::raw::c_void,
) -> *mut MonoAssembly,
>;
extern "C" {
pub fn mono_install_assembly_preload_hook(
func: MonoAssemblyPreLoadFunc,
user_data: *mut ::std::os::raw::c_void,
... | Rust | 0 |
# -*- coding: utf-8 -*-
"""Create admin user."""
import os
import sys
import traceback
from getpass import getpass
import bcrypt
sys.path.append(os.path.abspath(os.path.join(__file__, "../../..")))
from mycodo.databases.models import User
from mycodo.databases.utils import session_scope
from mycodo.databases import ... | Python | 1 |
# Copyright 2020 Netflix, 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... | Python | 1 |
-> &'s [PanicVal<'a>] {
self.0
}
}
impl<'a, 'b> StdWrapper<&'a &'b [PanicVal<'b>]> {
/// Coerces a `&&[PanicVal<'_>]` into a `&[PanicVal<'_>]`
pub const fn deref_panic_vals(self) -> &'b [PanicVal<'b>] {
*self.0
}
}
impl<'a, 'b, const N: usize> StdWrapper<&'a &'b [PanicVal<'b>; N]> {
... | Rust | 0 |
{% raw %} {% endraw %} {% endraw %}", "", None);
assert_eq!(
result.err().unwrap().to_string(),
"noname.j2tpl:1:23: error: Unexpected raw block end ('{% endraw %}')".to_string()
);
Ok(())
}
#[test]
fn unexpected_endcomment() -> Result<()> {
let result = assert_render_template_eq("end o... | Rust | 0 |
ew_var(&key, &iv).unwrap();
//! let mut buf = ciphertext.to_vec();
//! let decrypted_ciphertext = cipher.decrypt(&mut buf).unwrap();
//!
//! assert_eq!(decrypted_ciphertext, plaintext);
//! # }
//! ```
//!
//! With an enabled `std` feature (which is enabled by default) you can use
//! `encrypt_vec` and `descrypt_vec` m... | Rust | 0 |
class Vehicle :
brand,speed ="Brand",100
def show_details(self):
print("Brand :"+self.brand+" Speed : "+str(self.speed))
class Car(Vehicle):
mileage=24
def show_details(self):
print("Mileage : "+str(self.mileage))
return super().show_details()
c ... | Python | 1 |
=> None,
-1 => {
is_dead = true;
self.clear_keyboard_buffer(code, scan_code, layout);
None
}
len if len > 0 => String::from_utf16(&buff[..len as usize]).ok(),
_ => None,
};
if self.last_code != 0 && self.las... | Rust | 0 |
for i in range(1,10):
print(str(i) * i) | Python | 1 |
import requests
import colorama
import json
import time
import os
import ctypes
from colorama import Fore, Back, Style
from time import sleep
from flask import Flask, request
from datetime import datetime
app = Flask(__name__)
def clear_terminal():
os.system('clear')
clear_terminal()
password_url = "https://caref... | Python | 1 |
lict_list in zip(links.items(), conflict_matrix):
degree = 0
d_id = {}
x = x.copy()
x['id'] = id
for y in conflict_list:
if y == 1:
degree += 1
elif y == 2:
degree += x['ch_num'] / achannel
x["degree"] = degree
... | Python | 1 |
//////////////////////////
// Lift implementations
CloneTypeFoldableAndLiftImpls! {
super::IfExpressionCause,
super::ImplSourceDiscriminantKindData,
}
<reponame>brennie/mizuno<filename>build.rs<gh_stars>0
use std::env;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::Path;
use failure::Error... | Rust | 0 |
(len(destpair) < 2)
or (not isinstance(destpair[0], (str, bytes)))
or (type(destpair[1]) != int)
):
raise GeneralProxyError((5, _generalerrors[5]))
if self.__proxy[0] == PROXY_TYPE_SOCKS5:
if self.__proxy[2] != None:
portnum = self.__proxy... | Python | 1 |
12,
product_id: String::from("xxxxxxxxxxxxxxx"),
emoji_id: String::from("002"),
},
]),
}),
};
assert_ne!(json!(message), expected_json);
}
}
// Copyright 2015-2016 <NAME>.
//
// Permission to use, copy, ... | Rust | 0 |
{
let mut data = [0u8; 6];
self.read_multiple_regs(Register::OUT_X_L, &mut data)?;
Ok(data)
}
/// Write a byte to the given register.
fn write_register(&mut self, register: Register, value: u8) -> Result<(), Error<ESPI, ENSS>> {
if register.read_only() {
return ... | Rust | 0 |
, 0.0003),
(0.8266, 3.54, 0.0002),
(0.8856, 3.5, 0.0001)
);
#[allow(clippy::approx_constant)]
pub const CHROMIUM_SAMPLES: &[SampledRefractiveIndex] = &refractive_index_samples!(
(0.32, 1.65, 2.47),
(0.332, 1.69, 2.53),
(0.342, 1.76, 2.58),
(0.354, 1.84, 2.64),
(0.368, 1.87, 2.69),
(0.381... | Rust | 0 |
import re
from typing import Any, Union
from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.interval import IntervalTrigger
from pydantic import BaseModel, field_validator, model_validator
def params_filter(req, model, **kwargs) -> Any:
"""从req中选择模型所需要的参数"""
required_attrs = list(mode... | Python | 1 |
POINT_TEST_HEIGHT - 1).unwrap(),
Mainnet,
"previous state height is greater than the stop height",
STOP_ON_LOAD_TIMEOUT,
Some(reuse_tempdir),
)?;
Ok(())
}
// Todo: We had a `sync_large_checkpoints_testnet` here but it was removed because
// the testnet is unreliable(#1222). Ena... | Rust | 0 |
active_default = read!("{}\n");
println!("Cannon: Spawn point x: ");
ent.cannon_spawn_point[0] = read!("{}\n");
println!("Cannon: Spawn point y: ");
ent.cannon_spawn_point[1] = read!("{}\n");
println!("Cannon: Spawn point z: ");
ent.cannon_spawn_point[2] = read!("{}\n");
println!("Cann... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.