text string | label_name string | labels int64 |
|---|---|---|
ssl.h>
///
/// int SSL_get_cipher_bits(const SSL *ssl, int* np);
/// ```
#[no_mangle]
pub extern "C" fn mesalink_SSL_get_cipher_bits(
ssl_ptr: *mut MESALINK_SSL,
bits_ptr: *mut c_int,
) -> c_int {
let cipher = mesalink_SSL_get_current_cipher(ssl_ptr);
let ret = mesalink_SSL_CIPHER_get_bits(cipher, bits_... | Rust | 0 |
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2025/03/22 18:15
# @Author : hiro
# @Email : hiromesh@qq.com
# @FileName: test_command_status.py
import os
import json
import time
import unittest
from agentuniverse.agent.action.tool.tool import ToolInput
from agentuniverse.agent.action.tool.common_tool... | Python | 1 |
)")
logger.info("=" * 60)
async for msg in consumer:
if shutdown_event.is_set():
break
message_count += 1
# Display message information
logger.info(f"📨 Message #{message_count}")
logger.in... | Python | 1 |
age = 14
if age >= 18:
print('you are an Adult ')
else:
print('you are not an Adult')
path = "ios"
if path == 'wed development':
print("java script")
elif path == 'ios':
print("swift")
elif path == "android":
print("kotlin")
else:
print("something eles ") | Python | 1 |
odel,
# the selected row may jump around. Try to restore the initial
# locator to ensure the previously selected commit stays selected.
rw.graphView.verticalScrollBar().setValue(initialGraphScroll)
if (jumpTo == initialLocator
and jumpTo.commit not in ... | Python | 1 |
/// An iterator over the tables that are present in both schemas. The yielded tuples should be interpreted as `(previous_table, next_table)`.
fn table_pairs(&self) -> impl Iterator<Item = (&Table, &Table)> {
self.previous.tables.iter().filter_map(move |previous_table| {
self.next
... | Rust | 0 |
Table::from_qvs20_with_schema(s.as_bytes()).unwrap_err();
assert_eq!(err_msg, Qvs20ErrorTable::ErrorInFourthRowColumnNames);
let s = "[table name]\n[String][Integer][Decimal]\n[prop1][prop2][prop3]\n[name]";
let err_msg = Table::from_qvs20_with_schema(s.as_bytes()).unwrap_err();
assert... | Rust | 0 |
n_id
if updates:
return oldb.update(
cls.TABLENAME,
where='id=$id',
vars={'id': pid},
updated=datetime.now(),
**updates,
)
return 0
@classmethod
def update_event_date(cls, pid, event_date):
... | Python | 1 |
def load_state_dict(self, state_dict: dict[str, object]) -> None:
self._eod = False
self._pipeline.load_state_dict(state_dict)
@property
@override
def num_accumulate(self) -> int:
return self._num_accumulate
def _min_num_batches(num_batches: int, gang: Gang) -> int:
all_n... | Python | 1 |
return self.xa_elem.url()
@url.setter
def url(self, url: str):
self.set_property("url", url)
def __repr__(self):
return "<" + str(type(self)) + str(self.user_name) + ">"
class XAContactsURLList(XAContactsContactInfoList):
"""A wrapper around lists of contact URLs that employs fast en... | Python | 1 |
{
"name": "Web Refresher",
"version": "18.0.1.0.0",
"author": "Compassion Switzerland, Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"website": "https://github.com/OCA/web",
"depends": ["web"],
"installable": True,
"auto_install": False,
"assets": {
"web.... | Python | 1 |
no
}
#[inline]
fn mode(&self) -> u32 {
self.mode
}
#[inline]
fn nlink(&self) -> u64 {
self.nlink
}
#[inline]
fn uid(&self) -> u32 {
self.uid
}
#[inline]
fn gid(&self) -> u32 {
self.gid
}
#[inline]
fn rdev(&self) -> u64 {
... | Rust | 0 |
-n) - x.powi(n)).abs() < epsilon);
}
assert_eq!(I32F32::from_num(1), I32F32::from_num(42).powi(0));
assert_eq!(I32F32::from_num(1), I32F32::from_num(-42).powi(0));
assert_eq!(I32F32::from_num(1), I32F32::from_num(0).powi(0));
}
fn powf_float<T: Fixed>(x: T, n: T) -> T {
... | Rust | 0 |
import json
import time
import utils
from sakurallm.sakura import translate_rpg
f = open('ManualTransFile.json', encoding='utf8')
ori_data = json.load(f)
total_lines = len(ori_data)
f = open('r/sp.json', encoding='utf8')
result = json.load(f)
result2 = {}
i = 2
for key in ori_data:
# if i > 30:
# break... | Python | 1 |
riginal_top_token])}')")
print(f"Our model (sequential) predicts: {top_token} ('{tokenizer.decode([top_token])}')")
print(f"Tokens match: {top_token == original_top_token}")
if top_token == original_top_token:
print("✅ SUCCESS! Sequential processing works correctly!")
print(" This mea... | Python | 1 |
Rendering 3d line plot failed: {}", err_val),
}
}
}
/// Render given Array as a histogram
pub fn draw_hist(&self, hst: &Array, minval: f64, maxval: f64, title: Option<String>) {
let tstr = match title {
Some(s) => s,
None => format!("Cell({},{}))", self.c... | Rust | 0 |
this = unsafe { self.to_str() };
Some(this.cmp(other))
}
}
}
impl PartialOrd<&str> for NSString<'_> {
#[inline]
fn partial_cmp(&self, other: &&str) -> Option<Ordering> {
self.partial_cmp(*other)
}
}
impl PartialOrd<NSString<'_>> for str {
#[inline]
fn partial_cmp(... | Rust | 0 |
ns results in undefined behavior.
/// # Panic
/// This function panics if:
/// * `ptr` is null
/// * `ptr` is not aligned to a slice of type `T`. This is guaranteed if it was built from a slice of type `T`.
pub(super) unsafe fn new(ptr: *const u8) -> Self {
let ptr = NonNull::new(ptr as *mut... | Rust | 0 |
e); // Drive low byte (pass-through)
nop();
nop();
nop();
lcd_wr_deassert(); // Complete write operation
}
/// Reads a parameter value. Timing is different than reading from display memory.
/// NOTE: Assumes ADDR=1 from command phase.
fn data_read_parameter() -> u32 {
dir_read();
lcd_rd_assert(); // Start read... | Rust | 0 |
(((value as u32) & 0x01) << 14);
self.w
}
}
#[doc = "Mask to determine which IRQs are enabled (active high)\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum IRQ_CONF_IRQS_MASK_A {
#[doc = "0: `0`"]
IRQ_CONF_IRQS_MASK_DEFAULT = 0,
}
impl From<IRQ_CONF_IRQS_MASK_A>... | Rust | 0 |
# (C) Copyright 2005-2021 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at... | Python | 1 |
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any
from aws_lambda_powertools.utilities.parser.envelopes.base import BaseEnvelope
from aws_lambda_powertools.utilities.parser.models import APIGatewayProxyEventV2Model
if TYPE_CHECKING:
from aws_lambda_powertools.utilities.parse... | Python | 1 |
2> for CompilerOptimizationLevel {
fn from(val: u32) -> CompilerOptimizationLevel {
match val {
0 => CompilerOptimizationLevel::O0,
1 => CompilerOptimizationLevel::O1,
2 => CompilerOptimizationLevel::O2,
3 => CompilerOptimizationLevel::O3,
4 => Com... | Rust | 0 |
sert_eq!(server_name.host(), "example.com");
}
#[test]
fn parse_dns_name_with_port() {
let server_name = <&ServerName>::try_from("ruma.io:8080").unwrap();
assert!(!server_name.is_ip_literal());
assert_eq!(server_name.host(), "ruma.io");
}
}
// Copyright 2022 <NAME>.
//
// Licens... | Rust | 0 |
import sys
sys.path.insert(0, 'src')
from pageql.pageql import PageQL, _row_hash
def setup_items(r):
r.db.execute("CREATE TABLE items(id INTEGER PRIMARY KEY, name TEXT)")
r.db.executemany("INSERT INTO items(name) VALUES (?)", [("a",), ("b",)])
def test_dump_directive_reactive_inserts():
r = PageQL(':me... | Python | 1 |
.0.start();
// connect other node need peerID, address.
// floodsub pubsub need flood control
let mut connected_nodes = vec![(lpid, addr, floodsub_ctrl)];
while !not_connected_nodes.is_empty() {
connected_nodes.shuffle(&mut rng);
not_connected_nodes.shuffle(&mut... | Rust | 0 |
stdout = capfd.readouterr().out
assert "foo" in stdout
def test_run_stage_failure_writes_subprocess_stdout_stderr_to_process_stdout_stderr(
setup_bodywork_test_project: Iterable[bool],
project_repo_connection_string: str,
bodywork_output_dir: Iterable[Path],
capfd: CaptureFixture,
):
try:
... | Python | 1 |
from .addmm_handler import ADDMMFunctionHandler
from .batch_norm_handler import BatchNormModuleHandler
from .binary_elementwise_handler import BinaryElementwiseHandler
from .bmm_handler import AddBMMFunctionHandler, BMMFunctionHandler
from .conv_handler import ConvFunctionHandler, ConvModuleHandler
from .default_reshap... | Python | 1 |
let result = new_entry_array_link.insert_entry(key, partial_hash, value);
cell.link = Some(new_entry_array_link);
cell.linked_entries += 1;
let result = result.ok().unwrap();
(u8::MAX, result.0, result.1)
}
pub fn remove(
&mut self,
drop_entry: bool,
... | Rust | 0 |
"""
API route modules for Enterprise RAG Chatbot.
""" | Python | 1 |
pub n_memory_holes: u64,
}
/// Types used when deserializing L2 execution resources related data.
pub mod execution_resources {
use serde::{Deserialize, Serialize};
/// Sometimes `builtin_instance_counter` JSON object is returned empty.
#[derive(Copy, Clone, Debug, Deseria... | Rust | 0 |
from .config.settings import onnx_runtime_config as ort_cfg
from .inference.pipeline import LPRMultiTaskPipeline
from .common.typedef import *
from os.path import join
from .config.settings import _DEFAULT_FOLDER_
from .config.configuration import initialization
initialization()
class LicensePlateCatcher(object):
... | Python | 1 |
.sandbox
.run(Path::new(&path), args.as_slice(), &keep_fds)
.context("failed to start up sandbox")?
}
ExecutableInfo::CrosPath(_, None) => {
bail!(
"digest missing for TEE app {}",
app.app_info.app_name.clone()
);
... | Rust | 0 |
Node::Leaf(_) => {
// linear split of path down to leaf
let new_node = {
let old_value = &self.leaf_ref().unwrap().value;
if *old_value == value {
// below in tree, but same value - nothing new
return;
}
let mut new_node = Self::new_leaf(key.clone(), value);
for l i... | Rust | 0 |
s imported successfully!", "success")
else:
show_notification(f"Imported {success_count}/{total_count} settings", "warning")
except Exception as e:
show_notification(f"Import failed: {str(e)}", "error")
pass
# === NOTIFICATION for Export/Import ===
"""Create widget-popup displa... | Python | 1 |
5, 115, 76, 111, 111,
107, 44, 32, 77, 111, 109, 33, 32, 78, 111, 32, 92, 110, 39, 115, 33, 107, 104, 101, 120, 97,
100, 101, 99, 105, 109, 97, 108, 26, 0, 13, 236, 175, 115, 108, 101, 97, 100, 105, 110, 103,
68, 101, 99, 105, 109, 97, 108, 80, 111, 105, 110, 116, 251, 63, 235, 194, 208, 41, 120, 159,
7... | Rust | 0 |
">=" => Ok("<="),
"like" | "not like" | "ilike" | "not ilike" => Err(ErrorCode::UnknownException(format!(
"cannot inverse the operator: {:?}",
op
))),
_ => Ok(op),
}
}
#[derive(Debug, Copy, Clone, PartialEq)]
enum StatType {
Min,
Max,
Nulls,
}
im... | Rust | 0 |
import cv2
import torch
import numpy as np
from PIL import Image
from diffusers.utils import load_image
from diffusers.models import ControlNetModel
from insightface.app import FaceAnalysis
from pipeline_stable_diffusion_xl_instantid_img2img import StableDiffusionXLInstantIDImg2ImgPipeline, draw_kps
def resize_img(i... | Python | 1 |
from .. import IconBase
class IconTrash2(IconBase):
class_name = "lucide lucide-trash-2"
svg_data = {
"attrs": {
"width": "24",
"height": "24",
"view_box": "0 0 24 24",
"fill": "none",
"stroke": "currentColor",
"stroke_width": "2",
"stroke_linecap": ... | Python | 1 |
"""
In a file called twttr.py, reimplement Setting up my twttr from Problem Set 2,
restructuring your code per the below,
wherein shorten expects a str as input and returns that same str but with all vowels (A, E, I, O, and U) omitted,
whether inputted in uppercase or lowercase.
"""
"""
if __name__ == "__main__... | Python | 1 |
"""
validadigitacao - Biblioteca para validação de digitados via OCR e comparação com JSON.
Funcionalidades:
- Extração de texto via OCR (pytesseract + Pillow)
- Conversão de PDFs para imagens (pdf2image)
- Extração de campos estruturados via regex
- Comparação detalhada de JSON com deepdiff
- Geração de relatório em ... | Python | 1 |
thonAutoBrew = { 'exe': '%s/%s/bin/python%s' % ( HBAutoFrameworkVersionPath, HBPythonAutoVersion, HBPythonAutoVersion ),
'inc': '%s/%s/include/python%s' % ( HBAutoFrameworkVersionPath, HBPythonAutoVersion, HBPythonAutoVersion ),
'lib': glob.glob( "%s/%s/lib/*.dylib" % ( ... | Python | 1 |
import random
import string
#'password_generator' function takes length, include_letters, include_digits, include_symbols as arguments
def password_generator(length, include_letters, include_digits, include_symbols):
#the 'character_domain' is set to an empty string
character_domain = ''
#it adds/app... | Python | 1 |
"""
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Given linked list -- head = [4,5,1,9], which looks like following:

Example 1:
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
E... | Python | 1 |
the Rust homepage.
//!
//! This is the [toy HTTP+TLS client] example from the [futures tutorial]
//! extended to use our resolver.
//!
//! [toy HTTP+TLS client]: https://tokio.rs/docs/getting-started/tls/
//! [futures tutorial]: https://tokio.rs/docs/getting-started/futures/
extern crate futures;
extern crate native_... | Rust | 0 |
from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hash = {}
for i in range(0, len(nums)):
num = nums[i]
# 0になる値を計算
ans = target - num
# numがhashにあれば
# 値のindexと現在のindexを返す
if nu... | Python | 1 |
": self.np_input},
fetch_list=[out],
)
np.testing.assert_allclose(
self.np_out, fetches[0], rtol=1e-10
)
# paddle.Tensor.
for param_names in self.tensor... | Python | 1 |
Type::AutomaticEventOrientation => {
ffi::FMOD_STUDIO_PARAMETER_AUTOMATIC_EVENT_ORIENTATION
}
ParameterType::AutomaticDirection => ffi::FMOD_STUDIO_PARAMETER_AUTOMATIC_DIRECTION,
ParameterType::AutomaticElevation => ffi::FMOD_STUDIO_PARAMETER_AUTOMATIC_ELEVATION,
... | Rust | 0 |
phantom_fn"]
pub trait PhantomFn<A:?Sized,R:?Sized=()> { }
impl<A:?Sized, R:?Sized, U:?Sized> PhantomFn<A,R> for U { }
#[lang = "sized"] pub trait Sized : PhantomFn<Self> {}
#[lang="copy"] pub trait Copy : PhantomFn<Self> {}
// Test to make sure that private items imported through globs remain private
// when they'r... | Rust | 0 |
r;
/// NOTE: Unsafe! This should not crash!
fn const_char_to_string(value: *const c_char) -> String {
let c_str: &CStr = unsafe { CStr::from_ptr(value) };
let str_slice: &str = c_str
.to_str()
.expect("expected null-terminated string from Cstr!");
let str_buf: String = str_slice.to_owned();... | Rust | 0 |
fn update(&mut self, parameter: &mut InstanceParameter, ctx: &mut ggez::Context) -> AnimationState {
if self.original_scale.is_none() {
self.original_scale = Some(parameter.scale);
}
let delta_time = (timer::duration_to_f64(timer::delta(ctx)) * 1_000.0) as f32;
if self.time_left > 0.0 {
self.time_left ... | Rust | 0 |
from map_pos import MOVES
companions = {}
flipflop = True
def plant_tree():
global companions
plant(Entities.Tree)
companion, pos = get_companion()
x, y = pos
while companion == Entities.Carrot or (pos in companions and companion != companions[pos]):
harvest()
plant(Entities.Tree)
companion, pos = get_compa... | Python | 1 |
from __future__ import annotations
from abc import ABC
from abc import abstractmethod
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from faz.bot.wynn.api.http_request import HttpRequest
class BaseEndpoint(ABC):
__slots__ = ("_request", "_retries", "_retry_on_exc")
def __init__(self, request: HttpR... | Python | 1 |
"https://reign.rs/connect",
post,
put,
patch,
delete,
head,
options,
trace,
get
);
let res = service
.call(
Req::connect("https://reign.rs/connect")
.body(Body::empty())
.unwrap(),
... | Rust | 0 |
e,
stringify!($pat)
),
)));
}
}
};
}
#[macro_export]
macro_rules! expect {
( $e:expr ) => {
if !$e {
return ::std::result::Result::Err(::std::boxed::Box::new(::std::io::Error::new(
::s... | Rust | 0 |
raw content using the 'url' property
# if type == 'blob':
# file_url = item['url']
# file_response = requests.get(file_url)
# file_data = file_response.content
# # Process the file content as needed
# print(f'File: {path}')
# #print(file_d... | Python | 1 |
dress: String,
}
impl TestServer {
pub async fn spawn(overrides: &[(&str, &str)]) -> Self {
let defaults = &[
("http_server.host", "127.0.0.1"),
("http_server.port", "0"),
(
"postgres.database_name",
&format!("test-{}", Uuid::new_v4()),
... | Rust | 0 |
ime,
"hh3cPortalServerIP": hh3cPortalServerIP,
"hh3cPortalStatistic": hh3cPortalStatistic,
"hh3cPortalStatAuthReq": hh3cPortalStatAuthReq,
"hh3cPortalStatAckLogout": hh3cPortalStatAckLogout,
"hh3cPortalStatNotifyLogout": hh3cPortalStatNotifyLogout,
"hh3cPortalStatChallengeTimeo... | Python | 1 |
====================================================================================
def interpolate(attr, rast, attr_idx, rast_db=None):
return dr.interpolate(attr.contiguous(), rast, attr_idx, rast_db=rast_db, diff_attrs=None if rast_db is None else 'all')
def xatlas_uvmap(ctx, mesh_v, mesh_pos_idx, resolution)... | Python | 1 |
if let Ok(s) = std::env::var("RUST_LOG") {
log.parse_filters(&s);
}
log.init();
}
use super::F;
use simba::scalar::{SubsetOf, SupersetOf};
impl<V: SubsetOf<V>, D: SubsetOf<D>> SubsetOf<F<V, D>> for F<V, D> {
fn to_superset(&self) -> F<V, D> {
F {
x: self.x.to_superset(),
... | Rust | 0 |
from loguru import logger
from src.magic_pdf.libs.MakeContentConfig import DropMode, MakeMode
from src.magic_pdf.libs.commons import join_path
from src.magic_pdf.libs.language import detect_lang
from src.magic_pdf.libs.markdown_utils import ocr_escape_special_markdown_char
from src.magic_pdf.libs.ocr_content_type impo... | Python | 1 |
// * Ndx, column 6
// * DemangledName#hash column 7 to end
// Can't use split_whitespace() here, because we need to splitn and then get the remainder of the line
// after we've split the first 7 columns by whitespace. So we write a custom closure to group mul... | Rust | 0 |
}
}
pub trait MoneyConsumer {
fn consume(self) -> USD;
}
pub struct CryptoConsumer {
currency: Box<IntoUSD>,
}
impl CryptoConsumer {
pub fn new(currency: Box<IntoUSD>) -> Self {
CryptoConsumer { currency }
}
}
impl MoneyConsumer for CryptoConsumer {
fn consume(self) -> USD {
... | Rust | 0 |
_coordinator.device.has_air_purifier_control
):
descriptions = SENSOR_DESCRIPTIONS_BATTERY
elif device_coordinator.device.has_air_purifier_control:
descriptions = SENSOR_DESCRIPTIONS_FAN
else:
continue
for description in descriptions:
# Ad... | Python | 1 |
help="Whether the candidate file requires a reranking on relevance scores",
action='store_true')
args = p.parse_args()
qrels = load_qrels(args.reference_file)
preds = load_candidates(args.candidate_file, with_scores=args.with_reranker)
all_metrics = trec_eval(qrels, pre... | Python | 1 |
if self.ahead != Some(0) {
// the block currently available is not the block
// for the current position
self.bit_packer
.decompress(position_data, self.buffer.as_mut(), num_bits);
self.ahead = Some(0);
}
let block_len = compressed_block_s... | Rust | 0 |
ernal_memory_capabilities"];
vk_ext![NV_EXTERNAL_MEMORY, 1, "VK_NV_external_memory"];
vk_ext![EXT_VALIDATION_FLAGS, 2, "VK_EXT_validation_flags"];
vk_ext![EXT_SHADER_SUBGROUP_BALLOT, 1, "VK_EXT_shader_subgroup_ballot"];
vk_ext![EXT_SH... | Rust | 0 |
# WARNING: Please don't edit this file. It was generated by Python/WinRT v0.0.0
import enum
import winrt.system
from winrt._winrt_windows_gaming_input_preview import (
HeadsetGeqGains,
GameControllerProviderInfo,
LegacyGipGameControllerProvider,
)
__all__ = [
"DeviceCommand",
"GameControllerBatte... | Python | 1 |
this module.
type WeightInfo: WeightInfo;
}
/// Stores reward pool info.
#[pallet::storage]
#[pallet::getter(fn pools)]
pub type Pools<T: Config> = StorageMap<_, Twox64Concat, T::PoolId, PoolInfo<T::Share, T::Balance>, ValueQuery>;
/// Record share amount and withdrawn reward amount for specific `AccountId`
... | Rust | 0 |
mut auio = uio {
uio_iov: 0 as *mut iovec,
uio_iovcnt: 0,
uio_offset: 0,
uio_resid: 0,
uio_segflg: UIO_USERSPACE,
uio_rw: UIO_READ,
}; /* XXX */
iov[0usize].iov_base = dbuf;
iov[0usize].iov_len = len;
auio.uio_iov = iov.as_mut_ptr();
auio.uio_iovcnt ... | Rust | 0 |
parent=> u32,
obj_num=> u32,
checksum=> u32,
}
}
impl FlirRecordDirEntry {
/// Get the data associated with this record
pub fn data<'a>(&self, segment: &'a [u8]) -> Result<&'a [u8]> {
segment
.get(self.offset as usize..(self.offset + self.length) as usize)
... | Rust | 0 |
else:
self.attention_mask = None
pos_enc_cfg = munchify(OmegaConf.to_container(cfg.positional_encoding))
pos_enc_cfg.max_seq_len = seq_len
self.decoder_pos_embedding = positional_encoding_from_cfg(pos_enc_cfg, self.cfg.feature_dim)
decoder_layer = to... | Python | 1 |
>, String> {
match CITY.deref() {
Err(rr) => Err(format!("could not read city db: {}", rr)),
Ok(db) => db.lookup(addr).map_err(|rr| format!("{}", rr)),
}
}
#[cfg(test)]
pub fn get_country(_addr: IpAddr) -> Result<Country<'static>, String> {
Err("TEST".into())
}
#[cfg(test)]
pub fn get_asn(... | Rust | 0 |
)
@app.post(f"{config.APP_API_CONTEXT_PATH}/v1/sessions/{{session_id}}/refresh", status_code=204)
async def api_session_refresh(session_id: str) -> Response:
r = db.get_session_or_none(session_id)
if r is None:
raise HTTPException(status_code=400, detail="session not found")
refresh_result = awa... | Python | 1 |
res_dict = json.load(f)
key_list = res_dict[key]
key_vector = []
index_vector = []
for record in key_list:
num_index = int(record[index])
index_vector.append(num_index)
key_vector.append(record["value"])
... | Python | 1 |
#
# 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"); you may not us... | Python | 1 |
import os
from dotenv import load_dotenv
import json
load_dotenv()
from openai import OpenAI
client = OpenAI()
import requests
def get_weather(latitude, longitude):
response = requests.get(f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}¤t=temperature_2m,wind_speed_10m&hou... | Python | 1 |
[inline(always)]
pub fn variant(&self) -> BODVBAT_STATUS_A {
match self.bits {
false => BODVBAT_STATUS_A::NOT_PENDING,
true => BODVBAT_STATUS_A::PENDING,
}
}
#[doc = "Checks if the value of the field is `NOT_PENDING`"]
#[inline(always)]
pub fn is_not_pending(&... | Rust | 0 |
>(driver: &mut D) -> Option<Self> {
Some(Self::new(driver.gen()?))
}
fn mutate<D: Driver>(&mut self, driver: &mut D) -> Option<()> {
if let Ok(mut value) = self.lock() {
value.mutate(driver)?;
return Some(());
}
*self = Self::generate(driver)?;
S... | Rust | 0 |
import argparse
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
import numpy as np
import urllib2
from urlparse import urljoin
from bs4 import BeautifulSoup
from oauth2client import client
from oauth2client import file
from oauth2client impor... | Python | 1 |
.find(|release| !release.version.is_prerelease() && !release.yanked)
.unwrap_or(&self.releases[0])
}
}
fn map_to_release(conn: &mut Client, crate_id: i32, version: semver::Version) -> Release {
let rows = conn
.query(
"SELECT build_status,
yanked,... | Rust | 0 |
}
}
pub fn heap_sort<T: cmp::PartialOrd>(arr: &mut Vec<T>) {
build_heap(arr);
for i in (0..arr.len()).rev() {
arr.swap(0, i);
heapify(arr, 0, i);
}
}
fn build_heap<T: cmp::PartialOrd>(arr: &mut Vec<T>) {
let len = arr.len();
for i in (0..len / 2).rev() {
heapify(arr, i, l... | Rust | 0 |
(
"Please keep your seed in a safe place; if you lose it, you will not be able to"
" restore your wallet."
)
wallet.storage.write()
return {"seed": seed, "wallet": wallet, "msg": msg}
def restore_wallet_from_text(
text,
*,
path,
config,
passphrase=None,
password=No... | Python | 1 |
import glob
import os
import shutil
from tests import get_device_id, get_tests_output_path, run_cli
from TTS.vocoder.configs import WavegradConfig
config_path = os.path.join(get_tests_output_path(), "test_vocoder_config.json")
output_path = os.path.join(get_tests_output_path(), "train_outputs")
config = WavegradConf... | Python | 1 |
#!/usr/bin/python
"""
ZetCode wxPython tutorial
In this code example,
we create a simple wx.ListCtrl widget.
author: Jan Bodnar
website: www.zetcode.com
last modified: July 2020
"""
import wx
data = [
('Jessica Alba', 'Pomona', '1981'),
('Sigourney Weaver', 'New York', '1949'),
('Angelina Jolie', 'Los ... | Python | 1 |
import numpy as np
import mediapipe as mp
class PoseAnalyzer:
def __init__(self):
self.mp_pose = mp.solutions.pose
def analyze_pose(self, pose_landmarks):
moves = []
if self.detect_jab(pose_landmarks):
moves.append("Jab")
if self.detect_cross(pose_landmarks)... | Python | 1 |
from sqlalchemy import Column
from sqlalchemy import create_engine
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.orm import sessionmaker
class ProxyDict:
... | Python | 1 |
nel::FUSE_FSYNC_FDATASYNC != 0
}
#[doc(hidden)]
#[deprecated(
since = "0.3.3",
note = "This method will be removed in the future version."
)]
pub async fn reply<T: ?Sized>(self, cx: &mut Context<'_, T>) -> io::Result<()>
where
T: Writer + Unpin,
{
cx.reply(()... | Rust | 0 |
YPE
}
fn complement_usage(&self, origin: vk::BufferUsageFlags) -> vk::BufferUsageFlags;
fn map_memory_if_need(&self, _device: &GsDevice, _mappable_memory: &mut MemoryMappable) -> VkResult<()> { Ok(()) }
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum BufferStorageType {}
impl BufferStorageType {... | Rust | 0 |
rmation is sent and received.
/// Disable feature `send_socket` to remove the Send + Sync bounds. Note: bevy_ggrs requires `send_socket` to be enabled.
#[cfg(feature = "send_socket")]
pub trait NonBlockingSocket<A>: Send + Sync {
/// Takes an `UdpMessage` and sends it to the given address.
fn send_to(&mut self,... | Rust | 0 |
BlastBerryOverride : replaced={rep}, added={add}")
# ⑤ AthenaLootPackages_Client_BlastBerryOverride に Hotfix
if hotfix_text:
apply_hotfix_for_table(rows_ovr, hotfix_text, {"AthenaLootPackages_Client_BlastBerryOverride", "/BlastBerryLoot/DataTables/AthenaLootPackages_Client_BlastBerryOverride"})
#... | Python | 1 |
s = np.arange(K_N_min, K_N_max+1)
fig, axs = pt.subplots(1, len(K_Ms), figsize=(8,2.5), constrained_layout=True)
for m, K_M in enumerate(K_Ms):
M = 2**K_M
rates = {
kind: np.array([
np.mean([retrieval_rate[kind].get((K_N, K_M, rep), np.nan) for rep in range(num_reps)])
for K_N i... | Python | 1 |
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Ошибка подтверждения визита: {str(e)}"
)
# ===================== ОБЩИЕ ФУНКЦИИ =====================
def _assign_queue_numbers_on_confirmation(db: Session, visit: Visit) -> tuple[Dict[str, Any], List[... | Python | 1 |
) if "value" in df_processed.columns else [],
timestamp=df_processed["timestamp"].astype(str).tolist() if "timestamp" in df_processed.columns else [],
centroid_lat=df_processed["centroid_lat"].tolist() if "centroid_lat" in df_processed.columns else [],
centroid_lon=df_pro... | Python | 1 |
# -*- encoding:utf-8 -*-
# __author__=='Gan'
# LeetCode Weekly Contest 56.
# We have two special characters. The first character can be represented by one bit 0.
# The second character can be represented by two bits (10 or 11).
# Now given a string represented by several bits. Return whether the last character must be... | Python | 1 |
_capacity(4);
connected_parts.push(0);
let degrees = mat.degrees();
while perm.len() < nb_vertices {
// find the non-visited vertex with the lowest degree
let mut min_deg = nb_vertices;
let mut min_deg_vert = 0;
for (vert, vis) in visited.iter().enumerate() {
le... | Rust | 0 |
import random
# Ler os nomes dos alunos
aluno1 = input("Digite o nome do primeiro aluno: ")
aluno2 = input("Digite o nome do segundo aluno: ")
aluno3 = input("Digite o nome do terceiro aluno: ")
aluno4 = input("Digite o nome do quarto aluno: ")
# Criar uma lista com os nomes
alunos = [aluno1, aluno2, aluno3, aluno4]
... | Python | 1 |
import colight.plot as Plot
# %% [markdown]
# For a richer example, we'll use some sample data from ancient civilizations.
# %%
civilizations = [
{
"name": "Mesopotamia",
"start": -3500,
"end": -539,
"continent": "Asia",
"peak_population": 10000000,
},
{
"... | Python | 1 |
from .Approximator import Approximator
class RK4(Approximator):
def __init__(self, ads, time=0, arguments=[], argument_strength=[], attacker=[], supporter=[], name="") -> None:
super().__init__(ads, time, arguments, argument_strength, attacker, supporter)
self.name = "RK4"
def perform_iterati... | Python | 1 |
es=timestamp.minute % INTERVAL,
seconds=timestamp.second,
microseconds=timestamp.microsecond) + timedelta(minutes=INTERVAL + 5, seconds=30)
ny_timezone = timezone('America/New_York')
while (datetime.now(ny_timezone) < rounded_up_t... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.