text string | label_name string | labels int64 |
|---|---|---|
ii(),
&agents_neighborhood,
1.,
0.1,
);
assert_eq!(constraints.len(), agents.len());
assert_eq!(constraints[0].len(), 1);
assert_eq!(constraints[1].len(), 1);
let (_orca_0_1_ori, orca_0_1_dir) = constraints[0][0];
let (_orca_1_0_ori, orca_1_0_dir) = constraints[1][0];
as... | Rust | 0 |
@staticmethod
def _event_lifecycle_callback(conn, dom, event, detail, opaque):
"""Receives lifecycle events from libvirt.
NB: this method is executing in a native thread, not
an eventlet coroutine. It can only invoke other libvirt
APIs, or use self.queue_event(). Any use of logg... | Python | 1 |
leaf(&[2])),
]
);
check_map_multiproof(&proof, keys, &table);
let keys = vec![[64; 32], [129; 32]];
let proof = table.get_multiproof(keys.clone());
assert_eq!(
proof.proof_unchecked(),
vec![
(S::transform_key(&[128; 32]), HashT... | Rust | 0 |
def forward(self, x, target):
logprobs = torch.nn.functional.log_softmax(x, dim=-1, dtype=torch.float32)
non_pad_mask = target != self.padding_idx
nll_loss = -logprobs.gather(dim=-1, index=target.unsqueeze(1))
nll_loss = nll_loss.squeeze(1)[non_pad_mask]
smooth_loss = -logprobs.mean(dim=-1)[non_pad_... | Python | 1 |
_libuser::fs::{IFileSystemProxy, IFileSystemServiceProxy, FileSystemType};
/// Translate a FileSystemType into a str.
fn get_filesystem_type(filesystem_type: FileSystemType) -> &'static str {
match filesystem_type {
FileSystemType::FAT12 => "fat12fs",
FileSystemType::FAT16 => "fat16fs",
Fil... | Rust | 0 |
t_tokens = [
add_special_token_ids(e["input_ids"], add_bos=self.model.cfg.data.get("add_bos", False), add_eos=False)
for e in elems
]
max_new_tokens = self.sft_config.gen_kwargs.get("max_new_tokens", 64)
context_lengths = [len(x) for x in context_toke... | Python | 1 |
g import OutputImageDvi
sage: OutputImageDvi.example() # indirect doctest
OutputImageDvi container
"""
self.dvi = OutputBuffer(dvi)
@classmethod
def example(cls):
r"""
Construct a sample DVI output container.
This static method is meant for d... | Python | 1 |
ol = False,
execute_function: Callable[
[qiskit.QuantumCircuit, dict], Any
] = utils.execute,
**kwargs,
) -> np.ndarray:
"""Given a qiskit circuit, decodes and returns back the Original Audio Array.
Args:
circuit: A Qiskit Circuit representing the... | Python | 1 |
2DMS: D3D10_TEX2DMS_RTV,
pub Texture2DMSArray: D3D10_TEX2DMS_ARRAY_RTV,
pub Texture3D: D3D10_TEX3D_RTV,
}
#[cfg(feature = "Win32_Graphics_Dxgi_Common")]
impl ::core::marker::Copy for D3D10_RENDER_TARGET_VIEW_DESC_0 {}
#[cfg(feature = "Win32_Graphics_Dxgi_Common")]
impl ::core::clone::Clone for D3D10_RENDER_TARG... | Rust | 0 |
# 6 - Algoritmo de Cálculo de Desconto:
# Desenvolva um algoritmo que calcule o preço de um produto
# após aplicar um desconto. Solicite o preço original e o percentual
# de desconto.
pre_fin = 0
porc_desc = 0
pre_ini = float(input('Preço do produto: '))
if pre_ini < 99:
desc = 0
elif pre_ini > 100 and pre_ini < 1... | Python | 1 |
from __future__ import annotations
from typing import List
import pytest
from pydantic import BaseModel
from pydantic_resolve import Resolver, LoaderDepend
import tests.pydantic_v1.resolver.test_14_deps.mod_a as a
import tests.pydantic_v1.resolver.test_14_deps.mod_b as b
@pytest.mark.asyncio
async def test_loader_depe... | Python | 1 |
Stdin::FileDescriptor(_) => panic!("must occur after fork(2)"),
Stdin::Child(child) => child.into(),
}
}
}
#[cfg(unix)]
impl AsRawFd for Stdin {
fn as_raw_fd(&self) -> RawFd {
match self {
Stdin::Inherit => libc::STDIN_FILENO,
Stdin::File(f) => f.as_raw_f... | Rust | 0 |
left"),
};
let mut new_encoding = encoding.resource.0.clone();
new_encoding.pad(target_length, pad_id, pad_type_id, pad_token, direction);
Ok(ExTokenizersEncoding::new(new_encoding))
}
use fuel::fuel_camera::CameraMovement;
use fuel::glutin::VirtualKeyCode;
use fuel::{Control, Scene, Window};
pub fn ... | Rust | 0 |
r.map_err(|err| err.into()),
};
res.chain_err(|| format!("failed to print to journal at '{}'", SD_JOURNAL_SOCK_PATH))?;
Ok(())
}
/// Send an overlarge payload to systemd-journald socket.
///
/// This is a slow-path for sending a large payload that could not otherwise fit
/// in a UNIX datagram. Payload i... | Rust | 0 |
verting to tokens instead."
)
return self.convert_ids_to_tokens(token_ids)
# Override since phonemes cannot be converted back to strings
def convert_tokens_to_string(self, tokens, **kwargs):
logger.warning(
"Phonemes cannot be reliably converted to a string due to the one-ma... | Python | 1 |
NK_ARGS: [u8; 74] =
*b" /export:NvOptimusEnablement /export:AmdPowerXpressRequestHighPerformance ";
#[cfg(target_os = "windows")]
#[no_mangle]
pub static mut NvOptimusEnablement: i32 = 1;
#[cfg(target_os = "windows")]
#[no_mangle]
pub static mut AmdPowerXpress... | Rust | 0 |
let maybe_next_node = previous_node.levels[level_idx].as_mut();
// If the next pointer of the node we ended at on this level is the node for the search
// key, adjust the next pointer to point to the node after the node we are removing.
if let Some(next_node_ptr) = maybe_next_node {... | Rust | 0 |
from countrynames import to_code, to_code_3
def test_to_code():
assert to_code("Germany") == "DE"
assert to_code("UK") == "GB"
assert to_code("North Macedonia") == "MK"
assert to_code("Nothing") is None
def test_to_code_3():
assert to_code_3("Germany") == "DEU"
assert to_code_3("UK") == "GBR... | Python | 1 |
eshes\f\furn_practice_dummy.nif", 0x0E2A_2F3A, 0x31FE_B696),
(r"meshes\a\a_art_fists_gauntlets.nif", 0x0E2F_034F, 0x71F6_875F),
(r"meshes\fire_small.nif", 0x0E2F_6461, 0x0F1A_5A57),
(r"meshes\f\ex_turf00.nif", 0x0E57_7354, 0x9693_56E7),
(r"meshes\f\furn_web00.nif", 0x0E5A_7054, 0x931D_0029),
(r... | Rust | 0 |
our Borg passphrase and keys, that you would
need to get started after a catastrophic loss of your disk.
In addition it is important to understand that your backup data is
not encrypted with your passphrase, rather your passphrase encrypts
a key, and your backup data is ... | Python | 1 |
"d&d5", "dnd5", "choice"]));
m.insert("dnd5standard", Method::new(
"d&d", false, DND5STANDARD_DESC, DND5STANDARD_HELP, |stats| method_array(&DND35_ARRAY, stats),
&["d&d", "dnd", "d&d5", "dnd5", "pre-set", "choice"]));
m.insert("pfstandard", Method::new(
"d&d", false... | Rust | 0 |
class Solution:
def countCompleteDayPairs(self, hours: List[int]) -> int:
hmap = {}
hmap[(hours[0] % 24)] = 1
ans = 0
for i in range(1, len(hours)):
curr = (hours[i] % 24)
comp = (24 - curr) % 24 # handles curr == 0, because hr 24 == hr 0
if comp i... | Python | 1 |
| points.iter().find(|p| m == p.mac))
}
fn get_iw_dev_command() -> Command {
const PATH_ENV: &str = "PATH";
let path_system = "/usr/sbin:/sbin";
let path = env::var_os(PATH_ENV).map_or(path_system.to_string(), |v| {
format!("{}:{}", v.to_string_lossy().into_owned(), path_system)
});
const ... | Rust | 0 |
&mut encoder,
aux.align,
);
}
fn dispose(self: Box<Self>, factory: &mut Factory<B>, _aux: &Aux<B>) {
unsafe {
factory
.device()
.destroy_graphics_pipeline(self.graphics_pipeline);
factory
.device()
... | Rust | 0 |
# time: n^2
# space: 1
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
# m = len() - 1
# 0,0 -> 0, m
# 0, 1 -> 1, m
# 0, 2 -> 2, m
# 1, 0 -> 0, m - 1
# 2, 0 -> 0... | Python | 1 |
{
let cell_paint = self.get(x, y);
for j in 0..if x%2 == 0 { expander_w } else { 1 }
{
if cell_paint == Cell::Open
{
if (x, y) == entrance && entrance == exit && i == expander_h/... | Rust | 0 |
onst D5 = 16;
const D6 = 32;
const D7 = 64;
const D8 = 128;
#[doc = "All flags set to `on`"]
const DALL = 255;
}
);
bitflags!(
#[doc = "
Adresses of the different cards that can be controlled.
See the jumper setting on your card for the correct address.
"]
pub struct CardAddress: u16 {
#[doc = "... | Rust | 0 |
_, batch in zip(range(self.steps), self.data_iter):
mask = batch.pop('_mask')
batch_ds, batch_ms = self.eval_fn(params, batch, mask)
# All results are a replicated array shaped as follows:
# (local_devices, per_device_batch_size, elem_shape...)
# with each local device's entry being ident... | Python | 1 |
from . import instance, group, base, prototype, layout
from .context import context
from converter import utils
from sketchformat.layer_group import *
# LAYOUT_AXIS = {
# "NONE": None,
# "HORIZONTAL": LayoutAxis.HORIZONTAL,
# "VERTICAL": LayoutAxis.VERTICAL,
# }
# LAYOUT_ANCHOR = {
# "MIN": LayoutAnch... | Python | 1 |
f= open("document.txt" , "a")
f.write("Hi everyone! \n We are learning file I/0")
f.write("Using java \n I like programming in the java.")
| Python | 1 |
from hydra_gnn.utils import MP3D_BENCHMARK_DIR, HYDRA_TRAJ_DIR
import random
import os
import argparse
def generate_mp3d_split(hydra_dataset_dir, train_ratio, val_ratio):
test_ratio = 1 - train_ratio - val_ratio
assert test_ratio > 0, "Invalid train/val/test split."
# read all scene names
trajectory_... | Python | 1 |
#### "variable_reference.py"
#### Grace Hadiyanto
#### CS439 FA14
class VariableReference:
"""This class represents the occurence of a variable in the current
string. It holds a pointer to the current string, a start index, end index,
and name of the variable."""
__slots__ = {'_current_string', '_... | Python | 1 |
ry step-size epochs')
# 针对torch.optim.lr_scheduler.MultiStepLR的参数
parser.add_argument('--lr-steps', default=[7, 12], nargs='+', type=int, help='decrease lr every step-size epochs')
# 针对torch.optim.lr_scheduler.MultiStepLR的参数
parser.add_argument('--lr-gamma', default=0.1, type=float, help='decrease lr by... | Python | 1 |
import json
import re
import requests
def main():
all_meraki_roles = ["TOP", "JUNGLE", "MIDDLE", "BOTTOM", "UTILITY"]
all_json_roles = ["TOP", "JUNGLE", "MIDDLE", "BOTTOM", "SUPPORT"]
all_champs = {}
data = requests.get("https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-champion-statistics/glob... | Python | 1 |
# -*- coding:utf-8 -*-
# Given a 2D board and a word, find if the word exists in the grid.
#
# The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
#
# Example:
#
#
# board ... | Python | 1 |
::RegisterBlock {
0x4000_8000 as *const _
}
}
impl Deref for SPIS0_NS {
type Target = spis0_ns::RegisterBlock;
fn deref(&self) -> &Self::Target {
unsafe { &*SPIS0_NS::ptr() }
}
}
#[doc = "SPI Slave 0"]
pub mod spis0_ns;
#[doc = "I2C compatible Two-Wire Master Interface with EasyDMA 0"]
p... | Rust | 0 |
}
fn encode_and_verify_non_empty_with_attributes(input: &Frame, expected: &str) {
let (attributes, encoded_attributes) = create_attributes();
let mut frame = input.clone();
let _ = frame.add_attributes(attributes).unwrap();
let mut buf = empty_bytes();
buf.extend_from_slice(PADDING.as_bytes()... | Rust | 0 |
fn() -> Tm;
impl Clock for ClockFn {
fn now(&self) -> Tm {
self()
}
}
/// A jar containing the cookies seen so far.
#[derive(Debug)]
pub struct Jar<T: Clock> {
clock: T,
domain: Domain,
hosts: HashMap<IpAddr, Path>,
}
impl Default for Jar<ClockFn> {
fn default() -> Jar<ClockFn> {
... | Rust | 0 |
import io
import cv2
import numpy as np
from PIL import Image
def frame_to_jpeg_bytes(frame):
# frame: numpy BGR
ret, buf = cv2.imencode('.jpg', frame)
return buf.tobytes() if ret else None
def jpeg_bytes_to_frame(bts):
arr = np.frombuffer(bts, dtype=np.uint8)
img = cv2.imdecode(arr, cv2.IMREAD_CO... | Python | 1 |
format!("screenshot{}.png", counter),
CreationCollisionOption::ReplaceExisting,
)?
.GetResults()?;
{
let stream = file.OpenAsync(FileAccessMode::ReadWrite)?.GetResults()?;
let encoder =
... | Rust | 0 |
t.addWidget(confirmButton)
layout.addLayout(buttonLayout)
def on_confirm(self, name, incidence):
if incidence:
response = QMessageBox.question(self, "Confirmar Incidencia", f"¿Estás seguro de confirmar la incidencia '{incidence}' en {name}?", QMessageBox.Yes | QMessageBox.No)
... | Python | 1 |
}
#[tokio::test]
async fn test_apply_swaps_to_matrix() {
test_circuit(|ctx| {
Box::pin(async {
let weights = [3, 1, 2].map(|x| IntShare::<_, 8>::from_plain(ctx, x));
let mut matrix = ndarray::array![[1, 2, 3], [4, 5, 6], [7, 8, 9]]
... | Rust | 0 |
import math as m
def get_min_max(point_cloud):
xmin = xmax = point_cloud[0].x
ymin = ymax = point_cloud[0].y
for point in point_cloud:
if (point.x < xmin):
xmin = point.x
if (point.x > xmax):
xmax = point.x
if (point.y < ymin):
ymin = point.y
if (point.y > ymax):
ymax = poi... | Python | 1 |
"""
13) Tentando descobrir se um dado era viciado, um dono de cassino honesto (ha! ha! ha! ha!) o
lançou n vezes. Dados os n resultados dos lançamentos, determinar o número de ocorrências de
cada face.
""" | Python | 1 |
#!/usr/bin/python3
""" Holds that dumps python object into json string """
import json
def to_json_string(my_obj):
""" serialize python object into json string """
json_string = json.dumps(my_obj)
return json_string
| Python | 1 |
@property
def pad_token_type_id(self):
""" Id of the padding token type in the vocabulary."""
return self._pad_token_type_id
| Python | 1 |
in sequence (`e1` followed by `e2` followed by
//! `e3`), ignoring the return values.
//! * `a:e1 e2 b:e3 c:e4 { rust }` - _Action:_ match `e1`, `e2`, `e3`, `e4` in
//! sequence, like above. If they match successfully, run the Rust code in
//! the block and return its return value. The variable names bef... | Rust | 0 |
#!/usr/bin/env python3
"""
Script para verificar comunicación serial con router
"""
import serial
import time
import sys
import argparse
def test_communication(port, baudrate=115200, timeout=2):
"""
Prueba la comunicación serial con el router.
Args:
port: Puerto serial (ej: /dev/glinet-mango)
... | Python | 1 |
_CLASS_DEFAULT: ::std::os::raw::c_uint = 21;
pub const QOS_CLASS_UTILITY: ::std::os::raw::c_uint = 17;
pub const QOS_CLASS_BACKGROUND: ::std::os::raw::c_uint = 9;
pub const QOS_CLASS_UNSPECIFIED: ::std::os::raw::c_uint = 0;
pub type _bindgen_ty_53 = ::std::os::raw::c_uint;
pub type qos_class_t = ::std::os::raw::c_uint;... | Rust | 0 |
e;
type Future = Ready<Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, _req: R) -> Self::Future {
ready(Ok(Response::new(http_body::Empty::new())))
... | Rust | 0 |
#
# This file is part of pyasn1-modules software.
#
# Copyright (c) 2005-2017, Ilya Etingof <etingof@gmail.com>
# License: http://pyasn1.sf.net/license.html
#
# SNMPv3 message syntax
#
# ASN.1 source from:
# http://www.ietf.org/rfc/rfc3412.txt
#
from pyasn1.type import constraint
from pyasn1.type import namedtype
from ... | Python | 1 |
env,
io::{stdout, BufWriter, Write},
};
fn main() {
let args: Vec<String> = env::args().collect();
let file_data = std::fs::read(&args[1]).unwrap();
let header = b"EU4txt";
if file_data.len() < header.len() {
eprintln!("can only format plain eu4 file");
std::process::exit(1);
... | Rust | 0 |
ity
{
type EntityIdentifier = UnitEntityIdentifier;
type ParseError = Version3EntityDescriptorParseError;
#[inline(always)]
fn cast_entity_identifier(value: EntityIdentifier) -> Self::EntityIdentifier
{
value
}
#[inline(always)]
fn parse(_entity_body: &[u8], _device_connection: &DeviceConnection) -> Res... | Rust | 0 |
o an uppercase
("AbcdefG", "abcdef_g"), // PosX => pos_x
// text changes
("FooVec3Uni", "foo_vec3_uni"),
("GDNative", "gdnative_"),
("GDScript", "gdscript"),
];
tests.iter().for_each(|(class_name, expected)| {
let actual = module_na... | Rust | 0 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt5 UI code generator 5.15.11
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, Qt... | Python | 1 |
NABLE_SECURE_CHECKING_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: ENABLE_SECURE_CHECKING_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "Restricted mode."]
#[inline(always)]
pub fn enable(self) -> &'a mut W {
... | Rust | 0 |
ck7(x)
x = self.block8(x)
x = self.block9(x)
x = self.block10(x)
x = self.block11(x)
x = self.block12(x)
x = self.block13(x)
x = self.block14(x)
x = self.block15(x)
x = self.block16(x)
x = self.block17(x)
x = self.block18(x)
... | Python | 1 |
pt for a blank label
if params['label_type_main'] == 'character':
params['num_classes_main'] = 28
elif params['label_type_main'] == 'character_capital_divide':
params['num_classes_main'] = 72
else:
raise TypeError
if params['label_type_sub'] == 'phone61':
params['num_clas... | Python | 1 |
state: &RewardState) -> bool {
false
}
fn valid_last_hash(&self, _last_block: &Block) -> bool {
false
}
fn valid_state_hash(&self, _network_state: &NetworkState) -> bool {
false
}
fn valid_block_reward(&self, _reward_state: &RewardState) -> bool {
false
}
... | Rust | 0 |
))
.then(self.shift(periods))
.otherwise(fill_value)
// .alias(&name)
}
}
/// Get an array with the cumulative sum computed at every element
pub fn cum_sum(self, reverse: bool) -> Self {
self.apply(move |s: Series| Ok(s.cum_sum(reverse)), None... | Rust | 0 |
def scatterplot(df, feature, label, roundto=4, linecolor='orange'):
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
# create the plot
sns.regplot(x=df[feature], y=df[label], line_kws={"color": linecolor})
# calculate the regression line
m, b, r, p, err = stats... | Python | 1 |
e_basename)
adv_feature = attack(feature, target, source_labels=source,
feature_model=feature_model, pred_model=decision_model,
aux_samples=aux_samples)
save_one_img(adv_feature.detach().cpu(), adv_outp... | Python | 1 |
#
# SPDX-License-Identifier: MIT
#
# Copyright (c) 2025 Carsten Igel.
#
# This file is part of simplepycons
# (see https://github.com/carstencodes/simplepycons).
#
# This file is published using the MIT license.
# Refer to LICENSE for more information
#
""""""
# pylint: disable=C0302
# Justification: Code is generated
... | Python | 1 |
#[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 << 6)) | ((value as u32 & 0x01) << 6);
self.w
}
}
#[doc = "Port A-H Pin\\[n\\]
Falling Edge or Low Level Interrupt Trigger Type Enable Bit\nThe FLI... | Rust | 0 |
2]]),
go.Scatter3d(x=occluded_los_lines_x, y=occluded_los_lines_y, z=occluded_los_lines_z),
go.Scatter3d(x=[missile_pos[0], true_target_center_point[0]], y=[missile_pos[1], true_target_center_point[1]], z=[missile_pos[2], true_target_center_point[2]], line=dict(color=los_color))
]
... | Python | 1 |
cy builder depends on action space
if isinstance(action_space, Box):
self.pi = MLPGaussianActor(obs_dim, action_space.shape[0], hidden_sizes, activation).to(self.device)
elif isinstance(action_space, Discrete):
self.pi = MLPCategoricalActor(obs_dim, action_space.n, hidden_sizes, ... | Python | 1 |
visited.insert(r.id);
for next in &map.get_next_roads(r.id) {
if !self.visited.contains(&next.id) {
self.queue.push_back(next.id);
}
}
return false;
}
}
pub fn finish(&mut self, map: &Map) {
loop {
... | Rust | 0 |
std::{fs, path, process};
#[tokio::main]
async fn main() {
// parse CLI options
let matches = App::new("batalert")
.version("0.3.0")
.author("<NAME> <<EMAIL>>")
.about("Sends D-Bus notification when battery runs low.")
.arg(
Arg::with_name("uevent")
... | Rust | 0 |
ild(4) > span.article-meta-value")[
0].text
# 处理推文
note_content_detail.push_comment = []
all_push_elements = soup.select("#main-content > div.push")
for push_element in all_push_elements:
note_push_comment = NotePushComment()
if len(push_element.select("span")) < 3:
... | Python | 1 |
_string(),
)
}
fn info_XMM12() -> (RealReg, String) {
(
Reg::new_real(RegClass::V128, /*enc=*/ 12, /*index=*/ 26).to_real_reg(),
"%xmm12".to_string(),
)
}
fn info_XMM13() -> (RealReg, String) {
(
Reg::new_real(RegClass::V128, /*enc=*/ 13, /*index=*/ 27).to_real_reg(),
"%x... | Rust | 0 |
DEFAULT_TIME
return slurm_atrs
def get_slurm_attributes(queue, resources):
slurm_atrs = {}
# specially handled resource specifications
special_resources = set(["machines", "account", "timelimit"])
if resources:
for parm in resources.split(";"):
k, v = [ a.strip() for a in parm... | Python | 1 |
# napisac kalsę Dom
# ma posiadac pola prywatne kolor, liczba okien, metraz
# doac metody do odczytu tych pol
class Dom:
"""
klasa opisująca dom
"""
def __init__(self, metraz, kolor, liczba_okien):
self.__metraz = metraz
self.__kolor = kolor
self.__liczba_okien = liczba_okien
... | Python | 1 |
gap_start is set to the first
// tranche so that the range below will be empty.
let gap_start = gap_end.map(|end| end + 1).unwrap_or(tranche);
gap_end = Some(tranche);
(gap_start..tranche)
.map(|i| (i, &[] as &[_]))
.chain(std::iter::once((tranche, assignments)))
});
let pre_end = tranches.first().ma... | Rust | 0 |
me(data.get("muted_users", {}).items(), columns=["UserID", "Details"])
excel_file = "Supp0rtsBot_all_users.xlsx"
with pd.ExcelWriter(excel_file) as writer:
users_df.to_excel(writer, index=False, sheet_name="Users")
muted_df.to_excel(writer, index=False, sheet_name="Muted")
... | Python | 1 |
).await,
vec![vec![1,2,3,4,5], vec![6,7,8,9]]
);
assert_eq!(
chunk_concat_ok(vec![[1,2,3], [4,5,6], [7,8,9]], 10).await,
vec![vec![1,2,3,4,5,6,7,8,9]]
);
assert_eq!(
chunk_concat_ok(vec![[1,2,3], [4,5,6], [7,8,9]], 2).await,
v... | Rust | 0 |
os_key,
eth_dest_address,
eth_dest_key,
}
}
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
pub struct BridgeUserKey {
// the starting addresses that get Eth balances to send across the bridge
pub eth_address: EthAddress,
pub eth_key: EthPrivateKey,
// the cosmos addresses that get the ... | Rust | 0 |
tance provided for class: {}".format(base_cls.__name__)
)
return ret
return session._context.injector.inject(base_cls)
def _inject_or(base_cls, default=None):
if session._active and base_cls in self.session_inject:
ret = self.session_i... | Python | 1 |
need to go through all equations regardless
instr_eq = Y.get(eq, None) # Y has the eq to ind endog array map
newRHS = self.exog[eq].copy()
if instr_eq:
for i,LHS in enumerate(instr_eq):
yhat = GLS(LHS, self.instruments).fit().fittedvalues
... | Python | 1 |
, response: &http::Response<bytes::Bytes>) -> Self::Output {
if !response.status().is_success() && response.status().as_u16() != 200 {
crate::operation_deser::parse_update_trust_error(response)
} else {
crate::operation_deser::parse_update_trust_response(response)
}
}... | Rust | 0 |
wrap()
.first_element_child()
.unwrap()
.first_element_child()
.unwrap();
test(&element);
}
#[wasm_bindgen_test]
fn level_4() {
test_setup! {
.a {
b {
.c {
d {
color: "blue";
}
}
}
}
a {
.b {
c {
.d {
text: "hello world";
}
}
}
}
}
let ele... | Rust | 0 |
### loops ###
#There are 2 types of loops:
# 1: while loop -> a while loop will execute a block of code while a condition is true
# 2: for loop -> a for loop iterates over a sequence and the sequence can be contents of a collection type like: lists, tuples, dictionaries, etc.
## whie loop:
# Example 1:... | Python | 1 |
-linux-gnux32",
"x86_64-unknown-linux-musl",
"x86_64-unknown-netbsd",
"x86_64-unknown-redox",
];
const UPSTREAM_URL: &str = "https://static.rust-lang.org/";
fn file_sha256(file_path: &Path) -> Option<String> {
let file = Path::new(file_path);
if file.exists() {
let buffer = FileBuffer::ope... | Rust | 0 |
ize of: ", stringify!(HmdMatrix33_t))
);
assert_eq!(
::std::mem::align_of::<HmdMatrix33_t>(),
4usize,
concat!("Alignment of ", stringify!(HmdMatrix33_t))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<HmdMatrix33_t>())).m as *const _ as usize },
0usize,
co... | Rust | 0 |
Mode", 0u32, "Cabac"),
Self::Cavlc => serializer.serialize_unit_variant("EntropyMode", 1u32, "Cavlc"),
Self::UnknownValue(s) => serializer.serialize_str(s.as_str()),
}
}
}
}
#[doc = "Describes all the properties for encoding a video with the H.264 codec."]
#[deriv... | Rust | 0 |
from PIL import Image, ImageOps
import sys
import os
def main():
if len(sys.argv) < 3:
sys.exit("Too few command-line arguments")
elif len(sys.argv) > 3:
sys.exit("Too many command-line arguments")
else:
format = [".jpg", ".jpeg", ".png"]
inp = os.path.splitext(sys.argv[1])... | Python | 1 |
d the stemmed verb is vt, don't accepot
listetemp=liste;
liste=[]
for item in listetemp:
## print item['transitive'].encode("utf8"), transitive
if item['transitive']==u'y' or not transitive:
liste.append(item);
return liste;
#----------------------------
# generate possible conjugation
# ... | Python | 1 |
futures::{channel::mpsc, future::Either, pin_mut, prelude::*};
use parking_lot::Mutex;
use std::{
collections::{HashMap, HashSet},
error,
net::SocketAddr,
sync::{atomic, Arc},
};
/// Server that can be cloned.
///
/// > **Note**: This struct is designed to be easy to use, but it works by maintaining a background
... | Rust | 0 |
from typing import List
from collections import defaultdict
"""
TIME: 307ms
NOTE: Initial solution with binary search
"""
class Solution(object):
def avoidFlood(self, rains: List[int]) -> List[int]:
m = len(rains)
drain_inds = []
# lake[r] holds index at which r was filled
lake =... | Python | 1 |
import os
from setuptools import setup
def get_docs():
result = []
in_docs = False
f = open(os.path.join(os.path.dirname(__file__), 'phpserialize.py'))
try:
for line in f:
if in_docs:
if line.lstrip().startswith(':copyright:'):
break
... | Python | 1 |
softcap: Optional[float] = None,
):
"""Scaled dot product attention with transposed key and value.
Args:
query: Query tensor, with shape [B, T, N, H].
key: Key tensor, with shape [B, T, KV_LEN, H].
value: Value tensor, with shape [B, T, H, KV_LEN].
head_size (int): head dimension.
mask (to... | Python | 1 |
# generate prime numbers in given range
def prime_num(a,b):
prime_list = []
for i in range(a,b + 1):
prime_flag = True
for j in range(2,int(i ** 0.5) + 1):
if i % j == 0:
prime_flag = False
break
if prime_flag:
prime_list.append(i)
... | Python | 1 |
nel.add_players(event.players)
def on_set_as_overview(self, event: SetAsOverviewEvent):
point = event.point
self.notebook.SetSelection(0)
self.overview_panel.update_data([p.name for p in point.players], point.time, ServerStatus.ONLINE)
def load_icon(self):
self.SetIcons(wx.Icon... | Python | 1 |
ffi::GST_RTCP_SDES_PRIV => Self::Priv,
#[cfg(any(feature = "v1_20", feature = "dox"))]
ffi::GST_RTCP_SDES_H323_CADDR => Self::H323Caddr,
#[cfg(any(feature = "v1_20", feature = "dox"))]
ffi::GST_RTCP_SDES_APSI => Self::Apsi,
#[cfg(any(feature = "v1_20"... | Rust | 0 |
number_of_complited_hw=(12)
number_of_hours_spent=(90)
course_name='Python'
time_for_one_task=(number_of_hours_spent / number_of_complited_hw )
print(course_name,'total tasks',number_of_complited_hw,'hours spent',number_of_hours_spent,'average execution time',time_for_one_task) | Python | 1 |
E(&mut self) {
self.generic_parse(0)
}
fn generic_parse(&mut self, starting_state: usize) {
self.position = 0;
loop {
}
}
}
extern crate worker_type;
extern crate boss_type;
extern crate worker_trait;
use worker_trait::work::Work;
fn print_work<T : Work>(worker: &T) {
println!("Here is my work: ... | Rust | 0 |
CommonDialogRenderTargetInfo {
pub depthSurfaceData: ScePVoid,
pub colorSurfaceData: ScePVoid,
pub surfaceType: SceGxmColorSurfaceType,
pub colorFormat: SceGxmColorFormat,
pub width: SceUInt32,
pub height: SceUInt32,
pub strideInPixels: SceUInt32,
pub reserved: [SceUInt8; 32],
}
#[repr(... | Rust | 0 |
#!/usr/bin/env python3
"""
NAMDBin reads and writes the binary format used by NAMDBin
for restart files. I've written it to support coordinates
and velocities, because that's what LOOS supports, but the
same format is also used to store forces.
Alan Grossfield
University of Rochester Medical Center
2017
"""
import st... | Python | 1 |
from typing import Any
from fastapi import FastAPI, HTTPException, status
from scalar_fastapi import get_scalar_api_reference
app = FastAPI()
shipments = {
12701: {"weight": 0.6, "content": "glassware", "status": "placed"},
12702: {"weight": 2.3, "content": "books", "status": "shipped"},
12703: {"weight... | Python | 1 |
extension\0".as_ptr() as *const _,
Some(transmute(notify_remove_websocket_extension_trampoline::<Self, F> as usize)), Box_::into_raw(f))
}
}
fn connect_property_server_header_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_server_head... | Rust | 0 |
tc_relay = btc_anchoring_config
.local
.rpc
.map(BitcoinRpcClient::from)
.map(Box::<dyn BtcRelay>::from);
let service = BtcAnchoringService::new(
btc_anchoring_config.global,
Arc::new(RwLock::new(btc_anchoring_config.local.private_keys)),
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.