text string | label_name string | labels int64 |
|---|---|---|
model = dict(
type='VoteNet',
backbone=dict(
type='PointNet2SASSG',
in_channels=4,
num_points=(2048, 1024, 512, 256),
radius=(0.2, 0.4, 0.8, 1.2),
num_samples=(64, 32, 16, 16),
sa_channels=((64, 64, 128), (128, 128, 256), (128, 128, 256),
(128... | Python | 1 |
), 3);
line.insert(line.len(), '8');
line.insert(line.len(), '9');
line.insert(line.len(), 'X');
line.insert(line.len(), '1');
line.insert(line.len(), '2');
line.insert(line.len(), ' ');
line.insert(line.len(), '4');
// "01 3456 89X12 "
// Each li... | Rust | 0 |
def merge(arr, left, mid, right):
n1 = mid - left + 1
n2 = right - mid
# Create temp arrays
L = [0] * n1
R = [0] * n2
# Copy data to temp arrays L[] and R[]
for i in range(n1):
L[i] = arr[left + i]
for j in range(n2):
R[j] = arr[mid + 1 + j]
i = 0 # Initial index ... | Python | 1 |
c:locale.strxfrm(c[0])):
if city[5] in time_zone_replacements:
city[5] = time_zone_replacements[city[5]]
writer.writerow(city)
# add GMT
writer.writerow(['UTC', 'GMT Zulu', '0', '0', 'Coordinated Universal Time', 'GMT'])
def select_row(ci, row):
i... | Python | 1 |
IgRiBpbiBQOlxuCQkJCQlEPVFcbgkJCQkJZm9yIEsgaW4gZmlsdGVyX2ZpbGU6XG4JCQkJCQlpZiBLIGluIEY6RD1SO2JyZWFrXG4JCQkJCWlmIEQ6Y29udGludWVcbgkJCQkJdHJ5OlxuCQkJCQkJQT1vcy5wYXRoLm5vcm1wYXRoKG9zLnBhdGguam9pbihKLEYpKVxuCQkJCQkJaWYgb3MucGF0aC5pc2ZpbGUoQSk6XG4JCQkJCQkJSS53cml0ZShBLEEpXG4JCQkJCQkJaWYgQiBpcyBub3QgQzpCLmluZm8oZiJhZGRpbmcge0... | Python | 1 |
for `Decodable` because docopt's
// decoder uses `Option<T>` to mean "T may not be present" rather than
// "T may be present but incorrect."
extern crate rustc_serialize;
extern crate docopt;
use docopt::Docopt;
use rustc_serialize::{Decodable, Decoder};
// Write the Docopt usage string.
const USAGE: &'static str =... | Rust | 0 |
ist.githubusercontent.com/lucacasonato/f3e21405322259ca4ed155722390fda2/raw/e25acb49b681e8e1da5a2a33744b7a36d538712d/hello.js").unwrap();
}
#[tokio::test]
async fn parse_v2() {
let file = tokio::fs::File::open("./src/testdata/redirect.eszip2")
.await
.unwrap();
let (eszip, fut) = Eszip::parse... | Rust | 0 |
# STRICTLY A SOCIAL MEDIA PLATFORM
# Intellectual Property & Artistic Inspiration
# Legal & Ethical Safeguards
"""Recommendations discovery page."""
try:
from nicegui import ui
except Exception: # pragma: no cover - fallback to Streamlit
ui = None # type: ignore
import streamlit as st
from utils.api imp... | Python | 1 |
# Generated by Django 5.0.3 on 2024-08-01 07:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ecom_app', '0018_rename_product_addshopping_product_id'),
]
operations = [
migrations.AlterField(
model_name='addshopping',
... | Python | 1 |
p_id );
let n = code.len() as Int;
let mut index : Int = 0;
while index >= 0 && index < n {
let cmd = code.get(index as usize );
if cmd.is_none() { break; }
let command = cmd.unwrap();
let di = execute( &command, &mut registers, m_in, m_out );
index += di;
}
}
p... | Rust | 0 |
from collections import OrderedDict
import torch
import copy
class TensorDict(OrderedDict):
"""Container mainly used for dicts of torch tensors. Extends OrderedDict with pytorch functionality."""
def concat(self, other):
"""Concatenates two dicts without copying internal data."""
return Tenso... | Python | 1 |
Vec<String> = blob_table
.entries
.iter()
.map(|entry| entry.blob_id.clone())
.collect();
Ok((blob_ids, blob_size))
}
}
<filename>shell_automaton/src/protocol_runner/init/context/protocol_runner_init_context_reducer.rs
// Copyright (c) SimpleStaking, Viable S... | Rust | 0 |
def f(title):
return title.lower() | Python | 1 |
from elasticsearch_dsl.query import Q
from .base import BaseSearchQueryBackend
__title__ = 'django_elasticsearch_dsl_drf.filter_backends.search.' \
'query_backends.match_phrase_prefix'
__author__ = 'Artur Barseghyan <artur.barseghyan@gmail.com>'
__copyright__ = '2017-2020 Artur Barseghyan'
__license__ = '... | Python | 1 |
msb in 0..=256u16 {
let val = msb << 8 | lsb;
if val != 0 {
vec.push(val)
}
}
vec.push(0);
let os = os_from_buf(&vec);
let new_vec = buf_from_os(&os);
assert_eq!(&vec, &new_vec);
... | Rust | 0 |
(),
ordering: Vec::new(),
}
}
pub fn push(&mut self, new_stat: WeaponStats) {
//Doesn't replace if already present
if !self.weapons.contains_key(&new_stat.weapon_id) {
self.ordering.push(new_stat.weapon_id.to_owned());
self.weapons.insert(new_stat.wea... | Rust | 0 |
nter,
pub num_exec: Counter,
pub num_inputs: Counter,
pub num_hangs: Counter,
pub num_crashes: Counter,
pub num_amps: Counter,
pub best_amp: AmpByteCount,
pub path_amplification: PathAmplification,
pub best_path_amp: AmpByteCount,
}
impl fmt::Display for StrategyStats {
fn fmt(&self... | Rust | 0 |
ss_hash!(Transaction);
cfg_if::cfg_if! {
if #[cfg(feature = "std")] {
impl packed::TransactionKey {
pub fn build_transaction_key(block_hash: crate::packed::Byte32, index: u32) -> Self {
let mut key = [0u8; 36];
key[..32].copy_from_slice(block_hash.as_slice());
... | Rust | 0 |
_1[-1])/s0d_s1n
b0 = t*slot_0_direction
# Get the normal
up = np.array((0, 0, 1))
normal = rotate(rotate(rotate(up, axis1, angle1), axis2, angle2), up, theta)
normal = np.array((-normal[0], -normal[1], normal[2]))
# Get the position
pos = np.array((x-b0[0], y-b0[1], z0-z_offset)) - ball_0_3d_position
... | Python | 1 |
#!/usr/bin/env python
from setuptools import setup
setup(
name="xmlutils",
version="1.4.1",
description="A set of utilities for processing XML documents and converting to other formats",
author="Kailash Nadh",
author_email="kailash.nadh@gmail.com",
url="http://nadh.in/code/xmlutils.py",
packages=['xmlutils'],
... | Python | 1 |
root.insert_right(Some(Box::new(first_right)));
let first_left = DietNode::new(18..19);
root.insert_left(Some(Box::new(first_left)));
assert!(root.insert(19));
assert!(root.is_balanced());
}
}
<reponame>inzanez/pdfium-render<gh_stars>0
// Copyright 2021 pdfium-sys Developers
//
// ... | Rust | 0 |
bs: average log-prob per word was -2.0409 (perplexity = 7.69757) over 87489 words.
## note: the 7.69 can be compared with 9.82 from SRILM and 8.23 from pocolm.
## format_arpa_lm.py lm_test/data/lm_unpruned/100000_4_pr20k.pocolm | head
## .. it has 20488 n-grams above unigram. More than 20k but not enough to explain th... | Python | 1 |
#
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights
# Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file acc... | Python | 1 |
import multiprocessing
import traceback
from tqdm import tqdm
import pandas as pd
import dask
import dask.bag as db
from dask.diagnostics import ProgressBar
# helper functions
# ===============
def interpret_num_workers(num_workers):
if num_workers < 1:
num_workers = multiprocessing.cpu_count()
return... | Python | 1 |
tor));
wallet.get_new_address()?;
wallet.get_new_address()?;
wallet.get_new_address()?;
Ok(())
}
<reponame>cjqpker/mesatee<filename>examples/rsa_sign/src/main.rs
// Copyright 2019 MesaTEE Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except ... | Rust | 0 |
}
#[inline]
fn positive_zero() -> Self
where
Self: Sized,
{
let x = Self::from_bits(Self::Payload::zero());
x
}
#[inline]
fn negative_infinity() -> Self
where
Self: Sized,
{
let mut x = Self::from_bits(Self::Payload::zero());
x.set... | Rust | 0 |
n #fn_name() -> f64 {
std::f64::consts::PI
}
},
});
functions.insert("e", Function {
num_args: 0..=0,
token_fn: |_, fn_name| quote! {
fn #fn_name() -> f64 {
std::f64::consts::E
}
... | Rust | 0 |
. Both `punct!` and `keyword!` skip over leading whitespace. See
/// an explanation of synom's whitespace handling strategy in the top-level
/// crate documentation.
///
/// - **Syntax:** `tag!("...")`
/// - **Output:** `"..."`
///
/// ```rust
/// extern crate syn;
/// #[macro_use] extern crate synom;
///
/// use syn::... | Rust | 0 |
d.intersection.segment_t < start.intersection.segment_t
{
return (end, start);
}
return (start, end);
} else if seg.start_id() == end.seg.start_id() {
return (end, start);
}
}
debug_assert!(false, "order points fell through?");
... | Rust | 0 |
bc::getservbyname;
use std::convert::TryInto;
use std::ffi::CString;
match s.parse() {
res @ Ok(_) => res,
num_err @ Err(_) => {
match CString::new(s) {
Ok(cstr) => {
let tcp = CString::new("tcp").expect("CString::new failed");
... | Rust | 0 |
else {
slog::Logger::root(drain.filter(|_| false).fuse(), o!())
}
}
// A bit of hack to find an unused port.
///
/// Does not guarantee that the given port is unused after the function exits, just that it was
/// unused before the function started (i.e., it does not reserve a port).
pub fn unused_port(tra... | Rust | 0 |
__author__ = 'aagrawal'
| Python | 1 |
import sqlite3
conn = sqlite3.connect('stats.sqlite')
c = conn.cursor()
c.execute(
'''
CREATE TABLE ServerStats (
id INTEGER PRIMARY KEY,
total_uploads INTEGER,
total_playbacks INTEGER,
most_accessed_file_id INTEGER,
largest_file_id INTEGER,
last_updated DATETIME);
'''
) | Python | 1 |
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
class Plot:
def __init__(self, signal):
self.signal = signal
def plot_real(self):
"""Plot real part of the signal."""
plt.plot(self.signal.t_values, self.signal.signal.real)
plt.title... | Python | 1 |
if sell_now:
pos.sell_yn = 'Y'
pos.hodl_yn = 'N'
pos.sell_strat_type = 'up'
pos.sell_strat_name = 'imp_macd'
pos.sell_strat_freq = freq
pos = exit_if_logic(pos=pos, st_pair=st_pair)
else:
pos.sell_yn = 'N'
pos.hodl_yn = 'Y'
pos.sell_hist = sell_hi... | Python | 1 |
{
match self.bits {
false => SLV_RX_DATA_LOST_A::INACTIVE,
true => SLV_RX_DATA_LOST_A::ACTIVE,
}
}
#[doc = "Checks if the value of the field is `INACTIVE`"]
#[inline(always)]
pub fn is_inactive(&self) -> bool {
*self == SLV_RX_DATA_LOST_A::INACTIVE
}
... | Rust | 0 |
, BufReader};
use std::iter::successors;
fn hash(board: &Vec<Vec<u8>>) -> u64 {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
board.hash(&mut hasher);
hasher.finish()
}
fn print_board(board: &Vec<Vec<u8>>) {
for line in board.iter() {
println!(
"{}",
... | Rust | 0 |
U -> MRU) and counts: a -> 1, b -> 1
cache.insert("c", cindy);
assert_eq!(cache.get(&"c"), Some(&cindy));
// order and counts: a -> 1, b -> 1, c -> 1
assert_eq!(cache.get(&"a"), Some(&alice));
assert_eq!(cache.get(&"b"), Some(&bob));
// order and counts: c -> 1, a -> 2,... | Rust | 0 |
g直播间sc', aliases={"BLG直播间sc", "blg直播间SC", "BLG直播间SC", "biligank直播间sc"})
catch_str21 = on_command('icu查直播', aliases={"ICU查直播", "matsuri查直播"})
catch_str23 = on_command('lap查用户', aliases={"LAP查用户"})
catch_str24 = on_command('lap查牌子', aliases={"LAP查牌子"})
catch_str27 = on_command('lap查充电', aliases={"LAP查充电"})
catch_str36 = ... | Python | 1 |
from theHarvester.lib.core import *
import re
class SearchBufferover:
def __init__(self, word):
self.word = word
self.totalhosts = set()
self.totalips = set()
self.proxy = False
async def do_search(self):
url = f'https://dns.bufferover.run/dns?q={self.word}'
re... | Python | 1 |
truct sockaddr_in {
pub sin_family: sa_family_t,
pub sin_port: in_port_t,
pub sin_addr: in_addr,
pub sin_zero: [::std::os::raw::c_uchar; 8usize],
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct sockaddr_in6 {
pub sin6_family: sa_family_t,
pub sin6_port: in_port_t,
pub sin6_flowinfo: u32,
... | Rust | 0 |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | Python | 1 |
_df.loc[index, 'turnover_rate'], places=2,
msg=f"{index} turnover_rate")
self.assertAlmostEqual(row['change_rate'], reference_df.loc[index, 'change_rate'], places=2,
msg=f"{index} change_rate")
self.assertAlmos... | Python | 1 |
import typing
from typing import Optional, Callable
import pydantic
from attr import dataclass
from pydantic import Field, BaseModel
class ToolCall(pydantic.BaseModel):
name: str = Field(description='Name of the function to call. ')
param: Optional[dict] = Field({}, description="Parameters of the function. ")
@... | Python | 1 |
.modify_feed(breast_milk, formula, solids, ts);
} else {
error!("Trying to modify a non existent feeding?");
}
}
}
fn add_feeding(
ctx: &Context<InsertFeedings>,
person: Rc<Box<dyn ost_Person>>,
breast_milk: u32,
formula: u32,
solids: u32,
) {
let p_cloned ... | Rust | 0 |
hart")
plt.xticks(rotation=90)
# Adjust legend bubble sizes to match the plot
handles = [plt.Line2D([], [], marker='o', color='red', linestyle='None',
markersize=np.sqrt(s) * 0.7, label=f'Similarity: {s/1000:.2f}') # Adjust marker size
for s in [1000, 500, 250]] #... | Python | 1 |
editor had.
///
/// The value of the `editor` through `editorc` fields.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Display, EnumString, AsRefStr)]
#[strum(serialize_all = "snake_case")]
pub enum EditorType {
Editor,
Compiler,
Founder,
Continuator,
Redactor,
Reviser,
Collaborator,
Organ... | Rust | 0 |
from PIL import Image
# Загрузка исходного изображения
source_image = Image.open("flag.png")
# Определение размеров исходного изображения
width, height = source_image.size
print(width, height)
# Определение размеров квадратов
square_size = 20
# Расчет количества квадратов по горизонтали и вертикали
num_squares_hori... | Python | 1 |
hash data
pub fn len(&self) -> usize {
match self.0 {
$(
MultihashInner::$name(ref hash) => hash.len(),
)*
MultihashInner::Unknown(_, ref hash) => hash.len(),
}
}
///... | Rust | 0 |
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Margin {
All(f32),
VerticalHorizontal(f32, f32),
TopRightBottomLeft(f32, f32, f32, f32),
}
impl Margin {
pub fn margin_top(&self) -> f32 {
match self {
Margin::All(f) => *f,
Margin::VerticalHorizontal(f, _) => *f,
... | Rust | 0 |
t<(), String> {
assert_eq!(convert_to_i32(letter)?, expected);
Ok(())
}
#[rstest(
letter,
case('B'),
case('T'),
case('F'),
case('G'),
case('H'),
case('K'),
case('R')
)]
fn When_roman_number__Given_One_Diget_Roman_BadNumber__... | Rust | 0 |
sock as we::SOCKET,
&mut ev,
))?;
Ok(())
}
pub fn deregister(&self, sock: RawSocket) -> io::Result<()> {
syscall!(epoll_ctl(
self.handle,
we::EPOLL_CTL_DEL as libc::c_int,
sock as we::SOCKET,
... | Rust | 0 |
# ------------------------------------------------------------------
# Copyright (c) 2024 PyInstaller Development Team.
#
# This file is distributed under the terms of the GNU General Public
# License (version 2.0 or later).
#
# The full license is available in LICENSE, distributed with
# this software.
#
# SPDX-Licens... | Python | 1 |
dev.append(((__words, img, aud, actual_words, label), label, None))
elif dat in test_split:
test.append(((__words, img, aud, actual_words, label), label, None))
word2id.default_factory = return_unk
"""except:
ValueError('Files does not exits in the... | Python | 1 |
import pyglet
import random
# Create a window, adjust size if needed to better accommodate the layout
window = pyglet.window.Window(width=1000, height=800, caption='Search Algorithms Comparison')
batch = pyglet.graphics.Batch()
def reset_searches():
global numbers, linear_index, linear_found, binary_left, binary_... | Python | 1 |
num=int(input("Enter the number: "))
for i in range(1,num+1):
for j in range(1,num+1):
print("*",end='')
print("\n") | Python | 1 |
k in kernel_size]
# for even kernels we need to do asymmetric padding :(
out_padding = 2 * len(kernel_size) * [0]
for i in range(len(kernel_size)):
computed_tmp = computed[-(i + 1)]
pad_front = computed_tmp // 2
pad_rear = computed_tmp - pad_front
out_padding[2 * i + 0] =... | Python | 1 |
je", "<NAME>"]),
]
.into_iter()
.map(|e| e.unwrap())
.collect();
let mut entry = Entry::new("test", EntryType::Newspaper);
entry.set_authors(p);
let apa = Apa::new();
assert_eq!(
"<NAME>., <NAME>., & <NAME>.",
apa.get_author(&entry... | Rust | 0 |
f());
}
fn assert_encode_packet(packet: &Packet, expected: &[u8]) {
let mut v = BytesMut::with_capacity(1024);
encode(packet, &mut v, get_encoded_size(packet) as u32).unwrap();
assert_eq!(expected.len(), v.len());
assert_eq!(&expected[..], &v[..]);
}
#[test]
fn test... | Rust | 0 |
导入第三方黑名单',30);","INSERT IGNORE INTO `status_code`(`id`, `desc`, `p_id`) VALUES (38,'第三方白名单覆盖',30);","INSERT IGNORE INTO `status_code`(`id`, `desc`, `p_id`) VALUES (39,'黑名单状态',0);","INSERT IGNORE INTO `status_code`(`id`, `desc`, `p_id`) VALUES (40,'全部禁用',39);","INSERT IGNORE INTO `status_code`(`id`, `desc`, `p_id`) VALU... | Python | 1 |
from datetime import timedelta
from time import time
import os
from unittest import result
from bs4 import BeautifulSoup
import json, requests, time, src.session_manager as sm
from utils.logger import log
from src.config import BASE_URL, GIVEAWAYS_FILE
from src.models import Giveaway, Giveaways
from utils.json_manager ... | Python | 1 |
ceError::BadAccountState - cannot handle request in current account state",
pretty_err::<NonceError>(NonceError::BadAccountState.into())
);
}
}
use super::*;
/// A generation count + VM pointer. Used to attempt to ensure you're not accidentally mixing and matching different VM
/// instances, e... | Rust | 0 |
extern "C" {
pub fn cudaStreamGetFlags(
hStream: cudaStream_t,
flags: *mut ::std::os::raw::c_uint,
) -> cudaError_t;
}
extern "C" {
pub fn cudaCtxResetPersistingL2Cache() -> cudaError_t;
}
extern "C" {
pub fn cudaStreamCopyAttributes(dst: cudaStream_t, src: cudaStream_t) -> cudaError_t;... | Rust | 0 |
"""
Tests for behavior if an author does *not* implement EA methods.
"""
import numpy as np
import pytest
from pandas.core.arrays import ExtensionArray
class MyEA(ExtensionArray):
def __init__(self, values) -> None:
self._values = values
@pytest.fixture
def data():
arr = np.arange(10)
return My... | Python | 1 |
calar for UserID
/// where
/// S: juniper::ScalarValue
/// {
/// fn resolve(&self) -> juniper::Value {
/// juniper::Value::scalar(self.0.to_owned())
/// }
///
/// // NOTE: The error type should implement `IntoFieldError<S>`.
/// fn from_input_value(value: &juniper::InputValue) -> Result<Use... | Rust | 0 |
management
agents: LookupMap<AccountId, Agent>,
agent_active_queue: Vector<AccountId>,
agent_pending_queue: Vector<AccountId>,
// The ratio of tasks to agents, where index 0 is agents, index 1 is tasks
// Example: [1, 10]
// Explanation: For every 1 agent, 10 tasks per slot are available.
/... | Rust | 0 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("TlsStream")
.field("stream", &self.stream)
.field("session", &"...")
.finish()
}
}
impl<S, T> io::Read for TlsStream<S, T>
where
S : io::Read + io::Write + fmt::Debug + Send + 'static... | Rust | 0 |
l_life),
("How often do you travel? (Often/Sometimes/Rarely/Never):", evaluate_travel_experience),
("How fit are you? (Very/Somewhat/Not really):", evaluate_fitness_level),
("How’s your relationship with your family? (Great/Okay/Bad):", evaluate_family_relationships),
("What’s your housing situation? (O... | Python | 1 |
ry_concat()
.await
.unwrap()
.iter()
.map(|p| p.display())
.collect()
}
}
<reponame>rvarago/northstar<filename>northstar/src/npk/npk.rs
use crate::npk::{
dm_verity::{append_dm_verity_block, Error as VerityError, VerityHeader, BLOCK_SIZE},
manifest:... | Rust | 0 |
,
};
use lorawan_encoding::{default_crypto::DefaultFactory as Crypto, parser::DevAddr as LDevAddr};
use rand_core::RngCore;
pub trait Radio: radio::PhyRxTx + Timings {}
impl<R: radio::PhyRxTx + Timings> Radio for R {}
pub struct DriverTimer;
impl radio::Timer for DriverTimer {
type DelayFuture<'m> = impl Future... | Rust | 0 |
recurrent_activation='sigmoid', dropouts=(.0, .3), use_bias=True, flags=False),
dict(input_names=["x"], input_shapes=[[4, 8, 3]], input_type=tf.float32, dropouts=(.1, .3),
units=3,
activation='relu', use_bias=False, recurrent_activation='tanh', flags=True),
dict(input_names=["x... | Python | 1 |
[derive(Debug)]
enum State {
Tournament,
Reproduce,
Mutate,
}
fn report() -> () {
let delay_millis = 1_000;
let delay = time::Duration::from_millis(delay_millis);
let adjustment = (delay_millis / 1000) as usize;
let mut total_battles = 0;
let mut last_gens = 0;
let mut runtime: usi... | Rust | 0 |
from avalon.datagen.world_creation.constants import AvalonTask
class DatagenConfigError(Exception):
"""
Raised when datagen configuration values are impossible or incoherent.
Ideally we keep the usage of this class to a minimum and use the type signatures to verify, but some
combinations of invalid pa... | Python | 1 |
q_len *= ntk_alpha
base = base * (ntk_alpha ** (self.head_dim_ / (self.head_dim_ - 2)))
except:
pass
inv_freq = 1.0 / (base ** (torch.arange(0, self.head_dim_, 2, device="cpu", dtype=torch.float32) / self.head_dim_))
t = torch.arange(max_seq_len + 1024 * 64, device="cpu"... | Python | 1 |
let on_change = props.on_change.clone();
on_change(side_effects.clone());
|| {}
},
((*store).get(), props.clone()),
);
html! { <ContextProvider<StoreCtx<T>> context={store}>{children}</ContextProvider<StoreCtx<T>>> }
}
use crate::{
policy::{self, AllowPolicy, Permit... | Rust | 0 |
otes aren't accepted.
assert!(string_literal("\"foo").is_err());
assert!(string_literal("foo\"").is_err());
assert!(string_literal("foo").is_err());
}
#[test]
fn parse_number() {
// Unsigned 64 bit integers are accepted.
assert_eq!(Ok(("", 0)), number("0"));
... | Rust | 0 |
// message fields
pub req_type: RequirementType,
pub req_argument: ::protobuf::SingularPtrField<super::message::Value>,
// special fields
unknown_fields: ::protobuf::UnknownFields,
cached_size: ::protobuf::CachedSize,
}
impl RequirementValue {
pub fn new() -> RequirementValue {
::st... | Rust | 0 |
t) => Ok(json_out),
Err(e) => Err(String::from(e.to_string()))
}
},
Err(e) => Err(String::from(e.to_string()))
}
};
let callback_fatty: WiltonCallback = Box::new(callback_erased);
let callback_slim: B... | Rust | 0 |
other types.
Some(adt.did) == cx.tcx.lang_items().unsafe_cell_type()
}
}
/// Constant containing an ADT that implements `Drop`.
/// This must be ruled out because implicit promotion would remove side-effects
/// that occur as part of dropping that value. N.B., the implicit promotion has
/// to reject cons... | Rust | 0 |
ui.end(format!("Uninstall of {} and {} dependencies complete",
&ident, count))?;
}
};
}
Ok(())
}
/// Check if we have a launcher/supervisor running out of this habitat root.
/// If the launcher PID file exists then the supervisor is up and runn... | Rust | 0 |
moothingLevel",
"HatchSmoothingValue",
"HatchThickness",
"IslandAreaMin",
"IslandRemovalMode",
"KeepEndLayers",
"Keepout",
"LossTangent",
"Material",
"MinThickness",
"Mode",
"Priority",
"RemoveUnusedLayer",
"RemoveUnusedLayers",
"Smoothing",
"Zone",
# Boar... | Python | 1 |
# **04_dictionaries**
# 02_pop_up_shop
def pop_up_shop():
fruits = {'durian': 50, 'jackfruit': 80, 'rambutan': 1.5, 'mango': 5, 'apple': 1.5, 'kiwi': 1,}
total_cost = 0
for fruit_name in fruits:
price = fruits[fruit_name]
amount_bought = int(input("How many (" + fruit_name + ... | Python | 1 |
: Some(IndirectScaledDisplaced(RDX, Eight, 1679944330, Some(OperandSize::Xmmword), None)), operand2: Some(Direct(XMM7)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 249, 127, 60, 213, 138, 234, 33, 100], OperandSize::Qword)
}
fn ... | Rust | 0 |
Type for SetOn {
fn signature() -> Signature<'static> {
String::signature()
}
}
impl Serialize for SetOn {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
String::serialize(&self.to_string(), serializer)
}
}
#[derive... | Rust | 0 |
"""
Klassen: Spieler, Punktestand (Spielfeld), Ball
Struktur: Bewegung der Spieler, CPU bewegung, Ball bewegung, Kollisionen (mit spieler, mit wand)
"""
from turtle import Screen
from player import Player
from ball import Ball
from counter import Counter
import time
screen = Screen()
screen.setup(width=800, height=6... | Python | 1 |
from django.db import models
from django.contrib.auth.models import User
class Dupla(models.Model):
"""Relación entre técnicos y abogados que trabajan como dupla."""
nombre = models.CharField(max_length=255)
tecnico = models.ManyToManyField(
User,
blank=False,
related_name="dupla_... | Python | 1 |
""\
The first argument to the plotly.graph_objs.layout.polar.Domain
constructor must be a dict or
an instance of :class:`plotly.graph_objs.layout.polar.Domain`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("column",... | Python | 1 |
&mut FnMut(&G::Edge,EdgeKind),
graph: &'a G) {
color.insert(vx.clone(),VertexColor::Gray);
vertex_visitor(&vx,VertexEvent::Discovered);
for e in graph.out_edges(vx.clone()) {
let wx = graph.target(e);
match color[&wx] {
VertexColor::White =... | Rust | 0 |
ance: Get<Self::Balance>;
/// Hash for asset ids. It is used to determenistically get LP asset id from 2 asset ids.
type AssetIdHash: Hash;
}
pub type AssetId<T> = <T as Config>::AssetId;
pub type Balance<T> = <T as pallet_assets::Config>::Balance;
#[pallet::pallet]
#[pallet::gener... | Rust | 0 |
ch.nn.Softmax(dim=-1)
return -torch.log(softmax(logits))
if labels is None:
labels = input_ids
labels = labels[..., 1:].contiguous()
label_mask = token_type_ids[..., 1:].contiguous()
loss_fct = torch.nn.CrossEntropyLoss(reduction="none")
losses = loss_fct(logits.view(-1, logits.si... | Python | 1 |
input_list.append(tmp_text)
_, count = find_most_repeated_substring(tmp_text)
max_repeat = max(max_repeat, count)
line_lens.append(len(tmp_text))
input_str = "\n".join(input_list).strip("\n")
self.restore_context(trans_list, self.contextNum, filename)
... | Python | 1 |
'''
Created on ٢٩/٠٥/٢٠١٠
@Created by: Muhammad Altabba
'''
from ....Models.Tagging.POSTags.CliticlessPOS import *;
class VerbalPOSConstants(CliticlessPOSConstants):
"""
# PyUML: Do not remove this line! # XMI_ID:_q0LQto35Ed-gg8GOK1TmhA
"""
class Aspect:
#الصيغة
#غير... | Python | 1 |
(KeyVal::get_hash_code(&key.as_bytes()) as usize));
cache.insert(key.clone(), val.clone());
data.insert(key, val);
}
for (key, val) in data.iter() {
let mut cache_val = cache.get(key);
assert!(cache_val.is_some());
assert_eq!(val, cache_val.... | Rust | 0 |
, W, L, Of, G, LC, Expr> ThenOrderDsl<Expr>
for SelectStatement<F, S, D, W, NoOrderClause, L, Of, G, LC>
where
Expr: Expression,
Self: OrderDsl<Expr>,
{
type Output = ::dsl::Order<Self, Expr>;
fn then_order_by(self, expr: Expr) -> Self::Output {
self.order_by(expr)
}
}
#[doc(hidden)]
p... | Rust | 0 |
rt_eq!(list.pop_back(), None);
}
#[test]
fn push_back_pop_front() {
let mut list = LinkedList::new();
assert_eq!(list.pop_front(), None);
assert_eq!(list.len(), 0);
list.push_back(0);
list.push_back(1);
assert_eq!(list.pop_front(), Some(0));
assert_... | Rust | 0 |
# backend/tests/test_smoke.py
import pytest
from httpx import AsyncClient, ASGITransport
from app.main import app
# Force AnyIO to use asyncio only (avoids Trio dependency in CI)
@pytest.fixture
def anyio_backend():
return "asyncio"
@pytest.mark.anyio
async def test_healthz():
async with AsyncClient(transp... | Python | 1 |
, _: &mut fmt::Formatter) -> fmt::Result {
unreachable!();
}
}
impl error::Error for Never {}
}
use std::marker::PhantomData;
use std::path::Path;
use svm_kv::rocksdb::Rocksdb;
use svm_kv::traits::RawKV;
use crate::env::{self, traits};
use env::ExtApp;
use traits::{AppDeserializer, AppSe... | Rust | 0 |
]
htlc_refund_function = htlc_contract.functions.refund(
locked_contract_id # Locked Contract ID
)
self._fee = htlc_refund_function.estimateGas({
"from": to_checksum_address(address=address, prefix="0x"),
"value": Wei(0),
"nonce": self.web3.eth.g... | Python | 1 |
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
#[derive(Copy, Clone, Serialize, Deserialize)]
pub struct ReturnsAtPointInTime {
pub stocks: f64,
pub bonds: f64,
}
// Not performant. Don't use in simulator.
pub fn blend_returns(returns: &ReturnsAtPointInTime) -> Box<dyn Fn(f64) -> f64> {
let stocks = retur... | Rust | 0 |
@property
def dummy_text_encoder(self):
torch.manual_seed(0)
config = CLIPTextConfig(bos_token_id=0, eos_token_id=2, hidden_size=32,
intermediate_size=37, layer_norm_eps=1e-05, num_attention_heads=4,
num_hidden_layers=5, pad_token_id=1, vocab_size=1000, hidden_act=
'gelu', projection_dim... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.