text string | label_name string | labels int64 |
|---|---|---|
"singleton";
pub trait XRead {
fn read_sorted(&self) -> Result<Vec<(XReadEntryId, StreamInput)>, StreamReadErr>;
fn ack_req_sync(&self, ids: &[XReadEntryId]) -> Result<(), StreamAckErr>;
fn ack_prov_hist(&self, ids: &[XReadEntryId]) -> Result<(), StreamAckErr>;
fn ack_game_states(&self, ids: &[XReadEn... | Rust | 0 |
import yaml
import os
from typing import Dict, Any
def load_yaml(file_path: str) -> Dict[str, Any]:
"""Load YAML configuration file."""
with open(file_path, 'r') as f:
return yaml.safe_load(f)
def load_model_config(config_path: str) -> Dict[str, Any]:
"""Load model configuration from file."""
... | Python | 1 |
#[serde(rename = "SHA-224")]
Sha2_224,
#[serde(rename = "SHA-256")]
Sha2_256,
#[serde(rename = "SHA-384")]
Sha2_384,
#[serde(rename = "SHA-512")]
Sha2_512,
#[serde(rename = "SHA-512/224")]
Sha2_512_224,
#[serde(rename = "SHA-512/256")]
Sha2_512_256,
#[serde(renam... | Rust | 0 |
BACK_END_MAX_VERTEX_COUNT {
g.tri_list_uv(draw_state, &[1.0, 1.0, 1.0, opacity], tex, |f| {
f(
&pos[0..BACK_END_MAX_VERTEX_COUNT],
&uv[0..BACK_END_MAX_VERTEX_COUNT],
);
});
pos = &pos[BACK_END_MAX_VERTEX_COUNT.... | Rust | 0 |
("deployment_completed", {
"target_version": self.target_version,
"deployment_duration": (datetime.now() - self.deployment_start_time).total_seconds(),
})
except Exception as e:
logger.error(f"完成部署時發生錯誤: {e}")
def _send_deployment_not... | Python | 1 |
(Debug, Copy, Clone, TypeUuid, Component, Reflect, AsStd140, PartialEq)]
#[uuid = "817a079c-3acf-484a-b4b3-a6254c114200"]
#[cfg_attr(feature = "dev", derive(bevy_inspector_egui::Inspectable))]
pub struct WavesMaterial {
/// 振幅(控制波浪顶端和底端的高度)
///
/// 曲线最高点与最低点的差值,表现为曲线的整体高度
pub amplitude: f32,
/// 角速度... | Rust | 0 |
eak
}
println!("{:?}", dt.subsec_nanos() as f32 / 1_000_000f32);
Ok(())
}
fn draw(&mut self, ctx: &mut Context) -> GameResult<()> {
graphics::clear(ctx);
for body in &self.scene.bodies {
match &body.shape {
&Shape::Circle { radius } => {
... | Rust | 0 |
import os
import requests
import flask
import functions_framework
from urllib.parse import urlparse, parse_qs
from contextlib import suppress
from bs4 import BeautifulSoup
from youtube_transcript_api import YouTubeTranscriptApi
from langchain_openai.llms import OpenAI
from dotenv import load_dotenv
load_dotenv()
de... | Python | 1 |
),
MagicMock(**{"__getitem__.return_value": DefaultAggregation()}),
)
with self.assertRaises(AssertionError):
with self.assertLogs(level=WARNING):
metric_reader_storage.consume_measurement(
Measurement(1, observable_counter_0)
... | Python | 1 |
unnamed,
ref config,
..
} => {
path.visit(visitor);
for arg in unnamed {
arg.visit(visitor);
}
for conf in config {
conf.visit(visitor);
}
}
... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2004 - 2010 Detlev Offenbach <detlev@die-offenbachs.de>
#
# This is the install script for eric4's translation files.
"""
Installation script for the eric4 IDE translation files.
"""
import sys
import os
import shutil
import glob
from PyQt4.QtCore import... | Python | 1 |
import random
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4',... | Python | 1 |
)),
InnerError::ExtraToken { token } => ParseError::ExtraToken(token),
// Inner field is a unit-like enum `LexicalError::StringError` with no useful info
InnerError::User { .. } => ParseError::Other,
InnerError::UnrecognizedToken { token, expected } => {
m... | Rust | 0 |
import numpy as np
from libertem.masks import _make_circular_mask
from libertem.udf import UDF
class FEMUDF(UDF):
'''
Perform Fluctuation EM :cite:`Gibson1997`
This UDF calculates the standard deviation within a ring around the zero order diffraction peak.
Parameters
----------
center: Tup... | Python | 1 |
}
}
#[doc = "Reader of field `STOPBITS`"]
pub type STOPBITS_R = crate::R<u8, STOPBITS_A>;
impl STOPBITS_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> STOPBITS_A {
match self.bits {
0 => STOPBITS_A::HALF,
1 => STOPBITS_A::ONE,
... | Rust | 0 |
elib::error::Error>(())
/// ```
pub fn parse_u32_range(s: &str) -> Result<Vec<u32>> {
let split: Vec<&str> = s.split('-').collect();
if split.len() == 1 {
let val = parse_u32(s)?;
let vec = vec![val; 1];
Ok(vec) // Into Vec containing a single u32
} else if split.len() == 2 {
let range: Vec<u32> = (parse_u3... | Rust | 0 |
(duration: &Duration) -> String {
let mut sec = duration.as_secs();
let hour = sec / 3600;
sec -= hour * 3600;
let min = sec / 60;
sec -= min * 60;
if hour != 0 {
format!("{:02}:{:02}:{:02}", hour, min, sec)
} else {
format!("{:02}:{:02}", min, sec)
}
}
const PROGRESS_B... | Rust | 0 |
Error, lambda: ground_roots(eq))
raises(PolynomialError, lambda: nth_power_roots_poly(eq, 2))
def test_issue_19360():
f = 2*x**2 - 2*sqrt(2)*x*y + y**2
assert factor(f, extension=sqrt(2)) == 2*(x - (sqrt(2)*y/2))**2
f = -I*t*x - t*y + x*z - I*y*z
assert factor(f, extension=I) == (x - I*y)*(-I*t +... | Python | 1 |
import os
import time
#import wandb
from tqdm import tqdm, trange
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.utils import negative_sampling
from torch_geometric.loader import GraphSAINTRandomWalkSampler
from .base import Trainer
device = torch.device('c... | Python | 1 |
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
res1 = set()
res2 = set()
for num in nums1:
res1.add(num)
for num in nums2:
if num in res1:
res2.add(num)
return list(res2)
| Python | 1 |
{
origin: first_origin,
size: (width, 1),
inner_margin: inner_margin,
elems: elems,
}
}
pub fn align_elems(&mut self) {
let (x, y) = self.origin();
let mut current_x = x;
for elem in self.elems.iter_mut() {
elem.set_or... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#导入包
from re import T
from turtle import pu
import rospy
from geometry_msgs.msg import Twist
import sys,select,termios,tty
#第一步:获取一个键盘值
def get_one_key():
tty.setraw(sys.stdin.fileno()) #通过raw标准化输入
rlist, _, _ = select.select([sys.stdin], [], [], 0.1)
if r... | Python | 1 |
default_pd_lines_kws = {}
elif kind_plot == "both":
# by default, we need to distinguish the average line from
# the individual lines via color and line style
default_ice_lines_kws = {
"alpha": 0.3,
... | Python | 1 |
"0x59": "5",
"0x5A": "6",
"0x5B": "7",
"0x5C": "8",
"0x5D": "9",
"0x5E": "!",
"0x5F": "?",
"0x60": "/",
"0x61": ":",
"0x62": "”",
"0x63": "’",
... | Rust | 0 |
import streamlit as st
import openai
# Set up OpenAI API
openai.api_key = "your_api_key_here"
# Title
st.title("🥗 AI-Powered Nutrition Chatbot for Women")
# Sidebar - User Information
st.sidebar.header("👩 User Information")
age = st.sidebar.number_input("Age", min_value=12, max_value=100, value=25)
diet_preference... | Python | 1 |
import numpy as np
import matplotlib.pyplot as plt
# Generar datos
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# Crear el gráfico de líneas con diferentes estilos
plt.plot(x, y1, color='blue', linestyle=':', linewidth=2, label='Sen(x)') # Línea sólida azul
plt.plot(x, y2, color='red', linestyle='--', l... | Python | 1 |
'''OpenGL extension NV.representative_fragment_test
This module customises the behaviour of the
OpenGL.raw.GL.NV.representative_fragment_test to provide a more
Python-friendly API
Overview (from the spec)
This extension provides a new _representative fragment test_ that allows
implementations to reduce the amou... | Python | 1 |
# import package
from fastapi import FastAPI, Request, Header, HTTPException
import pandas as pd
# password/api key
API_KEY = "testingapitokenkey1234" #testing api token key 1234
# Create new dataframe
df = pd.DataFrame()
# Populate dataframe
df['UserName'] = ['Undertaker', 'Rey Mysterio', 'Edge']
df['Location'] = [... | Python | 1 |
Field {
annotation: None,
access_mod: Some(AccessModifier::Public),
instance_mod: Some(ClassInstanceModifier::Static),
is_final: false,
ty: Ty {
kind: TyKind::Primitive(Primitive {
kind: PrimitiveKind::String,
is_array: false,
}),
span: Span {
start: 14,
end: 21,
start_pos: Positi... | Rust | 0 |
&mut self.unknown_fields
}
fn as_any(&self) -> &dyn (::std::any::Any) {
self as &dyn (::std::any::Any)
}
fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) {
self as &mut dyn (::std::any::Any)
}
fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::st... | Rust | 0 |
RGERTOKEN", &mut v).unwrap(),
(8, false)
);
assert_eq!(v, b"12345678");
}
// This tests against mikedilger/formdata github issue #11
#[test]
fn stream_until_token_double_straddle_test() {
let cursor = Cursor::new(&b"12345IAMALARGETOKEN4567"[..]);
let mut buf ... | Rust | 0 |
/src/event/get_upcoming_reminders.rs<gh_stars>0
use crate::shared::usecase::UseCase;
use actix_web::rt::time::Instant;
use nettu_scheduler_api_structs::send_event_reminders::{AccountEventReminder, AccountReminders};
use nettu_scheduler_domain::{Account, CalendarEvent, Reminder};
use nettu_scheduler_infra::NettuContext;... | Rust | 0 |
import gradio as gr
from langchain_community.chat_models import ChatTongyi
from langchain_core.messages import HumanMessage, SystemMessage, AIMessage
from langchain_core.output_parsers import StrOutputParser
from api_config import api_config
api_key = api_config.get_api_key()
llm = ChatTongyi(
dashscope_api_key=... | Python | 1 |
///
/// thread::spawn(move || {
/// println!("{:?}", five);
/// });
/// }
/// ```
///
/// Sharing a mutable [`AtomicUsize`]:
///
/// [`AtomicUsize`]: core::sync::atomic::AtomicUsize
///
/// ```no_run
/// use std::sync::atomic::{AtomicUsize, Ordering};
/// use std::sync::Arc;
/// use std::thread;
///
//... | Rust | 0 |
)
.into_result(|_| DpdkError::new())?;
}
}
}
Ok(())
}
/// Callback fn passed to `rte_eth_add_rx_callback`, which is called on RX
/// with a burst of packets that have been received on a given port and queue.
unsafe extern "C" fn append_and_write_rx(
_po... | Rust | 0 |
.get_read_bytes_sec(tick))
.unwrap_or(Equal)
},
ProcessTableSortBy::DiskWrite => |pa, pb, tick| {
pa.get_write_bytes_sec(tick)
.partial_cmp(&pb.get_write_bytes_sec(tick))
.unwrap_or(Equal)
},
Proc... | Rust | 0 |
ient = ClientBuilder::new("centerdevice.de", client_credentials)
.build()
.authorize_with_code_flow(&redirect_uri, &code_provider)
.expect("API call failed.");
let result = client.token();
println!("Result: '{:#?}'", result);
}
use criterion::{
criterion_group, criterion_main, meas... | Rust | 0 |
(os.path.join(dname, "test_question_sequences.csv"), index=None)
# test_question_window_seqs.to_csv(os.path.join(dname, "test_question_window_sequences.csv"), index=None)
# ins, ss, qs, cs, seqnum = calStatistics(test_question_seqs, stares, "test question")
# print(f"test question interactions num: {in... | Python | 1 |
process.makeThingToBeDropped1 *
process.dependsOnThingToBeDropped1)
process.p2 = cms.Path(process.A *
process.B *
process.C *
process.D *
process.E *
process.F *
... | Python | 1 |
"""Expose missing context variable
Allows the user to let umongo document return missing rather than None for
empty fields.
"""
from contextlib import AbstractContextManager
from contextvars import ContextVar
import marshmallow as ma
__all__ = (
"ExposeMissing",
"RemoveMissingSchema",
)
EXPOSE_MISSING = C... | Python | 1 |
nyMessageEventContent::RoomMessage(
MessageEventContent::text_plain("Test message"),
))
.await;
assert!(session.expired());
let settings = EncryptionSettings {
rotation_period: Duration::from_millis(100),
..Default::default()
};
... | Rust | 0 |
.__ws = None
self.callback_save_data_func = callback_save_data_func
self.find_missing_kline_func = find_missing_kline_func
self.__tick_summary = QA_Tick_Summary(5)
def Shifting_Time(self, period):
"""
设定每次获取K线数据的时间区间长度(单位秒),超过300条数据将会获取失败,此处设定每次获取240条数据
"""
i... | Python | 1 |
_base_ = '../faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py'
model = dict(
backbone=dict(
plugins=[
dict(
cfg=dict(
type='GeneralizedAttention',
spatial_range=-1,
num_heads=8,
attention_type='0010',
... | Python | 1 |
, spellings in self.lexicon.items():
word_idx = self.word_dict.get_index(word)
_, score = self.lm.score(start_state, word_idx)
for spelling in spellings:
spelling_idxs = [tgt_dict.index(token) for token in spelling]
self.trie.insert(spelling_idxs, word... | Python | 1 |
text -->`
Comment(StrSpan<'a>),
/// DOCTYPE start token.
///
/// Example: `<!DOCTYPE note [`
DtdStart(StrSpan<'a>, Option<ExternalId<'a>>),
/// Empty DOCTYPE token.
///
/// Example: `<!DOCTYPE note>`
EmptyDtd(StrSpan<'a>, Option<ExternalId<'a>>),
/// ENTITY token.
///
//... | Rust | 0 |
pping_add(self.d.mul_int(rhs_ty))
.wrapping_add(self.ty.get()),
);
Matrix {
a: self.a * rhs.a + self.c * rhs.b,
b: self.b * rhs.a + self.d * rhs.b,
c: self.a * rhs.c + self.c * rhs.d,
d: self.b * rhs.c + self.d * rhs.d,
tx: Twip... | Rust | 0 |
import os
from config import SYNCED_FILE
import json
def save_synced_data_file_list(file_list: list):
old_list = load_synced_file_list()
with open(SYNCED_FILE, "w") as f:
file_list.extend(old_list)
json.dump(file_list, f)
def save_synced_activity_list(activity_list: list):
with open(SY... | Python | 1 |
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
use combine::easy::{Error, Info, ParseError};
use unicode_width::UnicodeWidthStr;
///
/// A set of extensions for the char type for shortha... | Rust | 0 |
from threading import local
__all__ = ['activate', 'deactivate', 'get_collector', 'add_module']
_active = local()
def activate():
"""
Activates a global accessible object, where we can save information about
required dojo modules.
"""
class Collector:
used_dojo_modules = []
def a... | Python | 1 |
assert_in!(
output.stderr.str(),
format!(
"
--> {}/src/lib.rs:10:11
|
10 | fn single(fixture: S) {{}}
| ^^^^^^^ `S` cannot be formatted using `{{:?}}`",
name
)
.unindent()
... | Rust | 0 |
lid_Loss = np.append(Pool_Valid_Loss, Valid_Loss, axis=1)
Pool_Train_Loss = np.append(Pool_Train_Loss, Train_Loss, axis=1)
Pool_Valid_Acc = np.append(Pool_Valid_Acc, Valid_Acc, axis=1)
Pool_Train_Acc = np.append(Pool_Train_Acc, Train_Acc, axis=1)
print('Evaluate Model Test Accuracy with pooled points')
sco... | Python | 1 |
population_quarterdecks_minimums'
from jvkdd3zp4bz import gs718ai1rwh, rzhunrgxilg as u5xopfu_2md, sehbmp2rxmn as ek8lkj128kp, zxl20awsv6w, rxxm3xvhjm1, n9okxw874y6 as pd6uu1c20ye, h8ndqkrs33e, fhlr6xl3fge as vayo5v3h1jq, qh9unyf09rz as ugcx1icxc7u
None[0j]: qenvz0zw08s = 0
return cep6n_ftnd6
'# leak_s... | Python | 1 |
def on_default_collision(self, arbiter):
#ignore collision for shapes with collision_type == 0
for shape in arbiter.shapes:
if shape.collision_type == 0:
return False
return True
class DebugPanel(Widget):
fps = StringProperty(None)
def __init__(self,... | Python | 1 |
};
use std::sync::Arc;
pub struct BvhNode {
pub left: Arc<dyn Hittable>,
pub right: Arc<dyn Hittable>,
pub box0: Aabb,
}
impl BvhNode {
pub fn new(mut list: HittableList, time0: f64, time1: f64) -> Self {
let len = list.objects.len();
// Self:BvhNode::new0(&mut list.objects , 0 , len , ... | Rust | 0 |
mpl)(ShellRequest::SetKind {
surface: make_handle(&shell_surface, ctoken),
kind: ShellSurfaceKind::Maximized { output },
}),
Request::SetTitle { title } => {
ctoken
.with_role_data(&data.surface, |data| d... | Rust | 0 |
ut responses: Punctuated<Variant, Comma> = Punctuated::new();
let mut methods: Vec<TraitItem> = Vec::new();
let mut handlers: Vec<Arm> = Vec::new();
let mut client_funcs: Vec<ItemFn> = Vec::new();
let mut err_type = None;
for method in input.items {
match method {
TraitItem::Method(m) => {
... | Rust | 0 |
m ExpectCt {
/// Enforce certificate compliance for the next [`Duration`]. Ensure that
/// your certificates are in compliance before turning on enforcement.
/// (_SpaceHelmet_ default).
Enforce(Duration),
/// Report to `Uri`, but do not enforce, compliance violations for the next
/// [`Duratio... | Rust | 0 |
m_hRgn = ::CreateEllipticRgn(x1, y1, x2, y2);
return m_hRgn;
}
HRGN CreateEllipticRgnIndirect(LPCRECT lpRect)
{
ATLASSERT(m_hRgn == NULL);
m_hRgn = ::CreateEllipticRgnIndirect(lpRect);
return m_hRgn;
}
HRGN CreatePolygonRgn(LPPOINT lpPoints, int nCount, int nMode)
{
ATLASSERT(m_hRgn == NU... | Rust | 0 |
# Copyright (C) 2013-2023 Bastian Kleineidam
#
# 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 is distr... | Python | 1 |
from flask import Blueprint, jsonify, request
from services.dataroom_service import DataroomService
dataroom_bp = Blueprint('dataroom', __name__)
@dataroom_bp.route('/company/dataroom/list', methods=['GET'])
def get_datarooms():
datarooms = DataroomService.get_all_datarooms()
return jsonify([dataroom.to_dict(... | Python | 1 |
", src, dst);
}
fail_count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
responder.send(&mut Err(Status::NOT_FOUND.into_raw())).unwrap();
}
DirectoryRequest::Open { flags, mode, path, object, control_han... | Rust | 0 |
if !crate::features::in_fuzzing_or_gas_metering() {
return Err(ApiError::InputError(format!("Point is not on curve, file {}, line {}", file!(), line!())));
}
}
bases.push(p);
scalars.push(scalar);
global_rest = local_re... | Rust | 0 |
#!/usr/bin/python
# numpy is love
import numpy
import subprocess
import string
import sys
# get the filename
if len(sys.argv) > 1:
fname = sys.argv[1]
else:
fname = "startup-times.dat"
# read the data
revno_to_times = {}
for line in map(string.strip, open(fname)):
if line.startswith("#") or line == "":
... | Python | 1 |
": {
"encoded": "87121",
"raw": "87121"
},
"city": {
"encoded": "101327353979588246869873249766058188995681113722618593621043638294296500696424",
"raw": "SLC"
},
"address1": {
"encoded": "6369... | Rust | 0 |
oup(1)
if (
group == f"{pkg}{analyzed_spec}"
or group == f"{pkg_canonical_name}{analyzed_spec}"
):
skip = True
break
... | Python | 1 |
0
cache.set_max_schedules(0);
assert_eq!(cache.max_schedules(), MAX_SCHEDULES);
cache.set_max_schedules(std::usize::MAX);
assert_eq!(cache.max_schedules(), std::usize::MAX);
}
}
use bevy::prelude::*;
use crate::game::components::HighlightSprite;
#[derive(Debug)]
pub enum Highligh... | Rust | 0 |
veUpdateFeeImport;
type nativeUpdateFee = nativeUpdateFeeImport;
/// An update_fee message to be sent or received from a peer
#[must_use]
#[repr(C)]
pub struct UpdateFee {
/// A pointer to the opaque Rust object.
/// Nearly everywhere, inner must be non-null, however in places where
/// the Rust equivalent takes a... | Rust | 0 |
ent everything!
#![allow(dead_code)]
use crate::error::{Error, ErrorKind};
use crate::eval::callable::Callable;
use crate::eval::environment::Exports;
use crate::eval::{Environment, Evaluate, Expression, Procedure};
use crate::read::datum::{datum_to_vec, Datum};
use crate::read::syntax_str::{
FORM_NAME_BEGIN, FORM... | Rust | 0 |
andle)
# Spawn 10 children that will wait on stdin to exit. The previous 10
# children will probably exit while we're doing this.
(stdin_reader, stdin_writer) = os.pipe()
for _ in range(10):
handle = cmd("cat").stdin_file(stdin_reader).stdout_file(stdout_writer).start()
child_pids.appen... | Python | 1 |
in self.cuckoo.items.iter().zip_eq(self.opprf_outputs.iter()) {
let mut payload = vec![0; PAD_LEN];
if let Some(item) = opt_item {
if item.input_index >= payloads.len() {
return Err(Error::InvalidPayloadsLength);
}
payload.exten... | Rust | 0 |
severity to stderr
#[macro_export]
macro_rules! bt_log_info {
($($arg:tt)+) => (if LOG_SEVERITY <= SEVERITY_INFO { bt_log!("INFO", $($arg)+) });
}
/// Log a message at TRACE severity to stderr
#[macro_export]
macro_rules! bt_log_trace {
($($arg:tt)+) => (if LOG_SEVERITY <= SEVERITY_TRACE { bt_log!("TRACE", $(... | Rust | 0 |
, EventDB>))
.route("/api/v1/start_polling_moneyforward", web::post().to(handle_start_polling_moneyforward::<EthDeployer, EthSender, EventWatcher<EventDB>, EventDB>))
.route("/api/v1/start_sync_bc", web::post().to(handle_start_sync_bc::<EthDeployer, EthSender, EventWatcher<EventDB>, EventDB>))
... | Rust | 0 |
import os
import tkinter as tk
from tkinter import ttk
import ttkbootstrap as tb
from ..components.scrolled_frame import ScrolledFrame
from ...utils.paths import PATHS
class LoadProjectDialog(tk.Toplevel):
def __init__(self, parent):
super().__init__(parent)
self.title("Load Project")
self.... | Python | 1 |
ty, $real: ty) => {
impl<Tp, Tq, Tc> Add<$rhs> for $lhs
where
Tp: TpType,
Tq: TqType,
Tc: TcType,
{
type Output = Expr<Tp, Tq, Tc, $real>;
#[inline]
fn add(self, other: $rhs) -> Self::Output {
Expr::Add(Box::new(self.into()), Box::new(other.into()))
}
}
impl<Tp, Tq, Tc> Sub<$rhs> for... | Rust | 0 |
#[sqlx_macros::test]
async fn it_describes_insert() -> anyhow::Result<()> {
let mut conn = new::<Sqlite>().await?;
let d = conn
.describe("INSERT INTO tweet (id, text) VALUES (2, 'Hello')")
.await?;
assert_eq!(d.columns().len(), 0);
let d = conn
.describe("INSERT INTO tweet (i... | Rust | 0 |
-> Template {
index(conn)
}
fn rocket() -> (Rocket, Option<DbConn>) {
let rocket = rocket::ignite()
.attach(DbConn::fairing())
.mount("/", routes![index, index_head, login, votes, vote])
.attach(Template::fairing());
let conn = match cfg!(test) {
true => DbConn::get_one(&r... | Rust | 0 |
{
test_suite.reset();
let port = alloc_port();
test_suite.start_agent_at(port);
test_suite.cfg_enabled(true);
test_suite.cfg_max_resource_groups(5);
test_suite.cfg_agent_address(format!("127.0.0.1:{}", port));
// Workload
// [req-{1..5} * 10, req-{6..10} * 1]
let mut wl = iter::rep... | Rust | 0 |
ert expr._schema.names == ['int16', 'datetime', 'float64_sum', 'count']
assert expr._schema.types == [types.int16, types.datetime, types.float64, types.int64]
def test_illegal_groupby(src_expr):
pytest.raises(ExpressionError, lambda: src_expr.groupby('int16').agg(src_expr['string']))
pytest.raises(Express... | Python | 1 |
IndyErrorKind::WalletItemNotFound,
"Item to update not found",
)),
_ => Err(err_msg(
IndyErrorKind::InvalidState,
"More than one row update. Seems wallet structure is inconsistent",
)),
}
}
///
/// deletes value and... | Rust | 0 |
# Copyright (C) 2018-2025 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
# hard_sigmoid paddle model generator
#
import numpy as np
from save_model import saveModel
import paddle
import sys
def hard_sigmoid(name: str, x, slope: float = 0.2, offset: float = 0.5, data_type='float32'):
paddle.enable_stat... | Python | 1 |
#!/usr/bin/env python
# This file is part of creddump.
#
# creddump 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.
#
# creddump is di... | Python | 1 |
TcpOption>);
impl TcpSegmentOptions {
pub fn new() -> TcpSegmentOptions {
TcpSegmentOptions(HashMap::new())
}
pub fn parse(bytes: &[u8]) -> Result<TcpSegmentOptions> {
match parsers::start(bytes) {
Ok((_, list)) => {
let mut options = TcpSegmentOptions::new();
... | Rust | 0 |
}
RustItem::Impl(mut item) => {
item.attrs.splice(..0, attrs);
Ok(Item::Impl(item))
}
RustItem::Use(mut item) => {
item.attrs.splice(..0, attrs);
Ok(Item::Use(item))
}
other => Ok(Item::Other(othe... | Rust | 0 |
}
/// Gets the JSON-RPC protocol version.
pub fn version(&self) -> Version {
match self {
Self::Success(s) => s.jsonrpc,
Self::Failure(f) => f.jsonrpc,
}
}
/// Gets the correlation id.
pub fn id(&self) -> Option<Id> {
match self {
Self::... | Rust | 0 |
Ok(&self.wavetables[id])
}
pub fn create_wave_group(
&mut self,
wavetable_id: usize,
name: &str,
derived_from: Option<Vec<usize>>,
) -> Result<&WaveGroup, Error> {
let id;
{
id = self.wave_groups.len();
}
let wgrp;
... | Rust | 0 |
class Player:
def __init__(self, name, age): # constructor
self.name = name
self.age = age
def get_details(self):
print(f"Name is {self.name}\nAge is {self.age}")
ply1 = Player("Sachin", 34)
ply1.get_details()
print("-" * 60)
ply2 = Player("Rahul", 31)
ply2.get_details()
p... | Python | 1 |
,
v_http_response: *mut RuxcHTTPResponse,
v_method: HTTPMethodType)
-> Result<(), Error>
{
unsafe {
(*v_http_response).retcode = -1;
if (*v_http_request).url.is_null() {
(*v_http_response).retcode = -20;
return Ok(());
}
};
let... | Rust | 0 |
from django.contrib import admin
from .models import Users,RoleGroup
# Register your models here.
admin.site.register(Users)
admin.site.register(RoleGroup)
| Python | 1 |
}
acc += TextSize::of(chunk);
Ok(())
});
found(res)
}
pub fn char_at(&self, offset: TextSize) -> Option<char> {
let mut start: TextSize = 0.into();
let res = self.try_for_each_chunk(|chunk| {
let end = start + TextSize::of(chunk);
if start <= offset && offset < end {
let off: usize = u32::fro... | Rust | 0 |
test
}
extern crate progress_streams;
use progress_streams::ProgressWriter;
use std::io::{Write, sink};
fn main() {
let mut total = 0;
let mut file = sink();
let mut writer = ProgressWriter::new(&mut file, |progress: usize| {
total += progress;
println!("Written {} Kib", total / 1024);
... | Rust | 0 |
import numpy as np
from matplotlib import pyplot as plt
from skimage import io
from skimage.color import rgb2hsv
class Span:
def __init__(self, span):
self.span = span
self.start = span[0][:2]
def sort_span(self):
self.span = sorted(self.span, key=lambda x: x[2]) # Sort by hue... | Python | 1 |
"name": "constructor",
"inputs": [
],
"outputs": [
]
}
],
"data": [
],
"events": [
]
}"#;
pub struct Stdout {}
impl Stdout {
pub fn new() -> Self {
Self {}
}
pub fn print(&self, args: &Value) -> InterfaceResult {
let text_vec = hex::decode(args["message"].as_str().unwrap()).unwrap();
l... | Rust | 0 |
iter(self, runner):
if self.by_epoch and self.every_n_inner_iters(runner, self.interval):
runner.log_buffer.average(self.interval)
elif not self.by_epoch and self.every_n_iters(runner, self.interval):
runner.log_buffer.average(self.interval)
elif self.end_of_epoch(runner)... | Python | 1 |
= File::create(format!("output-{}.txt", round)).unwrap();
// for &(src, dst) in graph.iter() {
// file.write_fmt(format_args!("{}\t{}", src, dst)).unwrap();
// }
// }
// let index = rng.gen_range(0, graph.len());
// let src = rng... | Rust | 0 |
export_policy")
.long("export_policy")
.value_name("POLICY_NAME")
.help("Export the contents of the policy file named <POLICY_NAME>.")
.takes_value(true),
)
.arg(
Arg::with_name("path")
.long("path")
... | Rust | 0 |
import math
import sys
from itertools import pairwise
point = int(input())
x = [int(i) for i in input().split(" ")]
y = [int(j) for j in input().split(" ")]
x = x[:point]
y = y[:point]
xs = list(pairwise(x))
ys = list(pairwise(y))
m = sys.maxsize
for i in range(len(xs)):
d = math.sqrt((pow(xs[i][1] - xs[i][0], 2... | Python | 1 |
# Copyright 2009-2017 Ram Rachum.
# This program is distributed under the MIT license.
'''
See documentation of class `ReadWriteLock` defined in this module.
'''
# todo: organize.
from python_toolbox import context_management
from . import original_read_write_lock
__all__ = ['ReadWriteLock']
class ContextManager... | Python | 1 |
import sys
import random
from circus import Circuit, Field
random.seed(0xDEADBEEF)
circuit = Circuit()
ff = Field(2305843009213693951)
# ff = Field(340282366920938463463374607431768211297)
bf = circuit.backend(ff)
def rand_func(fn, muls, inputs, outputs):
import random
bf = fn.backend(ff)
ins = []
... | Python | 1 |
_index];
unsafe {
next.wait_and_clear(&self.device);
}
next.fence_value = old_fence_value + 1;
}
}
}
#[cfg(all(feature = "metal"))]
type Api = hal::api::Metal;
#[cfg(all(feature = "vulkan", not(feature = "metal")))]
type Api = hal::api::Vulkan;
#[cfg(all(... | Rust | 0 |
210 => 2,
210 => 2,
210 => 2,
210 => 2,
210 => 2,
210 => 2,
210 => 2,
210 => 2,
210 => 2,
210 => 2,
210 => 2,
210 => 2,
210 => 2,
210 => 2,
210 => 2,
210 => 2,
210 => 2,
210 => 2,
210 => 2,
210 => 2,
210 => 2,
210 => 2,
210 => ... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.