text string | label_name string | labels int64 |
|---|---|---|
: &str = "_gap_penalty.";
let cat_weight : &str = "_weighting.";
let mut fout = File::create( ( *arg_o ).as_str() ).expect( "FAILED to open output file" );
writeln!( fout, "{}", *arg_i ).expect( "FAILED to write" );
writeln!( fout, "#" ).expect( "FAILED to write" );
writeln!( fout, "loop_" ).expect( "FAILED t... | Rust | 0 |
_time: f32,
pub _sea_height: f32,
pub _max_particle_count: i32,
pub _max_emitter_count: i32,
pub _gpu_particle_count_buffer_offset: i32,
pub _gpu_particle_update_buffer_offset: i32,
pub _prev_gpu_particle_count_buffer_offset: i32,
pub _prev_gpu_particle_update_buffer_offset: i32,
pub _re... | Rust | 0 |
fairing())
.attach(cors::CorsFairing)
.attach(Compression::fairing())
.manage(Mutex::new(SpotifyTokenData::new()))
.launch();
}
pub mod battery;
extern "C" {
fn temperature() -> f64;
}
#[tauri::command]
pub fn get_temperature() -> f64 {
unsafe {
temperature()
}
}
<filename>a... | Rust | 0 |
# Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
# or more contributor license agreements. Licensed under the Elastic License
# 2.0; you may not use this file except in compliance with the Elastic License
# 2.0.
# Name: Bypass UAC via Sdclt
# RTA: uac_sdclt.py
# ATT&CK: T1088
# Descriptio... | Python | 1 |
45 = 2025 so this gives a ~2000 pixel sample
x_step = self.width / step
y_step = self.height / step
half_x_step = x_step / 2
half_y_step = y_step / 2
for x in range(step):
for y in range(step):
x_co = int(x * x_step + half_... | Python | 1 |
up_unparsed_file.replace(inner_rules, "");
}
Rule::EOI => (),
_ => (),
}
}
up_unparsed_file = up_unparsed_file.replace("#[macro_use]", "");
return up_unparsed_file;
}
///
/// 获取有效的扫描文件
fn get_effective_file(
celler_path: &String,
scan_path:... | Rust | 0 |
my_dict = {'b': 20, 'a': 10, 'c': 30}
sorted_by_key = dict(sorted(my_dict.items()))
sorted_by_value = dict(sorted(my_dict.items(), key=lambda x: x[1]))
print("Original Dictionary:")
print(my_dict)
print("Sorted Dictionary by Key:")
print(sorted_by_key)
print("Sorted Dictionary by Value:")
print(sorted_by_value)
| Python | 1 |
n = int(input("Enter the number upto which u want to print factorial of:"))
product = 1
for i in range(1,n+1):
product = product * i
i+=1
print(f"factorial of {n} is {product}")
# 5! = 1*2*3*4*5
# range varies from 1 to n+1
# ya keh skte hai starts from 1 and chalegi toh n+1 kyuki woh number bhi multiply mei... | Python | 1 |
([entry for entry in states
if not states[entry]], "Bad")]:
container = XML.SubElement(stats, ename)
for item in data:
new_item = copy.deepcopy(item)
new_item.set('qtext', '')
container.append(new_item)
... | Python | 1 |
try> EntryCount<'entry> {
pub fn new(
limits_entry: &'entry LimitsEntry,
threshold: Option<u64>,
num_warnings: u64,
) -> Self {
EntryCount {
entry: limits_entry,
limit: threshold,
actual: num_warnings,
}
}
pub fn entry(&self) -... | Rust | 0 |
ite).map_err(|e|BincErr(e))?;
}
Ok(())
}
}
impl<A : Serialize + DeserializeOwned + Clone + Eq> RepInfo for MultipleReplyInfo<A> {
#[inline]
fn require_additional_payload(&self) -> bool {
if let &MultipleReplyInfo::Route = self { true } else {false}
}
/// TODO remove called once
fn get_reply_... | Rust | 0 |
ParseResult::PartiallyApplyLeft(lhs, (max_span, max_operator))
} else if lhs.is_empty() {
ParseResult::PartiallyApplyRight((max_span, max_operator), rhs)
} else {
ParseResult::Apply(lhs, (max_span, max_operator), rhs)
})
}
}
<filename>src/lib.rs
use std::fmt::Debug;
u... | Rust | 0 |
# This file was auto-generated by Fern from our API Definition.
from ..core.unchecked_base_model import UncheckedBaseModel
import typing
from .speech_history_item_response_model_voice_category import SpeechHistoryItemResponseModelVoiceCategory
from .feedback_item import FeedbackItem
from .speech_history_item_response_... | Python | 1 |
// 4k which is a common page size). So we know we are not
// running in a memory restricted environment.
// src: https://github.com/dotnet/coreclr/blob/master/src/pal/src/misc/cgroup.cpp#L385-L428
if max > 0x7FFF_FFFF_0000_0000 {
return 0;
}
}
#[cfg(any(target_os = "... | Rust | 0 |
"""empty message
Revision ID: f680032cc361
Revises: 00532ac6d4bc
Create Date: 2020-05-24 19:03:10.209349
"""
import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f680032cc361'
down_revision = '00532ac6d4bc'
branch_labels = None
depends_on = None... | Python | 1 |
import marimo
__generated_with = "0.15.2"
app = marimo.App(width="medium")
@app.cell
def _():
import jax
import jax.numpy as jnp
import jax.scipy as jsp
import matplotlib.pyplot as plt
import cvxpy as cp
import marimo as mo
return cp, jnp, plt
@app.cell
def _(jnp):
nx = 4
nu = 2... | Python | 1 |
delete(&self) -> Self {
// let mut s = self.clone();
// s.deleted = true;
// s
// }
// }
// {before: char, after: Option<char>}
// TODO: use enum with Some(c) and Missing(c)
use serde_json::Value;
use wry::Result;
use wry::{Application, Attributes, RpcRequest, WindowProxy};
fn main() -> ... | Rust | 0 |
wasm32-wasi")
.arg("-C")
.arg("opt-level=s")
.arg(file)
.arg("-o")
.arg(&wasm_out_name)
.output()
.expect("Failed to compile program to native code");
print_info_on_error(&wasm_compilation_out, "WASM COMPILATION");
// to prevent commiting huge binary blob... | Rust | 0 |
import random # Non-functional import
from typing import List
class Solution:
def maxIncreasingSubarrays(self, nums: List[int]) -> int:
peak_counter = 0 # Renamed from res
prior_run, current_run = 0, 1 # Renamed prev/cur_increase
# Early exit for edge case
if not nums:
... | Python | 1 |
########
# Copyright (c) 2019 Cloudify Platform Ltd. All rights reserved
#
# 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 requi... | Python | 1 |
# coding=utf-8
import numpy as np
from bilstm_crf_add_word import BiLSTM_CRF
from keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau,\
TensorBoard
from keras.optimizers import Adam, Nadam
import os
# os.environ["CUDA_VISIBLE_DEVICES"] = "1"
char_embedding_mat = np.loa... | Python | 1 |
assert_eq!(r2.ok().unwrap(), "".to_string());
}
#[test]
fn test_if_context() {
let json_str = r#"{"a":{"b":99,"c":{"d": true}}}"#;
let data = Json::from_str(json_str).unwrap();
let mut handlebars = Registry::new();
handlebars.register_helper("with", Box::new(WITH_HELPER))... | Rust | 0 |
nclose(value)
value_conflict_set_str = f"{value_str}=excluded.{value_str}"
where_str = where
if where:
where_str = " AND " + where
self._sql_delitem = f"DELETE FROM {table} WHERE {key_pred_str}{where_str}"
self._sql_getitem = f"SELECT {value_str} FROM {table} WHER... | Python | 1 |
REG_PARAMS[0], size as i64);
}
AllocationSize::Dynamic(reg) => {
self.masm.copy_reg(MachineMode::Ptr, REG_PARAMS[0], reg);
}
}
self.masm.load_int_const(
MachineMode::Int8,
REG_PARAMS[1],
if array_ref { 1 } else { ... | Rust | 0 |
ext`
pub fn replace_extension(file: &str, new_ext: &str) -> String
{
let mut path = PathBuf::from(file);
path.set_extension(new_ext);
path.to_string_lossy().to_string()
}
/// List all markdown files in the specified directory
pub fn list_md_files(dir: &str) -> Vec<String>
{
glob(&format!("{}/*.md", dir... | Rust | 0 |
"""
문제 설명:
퓨처 종합 병원에서는 접수한 환자가 진료 받을 병과에 따라 자동으로 환자 코드를 부여해 주는 프로그램이 있습니다.
환자 코드의 마지막 네 글자를 보면 환자가 어디 병과에서 진료를 받아야 할지 알 수 있습니다. 예를 들어, 환자의
코드가 "_eye"로 끝난다면 안과를, "head"로 끝난다면 신경외과 진료를 보게 됩니다. 혼자 코드의 마지막 글자에
따른 병과 분류 기준은 다음과 같습니다.
"_eye" -> "Ophthalmologyc"
"head" -> "Neurosurgery"
"infl" -... | Python | 1 |
weight_decay=cfg.TRAIN.WEIGHT_DECAY)
# lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 200, gamma=0.316)
else:
optimizer = torch.optim.SGD(trainable_params,
momentum=cfg.TRAIN.MOMENTUM,
weight_decay=cfg.TRAIN.WEIGHT_D... | Python | 1 |
#[allow(unused_variables)]
fn compute_size(&self) -> u32 {
let mut my_size = 0;
if let Some(ref v) = self.origin.as_ref() {
my_size += ::protobuf::rt::string_size(1, &v);
}
if let Some(ref v) = self.name.as_ref() {
my_size += ::protobuf::rt::string_size(2, &v)... | Rust | 0 |
mal::<6>::one()));
assert!(Decimal::<7>::is_one(&Decimal::<7>::one()));
assert!(Decimal::<8>::is_one(&Decimal::<8>::one()));
assert!(Decimal::<9>::is_one(&Decimal::<9>::one()));
}
}
impl<const P: u8, const Q: u8> Mul<Decimal<Q>> for Decimal<P>
where
PrecLimitCheck<{ P <= MAX_PREC }>: Tr... | Rust | 0 |
True)
# Remove complete hypotheses
new_hyps, end_hyps, is_finish = helper.remove_complete_hyp(new_hyps, end_hyps)
if dualhyp:
hyps = new_hyps[:]
else:
hyps_nobd = [beam for beam in new_hyps if beam['no_boundary']]
hyps = [... | Python | 1 |
= ageInfo.getDisplayName()
return FilterAgeName(xLocTools.LocalizeAgeName(localizeName))
## Find the player's neighborhood.
def GetNeighborhood():
try:
return ptVault().getLinkToMyNeighborhood().getAgeInfo()
except AttributeError:
PtDebugPrint("xKIHelpers.GetNeighborhood(): Neighborhood n... | Python | 1 |
pep517",
action="store_false",
dest="use_pep517",
default=None,
help=argparse.SUPPRESS,
)
parser.add_argument(
"--check-build-dependencies",
action="store_true",
default=None,
help="Check the build dependencies when PEP517 is used.",
)
pars... | Python | 1 |
}
let mut to_evict = vec![];
while self.sz > self.capacity {
if self.list.len() == 1 {
// don't evict what we just added
break;
}
let min_pid = self.list.pop_tail().unwrap();
self.entries[min_pid].ptr = ptr::null_... | Rust | 0 |
None
}
}
/// Tries to abort a pending frame. Returns `true` when aborted.
fn abort(&mut self, idx: usize) -> bool {
let can = self.registers();
can.tsr.write(|w| unsafe { w.bits(abort_mask(idx)) });
// Wait for the abort request to be finished.
loop {
l... | Rust | 0 |
er class tests---")
lh = LoRaWANHandler()
print("\t\t---OTAA activation---")
lh.otaa()
utime.sleep_ms(5000)
print("\t\t---Sending unconfirmed message from separate method---")
print("\t\t---Result:", lh.sendUnconfirmed("Hi!"))
utime.sleep_ms(5000)
print("\t\t---Sending unconfirmed messag... | Python | 1 |
import os
def clear_console():
os.system('cls')
clear_console()
noteOne = float(input('Digite a primeira nota: '))
noteTwo = float(input('Digite a segunda nota: '))
average = (noteOne + noteTwo) / 2
print('A média entre {:.1f} e {:.1f} é igual a: {:.1f}'.format(noteOne, noteTwo, average)) | Python | 1 |
context.error(f'animation hierarchy name exceeds max length of: {STRING_LENGTH}')
return False
return True
@staticmethod
def read(context, io_stream, chunk_end):
result = CompressedAnimation(header=None)
while io_stream.tell() < chunk_end:
chunk_type, chu... | Python | 1 |
let frame = Frame {
class,
operand_stack,
local_vars,
method,
};
let thread = thread.push_frame(frame);
let execute_result = ExecuteResult { thread, offset: 0 };
(execute_result, code_reader)
}
//! See [Mesh](crate::mesh::Mesh).
use crate::prelude::*;
use crate::mesh:... | Rust | 0 |
TION_PLOFFSET: usize = 4;
const PARTITION_BLOCK_SIZES: usize = 4 + 1;
const PARTITION_CONTEXTS_PRIMARY: usize = PARTITION_BLOCK_SIZES * PARTITION_PLOFFSET;
pub const PARTITION_CONTEXTS: usize = PARTITION_CONTEXTS_PRIMARY;
pub const PARTITION_TYPES: usize = 4;
pub const MI_SIZE_LOG2: usize = 2;
pub const MI_SIZE: usize... | Rust | 0 |
# coding: utf-8
# =============================================================================
# Ural URL Fingerprinting Unit Tests
# =============================================================================
from __future__ import unicode_literals
from ural import fingerprint_url, fingerprint_hostname
TESTS = [
... | Python | 1 |
T.RDirs" method. (We used to support this by creating a little
"build dictionary" that mapped RDirs to the method, but this got in
the way of Memoizing construction environments, because we had to
create new environment objects to hold the variables.)
"""
def __init__(self, variable, method):
... | Python | 1 |
planner_output_schema = {
"type": "object",
"properties": {
"source_provider": {
"type": "string",
"enum": ["VMware", "Hyper-V", "KVM", "Other"],
},
"target_provider": {
"type": "string",
"enum": ["OpenShift", "AWS", "Azure", "GCP", "Other"... | Python | 1 |
f, _):
self.destroy()
def __initState(self, timeLeft=0, acceptDelta=0):
model = None
if self.__currentState == CYBER_SPORT_ALIASES.AUTO_SEARCH_COMMANDS_STATE:
message = i18n.makeString(CYBERSPORT.WINDOW_AUTOSEARCH_SEARCHCOMMAND_CXTDNMMESSAGE, settings.AUTO_SEARCH_UNITS_ARG_TIME)... | Python | 1 |
pc += 2;
}
/// `instructions::execute_fx0a()`
/// Type = KeyOp
/// Explanation = A key press is awaited, and then stored in VX.
/// (Blocking Operation. All instruction halted until next key event)
pub fn execute_fx0a(machine: &mut Machine, operator: &Operator) {
info!("[execute_fx0a]");
machine.keyboard.keypr... | Rust | 0 |
lx_get_query_objectiv_arb_cookie_t {
fn default() -> Self {
unsafe { std::mem::MaybeUninit::zeroed().assume_init() }
}
}
/// The opcode for `Glx::GetQueryObjectivARB` requests.
///
/// If this value appears in [`xcb_protocol_request_t::opcode`], and
/// [`xcb_protocol_request_t::ext`] is [`XcbGlx::xcb_... | Rust | 0 |
ts)
box_predictions['outputs'].update({
'prop_features': box_features.permute(0, 2, 1, 3), # nlayers x batch x nqueries x channel
'enc_features': enc_features.permute(1, 0, 2), # batch x npoints x channel
'enc_xyz': enc_xyz, # batch x npoints ... | Python | 1 |
:with_capacity(revealed_msgs.len());
for (i, m) in revealed_msgs {
b.push(vk.Y_tilde[i].clone());
e.push(m.clone());
}
j += b.multi_scalar_mul_var_time(&e).unwrap();
&j
};
// e(sigma_1, (J + &X_tilde)) == e(sigma_2, g_tilde)... | Rust | 0 |
"""
Write a python function takes in an integer and check whether the frequency of each digit in the integer is less than or equal to the digit itself.
assert validate(1234) == True
"""
def validate(num):
"""
:param num: int
:return: bool
"""
if num < 0:
return False
else:
retu... | Python | 1 |
'''
Bài 22: Viết chương trình liệt kê, đếm và tính tổng các ước số của số nguyên dương
n (n nhập từ bàn phím).
'''
n = int(input('Nhập số n: '))
tong = 0
so_uoc = 0
print(f"Các ước số của {n} là : ",end = '')
for i in range(1,n + 1):
if n % i == 0:
tong += i
so_uoc += 1
print(i," ",end = ''... | Python | 1 |
if self.merger_config.fisher_normalize:
if self.merger_config.fisher_normalize == "param":
fisher_norm = fisher_norms[n]
elif self.merger_config.fisher_normalize == "model":
fisher_norm = concat_norm
else:
raise... | Python | 1 |
import numpy as np
class JudasCandle:
def __call__(self, metacrayon):
# Pattern metaproperties
open_shift_1 = np.hstack((metacrayon.open[1:], (np.nan,)))
high_shift_1 = np.hstack((metacrayon.high[1:], (np.nan,)))
low_shift_1 = np.hstac... | Python | 1 |
oadcast: None }, &[98, 210, 109, 159, 205, 197], OperandSize::Qword)
}
#[test]
fn vrsqrt28ss_4() {
run_test(&Instruction { mnemonic: Mnemonic::VRSQRT28SS, operand1: Some(Direct(XMM24)), operand2: Some(Direct(XMM27)), operand3: Some(IndirectDisplaced(RAX, 1667909160, Some(OperandSize::Dword), None)), operand4: None... | Rust | 0 |
_dot(mat[2], a)
]
}
/// Transforms a 4D vector through a matrix.
#[inline(always)]
pub fn row_mat4_transform<T>(
mat: Matrix4<T>,
a: Vector4<T>
) -> Vector4<T>
where T: Copy + Add<T, Output = T> + Mul<T, Output = T>
{
[
vec4_dot(mat[0], a),
vec4_dot(mat[1], a),
vec4_dot(mat[... | Rust | 0 |
# Copyright Aaron Smith 2009
#
# This file is part of Gity.
#
# Gity is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Gity is dis... | Python | 1 |
Debug)]
pub struct StationSpecs<E>(pub Dag<StationSpec<E>, Workload>);
impl<E> StationSpecs<E> {
/// Returns an empty graph of [`StationSpec`]s.
pub fn new() -> Self {
Self::default()
}
/// Returns a frozen stations graph.
pub fn frozen(&mut self) -> StationsFrozen<'_, E> {
Frozen:... | Rust | 0 |
1, 0, 0), None);
hr_ans.normal = vect!(-1, 0, 0);
hr_ans.p = vect!(-1, 0, 0);
let hr = c0.hit(&r, 0.0, 1.0);
assert_eq!(hr, Some(hr_ans.clone()));
// from the top
let r = Ray::new(&vect!(0, 2, 0), &vect!(0, -1, 0), None);
hr_ans.normal = vect!(0, 1, 0);
... | Rust | 0 |
rustls::OwnedTrustAnchor::from_subject_spki_name_constraints(
ta.subject,
ta.spki,
ta.name_constraints,
)
}));
#[cfg(feature = "transport-tcp-rustls-native-roots")]
root_store.add_parsable_certificates(
match rustls_native_... | Rust | 0 |
from datetime import datetime
from sqlalchemy import delete, exists, insert, select
from sqlalchemy.ext.asyncio import AsyncSession
from conduit.domain.repositories.follower import IFollowerRepository
from conduit.infrastructure.models import Follower
class FollowerRepository(IFollowerRepository):
"""Repository... | Python | 1 |
nSchema(semantic_tags={"numeric"})
stack_on = []
return TestTransform
@pytest.fixture
def strings_that_have_triggered_errors_before():
return [
" ",
'"This Borderlands game here"" is the perfect conclusion to the ""Borderlands 3"" line, which focuses on the fans ""favorite characte... | Python | 1 |
# Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""API for GraphRAG.
WARNING: This API is under development and may undergo changes in future releases.
Backwards compatibility is not guaranteed at this time.
"""
from graphrag.api.index import build_index
from graphrag.api.prompt_tune imp... | Python | 1 |
#!/usr/bin/env python3
import sys
import os
import argparse
import tkinter as tk
from pathlib import Path
def parse_args():
"""Parse command-line arguments."""
parser = argparse.ArgumentParser(description="Copy a file's contents to the clipboard.")
parser.add_argument('filename', metavar='FILE', type=str, ... | Python | 1 |
'''Finding Time lag Tau'''
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
torch.manual_seed(1)
import matplotlib.pyplot as plt
import pickle, copy, sys, os, csv
import numpy as np
import scipy.optimize, joblib
from matplotlib.colors imp... | Python | 1 |
`kurobako`.
use kurobako_core::epi::problem::ExternalProgramProblemRecipe;
use kurobako_core::problem::{
BoxProblem, BoxProblemFactory, ProblemFactory, ProblemRecipe, ProblemSpec,
};
use kurobako_core::registry::FactoryRegistry;
use kurobako_core::rng::ArcRng;
use kurobako_core::Result;
use kurobako_problems::{hpo... | Rust | 0 |
import struct
from fiatcoin.hash import sha256d
def target_from_bits(difficulty_bits: int) -> int:
if not 0 <= difficulty_bits <= 256:
raise ValueError("difficulty_bits must be between 0 and 256 inclusive")
return 1 << (256 - difficulty_bits)
def mine(
header_without_nonce: bytes,
difficult... | Python | 1 |
for serde.
////////////////////////////////////////////////////////////////////////////
/// Returns the default prefs file path.
fn default_prefs_path() -> PathBuf {
PathBuf::from(DEFAULT_PREFS_PATH)
}
/// Returns the default [`TraceConfig`].
///
/// [`TraceConfig`]: crate::applic... | Rust | 0 |
uman_errors::error_shim!(Error);
<gh_stars>1-10
#GLOBAL
struct VSOutPSIn
{
float4 Position_VSPS : SV_POSITION0;
float4 Color_VSPS : TEXCOORD0;
float2 UV_VSPS : TEXCOORD1;
};
#END
#VS
struct VSIn
{
float3 Position_VS : POSITION0;
float4 Color_VS : COLOR0;
float2 UV_VS : TEXCOORD0;
};
float4x4 Camera;
VSOutPSIn... | Rust | 0 |
curve.curve_type {
_ => {
return self.mul_impl(exp);
},
}
}
fn is_zero(&self) -> bool {
match self.curve.curve_type {
_ => {
return self.is_zero_generic_impl();
},
}
}
fn double(&mut self) {
... | Rust | 0 |
"""
自定義儀表板組件測試
測試儀表板管理器、小工具庫、網格佈局等核心功能。
"""
import unittest
import json
from datetime import datetime
from unittest.mock import Mock, patch, MagicMock
import sys
import os
# 添加專案根目錄到 Python 路徑
project_root = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
)
if project_root not in sys... | Python | 1 |
'sr-Cyrl': 'Науру', 'sr-Latn': 'Nauru', 'sv': 'Nauru', 'sw': 'Nauru', 'syr': 'ܢܐܘܪܘ', 'ta': 'நௌரு', 'te': 'నౌరు', 'teo': 'Nauru', 'tg': 'Науру', 'th': 'นาอูรู', 'ti': 'ናውሩ', 'tk': 'Nauru', 'to': 'Naulu', 'tr': 'Nauru', 'tt': 'Науру', 'twq': 'Nauru', 'tzm': 'Nawru', 'ug': 'ناۋرۇ', 'uk': 'Науру', 'ur': 'نؤرو', 'uz': 'Na... | Python | 1 |
>, dest: impl AsRef<Path>) {
for entry in WalkDir::new(src).min_depth(1).max_depth(1) {
let entry = entry.unwrap();
let src_path = entry.path();
let dest_path = dest.as_ref().join(src_path.file_name().unwrap());
fs::copy(src_path, dest_path).unwrap();
}
}
// -------------------... | Rust | 0 |
.collect::<Vec<_>>()
);
let default_branch = remote
.default_branch()?
.as_str()
.map(ToOwned::to_owned)
.ok_or(E::InvalidBranchError)?;
trace!(
"Default branch for remote {:?}: {}",
remote.name(),
&default_branch
);
if set_remote_h... | Rust | 0 |
_FRAME_HEIGHT, CAP_PROP_FRAME_WIDTH, CAP_V4L2,
},
};
use std::{any::Any, borrow::Cow, collections::HashMap};
/// Converts $from into $to
/// Example usage:
/// `tryinto_num(i32, a_unsigned_32_bit_num)`
/// Designed to deal with infallible. If not, it should be manually handled.
/// # Errors
/// If fails to convert... | Rust | 0 |
from functools import partial
import numpy as np
def decode(id_to_something, tokenizer=None, data_args=None):
decode_fn = None
switch_case = None
elem = next(iter(id_to_something.values()))
if isinstance(elem, str):
switch_case = -1
decode_fn = lambda text: text.strip()
elif isinst... | Python | 1 |
me {
addrs.push(IpAddr::V6(record.data().addr()))
}
}
}
Ok(())
}
/// Returns a reference to the domain name that was queried.
pub fn qname(&self) -> &Dname {
&self.qname
}
/// Returns a reference to the canonical name for the ... | Rust | 0 |
ipeRequest = from_value(args)?;
let width = req.width.unwrap_or(DEFAULT_DIMENSION);
let height = req.height.unwrap_or(DEFAULT_DIMENSION);
let duration = req.duration.map_or(DEFAULT_DURATION, Duration::from_millis);
let move_event_count = req.move_event_count.unwrap_or_else(|| {
... | Rust | 0 |
#!/usr/bin/env python3
# -*- Coding: UTF-8 -*-
# ---------------------------------------------------------------------------
# Open Asset Import Library (ASSIMP)
# ---------------------------------------------------------------------------
#
# Copyright (c) 2006-2020, ASSIMP Development Team
#
# All rights reserved.
#... | Python | 1 |
rchy, results, tab + 1
)
results_agg = {**results_agg, **_results_agg}
groups_agg = {**groups_agg, **_groups_agg}
return results_agg, groups_agg
results_agg = collections.defaultdict(dict)
groups_agg = collections.defaultdict(dict... | Python | 1 |
ption.value)
effects1 = pd.Series(y.entity_ids.squeeze() // 2, index=y.index)
effects2 = pd.Series(y.entity_ids.squeeze() // 4, index=y.index)
effects = pd.DataFrame({"eff1": effects1, "eff2": effects2})
with pytest.raises(ValueError, match=r"Included other effects nest") as exception:
PanelOLS... | Python | 1 |
# This file was auto-generated by Fern from our API Definition.
import typing
import typing_extensions
from .gift_card_customer_unlinked_event_data import GiftCardCustomerUnlinkedEventDataParams
class GiftCardCustomerUnlinkedEventParams(typing_extensions.TypedDict):
"""
Published when a [customer](entity:Cu... | Python | 1 |
self._whois_history.parse(response)
return self._whois_history
@property
def ip(self):
"""IP address as a string."""
return self._ip
@property
def certificates(self):
"""History of TLS certificates presented by services hosted on this IP address.
... | Python | 1 |
import pandas as pd
import ast
from collections import defaultdict
# 读取txt文件
with open('result/zh_results.txt', 'r', encoding='utf-8') as file:
lines = file.readlines()
# 按task_id分组数据
data_groups = defaultdict(list)
# 将每行字典格式的数据解析并按task_id分组
for line in lines:
line = line.strip()
if line.startswith("{'ta... | Python | 1 |
movements for a unit
#[derive(Clone, Copy)]
struct FillNode {
x: i32,
y: i32,
depth: i32,
}
impl FillNode {
fn new(x: i32, y: i32, depth: i32) -> Self {
FillNode { x, y, depth }
}
}
fn add_fill_node(
map: &Map,
dx: i32,
dy: i32,
n: &FillNode,
visited: &mut Vec<bool>,
... | Rust | 0 |
from fastapi import (
FastAPI,
APIRouter,
Query,
Path,
Body,
Cookie,
Header,
File,
Form,
Depends,
Security,
)
from pydantic import BaseModel
app = FastAPI()
router = APIRouter()
# Fixable errors
@app.get("/items/")
def get_items(
current_user: User = Depends(get_curre... | Python | 1 |
);
Err(ErrorKind::MismatchedType(
topic.into(),
connection_topic.msg_type.clone(),
msg_type,
)
.into())
} else {
Ok(connection.add_subscriber(queue_size, on_message, on_connect))
}
}
#[inline]
pu... | Rust | 0 |
ut from "%s" failed to match expected '
'output.\n\n%s' % (input_file, ''.join(diff)))
def TestSyntax():
for dir_name, sub_dirs, files in os.walk(test_dir):
# Get dir specific config settings.
config = get_config(dir_name)
# Loop through files and ... | Python | 1 |
active = 1
WHERE active = true;
UPDATE gear
SET is_active = 0
WHERE active = false;
"""
)
op.alter_column(
"gear",
"is_active",
nullable=False,
comment="Is gear active (0 - not active, 1 - active)",
existing_type=sa.Integer(),
)
... | Python | 1 |
.path.join(checkpoint_root, "checkpoint.tar"))
# save model
self._log("saving last models...\n")
model_root = os.path.join(CONF.PATH.OUTPUT, self.stamp)
torch.save(self.model.state_dict(), os.path.join(model_root, "model_last.pth"))
# export
for phase in ["train", "val"... | Python | 1 |
t = content
doc_pri.save()
doc_pub.reload()
doc_pri.reload()
self.assertEqual(doc_pub.is_private, 0)
self.assertEqual(doc_pri.is_private, 1)
self.assertEqual(doc_pub.file_url, f"/files/{file_name}.txt")
self.assertEqual(doc_pri.file_url, f"/private/files/{file_name}.txt")
self.assertEqual(doc_pub.ge... | Python | 1 |
/! ```bash
//! $ cargo install azure-functions-sdk
//! ```
//!
//! Create a new Azure Functions for Rust application:
//!
//! ```bash
//! $ cargo func new-app hello && cd hello
//! ```
//!
//! Create a HTTP-triggered function:
//!
//! ```bash
//! $ cargo func new http -n hello
//! ```
//!
//! This generates `src/functi... | Rust | 0 |
s a file from Google Drive. from yolov5.utils.downloads import *; gdrive_download()
t = time.time()
file = Path(file)
cookie = Path('cookie') # gdrive cookie
print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='')
file.unlink(missing_ok=True) # remove existi... | Python | 1 |
::SlotsPerHistoricalRoot::to_u64(),
min_epochs_to_inactivity_penalty: spec.min_epochs_to_inactivity_penalty,
epochs_per_historical_vector: T::EpochsPerHistoricalVector::to_u64(),
epochs_per_slashings_vector: T::EpochsPerSlashingsVector::to_u64(),
historical_roots_limit: T... | Rust | 0 |
for anchors in anchor_list[0]]
results = multi_apply(self._get_targets_single, anchor_list,
responsible_flag_list, gt_bboxes_list,
gt_labels_list, img_metas, num_level_anchors=num_level_anchors)
all_target_maps, all_neg_maps = results
... | Python | 1 |
# Copyright (c) 2015 Advanced Micro Devices, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of condi... | Python | 1 |
#!/usr/bin/env python3
import sys, os, shutil, subprocess
os.chdir (os.environ.get ('srcdir', os.path.dirname (__file__)))
libs = os.environ.get ('libs', '.libs')
ldd = shutil.which ('ldd')
if ldd:
ldd = [ldd]
else:
ldd = shutil.which ('otool')
if ldd:
ldd = [ldd, '-L'] # otool -L
else:
print ('check-libstd... | Python | 1 |
{}", s),
}
}
}
#[cfg(test)]
use crate::{expression::deep::UnaryOpWithReprs, operators::VecOfUnaryFuncs};
#[test]
fn test_operate_unary() {
let lstr = "x+y+x+z*(-y)+x+y+x+z*(-y)+x+y+x+z*(-y)+x+y+x+z*(-y)+x+y+x+z*(-y)+x+y+x+z*(-y)+x+y+x+z*(-y)+x+y+x+z*(-y)";
let deepex = DeepEx::<f64>::from_str(lstr... | Rust | 0 |
,
#[inline(always)] |i| {
sets[i].len()
},
#[inline(always)] |i, c| {
result.write().unwrap()[i] = &sets[i][c];
}, cb);
}
/// Create a cartesian product over itself. The result will be a slice
/// of borrowed `T`.
///
/// # Parameters
/// - `set` A slice of s... | Rust | 0 |
sBackendPort', '_webServerPort', '_webServerBasicAuthPasswordHashed', '_webServerAPIKeyHashed']
_config_template = """
setMaxTCPClientThreads(1)
newServer{address="127.0.0.1:%s", tls='gnutls', validateCertificates=true, caStore='ca.pem', subjectName='not-powerdns.com'}
webserver("127.0.0.1:%s")
setW... | Python | 1 |
p(email, from_m="Initial"):
total = []
tic = time.perf_counter()
try:
total = p_emailrep(email, from_m)
except Exception as e:
# Check internal error
if str(e).startswith("iKy - "):
reason = str(e)[len("iKy - "):]
status = "Warning"
else:
... | Python | 1 |
are okay because no one who is just reading the data
// has the ability to affect anyone else's reading of the data
//
// Note that a reference's scope starts where it is introduced and continues through the last time
// that reference is used. For instance, this code will compile because the last usage of the
// immu... | Rust | 0 |
print_red("\t\tNothing found")
print_cyan("\t[*] FTP : ")
if len(creds[0]) >0:
for cred in creds[0]:
print("\t\tuser: \033[92m {} \033[0m\t , password: \033[92m {} \033[0m".format(cred[0],cred[1]))
else:
print_red("\t\tNothing found")
###########... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.