text string | label_name string | labels int64 |
|---|---|---|
#
# ElementTree
# $Id$
#
# A simple XML tree builder, based on the ElementTree XML library.
#
# Note that this version does not support namespaces. This may be
# changed in future versions.
#
# history:
# 2004-03-28 fl created
#
# Copyright (c) 1999-2004 by Fredrik Lundh. All rights reserved.
#
# fredrik@pythonware... | Python | 1 |
e_defensive(self, 1)
my.is_wooden(self, True)
my.item_height(self, 4)
my.item_width(self, 4)
my.noise_on_dropping(self, 5)
my.normal_placement_rules(self, True)
my.on_fall_do(self, "me.on_fall()")
my.on_hit_and_now_dead_do(self, "me.on_hit_and_now_dead()")
my.on_idle_tick_freq_dice(self,... | Python | 1 |
t have a config file'
# Get correct weight if specified with shorthand
weight_url = None
if weight_filepath in WEIGHT_URL_DICT:
weight_url = WEIGHT_URL_DICT[weight_filepath]
weight_filepath = ut.grab_file_url(weight_url, appname='ibeis',
check_hash... | Python | 1 |
e plot is not needed
# Helper functions
def gcd(a, b):
while b:
a, b = b, a % b
return a
def mod_inverse(e, phi):
return pow(e, -1, phi)
def generate_large_prime(bits):
return sympy.randprime(2**(bits-1), 2**bits)
def generate_keypair_bits(bits):
p = generate_large_prime(bits//2)
q =... | Python | 1 |
bits.
/// This operation is sequentially consistent and creates happens-before edges that order
/// normal (non-atomic) loads and stores.
///
/// Inputs:
///
/// - MemFlags: Memory operation flags
/// - x: Value to be atomically stored
/// - p: An integer address type
#[allow(non_sn... | Rust | 0 |
for x in range(2, 30, 3):
print(x) | Python | 1 |
import os
import math
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
"""
The data is available from https://www.robots.ox.ac.uk/~vgg/data/flowers/102/
"""
class Flowers102DataProvider:
def __init__(self, save_path=None, train_batch_size=32, test_... | Python | 1 |
2.0, 6.0, 3.0, 7.0]);
//
let c = shuffle_m256d::<0b_1_0_0_1>(a, b).to_array();
assert_eq!(c, [2.0, 5.0, 3.0, 8.0]);
//
let c = shuffle_m256d::<0b_0_1_0_1>(a, b).to_array();
assert_eq!(c, [2.0, 5.0, 4.0, 7.0]);
//
let c = shuffle_m256d::<0b_1_1_1_1>(a, b).to_array();
assert_eq!(c, [2.0, 6.0, 4.0, 8.0])... | Rust | 0 |
//println!("Unable to fetch work item: {:?}", something);
is_running = false;
}
}
if sample % sample_frequency == 0 {
tooltrail.update_texture();
window.clear(Color::WHITE);
window.draw(&tooltrail);
window.displ... | Rust | 0 |
"""
phi_prompter.py
Defines a PromptBuilder for building Phi-2 Input/Output Prompts --> recommended pattern used by HF / Microsoft.
Also handles Phi special case BOS token additions.
Reference: https://huggingface.co/microsoft/phi-2#qa-format
"""
from typing import Optional
from models.backbones.llm.prompting.base_... | Python | 1 |
from typing import List
import numpy as np
from numba import njit, prange, types
from numba.typed import Dict as TypedDict
from numba.typed import List as TypedList
from ..data_structures import Qrels, Run
from ..metrics import get_hit_lists
@njit(cache=True)
def to_unicode(x):
"""Forces type conversion to numb... | Python | 1 |
());
while now != n {
now += T::one();
acc *= now;
fact.push(acc);
}
acc = T::one() / acc;
while now != T::zero() {
inv_fact.push(acc);
acc *= now;
now -= T::one();
}
inv_fact.push(T::one());
... | Rust | 0 |
val, POWERS_10[e as usize].low());
let rem = self_int_val % other.int_val;
Decimal::adjust_scale(rem, other.scale, self.negative)
} else {
let e = self.scale - other.scale;
debug_assert!(e > 0);
if e as u32 > MAX_PRECISION {
return Som... | Rust | 0 |
atRv<filename>flatrv-interp/src/main.rs
extern crate flatrv;
use flatrv::elf;
use flatrv::exec::{
EcallOutput, Exception, Extension, GlobalContext, Host, LowerAddressSpaceToken, Machine,
};
use nix::sys::mman::{mmap, mprotect, MapFlags, ProtFlags};
use std::{env, fs::File, io::Read};
struct TestHost {}
impl Host... | Rust | 0 |
).1.split_once('/').unwrap();
hdr.color_coords.as_mut().unwrap().green.0 =
num.parse::<f64>()? / denom.parse::<f64>()?;
continue;
}
if line.starts_with("green_y=") {
let (num, denom) = line.split_once('=').unwrap().1.split_once('/').unwrap();
... | Rust | 0 |
&str = "window.x";
/// For streams that belong to a window on the screen: absolute vertical window position on the
/// screen, integer formatted as text string. E.g. "343".
pub const PA_PROP_WINDOW_Y: &str = "window.y";
/// For streams that belong to a window on the screen: window width on the screen, integer
/// for... | Rust | 0 |
input, I>>,
{
pub fn get_serialized_atn() -> &'static str { _serializedATN }
pub fn set_error_strategy(&mut self, strategy: H) { self.err_handler = strategy }
pub fn with_strategy(input: I, strategy: H) -> Self {
antlr_rust::recognizer::check_version("0", "2");
let interpreter = Arc::new(P... | Rust | 0 |
alloc::format;
use super::*;
#[test]
fn test_context_display() {
let buf: ReadBuffer = b"1234567890ABCDEF"[..].into();
let err = EtError::new("Test").add_context_from_readbuffer(&buf);
let msg = format!("{}", err);
assert_eq!(
msg,
"Test\
... | Rust | 0 |
user must assert ``0 <= x <= 1``.
"""
super().__init__(step_mode)
def forward(self, x: torch.Tensor):
out_spike = torch.rand_like(x).le(x).to(x)
return out_spike
class WeightedPhaseEncoder(StatefulEncoder):
def __init__(self, K: int, step_mode='s'):
"""
* :ref:... | Python | 1 |
label=label)
print("Iniital state of minimal dfa: " + fin_init + '\n')
print("Final state of minimal dfa: " + ', '.join(fin_final) + '\n')
print("Minimal DFA transition table:\n")
print("{:<20}".format('States') + ''.join("{:<20}".format(i) for _, i in enumerate(alpha)))
for tab in sorted(table):
strs = [', '.jo... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
列表的基础语法使用
author: gxcuizy
date: 2018-10-17
"""
# 程序主入口
if __name__ == '__main__':
# 列表的定义
team_list = ['da_biao_guo', 'xiao_biao_mei', 'team']
print(team_list)
# 用len()输出列表长度
list_len = len(team_list)
print(list_len)
# 访问列表的元素值
# 访问第1... | Python | 1 |
# Run main event loop - wait for all tasks
print("Starting main event loop...")
# MicroPython compatible - wait for tasks individually
while self.tasks:
try:
# Wait for any task to complete (shouldn't happen in norm... | Python | 1 |
sername, mq_config.password)
mqttc.user_data_set({"mqConfig": mq_config})
mqttc.on_connect = self._on_connect
mqttc.on_message = self._on_message
mqttc.on_subscribe = self._on_subscribe
mqttc.on_log = self._on_log
# mqttc.on_publish = self._on_publish
mqttc.on_dis... | Python | 1 |
command in cmd_buf.commands.iter() {
self.process(gl, command, &cmd_buf.data_bytes, &cmd_buf.queries);
}
#[cfg(not(target_arch = "wasm32"))]
if cmd_buf.label.is_some() {
gl.pop_debug_group();
}
}
if let Some((fence, value)... | Rust | 0 |
(m)
}
);
gtmpl_fn!(
#[doc = r#"Given string, start, and length, return a substr."#]
fn substring(start: i64, len: i64, s: String) -> Result<String, FuncError> {
let from = if start < 0 { 0 } else { start as usize };
let to = if len < 0 { s.len() } else { len as usize };
if from > to... | Rust | 0 |
_char(s1, s2, s3, s1_pos+1, s2_pos, s3_pos+1)
} else if s2_pos < s2.len() && s3[s3_pos] == s2[s2_pos] {
Self::match_char(s1, s2, s3, s1_pos, s2_pos+1, s3_pos+1)
} else {
false
}
}
pub fn is_interleave(s1: String, s2: String, s3: String) -> bool {
if s1.len(... | Rust | 0 |
::test]
async fn config_validate_failure_no_version() -> Result<()> {
let mock = ExecMock::boxed()?;
let mut config = ConfigBuilder::default()
.name("name")
.file("file")
.list(ConfigListFileBuilder::default().build()?)
.build()?;
config.set_pl... | Rust | 0 |
mode:
continue
yield model
def set_active(self, model_id: str, is_active: bool) -> None:
"""Set the active status of a model"""
if model_id not in self._models:
logger.error(f"Cannot set active status: model {model_id} not found")
raise ModelNotF... | Python | 1 |
_interner() -> ThreadedRodeo {
ThreadedRodeo::with_hasher(Hasher::default())
}
/// A read-only view of a [`Rodeo`] or [`ThreadedRodeo`] that allows contention-free access to interned strings, both
/// key to string resolution and string to key lookups.
///
/// The hasher is the same as the Rodeo or ThreadedRodeo t... | Rust | 0 |
(v)
}
}
impl From<Weight> for u64 {
fn from(w: Weight) -> Self {
w.0
}
}
impl fmt::Display for Weight {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
#[cfg(test)]
mod tests {
use super::{Tally, TallyError, TallyResult, Weight};
use ... | Rust | 0 |
// 때문에 당장은 이 경우는 생략한다.
Frame::Array(_val) => unreachable!(),
}
Ok(())
}
/// 십진수 프레임을 스트림에 쓴다.
async fn write_decimal(&mut self, val: u64) -> io::Result<()> {
use std::io::Write;
// 값을 문자열로 변환한다.
let mut buf = [0u8; 20];
let mut buf = Cursor::new... | Rust | 0 |
from .convbn import ConvBN2d
__all__ = ["PointwiseConvBN2d"]
class PointwiseConvBN2d(ConvBN2d):
"""Conv2d + BatchNorm, restricted to pointwise convolution."""
def __init__(
self,
in_channels: int,
out_channels: int,
*, groups: int = 1,
padding_mode... | Python | 1 |
_W { w: self } }
}<reponame>jettr/tock<filename>chips/msp432/src/usci.rs
//! (enhanced) Universal Serial Communication Interface (USCI)
use kernel::common::registers::{register_bitfields, register_structs, ReadOnly, ReadWrite};
use kernel::common::StaticRef;
pub const USCI_A0_BASE: StaticRef<UsciARegisters> =
uns... | Rust | 0 |
udio_filters>` or list of
audio filters, or None to remove the audio filter.
`replace`
If True, the audio filter replaces the current audio filter immediately,
changing currently playing and queued sounds. If False, the audio
filter will be used the next time a sound is played or qu... | Python | 1 |
pted_blocks = []
decrypted_blocks = []
for block in blocks:
encrypted_block = s_des_encrypt(block, key1, key2,ip ,ip_inv)
decrypted_block = s_des_decrypt(encrypted_block, key1, key2, ip,ip_inv)
encrypted_blocks.append(encrypted_block)
decrypted_blocks.append(decrypted_block)
... | Python | 1 |
from tkinter import Tk, Toplevel
from .base import BaseWindow
from . import utilities as utils, system_config
class App(BaseWindow):
_main_app = None
def __init__(
self,
title="guizero",
width=500,
height=500,
layout="auto",
bg=None,
visible=True... | Python | 1 |
import numpy as np
from typing import List
from ..baseJointInterface import BaseJointInterface
class GripperInterface(BaseJointInterface):
def __init__(self, client, body_id, joint_names : List[str], mimic_config :dict, default_pose : np.ndarray):
super().__init__(client, body_id, joint_names, defaul... | Python | 1 |
req, self.auth)?;
// --
let github_response = crate::adapters::fetch_async(request).await?;
// --
if github_response.is_success() {
Ok(crate::adapters::to_json_async(github_response).await?)
} else {
match github_response.status_code() {
... | Rust | 0 |
#!/usr/bin/env python3
"""Unit tests for the common module."""
import unittest
from unittest.mock import patch
from codemcp.common import normalize_file_path
class CommonTest(unittest.TestCase):
"""Test for functions in the common module."""
def test_normalize_file_path_tilde_expansion(self):
"""T... | Python | 1 |
sign_type_t, sgx_quote_t, sgx_report_data_t,
sgx_spid_t, sgx_target_info_t,
};
pub use self::sgx_attestation_agent::SgxAttestationAgent;
pub use self::sgx_quote::SgxQuote;
use crate::{ParameterStore, TextureNode, TextureTarget};
use nannou::wgpu::{Device, TextureView};
use nannou::window::Window;
use nannou::{App,... | Rust | 0 |
_presets:
index = self._presets.index(values)
self._curve_row.set_button_value(index)
self._curve_row.set_slider_value(value, sindex)
def reset(self, *_) -> None:
self._cm.set_setting(0, "handbrake-direction")
self._cm.set_setting(0, "handbrake-mode")
self._cm.... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2024-09-15 23:31:59
# @Author : Litles (litlesme@gmail.com)
# @Link : https://github.com/Litles
# @Version : 1.0
import os
import re
import statistics
from collections import defaultdict
from func_lib import (
generate_dict_file_with_freq, load_word_fr... | Python | 1 |
name} tidak ada\n")
t.sleep(3)
else:
while True:
tanya = input(f"\nApakah anda ingin menghapus barang {cek[0]} : ")
t.sleep(1.5)
if tanya.lower() == "ya" or tanya.lower() == "yes":
print("\nMenghapus...\n", end="\r")
... | Python | 1 |
__title__ = "preshed"
__version__ = "3.0.9"
__summary__ = "Cython hash table that trusts the keys are pre-hashed"
__uri__ = "https://github.com/explosion/preshed"
__author__ = "Explosion"
__email__ = "contact@explosion.ai"
__license__ = "MIT"
__release__ = True
| Python | 1 |
pub const __NFTNL_OBJ_MAX: c_uint = 17;
pub const NFTNL_OBJ_CTR_PKTS: c_uint = 16;
pub const NFTNL_OBJ_CTR_BYTES: c_uint = 17;
pub const NFTNL_OBJ_QUOTA_BYTES: c_uint = 16;
pub const NFTNL_OBJ_QUOTA_CONSUMED: c_uint = 17;
pub const NFTNL_OBJ_QUOTA_FLAGS: c_uint = 18;
pub const NFTNL_OBJ_CT_HELPER_NAME: c_uint = 16;... | Rust | 0 |
# -*- coding: utf-8 -*-
import asyncio
import ccxt.pro
async def loop(exchange, symbol, n):
i = 0
while True:
try:
orderbook = await exchange.watch_order_book(symbol)
# print every 100th bidask to avoid wasting CPU cycles on printing
if not i % 100:
... | Python | 1 |
::{c::{}}};
use a::{b::{c::d}};
use a::{b::{c::{xxx, yyy, zzz}}};
// https://github.com/rust-lang/rustfmt/issues/3808
use d::{self};
use e::{self as foo};
use f::{self, b};
use g::a;
use g::{self, b};
use h::{a};
use i::a::{self};
use j::{a::{self}};
use {k::{a, b}, l::{a, b}};
use {k::{c, d}, l::{c, d}};
use b::{f:... | Rust | 0 |
to_string()).clone()
// }
// }
impl fmt::Display for SigningAlgorithm {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl From<String> for SigningAlgorithm {
// type Err = &'static str;
fn from(s: String) -> Self {
match s.to_lowercase().as_st... | Rust | 0 |
from django.contrib.gis.db.models.sql.compiler import GeoSQLCompiler as BaseGeoSQLCompiler
from django.db.backends.oracle import compiler
SQLCompiler = compiler.SQLCompiler
class GeoSQLCompiler(BaseGeoSQLCompiler, SQLCompiler):
pass
class SQLInsertCompiler(compiler.SQLInsertCompiler, GeoSQLCompiler):
def pla... | Python | 1 |
resolved_host = result.node
else:
resolved_host = address[0].decode("ascii")
port = address[1]
else: # IPv4
assert family == socket.AF_INET
resolved_host = address[0].decode("ascii")
port = address... | Python | 1 |
config.rs
use crate::error::*;
use crate::types::*;
use anyhow::{anyhow, bail};
use log::debug;
use nagios_range::NagiosRange;
use std::env;
use std::path::PathBuf;
use std::time::{Duration, Instant};
use url::Url;
use yaml_rust::yaml::{Hash, Yaml};
/// Parses a single mapping from YAML configuration.
/// This YAML is... | Rust | 0 |
r}"
# Load generated segmentation (label) image and input segmentation image.
gen_label_path = outdir_cfg / f"{cfg}_{input_ids[cfg]}_{seed}_label.png"
input_label_path = outdir_cfg / f"{cfg}_{input_ids[cfg]}_input.png"
assert gen_label_path.exists(), f"{cfg} ... | Python | 1 |
t).embed(embed);
data.create_message(&ctx, builder).await?;
Ok(())
}
async fn parse_username(
ctx: &Context,
command: &mut ApplicationCommand,
) -> DoubleResultCow<Option<Username>> {
let mut osu = None;
for option in command.yoink_options() {
match option.value {
CommandO... | Rust | 0 |
outube]".as_html(),
"<object width=\"560\" \
height=\"315\" data=\"http://www.youtube.com/embed/test\"></object>")
}
#[test]
fn sub() {
assert_eq!("[sub]Test text[/sub]".as_html(),
"<sub>Test text</sub>")
}
#[test]
fn sup() {
... | Rust | 0 |
"bspc desktop -f prev.local");
b.bind("ctrl + alt + Right", "bspc desktop -f next.local");
b.bind(
"ctrl + alt + shift + Left",
"bspc node -d prev.local --follow",
);
b.bind(
"ctrl + alt + shift + Right",
"bspc node -d next.local --follow",
);
// preselect the d... | Rust | 0 |
break
else:
print("Please enter a number")
players.append(Player(name))
names = ["Joe", "Smith", "Todd", "Jill", "Hunter", "Juliana", "Chris", "Jessica", "Nicole"]
for i in range(4):
players.append(Player(random.choice(names)))
names.remove(players[i+1].name)
all... | Python | 1 |
#!/usr/bin/env python3
import logging
import math
import time
from django.utils import timezone
import django
from oauthlib.oauth2 import OAuth2Error
from dateutil.relativedelta import relativedelta
django.setup()
from framework.celery_tasks import app as celery_app
from scripts import utils as scripts_utils
from ... | Python | 1 |
umber only. Multiple references may contain commas, e.g., \"(3, 4)\" and should be treated as two different values. If a range of references is provided, include all, e.g., \"(3-5)\" should become 3;4;5.""", json_schema_extra = { "linkml_meta": {'alias': 'references', 'domain_of': ['ScientificClaim']} })
# Model rebu... | Python | 1 |
ph_1 = draw_graph(
MLP(), input_size=(1, 128),
graph_name='MLP',
graph_dir='LR'
)
verify_result([model_graph_1])
def test_simple_ensemble(verify_result: Callable[..., Any]) -> None:
model_graph_1 = draw_graph(
EnsembleMLP(), input_size=(1, 128), depth=1,
graph_name=... | Python | 1 |
45], [45, 45, 45], [45, 45, 45]]
);
}
use na::{DefaultAllocator, Real};
use aliases::TVec;
use traits::{Alloc, Dimension};
/// The angle between two vectors.
pub fn angle<N: Real, D: Dimension>(x: &TVec<N, D>, y: &TVec<N, D>) -> N
where DefaultAllocator: Alloc<N, D> {
x.angle(y)
}
//pub fn oriented_angle<N: ... | Rust | 0 |
{
return TestResult::discard();
}
TestResult::from_bool(
x * y == y * x
)
}
}
quickcheck! {
fn identity_add(x: $uint_ty) -> bool {
x + $uint_ty::ZERO == x
}
}
quickcheck! {
fn identity_mul(x: $uint_ty) -> bool {
x * $uint_ty::one() == x
... | Rust | 0 |
VERSION,
rdb_load: Some(redisjson::type_methods::rdb_load),
rdb_save: Some(redisjson::type_methods::rdb_save),
aof_rewrite: None, // TODO add support
free: Some(redisjson::type_methods::free),
// Currently unused by Redis
mem_usage: Some(redisjson::type_methods::mem_usa... | Rust | 0 |
#!/usr/bin/env python3
"""
Jarvis Voice Assistant - Web Search Service Module
This module handles web search functionality.
"""
import webbrowser
import urllib.parse
class WebSearchService:
"""
Provides web search functionality.
"""
def __init__(self):
"""
Initialize the web sear... | Python | 1 |
=> SawItemDefaultImpl(unsafety),
ItemImpl(unsafety, implpolarity, ..) => SawItemImpl(unsafety, implpolarity)
}
}
#[derive(Hash)]
enum SawPatComponent {
SawPatWild,
SawPatBinding(BindingMode),
SawPatStruct,
SawPatTupleStruct,
SawPatPath,
SawPatTuple,
SawPatBox,
SawPatRef(Mut... | Rust | 0 |
"""Reader definitions that use back"""
from jack.core.tensorflow import TFReader
from jack.readers.implementations import nli_reader, create_shared_resources, extractive_qa_reader
@extractive_qa_reader
def modular_assertion_qa_reader(resources_or_conf=None):
from projects.knowledge_integration.qa.shared import X... | Python | 1 |
Formatter},
fs::File,
io::Write,
ops::AddAssign,
path::Path,
};
/// Table of row data.
pub struct Table<T> {
/// Data headings.
headings: Vec<String>,
/// Count data.
rows: Vec<Vec<T>>,
}
impl<T> Table<T> {
access!(rows, Vec<Vec<T>>);
/// Construct a new instance.
#[inlin... | Rust | 0 |
stdout to the response for debugging
if "stdout" in response:
return {"status": "success", "message": response.get("stdout", "")}
# Fallback
return {"status": "success"}
def generate_scene_diagnosis_code() -> str:
"""
Generates Python code that provides comprehensive diagno... | Python | 1 |
/// Add one line of key-value pairs to a passport.
fn add_line(&mut self, line: &str) {
// Split on spaces to get key:value pairs.
for kv_str in line.split(' ') {
if let Some((k,v)) = common::split2(kv_str, ":") {
self.fields.insert(String::from(k), String::from(v))... | Rust | 0 |
indy/ledger.rs
extern crate libc;
extern crate time;
extern crate serde_json;
use futures::Future;
use settings;
use utils::libindy::{
pool::get_pool_handle,
wallet::get_wallet_handle,
};
use utils::error;
use indy::ledger;
use utils::libindy::error_codes::map_rust_indy_sdk_error_code;
pub fn multisign_reque... | Rust | 0 |
import os
import argparse
from http.server import HTTPServer, SimpleHTTPRequestHandler
def run(
server_class=HTTPServer,
handler_class=SimpleHTTPRequestHandler,
port=8888,
directory=None,
):
if directory: # Change the current working directory if directory is specified
os.chdir(directory)... | Python | 1 |
downTrigger {
inner: Arc<Mutex<Inner>>,
workers: Arc<[worker::Entry]>,
}
unsafe impl Send for ShutdownTrigger {}
unsafe impl Sync for ShutdownTrigger {}
impl ShutdownTrigger {
pub(crate) fn new(workers: Arc<[worker::Entry]>) -> ShutdownTrigger {
ShutdownTrigger {
inner: Arc::new(Mutex:... | Rust | 0 |
# Input a Python list of student heights
student_heights = input("Give your student's height").split()
# number_of_students =len(student_heights)
#
# print(f"number of students are :{number_of_students}")
for n in range(0, len(student_heights)):
student_heights[n] = int(student_heights[n])
total_height=0
for he... | Python | 1 |
om_id` and `geom_uv` are set to 0.0.
pub fn cylinder_or_cone(num_segments: u32, is_cone: bool) -> Geometry {
// TODO(JP): Would be nice to do this without any reallocations.
let mut vertex_attributes = vec![];
let mut indices = vec![];
// "poles" are the centers of top/bottom faces
... | Rust | 0 |
from typing import Any, Dict, Iterator, List
import pandas as pd
from django.db.models.query import QuerySet
from .comments import Comments
from .labels import Labels
from data_export.models import ExportedExample
class Dataset:
def __init__(
self, examples: QuerySet[ExportedExample], labels: List[Label... | Python | 1 |
.val_at(0)?,
uncles_hash: serialized.val_at(1)?,
author: serialized.val_at(2)?,
state_root: serialized.val_at(3)?,
transactions_root: serialized.val_at(4)?,
receipts_root: serialized.val_at(5)?,
logs_bloom: serialized.val_at(6)?,
difficulty: serialized.val_at(7)?,... | Rust | 0 |
en you need to:
///
/// ```rust
/// # use futures_signals::map_ref;
/// # use futures_signals::signal::Mutable;
/// # fn main() {
/// # let mutable1 = Mutable::new(1);
/// # let mutable2 = Mutable::new(2);
/// #
/// let mapped = map_ref! {
/// let value1 = mutable1.signal(),
/// let value2 = mutable2.signal() =... | Rust | 0 |
rom(std::env::var("HOME")?);
config_base.push(".config/landlock");
let args: Vec<_> = env::args_os().collect();
let program_name = args.get(0).map(|s| s.to_string_lossy()).unwrap_or_default();
if args.len() < 2 {
eprintln!("usage: {} <cmd> [args]...\n", program_name);
eprintln!("Launch... | Rust | 0 |
import cmp.visitor as visitor
class Node:
def evaluate(self):
raise NotImplementedError()
class AtomicNode(Node):
def __init__(self, lex):
self.lex = lex
class UnaryNode(Node):
def __init__(self, node):
self.node = node
def evaluate(self):
value = self.node.evaluate()... | Python | 1 |
'''1.Faça uma sub-rotina que recebe duas listas A e B com dez
elementos inteiros como parâmetro. A sub-rotina deverá determinar
e mostrar o vetor C que contém os elementos que estão em A, mas
que não estão em B. A lista C deverá ser mostrada no programa
principal.'''
def diferenca(a, b):
for i in range(0,len(... | Python | 1 |
, 0x1F45, 0x1E56, 0x010C, 0x1E63, 0x3056, 0x3070, 0x04ED, 0x1FA7, 0x1EE8, 0x1F2B, 0x1B41, 0x00CA, 0x014F,
0x01D8, 0x30FA, 0x1F9D, 0x1E52, 0x00E4, 0x1FA0, 0x1F8A, 0x0103, 0x1F62, 0x1EEA, 0x04E7, 0x2224, 0x0390, 0x30D7, 0x1F92, 0x1E4C, 0x1FAC, 0x1E6A, 0x1E39,
0x0DDA, 0x1EE1, 0x021E, 0x1EC3, 0x0158, 0x1ED6, 0x011A, 0x30F7... | Rust | 0 |
perations::sign_transaction::sign_transaction;
/// Implementation for [`crate::ecalls::wallet_operation::wallet_operation`].
///
/// This processes an exchange of the following:
///
/// Request: [`SealedMessage`] of [`WalletRequest`]
///
/// Response: [`SealedMessage`] of [`WalletResponse`]
///
pub fn wallet_operation... | Rust | 0 |
import torch
from transformers import VideoMAEImageProcessor, VideoMAEForVideoClassification
import torch.nn as nn
import torchvision
import time
from .mamba_base import MambaConfig, ResidualBlock
def create_reorder_index(N, device):
new_order = []
for col in range(N):
if col % 2 == 0:
new_... | Python | 1 |
# Copyright 2013 Christoph Reiter
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
"""Everything related to Ubuntu Uni... | Python | 1 |
import tkinter as tk
# Знакомство с виджетами Entry
# row=0, column=1 || row - ряд || column - колонка
# sticky=tk.W || смешает на запад то есть в лево
# sticky=tk.E || смешает на восток то есть в право
# sticky=tk.CENTER || смешает в центр
# sticky='we' || от запада до востока, то есть расстягивает с лева на право
#... | Python | 1 |
from __future__ import annotations
from hypothesis import given
import polars as pl
from polars.testing.parametric.strategies.data import categories, data
@given(cat=categories(3))
def test_categories(cat: str) -> None:
assert cat in ("c0", "c1", "c2")
@given(cat=data(pl.Categorical, n_categories=3))
def test... | Python | 1 |
false
}
}
}
#[no_mangle]
pub extern "C" fn pipeline_info(metadata: *mut *const u8, metadata_size: *mut usize) -> bool {
lazy_static! {
static ref MESSAGE: Vec<u8> = divvun_schema::util::message_to_vec(module_metadata! {
name: "cg3",
version: "0.0.1",
comm... | Rust | 0 |
: &str = "✔";
pub struct ConsoleOutput {
buffer: String,
verbose: bool,
}
pub fn diff_text(expected: &str, actual: &str) -> (String, String, String) {
let expected = format!("{:?}", expected);
let expected = &expected[1..expected.len() - 1];
let actual = format!("{:?}", actual);
let actual = &... | Rust | 0 |
import os
from dotenv import load_dotenv
load_dotenv()
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'dev'
DEBUG = os.environ.get('FLASK_ENV') == 'development'
# API Keys
OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY')
PERPLEXITY_API_KEY = os.environ.get('PERPLEXITY_API_KEY')
... | Python | 1 |
LS_ENABLED_TIME_RANGES = os.getenv(
"SUMMARY_DEEPDRILLS_ENABLED_TIME_RANGES",
default="last_30_days,last_7_days,previous_day",
)
SUMMARY_DEEPDRILLS_ENABLED_TIME_RANGES = list(
map(lambda x: x.strip(), SUMMARY_DEEPDRILLS_ENABLED_TIME_RANGES.split(","))
)
for enabled_time_range in SUMMARY_DEEPDRILLS_ENABLED_T... | Python | 1 |
alse)
)
client.add_event_handler(dispatcher.handle_command, events.MessageEdited())
modules.register_all(to_load)
modules.send_config(db, babelfish)
await modules.send_ready(client, db, allclients)
if first:
try:
import git
repo = git.Repo()
... | Python | 1 |
fn run(rx: Receiver<Message>, tx: Sender<Frame>) {
let vm = Arc::new(Mutex::new(VM::new()));
let rb = RingBuffer::<Sample>::new(RECORD_BUFFER_CAPACITY);
let (producer, consumer) = rb.split();
let player = {
let vm = Arc::clone(&vm);
Worker::spawn("Player", CHANNEL_CAPACITY, move |i, o... | Rust | 0 |
pub shutdown_timeout: u64,
}
impl Default for ServiceConfig {
fn default() -> Self {
Self {
listen: default_service_listen(),
server_hostname: default_service_server_hostname(),
workers: default_service_workers(),
backlog: default_service_backlog(),
... | Rust | 0 |
andint(0, 2)
# 快答奖励
ex_moneys = 0
ex_message = ""
if cnt == timu_num and quirky != 0:
if cost_time < 20:
return await bot.send(event, message=f"作弊达咩哟~")
ex_moneys =... | Python | 1 |
signature::Signature;
pub use std::convert::{TryFrom, TryInto};
/// Represents a type which has not been decided upon yet
#[derive(Debug, Hash, PartialEq, Eq, Clone, Serialize, Deserialize)]
pub enum Todo {}
<reponame>stevebob/werewolf-game<gh_stars>1-10
use std::cell::RefCell;
use std::ops::DerefMut;
use game::*;
us... | Rust | 0 |
pub start_gas: U256,
/// Recipient
/// If None, then this is a contract creation
pub to: Option<H160>,
/// Transferred value
pub value: U256,
/// Data
pub data: Vec<u8>,
/// The standardised V field of the signature.
pub v: U256,
/// The R field of the signature.
pub r: ... | Rust | 0 |
Rectangle(*) => TEXTURE_RECTANGLE_ARB,
}
}
}
/// A texture.
///
/// TODO: Include client storage here for `GL_CLIENT_STORAGE_APPLE`.
pub struct Texture {
/// The OpenGL texture ID.
priv id: GLuint,
/// The texture target.
target: TextureTarget,
/// Whether this texture is weak. Weak tex... | Rust | 0 |
r"""
___ ____
/ _ \__ _| __ ) ___ _ __ __ _ _ __ ______ _
| | | \ \/ / _ \ / _ \| '_ \ / _` | '_ \|_ / _` |
| |_| |> <| |_) | (_) | | | | (_| | | | |/ / (_| |
\___//_/\_\____/ \___/|_| |_|\__,_|_| |_/___\__,_|
Any question? 0xbonanza@gmail.com
"""
import time
import requests
import json
import wins... | Python | 1 |
AF_EMPTY_T => String::from("(empty leaf)"),
_ => String::from("(unprintable)"),
};
match value.type_ {
sr_type_e_SR_UNKNOWN_T
| sr_type_e_SR_CONTAINER_T
| sr_type_e_SR_CONTAINER_PRESENCE_T
| sr_type_e_SR_LIST_T
| sr_type_e_SR_LEAF_EMPTY_T => println!("{}", v),
... | Rust | 0 |
'sweep': 'x',
'lon_0': -89.5,
'a': 6378169.00,
'b': 6356583.80,
'h': 35785831.00,
'units': 'm'}
geos_area.crs = CRS(proj_dict)
expected = (0.15185342867090912, 0.15133555510297725)
np.testing.assert_allclose(expected,
... | Python | 1 |
Arg,
}, // 0x3C
I64Store16 {
memarg: MemArg,
}, // 0x3D
I64Store32 {
memarg: MemArg,
}, // 0x3E
MemorySize {
size: u32,
}, // 0x3F
MemoryGrow {
grow: u32,
}, // 0x40
// Numeric Instructions
I32Const {
val: i32,
}, // 0x41
I64Co... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.