text string | label_name string | labels int64 |
|---|---|---|
ead=0)
go, _ = GrantOwner.objects.get_or_create(grant=g, person=greg)
go.save()
gb, _ = GrantBalance.objects.get_or_create(grant=g, date=date(2000,9,30), balance=4000, actual=0, month=0)
gb.save()
gb, _ = GrantBalance.objects.get_or_create(grant=g, date=date(2001,9,10), balance=... | Python | 1 |
model.endog_orig.index
ax.plot(index, self.model.endog_orig)
ax.plot(pred_index, predictions)
if alpha is not None:
pi = self.prediction_intervals(steps, theta, alpha)
label = "{0:.0%} confidence interval".format(1 - alpha)
ax.fill_between(
... | Python | 1 |
cargo:rerun-if-changed=tailwind.config.js");
println!("cargo:rerun-if-changed=postcss.config.js");
}
<gh_stars>1-10
//!# ApiResponseErr
//! [`ApiResponseErr`] is returned by enpoints to achieve a Json response success or failure
use crate::error;
///Is returned by enpoints to achieve a Json response success or fa... | Rust | 0 |
itializing I2C...\n")
.expect("Write should never fail");
let (i2c0_sda, _) = swm
.fixed_functions
.i2c0_sda
.assign(swm.pins.pio0_11.into_swm_pin(), &mut swm.handle);
let (i2c0_scl, _) = swm
.fixed_functions
.i2c0_scl
.assign(swm.pins.pio0_10.into_swm_pi... | Rust | 0 |
import redis
import functools
import pickle
class ToolCache:
def __init__(self, host='localhost', port=6379, db=0, password=None, timeout:int = 30):
# Establish a connection to the Redis server with the given credentials.
"""
Creates tool cache for MAS Ai tools.
Args:
... | Python | 1 |
el_fd_new(prev_qpos, qpos, env.dt)
qvel = qvel.clip(-10.0, 10.0)
rlinv = qvel[:3].copy()
rlinv_local = transform_vec(qvel[:3].copy(), qpos[3:7], env.cc_cfg.obs_coord)
rangv = qvel[3:6].copy()
expert["qvel"].append(qvel)
expert["rlinv"].append(rlinv... | Python | 1 |
panic!("Message decoded into incorrect variant."),
}
}
_ => panic!("Event decoded into incorrect variant."),
}
}
}
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub fn serialize_operation_crate_operation_add_tags_to_resource(
i... | Rust | 0 |
import streamlit as st
from PIL import Image
import os
from io import BytesIO
import base64
st.set_page_config(
page_title="Sobre Nosotros",
page_icon="👥",
layout="wide"
)
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@500;700&family=Poppins:wght@300;400;600... | Python | 1 |
import random
from pytest import mark
import dowhy.datasets
from .base import SimpleRefuter
@mark.usefixtures("fixed_seed")
class TestPlaceboRefuter(object):
@mark.parametrize(
["error_tolerance", "estimator_method", "num_samples"], [(0.03, "backdoor.linear_regression", 1000)]
)
def test_refuta... | Python | 1 |
mix of addition, deletion, and modification in a single layer directory
fn basic_scan() {
}
#[test]
fn file_moves() {
}
#[test]
fn file_copies() {
}
}/*
Copyright (c) 2020 <NAME>
Permission is hereby granted, free of charge, to any person obtaini... | Rust | 0 |
from sqlmodel import SQLModel, Field, Relationship
from typing import Optional, TYPE_CHECKING
from datetime import datetime
from sqlalchemy.sql import func
if TYPE_CHECKING:
from data.models.job import Job
from data.models.user import User
class Rating(SQLModel, table=True):
job_id: int = Field(
... | Python | 1 |
();
}
<filename>src/definitions.rs
#![allow(bad_style)]
use std;
use std::fmt;
pub const SHARED_MEMORY_VERSION: u32 = 9;
pub const STRING_LENGTH_MAX: usize = 64;
pub const STORED_PARTICIPANTS_MAX: usize = 64;
pub const TYRE_COMPOUND_NAME_LENGTH_MAX: usize = 40;
pub const TYRE_MAX: usize = 4;
pub const VEC_MAX: usize ... | Rust | 0 |
# Copyright 2020 gRPC 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 in writing... | Python | 1 |
EC, automatic end mode
// must be selected (AUTOEND=1). In this case, the STOP condition automatically follows the
// PEC transmission.
w.pecbyte().bit(self.cfg.smbus);
w.start().set_bit()
}
... | Rust | 0 |
or a concrete type, e.g. `Foo`, will
/// accept values _only_ of exactly type `Foo`. This feels very much like
/// Haskell's [_parametric polymorphism_](https://wiki.haskell.org/Polymorphism).
/// This is similar to [templates](https://en.cppreference.com/w/cpp/language/templates)
/// with the addition of [constraints ... | Rust | 0 |
TURE_ERROR | 0x0001;
}
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
/// Output character size
pub enum CharacterSize {
SevenBit = 0,
EightBit = 1,
}
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
/// Method for finding the largest dimension for splitting,
/// and sorting by th... | Rust | 0 |
"""
Test that data encoded with earlier versions can still be decoded correctly.
"""
from __future__ import absolute_import, division, print_function
import pathlib
import unittest
import numpy as np
import h5py
from bitshuffle import __zstd__
from packaging import version
TEST_DATA_DIR = pathlib.Path(__file__).p... | Python | 1 |
#!/usr/bin/env python3
"""
Simple API test to verify LLM provider is working correctly
"""
from utils.llm_provider import get_llm_provider
from utils.logger import get_logger
import json
logger = get_logger(__name__)
def test_api():
"""Test basic API functionality"""
provider = get_llm_provider("gpt-5", "tes... | Python | 1 |
# mysql/pyodbc.py
# Copyright (C) 2005-2016 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""
.. dialect:: mysql+pyodbc
:name: PyODBC
:dbapi: pyodbc
:connectstr... | Python | 1 |
рка схем
layer_schema_selected = (
hasattr(self, 'layer_schema_combo') and
self.layer_schema_combo.currentText() != "" and
self.layer_schema_combo.currentText() != "none"
)
# Если экспортируем только слои, схема файлов не нужна
if self.export... | Python | 1 |
responses: usize,
) -> Result<HashMap<String, V>, MemcacheError> {
let mut result = HashMap::new();
for _ in 0..=max_responses {
let Response {
header,
key,
extras,
value,
} = parse_response(reader)?.err()?;
if header.opcode == Opcode::Noop... | Rust | 0 |
#Initialissierung
ANTEIL_0_14weiter= 0.066
ANTEIL_15_49weiter= 0.029
ANTEIL_50_64weiter= 0.066
ANTEIL_0_14bleiben= 0.93
ANTEIL_15_49bleiben= 0.97
ANTEIL_50_64bleiben= 0.925
ANTEIL_65bleiben= 0.972
GEBURTEN_15_49= 0.2
schritt = 0
Kinder=float(input("Startanzahl der 0-14 jährigen:"))
Jugendliche=float(input("Startanz... | Python | 1 |
nit();
let script_tx: Vec<u8> = <Vec<u8>>::from_hex("0400008085202f8901fcaf44919d4a17f6181a02a7ebe0420be6f7dad1ef86755b81d5a9567456653c010000006a473044022035224ed7276e61affd53315eca059c92876bc2df61d84277cafd7af61d4dbf4002203ed72ea497a9f6b38eb29df08e830d99e32377edb8a574b8a289024f0241d7c40121031f54b095eae066d96b2557... | Rust | 0 |
"size": file.file_size,
"protect": cmd.lower().strip() == "/pbatch",
}
og_msg +=1
outlist.append(file)
except:
pass
if not og_msg % 20:
try:
await sts.edit(FRMT.format(total=l_msg_id-f_msg_id, cu... | Python | 1 |
= exploration_policy
self._inner_optimizer.module = exploration_policy
paths = exploration_trajectories.to_trajectory_list()
batch_samples = self._process_samples(paths)
self._adapt(batch_samples, set_grad=False)
self._policy = old_policy
self._inner_algo.policy = sel... | Python | 1 |
/// Prompt for a parseable value with a provided fallback value if empty.
///
/// ```no_run
/// use promptly::Promptable;
/// u32::prompt_default("Enter the year", 2018)?;
/// # Result::<_,Box<std::error::Error>>::Ok(())
/// ```
///
/// Default value is visible in the prompt as: `(defau... | Rust | 0 |
let b = i8x4::new(4, 3, 2, 2);
// call sadd8() to set GE bits
dsp::sadd8(::mem::transmute(a), ::mem::transmute(b));
let c = i8x4::new(1, 2, 3, ::std::i8::MAX);
let r: i8x4 = dsp_call!(dsp::sel, a, b);
assert_eq!(r, c);
}
}
#[test]
... | Rust | 0 |
e_ids[np.random.choice(len(nearest_pose_ids))] = id_render
src_rgbs = []
src_cameras = []
for id in nearest_pose_ids:
src_rgb = imageio.imread(train_rgb_files[id]).astype(np.float32) / 255.0
src_rgb = src_rgb[..., [-1]] * src_rgb[..., :3] + 1 - src_rgb[..., [-1]]
... | Python | 1 |
}
$lib.model.ext.delFormProp("test:guid", "_custom:risk:level")
''')
nodes = await core.nodes('syn:prop=test:guid:_custom:risk:level')
self.len(0, nodes)
nodes = await core.nodes('test:guid:_custom:risk:severity')
self.len(1, nod... | Python | 1 |
/// Attempt to fetch values "configurable", "enumerable", "writable" from the value,
/// if they're not there default to false
fn from_value(v: Value) -> Result<Self, &'static str> {
Ok(Self {
configurable: {
match from_value::<bool>(v.get_field_slice("configurable")) {
... | Rust | 0 |
ect("Created signature should be parsable");
}
echo_signature("test/roundtrip", signature);
let mut cursor = Cursor::new(&data[..]);
verifier.verify(&mut cursor, signature).expect("failed to verify just signed signature");
}
#[test]
fn verify_pgp_crate() {
let (sig... | Rust | 0 |
ecurity analysis:\n",
'suffix': "\n\nRecommendation: Follow security best practices and regular audits."
},
'general': {
'system': f"You are {agent_name}, a helpful AI assistant. Provide comprehensive and accurate responses.",
'prefix': "",
... | Python | 1 |
从 {source_dir} 到 {mixed_dir}")
print(f"\n混合集合创建完成! 文件保存在目录: {mixed_dir}")
def main_mixed_circuits():
"""主函数:生成混合尺寸的量子电路"""
print("生成混合尺寸的量子电路...")
# 生成电路
circuits = generate_mixed_circuits()
# 保存为QPY文件
output_dir = "mixed_qubit_circuits_new"
saved_files = save_circuits_t... | Python | 1 |
import flet as ft
import pandas as pd
import user
import movie_db_utils
def return_gallery_page(navigationBar: ft.NavigationBar, user: user.User) -> ft.View:
grid_view: ft.GridView = ft.GridView(expand=True, runs_count=5, child_aspect_ratio=2)
for index, row in user.movie_rating_data_frame.iterrows():
... | Python | 1 |
gs = rot2dOnR2(N)
for irr in gs.irreps:
type = FieldType(gs, [irr] * 3)
for i in range(3):
t1 = GeometricTensor(torch.randn(10, type.size, 11, 11), type)
for _ in range(5):
g = gs.fibergroup.sample()
... | Python | 1 |
tal_state: [bool; MAX_DIGITAL],
pub analog_state: [f32; MAX_ANALOG],
}
impl ControllerState {
pub fn new() -> Self {
Self {
status: ControllerStatus::Disconnected,
sequence: 0,
digital_state: [false; MAX_DIGITAL],
analog_state: [0.0; MAX_ANALOG],
... | Rust | 0 |
do not follow
/// > the whole BIP39 specifications.
///
/// # considerations
///
/// It is recommended to avoid using it as this is a weak
/// cryptographic scheme:
///
/// 1. it does not allow for mnemonic passwords (no plausible deniability);
/// 2. the use of an invariant of the cryptographic scheme makes it less
/... | Rust | 0 |
to_stream(WriteTap(&mut output));
istream.set_buffer_size(512);
istream.decode(&encoded[..]).status.unwrap();
match istream.buffer {
Some(StreamBuf::Owned(vec)) => assert!(vec.len() <= BUF_SIZE),
Some(StreamBuf::Borrowed(_)) => panic!("Unexpected borrowed buffer, where f... | Rust | 0 |
Len(F64(0.0), x * y * z))
.create_kernel(&Kernel {
name: "kern",
args: vec![KCBuffer("u", CF64), KCBuffer("databuf", CF64)],
src: "
u[x+x_size*(y+y_size*z)] = data(x,y,z,databuf);
",
needed: vec![],
})
.build()?;
g... | Rust | 0 |
# Copyright 2023 Google LLC
#
# 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 agreed to in writing, sof... | Python | 1 |
Giris < 5):
print("Az miktarda hatalı girişi her hoca olumlulukla kabul eder.")
else:
print("Biraz abartılı hatalı giriş olmuş.")
if (toplamHataliGiris > 10):
print("Bacım sen rast... | Python | 1 |
# Generated by Django 5.1.1 on 2024-11-18 01:21
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("core", "0029_alter_bill_image_delete_receiptimage"),
]
operations = [
migrations.CreateModel(
n... | Python | 1 |
t _) },
mip_level: destination.mip_level,
origin: destination.origin,
aspect: destination.aspect,
},
copy_size,
);
}
}
pub struct CommandEncoder(pub(crate) Box<dyn CommandEncoderTrait>);
impl CommandEncoder {
#[inline]
pub fn ... | Rust | 0 |
pbstrPath: *mut ::BSTR) -> ::HRESULT,
fn GetFilespec(&mut self, pbstrFilespec: *mut ::BSTR) -> ::HRESULT,
fn GetRecursive(&mut self, pbRecursive: *mut bool) -> ::HRESULT,
fn GetAlternateLocation(&mut self, pbstrAlternateLocation: *mut ::BSTR) -> ::HRESULT,
fn GetBackupTypeMask(&mut self, pdwTypeMask: *m... | Rust | 0 |
#[derive(Component)]
struct VFX;
#[derive(Component)]
pub struct AttackNearest {
pub damage: f32,
pub interval: Timer,
}
#[derive(Component)]
pub struct Item;
#[derive(Component)]
pub struct XpGem {
value: u32,
}
#[derive(Component)]
pub struct HitBox {
pub pos: Vec2,
pub size: Vec2,
pub dam... | Rust | 0 |
22ss1",
"name": "2022 Special Session",
"start_date": "2022-07-25",
"end_date": "2022-08-14",
"active": False,
},
{
"_scraped_name": "First Regular Session 123rd General Assembly (2023)",
"classification": "primary",
"id... | Python | 1 |
pl Default for NumberingFormatVal {
fn default() -> Self {
Self::Decimal
}
}
__string_enum! {
NumberingFormatVal {
Bullet = "bullet",
Decimal = "decimal",
DecimalZero = "decimalZero",
LowerLetter = "lowerLetter",
LowerRoman = "lowerRoman",
Ordinal = "... | Rust | 0 |
_permissive_rule(
original: &ConstraintPipeline,
modified: &mut ConstraintPipeline,
random: Arc<dyn Random + Send + Sync>,
) {
let constraints = original
.modules
.iter()
.map(|module| {
module
.get_constraints()
.map(|constraint| match... | Rust | 0 |
que identification for the text.
# epub_uid = ''
# A tuple containing the cover image and cover page html template filenames.
# epub_cover = ()
# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
# epub_pre_files = []
# HTML files s... | Python | 1 |
Record::builder()
.args(format_args!("arguments2"))
.level(Level::Error)
.target("second_target")
.module_path_static(Some("module_path1"))
.file_static(Some("file2"))
.line(Some(111))
.key_values(kvs)
.build();
let tests = &[
(record1.clone(... | Rust | 0 |
on_click=clear_calculator, use_container_width=True)
# Row 4 of the calculator (0, ., =)
with col1:
st.button("0", on_click=number_click, args=(0,), use_container_width=True)
with col2:
st.button(".", on_click=lambda: setattr(st.session_state, 'display',
st.session_state.display + '.' if '.' not... | Python | 1 |
# SPDX-FileCopyrightText: (C) 2023 - 2025 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
from scene_common.schema import SchemaValidation
import tests.common_test_utils as common
TEST_NAME = "NEX-T10458"
SCHEMA_PATH = "controller/src/schema/metadata.schema.json"
INVALID_SCHEMA_PATH = "../schem... | Python | 1 |
# -*- coding: utf-8 -*-
import tkinter as tk
from tkinter import messagebox
# 数独求解函数
def solve_sudoku(board):
# 找到下一个空格
empty = find_empty(board)
if not empty:
return True # 如果没有空格了,表示数独已解决
row, col = empty
# 尝试填入数字
for num in range(1, 10):
if is_valid(board, num, (row, col)):... | Python | 1 |
from __future__ import print_function, annotations
import contextlib
import decimal
import fractions
import os
from converter import safe_math, constants
def parse_quantity(quantity):
'''
Parse a quantity, supports pretty much everything with high precision
>>> parse_quantity('inf')
Decimal('Infini... | Python | 1 |
"""REST API endpoint for games.
Provides a game context for the user to interact with the procedures.
It automatically loads the current active dartboard and camera.
"""
import asyncio
import json
import redis
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
from countdart.database.crud import dartboard... | Python | 1 |
.truthy() {
Ok(format!("{} is valid!", value))
} else {
Err(format!("{} is not valid :(", value))
}
}
<filename>src/spi/clock.rs
use core::marker::PhantomData;
use crate::syscon::{self, clock_source::PeripheralClockSelector};
/// Contains the clock configuration for an SPI instance
pub struct ... | Rust | 0 |
import pandas as pd
df = pd.read_csv ( "/Users/deboraheunice/Desktop/lab_exam_practice/Deborah Eunice Arinaza - Exam_Table.csv")
df = df['Scientific Name'].unique()
df.to_csv('/Users/deboraheunice/Desktop/lab_exam_practice/Arinaza_B3_answer/b3_output3.csv')
| Python | 1 |
import numpy as np
import einops
from MFTIQ.utils import interpolation
from MFTIQ.utils.misc import ensure_numpy
def convert_to_point_tracking(MFT_result, queries):
"""Convert MFT results to point-tracking results.
args:
MFT_result: MFT.results.FlowOUTrackingResult
queries: (N xy) tensor with quer... | Python | 1 |
U: 'static + Uniforms,
A: 'static + Attachments,
{
raw: RawProgram,
uniform_locs: U::ULC,
state: Rc<ContextState>,
_marker: PhantomData<(*const V, *const A)>,
}
pub(crate) struct ProgramTarget(RawProgramTarget);
pub(crate) struct BoundProgram<'a, V: 'a + Vertex, U: 'static + Uniforms, A: 'static + ... | Rust | 0 |
impl<'a, T> Iterator for Drain<'a, T> {
type Item = (T, usize);
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn format_all_the_things()... | Rust | 0 |
"""Allow for null values
Revision ID: bc6304c73727
Revises: 6304f155141a
Create Date: 2024-10-18 09:24:37.921978
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
import sqlmodel
# revision identifiers, used by Alembic.
revision: str = "bc6304c73727"
down_revision: Union[str, N... | Python | 1 |
d['actions'] for d in dict], axis=0)
dict = pkl.load(open(dir + '/obs_dict.pkl', "rb"))
states = dict['raw_state']
# TODO: check if renaming is required for widowx to widowx_controller
controller = WidowXVelocityController('widowx', True)
rospy.sleep(2)
controller.move_to_neutral()
# contr... | Python | 1 |
pub const UART_UARTPCELLID2_UARTPCELLID2_MSB: u32 = 7;
pub const UART_UARTPCELLID2_UARTPCELLID2_LSB: u32 = 0;
pub const UART_UARTPCELLID2_UARTPCELLID2_ACCESS: &'static [u8; 3usize] = b"RO\0";
pub const UART_UARTPCELLID3_OFFSET: u32 = 4092;
pub const UART_UARTPCELLID3_BITS: u32 = 255;
pub const UART_UARTPCELLID3_RESET:... | Rust | 0 |
t_eq!(fn_range.count, 0);
let button = tab.wait_for_element("#incrementor")?;
button.click()?;
let result = tab.take_precise_js_coverage()?;
let updated_script_coverages: Vec<_> = result
.iter()
// discludes 'anonymous' scripts we inject into the page
.filter(|script_cov| scri... | Rust | 0 |
fn visit_macro(&mut self, _mac: &syn::Macro) {}
}
#[cfg(test)]
mod tests {
use super::*;
use syn::{parse_quote, Type};
#[test]
fn it_works() {
let t: Type = parse_quote!(Vec<T>);
let id: Ident = parse_quote!(T);
let mut exp = HashSet::new();
exp.insert(id);
let generics = exp.clone();
assert_eq!(e... | Rust | 0 |
from typing import List
from fastapi import APIRouter, HTTPException
from models.team import Team
from services.draw_logic import get_valid_pairings
from config.database import collection_name
from schema.schemas import list_serial, individual_serial
from bson import ObjectId
router = APIRouter()
@router.get("/", de... | Python | 1 |
#kata
#https://www.codewars.com/kata/61fef3a2d8fa98021d38c4e5/train/python
#this one times out
# def card_game(n):
# alice,bob=0,0
# while n>0:
# if n%2==0:
# alice+=n/2
# n=n/2
# bob+=1
# n=n-1
# else:
# alice+=1
# n=n-1
# ... | Python | 1 |
import sys
import getopt
import os
from kyber_py.ml_kem import ML_KEM_512, ML_KEM_768, ML_KEM_1024
from kyber_py.ml_kem.pkcs import (
ek_to_der,
ek_to_pem,
dk_to_der,
dk_to_pem,
)
def help_msg():
print(
f"""Usage: {sys.argv[0]} [options]
--dk FILE Decapsulation key file name
--dk-... | Python | 1 |
oints_line, points_square), 1)
pointsReconstructed_line = network_line.forward_inference(img, grid2)
pointsReconstructed_square = network_square.forward_inference(img, grid)
pointsReconstructed = torch.cat((pointsReconstructed_line, pointsReconstructed_square), 1)
print(results)
outdir = './outpu... | Python | 1 |
ator = Layout::new::<xlib::XEvent>();
unsafe {
let x_evt_ptr = alloc(allocator) as *mut xlib::XEvent;
xlib::XNextEvent(self.disp.raw, x_evt_ptr);
if (*x_evt_ptr).type_ == self.xkb_event_type {
Some(*(x_evt_ptr as *mut xlib::XkbEvent))
... | Rust | 0 |
.with_context(|| format!("{:#}", krate))
.expect("can't read");
match &krate.source {
Source::Registry { chksum, .. } => cf::util::validate_checksum(&bytes, chksum)
.expect("failed to validate checksum"),
_ => unreachable!(),
... | Rust | 0 |
UserId,
db: DbConn,
cache_http: State<'_, CacheHttp>,
) -> Result<Json<Vec<RandomInfix>>, SettingsError> {
use crate::db::schema::randominfixes::dsl::*;
let guilds = get_guilds_for_user(cache_http.inner(), &db, user.into())
.await?
.into_iter()
.map(|(guild, _)| BigDecimal::from_u64(guild.id.0))
... | Rust | 0 |
# Widget for displaying real-time logs
from PyQt6.QtWidgets import QWidget, QTextEdit, QVBoxLayout
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QFont
class StatusLogWidget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setObjectName("statusLogWidget") # For stylesh... | Python | 1 |
let list_of_word : Vec<String> = s.split(' ').filter(|s| s.len() == 5).map(|s| s.to_string()).collect();
for w in list_of_word.into_iter() {
word_collector.entry(w).and_modify(|e| *e += 1).or_insert(1);
}
}
let mut key_value : Vec<(String, u64)> = word_collector.into_iter().colle... | Rust | 0 |
descriptive_text = "\n".join(
[
f"On {entry.datetime}, the sentiment value was "
f"{entry.value}."
for entry in time_series_data
]
)
return header + descriptive_t... | Python | 1 |
import unittest
from hstrat._auxiliary_lib import is_strictly_decreasing
class TestIsStrictlyDecreasing(unittest.TestCase):
# tests can run independently
_multiprocess_can_split_ = True
def test_empty(self):
assert is_strictly_decreasing([])
def test_singleton(self):
assert is_stri... | Python | 1 |
eated in refresh if needed.
if _monitor:
_monitor.destroy()
_monitor = None
clear()
refresh(True)
msg = "BRAILLE: Initialized"
debug.print_message(debug.LEVEL_INFO, msg, True)
return True
def shutdown():
"""Shuts down the braille module. Returns True if the shutdown proc... | Python | 1 |
from typing import TYPE_CHECKING
from sqlalchemy import String
from sqlalchemy.orm import Mapped, mapped_column, relationship
from src.models.base_model import BaseModel
from src.models.mixins.custom_types import created_at_ct, updated_at_ct, uuid_pk
from src.schemas.user_schema import UserDB
if TYPE_CHECKING:
f... | Python | 1 |
let secret = ecdh::agree(&my_ecdh_key, &event.ecdh_pubkey.0)
.expect("Should never failed with valid ecdh key; qed.");
let mut master_key_buff = event.encrypted_master_key.clone();
let master_key = aead::decrypt(&event.iv, &secret, &mut master_key_buff[..])
... | Rust | 0 |
iter()
.map(|(session_id, _)| session_id)
.collect();
let _ = control.filter_broadcast(
Some(peer_ids),
self.proto_id,
fbb.finished_data().to_vec(),
);
... | Rust | 0 |
Channel>,
trans_mgr: TransportManager,
engine: Arc<Engine>,
observer: Box<dyn StateObserver>,
replica_cache: ReplicaCache,
marker: PhantomData<M>,
}
// Send is safe because the ReplicaCache field is not accessible outside of RaftWorker.
unsafe impl<M: StateMachine> Send for RaftWorker<M> {}
impl... | Rust | 0 |
| |d dS dS |dkr| D ]6}|d
krqt|ds
t|ds
t|dr dS qdS d| kr.dkrhn n6| D ],}dt | krVdkr6n n dS q6dS d| krdkrn n6| D ],}dt | krdkrn n dS qdS d S )N r r l TFiu Greeki i Hebrewi0 u ・HiraganaKatakanaHani` ... | Python | 1 |
cExpressionWithVar(
0xF7,
(
(Expr.PushLong, 0xFFFFFFFF),
Expr.Nop,
Expr.Return,
),
)
def _loc_1184D(): pass
label('loc_1184D')
Jump('loc_13836')
def _loc_11852(): pass
label('loc_11852')
MenuCreate(1, 0, 24.0, 0)
MenuAddIt... | Python | 1 |
#!/usr/bin/python3
if __name__ == "__main__":
from calculator_1 import add, sub, mul, div
import sys
if len(sys.argv) - 1 != 3:
print("Usage: ./100-my_calculator.py <a> <operator> <b>")
sys.exit(1)
x = {"+": add, "-": sub, "*": mul, "/": div}
if sys.argv[2] not in list(x.keys()):
... | Python | 1 |
height_m=105,
width_m=68,
players=list(player_dict.values()),
in_possession_team="TEAM_A",
)
return var2.pitch_control_field
def decompress_gzip_pitch_control_field(stored_pitch_control_field):
# Update the heatmap
decompressed_data = gzip.decompress(stored_pitch_control_fi... | Python | 1 |
_base_ = [
'_base_/models/mask_rcnn_DAMamba_fpn.py',
'_base_/datasets/coco_instance.py',
'_base_/schedules/schedule_1x.py',
'_base_/default_runtime.py'
]
# optimizer
model = dict(
backbone=dict(
pretrained='path/DAMamba-B.pth',
type='DAMamba_base',
pretrain_size=224,
... | Python | 1 |
5}
\protect\renewcommand{\sphinxcode}[1]{\colorbox{inlineVerbatimBorderColor}{\texttt{#1}}}
% Drawing and image positioning
%---------------------------------
\usepackage{tikz}
\usetikzlibrary{positioning}
% Reduce space between \item
%----------------------------------
\let\tempone\itemize
\let\temptwo\enditemiz... | Python | 1 |
import retrieve_unaligned_seq as unaligned_seq
import retrieve_aligned_seq as aligned_seq
GraphDatabase = unaligned_seq.GraphDatabase
URI = unaligned_seq.URI
AUTH = unaligned_seq.AUTH
DB_NAME = unaligned_seq.DB_NAME
def get_all_sample_names(tx):
query = """
MATCH (s:Sample)
RETURN s.name AS sample... | Python | 1 |
`serde::Deserialize` for `Row`.
#![doc(html_root_url = "https://docs.rs/ip2proxy/2.0.0")]
#![forbid(unsafe_code)]
#![warn(missing_docs)]
#![warn(missing_debug_implementations)]
use std::{
cmp::min,
io,
io::{ErrorKind, Read},
net::{IpAddr, Ipv4Addr, Ipv6Addr},
path::Path,
};
use bitflags::bitflag... | Rust | 0 |
0CX(NOPDtDlDU379-=DtDH9 R^^**1 BCCrw c [ XS5 n[ U R 5 5 nUR U[ R
R 5 [ X5 $ )Nr6 r r{ r insertr rx ry r; )r ... | Python | 1 |
import chess
class PieceEvaluation:
def __init__(self):
self.piece_values = {
chess.PAWN: 1,
chess.KNIGHT: 3,
chess.BISHOP: 3,
chess.ROOK: 5,
chess.QUEEN: 9,
chess.KING: 200,
}
def evaluate_position(self, board: chess.Boar... | Python | 1 |
let log_outputs = &docker.logs(&name, logs_options).try_collect::<Vec<LogOutput>>().await?;
let mut stderr = String::new();
let mut stdout = String::new();
for log_output in log_outputs {
match log_output {
LogOutput::StdErr { message } => stderr.push_str(String::from_utf8_lossy(&m... | Rust | 0 |
r Punctuated<T> {
type Target = [(T, Punct)];
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<T> std::ops::DerefMut for Punctuated<T> {
fn deref_mut(&mut self) -> &mut <Self as std::ops::Deref>::Target {
&mut self.inner
}
}
<reponame>shino16/cpr<filename>src/iter/cum.rs
use... | Rust | 0 |
import torch
import torchvision
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor
def get_model():
model = torchvision.models.detection.maskrcnn_resnet50_fpn()
in_features = model.roi_heads.box_predictor.cls_score.in_feat... | Python | 1 |
x> {
pub async fn new(
db: DBPtr,
engine: TxEngine<Tx>,
shard_id: ShardId,
chain_cfg: &ChainConfig,
net_cfg: &NetworkConfig,
) -> Result<Self> {
let keypair = net_cfg.keypair.to_libp2p_keypair();
let mut discv =
Discovery::new(keypair.public(),... | Rust | 0 |
# SPDX-FileCopyrightText: Copyright (c) 2021 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of sourc... | Python | 1 |
);
let visuals = ui.style().interact(&response);
if selected || response.hovered {
let bg_fill = if selected {
ui.style().visuals.selection.bg_fill
} else {
Default::default()
};
ui.painter()
.rect(... | Rust | 0 |
t takes about 5-6 milliseconds, meaning control frequency is capped at 200Hz.
# and if you factor in other operations like policy inference etc. the max control frequency is typically more like 30-60 Hz.
# Moreover on the rare occassions reading qpos can take 40 milliseconds which causes the control ste... | Python | 1 |
r"""Utility functions to get statistics from dataset."""
__all__ = [
# Functions
"data_overview",
"sparsity",
]
import pandas
from pandas import DataFrame, Series
def sparsity(df: DataFrame) -> tuple[float, float]:
r"""Quantify sparsity in the data."""
mask = pandas.isna(df)
col_wise = mask.... | Python | 1 |
to a value which isn't a string.
///
/// ```
/// use bson::{rawdoc, raw::ValueAccessErrorKind};
///
/// let doc = rawdoc! {
/// "string": "hello",
/// "bool": true,
/// };
///
/// assert_eq!(doc.get_str("string")?, "hello");
/// assert!(matches!(doc.get_str("bool").u... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.