text string | label_name string | labels int64 |
|---|---|---|
from fastapi import APIRouter, Depends, status, HTTPException, Response, Request, Form, File, UploadFile
from fastapi.security.oauth2 import OAuth2PasswordRequestForm
from fastapi.responses import HTMLResponse
from sqlalchemy.orm import Session
from app.database import get_db
from app import schemas, models, utils, oau... | Python | 1 |
let country_code_vec: Vec<u8> = data.drain(0..3 as usize).collect();
let country_code = String::from_utf8(country_code_vec)?;
let val = vec_to_u32(&value_vec)?;
Ok(CoinValue {
value: val,
country_code: country_code,
})
}
pub fn decode_list(da... | Rust | 0 |
is_present("do-twos");
match matches.subcommand() {
("bound", Some(sub_m)) => {
let bound = parse_nums(sub_m.values_of("bound").unwrap());
println!("Got: {:?}", bound);
let range = if bound.len() == 2 {
(bound[0]..(bound[1] + 1))
} else {
... | Rust | 0 |
; 16],
v: u32,
mut w: u32,
x: u32,
y: u32,
mut z: u32,
i: usize,
) -> ([u32; 16], u32, u32) {
block[i] = blk(&block, i);
let n = ((w & (x ^ y)) ^ y)
.wrapping_add(block[i])
.wrapping_add(0x5a82_7999)
.wrapping_add(rol(v, 5));
z = z.wrapping_add(n);
w = rol... | Rust | 0 |
# Copyright (c) Qualcomm Innovation Center, Inc.
# All rights reserved
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import torch
from executorch.exir.pass_base import ExportPass, PassResult
from .utils import merge_decomposed_graph... | Python | 1 |
from odoo import models
from odoo.addons.account.models.chart_template import template
class AccountChartTemplate(models.AbstractModel):
_inherit = "account.chart.template"
@template('generic_coa')
def _get_generic_coa_template_data(self):
"""Return the data necessary for the chart template.
... | Python | 1 |
{
table.push(format!("| {} | {} |", lpad(name), rpad(&version)));
eprintln!("ok");
}
Err(e) => {
eprintln!("fail ({})", e);
}
}
}
eprintln!("\n");
println!("{}", table.join("\n"));
Ok(())
}
use std::fmt;
use af... | Rust | 0 |
field: str = Field(default="created_at", json_schema_extra={"example": "name"})
direction: str = Field(default="desc", json_schema_extra={"example": "asc"})
# --- WebSocket Message Schemas ---
class ProjectWebSocketMessage(BaseModel):
"""Schema for WebSocket messages."""
type: str = Field(..., json_schem... | Python | 1 |
a\x87\xe4\xe8\xef,\
\xe9\xc1o.\xd4\xdc\xde2\x83\x91\x10O>\xf9\xa4v\
\xec\xd8A-\x1b\x83F\xc6\x12\x8dhdn\x03\x00\x80\
?0\x00\x00\x00\x00\xc5K\x064\x96\xcbe}\xf2\x93\
\x9f\xd4\xa7?\xfdiuvv\x92\xb0\x00\xd0\x16C#\
u\xfd\xe8\xcda\xfdb\xfda\x8d\xd7\xa7\xafW\xcd\x1a\
`\xae\xc7o4\xbdc?\xeefS\xac\x0dR\x8c\x00\
\x18\x01\x02\xe4\x... | Python | 1 |
1\xdb\xd5\xba4n\x89;K\x1a\xb6.4%S\
\x1d\x83\xbd}c\x97]^\xf5^\x16x\xdf\x04\xdbG\
T\x05\xb0Z\xdb\x10s\x0d\x86\xef\xd4p(K;y\
2+\x96\xf0\xb4\xf6\x19\x1f\xb19\xd2c\x07\xc4{\x0c\
c\xdc\xb5Cv\x8d\x9f)\x81\x12>\x92\xf1S\x1a\xcb\
|4\xc7(0\xed\x0b&\xf7F\xcf%\xe6\x0aI\xb0\
i/\xd48\xed\x80|q\x1bY\x01&\x8cy\xe9\x8c\
\xbbl\xa7q\x98\... | Python | 1 |
self.env.get_p_site(site_name=obj2)
target_R = self.env.get_R_site(site_name=obj2)
yaw = r2rpy(target_R)[2]
target_size = self.get_rotated_aabb_size(target_size, yaw)
source_pose = self.env.get_p_site(site_name=obj1)
# print("source_pose", source_pose)
# print("target_pos... | Python | 1 |
{111c0}'), ('\u{111ca}', '\u{111cc}'), ('\u{1122c}',
'\u{11237}'), ('\u{112df}', '\u{112ea}'), ('\u{11300}', '\u{11303}'),
('\u{1133c}', '\u{1133c}'), ('\u{1133e}', '\u{11344}'), ('\u{11347}',
'\u{11348}'), ('\u{1134b}', '\u{1134d}'), ('\u{11357}', '\u{11357}'),
('\u{11362}', '\u{11363}'... | Rust | 0 |
teps= test_steps, verbose= 1)
print("Train Loss: ", train_score[0])
print("Train Accuracy: ", train_score[1])
print('-' * 20)
print("Validation Loss: ", valid_score[0])
print("Validation Accuracy: ", valid_score[1])
print('-' * 20)
print("Test Loss: ", test_score[0])
print("Test Accuracy: ", test_score[1])
# Generate... | Python | 1 |
output = quote! {
impl #impl_generics ssz::Decode for #name #ty_generics #where_clause {
fn is_ssz_fixed_len() -> bool {
#(
#is_fixed_lens &&
)*
true
}
fn ssz_fixed_len() -> usize {
if <... | Rust | 0 |
import multiprocessing
import sys
import os
import subprocess
import time
import data
import GA_function_cost.GA_input_cost as input
waste_name = input.waste_name
N_INC_INITIAL = input.N_INC_INITIAL
N_INC_MAX = input.N_INC_MAX
N_TRANS_INITIAL = input.N_TRANS_INITIAL
N_TRANS_MAX = input.N_TRANS_MAX
N_GEN = input.N_GEN ... | Python | 1 |
ils::revcomp(&seq);
let mut rev_minim_pos = pos.clone();
rev_minim_pos.reverse();
for pos in &mut rev_minim_pos {
*pos = seq.len() - l - *pos;
}
aligner.semiglobal(&rev_read, Some(&rev_seq), Some(&rev_minim_pos));
if debug { println... | Rust | 0 |
post_base, post_quote) = {
(Account::unpack(&base_vault_acc.try_borrow_data()?)?.amount,
Account::unpack("e_vault_acc.try_borrow_data()?)?.amount)
};
let (pre_in, pre_out, post_in, post_out) = match side {
Side::Bid => (pre_base, pre_quote, post_base, post_quote... | Rust | 0 |
"""app URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based vie... | Python | 1 |
ew(err));
}
}
Err(err) => return Err(Box::new(err))
}
}
},
Err(err) => return Err(Box::new(err))
}
}
return Ok(true);
}
Err... | Rust | 0 |
_NUMBER + 1) % 8;
}
/*
After Start packet is sent, nrf5x will start to erase flash page, each page takes 2.05 - 89.7 ms
nrfutil need to wait accordingly for the image size
- (dual bank only) After sending all data -> send command to activate new firmware --> nrf52 erase bank0 and copy image
from bank1 ... | Rust | 0 |
import streamlit as st
from openai import OpenAI
st.title("A simple RAG application using Postgres and pgvector")
# Set OpenAI API key from Streamlit secrets
client = OpenAI (api_key=st.secrets["OPENAI_API_KEY"])
# Set a default model
if "openai_model" not in st.session_state:
st.session_state["openai_model"] = ... | Python | 1 |
data_colors = data['colors'] if len(data['colors'].shape) == 2 else data['colors'][0, :, :]
if data_colors.any() > 1:
data_colors = data_colors / 255.0
data_faces = data['faces'] if len(data['faces'].shape) == 2 else data['faces'][0, :, :]
if 'pred_labels' in data.keys():
data_labels = ... | Python | 1 |
from rest_framework import serializers
from .models import Warehouse
class WarehouseSerializer(serializers.ModelSerializer):
class Meta:
model = Warehouse
fields = ['id', 'name', 'location', 'capacity']
| Python | 1 |
pub len: u_char,
pub name: [u_char; 1usize],
}
impl ::std::default::Default for Struct_ngx_http_location_tree_node_s {
fn default() -> Struct_ngx_http_location_tree_node_s {
unsafe { ::std::mem::zeroed() }
}
}
pub type ngx_http_output_header_filter_pt =
::std::option::Option<extern "C" fn(r: *mu... | Rust | 0 |
"test"])
.help("Write output on standard output; keep original files unchanged.")
.display_order(100),
)
.arg(
Arg::with_name("keep")
.short("k")
.long("keep")
.conflicts_with_all(&["list", "test"])
... | Rust | 0 |
if self.adj_matrix[self.Nodes.index(v1)][self.Nodes.index(v2)] or self.adj_matrix[self.Nodes.index(v2)][self.Nodes.index(v1)]:
return True
return False
def __repr__(self):
rep_str = ""
for i in self.adj_matrix:
rep_str += str(i) + "\n"
return re... | Python | 1 |
{} to expressi's type representation",
type_description
)]
InternalTypeConversion {
// TODO: Use better representation than string
type_description: String,
},
#[fail(display = "Attempt to translate untyped value")]
NotTyped,
#[fail(display = "Attempt to translate a val... | Rust | 0 |
HandRank::from(2));
assert!(HandRank::from(2000) < HandRank::from(2));
assert!(HandRank::from(0) < HandRank::from(2));
assert_eq!(HandRank::from(2), HandRank::from(2));
}
#[rustfmt::skip]
#[rstest]
#[case("A♠ K♠ Q♠ J♠ T♠", 1, HandRankName::StraightFlush, HandRankClass::RoyalFlu... | Rust | 0 |
] $3.40
[TEST:DEF]
2018-10-01 <NAME>
(TEST:ABC) = $5.60
"#,
);
let expected_transactions = parse_transactions(
r#"
2018-10-01 <NAME>
TEST:ABC $1.20
TEST:DEF $-1.20
[TEST:ABC] $3.40
[TEST:DEF] $-3.40
2018-10-01 <NAME>
(TEST:ABC) $1.00
"#,
);
... | Rust | 0 |
GCPPixel)
feat.SetField('Line', gcp.GCPLine)
geom.SetPoint(0, gcp.GCPX, gcp.GCPY, gcp.GCPZ)
else:
geom = ogr.Geometry(geom_type)
feat.SetField('X', gcp.GCPX)
feat.SetField('Y', gcp.GCPY)
feat.SetField('Z', gcp.GCPZ)
geom.SetPoin... | Python | 1 |
, 1.026830, 1.040560, 1.032847, 1.028675, 1.000670, 1.037851, 1.000402, 1.000753, 1.024783, 1.006964,
1.006178, 1.012921, 1.002187, 1.001676, 1.046860, 1.019303, 1.042652, 1.032596, 1.044473, 1.056054, 1.037224, 1.004872, 1.018090, 1.005287, 1.007716, 1.014838, 1.005670, 1.024829,
1.026830, 1.040560, ... | Python | 1 |
let lookup_tables: Vec<_> = points
.into_iter()
.map(|point| LookupTable::<CachedPoint>::from(point.borrow()))
.collect();
let scalar_digits_vec: Vec<_> = scalars
.into_iter()
.map(|s| s.borrow().to_radix_16())
.collect();
... | Rust | 0 |
erator::KeyStruct;
use error::EnclaveError;
use std::string::ToString;
use pse_session::{create_pse_session, close_pse_session};
type Result<T> = result::Result<T, EnclaveError>;
#[derive(Copy,Clone)]
pub struct MonotonicCounter {
pub value: u32,
pub id: sgx_mc_uuid_t,
}
pub fn create_mc() -> Result<Monotoni... | Rust | 0 |
\setlength{\parindent}{0pt}
\setlength{\parskip}{0.5\baselineskip}
% Remove (sub)section numbering
% \makeatletter
% \renewcommand{\@seccntformat}[1]{}
% \makeatother
% Unification of labels
\global\def\labelhere{}
\newcommand{\rstlabel}[1]{\global\def\labelhere{\hypertarget{#1}{}\label{#1}}}
% RST Simulations in L... | Rust | 0 |
{}", err),
Ok(args) => {
let mut verbose = args.verbose;
verbose.set_default(case.default);
assert_eq!(verbose.log_level(), case.want);
}
};
}
}
struct TestCase<'a> {
input: &'a str,
default: Option<Level>,
want: Option<Level>,
}
}
<reponame>asc... | Rust | 0 |
/// Calculates the parents for the node at the given `index`.
pub fn parents(&self, index: u32) -> ExpanderGraphParentsIter {
ExpanderGraphParentsIter::new(self, index)
}
/// Calculates the expanded parents for the node at the given `index`.
pub fn expanded_parents(&self, index: u32) -> impl It... | Rust | 0 |
:{
error::{invalid_src_id_span, panic_on_syn_error, DiagnosticError, Result, SourceIdSpan},
typemap::ast::DisplayToTokens,
types::MethodVariant,
WRITE_TO_MEM_FAILED_MSG,
};
pub(in crate::java_jni) fn predefined_java_type_to_jni_sig() -> FxHashMap<SmolStr, SmolStr> {
let mut m = FxHashMap::default()... | Rust | 0 |
.score,
content=(point.payload or {}).pop("content", ""),
metadata=ChunkMetadata(**(point.payload or {}))
) for point in search_result
]
async def _bm25_search(self, query: str, top_k: int) -> VectorStoreQueryResult:
if not self.bm25_index:
... | Python | 1 |
t!("Enter second number (if exponent power/if modulus, b): ");
read(&mut num_2);
let num_1: f32 = num_1.trim().parse().unwrap();
let num_2: f32 = num_2.trim().parse().unwrap();
let operator: char = operator.trim().chars().next().unwrap();
let operators = String::from("+ ... | Rust | 0 |
def to_object(self, config: tfhConfig = tfhConfig()):
# NOTE: If the ambiguous token was never resolved, simply return the value as a str
return str(self.value)
@classmethod
def from_object(cls, obj: int):
return cls(obj)
def __repr__(self):
return f"tfhAmbiguo... | Python | 1 |
_time_s=wait_time_s,
)
async def on_capacity_consumed(
*,
model_family: str,
usage: FrozenUsage,
preconsumption_capacities: Capacities,
postconsumption_capacities: Capacities,
current_time: float,
) -> None:
logger = _get_loguru_logger()
l... | Python | 1 |
/
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language gove... | Rust | 0 |
args: CmdOptions = CmdOptions::from_args();
for file in &args.objfiles {
let mut f = File::open(&file)?;
let mut c = Counter::new();
wavefront::parse(&mut c, &mut f)?;
println!("filepath {}", file.to_string_lossy());
println!("min_bound {:.6} {:.6} {:.6}", c.min_bound.... | Rust | 0 |
'%s%s Passwords Containing "%s"'
% (self.search_term(k, pw_count), td, k)
)
results.append("")
results.append("\t\tPassword Length Statistics")
results.append("Password Length%sCount" % td)
for l in sorted(lengt... | Python | 1 |
t2 { x: 5, y: 10 };
let both_float = Point2 { x: 1.0, y: 4.0 };
let integer_and_float = Point2 { x: 5, y: 4.0 };
// In Enum Definitions
enum Option<T> {
Some(T),
None,
}
enum Result<T, E> {
Ok(T),
Err(E),
}
// In Method Definitions
// Generic ty... | Rust | 0 |
= client.post('/api/admin/profiles/%s/update_quota_deadline/' % user.id, data={'hours': 1})
self.assertEqual(res.status_code, status.HTTP_403_FORBIDDEN)
# Cannot read quota information
res = client.get('/api/admin/profiles/%s/used_quota/' % user.id)
self.assertEqual(res.status_c... | Python | 1 |
the ranges or two numbers in the range
/// separated by a hyphen, slashes can be combined with ranges to specify
/// step values
///
/// Example
/// ```
/// use cron_parser::parse_field;
/// use std::collections::BTreeSet;
///
/// // every 3 months
/// assert_eq!(parse_field("*/3", 1, 12).unwrap(),
/// BTreeSet::<u... | Rust | 0 |
# 사칙연산 클래스 만들기
#
# 목표
# a = FourCal()
# a.setdata(4,2)
# print(a.sum()) # 6
# print(a.mul()) # 8
# print(a.sub()) # 2
# print(a.div()) # 2
# 클래스 구조 만들기
class FourCal :
pass
a = FourCal()
print(type(a)) # <class '__main__.FourCal'>
# 객체에 숫자 지정할 수 있게 만들기
class FourCal :
def setdata(self, first, second) :
... | Python | 1 |
# Copyright (c) 2013 Amazon.com, Inc. or its affiliates. All Rights Reserved
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights ... | Python | 1 |
gnals[stock] = signal
final_signals = list(unique_signals.values())
final_signals.sort(key=lambda x: x['score'], reverse=True)
return final_signals
def get_stock_current_price(stock_code):
"""获取股票当前价格"""
try:
# 转换股票代码格式
if '.SH' in stock_code:
ticker = stock_co... | Python | 1 |
("Pacific/Samoa", "Samoa"),
("Pacific/Tahiti", "Tahiti"),
("Pacific/Tarawa", "Tarawa"),
("Pacific/Tongatapu", "Tongatapu"),
("Pacific/Truk", "Truk"),
("... | Python | 1 |
tect Rate', color=all_colors[0])
ax.fill_between(np.arange(0, 120), averages[0] - average_stds[0], averages[0] + average_stds[0], color=all_colors[0], alpha=0.2)
# ax.plot(np.arange(0, 120), averages[1], linewidth=3, label='Medium Rate')
ax.plot(np.arange(0, 120), averages[2], linewidth=3, label='CADENCE-High Detect Ra... | Python | 1 |
import pyautogui
import time
import random
pyautogui.PAUSE = 1
#place your list of text here
Message = []
Time1 = [65, 66, 67, 68, 69]
Time2 = [310, 311, 312, 313, 314]
# Start Program
print(len(Message))
time.sleep(2)
while True:
randomNumberForMessage = random.randint(0, len(Message)-1)
randomNumberFo... | Python | 1 |
#!/usr/bin/python3
import struct, array, time, i2c_base
CHANNEL_0 = 0
CHANNEL_1 = 1
CMD_ZERO = b"\x00"
CMD_RESET = b"\x06"
CMD_LATCH = b"\x04"
CMD_CONVERSION = b"\x08"
CMD_READ_CH0_16BIT = b"\x88"
CMD_READ_CH1_16BIT = b"\xA8"
msleep = lambda x: time.sleep(x/1000.0)
class MCP342X(object):
def __init__(self, addr... | Python | 1 |
sCIMultiDict[str]c # g7f)Write HTTP headersNr8 )r/ r r s r0
write_headers"AbstractStreamWriter.write_headers rK rL r8 r4 rM rO rP rQ rR r r r r r r r r r bytes bytearray
memoryviewr r r zlibZ_DEFAULT_STRATEGYrv r r ... | Python | 1 |
input("Entrada inválida. Pressione Enter para continuar.")
continue
if retorno == 0:
return
if 1 <= retorno <= len(mapa_indices):
item_escolhido = mapa_indices[retorno - 1]
preco = getattr(item_escolhido, "preco", 0)
if item_escol... | Python | 1 |
# Copyright 2019 Toolchain Labs, Inc. All rights reserved.
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import logging
from toolchain.aws.aws_api import AWSService
from toolchain.base.email import parse_email
from toolchain.base.toolchain_error import ToolchainAs... | Python | 1 |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name="index"),
# Alunos
path('listar_aluno', views.listarAluno, name='listar_aluno'),
path('incluir_aluno', views.incluirAluno, name='incluir_aluno'),
path('alterar_aluno/<int:id>', views.alterarAluno, name='alt... | Python | 1 |
import torch
import triton
import triton.language as tl
import time
# Triton kernel for vector addition
@triton.jit
def vector_add_kernel(
x_ptr, # Pointer to first input vector
y_ptr, # Pointer to second input vector
output_ptr, # Pointer to output vector
n_elements, # Total number of elements
... | Python | 1 |
import database
from api.models.blog import Blog | Python | 1 |
#!/usr/bin/env python3
"""
Graphically show camera shutter effect
Produced for "Python for Mechanical and Aerospace Engineering" by Alex Kenan, ISBN 978-1-7360606-0-5 and 978-1-7360606-1-2.
Copyright © 2020 Alexander Kenan. Some Rights Reserved. This work is licensed under a Creative Commons Attribution-NonCommercial-... | Python | 1 |
const EV3_SERIAL_BT: u8 = 2;
pub fn lap_dly_tsk(msec: u32) -> i32 {
unsafe { ev3_dly_tsk(msec) }
}
pub fn lap_speaker_play_tone(frequency: u16, duration: i32) -> i32 {
unsafe { ev3_speaker_play_tone(frequency, duration) }
}
pub fn lap_syslog(_string: &str) {
let y = [1u8, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36];
le... | Rust | 0 |
: false,
}
}
}
};
(SIGNED $ty: ty) => {
impl From<$ty> for Decimal {
#[inline]
fn from(val: $ty) -> Decimal {
let (int_val, negative) = if val < 0 {
(-(val as i128) as u128, true)
} else {
... | Rust | 0 |
"""
A collection of utility routines and classes used by the spatial
backends.
"""
class SpatialOperator:
"""
Class encapsulating the behavior specific to a GIS operation (used by lookups).
"""
sql_template = None
def __init__(self, op=None, func=None):
self.op = op
self.func = f... | Python | 1 |
to get specified screen")?;
// Enumerate monitors, getting a handle and DC for requested monitor.
// loljk, because doing that on Windows is worse than death
let h_dc_screen = winuser::GetDC(null_mut());
// Create a Windows Bitmap, and copy the bits into it
... | Rust | 0 |
64::MIN, 256, u64::MAX],
U64_TEST_VALUES.to_owned(),
],
v_required: vec![
vec![],
vec![i64::MIN],
vec![i64::MIN, 0],
vec![i64::MIN, 0, i64::MAX],
S64_TEST_VALUES.to_owned(),
],
w_required: vec![
vec![],
... | Rust | 0 |
"""
separators = ["<h1", "<h2", "<code", " ", ""]
df = pd.concat(dfs, axis=0, ignore_index=True)
splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
# cl100k_base is used for text ada 002 and later embedding models
encoding_name="cl100k_base",
chunk_size=TARGET_CHUNK... | Python | 1 |
all fraction of a pixel
for j in range(2):
assert_allclose(x[j], x[j + 1], atol=0.01)
assert_allclose(y[j], y[j + 1], atol=0.01)
@pytest.mark.parametrize("finder", ["iraf", "dao", "segmentation"])
def test_make_tweakreg_catalog_graceful_fail_no_sources(example_input, finder, log_watcher):
"""T... | Python | 1 |
"""Robot URDF visualizer
Requires yourdfpy and robot_descriptions. Any URDF supported by yourdfpy should work.
- https://github.com/robot-descriptions/robot_descriptions.py
- https://github.com/clemense/yourdfpy
The :class:`viser.extras.ViserUrdf` is a lightweight interface between yourdfpy
and viser. It can also tak... | Python | 1 |
dden: %s."
return msg % (len(self), len(self._override), self._override.keys())
def __setitem__(self, key, value):
"""Override an existing parameter (key) by value.
The parameter that is overridden is added to self._override, note that only *existing*
parameters may be overridden... | Python | 1 |
let mut array_29 = object.key("Tags").start_array();
for item_30 in var_28 {
{
let mut object_31 = array_29.value().start_object();
crate::json_ser::serialize_structure_crate_model_tag(&mut object_31, item_30)?;
object_31.finish();
}
... | Rust | 0 |
from typing import Iterator
from fastapi import Depends
from sqlalchemy.orm.session import Session
from app.infrastructure.sql.database import SessionLocal
# NAME_CAPITALIZED_SINGULAR
from app.domain.NAME_LOWER_SINGULAR import (
NAME_CAPITALIZED_SINGULARRepository
)
from app.infrastructure.sql.NAME_LOWER_SINGULA... | Python | 1 |
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import socketio
import asyncio
from app.mqtt.publisher import esp_mqtt_client
from app.mqtt.subscriber import init_mqtt_subscriber
from app.db.mongodb import connect_to_mongo
# from app.api.routes import router as api_router
sio = socketio.... | Python | 1 |
x1.sub(&x2);
x1.norm();
} else {
v.sub(&u);
v.norm();
t.copy(&x2);
t.add(p);
x2.cmove(&t,(BIG::comp(&x2,&x1)>>1)&1);
x2.sub(&x1);
x2.norm();
}
}
s... | Rust | 0 |
object_token=object_token,
random_seed=random_seed)
self._entity_layer = text_grid.TextGrid(self._native_maze.entity_layer)
self._variations_layer = (
text_grid.TextGrid(self._native_maze.variations_layer))
def regenerate(self):
self._native_maze.regenerate()
self._entity_layer = text... | Python | 1 |
https://en.wikipedia.org/wiki/Manjaro>).
Manjaro,
/// Mariner (<https://en.wikipedia.org/wiki/CBL-Mariner>).
Mariner,
/// Mint (<https://en.wikipedia.org/wiki/Linux_Mint>).
MidnightBSD,
/// MidnightBSD(<https://en.wikipedia.org/wiki/MidnightBSD>).
Mint,
/// NetBSD (<https://en.wikipedia.... | Rust | 0 |
ndgen, AccountId, Promise};
near_sdk::setup_alloc!();
#[near_bindgen]
#[derive(Default, BorshDeserialize, BorshSerialize)]
pub struct Storage {
computer: Computer,
counter: Counter,
}
#[near_bindgen]
impl Storage {
#[init]
pub fn new(owner: String) -> Self {
Self {
computer: Comput... | Rust | 0 |
yword.to_string() == "pub" && group.delimiter() == Delimiter::Parenthesis => {
let keyword = Some(to_ident(tokens.pop().unwrap()));
let group = Some(to_group(tokens.pop().unwrap()));
Visibility { keyword, group }
},
[.., TokenTree::Ident(keyword)] if keyword.to_string() == "pub" => {
let keyword = Some(... | Rust | 0 |
"`read()` method returns [stim17::R](stim17::R) reader structure"]
impl crate::Readable for STIM17 {}
#[doc = "`write(|w| ..)` method takes [stim17::W](stim17::W) writer structure"]
impl crate::Writable for STIM17 {}
#[doc = "Stimulus Port 17"]
pub mod stim17;
#[doc = "Stimulus Port 18\n\nThis register you can [`read`... | Rust | 0 |
# Copyright (c) 2021 PaddlePaddle 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 applic... | Python | 1 |
;
// result.points[3] = *w;
// result.size = 4;
// result.v = V3::zero();
// result
}
// #[inline(never)]
fn next1(&self, w: &Point) -> Simplex {
let s = self.points[0];
let t = geom::line_project_time(w.p, s.p, V3::zero());
if t < 0.0 {
s... | Rust | 0 |
;
let haystack_start = haystack.as_ptr() as usize;
if needle_start < haystack_start {
return None;
}
let needle_end = needle_start + needle.len();
let haystack_end = haystack_start + haystack.len();
if needle_end > haystack_end {
return None;
... | Rust | 0 |
2: (usize, Tok<'input>, usize),
__3: (usize, Annotated<Pattern>, usize),
__4: (usize, Tok<'input>, usize),
) -> Annotated<Pattern>
{
let __start0 = __0.0.clone();
let __end0 = __4.2.clone();
let __temp0 = __action198(
text,
__0,
__1,
__2,
__3,
__4,
... | Rust | 0 |
args = {**DEFAULT_CFG_DICT, **self.model.args, **custom, **kwargs, 'mode': 'benchmark'}
return benchmark(
model=self,
data=kwargs.get('data'), # if no 'data' argument passed set data=None for default datasets
imgsz=args['imgsz'],
half=args['half'],
... | Python | 1 |
<T, D>,
nodes: Vec<NodeInfo<'t, T>>,
}
impl<'t, T: 't, D: 't> TreePrinter<'t, T, D>
where T: fmt::Debug
{
pub fn new(tree: &'t VpTree<T, D>) -> Self {
TreePrinter {
tree: tree,
nodes: Vec::new(),
}
}
pub fn print(mut self, f: &mut fmt::Formatter) -> fmt::Res... | Rust | 0 |
t_size, render_points_as_spheres=True)
plotter.add_points(neighbor_points[point_index, :, :], point_size=neighor_point_size, color=neighbor_colors, render_points_as_spheres=True)
plotter.add_points(points[point_index], point_size=neighor_point_size*2, color='green', render_points_as_spheres=True)
plotter.sh... | Python | 1 |
3i::fill(100));
for p in read_extent.iter_points() {
if extent_to_copy.contains(p) {
assert_eq!(lod0.get(p), 1);
} else {
assert_eq!(lod0.get(p), 0);
}
}
}
#[test]
fn multichannel_accessors() {
let builder = ChunkMa... | Rust | 0 |
let e = format!("Error getting tag id from [{}]. E: {}", self.tag, e);
errors.push(e);
0
});
// TODO: Verify date has a good format. (YYYY-MM-DD)
let date = self.date.replace('/', "-");
if errors.len() > 0 {
re... | Rust | 0 |
t entries
/// immediately higher (as defined by <PublicKey as Ord>::cmp) than starting_point.
/// If None is provided for starting_point, we start at the first node.
#[must_use]
pub get_next_node_announcements: extern "C" fn (this_arg: *const c_void, starting_point: crate::c_types::PublicKey, batch_amount: u8) -> c... | Rust | 0 |
output2, spec_output)
ronghe = self.residual(output)
return ronghe # shape: [batch, feature_dim]
class Mol_SMILES_Decoder(nn.Module):
def __init__(self, config) -> None:
super().__init__()
self.decoder = TransformerSMILESDecoder(config=config)
def forward(self, src, x_em... | Python | 1 |
n x.cumsum(axis=axis)
def is_tensor(x: T.FloatingPoint) -> bool:
"""
Test if x is a tensor.
Args:
x (float or tensor)
Returns:
bool
"""
try:
shape(x)
return True
except Exception:
return False
def logical_not(x: T.Tensor) -> T.Tensor:
"""
... | Python | 1 |
if name not in labeled else None
is_side = is_bottom = False
if name not in labeled:
labeled.add(name)
else:
prism, depth_range = segment
color = colors[name].get(depth_range, "gray")
is_side = name == "李屯岩体... | Python | 1 |
from .ForecasterAutoregMultiSeriesCustom import ForecasterAutoregMultiSeriesCustom | Python | 1 |
a.len() - self.i;
let mut len: u32 = 0;
while (len as usize) != left {
let chr = self.data[self.i + len as usize];
if chr == b'"' {
len += 1;
let mut last_was_backslash = false;
... | Rust | 0 |
PathSegment {
fn hash<H: Hasher>(&self, state: &mut H) {
self.symbol.hash(state);
}
}
#[derive(Clone, Eq, PartialEq, Debug)]
pub struct LineStmt {
pub body: StrBody,
pub span: Span,
}
#[derive(Clone, Eq, PartialEq, Debug)]
pub struct StrBody {
pub segments: Vec<StrSegment>,
pub span: ... | Rust | 0 |
edResponse, HasMemberResponse,
HasStartedResponse, InstantiateMsg, IsActiveResponse, MembersResponse, QueryMsg,
RemoveMembersMsg,
};
use crate::state::{Config, CONFIG, WHITELIST};
#[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;
use cosmwasm_std::{to_binary, Binary, Deps, DepsMut, Env, MessageInf... | Rust | 0 |
as usize).collect()
}
/// Returns a vector with length `size` which is first filled with each integer value
/// in the (inclusive) range `[vals.0, vals.1]`. If `size` is greater than the
/// number of integers in the aforementioned range, the integers will repeat. After
/// being filled with `size` values, the vector... | Rust | 0 |
# Generated by Django 4.2.15 on 2024-10-14 07:24
from django.db import migrations
def migrate_urlhaus(apps, schema_editor):
AnalyzerConfig = apps.get_model("analyzers_manager", "AnalyzerConfig")
ac = AnalyzerConfig.objects.filter(name="URLhaus").first()
if not ac:
return
ac.mapping_data_model... | Python | 1 |
as plt
from matplotlib import font_manager, rc
font_path = "c:\windows\Fonts\gulim.ttc"
font = font_manager.FontProperties(fname=font_path).get_name()
rc('font', family=font)
plt.figure(figsize=(9,6))
plt.plot(hist.history['val_loss'],c='red', label='loss',marker='.')
plt.plot(hist.history['val_accuracy'],c='blue', l... | Python | 1 |
time.start.mjd, [53343.92, 53343.935, 53343.954]
)
def test_time_range_jyear():
cfg = """
observations:
datastore: $GAMMAPY_DATA/hess-dl3-dr1
obs_ids: [23523, 23526]
obs_time: {
start: [J2004.92654346, J2004.92658453, J2004.92663655],
stop: [J2004.92658453, ... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.