text string | label_name string | labels int64 |
|---|---|---|
nc def asyncio(
*,
client: AuthenticatedClient,
body: TimePlanAssociateBigPlanWithPlanArgs,
) -> Optional[Union[Any, TimePlanAssociateBigPlanWithPlanResult]]:
"""Use case for creating activities starting from a big plan.
Use case for creating activities starting from a big plan.
Args:
... | Python | 1 |
{
t.balance = 1;
r.balance = -1;
} else {
panic!("impossible")
};
let rl = r.left.take();
t.right = rl;
r.left = Some(t);
r
}
fn print(t: &AvlTree<i32, i32>) {
match *t {
None => println!("."),
Some(ref n) => {
let Avl{key, v, balance, ... | Rust | 0 |
eq!(
some_native_amount,
<Assets as MultiCurrency<AccountId>>::free_balance(
this_native_asset,
&this_runtime::TreasuryAccount::get()
) - this_treasury_amount
);
assert_eq!(
other_non_native_amount,
<Assets as MultiCurrency<AccountId>>::free_balance(
any_asset,
&this_runtime::Treasur... | Rust | 0 |
U> Map<T, U, AddAggregatorConfig> for AddAggregator
where
I: AggregateAs<U>,
U: std::ops::AddAssign<U> + Init,
T: IntoIterator<Item = I> + Send + 'static,
{
/// Input: T
/// Output: U
async fn map(&mut self, data: T) -> anyhow::Result<U> {
Ok(self.aggregate(data))
}
}
#[cfg(test)]
... | Rust | 0 |
from abc import ABC, abstractmethod
from typing import Literal
import pandas as pd
class PipelineOutput(ABC):
@abstractmethod
def save_trust_scores(self, trusts: pd.DataFrame):
"""
`trusts`: DataFrame with
* index: `user_id`
* columns: `trust_score`
"""
... | Python | 1 |
nnel to a file descriptor and returns it.
///
/// `flags` is a bit field of |fuchsia.io.OPEN_*| options. `dir` must be backed by a directory
/// protocol channel (even though it is wrapped in a std::fs::File).
///
/// Wraps fdio_open_fd_at.
pub fn open_fd_at(dir: &File, path: &str, flags: u32) -> Result<File, zx::Statu... | Rust | 0 |
= None
for idx, ele in enumerate(listoftensor):
if idx == 0 :
mask = ele
else:
mask = torch.logical_or(mask, ele)
return mask
@torch.no_grad()
def removeminmax(
self,
params: Union[Dict[str, torch.nn.Parameter], torc... | Python | 1 |
=> {
if !cfg.allow_remove {
anyhow::bail!("server has disabled remove for this client")
}
let n_removed = repo.remove_items(items)?;
write_packet(w, &Packet::RRmItems(serde_bare::Uint(n_removed)))?;
}
Packet::TR... | Rust | 0 |
#[inline(always)]
pub fn tx_pdm_sigmadelta_dither2(&self) -> TX_PDM_SIGMADELTA_DITHER2_R {
TX_PDM_SIGMADELTA_DITHER2_R::new(((self.bits >> 21) & 0x01) != 0)
}
#[doc = "Bit 22 - I2S TX PDM sigmadelta dither value"]
#[inline(always)]
pub fn tx_pdm_sigmadelta_dither(&self) -> TX_PDM_SIGMADELTA_... | Rust | 0 |
from .MLP import MLP
from .MAE_ViT_MsLd import MAE_ViT_MsLd
class MAE_ViT_MsLdCd(MAE_ViT_MsLd):
"""Masked Autoencoder with VisionTransformer backbone"""
def __init__(
self,
loss_cd=None,
predictor_hidden_size=2048,
**kwargs,
):
super().__init__(**kwargs)
#... | Python | 1 |
# Ported from LiquidMetal
# https://github.com/rmm5t/liquidmetal
SCORE_NO_MATCH = 0.0
SCORE_MATCH = 1.0
SCORE_TRAILING = 0.8
SCORE_TRAILING_BUT_STARTED = 0.9
SCORE_BUFFER = 0.85
WORD_SEPARATORS = ' \t_-'
def score(string, abbrev):
# short circuits
if len(string) < len(abbrev):
# string, abbrev = abbr... | Python | 1 |
data = [0, 4, 1, 3, 1, 2, 4, 1]
counts = [0]*5 # data가 0~4까지의 정수
N = len(data) # data의 크기
temp = [0]*N # 정렬된 결과 저장
# 1단계 : data 원소 별 개수 세기
for x in data: # data의 원소 x를 가져와서 counts[x]에 개수 기록
counts[x] += 1 # 왜 이게 나오지?
# 2단계 : 각 숫자까지의 누적 개수 구하기
for i in range(1, 5): ... | Python | 1 |
xdd\xad{j\xf1\xa3/\xdeiT\
\x908\xf7\xc5sT\xa7\xcb\xd0\xed\xa5\x8cu=\xc9\x12\
]|A\xb5\xf0\xe5\xd7\xfcM\xad\xda\xd6\xd5\x97\xe6\x99\
\x17z/8\xedWe\x8bF\xd6J\xddY\xdf\xad\xfd\
\xbc\xa3w\x1f\xc3\x5cU\xd7\x8d\xdb\xfbR\xde\xf3\xca\x8a\
\xe2\xd6\xe9U\xa4\x8d\x97\xe5\xe7\x04\x8cc\xd6\xb54o\
\xec\x99>\xdfq\xa3Ko\xf2\xb8i\xad\xd... | Python | 1 |
ormat
print(f"{'Operation':<25} {'Time Complexity':<15} {'Space Complexity':<15} {'Time (in seconds)':<20} {'Size (in bytes)':<15}")
for result in results:
print(f"{result[0]:<25} {result[1]:<15} {result[2]:<15} {result[3]:<20} {result[4]:<15}")
# Main function
def main():
# Define the root directo... | Python | 1 |
import water as problem
for succ, cost in problem.successors((3, 1)):
print(succ, end=" ")
| Python | 1 |
::OPCODE, value: opcode::OPCODE::SYSTEM as u32 },
Opcode{ patch: &patch::RD, value: 0 },
Opcode{ patch: &patch::FUNCT3, value: opcode::FUNCT3_SYSTEM::PRIV as u32 },
Opcode{ patch: &patch::RS1, value: 0 },
Opcode{ patch: &patch::FUNCT12, value: opcode::FUNCT12_PRIV::$funct... | Rust | 0 |
import sys
import heapq as hq
input = lambda : sys.stdin.readline().rstrip()
#나의 풀이 -> 나는 딕셔너리를 사용했다
heap = []
cnt = dict()
N = int(input())
for i in range(N):
x = int(input())
#-인 애들의 개수를 넣자
if x < 0 and (x * -1) not in cnt:
cnt[x * -1] = 1
elif x < 0:
cnt[x * -1] += 1
if x == 0 a... | Python | 1 |
from celery import Celery
from public_memes_api.config.config import HOST_REDIS
celery = Celery(
"tasks",
broker=f"redis://{HOST_REDIS}",
include="public_memes_api.tasks.tasks"
)
| Python | 1 |
na_datas = f"{ROOT_DIR}/examples/datas_dna.py"
if not os.path.isfile(dna_datas):
raise ValueError("Please press Update button first")
sys.path.append(f"{ROOT_DIR}/examples")
import datas_dna
datas_dna.load_dna_data()
cmds.warning("Loaded Succesfully!")
def saveimport(ROOT_DIR):
sys.path... | Python | 1 |
type!(inner => CompositeType => SequentialType => PointerType)
}
}
}
impl_subtype!(PointerType => SequentialType);
// Check that if we have multiple applicable projection bounds we pick one (for
// backwards compatibility reasons).
// check-pass
use std::ops::Mul;
trait A {
type V;
type U: Mul<S... | Rust | 0 |
bytes.len() >= $offset + $signature.len() && &$bytes[$offset..$offset + $signature.len()] == $signature
};
($bytes:expr, $([$([$offset:literal, $signature:literal]),*]),*) => {
$($(check_signature!($bytes, $offset, $signature))&&*)||*
};
}
/// Generates `FileFormat` enum using a database described ... | Rust | 0 |
LOG_LEVEL_SYZ_LOG_LEVEL_ERROR,
Level::Warn => SYZ_LOG_LEVEL_SYZ_LOG_LEVEL_WARN,
Level::Info => SYZ_LOG_LEVEL_SYZ_LOG_LEVEL_INFO,
Level::Debug => SYZ_LOG_LEVEL_SYZ_LOG_LEVEL_DEBUG,
_ => panic!("Level not supported"),
};
unsafe { syz_setLogLevel(level) };
}
fn initialize() -> Resu... | Rust | 0 |
?.expect("image should have a src");
// now build a raw HTTP client request (which also has all current cookies)
let raw = img.client().raw_client_for(Method::GET, &src).await?;
// we then read out the image bytes
let pixels = hyper::body::to_bytes(raw.into_body())
.map_err(error::CmdError::fr... | Rust | 0 |
haracters to their corresponding glyphs.
pub fn preprocess_indic(cs: &mut Vec<char>) {
constrain_vowel(cs);
decompose_matra(cs);
recompose_bengali_ya_nukta(cs);
reorder_marks(cs);
reorder_kannada_ra_halant_zwj(cs);
}
/// Denotes if/where a constraining character should be inserted.
enum InsertConst... | Rust | 0 |
cfg(not(all(target_pointer_width = "64", not(target_arch = "sparc"))))]
fn from_u32(x: &[u32]) -> math::LimbVecType {
x.iter().cloned().collect()
}
#[cfg(all(target_pointer_width = "64", not(target_arch = "sparc")))]
fn from_u32(x: &[u32]) -> math::LimbVecType {
let mut v = math::LimbVecType::default();
fo... | Rust | 0 |
inatedCipherSuiteList: usize = *MaximumNumberOfCipherSuites + 1;
#[derive(Debug)] pub static ref AllSupportedCipherSuites: &'static [CipherSuite] = CipherSuite::allSupportedCipherSuites();
}
#[allow(non_camel_case_types)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, NumFromPrimitive)]
#[repr(i32... | Rust | 0 |
a, headers=self.headers)
pass
def get_music_by_text(self, text):
ret = ConnectMysql.get_songs_by_search(self.conn, text)
return json.dumps(ret)
# 音乐推荐模块
class MusicRecommend():
def __init__(self):
self.current = 0
self.updateTimeStamp = [(self.current, time.time())]
... | Python | 1 |
text: &'input str,
___0: (usize, Tok<'input>, usize),
___1: (usize, ::std::vec::Vec<Atom>, usize),
___2: (usize, Atom, usize),
) -> Path
{
let ___start0 = ___0.0.clone();
let ___end0 = ___0.2.clone();
let ___temp0 = ___action136(
text,
___0,
);
let ___temp0 = (___start0, ___temp0, ___end0);
___action80(
text,
___temp0,... | Rust | 0 |
adapter.store_event(event_data, race_id, conn)
events_processed += 1
logger.info(f"✅ Stored event {event_id}")
# Get a few participants for this event
logger.info(f"👥 Getting participants for event {event_id}...")
... | Python | 1 |
set_line_width(chart_config.axis_width);
ctx.set_line_cap("square");
ctx.move_to(x, rect.y);
ctx.line_to(x, rect.y + rect.h);
ctx.stroke();
}
}
pub struct DrawXAxisOptions<'a> {
pub chart_colors: &'a ChartColors,
pub chart_config: &'a ChartConfig,
pub ctx: &'a dom::CanvasRenderingContext2d,
pub rect: Rect... | Rust | 0 |
output.status.success() {
Ok(())
} else {
let stdout = String::from_utf8(output.stdout).map_err(drop)?;
print!("{}", stdout);
Err(())
}
}
#[test]
fn check_code_formatting() {
let dir = project_root();
if run("rustfmt +stable --version", &dir).is_err() {
panic!(
... | Rust | 0 |
mpl<'a: 'b, 'b> GpioStatusBuilder<'a, 'b> {
#[inline]
pub fn add_id(&mut self, id: i8) {
self.fbb_.push_slot::<i8>(GpioStatus::VT_ID, id, 0);
}
#[inline]
pub fn add_on(&mut self, on: bool) {
self.fbb_.push_slot::<bool>(GpioStatus::VT_ON, on, false);
}
#[inline]
pub fn new... | Rust | 0 |
test() {
let test_input = "abcde fghij\n\
abcde xyz ecdab\n\
a ab abc abd abf abj\n\
iiii oiii ooii oooi oooo\n\
oiii ioii iioi iiio";
let valid_output = vec![
"abcde fghij",
... | Rust | 0 |
# Voting eligibility check based on age
def check_eligibility():
print("=== Voting Eligibility Checker ===")
name = input("Enter your name: ")
try:
age = int(input("Enter your age: "))
if age >= 18:
print(f"✅ Hello {name}, you are eligible to vote.")
else:
... | Python | 1 |
nfig::Config;
mod aws_endpoint;
#[cfg(feature = "client")]
pub mod client;
pub mod config;
pub mod error;
mod error_meta;
pub mod input;
pub mod model;
pub mod operation;
mod operation_deser;
mod operation_ser;
pub mod output;
mod query_ser;
mod rest_xml_wrapped_errors;
mod xml_deser;
pub static PKG_VERSION: &str = en... | Rust | 0 |
#tuplas:
# 1. Escreva um programa que receba uma tupla de números inteiros e como
# saída uma nova tupla com os elementos pares da tupla original. Por
# exemplo, se a tupla for (1, 2, 3, 4, 5), o programa deve imprimir (2, 4).
tupla_original = (1, 2, 3, 4, 5)
tupla_pares = ()
for numero in tupla_original:
if nume... | Python | 1 |
if shielded_instance_config_message:
properties.shieldedInstanceConfig = shielded_instance_config_message
request = client.messages.ComputeInstanceTemplatesInsertRequest(
instanceTemplate=client.messages.InstanceTemplate(
properties=properties,
description=args.description... | Python | 1 |
pass it around, " + &(n-1).to_string() + " bottles of beer on the wall.\n";
}
}
}
// thanks https://exercism.io/tracks/rust/exercises/beer-song/solutions/69e3124c1c67479285b2045c64d4450f
pub fn sing(start: i32, end: i32) -> String {
(end..=start).rev().map(|i| verse(i)).collect::<Vec<_>>().join("\n")... | Rust | 0 |
tion"),
)
.arg(
Arg::new("region")
.short('r')
.long("region")
.takes_value(true)
.value_name("REGION")
.help("Genomic region to consider"),
)
.next_help_heading("Input/Output")
.arg(
Arg::new("reference")
... | Rust | 0 |
# perfect number
for i in range(1,1001):
c=0
for j in range(1,i):
if(i%j==0):
c=c+j
if(i==c):
print(i)
# sum of even number
c=0
for i in range(1,10,1):
if(i%2==0):
c=c+i
print(c)
# prime number
for i in range(1,100):
for j in range(2,i):
if(i%j==0)... | Python | 1 |
("circulate", &self.circulate),
CirculateRequest => d.field("circulate_request", &self.circulate_request),
PropertyNotify => d.field("property", &self.property),
SelectionClear => d.field("selection_clear", &self.selection_clear),
SelectionRequest => d.field("selection_request", &self.se... | Rust | 0 |
turn the current user ID
MyEvents = Event.objects.filter(attendees=me) #filter the database
return render(request, 'events/my-events.html',{
'MyEvents':MyEvents,
})
else:
messages.success(request, ("you don't have evensts or access denied"))
return redirect('home')
def search_events(re... | Python | 1 |
alice_subnet_netuid, field_indices=[72]
).validators
alice_uid = subtensor.subnets.get_uid_for_hotkey_on_subnet(
hotkey_ss58=alice_wallet.hotkey.ss58_address, netuid=alice_subnet_netuid
)
assert validators[alice_uid] == 1
bob_uid = subtensor.subnets.get_uid_for_hotkey_on_subnet(
... | Python | 1 |
rser.read::<$item>()?,)*))
}
}
impl<$($item: VmValueEncoder),*> VmValueEncoder for ($($item,)*) {
fn serialize(&self, _builder: &mut VmValueBuilder) {
_builder.common.sink.write_byte(crate::abi::event_builder::TYPE_LIST);
#[allow(unused_mut)]
... | Rust | 0 |
{
input.push(buffer[1..].trim().parse::<i32>().unwrap() * -1);
} else {
break;
}
buffer.clear();
}
input
}
<reponame>gcarq/dotvanity<filename>src/main.rs
use data_encoding::HEXLOWER;
use sp_core::crypto::AccountId32;
use sp_core::crypto::Ss58AddressFormat;
use ... | Rust | 0 |
_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[doc = "*Required features: 'Phone_Notification_Management'*"]
#[repr(transparent)]
pub struct AccessoryNotificationType(pub u32);
impl AccessoryNotificationType {
pub const None: Self = Self(0u32);
pub const Phone: Self = Self(1u32);
pub con... | Rust | 0 |
pkg_dir = os.path.join(script_dir, 'test_pkg')
make_pkg(pkg_dir)
main_dir = os.path.join(pkg_dir, '__main__')
make_pkg(main_dir)
msg = ("Cannot use package as __main__ module; "
"'test_pkg' is a package and cannot "
"be direc... | Python | 1 |
4, 1, 35317, 1, 3, 9, 4)
)
koliJTSNotifications.setObjects(
*(("KOLIBRI-GW-JTS-MIB", "koliJTSServiceStart"),
("KOLIBRI-GW-JTS-MIB", "koliJTSServiceStop"),
("KOLIBRI-GW-JTS-MIB", "koliJTSGatewayConnected"),
("KOLIBRI-GW-JTS-MIB", "koliJTSGatewayDisconnected"),
("KOLIBRI-GW-JTS-MIB",... | Python | 1 |
)
op.alter_column(
"amoy_labels",
"address",
existing_type=sa.LargeBinary(),
type_=sa.VARCHAR(length=64),
nullable=True,
)
op.alter_column(
"amoy_labels",
"origin_address",
existing_type=sa.LargeBinary(),
type_=sa.VARCHAR(length=64),... | Python | 1 |
fn from(err: serde_json::Error) -> Self {
Self::Json(err)
}
}
impl From<String> for Error {
fn from(err: String) -> Self {
Self::Command(err)
}
}
use serde_json::Value;
use std::borrow::Cow;
#[derive(Clone, Copy)]
pub enum Async {
Start,
Instant,
End,
}
#[derive(Clone, Copy)]
... | Rust | 0 |
import os
import sys
import sysconfig
from pathlib import Path
def find_pywry_bin() -> Path:
"""Find the pywry binary."""
if hasattr(sys, "frozen"):
# pylint: disable=E1101,W0212
path = Path(sys._MEIPASS).resolve()
for bin_path in path.rglob("pywry*"):
if bin_path.is_file(... | Python | 1 |
import unittest
from netjsonconfig import OpenWrt
from netjsonconfig.utils import _TabsMixin
class TestDialup(unittest.TestCase, _TabsMixin):
maxDiff = None
_dialup_interface_netjson = {
"interfaces": [
{
"mtu": 1448,
"network": "xdsl",
"ty... | Python | 1 |
write_all(&checksum)?;
Ok(buf)
}
}
#[cfg(test)]
mod tests {
use super::*;
use rustc_serialize::hex::{FromHex, ToHex};
use std::fs::File;
use std::io::Read;
use crate::packfile::PackFile;
static PACK_FILE: &'static str =
"tests/data/packs/pack-73e0a23f5ebfc74c7ea1940e2843a... | Rust | 0 |
),
)
} else if let Some(matches) = matches.subcommand_matches("list") {
list(
matches.value_of("pkey").unwrap(),
matches.value_of("archive").unwrap()
)
} else if let Some(matches) = matches.subcommand_matches("binprint") {
try {
let buf = std::... | Rust | 0 |
Source;
use proc_macro::TokenStream;
use proc_macro2::{Literal, Span};
use quote::{quote, quote_spanned};
use syn::spanned::Spanned as _;
use syn::{
parse::Error, parse_macro_input, AttrStyle, Data, DeriveInput, Expr, Field, Fields,
GenericArgument, Lit, Meta, NestedMeta, PathArguments, Type,
};
use abigen::{e... | Rust | 0 |
IP_QUERY: &str = include_str!("sql/p2p_agent_store/gossip_query.sql");
pub(crate) const QUERY_NEAR_BASIS: &str =
include_str!("sql/p2p_agent_store/query_near_basis.sql");
pub(crate) const EXTRAPOLATED_COVERAGE: &str =
include_str!("sql/p2p_agent_store/extrapolated_coverage.sql");
pub(crate) ... | Rust | 0 |
let mut models = HashMap::new();
for glb_buf in glb_bufs {
let (document, buffers, images) = gltf::import_slice(glb_buf).unwrap();
load_models_from_gltf_data(
&document,
&buffers[0],
&images,
&vulkan_context,
descriptor_set_layouts,
... | Rust | 0 |
Value::Double(d) => format!("{}", d),
Value::Integer(i) => format!("{}", i),
Value::Text(s2) => s2.clone(),
}
}
}
/// Evaluates all arguments given to a function.
///
/// This is a convenience function to simplify the processing of arguments because most functions
/// do not care ab... | Rust | 0 |
0,
}
impl From<RpcError> for BitcoinRpcError {
fn from(err: RpcError) -> Self {
match num::FromPrimitive::from_i32(err.code) {
Some(err) => err,
None => Self::RpcUnknownError,
}
}
}
use super::{a, b};
#[test]
fn single_short() {
rule!(rule:&str = ["a"]);
assert... | Rust | 0 |
ass EpisodeState:
def __init__(self, system_prompt: SystemPrompt):
self.system_prompt = system_prompt
self.interactions: List[Interaction] = []
def update(self, interaction: Interaction):
self.interactions.append(interaction)
def format_reponse(
response: RESPONSE_TYPES,
inclu... | Python | 1 |
u8.try_into();
assert_eq!(three, Ok(SkippedNumber::Three));
let four: Result<SkippedNumber, _> = 4u8.try_into();
assert_eq!(four, Ok(SkippedNumber::Four));
}
#[derive(Debug, Eq, PartialEq, TryFromPrimitive)]
#[repr(u8)]
enum WrongOrderNumber {
Four = 4,
Three = 3,
Zero = 0,
One, // Zero + ... | Rust | 0 |
calc_distance_between_nodes_left_mawari(self_node_ref.node_id,
self_node_ref.predecessor_info[0].node_id);
chord_util::dprint(&("check_predecessor distance_check=".to_string()
+ distance_check.to_string().as_str()
+ " distance... | Rust | 0 |
se(version).is_ok()
}
pub fn encodable(self, crate_name: &str) -> EncodableVersion {
let Version { id, crate_id: _, num, updated_at, created_at,
downloads, features, yanked } = self;
let num = num.to_string();
EncodableVersion {
dl_path: format!("/api/v... | Rust | 0 |
# step1: define your own operator:
def selection_tournament(algorithm, tourn_size):
FitV = algorithm.FitV
sel_index = []
for i in range(algorithm.size_pop):
aspirants_index = np.random.choice(range(algorithm.size_pop), size=tourn_size)
sel_index.append(max(aspirants_index, key=lambda i: FitV... | Python | 1 |
"""
Write a function to extract the nth element from a given list of tuples.
assert extract_nth_element([('Greyson Fulton', 98, 99), ('Brady Kent', 97, 96), ('Wyatt Knott', 91, 94), ('Beau Turnbull', 94, 98)] ,0)==['Greyson Fulton', 'Brady Kent', 'Wyatt Knott', 'Beau Turnbull']
"""
def extract_nth_element(tuples, n):
... | Python | 1 |
ce emits the second 'Confirmed' event"
);
events
.find(|e| {
matches!(
e, invmgr::Event::BlockProcessed { block, .. }
if block.block_hash() == blk2.block_hash()
)
})
.expect("Alice is done processing the second block");
assert... | Rust | 0 |
, "mts", "ts", "m2t"]
signatures:
- parts:
- offset: 0
value: b"\x47"
- offset: 188
value: b"\x47"
- parts:
- offset: 4
value: b"\x47"
- offset: 196
value: b"\x47"
}
<gh_stars>1-10
//! Types for the `ApiGateway` service.
/// The [`... | Rust | 0 |
_id,
tie_word_embeddings=tie_word_embeddings,
**kwargs,
)
def _rope_scaling_validation(self):
"""
Validate the `rope_scaling` configuration.
"""
if self.rope_scaling is None:
return
if not isinstance(self.rope_scaling, dict) or le... | Python | 1 |
ch::asm!("ecall",
in("a0") arg0,
in("a1") arg1,
in("a2") arg2,
in("a6") fid,
in("a7") eid,
lateout("a0") ret,
);
}
ret
}
pub fn console_putchar(ch: usize) -> usize {
sbi_call(SBI_CONSOLE_PUTCHAR, 0, ch, 0, 0)
}
pub fn console_... | Rust | 0 |
path.len() == 0 {
return;
}
// Holder for event state.
let mut event_wrapper = Wrapper {
event,
// Initial State
phase: Phase::Creation,
can_propagate: true,
can_default: true,
can_bubble: true,
};
// --- Event Propagation
event_wrapper.phase = Phase::Propagation;
for node_i... | Rust | 0 |
k, bps)?;
// The least significant bit of val is the sign bit - the plus is weird tho
// if val and sgn mod = 0 then nothing happens
// if one is 1 the lsb = 1
// val & 1 = 1 => val is all 1s => flip all the bits
// if they are both 1 then val_eff += 2
// val & 1 = 0 => n... | Rust | 0 |
blocked: AtomicBool,
}
impl MutatorGlobal {
pub fn new() -> MutatorGlobal {
MutatorGlobal {
take_yield: AtomicBool::new(false),
still_blocked: AtomicBool::new(false),
}
}
#[inline(always)]
pub fn is_still_blocked(&self) -> bool {
self.still_blocked.load(... | Rust | 0 |
AL: [f32; 4] = [1.000, 0.498, 0.314, 1.000];
pub const TOMATO: [f32; 4] = [1.000, 0.388, 0.278, 1.000];
pub const ORANGE_RED: [f32; 4] = [1.000, 0.271, 0.000, 1.000];
pub const DARK_ORANGE: [f32; 4] = [1.000, 0.549, 0.000, 1.000];
pub const ORANGE: [f32; 4] = [1.000, 0.647, 0.000, 1.000];
pub const GOLD: [f32; 4] = [1.... | Rust | 0 |
ed by rust-bindgen 0.57.0 */
pub const TJ_NUMSAMP: u32 = 6;
pub const TJ_NUMPF: u32 = 12;
pub const TJ_NUMCS: u32 = 5;
pub const TJFLAG_BOTTOMUP: u32 = 2;
pub const TJFLAG_FASTUPSAMPLE: u32 = 256;
pub const TJFLAG_NOREALLOC: u32 = 1024;
pub const TJFLAG_FASTDCT: u32 = 2048;
pub const TJFLAG_ACCURATEDCT: u32 = 4096;
pu... | Rust | 0 |
# Introdução às Generator functions
# generator = (n for n in range(1000000))
# def generator(n=0):
# yield 1 # Pausar
# print('Continuando...')
# yield 2 # Pausar
# print('Mais uma...')
# yield 3
# print('Vou terminar')
# return 'Acabou'
def generator(n=0, maximun=10):
whil... | Python | 1 |
&write, tracks);
},
"modify-playlist" => {
if let Ok((playlist,tracks)) = read.get_playlist_by_title(&args[1]) {
modify::modify_playlist(&write, playlist, tracks);
} else {
println!("Playlist {} not found!", args[1]);
... | Rust | 0 |
s}
} // namespace TypeBuilder
} // namespace WebCore
#endif // ENABLE(INSPECTOR)
#endif // !defined(InspectorTypeBuilder_h)
""")
typebuilder_cpp = (
"""
#include "config.h"
#if ENABLE(INSPECTOR)
#include "InspectorTypeBuilder.h"
#include <wtf/text/CString.h>
namespace WebCore {
namespace TypeBuilder {
const ... | Python | 1 |
}
})
.arg({
let arg = Arg::with_name("data_dir")
.short("d")
.long("data-dir")
.value_name("PATH")
.takes_value(true)
.required(true)
.help("Directory to store install data");
match *... | Rust | 0 |
# model settings
norm_cfg = dict(type='SyncBN', requires_grad=True)
data_preprocessor = dict(
type='SegDataPreProcessor',
mean=[123.675, 116.28, 103.53],
std=[58.395, 57.12, 57.375],
bgr_to_rgb=True,
pad_val=0,
seg_pad_val=255)
model = dict(
type='EncoderDecoder',
data_preprocessor=data_... | Python | 1 |
efault() -> Self {
ColorsSrgb::light()
}
}
impl ColorsSrgb {
/// Default "light" scheme
pub fn light() -> Self {
Colors {
is_dark: false,
background: Rgba8Srgb::from_str("#FAFAFA").unwrap(),
frame: Rgba8Srgb::from_str("#BCBCBC").unwrap(),
acce... | Rust | 0 |
#!/usr/bin/python3
import subprocess, re, socket, struct, ctypes
class PrettyBigEndianStructure(ctypes.BigEndianStructure):
def __str__(self):
print_byte = lambda x: bytearray(x) if isinstance(x, (bytes, bytearray, ctypes.Array)) else x
return "{}: {{{}}}".format(self.__class__.__name__, ", ".join... | Python | 1 |
1_VIDEO_DECODER_EXTENSION,
) -> HRESULT,
fn VideoProcessorSetOutputTargetRect(
pVideoProcessor: *mut ID3D11VideoProcessor,
Enable: BOOL,
pRect: *const RECT,
) -> (),
fn VideoProcessorSetOutputBackgroundColor(
pVideoProcessor: *mut ID3D11VideoProcessor,
YCbCr: BOOL... | Rust | 0 |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
""" Utility functions for metric evaluation.
Author: Or Litany and Charles R. Qi
"""
import os
import sys
BASE_DIR = os.path.dirname(os.pat... | Python | 1 |
expr: Box::new(expr),
}
}
pub(crate) fn base(position: usize, column_type: ColumnType) -> BoxScalarExpr {
BoxScalarExpr::BaseColumn(BaseColumn {
position,
column_type,
})
}
pub(crate) mod lit {
use super::*;
pub(crate) fn int3... | Rust | 0 |
ncelled)?;
}
Ok(())
}
pub(crate) async fn basic_deliver(&mut self, channel: ChannelNumber, args: frame::BasicDeliverArgs) -> Result<()> {
let dc = DeliveredContent {
channel,
consumer_tag: args.consumer_tag,
delivery_tag: args.delivery_tag,
... | Rust | 0 |
moval of presentation slides.
pub mod delete;
pub mod get_presentation;
pub mod upload;
<reponame>opencollector/tantivy-py
use pyo3::{exceptions, prelude::*};
use tantivy as tv;
mod document;
mod facet;
mod index;
mod query;
mod schema;
mod schemabuilder;
mod searcher;
use document::Document;
use facet::Facet;
use i... | Rust | 0 |
om())
}
fn test_statement_distribution_msg() -> StatementDistributionMessage {
StatementDistributionMessage::NetworkBridgeUpdateV1(test_network_bridge_event())
}
fn test_availability_recovery_msg() -> AvailabilityRecoveryMessage {
let (sender, _) = oneshot::channel();
AvailabilityRecoveryMessage::RecoverAvailableD... | Rust | 0 |
let res = match status.code() {
Some(0) => {
log::info!(
"Project: '{}' Command: '{}' Exit success.",
project_name,
args,
... | Rust | 0 |
aths(&self, path_info: &PathInfo) -> Result<Option<Paths>, FetchError> {
let cookie_session = format!("JSESSIONID={}", self.session.as_ref().unwrap());
let url = format!("{}/.rest/nodes/v1/{}{}?depth=999&excludeNodeTypes=mgnl:resource&includeMetadata=true", self.url, path_info.repo_type, path_info.path)... | Rust | 0 |
# core/text_generate/generator.py
# -*- coding: utf-8 -*-
"""
增强的文案生成器 - 集成阿里云百炼API和Jinja2模板
"""
import json
import requests
import time
import os
from typing import Dict, Any, Optional, List
from jinja2 import Environment, FileSystemLoader, Template
from core.text_generate.prompt_manager import validate_scene_and_ty... | Python | 1 |
._ProjectId = params.get("ProjectId")
self._BeginDate = params.get("BeginDate")
self._EndDate = params.get("EndDate")
memeber_set = set(params.keys())
for name, value in vars(self).items():
property_name = name[1:]
if property_name in memeber_set:
... | Python | 1 |
0D;
const ALM1WKDAY: u8 = 0x14;
const PWRDNMIN: u8 = 0x18;
const PWRUPMIN: u8 = 0x1C;
}
struct BitFlags;
impl BitFlags {
const ST: u8 = 0b1000_0000;
const H24_H12: u8 = 0b0100_0000;
const AM_PM: u8 = 0b0010_0000;
const VBATEN: u8 = 0b0000_1000;
const PWRFAIL: u8 = 0b0001_0000;
const... | Rust | 0 |
"""Tests for regression configurations."""
import pytest
from enum import Enum
from typing import Any
from pydantic import BaseModel, ValidationError
from strux.configs import (
RegressionConfig,
ValidationLevel,
FieldConfig
)
from strux.strategies import (
ExactMatch,
NumericRange,
exact_matc... | Python | 1 |
service_config: Config, tlm2send: std::sync::mpsc::Receiver<Vec<u8>>, cmds: std::sync::mpsc::Receiver<TlmCmds>, _responses: std::sync::mpsc::Sender<TlmCmds>) {
const SLEEP_INTERVAL: time::Duration = time::Duration::from_millis(1000);
let mut telemetry_interval = time::Duration::new(5, 0);
// let socket... | Rust | 0 |
len() as f64);
let denominator = amp_spectrum.iter().fold(0_f64, |acc, x| acc + x) / amp_spectrum.len() as f64;
numerator / denominator
}
/// Calculates the spectral flux of a signal.
///
/// Spectral flux is a measure of the variability of the spectrum over time.
pub fn flux(amp_spectrum: &[f64], _sampling_... | Rust | 0 |
"""
Escopo de variáveis
Dois casos de escopo:
1. Variáveis globais: Variáveis que são criadas fora de qualquer função, ou seja, no nível mais alto do
- Variaveis globais são reconhecidas, ou seja, seu escopo compreende, todo o programa.
2. Variáveis locais: Variáveis que são criadas dentro de uma função e só pod... | Python | 1 |
fuse_status) on a fuse.
pub enum FuseStatus {
/// The fuse existed in the binary.
Present(bool),
/// The fuse existed in the binary and was updated with the supplied value.
Modified,
/// The fuse existed in the binary, but was marked as removed.
///
/// The binary contents will not be modifi... | Rust | 0 |
OutOfRange(i32),
}
impl From<RbspBitReaderError> for ScalingMatrixError {
fn from(e: RbspBitReaderError) -> Self {
ScalingMatrixError::ReaderError(e)
}
}
#[derive(Debug, Clone)]
pub struct SeqScalingMatrix {
// TODO
}
impl Default for SeqScalingMatrix {
fn default() -> Self {
SeqScalin... | Rust | 0 |
NAL_BUY",
int(property_data["price"] * 0.88), # Target 12% below asking
"major_renovation",
int(property_data["price"] * 0.35), # 35% value increase
"24_months"
)
else:
return ("HOLD", None, "monitor_market", None, "indefi... | Python | 1 |
import asyncio
import logging
import sys
logger = logging.getLogger("uvicorn.error")
def asyncio_setup(use_subprocess: bool = False) -> None:
if sys.platform == "win32" and use_subprocess:
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) # pragma: full coverage
| Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.