text string | label_name string | labels int64 |
|---|---|---|
with the
# provided quantization properties.
if not _is_ok_for_quantization(node, quant_properties, gm):
return None
return quant_properties
def annotate_graph( # type: ignore[return]
gm: torch.fx.GraphModule,
quantization_config: QuantizationConfig,
filter_fn: Optional[Callable[[No... | Python | 1 |
erialize::Error> {
let mut file = fs::File::open(path).map_err(deserialize::Error::Reader)?;
let ref_cell = RefCell::new(&mut file);
for file in parse(&ref_cell)?.all() {
let path = match dest.as_ref() {
Some(dest) => Cow::Owned(dest.as_ref().join(file.path())),
None => Cow... | Rust | 0 |
= Cell::new(0);
process.completion_code = OptionalCell::empty();
process.mpu_config = MapCell::new(mpu_config);
process.mpu_regions = [
Cell::new(None),
Cell::new(None),
Cell::new(None),
Cell::new(None),
Cell::new(None),
C... | Rust | 0 |
#!/usr/bin/env python
##################################################################
"""
Temporal subsets a variable
A couple of ways of indicating time for ioapiTools:
indices - 0-based index
DateTime - mx.DateTime objects
cdtime - cdtime objects
string - time string of fo... | Python | 1 |
mosaic_density : Cache<f32>,
pub mosaic_material : Cache<Option<Material>>,
}
pub fn new<Material>(mosaic: Box<voxel::mosaic::T<Material> + Send>) -> T<Material> {
T {
mosaic : mosaic,
density : lru_cache::LruCache::with_hasher(1 << 10, Default::default()),
normal : lru_cach... | Rust | 0 |
writeln!(
jsonfile,
"\t]"
).unwrap();
Ok(())
}
fn export_json_links(doc: &Document, jsonfile: &mut File) -> Result<(), Error> {
writeln!(
jsonfile,
"\t\"links\": ["
).unwrap();
let mut i = 0;
'loop_source: for key in doc.keys() {
// Unwrap is safe since key comes from keys()
let vec_dependen... | Rust | 0 |
name(&fname1)?)?[..],
b"Hello world"
);
assert!(std::fs::read(store.blob_fname(&fname2)?).is_err());
let n: u32 = store
.conn
.query_row("SELECT COUNT(filename) FROM ExtDocs", [], |row| row.get(0))?;
assert_eq!(n, 1);
Ok(())
}
#[test]... | Rust | 0 |
for m in self.modules():
if isinstance(m, CARAFEPack):
m.init_weights()
def slice_as(self, src, dst):
"""Slice ``src`` as ``dst``
Note:
``src`` should have the same or larger size than ``dst``.
Args:
src (torch.Tensor): Tensors ... | Python | 1 |
: &mut Vec<(Vec<u8>, Vec<u8>)>| -> Result<(), EngineError> {
batch.iter().try_for_each(|(k, v)| wb.put_cf(cf, k, v))?;
wb.write()?;
wb.clear();
callback(batch);
batch.clear();
Ok(())
};
// Collect keys to a vec rather than wb so that we can invoke the callback le... | Rust | 0 |
Data(
session: *const HAPI_Session,
node_id: HAPI_NodeId,
workitem_id: HAPI_PDG_WorkitemId,
data_name: *const ::std::os::raw::c_char,
data_array: *mut HAPI_StringHandle,
length: ::std::os::raw::c_int,
) -> HapiResult;
}
extern "C" {
pub fn HAPI_GetWorkitemResultIn... | Rust | 0 |
y, Clone)]
pub enum ClockOutput {
Clk0 = 0,
Clk1,
Clk2,
Clk3,
Clk4,
Clk5,
Clk6,
Clk7,
}
#[derive(Debug, Copy, Clone)]
pub enum OutputDivider {
Div1 = 0,
Div2,
Div4,
Div8,
Div16,
Div32,
Div64,
Div128,
}
const ADDRESS: u8 = 0b0110_0000;
impl PLL {
pub... | Rust | 0 |
#!/usr/bin/env python3
# Copyright 2022 University of Stuttgart (Pavel Denisov)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import glob
import os
import subprocess
import sys
import xml.etree.ElementTree as ET
from num2words import num2words
idir = sys.argv[1]
odir = sys.argv[2]
os.makedirs(odir, e... | Python | 1 |
fn inner_ssl_ctx_set_verify(ctx_ptr: *mut SSL_CTX_ARC, mode: c_int) -> InnerResult<c_int> {
let mode = VerifyModes::from_bits(mode).ok_or(Error::BadFuncArg)?;
let ctx = sanitize_ptr_for_mut_ref(ctx_ptr)?;
let ctx_mut = util::get_context_mut(ctx);
ctx_mut.verify_modes = mode;
Ok(SSL_SUCCESS)
}
/// ... | Rust | 0 |
- neg_inds (Tensor): Sampled negative indexes for each image.
"""
num_bboxes = bbox_pred.size(0)
# assigner and sampler
assign_result = self.assigner2d.assign(bbox_pred, cls_score, pred_centers2d, gt_bboxes,
gt_labels, center... | Python | 1 |
time),
// }
// }
// fn print(&self) {
// println!("Received: {}, {}", self.messages, self.bytes);
// println!("Elapsed: {} ({}, {})", self.time, self.messages / self.time, self.bytes / self.time)
// }
// }
// fn get_topic_partitions_count<X: ConsumerContext, C: Consumer<X>>(consum... | Rust | 0 |
aaa aabb bbbb cccc ccdd dddd
/// ```
/// where
/// - FFF the position state ([DRAW], [LOSS], [WINS], [BAD]) for [WHITE]
/// - fff the position state for [BLACK]
/// - shv applied transformations relative to a non-canonic [CPos] (see below)
/// - AAAA player and piece kind of piece A
/// - BBBB player and piece kind of ... | Rust | 0 |
'''
Sms
====
The :class:`Sms` provides access to sending Sms from your device.
.. note::
On Android your app needs the SEND_SMS permission in order to
send sms messages.
.. versionadded:: 1.2.0
Simple Examples
---------------
To send sms::
>>> from plyer import sms
>>> recipient = 9999222299
... | Python | 1 |
# Copyright 2021 Google LLC
#
# 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 applicable law or agreed to in writing, s... | Python | 1 |
import gymnasium as gym
import numpy as np
import pytest
from mani_skill2.envs.sapien_env import BaseEnv
from tests.utils import (
CONTROL_MODES_STATIONARY_SINGLE_ARM,
ENV_IDS,
OBS_MODES,
ROBOTS,
STATIONARY_ENV_IDS,
assert_obs_equal,
)
@pytest.mark.parametrize("env_id", ENV_IDS)
@pytest.mark.... | Python | 1 |
import streamlit as st
from llama_index.llms.ollama import Ollama
from pathlib import Path
import qdrant_client
from llama_index.core import SimpleDirectoryReader, VectorStoreIndex, Settings, PromptTemplate
from llama_index.core.storage.storage_context import StorageContext
from llama_index.vector_stores.qdrant import ... | Python | 1 |
bbox=box_2d_preds[valid_inds, :].numpy(),
box3d_camera=box_preds_camera[valid_inds].tensor.numpy(),
box3d_lidar=box_preds[valid_inds].tensor.numpy(),
scores=scores[valid_inds].numpy(),
label_preds=labels[valid_inds].numpy(),
sample_idx=s... | Python | 1 |
e ColorSpace::Yuv, channels 3, bps 1, planar);
PixelTypeDef!(pub const YUV_16; color_space ColorSpace::Yuv, channels 3, bps 2);
PixelTypeDef!(pub const YUV_16_PLANAR; color_space ColorSpace::Yuv, channels 3, bps 2, planar);
PixelTypeDef!(pub const YUV_16_SE; color_space ColorSpace::Yuv, channels 3, bps 2, e... | Rust | 0 |
=> match event {
/// Event::A => State::B,
/// _ => state,
/// }
/// State::B => {
/// warn!("cannot receive events in State::B");
/// state
/// }
/// })
/// }
/// ```
pub struct StateMachine<S> {
state: Option<S>,
}
impl<S: Debug> Debug f... | Rust | 0 |
} => {
assert_eq!(
input_fields.keys().collect::<Vec<_>>(),
vec!["name", "createat"]
);
}
_ => unreachable!(),
}
}
#[tokio::test]
async fn test_oneof_object_rename_field() {
#[derive(OneofObject)]
enum MyInput {
Name(i32),
... | Rust | 0 |
Debug-Options"] = "bugReporterEnabled"
if msg_attempt >= 3: # 如果已经尝试了很多次
return False, "Infinite captcha loop detected", {
"error_... | Python | 1 |
tive_n` must be provided. If both are provided, `budget` will be used.
`[BHvL24] <https://osf.io/preprints/socarxiv/j3bnt>`__ Broska, D., Howes, M., & van Loon, A. (2024, August 22). The Mixed Subjects Design: Treating Large Language Models as (Potentially) Informative Observations. https://doi.org/10.31235/o... | Python | 1 |
&str) -> Self {
Self::from_ext(s)
}
}
}
}
mime! {
// text
Text = "txt", "text/plain",
Html = "html", "text/html",
Js = "js", "application/javascript",
Css = "css", "text/css",
Json = "json", "application/json",
Csv = "csv", "text/csv",
Doc = "doc", "application/msword",
Docx = "docx", "application... | Rust | 0 |
success == 0 {
return Err(get_program_error_log(program_id));
}
for shader in shaders {
unsafe { gl::DetachShader(program_id, shader.id()); }
}
Ok(Program { id: program_id })
}
pub fn standard() -> Result<Program, String> {
let standard_vert = ... | Rust | 0 |
()
.write(format!("got {}!\n", len).as_bytes())
.unwrap();
TERM.stdout().lock().write(&read_buffer).unwrap();
TERM.stdout().lock().flush().unwrap();
}
Err(e) => {
println!("{:?}", ... | Rust | 0 |
import unittest
from unittest.mock import patch
from tmc import points
from tmc.utils import load_module, reload_module, get_stdout, sanitize
from functools import reduce
from random import randint
exercise = 'src.number_of_characters'
@points('2.number_of_characters')
class NumberOfCharactersTest(unittest.TestCase)... | Python | 1 |
#![allow(clippy::module_name_repetitions)] // This is fine.
mod ext;
mod dowser;
mod hash;
pub mod utility;
pub use self::dowser::{
Dowser,
DowserError,
};
pub use ext::Extension;
#[doc(hidden)]
pub(crate) use hash::{
NoHashU64,
NoHashState,
};
use std::path::{
Path,
PathBuf,
};
#[must_use... | Rust | 0 |
{
let body = hyper::body::to_bytes(req.body_mut())
.await
.map_err(|_| "Internal Server Error".to_string())?;
serde_json::from_slice(&body).map_err(|e| format!("Failed to parse JSON: {}", e))
}
// Generates a random string of length
pub fn gen_random(length: usize) -> String {
let mut rng ... | Rust | 0 |
u': 'પોલિનેશિયા', 'ha': 'Kasar Polynesia', 'he': 'פולינזיה', 'hi': 'पोलिनेशिया', 'hi-Latn': 'Polynesia', 'hr': 'Polinezija', 'hsb': 'Polyneziska', 'hu': 'Polinézia', 'hy': 'Պոլինեզիա', 'ia': 'Polynesia', 'id': 'Polinesia', 'ig': 'Polynesia', 'is': 'Pólýnesía', 'it': 'Polinesia', 'ja': 'ポリネシア', 'jv': 'Polinesia', 'ka': ... | Python | 1 |
(
"/ip4/12.34.56.78/tcp/1234/ln-handshake/123",
vec![
Ip4(Ipv4Addr::new(12, 34, 56, 78)),
Tcp(1234),
Handshake(123),
],
),
(
"/ip6/::1/tcp/0",
vec![Ip6(I... | Rust | 0 |
_address_mode {
#[doc = "< No address mode."]
M68K_AM_NONE = 0,
#[doc = "< Register Direct - Data"]
M68K_AM_REG_DIRECT_DATA = 1,
#[doc = "< Register Direct - Address"]
M68K_AM_REG_DIRECT_ADDR = 2,
#[doc = "< Register Indirect - Address"]
M68K_AM_REGI_ADDR = 3,
#[doc = "< Register Ind... | Rust | 0 |
def scale_schedule(begin, end, n, length, type='linear'):
if type == 'constant':
return end
elif type == 'linear':
return begin + (end - begin) * n / length
elif type == 'cos':
factor = (1 - math.cos(n * math.pi / length)) / 2
return (1 - factor) * begin + factor * end
el... | Python | 1 |
v)?;
parse_comma(lex, v)?;
let value = parse_string(lex, v)?;
Ok((value, ValueType::String, Some(MatchingRule::Timestamp(format.clone())), Some(Generator::DateTime(Some(format))), None))
}
// COMMA format=string COMMA s=string { $value = $s.contents; $type = ValueType.String; }
fn parse_date(lex: &mut Lexer<Mat... | Rust | 0 |
<T>,
right: &PrimitiveArray<T>,
op: F,
) -> Result<PrimitiveArray<T>>
where
T: PolarsNumericType,
T::Simd: Add<Output = T::Simd>
+ Sub<Output = T::Simd>
+ Mul<Output = T::Simd>
+ Div<Output = T::Simd>,
F: Fn(T::Simd, T::Simd) -> T::Simd,
{
if left.len() != right.len() {
... | Rust | 0 |
cies: HashMap<Ngram, u32>,
) {
let model = TrainingDataLanguageModel::from_text(
&TEXT.trim().to_lowercase().lines().collect::<Vec<_>>(),
&Language::English,
ngram_length,
"\\p{L}&&\\p{Latin}",
&lower_ngram_absolute_freq... | Rust | 0 |
9kwj, egif2bhqecm, qxit4hyfwrz: lebok3rq4cy, njkdo6kgl6h: h3a9qbet9lm, q65hkl9137a, jmnkuoew4zh: o2m9qtoea7j):
global lmxcmo5w4ia
assert b'', zytsbmu8b4f
'# jackboxes_alkalinity_pyramid -> manpower_reviews_gloves'
False[None]: rx8enicz9aw = be2gvcqtcf7
nonlocal fs093h8cdlp
import bnv145cpdy2, il... | Python | 1 |
# flake8: noqa
from pre_award.fund_store.config.fund_loader_config.cof.eoi import APPLICATION_BASE_PATH_COF_EOI
from pre_award.fund_store.config.fund_loader_config.cof.eoi import ASSESSMENT_BASE_PATH_COF_EOI
from pre_award.fund_store.config.fund_loader_config.cof.eoi import COF_EOI_ROUND_ID
from pre_award.fund_store.co... | Python | 1 |
match (a, b, c) {
(Token::Literal(n), Token::Plus, Token::Literal(m)) => {
stack.pop();
stack.pop();
stack.pop();
stack.push(Token::Literal(n + m));
}
_ => return Ok(()),
};
} // loop
}
fn eval(inp: ... | Rust | 0 |
if let Some(elem) = obj.get(key.as_str()) {
elements.push(elem.clone());
}
for value in obj.values() {
for element in Selector::RecursiveKey(key.clone()).eval(value.clone()) {
... | Rust | 0 |
seconds();
context.consume_execution_ended_event(
BTNodeExecutionEndedEvent::new(
&ended_at, &node_id, &node_tick_id, &result, &started_at, header, took_ms
)
).await;
result
}
}
#[async_trait]
impl BehaviorTreeNode for BTNode {
async fn do_tic... | Rust | 0 |
new_rtp_with_sizes(payload_size, 4, csrc_count).unwrap();
let rtp_buffer = RTPBuffer::from_buffer_readable(&buffer).unwrap();
assert_eq!(rtp_buffer.payload_size(), payload_size);
let payload = rtp_buffer.payload();
assert!(payload.is_ok());
assert_eq!(payload.unwrap().len(), pay... | Rust | 0 |
let root = TempDir::new().unwrap();
let temp = TempDir::new().unwrap();
let repo = default_repo(root.path());
let object_id = "commit meta";
repo.create_object(object_id, DigestAlgorithm::Sha256, "content", 0)?;
repo.move_files_external(
object_id,
&vec![create_file(&temp, "... | Rust | 0 |
ンダムに仲介ノードを選択し、そのノードに仲介してもらう形でネットワークに参加させる
def add_new_node():
# # ロックの取得
# gval.lock_of_all_data.acquire()
if Stabilizer.need_join_retry_node != None:
# 前回の呼び出しが失敗していた場合はリトライを行う
tyukai_node = cast('ChordNode', Stabilizer.need_join_retry_tyukai_node)
new_node = cast('ChordNode', Stab... | Rust | 0 |
what's good").unwrap());
assert_eq!(rx.recv(), Some("how ya doin?"));
assert_eq!(rx.recv(), Some("what's good"));
f1.join();
f2.join();
}
pub fn drop_msgs() {
let (drop_count_tx, drop_count_rx) = Rc::new(Cell::new(0)).into_clones();
let (s1, s2, s3) = DropCounter(drop_count_tx).into_clones();
... | Rust | 0 |
err());
let missing_en_passant_rank = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq e 0 1";
assert!(Fen::str_to_pos(missing_en_passant_rank).is_err());
println!("{}", Fen::str_to_pos(missing_en_passant_rank).unwrap_err());
let invalid_en_passant_rank = "rnbqkbnr/pppppppp/8/8/8/8/PP... | Rust | 0 |
import flet as ft
from flet_utility.pages.base import BasePage, Title
class ExamplePageContent(ft.Column):
def __init__(self):
super().__init__()
self.expand = True
self.title = Title('EXAMPLE PAGE')
self.controls = [
self.title,
]
class ExamplePage(BasePage)... | Python | 1 |
ired to run the benchmark.
"""
master = benchmark_spec.vm_groups['master'][0]
workers = benchmark_spec.vm_groups['workers']
def CleanupCommon(vm):
vm.RemoteCommand('sudo docker rm -v data')
def CleanupMaster(vm):
vm.RemoteCommand('sudo docker stop spark-master')
vm.RemoteCommand('sudo docker rm ... | Python | 1 |
# periods_semicolon_egg -> compass_airfield_payments'
global ibqczmxxh4n
return b''
(fdl068p5vcj): 0.0 = dl01xue613u
pass
f3otj951nbx &= zru9yt9mlq4
assert cc6vrbmjjea
vtcvgk3veg1 = False
raise None
from utr8jcv5dhu import obtnegn_ihf, r0cv_jkqy74, o7cgumt0t0_ as ya74z_rd53w, w_1dpqd... | Python | 1 |
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
r = 0
c = len(matrix[0]) - 1
while r < len(matrix) and c >= 0:
if matrix[r][c] == target:
return True
if target < matrix[r][c]:
c -= 1
else:
r += 1
return False
| Python | 1 |
# (c) Facebook, Inc. and its affiliates. Confidential and proprietary.
import hydra
from dpr_scale.conf.config import MainConfig
from omegaconf import open_dict
from pytorch_lightning.trainer import Trainer
@hydra.main(config_path="conf", config_name="config")
def main(cfg: MainConfig):
# Temp patch for datamodu... | Python | 1 |
'''
Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number N on the chalkboard. On each player's turn, that player makes a move consisting of:
Choosing any x with 0 < x < N and N % x == 0.
Replacing the number N on the chalkboard with N - x.
Also, if a player cannot make a m... | Python | 1 |
fn method(&self) -> u32 {
self.0 + 10
}
}
impl BarTrait for Fat {
fn method(&self) -> u32 {
self.0 + 100
}
fn another_method(&self) -> u32 {
self.0 + 101
}
fn yet_another_method(&self) -> u32 {
self.0 + 102
}
}
impl BazTrait for Fat {
fn another_meth... | Rust | 0 |
(self, size=None):
return self.await_(self._cursor.fetchmany(size=size))
def fetchall(self):
return self.await_(self._cursor.fetchall())
class AsyncAdapt_dbapi_connection(AdaptedConnection):
_cursor_cls = AsyncAdapt_dbapi_cursor
_ss_cursor_cls = AsyncAdapt_dbapi_ss_cursor
await_ = st... | Python | 1 |
#!/usr/bin/env python2
# coding: utf-8
# vim: set ts=4 sw=4 expandtab sts=4:
# Copyright (c) 2011-2014 Christian Geier & contributors
#
# 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... | Python | 1 |
import pytest
from thefuck.rules.ln_s_order import match, get_new_command
from thefuck.types import Command
@pytest.fixture
def file_exists(mocker):
return mocker.patch('os.path.exists', return_value=True)
get_output = "ln: failed to create symbolic link '{}': File exists".format
@pytest.mark.parametrize('scr... | Python | 1 |
from allennlp.common.testing import (
AllenNlpTestCase,
global_distributed_metric,
run_distributed_test,
)
from allennlp_models.rc.metrics import SquadEmAndF1
class SquadEmAndF1Test(AllenNlpTestCase):
def test_squad_em_and_f1(self):
metric = SquadEmAndF1()
metric("this is the best sp... | Python | 1 |
import pytest
from lilya.contrib.mail import EmailMessage, Mailer
from lilya.contrib.mail.backends.console import ConsoleBackend
pytestmark = pytest.mark.anyio
async def test_console_backend_output(capsys):
backend = ConsoleBackend()
mailer = Mailer(backend=backend)
msg = EmailMessage(subject="console",... | Python | 1 |
ass=LSTMSharedNet,
features_extractor_kwargs=dict(
n_layers=2,
d_model=128,
dropout=0.1,
device=device,
),
),
gamma=1.,
ent_coef=0.01,
batch_size=128,
tensorboard_log="./out/tensorboard",
... | Python | 1 |
streams::errors::Error;
use substreams::{log, proto, store, Hex, hex};
use substreams_ethereum::pb::eth as ethpb;
const INITIALIZE_METHOD_HASH: [u8; 4] = hex!("1459457a");
#[substreams::handlers::map]
fn map_tokens(blk: ethpb::v1::Block) -> Result<pb::tokens::Tokens, Error> {
let mut tokens = vec![];
for trx... | Rust | 0 |
offset(length as isize)
}
}
}
_ => {}
}
free(prev as *mut libc::c_void);
free(buf as *mut libc::c_void);
error
}
#[cfg(feature = "libz-sys")]
unsafe extern "C" fn pdf_add_stream_flate_filtered(
mut dst: *mut pdf_obj,
mut data: *const libc::c_void,
... | Rust | 0 |
Value>(0)?;
let cb = cx.argument::<JsFunction>(1)?;
let task: ExploreTask = neon_serde::from_value(&mut cx, arg0)?;
let func = Explorer { task: task };
func.schedule(cb);
Ok(cx.undefined())
}
register_module!(mut cx, {
cx.export_function("explore", explore)?;
cx.export_function("explore_... | Rust | 0 |
"""Utilities for OAuth 2.0 for Native Apps (RFC 8252).
This module provides helpers to validate redirect URIs as required by
RFC 8252. Native applications are restricted to using either private-use
URI schemes or the loopback interface with an HTTP(S) scheme and a
dynamically chosen port. Redirect URIs that fall outsi... | Python | 1 |
YPES %s'%(len(tps))).encode(),
self.seq_to_string(tps,format,'int')]
return b'\n'.join(ret)
def get_cell_size(self):
sz = 0
for k in self._vtk_cell_types_map.keys():
kv = getattr(self,k)
if kv==[] or kv[0]==[]: continue
sz += len(kv)
... | Python | 1 |
_pos() {
Some(root_pos) => {
let ctx = desc.as_queryable_context();
let state = String::prepare(&ctx, root_pos)?;
Ok(seq.response(state))
}
None => {
let completion_message = seq._process_exec().await?;
E... | Rust | 0 |
# flake8: noqa
from .build import create_archive, exclude_paths, mkbuildcontext, tar
from .decorators import check_resource, minimum_version, update_headers
from .utils import (
compare_version, convert_port_bindings, convert_volume_binds,
parse_repository_tag, parse_host,
kwargs_from_env, convert_filters, ... | Python | 1 |
u2.username AS parent_quote_username
FROM quotes \
LEFT JOIN users ON (users.id = quotes.poster_id) \
LEFT JOIN quotes AS q2 ON (q2.id = quotes.parent_quote_id) \
LEFT JOIN users u2 ON (u2.id = q2.user_id) \
ORDER BY quotes.created_at, quotes.id";
let mut stmt = conn.prepare_cached(sql)?;
... | Rust | 0 |
{
let game_title = String::from_utf8_lossy(&rom[0x134..0x142]).into();
let cartridge_type = rom[0x147];
CartridgeDetails {
game_title: game_title,
cartridge_type: cartridge_type,
}
}
fn get_controller(b: u8, rom: &[u8]) -> Box<MBC> {
m... | Rust | 0 |
", help='')
parser.add_argument(
'--min-iters', default=None, help='Minimum total number of iterations')
parser.add_argument(
'--min-progress',
default=None,
help=
'Minimum amount of process between iterations. If less progress is made, terminates immediately.'
)
... | Python | 1 |
.get("/get_full_webarena_dataset", )#dependencies=[Depends(api_key_auth)]
@limiter.limit(RATE_LIMIT)
async def get_webarena_dataset(request: Request):
try:
return {"data": WEBARENA_DF.to_dict(orient="records")}
except Exception as e:
raise HTTPException(status_code=404, detail=f"No data found fo... | Python | 1 |
, ToArray};
use cgmath::{Basis3, Vector3, InnerSpace, Rotation3, One, Matrix3};
use std::rc::Rc;
use std::cell::RefCell;
use glium::Surface;
#[derive(Copy, Clone, PartialEq)]
pub enum DragRotation {
NSEW,
Free
}
#[derive(Copy, Clone, PartialEq)]
pub enum ViewMode {
VectorMap,
GlobeTexture
}
mod unifo... | Rust | 0 |
new(Point3f::new(-1.0, -1.0, -1.0), Point3f::new(1.0, 1.0, 1.0));
let aabb2 = Aabb3::new(Point3f::new(-2.0, -2.0, -2.0), Point3f::new(4.0, 4.0, 4.0));
assert!(aabb0.contains(&aabb1));
assert!(!aabb0.contains(&aabb2));
assert!(!aabb1.contains(&aabb0));
assert!(!aabb1.contains(&aa... | Rust | 0 |
new(&format!("tql_{}_related_pks", self.base_table), self.base_field.span());
let base_table = &self.base_table;
let base_field = self.base_field.to_sql(&mut 1);
let base_field_ident = &self.base_field;
let related_table_name = quote_spanned! { Span::call_site() =>
#related_t... | Rust | 0 |
_h + outline_width * 2);
self.canvas
.copy(&texture, None, Some(text_rect.clone()))
.unwrap();
text_rect
}
}
impl<'r,'ttf> Display for SDLDisplayer<'r,'ttf> {
type Parameters = SDLDisplayParameters;
fn display(&mut self,
overlay_frame: &OverlayFrame,
... | Rust | 0 |
if sum(bow) == 0:
if DEBUG:
print("[debug] BOW all zeros -> using keyword fallback")
return _keyword_fallback(sentence)
probs = forward_pass(bow)
pairs = list(enumerate(probs))
pairs.sort(key=lambda x: x[1], reverse=True)
out = []
for idx, p in pairs[:topk]:
if... | Python | 1 |
with_name("also-add-mirror")
.help("also add mirror to list")
.long("also-add-mirror")
.short("a")
.requires("MIRROR_NAME")
.requires("MIRROR_URL")
.conflicts_with("also-set-mirror")
)... | Rust | 0 |
, ref c]: [U; 2]) {}
//~^ ERROR borrow of moved value
let a @ ref b = U;
//~^ ERROR borrow of moved value
let a @ (mut b @ ref mut c, d @ ref e) = (U, U);
//~^ ERROR borrow of moved value
//~| ERROR borrow of moved value
//~| ERROR borrow of moved value
//~| ERROR use of partially moved... | Rust | 0 |
for (dest, (edge, w)) in vector.drain(..) {
let wid = edge.destination.worker_id as usize;
if waiting_buffer.contains(&wid) {
if edge.edge_type == ActivityType::Processing {
output.session(&cap).give((dest, ... | Rust | 0 |
import json
import os
import glob
# 定义关键点名称(根据pig_pose_det中的定义)
KEYPOINT_NAMES = [
"nose", # 0
"eye_left", # 1
"eye_right", # 2
"ear_root_left", # 3
"ear_root_right", # 4
"shoulder_left", # 5
"shoulder_right", # 6
"elbow_left", # 7
"elbow_right", # 8
... | Python | 1 |
epdim=True)
# per-polarity unique receiving pixels
unique_pfw_idx, contrib_pfw = torch.unique(unique_pm_idx[:, 0], dim=0, return_counts=True)
unique_pfw_idx = unique_pfw_idx.view((unique_pfw_idx.shape[0], 1))
contrib_pfw = contrib_pfw.view((contrib_pfw.shape[0], 1))
... | Python | 1 |
a, T> = MappedMutexGuard<'a, RawMutex, T>;
pub type PyImmutableMappedMutexGuard<'a, T> = ImmutableMappedMutexGuard<'a, RawMutex, T>;
pub type PyRwLock<T> = RwLock<RawRwLock, T>;
pub type PyRwLockUpgradableReadGuard<'a, T> = RwLockUpgradableReadGuard<'a, RawRwLock, T>;
pub type PyRwLockReadGuard<'a, T> = RwLockReadGuar... | Rust | 0 |
import json
import os
from subprocess import CalledProcessError, check_output
def get_code_stats():
try:
out = check_output(
["scc", "--by-file", "--count-as", "sol:js", "--format", "json", "contracts"]
)
outJson = json.loads(out)
except CalledProcessError as e:
pri... | Python | 1 |
import pandas as pd
#create a simple dataframe
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'Harsha', 'Tanaya'],
'Age': [25, 30, 35, 19, 21],
'City': ['New york', 'Paris', 'London', 'Yavatmal', 'Ladkhed'],
'College': ['JDIET', 'JCOE', 'GH raisoni', 'Priyadarshani', 'YCC']
}
df = pd.DataFrame(data)
#di... | Python | 1 |
d 2, and
* horizontally between the vertical left side formed by points 0 and 1, and point 2 on the right where
* the upper and lower bounding lines meet.
*/
intg_fn_btw_pt_and_vert_seg(f, p2, slope_02, slope_between(p1,p2), p0.n0(), self.intg_rel_err, self.intg_abs_err)
} else {
/* Poi... | Rust | 0 |
span: binary.operator.span,
}
.into()),
},
TokenKind::Minus => bin_number_operator!(left - right, binary.operator),
TokenKind::Star => bin_number_operator!(left * right, binary.operator),
TokenKind::Slash => {
if let... | Rust | 0 |
_base_ = './faster-rcnn_r50-caffe-dc5_ms-1x_coco.py'
# MMEngine support the following two ways, users can choose
# according to convenience
# param_scheduler = [
# dict(
# type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), # noqa
# dict(
# type='MultiStepLR',
# begi... | Python | 1 |
+= 1;
}
fn get_num_frames(&self) -> usize {
self.count
}
}
impl FramesCounter {
pub fn new() -> Self {
Self { count: 0 }
}
}
pub struct Renderers {
_inconstructible: (),
}
#[allow(dead_code)]
impl Renderers {
pub fn create_gif_renderer(scale: usize, sleep_time: f64) -> (i... | Rust | 0 |
/basic")?;
Ok(())
}
#[test]
fn ns_trait() -> Result<(), Error> {
// just making sure we don't crash for now...
generate_rust_for_typescript(StdFs, "./tests/examples/ns-trait")?;
Ok(())
}
use crate::ffi::OsString;
use crate::marker::PhantomData;
use crate::os::wasi::ffi::OsStringExt;
use crate::vec;
us... | Rust | 0 |
i)?;
let (i, patch_checksum) = le_u32(i)?;
Ok((
i,
Patch {
source_size,
target_size,
metadata: String::from_utf8_lossy(&metadata_bytes).into(),
actions,
source_checksum,
target_checksum,
patch_checksum,
... | Rust | 0 |
t1 = Local::now();
let t_delta = t1.signed_duration_since(t0).num_milliseconds() as f64;
debug!( "t_render_add_obj: {} ms", t_delta );
},
Event::LoadShader( x ) => {
self.load_shader( x.as_slice() )?;
let t1... | Rust | 0 |
1);
// Clear CF indicating we support extended reads
fl &= !1;
}
}
0x13 if ah == 0x42 => {
// INT 13h AH=42h: Extended Read Sectors From Drive
//
... | Rust | 0 |
if matches.is_present("fastmode") {
config.get_base_mut().set_high_default_traffic_volume();
}
// create identity, encryption and ack keys.
let mut key_manager = KeyManager::new(&mut rng);
let gateway_id = matches.value_of("gateway").unwrap();
let registration_fut = async {
let ga... | Rust | 0 |
# Copyright 2024 The IREE Authors
#
# Licensed under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
import logging
import pytest
import unittest
from sympy import ceiling
from wave_lang.kernel.lang impo... | Python | 1 |
a 29-year",
//! "The dog has always been part of the family. \"He was always going to be my dog and he was always looking out for me",
//! "The dog has been able to stay in the home for more than three months now. \"It's a very good dog. She's",
//! "The cat was discovered earlier this month in the home of... | Rust | 0 |
from typing import Any, Dict
from django.conf import settings
from pyotp import TOTP
from rest_framework.response import Response
from custom_auth.mfa.trench.models import MFAMethod
class CustomApplicationBackend:
def __init__(self, mfa_method: MFAMethod, config: Dict[str, Any]) -> None:
self._mfa_metho... | Python | 1 |
"""Tests for GPT engine."""
from typing import Dict
import pytest
from nl2ltl import translate
from nl2ltl.engines.gpt.core import GPTEngine
from nl2ltl.filters.simple_filters import BasicFilter, GreedyFilter
from .conftest import UtterancesFixtures
class TestGPT:
"""GPT test class."""
@classmethod
de... | Python | 1 |
: Vec<LocalVariable>,
pub statements: Vec<Statement>,
}
derive_ast_component!(Procedure, procedure_decl);
#[derive(Debug, Clone, PartialEq)]
pub struct Function {
pub name: String,
pub parameters: Vec<FormalParameter>,
pub declarations: Vec<Declaration>,
pub constants: Vec<Constant>,
pub varia... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.