text string | label_name string | labels int64 |
|---|---|---|
*;
use std::{env, path};
struct MainState {
image1: graphics::Image,
image2: graphics::Image,
meshes: Vec<(Option<graphics::Image>, graphics::Mesh)>,
rect: graphics::Mesh,
rotation: f32,
}
impl MainState {
/// Load images and create meshes.
fn new(ctx: &mut Context) -> GameResult<MainState... | Rust | 0 |
#-*- coding:utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Work Entries - Contract Enterprise',
'category': 'Human Resources/Employees',
'sequence': 39,
'summary': 'Manage work entries',
'installable': True,
'depends': [
'hr_work_entry_co... | Python | 1 |
0x58], |d| (0.356_573_44 * d) - 273.884_02},
/// TBCR5B - Array Temp, Connector SA5B (*C)
ArrayTempSa5b => {vec![0xE1, 0x59], |d| (0.356_573_44 * d) - 273.884_02},
/// SDBCR5A - Sun Detector, Connector SA5A (W/m^2)
SunDetectorSa5a => {vec![0xE1, 0x5C], |d| d},
/// SDBCR5B - Sun Detector, Connector ... | Rust | 0 |
ns_topic));
}
headers
}
pub fn create_header<'a, T: Display>(key: &'a str, value: T) -> Header<'a, 'a> {
Header::new(key.as_bytes(), format!("{}", value).into_bytes())
}
<filename>src/basic/practice_2.rs<gh_stars>0
#[derive(PartialEq, Debug)]
// Declare Car struct to describe vehicle with four named field... | Rust | 0 |
5f9a1e/1/1/0]03e1c5b6e650966971d7e71ef2674f80222752740fc1dfd63bbbd220d2da9bd0fb)#cxmct4w8"])
assert_equal(descriptors(self.nodes[0].scantxoutset("start", [{"desc": "combo(tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1/1/*)", "range": 1500}])), [... | Python | 1 |
# coding: utf-8
# flake8: noqa
"""
Qualtrics Survey API
The Qualtrics Survey endpoints give you access to the structure of the surveys you create. Surveys have a complex structure, and you are encouraged to become familiar with the structure using your brand's Qualtrics page to build surveys at first. Then... | Python | 1 |
# @file
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"... | Python | 1 |
alt((
tag_no_case("left"),
tag_no_case("right"),
tag_no_case("non"),
tag_no_case("none"),
)),
end_of_line
);
map(
parse_field_value,
assoc_to_enum
)(input)
}
fn parse_number(input: &str) -> IResult<&... | Rust | 0 |
#!/usr/bin/env python
'''
Leetcode: Sudoku Solver
Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character '.'.
You may assume that there will be only one unique solution.
'''
from __future__ import division
import sys
INVALID = 0
# fill in (x,y) with val@
def ch... | Python | 1 |
inished refining raw data!')
# aggreagte data
logger.info(f'[LOAD] [LEAF - {DATASET_NAME.upper()}] Combine raw data...!')
_save_data(os.path.join(path, 'all_data', 'train_data_refined.json'), train_data)
_save_data(os.path.join(path, 'all_data', 'test_data_refined.json'), test_data)
logger.info... | Python | 1 |
christine.website/signalboost",
"https://christine.website/feeds",
]
.into_iter()
.map(|i| i.to_string())
.collect(),
)
.await?;
Ok(())
}
#[instrument(err)]
async fn mi() -> Result<()> {
let cli = mi::Client::new(env::var("MI_TOKEN")?, crate::APPLICATION_NAM... | Rust | 0 |
tory {
VoidTraderAllOfInventory {
item: None,
ducats: None,
credits: None,
}
}
}
<gh_stars>0
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// ... | Rust | 0 |
from reportlab.platypus import SimpleDocTemplate, Table, Paragraph, TableStyle
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
# Function to get item details from user
def get_item_details():
date = input("Enter Date (D... | Python | 1 |
from fastapi import APIRouter, Response, status
from ..misc import generate_qr, get_game_connect_link
from ..schemas import (
ErrorResponsesDict,
Game,
PathGameId,
Player,
QueryRoundsCount,
game_not_found,
not_enough_players,
player_already_connected,
)
router = APIRouter(prefix="/game... | Python | 1 |
import subprocess
from vivogpt import run
def add_student(num, name, age, gpa):
result = subprocess.run(
['c_and_py_stdentsys.exe', 'add', str(num), name, str(age), str(gpa)],
capture_output=True,
text=True,
encoding='gbk'
)
print(result.stdout)
def delete_student(num):
... | Python | 1 |
eratorMetaData {
static BROADCAST: OperatorMetaData = OperatorMetaData{
name: "Broadcast",
arity: Arity::Nary,
num_outputs: 1,
differential_parents: 1,
ordered_parents: true,
elementwise: false,
type_preserving: true,
... | Rust | 0 |
channel_data.data().as_ref();
if let Some(channel) = self.channels.get_mut(chid) {
match channel {
Channel::Session(_, stdin, _, _, _) | Channel::DirectTcpip(_, stdin) => match stdin
{
Some(stdin) => {
stdin.write_all(&data... | Rust | 0 |
#
# Copyright 2018 Analytics Zoo Authors.
#
# 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... | Python | 1 |
"""A helper module that injects SecureTransport, on import.
The import should be done as early as possible, to ensure all requests and
sessions (or whatever) are created after injecting SecureTransport.
Note that we only do the injection on macOS, when the linked OpenSSL is too
old to handle TLSv1.2.
"""
import sys
... | Python | 1 |
result.push(content[last_index..curr_index].to_vec());
}
else {
continue;
}
last_index = curr_index + 1;
is_inside_subscript = !is_inside_subscript;
}
if is_inside_subscript && content[curr_index] == ' ' as u1... | Rust | 0 |
("{} bytes", bytes)
}
else if bytes < 1500 * 1024
{
format!("{:.1} kB", (bytes as f64) / 1024.0)
}
else if bytes < 1500 * 1024 * 1024
{
format!("{:.1} MB", (bytes as f64) / 1024.0 / 1024.0)
}
else
{
format!("{:.1} GB", ((bytes / 1024 / 1024) as f64) / 1024.0)
... | Rust | 0 |
}
#[doc = "Bit 7 - The raw interrupt bit turns to high level when Rx buffer pointed by inlink is full and receiving data is not completed, but there is no more inlink for Rx channel 2."]
#[inline(always)]
pub fn in_dscr_empty_ch2_int_raw(&self) -> IN_DSCR_EMPTY_CH2_INT_RAW_R {
IN_DSCR_EMPTY_CH2_I... | Rust | 0 |
"".to_string()
};
let mut room_description = if items_descriptions.is_empty() {
description.to_string()
} else {
format!("{}\n\n{}", description, items_descriptions)
};
if !room_subjects.is_empty() {
room_description.push_str(&format!("\n{}", room_subjects));
}
... | Rust | 0 |
Array, 2, 1u16, 2u16, 3u16, 4u16);
test_encodable_array!(i16, I16Array, 2, -5i16, -6i16, -7i16, -8i16);
test_encodable_array!(u32, U32Array, 4, 1u32, 2u32, 3u32, 4u32);
test_encodable_array!(i32, I32Array, 4, -5i32, -6i32, -7i32, -8i32);
test_encodable_array!(u64, U64Array, 8, 1u64, 2u64... | Rust | 0 |
=> String::from(s),
None => {
warn!("Unreadable file name '{:?}'. Skipping!", oss);
continue;
}
}
None => {
warn!("Invalid file or directory '{:?}'. Skipping!", entry_path);
continue;
... | Rust | 0 |
\
~\xd2\xb6\xd6\x8e\x0cH\xb9\x1e\xb8\xe8k\x9e\xd5<.\
\xde-\xbf\x96\x1dJ\xce\xcd\xac\xe5R\x8d\x1c\xb1\x86\xf3\
A\xe3\x1bzt\xad\x1d\x1b\xc1\xbao\x83eo\xec\x9b\
{[\x05\x95\xb7\xb6\xc5\xfe#\xd4\xfdk\xa0\x8bK\xfb\
}\xaf\xcd\xf37\xf7\xab\x09K\xde\xe5\x88\xe3\x88\xe5\xbc\
`q\xdf\x0f\xbe\x06xg\xe1\xcd\xfa\xdci6m\xa6\
\xdc+\x7f... | Python | 1 |
import torch
def simple_gemm(mat_a: torch.Tensor, mat_b: torch.Tensor) -> torch.Tensor:
return torch.ops.cudabox.simple_gemm(mat_a, mat_b)
def tiled_gemm(mat_a: torch.Tensor, mat_b: torch.Tensor) -> torch.Tensor:
return torch.ops.cudabox.tiled_gemm(mat_a, mat_b)
| Python | 1 |
name="internlm-chat",
system="A chat between a curious <|User|> and an <|Bot|>. The <|Bot|> gives helpful, detailed, and polite answers to the <|User|>'s questions.\n\n",
roles=("<|User|>", "<|Bot|>"),
messages=(),
offset=0,
sep_style=SeparatorStyle.CHATINTERN,
sep="<eoh... | Python | 1 |
=====");
game1.print_state();
game1.part1_execute();
game1.print_end_state();
println!("===== Part 2 =====");
game2.print_state();
game2.part2_execute();
game2.print_end_state();
}
//! This module deals with various configurations that can be applied while creating a iso msg like
//! crypto... | Rust | 0 |
notifications_count);
if unread_notifications_count > 0 {
response.append("dialog-error");
} else {
response.append("dialog-information");
}
Ok(())
}))
.add_p(factory.property::<&str, _>("OverlayIconName", ()).emits_changed(dbus::tree::EmitsChangedSignal::Invalidates).access(dbus... | Rust | 0 |
al_delete_count {
for k in actual_start..(len - actual_delete_count) {
let from = Name::from_index(k + actual_delete_count);
let to = Name::from_index(k + item_count);
let from_present = array.has_property(env, from);
if from_present {
let from_val... | Rust | 0 |
0 para salir")
print("► Ingresa 1 para cambiar a ver categorias")
selected_game=input()
print("---------")
if selected_game == "0":
run=False
break
if selected_game == "1":
mode="categories"
elif selected_game != "" and selecte... | Python | 1 |
}
}
_ => None,
}
}
fn main() {
let app = Application::new().unwrap();
let mut builder = WindowBuilder::new(app.clone());
builder.set_handler(Box::new(AppState::default()));
builder.set_title("Text editing example");
let window = builder.build().unwrap();
window.show();... | Rust | 0 |
# coding=utf-8
# Copyright 2020 Mesh TensorFlow authors, T5 Authors and HuggingFace Inc. team.
#
# 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... | Python | 1 |
apacity_ORegan2022,
"Negative electrode thermal conductivity [W.m-1.K-1]"
"": graphite_LGM50_thermal_conductivity_ORegan2022,
"Negative electrode OCP entropic change [V.K-1]"
"": graphite_LGM50_entropic_change_ORegan2022,
# positive electrode
"Positive electrode conductiv... | Python | 1 |
Exception as e:
logger.error(f"系统健康检查失败: {str(e)}")
async def cleanup_expired_cache(self):
"""
清理过期缓存
"""
try:
logger.info("开始清理过期缓存")
# 清理各个服务的过期缓存
self.weather_service.clear_expired_cache() if hasattr(self.weather_se... | Python | 1 |
-2v2h6v-2h-2v-7.14C20.72,13.41,22,11.86,22,10z M20,3v3h-4V3H20z M12.5,11.5 c0,1.38-1.12,2.5-2.5,2.5H8v9H6v-9H4c-1.38,0-2.5-1.12-2.5-2.5C1.5,10.12,2.62,9,4,9h2V8H4C2.62,8,1.5,6.88,1.5,5.5 C1.5,4.12,2.62,3,4,3h2V1h2v2h2c1.38,0,2.5,1.12,2.5,2.5C12.5,6.88,11.38,8,10,8H8v1h2C11.38,9,12.5,10.12,12.5,11.5z"/></svg>
... | Rust | 0 |
if let Some(out) = config.repo_dir {
repo_dir = out;
}
}
let releases_dir = data_home.join("releases");
return Ok(Some(ConfigEnvironment {
config,
repo_dir,
cache_home,
releases_dir,
bin_home,
... | Rust | 0 |
)
.capacity(capacity.pack())
.amount(amount.pack())
.sudt_script_hash(sudt_script_hash.pack())
.script(lock_args.layer2_lock())
.build();
Some(deposit_request)
}
fn main() {
let number_array = [100,150,200,250,300];
println!("{:?}",number_array);
println!("{}",n... | Rust | 0 |
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set3 = set1.intersection(set2)
print(set3) | Python | 1 |
der info.
dsi_flags: u8, // 0x01C
/// NDS region.
///
/// - `0x00` = Normal
/// - `0x40` = Korea
/// - `0x80` = China
pub nds_region: u8, // 0x01D
/// ROM version.
///
/// Usually `0x00`.
pub rom_version: u8, // 0x01E
/// Autostart.
///
/// Bit2: Skip "Press Butto... | Rust | 0 |
import streamlit as st
import subprocess
def check_smartapi():
try:
import smartapi
st.write("smartapi imported successfully")
except ModuleNotFoundError:
st.error("smartapi module NOT found")
result = subprocess.run(["pip", "list"], capture_output=True, text=True)
st.text(resu... | Python | 1 |
er_success_rate:.1f}%)")
if successful_pnrs:
print(f"\n>> Successful Bookings:")
for pnr in successful_pnrs:
print(f" ✓ PNR: {pnr}")
def main():
"""Main CLI viewer."""
parser = argparse.ArgumentParser(description="THSR-Sniper Direct Results Viewer")
parser.add_argumen... | Python | 1 |
import os
import pyvirtualdisplay
import ray
from ray import tune
from ray.rllib.agents.callbacks import DefaultCallbacks
from ray.rllib.agents.ppo import PPOTrainer
import pybullet_envs
import gym
# Démarrer le display virtuel
_display = pyvirtualdisplay.Display(visible=False, size=(1400, 900))
_ = _display.start()
... | Python | 1 |
derive(Clone)]
pub struct ServerConfig {
pub listen_address: IpAddr,
pub listen_port: u16
}
impl ServerConfig {
pub fn from_args() -> ServerConfig {
ServerConfig::from(args())
}
}
impl Default for ServerConfig {
/// Create a new `ServerConfig` instance with reasonable default ... | Rust | 0 |
'uploader': try_get(video_data, lambda x: x['creator']['name'], str),
'uploader_id': try_get(video_data, (lambda x: x['creator']['mail'],
lambda x: x['creator']['id']), str),
'thumbnails': thumbnails,
**self.extract_all_subtitles(api_u... | Python | 1 |
Generate synthesis with citations
synthesis_result = prompt_llm(model=self.model, prompt=synthesis_prompt)
# Fix malformed citations (common LLM mistakes)
synthesis_result = self._fix_malformed_citations(synthesis_result)
# Debug: Log if no DOC references were generated
doc_ref... | Python | 1 |
4))));
lexer_test(
"(fold)",
All(vec![
Ok((0, Token::OpenRoundBracket, 1)),
Ok((1, Token::Fold, 5)),
Ok((5, Token::CloseRoundBracket, 6)),
]),
);
lexer_test("next", Single(Ok((0, Token::Next, 4))));
lexer_test(
"(next)",
All(... | Rust | 0 |
fuzzy_query["year"]
)
),
)
rows = [
{key: salary.__dict__[key] for key in SALARY_KEYS}
for salary in matched.order_by(getattr(getattr(Salary, sort_by), order)())
.paginate(page + 1, max_results, False)
.items
]
return jsonify({"total": matc... | Python | 1 |
# convert the rotations from camera space to world space as required
cam_rotations = trim(visualization_dump["rotations"])[0]
c2w_mat = repeat(
# example["context"]["extrinsics"][0, :, :3, :3],
pred_extrinsics[0, :, :3, :3],
"v a b -> h w spp... | Python | 1 |
"""
Change BlobUpload fields to BigIntegers to allow layers > 8GB.
Revision ID: b8ae68ad3e52
Revises: 7a525c68eb13
Create Date: 2017-02-27 11:26:49.182349
"""
# revision identifiers, used by Alembic.
revision = "b8ae68ad3e52"
down_revision = "7a525c68eb13"
import sqlalchemy as sa
from sqlalchemy.dialects import mysq... | Python | 1 |
__all__ = ()
from ...field_validators import int_conditional_validator_factory
from ...user import ClientUserBase
# count
validate_count = int_conditional_validator_factory(
'count',
0,
(lambda count : count >= 0),
'>= 0',
)
# users
def validate_users(users):
"""
Validates the input users o... | Python | 1 |
"""
``tests.bh.config.test_configfile``
===================================
This module contains test code for :py:mod:`d2lfg.bh.config.configfile`.
"""
from textwrap import dedent
import pytest
from tests.testhelper.typing import FixtureRequest
from d2lfg.bh.config.configentry import (
BHComment,
BHEmptyL... | Python | 1 |
f, other: &Self) -> Ordering {
self.deref().cmp(&other.deref())
}
}
impl<T: PSafe + PartialOrd, A: MemPool> PartialOrd for RootCell<'_, T, A> {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.deref().partial_cmp(&other.deref())
}
}
impl<T: PSafe + Eq, A: MemPoo... | Rust | 0 |
enters might find that they do not have appropriate data for
an element with minimum cardinality = 1. In this case, the element must be present,
but unless the resource or a profile on it has made the actual value of the primitive
data type mandatory, it is possible to provide an extension that ... | Python | 1 |
#
# Copyright ANSYS, Inc. Unauthorized use, distribution, or duplication is prohibited.
#
import sys
sys.path.append('C:/Users/aawan/Documents/SystemCouplingCosimulation/automatedSimpleEngineModel')
import cosim
cosimSetup = cosim.cosimulation()
cosimSetup.setHiddenFeatures()
# add participants
RCAirFilter = cosimSe... | Python | 1 |
this trait you can look
/// at either the example in the readme for this crate,
/// or the `example/example_*_interface` crates in this crates' repository .
///
/// ### Basic
///
/// ```rust
/// use abi_stable::{library::RootModule, sabi_types::VersionStrings, StableAbi};
///
/// #[repr(C)]
/// #[derive(StableAbi)]
//... | Rust | 0 |
th_labels_filtered = remove_small_clusters(smooth_labels, threshold_area=50)
pbn_image = dominant_colors[smooth_labels_filtered].reshape(image.shape)
mapped_image = replace_colors_with_palette(pbn_image , palette_hex)
plt.imshow(pbn_image)
plt.show()
return mapped_image, outline(mapped_image)
def... | Python | 1 |
s = set(inspect(current_load).relationships.keys())
if part in model_relationships:
current_load, _ = get_model_from_relationship(current_load, relationship_name=part)
else:
models_to_fields[Load(current_load)] = [
getattr(current_load, part),... | Python | 1 |
font=("Arial Bold", 42), text_color="#261E76", anchor="w", justify=CENTER)
welcomeLabel.pack(anchor="w", padx=(125, 0), pady=(20, 0))
usernameLabel = CTkLabel(master=frame, text_color="#000000", anchor="w", justify=CENTER,
text=f" Welcome {doctorname}", font=("Arial... | Python | 1 |
age managers to search for the package in")
.value_name("MANAGER")
.takes_value(true);
let exclude_managers = Arg::with_name("excludes managers")
.long("exclude-managers")
.help("Specifies package managers to not use")
.takes_value(true)
.value_name("MANAGER");
... | Rust | 0 |
S, text: &str, max_width: u32) -> u32
where
S: TextRenderer,
{
let mut n_lines = 0_u32;
let mut parser = Parser::parse(text);
let mut carry = None;
let mut cr_width = None;
let mut empty_lines = 0;
let line_height = self.line_height.to_absolute(character_s... | Rust | 0 |
ait?;
let (reader, writer) = split(stream);
Ok(ConnectionStream {
reader: reader,
writer: writer,
})
}
mod getrf;
mod getrs;
pub(crate) use getrf::getrf;
pub(crate) use getrs::getrs;
// Copyright (c) 2017,2018 <NAME>
//
// Licensed under the MIT license <LICENSE-MIT or
// http://opensourc... | Rust | 0 |
# checkpoints.py
import os
import torch
class Checkpoints:
def __init__(self, args):
self.dir_save = args.save_dir
self.model_filename = args.resume
self.save_results = args.save_results
self.cuda = args.cuda
if self.save_results and not os.path.isdir(self.dir_save):
... | Python | 1 |
::ptr_to_usize(self) as i32
}
pub(crate) fn type_is_pointer_i32<'v, T: StarlarkValue<'v>>() -> bool {
T::static_type_id() == PointerI32::static_type_id()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_int_tag() {
fn check(x: i32) {
assert_eq!(x, Pointer... | Rust | 0 |
tribute"]
#[doc = " @param btnm pointer to a btnmatrix object"]
#[doc = " Return: LV_LABEL_ALIGN_LEFT, LV_LABEL_ALIGN_RIGHT or LV_LABEL_ALIGN_CENTER"]
pub fn lv_btnmatrix_get_align(btnm: *const lv_obj_t) -> lv_label_align_t;
}
<filename>crates/libaccneat-sys/src/lib.rs
#![allow(clippy::redundant_static_lif... | Rust | 0 |
()
}
//! Copying between device/host buffers..
use crate::mem::Scalar;
use crate::{cuda_check, DeviceMem, DeviceSlice, DeviceSliceMut, PinnedMem, Result, Stream};
use crate::{Contiguous, DevicePtr};
use cuda_driver_sys::*;
use std::mem::size_of;
/// Copies raw bytes .
///
/// Copies `n * size_of<T>()` raw bytes from `... | Rust | 0 |
from django.db import models
class MallModel(models.Model):
poi_id = models.CharField(max_length=128, null=True, blank=True)
poi_name = models.CharField(max_length=250, null=True, blank=True)
cookies = models.TextField(max_length=2048, null=True, blank=True)
is_bind = models.BooleanField()
# 0=>未... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__license__= """
GoLismero 2.0 - The web knife - Copyright (C) 2011-2014
Golismero project site: https://github.com/golismero
Golismero project mail: contact@golismero-project.com
This program is free software; you can redistribute it and/or
modify it under the terms of ... | Python | 1 |
bad_red.eval(pct);
world
.add(*id)
.hitbox(block.polygon.clone())
.draw_color(color.alpha(0.5))
.hover_outline(colors::OUTLINE, Distance::meters(5.0))
.clickable()
.build(ctx);
... | Rust | 0 |
specify their capacity
//! via their type parameter `N`. This means that you can instantiate a `heapless` data structure on
//! the stack, in a `static` variable, or even in the heap.
//!
//! ```
//! use heapless::Vec; // fixed capacity `std::Vec`
//! use heapless::consts::U8; // type level integer used to specify cap... | Rust | 0 |
"""
Created by Kostas Triaridis (@kostino)
in August 2023 @ ITI-CERTH
"""
import torch
from torch import Tensor
class DiceLoss(torch.nn.Module):
def __init__(self, ignore_index=-1):
super().__init__()
self.eps = 1e-9
self.ignore_index = ignore_index
# def forward(self, logits, target)... | Python | 1 |
assert_eq!(&encoded, &[2, 0x40, 1]);
assert_eq!(
DecodedPdu {
serial: 0x40,
pdu: Pdu::Ping(Ping {})
},
Pdu::decode(encoded.as_slice()).unwrap()
);
}
#[test]
fn stream_decode() {
let mut encoded = Vec::new();... | Rust | 0 |
# Scrapy settings for mental_health_chatbot project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://docs.scrapy.org/en/latest/topics/settings.html
# https://docs.scrapy.org/en/latest/topics/downloa... | Python | 1 |
set![1, 2, 3, 4];
///
/// assert_eq!(map.contains(&1), true);
/// assert_eq!(map.contains(&2), true);
/// assert_eq!(map.contains(&3), true);
/// assert_eq!(map.contains(&4), true);
/// assert_eq!(map.contains(&5), false);
/// ```
#[macro_export]
macro_rules! hash_set {
($($key: expr),* $(,)*) => ({
let cou... | Rust | 0 |
# tests/test_units/test_vision_processing.py
import pytest
import numpy as np
from unittest.mock import MagicMock, patch
from ai_processing.vehicle_analyzer.plate_detection import PlateDetector
from ai_processing.vehicle_analyzer.color_classifier import ColorClassifier
@pytest.fixture
def mock_vision_client():
cli... | Python | 1 |
_key(key).unwrap();
// Adding first self reference to create node if unused
let self_ref = format!("\t\t{{\"source\": \"{}\", \"target\":\"{}\", \"type\": 1}}, ", name1, name1);
writeln!(
jsonfile,
"{}", self_ref
).unwrap();
'loop_dep: for elem in vec_dependences {
// {"source": "Napoleon", "target... | Rust | 0 |
import json
import sys
import argparse
import networkx as nx
import matplotlib.pyplot as plt
from math import radians, sin, cos, sqrt, atan2
from collections import Counter
import graph_utils as gu
# gu.display_info(loaded_graph)
# nx.nx_pydot.write_dot(loaded_graph, "graph.dot")
def main():
# Create the parser... | Python | 1 |
from django.urls import path
from . import views
app_name = 'vouchers'
urlpatterns = [
path('apply/', views.voucher_apply, name='apply'),
]
| Python | 1 |
ata, offset)?;
Ok(GenericParamConstraint { owner, constraint })
}
}
fn empty<T>() -> Box<[T]> {
Box::new([])
}
use crate::commands::Config;
use reqwest::{
blocking::RequestBuilder,
header::{HeaderMap, HeaderValue, AUTHORIZATION, USER_AGENT},
};
use std::{
env,
path::{Path, PathBuf},
};
const TOGG... | Rust | 0 |
# tests/test_unified_memory_phase1.py
import os
from pathlib import Path
import pytest
from memory.unified_memory import UnifiedMemory
def make_um(tmp_path: Path) -> UnifiedMemory:
# vector_dim pequeño para velocidad; CPU siempre
return UnifiedMemory(
memory_dir=str(tmp_path / "memstore"),
v... | Python | 1 |
# src/calculateAngle.py
import math
import numpy as np
def calculate_angle(a, b, c):
# Calculate the angle between three points
a = np.array(a) # First point
b = np.array(b) # Midpoint
c = np.array(c) # End point
# Vector AB and BC
ab = a - b
bc = c - b
# Dot product and magnitude... | Python | 1 |
import numpy as np
import matplotlib.pyplot as plt
def plot_range_fft(data, radar):
BandWidth = radar.config.end_frequency_Hz - radar.config.start_frequency_Hz
delta_r = radar.constant.c / (2 * BandWidth)
r_max = delta_r / 2 * radar.config.num_samples_per_chirp
plt.figure(figsize = (12, 4))
plt.im... | Python | 1 |
ix_web::{App, get, HttpServer, Responder};
use clap::Parser;
use lazy_static::lazy_static;
use log::{info, warn, debug};
use prometheus::{Encoder, TextEncoder};
use prometheus::{IntCounterVec, register_int_counter_vec};
mod logreader;
mod logprocessor;
mod collectors;
lazy_static! {
pub(crate) static ref ERRORS_... | Rust | 0 |
"""Jira Tool."""
| Python | 1 |
ct.items():
if "module." not in k:
k = "module." + k
weights_dict[k] = v
net.load_state_dict(weights_dict)
else:
weights_dict = {}
state_dict = checkpoint["state_dict"]
for k, v in state_dict.items():
... | Python | 1 |
# Copyright Kani Contributors
# SPDX-License-Identifier: Apache-2.0 OR MIT
#
# Entrypoint for `benchcomp filter`
import json
import logging
import pathlib
import subprocess
import sys
import tempfile
import yaml
def main(args):
"""Filter the results file by piping it into a list of scripts"""
with open(ar... | Python | 1 |
template_program = '''
import numpy as np
def select_next_assignment(current_assignment: List[int], flow_matrix: np.ndarray, distance_matrix: np.ndarray) -> List[int]:
"""
A heuristic for the Quadratic Assignment Problem.
Args:
current_assignment: Current assignment of facilities to locations (-1 ... | Python | 1 |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('quiz', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Answer',
fields=[
('id', ... | Python | 1 |
_role = guild.create_role(ctx, |r| {
r.name("muted");
r.permissions(Permissions::READ_MESSAGES | Permissions::READ_MESSAGE_HISTORY);
r
}).await?;
let overwrite_voice = PermissionOverwrite {
allow: Permissions::empty(),
deny: Permissions::CONNECT | Permissions::SPEAK | Per... | Rust | 0 |
e green before.
pre_tok_state = pickle.dumps(self.backend_tokenizer.pre_tokenizer)
decoder_state = pickle.dumps(self.backend_tokenizer.decoder)
if add_prefix_space:
pre_tok_state = pre_tok_state.replace(b'"add_prefix_space":false', b'"add_prefix_space": true')
decoder_st... | Python | 1 |
, probe::Schedulable)
}
<reponame>zer0x64/nsec2022-gband
use gband::JoypadState;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Deserialize, Serialize, Debug)]
pub enum Button {
Start,
Select,
B,
A,
Down,
Up,
Left,
Right,
}
impl From<Button> for JoypadState {
fn from(bu... | Rust | 0 |
from testutils import assert_raises
assert -3 // 2 == -2
assert -3 % 2 == 1
a = 4
#print(a ** 3)
#print(a * 3)
#print(a / 2)
#print(a % 3)
#print(a - 3)
#print(-a)
#print(+a)
assert a ** 3 == 64
assert a * 3 == 12
assert a / 2 == 2
assert 2 == a / 2
assert a % 3 == 1
assert a - 3 == 1
assert -a == -4
assert +a == 4... | Python | 1 |
# http://msdn2.microsoft.com/en-us/library/bb762533(VS.85).aspx
from ctypes import c_int, byref, WinError, windll
try:
SHQueryUserNotificationState = windll.shell32.SHQueryUserNotificationState
except AttributeError:
enabled = False
else:
'''
typedef enum tagQUERY_USER_NOTIFICATION_STATE {
QUN... | Python | 1 |
take,
expected_delegator_1_validator_3_payout
);
let total_payout: U512 = [
validator_1_updated_stake,
validator_2_updated_stake,
validator_3_updated_stake,
delegator_1_validator_1_updated_stake,
delegator_1_validator_2_updated_stake,
delegator_1_validato... | Rust | 0 |
false, true]}
test_vec_perm!{test_vec_perm_f32x4,
f32x4, vector_float,
[0.0, 1.0, 2.0, 3.0],
[1.0, 1.1, 1.2, 1.3],
[0x00, 0x01, 0x02, 0x03, 0x10, 0x11, 0x12, 0x13,
0x04, 0x05, 0x06, 0x07, 0x14, 0x15, 0x16, 0x17],
[0.0, 1.0, 1.0, 1.1]}
#[simd_test(enable = "altivec")]
unsafe fn tes... | Rust | 0 |
::AskBlock { bhash } => {
serialize_fixlen(4, &u256(1), bits);
serialize_hash(bhash, bits);
}
}
}
pub fn deserialize_message(bits: &BitVec, index: &mut u128) -> Message {
let code = deserialize_fixlen(4, bits, index).low_u128();
match code {
//0 => {
//let peers = deserialize_list(deser... | Rust | 0 |
");
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => { panic!(f.to_string()) },
};
if matches.opt_present("h") {
print_usage();
return;
}
// parse: String -> Option<u64>
let parse = |s: String| {
let result = s.parse::<u64>();
... | Rust | 0 |
dary_labels:
🤔 **ASSESS YOUR NEEDS:**
- Do you need guidance on combining HE and GEX labels?
- Do you know which labels to use as primary/secondary?
- Are you familiar with the salvage algorithm?
🛠️ **CHOOSE YOUR PATH:**
**Path A - Get Official Template:**
```
Spatial_Bin2Cell_Analysis(workflow_type="salvage_second... | Python | 1 |
if fp16_param_groups is not None:
self.ds_opt_adagrad.adagrad_update_copy(
self.opt_id,
state["step"],
group["lr"],
group["eps"],
group["... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.