text string | label_name string | labels int64 |
|---|---|---|
_functions_visited.clear();
let api_function_num = self.api_functions.len();
for _ in 0..api_function_num {
self.api_functions_visited.push(false);
}
//TODO:还有别的序列可能需要reset
}
//检查是否所有函数都访问过了
pub fn check_all_visited(&self) -> bool {
let mut visited_nodes ... | Rust | 0 |
ID);
if !thread_handle.is_null() {
println!("5 -> {}", pid);
if kernel32::SuspendThread(thread_handle) != DWORD::max_value() {
println!("6");
let mut context = zeroed();
... | Rust | 0 |
import random
import numpy as np
def generate_random_bits(length):
return [random.randint(0, 1) for _ in range(length)]
def generate_random_bases(length):
return [random.choice(['+', 'x']) for _ in range(length)]
def measure_in_basis(bit, basis):
if basis == '+':
return bit # 0 -> 0, 1 -> 1
... | Python | 1 |
yptoKeyType.CSEK and
keywrapper.crypto_key_sha256 == key_sha256):
return keywrapper.crypto_key
def GetEncryptionKeyWrapper(boto_config):
"""Returns a CryptoKeyWrapper for the configured encryption key.
Reads in the value of the "encryption_key" attribute in boto_config, and if
present, verifies... | Python | 1 |
der.wide_data_test,
cs_loader.labels_test)
train_data = cs_loader.gendata(cs_loader.train_size / args.batch_size, cs_loader.deep_data,
cs_loader.embeddings_index,
cs_loader.wide_data, cs_loader.labels)
tpba... | Python | 1 |
hi_adam = return_greeting("Adam")
print(hi_adam) | Python | 1 |
false,
err_str: "Insert failed".into(),
}
}
#[marine]
#[derive(Debug)]
pub struct RewardBlock {
pub block_number: i64,
pub timestamp: i64,
pub block_miner: String,
pub block_reward: String,
}
impl RewardBlock {
fn from_row(row: &[Value]) -> Self {
RewardBlock {
blo... | Rust | 0 |
on) as file:
# gt_questions = json.load(file)
# with open(args.gt_file_answers) as file:
# gt_answers = json.load(file)
gt_questions = json.load(open(args.gt_file_question, "r"))
gt_questions = get_chunk(gt_questions, args.num_chunks, args.chunk_idx)
gt_answers = json.load(open(args.gt_... | Python | 1 |
CsReq = 4483
TreasureDungeonFinishScNotify = 4432
UseTreasureDungeonItemScRsp = 4477
InteractTreasureDungeonGridCsReq = 4443
GetTreasureDungeonActivityDataCsReq = 4472
GetTreasureDungeonActivityDataScRsp = 4485
EnterTreasureDungeonScRsp = 4446
EnterTreasureDungeonCsReq = 4416
InteractTre... | Python | 1 |
import unittest
import settings
import time
import mosquitto
def on_message(mosq, obj, msg):
obj.message_queue.append(msg)
class mqtt_publish_in_callback(unittest.TestCase):
message_queue = []
@classmethod
def setUpClass(self):
self.client = mosquitto.Mosquitto("pubsubclient_ut", clean_ses... | Python | 1 |
// 加入一个计算 5 次方程 5x^5 + 4x^4 + ... + x = k 的电路组件
// 这里以**新创建的变量** x 作为输入
// 以结果变量 k 作为输出
let k_var = compose_proof_of_quintic_equ_root(&mut circuit, x_var)?;
// println!("after adding the quintic equ root: ");
// for v in 0..circuit.num_vars() { println!("{}: {}", v, circuit.witness(v).unwrap())... | Rust | 0 |
import pandas as pd
import ipaddress
# Load CSV file
rules = pd.read_csv("Firewall.csv")
print(" => Firewall Rule Analyzer Summary \n")
# Total rules
total_rules = len(rules)
print(f" Total Rules: {total_rules}")
# Allow vs Deny count
action_counts = rules["Action"].value_counts()
print("\n Rule Actions:")
print(ac... | Python | 1 |
&File) -> IOResult<()> {
match self {
LockPolicy::LockSharedDuringAppendingAndLockExclusiveDuringUploading => file.lock_shared(),
LockPolicy::AlwaysLockExclusive => file.lock_exclusive(),
LockPolicy::None => Ok(()),
}
}
#[allow(dead_code)]
fn lock_for_upl... | Rust | 0 |
.listener.sl_arg {
arg = i; // Found the match
break;
}
}
if arg < MAX_SENSOR_LISTENERS {
// Found the Wrapped Sensor Listener. Register the associated Sensor Listener with Mynewt.
// Pass the associated listener to the unsafe Mynewt API.
unsafe { sens... | Rust | 0 |
marks=pytest.mark.dependency(name="case_insensitive_2"),
),
pytest.param(
"ALEgria",
"alergia",
marks=pytest.mark.dependency(name="case_insensitive_3"),
),
pytest.param(
"muro",
"RuMo",
marks=pytest.mark.dependenc... | Python | 1 |
'False'
else:
return t_statistic, p_value, 'True'
def statistic_dis_compare(dis1, dis2, is_t_test=False, is_wt_test=False):
t1_stat = None
p1_value = None
t_result = None
t2_stat = None
p2_value = None
wt_result = None
if is_t_test:
# Independent sample t-test
... | Python | 1 |
r(nondirs[0], "name")
assert hasattr(nondirs[0], "id")
assert hasattr(nondirs[0], "type")
# AND: Should be able to find nested content
nested_results = [r for r in results if "nested_folder" in r[0][0]]
assert len(nested_results) == 1
_, nested_dirs, nested_nondirs = nes... | Python | 1 |
}
let result = deconfigure_core(&mut config_json, args, &schema);
if args.supervisor_exists {
systemd::start_service(SUPERVISOR_SERVICE)?;
}
result
}
fn deconfigure_core(
config_json: &mut ConfigMap,
args: &Args,
schema: &OsConfigSchema,
) -> Result<()> {
store_api_key(co... | Rust | 0 |
from dance.transforms import CellPCA, WeightedFeaturePCA
from dance.transforms.graph import DSTGraph, NeighborGraph, PCACellFeatureGraph, SpaGCNGraph
def test_reprs(subtests):
with subtests.test("CellPCA"):
t = CellPCA(n_components=100)
assert repr(t) == "CellPCA(n_components=100)"
with subte... | Python | 1 |
rive(Serialize, Deserialize)]
pub struct JSONNLP {
meta: Meta,
#[serde(default)]
docs: Vec<Document>,
}
/*
fn deserialize_any<'de, T, D>(deserializer: D) -> Result<Option<T>, D::Error>
where
T: Deserialize<'de>,
D: Deserializer<'de>,
{
Deserialize::deserialize(deserializer).map(Some)
}
*/
/// This function conv... | Rust | 0 |
print_log(&self, log: &Log) {
let (_c, r) = self.size;
let rows = usize::try_from(r).unwrap();
let len = log.len();
let range = if len <= rows {
0..len
} else {
let start = len - rows;
start..len
};
for i in range {
... | Rust | 0 |
si = stock_df['RSI'].iloc[-1]
print("\n简单技术分析:")
print(f"当前价格: {current_price:.2f}")
print(f"20日均线: {ma20:.2f}")
print(f"60日均线: {ma60:.2f}")
print(f"当前RSI(14): {current_rsi:.2f}")
# 趋势分析
if current_price > ma20 > ma60:
trend = "多头排列,可... | Python | 1 |
ind_error
mocked_point.value = 1
mocked_point.dimensions = {
"protocol": "tcp",
"not_accurate_listen": '["127.0.0.1:8080"]',
"nonlisten": "[]",
"bind_ip": "10.0.0.1",
"bk_target_ip": "10.0.0.1",
"display_name": "test",
"... | Python | 1 |
"
THOST_FTDC_SEX_None = 48
"""未知"""
THOST_FTDC_SEX_Man = 49
"""男"""
THOST_FTDC_SEX_Woman = 50
"""女"""
class TThostFtdcUserTypeType(Enum):
"""用户类型类型"""
THOST_FTDC_UT_Investor = 48
"""投资者"""
THOST_FTDC_UT_Operator = 49
"""操作员"""
THOST_FTDC_UT... | Python | 1 |
def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'][api] + '/' + path
if api == 'private':
self.check_required_credentials()
nonce = self.nonce()
body = self.json(self.extend({'nonce': nonce}, params))
... | Python | 1 |
import sys
sys.setrecursionlimit(10 ** 8)
input = sys.stdin.readline
def dfs(sx, sy):
# 도착 지점에 도달하면 1(한 가지 경우의 수)를 리턴
if sx == m-1 and sy == n-1:
return 1
# 이미 방문한 적이 있다면 그 위치에서 출발하는 경우의 수를 리턴
if dp[sx][sy] != -1:
return dp[sx][sy]
ways = 0
for i in range(4):
nx, n... | Python | 1 |
nking all teeth with voxel of {} (s): ".format(voxel_size), shrink_time)
shrinking_info['shrinking_time'] = shrink_time
params.params_log_info['shrinking_parameters'] = shrinking_info
unn = np.array(unn)
centers = np.array(centers)
impacted = np.array(impacted)
mid_o_dir = os.path.abspa... | Python | 1 |
def f(ip, n):
i = 0
out = ''
for c in ip:
if i == n:
out += '\n'
i = 0
i += 1
out += c
return out | Python | 1 |
import allure
from locators.order_feed_page_locators import OrderFeedPageLocators
from pages.base_page import BasePage
class OrderFeedPage(BasePage):
@allure.step('Выбор последнего созданного заказа')
def select_last_order(self):
self.click(OrderFeedPageLocators.ORDER_IN_FEED_LINK)
@allure.... | Python | 1 |
import cv2
import easyocr
import re
from PIL import Image
import numpy as np
import certifi
import ssl
import urllib
# Define a list of city names in Pakistan
pakistan_cities = ['Karachi', 'Lahore', 'Islamabad', 'Rawalpindi', 'Faisalabad', 'Multan', 'Peshawar', 'Quetta', 'Sialkot']
def remove_special_characters(inpu... | Python | 1 |
# Copyright (c) ONNX Project Contributors
#
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import onnx
from onnx.backend.test.case.base import Base
from onnx.backend.test.case.node import expect
class Floor(Base):
@staticmethod
def export() -> None:
node = onnx.helper.make_node(
... | Python | 1 |
from __future__ import unicode_literals
import traceback
import frappe
from frappe.utils.fixtures import sync_fixtures
@frappe.whitelist()
def execute():
"""
Updates the woocommerce_identifier field on all customers
"""
sync_fixtures("woocommerce_fusion")
customers = frappe.db.get_all(
"Customer",
filter... | Python | 1 |
mbers(&self) -> SyntaxResult<TsTypeElement> { support::required_node(&self.syntax) }
pub fn r_curly_token(&self) -> SyntaxResult<SyntaxToken> {
support::required_token(&self.syntax, T!['}'])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ImportDecl {
pub(crate) syntax: SyntaxNode,
}
impl ImportDecl {
... | Rust | 0 |
from flaskr.bot.utils.is_admin import is_admin
from flaskr import db
from flaskr.bot.admin.admin_constants import EXAM_OPTIONS, RECIEVE_EXAM_NAME
from telegram.ext import CallbackContext, CallbackContext
from telegram import Update, ReplyKeyboardRemove
from telegram.replykeyboardmarkup import ReplyKeyboardMarkup
from ... | Python | 1 |
self.init_image_coor(intrinsic, H, W)
gt_points, pred_points = self.select_points_groups(target, prediction, intrinsic, mask)
gt_p12 = gt_points[:, :, :, 1] - gt_points[:, :, :, 0]
gt_p13 = gt_points[:, :, :, 2] - gt_points[:, :, :, 0]
pred_p12 = pred_points[:, :, :, 1] - pred_... | Python | 1 |
ect_pixel_values = (
batch["object_pixel_values"].unsqueeze(0).to(accelerator.device)
)
num_objects = batch["num_objects"].unsqueeze(0).to(accelerator.device)
all_object_pixel_values = all_object_pixel_values.to(
dtype=weight_dtype, device=accelerator... | Python | 1 |
range_start: isize,
range_end: isize,
total_count: isize,
data: &'a [T],
}
#[derive(Serialize)]
pub struct ChannelListingResults<'a, T: 'a> {
channel: String,
target: String,
data: &'a [T],
}
#[derive(Deserialize)]
pub struct ToChannel {
#[serde(default)]
pub channel: ... | Rust | 0 |
"""Test init of IronOS integration."""
from unittest.mock import AsyncMock
from pynecil import CommunicationError
import pytest
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
@pytest.mark.usefixtures("mock_pynecil", "... | Python | 1 |
ssert hasattr(chunk.choices[0].delta, "prompt_token_ids")
assert hasattr(chunk.choices[0].delta, "completion_token_ids")
if is_first_chunk:
is_first_chunk = False
assert isinstance(chunk.choices[0].delta.prompt_token_ids, list)
assert chunk.choices[0].delta.completion... | Python | 1 |
)
if filename:
fin = zfile.open(name, 'r')
outFile = os.path.join(destDir, name)
fout = open(outFile, 'wb')
content = fin.read(chunk_size)
content_size = len(content)
... | Python | 1 |
in 0..input_data.len() {
assert_eq!(&input_data[i].hash(), &v[i].hash);
assert_eq!(&input_data[i].hash(), &v[i].hash);
assert_eq!(i, v[i].index);
assert!(v[i].is_leaf);
}
}
#[test]
fn test_ensure_even() {
let input_data: Vec<H256> = gen_merkl... | Rust | 0 |
String::new();
for i in min..=max {
if plants.contains(&i) {
out.push('#')
} else {
out.push('.')
}
}
out
}
fn step(plants: BTreeSet<i32>, spread: &BTreeSet<u8>) -> BTreeSet<i32> {
let min = plants.iter().next().unwrap() - 2;
let max = plants.iter().... | Rust | 0 |
.name, "*Ziga")]
#for Ziga in Apagar_Ziga:
for objeto in context.selected_objects:
if fnmatch.fnmatchcase(objeto.name, "ma*"):
objeto.name = "MaxillaCopyZiga"
MaxilaCopia = objeto
objeto.animation_data_clear()
print("Maxila OK", objeto)
if f... | Python | 1 |
tput as-is. If it
/// does not, the value of `aliases[i]` (which means the alias to another
/// index) is output.
///
/// The more likely a particular index is to be output, the more of the value
/// will be included in `aliases`.
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct WalkerTable {
//... | Rust | 0 |
server = futures[future]
wg.post_message(LogBox.Msg(f"Syncing clocks failed on {server.host} with error: {future.result()}", "error", debug=True, timestamp=True))
if failed:
# Stop if one of the servers failed
wg.post_messa... | Python | 1 |
_arg: PathBuf,
},
/// subcommand with args
#[structopt(name = "complex")]
Complex(ComplexType),
}
#[derive(StructOpt)]
enum ComplexType {
#[structopt(name = "nested-subcommand")]
NestedSubcommand {
/// helped for nested subcommand arg
#[structopt(long = "some-arg")]
some... | Rust | 0 |
)?;
bytes.write_u8(self.lowres_image_height)?;
if self.version[0] >= 7 && self.version[1] >= 2 {
bytes.write_u16::<LittleEndian>(self.depth)?;
}
if self.version[0] >= 7 && self.version[1] >= 3 {
bytes.write_u8(0)?;
bytes.write_u8(0)?;
byt... | Rust | 0 |
# coding: utf-8
# Copyright (c) 2016, 2025, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | Python | 1 |
mbeddings::new(p / "embeddings", config);
let encoder = LongformerEncoder::new(p / "encoder", config);
let pooler = if add_pooling_layer {
Some(LongformerPooler::new(p / "pooler", config))
} else {
None
};
let max_attention_window = *config.attention_wind... | Rust | 0 |
omicBool, Ordering, ATOMIC_BOOL_INIT};
use chrono;
use clap::ArgMatches;
use slog::{Drain, Logger};
use slog_async::{Async, OverflowStrategy};
use slog_scope::GlobalLoggerGuard;
use slog_term::{PlainDecorator, TermDecorator};
use tikv::config::{MetricConfig, TiKvConfig};
use tikv::util;
use tikv::util::collections::H... | Rust | 0 |
.lock()
.expect(zinc_const::panic::SYNCHRONIZATION)
.failed += 1;
println!(
"[INTEGRATION] {} {} ({})",
"FAILED".bright_red(),
... | Rust | 0 |
t max_aspect_num, max_aspect_den;
/// int32_t base_width, base_height;
/// uint32_t win_gravity;
/// } xcb_size_hints_t;
/// ```
///
/// Declaration taken from
/// [here](https://cgit.freedesktop.org/xcb/util-wm/tree/icccm/xcb_icccm.h).
///
/// Returns XError::InvalidPrope... | Rust | 0 |
import pkgutil
import sys
from importlib import import_module
from pathlib import Path
from types import ModuleType
from typing import List
def get_path(module: ModuleType) -> str:
if getattr(sys, "frozen", False):
# frozen
if getattr(sys, "_MEIPASS", False):
# PyInstaller
... | Python | 1 |
self == ERR22_A::ERR22_0
}
#[doc = "Checks if the value of the field is `ERR22_1`"]
#[inline(always)]
pub fn is_err22_1(&self) -> bool {
*self == ERR22_A::ERR22_1
}
}
#[doc = "Write proxy for field `ERR22`"]
pub struct ERR22_W<'a> {
w: &'a mut W,
}
impl<'a> ERR22_W<'a> {
#[doc = r"Wr... | Rust | 0 |
import tkinter as tk
from tkinter import ttk
# Create instance
win = tk.Tk()
# Add a title
win.title("Python GUI")
# Adding a Label
ttk.Label(win, text="A Label").grid(column=0, row=0)
# Start GUI
win.mainloop()
| Python | 1 |
point formula")
f_prime = five_end_point_2(fx0, fxh, fx2h, fx3h, fx4h, x0, h)
elif i == len(x) - 1 or i == len(x) - 2:
fxh = fx[i - 1]
fx2h = fx[i - 2]
fx3h = fx[i - 3]
fx4h = fx[i - 4]
print("5 End point formula")
f_prime = fi... | Python | 1 |
push(ffi::IoVec::from_str(&self.msg_field));
if !self.pid_field.is_empty() {
self.iovecs.push(ffi::IoVec::from_str(&self.pid_field));
}
&self.iovecs
}
fn send(&mut self) -> std::io::Result<()> {
let ret = unsafe {
let iovecs = self.prepare();
... | Rust | 0 |
t
fisrtround = 1
else:
print(chunk["choices"][0]["delta"]["content"], end="", flush=True)
full_response += chunk["choices"][0]["delta"]["content"]
except:
pass
delta = datetime.dat... | Python | 1 |
#.######.########.#
.###.#######.####.#.
#####.##.#.##.###.##
..#####..#.#########
####################
#.####....###.#.#.##
##.#################
#####.##.###..####..
..######..##.#######
####.##.####...##..#
.#####..#.######.###
##...#.##########...
#.##########.#######
.####.#.#... | Rust | 0 |
.top_left_with_margin_on(id, border_thickness)
.graphics_for(id)
.place_on_kid_area(false)
.set(state.icon, ui);
}
ButtonType::Uncollapse => {
let icon_triangles = classic_frame::make_uncollapse_button_icon(
... | Rust | 0 |
import subprocess
import time
# DNS_SERVER = "8.8.8.8"
DNS_SERVER = "127.0.0.2"
# DNS_SERVER = "192.168.1.1"
DELAY = 0.003
websites = filter(lambda x: bool(x.strip()), open("websites.txt").readlines())
print("Creating threads for each website")
processes: list[subprocess.Popen] = [
subprocess.Popen(["nslookup", w... | Python | 1 |
import logging
from tests.common.errors import RunAnsibleModuleFail
logger = logging.getLogger(__name__)
def prepare_testbed_ssh_keys(duthost, ptfhost, dut_username):
'''
Prepares testbed ssh keys by generating ssh key on ptf host and adding this key to known_hosts on duthost
@param duthost: instance o... | Python | 1 |
s(COMMON_PG_PAT_NUM) # 这个类可以获取常见的piano_guitar组合
common_pattern_cls.restore('PianoGuitar') # 直接从sqlite文件中读取
self.common_pg_pats = common_pattern_cls.common_pattern_list # 常见的bass组合列表
# 2.获取和弦的根音组合
self.pg_avr_root = get_nearest_number_multiple(PG_AVR_NOTE, 12)
rc_pattern_cls =... | Python | 1 |
pass_by_ref)]
pub fn should_clamp_with_overflow(bounds: &Bounds, overflow_bounds: &Option<Bounds>) -> bool {
if let Some(overflow_bounds) = overflow_bounds {
bounds_in_bounds(*bounds, *overflow_bounds)
} else {
bounds_in_bounds(*bounds, (0.0, 1.0).into())
}
}
// =============
// === Tests... | Rust | 0 |
from adhocracy.model import CategoryBadge
from adhocracy.lib.helpers.badge_helper import get_parent_badges
badge0 = CategoryBadge.create(u'testbadge0', u'#ccc', True, u'descr')
badge11 = CategoryBadge.create(u'testbadge11', u'#ccc', True, u'descr')
badge12 = CategoryBadge.create(u'test... | Python | 1 |
#read a file
file=open("abc.txt","r")
data=file.read() #read whole file
# data=file.read(10) #read only 10 character from file
print(data)
file.close() | Python | 1 |
BRIDGE_PREFIX={}",
include_prefix.to_string_lossy(),
);
}
if let Some(links) = &self.links {
println!("cargo:CXXBRIDGE_LINKS={}", links.to_string_lossy());
}
for (i, header_dir) in self.header_dirs.iter().enumerate() {
if header_dir.exp... | Rust | 0 |
import concurrent.futures
import sys
import time
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.chrome.webdriver import WebDriver as Chrome
from selenium.webdriver.common.by import By
# takes YouTub... | Python | 1 |
import math
TOP_LIM = 9976543091
first_primes = [2, 3, 5, 7, 11, 13, 17,]
def is_pandigital(l):
strint = str(l)
for i in range(0, len(strint)):
if str(i) not in strint:
return False
return True
def is_pansubprime(m):
z_index = 0
for z in range(1,len(str(m))-2):
#print(... | Python | 1 |
": kwargs.get("content"),
"audio_input": kwargs.get("audio_input")
}
def process_response(self, response: Dict[str, Any]) -> Dict[str, Any]:
return response
class ClothesSceneGenerator(VideoGenerator):
"""服装场景视频生成器"""
def __init__(self, **kwargs):
super().__in... | Python | 1 |
default_app_config = 'django.contrib.postgres.apps.PostgresConfig'
| Python | 1 |
ush(".to");
home
})
.unwrap();
assert_eq!(options.config, expected);
}
#[test]
fn cli_flag_config() {
let options = run(vec!["--config", "~/whatever"]);
let expected = PathBuf::from("~/whatever");
assert_eq!(options.config, expected);
}
<reponame>Haitei/Sakura-RS
use crate... | Rust | 0 |
um(tf.multiply(roi_outside_weights, diff_sL1), reduction_indices=[1]))
# Constant for weighting bounding box loss with classification loss
roi_bbox_reg = cfg.TRAIN.FRCNN_BBOX_LAMBDA * roi_bbox_reg
return roi_bbox_reg
def smoothL1(x, sigma):
'''
Tensorflow implementati... | Python | 1 |
16().collect::<Vec<u16>>();
window_name.push(0);
_sapp_win32_hwnd = CreateWindowExW(
win_ex_style, // dwExStyle
class_name.as_ptr(), // lpClassName
window_name.as_ptr(), // lpWindowName
win_style, // dwStyle
CW_USEDEFAULT, ... | Rust | 0 |
ad_texture(&mut factory, &include_bytes!("image/water.png")[..]).unwrap();
let flow_texture = load_texture(&mut factory, &include_bytes!("image/flow.png")[..]).unwrap();
let noise_texture = load_texture(&mut factory, &include_bytes!("image/noise.png")[..]).unwrap();
let program = {
let vs = gfx::S... | Rust | 0 |
, y }
}
}
fn output_to_queue(recv: Receiver<i64>, queue: Arc<RwLock<VecDeque<Message>>>) {
let mut buffer = vec![];
loop {
let value = recv.recv();
if let Err(_) = value {
// println!("Err in monitor thread while reading data: {}", err);
break;
}
if... | Rust | 0 |
len = s.len();
s.remove(len - 1);
write!(f, "{}", s)
}
}
/// A top level statement in GDL. The only types of top level statements are `Rule`s and
/// `Sentence`s
#[derive(Debug, Clone, Hash, Eq, PartialEq, RustcDecodable, RustcEncodable, Ord, PartialOrd)]
pub enum Clause {
// A rule clause
... | Rust | 0 |
number_of_machines,
start_machine,
starting_ip,
is_dry_run,
)
if not machines:
raise RuntimeError("No machines were created...")
print()
setup_network(machines, is_dry_run, args.network_name)
print()
if is_dry_run:
print("Dry Run: not initalizing ma... | Python | 1 |
odel_name}"
if model_name == "DeepLabV3Plus":
# drop depth and decoder_channels
model_conf.uq_method.model.pop("encoder_depth")
model_conf.uq_method.model.pop("decoder_channels")
module = instantiate(model_conf.uq_method, freeze_decoder=True)
seg_model = mod... | Python | 1 |
tr;
pub fn fill_bytes(v: &mut [u8]) {
let mib = [libc::CTL_KERN, libc::KERN_ARND];
// kern.arandom permits a maximum buffer size of 256 bytes
for s in v.chunks_mut(256) {
let mut s_len = s.len();
let ret = unsafe {
libc::sysctl(mib.as_ptr(), mib.len()... | Rust | 0 |
s)))
.collect::<Result<Vec<String>, _>>()?
.join(":");
let mut script = String::new();
script += "set -o errexit\n";
script += "set -o pipefail\n";
script += "pkg install -q git\n";
script += &format!("mkdir -p '{}'\n", getenv("GITHUB_WORKSPACE")?);
script += &format!("cd '{}'\... | Rust | 0 |
.field(
"resource_type_opt_in_preference",
&self.resource_type_opt_in_preference,
);
formatter.finish()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct UpdateRecoveryPointLifecycleInput {
/// <p>The name of a logical container where bac... | Rust | 0 |
ST ARROW AND SOUTH WEST ARROW
(b"setmn", "\u{2216}"), // SET MINUS
(b"sext", "\u{2736}"), // SIX POINTED BLACK STAR
(b"sfr", "\u{1D530}"), // MATHEMATICAL FRAKTUR SMALL S
(b"sharp", "\u{266F}"), // MUSIC SHARP SIGN
(b"shchcy", "\u{0449}"), // CYRILLIC SMALL LETTER SHCHA
(b"shcy", "\u{... | Rust | 0 |
ort(concat!(
"[",
file!(),
":",
line!(),
"]",
"failed to schedule task"
));
false
}
Ok(_) => true,
}
};
}
/// a hacky macro which a... | Rust | 0 |
_program_from_1202_state(input).unwrap();
print!("Day2: {}", value);
}
<gh_stars>0
use async_trait::async_trait;
use fluvio_types::SpuId;
use crate::stores::spu::*;
use crate::stores::spg::K8SpuGroupSpec;
use crate::dispatcher::k8::metadata::K8Obj;
pub type SpuGroupObj = K8Obj<K8SpuGroupSpec>;
/// need for addin... | Rust | 0 |
T_WANTSND: ::c_int = 0x2000000; // Want above
pub const NFSMNT_RCVLOCK: ::c_int = 0x4000000; // Rcv socket lock
pub const NFSMNT_WANTRCV: ::c_int = 0x8000000; // Want above
pub const NFSMNT_WAITAUTH: ::c_int = 0x10000000; // Wait for authentication
pub const NFSMNT_HASAUTH: ::c_int = 0x20000000; // Has authenticator
pu... | Rust | 0 |
# Import necessary libraries
import cv2
from jetcam.csi_camera import CSICamera
# Initialize the CSI camera
camera = CSICamera(capture_width=1280, capture_height=720, downsample=4, capture_fps=60)
# Setup for video saving
output_filename = 'output.avi' # Name of the file to save
fourcc = cv2.VideoWriter_fourcc(*'XVI... | Python | 1 |
#!/usr/bin/python3
def square_matrix_map(matrix=[]):
return list(map(lambda row: list(map(lambda col: col**2, row)), matrix))
| Python | 1 |
impl crate::Readable for FSM_RD_H {}
#[doc = "`write(|w| ..)` method takes [fsm_rd_h::W](fsm_rd_h::W) writer structure"]
impl crate::Writable for FSM_RD_H {}
#[doc = "Internal. Only to be used through TI provided API."]
pub mod fsm_rd_h;
#[doc = "Internal. Only to be used through TI provided API.\n\nThis register you c... | Rust | 0 |
utils::output_log_for_all_log_levels(line_content_2);
Logger::update_main_logger(Some(trace_filter.to_owned()), None, Some(false), None).unwrap();
utils::apply_new_config();
utils::output_log_for_all_log_levels(line_content_3);
Logger::update_main_logger(None, None, Some(true), No... | Rust | 0 |
from dotenv import load_dotenv
from langchain_chroma import Chroma
from langchain_core.messages import HumanMessage, SystemMessage, AIMessage
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
# Load environment variables
load_dotenv()
# Connect to your document database
persistent_directory = "db/chroma_db"
e... | Python | 1 |
level: LogLevel) -> str:
print_date = self._logger_config["format"]["date"]
print_time = self._logger_config["format"]["time"]
print_level = self._logger_config["format"]["level"]
print_src = self._logger_config["format"]["source"]
format_msg = ""
if print_date:
... | Python | 1 |
ge.reply_text("Введите запрос.")
return
results = search(query)
if not results:
escaped_query = escape_markdown_v2(query)
await update.message.reply_text(
text=f"❌ Ничего не найдено по запросу: *{escaped_query}*",
parse_mode='MarkdownV2'
)
return
... | Python | 1 |
"""
to convert dlis into json well log format. we will assume the following
The hierarchy of DLIS file is as follows
Physical file
|_Logical file1
|_Frame1
|_Channel1(Curve1)
|_Channel2(Curve2)
|_Frame2
|_Logical file2
A JSON Well Log file consists of on... | Python | 1 |
_t_prev**0.5 * pred_original_sample + pred_sample_direction + variance
# 8. Algorithm 1 Line 5 https://arxiv.org/pdf/2201.09865.pdf
prev_known_part = (alpha_prod_t_prev**0.5) * original_image + ((1 - alpha_prod_t_prev) ** 0.5) * noise
# 9. Algorithm 1 Line 8 https://arxiv.org/pdf/2201.09865.pd... | Python | 1 |
"link_to_left_port" };
let trace = json!({ "id": &self.get_id(), "packet":packet.stringify()? });
add_to_trace(TraceType::Trace, trace_params, &trace, _f);
}
}
self.link_to_ports.left.send(LinkToPort... | Rust | 0 |
matches = log_optimal_transport(matches, self.bin_score, self.sinkhorn_iters) # [b, N+1, N+1]
else:
z0 = self.matchability(graph_embedding) # [b, 1, N]
matches = log_double_softmax(matches, z0, z0) # [b, N+1, N+1]
# matches.exp() should be probability
# Refinem... | Python | 1 |
;
match age() {
0 => println!("I haven't celebrated my first birthday yet"),
// 绑定
n @ 1..=12 => println!("I'm a child of age {:?}", n),
n @ 13..=19 => println!("I'm a teen of age {:>}", n),
n => println!("I'm an old person of age {:?}", n),
}
match some_number() {
... | Rust | 0 |
atorRun {
product_config,
watch_namespace,
},
}) => {
stackable_operator::utils::print_startup_string(
built_info::PKG_DESCRIPTION,
built_info::PKG_VERSION,
built_info::GIT_VERSION,
... | Rust | 0 |
_dealer_node
})
);
}
#[test]
fn should_return_error_if_registry_version_too_old() {
let dkg_config = dkg_config(NiDkgConfigData {
receivers: set_of(&[NODE_1]),
registry_version: REG_V2,
..minimal_dkg_config_data_without_resharing()
});... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.