text string | label_name string | labels int64 |
|---|---|---|
# -*- coding:utf-8 -*-
# ! ./usr/bin/env python
# __author__ = 'zzp'
import cv2
import json
import glob
import numpy as np
from os.path import join
from os import listdir
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--dir',type=str, default='./GOT_10k', help='your got_10k data dir')
args =... | Python | 1 |
# pseudo_labels: pseudo labels, list with the length (selected_nodes_num)
# emb: embeddings of explanations, tensor with the shape (selected_nodes_num, emb_dim)
# pl_mask: pseudo label mask, tensor with the shape (nodes_num)
# return: pseudo_labels with the shape (nodes_num), emb with the shape (nodes_... | Python | 1 |
.filter(|dir_path| Some(&**path) == dir_path.parent())
.map(|dir_path| filename_to_module(dir_path.to_str().unwrap()))
.collect();
reg.render_to_write(
INDEX_TEMPLATE,
&Index {
name,
directories: &directory_modules,
... | Rust | 0 |
_Accounts {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
::protobuf::text_format::fmt(self, f)
}
}
impl ::protobuf::reflect::ProtobufValue for CAccountHardware_QueryAccountsRegisteredToSerial_Accounts {
fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef {
:... | Rust | 0 |
Error::Parse)?
.trim()
.to_lowercase()
.to_owned();
let value = splits.next().ok_or(Error::Parse)?.trim().to_owned();
Ok(MetaTextElement { key, value })
}
}
pub fn get_merged_rfc_metadata() -> Result<Vec<GhMetadata>> {
init_working_repo()?;
let mut text_... | Rust | 0 |
"""
None
"""
from collections import deque
class Solution:
def wallsAndGates(self, rooms: List[List[int]]) -> None:
"""
Do not return anything, modify rooms in-place instead.
"""
def find_neighbors(y, x, rooms):
deltas = [(-1, 0), (0, -1), (0, 1), (1, 0)]
... | Python | 1 |
a = "SELECT * FROM Usuario WHERE cuil = %s OR email = %s"
valores = (cuil_o_email, cuil_o_email)
resultados = self.db.obtener_datos(consulta, valores)
if resultados:
usuario = resultados[0]
codigo = self.generar_codigo_verificacion()
# Guarda el ... | Python | 1 |
th_base_dir<P: AsRef<Path>>(base_dir: P, shards: usize) -> Result<Self> {
fs::create_dir_all(base_dir.as_ref())?;
// check dir
let dir_num = fs::read_dir(base_dir.as_ref())?
.map(|dir| Ok(dir?.file_type()?.is_dir()))
.collect::<Result<Vec<_>>>()?
.len();
... | Rust | 0 |
sert_eq!(
AssetId::from_str("oMb2yzA542yQgwn8XtmGefTzBv5NJ2nDjh").unwrap(),
testnet_asset
);
}
}
use std::convert::{TryFrom, TryInto};
use std::error::Error;
use aya::maps::{MapRefMut, PerfEventArray};
use aya::programs::{tc, Link, SchedClassifier, TcAttachType};
use aya::util::onli... | Rust | 0 |
from django.db import models
class CourseStatusEnum(models.TextChoices):
UPCOMING = "upcoming"
ONGOING = "ongoing"
COMPLETED = "completed"
class CourseLevelStatusEnum(models.TextChoices):
BEGINNER = "beginner"
INTERMEDIATE = "intermediate"
ADVANCED = "advanced"
| Python | 1 |
__all__ = [
"assign",
"costfunc",
"machine",
"optimize",
"state",
"utils",
"vgen"
] | Python | 1 |
mcp":
return {"error": "Invalid URI scheme"}
# Mock data - would fetch from actual API when deployed
resource_data = {
"bondmcp://health/guidelines": {
"type": "health_guidelines",
"data": "[DEVELOPMENT MODE] Health guidelines would be fet... | Python | 1 |
toRegressivePipeline(SklearnPerSegmentModel(ExtraTreesRegressor(n_estimators=100)),
**params)
}
ensebmle_models = [pipelines['CatBoost'], pipelines['RandomForestExtraTrees']]
# усреднение прогнозов базовых моделей
pipelines['VotingEnsemble'] = Vot... | Python | 1 |
after_bool, node, ret=node)
if type(node.value) is int: # noqa: E721
if self.handler_predicate_by_event[TraceEvent.after_int](node):
return self.emit(TraceEvent.after_int, node, ret=node)
if type(node.value) is float: # noqa: E721
if self.han... | Python | 1 |
Rect) -> Mat4 {
let mut result: Mat4 = [0.0; 16];
mat4::perspective(
&mut result,
to_radian(45.0),
rect.width() / rect.height(),
1.0,
Some(100.0),
);
result
}
fn normal_matrix(&self) -> Mat3 {
let mut result: Ma... | Rust | 0 |
istd implementation for Redox, following http://pubs.opengroup.org/onlinepubs/7908799/xsh/unistd.h.html
#![no_std]
extern crate platform;
pub use platform::types::*;
pub const R_OK: c_int = 1;
pub const W_OK: c_int = 2;
pub const X_OK: c_int = 4;
pub const F_OK: c_int = 8;
pub const SEEK_SET: c_int = 0;
pub const ... | Rust | 0 |
from time import sleep
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
# Chrome_driver - Chrome browser
x = 5
service_obj = Service()
driver = webdriver.Chrome(service=service_obj)
driver.maximize_window()
driver.get("https://www.saucede... | Python | 1 |
ain=True, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=2)
# TRAINING UNPRUNED
print('Unpruned:', train_thresholds(torch_model, trainloader, trainset, device))
print('Pruned:', train_thresholds(pruned_to... | Python | 1 |
ze up to minimum alignment
let mut material_stride =
queue.device().physical_device().limits().min_uniform_buffer_offset_alignment() as usize;
material_stride = (size_of::<MaterialUniform>() + material_stride - 1) / material_stride * material_stride;
debug!("material stride: {}", material_stride);
let material_b... | Rust | 0 |
"NVJpA",
"RVM",
"SPEXD",
"CARZ",
"KYNpD",
"UBPSU",
"DATE",
"FFN",
"RLJ",
"BONO",
"FENG",
"MRHpA",
"NGL",
"SAPXD",
"EAGLU",
"BKEP",
"GGE",
"HMNY",
"TTTM",
"TTTM.U",
"UZA",
"HKK",
"ABA.CL",
"AGRG",
"ALZ.CL",
"AMPE",
"CNTR",
"CONG",
"EQIN",
"FTBpC.CL",
"GRPC",
... | Rust | 0 |
#[test]
fn from_alt_url() {
assert_eq!(get_index_url(&prep_config("from_alt_url"), "file:///usr/local/share/cargo"),
Ok(("outside-the-scope-of-this-document".to_string(), "tralternative".into())));
}
#[test]
fn from_name() {
assert_eq!(get_index_url(&prep_config("from_name"), "alternative"),
... | Rust | 0 |
from expressQL import col, cols, text, num, SQLCondition, AndCondition, OrCondition, Func
def arithmetic_comparisons():
print("== Arithmetic Comparisons ==")
age, salary, name = cols("age", "salary", "name")
# Example 1: Simple age > 18
cond1 = age > 18
print("Age > 18:")
print(cond1.sql_strin... | Python | 1 |
lain_read(format!("invokedynamic {} (JVMS§6.5)", CPLookup(&self.cp, CPEntryKind::InvokeDynamicInfo, typ)));
},*/
0xb9 => {
let typ = self.read_cp()?;
let _arg_count = self.read_u8()?; // probably should check this idc
let zero = self.read_u8()?;
if zero != 0 {
panic!("invalid invokeint... | Rust | 0 |
"""
Write a function to remove the parenthesis and what is inbetween them from a string.
assert remove_parenthesis(["python (chrome)"])==("python")
"""
def remove_parenthesis(input_string):
"""
This function takes a string as an argument and returns the string with all parenthesis and their content removed.
... | Python | 1 |
import json
import os
from contextlib import asynccontextmanager
import re
import asyncio
import base64
from fastapi.responses import StreamingResponse
from fastapi.staticfiles import StaticFiles
from fastapi import FastAPI, Request, UploadFile, File,HTTPException,WebSocketDisconnect,WebSocket
from voiceapi.asr import ... | Python | 1 |
"""
Portfolio API routes
"""
from flask import Blueprint, request, jsonify
from api.services.portfolio_service import PortfolioService
bp = Blueprint('portfolio', __name__, url_prefix='/api/portfolio')
portfolio_service = PortfolioService()
@bp.route('/', methods=['GET'])
def get_portfolio():
"""
Get the cur... | Python | 1 |
d2 = c2 - from_user1
to_sell = 0
# --- LOG DATA ---
hours.append(hr)
u1_consumption.append(round(c1, 2))
u1_production.append(round(p1, 2))
u1_battery.append(round(u1['battery'], 2))
u1_sold.append(round(to_sell, 2))
u2_consumption.append(round(c2, 2))
u2_from_user1.append(roun... | Python | 1 |
CONFIG_S {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FISHEYE_CONFIG_S")
.field("au16LMFCoef", &self.au16LMFCoef.to_vec())
.finish()
}
}
// Fix incomplete Eq trait for FISHEYE_CONFIG_S
#[cfg(feature = "mpi-gdc")]
impl Eq for FISHEYE_CONF... | Rust | 0 |
J(7i32),
J(8i32),
]));
expect_count(10, assert_static(prop_oneof![
J(0i32),
J(1i32),
J(2i32),
J(3i32),
J(4i32),
J(5i32),
J(6i32),
J(7i32),
J(8i32),
J(9i32),
]));
... | Rust | 0 |
file_path_list=[r'G:\new\SRR21661947\SRR21661947.out-fanse2high.sorted.bed',
r'G:\new\SRR21661947\SRR21661947.out-splice-high.sorted.bed',
r'G:\new\SRR21661948\SRR21661948.out-fanse2high.sorted.bed',
r'G:\new\SRR21661948\SRR21661948.out-splice-high.sorted.bed',
... | Python | 1 |
import json
from pathlib import Path
class NotebookBuilder:
"""
A class to build a Jupyter notebook programmatically.
"""
def __init__(self):
"""
Initializes a new instance of the NotebookBuilder class.
Sets up the initial structure of the notebook with metadata and an empty ... | Python | 1 |
equence name |
|7 |int |Target sequence length |
|8 |int |Target start on original strand (0-based) |
|9 |int |Target end on original strand (0-based) |
|10 |int |Number of residue matches |
|11 |int |Alignment block length |... | Rust | 0 |
nsafe { (*p).right = w };
}
}
unsafe { (*u).parent = w };
let b = unsafe { (*w).left };
if b == ptr::null_mut() {
unsafe { (*u).right = ptr::null_mut() };
} else {
unsafe { (*b).parent = u };
unsafe { (*u).right = b };
}
... | Rust | 0 |
# Warp https://github.com/mihaidusmanu/d2-net
import os
import sys
import torch
import torch.nn as nn
from xrloc.utils.miscs import get_parent_dir, download_model
sys.path.append(get_parent_dir(__file__) + '/../3rdparty/d2net')
from lib.model_test import D2Net as D2N
from lib.pyramid import process_multiscale
class... | Python | 1 |
# Global singleton instance
_docker_cleaner: Optional[DockerResourceCleaner] = None
def start_docker_cleanup(cleanup_interval_seconds: int = 120):
"""Start the global Docker cleanup service."""
global _docker_cleaner
if _docker_cleaner is None:
_docker_cleaner = DockerResourceCleaner(cleanup_inter... | Python | 1 |
r bidirectional output enable"]
PINCFG_1 = 1,
#[doc = "2: Shifter pin bidirectional output data"]
PINCFG_2 = 2,
#[doc = "3: Shifter pin output"]
PINCFG_3 = 3,
}
impl From<PINCFG_A> for u8 {
#[inline(always)]
fn from(variant: PINCFG_A) -> Self {
variant as _
}
}
#[doc = "Field `PI... | Rust | 0 |
state.handle();
auth.dispatch(&mut handle, request.into()).unwrap()
};
// ----------------------------------------------------
// THEN
// A non-error response is returned and
// the response's error code is Nil and
// the response'... | Rust | 0 |
oducts
eq_Acr=linfunc.cross_product(crR02R13,R13)
Acr_x,Acr_y,Acr_z=sm.symbols('Acr_x Acr_y Acr_z',real=True)
Acr=sm.MutableDenseNDimArray([Acr_x,Acr_y,Acr_z])
for cc in range(3):
Der=Der.subs(eq_Acr[cc],Acr[cc])
eq_Bcr=linfunc.cross_product(crR02R13,R02)
Bcr_x,Bcr_y,Bcr_z=sm.symbols('Bcr_x Bcr_y Bcr_z',real=True)
Bc... | Python | 1 |
e above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE... | Rust | 0 |
import pytest
import sqlalchemy
from testcontainers.core.utils import is_arm
from testcontainers.mssql import SqlServerContainer
@pytest.mark.skipif(is_arm(), reason="mssql container not available for ARM")
@pytest.mark.parametrize("version", ["2022-CU12-ubuntu-22.04", "2019-CU25-ubuntu-20.04"])
def test_docker_run_... | Python | 1 |
// H R H
let mut balls = Balls::new(GridSize(3));
balls.add(Point(0, 0)).unwrap();
balls.add(Point(0, 2)).unwrap();
// Top edge
assert_eq!(Ok(Beam::HeadOn), walk_from_edge(&mut balls, Coord(-1, 0)));
assert_eq!(Ok(Beam::Reflect), walk_from_edge(&mut balls, ... | Rust | 0 |
import unittest
from regex_classifier import *
from utils import prettify_matches
class TestMatchRegex(unittest.TestCase):
def __init__(self, methodName: str = "runTest") -> None:
super().__init__(methodName)
self.clf = RegexClassifier()
def test_matcher(self):
matches = self.clf.match_... | Python | 1 |
#!/usr/bin/env python3
"""
Stage 2 Quality Checks v1
Performs quality validation on synthesized active QA samples.
Checks performed:
- Field completeness
- Clarification questions presence when needed
- Text length thresholds
- Near-duplicate detection using simple hashing
Usage:
python tools/stage2_quality_check... | Python | 1 |
::new(String::from("sq1"), 21, 19, 80, 81),
/// ]);
/// # Ok::<(), io::Error>(())
/// ```
pub fn read_index(&mut self) -> io::Result<Index> {
let mut buf = String::new();
let mut index = Vec::new();
loop {
buf.clear();
match read_line(&mut self.inner, &m... | Rust | 0 |
serializer=serializer,
ctx=ctx,
value_type="int_array_value",
)
if widget_state.value_changed:
proto.value[:] = serializer(widget_state.value)
proto.set_value = True
if ctx:
save_for_app_testing(ctx, element_id, format_fu... | Python | 1 |
import queue
import os
import time
import xlrd
import threading
from lib.log import MY_LOGGER as logger
import random
from config.config import USER_AGENTS, OS, BASE_DIR
from urllib.parse import urlparse
from lib.api_to_ip import Get_Api
from selenium import webdriver
from selenium.webdriver.common.desired_capabilitie... | Python | 1 |
if teacher_answer == winner:
gt = {"answer": f"[[Solution]]:\nLet's think step by step.\n\n{gt_rationale}\n\n[[Final Answer]]:\n${gt_answer}$\n"}
exam = {"rationale": teacher_rationale}
accuracy[dim] += scorer.score_exam_result(gt, exa... | Python | 1 |
ica/Menominee', 'America/Menominee'), ('Pacific/Ponape', 'Pacific/Ponape'), ('Mexico/BajaSur', 'Mexico/BajaSur'), ('Australia/NSW', 'Australia/NSW'), ('Asia/Krasnoyarsk', 'Asia/Krasnoyarsk'), ('Asia/Damascus', 'Asia/Damascus'), ('Europe/Busingen', 'Europe/Busingen'), ('Indian/Mayotte', 'Indian/Mayotte'), ('America/Mana... | Python | 1 |
import unittest
import numpy as np
from laika import AstroDog
from laika.helpers import ConstellationId
from laika.raw_gnss import correct_measurements, process_measurements, read_raw_ublox
from laika.opt import calc_pos_fix
from selfdrive.test.openpilotci import get_url
from tools.lib.logreader import LogReader
de... | Python | 1 |
#소프트맥스 함수의 특징
'''
1) 소프트맥스 함수의 출력은 0~1.0 사이의 실수이다.
2) 소프트맥스 함수의 출력의 총합은 1이다.
-> 소프트맥스 함수의 출력을 '확률'로 해석할 수 있다.
y[0]의 확률은 0.018%(1.8%), y[1]의 확률은 0.245%(24.5%), y[2]의 확률은 0.737%(73.7%)
-> 소프트맥스 함수를 이용함으로써 문제를 확률적(통계적)으로 대응할 수 있다.
소프트맥스 함수를 적용해도 각 원소의 대소 관계는 변하지 않는다.
-> 지수 함수 y=exp(x)가 단조 증가 함수이기 때문.
신경망을 이용한 분류에서는 일... | Python | 1 |
occurred"]
EVT_SCHDL_ENTRY_ERROR_1 = 1,
}
impl From<EVT_SCHDL_ENTRY_ERROR_A> for bool {
#[inline(always)]
fn from(variant: EVT_SCHDL_ENTRY_ERROR_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `EVT_SCHDL_ENTRY_ERROR`"]
pub type EVT_SCHDL_ENTRY_ERROR_R = crate::R<bool, EVT_SCHDL_ENT... | Rust | 0 |
to the original image, minus 1.
/// This value represents the size of the entire palette from which the colors in the
/// graphic were selected, not the number of colors actually used in the graphic.
/// For example, if the value in this field is 3, then the palette of the original image
/// had 4 ... | Rust | 0 |
}
}
}
pub fn register_transfer_transaction_module(ctx: &mut ModuleContext) -> NeonResult<()> {
let js_object = JsObject::new(ctx);
let build_incomplete_hex_linear_fee_fn = JsFunction::new(ctx, build_incomplete_hex_linear_fee)?;
js_object.set(
ctx,
"buildIncompleteHexLinearFee",
... | Rust | 0 |
me): The DataFrame containing the column to be transformed.
fit_column (str): The name of the column to be transformed.
distribution_strategy (Literal['uniform', 'normal'], optional): The distribution strategy to be used. Defaults to "uniform".
save_name_transformation (str, optional): The name ... | Python | 1 |
let t = ms as f32 / 1000.0;
let pos = traj.position(t);
println!(
"{:04} -> {}",
ms,
pos.map(|(p, _accel)| p.to_string())
.unwrap_or_else(String::new)
);
}
}
}
<filename>src/test/run-pass/higher-rank-t... | Rust | 0 |
self._generate_u(num_samples),
mean_function=self.mean_function,
sample_axis=sample_axis,
**kwargs)
def _generate_u(self, num_samples: int, L: tf.Tensor = None):
"""
Returns samples $u ~ q(u)$.
"""
q_s... | Python | 1 |
// }
// });
// self.rooms.push(room)
// }
// }
// }
// fn apply_horizontal_tunnel(&mut self, x1: i32, x2: i32, y: i32) {
// use std::cmp::{max, min};
// for x in min(x1, x2)..=max(x1, x2) {
// if l... | Rust | 0 |
#使用
import numpy as np
import cv2
# 初始化参数
board_cols = 7 #橫向角點個數(行數-1)
board_rows = 4 #直向角點個數(列數-1)
square_size = 35.0 #一小方格邊長
# 准备物体点
objp = np.zeros((board_cols * board_rows, 3), np.float32)#三維點座標
objp[:, :2] = np.mgrid[0:board_cols, 0:board_rows].T.reshape(-1, 2)
objp *= square_size
# 打印物体点以确认
print("Object P... | Python | 1 |
ar-module-left.html")),
(EDIT_MODULE_RIGHT, include_str!("../../../../../../.template_output/jig/edit/sidebar-module-right.html")),
(EDIT_MODULE_DRAG_SLOT, include_str!("../../../../../../.template_output/jig/edit/sidebar-module-drag-slot.html")),
(EDIT_MODULE_SELECTION, include_str!... | Rust | 0 |
c_address(&self) -> Address {
let secp = Secp256k1::signing_only();
let public_key = PublicKey::from_secret_key(&secp, &*self).serialize_uncompressed();
// NOTE: An ethereum address is the last 20 bytes of the keccak hash of
// the public key. Note that `libsecp256k1` public key is se... | Rust | 0 |
cerramiento interior sobre este espacio
Tilt::BOTTOM => w.nextto.as_ref().map(|s| s == &spaceid).unwrap_or(false),
_ => false,
}
})
}
/// Grosor de un elemento opaco
fn wall_thickness(&self, wallid: &str) -> f32 {
self.get_wall(wallid)
... | Rust | 0 |
Long rate of change period. Default is `14`.
///
/// Range in \(`period3`; [`PeriodType::MAX`](crate::core::PeriodType)\).
pub period2: PeriodType,
/// Short rate of change period. Default is `11`.
///
/// Range in \[`1`; `period2`\).
pub period3: PeriodType,
/// Signal 2 reverse points left limit. Default i... | Rust | 0 |
Pubkey,
market: Pubkey,
event_queue: Pubkey,
bids: Pubkey,
asks: Pubkey,
authority: Pubkey,
lamports_target_account: Pubkey,
) -> Instruction {
let data = AgnosticOrderbookInstruction::CloseMarket
.try_to_vec()
.unwrap();
let accounts = vec![
AccountMeta::new(mar... | Rust | 0 |
# Databricks notebook source
# MAGIC %md
# MAGIC # Final Visualization
# COMMAND ----------
# MAGIC %md
# MAGIC Obtain the job parameter and store it in the variable **my_catalog**.
# COMMAND ----------
my_catalog = dbutils.widgets.get('catalog_name')
target = dbutils.widgets.get('target')
print(f'Accessing the {ta... | Python | 1 |
luate_division;
mod s0400_nth_digit;
use std::env;
use std::fmt;
use std::fs::File;
use std::io::{self, BufRead};
use std::process;
#[derive(Debug)]
enum InputError {
InvalidLineFormat,
InvalidMinMax,
InvalidLetter,
}
impl fmt::Display for InputError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Res... | Rust | 0 |
self.content = Some(content);
}
/// Return the `MiniON` as a `String`.
/// ## Example
/// ```
/// use minimal_object_notation::*;
///
/// let mut minion = MiniON::new("greeting".to_string());
///
/// minion.set_content("Hello, world!".to_string());
///
... | Rust | 0 |
> 16 & 0xFFFF) as u16,
}
}
}
#[repr(C)]
pub struct Registers {
ds: u32,
edi: u32,
esi: u32,
ebp: u32,
esp: u32,
ebx: u32,
edx: u32,
ecx: u32,
eax: u32,
pub interrupt: u32,
error: u32,
eip: u32,
cs: u32,
eflags: u32,
useresp: u32,
ss: u32,
}
... | Rust | 0 |
5796e876114af58a60a1](https://glm.g-truc.net/0.9.4/api/a00151.html#gae2dca3785b6d5796e876114af58a60a1)
pub fn look_at(pos: Vec3, target: Vec3, up: Vec3) -> Mat4 {
let zaxis: Vec3 = (target - pos).normalize();
let xaxis = zaxis.cross(up).normalize();
let yaxis = xaxis.cross(zaxis);
Mat4::mat4([
... | Rust | 0 |
always)]
pub fn i2c_0(self) -> &'a mut W {
self.variant(SLAVE_SEL_A::I2C_0)
}
#[doc = "Select i2c_1 as the sensor that will be accessed by the Wishbone Master"]
#[inline(always)]
pub fn i2c_1(self) -> &'a mut W {
self.variant(SLAVE_SEL_A::I2C_1)
}
#[doc = "Select spi_0 as the... | Rust | 0 |
used_registers = used_registers.with(dest_reg);
instructions.push(format!("movq {},%{}", lhs_loc, dest_reg));
instructions.append(&mut rhs_ins);
Loc::Register(dest_reg)
},
// Nowhere is safe! Store LHS on the stack
None => {
let lhs_in_reg = matc... | Rust | 0 |
import os
import argparse
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description="SORT demo")
parser.add_argument(
"--scene_idxes_file",
type=str,
help="File containing idxes of scenes to run tracking",
)
parser.add_argument(
"--... | Python | 1 |
}
Err(error::Error::InvalidOperatorType {
expected: "Vector".to_owned(),
found: self.type_name().to_owned(),
})
}
pub fn get_raster(self) -> Result<Box<dyn RasterOperator>> {
if let TypedOperator::Raster(o) = self {
return Ok(o);
}
Er... | Rust | 0 |
self.tx[idx], data_u16[idx]) };
}
// Handle final byte of odd-sized transfers
if data.len() & 1 == 1 {
self.tx[data_u16.len()] = data[data.len() - 1] as u16;
}
}
/// Copy rx buffer into `data`
pub fn read_rx(&self, btable: &BTableRow, data: &mut [u8]) ->... | Rust | 0 |
();
(eth_private_key, ton_private_key)
}
#[test]
fn test_sign() {
let message_text = b"hello_world1";
let (private_key, _) = default_keys();
let signer = EthSigner::new(private_key);
let res = signer.sign(message_text);
let expected = hex::decode("ff244ad55... | Rust | 0 |
self == EXTIPSEL0R::PORTC
}
#[doc = "Checks if the value of the field is `PORTD`"]
#[inline]
pub fn is_portd(&self) -> bool {
*self == EXTIPSEL0R::PORTD
}
#[doc = "Checks if the value of the field is `PORTE`"]
#[inline]
pub fn is_porte(&self) -> bool {
*self == EXTIPSEL0R... | Rust | 0 |
for example
//! a spritemap.
//!
//! [embedded-graphics]: https://docs.rs/embedded-graphics
//! [`Pixel`]: ./drawable/struct.Pixel.html
//! [`Point`]: ./geometry/struct.Point.html
//! [`Size`]: ./geometry/struct.Size.html
//! [`Drawable`]: ./drawable/trait.Drawable.html
//! [`DrawTarget`]: ./draw_target/trait.DrawTa... | Rust | 0 |
test channel".to_string(),
description: None,
banner_id: None,
})
.await;
client
.test(Request {
channel_id: channel.id,
})
.await;
}
}
use grid::DIRECTIONS;
use prelude::*;
use rand::{thread_rng, Rn... | Rust | 0 |
import torch
import torch.nn.functional as F
import torch.nn.functional as F
import torch
def _dpc_knn_single(video_tensor: torch.Tensor, k: int, n_to_keep: int) -> torch.Tensor:
"""
(内部帮助函数) 根据DPC-KNN算法从单个视频样本中选择关键token。
Args:
video_tensor (torch.Tensor): 输入的单个视频token张量,形状为 [token_number, chann... | Python | 1 |
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def __str__(self):
return f"Name is {self.name}\nSalary is {self.salary}"
@staticmethod
def Pro_fund(amt):
return amt * 0.05
emp1 = Employee("Micheal", 60000)
print(emp1)
print(... | Python | 1 |
tts: Some("面具"),
keywords: &["假扮", "匿名", "眼鏡", "面", "面具", "鼻"],
},
#[cfg(feature = "yue_Hans")]
crate::Annotation {
lang: "yue_Hans",
tts: Some("面具"),
keywords: &["假扮", "匿名", "眼镜", "面", "面具", "鼻"],
},
#[cfg(feature = "zh")... | Rust | 0 |
from rest_framework import viewsets
from hectareas.serializers import HectareasSerializer
from hectareas.models import Hectareas
from drf_yasg.utils import swagger_auto_schema # type: ignore
from drf_yasg import openapi # type: ignore
# Create your views here.
class HectareasView(viewsets.ModelViewSet):
seria... | Python | 1 |
"""
Tracing init
# Automatically patch all supported libraries when this module is imported
"""
from ddtrace import patch
patch(sqlalchemy=True, structlog=True, requests=True, psycopg=True, botocore=True)
| Python | 1 |
the processing of
//! \.{\\halign} and \.{\\valign}, since the appearance of tab marks and
//! \.{\\cr} in certain places is supposed to trigger the beginning of special
//! \<v_j> template text in the scanner. This magic is accomplished by an
//! |align_state| variable that is increased by~1 when a `\.{\char'173}' is
... | Rust | 0 |
use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not claim
* that you wrote... | Rust | 0 |
import re
from langchain_core.agents import AgentAction, AgentFinish
from .agent_scratchpad import _format_docs
def extract_between_tags(tag: str, string: str, strip: bool = True) -> str:
ext_list = re.findall(f"<{tag}\s?>(.+?)</{tag}\s?>", string, re.DOTALL)
if strip:
ext_list = [e.strip() for e in... | Python | 1 |
/// skipped.
async fn l1_balances(&self) -> Result<(BigUint, BigUint), ClientError> {
let ethereum = self.wallet.ethereum(&self.config.web3_url).await?;
let eth_balance = ethereum.balance().await?;
let erc20_balance = ethereum
.erc20_balance(self.wallet.address(), self.main_to... | Rust | 0 |
# 题目:nums1 中数字 x 的 下一个更大元素 是指 x 在 nums2 中对应位置 右侧 的 第一个 比 x 大的元素。
# 思路:和739类似,前者保存的是索引,本题保存的是元素值,
# 我们先去遍历nums,如果找到异常值,再去nums1匹配,如果存在就保存结果
# 标准写法
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
result = [-1]*len(nums1)
stack = [0]
for i in rang... | Python | 1 |
ub id: usize,
}
// Actor definition
pub struct GlimmerInstance {
pub id: usize,
sender: Sender<Messages>,
manager: Addr<GlimmerManager>,
kill_handle: Option<SpawnHandle>,
}
impl Actor for GlimmerInstance {
type Context = Context<Self>;
fn stopped(&mut self, _ctx: &mut Self::Context) {
... | Rust | 0 |
<div style='display: inline-block; background-color: #f8f9fa; border: 1px solid #dee2e6; padding: 10px; border-radius: 15px; max-width: 70%;'>
{message.content}
</div>
</div>
""", unsafe_allow_html=True)
st.caption(f"{... | Python | 1 |
icycle"
2: 15, # "motorcycle"
3: 18, # "truck"
4: 20, # "other-vehicle"
5: 30, # "person"
6: 31, # "bicyclist"
7: 32, # "motorcyclist"
8: 40, # "road"
9: 44, # "parking"
10: 48, # "sidewalk"
11: 49, # "other-ground"
12: 50, # "building"
13: 51, # "fence"
1... | Python | 1 |
from hachoir.field import joinPath, MissingField
class EditorError(Exception):
pass
class FakeField(object):
"""
This class have API looks similar to Field API, but objects don't contain
any value: all values are _computed_ by parent methods.
Example: FakeField(editor, "abc").size calls editor.... | Python | 1 |
{
state: AccountState::Initialized,
owners: btreemap! {Pubkey::from_str("<KEY>").unwrap() => 1000},
max_owners: 101,
};
let recovery_keys = btreemap! {
Pubkey::from_str("<KEY>").unwrap() => 1,
};
assert_eq!(
Processor::process_in... | Rust | 0 |
# coding=utf-8
# Copyright 2021-present, the Recognai S.L. team.
#
# 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 ... | Python | 1 |
# Copyright 2020 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 to use, ... | Python | 1 |
acing_subscriber::EnvFilter::from_default_env())
.try_init()
.map_err(|e| anyhow::anyhow!(e))?;
let mut app = viz::new();
let config = app.config().await;
dbg!(&config);
let users = Users::default();
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
sub: Strin... | Rust | 0 |
class Solution:
def diStringMatch(self, s: str) -> List[int]:
ans = []
mini = 0
maxi = len(s)
for c in s:
if c == 'I':
ans.append(mini)
mini += 1
else:
ans.append(maxi)
maxi -= 1
return ans + [mini]
| Python | 1 |
e-components|dash-html-components' // 'all')."
" The default argument is 'all'.",
default="all",
)
parser.add_argument(
"--concurrency",
type=int,
default=3,
help="Maximum concurrent steps, up to 3 (ie all components in parallel)",
)
parser.add_argument(
... | Python | 1 |
from neo4j import GraphDatabase
import json
import os
from dotenv import load_dotenv
# Load .env
load_dotenv()
# Neo4j credentials
NEO4J_URI = os.getenv("NEO4J_URI") or "bolt://localhost:7687"
NEO4J_USERNAME = os.getenv("NEO4J_USERNAME") or "neo4j"
NEO4J_PASSWORD = os.getenv("NEO4J_PASSWORD") or "leomessi"
driver = ... | Python | 1 |
import os
from pathlib import Path
from dotenv import load_dotenv
def load_env():
"""Load environment variables from the project root .env file."""
env_path = Path(__file__).resolve().parent.parent / '.env'
if env_path.exists():
load_dotenv(env_path)
else:
# fallback: load default envi... | Python | 1 |
buff.writeIndentedLines("{name}.setAutoDraw(true);\n".format(**self.params))
buff.writeIndentedLines("{name}.play();\n".format(**self.params))
# because of the 'if' statement of the time test
buff.setIndentLevel(-1, relative=True)
buff.writeIndented("}\n\n")
if self.par... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.