text string | label_name string | labels int64 |
|---|---|---|
from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
# Initialize the FastAPI app
app = FastAPI()
# ----------------------------
# Middleware Configuration
# ----------------------------
# Enable CORS to allow requests from the frontend application (e.g., local... | Python | 1 |
n `2`.
"""
# STACK
pass
# GAS
charge_gas(evm, GAS_BASE)
# OPERATION
push(evm.stack, U256.from_be_bytes(evm.message.block_env.prev_randao))
# PROGRAM COUNTER
evm.pc += Uint(1)
def gas_limit(evm: Evm) -> None:
"""
Push the current block's gas limit onto the stack.
He... | Python | 1 |
"""Secret Manager resolution helpers.
Provides thin wrappers to access secrets and resolve the Surfe API credentials
and base URL with orderly fallbacks (Secret Manager → env → default).
"""
from __future__ import annotations
import os
from typing import Optional
from google.cloud import secretmanager
def access_... | Python | 1 |
: usize, event: ContextMenuEvent) -> Msg {
event.prevent_default();
Msg::RightPick(idx)
}
fn main() {
web_logger::init();
yew::initialize();
let app: App<_, Model> = App::new(());
app.mount_to_body();
yew::run_loop();
trace!("Started");
}
<gh_stars>0
// Copyright 2017 Parity Technologie... | Rust | 0 |
eam_0',
'alias_model_id': crm_lead_model_id,
'alias_parent_model_id': crm_team_model_id,
'alias_parent_thread_id': crm_team0.id,
'alias_defaults': "{'type': 'opportunity', 'team_id': %s}" % crm_team0.id,
})
mail_alias1 = self.env['mail.alias'].create({
... | Python | 1 |
#!/usr/bin/env python3
"""
change school topic
"""
import pymongo
def update_topics(mongo_collection, name, topics):
"""
update many rows
"""
return mongo_collection.update_many(
{"name": name},
{"$set": {"topics": topics}}
)
| Python | 1 |
if self.interrupt_should_trigger(InterruptFlags::VBLANK) {
InterruptFlags::VBLANK
} else if self.interrupt_should_trigger(InterruptFlags::LCD) {
InterruptFlags::LCD
} else if self.interrupt_should_trigger(InterruptFlags::TIMER) {
InterruptFlags::TIMER
} else i... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Description: Create a Plex collection from a text file list of rating keys.
# Author: /u/SwiftPanda16
# Requires: plexapi, requests
import requests
from plexapi.server import PlexServer
### EDIT SETTINGS ###
PLEX_URL = 'http://localhost:32400'
PLEX_TOKEN... | Python | 1 |
`, and `z` and `w` from `vec2`.
pub fn shuffle_merge<const X: u32, const Y: u32, const Z: u32, const W: u32>(vec1: Vector, vec2: Vector) -> Self {
let data = unsafe {
(
from_raw_parts((&vec1 as *const Vector) as *const f32, 4),
from_raw_parts((&vec2 as *const Vector) as *const f32, 4),
)
};
Self {... | Rust | 0 |
rmal for initialization
# # cf https://github.com/pytorch/pytorch/pull/5617
# module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
# if module.bias is not None:
# module.bias.data.zero_()
# elif isinstance(module, nn.Embedding):
# ... | Python | 1 |
import plotly.graph_objects as go
from enforce_typing import enforce_types
from plotly.subplots import make_subplots
from pdr_backend.statutil.seasonal import SeasonalPlotdata
colors = ["black", "blue", "green", "red"]
minor = {"ticks": "inside", "showgrid": True}
@enforce_types
def plot_relative_energies(seasonal_... | Python | 1 |
1000668);
keysyms.insert("Arabic_9", 0x1000669);
keysyms.insert("Arabic_semicolon", 0x05bb);
keysyms.insert("Arabic_question_mark", 0x05bf);
keysyms.insert("Arabic_hamza", 0x05c1);
keysyms.insert("Arabic_maddaonalef", 0x05c2);
keysyms.insert("Arabic_hamzaonalef", 0x05c3);
keysyms.insert("Arabic_hamzaonwaw... | Rust | 0 |
raise Exception( "TestMemory doesn't know how to handle message type {}"
.format( memreq.type_ ) )
#-----------------------------------------------------------------------
# line_trace
#-----------------------------------------------------------------------
def line_trace... | Python | 1 |
in 0..(*A).count {
let h = c2PlaneAt(A, i);
let idx = c2Support((*B).verts, (*B).count, c2Mulrv(a_in_b.r, c2Neg(h.n)));
let p = c2Mulxv(b_in_a, (*B).verts[idx as usize]);
let d = c2Dist(h, p);
if d > sep {
sep = d;
index = i;
}
}
*face_ind... | Rust | 0 |
_count());
assert_eq!(((cost1 + cost2) / 2 + cost2) / 2, testee.get_average());
assert_eq!((cost1 + cost2) / 2, testee.get_mode());
assert_eq!(&((cost1 + cost2) / 2), testee.get_cost(&key1).unwrap());
assert_eq!(&cost2, testee.get_cost(&key2).unwrap());
}
#[test]
fn test_exe... | Rust | 0 |
from __future__ import annotations
import numpy as np
from pydantic import BaseModel, ConfigDict
class CACipherParams(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
gens: int
ps: list[int]
idl_points: np.ndarray = np.empty(0, dtype=int)
def validate_idl_points(self, dim: in... | Python | 1 |
from typing import Optional
from runtime.entities.document_entities import Document
from runtime.rag.retrieve.rerank_base import BaseRerankRunner
from runtime.rag.retrieve.rerank_factory import RerankFactory
from runtime.rag.retrieve.retrieve import RerankMode, CosineWeight
class RerankProcessor:
def __init__(se... | Python | 1 |
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
n = len(triangle)
dp = [[0] * n for _ in range(n)]
for j in range(n):
dp[n - 1][j] = triangle[n - 1][j]
print(dp)
for i in range(n - 2, -1, -1):
for j in range(i... | Python | 1 |
",
"AsyncFineTuningWithRawResponse",
"FineTuningWithStreamingResponse",
"AsyncFineTuningWithStreamingResponse",
"VectorStores",
"AsyncVectorStores",
"VectorStoresWithRawResponse",
"AsyncVectorStoresWithRawResponse",
"VectorStoresWithStreamingResponse",
"AsyncVectorStoresWithStreaming... | Python | 1 |
).with_stderr_does_not_contain("[..][FIXING][..]")
.run();
}
#[test]
fn fix_path_deps() {
let p = project()
.file(
"Cargo.toml",
r#"
[package]
name = "foo"
version = "0.1.0"
[dependencies]
bar =... | Rust | 0 |
able for the `fimo-core` interface.
///
/// [`ModuleInterface`]: fimo_module_core::rust::ModuleInterface
#[macro_export]
macro_rules! fimo_core_interface_impl {
(id) => {
"fimo::interface::core"
};
(version) => {
$crate::rust::INTERFACE_VERSION
};
(to_ptr, $vtable: expr) => {
... | Rust | 0 |
# YOLOv3 🚀 by Ultralytics, AGPL-3.0 license
"""AutoAnchor utils."""
import random
import numpy as np
import torch
import yaml
from tqdm import tqdm
from utils import TryExcept
from utils.general import LOGGER, TQDM_BAR_FORMAT, colorstr
PREFIX = colorstr("AutoAnchor: ")
@TryExcept(f"{PREFIX}ERROR")
strid... | Python | 1 |
.as_raw())?;
let error = eps.compute_error(i, slepc_sys::EPSErrorType::EPS_ERROR_RELATIVE)?;
let (re, im) = (kr, ki);
world.print(&format!("{:9.6} {:9.6}i {:12.2e} \n", re, im, error))?;
}
#[cfg(feature = "gnuplot")]
{
let (istart, iend) = xr.get_ownership_range()?;
... | Rust | 0 |
"""Adjustment options screen object are define here"""
from page_objects.common_objects import CommonObjects
class AdjustmentOptions(CommonObjects):
adjustment_option_xpath = {
"saveButton": "//body/div[@id='__nuxt']/div[@id='__layout']/div[@id='inspire']/div[1]/main[1]/div[1]/div[1]"
... | Python | 1 |
import requests
import json
#functions
def ziptogps(zipcode):
urltemp="https://atlas.microsoft.com/search/address/json?&subscription-key={{your_subscription_key}}}&api-version=1.0&language=en-US&query="+str(zipcode)+",USA"
response1 = requests.get(urltemp)
if response1.status_code == 200:
data1 = r... | Python | 1 |
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
import time
# Configurar el navegador (asegúrate de tener ChromeDriver instalado)
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)
driver.g... | Python | 1 |
# Atividade 08:
# Média de Notas:
# Desenvolva um programa que solicite as notas dos alunos até
# que o usuário digite -1. Calcule e exiba a média das notas
# inseridas.
cont = 0
soma = 0
media = 0
n1 = 0
while n1 != -1:
n1 = float(input("Enter the note: "))
cont += 1
if n1 != -1:
soma += n1
media = soma ... | Python | 1 |
from django import forms
from .models import booking,reserve
class bookingForm(forms.ModelForm):
class Meta:
model = booking
fields = '__all__'
class reserveForm(forms.ModelForm):
class Meta:
model = reserve
fields = '__all__'
| Python | 1 |
$crate::_color_spec_inner!(@acc($acc), @rest($($rest)*))
};
(@acc($acc:expr), @rest(Fg($color:expr) $($rest:tt)*)) => {
$crate::_color_spec_inner!(@acc($acc.set_fg(::std::option::Option::Some($color))), @rest($($rest)*))
};
(@acc($acc:expr), @rest(Bg($color:expr) $($rest:tt)*)) => {
... | Rust | 0 |
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file ex... | Python | 1 |
"""Indy non-revocation interval."""
from time import time
from typing import Optional
from marshmallow import EXCLUDE, fields
from ...messaging.models.base import BaseModel, BaseModelSchema
from ...messaging.valid import INT_EPOCH_EXAMPLE, INT_EPOCH_VALIDATE
class IndyNonRevocationInterval(BaseModel):
"""Indy ... | Python | 1 |
;
insert_into(commits::table)
.values(vec![
NewCommitModel {
commit_id: "first:sawtooth".into(),
commit_num: 1,
service_id: None,
},
// service 1
NewCommitModel {
... | Rust | 0 |
atchStatus::Rejected).await;
assert!(matches!(rx.try_next(), Err(mpsc::TryRecvError { .. })));
}
#[tokio::test]
async fn smoke() {
let (hosts, partitions, mut rx) = smoke_start(StatusCode::OK, BatchStatus::Delivered).await;
for _ in 0..partitions.len() {
let output = rx... | Rust | 0 |
"),
VfioError::IommuDmaUnmap => write!(f, "failed to remove guest memory map from iommu table"),
VfioError::VfioDeviceGetIrqInfo => write!(f, "failed to get vfio device irq info"),
VfioError::VfioDeviceSetIrq => write!(f, "failed to set vfio deviece irq"),
}
}
}
struct V... | Rust | 0 |
o::NodeInfo>, id : u32) -> Result<ArRmRs<chord_node::ChordNode>, chord_util::GeneralError> {
// TODO: ここでのロックをはじめとしてRust実装ではロック対象を更新するか否かでRWロックを使い分けるようにする. at find_successor
// そうでないと、少なくともglobal_xxxの呼び出しを同一ノードもしくは、いくつかのノードに行うような運用でクエリが並列に
// 動作せず、パフォーマンスが出ないはず
// TODO: 実システム化する際か、シミュレータでもノ... | Rust | 0 |
nning', False)}")
# 比较统计信息
stats_before = status_before.get('stats', {})
stats_after = status_after.get('stats', {})
logger.info(f"统计信息变化:")
logger.info(f" 操作次数: {stats_before.get('total_operations', 0)} -> {stats_after.get('total_op... | Python | 1 |
del.state_dict(),
"model": pruned_model,
}
torch.save(checkpoint, model_path)
prun_iter_cnt += 1
time_elapsed = time.time() - since
print(
"This iteration took {:.0f}m {:.0f}s".format(
time_elapsed // 60, time_elapsed % 60
)
... | Python | 1 |
h self {
NodeContact::Enr(enr) => Some(enr.seq()),
_ => None,
}
}
pub fn public_key(&self) -> CombinedPublicKey {
match self {
NodeContact::Enr(ref enr) => enr.public_key(),
NodeContact::Raw { public_key, .. } => *public_key.clone(),
}
... | Rust | 0 |
` may differ, but `s.parse()` and `s_.parse()` must be same
let d_ = match s_.parse::<NaiveDateTime>() {
Ok(d) => d,
Err(e) => {
panic!("`{}` is parsed into `{:?}`, but reparsing that has failed: {}", s, d, e)
}
};
assert!(
d == d_,... | Rust | 0 |
)
.arg(
Arg::with_name("powershell")
.short("p")
.long("powershell"))
)
}
extern crate parking_lot;
use parking_lot::RwLock;
use std::cell::UnsafeCell;
use std::cmp::Ordering;
use st... | Rust | 0 |
dItemResult_t>() as i32;
unsafe fn from_raw(raw: *mut libc::c_void) -> Self {
let val = &mut *(raw as *mut sys::DownloadItemResult_t);
if val.m_eResult == sys::EResult::k_EResultOK {
Ok(DownloadItemResult {
app_id: AppId(val.m_unAppID),
published_file_id:... | Rust | 0 |
from PIL import Image
# this neat function is based on easy-thumbnails
def scale_and_crop(image, size, crop=False, upscale=False, quality=None):
"""
Resize, crop and/or change quality of an image.
:param image: Source image file
:param type: :class:`django.core.files.images.ImageFile`
:param siz... | Python | 1 |
Mode::S_IRWXU.bits())
})
}
#[cfg(not(any(target_os = "android", target_os = "linux", target_os = "freebsd")))]
{
let _ = name;
Err(nix::Error::Sys(errno::Errno::ENOSYS))
}
};
#[cfg(all(unix, not(any(target_os = "ios", target_os = "macos"))))] // can't read/write on mac
let ret = ret.or_else(|_e| {
... | Rust | 0 |
.sort(key=lambda f: int(''.join(filter(str.isdigit, f))));
# Else open the unique image
else:
image = cv2.imread(args.image_path);
frame_index = 0;
step = 1;
while True:
#######################################################
## Show Trajectories
##################... | Python | 1 |
());
ret
}
#[test]
fn t() {
let (cx, _) = get();
assert!(cx.errors.is_empty());
}
<filename>src/libstd/macros.rs
//! Standard library macros
//!
//! This modules contains a set of macros which are exported from the standard
//! library. Each macro is available for use when linking against the standard
//! librar... | Rust | 0 |
-> Vector2<f32> {
let width = Self::WIDTH as f32;
let height = Self::ONE_GLYPH_HEIGHT as f32;
Vector2(width,height)
}
/// Do operation on borrowed texture data. Panics, if inside `operation` the texture data will
/// be borrowed again (e.g. by calling `with_borrowed_data`.
pub ... | Rust | 0 |
ncode for RefuseReason {
fn encode<W: encode::Write>(&self, e: &mut Encoder<W>) -> Result<(), encode::Error<W::Error>> {
match self {
RefuseReason::VersionMismatch(versions) => {
e.array(2)?;
e.u16(0)?;
e.array(versions.len() as u64)?;
... | Rust | 0 |
import pytest
import torch
from vap.audio import load_waveform
import vap.transforms as VT
import vap.functional as VF
BATCH_SIZE = 4
SAMPLE_RATE = 16_000
@pytest.fixture
def waveform():
x, _ = load_waveform(
"example/student_long_female_en-US-Wavenet-G.wav", sample_rate=SAMPLE_RATE
)
x = torch.... | Python | 1 |
assert pytest.raises(TypeError, diagonalize_pauli_word, non_pauli_word)
qwc_diagonalization_io = [
(
[PauliX(0) @ PauliY(1), PauliX(0) @ PauliZ(2)],
(
[RY(-np.pi / 2, wires=[0]), RX(np.pi / 2, wires=[1])],
[PauliZ(wires=[0]) @ PauliZ(wires=[1]), Pau... | Python | 1 |
umulatorStoreType,
hash: HashValue,
) -> Result<Option<AccumulatorNode>> {
self.node_store.get(Self::get_store_key(store_type, hash))
}
fn multiple_get(
&self,
_store_type: AccumulatorStoreType,
_hash_vec: Vec<HashValue>,
) -> Result<Vec<AccumulatorNode>, Error> ... | Rust | 0 |
from __future__ import annotations
import json
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Any
try:
import yaml # type: ignore
except Exception: # noqa: BLE001
yaml = None # 允许纯 JSON 环境
@dataclass
class TargetConfig:
name: str
cmd: List[str]
cwd: Optional... | Python | 1 |
"""Extract features from images for a given structure"""
import numpy as np
import torch
from ..pipeline import PipelineStep
from .feature_extraction import HANDCRAFTED_FEATURES_NAMES, HandcraftedFeatureExtractor
class NucleiConceptExtractor(PipelineStep):
"""Class for Nuclei concept extraction.
Extract nuc... | Python | 1 |
#!/usr/bin/env python
import os
import sys
import shutil
import time
import psycopg2
COCKROACH_HOME='/mnt/data1/scratch/work/adsl-work/d2s/applications/cockroach/cockroach-beta-20160714.linux-amd64'
CURR_DIR=os.path.dirname(os.path.realpath(__file__))
def stop_cluster():
# No -s 9!
os.system('killall cockroach')
#... | Python | 1 |
"""Configuration module for the Tweet 2 Token Pipeline."""
import os
from dotenv import load_dotenv
import sys
# Load environment variables from .env file
load_dotenv()
# Check if required environment variables are set
PUMP_PORTAL_API_KEY = os.getenv("PUMP_PORTAL_API_KEY")
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
if... | Python | 1 |
sor,
quantile: float) -> JTensor:
"""Calculates quantile loss.
Args:
pred: B x T
actual: B x T
quantile: quantile at which loss is computed.
Returns:
per coordinate loss.
"""
dev = actual - pred
loss_first = dev * quantile
loss_second = -dev * (... | Python | 1 |
,read -> (1,q0);
q0,write -> (1,q0);
q0,closer -> (1,qf) (1,q0); // Check (F closew), and also keep AG running
q0,closew -> (1,q0);
q0,end -> ;
qf,newr -> (1,qf);
qf,neww -> (1,qf);
qf,br -> (1,qf) (2,qf);
qf,read -> (1,qf);
qf,write -> (1,qf);
qf,closer -> (1,qf);
qf,cl... | Rust | 0 |
;",
name: "_record",
kind: Kind::Pseudo,
};
/// ANYNONARRAY - pseudo-type representing a polymorphic base type that is not an array
pub const ANYNONARRAY: Type = Type {
oid: 2776,
descr: "ANYNONARRAY - pseudo-type representing a polymorphic base type that is not an array",
name: "anynonarray",
... | Rust | 0 |
_image_sum_f32("gradient-1c-32b-float.tiff", ColorType::Gray(32), 128.03194);
}
#[test]
fn test_gray_f64() {
test_image_sum_f64(
"gradient-1c-64b-float.tiff",
ColorType::Gray(64),
128.0319210877642,
);
}
#[test]
fn test_rgb_u8() {
test_image_sum_u8("rgb-3c-8b.tiff", ColorType::RGB(... | Rust | 0 |
s[1].volume_id)
mock_ListVolumes.assert_called_once()
# If a list of 1 volume ID is passed, that volume only should be returned
self._module.SetUp(
'test-remote-profile-name',
'test-remote-zone',
'fake_incident_id',
remote_instance_id='',
volume_ids=FAKE_VOLUME.volum... | Python | 1 |
impl From<&Row> for ResponseApiKey {
fn from(row: &Row) -> Self {
Self {
created_at: row.get("created_at"),
updated_at: row.get("updated_at"),
id: row.get("id"),
client_id: row.get("client_id"),
user_id: row.get("user_id"),
name: row.... | Rust | 0 |
"""
Benchmarks for validation.
This package is *not* public API.
"""
| Python | 1 |
(_, Defmacro) => Greater,
(If, If) => Equal,
(If, _) => Less,
(_, If) => Greater,
(CoreLet, CoreLet) => Equal,
(CoreLet, _) => Less,
(_, CoreLet) => Greater,
(Quote, Quote) => Equal,
(Quote, _) => Less,
(_, Quote) => Greater,
(Quasiquote, Quasiquote... | Rust | 0 |
ng_values(df)
time_splitting(df)
drop_years(df, [2016, 2017, 2018])
feature_engineering(df)
print(df.columns)
print(len(df))
df.to_csv('data/US_Accidents_March23_cleaned.csv', index=False)
#print(df_ml.columns)
df_ml = df.copy()
df_ml = binning_columns(df_ml)
df_ml = ch... | Python | 1 |
xpand DP
suite.addTest(GPT2CheckpointTestCase('test_mp1_gpu2_load_gpu4_node1_with_zero1'))
suite.addTest(GPT2CheckpointTestCase('test_mp1_gpu2_load_gpu4_node1_with_zero2'))
suite.addTest(GPT2CheckpointTestCase('test_mp1_gpu2_load_gpu4_node1_with_zero2_offload'))
suite.addTest(GPT2CheckpointTestCase('te... | Python | 1 |
phere.
let bounding_sphere = calculate_bounding_sphere_from_points(&points);
assert!(sphere_contains_points(&points, &bounding_sphere));
}
#[test]
fn sphere_no_spheres() {
let bounding_sphere = calculate_bounding_sphere_from_spheres(&[]);
assert_eq!((Vec3A::ZERO, 0f32), boun... | Rust | 0 |
"""Test the hardware websocket API."""
from collections import namedtuple
import datetime
from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory
import psutil_home_assistant as ha_psutil
from homeassistant.components.hardware.const import DOMAIN
from homeassistant.core import HomeAssistant
fr... | Python | 1 |
}sec ({}us) ({:.3}fps)", start.elapsed().as_secs_f64(), elapsed.as_micros(), 1.0 / start.elapsed().as_secs_f64());
}
}
fn update_window(bus: &mut Bus, window: &mut Window) -> bool {
if bus.tia.cycles.color_clock == 0 /*&& bus.tia.cycles.scanline == 0 */{
window.update_with_buffer(&bus.tia.framebuffer, ... | Rust | 0 |
from fastapi import Depends, HTTPException, status, Request
from fastapi.security import APIKeyCookie
from typing import Optional
import jwt
import os
from sqlalchemy.ext.asyncio import AsyncSession
from backend.db.session import get_db_session
from dotenv import load_dotenv
from backend.db.repositories.guest import Gu... | Python | 1 |
(z1*z2*z3)
let mut t3: f2elm_t = [[0; 12]; 2]; // t2 = 1/(z1*z2)
fp2mul_mont(z1 as *const felm_t, z2 as *const felm_t, t0.as_mut_ptr()); // t3 = 1/z1
fp2mul_mont(
z3 as *const felm_t,
t0.as_mut_ptr() as *const felm_t,
t1.as_mut_ptr(),
); // z2 = 1/z2
... | Rust | 0 |
{
return;
}
KVM_FDS.store(Arc::new(kvm_fds));
let gic_config = GICConfig {
version: kvm_bindings::kvm_device_type_KVM_DEV_TYPE_ARM_VGIC_V3,
vcpu_count: 4_u64,
max_irq: 192_u32,
msi: false,
dist_range: (0x0800_0000, 0x0001_... | Rust | 0 |
LeqText,
LeqTimestamp,
LeqDate,
LeqParty,
LessInt64,
LessDecimal,
LessNumeric,
LessText,
LessTimestamp,
LessDate,
LessParty,
GeqInt64,
GeqDecimal,
GeqNumeric,
GeqText,
GeqTimestamp,
GeqDate,
GeqParty,
GreaterInt64,
GreaterDecimal,
Grea... | Rust | 0 |
reponame>emirayka/nia_interpreter_core
use crate::interpreter::error::Error;
use crate::interpreter::interpreter::Interpreter;
use crate::interpreter::value::Value;
use crate::library;
pub fn remove_item_from_root_alist(
interpreter: &mut Interpreter,
name: &str,
key: Value,
) -> Result<(), Error> {
l... | Rust | 0 |
{}", error),
};
return EXIT_ERR;
}
EXIT_OK
}
impl ClobberMode {
fn from_matches(matches: &ArgMatches) -> ClobberMode {
if matches.is_present(OPT_FORCE) {
ClobberMode::Force
} else if matches.is_present(OPT_REMOVE_DESTINATION) {
ClobberMode::RemoveDes... | Rust | 0 |
as_ref().try_into()?;
Vector3::new(tx, ty, tz)
}
};
let iso = {
if r.is_none() {
Isometry3::new(pos, Vector3::new(0.0, 0.0, 0.0))
} else {
let quaternion: Result<(f32, f32, f32, f32), &str> = r.as_ref().try_into();
if let Ok(quaternion) = quate... | Rust | 0 |
import logging
from pajbot.managers.db import DBManager
from pajbot.models.user import User
from pajbot.models.webcontent import WebContent
from pajbot.modules import ChattersRefreshModule
import markdown
from flask import render_template
from flask.typing import ResponseReturnValue
from markupsafe import Markup
from... | Python | 1 |
::reflect::MessageDescriptor {
::protobuf::MessageStatic::descriptor_static(None::<Self>)
}
}
impl ::protobuf::MessageStatic for Event_UpdateOperationStatus {
fn new() -> Event_UpdateOperationStatus {
Event_UpdateOperationStatus::new()
}
fn descriptor_static(_: ::std::option::Option<Ev... | Rust | 0 |
f" * Unique overlaps: {overlap_regions}\n"
log += f" * Total overlap size: {overlap_bp} bp\n"
log += f" * Percentage of {set_names[i]}: {pct_of_set1:.2f}%\n"
log += f" * Percentage of {set_names[j]}: {pct_of_set2:.2f}%\n"
log += f" * ... | Python | 1 |
out_grad_fp8,
ctx.w_fp8_t.contiguous().t(),
out_dtype=ctx.out_dtype,
scale_a=out_grad_scale,
scale_b=ctx.inv_scale_w,
use_fast_accum=True,
)[0]
w_grad = torch._scaled_mm(
out_grad_fp8.t().contiguous(),
ctx.x... | Python | 1 |
-
logger.debug("Phase 3: Heuristic-Based Merging & Refinement")
result.merge_by_punctuation(
punctuation=['、', ',', ','],
max_chars=40,
max_words=15
)
result.merge_by_gap(
min_gap=gap_threshold,
... | Python | 1 |
t VK_INDIRECT_COMMANDS_TOKEN_TYPE_MAX_ENUM_NV: VkIndirectCommandsTokenTypeNV = u32::MAX;
const VK_INDIRECT_STATE_FLAG_FRONTFACE_BIT_NV: VkIndirectStateFlagBitsNV = 1;
const VK_INDIRECT_STATE_FLAG_BITS_MAX_ENUM_NV: VkIndirectStateFlagBitsNV = u32::MAX;
const VK_INDIRECT_COMMANDS_LAYOUT_USAGE_EXPLICIT_PREPROCESS_BIT_NV... | Rust | 0 |
# Copyright 2018 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Python | 1 |
'component': 'VRow',
'content': [
{
'component': 'VCol',
'props': {
'cols': 12,
'md': 6
... | Python | 1 |
# device=t.device.type)
device=dvc,
)
a.tensor = t
return a
def torch2warp_vec3(t, copy=False, dtype=warp.types.float32, dvc="cuda:0"):
assert t.is_contiguous()
if t.dtype != torch.float32 and t.dtype != torch.int32:
raise RuntimeError(
"Error aliasing Torch tenso... | Python | 1 |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 16 17:38:11 2020
@author: giamp
"""
import numpy as np
name = 'polak 6'
startp = np.zeros(4)
lb = startp - 10.0
ub = startp + 10.0
n = len(lb)
nint = 2
ncont = n-nint
lbmix = np.zeros(n); lbmix[:ncont] = lb[:ncont]
ubmix = 100*np.ones(n); ubmix[:n... | Python | 1 |
30, 0),
entry!(26, 0, 1, 26, 27, 1),
entry!(26, 0, 2, 26, 27, 0),
entry!(26, 0, 3, 24, 31, 0),
entry!(26, 0, 4, 25, 30, 1),
entry!(27, 0, 3, 25, 30, 0),
entry!(27, 0, 2, 28, 24, 0),
entry!(27, 0, 1, 25, 31, 1),
entry!(27, 0, 0, 25, 31, 0),
entry!(27, 0, 1, 25, 31, 1),
entry!(27,... | Rust | 0 |
key PEM files, in that order.
Https(TcpListener, Arc<SslContext>)
}
impl Clone for HttpListener {
fn clone(&self) -> HttpListener {
match *self {
HttpListener::Http(ref tcp) => HttpListener::Http(tcp.try_clone().unwrap()),
HttpListener::Https(ref tcp, ref ssl) => HttpListener::... | Rust | 0 |
se:
retries = retries - 1
continue
notice("Return async_wrapper task started.")
end({"failed": 0, "started": 1, "finished": 0, "ansible_job_id": jid, "results_file": job_path,
"_ansible_suppress_tmpdir_delete": (not preserve_tmp)}, 0)
... | Python | 1 |
[tag("Function")]
Function(Function),
#[tag("UrlValue")]
Url(UrlValue),
#[tag("Str")]
Str(Str),
}
#[ast_node]
pub enum ImportLayerName {
#[tag("Ident")]
Ident(Ident),
#[tag("Function")]
Function(Function),
}
#[ast_node]
pub enum ImportSupportsType {
#[tag("SupportsCondition"... | Rust | 0 |
#!/usr/bin/env python
# coding: utf-8
# 简介: iOS app图标生成脚本, 生成后直接拖入xcode中就行
# 用法: python autoExportAppIcon.py /path/xxx.png
import sys
import os
try:
from PIL import Image
except:
print ('\033[31m' + '缺少Image模块,正在安装Image模块,请等待...' + '\033[0m')
success = os.system('python -m pip install Image')
if succ... | Python | 1 |
import time
import numpy as np
from rtde.rtde import RTDE
def test():
rtde = RTDE("192.168.1.102")
# Test joint control functions
# Set home first
home = np.array([1.57, -1.7, 2, -1.87, -1.57, 3.14])
incremental = 0.001 * np.ones(6)
try:
# Move to home
rtde.move_joint(home)
... | Python | 1 |
{})
def identify_key_points(self, analysis):
messages = [
{"role": "system", "content": "당신은 카피킬러 AI입니다."},
{"role": "user", "content": f"다음 글의 주요 포인트를 식별해주세요: {analysis}"}
]
response = requests.post(self.api_url, json=messages)
response.raise_for_status()
... | Python | 1 |
Ok(())
}
}
#[cfg(test)]
mod two_star {
use super::find_solution;
use error::Result;
use std::io::Cursor;
const TEST_CHAIN: &str = r"2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2";
#[test]
fn solution() -> Result<()> {
assert_eq!(find_solution(Cursor::new(TEST_CHAIN), true)?, 66);
... | Rust | 0 |
ef))?;
write!(self.0, " {})", &src[num.span().into_range()])?;
}
Ty::Tuple(tys) => {
write!(self.0, "(tuple")?;
for ty in tys {
write!(self.0, " ")?;
self.visit_ty(src, ty.as_ref())?;
}
... | Rust | 0 |
cpu.y = 0x10;
cpu.pc = 0x0800;
bus.write_u16(cpu.pc + 1, 0x1234);
bus.write_u8(0x1244, 0b0001_1111);
let cycles = cpu.execute_instruction(opcode.opcode, &mut bus);
assert_eq!(cycles, opcode.cycles);
assert_eq!(cpu.a, 0b0001_1111);
assert_eq!(cpu.flags, 0b00... | Rust | 0 |
RuleOrder,
}
/// Implementation of [Display] for HitPolicy.
impl std::fmt::Display for HitPolicy {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
HitPolicy::Unique => write!(f, "UNIQUE"),
HitPolicy::Any => write!(f, "ANY"),
HitPolicy::Priority => write!(f, "PRIO... | Rust | 0 |
-mpic/4397559/img_id2888036067946267033.jpeg/600x800 600w" sizes="(max-width: 1456px) 15vw, 217px"></div></div><div class="_3wBhh _4J3Mp" aria-hidden="true"><div class="_2QAep" style="transform:translateX(0px)"><span class="_2AqOy _1a43J"></span><span class="_2AqOy"></span><span class="_2AqOy"></span><span class="_2AqO... | Python | 1 |
{~#ifeq kind "Add"}}apply_diff_add{{/ifeq~}}
{{~#ifeq kind "Mul"}}apply_diff_mul{{/ifeq~}}
{{~else~}}
restrict
{{~/with~}}
{{~/inline}}
/// Returns the domain of {name} for the given arguments.
#[allow(unused_mut)]
pub fn get_{{name}}(&self{{>args_decl}}) -> {{>value_type.name value_type}} {
... | Rust | 0 |
patch_end = min(patch_start + self.patch_length, T)
# Create full-size mask, mask only selected patch in the selected window
past_observed_mask = torch.ones((T, C), dtype=torch.bool)
past_observed_mask[patch_start:patch_end] = 0
return {
**item,
"past_ob... | Python | 1 |
from ultralytics import YOLO
import numpy as np
import cv2
class YoloSeg():
def __init__(self, model_path):
self.model = YOLO(model_path)
self.model.to("cuda")
_ = self.model.predict(np.zeros((640, 640, 3)))
def segment_image(self, img_path):
results = self.model(img_path)
... | Python | 1 |
# .github/scripts/update_achievements.py
# This script fetches GitHub stats and updates the README with achievements and dynamic skill tree colors.
import os
import requests
import re
import json
# --- Configuration ---
GITHUB_USERNAME = os.getenv('GITHUB_USERNAME')
GITHUB_TOKEN = os.getenv('GITHUB_TOKEN')
# Base UR... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.