text string | label_name string | labels int64 |
|---|---|---|
= db.prepare_cached(
"SELECT unit AS best_parent_unit, witnessed_level \
FROM units WHERE is_free=1 \
ORDER BY witnessed_level DESC, level-witnessed_level ASC, unit ASC LIMIT 1",
)?;
stmt.query_row(&[], |row| spec::StaticUnitProperty {
level: 0, //Not ... | Rust | 0 |
low_freq_factor = self.config.get("rope_scaling", {}).get("low_freq_factor", 1.0)
high_freq_factor = self.config.get("rope_scaling", {}).get("high_freq_factor", 4.0)
origin_context_len = self.config.get("rope_scaling", {}).get("original_max_position_embeddings", 8192)
max_position_embedd... | Python | 1 |
846e1d404b2bf63323a", 1205);
}
#[test]
fn incre_merkle_serde_should_be_ok() {
let inc_mekle_str = r#"{
"_active_nodes":[
"ed48bedde2ab467a53bb084025ca439a6087d342e1371d214f7e2286566f95a7",
"adcf13bc2ac6feeec5e321e4d8a726fa2479f3002f507095502592a3f532dd47"... | Rust | 0 |
# -*- coding: utf-8 -*-
# Homework1
# matrix-1
import numpy as np
# 1.請用亂數種子123,隨機產生㇐維、⾧度為15的矩陣,數字介於5~15 之間、列印輸出
np1 = np.random.RandomState(123).randint(5,16,size=15)
print("隨機正整數:",np1)
# 2.轉成3*5 的矩陣並列印出來
np2 = np1.reshape(3,5)
print("X矩陣內容:")
print(np2)
# 3. 印出矩陣最大值
print("最大:", np.max(np2))
# 4. 印出矩陣最小值
prin... | Python | 1 |
from .ReadHelper import read_int_8, read_int_16le, signed8, signed16
# Do you even embroider .bro?
def read_bro_stitches(f, out):
count = 0
while True:
count += 1
b = bytearray(f.read(2))
if len(b) != 2:
break
if b[0] != 0x80:
out.stitch(signed8(b[0]), ... | Python | 1 |
l:
if unordered:
for df in pool.imap_unordered(read_sas_chunk, args, chunksize=1):
dfs.append(df)
else:
dfs = pool.starmap(read_sas_chunk, args)
# Only accept returned objects if they are a Polars DataFrame.
dfs = [df for df in dfs if isinstance(df, pl.D... | Python | 1 |
100325 ),
( "file_type_typescript_official", 0x100326 ),
( "file_type_typescript", 0x100327 ),
( "file_type_typo3", 0x100328 ),
( "file_type_unibeautify", 0x100329 ),
( "file_type_vagrant", 0x10032A ),
( "file_type_vala", 0x10032B ),
( "file_type_vapi", 0x10032C ),
( "file_type_vash", 0x10032D ),
( "file_type_vba", 0x1... | Rust | 0 |
dient and target param update
new_train_states = {
key: self.train_states[key].apply_gradients(grads=grad[key])
for key, grad in zip(self.train_state_keys, grads)
}
new_target_params = {
key: update_target_network(
new_train_states[key].params,... | Python | 1 |
#!/usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author:quincy qiang
@license: Apache Licence
@file: utils.py
@time: 2024/06/06
@contact: yanqiangmiffy@gamil.com
@software: PyCharm
@description: coding..
"""
import json
import datasets
from transformers import AutoTokenizer, AutoModel, AutoConfig
def load_model(
... | Python | 1 |
from benchmark_helper import time_with_torch_timer
import torch
import torch._dynamo
import torch._inductor.config as inductor_config
inductor_config.triton.mm = "triton"
@torch._dynamo.optimize("inductor", nopython=True)
def inductor_mm(a, b):
return torch.mm(a, b)
def torch_mm_relu(a, b):
return torch.... | Python | 1 |
MAX_CANDIDATES;
let e in MAX_VOTERS .. MAX_VOTERS * MAXIMUM_VOTE as u32;
let fixed_v = MAX_VOTERS;
clean::<T>();
let votes_per_voter = e / fixed_v;
let all_candidates = submit_candidates_with_self_vote::<T>(c, "candidates")?;
let _ = distribute_voters::<T>(all_candidates, fixed_v, votes_per_voter as usiz... | Rust | 0 |
fill in the actual string, and then morphing the lexer back.
// Look in the function next_token on the full lexer for how this is done.
#[token("\"", |_| String::new())]
#[token("'", |_| String::new())]
StringLiteral(String),
#[regex("[0-9][0-9_]*")]
#[regex("0x[0-9a-fA-F_]+")]
IntegerLite... | Rust | 0 |
'''
Este módulo contiene la clase `Participant` que extiende de `sqlalchemy.orm.DeclarativeBase`
y representa un modelo de tabla
'''
from typing import TYPE_CHECKING
from sqlalchemy import ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship
from backend.database.database import Base
if TYPE_CHE... | Python | 1 |
import importlib
import sys
import warnings
import numpy as np
from numpy.testing import assert_almost_equal
import pytest
from dipy.data import get_fnames
from dipy.utils.optpkg import optional_package
tf, have_tf, _ = optional_package("tensorflow", min_version="2.18.0")
torch, have_torch, _ = optional_package("tor... | Python | 1 |
)]
#[must_use]
pub fn round_extract0_i32(self) -> i32 {
unsafe { _mm_cvt_ss2si(self.0) }
}
/// Round the `i64` to `f32` and replace lane 0.
///
/// Subject to the current thread's [rounding
/// mode](https://doc.rust-lang.org/core/arch/x86_64/fn._mm_setcsr.html#rounding-mode)
///
/// Not availabl... | Rust | 0 |
num_divs = int(self.format_combo_box_divs.currentText())
chunk_size = (self.end_hex - self.start_hex) // num_divs
if self.end_hex < self.start_hex:
error_range = (
f'\n\n !!!!! ERROR !!!!!! \n Your Start HEX {start_hex} is MORE than your Stop H... | Python | 1 |
(RistrettoPoint::random(&mut OsRng));
assert!(set
.iter()
.prove_with_offset(&gens, &mut t.clone(), l, &r, Some(&C_new))
.is_ok()); // Ok!
set.push(RistrettoPoint::random(&mut OsRng));
assert_eq!(
set.iter()
.prove_with_offset(&gens... | Rust | 0 |
Array frame.
///
/// # Panics
///
/// panics if `self` is not an array
pub(crate) fn push_bulk(&mut self, bytes: Bytes) {
match self {
Frame::Array(vec) => {
vec.push(Frame::Bulk(bytes));
}
_ => panic!("not an array frame"),
}
}... | Rust | 0 |
let field = field.expect("Failed to find field");
field.value_mut()
}
pub type GetObjectFieldFn =
unsafe extern "C" fn(env: *mut Env, obj: JObject, field_id: JFieldId) -> JObject;
unsafe extern "C" fn get_object_field(env: *mut Env, obj: JObject, field_id: JFieldId) -> JObject {
assert_valid_env(env)... | Rust | 0 |
"Tried to close aggregate but wrong name was found"
);
agg.is_completed = true;
}
_ => panic!("Unexpected agg_closer"),
}
}
fn append_var_header(&mut self, context: &'static [u8], type_name: &[u8], which: u32) {
self.pus... | Rust | 0 |
(value.clone()));
}
let actual_root_hash = tree.get_root_hash(version).unwrap();
assert_eq!(actual_root_hash, expected_root_hash);
}
fn restore_without_interruption<V>(
btree: &BTreeMap<HashValue, V>,
target_version: Version,
target_db: &Arc<MockTreeStore<V>>,
try_resume: bool,
) where
... | Rust | 0 |
meter(
py,
source_params,
zstd_sys::ZSTD_cParameter::ZSTD_c_targetLength,
)?;
let strategy = get_cctx_parameter(
py,
source_params,
zstd_sys::ZSTD_cParameter::ZSTD_c_strategy,
)?;
... | Rust | 0 |
dist = np.einsum('ij,ij->i', P[:,:2], bladedir)
if pass_inside:
P_inside = np.array(P)
idx_fail_i = dist > r_ap
P_inside[idx_fail_i] = float('nan')
# pass_outside always True in this function
P_outside = np.array(P)
idx_fail_o = dist <= r_ap
P_outside[idx_fail_o] ... | Python | 1 |
title_value.encode('gbk', 'ignore'),
title[i].get_attribute('href'),
product_value.encode('gbk', 'ignore'),
member_name,
tel,
address
)
writer.writerow(data)
js = 'var q=document.documentElement.scrollTop=... | Python | 1 |
ndex + 1 == len(self.stack):
self.error("Newest frame")
return
try:
count = int(arg or 1)
except ValueError:
self.error("Invalid frame count (%s)" % arg)
return
if count < 0:
_newframe = len(self.stack) - 1
else:
... | Python | 1 |
- ox, sy - oy, sz - oz).length()
}
fn distance_to(&self, other: &Nanobot) -> u32 {
self.distance_to_point(&other.position)
}
fn point_in_range(&self, point: &Position) -> bool {
self.distance_to_point(point) <= self.radius
}
fn other_in_range(&self, other: &Nanobot) -> bool {... | Rust | 0 |
s'))
elif data_len < len_data_in:
# truncate data_in according to data_len
olen = data_len>>3
lastbits = (8-(data_len%8))%8
if lastbits:
# zero last bits after data_len
if py_vers < 3:
data_in = data_in[:olen] + ... | Python | 1 |
"""
Write a python function to find whether the parity of a given number is odd.
assert find_Parity(12) == False
"""
def find_parity(num):
"""
This function takes an integer as an argument and returns a boolean value indicating whether the parity of the number is odd.
"""
return num % 2 != 0 | Python | 1 |
Error> {
unimplemented!();
}
fn proof_message(
&self,
_secp: &Secp256k1,
_id: &Identifier,
_switch: SwitchCommitmentType,
) -> Result<ProofMessage, Error> {
unimplemented!();
}
/// Create a BP rewind nonce for Non-Interactive-Transaction that will allow to rewind the value and the message
fn nit_re... | Rust | 0 |
from os import path
from platform import system
from sysconfig import get_config_var
from setuptools import Extension, find_packages, setup
from setuptools.command.build import build
from setuptools.command.egg_info import egg_info
from wheel.bdist_wheel import bdist_wheel
sources = [
"bindings/python/tree_sitter... | Python | 1 |
l228hx as vg41iok2d6m
pass
'# kites_gallows_deputies -> wiggles_thicknesses_contempt'
assert a27_xm7_ohd
import tiyrlmv78ze as idw3086pthv, jet3wvyf30u, q2yo5lc31ga, fym8t9t7r_4 as j9dokqbiy6n, b1gtfetge_o as yedz3twygsn
nonlocal q0vy8xc72yq
raise b''
nnzttrxg5ml
@af6hgh5047e
@(yield from Fa... | Python | 1 |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright 2022 Spotify AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | Python | 1 |
node: Node<&str> = Node::new("one");
node.insert_before(Box::new(Node::new("two")));
node.remove_before();
}
#[test]
fn node_next() {
let mut node: Node<&str> = Node::new("one");
node.insert_after(Box::new(Node::new("two")));
assert_eq!("two", *node.next().unwrap());
}
#[test]
fn node_prev() {
... | Rust | 0 |
e_point(&mut line);
let (x2, y2) = parse_point(&mut line);
if x1 == x2 {
let (y1, y2) = min_max(y1, y2);
for y in y1..=y2 {
add_line(&mut p1, (x1, y));
add_line(&mut p2, (x1, y));
}
} else if y1 == y2 {
let (x1, x2)... | Rust | 0 |
this has 4 bytes
let mut i = 0;
let audio_format: [u8; 2] = self.audio_format.to_le_bytes().into_iter().filter(|_| {
if i < 2 { i += 1; true } else { false }
}).collect::<Vec<u8>>()
.as_slice()
.try_into()
.unwrap(); // this has 2
let mut ... | Rust | 0 |
"""
"Alpha function" synapse of Rall. Chapter 12.2
"""
from __future__ import division
from PyDSTool import *
from PyDSTool.Toolbox.phaseplane import *
from common_lib import *
icdict = {'a1': 0, 'a2': 0}
pardict = {'tau_syn': 2, 'vthresh': -10,
'vpre': -80}
DSargs = args()
DSargs.name = 'alpha_syn'
DSar... | Python | 1 |
ength as usize {
for y in 0usize..length as usize {
let point = (x as isize, y as isize);
let tile = grid_map.get(&point).unwrap();
let size = tile.grid.size;
let inner_grid = tile.grid.data
.iter()
.filter(|&point| point.0 != 0 && point.0 != size - 1 && point.1 != 0 && point.1 != size - 1)
... | Rust | 0 |
import _plotly_utils.basevalidators
class Histogram2DcontourValidator(_plotly_utils.basevalidators.CompoundArrayValidator):
def __init__(
self,
plotly_name="histogram2dcontour",
parent_name="layout.template.data",
**kwargs,
):
super(Histogram2DcontourValidator, self).__... | Python | 1 |
# ESTRUCTURA DE DATOS
str = "hola"
str2 = "chao"
str = str2 #asignacion por valor
str2 = "adios"
print(str)
print (str2)
| Python | 1 |
results: vec![1, 1, 5],
total: 9
}])
);
let segments = parse_dice_segments("+ 2 + 2d12kh1 / 2").expect("Failed to unpack results");
let rolls_with_modifiers = group_modifiers_to_dicerolls(&segments);
let results = roll_dice_segments(&rolls_with_modifiers, &mut rng);
asse... | Rust | 0 |
'''
code by Tae Hwan Jung(Jeff Jung) @graykode
'''
import tensorflow as tf
import numpy as np
tf.reset_default_graph()
sentence = (
'Lorem ipsum dolor sit amet consectetur adipisicing elit '
'sed do eiusmod tempor incididunt ut labore et dolore magna '
'aliqua Ut enim ad minim veniam quis nostrud exerci... | Python | 1 |
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that msvs_list_excluded_files=0 doesn't list files that would
normally be in _excluded_files, and that if that flag is not set,... | Python | 1 |
igh Byte"]
pub struct OCR_C_H {
register: ::vcell::VolatileCell<u8>,
}
#[doc = "Output Compare Register C High Byte"]
pub mod ocr_c_h;
// TODO: Remove after implementing functional change
#![allow(dead_code)]
//! Consensus internal traits that are used in the `payload_builder`.
use ic_interfaces::{consensus::Paylo... | Rust | 0 |
_bindgen]
pub #fn_sig #block
};
output.into()
}
_ => panic!("This macro is intended to be used on functions only."),
}
}
use chrono::{offset, DateTime};
use serde_derive::Deserialize;
use std::fmt;
#[derive(Deserialize, Debug, Clone)]
pub struct GithubUser {
... | Rust | 0 |
::declaration::property_keywords_impl;
use crate::stylesheets::rule_parser::StyleParseErrorKind;
use crate::values::CSSFloat;
#[derive(Clone, Debug, PartialEq)]
#[repr(u8)]
pub enum LineStyle {
Hidden,
None,
Inset,
Groove,
Outset,
Ridge,
Dotted,
Dashed,
Solid,
Double,
}
property_keywords_impl! { LineStyle,
... | Rust | 0 |
&Address) -> String {
AddressEncoder::encode_address_as_string(self.network_prefix, &address)
}
/// encode address as Base58 encoded string
pub fn encode_address_as_bytes(network_prefix: NetworkPrefix, address: &Address) -> Vec<u8> {
let prefix_byte = network_prefix as u8 + address.address_... | Rust | 0 |
opulate_deep_object_query_params_dict(
prior_params_key: str,
value: Dict,
params: Dict[str, List[str]],
):
if not _is_set(value):
return
for key, val in value.items():
if not _is_set(val):
continue
params_key = f"{prior_params_key}[{key}]"
if isinstanc... | Python | 1 |
r.uniform(key2, [num_samples])
if uniform:
radius_range = BoxRegion(radius_range.min ** 2, radius_range.max ** 2)
r = jnp.sqrt(radius_range.convert_from_unit_interval(r))
else:
r = radius_range.convert_from_unit_interval(r)
return direction * r[:, None]
multi_shuffle = jax.vmap(lambda x, key, k: jnr... | Python | 1 |
writes: Some(Vec::new()),
position: Some(1),
rate_limit_per_user: None,
recipients: None,
rtc_region: None,
thread_metadata: None,
topic: None,
user_limit: None,
video_quality_mode: None,
}]);
let threads = ... | Rust | 0 |
amount = 100;
json!({
"ts": ts,
"ticker": ticker,
"amount": amount,
})
})
}
fn t(n_in_rows: u64, upper_limit_bytes: u64) {
setup_test_logger_with_level(LevelFilter::Warn);
let source_trade = _gen_source_input(n_in_rows).collect();
let test_source_t... | Rust | 0 |
from datetime import timezone
import requests
from bs4 import BeautifulSoup
import tldextract
import re
from zoneinfo import ZoneInfo
from datetime import datetime
from collections import OrderedDict
import hashlib
from collections import Counter
import spacy
from urllib.parse import urlparse
def to_utc(dt):
if no... | Python | 1 |
ep 7: Log results ===
ConsoleLog("Conset Analysis", f"Can make {limiting_consets} consets with current storage and gold.")
for model_id, possible in possible_per_mat.items():
name = model_id.name if hasattr(model_id, "name") else str(model_id)
need = shortages[model_id]
if model_id in b... | Python | 1 |
ef init_parameters(self):
# pass
#
# @torch.jit.ignore
# def set_grad_checkpointing(self, enable=True):
# self.transformer.grad_checkpointing = enable
#
# def _global_pool(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
# if self.global_average_pool:
# return... | Python | 1 |
out_str += f'\n if target_data.dead:'
out_str += f'\n return'
out_str += f'\n target_data.status.setdefault({cid},0)'
out_str += f'\n target_happy = add_time'
out_str += f'\n target_happy *= 1 + attr_calculation.get_experience_level_weight(tar... | Python | 1 |
ecutor::spawn(future) ),
}})
}
}
#[ cfg( target_arch = "wasm32" ) ]
//
impl<Out: 'static + Send> SpawnHandle<Out> for AsyncGlobal
{
fn spawn_handle_obj( &self, future: FutureObj<'static, Out> ) -> Result<JoinHandle<Out>, SpawnError>
{
Ok( JoinHandle{ inner: crate::join_handle::InnerJh::AsyncGlobal
{
task... | Rust | 0 |
ps}
list_tensor_data = {
f"past_tracked_objects.{feature_name}": past_tracked_objects for feature_name in self.agent_features
}
list_list_tensor_data: Dict[str, List[List[torch.Tensor]]] = {}
scripted_builder = torch.jit.script(self.feature_builder)
scripted_tensors... | Python | 1 |
for square in range(64):
ROOK_ATTACKS_NO_MAGIC[square] = []
x = square % 8
y = square // 8
for blocker_subset in ROOK_BLOCKER_SUBSET[square]:
mask = 0
for dx, dy in directions:
cx, cy = x + dx, y + dy
while 0 <= cx < 8 and 0 <=... | Python | 1 |
skip_serializing_if = "Vec::is_empty",
deserialize_with = "crate::utils::deserialize_null_vector::deserialize"
)]
pub events: Vec<String>,
#[serde(
default,
skip_serializing_if = "crate::utils::zero_i64",
deserialize_with = "crate::utils::deserialize_null_i64::deseria... | Rust | 0 |
operator,
left,
right,
}: Infix,
env: &Rc<RefCell<Environment>>,
) -> Object {
let left = eval_expression(*left, env);
let right = eval_expression(*right, env);
match operator {
InfixOperator::Plus => left + right,
InfixOperator::Minus => left - right,
Infi... | Rust | 0 |
mg, (0, 0))
# Game over conditions
if not game_over:
bird_movement += gravity
bird_rect.centery += bird_movement
rotated_bird = pygame.transform.rotozoom(bird_img, bird_movement * -6, 1)
if bird_rect.top < 5 or bird_rect.bottom >= 550:
game_over = True
scre... | Python | 1 |
g("read-client-keys")
.value_name("FILENAME")
.takes_value(true)
.help("Read client keys and stakes from the YAML file"),
)
}
#[allow(clippy::field_reassign_with_default)]
pub fn extract_args(matches: &ArgMatches) -> Config {
let mut args = Config::default();... | Rust | 0 |
# Copyright (C) 2016 - 2025 ANSYS, Inc. and/or its affiliates.
# SPDX-License-Identifier: MIT
#
#
# 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 limita... | Python | 1 |
# $Id: inc_const.py 4177 2012-06-26 02:28:59Z nanang $
# Useful constants
##########################
# MENU OUTPUT
#
##########################
# EVENTS
#
# Text to expect when there is incoming call
EVENT_INCOMING_CALL = "Press .* answer"
##########################
# CALL STATES
#
# Call state is CALLING
STATE... | Python | 1 |
def multiplication_table(n):
for i in range(1, n + 1):
for j in range(1, n + 1):
print(f'{i} * {j} = {i * j}')
print()
if __name__ == "__main__":
print("Процедурная парадигма для переиспользования кода в программе")
multiplication_table(1)
print()
multiplication_table(3)... | Python | 1 |
rt=162
_CMDSCANTHREADSTART._serialized_end=222
_RESPSCANWIFISTART._serialized_start=224
_RESPSCANWIFISTART._serialized_end=243
_RESPSCANTHREADSTART._serialized_start=245
_RESPSCANTHREADSTART._serialized_end=266
_CMDSCANWIFISTATUS._serialized_start=268
_CMDSCANWIFISTATUS._serialized_end=287
_CMDSCANTHREA... | Python | 1 |
)
)
@callback
def alarm_status_update_callback():
"""Send status update received from alarm to Home Assistant."""
_LOGGER.debug("Sending request to update panel state")
async_dispatcher_send(hass, SIGNAL_PANEL_MESSAGE)
@callback
def zones_update_callback(status):
""... | Python | 1 |
old_outputs: FnvHashSet<H256>,
pub new_inputs: FnvHashSet<OutPoint>,
pub new_outputs: FnvHashMap<H256, (u64, bool, usize)>,
}
impl CellSetDiff {
pub fn push_new(&mut self, block: &Block) {
for tx in block.transactions() {
let input_iter = tx.input_pts_iter();
let tx_hash = t... | Rust | 0 |
rows[1:]) + "</tbody></table>")
class ToolCopyToClipboardBase(ToolBase):
"""Tool to copy the figure to the clipboard."""
description = 'Copy the canvas figure to clipboard'
default_keymap = mpl.rcParams['keymap.copy']
def trigger(self, *args, **kwargs):
message = "Copy tool is not available"... | Python | 1 |
on("📁 Ke Halaman Upload"):
st.session_state.page = "upload"
st.rerun()
else:
st.error("❌ Gagal memuat data dashboard")
# Halaman Log
elif st.session_state.page == "log":
st.header("📝 Log Aktivitas", divider="rainbow")
try:
log_df = read_log... | Python | 1 |
= x #-- transform x to mesh scalar field
res.sfYArray = y #-- transform y to mesh scalar field
res.sfXCellBounds = vlon #-- needed if set cnFillMode = "CellFill"
res.sfYCellBounds = vlat #-- needed if se... | Python | 1 |
>>> def f(a, b, c, d, e): pass
>>> f()
Traceback (most recent call last):
...
TypeError: f() missing 5 required positional arguments: 'a', 'b', 'c', 'd', and 'e'
>>> def f(a, b=4, c=5, d=5): pass
>>> f(c=12, b=9)
Traceback (most recent call last):
...
TypeError: f() missing ... | Python | 1 |
"""
AI-Powered Energy Storyteller using Claude API
Transforms battery data into engaging stories with dynamic creativity
"""
import json
from typing import Dict, List, Optional
from anthropic import Anthropic
import os
class AIEnergyStoryteller:
def __init__(self, api_key: Optional[str] = None):
"""Initia... | Python | 1 |
# Author: wangxy
# Emial: 1393196999@qq.com
import numpy as np
def inverse_rigid_trans(Tr):
''' Inverse a rigid body transform matrix (3x4 as [R|t])
[R'|-R't; 0|1]
'''
inv_Tr = np.zeros_like(Tr) # 3x4
inv_Tr[0:3, 0:3] = np.transpose(Tr[0:3, 0:3])
inv_Tr[0:3, 3] = np.dot(-np.transpose(Tr[0... | Python | 1 |
vent", js_name = "detail", getter = detail)]
pub fn detail(this: &IMouseEvent) -> f64;
#[wasm_bindgen(method, js_class = "IMouseEvent", js_name = "posx", getter = posx)]
pub fn posx(this: &IMouseEvent) -> f64;
#[wasm_bindgen(method, js_class = "IMouseEvent", js_name = "posy", getter = posy)]
pub fn ... | Rust | 0 |
let (tx, rx) = channel();
let window = gtk::Window::new(gtk::WindowType::Toplevel);
let sw = ScrolledWindow::new(None, None);
let stories = gtk::Box::new(gtk::Orientation::Vertical, 20);
let spinner = gtk::Spinner::new();
let header = Header::new(stories.clone(), tx.clone());
... | Rust | 0 |
import os
import time
import pytest
# general tool elements
from rafcon.utils import log
logger = log.get_logger(__name__)
@pytest.mark.unstable
@pytest.mark.parametrize("state_machine_name,expected_warnings", [
("dynamic_library_insertion", 2),
("dynamic_library_insertion_and_deletion", 0),
("dynamic_st... | Python | 1 |
Into<Vector2> for Viewport {
fn into(self) -> Vector2 {
Vector2 {
x: self.width as f32,
y: self.height as f32,
}
}
}
// run-rustfix
#![allow(dead_code)]
fn unwrap_or() {
// int case
match Some(1) {
Some(i) => i,
None => 42,
};
// int cas... | Rust | 0 |
);
assert_eq!(format!("{:?}", MediaTypes::Album), "Album");
assert_eq!(format!("{}", MediaTypes::MediaItem), "media_item");
assert_eq!(format!("{:?}", MediaTypes::MediaItem), "MediaItem");
}
}
<reponame>drmingdrmer/tokio-entry
use std::str::FromStr;
use proc_macro::TokenStream;
use proc_ma... | Rust | 0 |
lf.fixture_data['replaced_03']['existing_mclag_config'])
self.initialize_config_requests(self.fixture_data['replaced_03']['expected_config_requests'])
result = self.execute_module(changed=True)
self.validate_config_requests()
def test_sonic_mclag_overridden_01(self):
set_module_args... | Python | 1 |
64>, RispErr> {
args.iter().map(|x| parse_single_float(x)).collect()
}
fn parse_single_float(exp: &RispExp) -> Result<f64, RispErr> {
match exp {
RispExp::Number(num) => Ok(*num),
_ => Err(RispErr::Reason("expected a number".to_string())),
}
}
static IMAGES_BASE_URL: &str = "/static/images"... | Rust | 0 |
# Code generated by Lark OpenAPI.
from typing import Any, Optional, Union, Dict, List, Set, IO, Callable, Type
from lark_oapi.core.model import BaseRequest
from lark_oapi.core.enum import HttpMethod, AccessTokenType
from .folder import Folder
class CreateUserMailboxFolderRequest(BaseRequest):
def __init__(self) ... | Python | 1 |
installed
if importlib.util.find_spec("transformers") is None:
raise ImportError(
"Whisper models require transformers. Please install with:\n"
"brew reinstall ctrlspeak --with-whisper"
)
# Dynamically import W... | Python | 1 |
,
# [[18, 34, 34], [10, 34, 34], [6, 34, 34]]
'ori_shape': X.shape[1:]}, # [32, 64, 64]
os.path.join(wave_dir, 'time_downsample/', "{:06d}".format(sim_id)))
torch.save({'coef': [torch.cat(coef_downsample_space[i]) for i in range(N_downsample)], # [... | Python | 1 |
"""
Vendor packages for BaiduDriver SDK
"""
__all__ = ["baidu_netdisk_sdk"]
| Python | 1 |
#!/usr/bin/env python3
import argparse
import os
import subprocess
def main():
args = parse_args()
git_checkout(firefox_android_repo(args), args.branch)
local_properties = '\n'.join([
"autoPublish.application-services.dir=../../",
])
print("Local properties:")
print(local_properties)
... | Python | 1 |
import torch.nn as nn
from . import convnext_tiny, convnext_small, convnext_base, convnext_large, convnext_xlarge, ConvNeXt
def forward(self, x):
for i in range(self.num_depths):
x = self.downsample_layers[i](x)
x = self.stages[i](x)
return x.flatten(2).permute(0, 2, 1).contiguous()
def adju... | Python | 1 |
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
import pytest
from cryptography.hazmat.primitives.ciphers.aead import (
AESCCM,
AESGCM,
AESOCB3,
AESSIV,
ChaCha20Poly1... | Python | 1 |
ut = res_builder.body(p)?.send_async();
} else {
res_fut = res_builder.body(())?.send_async();
}
let rt = Runtime::new().unwrap();
rt.block_on(async {
select! {
result = res_fut => {
let mut response = result.map_err(ClientErro... | Rust | 0 |
branch id: {}", e));
}
};
// let branch = if
create_to_address(
&db_data,
branch_id,
prover,
(account, &extsk),
&to,
value,
memo,
)
.map_err(|e| format_err!("Error while creating tran... | Rust | 0 |
= "MONOCHROME1": # 0 = white
pixels = np.max(pixels) - pixels
pixels = self._apply_high_contrast_windowing(pixels)
# Convert grayscale to 3-channel image for compatibility
# pixels = np.stack((pixels,) * 3, axis=-1) # Convert to RGB by duplicating the channels
... | Python | 1 |
"""Run TPC-H benchmarks with Ray runner on local Parquet data and upload results to Google sheets."""
from __future__ import annotations
import asyncio
import os
import sys
import time
from ray.job_submission import JobStatus, JobSubmissionClient
import daft
from tools.ci_bench_utils import get_run_metadata, tail_l... | Python | 1 |
n(), true);
}
#[test]
fn test_check_for_left_diagonal_win(){
let mut gs: GameState = GameState::init();
gs.create_and_add_player('+');
gs.create_and_add_player('O');
gs.place_on_board(5, 1);
assert_eq!(gs.check_for_win(), false);
... | Rust | 0 |
dule"] = config["datamodule"]
if "seed" in config:
hparams["seed"] = config["seed"]
if "callbacks" in config:
hparams["callbacks"] = config["callbacks"]
# save number of model parameters
hparams["model/params_total"] = sum(p.numel() for p in model.parameters())
hparams["model/params... | Python | 1 |
return sum(p.numel() for p in model.parameters() if p.requires_grad)
if __name__ == '__main__':
img = torch.randn(1, 3, 224, 224)
net = coatnet_0()
out = net(img)
print(out.shape, count_parameters(net))
net = coatnet_1()
out = net(img)
print(out.shape, count_parameters(net))
net ... | Python | 1 |
>,
C: Into<Color>,
{
ENGINE.with(|e| {
let mut engine = e.get().expect(NOT_INIT).borrow_mut();
engine.canvas.set_draw_color(color);
engine.canvas.draw_rects(rects.into())
})
}
/// Draw a filled rectangle denoted by `rect` in the specified color.
pub fn fill_rect<R, C>(rect: R, color... | Rust | 0 |
quote_spanned! {span=>
#[allow(warnings)]
async fn #name() {
#make
let value = #make_value_name().await;
fn check<T>(_: T)
where T: ::axum::response::IntoResponse
{}
check(value);
... | Rust | 0 |
offset[1]) * uv_scale_inv[1], uv_bits) as u16;
PackedVertex {
p: [p_0, p_1, p_2, 0],
n: [n_0, n_1, n_2, 0],
t: [t_0, t_1],
}
})
.collect();
let (vertex_count, vertex_remap) = meshopt::generate_vertex_remap(&quantized_vertices,... | Rust | 0 |
<gh_stars>1-10
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
mod admin_script_builder;
mod writeset_builder;
pub use admin_script_builder::{
encode_custom_script, encode_halt_network_transaction, encode_remove_validators_transaction,
};
pub use writeset_builder::{build_change... | Rust | 0 |
x data with a different layout create new `VertexPointers` with
/// a different layout.
pub fn default_vertex_pointers<T>(context: &mut Context) -> VertexPointers<T> {
super::new_vertex_pointers(context)
.with_divisor(1)
.add(3, 4, GlType::Float, false)
.add(4, 4, GlType::Float, false)
... | Rust | 0 |
, 0, 0, 0, 0, 0, 0,
0, // 0xBF
0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, // 0xDF
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xEF
4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xFF
];
// This function is a copy of core::str::utf8_cha... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.