text string | label_name string | labels int64 |
|---|---|---|
icer.slice_non_whitespace(), Some("This"));
/// ```
///
/// [`slice_whitespace`]: struct.StrSlicer.html#method.slice_whitespace
pub fn slice_non_whitespace(&mut self) -> Option<&'str str> {
self.slice_until(|char: char| char.is_whitespace())
}
/// Skips past the rest of the line.
... | Rust | 0 |
orrowedHandleOrSocket<'a>;
/// Portability abstraction over `OwnedFd` and `OwnedHandleOrSocket`.
#[cfg(windows)]
pub type OwnedGrip = OwnedHandleOrSocket;
/// Portability abstraction over `AsFd` and `AsHandleOrSocket`.
#[cfg(not(windows))]
pub trait AsGrip: AsFd {
/// Extracts the grip.
fn as_grip(&self) -> Bo... | Rust | 0 |
k_to_index[{:?}] should have been {:?}={:?} but was {:?}={:?}",
&data.block,
index,
data,
bti_index,
bti_index.map(|i| self.block_data.get(usize::from(i))),
));
}
}
// Check th... | Rust | 0 |
TEXT => "createTextVNode",
RH::CREATE_STATIC => "createStaticVNode",
RH::RESOLVE_COMPONENT => "resolveComponent",
RH::RESOLVE_DYNAMIC_COMPONENT => "resolveDynamicComponent",
RH::RESOLVE_DIRECTIVE => "resolveDirective",
RH::RESOLVE_FILTER => "resolveFilter",
... | Rust | 0 |
EMOTION:([^\]]+)\]'
matches = re.findall(emotion_pattern, text)
clean_text = re.sub(emotion_pattern, '', text).strip()
emotion = matches[-1] if matches else None
return emotion, clean_text
def main():
"""主函数"""
try:
print("🎭 启动 Live2D AI数字人窗口...")
... | Python | 1 |
run_config.round_num}_{run_config.nameaddition}.json"
)
json_write(json_path, run_config)
else:
for run_config in run_configs:
with contextlib.suppress(FileExistsError):
os.makedirs("./AutoCOBRAK" + run_config.results_folder)
json_path = (
... | Python | 1 |
mylist=[1,25,6,2,5,6,2]
def max_product(arr):
max1,max2=0,0
for element in arr:
if element>max1:
max2=max1
max1=element
elif element>max2:
max2=element
return max1*max2
print(max_product(mylist)) | Python | 1 |
&[], &encoded_sub_tlv, &mut encrypted_data)?;
encrypted_data.extend(&auth_tag);
event_emitter
.lock()
.expect("couldn't access event_emitter")
.emit(&Event::DevicePaired);
debug!("M6: Sending SRP Exchange Response");
Ok(v... | Rust | 0 |
from sqlalchemy import Column, Integer, Date, Time, JSON, DateTime, String
from datetime import datetime
from database import Base
def now_local():
"""
タイムゾーン情報なしのローカル時間を返す。
Returns:
datetime: 現在のローカル時間。
"""
return datetime.now()
class AttendanceRecord(Base):
"""
勤怠記録を管理するモデル。
... | Python | 1 |
i32 = 1;
/// public static final [FLAG_MATCH_MANIFEST](https://developer.android.com/reference/android/content/pm/LauncherApps.ShortcutQuery.html#FLAG_MATCH_MANIFEST)
pub const FLAG_MATCH_MANIFEST : i32 = 8;
/// public static final [FLAG_MATCH_PINNED](https://developer.android.com/reference/a... | Rust | 0 |
n test_flow_on_concave() {
unimplemented!();
}
#[test]
#[ignore]
fn test_flow_on_convex() {
unimplemented!();
}
#[test]
fn test_flow_on_flat_surface_with_offset() {
// This is the top part of an icosphere, will try to hit it by shooting a vertex
// from exac... | Rust | 0 |
y/int, // A fresh region `y` (2)
z: fn(x: &x/int, // Refers to `x` at (1)
y: &y/int, // Refers to `y` at (2)
z: &z/int) -> &z/int) // A fresh region `z` (3)
-> &x/int {
if false { return z(x, y, x); }
if false { return z(x, y, y); }
... | Rust | 0 |
from random import choice as random_choice
from typing import Tuple
from random import uniform as random_uniform
common_mult = 1.2
uncommon_mult = 7.6
rare_mult = 19.8
epic_mult = 917
legendary_mult = 3846
base_mult = 0.01
# 0.1 1000 hours
# 0.01 100 hours
# 0.01 100 hours
# 0.001 10 hours increasing ~x3 the chance
... | Python | 1 |
: Some(thread),
}
}
}
use super::scaling::Scaling;
use crate::{module::Direction, region::region_map::RegionMap};
use bevy_egui::egui::Pos2;
pub struct MapWallInteraction {
pub tile_x: u32,
pub tile_y: u32,
pub selected_wall: Option<Direction>,
}
impl MapWallInteraction {
pub fn new(scale:... | Rust | 0 |
import requests
RapidAPIKey = ""
class DeepSearch:
def search(query: str = ""):
query = query.strip()
if query == "":
return ""
if RapidAPIKey == "":
return "请配置你的 RapidAPIKey"
url = "https://bing-web-search1.p.rapidapi.com/search"
querystring = ... | Python | 1 |
specific language governing permissions and
// limitations under the License.
/**
* This test ensures that you can change the problem size between solves.
* This problem demonstrates the flexibility of the current Rust API. Although the problem size
* changes, we can still use the solution from the previous solve... | Rust | 0 |
A = [1,-2,3,4,-56,6,-7,7,-77,5,4,-9,3,2,2,2]
positive_list = []
negative_list = []
positive_list=[element for element in A if element>0]
negative_list=[element for element in A if element<0]
print(positive_list,negative_list)
print(max(positive_list))
positive_list.sort() | Python | 1 |
{ tabla: HashMap::new() },
parametros: vec![],
direccion: dir,
num_cuadruplo: cuad,
era: vec![
(0, 0),
(0, 0),
(0, 0)
]
};
self.tabla.insert(nombre_func.clone(), func.clone());
Ok(("Funcion agregada", func.clo... | Rust | 0 |
NVALIDPARAMETERVALUE_PARAMINCOMPLETE = 'InvalidParameterValue.ParamIncomplete'
# 消息Payload超出限制。
INVALIDPARAMETERVALUE_PAYLOADOVERLIMIT = 'InvalidParameterValue.PayloadOverLimit'
# prefix不合法。
INVALIDPARAMETERVALUE_PREFIXINVALID = 'InvalidParameterValue.PrefixInvalid'
# 创建的产品名已存在。
INVALIDPARAMETERVALUE_PRODUCTALREADYE... | Python | 1 |
self) -> Result<(), Error> {
if !self.timg.is_counter_active() {
return Err(Error::TimerInactive);
} else if !self.timg.is_alarm_active() {
return Err(Error::AlarmInactive);
}
self.timg.set_counter_active(false);
Ok(())
}
}
impl<T> Periodic for Tim... | Rust | 0 |
lone());
false
} else {
false
}
};
if !has_ended {
state.current.set(Some(Current::new(state.clone())));
state
.rounds_played
.store(rounds_played + 1, Ordering::SeqCst);
log::inf... | Rust | 0 |
# -------- ADDING POISSON-GAUSSIAN NOISE ON RAW -
# Mode1: set sigma_s and sigma_c
# img_mosaic_noise = isp.add_PG_noise(img_mosaic, sigma_s=0.01, sigma_c=0.02)
# Mode2: set random sigma_s and sigma_c
img_mosaic_noise = isp.add_PG_noise(img_mosaic)
# -------- ISP PROCESS --------------------------
... | Python | 1 |
# Copyright The IETF Trust 2007-2020, All Rights Reserved
# -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib.syndication.views import Feed
from django.utils.feedgenerator import Atom1Feed
from ietf.doc.models import Document, TelechatDocEvent
from ietf.utils.timezone import date_today
cla... | Python | 1 |
import pandas as pd
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, Dataset
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score
from sklearn.preprocessing import LabelEncoder
from transformers import HubertModel, AutoFeatureExtractor
import librosa
import nump... | Python | 1 |
ngine.as_deref()
}
/// <p>The version of the cache engine that is used in this cluster.</p>
pub fn engine_version(&self) -> std::option::Option<&str> {
self.engine_version.as_deref()
}
/// <p>The current state of this cluster, one of the following values: <code>available</code>, <code>creati... | Rust | 0 |
RMS:", rms)
print("camera matrix:\n", camera_matrix)
print("distortion coefficients: ", dist_coefs.ravel())
print("newcameramtx:\n", newcameramtx)
print("roi: ", roi)
data = {
"RMS": rms,
"CameraMatrix": camera_matrix.tolist(),
"DistortionCoefficients": dist_coefs.ravel().tolist(),
... | Python | 1 |
from typing import Self
from mmisp.plugins.enrichment.data import EnrichAttributeResult
from mmisp.plugins.enrichment.enrichment_plugin import EnrichmentPluginInfo, EnrichmentPluginType, PluginIO
from mmisp.plugins.models.attribute import AttributeWithTagRelationship
from mmisp.plugins.plugin_type import PluginType
fr... | Python | 1 |
from __future__ import annotations
from typing import TYPE_CHECKING, NamedTuple
from trueseeing.api import Signature
if TYPE_CHECKING:
from typing import Optional, TypedDict, Dict, List
from trueseeing.api import SignatureHelper, ConfigMap
from trueseeing.core.android.context import APKContext
from trueseeing... | Python | 1 |
"""Periodic Table of Elements, by Al Sweigart al@inventwithpython.com
Displays atomic information for all the elements.
This code is available at https://nostarch.com/big-book-small-python-programming
Tags: short, science"""
# Data from https://en.wikipedia.org/wiki/List_of_chemical_elements
# Highlight the table, cop... | Python | 1 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Paul Arthur <paul.arthur@flowerysong.com>
# Copyright: (c) 2019, XLAB Steampunk <steampunk@xlab.si>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_fun... | Python | 1 |
(|| Duration::from_secs(0));
let time_since_last_seen = now_epoch_ts
.checked_sub(ts)
.unwrap_or_else(|| Duration::from_secs(0));
result.push((meta, time_since_last_seen));
}
Ok(result)
}
pub fn get_executor_metadata(&self, executor_id: &s... | Rust | 0 |
from django.db import models
class TRelacionCodbarras(models.Model):
# id = models.AutoField(db_column='id',auto_created=True, primary_key=True) # Field name made lowercase.
idinternoean = models.CharField(db_column='IdInternoEAN', max_length=50) # Field name made lowercase.
codbarrasasignado = models.Ch... | Python | 1 |
862192, 25954476, 25994479, 26008752, 26036460, 26038202,
26078874, 26118327, 26132679, 26207601, 26262418, 26270737, 26274860, 26431248, 26434268,
26562736, 26580134, 26593740, 26618561, 26844181, 26866971, 26907883, 27005270, 27023584,
27024044, 27057184, 23061395, 23077554, 23138588, 23185172... | Rust | 0 |
rposes
print("Postgres Error:", e)
# Check the error code to determine the type of error
if e.pgcode == '23505':
# Integrity violation (e.g., unique constraint violation)
return {'error': 'Integrity violation. Duplicate key.'}, 400
elif e.pgcode == '23503':
... | Python | 1 |
-> LeafElt<K, V> {
return LeafElt::new(k, v);
}
}
impl<K: Clone + TotalOrd, V: Clone> Clone for BranchElt<K, V> {
///Returns a new BranchElt by cloning the key, value, and left child.
fn clone(&self) -> BranchElt<K, V> {
BranchElt::new(self.key.clone(),
self.value.cl... | Rust | 0 |
effectively an immutable clonable-HAMT of bank style account,
//! which contains a non negative value representing your balance with the
//! identifier of this account as key.
use crate::value::*;
use imhamt::{Hamt, InsertError, UpdateError};
use std::collections::hash_map::DefaultHasher;
use std::fmt::{self, Debug};... | Rust | 0 |
ader<u8, SETCLR5_A>);
impl SETCLR5_R {
pub(crate) fn new(bits: u8) -> Self {
SETCLR5_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<SETCLR5_A> {
match self.bits {
0 => Some(SETCLR5_A::INDEPEND... | Rust | 0 |
ed: [None; MAX_TABLE_TAG],
tag_sizes: [0; MAX_TABLE_TAG],
tag_offsets: [0; MAX_TABLE_TAG],
tag_save_as_raw: [false; MAX_TABLE_TAG],
is_write: false,
io: None,
}
}
pub fn open_from_file<P: AsRef<Path>>(
context: Box<Context>,
fil... | Rust | 0 |
lization handlers if configured.
Note: aiosqlite uses the same sqlite3 module type registration as the
sync adapter, so this shares the implementation.
"""
if self.driver_features.get("enable_custom_adapters", False):
from sqlspec.adapters.sqlite._type_handlers import regist... | Python | 1 |
.try_from_type(ACCESS_KEY).optional()?.or(rd.default_register_access);
let access_mode = match access_mode {
Some(a) => a,
None => return v.table_validation_error(format!("register access mode is undefined")),
};
let (read_location, write_location) = {
let index: Option<u64> = v.try... | Rust | 0 |
ip of the network/type tag
match p256::AffinePoint::decompact(FieldBytes::from_slice(&input[1..])).into() {
Some(point) => Ok(PublicKey(
p256::PublicKey::from_affine(point).map_err(Error::from)?,
)),
None => Err(Error::not_compact()),
... | Rust | 0 |
}
last_index = cell_index;
cell_index = cell.next;
}
let new_index = self.cell_count;
self.cell_count += 1;
let cell = Cell {
x: x,
area,
cover,
next: cell_index,
};
if last_index != -1 {
... | Rust | 0 |
</a>
<span class="playable">[可播放]</span>
</div>
<div class="bd">
<p class="">
导演: 陈凯歌 Kaige Chen 主演: 张国荣 Leslie Cheung / 张丰毅 Fengyi Zha...<br>
1993&n... | Python | 1 |
e by the
# parent.
suite_nodes, new_working_stack, new_prefix, ai = self._copy_nodes(
working_stack + [suite_tos], suite.children, until_line, line_offset,
is_nested=True,
)
added_indents += ai
if len(suite_nodes) < 2:
... | Python | 1 |
if tab.account_cursor != 0 {
tab.account_cursor -= 1;
}
} else {
let account = tab
.ledger
.accounts
.get_mut(tab.account_cursor)
.expect("Unreachable: txn del acc cursor bounds");
let cursor = ... | Rust | 0 |
# Import packages
from dash import Dash, html, dash_table, dcc, callback, Output, Input
import pandas as pd
import plotly.express as px
import dash_mantine_components as dmc
# Incorporate data
df = pd.read_csv(
"https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv"
)
# Initialize the app - i... | Python | 1 |
or w in range(0,5):
op(x) # warmup
start = time.time()
op(x)
stop = time.time()
self.time['OP{}'.format(i)]=stop-start
i = i + 1
else:
return i
class... | Python | 1 |
;
enc.encode_sized(&fuse_kernel::fuse_lk_out { lk: lock })
}
}
// }}}
<gh_stars>1000+
//! Image Processing Functions
use std::cmp;
use crate::image::{GenericImage, GenericImageView, SubImage};
use crate::traits::{Lerp, Pixel, Primitive};
pub use self::sample::FilterType;
pub use self::sample::FilterType::{Catmul... | Rust | 0 |
len(all_odos) > config.odo_delta:
last_odo = all_odos[-config.odo_delta]
last_millis = all_millis[-config.odo_delta]
vel = 0
if temp_odo != last_odo:
if millis - last_millis == 0: vel = 0
else: vel = (temp_odo - last_odo) / (millis - last_millis)
... | Python | 1 |
::{ParticleRenderBillboardType, ParticleRenderData};
pub use rgb_texture_loader::RgbTextureLoader;
pub use sky_material::SkyMaterial;
pub use static_mesh_material::StaticMeshMaterial;
pub use terrain_material::{TerrainMaterial, TERRAIN_MESH_ATTRIBUTE_TILE_INFO};
pub use texture_array::{GpuTextureArray, TextureArray, Te... | Rust | 0 |
program: Program,
brdf_integration_program: Program,
) -> Skybox
where
F: Facade,
P: AsRef<Path>,
{
let hdr_texture = load_hdr_texture(facade, path.as_ref());
let width = 2048;
let height = 2048;
let rect = glium::Rect {
left: 0,
bottom: 0,
width,
height,
... | Rust | 0 |
.iter::<usize>().take(vs).enumerate() {
is_ac &= ord[u] == !0usize;
ord[u] = i;
}
for (u, v) in edges.take(es) {
is_ac &= ord[u] < ord[v];
}
is_ac
}
<filename>src/man/mod.rs
use std::{
env,
fs,
io::{
self,
Read
},
path::PathBuf
};
pu... | Rust | 0 |
match decoder.read_byte()? {
byte @ b'0'..=b'9' => buf.push(byte as char),
byte => {
decoder.end_with(byte)?;
break T::from_str_radix(&buf, 10).map_err(|_| DecodeError::Parse.into());
}
}
}
}
#[test]
fn test_numeric_u8() {
let tes... | Rust | 0 |
import subprocess
import pytest
@pytest.mark.uses_network
def test_pbr_integration(pbr_package, venv):
"""Ensure pbr packages install."""
cmd = [
'python',
'-m',
'pip',
'-v',
'install',
'--no-build-isolation',
pbr_package,
]
venv.run(cmd, stderr... | Python | 1 |
#!/usr/bin/env python3
"""
Very simple direct test of journal matching without any complex features.
"""
import sys
sys.path.append('src')
import os
os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'
os.environ['TOKENIZERS_PARALLELISM'] = 'false'
def direct_search_test():
"""Test direct search functionality step by ste... | Python | 1 |
let glClearColor_p = transmute::<nn_cv, glClearColor_t>(Self::ptr_filter(f(b"glClearColor\0".as_ptr())).ok_or("glClearColor")?);
let glClearDepth_p = transmute::<nn_cv, glClearDepth_t>(Self::ptr_filter(f(b"glClearDepth\0".as_ptr())).ok_or("glClearDepth")?);
let glClearStencil_p = transmute::<nn_cv, glClear... | Rust | 0 |
with col:
st.image(get_proxied_image_url(movie.get('cover_url')), use_container_width=True)
# 使用 douban_id 生成唯一的key
if st.button(f"#{int(movie.get('ranking', 0))} {movie.get('name_cn', '')}",
key=f"btn_movie_{movie... | Python | 1 |
import numpy as np
def zNew(p,T,ro,H2S,Co2,N2):
erp = 0.000000001
# Пересчет в мольные доли
H2S = H2S / 100
Co2 = Co2 / 100
N2 = N2/ 100
gr = ro* 1.2041
mw = gr * 24.0551
mwCH = mw - 34.082 * H2S - 44.01 * Co2 - 28.01 * N2
grCH = mwCH / 24.0551 / 1.2041
PcCH = (48.10... | Python | 1 |
min_image_extent: VkExtent2D,
pub max_image_extent: VkExtent2D,
pub max_image_array_layers: u32,
pub supported_transforms: VkFlags,
pub current_transform: VkSurfaceTransformFlagBitsKHR,
pub supported_composite_alpha: VkFlags,
pub supported_usage_flags: VkFlags
}
#[repr(C)] pub(crate) struct VkSurfaceFormatKHR {... | Rust | 0 |
codeBatch_1(adata_cm, adatas, dataloader=testloader, num_gene=num_gene, num_cell=num_cell,device=device,out=out, DRUG=DRUG,source_batch=source_batch,target_batch=target_batch,sampler=sampler, unshared_encoder=unshared_encoder) # save latent rep
elif out=='predict':
if sampler=='smote' or sampler=='weight':
... | Python | 1 |
_id)):
video_track_instances.append(
np.array([
frame_id + 1,
pred_track_instances.instances_id[i].cpu(),
pred_track_instances.bboxes[i][0].cpu(),
pred_track_instances.bboxes[i][1].cpu(),
... | Python | 1 |
if instance_emb is not None and isinstance(instance_emb, torch.Tensor):
accelerator.print("[修复] 使用实例嵌入替代类别嵌入")
class_emb_raw = instance_emb.clone().detach()
else:
... | Python | 1 |
0_RSS_MODE_DIS) |
FIELDX!(RXQ0_IDT_TBL_SIZE, RXQ0_IDT_TBL_SIZE_DEF) |
RXQ0_RSS_HSTYP_ALL |
RXQ0_RSS_HASH_EN |
RXQ0_IPV6_PARSE_EN;
if (self.cap & CAP_GIGA > 0) {
FIELD_SET32!(val, RXQ0_ASPM_THRESH, RXQ0_ASPM_THRESH_100M);
}
self.write(RXQ0, val);
/* ... | Rust | 0 |
n [N x T] tensor of terms in the lower-bound.
- xstart_mse: an [N x T] tensor of x_0 MSEs for each timestep.
- mse: an [N x T] tensor of epsilon MSEs for each timestep.
"""
device = x_start.device
batch_size = x_start.shape[0]
vb = []
xstart_mse... | Python | 1 |
impl FnType {
pub fn self_conversion(&self, cls: Option<&syn::Type>) -> TokenStream {
match self {
FnType::Getter(st) | FnType::Setter(st) | FnType::Fn(st) | FnType::FnCall(st) => {
st.receiver(cls.expect("no class given for Fn with a \"self\" receiver"))
}
... | Rust | 0 |
)
return {"analysis_summary": analysis_result_str}
except Exception as e:
logger.error(f"Error during trend analysis execution: {e}", exc_info=True)
error_message = f"Error analyzing trends: {e}. Check logs for details."
if "rate limit" in str(e).lower():
... | Python | 1 |
chase any origin of shell
///
/// Parameters:
/// - `status`: Status to set LastDayOfSale StorageValue
fn set_last_day_of_sale_status(status: bool) -> DispatchResult {
<LastDayOfSale<T>>::put(status);
Self::deposit_event(Event::PreorderOriginOfShellsStatusChanged { status });
Ok(())
}
/// Set initial Ori... | Rust | 0 |
from robyn import Robyn, Request
from common.router_group import RouterGroup
from service_wallet.services.wallet_service import *
class WalletController:
def __init__(self, app: Robyn):
self.app = RouterGroup(app, "/api/v1/wallet/")
self.__setup_routes()
def __setup_routes(self):
@se... | Python | 1 |
f"{text} world"
class GpuAppendSuffix(cocoindex.op.FunctionSpec):
suffix: str
@cocoindex.op.executor_class(gpu=True)
class GpuAppendSuffixExecutor:
spec: GpuAppendSuffix
def __call__(self, text: str) -> str:
return f"{text}{self.spec.suffix}"
class GpuAppendSuffixWithAnalyzePrepare(cocoindex... | Python | 1 |
#!/usr/bin/env python3
#
# Copyright 2024 Wolfgang Hoschek AT mac DOT com
#
# 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 require... | Python | 1 |
let mut counts = vec![0; k];
update_assignments(data, &mut assignments, &mut counts, &mut costs, ¢res);
let mut objective = costs.iter().fold(0.0, |a, b| a + *b);
let mut converged = false;
let mut iter = 0;
while iter < self.max_iter {
update_centres(dat... | Rust | 0 |
import numpy as np
from scipy.linalg import null_space
# Définir la matrice de transformation A_Φ
A_phi = np.array([
[3, 2, 1],
[1, 1, 1],
[1, -3, 0],
[2, 3, 1]
], dtype=float)
# Afficher la matrice
print(" Matrice A_Φ :\n", A_phi)
# Rang de A_Φ
rank = np.linalg.matrix_rank(A_phi)
print("\n Rang de A... | Python | 1 |
n the state
class TimeHandler:
def __init__(self, name: str, freq: bool = False, period: bool = False) -> None:
self.name = name
self.freq = freq
self.period = period
if not self.period and not self.freq:
print(f"Warning: No timings logged for {name}")
self._sta... | Python | 1 |
import numpy as np
from gymnasium import spaces
from stable_baselines3 import PPO
from stable_baselines3.common.vec_env import VecEnv, VecExtractDictObs, VecMonitor
class DictObsVecEnv(VecEnv):
"""Custom Environment that produces observation in a dictionary like the procgen env"""
metadata = {"render_modes"... | Python | 1 |
import klotho
import klotho.aws as aws
app = klotho.Application(
"my-app",
project="test_container",
environment="default",
default_region="us-west-2",
)
dynamodb = aws.DynamoDB(
"my-dynamodb",
attributes=[
{"Name": "id", "Type": "S"}, # Partition key (Primary Key)
{"Name... | Python | 1 |
for variant in variants {
let literal = match_on_raw_type(*variant.a());
writeln!(
&mut w,
"{} => {}::{},",
literal,
type_name,
enum_variant_name(variant.b())
... | Rust | 0 |
"""Power BI agent."""
| Python | 1 |
import pyautogui
import time
import pyperclip
from openai import OpenAI
client = OpenAI(
api_key="write your api key", # write your API
)
def is_last_message_from_sender(chat_log, sender_name="Rehman"):
# Split the chat log into individual messages
messages = chat_log.strip().split("/2024] ")[-1]
i... | Python | 1 |
ashSet::from_iter(grid.iter().copied());
let (range_x, range_y, range_z, _range_w) = extents(&previous);
for x in range_x.start() - 1..=range_x.end() + 1 {
for y in range_y.start() - 1..=range_y.end() + 1 {
for z in range_z.start() - 1..=range_z.end() + 1 {
let previously_active = previous.contai... | Rust | 0 |
ELETON_ARMY: Card = Card(
"skeleton_army", False, 3, [Units.SKELETON], 26000012
)
SKELETON_BARREL: Card = Card(
"skeleton_barrel", False, 3, [Units.SKELETON], 26000056
)
SKELETON_DRAGONS: Card = Card(
"skeleton_dragons", False, 4, [Units.SKELETON_DRAGON], 26000080
)
SKELE... | Python | 1 |
"""Input/output utilities for orbit family data.
This module provides functions for serializing and deserializing orbit family
objects using pickle, which preserves object relationships automatically.
"""
from pathlib import Path
from typing import TYPE_CHECKING
import pickle
from hiten.utils.io.common import _ens... | Python | 1 |
der Unpacking.
#[no_mangle]
pub extern "stdcall" fn GetBackgroundFlags() -> c_int {
BACKGROUND_UNPACK | BACKGROUND_PACK
}
use std::fmt;
#[derive(Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum ChessPiece {
NoPiece = 0x00,
WhitePawn = 0x01,
WhiteKnight = 0x02,
WhiteBishop = 0x03,
WhiteRook = 0x04,
... | Rust | 0 |
(bin_name));
assert_eq!(store.get(entity_key).unwrap(), Some(new_data));
Ok(())
})
}
#[test]
fn partially_update_existing() {
run_test(|store| -> Result<(), ()> {
let entity_key = EntityKey {
subgraph_id: TEST_SUBGRAPH_ID.clone(),
entity_type: "user".to_owned(),... | Rust | 0 |
DLaneIndex; 16] },
V8x16LoadSplat { memarg: MemoryImmediate },
V16x8LoadSplat { memarg: MemoryImmediate },
V32x4LoadSplat { memarg: MemoryImmediate },
V64x2LoadSplat { memarg: MemoryImmediate },
I8x16NarrowI16x8S,
I8x16NarrowI16x8U,
I16x8NarrowI32x4S,
I16x8NarrowI32x4U,
I16x8WidenLow... | Rust | 0 |
es_faces[e1] = i
if e2 in edges_set:
edges_faces[e2] = i
if e3 in edges_set:
edges_faces[e3] = i
face_idx = []
for e in edges:
face_i = edges_faces[e]
face_idx.append(face_i)
f_center = mesh.triangles_center[face_idx]
f_normals = mesh.face_normal... | Python | 1 |
se CompositeParallelSalesforce to cache 200 at a time
return self._sf_connection.query_single_record(query)
@memorable
def find_record(self, *args, fields="Id", where=None, **kwargs):
"""Find a particular record"""
query_from = self._parse_from_from_args(args, kwargs... | Python | 1 |
self._RegionId = RegionId
def _deserialize(self, params):
self._LoadBalancerId = params.get("LoadBalancerId")
self._LoadBalancerName = params.get("LoadBalancerName")
self._VpcId = params.get("VpcId")
self._RegionId = params.get("RegionId")
memeber_set = set(params.keys(... | Python | 1 |
elf.client.watchers(issue)
watchers = []
for watcher in watchlist.watchers:
watchers.append(watcher.name)
return watchers
def get_issue(self, issue_id):
"""Retrieve an issue object with a specific id."""
issue = self.client.issue(str(issue_id))
return issue
def get_issue_count(self, ... | Python | 1 |
):
raise ValueError("restypes, residue_indices, chain_indices must have the same length.")
# Mask the inputs.
mask = (
chemtypes == non_polymer_chemtype
if non_polymer_only
else chemtypes != non_polymer_chemtype
)
masked_chain_indices = chain_indices[mask]
masked... | Python | 1 |
"""add_deployment_version_to_flow_run
Revision ID: bd6efa529f03
Revises: aeea5ee6f070
Create Date: 2024-04-03 09:44:18.666688
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "bd6efa529f03"
down_revision = "aeea5ee6f070"
branch_labels = None
depends_on = None
... | Python | 1 |
"""Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs in O(n) time and without using the division operati... | Python | 1 |
def unshard(x: jnp.ndarray):
num_devices, batch_size = x.shape[:2]
rest = x.shape[2:]
return x.reshape(num_devices * batch_size, *rest)
| Python | 1 |
pler, mapper=lambda x: x, num_workers=3
)
self._check_is_range(dl, N)
# test that batch_size works correctly
dl = build_detection_test_loader(
dataset=ds, sampler=sampler, mapper=lambda x: x, batch_size=4, num_workers=0
)
self._check_is_range(dl, N)
def ... | Python | 1 |
StringEncoding::UTF16 => CanonicalOption::UTF16,
StringEncoding::CompactUTF16 => CanonicalOption::CompactUTF16,
}
}
}
/// Decode an "interface-only" component to a wit `Interface`.
pub fn decode_interface_component(bytes: &[u8]) -> Result<Interface> {
decoding::InterfaceDecoder::new(&d... | Rust | 0 |
FileId::from(v.clone())),
contract_id: services.contract_id.map(|v| ContractId::from(v.clone())),
account_id: utils::optional_account_id(services.account_id)?,
token_id: services.token_id.map(|v| TokenId::from(v.clone())),
topic_sequence_num: services.topic_sequence_numbe... | Rust | 0 |
Returns:
True if database is available, False otherwise
"""
db_path = get_source_db_path()
if not os.path.exists(db_path):
return False
conn = get_source_db_connection()
if not conn:
return False
try:
cursor = conn.cursor()
cursor.exe... | Python | 1 |
"ibrion": 2,
"isif": 3 if relax_cell else 2,
"lcharg": False,
"lreal": "auto",
"lwave": True,
"nsw": 500 if relax_cell else 250,
}
# To ensure vasp_gam --> vasp_std issues are auto-fixed
with change_settings({"VASP_USE_CUSTODIAN": True}):
summary1 = run... | Python | 1 |
.iter()) {
if &val_arg.typ() == typ {
let term = term::dtyp_slc(typ.clone(), slc.clone(), var.clone());
let prev = map.insert(term, val_arg.clone());
debug_assert! { prev.is_none() }
}
}
Ok(())
}
}
impl TheoSynth for AdtSynth ... | Rust | 0 |
# src/mind_state/supportive_state.py
from src.ai.actions.call import CallAction
from src.ai.actions.cover import CoverAction
from src.ai.actions.coordinate_with_allies import CoordinateWithAlliesAction
from src.ai.fsm.fsm_state import FSMState
class SupportiveState(FSMState):
def __init__(self, fsm_controller):
... | Python | 1 |
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::dhcp-client-id\0".as_ptr() as *const _,
Some(transmute(
notify_dhcp_client_id_trampoline::<Self, F> as usize,
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.