text string | label_name string | labels int64 |
|---|---|---|
import pickle
import json
import sys
from os import walk
root = '.'
sys.path.insert(0, root)
from blender_body import ex as body_ex
recover_json_string = ' '.join(sys.argv[sys.argv.index('--') + 1:])
json_config = json.loads(recover_json_string)
r = body_ex.run(config_updates=json_config)
| Python | 1 |
M_VEC3_T: StrhashT = StrhashT {
u64_: 10165899445488706529u64,
};
pub const TM_TYPE_HASH__TM_VEC4_T: StrhashT = StrhashT {
u64_: 16105198182785596086u64,
};
pub const TM_TYPE_HASH__TM_MAT44_T: StrhashT = StrhashT {
u64_: 6274398046370934111u64,
};
pub const TM_COLLABORATION_SESSION_ARCHITECTURE__P2P: Strhas... | Rust | 0 |
ey::IdToString),
last_id: 0,
lists_by_name: UnorderedMap::new(StorageKey::ListsByName),
lists_by_owner_id: UnorderedMap::new(StorageKey::ListsByOwnerId),
lists_by_inviter_id: UnorderedMap::new(StorageKey::ListsByInviterId),
}
}
#[payable]
pub fn create_list(
&mut self,
list_name: S... | Rust | 0 |
K_LOGIC_OP_NAND: VkLogicOp = 14;
pub const VK_LOGIC_OP_SET: VkLogicOp = 15;
pub const VK_LOGIC_OP_MAX_ENUM: VkLogicOp = 2147483647;
pub type VkLogicOp = ::std::os::raw::c_uint;
pub const VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK: VkBorderColor = 0;
pub const VK_BORDER_COLOR_INT_TRANSPARENT_BLACK: VkBorderColor = 1;
pub c... | Rust | 0 |
block_modes::Cbc;
use ::secstr::SecVec;
type Aes256Cbc = Cbc<Aes256, Iso7816>;
/// The demo used in this blog post:
/// https://markv.nl/blog/symmetric-encryption-in-rust
#[test]
fn demo() {
// Key must be 32 bytes for Aes256. It should probably be the hashed
// version of the ... | Rust | 0 |
mode: Option<BlendMode>,
filter_mode: FilterMode,
bounds: Point2,
layout: Layout<glyph_brush::BuiltInLineBreaker>,
font_id: FontId,
font_scale: PxScale,
cached_metrics: RefCell<CachedMetrics>,
}
impl Default for Text {
fn default() -> Self {
Text {
fragments: Vec::new(),... | Rust | 0 |
csv_out = peers[['stock_code','industry','y_pred','rank']].to_csv(index=False)
st.download_button('⬇️ 下载行业同业对比CSV', data=csv_out, file_name=f'peers_{code}_{target_date.date()}.csv', mime='text/csv')
except Exception as _e:
st.error(f... | Python | 1 |
#[test]
fn request_block_sync_for_needed_blocks() {
let (chain_state, import_notifications) = TestChainState::new();
let block_status = chain_state.block_status();
let (global_tx, global_rx) = tracing_unbounded("test");
let block_sync_requester = TestBlockSyncRequester::default();
let until_imported = Unt... | Rust | 0 |
import os
import torch as t
from PIL import Image
from torch.utils.data import Dataset
from torchvision import transforms as T
import pdb
class Shanghai_2020(Dataset):
def __init__(self, root, seq_len=20, seq_interval=None, transforms=None, train=True, test=False, nonzero_points_threshold=None):
self.root ... | Python | 1 |
import json
import xmltodict
from ncclient import manager
device = {
"host": "10.10.20.40",
"port": "830",
"username": "admin",
"password": "RG!_Yw200",
"type": "nexus"
}
cfg = """
<config>
<network-instances xmlns="http://openconfig.net/yang/network-instance">
<network-instance>
<nam... | Python | 1 |
()
//! );
//!
//! let mvp_data = CameraMvp {
//! model: camera.model_array(),
//! view: camera.view_array(),
//! proj: camera.proj_array(),
//! };
//!
//! let mvp = BufferAttribute::from_data(
//! mvp_data,
//! context.device.clone()
//! );
//!
//! let tri... | Rust | 0 |
import numpy as np
from scipy.linalg import hilbert
from scipy.linalg import inv
def power_method(A, max_iter=1000, tol=1e-12):
n = A.shape[0]
x = np.ones(n)
x = x / np.linalg.norm(x)
lambda_old = 0
for k in range(1, max_iter + 1):
x_new = A @ x
x_new_norm = np.linalg.norm(x_new)
... | Python | 1 |
from django.shortcuts import render, redirect
from .forms import HighEmployeeForm
from .models import HighEmployee,MiddleEmployee
from .forms import MiddleEmployeeForm
from .forms import UploadedFileForm
def add_high_employee(request):
if request.method == 'POST':
form = HighEmployeeForm(request.POST)
... | Python | 1 |
Fun {
let ty_args = cons.identity_ty_args();
let field = &cons.fields()[field_index];
let accessor_fun_ty = field.accessor_fun_type(cons);
let record_instance_ty = Ty::Record(Box::new(record::Instance::new(
cons.clone(),
ty_args.clone(),
)));
let expr_params = &[ExprParam {
... | Rust | 0 |
// get the head, it will become the finalized root of epoch 4
let checkpoint_root = setup_harness.harness.chain.head_info().unwrap().block_root;
setup_harness
// epoch 3 will be entirely skip slots
.skip_slots(E::slots_per_epoch() as usize)
.apply_blocks_while(|_, state| state.final... | Rust | 0 |
_capabilities: RsnCapabilities) -> Self {
Self::wpa2_rsne().with_caps(rsn_capabilities)
}
pub fn wpa2_wpa3_rsne() -> Self {
Rsne {
group_data_cipher_suite: Some(CIPHER_CCMP_128),
pairwise_cipher_suites: vec![CIPHER_CCMP_128],
akm_suites: vec![AKM_SAE, AKM_PSK... | Rust | 0 |
es_2], Original ATen: [_c10d_functional.wait_tensor]
torch.ops._c10d_functional.wait_tensor.default(buf38)
# Topologically Sorted Source Nodes: [], Original ATen: []
torch.ops.fsdp.split_with_sizes_copy.default(reinterpret_tensor(buf38, (2, 128), (128, 1), 0), [128], 1, out=[reinterpret_tensor(b... | Python | 1 |
manager_impl as
*const zwp_primary_selection_device_manager_v1_interface
as *const libc::c_void,
manager as *mut libc::c_void, None);
}
unsafe extern "C" fn handle_display_destroy(mut listener: *mut wl_liste... | Rust | 0 |
odes
/// for each ID.
fn lower_package<'gcx>(
cx: &impl Context<'gcx>,
node_id: NodeId,
ast: &'gcx ast::Package<'gcx>,
) -> Result<HirNode<'gcx>> {
let mut next_rib = node_id;
let mut names = Vec::new();
let mut decls = Vec::new();
let mut params = Vec::new();
for item in &ast.items {
... | Rust | 0 |
}
// Make edits
for edit in edits.into_iter().rev() {
match edit {
Insert(idx, insert_text) => text.insert_str(idx, &insert_text),
Delete(range) => text.replace_range(range, ""),
}
}
text
}
fn main() -> Result<(), Box<dyn Error>> {
let mut config = config::C... | Rust | 0 |
import json
def load_json(filepath):
"""Carga y devuelve el contenido del archivo JSON."""
try:
with open(filepath, 'r', encoding='utf-8') as file:
return json.load(file)
except FileNotFoundError:
print(f"Error: El archivo {filepath} no existe.")
return {}
except jso... | Python | 1 |
ts")]
pub mod heartbeats;
pub mod invocation;
pub mod leadership;
#[cfg(feature = "leases")]
pub mod leases;
mod log_entry;
pub mod node;
#[cfg(feature = "prototyping")]
pub mod prototyping;
pub mod retry;
pub mod state;
#[cfg(feature = "tracer")]
pub mod tracer;
mod util;
pub mod voting;
use std::con... | Rust | 0 |
"缴款截止日期",
"上市日",
]
]
big_df["配股比例"] = "10配" + big_df["配股比例"].astype(str)
big_df["配股数量"] = pd.to_numeric(big_df["配股数量"], errors="coerce")
big_df["配股价"] = pd.to_numeric(big_df["配股价"], errors="coerce")
big_df["最新价"] = pd.to_numeric(big_df["最新价"], errors="coerce")
big_d... | Python | 1 |
import builtins
from infra.configsettings import ConfigManager
from aws_cdk.aws_stepfunctions import StateMachineType
from infra.storage.topology import RivSharedDataStores
from infra.userportal.functions.topology import RivUserPortalFunctionSet
from infra.userportal.states.topology import RivUserPortalStateMachines
f... | Python | 1 |
from .User import User
from action.classroom_management.ManageClassroom import ManageClassroom
from action.course_management.ManageCourse import ManageCourse
from action.ListUserInfo import ListUserInfo
from action.event.SearchEvent import SearchEvent
class Admin(User):
def __init__(self, userid, username, pwd, e... | Python | 1 |
;
}
extern "C" {
#[doc = " \\fn void ARQ_PostRequest(ARQRequest *req,u32 owner,u32 dir,u32 prio,u32 aram_addr,u32 mram_addr,u32 len)"]
#[doc = " \\brief Enqueue a ARAM DMA transfer request."]
#[doc = ""]
#[doc = " \\param[in] req structure to hold ARAM DMA request informations."]
#[doc = " \\param[i... | Rust | 0 |
has_parking(value: Option<&String>) -> bool {
value == Some(&"parallel".to_string())
|| value == Some(&"diagonal".to_string())
|| value == Some(&"perpendicular".to_string())
}
let parking_lane_fwd = has_parking(osm_tags.get(osm::PARKING_RIGHT))
||... | Rust | 0 |
339], [18, 17, 340], [18, 16, 341], [18, 12, 342], [18, 7, 343], [18, 16, 344], [7, 18, 345], [18, 12, 346], [18, 5, 347], [5, 4, 348], [18, 16, 349], [18, 7, 350], [18, 12, 351], [18, 6, 352], [18, 13, 353], [7, 18, 354], [16, 18, 355], [7, 18, 356], [16, 18, 357], [18, 7, 358], [18, 12, 359], [23, 7, 360], [23, 12, ... | Python | 1 |
return match.strip()
# 方法4: 如果脚本很短且主要是剧情内容,进行简单清理后返回
if len(script_content) < 50000 and '[Dialog]' in script_content:
# 移除明显的JavaScript代码行
lines = script_content.split('\n')
story_lines = []
for line in lines:
line = line.strip()
# ... | Python | 1 |
from synth.logic.builder import LogicBuilder, Unsigned
def build_counter(build: LogicBuilder, bits: int) -> Unsigned:
curr = build.new_unsigned(bits, "curr")
curr %= curr.add_trunc(1).delay()
return curr
| Python | 1 |
_at(idx).unwrap();
let mut i = chain_node.msgs.len() as i64 - 1;
while i >= 0 && (chain_node.gas_limit > gas_limit || (chain_node.gas_perf < 0.0)) {
let gas_reward = get_gas_reward(&chain_node.msgs[i as usize], base_fee);
chain_node.gas_reward -= gas_reward;
chain_no... | Rust | 0 |
the scene as a child of another entity,
//! or by accessing the entities of the scene.
use bevy::prelude::*;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_startup_system(setup)
.add_system(move_scene_entities)
.run();
}
#[derive(Component)]
struct MovedScene;
fn setup... | Rust | 0 |
eck_valid_input(111_111, 100_000, 999_999));
assert!(check_valid_input(123_345, 100_000, 999_999));
assert!(!check_valid_input(223_450, 100_000, 999_999));
assert!(!check_valid_input(123_789, 100_000, 999_999));
}
#[test]
fn test_valid_non_repeated() {
assert!(!check_valid_i... | Rust | 0 |
gles2() -> bool;
}
extern "C" {
pub fn sapp_html5_ask_leave_site(ask: bool);
}
extern "C" {
pub fn sapp_metal_get_device() -> *const ::std::os::raw::c_void;
}
extern "C" {
pub fn sapp_metal_get_renderpass_descriptor() -> *const ::std::os::raw::c_void;
}
extern "C" {
pub fn sapp_metal_get_drawable() -> *... | Rust | 0 |
\n}\
\n"
);
}
use crate::common::*;
#[distributed_slice(TESTS)]
fn help_works() {
let assert = command().args(&["help"]).assert();
assert
.success()
.stdout(regex_match(r"(?i)usage"))
.stderr(predicate::str::is_empty());
}
#[distributed_slice(TESTS)]
fn h_flag_works... | Rust | 0 |
};
Some(Tile {
texture_index: tile_instance.t as u16,
flip_x,
flip_y,
..Default::default()
})
}
None => None,
}
}
}
/// Creates a tile maker that returns the result of ... | Rust | 0 |
u64, Tag)>,
depth: u64,
end_document: bool,
tag: Option<Tag>,
element: Option<XmlItem>,
last_attribute_tag: Option<Tag>,
}
impl<'a> XmlEncodingReader<'a> {
fn is_empty2(&mut self) -> TTLVResult<bool> {
// eprintln!("is_empty2: ");
if self.end_document {
return Ok(tru... | Rust | 0 |
`\"Win32_Media_Multimedia\"`*"]
pub const MM_AHEAD_MULTISOUND: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Multimedia\"`*"]
pub const MM_AHEAD_PROAUDIO: u32 = 3u32;
#[doc = "*Required features: `\"Win32_Media_Multimedia\"`*"]
pub const MM_AHEAD_SOUNDBLASTER: u32 = 2u32;
#[doc = "*Required features: `\"Win3... | Rust | 0 |
# 지훈이는 행이 0이거나 r - 1 혹은 열이 0 또는 c - 1일 경우 탈출 할 수 있음
# 불 번짐 -> 지훈이 이동 가능 경로 파악 (하나의 bfs 에서 진행)
# - 불은 벽과 불이 난 공간이 아니면 번짐
# 결과는 time + 1 (탈출에 시간 소요)
from collections import deque
R, C = map(int, input().split())
graph = []
fq = deque()
jx = jy = 0
for i in range(R):
data = list(input())
graph.append(data)
fo... | Python | 1 |
KissErrKind::EFormat, "result format error {:?}", v);
}
}
}
///--------------在这个文件里聚合一下查询接口,用简单的公共方法提供----------------------------------------
///方法命令刻意和https://fisco-bcos-documentation.readthedocs.io/zh_CN/latest/docs/api.html
///保持大小写和拼写一致,以便查找,局部不遵循rust命令规范
impl BcosSDK {
pub fn getBlockNumber(&mut ... | Rust | 0 |
return_value = 0
subtask_ids = rtm.get_requested_task_subtask_ids(task_id)
result = yield self.rpc.restart_subtasks(task_id, subtask_ids)
assert "Not enough funds" in result
@inlineCallbacks
def test_abort_subtask(self):
rtm = self.requested_task_manager
task_id = yield... | Python | 1 |
();
if let Ok(Ok(port)) = env::var("PORT").map(|p| p.parse::<u16>()) {
opts.listen_addr.set_port(port);
}
let options = ExporterOptions {
elasticsearch_url: opts.elasticsearch_url.clone(),
elasticsearch_global_timeout: *opts.elasticsearch_global_timeout,
elasticsearch_query... | Rust | 0 |
def countChar(s):
HashM={}
for char in s:
if char in HashM:
HashM[char]+=1
else:
HashM[char] = 1
print(HashM)
sortedKeys = sorted(HashM)
print(sortedKeys)
nhigh=0
for r,t in sortedKeys.items():
if t > nhigh:
nhigh=t
for i,j i... | Python | 1 |
# Maintains the maximum of all 2nd moment running avg. till now
torch.max(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq)
# Use the max. for normalizing running avg. of gradient
denom = max_exp_avg_sq.sqrt().add_(group['eps'])
else:... | Python | 1 |
yModeBar': False})
st.markdown("### 板块异动总次数前20")
# 选择板块异动总次数前20的板块
top20_change_times = df.nlargest(20, '板块异动总次数').copy()
# 确保 '板块异动总次数' 为整数,并进行必要的格式化
top20_change_times['板块异动总次数'] = top20_change_times['板块异动总次数'].astype(int)
# 创建水平条形图
fig_change_times = px.bar(
top20_change_ti... | Python | 1 |
"graffiti of the {}.",
"a drawing of the {}.",
"a doodle of the {}.",
],
"flowers102": [
"flowers : {}.",
],
"stl10": [
"a photo of a {}.",
"a photo of the {}.",
],
"eurosat": [
"a centered sate... | Python | 1 |
32>::from_angle_x(Deg(180.0)),
// Matrix4::<f32>::from_angle_x(Deg(270.0)),
// Matrix4::<f32>::from_angle_x(Deg(0.0)) * Matrix4::from_angle_y(Deg(180.0)),
// Matrix4::<f32>::from_angle_x(Deg(90.0)) * Matrix4::from_angle_y(Deg(180.0)),
// Matrix4::<f32>::from_angle_x(Deg(180.0)) * Matrix4::from_angle_... | Rust | 0 |
ion.
fn into_iter(self) -> Self::IntoIter {
Self::IntoIter { queue: self }
}
}
pub struct HashKeyedPriorityQueueIntoIter<TKey, TPriority>
where
TKey: Hash + Clone + Eq,
TPriority: Ord,
{
queue: HashKeyedPriorityQueue<TKey, TPriority>,
}
impl<TKey: Hash + Clone + Eq, TPriority: Ord> Iterato... | Rust | 0 |
"batch_size": 32,
"path_to_plot_model": path_to_model, # Replace with the path to your model if you needed it. path like path_to_folder + model.pt
"num_models": None,
"from_last": False,
"prefix": "model-",
"path_to_trajectories": path_to_trajectories,
"loss_name":... | Python | 1 |
ache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/// Creates a Cocoa delegate to use e.g. with `NSWindow.setDelegate_`.
/// Adds instance variables and m... | Rust | 0 |
RGS]", args[0]);
println!("Available COMMANDs are:");
println!(" status");
println!(" tx TXID");
println!(" puttx RAWTX");
println!(" blocksummary OFFSET LIMIT");
println!(" block+txids HASH_OR_HEIGHT");
println!(" block+txs HASH_OR_HEIGHT");
... | Rust | 0 |
ync_trait]
pub trait Handler: Cloneable + Send + Sync + 'static {
/// Called by Rocket when an error with `status` for a given `Request`
/// should be handled by this handler.
///
/// Error handlers _should not_ fail and thus _should_ always return `Ok`.
/// Nevertheless, failure is allowed, both fo... | Rust | 0 |
ict(type='PointShuffle'),
dict(num_points=200000, type='PointSample'),
dict(
point_cloud_range=[
-54.0,
-54.0,
-5.0,
54.0,
54.0,
3.0,
],
... | Python | 1 |
plist").unwrap();
bencher.iter(|| {
let parser = xml_stringify::XmlStringParser::new(&text);
parser.parse()
})
}
benchmark_group!(roxmltree, tiny_roxmltree, ehf_roxmltree, large_roxmltree);
benchmark_group!(xmltree, tiny_xmltree, ehf_xmltree, large_xmltree);
benchmark_group!(sdx, tiny_sdx_docu... | Rust | 0 |
ddParams(l2cache_params)
l3cache = sst.Component("l3cache", "memHierarchy.Cache")
l3cache.addParams(l3cache_params)
memLink.connect(l1cache, l2cache)
memLink.connect(l2cache, l3cache)
memLink.connect(l3cache, memctrl)
elif option == 4: # L1 <-> L2/distrib <-> L3/distr <-> Mem
l1_bus = Bus("l1... | Python | 1 |
import gradio as gr
import sympy as sp
# Dictionary of electrical engineering formulas
formulas = {
"Ohm's Law": "V = I * R",
"Power": "P = V * I",
"Energy Stored in Capacitor": "E = 1/2 * C * V**2",
"Energy Stored in Inductor": "E = 1/2 * L * I**2",
"Resonant Frequency (LC Circuit)": "f = 1 / (2 *... | Python | 1 |
env(attr_map: &Vec<Attribute>) -> Result<(), Vec<Error>> {
// Init dotenv to get vars for .env
let mut errors = Vec::new();
match dotenv::dotenv() {
Ok(_) => (), // Skip .env
Err(_) => errors.push(Error{message: "unable to find '.env' in current dir".to_string()}),
};
match try_init... | Rust | 0 |
def spam():
print(eggs)
eggs = 42
spam()
print(eggs)
| Python | 1 |
from __future__ import annotations
from typing import Optional
import polars as pl
from functime.preprocessing import lag
def _join_X_y(y: pl.LazyFrame, X: pl.LazyFrame) -> pl.LazyFrame:
on = set(y.columns[:2]) & set(X.columns[:2])
if len(on) < 1:
raise ValueError(
"`X` must have at lea... | Python | 1 |
visited1 = set()
visited2 = set()
print(visited1)
print(visited2)
data = (1,2)
visited1.add(data)
print('visited1:', visited1)
visited2 = visited2|{data}
print('visited2:', visited2)
visited1.add(data)
print('visited1:', visited1)
visited2 = visited2|{data}
print('visited2:', visited2)
data = (3,4)
visited1.add(dat... | Python | 1 |
t, uniform_type, element_count, values);
}
/// Common parts of the uniform value validation routine.
fn validate_uniform<T, U: Debug>(count: usize, uniform_type: U, element_count: usize, values: &[T]) {
let expected_len = count * element_count;
if expected_len > values.len() {
panic!("Too small uniform... | Rust | 0 |
sns.heatmap(Acc_mat_df, vmin= -0.01, vmax=1.01, mask=~off_diag_mask,
fmt=".3f", cbar_kws={'pad': 0.01},
annot=True, cmap='Blues', linewidths=1)
sns.heatmap(Acc_mat_df, annot=True, mask=off_diag_mask,
cmap='OrRd', fmt=".3f",
cbar_k... | Python | 1 |
import logging
from aiogram import types
from aiogram.types import CallbackQuery
logger = logging.getLogger(__name__)
def get_real_user_id(event: types.Message | CallbackQuery | types.Update) -> int:
"""Get real user ID from any event type"""
# logger.info(f"Getting real user ID from event type: {type(event)... | Python | 1 |
)));
assert_eq!(126, si.count());
}
}
#[test]
fn test_row_quad_iter() {
for i in 0..9 {
// 9 choose 4 = 126
let si = MultiRelatedIndexIterator::new(4)
.set_gen_position(Box::new(RowGenPosition::new(i)));
assert_eq!(126, si.coun... | Rust | 0 |
"""Test utilities and fixtures for hippo_mem."""
from .fake_hf import FAKE_MODEL_ID, is_fake_model_id, resolve_fake_model_id
__all__ = [
"FAKE_MODEL_ID",
"is_fake_model_id",
"resolve_fake_model_id",
]
| Python | 1 |
import struct
import os, sys, glob
def read_utf16_str (f, offset=-1, len=2):
if offset >= 0:
f.seek(offset)
str = f.read(len)
return str.decode('UTF-16LE')
def read_uint16 (f):
return struct.unpack ('<H', f.read(2))[0]
def get_word_from_sogou_cell_dict (fname):
f = open (fname, 'rb')
... | Python | 1 |
Count: 1,
Quality: 0,
},
BufferUsage: dxgitype::DXGI_USAGE_RENDER_TARGET_OUTPUT,
BufferCount: 1,
OutputWindow: inner.get_hwnd() as _,
Windowed: true as _,
SwapEffect: dxgi::DXGI_SWAP_EFFECT_DISCARD,
Flags: 0,
};
info!("Creating swap chai... | Rust | 0 |
randomness.
//! * `Limit`: The upper limit for the length of dynamic data structures generated by the
//! implementor of `DieOnce` or `Die`. The implementor is allowed to freely interpret or even
//! ignore this value.
//!
//! ```
//! use dicetest::prelude::*;
//! use dicetest::{Limit, Prng};
//!
//! // Provides the r... | Rust | 0 |
N-YunjieNeural",
voice_name="云杰",
gender="male",
style="elegant",
description="儒雅男声,适合文雅绅士的角色",
suitable_for=["male_supporting", "elegant_male"]
),
# 儿童语音
"child_female": VoiceProfile(
... | Python | 1 |
.), bb(3.)));
bb(aeabi_f2d(bb(2.)));
bb(aeabi_f2iz(bb(2.)));
bb(aeabi_f2lz(bb(2.)));
bb(aeabi_f2uiz(bb(2.)));
bb(aeabi_f2ulz(bb(2.)));
bb(aeabi_fadd(bb(2.), bb(3.)));
bb(aeabi_fcmpeq(bb(2.), bb(3.)));
bb(aeabi_fcmpgt(bb(2.), bb(3.)));
bb(aeabi_fcmplt(bb(2.), bb(3.)));
bb(aeabi_fd... | Rust | 0 |
import sys
input = sys.stdin.readline
def find_b(r, c):
visited[r][c] = True
color = board[r][c]
stack = [(r, c)]
while stack:
r, c = stack.pop()
for dr, dc in [(-1, 0), (0, 1), (1, 0), (0, -1)]:
nr, nc = r + dr, c + dc
if not (0 <= nr < N and 0 <= nc < N and no... | Python | 1 |
except
// according to those terms.
extern crate rouille;
use rouille::Response;
fn main() {
// This example shows how to serve static files with rouille.
// Note that like all examples we only listen on `localhost`, so you can't access this server
// from another machine than your own.
... | Rust | 0 |
import torch
import numpy as np
from torchqc.states import QuantumState
from torchqc.operators import Operator
import numpy as np
def runge_kutta4(problem, t0, y0: Operator|QuantumState, time: np.ndarray, h: float):
y = y0
y_values = [y0]
time_tensor = torch.from_numpy(time).reshape(len(time), 1)
for ... | Python | 1 |
# Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmseg.models.utils import (nchw2nlc2nchw, nchw_to_nlc, nlc2nchw2nlc,
nlc_to_nchw)
def test_nchw2nlc2nchw():
# Test nchw2nlc2nchw function
shape_nchw = (4, 2, 5, 5)
shape_nlc = (4, 25, 2)
def test_func(x... | Python | 1 |
ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::collections::HashSet;
use map::Map;
use map::Node;
use map::Direction;
use map::Point;
#[derive(Eq, Part... | Rust | 0 |
1]], xState[win[2]]) == 3):
print("X's win")
return 1
if(sum(zState[win[0]], zState[win[1]], zState[win[2]]) == 3):
print("O's win")
return 0
return -1
if __name__ == "__main__":
xState = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
zState = [0, 0, 0, 0, 0, 0... | Python | 1 |
d(),
"label": script_label,
}
)
queue.append(cur_node_child)
fetched_nodes_info.append(cur_node_info_class)
else:
node_info_dict[cur_node.get_node_id()] = (... | Python | 1 |
type": "bot_message"
}
}"##
.to_string())
});
let response = scheduled_message(&mock, ¶m, &"test_token".to_string())
.await
.unwrap();
let expect = ScheduledMessageResponse {
ok: true,
channel: Some("C1H9RESGL".to_string()),
... | Rust | 0 |
# Copyright (C) 2022 David Cattermole.
#
# This file is part of mmSolver.
#
# mmSolver is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later ve... | Python | 1 |
16x16(_in: &[SoaFloat4; 4], _out: &mut [Float4x4; 4]) {
unsafe {
let tmp0 = _mm_unpacklo_ps(_in[0].x.data, _in[0].z.data);
let tmp1 = _mm_unpacklo_ps(_in[0].y.data, _in[0].w.data);
_out[0].cols[0].data = _mm_unpacklo_ps(tmp0, tmp1);
_out[1].cols[0].data = _mm_unpa... | Rust | 0 |
# -*- coding: utf-8 -*-
# Copyright (c) 2020 Kumagai group.
import numpy as np
import pytest
from pydefect.analyzer.defect_charge_info import DefectChargeInfo, AveChargeDensityDist
from pymatgen.electronic_structure.core import Spin
from pymatgen.core import Structure, Lattice
from pymatgen.io.vasp import Chgcar
from ... | Python | 1 |
program_id,
)
.map_err(|_| SafeErrorCode::InvalidVault)?;
if safe_vault.owner != safe_vault_authority {
return Err(SafeErrorCode::InvalidVault)?;
}
}
// Vesting.
{
let vesting = Vesting::unpack(&vesting_acc_info.try_borrow_data()?)?;
... | Rust | 0 |
wH = 5 # 1
wL = 4 # 2
insp = 1 # 3
ousp = 2 # 4
inc = 1
jump = (wH * 3) - (wH + 1)
ch = ord('A') + wH - 1 # print char
for x in range(1, wH + 1):
for y in range(1, wL + 1):
for z in range(1, ousp + 1):
print(" ", end="")
print(chr(ch), end="")
for z in range(1, insp + 1):
... | Python | 1 |
Display::fmt(self, f)
}
}
};
}
impl Display for ast::Expr {
fn fmt(&self, mut f: &mut Formatter) -> Result {
match self {
ast::Expr::Null => write!(f, "null"),
ast::Expr::Bool(val) => write!(f, "{}", val),
ast::Expr::Int(val) => wr... | Rust | 0 |
file(path.clone()) {
Ok(ok) => log(format!("Finished loading file: {}", ok), LOG_STDOUT),
Err(e) => log(format!("Error loading file: {}", e), LOG_STDERR),
}
}
let (tx, rx) = two_lock_queue::unbounded::<QueueAction>();
// Start the gRPC Server in a thread
let grpc_path =... | Rust | 0 |
import os
from invoke import Context, task
WINDOWS = os.name == "nt"
PROJECT_NAME = "exercise_mlops"
PYTHON_VERSION = "3.11"
# Setup commands
@task
def create_environment(ctx: Context) -> None:
"""Create a new conda environment for project."""
ctx.run(
f"conda create --name {PROJECT_NAME} python={PY... | Python | 1 |
import re
def find_first_curly_brace_and_closing_tag(text):
curly_brace_index = re.search(r"{", text).start() if re.search(r"{", text) else -1
if curly_brace_index != -1:
closing_tag_index = re.search(r"</", text[curly_brace_index:]).start()
if closing_tag_index is not None:
closing... | Python | 1 |
import time
import json
import pytest
from common.observability.loki_logger import log_to_loki
class DummyResponse:
def __init__(self, status_code=200, text="OK"):
self.status_code = status_code
self.text = text
@pytest.fixture(autouse=True)
def fake_post(monkeypatch):
"""
Monkeypatch r... | Python | 1 |
::SliceRandom, Rng, SeedableRng};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::{error::Error, fs::File, io::prelude::*, path::Path, vec::Vec};
// pinecone does not support u128, so we use two u64 representing the id
type Id = (u64, u64);
type Value = u32;
type Data = Vec<(Id, Value)>;
... | Rust | 0 |
ist_path):
with open(list_path, "r", encoding="utf-8") as f:
list_content = f.read()
# Windowsパス区切り文字とディレクトリ名を修正
list_content = list_content.replace("Data\\LUNA0712\\wavs\\", "Data/LUNA0712/raw/")
list_content = list_content.replace("Data\\\\LUNA0712\\\\wa... | Python | 1 |
eady a content match
if server.category == "reference":
score += 5
elif server.category == "official":
score += 3
return score
def get_search_info(self) -> dict:
"""Get information about the search capabilities."""
info = {
... | Python | 1 |
"""
Open Crawler v 1.0.0 | search.py
-- Note the official search functions doesnt count the clicks or learn from search patterns etc :]
"""
from mongo_db import connect_db, _DB
from rich import print
import time
import json
import sys
import os
import re
def mongodb():
# Config File
config_file = "confi... | Python | 1 |
workloads_dict = namespace_obj.get('workloads', {})
assert len(workloads_dict) == 1, \
f"Validation failed: Expected 1 workload in '{namespace}', but found {len(workloads_dict)}."
# Check for the specific workload key
workload_obj = workloads_dict.get(workload)
... | Python | 1 |
oto: DeprecatedPlaybookTaskDefinition) -> \
(PlayBookTask, str):
task_type = task_proto.type
task_type_display = task_type_display_map.get(task_type, f"{task_type}: Unknown")
if task_type == DeprecatedPlaybookTaskDefinition.Type.METRIC:
task = task_proto.metric_task
elif task_type == Dep... | Python | 1 |
import typer
from aioscore.contracts.validator import validate_stream
from aioscore.normalization.apply import normalize_stream
from aioscore.scoring.final import score_stream
app = typer.Typer(add_completion=False, help="AI Opportunity Score CLI")
@app.command("validate")
def cmd_validate(
inp: str = typer.Argum... | Python | 1 |
aset_smiles))
for pred, pred_p2 in zip(predictions, predictions_p2):
self.assertTrue(np.array_equal(pred, pred_p2))
e1_p2, e2_p2 = pipeline2.evaluate(self.dataset_smiles, [Metric(accuracy_score)])
self.assertEqual(e1, e1_p2)
self.assertEqual(e2_p2, {})
def test_complete_... | Python | 1 |
+ 14;
pub const TB_SETSTATE: UINT = WM_USER + 17;
pub const TB_GETSTATE: UINT = WM_USER + 18;
pub const TB_ADDBITMAP: UINT = WM_USER + 19;
STRUCT!{struct TBADDBITMAP {
hInst: HINSTANCE,
nID: UINT_PTR,
}}
pub type LPTBADDBITMAP = *mut TBADDBITMAP;
pub const HINST_COMMCTRL: HINSTANCE = -1isize as HINSTANCE;
pub ... | Rust | 0 |
're at height offset
reader.seek(SeekFrom::Current(3))?;
break;
}
} else if page == 0xD8 {
depth += 1;
} else if page == 0xD9 {
depth -= 1;
if depth < 0 {
return Err(ImageError::CorruptedImage);
}... | Rust | 0 |
C=C(C)C(=O)c2c(O)c(C)cc3c2C(=O)C(N)=C(NC(=O)/C=C\C=C/C=C\C(C)C(O)CC1=O)C3=O"
result = mol_to_smiles(shape_from_smiles(smiles,
retain_atom_types=True))
expected = "C1CCCCCCCCCCCNC2CCC3C(CCCCCCCCCCC1)CCCC3C2"
assert result == expected
def test_identical_scaffold_... | Python | 1 |
import theano
import theano.tensor as T
import numpy as np
probabilities = T.vector()
nb_samples = T.iscalar()
rng = T.shared_randomstreams.RandomStreams(1234)
def sample_from_pvect(pvect):
""" Provided utility function: given a symbolic vector of
probabilities (which MUST sum to 1), sample one element
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.