text string | label_name string | labels int64 |
|---|---|---|
nfig_dir)
try:
config = read_python_file(config_pathname)
except Exception as e:
raise Failure("error reading config file:\n%s" % e)
export_dir = os.path.join(config['working_dir'], tag)
if os.path.exists(export_dir):
shutil.rmtree(export_dir)
export_tag(config['working_dir... | Python | 1 |
results['metrics'][f'avg_{metric}'] = sum(scores) / len(scores)
return results
def _calculate_relevance(
self,
question: str,
answer: str,
retrieval_result: RetrievalResult
) -> float:
"""计算回答相关性(简化版本)"""
# 基于检索分数的相关性
if ... | Python | 1 |
import json
import logging
import os
import wandb
from utils.distributed import get_rank, is_main_process
import warnings
def set_system(config_path):
with open(config_path, "r") as f:
config = json.load(f)
if "NinjaPath" in config:
os.environ["PATH"] = config["NinjaPath"] + ":" + os.environ... | Python | 1 |
{"method": "exit"}));
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::Config;
#[test]
fn test_config_deserialization() {
let config: Config = toml::from_str(
r#"
[visual_mode]
move_down = "<key_up>"
"#,
)
.unwrap();
... | Rust | 0 |
d_values]
idxs = [valid_idxs[idx] for idx in idxs]
self.this_views_info = dict(
scene=scene,
idxs=idxs,
)
base_path = os.path.join(self.data_root, scene)
intrinsic_path = osp.join(base_path, 'intrinsic/intrinsic_depth.txt')
with open(int... | Python | 1 |
from models.employee import Employee
class EmployeeService:
def __init__(self):
self.employees = {}
self.next_employee_id = 1
def get_all_employees(self):
return list(self.employees.values())
def create_employee(self, name, email, phone):
employee_id = self.next_employee_i... | Python | 1 |
_base_ = 'regnetx-800mf_8xb32_in1k.py'
_deprecation_ = dict(
expected='regnetx-800mf_8xb32_in1k.py',
reference='https://github.com/open-mmlab/mmclassification/pull/508',
)
| Python | 1 |
# This file is part of sbi, a toolkit for simulation-based inference. sbi is licensed
# under the Apache License Version 2.0, see <https://www.apache.org/licenses/>
# NOTE: This is inspired by the sbibm-package <https://github.com/sbi-benchmark/sbibm>
from .base_task import Task
from .gaussian_linear import GaussianLi... | Python | 1 |
"),
&signature,
&signature,
&format!("Merge: {} into {}", remote.id(), local.id()),
&result_tree,
&[&local_commit, &remote_commit],
)?;
info!("successfully merged from {} to {}", remote.id(), local.id());
Ok(())
}
<filename>examples/abop_1_9.rs<gh_stars>0
mod helper... | Rust | 0 |
settings: &T,
channel: &mut C,
await_response_byte: u8,
busy_repeat_byte: u8,
lookup_func: L
) -> DiagServerResult<Vec<u8>> {
// Clear IO buffers
channel.clear_rx_buffer()?;
channel.clear_tx_buffer()?;
let target = cmd.get_sid_byte();
if !cmd.requires_response() {
// Just se... | Rust | 0 |
fn parse_unary_logand() {
use crate::lexer::Lexer;
let node = Parser::new(&mut Lexer::new("!0 && !1")).parse_expr();
insta::assert_debug_snapshot!(node);
}
#[test]
fn parse_lt_le_gt_ge() {
use crate::lexer::Lexer;
let node = Parser::new(&mut Lexer::new("0 < 1 && 0 <= 1 && 0 > 1 && 0 >= 1")).parse_e... | Rust | 0 |
ting the localized lookups table...')
lockor, loczhs, loczht, loczhh=getloclk(font, 'KOR'), getloclk(font, 'ZHS'), getloclk(font, 'ZHT'), getloclk(font, 'ZHH')
locglrpl(newmap)
print('Getting uvs...')
uvdic=getuvs(font['cmap'])
print('Processing locl Variant ...')
locvar(newmap)
print('Processing uvs glyphs...')
setuvs... | Python | 1 |
count += 1;
}
fn set_prop(&mut self, key: &str, value: &JsonValue) {
self.props.insert(key.to_string(), value.dump());
}
fn set_frame(&mut self, frame: Rect<f32>) {
self.frame = frame;
}
fn measure(&self, constraints: Size<Number>) -> Size<f32> {
Size { width: constrai... | Rust | 0 |
eq!("\"hello\\nworld\"", to_double_quoted_str("hello\nworld"));
assert_eq!("\"hello\\\\ world\"", to_double_quoted_str("hello\\ world"));
assert_eq!("\"hello\\\"world\"", to_double_quoted_str("hello\"world"));
assert_eq!("\"\\\"\\\"\\\"\\n\\\\\"", to_double_quoted_str("\"\"\"\n\\"));
ass... | Rust | 0 |
traint components.
"""
# expect ev to have shape (num_constr, S) or (num_constr,)
ev = self.fun(np.asarray(x))
try:
excess_lb = np.maximum(self.bounds[0] - ev.T, 0)
excess_ub = np.maximum(ev.T - self.bounds[1], 0)
except ValueError as e:
raise... | Python | 1 |
# -*- coding: utf-8 -*-
from 臺灣言語工具.辭典.文字辭典 import 文字辭典
from 臺灣言語工具.基本物件.公用變數 import 無音
from 臺灣言語工具.基本物件.詞 import 詞
from 臺灣言語工具.解析整理.型態錯誤 import 型態錯誤
from 臺灣言語工具.解析整理.解析錯誤 import 解析錯誤
from 臺灣言語工具.解析整理.參數錯誤 import 參數錯誤
class 型音點:
def __init__(self):
self.表 = {}
self.條 = set()
class 型音辭典(文字辭典):
... | Python | 1 |
#[test]
fn short_stop_valid() {
let launch_type = detect_type(gen_mock_args("-s"));
assert_eq!(launch_type, LaunchType::Stop);
}
#[test]
fn short_restart_valid() {
let launch_type = detect_type(gen_mock_args("-r"));
assert_eq!(launch_type, LaunchType::Restart);
}... | Rust | 0 |
import requests
import sys
import random
import re
import base64
import time
from requests.packages.urllib3.exceptions import InsecureRequestWarning
def title():
print('+------------------------------------------')
print('+ \033[34mPOC_Des: http://wiki.peiqi.tech \033[0m')
... | Python | 1 |
_gates(optimized_qc)
# visualize_circuits(qc, optimized_qc)
stim_circuit_string = qiskit_to_stim(optimized_qc)
# print("Stim Circuit:\n", stim_circuit_string)
run_stim_simulation(stim_circuit_string)
original_depth = qc.depth()
optimized_depth = optimized_qc.depth()
... | Python | 1 |
import torch
from torch import nn
from torch.nn import functional as F
import numpy as np
from .utils import fspecial_gauss
class VIFs(nn.Module):
def __init__(self, channels=3):
super(VIFs, self).__init__()
'''spatial domain VIF
https://live.ece.utexas.edu/research/Quality/VIF.htm
... | Python | 1 |
ict): 记录对象
default_values (dict): 默认值字典
record_index (int): 记录索引(用于生成默认ID)
Returns:
tuple: (fixed_record, fixes_applied)
fixed_record (dict): 修复后的记录
fixes_applied (list): 应用的修复列表
"""
fixed_record = record.copy... | Python | 1 |
# MIT License
#
# Copyright (c) 2020 Jiaming Song
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge,... | Python | 1 |
import requests
from bs4 import BeautifulSoup
import os
from urllib.parse import urlparse
ignored_domains = ['instagram.com', 'twitter.com', 'youtube.com', 'facebook.com', 'mailto:']
def delete_files_in_folder(folder_path):
files = os.listdir(folder_path)
for file_name in files:
file_path = os.pa... | Python | 1 |
ling_crop_size=image_pooling_crop_size)
tf.logging.info(current_config)
if current_config[_INPUT] < 0:
operation_input = features
else:
operation_input = branch_logits[current_config[_INPUT]]
if current_config[_OP] == _CONV:
if cu... | Python | 1 |
int=kd_joint,
# Note: torque limits will be enforced via the QP. We'll set them to None here
# because we don't want to clip the values before the QP
tau_min=None,
tau_max=None,
)
@jax.jit
def compute_control_jit(z, z_des):
return compute_control(robot, osc_controlle... | Python | 1 |
mut mode: char = '\0';
let mut typ: char = '\0';
let mut plus_is_set = false;
for ch in mode_string.chars() {
match ch {
'+' => {
if plus_is_set {
return Err(format!("invalid mode: '{}'", mode_string));
}
plus_is_set =... | Rust | 0 |
_b_encoded).unwrap();
let blinding_a = LocationTable::random(&mut rng, table_size).unwrap();
let blinding_a = encoded::lazily_encode_table(&blinding_a);
let blinding_b = LocationTable::random(&mut rng, table_size).unwrap();
let blinding_b = encoded::lazily_encode_table(&blinding_b);
let blindings =... | Rust | 0 |
self.bbox = (0, 0, 400, 600)
def find(self, selector, apply_exclusions=True):
for text, elem in elements.items():
if f'"{text}"' in selector:
return elem
return None
mock_page = MockPage()
guides = Guides(context=mock_page)
# Use Guid... | Python | 1 |
rue,
help='Path to txt file with image paths')
parser.add_argument('--depth_paths', type=str, required=True,
help='Path to txt file with depth map paths')
parser.add_argument('--output_path', type=str, required=True,
help='Output directo... | Python | 1 |
# Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmcls.models.losses.utils import convert_to_one_hot
def ori_convert_to_one_hot(targets: torch.Tensor, classes) -> torch.Tensor:
assert (torch.max(targets).item() <
classes), 'Class Index must be less than number of classe... | Python | 1 |
if min_bound <= j && j <= max_bound && a_char == b_char &&
!b_consumed[j] {
b_consumed[j] = true;
matches += 1.0;
if j < b_match_index {
transpositions += 1.0;
}
b_match_index = j;
... | Rust | 0 |
WASM_BINARY_BLOATY`.
//! The former is a compact WASM binary and the latter is not compacted.
//!
//! ## Environment variables
//!
//! By using environment variables, you can configure which WASM binaries are built and how:
//!
//! - `SKIP_WASM_BUILD` - Skips building any WASM binary. This is useful when only native sh... | Rust | 0 |
IterExpr<'l, L> {SliceIterExpr<'r, R>});
impl_mul_op!(impl<'l, L, R, N> SubsetIterExpr<'l, L> {UniChunkedIterExpr<R, N>});
impl_mul_op!(impl<'l, 'r, L, R> SubsetIterExpr<'l, L> {ChunkedIterExpr<'r, R>});
impl_mul_op!(sparse impl<'l, L, R> SubsetIterExpr<'l, L> {SparseExpr<R>});
impl_mul_op!(impl<'l, 'r, L, R> ... | Rust | 0 |
# This file is part of django-ca (https://github.com/mathiasertl/django-ca).
#
# django-ca 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... | Python | 1 |
#!/usr/bin/env python
# coding=utf-8
from PIL import Image
from numpy import *
import numpy as np
import matplotlib.pyplot as plt
import sys
def LoadPicture(name):
img = Image.open(name)
m,n = img.size
img = img.convert("L")
realMat = array(img)
#print img.mode,imgMat.shape
#plt.gray()
#pl... | Python | 1 |
inspired by the one
//! used and provided in `stdio-utils` repository authored by Consolero:
//!
//! <https://github.com/consolero/stdio-utils-rs/blob/dev/0.1/tools/src/bin/quality-control.rs>
//!
//! Developers should run this script before pushing their pull requests to
//! the main repository to make sure that the ... | Rust | 0 |
.push(Value::Integer(std::mem::size_of::<Rc<Value>>() as i32));
Ok(())
});
class_file.native_methods.insert("addressSize0()I".to_string(), |state, _vm| {
state
.current_frame_mut()
.operand_stack
.push(Va... | Rust | 0 |
)?;
Ok(buf)
}
pub fn hello_add(a: u32, b: u32) -> u32 {
a + b
}
pub fn hello_add_conditional(a: u32, b: u32) -> u32 {
if a <= 0 || b <= 0 {
0
} else {
a + b
}
}
<reponame>Alexhuszagh/bdb
use std::convert::AsRef;
use std::fs::File;
use std::io::{BufRead, BufReader, BufWriter, C... | Rust | 0 |
r hex editor and create a new document. Write the club's name by adding a space after every character. Now, replace the 20 to 00.
Example:
Chelsea
C h e l s e a
43 00 68 00 65 00 6C 00 73 00 65 00 61 00
1. Copy the hex string and do a search in the game's process memory. Keep searching until ... | Rust | 0 |
# SPDX-FileCopyrightText: Copyright (c) 2023 - 2024 NVIDIA CORPORATION & AFFILIATES.
# SPDX-FileCopyrightText: All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtai... | Python | 1 |
# sources:
#
# https://medium.com/@amadatiq/pandasai-making-data-analysis-conversational-and-fun-3acc76584cb3
from pandasai import SmartDataframe
import pandas as pd
from langchain_community.llms import Ollama
llm = Ollama(model="llama3:8b")
df = pd.DataFrame({
"country": [
"United States", "United Kingd... | Python | 1 |
f check_mod_version(mod_version_json: Dict[str, Any]) -> None:
assert mod_version_json['friendly_version'] == '1.0.0.0', 'Version should match'
assert mod_version_json['game_version'] == '1.2.3', 'Game version should match'
assert mod_version_json['download_path'] == '/mod/1/Test%20Mod/download/1.0.0.0', 'D... | Python | 1 |
}")
except requests.exceptions.RequestException as e:
failed_items += 1
print(f"Error adding item {item.id}: {e}")
print(f"Added {successful_items} items successfully, {failed_items} items failed")
return successful_items, failed_items
def delete_collection(api_url... | Python | 1 |
class AK_BinaryAmplitudeGate:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"float_list": ("FLOAT", {"defaultInput": True}), # Assuming ComfyUI has a type for lists of floats
"min_value": ("FLOAT", {
... | Python | 1 |
import random
stages = ['''
+---+
| |
O |
/|\\ |
/ \\ |
|
=========
''', '''
+---+
| |
O |
/|\\ |
/ |
|
=========
''', '''
+---+
| |
O |
/|\\ |
|
|
=========
''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
... | Python | 1 |
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: RX_ADC_POLW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "ADC output of 1'b0 maps to -1, 1'b1 maps to +1 (default)"]
#[inline]
pub fn _0(self) -> &'a mut W {
sel... | Rust | 0 |
R R
R R t NoneR R t _timet _putR R t notifyR ( R t itemt blockt timeoutt endtimet remaining( ( s Queue.pyt putk s*
c C s | j | t S( s Put an item into the queue without blocki... | Python | 1 |
matrix_rooms config"""
rooms = {
"!room1:example.com": Mock(display_name="Room 1", encrypted=False),
"!room2:example.com": Mock(display_name="Room 2", encrypted=True),
}
config = {
"matrix_rooms": {
"room1": {"id": "!room1:example.com", "mesht... | Python | 1 |
like = True
def like():
print("I want to buy them")
return 1
| Python | 1 |
,
33: LocationReport,
# LPPa, class 2
45: UplinkUELPPaTransport,
}
# MME initiated procedures
MMEUESigProcDispatch = {
# E-RAB mgt, includes UE signalling, class 1
5: ERABSetup,
6: ERABModify,
7: ERABRelease,
# Ctxt mgt, includes UE signalling, class 1
9: InitialContextSetup,
23... | Python | 1 |
if let Some(v) = self.error_type {
os.write_enum(1, v.value())?;
}
os.write_unknown_fields(self.get_unknown_fields())?;
::std::result::Result::Ok(())
}
fn get_cached_size(&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields(&self) -> &::protobuf... | Rust | 0 |
ystem::open(&exp_opt.n5_path)?);
let started = Instant::now();
let data_attrs = Arc::new(n.get_dataset_attributes(&exp_opt.dataset).with_context(
|| {
format!(
"Failed to read dataset attributes ({}): {}",
&exp_opt.n5_path, &exp_opt.da... | Rust | 0 |
np_array_sliced = np_array[slc]
np_composite_sliced = self._to_np(composite_sliced)
self.assertEqual(np.all(np_array_sliced == np_composite_sliced) , True)
def test_composite_get_set(self) -> None:
composite, np_array = self.get_arrays()
composite[composite > 6] = -1
... | Python | 1 |
import pygal
from pygal.style import Style
from datetime import datetime
from app_data import get_stock_data, get_stock_symbol, get_start_date, get_end_date, get_chart_type
def generate_chart(chart_type):
stock_data = get_stock_data()
if not stock_data:
print("No stock data retrieved. Check if API dat... | Python | 1 |
"""
示例1:基础路由
演示Flask路由的基本用法
"""
from flask import Flask
# 创建Flask应用
app = Flask(__name__)
# 1. 基本路由
@app.route('/')
def index():
"""主页路由"""
return '<h1>欢迎来到首页</h1><p>这是最基本的路由示例。</p>'
@app.route('/hello')
def hello():
"""简单的问候路由"""
return '<h1>Hello, Flask!</h1>'
# 2. 多个URL指向同一个视图
@app.route('/ab... | Python | 1 |
::PathName};
use crate::ir::Ir;
use super::type_reference::TypeReference;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct LogicalStream<F: Clone + PartialEq, P: Clone + PartialEq> {
/// User-defined fields
fields: InsertionOrderedMap<PathName, F>,
/// Streams adhering to the Tydi specification
... | Rust | 0 |
#[cfg(feature = "dag-pb")]
use crate::pb::{DagPbCodec, Error as PbError};
use crate::raw;
use crate::IpldCodec;
use libipld_core::codec::Codec;
use std::convert::TryFrom;
use thiserror::Error;
/// The `EncodeDecodeIpld` trait allows to encode/decode [`Ipld`] objects.
///
/// It is usually implemented by IPLD Codec co... | Rust | 0 |
ierBase::new(Tribe::Atlantean),
SoldierBase::new(Tribe::Frisian),
SoldierBase::new(Tribe::Amazon),
// SoldierBase::new(Tribe::Custom),
])
}
// parallel-fight them against each other, and enter results into table
pub fn fight_all_parallel(
&self,
results_total_wins:... | Rust | 0 |
erved: [u8; 6],
channels: u16, height: u32, width: u32, depth: u16, color_mode: u16
}
impl PSDHeader
{
fn validate(self) -> Result<Self, PSDLoadingError>
{
let file_signature: u32 = unsafe { std::mem::transmute(['8' as u8, 'B' as u8, 'P' as u8, 'S' as u8]) };
let read_signature: u32 = unsafe { std::mem::transmut... | Rust | 0 |
2),
Constraint::Length(board_height as u16),
Constraint::Length(1),
Constraint::Min(1),
])
.split(f.size());
let text = vec![
Text::styled(CIRCLE, Style::default().fg(BULL_COLOR)),
Text::raw(" Correct color, correct... | Rust | 0 |
asset(
b"shib".to_vec().try_into().unwrap(),
AssetType::Token,
existential_balance.into(),
)
.unwrap();
let second_token_id = AssetRegistry::register_asset(
b"doge".to_vec().try_into().unwrap(),
AssetType::Token,
existential_balance.into(),
)
.unwrap();
let pool_share_id = AssetRegistry::... | Rust | 0 |
derive_reference_doc::impl_derive_reference_doc(ast)
.unwrap_or_else(|err| err.to_compile_error())
.into()
}
<filename>src/program-rust/src/lib.rs
use borsh::{BorshDeserialize, BorshSerialize};
use solana_program::{
account_info::{next_account_info, AccountInfo},
entrypoint,
entrypoint::Prog... | Rust | 0 |
(), 8);
assert_equal(get_chunks_capacities(&event), [8]);
event.extend(0..32);
assert!(event.0.list.lock().free_chunk.is_none());
assert_equal(get_chunks_capacities(&event), [8, 8, 16, 16]);
}
#[test]
fn resize_test(){
let event = EventQueue::<usize, S>::new();
let mut reader = EventReader::ne... | Rust | 0 |
#
# This file is part of Cosmonium.
#
# Copyright (C) 2018-2024 Laurent Deru.
#
# Cosmonium 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 vers... | Python | 1 |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import cv2
import numpy as np
import plotly.express as px
# In[54]:
import sys
# Install required packages
get_ipython().system('{sys.executable} -m pip install opencv-python numpy plotly')
import cv2
import numpy as np
import plotly.express as px
# Loading Image... | Python | 1 |
import numpy as np
import matplotlib.pyplot as plt
import spm1d
import spm1d.stats.nonparam_old
# load data
dataset = spm1d.data.uv1d.regress.SimulatedPataky2015c()
dataset = spm1d.data.uv1d.regress.SpeedGRF()
y,x = dataset.get_data()
# reduce sample size to check differences between new and old nonpara... | Python | 1 |
upied(mut occupied) => {
occupied.get_mut().1 = op;
}
Entry::Vacant(vacant) => {
vacant.insert((len, op));
}
}
}
if ops.len() != map.len() {
let plural_s = plural_s(map.len());
i... | Rust | 0 |
address += len(chunk)
if self.isp_recv_debug():
break
def install_flash_bootloader(self, data):
self.flash_dataframe(data, address=0x80000000)
def boot(self, address=0x80000000):
out = struct.pack('II', address, 0)
crc32_checksum = struct.p... | Python | 1 |
from pydantic import BaseModel
class api_request_param(BaseModel):
service: str = "" # SERVICE_DICT.get(1).get('service_name')
API_KEY: str = ""
format: str = "json" # OR XML
jsonVD: str = "Y"
jsonMVD: str = "Y"
language: str = "kr" # OR en
start_nmb: str = "1"
end_nmb: str = "... | Python | 1 |
pub struct VideoComponentBitDepthFlagBitsKHR(pub u32);
impl VideoComponentBitDepthFlagBitsKHR {
#[inline]
#[doc = "Converts this enum variant to the corresponding bitmask"]
pub const fn bitmask(&self) -> VideoComponentBitDepthFlagsKHR {
VideoComponentBitDepthFlagsKHR::from_bits_truncate(self.0)
... | Rust | 0 |
odes_in_namespace("", PDFX_NAMESPACE):
key = node.localName
while True:
# see documentation about PDFX_NAMESPACE earlier in file
idx = key.find("\u2182")
if idx == -1:
break
key = (
... | Python | 1 |
(@arg race: -r --race
+takes_value
"Sets opponent race"
)
(@arg difficulty: -d --difficulty
+takes_value
"Sets opponent diffuculty"
)
(@arg ai_build: -b --("ai-build")
+takes_value
"Sets opponent build"
)
(@arg sc2_version: --("sc2-version")
+takes_value
"Sets sc2 ver... | Rust | 0 |
# https://leetcode.com/problems/construct-product-matrix/
class Solution:
def constructProductMatrix(self, grid: List[List[int]]) -> List[List[int]]:
m, n = len(grid), len(grid[0])
tl = [[1]*(n+2) for _ in range(m+2)]
tr = [[1]*(n+2) for _ in range(m+2)]
bl = [[1]*(n+2) for _ in ran... | Python | 1 |
}
fn store_accum(&mut self, location: &llir::Location) -> error::Result<()> {
self.load_stack_pointer_if_necessary(location)?;
let param = self.location_to_parameter(location)?;
self.registers.save_later(Register::Accum, param);
Ok(())
}
fn lookup_frame_size(&self, sym... | Rust | 0 |
}
}
use std::collections::HashMap;
type Input = Op;
type Output = u64;
register!(
"input/day14.txt";
run(input: Input) -> Output {
(
run1(&input),
run2(input),
)
}
);
#[derive(Debug, Default)]
struct State1 {
memory: HashMap<u64, u64>,
keep_mask: u64,
... | Rust | 0 |
nse[0])
print('-----------------------------------------------------------')
for k, x in enumerate(new_sample):
x = x.replace('\nFIX = """\nAdd more test cases.\n"""','')
x = x.replace('\n\n\ndef','\ndef')
x ... | Python | 1 |
s in mempool - should by empty all
assert!(current_mempool_state.result().applied.is_empty());
assert!(current_mempool_state.result().branch_delayed.is_empty());
assert!(current_mempool_state.result().branch_refused.is_empty());
assert!(current_mempool_state.result().refused.is_empty());... | Rust | 0 |
from typing import Dict
from apps.model.unidadeArgumental import UnidadeArgumental
class Argumento:
"""
Classe base que representa um argumento do estudo
que será utilizado para o cálculo de indicadores
e para geração de gráficos.
"""
def __init__(self, listaNomes, chave, nome):
self.... | Python | 1 |
import requests
from moviepy import AudioFileClip, ImageClip, concatenate_videoclips, CompositeAudioClip, afx,concatenate_audioclips,TextClip,CompositeVideoClip,VideoFileClip
import uuid
import os
from config import get_resource_path, get_user_data_dir
# JSON数据
data1= {
"audio_durations": [
9888000,
7488000... | Python | 1 |
: 0u32,
relay_vrf_modulo_samples: 0u32,
n_delay_tranches: 2u32,
no_show_slots: 0u32,
needed_approvals: 1u32,
active_validator_indices: vec![],
dispute_period: 6,
random_seed: [0u8; 32],
}
}
#[test]
fn requests_session_info() {
let (ctx, mut ctx_handle) = make_subsystem_context(TaskExecutor::new());
let... | Rust | 0 |
>(
request: WfsRequest,
ctx: C,
) -> Result<Box<dyn warp::Reply>, warp::Rejection> {
// TODO: authentication
// TODO: more useful error output than "invalid query string"
match request {
WfsRequest::GetCapabilities(request) => get_capabilities(&request),
WfsRequest::GetFeature(reques... | Rust | 0 |
ls'][data_ctr].detach().cpu().item())]
label_ids = tokenizer.encode(label_text, return_tensors="pt", truncation=False, padding=False, add_special_tokens=False).to(model.device)
model_input.append(model.get_input_embeddings()(label_ids))
model_input.append(model.get_input_... | Python | 1 |
from rest_framework import serializers
from core.constants import PHONE_MAX_LENGTH
from core.validators import PhoneNumberValidator
from verifications.constants import VERIFICATION_CODE_MAX_LENGTH, VERIFICATION_TOKEN_MAX_LENGTH
from verifications.models import Verification
from verifications.validators import Verifica... | Python | 1 |
ETERS__cutoffFrequency: &'static [u8; 52usize] =
b"http://lv2plug.in/ns/ext/parameters#cutoffFrequency\0";
pub const LV2_PARAMETERS__decay: &'static [u8; 42usize] =
b"http://lv2plug.in/ns/ext/parameters#decay\0";
pub const LV2_PARAMETERS__delay: &'static [u8; 42usize] =
b"http://lv2plug.in/ns/ext/parameters... | Rust | 0 |
(&mut rand::thread_rng()) as f32
}
}
/// A chirp is a signal in which frequency increases with time.
/// Based on:
/// https://en.wikipedia.org/wiki/Chirp#Linear
pub struct ChirpGen {
start_freq: f32,
end_freq: f32,
sweep_time: f32,
}
impl ChirpGen {
/// Create chirp signal
/// * start_freq... | Rust | 0 |
#
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
#
from typing import Literal, Optional, Union
from airbyte_cdk.destinations.vector_db_based.config import VectorDBConfigModel
from airbyte_cdk.utils.oneof_option_config import OneOfOptionConfig
from pydantic import BaseModel, Field
class UsernamePasswordAut... | Python | 1 |
strings(VS, None, None, FS)
.expect("program creation")
.ignore_warnings();
// create a single GPU tessellation that holds both the triangles (like in 01-hello-world)
let triangles = surface
.new_tess()
.set_vertices(&TRI_RED_BLUE_VERTICES[..])
.set_mode(Mode::Triangle)
.build()
.unwrap... | Rust | 0 |
.display_order(14)
.help("If the SSID or password could be mistaken for a hexadecimal value,
this option will add double-quotes around the SSID and password")
)
.get_matches();
let mut password = String::new();
if options.is_present("ask") {
... | Rust | 0 |
from random import randint
import torch
from problog.logic import Constant
from deepproblog.dataset import DataLoader
from deepproblog.dataset import NoiseMutatorDecorator, MutatingDataset
from deepproblog.engines import ExactEngine
from deepproblog.examples.MNIST.data import MNISTOperator, MNIST_train, MNIST_test
fr... | Python | 1 |
ConstraintRentExempt, RentExempt);
try_parse!(ident, input, ConstraintExpr, Expr);
Err(Error::new(ident.span(), "Unknown attribute"))
}
}
#[derive(Debug)]
pub struct ConstraintInit;
impl Constraint for ConstraintInit {
const NAME: &'static str = "init";
fn continue_parse(input: ParseStr... | Rust | 0 |
_USE_PLATFORM_WIN32_KHR")]
unsafe impl<'m, 'l: 'm> StructExtends<VkMemoryAllocateInfo<'m>> for VkExportMemoryWin32HandleInfoNV<'l> {
#[inline]
unsafe fn extend(&self, next: *const c_void) -> *const c_void {
assert!(self.pNext.get().is_null());
self.pNext.set(next);
self as *const VkExportMemoryWin32Hand... | Rust | 0 |
ring)
string = re.sub(r"\'s", " 's", string)
string = re.sub(r"\'ve", " 've", string)
string = re.sub(r"n\'t", " n't", string)
string = re.sub(r"\'re", " 're", string)
string = re.sub(r"\'d", " 'd", string)
string = re.sub(r"\'ll", " 'll", string)
#string = re.sub(r",", " , ", string)
#string = re.sub(r... | Python | 1 |
Create a new error
pub fn new(code: u32, message: &str) -> Self {
Self {
code,
message: String::from(message),
}
}
/// Return the error code
#[inline]
pub fn code(&self) -> u32 {
self.code
}
/// Return the error message
#[inline]
pub... | Rust | 0 |
for line in &mut lines.lines {
for span in &mut line.0 {
span.style = style.patch(span.style);
}
}
lines
}
None => Text::from(vec![Spinner::new(args.frame_number)
.style(style)
.label("Loading...")
.into_s... | Rust | 0 |
statistics
//
// SRTO_EVENT - events? not a configuration option
// SRTO_PEERVERSION - read only, could be helpful as a statistic
// SRTO_RCVDATA - read only, could be helpful as a statistic
// SRTO_RCVKMSTATE - read only, could be helpful as a statistic?
// SRTO_RENDEZVOUS - read only, maybe useful as as a read only ... | Rust | 0 |
loper.mozilla.org/en-US/docs/Web/API/AudioBufferSourceNode/AudioBufferSourceNode)"]
#[doc = ""]
#[doc = "*This API requires the following crate features to be activated: `AudioBufferSourceNode`, `AudioBufferSourceOptions`, `BaseAudioContext`*"]
pub fn new_with_options(
context: &BaseAudioContext,
... | Rust | 0 |
resumably because you
/// want to get its geometry via [ncdirectf_geom()][0], or to use the same
/// file with [ncdirectf_render()][1] multiple times).
///
/// You must destroy the result with [ncdirectf_free()][2];
///
/// [0]: NcVisual#method.ncdirectf_geom
/// [1]: NcVisual#method.ncdirec... | Rust | 0 |
from gensim.models import Word2Vec
import pdb
import pickle as pkl
import numpy as np
import re
import nltk
from gensim.parsing.preprocessing import STOPWORDS
from string import punctuation
from nltk.stem import PorterStemmer
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.stem import WordNetLemmatizer... | Python | 1 |
globals
.peers
.read()
.peers_on_subnet(subnet_id)
.count();
if peers_on_subnet > TARGET_SUBNET_PEERS {
trace!(self.log, "Discovery ignored";
"reason" => "Already connected to desired peers",
"connected_peers_on_subnet"... | Rust | 0 |
import asyncio
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import ContextTypes, ConversationHandler
from bot.utils.keyboards import Keyboards
class ChannelManager:
def __init__(self, bot_instance):
self.bot = bot_instance
self.db = bot_instance.db
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.