text string | label_name string | labels int64 |
|---|---|---|
from flask import Flask, jsonify, request
app = Flask(__name__)
# Ruta raíz para verificar si la API funciona
@app.route('/', methods=['GET'])
def home():
return "Bienvenido a la API RESTful de Kr-11"
# Ruta para obtener un mensaje de saludo
@app.route('/api/hola', methods=['GET'])
def saludo():
return jsoni... | Python | 1 |
import pytest
from helpers.client import QueryRuntimeException
from helpers.cluster import ClickHouseCluster
from helpers.test_tools import TSV
cluster = ClickHouseCluster(__file__)
instance = cluster.add_instance(
"instance", user_configs=["configs/combined_profile.xml"]
)
q = instance.query
@pytest.fixture(sc... | Python | 1 |
write!(f, " {}", c)?;
}
write!(f, " )")
}
Code::LiteralBool(v) => write!(f, "{}", if *v { "TRUE" } else { "FALSE" }),
Code::LiteralFloat(v) => write!(f, "{}", v),
Code::LiteralInteger(v) => write!(f, "{}", v),
Co... | Rust | 0 |
# 4 - Sequência de Collatz:
# Crie um programa que solicite um número ao usuário e use um
# laço while para gerar e exibir a sequência de Collatz até chegar
# ao número 1.
s = 0
ss = 0
n = float(input('Digite um numero: '))
while n > 1:
n += 1
if n % 2 == 0:
s = n + (n / 2)
print(f'{s} par')
else:
p | Python | 1 |
assert isinstance(result, dict)
# If not blocked by security validation, may fail at API level
# which is also acceptable
except Exception:
# Exception due to API failure or other issues is acceptable
# as long as no actual traversal occurs
... | Python | 1 |
"""Yahoo Finance utils directory."""
| Python | 1 |
pub const SUBLANG_CHINESE_HONGKONG: u32 = 3u32;
#[doc = "*Required features: 'Win32_System_SystemServices'*"]
pub const SUBLANG_CHINESE_MACAU: u32 = 5u32;
#[doc = "*Required features: 'Win32_System_SystemServices'*"]
pub const SUBLANG_CHINESE_SIMPLIFIED: u32 = 2u32;
#[doc = "*Required features: 'Win32_System_SystemServ... | Rust | 0 |
""Handle shutdown signals"""
logger.info(f"Received signal {signum}, shutting down watchdog")
system_watchdog.stop()
sys.exit(0)
if __name__ == "__main__":
# CLI interface
import argparse
parser = argparse.ArgumentParser(
description="System Autonomy Core - Health Watchdog"
)
... | Python | 1 |
_bytes_with_nul()),
)
.into_rust()
.map_or_else(
|e| Err(Error::from(e)),
|v| Ok(Symbol::new(caster(v.symbol))),
)
}
}
}
<gh_stars>100-1000
use super::DeferrerAux;
use crate::queue::FnOnceQueue;
use crate::{task::Task, Stakker};... | Rust | 0 |
_eq!(request.sp_timestamps, (None, Some(123456789)));
assert_eq!(request.is_read_request, true);
}
#[rstest]
fn test_prepared_request_from_request_json_for_get_request_with_two_timestamps(
request_builder: RequestBuilder,
) {
let rev_reg_id = Revocati... | Rust | 0 |
import os
import sys
import cv2
import time
from imageio import imread
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class Equirec2Cube(nn.Module):
def __init__(self, cube_dim, equ_h, FoV=90.0):
super().__init__()
self.cube_dim = cube_dim
self.equ_h =... | Python | 1 |
ConstCode::Null => { return Ok(Expr::Single(Opcode::Const(ConstCode::Null))) },
},
_ => { return Err(format!("Opcode misplaced by lexer!")) }
},
Token::Num(f) => { return Ok(Expr::Single(Opcode::Num(-f))) },
Token::Sym(s) => {
return Ok(Expr::Double(Opcode::Sym(s.clone()), Opcode::Ma... | Rust | 0 |
import django.contrib.admin.models
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("contenttypes", "__first__"),
]
operations = [
migration... | Python | 1 |
(
app.env.thumbnails,
"copying gallery thumbnails...",
"brown",
len(app.env.thumbnails),
):
source_path = pathlib.Path(app.srcdir) / path
target_path = pathlib.Path(app.outdir) / "_images" / source_path.name
try:
shutil.copy(source_path, target_pat... | Python | 1 |
assert jnp.all(jnp.isfinite(w))
warp.append(w)
warp = jnp.stack(warp, axis=-1)
# Apply the warp to update img_mat.
img_mat = jnp.clip(
jnp.matmul(a_mat, warp, precision=jax.lax.Precision.HIGHEST), 0, 1
)
corrected_img = jnp.reshape(img_mat, img.shape)
return corrected_img
class... | Python | 1 |
import torch
# Load the original checkpoint
checkpoint = torch.load('path/to/original/checkpoint/1.pth', map_location='cpu')
# Filter out all weights that contain 'vlm'
old_state_dict = checkpoint['model_state_dict']
new_state_dict = {k: v for k, v in old_state_dict.items() if 'vlm' not in k}
print(new_state_dict.k... | Python | 1 |
into LP
// let cash = Cw20Contract(cash_addr.clone());
let allow_msg = Cw20ExecuteMsg::IncreaseAllowance {
spender: pair_addr.to_string(),
amount: Uint128::new(10000),
expires: None,
};
let _ = app
.execute_contract(owner.clone(), cash_addr.clone(), &allow_msg, &[])
... | Rust | 0 |
u32 {
rhs.orig - self.orig
}
}
struct DeltaBlock {
/// Folds original -> folded.
folds: Vec<FoldPair>,
}
impl DeltaBlock {
fn create(fp: FoldPair) -> DeltaBlock {
DeltaBlock { folds: vec![fp] }
}
fn stride(&self) -> Option<u32> {
if self.folds.len() >= 2 {
... | Rust | 0 |
# Copyright 2020 Ram Rachum and collaborators.
# This program is distributed under the MIT license.
import click
import webbrowser
import pathlib
import re
import time
from typing import (Optional, Tuple, Union, Container, Hashable, Iterator, Mapping,
Iterable, Any, Dict, FrozenSet, Callable, Type,... | Python | 1 |
=[
{'label': 'year', 'value': 'year'},
{'label': 'weekday', 'value': 'weekday'},
{'label': 'category', 'value': 'category'},
],
value='year',
),
], size... | Python | 1 |
BALANCE: u32 = 8;
pub const MIDI_CTL_MSB_PAN: u32 = 10;
pub const MIDI_CTL_MSB_EXPRESSION: u32 = 11;
pub const MIDI_CTL_MSB_EFFECT1: u32 = 12;
pub const MIDI_CTL_MSB_EFFECT2: u32 = 13;
pub const MIDI_CTL_MSB_GENERAL_PURPOSE1: u32 = 16;
pub const MIDI_CTL_MSB_GENERAL_PURPOSE2: u32 = 17;
pub const MIDI_CTL_MSB_GENERAL_PU... | Rust | 0 |
(&self) -> Result<IrqWait, Error> {
let check = self.byte_time();
let mut irq = IrqWait {
line: None,
rf: self,
irq: Irq::SyncAddressMatch,
high: true,
check,
};
if let Some(line) = &self.dios[0] {
if self.mode == Mo... | Rust | 0 |
ants(&self) -> &Vec<Status> {
&self.descendants
}
}
#![cfg_attr(not(feature = "std"), no_std)]
//! API to use files as a lock. Supports non-std crates by disabling feature
//! `std`.
//!
//! # Types
//! Currently, only one type is provided: [`LockFile`]. It does not destroy the
//! file after closed. Locks... | Rust | 0 |
supported dispatchable functions are documented as part of the [`Call`] enum.
//!
//! ## Overview
//!
//! The timestamp module allows the validators to set and validate a timestamp with each block.
//!
//! It uses inherents for timestamp data, which is provided by the block author and validated/verified by other valida... | Rust | 0 |
sending packets: {e}")
break # Exit loop on any socket error
# 🚀 Function to start a UDP flood attack
def start_udp_flood(user_id, target_ip, target_port):
stop_flag = multiprocessing.Event()
processes = []
for _ in range(min(2, multiprocessing.cpu_count())):
process = multiprocessi... | Python | 1 |
xpected, got list')
# main def main():
# my_global_dict Exception: TypeError('module, class, method, function, traceback, frame, or code object was expected, got dict')
# my_global_str Exception: TypeError('module, class, method, function, traceback... | Python | 1 |
'{vessel_id}' 体积: {liquid_volume}mL (数值格式)")
return float(liquid_volume)
# 检查其他可能的体积字段
volume_keys = ['current_volume', 'total_volume', 'volume']
for key in volume_keys:
if key in vessel_data:
try:
volume = float(vessel_data[key])
if volu... | Python | 1 |
asset.mesh_dir = mesh_dir
tasks.append(asset.download())
try:
await asyncio.gather(*tasks)
LOGGER.info("All assets downloaded successfully.")
except Exception as e:
LOGGER.error(f"Error downloading assets: {e}")
def add_custom_element(self... | Python | 1 |
and not line_strip.startswith('%%'):
current_section = line_strip[1:].strip()
elif line_strip.startswith('%%'):
current_param_type = line_strip[2:].strip()
elif '=' in line_strip and line_strip.split('=')[0].strip() == param_name:
... | Python | 1 |
derive(Debug, PartialEq)]
pub enum Mod<U = ()> {
Module {
body: Vec<Stmt<U>>,
type_ignores: Vec<TypeIgnore>,
},
Interactive {
body: Vec<Stmt<U>>,
},
Expression {
body: Box<Expr<U>>,
},
FunctionType {
argtypes: Vec<Expr<U>>,
returns: Box<Expr<U>... | Rust | 0 |
"""
Utility functions
"""
import os
import numpy as np
from PIL import Image
def load_dict(lang):
"""Read the dictionnary file and returns all words in it.
"""
lang_dict = []
with open(
os.path.join(os.path.dirname(__file__), "dicts", lang + ".txt"),
"r",
encoding="utf8",
... | Python | 1 |
from langchain_core.tools import tool
import utils
@tool
def list_available_agents():
"""List the name of available agents along with the type of task it's designed to be assigned."""
return utils.all_agents() | Python | 1 |
for i in range(100):
if i%2 == 0:
continue
print(i)
else:
print(i)
| Python | 1 |
if cam < halved || cam == 1 {
0
} else {
let calced = cam - halved;
if calced <= 1 {
0
} else {
calced - 1
}
}
}
pub struct MainState {
screen: Box<dyn Screen>,
font: Font,
default_style: FontStyle,
_rendered_pattern_reminder:... | Rust | 0 |
import pytest
import scanpy as sc
import scib
def test_mouse(adata_paul15):
assert "S_score" not in adata_paul15.obs.columns
assert "G2M_score" not in adata_paul15.obs.columns
assert "phase" not in adata_paul15.obs.columns
scib.pp.score_cell_cycle(
adata_paul15,
organism="mouse",
... | Python | 1 |
user_column = self.schema.user_column,
balance_column = self.schema.balance_column,
);
let params = params! {
"user" => user,
"balance" => balance,
};
log::trace!("insert_balance: {} {:?}", query, params);
Ok(tx.drop_exec(query, ... | Rust | 0 |
rate::Reg<u32, _AFEC_LCDR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _AFEC_LCDR;
#[doc = "`read()` method returns [afec_lcdr::R](afec_lcdr::R) reader structure"]
impl crate::Readable for AFEC_LCDR {}
#[doc = "AFEC Last Converted Data Register"]
pub mod afec_lcdr;
#[doc = "AFEC Interrupt Enable Register\n\nThis ... | Rust | 0 |
# zigtorch/native.py
import ctypes
import numpy as np
import os
# Load the shared library
_lib_path = os.path.join(os.path.dirname(__file__), '../zig-out/lib/libzigtorch.so')
_lib = ctypes.CDLL(_lib_path)
# Define function signatures
_lib.addMatricesFloat.argtypes = [
ctypes.POINTER(ctypes.c_float),
ctypes.PO... | Python | 1 |
ith_id(ThreadId::current())
}
/// Accesses the entry for the current thread with a given cached ID.
/// Repeated calls with cached IDs should be faster than reloading the ID
/// everytime. No initialization is performed.
pub fn get_with_id(&self, id: ThreadId) -> Option<&T> {
let mut table ... | Rust | 0 |
fn map_hor_vert_line(&mut self, a: &Point, b: &Point) {
let d_x = b.0 - a.0;
let d_y = b.1 - a.1;
if d_x != 0 {
let is_neg = d_x.is_negative();
for d_x in 0..=d_x.abs() {
let x = if is_neg { a.0 - d_x } else { a.0 + d_x };
self[a.1 as... | Rust | 0 |
rated %i of 4000 points in %f seconds" % ( scale, len( p["P"].data ), elapsed ) )
# Eventually, it is better to throw an exception than to consume unbounded amounts of time and memory
m = uvScaledPlane( 0.000003 )
with self.assertRaisesRegex( RuntimeError, "MeshAlgo::distributePoints : Cannot generate more than ... | Python | 1 |
# is me ye hota hy ke hm ek error de dety hen custom ke agr esa hwa tw tm erro de dena
a = int(input("enter your number : "))
b = int(input("enter your number : "))
if (b == 0):
raise ZeroDivisionError("Hey you cant divide by zero in python")
else:
print(f"the divide is {a/b}") | Python | 1 |
uct Helper {
pub now: Timestamp,
pub first_expected_data: challenge::Data,
pub second_expected_data: challenge::Data,
pub challenge_expiration: Duration,
pub zero_path_id: Id,
pub first_path_id: Id,
pub second_path_id: Id,
pub manager: ServerManager,
}
<filename>src/lib.rs
//! A crate wh... | Rust | 0 |
import pygame
import sys
pygame.init()
blanco = (255, 255, 255)
negro = (0, 0, 0)
pantalla_ancho = 800
pantalla_alto = 600
velocidad = 3
velocidad_x = 2
velocidad_y = 2
pantalla = pygame.display.set_mode((pantalla_ancho, pantalla_alto))
pygame.display.set_caption("Aterrizaje de vuelos")
avion = pygame.image.load(... | Python | 1 |
Firm,
#[serde(rename = "VOTINGRIGHTS_75TO100PERCENT_AS_FIRM")]
VotingRights75To100AsFirm,
#[serde(rename = "RIGHTTOAPPOINTANDREMOVEMEMBERS")]
RightToAppointAndRemoveMembers,
#[serde(rename = "RIGHTTOAPPOINTANDREMOVEMEMBERS_AS_TRUST")]
RightToAppointAndRemoveMembersAsTrust,
#[serde(rename = "... | Rust | 0 |
import asyncio
from pathlib import Path
from http.cookiejar import MozillaCookieJar
from loguru import logger
from bs4 import BeautifulSoup
from aiohttp import ClientSession, CookieJar
src_dir = Path(__file__).parent.absolute()
cookie_path = src_dir.joinpath("repo.e-hentai.org_cookies.txt")
groups_txt = src_dir.joinp... | Python | 1 |
# Copyright 2018 The Texar Authors. All Rights Reserved.
#
# 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 ... | Python | 1 |
self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _FLASH_BOOTCFG_ENW<'a> {
w: &'a mut W,
}
impl<'a> _FLASH_BOOTCFG_ENW<'a> {
#[doc = r"Sets the field ... | Rust | 0 |
Set):
queryset = ClusterType.objects.all()
serializer_class = ClusterTypeSerializer
class BaseObjectClusterViewSet(RalphAPIViewSet):
queryset = BaseObjectCluster.objects.all()
serializer_class = BaseObjectClusterSerializer
class ClusterFilterSet(NetworkableObjectFilters):
class Meta(NetworkableO... | Python | 1 |
rs']:
try:
ioc_by_conn = next(
(x for x in self.__iocs_by_conn
if ioc['type'] in x['ioc_type']),
None)
if ioc_by_conn:
ioc_by_conn['pipeline'].srem(
ioc['indicator'],
... | Python | 1 |
#Arithmatic : +,-,/,*,%,**,//
# a = 10
# b = 20
# print(a+b)
# print("x"+"y")
# print(str(a)+"x")
# print(11%2)
# print(10**3)
# print(45//2)
# logical
# print(True and True)
# print(True and False)
# print(False and True)
# print(False and False)
# print(True or True)
# print(True or False)
# print(False or T... | Python | 1 |
import ldap
from getpass import getpass
# Create LDAPObject instance
l = ldap.initialize('ldap://localhost:1389',trace_level=1)
print('Password:')
cred = getpass()
try:
# Set LDAP protocol version used
l.set_option(ldap.OPT_PROTOCOL_VERSION,3)
# Try a bind to provoke failure if protocol version is not suppor... | Python | 1 |
,
// Todo: The nested list unpack looks like a bug somewhere.
// Likely join code mistakenly repacks a list into a list of PrismaValue somewhere in the core.
ScalarCondition::In(vals) => match vals.split_first() {
// List is list of lists, we need to flatten.
Some((... | Rust | 0 |
# Copyright (C) 2012 Robert Lanfear and Brett Calcott
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This program... | Python | 1 |
}{}{}",
"███".bright_red(),
"███".bright_yellow(),
"███".bright_green(),
"███".bright_cyan(),
"███".bright_blue(),
"███".bright_magenta(),
"███".bright_black(),
"███".bright_white()
));
info.push(format!(
" {}{}{}{}{}{}{}{}",
"███... | Rust | 0 |
;
}
}
}
/// The Chart object represents an Excel chart. It provides functions for adding data series to the chart and for configuring the chart.
///
/// A Chart object isn't created directly. Instead a chart is created by calling the Workbook.add_chart() function from a Workbook object. For example:... | Rust | 0 |
df_50 = data[data.site_id == site_id]['volume_50'].apply(
lambda x: all_distr_dict[distr].cdf(x, **distr_args))
#Get site_cdf_10 and site_cdf_90 based on proportions
#Get min and max values for site_id volume
max_site = min_max_site_id.loc[min_max_site_id.index == site_id, 'max']
... | Python | 1 |
let error = parse_error(dml);
error.assert_are(&[
DatamodelError::new_validation_error(
"The type `Unsupported(\"Text\")` you specified in the type definition for the field `text` is supported as a native type by Prisma. Please use the native type notation `String @pg.Text` for full support."... | Rust | 0 |
Error::new(
io::ErrorKind::NotFound,
format!("group {}: not found", g),
))?;
Some(group.gid())
},
None => ugid,
};
// lookup auxilary groups if specified separately.
let gids = match groups {
Some(groups) => {
let mu... | Rust | 0 |
al BDD: {}\nNot eq:\nGot: {}\nExpected: {}",
man.print_bdd(r2),
man.print_bdd(res),
man.print_bdd(expected)
);
}
#[test]
fn wmc_test_2() {
let mut man = BddManager::new_default_order(4);
let x = man.var(VarLabel::new(0), true);
let y = man.var(VarLabel::new(1), true);
let f1... | Rust | 0 |
parser.add_argument('-d', '--dest',type=str, default='output/cropped')
parser.add_argument('-s','--size',type=int, default=416)
parser.add_argument('-i','--img_folder',type=str, default='/mnt/d/data/VOC')
parser.add_argument('-r','--resize_type',type=str, default=RESIZE_METHOD_BILINEAR,
... | Python | 1 |
indent)
for fr, to, direction in self.edges:
if direction == Direction.OUT:
fr, to, direction = to, fr, Direction.IN
caller_name = self.get_name(fr)
callee_name = self.get_name(to)
fp.write(f"{caller_name} {self.mermaid_dir... | Python | 1 |
ht
// be the basis for a good serial-port-free `print!` implementation.
/* // We can't use any of the `print*!` macros because `std` depends on this crate.
// Instead, try using the semihosting interface to access the host's `stderr` or
// `stdout`.
// TODO: B... | Rust | 0 |
, sender.channel_sequence_number(receiver.account()).await?);
assert_eq!(1, receiver.channel_sequence_number(sender.account()).await?);
let _ = common::transfer(sender.clone(), receiver.clone(), 300).await?;
assert_eq!(2, sender.channel_sequence_number(receiver.account()).await?);
assert_eq!(2, receive... | Rust | 0 |
func_list = [event_handle, event_handle, event_handle_final]
i = 0
def lone_function() -> bool:
global i
i += 1
if i < 3:
return event_handle()
return event_handle_final()
exit_event_handler = None
if args.exit_event_type == "function-list":
exit_event_handler = func_list
elif args.e... | Python | 1 |
iters {
return FractalPoint {
iterations: i,
re: x,
im: y
}
}
let xy = x * y;
x = x2 - y2;
y = 2.0 * xy;
i += 1;
x += self.p_re;
y += self.p_i... | Rust | 0 |
# Copyright (C) 2018-2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from openvino.tools.mo.ops.Cast import Cast
from openvino.tools.mo.ops.cumsum import CumSum
from openvino.tools.mo.front.common.partial_infer.utils import int64_array
from openvino.tools.mo.front.common.replacement import FrontReplacemen... | Python | 1 |
uper::*;
use crate::common::configuration;
const SERVER_RETRY_WAIT: Duration = Duration::from_secs(1);
const TIMEOUT: Duration = Duration::from_secs(60);
pub struct ServerBootstrap {
pub server: JormungandrProcess,
pub config: JormungandrParams,
pub mock_port: u16,
}
pu... | Rust | 0 |
# Reading Entire Binary File:
with open('binaryfile.bin', 'rb') as file:
content = file.read()
print(content)
# Reading Binary File in Chunks:
chunk_size = 1024
with open('binaryfile.bin', 'rb') as file:
while True:
chunk = file.read(chunk_size)
if not chunk:
break
print... | Python | 1 |
str
/// ```
/// use fs_pro::File
///
/// let file = File::new("my_file.txt").unwrap();
/// assert_eq!(file.extension().unwrap(), "txt");
/// ```
pub fn extension(&self) -> error::Result<&str> {
path_stuff::extension(self.path.as_path())
}
/// parses the file path and returns fs_pro::ParsedPathFile... | Rust | 0 |
losses: 0,
points: 0,
}
}
}
pub fn tally(input: &str) -> String {
let mut result = String::from("Team | MP | W | D | L | P");
if input.is_empty() {
return result;
}
result.push('\n');
let mut stat_map: HashMap<String, Stats... | Rust | 0 |
: self.on_destroy,
}
# Register the Window class.
wc = WNDCLASS()
hinst = wc.hInstance = GetModuleHandle(None)
wc.lpszClassName = "PythonTaskbarDemo"
wc.lpfnWndProc = message_map # could also specify a wndproc.
class_atom = RegisterClass(wc)
# Create the ... | Python | 1 |
from setuptools import setup, find_packages
from versioneer import find_version
with open("README.md", "r", encoding="utf8") as fh:
long_description = fh.read()
with open('requirements.txt') as req:
require = req.readlines()
install_requires = [r.strip() for r in require]
setup(
name='hydrobr',
descr... | Python | 1 |
er}에서 유사도로 선택된 파일:")
for filename, similarity in similar_files:
logging.debug(f"{filename}: {similarity}")
for filename, similarity in similar_files:
if filename not in embeddings:
logging.warning(f"File {filename} not found in embeddings. Skipping.")
... | Python | 1 |
ume_init()).expect("undefined out_duration"),
out_sample_position.assume_init(),
)
}
}
}
<filename>croaring/src/bitmap/iter.rs
use std::iter::{FromIterator, IntoIterator};
use std::marker::PhantomData;
use super::Bitmap;
#[derive(Clone)]
pub struct BitmapIterator<'a> {
iter... | Rust | 0 |
ts_everything_but_modules(self):
items = [
name
for name, value in vars(argparse).items()
if not name.startswith("_")
if not inspect.ismodule(value)
]
self.assertEqual(sorted(items), sorted(argparse.__all__))
def test_main():
# silence warning... | Python | 1 |
except Exception as e:
if isinstance(e, TencentCloudSDKException):
raise
else:
raise TencentCloudSDKException(type(e).__name__, str(e))
def ModifyRealtimeLogDeliveryTask(self, request):
"""通过本接口修改实时日志投递任务配置。本接口有如下限制:<li>不支持修改实时日志投递任务目的地类型(TaskType);... | Python | 1 |
ING_COUNT)
.map(|ring_index| {
let power: u32 = 1 << (2 * u32::from(ring_index));
[
RistrettoPoint::identity(),
Ristretto::mul_generator(&Scalar25519::from(power)),
Ristretto::mul_generator(&Scalar25519::from(power *... | Rust | 0 |
"::",
stringify!(SpinSpeed)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<ovrLayerLoadingIcon2_>())).SpinScale as *const _ as usize },
44usize,
concat!(
"Offset of field: ",
stringify!(ovrLayerLoadingIcon2_),
"::",
st... | Rust | 0 |
import disnake
from disnake import Button, ButtonStyle
from disnake.ext import commands
from disnake.utils import get
import asyncio
# ALSO YOU CAN USE / COMMANDS IT SO EASY, can swap @bot.command() -> @bot.slash_command()
intents = disnake.Intents.default()
intents.members = True
intents.message_content = True
bot... | Python | 1 |
][0], # next value
),
)
if "final_info" in info:
for info_item in info["final_info"]:
if info_item is not None:
logger.info(f"| total_return={info_item['total_return']:.4f}, total_profit = {info_item['total_profit']:.4... | Python | 1 |
# Import libraries
from as5048b import as5048b
import time
import socket
host, port = "192.168.1.12", 25001
# Create instances of as5048b class
encoder_local_z1 = as5048b(282.78, address=0x41) # Encoder for the first local Z-axis (yaw)
encoder_local_x = as5048b(66.42, address=0x40) # Encoder for local X-axis (rol... | Python | 1 |
##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2012-2015 Uwe Hermann <uwe@hermann-uwe.de>
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of t... | Python | 1 |
import argparse
import pandas as pd
import json
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--p_in", nargs="+", help="perplexity jsonls to evaluate")
parser.add_argument("--a_in", nargs="+", help="automatic measure jsonls to evaluate")
parser.add_argument("--out... | Python | 1 |
eys.send('GalaxyMapOpen')
# Wait for map to load
# if not self.status_parser.wait_for_gui_focus(GuiFocusGalaxyMap):
# logger.debug("goto_galaxy_map: Galaxy map did not open.")
# TODO - check this to OCR check
#sleep(2)
# Scale the regions bas... | Python | 1 |
gma rs java_package_name(be.abyx.aurora)
// We don't need very high precision floating points
#pragma rs_fp_relaxed
// Center position of the circle
int centerX = 0;
int centerY = 0;
// Radius of the circle
int radius = 0;
// Destination colour of the background can be set here.
float destinationR;
float destination... | Rust | 0 |
data length (in bytes, MUST be multiple of 8)."]
pub fn br_des_tab_cbcenc_run(
ctx: *const br_des_tab_cbcenc_keys,
iv: *mut cty::c_void,
data: *mut cty::c_void,
len: usize,
);
}
extern "C" {
#[doc = " \\brief CBC decryption with DES (`des_tab` implementation)."]
#[doc... | Rust | 0 |
= MAX_TURN_DEGREE
if track_dir == 0:
if max_orange_area >= LINE_THRESH:
track_dir = 1
turning = True
elif max_blue_area >= LINE_THRESH:
track_dir = -1
turning = True
elif track_dir == 1:
if max_orange_area >= LINE_THRESH:
turn... | Python | 1 |
The background themes that the emote is available in.
pub theme_mode: Vec<types::EmoteThemeMode>,
}
impl Emote {
/// Create an emote builder for this emote.
///
/// # Examples
///
/// ```rust, no_run
/// use twitch_api2::helix::{self, chat::get_channel_emotes};
/// # use twitch_api2::c... | Rust | 0 |
ive(Debug, Copy, Clone)]
pub struct memp_desc {
#[doc = " Textual description"]
pub desc: *const ::std::os::raw::c_char,
#[doc = " Element size"]
pub size: u16_t,
#[doc = " Number of elements"]
pub num: u16_t,
#[doc = " Base address"]
pub base: *mut u8_t,
#[doc = " First free element... | Rust | 0 |
to_address: String,
amount: f64,
) -> Result<NodeResponse<Option<String>>, Error> {
let rq = self.get_request_builder();
rq.json(&Request::from((
String::from("sendfrom"),
Some(json!(vec![
Value::from(account.clone()),
Value::from(to_a... | Rust | 0 |
> None:
"""Displays the menu options"""
print("1. Start a new session")
print("2. Exit")
@staticmethod
def is_playing_again() -> bool:
"""Asks the player to play again or exit the game"""
while True:
UI.ui_menu()
choice = input(">>> ")
... | Python | 1 |
from pwn import * # Import pwntools
####################
#### CONNECTION ####
####################
LOCAL = True
REMOTETTCP = False
REMOTESSH = False
GDB = False
local_bin = "./vuln"
remote_bin = "~/vuln" #For ssh
libc = ELF("/lib/x86_64-linux-gnu/libc.so.6") #Set library path when know it
if LOCAL:
p = process(... | Python | 1 |
import os
import json
from PIL import Image
import streamlit_authenticator as stauth
import numpy as np
import tensorflow as tf
import streamlit as st
import time
import yaml
from yaml.loader import SafeLoader
from langchain_core.prompts import ChatPromptTemplate
from langchain_groq import ChatGroq
working_dir = os.p... | Python | 1 |
numba__scope_dict = eval(the_cmd[the_cmd.find('OD'):])
except Exception as err:
print('-------------------')
print('Decypher for NumbaScopeDict has failed. Will use the default dict.')
numba__scope_dict = OD([
(r'Speed [rpm]', ( 'ACM.omega_r_mec... | Python | 1 |
):
return self.get_perm('VIEW')
@property
def edit_id_perm(self):
return self.get_perm('EDIT_ID')
@property
def edit_title_perm(self):
return self.get_perm('EDIT_TITLE')
@property
def edit_acl_perm(self):
return self.get_perm('EDIT_ACL')
@property
def ... | Python | 1 |
def solve(grid):
h, w = len(grid), len(grid[0])
bgs = sorted({grid[r][c] for r in range(h) for c in range(w) if grid[r][c] != 2})
bg0, bg1 = bgs[0], bgs[1]
reg_min = {bg0: w, bg1: w}
reg_max = {bg0: -1, bg1: -1}
for r in range(h):
for c in range(w):
v = grid[r][c]
... | Python | 1 |
kelihood=lik, X=X, Y=Y, Z=Z)
# model = bayesnewton.models.SparseVariationalQuasiNewtonGP(kernel=kern, likelihood=lik, X=X, Y=Y, Z=Z)
lr_adam = 0.1
lr_newton = 0.3
iters = 300
opt_hypers = objax.optimizer.Adam(model.vars())
energy = objax.GradValues(model.energy, model.vars())
unscented_transform = bayesnewton.cubatur... | Python | 1 |
atetime(2008, 1, 1): datetime(2007, 12, 31),
datetime(2008, 1, 4): datetime(2008, 1, 3),
datetime(2008, 1, 5): datetime(2008, 1, 4),
datetime(2008, 1, 6): datetime(2008, 1, 4),
datetime(2008, 1, 7): datetime(2008, 1, 4),
datetime(2008, 1, 8... | Python | 1 |
c,
"timestamp_decode_sequential",
&LARGER_BATCH_SIZES,
|batch_size| {
let decoded: Vec<i64> = (1..batch_size).map(convert_from_usize).collect();
let mut encoded = vec![];
influxdb_tsm::encoders::timestamp::encode(&decoded, &mut encoded).unwrap();
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.