text string | label_name string | labels int64 |
|---|---|---|
StructValueRef::ValueRef { val: self }
}
#[allow(clippy::needless_lifetimes)]
#[inline]
fn upcast_gat<'short, 'long: 'short>(long: StructValueRef<'long>) -> StructValueRef<'short> {
long
}
}
impl<'a> ScalarRef<'a> for StructValueRef<'a> {
type ColumnType = StructColumn;
type Scala... | Rust | 0 |
ation.value, axis.max_value);
if v == axis.default_value {
v = 0.0;
} else if v < axis.default_value {
v = (v - axis.default_value) / (axis.default_value - axis.min_value);
} else {
v = (v - axis.default_value) ... | Rust | 0 |
,
'original_data_path': original_data_path,
'test_data_path': test_data_path,
'seed_window_raw_path': seed_window_raw_path,
'seed_window_scaled_path': seed_window_scaled_path,
'history_path': history_path,
'best_epoch': best_epoch,
'best_val_loss': best_val_loss,
... | Python | 1 |
Debug)]
pub struct DCB {
pub DCBlength: ::DWORD,
pub BaudRate: ::DWORD,
pub BitFields: ::DWORD,
pub wReserved: ::WORD,
pub XonLim: ::WORD,
pub XoffLim: ::WORD,
pub ByteSize: ::BYTE,
pub Parity: ::BYTE,
pub StopBits: ::BYTE,
pub XonChar: ::c_char,
pub XoffChar: ::c_char,
... | Rust | 0 |
[..])
};
let buf = [1_u8; 16];
assert_eq!(writer.write(&buf).unwrap(), buf.len());
}
#[test]
#[allow(deprecated)]
fn error() {
let invalid_utf8 = b"\xff";
let res = if let Err(error) = ::std::str::from_utf8(invalid_utf8) {
Err(Left(error))
} ... | Rust | 0 |
nc(a.as_slice());
let fut3 = b3.copy_from_async(a.as_slice());
fut3.await;
fut2.await;
fut1.await;
assert_eq!(a, b1);
assert_eq!(a, b2);
assert_eq!(a, b3);
}
#[tokio::test]
async fn memcpy_async_d2h() {
let device = Device::nth(0).unwrap();
... | Rust | 0 |
import networkx as nx
import os
def cargar_rutas(nombre_archivo):
grafo = nx.Graph()
if not os.path.exists(nombre_archivo):
with open(nombre_archivo, 'w') as archivo:
archivo.write('"Pueblo Paleta", "Aldea Azalea", 100\n')
archivo.write('"Aldea Azalea", "Ciudad Safiro", 150\n')
... | Python | 1 |
initial_scale=2**5)
elif args.plugin == "low_level_zero":
plugin = LowLevelZeroPlugin(initial_scale=2**5)
logger.info(f"plugin: {plugin}")
booster = Booster(plugin=plugin, **booster_kwargs)
ctx = (
LazyInitContext(default_device=get_accelerator().get_current_device())
if args.pl... | Python | 1 |
routes![module_info, preload]
}
#[doc = "Reader of register FLCTL_POWER_STAT"]
pub type R = crate::R<u32, super::FLCTL_POWER_STAT>;
#[doc = "Flash power status\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum PSTAT_A {
#[doc = "0: Flash IP in power-down mode"]
PSTAT_0 = 0... | Rust | 0 |
lateau => climate(2.0, 0.0),
BambooJungle => climate(0.95, 0.9),
BambooJungleHills => climate(0.95, 0.9),
SoulSandValley => climate(2.0, 0.0),
CrimsonForest => climate(2.0, 0.0),
WarpedForest => climate(2.0, 0.0),
BasaltDeltas => climate(2.0, 0.0),... | Rust | 0 |
instruction.
Jcc { cond: Condition, offset: i8 },
/// Jump to a fixed [address][`Address`].
Jmp { address: Address },
/// Call a function at a fixed [address][`Address`].
///
/// More specifically, push the address of the following instruction onto the call stack, then
/// [`Jmp`][`Instruc... | Rust | 0 |
eq!(name, "dummy"),
other => panic!("unexpected error: {}", other),
}
}
#[test]
fn test_delete_experiment() {
let db = Database::temp().unwrap();
let config = Config::default();
::crates::lists::setup_test_lists(&db, &config).unwrap();
// Create a dummy... | Rust | 0 |
data('gamma', gamma)
md.add_macro("Sqr(a)", "a*a");
md.add_macro("WW1", "mu*(0.5+gamma)")
md.add_macro("WW2", "mu*(0.5-gamma)")
md.add_macro("WW3", "kappa*(1-1/Det(F)) - 2*WW2*pow(Det(F),-2/3) - WW1*pow(Det(F),-4/3)")
md.add_macro("I1", "Norm_sqr(F)")
md.add_macro("I2", "Sqr(Det(F))*Norm_sqr(Inv(F))")
md.... | Python | 1 |
ches,
udp_packets_in_regex: RegexMatches,
udp_packets_out_regex: RegexMatches,
start_date: DateTime<Local>,
counters: Counters,
template: String,
}
impl Motd {
pub fn new(template: String, counters: Counters) -> Motd {
let start_date_regex = Regex::new(r"(?i)\{\{\s*start_date\s*\}\}")
... | Rust | 0 |
=> || gst_controller_sys::gst_proxy_control_binding_get_type(),
}
}
impl ProxyControlBinding {
#[cfg(any(feature = "v1_12", feature = "dox"))]
pub fn new<P: IsA<gst::Object>, Q: IsA<gst::Object>>(
object: &P,
property_name: &str,
ref_object: &Q,
ref_property_name: &str,
... | Rust | 0 |
from setuptools import find_packages
from setuptools import setup
setup(
name='ros2cli',
version='0.40.1',
packages=find_packages(exclude=['test']),
extras_require={
'completion': ['argcomplete'],
'test': [
'pytest',
],
},
data_files=[
('share/ament_i... | Python | 1 |
andscapeTest):
helpers = [MonitorHelper, LogKeeperHelper]
def setUp(self):
LandscapeTest.setUp(self)
self.plugin = StubDataWatchingPlugin(1)
self.plugin.register(self.monitor)
self.mstore.add_schema(Message("wubble", {"wubblestuff": Int()}))
def test_get_message(self):
... | Python | 1 |
# Copyright (c) 2018 Giphy Inc.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import torch.nn as nn
import torch.nn.functional as F
from model_training.models.adap... | Python | 1 |
"""Common get info functions for vlan"""
# Python
import logging
# Genie
from genie.metaparser.util.exceptions import SchemaEmptyParserError
log = logging.getLogger(__name__)
def verify_Software_Fed_Igmp_Snooping(device, state, vlan, key, value):
'''
Api method to call parser and return boolean True If Vlan P... | Python | 1 |
from contextlib import contextmanager
import logging
@contextmanager
def all_logging_disabled(highest_level=logging.CRITICAL):
"""
A context manager that will prevent any logging messages
triggered during the body from being processed.
:param highest_level: the maximum logging level in use.
This... | Python | 1 |
().collect(), Vec::new())
}
}
_ => (env::args_os().collect(), Vec::new()),
}
}
// Temporary warning function
fn warn_accesss_token(token: &str, ui: &mut UI) {
if !token.starts_with("_") {
ui.warn("WARNING:").unwrap();
ui.warn(
"Github tokens are being dep... | Rust | 0 |
from services.vulnerability_intelligence.handlers.base_handler import BaseHandler
from models.vulnerability_intelligence import VulnerabilityIntelligence
from dateutil import parser as dateutil_parser
class CisaKevHandler(BaseHandler):
def apply(self, vuln_intelligence: VulnerabilityIntelligence):
try:
... | Python | 1 |
underline("__this is an__ underlined string"),
Some((Underline(vec![Text("this is an".to_owned())]), 14))
);
assert_eq!(
parse_underline("__testing__ underlined__ strings"),
Some((Underline(vec![Text("testing".to_owned())]), 11))
);
}
#[test]
fn ... | Rust | 0 |
r"""可访问资源数量
:rtype: int
"""
return self._AssetCount
@AssetCount.setter
def AssetCount(self, AssetCount):
self._AssetCount = AssetCount
@property
def LogCount(self):
r"""访问/行为日志数量
:rtype: int
"""
return self._LogCount
@LogCount.set... | Python | 1 |
## Example Generation after pretraining ############################################################
########################################################################################################################
print("Generating")
prompt = "Hello W"
generate_after_training(model, prompt, tokenizer, temp=0.0... | Python | 1 |
> HasSeek for Cursor<T> { }
impl<'a> HasSeek for PeekCursor<'a> { }
impl<T: Seek + Read> HasSeek for SeekPeekReader<T> { }
impl<T> AsSeek for BufPeekReader<T> { }
make_as_trait!(BufRead);
impl<T: AsRef<[u8]>> HasBufRead for Cursor<T> { }
impl<'a> HasBufRead for PeekCursor<'a> { }
impl<T: Read> HasBufRead for BufPeekRe... | Rust | 0 |
-1 1.2
2
'''
for device in self.devices:
fsa0 = k2.Fsa.from_str(s0).to(device).requires_grad_(True)
fsa1 = k2.Fsa.from_str(s1).to(device).requires_grad_(True)
fsa2 = k2.Fsa.from_str(s2).to(device).requires_grad_(True)
fsa_vec = k2.create_fsa_v... | Python | 1 |
ice context (DC) to which send data (pixels/RGB(A) colors)
let screen = GetDC(None);
let pixels_upperleftcorner_x = 0;
let pixels_upperleftcorner_y = 0;
// https://docs.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-transparentblt
TransparentBlt(
screen.to_... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by TaoYuan on 2017/12/17.
# @Link : http://blog.csdn.net/lftaoyuan
# Github : https://github.com/seeways
# @Remark : Python学习群:315857408
# Python提供了HTMLParser来非常方便地解析HTML
from html.parser import HTMLParser # 查找标记和其他标记和调用处理程序函数
from html.entities import name... | Python | 1 |
utputs)
merged.append(m)
return merged
if __name__ == "__main__":
# Testing code below. It creates a simple model to train on MNIST and
# tries to run it on 2 GPUs. It saves the graph so it can be viewed
# in TensorBoard. Run it as:
#
# python3 parallel_model.py
import... | Python | 1 |
// speedup in some scenarios.
program += &format!(r#"
unsafe {{
let old_size = self.buf.len();
let new_size = old_size + {};
if new_size > self.buf.capacity() {{
self.buf.reserve(new_size - old_size);
... | Rust | 0 |
contiguous in memory.
'''
if self._spatial_radius is None:
raise ValueError("Spatial radius has not been set")
if self._range_radius is None:
raise ValueError("Range radius has not been set")
if self._min_density is None:
raise... | Python | 1 |
Did you get any writing done today?",
"When will you stop wasting time plotting fractals?"
],
body
);
}
#[test]
/// You can turn almost any iterator into a peekable iterator by calling the Iterator
/// trait's peekable method.
/// Calling peek tries t... | Rust | 0 |
Self::Output {
unsafe{
let ptr = self.get_unchecked((MIN as usize)..=(MAX as usize)).as_ptr().cast();
&*ptr
}
}
}
#[allow(clippy::cast_sign_loss)]
impl<T, const N: usize, const MIN: irang, const MAX: irang>
core::ops::IndexMut<iter::ConstRange<MIN, MAX>> for [T; N]
where
... | Rust | 0 |
# cook your dish here
n = int(input())
if(n%2==0):
print(1)
else:
print(2)
| Python | 1 |
cted = to_vec(Struct { tag: "Struct", content: value });
assert_eq!(to_vec(s), expected);
}
/// Тестирует запись перечислений со значениями разных видов при из записи без тега
#[test]
fn test_enum_untagged() {
#[derive(Serialize)]
#[serde(untagged)]
enum E {
... | Rust | 0 |
f):
"""ステップインジケーターの更新とクリーンアップ"""
from src.facilities.ui.wizard_service_panel import WizardServicePanel
panel = Mock()
mock_indicator_panel = Mock()
panel.indicator_panel = mock_indicator_panel
with patch.object(panel, '_create_step_indicator') as mock_cr... | Python | 1 |
import numpy as np
import matplotlib.pyplot as plt
# Load data from text file
X = np.loadtxt("jaint_feats.txt")
centroid_old = np.loadtxt("jain_centers.txt")
centroid_new = np.zeros([2, 2])
plt.scatter(X[:, 0], X[:, 1], s=10, color='blue')
plt.scatter(centroid_old[:, 0], centroid_old[:, 1], marker='*', s=250, color='... | Python | 1 |
0 = 0,
#[doc = "1: Receive FIFO/Buffer depth = 4 datawords."]
_001 = 1,
#[doc = "2: Receive FIFO/Buffer depth = 8 datawords."]
_010 = 2,
#[doc = "3: Receive FIFO/Buffer depth = 16 datawords."]
_011 = 3,
#[doc = "4: Receive FIFO/Buffer depth = 32 datawords."]
_100 = 4,
#[doc = "5: Rec... | Rust | 0 |
from enum import Enum
from functools import lru_cache
import MetaTrader5 as mt5
from more_itertools import first
from src.symbol import Symbol
from src.time_frame import TimeFrame
class DefaultTimeFrames(Enum):
M1 = TimeFrame(name="m1", included_m1=1)
M5 = TimeFrame(name="m5", included_m1=5)
M15 = TimeFram... | Python | 1 |
from utils.prepare_input import prepare_qa_inputs
from utils.constant import GENERATION_TEMPERATURE, MAX_TOKENS, COT_PROMPT
import anthropic
import os
import time
import json
from tqdm import tqdm
from dotenv import load_dotenv
load_dotenv()
def generate_response(model_name: str,
prompt: str,
... | Python | 1 |
cle.clone(), max_movement);
// Get the points for the obstacle
let obstacle = get_points_obstacle(pos_obstacle.clone());
// ======================= (2) Plot ================================
// Path Plot
let data1 = path.clone();
let s1: Plot = Plot::new(data1).point_style(
PointSty... | Rust | 0 |
HC>::default(),
trivial_literal_context : 0,
distance_context : 0,
meta_block_remaining_len : 0,
block_type_length_state : BlockTypeAndLengthState::<AllocHC> {
block_length_index : 0,
block_length : [0; 3],
num_block_types : [0;3]... | Rust | 0 |
k_id: 任務 ID
Returns:
處理狀態信息
"""
if task_id not in processing_tasks:
raise HTTPException(status_code=404, detail="任務不存在")
task = processing_tasks[task_id]
return ProcessingStatus(
task_id=task_id,
status=task["status"],
progress=task["progress"],
... | Python | 1 |
}
}
}
#[derive(Debug)]
struct FileBlobCore {
base_dir: Option<PathBuf>,
}
impl FileBlobCore {
fn blob_path(&self, key: &str) -> Result<PathBuf, Error> {
self.base_dir
.as_ref()
.map(|base_dir| base_dir.join(key))
.ok_or_else(|| return Error::from("FileBlob unexp... | Rust | 0 |
Error:
assert False, "Memgraph process didn't exit cleanly!"
time.sleep(1)
def execute_test_switch_transactional_analytical(memgraph_binary: str, tester_binary: str) -> None:
def execute_queries(queries):
return execute_tester(tester_binary, queries, should_fail=False, check_failure=True, user... | Python | 1 |
a_manager = ChromaDBManager()
vector_store = chroma_manager.initialize_vector_store()
# Create dummy documents and nodes
doc1 = Document(text="The quick brown fox jumps over the lazy dog.", metadata={"source": "animal_facts"})
doc2 = Document(text="A car is a wheeled motor vehicle used for transportati... | Python | 1 |
)
}
/// buyer deposit eth to contract address
fn erc20_approve(&self, swap: &mut Swap) -> Result<H256, ErrorKind> {
let nc = self.eth_node_client.lock();
nc.erc20_approve(
swap.secondary_currency,
swap.secondary_amount,
swap.secondary_fee,
)
}
/// buyer deposit eth to contract address
fn buyer_d... | Rust | 0 |
$ S SK Jr S SKJr SS/rg) get_subprocess_handlerSubprocessHandlerr r NEtorch.distributed.elastic.multiprocessing.subprocess_handler.handlersr Otorch.distributed.elastic.multiprocessing.subprocess_handler.subprocess_handlerr __all__ Htorch\distri... | Python | 1 |
bbb][1]),np.std(byYearBiasDict3[bbb][1])],\
[np.mean(byYearBiasDict3[bbb][2]),np.std(byYearBiasDict3[bbb][2])],]
byYearBiasDict4={}
ttt=0
for ccc in byYearBiasDict3_2.keys():
byYearBiasDict4[ccc] = byYearBiasDict3_2[ccc]
############ ... | Python | 1 |
#!/usr/bin/env python3
"""
XML 단위별 파서
XML 파일에서 문장(<s>) 단위와 어절(<w>) 단위를 추출하는 기능
"""
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import List, Dict, Any, Tuple
import pandas as pd
import re
class XMLUnitParser:
"""XML 파일에서 문장과 어절 단위를 추출하는 파서"""
def __init__(self):
pass
... | Python | 1 |
.args[0], ast.Name):
arg_name = node.args[0].id
else:
args = ','.join( [self.visit(a) for a in node.args[0].elts] )
if len(node.args[0].elts) == 4: ## simple rule: if there are 4 items, its a direct SIMD type
direct = True
if node.keywords:
for key in node.keywords:
if key.arg == 'dtype':
... | Python | 1 |
s.
"""
X_IGNORE = 0x01
Y_IGNORE = 0x02
Z_IGNORE = 0x04
VX_IGNORE = 0x08
VY_IGNORE = 0x10
VZ_IGNORE = 0x20
AX_IGNORE = 0x40
AY_IGNORE = 0x80
AZ_IGNORE = 0x100
FORCE_SET = 0x200
YAW_IGNORE = 0x400
YAW_RATE_IGNORE = 0x800
class MotorTestOrder(IntEnum):
"""Replica ... | Python | 1 |
de::Serialize, serde::Deserialize))]
pub struct ExecutionPayload<
const BYTES_PER_LOGS_BLOOM: usize,
const MAX_EXTRA_DATA_BYTES: usize,
const MAX_BYTES_PER_TRANSACTION: usize,
const MAX_TRANSACTIONS_PER_PAYLOAD: usize,
> {
pub parent_hash: Hash32,
pub fee_recipient: ExecutionAddress,
pub sta... | Rust | 0 |
[test]
fn f64_ulps_test4() {
let x: f64 = unsafe { mem::transmute(0xd017f6cc63a7f026_u64) };
let y: f64 = unsafe { mem::transmute(0xd017f6cc63a7f023_u64) };
println!("DIST IS {}",x.ulps(&y));
assert!(x.ulps(&y) == 3);
}
#[test]
fn f64_ulps_test5() {
let x: f64 = 2.0;
let ulps: i64 = unsafe { me... | Rust | 0 |
feature
/// matrix will not be normalized by default.
pub fn params() -> ElasticNetParams<F> {
ElasticNetParams::new()
}
/// Create a ridge model
pub fn ridge() -> ElasticNetParams<F> {
ElasticNetParams::new().l1_ratio(F::zero())
}
/// Create a lasso model
pub fn lasso... | Rust | 0 |
_tracing\'"]
impl StructureType {
pub const COPY_MEMORY_TO_ACCELERATION_STRUCTURE_INFO_KHR: Self = StructureType(1_000_150_012);
}
#[doc = "Generated from \'VK_KHR_ray_tracing\'"]
impl StructureType {
pub const PHYSICAL_DEVICE_RAY_TRACING_FEATURES_KHR: Self = StructureType(1_000_150_013);
}
#[doc = "Generated f... | Rust | 0 |
import requests
from concurrent.futures import ThreadPoolExecutor, as_completed
URL = "http://localhost:8000/wardrobe/remove-background"
USER_ID = "fc39d9f5-dfba-4f5f-bc73-f5638f8e6208"
CATEGORY = "tops"
IS_LONG_TOP = False
IMAGE_PATH = "./images/green_sweat.jpg"
def start_job():
with open(IMAGE_PATH, "rb") as im... | Python | 1 |
//let params: Vec<String> = params.into_iter().map(|a| a.as_ref().to_string()).collect();
ctx.tx.query_raw(&sql_text, params).await.map_err(to_anyhow)?
.try_collect().await.map_err(to_anyhow)
};
let filter = QueryFilter::from_filter_input_opt(filter_json)?;
let (_entries, entries_as_typ... | Rust | 0 |
attribs(self, features: list[dict], existing_features: list[dict]) -> list[Feature]:
items = []
features_dict = {x["GIS_ID"]: x for x in features}
for properties in existing_features:
apply_category(Categories.TRANSFORMER, properties)
if properties["ref"] in features_dict... | Python | 1 |
orig_dict[keyname] = value
return orig_dict
def print_dict(val, nesting: int = -4, start: bool = True):
"""Outputs a nested dictionary."""
if isinstance(val, dict):
if not start:
print("")
nesting += 4
for k in val:
print(nesting * " ", end="")
... | Python | 1 |
src=sorted_indices_to_remove
)
# Zero out probabilities for removed tokens
probabilities[indices_to_remove] = 0.0
# Renormalize probabilities
probabilities /= probabilities.sum(dim=-1, keepdim=True)
# Sample... | Python | 1 |
parser.add_argument("--vision_tower", type=str, default="openai/clip-vit-large-patch14-336")
parser.add_argument("--data_path", type=str, required=True)
parser.add_argument("--image_folder", type=str, required=True)
parser.add_argument("--output_dir", type=str, required=True)
parser.add_argument("--... | Python | 1 |
Int8)]
"""
return list(self.values())
@overload
def to_frame(self, *, eager: Literal[False] = ...) -> LazyFrame: ...
@overload
def to_frame(self, *, eager: Literal[True]) -> DataFrame: ...
def to_frame(self, *, eager: bool = True) -> DataFrame | LazyFrame:
"""
Crea... | Python | 1 |
e elements:
1) the loss
2) the sample size, which is used as the denominator for the gradient
3) logging outputs to display while training
"""
net_output = model(**sample["net_input"])
logits = model.get_logits(net_output, sample=sample, **self.kwargs)
# some mode... | Python | 1 |
do * ((k) + l1 * (4))].i = ca.i + cb.i;
ch[(0) + ido * ((k) + l1 * (7))].r = ca.r - cb.r;
ch[(0) + ido * ((k) + l1 * (7))].i = ca.i - cb.i;
}
}
{
let mut ca: cmplx = cmplx { r: 0.0, i: 0.0 };
let mut cb: cmpl... | Rust | 0 |
import torch
import torch.nn.functional as F
class Optimization():
def __init__(self, train_loader, device):
self.train_loader = train_loader
self.device = device
def cdw_feature_distance(self, old_model, old_classifier, new_model):
"""cosine distance weight (cdw): calculate feature d... | Python | 1 |
from flet.core.matplotlib_chart import MatplotlibChart
| Python | 1 |
# Perform stepweight decay
if p.dtype in {torch.float16, torch.bfloat16}:
p_fp32.data.mul_(1 - step_size * weight_decay)
else:
p.data.mul_(1 - step_size * weight_decay)
# p = p - lr * grad / denom... | Python | 1 |
($q.clone());
$crate::conj!($($g),*).iter().map(move |s| s.reify(&var))
}};
(@ $n:expr, $q:ident, $($g:expr),* $(,)?) => {{
let $q = $crate::prelude::Var::new(stringify!($q));
let var = $crate::prelude::Value::var($q.clone());
$crate::conj!($($g),*).run($n).map(move |s| s.reify(... | Rust | 0 |
from words import words
from tkinter import *
import random
from tkinter import messagebox
def slider():
global count,sliderwords
text='Welcome to Typing Speed Calculator!!'
if count>= len(text):
count =0
sliderwords =''
sliderwords += text[count]
count +=1
fontlabel.configure(... | Python | 1 |
G", "Togo"],
"🇹🇭": ["TH", "Thailand"],
"🇹🇯": ["TJ", "Tajikistan"],
"🇹🇰": ["TK", "Tokelau"],
"🇹🇱": ["TL", "East Timor", "Timor-Leste"],
"🇹🇲": ["TM", "Turkmenistan"],
"🇹🇳": ["TN", "Tunisia"],
"🇹🇴": ["TO", "Tonga"],
"🇹🇷": ["TR", "Turkey", "Tür... | Python | 1 |
from fastapi import APIRouter
from lib.api import *
router_it = APIRouter()
@router_it.get("/italy/fixtures-ids")
async def get_fixtures_ids(date:str):
league = "italy"
league_id = 135
season = 2023
return fixtures_ids(league, league_id, season, date)
@router_it.get("/italy/fixtures")
async def get_f... | Python | 1 |
## Demonstrates how to create a "pull" subscription
import win32con
import win32event
import win32evtlog
query_text = '*[System[Provider[@Name="Microsoft-Windows-Winlogon"]]]'
h = win32event.CreateEvent(None, 0, 0, None)
s = win32evtlog.EvtSubscribe(
"System",
win32evtlog.EvtSubscribeStartAtOldestRecord,
... | Python | 1 |
MODE_SET3_R(crate::FieldReader<u32, u32>);
impl REG_GPIO_INT_MODE_SET3_R {
pub(crate) fn new(bits: u32) -> Self {
REG_GPIO_INT_MODE_SET3_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for REG_GPIO_INT_MODE_SET3_R {
type Target = crate::FieldReader<u32, u32>;
#[inline(always)]
fn ... | Rust | 0 |
compact: TargetCompact) -> Self {
Target::from(target_compact).into()
}
}
/// Convert `Target` to `Difficulty`
impl From<Target> for Difficulty {
fn from(target: Target) -> Self {
Difficulty(&*policy::BLOCK_TARGET_MAX / &FixedUnsigned10::from(target))
}
}
/// Convert `FixedUnsigned10` to `... | Rust | 0 |
tap member theo khoang score
match con.zrangebyscore(key,min,max) {
Ok(i) => i,
_ => Vec::new(),
}
}
fn zrangebyscore_withscores(con:&Connection,key:&str,min:f64,max:f64)-> Vec<(String,f64)>{ //--> tra ve tap (member,score) theo khoang score
match con.zrangebyscore_withscores(key,min,max) {... | Rust | 0 |
{
Application(&mut self)
}
}
impl From<*mut c_void> for Application {
fn from(application_ref: *mut c_void) -> Application {
Application(application_ref as ApplicationRef)
}
}
<filename>src/components/mod.rs
mod component;
mod progress_bar;
mod timer;
mod label;
mod group;
pub use compone... | Rust | 0 |
puts error messages and
# it ends up with test failure.
# Restart U-Boot to clear the previous state.
# TODO: Ideally EFI test cases need to be fixed, but it will
# increase the number of system reset.
u_boot_console.restart_uboot()
# setup test environment
check_mksquashfs_version()
ge... | Python | 1 |
ass SelectorList(Immutable):
"""Selector list."""
__slots__ = ("selectors", "is_not", "is_html", "_hash")
selectors: tuple[Selector | SelectorNull, ...]
is_not: bool
is_html: bool
def __init__(
self,
selectors: Optional[Iterable[Selector | SelectorNull]] = None,
is_not... | Python | 1 |
_co_attention_s1,final_co_attention_s2,final_co_attention_s3)
return (torch.cat([score1,score2,score3]),torch.cat([x1s_co,x2s_co,x3s_co]))
# else:
# feature1, cam1, score1=self.vgg(input1)
# return cam1, score1
# return torch.cat([score1,score2])
def get_heatmaps(se... | Python | 1 |
er(&mut system_data, &mut registers, opcode),
0xF2 => read_io_port_with_c_offset_to_accumulator(&mut system_data, &mut registers),
0xF3 => disable_interupts(&mut system_data, &mut registers),
0xF4 => println!("Illegal Opcode - 0x{:X} --- 0x{:X}", registers.program_counter, opcode), // Illegal
0xF5 => push_16_bit_regist... | Rust | 0 |
, SLT_BereqHeader, "Date: Fri, 05 Aug 2016 13:23:34 GMT";
32769, SLT_BereqHeader, "Host: 127.0.0.1:1200";
32769, SLT_BackendOpen, "19 boot.default 127.0.0.1 42000 127.0.0.1 51058";
32769, SLT_VCL_return, "fetch";
32769, SLT_Timestamp, "Bereq: 1... | Rust | 0 |
import re
from itertools import *
from sys import stdin
from collections import defaultdict
sinks = re.compile('to (\w+)')
nums = re.compile(r'(\d+)')
getnums = lambda s: map(int, nums.findall(s))
lines = stdin.readlines()
bots = defaultdict(set)
outs = defaultdict(set)
done = set()
# Keep looping over lines until ... | Python | 1 |
// Make `xs` a heap.
/// `f(x,y)` is whether `x` must be nearer to the root than `y`.
#[inline] pub fn build<A, F: Fn(&A, &A) -> bool>(arity: usize, f: F, xs: &mut [A]) {
if xs.len() <= 1 { return };
for k in (0..xs.len()>>1).rev() { sift_down(arity, &f, xs, k) }
}
/// Given a slice `xs` which is already a hea... | Rust | 0 |
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", match *self {
Error::DeserializeAnyUnsupported => "`bytekey` is not a self-describing format",
Error::UnexpectedEof => "encountered unexpected EOF when deserializing utf8",
... | Rust | 0 |
dropout_rate=dropout_rate,
activations=activations,
optimizer=optimizer)
@property
def target_activation(self):
return "linear"
@target_activation.setter
... | Python | 1 |
{
info!(target: name, "{}ing", operation);
let res = app.switch(config, operation);
if let Err(ref e) = res {
error!(target: name, "{:#}", e);
}
trace!(
target: name,
"completed in {} ms",
(Instan... | Rust | 0 |
# -*- encoding: utf-8 -*-
{
'name': 'Reporte de trazabilidad ',
'version': '10.0',
'author': 'Jaime Guerrero Rangel',
'category': 'Excel',
'description': """
* Este módulo agrega un reporte de excel sobre movimientos de productos.
- Selecciona un producto, almacén y fechas para ... | Python | 1 |
// downstream crates? :/
pub(crate) mod internal {
use std::ops::{Add, Sub, Mul, Div, Neg};
macro_rules! markers {
($( $name:ident[$($bound:tt)+]; )+)
=> {$(
pub trait $name: $($bound)+ { }
impl<T> $name for T where T: $($bound)+ { }
)+};
}
markers... | Rust | 0 |
* mut UCD_info = _UCD_create(core_path.as_ptr());
let mut c = MaybeUninit::uninit();
let _ret = unw_init_remote(c.as_mut_ptr(),asp,ui as * mut libc::c_void );
_UCD_add_backing_file_at_vaddr(ui, test_heap_start, test_heap_path.as_ptr());
_UCD_add_backing_file_at_vaddr(ui... | Rust | 0 |
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# 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 law or... | Python | 1 |
vavg: u16,
#[br(pad_before = 2)]
vrms: u16,
#[br(pad_before = 2)]
vpp: u16,
#[br(pad_before = 2)]
vp: u16,
frequency_high: u16,
frequency_low: u16,
#[br(pad_before = 2)]
cycle_ns: u16,
#[br(pad_before = 2)]
time_plus_ns: u16,
#[br(pad_before = 2)]
time_minus_ns: u... | Rust | 0 |
import sys
from transformers import AutoTokenizer
dataset = sys.argv[1]
model_name_or_path = sys.argv[2]
max_len = int(sys.argv[3])
subword_len_counter = 0
tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)
max_len -= tokenizer.num_special_tokens_to_add()
with open(dataset, "rt") as f_p:
for line i... | Python | 1 |
WoodDresser = 2529,
PalmWoodLantern = 2530,
PalmWoodPiano = 2531,
PalmWoodTable = 2532,
PalmWoodLamp = 2533,
PalmWoodWorkBench = 2534,
OpticStaff = 2535,
PalmWoodBookcase = 2536,
MushroomBathtub = 2537,
MushroomBed = 2538,
MushroomBench = 2539,
MushroomBookcase = 2540,
MushroomCandelabra = 2541,... | Rust | 0 |
ATTR, DrawType, ParsedStyle, R_ATTR};
use super::ViewBox;
pub fn handle_circle<'a>(
context: &mut Context,
circle: roxmltree::Node,
style: Rc<RefCell<ParsedStyle>>,
parent_attributes: Option<HashMap<&str, &str>>,
root: &'a roxmltree::Document<'a>,
) {
let scale = context.device.density;
le... | Rust | 0 |
e(self):
group = Group({"name": "test", "domain": self.user.domain})
group.save()
self.addCleanup(group.delete)
self.commcare_user_updater.update('groups', [group._id])
self.assertIn(GROUPS_FIELD, self.user_change_logger.change_messages.keys())
def test_update_groups_does_no... | Python | 1 |
query::{*, tests_cfg::*};
///
/// let query = Query::select()
/// .from(Char::Table)
/// .column((Char::Table, Char::Character))
/// .to_owned();
///
/// assert_eq!(
/// query.to_string(MysqlQueryBuilder),
/// r#"SELECT `character`.`character` FROM `character`"#... | Rust | 0 |
,
pub normal: Vec3,
pub mat_ptr: Arc<Box<dyn Material + Sync + Send + 'static>>,
pub t: f64,
pub front_face: bool,
}
impl HitRecord {
pub fn from_face_normal(
r: &Ray,
p: Point3,
outward_normal: &Vec3,
t: f64,
mat_ptr: Arc<Box<dyn Material + Sync + Send + 'st... | Rust | 0 |
: u16 = 1;
/// function.
pub const IMAGE_SYM_DTYPE_FUNCTION: u16 = 2;
/// array.
pub const IMAGE_SYM_DTYPE_ARRAY: u16 = 3;
// Values for `ImageSymbol::storage_class`.
pub const IMAGE_SYM_CLASS_END_OF_FUNCTION: u8 = 0xff;
pub const IMAGE_SYM_CLASS_NULL: u8 = 0x00;
pub const IMAGE_SYM_CLASS_AUTOMATIC: u8 = 0x01;
pub con... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.