text string | label_name string | labels int64 |
|---|---|---|
self if/when we find an alternative peer
// with more work than ourselves
// we should not need to reset the header head here
return false;
}
}
true
}
fn headers_received(&self, bhs: Vec<core::BlockHeader>, addr: SocketAddr) {
info!(
LOGGER,
"Received block headers {:?} from {}",
bhs.... | Rust | 0 |
: reloc_sink.func_relocs,
address_map: address_transform,
value_labels_ranges: ranges.unwrap_or(Default::default()),
stack_slots: context.func.stack_slots,
traps: trap_sink.traps,
unwind_info,
stack_maps: stack_map_sink.finish(),
})
}
}... | Rust | 0 |
;
use std::io::{self, prelude::*, BufReader};
#[macro_use]
extern crate text_io;
fn part1(filename: &str) -> io::Result<usize> {
let file = File::open(filename)?;
let reader = BufReader::new(file);
let lines: Vec<String> = reader
.lines()
.map(|line| line.expect("Could not parse line"))
... | Rust | 0 |
lo).into(), lng)),
&Point::from(LatLng::new(Rad(lat.hi).into(), lng)),
)
}
impl Rect {
/// contains reports whether this Rect contains the other Rect.
pub fn contains(&self, other: &Self) -> bool {
self.lat.contains_interval(&other.lat) && self.lng.contains_interval(&other.lng)
}
/... | Rust | 0 |
t detections to improve Bot Management.
[Learn more about JavaScript Detections](https://developers.cloudflare.com/bots/reference/javascript-detections/).
"""
suppress_session_score: bool
"""
Whether to disable tracking the highest bot score for a session in the Bot
Management cookie.
"""
... | Python | 1 |
test_distance_inside_normal() {
let dis = Point([2.0, 2.0]).distance_to_space(&[0.0, 0.0], &[3.0, 3.0]);
assert_eq!(dis, 0.0);
}
#[test]
fn distance_to_half_space() {
let dis = Point([-2.0, 0.0])
.distance_to_space(&[0.0, f64::NEG_INFINITY], ... | Rust | 0 |
from sqlalchemy import (
Column,
DateTime,
Enum,
ForeignKey,
Integer,
PickleType,
String,
Table,
)
from sqlalchemy.orm import registry, relationship
from pyrelay.nostr.event import EventKind, NostrEvent, NostrTag
mapper_registry = registry()
event = Table(
"event",
mapper_regi... | Python | 1 |
let handle = loader.load(name, format, progress, storage);
(true, AssetPrefab::Handle(handle))
}
slot => (false, slot),
};
*self = next;
Ok(ret)
}
}
/// Helper structure for loading prefabs.
///
/// The recommended way of using this from `State`s... | Rust | 0 |
_bindings
.write_to_file(nl_out_path.join("libnl.rs"))
.expect("Unable to write libnl bindings");
}
#[cfg(not(target_os = "linux"))]
fn main() {}
use crate::elasticsearch::Elasticsearch;
use crate::executor_manager::get_executor_manager;
use crate::gucs::ZDB_DEFAULT_ROW_ESTIMATE;
use crate::utils::find... | Rust | 0 |
)),
("op", InvalidOp { op, .. }) => Ok(Val::from(op.as_ref())),
("rhs", InvalidOp { rhs, .. }) => Ok(Val::from(rhs.as_ref())),
("file", IoError { file, .. }) => Ok(Val::from(file.as_ref())),
("reason", IoError { reason, .. }) => Ok(Val::from(reason.as_ref(... | Rust | 0 |
<gh_stars>0
///
pub mod decode;
///
pub mod index;
/// The offset to a chunk as seen relative to the beginning of the file containing it.
pub type Offset = u64;
/// A chunk file providing a table into the parent data.
pub struct Index {
/// Validated chunks as defined by their index entries.
///
/// Note ... | Rust | 0 |
args_format=arg_names.iter().map(|x| format!("{}: {{:?}}", x)).collect::<Vec<_>>().join(", "),
args_from_data=call_args.iter().map(|x| format!("&{}", x)).collect::<Vec<_>>().join(", "),
);
method_call = format!( r#"
{method_id} => {{
trace.push(format!("{func_name}({args_format})", ... | Rust | 0 |
amed>()
.eq(["a","b","e"].iter().cloned())
);
let _:GetFieldType<Renamed,FP!(a)>;
let _:GetFieldType<Renamed,FP!(b)>;
let _:GetFieldType<Renamed,FP!(e)>;
}
////////////////////////////////////////////////////////////////////////////////
#[derive(Structural,Clone)]
struct Foo<T>{
#[... | Rust | 0 |
0 => Ok(None),
n => {
let first = JoinSplit::zcash_deserialize(&mut reader)?;
let mut rest = Vec::with_capacity((n - 1) as usize);
for _ in 0..(n - 1) {
rest.push(JoinSplit::zcash_deserialize(&mut reader)?);
}
... | Rust | 0 |
#!/usr/bin/env python3
from typing import List
def solve_n_quees(n: int) -> List[List[int]]:
cols = set()
# right up
ru_diag = set()
# right down
rd_diag = set()
res = []
board = [['.'] * n for i in range(n)]
def backtrack(row):
if row == n:
board_copy = ["".join(... | Python | 1 |
or R {
type Target = crate::R<EVENT_REQ_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<EVENT_REQ_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<EVENT_REQ_SPEC>) -> Self {
R(reader)
}
}
#[doc = "DC Latch event\n\nValue on ... | Rust | 0 |
'''5 - Crie um programa que solicite ao usuário a idade de várias pessoas. Armazene apenas idades válidas (entre 0 e 120) em uma lista. Use for, try/except, continue para ignorar entradas inválidas, e break para encerrar o programa se o usuário digitar "fim". No final, exiba a lista das idades válidas.'''
def coletar_... | Python | 1 |
CellInputVecIterator {
fn len(&self) -> usize {
self.2 - self.1
}
}
impl ::core::iter::IntoIterator for CellInputVec {
type Item = CellInput;
type IntoIter = CellInputVecIterator;
fn into_iter(self) -> Self::IntoIter {
let len = self.len();
CellInputVecIterator(self, 0, len)... | Rust | 0 |
pub(crate) use libloragw_sx1302_sys as llg;
// Ensures we only have 0 or 1 gateway instances opened at a time.
// This is not a great solution, since another process has its
// own count.
static GW_IS_OPEN: AtomicBool = AtomicBool::new(false);
/// A LoRa concentrator.
pub struct Concentrator {
/// Used to preven... | Rust | 0 |
from langchain_huggingface import HuggingFaceEmbeddings
EmbeddingsModel = HuggingFaceEmbeddings
def get_embedding_model(
model_id: str,
device: str = "cpu",
) -> EmbeddingsModel:
"""Gets an instance of a HuggingFace embedding model.
Args:
model_id (str): The ID/name of the HuggingFace embedd... | Python | 1 |
, 5, 4, 3, 2, 1, 0]);
}
//! zebra-checkpoints arguments
//!
//! For usage please refer to the program help: `zebra-checkpoints --help`
#![deny(missing_docs)]
#![allow(clippy::try_err)]
use structopt::StructOpt;
/// zebra-checkpoints arguments
#[derive(Debug, StructOpt)]
pub struct Args {
/// Path to zcash-cli co... | Rust | 0 |
_input(&self, btn_st: ElementState, btn: MouseButton) {
match btn {
MouseButton::Left => { match btn_st {
ElementState::Pressed =>
printlnc!(teal: "Left mouse button pressed on background."),
ElementState::Released =>
printlnc!(cyan: ... | Rust | 0 |
from fvcore.common.config import CfgNode as _CfgNode
class CfgNode(_CfgNode):
"""
The same as `fvcore.common.config.CfgNode`, but different in:
1. Use unsafe yaml loading by default.
Note that this may lead to arbitrary code execution: you must not
load a config file from untrusted sources b... | Python | 1 |
e(num_th) must be int"
df = pd.DataFrame([], columns=["pro", "fpr", "threshold"])
binary_amaps = np.zeros_like(amaps, dtype=np.bool)
min_th = amaps.min()
max_th = amaps.max()
delta = (max_th - min_th) / num_th
for th in np.arange(min_th, max_th, delta):
binary_amaps[amaps <= th] = 0
... | Python | 1 |
bel 54", "Label 55", "Label 56"
]
labels = []
for i in range(8):
row_labels = []
for j in range(7):
label_text = label_texts[i * 7 + j]
label = create_label_with_border(frame3, label_text, i, j)
row_labels.append(label)
labels.append(row_labels)
# Frame 4 : Affichage des données M... | Python | 1 |
er.step()
scheduler.step()
checkpoint_dict = {
"optimizer": optimizer.state_dict(),
"scheduler": scheduler.state_dict()
}
optimizer = optim.SGD(model, 0.1)
scheduler = WarmupScheduler(optimizer, 5, 0.05, 0.1, [6, 14], 0.5)
optimizer.load_state_dict(checkpoint_dict["optimize... | Python | 1 |
use std::fs::{create_dir_all, read_dir, rename};
use std::hash::Hash;
use std::mem;
use std::path::PathBuf;
use std::sync::{Arc, RwLock};
pub const TOMBSTONE: &str = "<<>>";
pub const ESCAPED_TOMBSTONE: &str = "<<>><<>>";
lazy_static! {
static ref TOMBSTONE_REGEXP: Regex = Regex::new(TOMBSTONE).expect("regexp");
... | Rust | 0 |
&MultiplexedRequest| { &m.request },
|m: &mut MultiplexedRequest| { &mut m.request },
));
::protobuf::reflect::MessageDescriptor::new::<MultiplexedRequest>(
"MultiplexedRequest",
fields,
file_descriptor_prot... | Rust | 0 |
assert_eq!(
poscar.unscaled_cart_positions(),
Cow::from(UNSCALED_CARTS),
"{}", dbg,
);
assert_eq!(
poscar.scaled_cart_positions(),
Cow::from(SCALED_CARTS),
"{}", dbg,
... | Rust | 0 |
]:
"""Test custom post processing of match data"""
if (
match_dict[self.MATCH_RESULT] is True
and "NEUTRAL_MEDICAL_VIRUS" in match_dict[self.NEUTRAL_MATCH_FIELD]
and "NEUTRAL_INSECT" in match_dict[self.NEUTRAL_MATCH_FIELD]
):
match_dict[self.MATCH_... | Python | 1 |
def suma(*args):
total = 0
for i in args:
total += i
return total
compus = [1,3,4,5,1,3,2]
print(suma(3,2,5))
def printes_users(**user):
data = list(user.items())
mensaje = "Bienvenido " + data[0][1]
if(data[1][1] == "Admin"):
mensaje += " Admin"
print(mensaje)
printes_user... | Python | 1 |
import gym
import rlbench.gym
env = gym.make('reach_target-state-v0', render_mode='human')
training_steps = 120
episode_length = 40
for i in range(training_steps):
if i % episode_length == 0:
print('Reset Episode')
obs = env.reset()
obs, reward, terminate, _ = env.step(env.action_space.sample(... | Python | 1 |
# -*- coding: utf-8 -*-
# Copyright 2025 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... | Python | 1 |
(&ChannelsReportResponseBody { channels, reports }),
"etag",
format!(r#""{}""#, etag),
))
}
async fn youtube_channel_subscriber(
id: String,
start_at: Option<DateTime<Utc>>,
end_at: Option<DateTime<Utc>>,
pool: &PgPool,
) -> Result<ChannelsReport, Rejection> {
let rows = sqlx::q... | Rust | 0 |
d as i64 - mean).abs() < 1000);
println!("mean:{} buckets:{:?} pass:{}", mean, buckets, pass);
assert!(pass);
}
#[test]
fn test_edges_large() {
let distr = UniformInt::new_inclusive(u32::MIN, u32::MAX);
println!("distr: {:#x?}", distr);
let mut rng = crate::new();
let mut zeros = 0;
for _ in 0..10000 {
let va... | Rust | 0 |
current_block = 2;
break;
}
if socket::bind4(
(*d).s1 - 1i32,
(*d).localip.as_mut_ptr(),
1025u32.wrapping_add(random::random(64510u32)) as (u16),
) == 0i32
{
current_block = 7;
... | Rust | 0 |
st:
atlas_resolution = int(int(atlas.tlm_atlas_lightmap_resolution) / int(scene.TLM_EngineProperties.tlm_resolution_scale) * int(supersampling_scale))
utilized = 0
atlasUsedArea = 0
for obj in bpy.context.scene.objects:
if obj.TLM_ObjectProperties.tlm_mesh_lightmap_use:
... | Python | 1 |
as *const _) }
}
}
#[cfg(feature = "rtic")]
unsafe impl Send for Instance {}
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - FIFO Access Port"]
pub fifo: FIFO,
_reserved1: [u8; 252usize],
#[doc = "0x100 - FIFO size and remaining slots open values"]
pub fifoptr: ... | Rust | 0 |
"""Run depth first search on an undirected graph. O(E + V) time."""
# https://algs4.cs.princeton.edu/41graph
class DepthFirstSearch:
"""Gets vertices in graph connected to the source vertex (src_node) O(E + V)"""
def __init__(self, graph_undirected, src_node):
"""Gets vertices in graph connected to t... | Python | 1 |
ive(Clone, Copy, Default)]
struct ShaderData {
reflectance_texture_id: Option<BindlessId>,
}
#[derive(Clone, Copy, Default)]
struct GeometryAttribRequirements {
normal_buffer: bool,
uv_buffer: bool,
alias_table: bool,
}
#[derive(Clone, Copy, Default)]
struct GeometryAttribData {
normal_buffer: Opt... | Rust | 0 |
p_forms(G, 1) == 0:
verbose("no wt 1 cusp forms for N=%s, chi=%s by Riemann-Roch" % (N, chi._repr_short_()), level=1)
return []
except NotImplementedError:
pass
from sage.modular.modform.constructor import EisensteinForms
chi = chi.minimize_base_ring()
K = chi.base_ring(... | Python | 1 |
KEY_hebrew_gimel: u32 = 0x0ce2; /* U+05D2 HEBREW LETTER GIMEL */
pub const KEY_hebrew_gimmel: u32 = 0x0ce2; /* deprecated */
pub const KEY_hebrew_dalet: u32 = 0x0ce3; /* U+05D3 HEBREW LETTER DALET */
pub const KEY_hebrew_daleth: u32 = 0x0ce3; /* deprecated */
pub const KEY_hebrew_he: u32 = 0x0ce4; /* U+05D4 HEBREW LET... | Rust | 0 |
`#[start]` attribute. This is an error because there must be a unique entry
point into a Rust program. Example:
```
#![feature(start)]
#[start]
fn foo(argc: isize, argv: *const *const u8) -> isize { 0 } // ok!
```
"##,
E0197: r##"
Inherent implementations (one that do not implement a trait but provide
methods assoc... | Rust | 0 |
();
println!("{}", String::from_utf8_lossy(&plain_text));
Ok(())
}
fn array_from_base64<const N: usize>(input: &str) -> [u8; N] {
let mut arr = [0u8; N];
base64::decode_config_slice(input, base64::STANDARD, &mut arr).unwrap();
arr
}
<gh_stars>0
use rayon::iter::{Map, ParallelIterator};
pub trait... | Rust | 0 |
try:
import anywidget # noqa: F401
except ImportError:
# When anywidget isn't available, create stand-in JupyterChart class
# that raises an informative import error on construction. This
# way we can make JupyterChart available in the altair namespace
# when anywidget is not installed
class Ju... | Python | 1 |
import paddle
import numpy as np
import pickle
import sys
f = open('result.txt', 'w')
f.write("======local_vis: \n")
try:
paddle.enable_static()
exe = paddle.static.Executor(paddle.CPUPlace())
# test dygraph
[prog, inputs, outputs] = paddle.static.load_inference_model(
path_prefix="pd_model_dy... | Python | 1 |
((self.rate as f64 * PAL_RATE) / (self.factor * tempo * 100.0)) as usize;
}
pub fn reset_voice(&mut self, voice: usize) {
let v = &mut self.voices[voice];
v.pos = 0.0;
v.period = 0.0;
v.note = 0;
v.pan = 0;
v.vol = 0;
v.smp = 0;
v.end = 0;
... | Rust | 0 |
e_dir.join("stderr1.txt"))
.wrap_err(BitcoindError::TestInstance)?;
let bitcoind_child = Command::new(&self.conf.bitcoind_path)
.arg(&self.datadir_arg)
.args(args)
.stdout(stdout)
.stderr(stderr)
.spawn()
.wrap_err(BitcoindError... | Rust | 0 |
from pip._vendor import requests
from bs4 import BeautifulSoup
import csv
# Set the URL
my_url = "https://friends.fandom.com/wiki/Episode_List"
descriptions_url = "https://friends.fandom.com/wiki/List_of_Friends_Episodes"
# Make background request in python
data = requests.get(descriptions_url)
soup = BeautifulSoup(... | Python | 1 |
, 3), (17, 5), (18, 12 + DRAM_BASE)]);
let expected_fregs = helper::create_fregs(vec![]);
helper::run(&mut emu, data, &expected_xregs, &expected_fregs);
assert_eq!(20 + DRAM_BASE, emu.cpu.pc);
}
<reponame>tommilligan/cargo-raze<filename>examples/vendored/non_cratesio_library/cargo/vendor/winapi-i686-pc-wi... | Rust | 0 |
# -*- coding: utf-8 -*-
# @Author: Jie Yang
# @Date: 2019-03-29 16:10:23
# @Last Modified by: Jie Yang, Contact: jieynlp@gmail.com
# @Last Modified time: 2019-04-12 09:56:12
# convert the text/attention list to latex code, which will further generates the text heatmap based on attention weights.
import numpy ... | Python | 1 |
ion is
/// re-raised during the handler.
///
/// # Arguments
///
/// * t - The argument to pass along to the condition handler.
///
/// # Return value
///
/// If a handler is found, its return value is returned, otherwise this
/// function will not return.
pub fn raise(&self,... | Rust | 0 |
// NOTE: this benchmark currently doesn't have any components because the length of a db
// read/write is not captured. Otherwise, it is quite influenced by how much data
// `T::ElectionDataProvider` is reading and passing on.
assert!(<MultiPhase<T>>::snapshot().is_none());
assert!(<MultiPhase<T>>::current_pha... | Rust | 0 |
# return
cmd = f"ai_engine 1 5 --user_data_dir={base_dir}"
json_output = {
"ai_switch": self.ai_switch,
"ai_waste_switch": self.ai_waste_switch,
"command_type": "ai_engine",
"command": cmd,
"command_description": "waste",
... | Python | 1 |
else:
failed_results.append(parsed)
except Exception as e:
failed_results.append({'error': str(e), 'operation_num': i})
# Periodic memory cleanup
if i % 10 == 0:
gc.collect()
final_memory = pr... | Python | 1 |
0xffffffff down to 0.
now: 0xffffffff_u32.wrapping_sub(self.pit.cval0.read().bits()),
}
}
}
/// A monotonic nondecreasing timer - like MonoTimer, but the resources cannot
/// be released, so the type can implement Copy.
#[derive(Clone, Copy)]
pub struct CopyableMonoTimer {
frequency: Hertz... | Rust | 0 |
cee01047effd6e7d0b5c19743",
"stdlib_folder": stdlib_path(),
"modules_folders": [modules_path()],
});
let errors = diagnostics_with_config(MoveFile::with_content("script", source), config);
assert!(errors.is_empty(), "{:#?}", errors);
}
#[test]
fn test_compile... | Rust | 0 |
val: 2,
left: Some(Rc::new(RefCell::new(TreeNode::new(3)))),
right: Some(Rc::new(RefCell::new(TreeNode::new(1)))),
}))),
})));
assert_eq!(res, invert_tree(root));
}
<filename>pkmnapi-api/tests/hm_moves.rs<gh_stars>1-10
use pkmnapi_api::responses::hm_moves::HMMoveResponseA... | Rust | 0 |
isor = 4;
}
}", |cx, failed, pt| {
let mut builder = Builder::new(pt.clone(), cx);
super::build_timer(&mut builder, cx, pt.get_by_name("tim").unwrap());
assert!(unsafe{*failed} == false);
assert!(builder.main_stmts().len() == 1);
assert_equal_source(builder.main_stmts()[0].d... | Rust | 0 |
iter().any(|d| d.name == "structopt"));
assert!(graph.nodes.iter().any(|d| d.name == "toml"));
}
// TODO: remove this and uncomment the next occurrence.
#[rustfmt::skip]
#[test]
fn render_dep_graph_self() {
let mut cfg = Config::default();
cfg.depth = Some(1);
let graph = get_dep_graph(cfg).unwrap();
... | Rust | 0 |
inner: BoxStream<'static, Result<Bytes, Box<dyn std::error::Error + Send + Sync + 'static>>>
}
}
#[tokio::test]
async fn test_wrapper() {
//
let hyper_body = HyperBody::from("foo");
let body = Body::with_hyper_body(hyper_body);
let _ = BodyWrapper {
in... | Rust | 0 |
import dns.resolver
from config import Settings
class DomainService:
def __init__(self, settings: Settings):
self.server_ip = settings.server_ip
self.deploy_domain = settings.deploy_domain
def _is_apex_domain(self, hostname: str) -> bool:
"""Check if domain is apex (no subdomain)"""
... | Python | 1 |
class Settings:
APP_NAME = 'API App 1'
VERSION = "0.0.2"
DESCRIPTION="Simple FastAPI application"
CONTACT={
"name": "Lenka Kargerová",
"url": None,
"email": "kargerova@gmail.com",
}
DOCS_URL="/"
SERVER_PATH="/app1/api"
app_settings = Settings() | Python | 1 |
e: Optional[str],
swanlab_logdir: Optional[str],
swanlab_media_dir: Optional[str],
error: Optional[ParseErrorInfo] = None,
):
"""
生成的指标信息对象
:param column_info: 此指标对应的列信息
:param metric: 此指标的数据
:param metric_buffers: 此指标的媒体数据,如果为None,表示没有媒体数据
:pa... | Python | 1 |
-> ! {
exit_qemu(QemuExitCode::Success);
}
/// This function is called on panic.
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
use core::fmt::Write;
let _ = writeln!(test_kernel_pie::serial(), "PANIC: {}", info);
exit_qemu(QemuExitCode::Failed);
}
#[derive(Eqr)]
//~^ ERROR cannot find derive mac... | Rust | 0 |
"""
此模块用于处理配置中心相关的查询,包括从不同的配置中心获取 SQL 查询语句。
本模块提供了 `get_query_sql` 函数,用于根据配置中心类型和 Apollo 应用名称获取对应的查询 SQL。支持从 Nacos 和 Apollo 配置中心获取数据。
:author: assassing
:contact: https://github.com/hxz393
:copyright: Copyright 2023, hxz393. 保留所有权利。
"""
import logging
from typing import Dict, Optional
from config.settings import SQ... | Python | 1 |
= "openat";
assert!(syscall_exists(openat));
}
}
<gh_stars>1-10
use cgmath::{Matrix4, Vector3};
// use time::Duration;
use amethyst::engine::{State, Trans};
use amethyst::context::Context;
use amethyst::config::Element;
use amethyst::ecs::{World, Entity};
pub struct HelloWorld;
impl State for HelloWorld... | Rust | 0 |
import logging
import pytest
from plenum.test.helper import checkViewNoForNodes, waitForViewChange, sdk_send_random_and_check
from plenum.test.node_catchup.helper import ensure_all_nodes_have_same_data
from plenum.test.node_request.helper import sdk_ensure_pool_functional
from plenum.test.pool_transactions.helper imp... | Python | 1 |
iming.add_time("releasing_batches"):
self.training_iteration = training_iteration
if not self.cfg.async_rl:
# in synchronous RL, we release the trajectories after they're processed by the learner
self._release_traj_tensors(batch_idx)
if not self.avai... | Python | 1 |
edtext(r"r{\color[rgb]{1,0,0}igh}t", textattrs=[text.halign.right, text.vshift.mathaxis, trafo.mirror(), trafo.scale(1.2)], arclenfromend=0.5, exclude=0.1)])
c.insert(sc, [trafo.translate(12, 12)])
# UnicodeEngine output with afm and pfm
ue_afm = text.UnicodeEngine()
c.insert(ue_afm.text(10, 9, "UnicodeEngine output (... | Python | 1 |
Self: Sized;
/// Function of converter for a generated value
fn to_data_value(&self) -> DataValue;
}
impl ForGetValueAtGeneratorType for SbrdInt {
fn get_generator_type() -> GeneratorType {
GeneratorType::GetIntValueAt
}
fn parse(s: &str) -> Result<SbrdInt, BuildError> {
SbrdInt::... | Rust | 0 |
event.wait()
yield 0
yield 1
async def handle_value(
recv_chan: trio.abc.ReceiveChannel[int],
value: int,
task_status: trio.TaskStatus,
) -> None:
task_status.started()
assert await recv_chan.receive() == value
async with agen() as recv_chan:
... | Python | 1 |
import os
from quotientai import QuotientAI
from tracing_example import (
get_article_summary,
)
from prompts import system_prompt_article_summary
from example_article import invest_ottawa_article
from dotenv import load_dotenv
load_dotenv()
quotient = QuotientAI()
def try_quotient():
article_text = invest_... | Python | 1 |
0x0;
/// Low level.
pub const LO: u32 = 0x1;
/// Medium level.
pub const MED: u32 = 0x2;
/// High level.
pub const HI: u32 = 0x3;
}
/// Interupt mode
#[allow(non_upper_case_globals)]
pub mod adc_ch_intmode {
/// Interrupt on conversion complete.
pub const COMPLETE: u32 = 0x0;
/// Interrupt ... | Rust | 0 |
import shutil
import subprocess
from typing import Iterator, Union
def is_installed(lib_name: str) -> bool:
lib = shutil.which(lib_name)
if lib is None:
return False
return True
def play(
audio: Union[bytes, Iterator[bytes]],
notebook: bool = False,
use_ffmpeg: bool = True
) -> Non... | Python | 1 |
'''Реализуйте класс Rectangle, описывающий прямоугольник. При создании экземпляра класс должен принимать два аргумента в следующем порядке:
length — длина прямоугольника
width — ширина прямоугольника
Экземпляр класса Rectangle должен иметь два атрибута:
length — длина прямоугольника
width — ширина прямоугольника
Клас... | Python | 1 |
v': 'gunjalgondiska', 'tg': 'Гунҷала Гондӣ', 'vec': 'gunjala', 'zh': '贡贾拉贡德文', 'zh-Hans': '贡贾拉贡德文', 'zu': 'isi-Gunjala Gondi'},
'Gonm': {'bs': 'masaram gondi pismo', 'bs-Cyrl': 'масарам гонди писмо', 'bs-Latn': 'masaram gondi pismo', 'en': 'Masaram Gondi', 'et': 'Masarami gondi', 'eu': 'masaram gondiera', 'ff-Adlm'... | Python | 1 |
"""
Run tests for the NekosLifeAPI class.
Usage:
cd tests
poetry run python3 -m pytest nekos_life.py
"""
from anime_api.apis import NekosLifeAPI
from anime_api.apis.nekos_life.objects import EightBall, Fact, Image
from anime_api.apis.nekos_life.types import ImageType
def test_get_eight_ball():
"""
Te... | Python | 1 |
mut self, filter: Box<dyn DspFilter>, sample_rate: f32) {
self.filters.push(ChainedFilter {
wrapped_filter: filter,
sampling_period: (1.0 / sample_rate),
period_counter: 0.0
});
}
pub fn consume(&mut self, input_sample: f32, delta_time: f32) {
// Alwa... | Rust | 0 |
).await?;
let logs: Vec<Entry<LogEntry>> = vec![
Entry {
log_id: LogId { term: 1, index: 2 },
payload: EntryPayload::Blank,
},
Entry {
log_id: LogId { term: 3, index: 4 },
payload: EntryPayload::Normal(EntryNormal {
data: LogEn... | Rust | 0 |
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('games/create/', views.game_create, name='game_create'),
path('games/play/', views.show_game, name='show_game'),
path('... | Python | 1 |
import numpy as np
import matplotlib.pyplot as plt
class TB_DataLoad():
def __init__(self, dataPath):
self.Rdata = np.loadtxt(dataPath)
def ALLDataLoad(self):
Rdata = self.Rdata
return Rdata
class TB_DataPlot():
def __init__(self, dataPath):
self.Rdat... | Python | 1 |
7094977,1617094988; smidV2=202104061553193a7c1a21482c01657352bb93535ed8a2007fa273ba4ff5ac0; xhs_spid.5dde=3af7c19f4aa1caf1.1617094977.13.1621407883.1620637217.692ca0a4-eabc-4f38-b1e9-ec9c4b8d49cb; xhsTracker=url=noteDetail&xhsshare=CopyLink; timestamp2=20210820052eb992f8ab1118df72dac4; timestamp2.sig=RZfppzLR9XZPvgIYhK... | Python | 1 |
: u8) -> DispatchResult {
ensure_root(origin)?;
ensure!(<SenseEntity<T>>::contains_key(&account_id), Error::<T>::EntityUnknown);
let now = <frame_system::Pallet<T>>::block_number();
let v = u64::from(value);
let current = Self::trust(&account_id);
let updated = EntityProperty {
value: current.va... | Rust | 0 |
partment).filter(Department.id == department_id).first()
if not db_department:
raise HTTPException(status_code=404, detail="Department not found")
for field, value in department.dict(exclude_unset=True).items():
setattr(db_department, field, value)
db.commit()
db.refresh(db_dep... | Python | 1 |
1() {
test_decoding_result_ok(
&[0xeb, 0xd4, 0x13, 0x07],
Instruction {
size: 0,
operation: BFEXTS,
operands: [ARIND(A4), DR(D1)],
extra: Bitfield(STATIC(12), STATIC(7)),
},
&[" bfexts (a4){12:7},d1"]... | Rust | 0 |
es(4096, extra_toks_per_seq=1)
data_loader = torch.utils.data.DataLoader(dataset, collate_fn=alphabet.get_batch_converter(), batch_sampler=batches)
output_dir = os.path.join(outpath, "temp")
create_empty_path(output_dir)
with torch.no_grad():
for batch_idx, (labels, strs, toks) in enumerate(da... | Python | 1 |
Builder;
use std::env;
use std::path::Path;
fn main() {
let dest = env::var("OUT_DIR").unwrap();
Builder::new("../truffle/build/contracts/RustCoin.json")
.generate()
.unwrap()
.write_to_file(Path::new(&dest).join("rust_coin.rs"))
.unwrap();
}
//----------------------------------... | Rust | 0 |
T_B.ndim}-dimensional and must be 1-dimensional. ")
n_A = T_A.shape[0]
n_B = T_B.shape[0]
l = n_A - m + 1
ignore_trivial = core.check_ignore_trivial(T_A, T_B, ignore_trivial)
excl_zone = int(np.ceil(m / config.STUMPY_EXCL_ZONE_DENOM))
if ignore_trivial: # self-join
core.check_window_s... | Python | 1 |
1..1 << i {
let pos = tree_index_from_u64(i, j as u64);
print_node(
1 << tree.get_height() >> (i - 1),
&pos,
&leaves,
&paddings,
&internals,
);
}
println!();
}
}
// HELPER FUNCTIONS
... | Rust | 0 |
id: Option<NonZeroU8>) -> Option<Header> {
let tid = tid.map_or(0, NonZeroU8::get);
if nli < 4 && tid < 16 {
Some(Header(0x80 + (nli << 4) + tid))
} else {
None
}
}
/// Network link ID.
pub fn nli(&self) -> u8 {
(self.0 & 0x30) >> 4
}
... | Rust | 0 |
"""
calculate_combustible_land_area.py iterates calculates the total land area covered by combustible
fuels in each fire zone.
The fuel types vector file is retrieved from our object store bucket, and the fire zones
(simplified polygons) are pulled from our database.
"""
import logging
from contextlib import contextm... | Python | 1 |
oughtime messages are represetned by [`RtMessage`](struct.RtMessage.html) which
//! implements the mapping of Roughtime `u32` [`tags`](enum.Tag.html) to byte-strings.
//!
//! # Server
//!
//! A Roughtime server implementation is in `src/bin/server.rs`. The server is
//! configured via a yaml file:
//!
//! ```yaml
//... | Rust | 0 |
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from ..controllers import payments as controller
from ..schemas import payments as schema
from ..dependencies.database import engine, get_db
from ..schemas.payments import PaymentCreate
router = APIRouter(
tags=['Payments'],
... | Python | 1 |
<key>T</key>
<integer>-30</integer>
<key>U</key>
<integer>-10</integer>
<key>V</key>
<integer>-30</integer>
<key>W</key>
<integer>-10</integer>
</dict>
<key>T</key>
<dict>
<key>A</key>
<integer>-65</integer>
<key>H</key... | Rust | 0 |
# Crie um programa que leia nome e duas notas de vários alunos e guarde tudo em uma lista composta.
# No final, mostre um boletim contendo a média de cada um e permita que o usuário possa mostrar as
# notas de cada aluno individualmente.
alunos = []
dados = []
while True: # loop infinito
nome = str(input('Nome: '... | Python | 1 |
let test = r#"
be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe
edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc
fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg
fbegcd cbd adcefb dageb afcb bc aefdc ecdab fgdeca f... | Rust | 0 |
ush pull output pin
pub fn into_output(self) -> $PXi<Output> {
unsafe { modify_reg!(crate::$gpiox, $GPIOX, MODER, $moder: 0x1) };
$PXi { _mode: PhantomData }
}
}
impl $PXi<Output> {
pub fn downgrade(self) -> $PXx<Output> {
... | Rust | 0 |
let x = x0 + radius * dx;
let y = y0 + radius * dy;
match coord2index(x, y, densmap.bin_size, densmap.shape) {
Some(i) => {
let is_filled = densmap.data[i] >= cutoff;
match (direction, is_filled) {
// If we are increasing the rad... | Rust | 0 |
onent of the incoming light and allows color measurements to be made
//! accurately. The high sensitivity, wide dynamic range, and IR blocking
//! filter make the TCS3472 an ideal color sensor solution for use under
//! varying lighting conditions and through attenuating materials.
//!
//! The TCS3472 color sensor has ... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.