text
string
label_name
string
labels
int64
ngo can't redirect to the slash URL while maintaining POST data. # Change your form to point to 127.0.0.1:8000/submit_number/3/ (note the trailing slash), # or set APPEND_SLASH=False in your Django settings. APPEND_SLASH=False # HTTPS settings for production # SESSION_COOKIE_SECURE = True # CSRF_COOKIE_SECURE ...
Python
1
enum Error { InvalidBundle, VarError(env::VarError) } impl From<env::VarError> for Error { fn from(e: env::VarError) -> Error { Error::VarError(e) } } impl Command { pub fn new() -> Result<Self, Error> { Ok(Command{ bundle: env::var("COG_BUNDLE").expect("missing bundle"), name: env::var...
Rust
0
ton = group.buttons.create( type="Ansible Playbook", playbook_cat_item=ansible_catalog_item_create_empty_file.name, inventory=inventory, hosts=target_machine.hostname if inventory == "Specific Hosts" else None, text=fauxfactory.gen_alphanumeric(start="btn_"), hover=fauxfa...
Python
1
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. macro_rules! impl_marker_for { ($traitname:ident, $($ty:ty)*) => { $( impl $tr...
Rust
0
self) -> mem::Shared<dispdrv::HOSBinderDriver> { self.hos_binder_driver.clone() } pub fn increase_refcounts(&mut self) -> Result<()> { self.hos_binder_driver.get().adjust_refcount(self.handle, 1, dispdrv::RefcountType::Weak)?; self.hos_binder_driver.get().adjust_refcount(self.handle, 1,...
Rust
0
a>> { unit.pkg .targets() .iter() .find(|t| t.linkable()) .map(|t| Unit { pkg: unit.pkg, target: t, profile: lib_or_check_profile(unit, t, cx), kind: unit.kind.for_target(t), }) } /// If a build script is scheduled to be run fo...
Rust
0
let msg = claim_vested(deps.storage, env, info.sender)?; match msg{ Some(msg) => Ok(Response::new() .add_attribute("action", "claim_rewards") .add_message(msg)), None => Ok(Response::new() .add_attribute("action", "claim_rewards")) ...
Rust
0
self.get_value_to_append(_BlobQueryStringConstants.SIGNED_VERSION) + self.get_value_to_append(_BlobQueryStringConstants.SIGNED_RESOURCE) + self.get_value_to_append(_BlobQueryStringConstants.SIGNED_TIMESTAMP) + self.get_value_to_append(_BlobQueryStringConstants.SIGNED_CACHE_CO...
Python
1
} } HirKind::Class(hir::Class::Bytes(ref cls)) => { for range in cls.iter() { set.remove_all(range.start(), range.end()); } } HirKind::Repetition(ref x) => { remove_matching_bytes(&x.hir, set); } HirKind::Group(ref x) =>...
Rust
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Выполнить индивидуальное задание 2 лабораторной работы 2.19, добавив аннтотации типов. # Выполнить проверку программы с помощью утилиты mypy. import argparse import json from datetime import datetime from pathlib import Path from validation import ListWorkers def a...
Python
1
)) def solve_maxsat_z3(path, k_iter): start = time.time() constraints, header = read_uf(path) variables = Bools(' '.join([str(i) for i in range(header['num_nodes'])])) ands = [] for con in constraints: temp = [] for node in con: ind = abs(node) - 1 if node > ...
Python
1
_entries.async_remove(entry.entry_id) await hass.async_block_till_done() assert len(mock_init.mock_calls) == 1 assert mock_init.mock_calls[0][1][0] == "mqtt" assert mock_init.mock_calls[0][2]["context"] == expected_context @pytest.mark.usefixtures("mock_async_zeroconf") @pytest.mark.p...
Python
1
cts representing this statement. """ # Store the current location. loc = l.get_location() pf = statements.parse(l) if pf is None: l.error("expected statement.") return pf(l, loc) def parse_block(l): """ This parses a block of Ren'Py statements. It returns a list of the ...
Python
1
# {'params': self.color_net.parameters(), 'lr': lr}, {'params': self.msg_decoder.parameters(), 'lr': lr}, ] else: params = [ # {'params': self.encoder.parameters(), 'lr': lr}, # {'params': self.sigma_net.parameters(), 'lr': lr...
Python
1
def box_xyxy_expand2square(box, *, w, h): if w == h: return box if w > h: x1, y1, x2, y2 = box y1 += (w - h) // 2 y2 += (w - h) // 2 box = x1, y1, x2, y2 return box assert w < h x1, y1, x2, y2 = box x1 += (h - w) // 2 x2 += (h - w) // 2 box = x...
Python
1
Node::DropDatabase(plan) => self.visit_drop_database(plan), PlanNode::CreateTable(plan) => self.visit_create_table(plan), PlanNode::DropTable(plan) => self.visit_drop_table(plan), PlanNode::DescribeTable(plan) => self.visit_describe_table(plan), PlanNode::OptimizeTable(pl...
Rust
0
import requests, json from bs4 import BeautifulSoup from pathlib import Path def get_verbs(soup): div = soup.find('div', id='mw-pages') groups = div.find_all('div', class_='mw-category-group') verbs = [] for group in groups: for li in group.find_all('li'): link = li.find('a') ...
Python
1
bool { if if pressed(ctx, eng, Control::Up) { if self.cursor >= 2 { self.cursor -= 2; true } else { false } } else if pressed(ctx, eng, Control::Down) { if self.cursor <= 2 { self.cursor += 2...
Rust
0
ithProgress(printTime, progress): return (printTime / progress) - printTime # Can we calculate yet? if printTime > 0: all = [ calcTimeLeftWithProgress(printTime=printTime, progress=progressFloat) if progressFloat is not None else None, cal...
Python
1
from gector.gec_model import GecBERTModel from utils.helpers import get_target_sent_by_edits # 初始化模型参数 model = GecBERTModel( vocab_path='data/output_vocabulary', # 你的vocab路径 model_paths=['models/roberta/roberta_1_gectorv2.th'], # 你的模型路径 weigths=[1.0], # 单个模型的...
Python
1
# Copyright Materialize, Inc. and contributors. All rights reserved. # # Use of this software is governed by the Business Source License # included in the LICENSE file at the root of this repository. # # As of the Change Date specified in that file, in accordance with # the Business Source License, use of this software...
Python
1
0 ), "Please fit the metric before moving parameters to device" self.device = device self.sensitive_vector = self.sensitive_vector.to(self.device) def fit(self, sensitive_idx, num_dims): """Fit Causal Distance metric Parameters ------------ sensitive_a...
Python
1
#[structopt(short = "i", long)] /// Interval to update data from API (seconds) [default: 1] pub update_interval: Option<u64>, // Flags // #[structopt(short = "p", long)] /// Enable pre / post market hours for graphs pub enable_pre_post: bool, #[structopt(long)] /// Hide help icon i...
Rust
0
name == "delete").delete() delete_user = User.objects.get(User.nickname == "delete") assert delete_user is None async def test_soft_delete_sync(self): user = User.objects.create(username=f"test_{time.time()}", nickname="soft_delete") delete = User.objects.filter(User.nickname == "so...
Python
1
ep > 10: self.saver.save(self.sess, self.tmp) best_loss = loss if len(avg_seed) >= self.window: avg_seed.pop(0) avg_seed.append(self._transform(X)) if early_stopping: self.saver.restore(self.sess, self.tmp) lo...
Python
1
ze_h-1) # (N_logRatioInt, patchSize, patchSize), clip to range [0, _imgResize_h) for indexing _pixel_w_int = _patch_w_min[:,None,None] + _patchRelativeCoords[1:2] _pixel_w = np.clip(_pixel_w_int, a_min=0, a_max=_imgResize_w-1) patches[_select] = _imgResize[_pixel_h, _pixel_w, :] # (N_...
Python
1
# SPDX-License-Identifier: GPL-3.0-or-later # Copyright (C) 2016-2020 by Nathan Lovato, Daniel Oakey, Razvan Radulescu, and contributors import bpy from .utils.functions import get_sequences_under_cursor from .utils.doc import doc_name, doc_idname, doc_brief, doc_description class POWER_SEQUENCER_OT_snap(bpy.types.O...
Python
1
tor<Item = NoisePassParams> { let mut rng = ChaCha8Rng::seed_from_u64(seed); let tresholds = iter::repeat_with(|| NeuronValue(rng.gen())) .take(neuron_count) .collect(); let effect_count = neuron_count .checked_mul(connection_count) .ok_or(network::Error::EffectCountOve...
Rust
0
( &rrule.by_set_pos, &self.timeset, start, end, &self.ii, &dayset, self.dt_start.timezone(), )?; for res in pos_list { if rrule...
Rust
0
ub const snd_pcm_chmap_position_SND_CHMAP_TRL: snd_pcm_chmap_position = 25; pub const snd_pcm_chmap_position_SND_CHMAP_TRR: snd_pcm_chmap_position = 26; pub const snd_pcm_chmap_position_SND_CHMAP_TRC: snd_pcm_chmap_position = 27; pub const snd_pcm_chmap_position_SND_CHMAP_TFLC: snd_pcm_chmap_position = 28; pub const sn...
Rust
0
p_manager, 1 as libc::c_int, b"Not enough memory to allocate comment string\n\x00" as *const u8 as *const libc::c_char, ); return 0 as libc::c_int; } sprintf( (*cp).comment, b"%s%s\x00" as *const u8 as *const libc::c_char, comment.as_ptr(), version, ); }...
Rust
0
from utils.gemini_client import get_gemini from langchain.prompts import ( PromptTemplate, FewShotPromptTemplate, FewShotChatMessagePromptTemplate, ChatPromptTemplate, ) chat = get_gemini() # Few Shot Examples examples = [ {"input": "2+2", "output": "4"}, {"input": "2+3", "output": "5"}, ] ex...
Python
1
odels::InlineObject, ) -> Result<(), Error>; fn close_conversation( &self, conversation_id: &str, bot_id: &str, user_id: &str, channel_id: &str, inline_object1: crate::models::InlineObject1, ) -> Result<(), Error>; fn create_conversation( &self, ...
Rust
0
nt `Eq`, `Ord`, and `Hash` if they do not contain a `double` value, `Copy` if they //! wrap a copyable primitive type, `Default` if they wrap a type implementing `Default`, and `Display` if they wrap a //! type implementing `Display`. #![warn(clippy::all, missing_docs)] #![doc(html_root_url = "https://docs.rs/conjure-c...
Rust
0
} if 0 != self_delimited { let sdlen: c_int = encode_size(i32::from(*len.offset((count - 1i32) as isize)), ptr); ptr = ptr.offset(sdlen as isize) } i = 0i32; while i < count { memmove( ptr as *mut c_void, *frames.offset(i as isize) as *const c_void, ...
Rust
0
impl_sha3!(Sha3_384Core, Sha3_384, U48, U104, SHA3, "SHA-3-384"); impl_sha3!(Sha3_512Core, Sha3_512, U64, U72, SHA3, "SHA-3-512"); impl_shake!( Shake128Core, Shake128, Shake128ReaderCore, Shake128Reader, U168, SHAKE, "SHAKE128", ); impl_shake!( Shake256Core, Shake256, Shake256Re...
Rust
0
ve(Serialize)] #[serde(untagged)] pub enum InlineQueryResult{ Article(InlineQueryResultArticle), Voice(InlineQueryResultVoice) } #[derive(Serialize)] pub struct InlineQueryResultArticle{ #[serde(rename(serialize = "type"))] pub query_type: String, id: u8, title: String, input_message_conten...
Rust
0
self._atoms.append(atom) else: self.coord = atom.coord self._atoms = [atom] @property def magmom(self): """ Calculates the composition weighted average magnetic moment of the atoms on the Site. Returns: float or None ...
Python
1
_type() { let b = || BI::Boolean.into_plain().into_type(); parse_ok!(type_tag, "[4]", TypeTag::new(4)); parse_ok!(type_tag, "[UNIVERSAL 77]", TypeTag::new(77).universal()); parse_ok!( type_tag, "[APPLICATION 23] IMPLICIT", TypeTag::new(23).application(...
Rust
0
for (idx, (name, _)) in item_list.iter().enumerate() { unsafe { AppendMenuW(handle, MF_STRING, WM_USER as usize + idx, name.clone()) }.ok()?; } let menu = ContextMenu { handler_list: item_list.into_iter().map(|(_, handler)| handler).collect(), handle, ...
Rust
0
# === Parameters for Multimodal EEG-fNIRS Project (TU Berlin Dataset) === # Scaling EEG microvolt data (if needed) SCALE_MICROVOLTS = 1e-3 # Sampling rates FREQ_LSL = 500 # EEG sample rate (Hz) FREQ_MODEL = 100 # (Optional) Target sample rate for model input LINE_NOISE_FREQ = 60 # Notch filter frequ...
Python
1
ithm will /// clamp results if passed factor is out of range. /// # Example /// /// ``` /// use photon_rs::effects::adjust_contrast; /// use photon_rs::native::open_image; /// /// let mut img = open_image("img.jpg"); /// adjust_contrast(&mut img, 30_f32); /// ``` #[wasm_bindgen] pub fn adjust_contrast(mut photon_image:...
Rust
0
import os import numpy as np import random # Function to EEG data, provided by EE C247 class def load_data(dir_path): X_test = np.load(os.path.join(dir_path,"X_test.npy")) X_test = np.expand_dims(X_test,axis=-1) y_test = np.load(os.path.join(dir_path,"y_test.npy")) y_test -= np.amin(y_test) pers...
Python
1
self.validator.check_svg_type(x, 'coordinate') self.validator.check_svg_type(y, 'coordinate') if self.profile == 'tiny': if isinstance(x, float): x = round(x, 4) if isinstance(y, float): y = round(y, 4) p...
Python
1
#!/usr/bin/env python import re import sys from os import path as op from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand def _read(fname): try: return open(op.join(op.dirname(__file__), fname)).read() except IOError: return '' _meta = _read('a...
Python
1
but # but that converts forward slashes to backslashes and this causes # its own set of problems. if url.startswith('file://'): filename = urllib.parse.urlparse(url).path if re.match(r'^/[a-zA-Z]:', filename): filename = filename[1:] return filename if return_filename els...
Python
1
c = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | ((value as u32 & 0x01) << 2); self.w } } #[doc = "Field `CH3REQMASKC` writer - Channel 3 Request Mask Clear"] pub struct CH3REQMASKC_W<'a> { w:...
Rust
0
import re from unidecode import unidecode import pyopenjtalk # Regular expression matching Japanese without punctuation marks: _japanese_characters = re.compile( r'[A-Za-z\d\u3005\u3040-\u30ff\u4e00-\u9fff\uff11-\uff19\uff21-\uff3a\uff41-\uff5a\uff66-\uff9d]') # Regular expression matching non-Japanese character...
Python
1
<Dst>; } impl<T> OverflowingAs for T { #[inline] #[cfg_attr(track_caller, track_caller)] fn overflowing_as<Dst>(self) -> (Dst, bool) where Self: OverflowingCast<Dst>, { self.overflowing_cast() } } /** Used to cast values, panicking if the value does not fit. This is a convenie...
Rust
0
been processed. """ index = 0 for command_failed in self.commands_failed: logger.error(f"The {command_failed.title} command with PID {command_failed._process.pid} failed.") logger.error(command_failed.stderr) while self.commands_in_progress: if ...
Python
1
/// Line-drawing iterator pub struct Bresenham { x: i32, y: i32, dx: i32, dy: i32, x1: i32, diff: i32, octant: Octant, } struct Octant(u8); impl Octant { /// adapted from http://codereview.stackexchange.com/a/95551 #[inline] fn from_points(start: Point, end: Point) -> Octant ...
Rust
0
_loop.manual_loop.optim_step_progress" ) return checkpoint def _migrate_loop_structure_after_dataloader_loop_removal(checkpoint: _CHECKPOINT) -> _CHECKPOINT: """The dataloader loops (``_DataLoaderLoop``, ``_PredictionLoop`, and ``_EvaluationLoop``) were flattened into the ``_EvaluationEpochLoop`` ...
Python
1
"""Definitions used in data processing.""" import polars as pl # Dictionary mapping Status integer to string state_dict = { 1: "CC_Chg", 2: "CC_DChg", 3: "CV_Chg", 4: "Rest", 5: "cycle_count", 7: "CCCV_Chg", 8: "CP_DChg", 9: "CP_Chg", 10: "CR_DChg", 13: "Pause", 16: "Pulse"...
Python
1
box.add(label) button = toga.Button("Ok", on_press=on_press, style=Pack(padding=10)) button.install_object = install_object box.add(button) self.main_window.content = box async def gen_version(self, config): """gera a versão dos arquivos""" version = {} ...
Python
1
labels: self.labels, value: self.value, timestamp: Some(timestamp), value_set: PhantomData {}, } } /// Adds the current timestamp to the instance. The timestamp /// is calculated as milliseconds from the current `UNIX_EPOCH` as per /// specification. /...
Rust
0
import sys from typing import TYPE_CHECKING if TYPE_CHECKING: from ._x import X from ._y import Y from ._z import Z from . import x from . import y from . import z else: from _plotly_utils.importers import relative_import __all__, __getattr__, __dir__ = relative_import( __name_...
Python
1
# -*- ecoding: utf-8 -*- # @ModuleName: mobility_generation # @Function: 用深圳市的home-based flow拟合gravity model,为其他三个城市生成flow # # @Time: 2023/12/27 19:41 import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib as mpl import pickle from sklearn.linear_model import LinearRegression from skle...
Python
1
!("{:?}", encoded); } #[allow(dead_code)] fn test_b_tree_map() { let mut tree: BTreeMap<u32, u32> = BTreeMap::new(); for ii in 0..256 { tree.insert(ii, 0); } let lower: Vec<(u32, u32)> = tree .range((Included(&0), Included(&128))) .map(|(&k, &v)| (k, v)) .collect(); ...
Rust
0
(always)] pub fn is_aux_timer2_ev1(&self) -> bool { *self == WU1_EV_A::AUX_TIMER2_EV1 } #[doc = "Checks if the value of the field is `AUX_TIMER2_EV0`"] #[inline(always)] pub fn is_aux_timer2_ev0(&self) -> bool { *self == WU1_EV_A::AUX_TIMER2_EV0 } #[doc = "Checks if the value...
Rust
0
fsadagrad(z.parameters, lr=lr_schedule, momentum=momentum_schedule) trainer = C.Trainer(z, (loss, error), [learner]) # training loss_summary = [] start = time.time() for epoch in range(0, ep...
Python
1
Without a logger, all log data is"] #[doc = " silently discarded."] pub fn vnc_Logger_destroyLogger(); } <gh_stars>100-1000 use std::{ cell::RefCell, rc::Rc, sync::{atomic::Ordering, Mutex}, }; use smithay::{ reexports::{ wayland_protocols::xdg_shell::server::xdg_toplevel, way...
Rust
0
true } fn should_use_shadow_stacks(&self) -> bool { false } fn should_use_context_management(&self) -> bool { false } fn should_use_accel_raise_pri(&self) -> bool { false } fn should_use_icall_sanitizer(&self) -> bool { false } fn name(&self) ...
Rust
0
b'p', ], storage_key, value_key: key, }; self.hash_builder .borrow_mut() .hash_encoded(&key_pair) .into() } /// Returns an offset key for the given key. fn key_at<Q>(&self, key: &Q) -> Option<Key> where K: ...
Rust
0
es[j] = 0; j += i; } } } i += 1; } ans } /// 力扣(263. 丑数) https://leetcode-cn.com/problems/ugly-number/ /// 丑数 就是只包含质因数 2、3 和/或 5 的正整数。 /// 1 通常被视为丑数。 pub fn is_ugly(num: i32) -> bool { if num <= 0 { return false; } let mut n...
Rust
0
n::Dispatch::new() .format(|out, message, record| { out.finish(format_args!( "{}[{}][{}] {}", Local::now().format("[%Y-%m-%d][%H:%M:%S]"), record.target(), record.level(), message )) }) .chain...
Rust
0
ue: int): """HPを設定""" if self.derived_stats: self.derived_stats.hp = max(0, value) @property def max_hp(self) -> int: """最大HP""" return getattr(self.derived_stats, 'max_hp', 0) if self.derived_stats else 0 def gain_experience(self, amount: int) -> bool: ...
Python
1
ctError::*; use self::SocketAddr::*; let is_blocked = match remote_address { V4(internet_protocol_version_4_address) => self.internet_protocol_version_4_access_control_list.longest_match(internet_protocol_version_4_address).is_none(), V6(internet_protocol_version_6_address) => self.internet_protocol_versio...
Rust
0
2D or 3D.") axes = "YX" if len(patch_size) == 2 else "ZYX" shannon_img = np.zeros_like(image, dtype=float) extractor = create_array_extractor(source=[image], axes=axes) tiling = TilingStrategy( data_shapes=[(1, 1, *image.shape)], tile_size=patch_size, ...
Python
1
usty Life") .padding((1, 1, 1, 0)) .content(TextView::new("").with_id("text")) .with_id("dialog") ); siv.run(); } fn randomize_life(matrix_size: i32) -> Vec<Vec<bool>> { let mut randomized_matrix: Vec<Vec<bool>> = Vec::new(); let mut thread_rng = rand::thread_rng();...
Rust
0
import matplotlib.pyplot as plt import matplotlib.image as mpimg import csv def plot_gps_on_map_with_image(map_image_path, gps_csv, map_bounds): img = mpimg.imread(map_image_path) min_lat, max_lat = map_bounds['min_lat'], map_bounds['max_lat'] min_lon, max_lon = map_bounds['min_lon'], map_bound...
Python
1
, '𝔱', 'ᦻ', '𑤓', '\u{11439}', '𑇱', 'ᙀ', '∊', '𒿨', '𒆑', '𒄦', '𐙟', '⓹', '𐊅', '\u{1e01e}', 'ꅪ', '𝠡', 'ஸ', '𘳋', '\u{11a98}', '𖹋', '𖠰', '𘭔', 'Ở', 'ኑ', 'ꭻ', '¼', 'ꔱ', 'ȶ', '𝌥', '𒃆', '🔗', '𑖮', '🥮', 'ꔵ', 'ܔ', '𒎀', 'ꪽ', '΅', 'ꥠ', '𐺛', '\u{aa31}', '🢦', 'ᴘ', '𓆽', '𛀥', '𑱘', '𛄒', '𓍱', '...
Rust
0
length_lookup_component_uint; let b2_uint = &b_uint / &two_to_bit_length_lookup_component_uint; let z_uint = (&a_uint - &b_uint) / &modulus_uint; let z1_uint = &z_uint % &two_to_delta_length_lookup_component_uint; let z2_uint = &z_uint / &two_to_delta_length_lookup_component_uint; ...
Rust
0
x(); let mut covariance_matrix_scaled = DMatrix::<f64>::zeros(3, 3); for i in 0..covariance_matrix.len() { covariance_matrix_scaled[i] = covariance_matrix[i] / scale; } // scale the matrix down for (index, value) in covariance_matrix.iter().enumerate() { covariance_matrix_scaled[ind...
Rust
0
m: i8, span: Span, arg: Span) { if let Some(Constant::Int(v)) = constant_simple(cx, e) { if match m { 0 => v.to_u128_unchecked() == 0, -1 => all_ones(&v), 1 => v.to_u128_unchecked() == 1, _ => unreachable!(), } { span_lint( ...
Rust
0
API response")?), 401 => Err(anyhow!("Invalid API key")), 403 => Err(anyhow!("Access denied")), 404 => Err(anyhow!( "Failed to find a check with the uuid: {}", check_id )), _ => Err(anyhow!("Unexpected error: {}", resp.error())...
Rust
0
<$SPIX, $WORD> {} impl hal::blocking::spi::write::Default<$WORD> for Spi<$SPIX, $WORD> {} )+ )+ } } macro_rules! pins { ($($SPIX:ty: SCK: [$($SCK:ty),*] MISO: [$($MISO:ty),*] MOSI: [$($MOSI:ty),*])+) => { $( $( impl Pi...
Rust
0
pub resource: Resource, pub kind: AlertRuleKindEnum, } impl AlertRuleTemplate { pub fn new(kind: AlertRuleKindEnum) -> Self { Self { resource: Resource::default(), kind, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct AlertRuleTemp...
Rust
0
from langchain_openai import ChatOpenAI from config import OPENAI_API_KEY class OpenAIAgent: """OpenAI agent class to allow OpenAI models to be used for experts""" def __init__(self, model_name="gpt-4.1"): api_key = OPENAI_API_KEY if not api_key: raise ValueError("Missing OpenAI A...
Python
1
""" @file scene_dataset.py @author Jianfei Guo, Shanghai AI Lab @brief Dataset implementation abstract interfaces. """ import numpy as np from typing import Any, Dict, List, Literal, Tuple, Union from abc import ABC, abstractmethod from nr3d_lib.config import ConfigDict class SceneDataset(ABC): @abstractmetho...
Python
1
ze overflowed"); // let quota = ResourceQuota::new(Some("DatenLordWokerQuota")).resize_memory(mem_size); // let ch_builder = ChannelBuilder::new(Arc::<Environment>::clone(&env)).set_resource_quota(quota); // TODO: increase concurrent queue size let controller_server = grpcio::ServerBuilder::new(Arc::new...
Rust
0
Optional[VersionedTransaction]: """ Build and sign a transaction from a trading signal. Args: signal: Trading signal Returns: Signed VersionedTransaction or None if failed """ # 🚀 REAL PROFIT GENERATION: Use actual swaps instead of placeholders ...
Python
1
at(x as uint, y as uint).solid { return y; } } } end_y } use diesel::result::Error; use crate::utils::connections::*; pub trait CRUD<CreatedModel, UpdateModel, PK> { fn create(conn: DB, from: &CreatedModel) -> Result<Self, Error> where Self: Sized; fn r...
Rust
0
from collections import defaultdict class RangeFreqQuery: def __init__(self, arr): """ Initializes the class with the given array `arr`. """ self.frequency = defaultdict(list) for idx, value in enumerate(arr): self.frequency[value].append(idx) def query(self...
Python
1
O_ASSEMBLYREFOS_ASSEMBLYREF: ::std::os::raw::c_int = 3; pub const MONO_ASSEMBLYREFOS_SIZE: ::std::os::raw::c_int = 4; pub type _bindgen_ty_5 = ::std::os::raw::c_int; pub const MONO_ASSEMBLYREFPROC_PROCESSOR: ::std::os::raw::c_int = 0; pub const MONO_ASSEMBLYREFPROC_ASSEMBLYREF: ::std::os::raw::c_int = 1; pub const MONO...
Rust
0
Error) -> Self { Self::Test(inner) } } impl From<SetupCommandError> for Error { fn from(inner: SetupCommandError) -> Self { Self::Setup(inner) } } impl From<ProveCommandError> for Error { fn from(inner: ProveCommandError) -> Self { Self::Prove(inner) } } impl From<VerifyCo...
Rust
0
from __future__ import annotations import logging import os import signal import watchdog.events import watchdog.observers.polling try: import watchdog_gevent EVENTED_OBSERVER = watchdog_gevent.Observer except ImportError: EVENTED_OBSERVER = watchdog.observers.Observer def setup_file_watcher(path, use...
Python
1
0, 500, 750, 1000] for test_hz in test_frequencies: try: result = await self.benchmark_frequency(test_hz, test_duration) # Consider successful if we achieve >80% of target frequency if result['frequency_accuracy'] >= 0.8: ...
Python
1
sym.to_string() } pub static PRIM_APPEND: FoldErr<RDatum> = FoldErr { fold: append }; fn append(mut lists: Vec<RDatum>) -> Result<RDatum, RuntimeError> { let mut res = match lists.pop() { Some(elem) => elem, None => return Ok(Datum::Nil) }; loop { match lists.pop() { ...
Rust
0
@classmethod def from_json(cls, json): return cls( html_type=str(json['htmlType']), id_=str(json['id']), name=str(json['name']), value=str(json['value']), autofill_type=str(json['autofillType']), filling_strategy=FillingStrategy.from_...
Python
1
rom_args(); if let Err(err) = setup_logger(opt.verbose, &opt.log_file) { eprintln!("Error initializing logger. {:?}", err); process::exit(1); } info!("Verbosity level {}", opt.verbose); let full_text = opt.text.join(" "); debug!("Input arg count: {}", opt.text.len()); debug!("...
Rust
0
name.len() - 1]; let mut names = Vec::new(); for number in start..end { let character = Self::number_to_char(number)?; let name = format!("{}{:X}", name_template, number); names.push((character, name)); } Ok(names) } // or single codepoints ...
Rust
0
} pub fn mock_env<U: Into<HumanAddr>>(sender: U, sent: &[Coin], height: u64, time: u64) -> Env { Env { block: BlockInfo { height, time: time, chain_id: "secret-testnet".to_string(), }, message: MessageInfo { ...
Rust
0
# flake8: noqa """Tests fp8 models against ground truth generation Note: these tests will only pass on L4 GPU. """ import os from typing import Optional import pytest from tests.kernels.utils import override_backend_env_variable from tests.quantization.utils import is_quant_method_supported from ...utils import chec...
Python
1
b1, m, search, search_m = tracker.track(image) handle.report(m) if VIS: '''Visualization''' # original image image_ori = image[:, :, ::-1].copy() # RGB --> BGR image_name = imagefile.split('/')[-1] save_path = os.path.join(save_dir, image_name...
Python
1
import hecate as hc import sys def sqrt(x) : term1 = x * hc.Plain([2.214]) x2 = x*x term2 = x2 * hc.Plain([-1.098]) term3 = term1 + term2 x2_1 = x*x x3 = x2_1 *x term4 = x3 * hc.Plain([0.173]) term5 = term3+term4 return term5 def sum_elements(data): i = 4096 for i in r...
Python
1
_BLOB_FILE: &str = "rocksdb.titandb.\ num-obsolete-blob-file"; pub const ROCKSDB_TITANDB_LIVE_BLOB_FILE_SIZE: &str = "rocksdb.titandb.\ live-blob-file-size"; pub const ROCKSDB_TITANDB_OBSOLETE_BLOB_FILE_SIZE...
Rust
0
statement by selecting the row with the latest Publish Date latest_income = filtered_df.loc[filtered_df["Publish Date"].idxmax()] # drop the SimFinID column latest_income = latest_income.drop("SimFinId") return ( f"## {freq} income statement for {ticker} released on {str(latest_income['Publish...
Python
1
cret_key.as_ptr(), public_key.as_mut_ptr()); } } pub fn ed25519_donna_sign( message: &[u8], secret_key: &[u8; 32], public_key: &[u8; 32], ) -> [u8; 64] { let mut signature: [u8; 64] = [0u8; 64]; let message_len: size_t = message.len(); unsafe { ed25519_sign( message.as_...
Rust
0
ponentT>, } impl<ComponentT: Component> ComponentLink<ComponentT> { /// Sends a message to the component. pub fn send(&self, message: ComponentT::Message) { self.sender.send(ComponentMessage(LinkMessage::Component( self.component_id, DynamicMessage(Box::new(message)), ))...
Rust
0
env_action = np.concatenate(env_action, axis=-1) return env_action def get_replay_hra_action( action: np.ndarray, env_obs: Dict[str, np.ndarray], action_pose_repr: str='abs', calib_cam2base: np.ndarray=None, hand_to_eef: np.ndarray=None, n_robots: int=1,...
Python
1