text string | label_name string | labels int64 |
|---|---|---|
result.push((
Vec::from(&collection_type[..]),
Vec::from(&collection_name[..]),
collection_items_result.into_iter(),
))
}
db.import(result);
ok()
}
#[nif(schedule = "DirtyIo")]
fn sled_tree_open(db: SledDb, name: String) -> NifResult<SledTree> {
rustler... | Rust | 0 |
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Python | 1 |
# --8<-- [start:to_arrow]
import polars as pl
import pyarrow as pa
df = pl.DataFrame({"foo": [1, 2, 3], "bar": ["ham", "spam", "jam"]})
arrow_table = pa.table(df)
print(arrow_table)
# --8<-- [end:to_arrow]
# --8<-- [start:to_polars]
polars_df = pl.DataFrame(arrow_table)
print(polars_df)
# --8<-- [end:to_polars]
# --... | Python | 1 |
;
}
use nom::simple_errors::Context;
use nom::Err::Error;
use nom::ErrorKind;
use nom::types::CompleteStr;
use nom::{digit, space};
use ast::lexer;
macro_rules! check_parser {
($parser_fn:ident; $input:expr => $rest:expr, $output:expr) => {
assert_eq!($parser_fn(CompleteStr($input)), Ok((CompleteStr($rest)... | Rust | 0 |
/// println!("Focused HWND: {}", p.hwnd_focus);
/// Ok(true)
/// }
/// });
/// ```
}
fn_wm_withparm_noret! { wm_init_menu_popup, co::WM::INITMENUPOPUP, wm::InitMenuPopup,
/// [`WM_INITMENUPOPUP`](https://docs.microsoft.com/en-us/windows/win32/menurc/wm-initmenupopup)
/// m... | Rust | 0 |
if !surface.initialized.swap(true, Ordering::Relaxed) {
let wl_egl_surface = wayland_egl::WlEglSurface::new(&surface.handle, width, height);
let egl_surface = unsafe {
egl.create_window_surface(
egl_display,
egl_config,
wl_egl_surface.ptr() as egl::NativeWindowType,
... | Rust | 0 |
#!/usr/bin/env python3
from random import randint
with open('flag.txt', 'rb') as f:
flag = f.read()
with open('secret-key.txt', 'rb') as f:
key = f.read()
def encrypt(ptxt, key):
ctxt = b''
for i in range(len(ptxt)):
a = ptxt[i]
b = key[i % len(key)]
ctxt += bytes([a ^ b])
... | Python | 1 |
c.local.usb_dap.process().ok();
// Process TX data.
(&mut c.shared.usb_serial, &mut c.shared.uart_tx_producer).lock(
|usb_serial, uart_tx_producer| {
while uart_tx_producer.ready() {
if let Ok(data) = read_usb_serial_byte_cs(usb_serial) {
... | Rust | 0 |
yType> for TocEntryType {
unsafe fn from_glib(value: ffi::GstTocEntryType) -> Self {
skip_assert_initialized!();
match value {
ffi::GST_TOC_ENTRY_TYPE_ANGLE => Self::Angle,
ffi::GST_TOC_ENTRY_TYPE_VERSION => Self::Version,
ffi::GST_TOC_ENTRY_TYPE_EDITION => Self::... | Rust | 0 |
24usize,
concat!(
"Offset of field: ",
stringify!(ag_stats),
"::",
stringify!(total_file_matches)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<ag_stats>())).time_start as *const _ as usize },
32usize,
concat!(
... | Rust | 0 |
final model on all domains:")
for i, domain in enumerate(domains):
cmd = [
sys.executable, "val.py",
"--data", domain,
"--weights", final_weights,
"--batch-size", "32",
"--name", f"eval_final_on_domain_{i+1}",
"--save-json" # For... | Python | 1 |
# 704. Binary Search
from typing import List
class Solution:
def search(self, nums: List[int], target: int) -> int:
l, h = 0, len(nums) - 1
while l <= h:
mid = l + (h - l) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
... | Python | 1 |
st_week = entry['week']
f.write(f' <li>{entry["day"]}: <span class="nad-dose">{entry["dose"]} mg</span></li>\n')
f.write(' </ul>\n')
# Tirzepatide progression
f.write('''
</div>
<div class="summary-card">
<h3>Tirzepati... | Python | 1 |
so that it supports wrapping ANY type.
// Execute `rustlings hint generics2` for hints!
//
// struct Wrapper {
// value: u32,
// }
// impl Wrapper {
// pub fn new(value: u32) -> Self {
// Wrapper { value }
// }
// }
use std::fmt::Debug;
// 类型系统术语:?
// T ,泛型 代表 所有的具体类型
struct Wrapper<T> {
... | Rust | 0 |
async fn getblocks(request: P2PMap) -> P2PMap;
async fn getdata(request: P2PMap) -> P2PMap;
async fn headers(request: P2PMap) -> P2PMap;
async fn inv(request: P2PMap) -> P2PMap;
async fn mempool(request: P2PMap) -> P2PMap;
async fn ping(request: P2PMap) -> P2PMap;
async fn pong(request: P2PMap) ... | Rust | 0 |
src = f"{self.build_folder}/third_party/libs/"
dst = f"{self.build_folder}/lib/"
copy(self, "*", src, dst)
def package_info(self):
# Note: package_info collects information in self.cpp_info. It is called from the Conan
# application.
#
# This call is made imm... | Python | 1 |
. Moves every email used in the batch into DATETIME/ and compresses it.
fn digest(ctx: &Context) -> Result<()> {
let hx_path = ctx.hx_path();
if !hx_path.exists() {
warn!("No history found! Creating...");
create_dir(hx_path).chain_err(|| "Could not create history dir")?;
}
write_diges... | Rust | 0 |
tiling_spec.tile_size_in_pixels.axis_size_y(),
tiling_spec.tile_size_in_pixels.axis_size_x(),
query_elapsed.as_nanos(),
number_of_tiles,
number_of_tiles as u128
* tiling_spec.tile_size_in_pixels.... | Rust | 0 |
"""
Base Resource Management Models
This module defines the base models and enums for resource management.
"""
import enum
from sqlalchemy import Column, String, Integer, Float, ForeignKey, DateTime, JSON, Enum, Boolean
from sqlalchemy.orm import relationship
from datetime import datetime
from app.models.physical_ed... | Python | 1 |
from random import randint
def jugar():
opciones = ["Piedra", "Papel", "Tijera"]
while True:
valor_aleatorio = randint(0, 2)
juego_computador = opciones[valor_aleatorio]
juego_usuario = input("¿Qué eliges? Piedra, Papel, Tijera (o 'salir' para terminar): ").capitalize()
if j... | Python | 1 |
TRANSLATE_MOCK = ('[Verse 2] Я хочу немного повеселиться. Но это не так просто. Это то, чего я действительно хочу? '
'Сделай еще один шаг, и я окажусь на грязной стороне. И я поздороваюсь со своей ночной бабочкой. '
'Кто хочет иметь бабочку-переключатель? Ты можешь быть богатой, ты м... | Python | 1 |
constant.NAN
pub const NAN: ReaperVolumeValue = ReaperVolumeValue(f64::NAN);
/// The negative infinity volume (-1000.0 = -inf dB).
pub const MINUS_INF: Db = Db(-1000.0);
/// The "soft minimum" volume (-150.0 dB).
pub const MINUS_150_DB: Db = Db(-150.0);
/// The "unaltered" volume (0.0 dB).
... | Rust | 0 |
# check that one-sided thresholding works
img = atlasreader.process_img(stat_img, direction="neg", cluster_extent=20)
assert isinstance(img, nb.Nifti1Image)
# check that negative voxel threshold works
img = atlasreader.process_img(stat_img, cluster_extent=20, voxel_thresh=-10)
assert isinstance(i... | Python | 1 |
try:
queryset = self.get_queryset().filter(is_active=True)
# Group faces by role
faces_by_role = {}
roles = ['primary', 'caregiver', 'family', 'other']
for role in roles:
role_faces = queryset.filter(role=role... | Python | 1 |
import numpy as np
class KernelBayesianRegression:
def __init__(self, alpha, beta, kernel='rbf', length_scale=0.5, kernel_params=None):
self.alpha = alpha
self.beta = beta
self.kernel = kernel
self.length_scale = length_scale
self.kernel_params = kernel_params or {}
... | Python | 1 |
("Login Record", record_create_obj.title)
self.assertIsNone(record_create_obj.notes)
self.assertListEqual(record_create_obj.fields[0].value, []) # no passkey set
self.assertListEqual(record_create_obj.fields[1].value, ["john.smith@localhost"])
# Make sure no password is set
self... | Python | 1 |
None;
}
};
let frame_size = protocol_utils::resp3_frame_size(&frame);
if frame_size >= globals().blocking_encode_threshold() {
// since this isn't called from the Encoder/Decoder trait we can use spawn_blocking here
_trace!(
inner,
"Parsing monitor frame with blocking task with size {}",... | Rust | 0 |
None, r, g, b, a }))
}, 256)(input)?;
Ok((input, colors))
}
#[tracing::instrument]
fn parse_MATT(input: &[u8]) -> IResult<&[u8], MaterialV1> {
tracing::trace!("parse_MATT(len: {})", input.len());
let (input, id) = le_u32(input)?;
let (input, kind) = le_u32(input)?;
let (input, weight) = le_f32... | Rust | 0 |
let bits = match self.width {
Width::As32 => self.into_bits() & 0xFFFF_FFFF,
Width::As64 => self.into_bits(),
};
// Even though overflow would not occur since we currently mask the shift amount,
// still do a `checked_shr` since this masking behaviour is very od... | Rust | 0 |
import re
from typing import List, Dict
RULES = [
{
"id": "SQLI_STR_CONCAT",
"pattern": re.compile(r"(SELECT|INSERT|UPDATE|DELETE).*['\"]\s*\+\s*\w+", re.IGNORECASE | re.DOTALL),
"description": "Possible SQL injection via string concatenation.",
"cwe": "CWE-89",
"severity": ... | Python | 1 |
models--\n\n')
f.write(script)
"""add native functions"""
script = SqlModelHelper(Function).get_data_load_statement(get_native_functions())
f.write('\n\n-- -----------\n')
f.write('-- native functions--\n\n')
f.write(script)
if apply:
_test_... | Python | 1 |
7), "G");
}
}
<reponame>david-sawatzke/xmc1100-rs
#[doc = "Reader of register NVMSTATUS"]
pub type R = crate::R<u16, super::NVMSTATUS>;
#[doc = "Write Protocol Error\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum WRPERR_A {
#[doc = "0: No write protocol failure occurred."]
VALUE1,
... | Rust | 0 |
}
pub async fn cancel_request(
&self,
host: impl Into<Fqdn> + Clone,
uuid: &Uuid,
) -> Result<(), ImlActionClientError> {
let action = Action::ActionCancel {
id: ActionId(uuid.to_hyphenated().to_string()),
};
let x =
build_invoke_rust... | Rust | 0 |
import pandas as pd
import os
import glob
# 存储所有读取的group文件
all_groups_df = pd.DataFrame()
# ADMET数据
admet_file = "/data/home/zhangzhiyong/lead_optimization/PromptDiffModel/data/optimized_ligand/admet_comparison_prompts_fg.csv"
admet_df = pd.read_csv(admet_file)
print(f"ADMET CSV包含 {len(admet_df)} 行数据")
# 遍历group_1到g... | Python | 1 |
inline]
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Self::Value::from(v))
}
#[inline]
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
where
E: Error,
{
O... | Rust | 0 |
any confchange request besides leave joint request
// will be rejected
let resp = call_conf_change(
&mut cluster,
region_id,
ConfChangeType::RemoveNode,
new_learner_peer(3, 3),
)
.unwrap();
must_contains_error(&resp, "in joint");
let resp = call_conf_change_v2(
... | Rust | 0 |
should_panic
# use glsp_engine::*;
# Engine::new().run::<_, ()>(|| {
return Err(GError::macro_no_op())
# }).unwrap();
```
*/
#[macro_export]
macro_rules! macro_no_op {
() => {
return Err($crate::GError::macro_no_op())
};
}
/* BSD 3-Clause License
*
* Copyright © 2019, <NAME> <<EMAIL>>.
* Copyright ©... | Rust | 0 |
ew_layer
layer.update()
return {'FINISHED'}
# Menu UI
def add_object_button(self, context):
layout = self.layout
layout.separator()
layout.operator(
OBJECT_OT_add_wire_skin.bl_idname,
text="Wire + Skin",
icon='MOD_SKIN')
layout.operator(
OBJECT_O... | Python | 1 |
Vec::new();
let result = file.unwrap().read_to_end(&mut contents).expect("Unable to open ROM");
return contents;
}
}
<filename>18-ErrorHandling/10-defining-an-error-type.rs
// Sometimes it simplifies the code to mask all of the different errors with a
// single type of error. We'll show this with a... | Rust | 0 |
from llama_index.core.program import BasePydanticProgram
from llama_index.program.evaporate import DFEvaporateProgram
def test_class():
names_of_base_classes = [b.__name__ for b in DFEvaporateProgram.__mro__]
assert BasePydanticProgram.__name__ in names_of_base_classes
| Python | 1 |
from mmcv.runner.hooks import HOOKS, Hook
from mmdet3d.core.hook.utils import is_parallel
import math
__all__ = ['FusionRateControlHook']
@HOOKS.register_module()
class FusionRateControlDepthHook(Hook):
""" """
def __init__(self, temporal_end_iter=1, temporal_start_iter=-1):
super().__init__()
... | Python | 1 |
from pyspark.sql.functions import col, trim, regexp_extract
from pyspark.sql.types import IntegerType
from pyspark.sql.window import Window
from pyspark.sql.functions import row_number
from spark_session import get_spark_session
def transform_date_dim(mysql_date_df, csv_date_df=None):
spark = get_spark_session()
... | Python | 1 |
one)]
pub struct ovrBoundaryTriggerResult_ {
#[doc = " Closest point on the boundary surface."]
pub ClosestPoint: ovrVector3f,
#[doc = " Normal of the closest point on the boundary surface."]
pub ClosestPointNormal: ovrVector3f,
#[doc = " Distance to the closest guardian boundary surface."]
pub ... | Rust | 0 |
rker = _worker if worker is None else worker
dbsession.add(requested_task)
dbsession.flush()
return requested_task
return _create_requested_task
@pytest.fixture
def requested_task(
create_requested_task: Callable[..., RequestedTask],
schedule_config: ScheduleConfigSchema,
):
r... | Python | 1 |
as NomErr;
use types::*;
pub(crate) fn s2k_iv(inp: &[u8]) -> IResult<&[u8], [u8; 8]> {
let mut out = [0u8; 8];
let (remaining, slice) = match take!(inp, 8) {
IResult::Done(remaining, slice) => (remaining, slice),
IResult::Error(e) => return IResult::Error(e),
IResult::Incomplete(i) =>... | Rust | 0 |
{
x: b.x + 1.0,
y: b.y.mul_add(-1.0, 1.0),
};
let c_scr = half_scr
* Vec2 {
x: c.x + 1.0,
y: c.y.mul_add(-1.0, 1.0),
};
let a_px = a_scr.map(|e| e as i32);
... | Rust | 0 |
{
Arc::new(DummyData { id, item_size })
}
// Some constants
static CACHE_SIZE_BYTES: u64 = 65536_u64;
static ITEM_SIZE_BYTES: u64 = 512_u64;
static MAX_EXPECTED_ITEMS_IN_CACHE: u64 = CACHE_SIZE_BYTES / ITEM_SIZE_BYTES;
/// Tests whether the cache size is limited by the size of the ite... | Rust | 0 |
=> (true, 0b01), // pllclk / 1
72_000_000 => (true, 0b00), // pllclk / 1.5
96_000_000 => (true, 0b11), // pllclk / 2
_ => (false, 0),
};
usbclk_valid = valid;
// Configure USB prescaler
rcu.cfg0.modify(|_, w| unsafe { w.us... | Rust | 0 |
# Copyright (c) "Neo4j"
# Neo4j Sweden AB [https://neo4j.com]
# #
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# #
# https://www.apache.org/licenses/LICENSE-2.0
# #
# Unless re... | Python | 1 |
import os
import aiofiles
import asyncio
import time
from multiprocessing import Manager, Process
import pyfiglet
from termcolor import colored
from eth_utils import keccak
# Файлы для работы
RICH_FILE = 'RichETH.txt'
FOUND_FILE = 'FoundETH.txt'
STATE_FILE = 'state_eth.txt'
# Чтение состояния
async def read_state():
... | Python | 1 |
isolatethread_t);
}
#[link(name = "GG")]
extern "C" {
pub fn create_isolate() -> *mut graal_isolatethread_t;
}
#[link(name = "GG")]
extern "C" {
pub fn eval(
arg1: *mut graal_isolatethread_t,
arg2: *mut ::std::os::raw::c_char,
arg3: *mut ::std::os::raw::c_char,
) -> *mut ::std::os::r... | Rust | 0 |
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
import os
import sys
import yaml
from tqdm import tqdm
def Data_downloader(year, start_idx, end_idx):
url = "https://www.ncei.noaa.gov/data/local-climatological-data/access/"+f"{year}"+"/"
download_path = "/Users/anikbhowmick/Pyth... | Python | 1 |
import gc
class Node:
def __init__(self,data):
self.data=data
self.next=None
self.prev=None
class DoublyLinkedList:
def __init__(self):
self.head=None
def deleteNode(self,dele):
if self.head is None or dele is None:
return
if self.head == dele:
self.head=dele.next
if dele.next is not None:
del... | Python | 1 |
break String::from("Connection has been closed")
}
let message_bytes = Vec::from(&buf[..n]);
let mut chat_rooms = chat_rooms.lock().unwrap();
if let Err(msg) = chat_rooms.handle_messag... | Rust | 0 |
desired = 100
rate = 5
years = 10
principle = desired / ((1 + rate/100)**years)
print(principle) | Python | 1 |
",
"ptrDSIh",
"ptrTIMh",
"ptrLSPh",
"ptrCYCh",
"ptrELMh",
"ptrNODh",
"ptrGEOh",
"ptrTRANh",
"Glbnnod",
"ptrGNODl",
"ptrGNODh",
"qrDmpKy",
"MSUPkey",
"PSDkey",
"cycMSUPkey",
"XfemCrkPropTech",
]
boundary_condition_index_table = [
"numdis", # number of... | Python | 1 |
_base_ = './gfl_r50_fpn_ms-2x_coco.py'
model = dict(
backbone=dict(
type='ResNet',
depth=101,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
norm_eval=True,
style='pytorch',
init_cfg=dict(... | Python | 1 |
.blit(font.render(qi[1], True, (255,255*int(qi[0]),0)), toPygame(x,y,False))
else:
pygame.draw.rect(screen, (0,0,0), Rect(toPygame(x,y,False),(60,60)),0)
def line(pos1,pos2):
pygame.draw.line(screen,(0,0,255),pos1,pos2,2)
def drawAll():
screen.fill((127,127,127))
for x in rang... | Python | 1 |
let link = ctx.link().clone();
Box::new(move |_, e: &ToasterMsg| {
if let ToasterMsg::Toast(_) = e {
let link = link.clone();
Timeout::new(timeout, move || {
link.send_message(ToasterMsg::Clear);
... | Rust | 0 |
_waiting) = self.waiting.get_mut(&shard) {
if let Some(tx_pool_wanted) = self.wanted_tags.get_mut(&shard) {
for hash in hashes {
if let Some(waiting_tx) = tx_pool_waiting.remove(hash) {
// remove from wanted_tags as well
for tag in waiting_tx.missing_tags {
let remove = if let Some(wanted... | Rust | 0 |
import subprocess
def run_command(command):
result = subprocess.run(command, shell=True, capture_output=True, text=True)
return result.stdout.strip()
def command_exists(command):
"""Check if a command exists on the system."""
return subprocess.call(f"type {command}", shell=True, stdout=subprocess.PIPE... | Python | 1 |
st): .4f}, total_accuracy={np.mean(total_accuracy_list): .4f}')
file = open(f'{slam.out_dir}/rendered/rendering_eval.txt', 'a')
file.write(f'Average: ' +
f'psnr: {slam.psnr_sum/count:.4f} ' +
f'ssim: {slam.ssim_sum/count:.4f} ' +
f'lpips: {slam.lpips_sum/cou... | Python | 1 |
import gym
from stable_baselines3 import DQN
from stable_baselines3.common.env_checker import check_env
from drone_delivery_gym_env_opt import DroneDeliveryEnv
# Create the environment
env = DroneDeliveryEnv()
# Optional: Check if the environment follows Gym's API
check_env(env)
# Define the DQN model
model = DQN(
... | Python | 1 |
2, 6, 12, 11, 0, 1,
9, 0, 0, 1, 6, 11, 0, 1, 8, 1, 1, 11, 0, 1, 8, 1, 1, 8, 1, 11, 76, 105, 98, 114, 97,
83, 121, 115, 116, 101, 109, 5, 82, 111, 108, 101, 115, 10, 67, 97, 112, 97, 98, 105,
108, 105, 116, 121, 13, 76, 105, 98, 114, 97, 82, 111, 111, 116, 82, 111, 108, 101, 31,
... | Rust | 0 |
_adj = cap - nsh_out @ price
nsh_in['_CASH_'] = cash
nsh_out['_CASH_'] += cap_adj
res = pd.DataFrame({'old_nsh': nsh_in.round(2),
'new_nsh': nsh_out.round(2),
'diff_nsh': (nsh_out - nsh_in).round(2),
'... | Python | 1 |
#!/usr/bin/env python
#
# Copyright 2015 clowwindy
#
# 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 ... | Python | 1 |
'a Stupex<T>, closure_handle: Option<ClosureHandle>) -> Self {
lock.locked.store(true, Ordering::Relaxed);
Self {
lock,
_closure_handle: closure_handle,
}
}
}
impl<T: ?Sized> Deref for StupexGuard<'_, T> {
type Target = T;
fn deref(&self) -> &T {
un... | Rust | 0 |
res.access_token), expires.eq(0), user_id.eq(user_id_)); // TODO: expires
insert_into(sessions).values(&new_session).execute(&db.0).unwrap();
}
pub struct SessionInfo {
access_token: String,
login_name: String
}
pub mod github {
pub fn login_form(state: &str, env: &Environment) -> String {
for... | Rust | 0 |
tm2) in res]
res.sort()
sel = list(reversed(res[- n:]))
print('Discrepancies (%d of %d):' % (len(sel), len(res)))
for (_, nm, ctxt, detail, tm1, tm2) in sel:
print('%s in %s(%s): %.4fs vs %.4fs' % (nm, ctxt, detail, tm1, tm2))
def main():
import sys
# FIXME: use argparse or whatever
if len(sys.argv)... | Python | 1 |
(|f| (&f.name[..], f)).collect();
// first round - filter indices whose values are outside the field's valid ranges
for (&name, indices) in indices_by_field.iter_mut() {
let matching_indices = indices.iter().filter_map(|i| {
if values_by_field_index.get(*i).unwrap().iter().all(|v| {
... | Rust | 0 |
""" /*
* EJERCICIO:
* - Crea ejemplos de funciones básicas que representen las diferentes
* posibilidades del lenguaje:
* Sin parámetros ni retorno, con uno o varios parámetros, con retorno...
* - Comprueba si puedes crear funciones dentro de funciones.
* - Utiliza algún ejemplo de funciones ya creadas en el ... | Python | 1 |
"PredictionOutput") -> None:
r"""
Saves model predictions to `output_dir`.
A custom behavior that not contained in Seq2SeqTrainer.
"""
if not self.is_world_process_zero():
return
output_prediction_file = os.path.join(self.args.output_dir, "generated_predict... | Python | 1 |
if -s is given, ignore -x
let zero = matches.is_present(options::ZERO);
let verbose = matches.is_present(options::VERBOSE);
for path_str in matches.values_of(options::FILE).unwrap() {
show_if_err!(wipe_file(
path_str, iterations, remove, size, exact, zero, verbose, force,
));
... | Rust | 0 |
parse_from_str(t, "%Y-%m-%d %H:%M:%S.f") {
Some(k)
} else if let Ok(k) = NaiveDate::parse_from_str(t, "%Y-%m-%d") {
Some(k.and_hms(0, 0, 0))
} else {
None
}
}
let after_time = matches
.value_of("after-time")
.map(|t| parse_time(t).expect("parsing after-time").timestamp_nanos() as u64);
... | Rust | 0 |
Zmmword),
None,
)),
operand4: None,
lock: false,
rounding_mode: None,
merge_mode: Some(MergeMode::Zero),
sae: false,
mask: Some(MaskReg::K4),
broadcast: None,
},
&[98, 242, 165, 196, 170, 131,... | Rust | 0 |
plotter.set_series_data(series_name, points=series_points)
# Add un-trained discriminator
plotter.set_supplementary_data(discriminator=discrim)
# Call figure() to generate discriminator image, if possible.
with warnings.catch_warnings():
warnings.filterwarnings("... | Python | 1 |
buf: &[u8] = unsafe {
slice::from_raw_parts(
(&self.raw as *const fuse_kernel::fuse_attr_out)
as *const u8,
fuse_kernel::FUSE_COMPAT_ATTR_OUT_SIZE,
)
};
return enc.encode_bytes(buf);
}
enc.encode_sized(&self.raw)
}
}
// }}}
<filename>2020/aoc8/src/main.rs
use lazy_static::lazy_stat... | Rust | 0 |
de::de::Deserializer<'de>>(des: D) -> Result<Self, D::Error> {
let s = String::deserialize(des)?;
let micro_gtu = s.parse::<u64>().map_err(|e| serde::de::Error::custom(format!("{}", e)))?;
Ok(Amount {
micro_gtu,
})
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
/// An ... | Rust | 0 |
/src/audio_ports.rs
use bitflags::bitflags;
use clack_common::extensions::{Extension, PluginExtension};
use clap_sys::ext::audio_ports::*;
use std::marker::PhantomData;
#[repr(C)]
pub struct PluginAudioPorts(
clap_plugin_audio_ports,
PhantomData<*const clap_plugin_audio_ports>,
);
bitflags! {
#[repr(C)]
... | Rust | 0 |
Err(e) => panic!("error happened in detection: {}", e),
}
assert!(line_matching_format_expression($exp, $input).unwrap_or(false));
};
}
macro_rules! match_format {
($example:expr, $format:expr) => {
assert!(line_matching_format_expression($format, $e... | Rust | 0 |
# coding=utf-8
"""
按从外到里的顺序顺时针打印矩阵
每一圈的开始位置总是坐上角元素[0, 0], [1, 1]...
"""
def print_matrix(matrix):
"""
:param matrix: [[]]
"""
rows = len(matrix)
cols = len(matrix[0]) if matrix else 0
start = 0
ret = []
while start * 2 < rows and start * 2 < cols:
print_circle(matrix, start, ro... | Python | 1 |
_remember_data_tag_is_correct",
]
test_names = _get_test_names_for_obj(ExponentTransformer)
assert set(expected_tests).issubset(test_names)
@pytest.mark.skipif(
not run_test_for_class(parametrize_with_checks),
reason="run test only if softdeps are present and incrementally (if requested)",
)
@pa... | Python | 1 |
;
container.with_database(
&database_id,
vec![
"CREATE TABLE my_table(a INT64, b STRING(MAX)) PRIMARY KEY(a)",
"CREATE TABLE person(id INT64, name STRING(MAX) NOT NULL, data BYTES(MAX)) PRIMARY KEY(id)",
],
)
.await;
let client... | Rust | 0 |
rientation::Horizontal)
.build();
learn_more_e2e.append(&learn_more_e2e_btn);
learn_more_e2e.append(>k::Label::new(Some(" about end-to-end encryption.")));
let goto_settings = icon_button("security-high", "Backup Now");
goto_settings.connect_clicked({
let info ... | Rust | 0 |
the value of the field is `VALUE2`"]
#[inline(always)]
pub fn is_value2(&self) -> bool {
**self == AHIBIO0PEV_A::VALUE2
}
}
impl core::ops::Deref for AHIBIO0PEV_R {
type Target = crate::FieldReader<bool, AHIBIO0PEV_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0... | Rust | 0 |
afe fn popow_header_get_interlinks(
popow_header_ptr: ConstPoPowHeaderPtr,
interlinks_out: *mut CollectionPtr<BlockId>,
) -> Result<(), Error> {
let popow_header = const_ptr_as_ref(popow_header_ptr, "popow_header_ptr")?;
let interlinks_out = mut_ptr_as_mut(interlinks_out, "interlinks_out")?;
*interl... | Rust | 0 |
import asyncio
import aiomysql
loop = asyncio.get_event_loop()
@asyncio.coroutine
def test_example_executemany():
conn = yield from aiomysql.connect(host='127.0.0.1', port=3306,
user='root', password='',
db='test_pymysql', loop=loop)
... | Python | 1 |
`Block::next` (AtomicPtr) may be safely zero initialized.
// [2] `Block::slots` (Array) may be safely zero initialized because of [3, 4].
// [3] `Slot::task` (UnsafeCell) may be safely zero initialized because it
// holds a MaybeUninit.
// [4] `Slot::state` (AtomicUsize) may be... | Rust | 0 |
')
# Ensure both data_categories are present for total sum calculation
conf_df = conf_df.reindex(columns=data_categories, fill_value=0).fillna(0).astype(int)
conf_df = conf_df.sort_index()
# Plot 'All Other Categories (OR)' as a line
if 'All Other Categories ... | Python | 1 |
onfig=None, name=None):
"""Create a new Experiment."""
if config is None:
config = Config.from_file(self._default_config_path)
save_dir = self._int_dirs.new_dir(name=name)
cfg_path = self._config_path(save_dir)
config.to_file(cfg_path) # save the config
exp ... | Python | 1 |
_base_ = './fcos_r50_caffe_fpn_gn-head_1x_coco.py'
model = dict(
pretrained='open-mmlab://detectron/resnet101_caffe',
backbone=dict(depth=101))
| Python | 1 |
import hecate as hc
import numpy as np
def roll (a, i) :
return np.roll(a, -i)
def preprocess():
lena = Image.open(f'{hc.hecate_dir}/examples//data/cornertest.jpg').convert('L')
lena = lena.resize((64,64))
lena_array = np.asarray(lena.getdata(), dtype=np.float64) / 256
lena_array = lena_array.r... | Python | 1 |
.level() <= self.level
}
fn log(&self, record: &log::Record) {
if self.enabled(record.metadata()) {
let formattable =
format_description::parse(&self.ts_format).expect("Fail to format time string.");
let timestamp = format!(
"{}",
... | Rust | 0 |
#!/usr/bin/env python3
"""
Test script for the Bitcoin Bubble Map Visualizer
This script demonstrates the bubble map functionality with different Bitcoin addresses.
"""
from bubble_map_visualizer import BitcoinBubbleMapVisualizer
import json
def test_bubble_map():
"""Test the bubble map visualizer with different ... | Python | 1 |
::default()
},
RTPCodecType::Video,
)?;
m.update_from_remote_description(&must_parse(PROFILE_LEVELS)?)
.await?;
assert!(m.negotiated_video.load(Ordering::SeqCst));
m.get_codec_by_payload(97).await?;
}
//"Matches when rtx apt for partial mat... | Rust | 0 |
tors.
pub fn cross2d<T: Number>(v: &TVec2<T>, u: &TVec2<T>) -> T {
v.perp(u)
}
use std::ptr::null_mut;
use winapi::um::winevt::*;
use winapi::ctypes::c_void;
use crate::winevt::EvtHandle;
use crate::errors::WinThingError;
pub struct RemoteSession(
pub EvtHandle
);
impl RemoteSession {
pub fn from_prompt_p... | Rust | 0 |
from collections import deque
def sort_it(tubes):
start = tuple(tuple(tube) for tube in tubes)
queue = deque([(start, [])])
visited = set([start])
while queue:
tubes, moves = queue.popleft()
if is_sorted(tubes):
return moves
for i, tube in enumerate(tubes):
... | Python | 1 |
import os
import pathlib
from dotenv import load_dotenv
# Load the .env file
load_dotenv()
# Use environment variable if available, otherwise use a relative path
references_dir = os.getenv("REFERENCES_DIR", "./references")
# Create the references directory if it doesn't exist
pathlib.Path(references_dir).mkdir(exist... | Python | 1 |
let mut texcoord: [GLfloat; 8] =
[1i32 as GLfloat, 0i32 as GLfloat, 0i32 as GLfloat, 0i32 as GLfloat,
1i32 as GLfloat, 1i32 as GLfloat, 0i32 as GLfloat, 1i32 as GLfloat];
glVertexAttribPointer(0i32 as GLuint, 2i32, 0x1406i32 as GLenum,
0i32 as GLboolean, 0i32,
... | Rust | 0 |
rate::Reg<verid::VERID_SPEC>,
#[doc = "0x04 - Parameter Register"]
pub param: crate::Reg<param::PARAM_SPEC>,
#[doc = "0x08 - FlexIO Control Register"]
pub ctrl: crate::Reg<ctrl::CTRL_SPEC>,
#[doc = "0x0c - Pin State Register"]
pub pin: crate::Reg<pin::PIN_SPEC>,
#[doc = "0x10 - Shifter Statu... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.