text string | label_name string | labels int64 |
|---|---|---|
g
global isDialogPlaying
global dialogFileToPlay
isDialogPlaying = False
stopPlayingCurrentDialog = False
readyToPlayDialog = False
dialogFileToPlay = ""
try_makedir("cache") # create the cache directory if it doesn't exist that stores the tts dialogs
# press F2 to stop the current dia... | Python | 1 |
"""Creando tabla intermedia de habilidades y pokemon
Revision ID: 914e13f16ac8
Revises: 523714788163
Create Date: 2024-11-06 21:48:18.153637
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '914e13f16ac8'
down_revision: U... | Python | 1 |
-lang.org/nightly/core/default/trait.Default.html#tymethod.default).
pub fn new(width: usize, height: usize) -> Self {
Pixels {
width: width,
height: height,
pixels: vec![Pixel::default(); width * height]
}
}
}
impl ops::Index<usize> for Pixels {
type Out... | Rust | 0 |
# Copyright (C) 2023 Salvatore Sanfilippo <antirez@gmail.com>
# All Rights Reserved
#
# This code is released under the BSD 2 clause license.
# See the LICENSE file for more information
import uasyncio as asyncio
from freakwan import FreakWAN
fw = FreakWAN()
# Connect to WiFi ASAP if the configuration demands so.
wi... | Python | 1 |
"""
Utilities package containing helper functions and classes.
"""
| Python | 1 |
----
//
// ---------------------------------------------------------------------
// Magic Bitboards
// ---------------------------------------------------------------------
//
// Bishops
// ----------------
//
// Guidance can be found f.e. here:
// https://stackoverflow.com/questions/30680559/how-to-find-magic-bitboa... | Rust | 0 |
"""
A [Highway layer](https://arxiv.org/abs/1505.00387) that does a gated combination of a linear
transformation and a non-linear transformation of its input.
"""
from typing import Callable
import torch
from multimedeval.overrides_ import overrides
class Highway(torch.nn.Module):
"""
A [Highway layer](http... | Python | 1 |
33333333332).on(cirq.LineQubit(3)),
]), cirq.Moment(operations=[
cirq.FSimGate(theta=-0.7853981633974483, phi=0.1308996938995747).on(
cirq.LineQubit(1), cirq.LineQubit(2)),
]), cirq.Moment(operations=[
cirq.rz(np.pi * 1.0421187073203755).on(cirq.LineQubit(1)),
cirq.rz(np.pi *... | Python | 1 |
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
# Original keyboard
def build_initial_admin_keyboard():
return InlineKeyboardMarkup(
inline_keyboard=[
[InlineKeyboardButton(text="➕ Add admins", callback_data="add_admins_prompt")],
[InlineKeyboardButton(text="🗑... | Python | 1 |
version}\n"
file.write(line)
@staticmethod
def flatten_requirements(requirements: dict):
"""
打平依赖情况
:param: {package: version_sig} # {QPT: ==1.0b1.dev1}
:return: requirements: {package: abs_version} # {QPT: 1.0b1.dev1}
"""
all_req = OrderedDict()
... | Python | 1 |
from es.models.core.driver import ChromeDriver
from es.utils import get_idpw
# from es.models.debugger import debugger
# debugger.start(__file__)
web = ChromeDriver(keep_alive=True)
web.set_window_size(1920 * 3 // 4, 1080)
web.set_window_position(0, 0)
web.set_repeat(3, 0.01)
web.get("https://hana-prd-ap-4.ssu.ac.kr:... | Python | 1 |
ted_data=_encrypted_data)
class ReqPqRequest(TLRequest):
CONSTRUCTOR_ID = 0x60469778
SUBCLASS_OF_ID = 0x786986b8
def __init__(self, nonce: int):
"""
:returns ResPQ: Instance of ResPQ.
"""
self.nonce = nonce
def to_dict(self):
return {
'_': 'ReqPqRe... | Python | 1 |
# (c)2020, Anton Karneliuk
msg = {
"unknown_arg": "There is no such argument. Run '--help' for details.",
"help": "The following keys are availble:\n\n -u (--user): Provide the username to connect to the network element\n -p (--pass): Provide the password to connect to the network element\n -h (--... | Python | 1 |
scenario_telemetry=scenario_telemetry,
)
except Exception as e:
logging.error(
f"uncaught exception on scenario `run()` method: {e} "
f"please report an issue on https://github.com/krkn-chaos/krkn"
... | Python | 1 |
batch_capacity = req.batch_capacity;
}
if req.plan_print {
conf.plan_print = true;
}
if let Some(servers) = req.servers.take() {
match servers {
Servers::Local(_) => conf.reset_servers(ServerConf::Local),
Servers::Part(mut p) => {
if !p.servers.i... | Rust | 0 |
if index == 0 {
""
} else {
&self.customer_name
}
}
}
#[derive(Clone, Builder)]
pub struct OrderItem {
pub product_name: String,
pub quantity: u32,
pub item_price: f32,
}
#[derive(Clone, Builder)]
pub struct SummaryRow {
pub product_name: String,
... | Rust | 0 |
import numpy as np
def euclidean_dist( test_matrix, train_matrix):
"""
Args:
x: pytorch Variable, with shape [m, d]
y: pytorch Variable, with shape [n, d]
Returns:
dist: pytorch Variable, with shape [m, n]
"""
num_test = test_matrix.shape[0]
num_train = train_matrix.shape[0]
... | Python | 1 |
"""
Create a random 4×4 matrix, and find:
Maximum value
Minimum value
Index of the maximum value
"""
import numpy as np
matrix = np.random.rand(4,4)
print(f"4x4 Matrix: {matrix}")
# now find Maximum Value
print(f"Maximum element value: {np.max(matrix)}")
# now find minumum value
print(f"Minimum Element: {np.min... | Python | 1 |
ry.x` and `build.rs` from
//! the root of this crate.
//!
//! ``` text
//! $ cat >memory.x <<'EOF'
//! MEMORY
//! {
//! /* NOTE K = KiBi = 1024 bytes */
//! FLASH : ORIGIN = 0x08000000, LENGTH = 256K
//! RAM : ORIGIN = 0x20000000, LENGTH = 40K
//! }
//! EOF
//! ```
//!
//! 5) Optionally, set a default build targe... | Rust | 0 |
from tkinter import filedialog
from tkinter import Tk
from tkinter import Button
# https://stackoverflow.com/questions/44403566/add-multiple-extensions-in-one-filetypes-mac-tkinter-filedialog-askopenfilenam
ventana = Tk()
extension_por_defecto = ".docx"
extensiones = [("Archivos de texto", ".txt"), ("Documentos de Mic... | Python | 1 |
\n}\n"),
"@media (min-width: 1px) {\
\n .first {\
\n font-weight: 100;\
\n }\
\n .second {\
\n font-weight: 200;\
\n }\
\n}\n"
);
}
<gh_stars>100-1000
//! Conversion module
//!
//! This module is in charge of converting a Tzif fil... | Rust | 0 |
packet(self.buffer, self.buffer_len, self.recv_buffer, conn).await? };
let mut packet = UnsubackPacket::<'b, 1, MAX_PROPERTIES>::new();
if let Err(err) = packet.decode(&mut BuffReader::new(self.buffer, read)) {
Err(err)
} else {
Ok(*packet.reason_code... | Rust | 0 |
import glob
import os
from PIL import Image,ImageOps
import random
import tensorflow as tf
import time
from datetime import datetime
from os.path import join
import numpy as np
def normalize_batch(imgs):
return (imgs - np.array([0.485, 0.456, 0.406])) /np.array([0.229, 0.224, 0.225])
... | Python | 1 |
together, requiring both to succeed.
fn then<Other: Parser<Iter>>(self, other: Other) -> combinators::Then<Iter, Self, Other> {
combinators::Then::new(self, other)
}
/// Apply the provided function to the Output of this Parser.
fn transform<F: Fn(Self::Output) -> Option<T>, T>(
self,
... | Rust | 0 |
from u_2_net import my_u2net_test
from to_background import to_background
from to_background import to_standard_trimap
from m_dlib import ai_crop
import numpy as np
from PIL import Image
if __name__ == "__main__":
org_img = "..\\aiphoto\\img\\meinv.jpg"
alpha_img = "..\\aiphoto\\img\\meinv_alpha.png"
alph... | Python | 1 |
e(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bo... | Rust | 0 |
ateAxis(t,id='time')
t.units=s.getTime().units
t.designateTime()
s3.setAxis(0,t)
cdutil.setTimeBoundsMonthly(s3)
a = cdutil.JJA(s3)
if a is None:
raise RuntimeError, "data with gap returned None"
# Now gets seasonal cycle, should have JJA all missing
print 'Testing seasonal cycle on data with years of gap should ... | Python | 1 |
mut Array2<f64>,
eq_class_count: &[u32],
tolerance: f64,
thr: f64,
infrv_quant: f64,
min_spread: f64,
delta_file: &mut File,
unionfind_struct: &mut UnionFind<usize>,
) -> pg::Graph<usize, EdgeInfo, petgraph::Undirected> {
let start = Instant::now();
// create a hash of eqclasses
... | Rust | 0 |
EN access was provided after starting the session.
///
/// # Arguments
///
/// * `session_handle` - A [`SessionProxy`] object path.
/// * `options` - ?
/// * `stream` - The PipeWire stream node the coordinate is relative to
/// * `slot` - Touch slot where touch point appeared
/// * `x` -... | Rust | 0 |
cause "Timers can only be used with threads started with QThread"
QObject o;
QObject::connect(&o, &QObject::destroyed, reciever, std::forward<T>(func), Qt::QueuedConnection);
#endif
}
}}
/// Call the callback once, after a given duration.
pub fn single_shot<F>(interval: std::time::Duration, func: F... | Rust | 0 |
from importlib.metadata import entry_points
from . import caching
from ._version import __version__ # noqa: F401
from .callbacks import Callback
from .compression import available_compressions
from .core import get_fs_token_paths, open, open_files, open_local, url_to_fs
from .exceptions import FSTimeoutError
from .ma... | Python | 1 |
.path.is_ident("packable"))
}
pub(crate) fn skip_stream(stream: ParseStream) -> Result<()> {
stream.step(|cursor| {
let mut rest = *cursor;
while let Some((_, next)) = rest.token_tree() {
rest = next;
}
Ok(((), rest))
})
}
pub(crate) fn parse_kv<T: Parse>(ident: &'s... | Rust | 0 |
test_empty_menu() {
let prompt = "Choose one.";
let menu = &[];
assert_eq!(select(menu, prompt), "");
}
extern crate serde;
extern crate toml;
use serde::{de, Deserialize};
use std::fmt;
macro_rules! bad {
($toml:expr, $ty:ty, $msg:expr) => {
match toml::from_str::<$ty>($toml) {
O... | Rust | 0 |
ks parsing malformed switch with two defaults that are seperated by cases.
#[test]
fn check_switch_seperated_defaults() {
check_invalid(
r#"
let a = 10;
switch (a) {
default:
a = 20;
break;
case 10:
a = 60;
... | Rust | 0 |
#!/usr/bin/env python3
import os
import sys
import ssl
import zipfile
import hashlib
import urllib.request
import urllib.error
# Disable certificate checking because it always fails on Windows
# We verify the checksum anyway.
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NON... | Python | 1 |
import numpy as np
import cv2
from .warp_for_xray import (
estimiate_batch_transform,
transform_landmarks,
std_points_256,
)
import numpy as np
class FasterCropAlignXRay:
"""
修正到统一坐标系,统一图像大小到标准尺寸
"""
def __init__(self, size=256):
self.image_size = size
self.std_points = st... | Python | 1 |
}
if let Some(value_swap) = SwapDTO::cfrom(item, huuid) {
v_nswap.push(value_swap);
}
if let Some(value_disks) = DiskDTO::cfrom(item, huuid).as_mut() {
v_ndisks.append(value_disks);
}
if let Some(value_iostats) = IoB... | Rust | 0 |
import das_client, rrClient
import json, datetime
def today() :
return datetime.datetime.now().date()
def daysAgo(n) :
date = today()
return date - datetime.timedelta(days=n)
def day(string) :
return datetime.datetime.strptime(string, "%Y%m%d").date()
def getRunsForDate(date, minlumis=10) :
'''
... | Python | 1 |
# Time: O(n)
# Space: O(h), h is height of binary tree
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
# @param root, a tree node
# @return nothing, do it in place
def flatten(self, root):
self.flat... | Python | 1 |
fn operands(&self) -> Vec<LTerm<U, E>> {
self.0.operands()
}
}
impl<U, E> std::fmt::Display for DisequalityConstraint<U, E>
where
U: User,
E: Engine<U>,
{
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
for (u, v) in self.0.iter() {
write!(f, "{} != {},"... | Rust | 0 |
pub fn add_player(&mut self, player_idx: i32) {
for i in 0..player_idx {
let new_player = Player::new(utils::players_pos(i), i);
self.state.world.player.push(new_player);
self.state.world.keys.push(Keys::new());
}
}
pub fn add_brock(&mut self) {
let o... | Rust | 0 |
import os
import discord
from discord.ext import commands
from discord import app_commands
# 從 utils/json_utils.py 匯入
from utils.json_utils import load_json, save_json
from config.config import FORUM_CHANNELS_FILE, NCBC_DISCRIPTION, NCBC_FORUM_TAGS
class ForumConfigCog(commands.Cog):
def __init__(self, bot: comma... | Python | 1 |
_paths)
finder = list_modules.ModulesFinder(stdlib=stdlib, user_modules=user_modules)
finder.inspect()
path = os.path.join(stdlib_dir, "brython_modules.js")
output_path = path if (not args.output_path) else args.output_path
finder.make_bryt... | Python | 1 |
)]
#[strum(ascii_case_insensitive)]
enum CaseInsensitiveEnum {
NoAttr,
#[strum(ascii_case_insensitive = false)]
NoCaseInsensitive,
#[strum(ascii_case_insensitive = true)]
CaseInsensitive,
}
#[test]
fn case_insensitive_enum_no_attr() {
assert_from_str(CaseInsensitiveEnum::NoAttr, "noattr");
}
#... | Rust | 0 |
loop {
let previous = ledge;
ledge += (DEFAULT_RADIX - 1) * length * pow(DEFAULT_RADIX, length - 1);
length += 1;
if position <= ledge {
return (length - 1, position - 1 - previous);
}
}
};
... | Rust | 0 |
Pinned reference to the field
/// let _: &mut U = this.field; // Normal reference to the field
/// }
/// }
/// ```
///
/// Note that borrowing the field where `#[pin]` attribute is used multiple
/// times requires using [`.as_mut()`][`Pin::as_mut`] to avoid
/// consuming the `Pin`.
///
/// If you want to i... | Rust | 0 |
or_and_exit(&format!(
": failed to run '{:?}':\n{}\n{}\n",
command, stdout, stderr
));
}
}
pub fn create_dir_all<P: AsRef<Path>>(path: P) {
if let Err(error) = fs::create_dir_all(path.as_ref()) {
print_error_and_exit(&format!(
": failed to create '{}': {}",
... | Rust | 0 |
[37m\"\x1B[0m")
}
/// Called after each series of `write_string_fragment` and
/// `write_char_escape`. Writes a `"` to the specified writer.
#[inline]
fn end_string<W>(&mut self, writer: &mut W) -> io::Result<()>
where
W: ?Sized + io::Write,
{
writer.write_all(b"\x1... | Rust | 0 |
use libc::strcmp;
use std::ffi::CStr;
use std::ffi::VaList;
use std::fmt;
use std::ptr;
#[cfg(feature = "llvm_defs")]
use inkwell::context::Context;
#[cfg(feature = "llvm_defs")]
use inkwell::module::Module;
#[cfg(feature = "llvm_defs")]
use inkwell::AddressSpace;
use crate::{exceptions, predefined, symbols};
use un... | Rust | 0 |
Keyword(s) => match find_in_fields(fields, s) {
Some(pos) => {
let mut new_values = (**values).to_owned();
new_values[pos] = b.to_owned();
Ok(Calcit::Record(name.to_owned(), fields.to_owned(), Arc::new(new_values)))
}
None => CalcitErr::err_str(format!("invalid fiel... | Rust | 0 |
= Self::Output, Error = Self::Error> + Send>;
fn upgrade_inbound(self, socket: Negotiated<C>, _: Self::Info) -> Self::Future {
Box::new(self.handshake(socket))
}
}
impl<C> OutboundUpgrade<C> for PlainText2Config
where
C: AsyncRead + AsyncWrite + Send + 'static
{
type Output = (PeerId, PlainTe... | Rust | 0 |
!(line.rendered_height(9), 1);
}
#[test]
fn height_test_2() {
let mut line = Line::new();
line.add_text("ab c d e", SegStyle::UserMsg);
assert_eq!(line.rendered_height(1), 8);
assert_eq!(line.rendered_height(2), 4);
assert_eq!(line.rendered_height(3), 3);
ass... | Rust | 0 |
te(f"""
SELECT
i.name AS index_name,
i.is_unique,
i.is_unique_constraint,
i.is_primary_key,
i.type,
i.type_desc,
ic.is_descending_key,
c.name AS column_name
FROM
... | Python | 1 |
from direct.directnotify import DirectNotifyGlobal
from pirates.creature import DistributedCreature
from pirates.pirate import AvatarTypes
from pirates.piratesbase import PiratesGlobals
from otp.otpbase import OTPRender
class DistributedAnimal(DistributedCreature.DistributedCreature):
def __init__(self, cr):
... | Python | 1 |
ck(elif_block, true)?.unwrap());
}
}
}
if let Some(else_block) = else_br {
return Ok(self.eval_block(else_block, true)?.unwrap());
}
Ok(Type::Nil)
}
// util
fn out(&self, val: &Result<Type, (String, ErrorType)>, tok: &Token) -> Result... | Rust | 0 |
l::Plus => "+",
Symbol::Minus => "-",
Symbol::Semicolon => ";",
Symbol::Colon => ":",
Symbol::Comma => ",",
Symbol::Period => ".",
Symbol::Equals => "=",
Symbol::ParenOpen => "(",
Symbol::ParenClose => ")",
Symbo... | Rust | 0 |
;
if result == -1 {
panic!("Tcl_RegExpExecObj failed");
} else if result == 0 {
return None;
}
let mut info: tcl_regexp_info = unsafe { mem::zeroed() };
unsafe {
Tcl_RegExpGetInfo(self.re, &mut info);
let s = start as c_long + (*inf... | Rust | 0 |
&dyn IBrush,
options: DrawTextOptions,
) {
self.assert_can_draw("draw_text");
let text = text.to_wide_null();
unsafe {
let format = format.get_raw();
self.raw_rt().DrawText(
text.as_ptr(),
text.len() as u32,
f... | Rust | 0 |
import pika
import pika.exceptions
import json
from app import Product, db, app
params = pika.URLParameters("amqps://hlvufrru:fhvdfqZzT2DgfRzz7qXQZwX1oMqZyV3S@moose.rmq.cloudamqp.com/hlvufrru")
connection = pika.BlockingConnection(params)
channel = connection.channel()
channel.queue_declare(queue="main")
def callb... | Python | 1 |
|err| {
error!("{}", err);
std::process::exit(1);
});
config.operation_persister = Some(Box::new(RemotePersister));
let compiler = Compiler::new(Arc::new(config), Arc::new(common::NoopPerfLogger));
if opt.watch {
if let Err(err) = compiler.watch().await {
error!("{... | Rust | 0 |
}
}
}
impl TryFrom<&pb::NiDkgTranscript> for NiDkgTranscript {
type Error = String;
fn try_from(summary: &pb::NiDkgTranscript) -> Result<Self, Self::Error> {
Ok(Self {
dkg_id: NiDkgId::from_option_protobuf(summary.dkg_id.clone(), "NiDkgTranscript")?,
threshold: NiDkg... | Rust | 0 |
= w;
}
fn weight(&self) -> Double {
self.weight_
}
fn set_delay(&mut self, d: Double) {
self.delay_ = d;
}
fn delay(&self) -> Double {
self.delay_
}
fn set_source(&mut self, s: Index) {
self.source_ = s;
}
fn source(&self) -> Index {
... | Rust | 0 |
}
}
impl Deserializable for BlkMasterInfo {
fn read_from(&mut self, cell: &mut SliceData) -> Result<()> {
self.master.read_from(cell)
}
}
impl Serializable for BlkMasterInfo {
fn write_to(&self, cell: &mut BuilderData) -> Result<()> {
self.master.write_to(cell)
}
}
define_HashmapE!(... | Rust | 0 |
from netmiko import ConnectHandler
def connect_to_router(ip, username, password):
device = {
'device_type': 'cisco_ios_telnet',
'ip': ip,
'username': username,
'password': password,
}
return ConnectHandler(**device)
def get_rip_routes(ip, username, password):
conn = con... | Python | 1 |
"""
Web应用程序主文件
使用Flask构建Web界面
"""
from flask import Flask, render_template, jsonify, request
from flask_socketio import SocketIO, emit
import json
from datetime import datetime, date, timedelta
import logging
from typing import Dict, List
from functools import wraps
import threading
import time
import matplotlib
matpl... | Python | 1 |
},
};
}
::std::result::Result::Ok(())
}
// Compute sizes of nested messages
#[allow(unused_variables)]
fn compute_size(&self) -> u32 {
let mut my_size = 0;
if let Some(ref v) = self.snapshottableDirList.as_ref() {
let len = v.comp... | Rust | 0 |
"""
🤖 KanterMator - Mega Flemme Edition
Agent d'automatisation Google Workspace pour l'éducation
Ce package contient tous les modules nécessaires pour automatiser
la gestion des progressions pédagogiques et l'organisation Google Drive.
📍 Localisation officielle : Bureau Mac → mega-flemme/
🎯 Projet principal d'auto... | Python | 1 |
+ 4)..(header_end + 8)], seq_num);
},
Icmpv4PacketKind::TtlExpiredUdp { ipv4_header, source_port, dest_port, len, checksum } => {
buffer[0] = 11;
buffer[1] = 0;
buffer[4..8].clone_from_slice(&[0x00, 0x00, 0x00, 0x00]);
buffer[17] = 17;
let hea... | Rust | 0 |
() }
#[inline] fn from_u8(n: u8) -> Option<$T> { n.$to_ty() }
#[inline] fn from_u16(n: u16) -> Option<$T> { n.$to_ty() }
#[inline] fn from_u32(n: u32) -> Option<$T> { n.$to_ty() }
#[inline] fn from_u64(n: u64) -> Option<$T> { n.$to_ty() }
#[inline] fn from_f... | Rust | 0 |
JPG)).unwrap();
let expected = image::open("tests/gsi-seamlessphoto-z14-x14622-y6017.jpg").unwrap();
for ((_, _, a), (_, _, e)) in actual.pixels().zip(expected.pixels())
{
assert_eq!(a, e);
}
}
#[test]
fn get_dems()
{
let dem_from_png = smol::block_on(gsi::tile::get_tile_as_dem(ID_DEM_PNG, X, Y, Z, EXT_PNG)).un... | Rust | 0 |
t)
}
fn atomic_nand_and_or(&self, clear: $ty, set: $ty) {
atomic_rmw!(self.value, $ty,
"bics $0, $2\n\
orrs $0, $3",
clear, set)
}
}
};
}
ex_impl!(u32);
ex_impl!(u16);
e... | Rust | 0 |
urHours),
// FFIInterval::SixHours => Ok(Interval::SixHours),
// FFIInterval::EightHours => Ok(Interval::EightHours),
// FFIInterval::TwelveHours => Ok(Interval::TwelveHours),
// FFIInterval::OneDay => Ok(Interval::OneDay),
// FFIInterval::ThreeDays => Ok(Interval::ThreeDays),
// FFIInterval::On... | Rust | 0 |
.iter() {
//let test : &String = &res_convert_index[ residue ];
residue_3_lettars.push( res_convert_index[ residue ].to_string() );
}
residue_3_lettars
}
<reponame>mbc-git/rust
#![deny(break_with_label_and_loop)]
macro_rules! foo {
( $f:block ) => {
'_l: loop {
break '_l $f; //~ERROR
... | Rust | 0 |
errors::{EthcoreError as Error, BlockError, EthcoreResult},
header::Header,
ids::BlockId,
};
use spec::{Spec, SpecHardcodedSync};
use ethereum_types::{H256, H264, U256};
use parity_util_mem::{MallocSizeOf, MallocSizeOfOps};
use kvdb::{DBTransaction, KeyValueDB};
use parking_lot::{Mutex, RwLock};
use fastmap::H256Fas... | Rust | 0 |
ef validate_prompt_input_variables(self) -> Self:
"""Validate that prompt input variables are consistent."""
memory_keys = self.memory.memory_variables
input_key = self.input_key
if input_key in memory_keys:
msg = (
f"The input key {input_key} was also found i... | Python | 1 |
WinProbability: The parsed match probabilities.
"""
return WinProbability(
home=data.get("homeWin", 0.0),
draw=data.get("draw", 0.0),
away=data.get("awayWin", 0.0),
)
def parse_match_stats(
data: list[dict[str, any]], win_probabilities: dict[str, any]
) -> MatchStats:
... | Python | 1 |
.
Integer(usize),
/// A manual, string event.
Str(&'static str),
}
/// Types of data deployed from Beetle.
#[derive(Debug)]
pub enum EventData {
/// Nothing is happening. Often used as a transport for event data.
NoOp,
/// A key has been pressed.
KeyDown(KeyInfo, Option<Point2D<u32>>),
... | Rust | 0 |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
Pull a specified revision of chromium from SVN.
Usage: python pull-chromium.py <topsrcdir> <chromiumtree> <revision... | Python | 1 |
# zad1testy.py
from testy import *
from zad1test_spec import ALLOWED_TIME, TEST_SPEC
from copy import deepcopy
class Node:
def __init__(self):
self.val = None
self.next = None
def tab2list(t):
n = len(t)
p = None
for i in range(n-1,-1,-1):
q = Node()
q.val = t[i]
q.ne... | Python | 1 |
def _check_input_dim(self, input):
if input.dim() != 5:
raise ValueError('expected 5D input (got {}D input)'
.format(input.dim()))
super(SynchronizedBatchNorm3d, self)._check_input_dim(input)
@contextlib.contextmanager
def patch_sync_batchnorm():
import to... | Python | 1 |
if args.exclude_users is not None:
excludeUsers = []
for u in args.exclude_users.split(','):
excludeUsers.append(u.strip())
if args.limit_users is not None:
sql_excludeUsers = sql.SQL('AND anno.username NOT in %s')
else:
s... | Python | 1 |
eam }
}
/// Send a request to the forker process to create a new container
pub async fn create<'a, I: Iterator<Item = &'a Container> + Clone>(
&mut self,
config: &Config,
manifest: &Manifest,
console: Option<OwnedFd>,
containers: I,
) -> Result<Pid, Error> {
... | Rust | 0 |
import numpy as np
from PIL import Image
def f1(x,t): return 10*(np.sin(x/100+t)**3+np.sin(np.pi*x/200))
def f2(x,t): return 10*(np.cos(x/100+t)**3+np.cos(np.pi*x/200))
def s(r,f): return [1]*f+r[:(-f)] if f>0 else r[(-f):]+[1]*(-f)
img1 = [[0]*888 if m%8 in {1,2} else [0 if n%8 in {1,2} else 1 for n in range(888)] ... | Python | 1 |
hem two at a time
.tuple_windows::<(_, _)>()
// Map to a crossing type and filter out those that we don't need
.filter_map(|(pnt0, pnt1)| to_crossing_type(pnt0, pnt1, warm_side, cold_side))
// Scan the iterator and coalesce crossings into levels
.scan(None, |bottom_p: &mut Option... | Rust | 0 |
sgx_status_t::SGX_SUCCESS => match verify {
sgx_rsa_result_t::SGX_RSA_VALID => Ok(true),
_ => Ok(false),
},
_ => Err(ret),
}
}
}
///
/// rsgx_rsa3072_verify_slice verifies the input digital signature for the given data- set based on the RSA 3072 publi... | Rust | 0 |
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.co... | Python | 1 |
or_else(|| gen_cli_id(&peeraddr)),
&req.msg.env_id,
(
req.msg.cpu_num.take(),
req.msg.mem_size.take(),
req.msg.disk_size.take(),
),
&req.msg.vm_port,
req.msg.deny_outgoing.take(),
)
.c(d!())
.and_then(|_| send_ok!(req.uuid, "Success... | Rust | 0 |
impl ::protobuf::reflect::ProtobufValue for CDeviceAuth_AddAuthorizedBorrowers_Response {
fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef {
::protobuf::reflect::ReflectValueRef::Message(self)
}
}
#[derive(PartialEq,Clone,Default)]
#[cfg_attr(feature = "with-serde", derive(Serialize, Deserializ... | Rust | 0 |
class Solution:
def maxProduct(self, nums: list[int]) -> int:
# Initialize the maximum subarray product with the maximum value in nums
maxSub = max(nums)
# Initialize current minimum and maximum products to 1
currMin, currMax = 1, 1
for num in nums:
# If the curr... | Python | 1 |
from jarvis.analysis.stm.tersoff_hamann import TersoffHamannSTM
import matplotlib.pyplot as plt
import os
from jarvis.db.figshare import make_stm_from_prev_parchg
from jarvis.core.image import Image
name = os.path.join(os.path.dirname(__file__), "PARCHG")
from jarvis.core.image import Image
from io import BytesIO
de... | Python | 1 |
import os
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import classification_report, roc_curve, auc, confusion_matrix
import joblib
# Define base directory as the root of the project
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
DATA_DIR = os... | Python | 1 |
_incompatible_types(
err.kind(),
&Type::NUM,
&Type::Tuple(vec![Type::NUM; 2].into()),
);
}
#[test]
fn parametric_fn_passed_as_arg_with_recursive_requirements() {
let code = r#"
concat = |x| { |y| (x, y) };
partial = concat(3); // (U) -> (Num, U)
bogus = |fun| { |... | Rust | 0 |
or the signer language version of the disclosure that you want to retrieve, as a query parameter. The following languages are supported:
*
* - Arabic (`ar`)
* - Bulgarian (`bg`)
* - Czech (`cs`)
* - Chinese Simplified (`zh_CN`)
* - Chinese Traditional (`zh_TW`)
* - Croa... | Rust | 0 |
"""
WSGI config for myblog project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTIN... | Python | 1 |
# NOTE: mesh grid has shape: len(y) x len(x), i.e. first dim is y
x,y = np.meshgrid(xp,yp)
f = np.exp(x+y) + np.sin((x-2*y)*3)
fy,fx = np.gradient(f, yp, xp)
fhat = intgrad((fx,fy),(xp,yp),constant = 1)
# # --- 3D
# xp = np.linspace(0,1,4)
# yp = np.linspace(0,1,5)... | Python | 1 |
;
}
/// XP3 archive filter mainy used for encryption
pub struct XP3ArchiveFilter<T, F: XP3FilterMethod> {
stream: T,
hash: u32,
phantom_method: PhantomData<F>
}
impl<T, F: XP3FilterMethod> XP3ArchiveFilter<T, F> {
pub fn new(stream: T, hash: u32) -> Self {
Self {
stream, hash,... | Rust | 0 |
#
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree.
#
from pystemd.base import SDObject, overwrite_interface_method
from pystemd.dbuslib import apply_signature
from pystemd.system... | Python | 1 |
import random
from twilio.rest import Client
from django.conf import settings
TWILIO_USERNAME = "lcatejas120@gmail.com"
TWILIO_PASSWORD = "Jijo@123#Jijo@123#"
TWILIO_ACCOUNT_SID = "AC865c605dc24100a2b54ba9e1b3ca200b"
TWILIO_ACCOUNT_TOKEN = "f4bca41991c4a379336212c27d22a20f"
TWILIO_PHONE_NUMBER = "+16593992305"
def gen... | Python | 1 |
from types import ModuleType as _ModuleType
from unittest.mock import MagicMock as _MagicMock
ITTAPI_NATIVE_MODULE_NAME = 'ittapi.native'
class IttapiNativeMock(_ModuleType):
def __init__(self):
super().__init__(ITTAPI_NATIVE_MODULE_NAME)
self.attrs = {
'detach': _MagicMock(),
... | Python | 1 |
_static::lazy_static;
lazy_static! {
/// Hash tree that retains the correspondence of locale elements to code pages
pub static ref LOCALE_TO_CP_MAP: AHashMap<&'static str, TableNode> = {
let mut root = AHashMap::with_capacity(96);
let mut map_af = AHashMap::with_capacity(1);
map_af.inse... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.