text string | label_name string | labels int64 |
|---|---|---|
is_any,
left,
right,
cmp,
}
}
fn iter_lines<'a>(left: &'a str, right: &'a str) -> impl Iterator<Item = (&'a str, &'a str)> {
let (l_iter, r_iter) = (left.lines(), right.lines());
l_iter.zip_longest(r_iter).map(|pair| match pair {
... | Rust | 0 |
VanitySecretType::Phrase(phrase) => {
let secret_type = vanity::SecretType::Phrase {
language: phrase.phrase_opts.language.language.to_owned(),
words: phrase.phrase_opts.words.0,
};
(secret_type, &phrase.common_opts)
... | Rust | 0 |
print(int(input('Insira um numero: ')))
num = 7
cont = 0
chance = 0
while chance != num:
cont = cont + 1
#print('Errou')
print(f'Chance {cont}. Tente novamente!')
| Python | 1 |
return self._get_connection(using).indices.forcemerge(
index=self._name, **kwargs
)
def shrink(self, using=None, **kwargs):
"""
The shrink index API allows you to shrink an existing index into a new
index with fewer primary shards. The number of primary shards in the
... | Python | 1 |
(store, &child);
if child_id == id {
return Some((parent, index as u32));
}
}
None
}
pub fn find_iter_by_id(
store: >k::TreeStore,
id: page_store::Id,
) -> Option<gtk::TreeIter> {
fn find_in_children(
store: >k::TreeStore,
id: page_store::Id,
... | Rust | 0 |
=> true,
}
}
#[cfg(any(test, feature = "bench"))]
pub fn get_valid_txfm_types(tx_size: TxSize) -> &'static [TxType] {
let size_sq = tx_size.sqr_up();
use TxType::*;
if size_sq == TxSize::TX_64X64 {
&[DCT_DCT]
} else if size_sq == TxSize::TX_32X32 {
&[DCT_DCT, IDTX]
} else {
&[
DCT_DCT,
... | Rust | 0 |
# KITTY'S LTD (Lockergoga)
"cf933a629598e5e192da2086e6110ad1974f8ec3",
# Mozilla Corporation (AutoIt NetWire)
"b6b24aea9e983ed6bda9586a145a7ddd7e220196",
# FDSMMCME (Emotet)
"4d1bc69003b1b1c3d0b43f6c17f81d13e0846ea7",
# ULTRA PARTNERS LTD
... | Python | 1 |
aes-256-ctr";
#[cfg(feature = "cipher-bf-cfb")]
const CIPHER_BF_CFB: &'static str = "bf-cfb";
#[cfg(feature = "cipher-camellia-cfb")]
const CIPHER_CAMELLIA_128_CFB: &'static str = "camellia-128-cfb";
#[cfg(feature = "cipher-camellia-cfb")]
const CIPHER_CAMELLIA_192_CFB: &'static str = "camellia-192-cfb";
#[cfg(featur... | Rust | 0 |
bvecs_concat[i] += ' '
bvecs_concat = '\n'.join(str(v) for v in bvecs_concat) # transform list into lines of strings
# Write files
new_f = open(arguments.obval, 'w')
new_f.write(bvals_concat)
new_f.close()
printv("Generated file: {}".format(arguments.obval))
new_f = open(arguments.ob... | Python | 1 |
self._logger.exception(err)
self._accept_notifier.setEnabled(False)
try:
self._socket.close()
except socket.error:
pass
self._socket = None
self._connected = False
def _notify_accept(self):
"""Callback called when a client is conne... | Python | 1 |
import numpy as np
from bokeh.layouts import column, row
from bokeh.models import ColumnDataSource, CustomJS, Slider
from bokeh.plotting import figure, output_file, save
x = np.linspace(0, 1, 500)
y1 = 5.0 * (1 - x**2) ** 2.0
y2 = 5.0 / (1 + 2.0 * x**2) ** 2 # Initial data for the second line
source = ColumnDataSour... | Python | 1 |
size & 0x7fffffff);
let b2 = self.subsegment_duration;
let b3 = ((self.starts_with_sap as u32) << 31) | (((self.sap_type & 0x7) as u32) << 28) | (self.sap_delta_time & 0x0fffffff);
b1.to_bytes(stream)?;
b2.to_bytes(stream)?;
b3.to_bytes(stream)?;
Ok(())
}
}
<repona... | Rust | 0 |
::*;
use super::tr::IdxNode;
use super::vfile::VarFile;
use rabuf::{SmallRead, SmallWrite};
use std::cell::RefCell;
use std::convert::TryInto;
use std::fs::OpenOptions;
use std::io::{Read, Result, Write};
use std::path::Path;
use std::rc::Rc;
type HeaderSignature = [u8; 8];
//const CHUNK_SIZE: u32 = 4 * 1024;
//const... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
Minimalistic implementation of l1 minimization via coordinate descent.
Reference: www.jstatsoft.org/v33/i01/paper
Author: Fabian Pedregosa <fabian@fseoane.net>
"""
import numpy as np
MAX_ITER = 100
def l1_coordinate_descent(X, y, alpha, max_iter=MAX_ITER):
"""
Solves a problem ... | Python | 1 |
# -*- coding: UTF-8 -*-
"""
Define utility classes/functions here.
"""
__author__ = 'kensk8er'
class Name2Proba(dict):
"""Data Structure for storing mapping from name to gender probability."""
def __init__(self):
super(Name2Proba, self).__init__()
self._fixed_keys = set()
self._key2c... | Python | 1 |
, "Cover (click to change)"))
self.titleLine.setToolTip(_translate("Dialog", "Title"))
self.titleLine.setPlaceholderText(_translate("Dialog", "Title"))
self.authorLine.setToolTip(_translate("Dialog", "Author"))
self.authorLine.setPlaceholderText(_translate("Dialog", "Author"))
se... | Python | 1 |
import logging
import threading
import time
from octoeverywhere.sentry import Sentry
from .moonrakerclient import MoonrakerClient, JsonRpcResponse
# A class to handle the popup notification actions from the service.
class UiPopupInvoker():
def __init__(self, logger:logging.Logger):
self.Logger = logger
... | Python | 1 |
![no_std]"));
assert!(!check_magic(b"#![deny(warnings)]"));
assert!(!check_magic(b"#[use_macros]"));
assert!(!check_magic(b"#!@?%!"));
}
#[test]
fn valid_executables() {
assert!(is_executable("/usr/bin/cp").unwrap());
assert!(is_executable("/usr/bin/env").unwrap());
... | Rust | 0 |
MsgAddressIntOrNone,
};
use ton_types::{
BuilderData, IBitstring,
};
use crate::util::{
create_external_inbound_msg, create_internal_msg,
};
///////////////////////////////////////////////////////////////////////////////////////
#[derive(Clone, Debug)]
pub struct AddressWrapper {
pub addr: MsgAddress
}... | Rust | 0 |
- A txout index.
/// * `amount` - A satoshi amount.
///
/// # Example
///
/// ```
/// use cfd_rust::{Address, OutPoint, Transaction, TxInData, TxOutData};
/// let outpoint = OutPoint::from_str(
/// "0202020202020202020202020202020202020202020202020202020202020202",
/// 1).expect("Fail");
/// let... | Rust | 0 |
}
fn part2(input: &str, days: usize) -> usize {
let mut floor = Floor::parse(input);
floor.run(days);
floor.count_flipped_tiles()
}
#[cfg(test)]
mod tests {
use super::*;
use indoc::indoc;
static EXAMPLE1: &str = indoc! {"
sesenwnenenewseeswwswswwnenewsewsw
neeenesenwnwwswne... | Rust | 0 |
ply: # done after this packet
self.reply = None
self.transaction_active = False
self.seq = 0
return ret.ToWireFormat()
def SetChannelBusyCount(self, busy_count): # pylint: disable=invalid-name
"""Mark the channel busy for next busy_count read calls."""
self.busy_count = busy_count
... | Python | 1 |
import clickhouse_connect
from typing import Any
from sql_runner.core import ConnectionConfig, SQLRunner
class ClickHouseRunner(SQLRunner):
def __init__(
self,
connection_config: ConnectionConfig,
**kwargs: Any
):
super().__init__(connection_config=connection_confi... | Python | 1 |
}
aoc::print_solution1(format!("{} combined yes answers", result).as_str());
}
fn part2() {
let mut chars: HashSet<char> = HashSet::new();
let mut result = 0;
for (i, section) in file::sections().enumerate() {
let mut count = 0;
for (pos, line) in section.enumerate() {
if ... | Rust | 0 |
format_implementation(&Display2Format(&123u8), &[index, b'1', b'2', b'3', 0xff]);
}
<reponame>1Blackdiamondsc/mobilecoin
// Copyright (c) 2018-2021 The MobileCoin Foundation
//! GRPC authenticator that relies on a shared secret for generating and verifying tokens.
use super::*;
use displaydoc::Display;
use hmac::{Hm... | Rust | 0 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DmarSatc")
.field("header", &*self as &DmarSatcHeader)
// TODO: print out device scopes
.finish()
}
}
/// The list of different "Remapping Structure Types".
///
/// Refer to section 8.2 in the V... | Rust | 0 |
depr_msg = f"'{freq_depr[1:]}' is deprecated and will be removed in a "
f"future version. Please use '{freq[1:]}' instead."
depr_msg_res = f"'{freq_depr_res[1:]}' is deprecated and will be removed in a "
f"future version. Please use '{freq_res[1:]}' instead."
with tm.assert_produces_war... | Python | 1 |
let from_balance = self.balance_of_or_zero(from, id);
if from_balance < value {
return Err(Error::InsufficientBalance);
}
self.balances.insert((*from, *id), from_balance - value);
Ok(())
}
fn approved_or_owner(&self, account... | Rust | 0 |
s i32);
println!("{}", r.sum() * (x as i32));
return;
}
}
}
}
<reponame>bryan-lott/net-parser-rs<gh_stars>0
use crate::{
errors::{self, Error, ErrorKind},
flow,
layer4::Layer4FlowInfo,
};
use log::*;
use nom::{Err as NomError, ErrorKind as NomErrorKin... | Rust | 0 |
#!/usr/bin/python3
# coding=utf-8
"""
OneForAll subdomain takeover module
:copyright: Copyright (c) 2019, Jing Ling. All rights reserved.
:license: GNU General Public License v3.0, see LICENSE for more details.
"""
import time
import json
from threading import Thread
from queue import Queue
import fire
from common.t... | Python | 1 |
y, x, c='green')
plt.xlabel('Episode')
plt.ylabel('Step_Size')
"""
plt.figure(2)
plt.plot(y, z, c='blue')
plt.xlabel('Episode')
plt.ylabel('Average Return')
"""
figure = plt.figure(4)
ax = Axes3D(figure)
X = np.arange(0, turn, 1)
Y = json.loads(str(step_size))
... | Python | 1 |
or i in range(len(y)):
x[i].append('')
x[i].extend(y[i])
return x
else:
for i in range(len(x)):
y[i].append('')
y[i].extend(x[i])
return y
def chformat(allpeaks,realpeaks,result,calcst):
title1 = ['Wavelength(nm)','Spectrum','T=Spec/ma... | Python | 1 |
caretaker,
app,
lang,
)
}
}
}
break;
} else if !inp.shown() {
caretaker.pop().unwrap();
return;
}
}
}
/// **DEPRECATED**
//... | Rust | 0 |
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
"""
Be sure to check the learn guides for more usage information.
This example is for use on (Linux) computers that are using CPython with
Adafruit Blinka to support CircuitPython libraries. CircuitPython does
not support PI... | Python | 1 |
parse_zero_prefixable_int(),
)).map(|b: &[u8]| {
unsafe { from_utf8_unchecked(b, "`.` and `parse_zero_prefixable_int` filter out npn-ASCII") }
})
});
// zero-prefixable-int = DIGIT *( DIGIT / underscore DIGIT )
parse!(parse_zero_prefixable_int() -> &'a str, {
recognize((
skip_many1(... | Rust | 0 |
, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(
f,
"{} '{}'",
if self.operation == Operation::SerializeGraph {
"serialize to"
} else {
"deserialize from"
},
self.bin_dir
)
... | Rust | 0 |
---------------
# get_pose ray_o ray_v D = depth s = sdf(o + Dv)
# rays_o, rays_d = self.gen_rays()
# 实际上形参已经有rays_o, rays_d
# img_idx 计算gs_depth然后转换到世界坐标 射线查询深度 射线查询sdf表面所在位置 根据差值计算判据 规定采样near far
... | Python | 1 |
import numpy as np
import bpy
from bpy.props import FloatProperty, EnumProperty, BoolProperty, IntProperty, FloatVectorProperty
from sverchok.node_tree import SverchCustomTreeNode
from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level
from sverchok_extra.dependencies import sdf
from sve... | Python | 1 |
);
assert_eq!(query[0].entity, first);
// query which is inside bounding_box of both first and second
let query: Vec<_> = world
.read_resource::<Space>()
.query_point(Point::new(2.5, 0.5), 1.0)
.collect();
assert!(!query.is_empty());
assert_eq... | Rust | 0 |
one,
{
pub fn to_owned(&self) -> Value<K, V> {
match self {
ValueCow::Owned(owned) => owned.clone(),
ValueCow::Borrowed(borrowed) => borrowed.to_value(),
}
}
pub fn into_owned(self) -> Value<K, V> {
match self {
ValueCow::Owned(owned) => owned,
ValueCow::Borrowed(borrowed) => ... | Rust | 0 |
import cv2
image=cv2.imread("./rdj.jpg")
print("Image array dimension: ",image.shape)
newImage=image[:400,:400]
c=0
while True:
for i in range(0,400,100):
for j in range(0,400,100):
if c%2==0:
newImage[i:i+100,j:j+100]=(0,0,0)
else:
newImage[i:i+100,... | Python | 1 |
}));
}
}
Ok(None) => {
tx1.send(w).unwrap();
thread::sleep(time::Duration::from_millis(200));
}
Err(_e) => {
drop(tx1);
p.abandon_with_message(console::style("✗").red().to_string().as_str());
return Err(HMError::Regular(hmek::... | Rust | 0 |
# 圈中测试集样本
## lable列表
plt.xlabel(iris_feature[0], fontsize=13)
plt.ylabel(iris_feature[1], fontsize=13)
plt.xlim(x1_min, x1_max)
plt.ylim(x2_min, x2_max)
plt.title(u'鸢尾花Ridge特征分类', fontsize=16)
plt.grid(b=True, ls=':')
plt.tight_layout(pad=1.5)
# 子图4:KNeighborsClassifier
plt.subplot(224)
## 区域图
plt.pcolormesh(x1, ... | Python | 1 |
_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<DAINT_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Field `INEPINT0` reader - IN Endpoint 0 Interrupt Bit"]
pub struct INEPINT0_R(crate::FieldReader<bool, bool>);
impl INEPINT0_R {
pub(crate) fn new(bits: bool) -> Self {
INEPINT0_R(cra... | Rust | 0 |
address <= self.end
}
}
impl From<Range<usize>> for MemRange {
fn from(range: Range<usize>) -> Self {
Self::new(range.start, range.end - 1)
}
}
impl From<RangeInclusive<usize>> for MemRange {
fn from(range: RangeInclusive<usize>) -> Self {
let (start, end) = range.into_inner();
... | Rust | 0 |
def validate_threshold(threshold: str) -> float:
"""Validate and convert threshold input"""
try:
value = float(threshold)
if value < 0 or value > 100:
raise ValueError("Threshold must be between 0 and 100")
if value < 50:
print("⚠️ Warning: Threshold below 50% is... | Python | 1 |
ff\xcb\xcc\xc1\xed\xc6\t",),
),
(
"get",
[123],
None,
(123,),
),
],
)
def test_get_safe_key(method_name, args, kwargs, expected_key):
assert _get_safe_key(method_name, args, kwargs) == expected_key
@pytest.mark.parametrize(
"key,expec... | Python | 1 |
xit()
if tc300obj.is_open(sn) == 0:
print("TC300IsOpen failed")
tc300obj.close()
exit()
ChannelReadWrite(tc300obj)
print("--------------------------- Channel 1 Read&Write finished-------------------------")
ChannelParametersReadWrite(tc300obj)
... | Python | 1 |
cx, r, w))?;
*state = TransferState::ShuttingDown;
}
TransferState::ShuttingDown => {
ready!(Pin::new(&mut *w).poll_shutdown(cx))?;
*state = TransferState::Done;
}
TransferState::Done => return Poll::Ready(Ok(())),
... | Rust | 0 |
import json
from pytchat.parser.live import Parser
from pytchat.processors.compatible.processor import CompatibleProcessor
parser = Parser(is_replay=False)
def test_textmessage(mocker):
'''api互換processorのテスト:通常テキストメッセージ'''
processor = CompatibleProcessor()
_json = _open_file("tests/testdata/compatible/t... | Python | 1 |
.as_slice(), &mut dl_dest).unwrap();
Box::new(futures::future::ok(()))
}
}
use std::fmt::{self,Display};
/// Enum for all types of duration of silences - only used in silences
#[derive(Debug,PartialEq,Clone)]
pub enum Expire {
/// No time expiration with optional expire on resolve
NoExpiration(boo... | Rust | 0 |
# 绑定处理程序
from aiohttp.abc import Application
from telegram.ext import CommandHandler
from config import TG_BOT_TOKEN
application = Application.builder().token(TG_BOT_TOKEN).build()
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("profile", profile))
application.add_handl... | Python | 1 |
Error("only 0D keys are supported")
jax_key = key.numpy()
if n is None and new_axis is None:
jax_a, jax_b = jax.random.split(jax_key)
return ntensor(jax_a), ntensor(jax_b)
elif n and new_axis:
if not isinstance(n, int):
raise ValueError(f"n must be int (got {n}) to ensur... | Python | 1 |
import importlib
from simbricks.runner.main_runner.plugins import plugin
from simbricks.utils import load_mod
class RunnerPluginLoadError(Exception):
pass
def load_plugin(path: str) -> type[plugin.FragmentRunnerPlugin]:
module = None
# try to import module
try:
module = importlib.import_modu... | Python | 1 |
import zipfile
import glob
import os
import pandas as pd
import numpy as np
# generate fake data
cfg_tickers = ['AAP','M','SPLS']
cfg_ntickers = len(cfg_tickers)
cfg_ndates = 10
cfg_dates = pd.bdate_range('2018-01-01',periods=cfg_ndates).tolist()+pd.bdate_range('2018-02-01',periods=cfg_ndates).tolist()
cfg_nobs = cf... | Python | 1 |
use fumen::{CellColor, Fumen, Page};
use pcf::{BitBoard, Piece, Placement};
pub fn draw_placements(page: &mut Page, placements: &[Placement]) {
for placement in placements {
blit(
page,
placement.board(),
pcf_piece_to_fumen_piece(placement.kind.piece()).into(),
)... | Rust | 0 |
",
"SDBT",
"ZEP",
"DSP.WS",
"GZV",
"MMRpM",
"MV",
"SYMX",
"TNDM",
"BPAX",
"GLG.U",
"GLG.WS",
"HFB",
"KIDS",
"SD",
"SDZST",
"TAZST",
"AMCN",
"ARYX",
"BFRM",
"BJW",
"FTBpB",
"GPH.U",
"GRO",
"RRY",
"RSU",
"AREX",
"CLA.U",
"DOD",
"EST.U",
"EWV",
"FXP",
"ICXT",... | Rust | 0 |
: Sn, buf: &[u8]) -> Result<u16, Self::Error> {
debug_assert_eq!(self.sn_sr(sn)?, Ok(SocketStatus::Udp));
let data_len: u16 = match u16::try_from(buf.len()) {
Ok(l) => l,
Err(_) => return Ok(0),
};
let free_size: u16 = self.sn_tx_fsr(sn)?;
if data_len <= ... | Rust | 0 |
import os, sys
# insert parent directory at beginning of python search path
from pathlib import Path
sys.path.insert(0,os.fspath(Path(__file__).parents[2]))
# use QuitListener for Linux or PC <- doesn't work on Mac
#from tools.quit_listener import QuitListener
import numpy as np
import parameters.simulation_parameters ... | Python | 1 |
beg_pos = tokenized.char_to_token(beg + 2)
except:
beg_pos = None
if end_pos is None:
try:
end_pos = tokenized.char_to_token(end - 2)
if end_pos is None:
end_pos = tokeniz... | Python | 1 |
menu.push_str(&format!(
"{}: {}\n",
counter,
entry.file_stem().unwrap().to_str().unwrap()
));
counter += 1;
}
menu
}
// Take the user's choice
fn get_input(question: &str) -> String {
let mut buf = String::new();
print!("{}", question);
io... | Rust | 0 |
# Copyright (c) 2022 Iluvatar CoreX. All rights reserved.
# Copyright Declaration: This software, including all of its code and documentation,
# except for the third-party software it contains, is a copyrighted work of Shanghai Iluvatar CoreX
# Semiconductor Co., Ltd. and its affiliates ("Iluvatar CoreX") in accordance... | Python | 1 |
import os
from dotenv import load_dotenv
from pytz import timezone # Import timezone from pytz
from src.updateUser import schedule_jobs
from src.mainHandler import main_menu, start, set_product,get_all_products,send_loot_deals
from src.callBack import daily_notification, weekly_notification, minimum_price, custom_mini... | Python | 1 |
lag might
//! change some behavior of the operators on [QuadraticSurd].
//! - `num-complex`: Enable converting [QuadraticSurd] to `num_complex::Complex`. You probably want to enable
//! the `complex` feature at the same time.
//! - `num-bigint`: Enable using big integers as the internal representation.
//!
pub mod con... | Rust | 0 |
import re
from kittens.tui.handler import result_handler
from kitty.key_encoding import KeyEvent, parse_shortcut
def encode_key_mapping(window, key_mapping):
mods, key = parse_shortcut(key_mapping)
event = KeyEvent(
mods=mods,
key=key,
shift=bool(mods & 1),
alt=bool(mods & 2),... | Python | 1 |
from django.db.models import TextChoices
class OrderStatus(TextChoices):
PENDING = "PENDING", "PENDING"
DELIVERED = "DELIVERED", "DELIVERED"
CANCELLED = "CANCELLED", "CANCELLED"
| Python | 1 |
# 요일 변환: 월=0 ~ 일=6
KOREAN_DAY_TO_WEEKDAY = {
"월": 0, "화": 1, "수": 2, "목": 3, "금": 4, "토": 5, "일": 6,
}
WEEKDAY_TO_CATEGORY = {
0: "평일", # 월
1: "평일", # 화
2: "평일", # 수
3: "평일", # 목
4: "평일", # 금
5: "토", # 토
6: "일", # 일
}
# 테니스장 ID Matching
COURT_FAC_ID_MAP = {
("탄천", "1번 코트",... | Python | 1 |
2]
uncertainty[:, 3] = L[:, 1, 1]
uncertainty[:, 4] = L[:, 1, 2]
uncertainty[:, 5] = L[:, 2, 2]
return uncertainty
def strip_symmetric(sym):
return strip_lowerdiag(sym)
def build_rotation(r):
norm = torch.sqrt(r[:, 0] * r[:, 0] + r[:, 1] * r[:, 1] + r[:, 2] * r[:, 2] + r[:, 3] * r[:, 3])
... | Python | 1 |
8>, CommonError> {
Ok(self.to_bytes()?)
}
}
impl<'a> Deserialize<'a> for Pair {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'a> {
struct PairVisitor;
impl<'a> Visitor<'a> for PairVisitor {
type Value = Pair;
fn expecting(&... | Rust | 0 |
from django.contrib.auth.decorators import login_required
from django.forms import ModelForm
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.utils.text import slugify
from django.views.generic import ListView, DetailView
from blog.models impo... | Python | 1 |
[derive(Clone, Debug, PartialEq, Call, Encode)]
pub struct VoteOnStatusUpdateCall<T: StakedRelayers> {
pub _runtime: PhantomData<T>,
pub status_update_id: u64,
pub approve: bool,
}
#[derive(Clone, Debug, PartialEq, Call, Encode)]
pub struct ReportOracleOffline<T: StakedRelayers> {
pub _runtime: Phantom... | Rust | 0 |
)?;
let cgroups_path = utils::get_cgroup_path(
&spec.linux.context("no linux in spec")?.cgroups_path,
container.id(),
);
// remove the cgroup created for the container
// check https://man7.org/linux/man-pages/man7... | Rust | 0 |
board, &mut editor, &mut writer);
assert!(editor.open_called_with(&path_to_file));
}
#[test]
fn it_creates_a_new_file_when_there_is_none() {
let key = String::from("test");
let mut board = BoardMock::new();
let mut editor = EditorMock::new();
let mut writer = Cursor... | Rust | 0 |
import numpy as np
import torch
import quik
def pack_to_i4(X):
def two_compl(x, bits):
return torch.where(x < 0, 2 ** bits + x, x)
X_i8 = two_compl(X.to(dtype=torch.int8), 4).to(torch.uint8)
X_i4 = X_i8[:, 0::2] | (X_i8[:, 1::2] << 4)
return X_i4
def int4_kernel_test():
B, M, K, N = 1,... | Python | 1 |
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
fr... | Python | 1 |
: &Req, result: Result<&Res, &Error>) -> Option<Self::Future> {
if result.is_err() && self.0 > 0 {
Some(future::ready(Limit(self.0 - 1)))
} else {
None
}
}
fn clone_request(&self, req: &Req) -> Option<Req> {
Some(*req)
}
}
#[derive(Clone)]
struct Unl... | Rust | 0 |
t_avg_trades = sum(m.get("total_trades", 0) for m in first_half) / len(
first_half
)
second_avg_trades = sum(m.get("total_trades", 0) for m in second_half) / len(
second_half
)
trade_trend = (
"increasing" if second_avg_trades > first_avg_trades else ... | Python | 1 |
from get_from_netbox import devices, vlans
from genie.conf import Genie
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--testbed", dest="testbed")
args, unknown = parser.parse_known_args()
def disconnect():
for device in testbed.devices:
testbed.devices[device].disconnect_all()
... | Python | 1 |
.field("orig_rax", &self.orig_rax)
.field("fs_base", &self.fs_base)
.field("gs_base", &self.gs_base)
.finish()
}
}
impl Amd64CoreRegs {
/// create `Amd64CoreRegs` from user and fp regs.
pub fn from(regs: libc::user_regs_struct, i387: libc::user_fpregs_struct... | Rust | 0 |
::three(),
]
.iter_mut()
.zip(WAKERS.iter_mut())
.filter(|(channel, _)| ral::read_reg!(register, channel, TFLG, TIF == 1))
.for_each(|(channel, waker)| {
ral::write_reg!(register, channel, TCTRL, 0);
if let Some(waker) = waker.take(... | Rust | 0 |
GPT3A = 14,
#[doc = "13: GPT2B interrupt event, controlled by GPT2:TBMR"]
GPT2B = 13,
#[doc = "12: GPT2A interrupt event, controlled by GPT2:TAMR"]
GPT2A = 12,
#[doc = "11: AUX combined event, the corresponding flag register is here AUX_EVCTL:EVTOMCUFLAGS"]
AUX_COMB = 11,
#[doc = "10: AUX S... | Rust | 0 |
= root_cfg.appender("con");
let mut app_builder = Appender::builder();
if let Some(ref f) = filter {
app_builder = app_builder.filter(Box::new(f.clone()));
}
if settings.stdout_color {
let con_appender = ConsoleAppender::new(prefix);
config = config.a... | Rust | 0 |
opt_com = '--interface ' + getattr(sop, 'interface_s') + ' '
if getattr(sop, 'gateway'):
opt_com += '--gateway ' + getattr(sop, 'gateway') + ' '
if getattr(sop, 'target'):
opt_com += '--target ' + getattr(sop, 'target') + ' '
if getattr(sop, 'sniffer').lower() == 'y':
opt... | Python | 1 |
layer_padding='SAME',
previous_layer_rf_info=rf_info)
proto_layer_rf_info = compute_layer_rf_info(layer_filter_size=prototype_kernel_size,
layer_stride=1,
lay... | Python | 1 |
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import JointState
from geometry_msgs.msg import Twist
class PositionVelocityPublisher(Node):
def __init__(self):
super().__init__('position_velocity_publisher')
self.publisher_ = self.create_publisher(JointState, 'joint_command', 10)
... | Python | 1 |
Ok(Some(T::WeightInfo::rebond(removed_chunks)).into())
}
/// Set `HistoryDepth` value. This function will delete any history information
/// when `HistoryDepth` is reduced.
///
/// Parameters:
/// - `new_history_depth`: The new history depth you would like to set.
/// - `era_items_deleted`: The numbe... | Rust | 0 |
variant: CEIMSEL_A) -> Self {
variant as _
}
}
#[doc = "Field `CEIMSEL` reader - Comp. E Neg. Channel Input Select 0"]
pub struct CEIMSEL_R(crate::FieldReader<u8, CEIMSEL_A>);
impl CEIMSEL_R {
pub(crate) fn new(bits: u8) -> Self {
CEIMSEL_R(crate::FieldReader::new(bits))
}
#[doc = r"Get ... | Rust | 0 |
uctions.clone();
}
let program = CompleteLineProgram {
header: rows.program.header,
};
Ok((program, sequences))
}
}
/// Deprecated. `CompleteLineNumberProgram` has been renamed to `CompleteLineProgram`.
#[deprecated(
note = "CompleteLineNumberProgram has been rename... | Rust | 0 |
nsor(self._initial_value).double()
elif isinstance(initial_patch_value, float):
initial_value = np.ones(self.patch_shape) * initial_patch_value
self._patch.data = torch.Tensor(initial_value).double()
elif self._patch.shape == initial_patch_value.shape:
self._patch.dat... | Python | 1 |
.pop();
let bin = format!(r#""binary":"{}","#,path);
self.string_for_session.push_str(&bin);
self.string_for_session.push('}');
self
}
///More info on the FF args here:
///https://developer.mozilla.org/en-US/docs/Mozilla/Command_Line_Options?redirectlocale=en-US&redirectslug=... | Rust | 0 |
p
class SeparableConv3d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, padding=0, dilation=1, bias=False):
super(SeparableConv3d, self).__init__()
self.spitalwise = nn.Conv3d(in_channels, in_channels, kernel_size, stride, padding, dilation, groups=in_channels,
... | Python | 1 |
prob = random.random()
# mask token with 15% probability
if prob < 0.15:
masked_video[i][j] = [0.] * video.shape[-1]
video_labels_index[i].append(j)
else:
video... | Python | 1 |
ta, val_data)
weight_history.append(history['modality_weights'])
print(f"Epoch {epoch + 1}/5 - Weights:", history['modality_weights'])
# Plot weight evolution
print("\nPlotting weight evolution...")
plot_weight_evolution(weight_history, output_dir / 'weight_evolution.png')
# Ev... | Python | 1 |
&'static str> {
Html(include_str!("../../static/index.html"))
}
#[get("/chrust.js")]
fn javascript() -> JavaScript<&'static str> {
JavaScript(include_str!("../../static/js/chrust.js"))
}
#[get("/chrust.css")]
fn css() -> Css<&'static str> {
Css(include_str!("../../static/css/chrust.css"))
}
// /img/chess... | Rust | 0 |
# All code function
def create_cltv_p(dataframe, month=3):
# 1. Preprocess
dataframe.dropna(inplace=True)
dataframe = dataframe[~dataframe["Invoice"].str.contains("C", na=False)]
dataframe = dataframe[dataframe["Quantity"] > 0]
dataframe = dataframe[dataframe["Price"] > 0]
replace_with_thresh... | Python | 1 |
import pyodbc
conn = pyodbc.connect(
'DRIVER={SQL Server};'
'SERVER=WIN-DBFHEB1G4A7\SQLEXPRESS\\SQLEXPRESS;'
'DATABASE=BankDB;'
'Trusted_Connection=yes;'
)
| Python | 1 |
/// Check whether a `NestedRanges2D<T, S>` is empty
pub fn is_empty(&self) -> bool {
self.ranges.is_empty()
}
}
use ndarray::Array1;
impl From<&NestedRanges2D<u64, u64>> for Array1<i64> {
/// Create a Array1<i64> from a NestedRanges2D<u64, u64>
///
/// This is used when storing a STMOC into... | Rust | 0 |
if accumulated > 0:
w_tmp_a = torch.div(w_accumulate, torch.tensor(accumulated).to(device)).view(-1)
if weighting_method == 'fedvarp':
w_tmp_a += update_all_avg.to(device)
update_all_avg = torch.mean(update_per_node, 0)... | Python | 1 |
m.read_i32::<Endian>()?;
let ns = from.read_i32::<Endian>()?;
MarkResult::Success(s, ns)
}
2 => {
MarkResult::CE(String::deserialize(from)?)
}
3 => MarkResult::RTE,
4 => MarkResult::TLE,
5 =>... | Rust | 0 |
ождь \U00002614',
'heavy intensity rain': 'Дождь \U00002614',
'very heavy rain': 'Дождь \U00002614',
'extreme rain': 'Дождь \U00002614',
'freezing rain': 'Дождь \U00002614',
'light intensity shower rain': 'Дождь \U00002614',
'shower rain': 'Дождь \U00002614',
'heavy intensit... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.