text string | label_name string | labels int64 |
|---|---|---|
pub dependencies: Vec<String>,
/// GraphQL type of the entity.
pub graphql: GraphQL,
/// Id of the entity.
pub id: String,
/// Name of the entity.
pub name: String,
/// Path of the entity.
pub path: PathBuf,
/// Raw representation of the entity.
pub raw: String,
}
impl Entity... | Rust | 0 |
file: &mut R,
fmt: TotemFormat,
) -> Result<PaletteC4, error::UnpackError> {
match ptype {
PALETTE_A3RGB5 => {
let mut palettedata = [0u16; 16];
fmt.read_u16_into(file, &mut palettedata)?;
let mut retdata = [0u32; 16];
... | Rust | 0 |
logger.info(f'train std value: {np.std(self.train, axis=(0, 1))}')
min_train_val = [f'{val:.2f}' for val in np.min(self.train, axis=(0, 1))]
logger.info(f'test min value: {min_train_val}')
logger.info(f'train max value: {np.max(self.train, axis=(0, 1))}')
logger.info('-----val-----')
... | Python | 1 |
= groups.left.list_members(&deps.querier, last, QUERY_LIMIT)?;
}
TOTAL.save(deps.storage, &total)?;
Ok(())
}
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn execute(
deps: DepsMut<TgradeQuery>,
env: Env,
info: MessageInfo,
msg: ExecuteMsg,
) -> Result<Response, ContractError> {
... | Rust | 0 |
"""
Taking parameters:
n_pixels: pixel dimensions of detector assuming square shape (flat 1d here)
radius: radius of assumed circular object to scan
phi: the angle at the source between the middle of the detector and the edge
Function determines and plots the distances:
d_source_obj: distance from source to object
d... | Python | 1 |
bool:
"""Check if configuration is initialized."""
return self.initialized
def initialize(
self,
api_base_url: str,
model_name: str,
auto_run_mode: bool = True,
show_ai_responses: bool = True,
**kwargs
) -> None:
"""Initialize configu... | Python | 1 |
from typing import List
# Time Complexity O(n log n)
# - traversing for loop takes O(n) to create hash dictionary,
# - and when sorting by sorted function(TimSort) it takes O(nlogn)
# Space Complexity O(n log n)
# - creating hash dictionary takes O(n)
# - and when sorting takes O(n), hash[x] occupy O(1)
class Solutio... | Python | 1 |
w.push(layout::ADDRESS);
let bytes = self.as_slice();
// This code calls for using a loop.
// In order to assure there is no usage of `loop` when compiled to Wasm,
// we manually inject multiple statements.
//
... | Rust | 0 |
line_text).unwrap_or(0);
};
let typo_bounds = line.get_typographic_bounds();
let is_inside_y = point.y >= 0. && point.y <= self.frame_size.height;
let is_inside_x =
point_in_string_space.x >= 0. && point_in_string_space.x <= typo_bounds.width;
let is_inside = is_insi... | Rust | 0 |
import sys
# 표준 입력을 'input.txt'에서 읽도록 재지정
sys.stdin = open('input.txt')
# 트리의 노드 수 입력
N = int(input())
# 전위 순회 함수
def preorder(now):
if trees.get(now): # 현재 노드에 자식이 있는 경우
print(now, end='') # 현재 노드 출력
preorder(trees[now][0]) # 왼쪽 자식을 기준으로 재귀 호출
preorder(trees[now][1]) # 오른쪽 자식을 기준으로 재... | Python | 1 |
geoms.append(rect)
# Visits
visit_lvl = value_grid[j, i]
if visit_lvl > 0.05 :
intensity = visit_lvl.item() * 0.5
color = (1.0 - intensity, 1.0 - intensity, 1.0) # Blueish gradient base... | Python | 1 |
from airflow import DAG
from airflow.operators.bash import BashOperator
from airflow.providers.apache.spark.operators.spark_submit import SparkSubmitOperator
from datetime import datetime
from datetime import timedelta
with DAG(
'bigdata_etl_dag',
start_date=datetime(2025, 4, 18),
schedule_interval='@dail... | Python | 1 |
# miasta = [('Warszawa', 25), ('Kraków', 20), ('Wrocław', 15), ('Gdańsk', 10), ('Poznań', 5)]
# for miasto, temperatura in miasta:
# temp_f = temperatura * 9/5 + 32
# print(f'Temperatura w {miasto} wynosi {temperatura}°C, co odpowiada {temp_f}°F')
# x = 10/3
# print(round(x, 2))
# def obliczanie_temperatury_... | Python | 1 |
_method) = __jni_env.require_class_method("java/nio/file/attribute/BasicFileAttributes\0", "lastModifiedTime\0", "()Ljava/nio/file/attribute/FileTime;\0");
__jni_env.call_object_method_a(self.0.object, __jni_method, __jni_args.as_ptr())
}
}
/// [lastAccessTime](https://devel... | Rust | 0 |
dir.to_str().expect("data_local_dir is not utf-8"),
)?;
}
let defaults: File<FileSourceString> = File::from_str(DEFAULTS, FileFormat::Yaml);
settings.merge(defaults)?;
Ok(settings)
}
pub(crate) fn read_settings() -> anyhow::Result<Config> {
let mut settings = default_settings()?;
// ... | Rust | 0 |
}
}
use crate::*;
use crate::{memory_block::ActivatedMemoryBlock, syscall_defs::*};
use memory_block::{MemoryBlock, Protection};
use std::{os::raw::c_char, ffi::CStr};
use fs::{FileDescriptor, FileSystem/*, MissingFileCallback*/};
use elf::ElfLoader;
use cinterface::MemoryLayoutTemplate;
use goblin::elf::Elf;
pub... | Rust | 0 |
IC_EOI: u32 = 0x0B0;
/// Logical Destination Register (LDR). Read/write in xAPIC mode.
pub const XAPIC_LDR: u32 = 0x0D0;
/// Spurious Interrupt Vector Register (SVR). Read/write. See Section 10.9 for reserved bits.
pub const XAPIC_SVR: u32 = 0x0F0;
/// In-Service Register (ISR); bits 31:0. Read-only.
pub const XAPIC... | Rust | 0 |
r_km64
0x2000_0037, 0x1C00_0001,// VEX_Kmovb_kr_km8
0x2000_0037, 0x1A00_0001,// VEX_Kmovd_kr_km32
0x2000_0037, 0x1E00_0001,// VEX_Kmovw_m16_kr
0x2000_0037, 0x1A00_0001,// VEX_Kmovq_m64_kr
0x2000_0037, 0x1C00_0001,// VEX_Kmovb_m8_kr
0x2000_0037, 0x1A00_0001,// VEX_Kmovd_m32_kr
0x2000_0037, 0x1E00_0001,// VEX_Kmov... | Rust | 0 |
_LamV=LamV, _LamV_bas=LamV_bas, _LamV_core=LamV_core, _LamV_ap=LamV_ap, _Radius=bR * cd))
#SURFACE CONSTRAINT
CompuCellSetup.register_steppable(steppable=surface_constraint(10, _lambda_surface_apical=lambda_surface_apical))
#SUB-APICAL AND SUB-BASAL LONGITUDINAL STIFFNESS CONSTRAINT
CompuCellSetup.register_steppable... | Python | 1 |
InterestRateModel {
base_rate: Rate::saturating_from_rational(5, 100).into(),
kink_rate: Rate::saturating_from_rational(15, 100).into(),
full_rate: Rate::saturating_from_rational(35, 100).into(),
kink_utilization: Ratio::from_percent(80).into(),
... | Rust | 0 |
/// * `pt` - A plaintext of type `Vec<u8>` which must be a multiple of 16 bytes long.
/// * `iv` - An IV of type `[u8; AES_BLOCKSIZE]`
///
/// On success, a ciphertext of type `Vec<u8>` is returned.
/// On failure, a `KcapiError` is returned
///
/// ## Examples
///
/// ```
/// let key = vec![0u8; 16]; // <KEY>
/// let ... | Rust | 0 |
import torch
class Agent():
def __init__(self, critic, critic_optimizer, actor,
actor_optimizer, gamma, lmbda, eps, epochs):
self.critic = critic
self.critic_optimizer = critic_optimizer
self.loss = torch.nn.MSELoss()
self.actor = actor
self.actor_optimize... | Python | 1 |
import os
import re
from collections import defaultdict
from gen_airr_bm.core.analysis_config import AnalysisConfig
def get_sequence_files(analysis_config: AnalysisConfig, model: str, reference_data: str):
comparison_files_dir = defaultdict(set)
ref_dir = f"{analysis_config.root_output_dir}/{reference_data}_... | Python | 1 |
jvalue(&arg0.into())];
// let __jni_env = __jni_bindgen::Env::from_ptr(self.0.env);
// let (__jni_class, __jni_method) = __jni_env.require_class_method("android/transition/TransitionSet\0", "removeListener\0", "(Landroid/transition/Transition$TransitionListener;)Landroid/transition/Trans... | Rust | 0 |
let want = CHUNK_LEN - self.chunk_state.len();
let take = min(want, input.len());
self.chunk_state.update(&input[..take]);
input = &input[take..];
}
}
/// Finalize the hash and write any number of output bytes.
pub fn finalize(&self, out_slice: &mut [u8]) {... | Rust | 0 |
e) if settings["imdb"] else None
TEMPLATE = settings['template']
# waiting overs here @LazyDeveloperr
if imdb:
cap = TEMPLATE.format(
query=search,
title=imdb['title'],
votes=imdb['votes'],
aka=imdb["aka"],
seasons=imdb["seasons"],
... | Python | 1 |
(Backends.native)
if devname.lower() == "hackrf" and self.__hackrf_native_enabled:
supports_rx, supports_tx = True, True
backends.add(Backends.native)
if devname.lower() == "rad1o" and self.__hackrf_native_enabled:
supports_rx, supports_tx = True, True
b... | Python | 1 |
cards[1], cards[2], cards[3], cards[4],
))
}
fn is_straight_flush(ranks: &Vec<u32>, suits: &Vec<Suit>, cards: &Vec<Card>) -> Option<Self> {
let is_low_straight = [13, 4, 3, 2, 1].iter().eq(ranks);
let straight = is_low_straight
|| ranks
.iter()
... | Rust | 0 |
# Tag: String, Sliding Window
# Time: O(N)
# Space: O(1)
# Ref: -
# Note: -
# You are given a binary string s and an integer k.
# A binary string satisfies the k-constraint if either of the following conditions holds:
#
# The number of 0's in the string is at most k.
# The number of 1's in the string is at ... | Python | 1 |
ed as additional
explanation in self.fail().
'''
# task -> (old signature, new signature)
sig_diff = {}
for task in old_sigs:
if task in curr_sigs and \
old_sigs[task] != curr_sigs[task]:
sig_diff[task] = (old_sigs[task], curr_sigs[task])
if not sig_diff:
... | Python | 1 |
#Cristopher Méndez Cervantes | Ángel Cristo Castro Martín
##Teniendo en cuenta que deben de existir las pólizas para trabajar con los siniestros, primeramente el usuario se verá forzado a al menos introducir
#una póliza en el sistema.
from Utilidades import ComprobarMatricula
def CrearSiniestro(id_siniestro:int, nros... | Python | 1 |
# -*- coding: utf-8 -*-
from odoo import exceptions, _
from odoo.http import Controller, request, route
from odoo.addons.bus.models.bus import dispatch
class BusController(Controller):
""" Examples:
openerp.jsonRpc('/longpolling/poll','call',{"channels":["c1"],last:0}).then(function(r){console.log(r)});
... | Python | 1 |
# 各スロットをチェック
for slot in inventory.slots:
if hasattr(slot, 'item') and slot.item:
used_slots += 1
quantity = getattr(slot, 'quantity', 1)
# 重量チェック
if hasattr(slot.item, 'weight'):
total_weight... | Python | 1 |
# 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, software
# distributed under t... | Python | 1 |
method = 'VMRNN_B'
# model
patch_size = 2
depths = 6
window_size = 4
drop_rate = 0.
attn_drop_rate = 0.
drop_path_rate = 0.1
#
embed_dim = 128
num_heads = 8
# training
batch_size = 8
lr = 1e-4
sched = 'cosine'
warmup_epoch = 5
# sched = 'onecycle'
# sched = 'multistep'
# decay_epoch = [40,80]
# decay_rate = 0.1
# sche... | Python | 1 |
with Pool(processes=threads) as pool:
for i in range(int(args.threads)):
Process(target=cruncher, args=(i,)).start()
exit(0)
threads = int(args.threads)
def cruncher(thread_id: int):
db = pymongo.MongoClient()['puzzler']
play_coll = db['puzzle2_puzzle'... | Python | 1 |
# Copyright (C) 2024 qBraid
#
# This file is part of the qBraid-SDK
#
# The qBraid-SDK is free software released under the GNU General Public License v3
# or later. You can redistribute and/or modify it under the terms of the GPL v3.
# See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.ht... | Python | 1 |
},
5 => { //add new pair
println!("Add a new pair (Price_Ticker/Ref_Ticker):\nEnter Price Ticker:");
let price_ticker = get_input_string();
println!("Enter Ref Ticker:");
let ref_ticker = get_input_string();
lib::c... | Rust | 0 |
ffffff", relief="flat", command=handle_study_plan)
plan_button.pack(side="left", padx=10, pady=10)
clear_button = tk.Button(button_frame, text="Clear Doubt", font=("Arial", 14), bg="#4caf50", fg="#ffffff", activebackground="#388e3c", activeforeground="#ffffff", relief="flat", command=handle_clear_doubt)
clear_button.p... | Python | 1 |
map.insert(5, 57); // 500
map.insert(6, 111); // 1000
// hack for task scheduling
map.insert(7, 11); // 100
map.insert(8, 23); // 200
map.insert(9, 34); // 300
map.insert(10, 45); // 400
map.insert(11, 57); // 500
let time_span = 1_000 / map.remove(&setup_val).unwrap();
println... | Rust | 0 |
self.write_line(message);
self.cursor.reset_position()?;
Ok(())
}();
if let Err(e) = result {
eprintln!("Error on TerminalPrinter: {}", e);
}
}
fn write_line(&mut self, message: &str) {
let result = || -> SomaResult<()> {
s... | Rust | 0 |
self.flags.name,
loggers)
self.log.write_flags(self.flags)
def _init_tensorboard(self):
X_test = self.X_test.reshape(self.X_test.shape[0], -1)
sample_task = utils.LayerOutputLogger(self.model, X_test)
model_parameter_task = utils.ModelParameterLogger(self.mode... | Python | 1 |
xt(&mut self) -> Option<Self::Item> {
if let Some((row, idx)) = self.index.next() {
Some((self.data_by_row(row), idx))
} else {
None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn first() {
let data = vec![1, 2, 3, 4];
let index ... | Rust | 0 |
.into_iter().collect::<String>() == s
},
);
prop::test_with_prop(prop, 5, TEST_COUNT, RNG::new())
}
}
use crate::ecs::collision::*;
use crate::ecs::components::*;
use specs::prelude::*;
pub struct Player {}
impl Player {
pub fn new() -> Player {
Player {}
}
}
impl Component for Player... | Rust | 0 |
destroyed (in case of a lower total issuance
/// over freezing period).
type Surplus: OnUnbalanced<NegativeImbalanceOf<Self>>;
/// The issuance to ignore. This is subtracted from the `Currency`'s `total_issuance` to get
/// the issuance by which we inflate or deflate the gilt.
#[pallet::constant]
type Ign... | Rust | 0 |
_base_ = [
'../_base_/models/upernet_convnext.py', '../_base_/datasets/ade20k.py',
'../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py'
]
crop_size = (512, 512)
data_preprocessor = dict(size=crop_size)
checkpoint_file = 'https://download.openmmlab.com/mmclassification/v0/convnext/downstream/co... | Python | 1 |
in_fn = instance.get_typed_func::<(), (), _>(&mut store, "main")?;
// And finally we can call the wasm!
let x = hello.call(&mut store, ())?;
println!("back in rust ecs id {}", x);
let x = component_test.call(&mut store, ())?;
println!("rust component id {}", x);
main_fn.call(&mut store, ())?;
... | Rust | 0 |
tFieldGeometry;
pub fn PxGeometryHolder_heightField(self_: *const PxGeometryHolder, ) -> *const PxHeightFieldGeometry;
pub fn PxGeometryHolder_storeAny_mut(self_: *mut PxGeometryHolder, geometry: *const PxGeometry, ) -> ();
pub fn PxGeometryHolder_new() -> PxGeometryHolder;
pub fn PxGeometryHolder_new_1(geometry: *cons... | Rust | 0 |
from copy import deepcopy
from typing import List, Tuple, Dict, Set
from queue import Queue
import pytest
import numpy as np
from core.roadmap.dispatcher import TaskDispacher
from core.roadmap.constants import ACC_GRAPH_RIGHT
@pytest.mark.unit_test
def test_dispatcher_1() -> None:
start_node: int = 4
data_q... | Python | 1 |
hes
def plot(self) -> None:
plt.clf()
plt.close()
fig, axs = plt.subplots(4, 4)
patch_size = 2 * self.DESCRIPTOR_RADIUS + 1
for i in range(16):
axs[i // 4, i % 4].imshow(
self.descriptors[:, i].reshape([patch_size, patch_size])
)
... | Python | 1 |
able!("All other tokens are for streams"),
}
}
}
}
fn decode_ack_delay(&self, v: u64) -> Duration {
// If we have remote transport parameters, use them.
// Otherwise, ack delay should be zero (because it's the handshake).
if let Some(r) = self.tps.bor... | Rust | 0 |
"""
Write a function takes as input two lists [a_1,...,a_n], [b_1,...,b_n] and returns [a_1+b_1,...,a_n+b_n].
assert sum_list([10,20,30],[15,25,35])==[25,45,65]
"""
def sum_list(a, b):
return [a[i] + b[i] for i in range(len(a))]
def sum_list(a, b):
return [x + y for x, y in zip(a, b)]
def sum_list(a, b):
... | Python | 1 |
import torch
import torch.nn as nn
import torch.nn.functional as F
class CeNetBase(nn.Module):
def __init__(self,
num_entity,
num_relation,
dim,
drop_prop=0.4,
lambdax=0.3,
alpha=0.1,
mode='soft'... | Python | 1 |
{
err(codemap, x.span, DialectError::Def)
}
}
pub(crate) fn check_load<T>(
&self,
codemap: &Arc<CodeMap>,
x: Spanned<T>,
) -> anyhow::Result<Spanned<T>> {
if self.enable_load {
Ok(x)
} else {
err(codemap, x.span, DialectEr... | Rust | 0 |
from back_game.app_settings.views import (
create_lobby,
is_user_in_lobby,
join_lobby,
join_specific_lobby,
join_tournament,
)
from django.urls import path
urlpatterns = [
path("create_lobby/", create_lobby, name="create_lobby"),
path("join_lobby/", join_lobby, name="join_lobby"),
path(... | Python | 1 |
pub data: FLAC__EntropyCodingMethod__bindgen_ty_1,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union FLAC__EntropyCodingMethod__bindgen_ty_1 {
pub partitioned_rice: FLAC__EntropyCodingMethod_PartitionedRice,
_bindgen_union_align: [u64; 2usize],
}
#[test]
fn bindgen_test_layout_FLAC__EntropyCodingMethod__bindgen... | Rust | 0 |
p(self, agent))]
async fn update_plugin(
&self,
agent: &HttpAgent,
id: &PackageId,
path: &Path,
) -> Result<(), CliError> {
let target = fluvio_index::package_target()?;
debug!(%target, %id, "Fluvio CLI updating plugin:");
let version = fetch_latest_versi... | Rust | 0 |
AppSettings::UnifiedHelpMessage,
])
.subcommand(modules_cli::make_subcommand())
.subcommand(bindings_cli::make_subcommand())
.subcommands(hardware_cli::make_subcommands())
}
/// Determine which child rust module is responsible for the command and pass
/// the execution to i... | Rust | 0 |
from contextlib import asynccontextmanager
import logging
from fastapi import FastAPI
from app.api.v1.endpoints import user, posts, comments
from app.pubsub.async_kafka_producer import AsyncKafkaProducer
from app.core.async_elasticsearch_client import AsyncElasticsearchClient
logging.basicConfig(
level=logging.D... | Python | 1 |
= "dev-dependencies")]
dev_dependencies: Option<BTreeMap<String, TomlDependency>>,
#[serde(rename = "dev_dependencies")]
dev_dependencies2: Option<BTreeMap<String, TomlDependency>>,
}
impl TomlTarget {
fn new() -> TomlTarget {
TomlTarget::default()
}
fn name(&self) -> String {
... | Rust | 0 |
d endpoints of the stream.
send_endpoints: Vec<SendEndpoint<Arc<Message<D>>>>,
}
impl<D> StreamEndpoints<D>
where
for<'a> D: Data + Deserialize<'a>,
{
pub fn new(stream_id: StreamId, stream_name: String) -> Self {
Self {
stream_id,
stream_name,
recv_endpoints: Ve... | Rust | 0 |
= expr.bind("i").map_err(|_| LayoutParseError)?;
Ok(Some(TimePattern {
values: (0..ndiv).map(|i| func(i as f64) as f32).collect(),
nbeats,
}))
}
TimeInput::Poly {
ndiv0,
ndiv1,
nbeats,
} => {
if ndiv0 == 0 || ndiv1 == 0 {
return Err(LayoutParseError);
}
let mut out: Vec<f32> =... | Rust | 0 |
rete_output.device),
},
output=bsym.output,
)
else:
assert isinstance(new_concrete_output, torch.Tensor)
new_bsym = BoundSymbol(
thunder.prims.t... | Python | 1 |
assert_eq!(
"a + b",
print_eqn(&Expr0::Op2(
BinaryOp::Add,
Box::new(Expr0::Var("a".to_string(), Loc::new(1, 2))),
Box::new(Expr0::Var("b".to_string(), Loc::new(5, 6))),
Loc::new(0, 7),
))
);
assert_eq!(
"a + b * c",
print_eq... | Rust | 0 |
import sys
import pyparsing as pp
from src.core import Term, Atom
from src.ilp import Language_Frame, Program_Template, Rule_Template
from src.dilp import DILP
import tensorflow as tf
tf.compat.v1.enable_eager_execution()
# relationship will refer to 'track' in all of your examples
relationship = pp.Word(pp.alphas)... | Python | 1 |
(VecStorage)]
pub struct Hero {
pub lives: i32,
pub score: i32,
pub blinking: bool,
pub render: bool,
pub reset_position: bool,
pub blink_timer: Duration,
}
#[derive(Component, Debug, Copy, Clone)]
#[storage(VecStorage)]
pub struct Boss {
pub lives: i32,
pub normal_lives: ... | Rust | 0 |
# Copyright 2013 DEVSIM LLC
#
# SPDX-License-Identifier: Apache-2.0
import devsim
import test_common
device = "MyDevice"
region = "MyRegion"
contacts = ("top", "bot")
def run_initial_bias(use_circuit_bias, net_doping=1e16):
"""
use_circuit for topbias
"""
test_common.SetupResistorConstants(device, r... | Python | 1 |
print ("*******************")
print ("Bem Vindo ao jogo!!")
print ("*******************")
numero_secreto = 972
total_tentativas = 25
rodada = 1
while (rodada <= total_tentativas):
print(f"tentativa {rodada} de {total_tentativas}")
chute_str = input ("digite seu número:")
print ("você digitou o numero:",... | Python | 1 |
#!/usr/bin/env python
# Copyright NumFOCUS
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0.txt
#
# Unless required by applicable law or... | Python | 1 |
))
plt.rcParams["font.size"] = 80
for ax in axs.flatten():
ax.tick_params(axis="both", labelsize=80)
num_bins = 1000
# Tensor distribution - original
if tensor is not None:
axs[0, 0].hist(tensor, bins=num_bins, color="blue", alpha=0.5)
axs[0, 0].set_title(f"Original Distribu... | Python | 1 |
aking.mint == mint_reserve.key(),
constraint = token_reserve_staking.owner == treasury.key(),
constraint = token_reserve_staking.key() == treasury.load()?.token_reserve_staking
)]
pub token_reserve_staking: Box<Account<'info, TokenAccount>>,
#[account(
mut,
... | Rust | 0 |
A;
pub const IMAGE_REL_MIPS_SECREL: WORD = 0x000B;
pub const IMAGE_REL_MIPS_SECRELLO: WORD = 0x000C;
pub const IMAGE_REL_MIPS_SECRELHI: WORD = 0x000D;
pub const IMAGE_REL_MIPS_TOKEN: WORD = 0x000E;
pub const IMAGE_REL_MIPS_JMPADDR16: WORD = 0x0010;
pub const IMAGE_REL_MIPS_REFWORDNB: WORD = 0x0022;
pub const IMAGE_REL_... | Rust | 0 |
(inst.durations[op_id], j, o)
})
.unwrap()
.0
});
}
pub fn find_solution_lpt(inst: &Instance) -> Solution {
return find_solution(&inst, &mut |candidates| {
candidates
.iter()
.enumerate()
.max_by_key(|&(_, &op_id)| {
let [j, o] = inst.op_from_id(op_id);
... | Rust | 0 |
to_owned() });
let b : Arc<Stored> = Arc::new(B::Str("Hello World".to_owned()));
let c : Arc<Stored> = Arc::new(B::Int(42));
// ... and then transform it to trait objects.
// We use clone here so we can later assert that de-/serialization does not
// change anything.
let... | Rust | 0 |
s and their dependencies on source
files.
You cannot build extension modules with this function, that is,
using ``-c`` is not allowed. Use the ``compile`` command instead.
Examples
--------
The command ``f2py -m scalar scalar.f`` can be executed from Python as
follows.
.. literalinclu... | Python | 1 |
ub fn is_1(&self) -> bool {
*self == CH4OC_A::_1
}
}
#[doc = "Write proxy for field `CH4OC`"]
pub struct CH4OC_W<'a> {
w: &'a mut W,
}
impl<'a> CH4OC_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CH4OC_A) -> &'a mut W {
{
... | Rust | 0 |
] .
pub fn case_action(input: &str) -> ParseResult<(Vec<Expression>, Statement)> {
tuple((comma_separated(case_label), char(':'), stmt))
.map(|(labels, _colon, statement)| (labels, statement))
.parse(input)
}
/// 190 case_label = [expression] .
pub fn case_label(input: &str) -> ParseResult<Expressi... | Rust | 0 |
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) Saga Inc.
# Distributed under the terms of the GPL License.
"""
Contains tests for the cast_output decorator.
"""
import pandas as pd
import pytest
from mitosheet.public.v1.sheet_functions.types.decorators import cast_output
CAST_TESTS = [
(
[pd.Serie... | Python | 1 |
_since_improvement += 1
print("\nEpochs since last improvement: %d\n" % (epochs_since_improvement,))
else:
epochs_since_improvement = 0
save_checkpoint(epoch, encoder, decoder, encoder_optimizer, decoder_optimizer, input_lang, output_lang,
val_loss, is_be... | Python | 1 |
import os
from openai import OpenAI
def f(project):
client = OpenAI(
api_key=os.getenv("ZHIPUAI_API_KEY"),
base_url="https://open.bigmodel.cn/api/paas/v4/"
)
tools = [{
"type": "web_search",
"web_search": {
"enable": True # 启用网络搜索
}
}]
r... | Python | 1 |
),
)
}
}
fn connect_property_wep_tx_keyidx_notify<F: Fn(&Self) + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_wep_tx_keyidx_trampoline<P, F: Fn(&P) + 'static>(
this: *mut nm_sys::NMSettingWirelessSecurity,
_par... | Rust | 0 |
::*;
#[test]
fn should_build_config() {
let config = EmailClientConfig::build();
assert!(config.forward_all_emails_to_fixed_recipients.is_none());
}
/*
#[test]
fn should_build_optional_fixed_recipients() {
std::env::set_var("LS_EMAIL_FORWARD_ALL_EMAILS_TO_FIXED_RECIPIE... | Rust | 0 |
let heap = FrozenHeap::new();
let fs: FrozenStringValue = heap.alloc_string_value("xyz");
let fv: FrozenValue = heap.alloc_string_value("xyz").unpack();
assert_eq!(Hashed::new(fs).hash(), fv.get_hashed().unwrap().hash());
assert_eq!(Hashed::new(s).hash(), Hashed::new(fs).hash())... | Rust | 0 |
test_html(b"<pre>\tworld</pre>", " world\n", 40);
test_html(b"<pre>H\tworld</pre>", "H world\n", 40);
test_html(b"<pre>He\tworld</pre>", "He world\n", 40);
test_html(b"<pre>Hel\tworld</pre>", "Hel world\n", 40);
test_html(b"<pre>Hel... | Rust | 0 |
/ (tp + fp).sum().float() * 100.0
r_o = tp.sum().float() / (tp + fn).sum().float() * 100.0
f_o = 2 * p_o * r_o / (p_o + r_o)
if i % 100 == 0:
print_log_message('Test: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
... | Python | 1 |
# 1- Crea una lista con los números del 1 al 5. Muestra el contenido de la lista por pantalla.
# numeros = [1, 2, 3, 4, 5]
# print(numeros[3])
# 2- Crea una lista vacía. Agrega los nombres "Ana", "Luis" y "Carlos" usando el método append() y luego imprime la lista.
""" nombres = []
nombres.append("Ana")
nombres.append... | Python | 1 |
from typing import Tuple
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
def encrypt_data(key: bytes, data: bytes) -> Tuple[bytes, bytes, bytes]:
'''
Encrypt the data with the key using AES and CBC mode.
The provided key bytes is long enough (>= 64 bytes). Use the prefix of the provided... | Python | 1 |
writeln!(w, "impl modules::Timer16 for {} {{", TYPE_NAME)?;
writeln!(w, " type CompareA = {};", find_reg_suffix("OCR", "A").name)?;
writeln!(w, " type CompareB = {};", find_reg_suffix("OCR", "B").name)?;
writeln!(w, " type Counter = {};", find_reg("TCNT").name)?;
writeln!(w, " ... | Rust | 0 |
perty
def time_created(self):
"""
**[Required]** Gets the time_created of this SecurityAttribute.
Date and time the security attribute was created, in the format defined by RFC3339.
Example: `2016-08-25T21:10:29.600Z`
:return: The time_created of this SecurityAttribute.
... | Python | 1 |
from django.utils.translation import gettext_lazy as _
#: All 31 states, plus the `Ciudad de México`.
STATE_CHOICES = (
('AGU', _('Aguascalientes')),
('BCN', _('Baja California')),
('BCS', _('Baja California Sur')),
('CAM', _('Campeche')),
('CDMX', _('Ciudad de México')),
('CHH', _('Chihuahua')... | Python | 1 |
iant(INT_PERIOD_A::WDT2POW24)
}
#[doc = "2**23 clock cycles."]
#[inline(always)]
pub fn wdt2pow23(self) -> &'a mut W {
self.variant(INT_PERIOD_A::WDT2POW23)
}
#[doc = "2**22 clock cycles."]
#[inline(always)]
pub fn wdt2pow22(self) -> &'a mut W {
self.variant(INT_PERIOD_A:... | Rust | 0 |
sync_on;
self.voices[v_num].ring = ring_on;
self.voices[v_num].test = test_on;
if test_on {
self.voices[v_num].wf_cnt = 0;
}
}
}
}
// SDL2 audio callback implementation - this is where the samples are being converted to output sound
#[cfg(no... | Rust | 0 |
str = "system_name";
rpc_methods_vec.push(state_name_name);
io.add_sync_method(state_name_name, |_: Params| {
let parsed = "world";
Ok(Value::String(format!("hello, {}", parsed)))
});
// system_version
let state_version_name: &str = "system_version";
rpc_methods_vec.push(state_version_name);
io.add_sync_met... | Rust | 0 |
yntax!")),
}
}
/// ### parse_lstime
///
/// Convert ls syntax time to System Time
/// ls time has two possible syntax:
/// 1. if year is current: %b %d %H:%M (e.g. Nov 5 13:46)
/// 2. else: %b %d %Y (e.g. Nov 5 2019)
pub fn parse_lstime(tm: &str, fmt_year: &str, fmt_hours: &str) -> Result<SystemTime, ParseError> {... | Rust | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020 Alibaba Group Holding Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache... | Python | 1 |
ref-counted and cloneable. With these you lock the mutex and
/// get access to the stored data.
#[derive(Clone)]
pub struct MutexRef<T> {
rc_ref: RcRef<*const Mutex<T>>,
}
impl<T> MutexRef<T> {
fn mutex(&self) -> &Mutex<T> {
unsafe { &**self.rc_ref }
}
/// Acquires the mutex.
///
/// ... | Rust | 0 |
class Solution:
def kthFactor(self, n: int, k: int) -> int:
# If i is a divisor of n, then n // i is also a divisor of n. So, we can
# find all the divisors of n by processing the numbers <= sqrt(n).
factor = 1
i = 0 # i-th factor
while factor < int(math.sqrt(n)):
if n % factor == 0:
... | Python | 1 |
"""Create settings and application directly from embeddings.
This is a convenience method that creates a TxtAISettings instance
and initializes an Application from an embeddings path in one step.
Args:
embeddings_path: Path to embeddings directory or archive file
... | Python | 1 |
# Copyright (c) 2014 The University of Manchester
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | Python | 1 |
from openai import OpenAI
# Modify OpenAI's API key and API base to use vLLM's API server.
openai_api_key = "EMPTY"
openai_api_base = "http://localhost:8000/v1"
client = OpenAI(
# defaults to os.environ.get("OPENAI_API_KEY")
api_key=openai_api_key,
base_url=openai_api_base,
)
models = client.models.list(... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.