text string | label_name string | labels int64 |
|---|---|---|
print ("\33[1;35;40mQual é o maior número?\n\33[m")
numeros=[]
for i in range(5):
numeros.append(float(input(f"\33[1;37;40mInforme o {i+1}° número: \33[m")))
print("\33[1;35;40mO maior número é: \33[m", max(numeros))
#Isso aqui abaixo funciona tmb!
# if (numeros[0] > numeros[1] and numeros[0] > numeros[2] and n... | Python | 1 |
np.zeros((d,d),dtype=np.complex))
W_delta[i,j]=delta
W_hat[k]=W[k]+W_delta
check_gradient_W[k][i,j]=( obj_func.objective_func_UW(Nr,Nt,d,Pt,sigma,User,H,W_hat,U) - obj_func.objective_func_UW(Nr,Nt,d,Pt,sigma,User,H,W,U) )/(2*delta)
... | Python | 1 |
) as $offsets_name: ident
) => {
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
$struct_vis struct $offsets_name {
$(
$field_vis $field: usize
),*
}
$( #[$attribute] )*
#[repr(C)]
$struct_vis struct $name {
$(
$field_vis $field: $ftype
),*
}
impl $name {
///... | Rust | 0 |
version
std::os::unix::fs::symlink(&to_install, current).unwrap();
} else {
println!("Installing first version");
std::os::unix::fs::symlink(&to_install, current).unwrap();
}
// Install all the links for the new... | Rust | 0 |
te bindings!");
}
use std::cmp::{Ord, Ordering};
use std::fmt::{self, Debug};
use syn::Ident;
use crate::graph::{Node, Disambiguate};
#[cfg_attr(test, derive(PartialEq))]
pub enum Leaf {
Trivia,
Token {
ident: Ident,
priority: usize,
callback: Option<Ident>,
},
}
impl Leaf {
... | Rust | 0 |
class Solution:
def numberToWords(self, num: int) -> str:
if num == 0:
return "Zero"
digits = [
"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seven... | Python | 1 |
s is normally done
//! via `liblog` (a native Android lib). Instead of using `liblog`, this crate
//! writes directly to the `logd` socket with the trivial protocol below.
//! This logger is written in pure Rust without any need for ffi.
//!
//! [log]: https://docs.rs/log/*/log/
//! [`error!`]: https://docs.rs/log/*/lo... | Rust | 0 |
let t1 = *s_sub_sc_t.get_unchecked(i) - *s_sub_sc.get_unchecked(i);
flag = flag * (ClearModp::from(1) - t1.reveal());
let t1 = *s_sub_cs_t.get_unchecked(i) - *s_sub_cs.get_unchecked(i);
flag = flag * (ClearModp::from(1) - t1.reveal());
let t1 = *s_sub_ss_t.get_unchecked(i) - *s_sub_ss... | Rust | 0 |
ess that created the specified window.
pub fn get_window_thread_process_id(hwnd: HWND) -> (DWORD, DWORD) {
unsafe {
let mut process_id: DWORD = 0;
let thread_id = winapi::um::winuser::GetWindowThreadProcessId(
hwnd,
&mut process_id as *mut _ as LPDWORD,
);
(th... | Rust | 0 |
# Some examples of reading text files with different options
#
# The file sample.txt is a UTF-8 encoded text file with Windows
# line-endings (\r\n).
# (a) Reading a basic text file (UTF-8 default encoding)
print("Reading a simple text file (UTF-8)")
with open('sample.txt', 'rt') as f:
for line in f:
prin... | Python | 1 |
.chars()
.enumerate()
.filter(|(_, ch)| *ch == '#')
.map(move |(c, _)| (r.try_into().unwrap(), c.try_into().unwrap()))
})
.collect();
let (laser_pos, asteroid_rays): (Point, HashMap<Point, Vec<Point>>) = map
.iter()
.map(|(r0, c0)| {
... | Rust | 0 |
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from typing_extensions import TypedDict
from unstructured_client.types import BaseModel
class ElasticsearchConnectorConfigTypedDict(TypedDict):
es_api_key: str
hosts: str
index_name: str
class Ela... | Python | 1 |
import steel
COMPRESSION_TYPES = (
(0, 'No compression'),
(1, '8-bit RLE'),
(2, '4-bit RLE'),
(3, 'Bit Field'),
(4, 'JPEG'), # Generally not supported for screen display
(5, 'PNG'), # Generally not supported for screen display
)
class PaletteColor(steel.Structure):
blue = steel.Integer... | Python | 1 |
fn get_code_points_offset_length(&self, _index: usize, code_point_offset: usize) -> usize {
code_point_offset
}
fn get_word_candidate_length(&self, _index: usize) -> usize {
0
}
}
fn build_plugin() -> MecabOovPlugin {
let mut plugin = MecabOovPlugin {
categories: HashMap::new... | Rust | 0 |
n::{prelude::*, JsCast, JsValue};
use wasm_bindgen_futures::spawn_local;
use web_sys::{
ErrorEvent, MessageEvent, RtcConfiguration, RtcDataChannel, RtcDataChannelInit,
RtcDataChannelType, RtcIceConnectionState, RtcPeerConnection, RtcPeerConnectionIceEvent,
RtcSdpType, RtcSessionDescriptionInit, WebSocket,
}... | Rust | 0 |
c", "mod2_lib1.c"))
assert os.path.exists(os.path.join(extract_dir, "codegen", "host", "include", "tvmgen_mod1.h"))
assert os.path.exists(os.path.join(extract_dir, "codegen", "host", "include", "tvmgen_mod2.h"))
# check CRT runtime directory
assert os.path.exists(os.path.join(extract_dir, "runtime"))
... | Python | 1 |
::{Deserialize, Serialize};
use std::{fmt, net::SocketAddr};
use unwrap::unwrap;
const MSG_HEADER_LEN: usize = 9;
const MSG_PROTOCOL_VERSION: u16 = 0x0001;
/// Final type serialised and sent on the wire by QuicP2p
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum WireMsg {
EndpointEchoReq,
EndpointEcho... | Rust | 0 |
func.blocks.insert(MilBlockId(4), create_test_block(MilBlockId(4), &[], &[], MilEndInstructionKind::Return(Some(MilOperand::RefNull))));
func.block_order = vec![MilBlockId(0), MilBlockId(1), MilBlockId(2), MilBlockId(3), MilBlockId(4)];
let mut cfg = FlowGraph::for_function(&func);
as... | Rust | 0 |
from uuid import UUID
import pytest
from supriya.patterns import (
ChainPattern,
Event,
EventPattern,
NoteEvent,
SequencePattern,
)
from .conftest import run_pattern_test
@pytest.mark.parametrize(
"stop_at, input_a, input_b1, input_b2, input_c, expected, is_infinite",
[
(
... | Python | 1 |
>
where
T: AnimationSampling,
T::Channel: DeserializeOwned + Serialize,
T::Primitive: DeserializeOwned + Serialize,
{
type SystemData = (
ReadExpect<'a, Loader>,
Read<'a, AssetStorage<Sampler<T::Primitive>>>,
Read<'a, AssetStorage<Animation<T>>>,
);
type Result = Handle<A... | Rust | 0 |
import os
import unittest
import json
from typing import Dict
import jc.parsers.proc_iomem
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
class MyTests(unittest.TestCase):
f_in: Dict = {}
f_json: Dict = {}
@classmethod
def setUpClass(cls):
fixtures = {
'proc_iomem': (
... | Python | 1 |
run() -> Result<Key, Error> {
pub fn run() -> Result<(), Error> {
let json = r###"{"key":"<KEY>"}"###;
let config : Config = serde_json::from_str(json).unwrap();
// let config = serde_json::from_str(json).unwrap() as Config;
// let key = c.key;
// println!("The config is {:?}", config);
// let serialized... | Rust | 0 |
/directory_foo",
);
te.assert_output(
&["foo", "one/two/three"],
"one/two/three/d.foo
one/two/three/directory_foo",
);
te.assert_output_subdirectory(
"one/two",
&["foo", "../../"],
"../../a.foo
../../one/b.foo
../../one/two/c.foo
... | Rust | 0 |
!("Watch error: {:?}", e),
_ => (),
}
}
}
fn replace(args: &ArgMatches) {
if args.is_present("css-only") {
make_css(args);
return;
}
if args.is_present("watch") {
watch(args).unwrap();
return;
}
let input = get_input_from(args);
let out... | Rust | 0 |
import pytest
from click.testing import CliRunner
from patchwork.app import cli, find_patchflow
@pytest.fixture
def config_dir(tmp_path):
config_dir = tmp_path / "config"
config_dir.mkdir(parents=True, exist_ok=True)
return config_dir
@pytest.fixture
def patchflow_dir(config_dir):
patchflow_dir = c... | Python | 1 |
join(
old_folder, f"videos/chunk-{episode_chunk:03d}/{video_key}/episode_{old_index}.mp4"
),
os.path.join(old_folder, f"videos/chunk-000/{video_key}/episode_000000.mp4"),
]
# Find the first existing source path
source_video_path = ... | Python | 1 |
from .encoder_decoder_window_service import EncoderDecoderWindowService
from .tokenizer_service import TokenizerService
class T0ppWindowService(EncoderDecoderWindowService):
def __init__(self, service: TokenizerService):
super().__init__(service)
@property
def max_sequence_length(self) -> int:
... | Python | 1 |
);
assert_eq!(
unsafe {
&(*(::core::ptr::null::<usb_device_descriptor_t>())).bLength as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(usb_device_descriptor_t),
"::",
stringify!(bLength)
)
);
assert_eq!(
unsafe {
&(*(::core::ptr::null::<usb_device_descriptor_t>()... | Rust | 0 |
);
// initialize logging; no need for this level of safety, but why the hell not
INITIALIZE.call_once(|| configure_logging(input_args.verbosity));
if !input_args.binary.is_file() {
error!(
"Binary {} does not exist or is not a file.",
input_args.binary.display()
);
... | Rust | 0 |
the provider has been instantiated so Mbed Crypto has been initialized
// * self.key_handle_mutex prevents concurrent accesses
// * self.key_slot_semaphore prevents overflowing key slots
unsafe {
key_handle = KeyHandle::open(key_id)?;
key_attrs = key_handle.attribute... | Rust | 0 |
{
(d & 0xffe00c00) == 0x38c00400
}
pub const fn is_STR_B_ldst_immpost(d: u32) -> bool {
(d & 0xffe00c00) == 0x3c000400
}
pub const fn is_LDR_B_ldst_immpost(d: u32) -> bool {
(d & 0xffe00c00) == 0x3c400400
}
pub const fn is_STR_Q_ldst_immpost(d: u32) -> bool {
(d & 0xffe00c00) == 0x3c800400
}
pub co... | Rust | 0 |
tate_dict(checkpoint['model'], strict=False)
if args.model != 'lavt_one':
model_class = BertModel
bert_model = model_class.from_pretrained(args.ck_bert)
if args.ddp_trained_weights:
bert_model.pooler = None
bert_model.to(args.local_rank)
bert_model = torch.nn.par... | Python | 1 |
# setup.py
#
# DO NOT REMOVE setup.py. It is needed for
# including example files in the shipped package
import os
import shutil
from setuptools import setup
from setuptools.command.build_py import build_py as _build_py
class build_py(_build_py):
def run(self):
super().run()
extra_dirs = [
... | Python | 1 |
.
*/
/// Convert raw genome weights to actual weights used in the network.
pub fn raw_to_weight(raw: u32) -> f64 {
((raw as f64) - 524288.0) / 10000.0
}
/// Converts a segment of a genome from its base-4 ATCG reprecentation to
/// a number.
fn to_num(segment: &[u8]) -> u32 {
// We are essentially doing a base 4... | Rust | 0 |
import argparse
from zipfile import ZipFile
import os
def main(args):
addon_name = 'mitsuba-blender'
base_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
addon_dir = os.path.join(base_dir, addon_name)
with ZipFile('mitsuba-blender.zip', 'w') as archive:
# Package miscellaneo... | Python | 1 |
AAU" => 'N',
b"CCA" => 'P',
b"CCC" => 'P',
b"CCG" => 'P',
b"CCT" => 'P',
b"CCU" => 'P',
b"CAA" => 'Q',
b"CAG" => 'Q',
b"AGA" => 'R',
b"AGG" => 'R',
b"CGA" => 'R',
b"CGC" => 'R',
b"CGG" => 'R',
b"CGT" => 'R',
... | Rust | 0 |
import unittest
from main.org.core.chromosome.template import Template
from main.org.core.post_process.post_process_chromosomes import *
class Test(unittest.TestCase):
def test_remove_clones(self):
# 1) construct the pop of chromosomes
t1 = Template(['generate', 'code', '*'])
t2 = Templa... | Python | 1 |
cfg(feature = "dim2")]
let normalizer = na::convert::<_, N>(4.0) / (N::pi() * h.powi(8));
#[cfg(feature = "dim3")]
let normalizer = na::convert::<_, N>(315.0 / 64.0) / (N::pi() * h.powi(9));
if r <= h {
normalizer * (h * h - r * r).powi(3)
} else {
N::zer... | Rust | 0 |
ub span: Span
}
impl JParameter {
pub fn new(span: Span, ty: JType, name: Ident) -> Self {
JParameter {
name: name,
ty: ty,
span: span
}
}
}
impl Display for JParameter
{
fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> {
formatter.write_fmt(format_args!("{} ", self.ty... | Rust | 0 |
m` manual*. The Open Group, 2016.
//! [The Open Group Base Specifications Issue 7](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/cksum.html).
//!
//! [1]: https://en.wikipedia.org/wiki/Cksum
#[cfg(feature = "generic")]
extern crate digest;
#[cfg(feature = "generic")]
extern crate generic_array;
use core... | Rust | 0 |
import requests
from time import sleep
from utils.image_utils import capture_and_convert_to_base64 # 导入通用方法
import config # 导入配置文件
# 将 Base64 编码的图片数据传递给 OpenAI API
def send_to_openai(image_base64, text):
url = config.OPENAI_BASE_URL # OpenAI API 接口地址
headers = {
"Content-Type": "application/json",
... | Python | 1 |
"""
A small Python program that uses the GitHub search API to list
the top projects by language, based on stars.
GitHub Search API documentation: https://developer.github.com/v3/search/
Additional parameters for searching repos can be found here:
https://help.github.com/en/articles/searching-for-repositories#search-b... | Python | 1 |
'initial_values']):
args = (kwds.pop('M'),
kwds.pop('m'),
kwds.pop('coeffs'),
kwds.pop('initial_values'))
M, m, coeffs, initial_values = self.parse_direct_arguments(*args)
else:
raise ValueError("Number of positiona... | Python | 1 |
db.get_monitor_map().unwrap(),
HashMap::from_iter(vec![(monitor_id.clone(), monitor_data.clone())])
);
}
// Inserting a monitor that overlaps subaddresses of another monitor should result in an error.
#[test_with_logger]
fn test_overlapping_add_monitor_fails(logger: Logger) {
... | Rust | 0 |
from django.db import models
from django.contrib.auth.models import User
from tasks.models import Task
class Comment(models.Model):
"""
Comment model, related to User and Task
"""
owner = models.ForeignKey(User, on_delete=models.CASCADE)
task = models.ForeignKey(Task, on_delete=models.CASCADE)
... | Python | 1 |
l, weights_path, number_images=100):
generator = conditioal_net_utils.generator_SN(self.config.LATENT_DIM, self.config.IMAGE_SHAPE,self.config.num_classes,
self.config.NUMBER_RESIDUAL_BLOCKS, base_name="generator")
generator.load_weights(weights_path)
... | Python | 1 |
covery = 1u8;
if lchk.is_null() {
/* Mark end of the window */
(*asoc).fast_recovery_tsn = (*asoc).sending_seq.wrapping_sub(1u32)
} else {
(*asoc).fast_recovery_tsn = (*lchk).rec.data.tsn.wrapping_sub(1u32)
}
... | Rust | 0 |
t path= Path::new( &code_dir() )
.join("rust")
.join("advent-of-code")
.join(year)
.join(type_dir)
.join(filename);
path.to_str().unwrap().to_string()
}
pub fn unittest_dir(year :&str, filename :&str) -> String {
file_dir(year, filename, "unittest")
}
pub fn data_dir(ye... | Rust | 0 |
tation:
# rotate the point cloud
euler_ab=np.random.rand(3)*np.pi*2/self.rot_factor # anglez, angley, anglex
rot_ab= Rotation.from_euler('zyx', euler_ab).as_matrix()
if(np.random.rand(1)[0]>0.5):
src_pcd=np.matmul(rot_ab,src_pcd.T).T
... | Python | 1 |
apshot_load.put(
snapshot_path="foo",
mem_backend={"backend_type": "File"},
)
# API request with invalid `backend_type` should fail.
with pytest.raises(
RuntimeError, match="unknown variant `foo`, expected `File` or `Uffd`"
):
vm.api.snapshot_load.put(
... | Python | 1 |
import numpy as np
# Define the grid
grid = np.array([['x', 'x', 'x'], ['x', '73', '47'], ['x', 'x', 'x']])
# Define the range of possible numbers
numbers = list(range(34, 79))
# Remove the numbers already in the grid from the list of possible numbers
for row in grid:
for num in row:
if num != 'x' and i... | Python | 1 |
# "Copyright 2025, Battelle Energy Alliance, LLC All Rights Reserved"
from __future__ import division
from operator import *
import statistics
import sys
import csv
# Import code for model simulation:
from pypdevs.simulator import Simulator
import matplotlib.pyplot as plt
import numpy as np
import pylab
import time... | Python | 1 |
/// let foo = try_get_provider_param!(params, "foo");
/// ```
#[macro_export]
macro_rules! try_get_provider_param {
( $params:expr , $key:tt ) => {
match $params.remove($key) {
Some(value) => value,
None => return Box::new(future::err(BrokerError::ProviderInput(
conc... | Rust | 0 |
<reponame>balrog-rust/cursive
use crate::logger;
use crate::theme;
use crate::view::View;
use crate::Printer;
use crate::Vec2;
use unicode_width::UnicodeWidthStr;
/// View used for debugging, showing logs.
pub struct DebugView {
// TODO: wrap log lines if needed, and save the line splits here.
}
impl DebugView {... | Rust | 0 |
import os
os.system('cls' if os.name == 'nt' else 'clear')
n=10
print (n)
print("La suma de 5 + 3 es:", 5+3)
print("La resta de 10 - 5 es:", 10-5)
print("La multiplicacion 100 * 2 es:", 100*2)
print("La division de 20 / 10 es:", 20/10)
| Python | 1 |
h independently at random with
// probability p.)
// [TODO] Switch to the faster implementation using geometric distributions
// for sparse graphs.
fn get_er_graph(&mut self, n: u64, p: f64) -> CLQResult<Self::GraphType> {
let mut v = Vec::new();
let mut rng = rand::thread_rng();
... | Rust | 0 |
nd="#BDB77A", activebackground='orange', fg="white", cursor="hand2", command=clear)
cle_btn.place(x=130, y=650)
# The next button
nex_btn = Button(text="Next", width=14, font=("Georgia", 10, 'bold'), borderwidth=1,
background="#70E121", activebackground='orange', fg="white", cursor="hand2")
nex_btn.pl... | Python | 1 |
(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 27)) | (((value as u32) & 0x01) << 27);
self.w
}
}
#[doc = "Reader of field `ENABLE_PRESENT`"... | Rust | 0 |
::Value("Integer overflow".into())),
op_subtract_underflow_int: "-9223372036854775807 - 2" => Err(Error::Value("Integer overflow".into())),
op_subtract_overflow_float: "2e308 - -2e308" => Ok(Float(std::f64::INFINITY)),
op_subtract_round_int_float: "9223372036854775807 - -10.0" => Ok(Float(9_223_372_036_854_... | Rust | 0 |
cp.CtX01UyCeO0.JAG.AHPpx5",
},
{
pass: "<PASSWORD>(`",
hash: "$7$A!....1....TrXs5Zk6s8sWHpQgWDIXTR8kUU3s6Jc3s.DtdS8M2i4$a4ik5hGDN7foMuHOW.\
cp.CtX01UyCeO0.JAG.AHPpx5",
},
{
pass: "<PASSWORD>(`",
hash: "$7$... | Rust | 0 |
from django.db import models
class MinimalUser(models.Model):
REQUIRED_FIELDS = ()
USERNAME_FIELD = "id"
| Python | 1 |
execute_with_policy(usecase, &policy, &ctx)
.await
.map(|event| HttpResponse::Ok().json(APIResponse::new(event)))
.map_err(|e| match e {
UseCaseErrorContainer::Unauthorized(e) => NettuError::Unauthorized(e),
UseCaseErrorContainer::UseCase(e) => handle_error(e),
})... | Rust | 0 |
(&mut self) -> Result<()> {
try!(self.pong());
Ok(())
}
fn process_pong(&mut self) -> Result<()> {
// TODO
Ok(())
}
fn process_message(&mut self, args: &MessageArg, message: Vec<u8>) -> Result<()> {
if let Some((Some(max), delivered)) = self.dispatch_message(arg... | Rust | 0 |
y contains following keys.
- scores (Tensor): Classification scores, has a shape
(num_instance, )
- labels (Tensor): Labels of bboxes, has a shape
(num_instances, ).
- bboxes (Tensor): Has a shape (num_instances, 4),
the last dimension... | Python | 1 |
lel, so the fsync may complete before the write is issued to the storage. The same is also true for previously issued writes that have not completed prior to the fsync.
#[derive(Debug)]
pub struct Fsync {
fd: types::Target,
;;
/// The `flags` bit mask may contain either 0, for a normal f... | Rust | 0 |
0, 64.0, -18.0);
let entity = w
.create_entity()
.with(PositionComponent {
current: old_pos,
previous: old_pos,
})
.build();
// Trigger flagged storage event.
w.write_component::<PositionComponent>()
.g... | Rust | 0 |
tore` trait](trait.RStore.html), so that all
types stored in an [`RData`](struct.RData.html) must implement `GStore`.
This trait is automatically implemented for most types. The main counterexample is
[`Root`](struct.Root.html) (and any type which transitively contains a `Root`, like
[`Val`](enum.Val.html)), bec... | Rust | 0 |
0: u32 = 0;
pub const RTE_IPV4_MAX_PKT_LEN: u32 = 65535;
pub const RTE_IPV4_HDR_IHL_MASK: u32 = 15;
pub const RTE_IPV4_IHL_MULTIPLIER: u32 = 4;
pub const RTE_IPV4_HDR_DSCP_MASK: u32 = 252;
pub const RTE_IPV4_HDR_ECN_MASK: u32 = 3;
pub const RTE_IPV4_HDR_ECN_CE: u32 = 3;
pub const RTE_IPV4_HDR_DF_SHIFT: u32 = 14;
pub co... | Rust | 0 |
**kwargs):
if ignore_label is None:
ignore_label = -100
super().__init__(
lossf = nn.CrossEntropyLoss(ignore_index=ignore_label),
resize_x = resize_x,
align_corners = align_corners)
self.boundary_f = boundary_2d(ignore_label=ignore... | Python | 1 |
ring(bts)
return ent
def parse_entries(self, fl: BytesIO) -> Generator[Entry, None, None]:
"""Parse a stream of Kythe entries from a file."""
while True:
bts = self.next_entry(fl)
if bts == b"":
break
yield self.parse_entry(bts)
def t... | Python | 1 |
valid SCID block num
do_handling_query_channel_range(
&net_graph_msg_handler,
&node_id_2,
QueryChannelRange {
chain_hash: chain_hash.clone(),
first_blocknum: 0xffffff,
number_of_blocks: 1,
},
true,
vec
np.testing.assert_equal(nbarr, arr)
@unittest.expectedFailure
def test_set_arrays(self):
# Test setting an entire array of arrays (multiple records)
arr = np.zeros(2, dtype=recordwith2darray).view(np.recarray)
nba... | Python | 1 |
from __future__ import annotations
from typing import Any, TYPE_CHECKING
import numpy as np
if TYPE_CHECKING: # pragma: no cover
from pyNastran.bdf.bdf import BDF
DOF_MAP = dict[tuple[int, int], int]
def get_ieids_eids(model: BDF, etype: str, eids_str,
idtype: str='int32') -> tuple[int, Any... | Python | 1 |
st": {}
/// }
/// ```
TokenList {},
/// # TokenBalances
///
/// Returns [TokenBalancesResponse]
/// All DAO Cw20 Balances
///
/// ## Example
///
/// ```json
/// {
/// "token_balances": {
/// "start"?: {
/// "native": "uosmo" | "cw20": "os<PASSWORD... | Rust | 0 |
expiration_ref.cleanup();
expired
};
trace!("Cleaning up mock {} expired keys", expired.len());
cleanup_keys(&tx, expired);
Ok(())
});
trace!("Creating mock redis command stream...");
Box::new(command_ft.select(timer_ft).map(|_| ()).map_err(|(e, _)| e))
}
// Regression test for #3559... | Rust | 0 |
/// [`UnsafeUnpin`]: https://docs.rs/pin-project/1/pin_project/trait.UnsafeUnpin.html
/// [drop-guarantee]: core::pin#drop-guarantee
/// [pin-projection]: core::pin#projections-and-structural-pinning
/// [pinned-drop]: macro@pin_project#pinned_drop
/// [repr-packed]: https://doc.rust-lang.org/nomicon/other-reprs.html#r... | Rust | 0 |
# Say hello
#Say hello
"""
Ignore this
"""
# comments
name = input("What's your name? ")
print(f"hello, {name}")
| Python | 1 |
from sys import setrecursionlimit
setrecursionlimit(4000)
def f(n):
if n < 5:
return 4
if n > 4:
return 4 * f(n-4)
print(f(4444)/f(4400))
| Python | 1 |
pub fn g_static_rec_mutex_lock_full(mutex: *mut GStaticRecMutex, depth: guint);
}
extern "C" {
pub fn g_static_rec_mutex_unlock_full(mutex: *mut GStaticRecMutex) -> guint;
}
extern "C" {
pub fn g_static_rec_mutex_free(mutex: *mut GStaticRecMutex);
}
pub type GStaticRWLock = _GStaticRWLock;
#[repr(C)]
#[deri... | Rust | 0 |
'''
Developed by Ellen Red
'''
from machine import Pin, PWM
import time
import imu
import kalman_pid
motor1 = PWM(Pin(22))
motor2 = PWM(Pin(18))
motor3 = PWM(Pin(12))
motor4 = PWM(Pin(4))
freq = 30
duty_u16 = 0
#5%
def slow():
motor1.duty_u16(3251)
motor2.duty_u16(3251)
motor3.duty_u16(3251)
motor... | Python | 1 |
Inst::ShiftRR {
shift_op: ShiftOp::AShR64,
rd: writable_gpr(4),
rn: gpr(5),
shift_imm: SImm20::maybe_from_i64(-524288).unwrap(),
shift_reg: None,
},
"EB450000800A",
"srag %r4, %r5, -524288",
));
insns.push((
Inst... | Rust | 0 |
//////////////////////////////////////////////////////////////////////////////
/*
* Copyright (c) 2021 gematik GmbH
*
* 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... | Rust | 0 |
0, 1, r, C, sigma))
S = 1
H = 1.1
L = 0.9
C = 0.005
r = 0.04
sigma = 0.25
# payoff_delta = delta_cal(S, H, L, r, 0, C, sigma, option_type='payoff')
# euro_delta = delta_cal(S, H, L, r, 0, C, sigma, option_type='euro')
# #amer_delta = delta_cal()
# payoff_gamma = gamma_cal(S, H,... | Python | 1 |
| trainable params: {trainable_params:,d} || trainable%: {100 * trainable_params / all_param}"
)
print(f'lora params: {lora:,d}')
print(f'linear params: {linear:,d} || imagebind params: {imagebind:,d} || llama params: {llama:,d}')
def load_stage_1_parameters(self, path):
delta_ckpt... | Python | 1 |
'Not supported command keys: {}'.format(forbidden_keys)
)
elif isinstance(command, str):
command = {'text': command}
command.setdefault('username', defaults['username'])
command.setdefault('display_name', defaults['display_name'])
return BotCommand(
... | Python | 1 |
atus_code=status.HTTP_404_NOT_FOUND, detail="Category not found"
)
@router.get("/detail/{product_slug}", summary="Получить детальную информацию о товаре")
async def product_detail(session: session, product_slug: str) -> Dict[str, str]:
"""Получение детальной информации о продукте по его slug.
Args:
... | Python | 1 |
(b"Poincareplane", "\u{210C}"),
(b"Popf", "\u{2119}"),
(b"Pr", "\u{2ABB}"),
(b"Precedes", "\u{227A}"),
(b"PrecedesEqual", "\u{2AAF}"),
(b"PrecedesSlantEqual", "\u{227C}"),
(b"PrecedesTilde", "\u{227E}"),
(b"Prime", "\u{2033}"),
(b"Product", "\u{220F}")... | Rust | 0 |
use secp::key::SecretKey;
use rand::os::OsRng;
use core::{Transaction, Input, Output, DEFAULT_OUTPUT};
/// Context information available to transaction combinators.
pub struct Context {
secp: Secp256k1,
rng: OsRng,
}
/// Accumulator to compute the sum of blinding factors. Keeps track of each
/// factor as well as ... | Rust | 0 |
Value::Int(num1 & num2)
}
_ => Value::Null,
},
BinOp::BitOr => match (arg1, arg2) {
(Value::Int(num1), Value::Int(num2)) => {
Value::Int(num1 | num2)
}
_ => Value::Null,
... | Rust | 0 |
from datetime import date
from django.db import models
from django.core.exceptions import ValidationError
from .fields import BooleanChoiceField
# Create your models here.
class Animal(models.Model):
name = models.CharField(max_length=100)
species = models.CharField(max_length=100)
birth_date = models.Da... | Python | 1 |
")]
const KEYWORD_FILE: &str = "assets/hi robot_mac.ppn";
#[cfg(target_os = "windows")]
const KEYWORD_FILE: &str = "assets/hi robot_windows.ppn";
fn read_audio_file() -> Vec<u8> {
let mut file = File::open("assets/single.raw").unwrap();
let mut audio_u8 = Vec::new();
// Read file to memory
file.read_t... | Rust | 0 |
class Solution:
def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]:
ret = []
prefix = 0
for num in nums:
prefix ^= num
ret.append((2 ** maximumBit - 1) ^ prefix)
return ret[::-1]
| Python | 1 |
import json
import time
from pubsub import pub
from src.common import constant
from src.common import runtime_data_info
from src.common.obj import IdentifyMsg
def send_msg(mzml_name=None, mzml_index=None, step=None, status=None, msg=None, channel=None):
#
start_timestamp = runtime_data_info.runtime_data.sta... | Python | 1 |
#!/usr/bin/python3
import inspect
import io
import sys
import cmd
import shutil
import console
"""
Cleanup file storage
"""
import os
file_path = "file.json"
if not os.path.exists(file_path):
try:
from models.engine.file_storage import FileStorage
file_path = FileStorage._FileStorage__file_path
... | Python | 1 |
}
]
);
}
#[test]
fn get_reference() {
let mut rng = rand::rngs::StdRng::seed_from_u64(42);
let refs = References::from_stream(std::io::Cursor::new(FASTA)).unwrap();
let seqs: Vec<(usize, char)> = (0..10).map(|_| refs.choose_reference(&mut rng)).collect();
... | Rust | 0 |
::Wrapper {
/// [getConnection](https://developer.android.com/reference/javax/sql/DataSource.html#getConnection())
///
/// Required features: "java-sql-Connection"
#[cfg(any(feature = "all", all(feature = "java-sql-Connection")))]
pub fn getConnection<'env>(&'env self) -> __jni_... | Rust | 0 |
iter)):
out = batched_preds_pmap(params, batch_i)
outs.append(out)
# Have enough to accumulate
if len(outs) == num_accumulations:
megabatch = jax.tree_multimap(lambda *xs: jnp.concatenate(xs, 1), *outs)
loss_info = loss_megabatch_pmap(mega... | Python | 1 |
0)
}
#[doc = "Clock enabled"]
#[inline(always)]
pub fn _1(self) -> &'a mut W {
self.variant(DAC0_A::_1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
... | Rust | 0 |
r, TextEncoder};
use crate::core::{logging, logpump, status as bot_status, BotConfig, BotContext, BotStats, ColdRebootData};
use crate::error::{EventHandlerError, StartupError};
use commands::ROOT_NODE;
use translation::Translations;
mod commands;
mod core;
pub mod cache;
use cache::Cache;
mod parser;
pub use par... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.