text
string
label_name
string
labels
int64
# MIT License # # Copyright (c) [2025] [Ashwin Natarajan] # # 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, copy, modify...
Python
1
h_restriction, mesh_basis, libceed.VECTOR_ACTIVE) op_build.set_field("weights", libceed.ELEMRESTRICTION_NONE, mesh_basis, libceed.VECTOR_NONE) op_build.set_field("qdata", q_data_restriction, libceed.BASIS_NONE, libceed.VECTOR_ACTIVE) # Compute the quadrature data for the mass + diffusion operator q_dat...
Python
1
from typing import Optional from ray._private.accelerators import TPUAcceleratorManager from ray.util.annotations import PublicAPI @PublicAPI(stability="alpha") def get_current_pod_name() -> Optional[str]: """ Return the name of the TPU pod that the worker is a part of. Returns: The name of the T...
Python
1
"""Page crawler package."""
Python
1
config`. #[derive(Debug, Deserialize, Serialize, PartialEq)] struct ExampleConfig { not_from_package: u8, } /// The platform BuildTypes. /// /// These control security and behavioral settings within the platform. /// /// Not presently used. #[derive(Debug, Deserialize, Serialize, PartialEq)] pub enum BuildType { ...
Rust
0
target { high = mid as i8 - 1; } } return None; } fn main() { let err_msg = "Usage: please provide a list of sorted integers \"1, 4, 5, 11, 12\" and the integer to find \"11\""; let args: Vec<String> = env::args().collect(); if args.len() < 3 { panic!(err_msg); } let arr: Vec<i32> = a...
Rust
0
model: WDModel, model_name: str, loader: DataLoader, optimizer: Optimizer, scheduler: LRScheduler, n_epochs: int = 1, idx: Optional[int] = None, ): r""" Standard Pytorch training loop """ steps = len(loader) for epoch in range(n...
Python
1
alue_id(), self.input2_id.value_id(), self.output_id.gradient_id()], vec![self.input1_id.gradient_id(), self.input2_id.gradient_id()]) } fn run (&self, data: &Storage) -> Result<Box<Any>>{ let input1 = data.get(&self.input1_id.value_id())?; let input2 = data.get(&self.input2_id.value_id())?; let output_grad ...
Rust
0
from easy.message import * from easy import Config from tradingBot.coins.coin import Coin from tradingBot.model.queueManager import QueueManager def checkingTurnover(config: Config, pricesQueueManager: QueueManager): averageTurnover = pricesQueueManager.getAverage("turnover") lastStamp = pricesQueueManager.get...
Python
1
import pytest import time from utils.exception_handler.decorator_error_handler import exception_handler from pages.my_files_editor_page import MyFilesEditorPage from locators.my_files_editor_locators import MyFilesEditorLocators import allure @allure.severity(allure.severity_level.CRITICAL) # TRIVIAL, MINOR, NORMAL, C...
Python
1
ERS.write() { if let Some(renderer) = renderers.get_mut(renderer) { match renderer.renderer.add_resource(id.to_owned(), resource) { Ok(id) => Ok(id.to_string()), Err(error) => Err(format!("{:#?}", error).into()), } } else { Err(format!(...
Rust
0
max(width, d * 1.5) x, y = x0, y0 x -= width y -= width if x < 0: x = 0 if y < 0: y = 0 width1 = width * 2 width2 = width * 2 if x + width > image_width: width1 = image_width - x if y + width > image_height: width2 = image_height - y width ...
Python
1
else { Some(self.tx.subscribe(buffer)) }; Ok(VecSubscription::new(VecInitialValue::new_incremental(initial, Arc::new(default_on_err)), events)) } } impl<T, Codec> Drop for MirroredVec<T, Codec> { fn drop(&mut self) { // empty } } /// A snapshot view of an observable vector. pub struct Mi...
Rust
0
n = int(input('enter any number')) total = 0 for i in range (1,n+1): total += 1 print('sum',total)
Python
1
assert_eq!(resp.status(), StatusCode::CREATED); let body: serde_json::Value = resp.json().await?; app.stop(false).await; insta::assert_json_snapshot!(body, {".last_used" => "[timestamp]"}); Ok(()) } #[actix_rt::test] async fn create_conflict() -> anyhow::Result<()> { let app = initialize_se...
Rust
0
true } pub fn log(&self) { info!("Summary:"); for tal in &self.tals { info!( "{}: {} valid ROAs, {} VRPs.", tal.tal.name(), tal.roas, tal.vrps ) } } } impl Default for Metrics { fn default() -> Self { Self::new() ...
Rust
0
features: &[XML_Feature] = &[ XML_Feature { feature: XML_FeatureEnum::SIZEOF_XML_CHAR, name: wch!("sizeof(XML_Char)\x00"), value: ::std::mem::size_of::<XML_Char>() as c_long, }, XML_Feature { feature: XML_FeatureEnum::SIZEOF_XML_LCHAR, ...
Rust
0
mut offset: u64 = 0; let data = (0..batches) .map(|_b| { (0..count) .map(|_| { let result = ( Key::single(offset, offset, tags_from_offset(offset)), offset.to_string(), ); ...
Rust
0
d: %s" % framework_path ) for path in framework_directory_listing: link_points_to = os.path.join(framework_path, path) # Only want to link to directories that have the glob pattern "Qt*.framework" and # are not part of the webengine framework...
Python
1
"Predicted"] = train_predict train_predicted_df.head(3) # Passengers Predicted # Month # 1949-02-01 118.0 133.908920 # 1949-03-01 132.0 136.690216 # 1949-04-01 129.0 144.057098 test_predicted_df = df[1+position:] test_predicted_df["Predicted"] = test_predict test_predicted_df.head(3)...
Python
1
boundary { self.expand(1); } stable } } pub fn run() { let mut initial_grid = Vec::<Cell>::new(); let mut width = None; for line in io::stdin().lock().lines() { let line = line.expect("read error"); let mut items: Vec<Cell> = line.chars().map(|c| Cell::from_char(c)...
Rust
0
_none() { min_dist = Some(dist); step_options = vec![step_option]; } else if dist == min_dist.unwrap() { step_options.push(step_option); } else if dist < min_dist.unwrap() { min_dist = Some(dist); ...
Rust
0
flags: u8, sgx_tcb_evaluation_flags: u16, pse_evaluation_flags: u16, latest_equivalent_tcb_psvn: tcb_psvn_t, latest_pse_isvsvn: pse_isvsvn_t, latest_psda_svn: psda_svn_t, xeid: u32, gid: u32, signature: sgx_ec256_signature_t, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ...
Rust
0
ith the promotion event." ) @staticmethod def resolve_rule_id(root: models.PromotionEvent, _info): return root.parameters.get("rule_id", None) class PromotionRuleCreatedEvent(ModelObjectType[models.PromotionEvent]): class Meta: description = ( "History log of the promotion...
Python
1
+ʧeb@~mAS{L42܃7e"F_֐~FPgԊ ċp4(](;D$݃@c) `PGP#2[6W0\bshQF|okgr-] Qԍs*`UC?.EF_l D5 m( RF[ 5܋ۺ1oH C,SK3ѐzCHeB; *@JǦ6rLfluSeEd/&cs/kitݺ ^%GQ:T  GT HҠ k2c:w^{H<P_}%w X#TczN pH;Cݰ4ťFSꃽu3Z>?},YVCwruF.( Jү8#LJdR4TFԖo€ j\X$v dPb|7qo5Y꒎|qG@%ǥNr$j(8*'q*6#e/:8pljʁa"...
Python
1
import sys import os from sentence_transformers import SentenceTransformer, util import pandas as pd # Añadir el directorio del servidor al path para resolver las importaciones sys.path.append(os.path.dirname(os.path.abspath(__file__))) # Cargar el archivo Excel df = pd.read_excel('data/Base_conocimiento_pre.xlsx') ...
Python
1
p(); assert_eq!(clean_root_hash, corrupt_root_hash); missing_trie_keys_should_find_key_of_corrupt_value::<TestKey, TestValue, _, _, error::Error>( correlation_id, &clean_context.environment, &clean_context.store, &corrupt_context.environment, &corrupt_context.store, ...
Rust
0
); unsafe_pinned!(sink: VecDeque<Out>); unsafe_unpinned!(in_flight_requests: FnvHashSet<u64>); } impl<In, Out> Stream for FakeChannel<In, Out> where In: Unpin, { type Item = In; fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { self.stream().poll_next(cx) ...
Rust
0
from tkinter import * root = Tk() myB = Button(root, text="Click Me", padx=40, pady=20) #padx increase weight #pady increase height myB.pack() root.mainloop() #Himel Sarder #Dept. of CSE, BSFMSTU
Python
1
}) return JsonResponse({'success': False, 'error': 'This email is already subscribed.'}) # Create new subscription Newsletter.objects.create(email=email) return JsonResponse({'success': True, 'message': 'Thank you for subscribing!'}) except json.JSONDecodeError: return ...
Python
1
ring.replace(comment, "") return string string = remove_comments_by_regex(string, r"'''(.*?)'''") string = remove_comments_by_regex(string, r"\"\"\"(.*?)\"\"\"") return string def get_text_embedding(text: str): if text == "": text = "None" ada_embedd...
Python
1
from odoo import models class L10nLatamDocumentType(models.Model): _inherit = "l10n_latam.document.type" def _l10n_uy_edi_get_move_type(self, journal_type="purchase"): """ This method should be moved to latam module in future versions, will be available in 18, is a temporal method here. It is necessa...
Python
1
# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
Python
1
# Copyright 2016 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
Python
1
""" Copyright 2019 kivou.2000607@gmail.com This file is part of yata. yata is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. yata is dist...
Python
1
# This file was auto-generated by Fern from our API Definition. from ..core.unchecked_base_model import UncheckedBaseModel import pydantic from .tool_message_v2content import ToolMessageV2Content from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing class ToolMessageV2(UncheckedBaseModel): """ A...
Python
1
"""Unit tests for the handlers module.""" # pylint: disable=C0116 # pylint: disable=W0613 # pylint: disable=C0413 # pylint: disable=E0401 import unittest from unittest.mock import patch, MagicMock import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../src"))) import main c...
Python
1
Public) -> Self { Self::Ed25519(x) } } impl TryFrom<MultiSigner> for ed25519::Public { type Error = (); fn try_from(m: MultiSigner) -> Result<Self, Self::Error> { if let MultiSigner::Ed25519(x) = m { Ok(x) } else { Err(()) } } } impl From<sr25519::Public> for MultiSigner { fn from(x: sr25519::Public) -> Self...
Rust
0
rd. "Using the “Chandrasekhar Recursions” for likelihood # evaluation of DSGE models." Computational Economics 45, no. 4 (2015): # 693-705. # # Koopman, Siem J., and James Durbin. "Fast filtering and smoothing for # multivariate state space models." Journal of Time Series Analysis 21, no. # 3 (2000): 281-296. # # McAda...
Python
1
s_secret_access_key, region_name=region_name ) # Specify the bucket name bucket_name = 'your_bucket_name' # Specify the prefix of the files you want to delete file_prefix_to_delete = 'prefix_to_delete/' # List objects in the specified S3 bucket with the specified prefix response = s3_client.list_objects_v2(Bucke...
Python
1
: i32 = num.parse().unwrap(); if current > large { large = current; } if current < small { small = current; } } sum += large - small; } println!("Part1: {}", sum); } fn part2(rows: &Vec<&str>) { let mut sum: ...
Rust
0
# -*- coding: utf-8 -*- """ Created on Tue Dec 24 15:54:36 2019 @author: zixing.mei """ from pyod.models.iforest import IForest clf = IForest(behaviour='new', bootstrap=False, contamination=0.1, max_features=1.0, max_samples='auto', n_estimators=500, n_jobs=-1, random_state=None,verbose=0) clf.fit(x) ...
Python
1
" )] fn test_all_blackholed_never_succeeds(fail_addrs: Vec<SocketAddr>) { let mut executor = fasync::Executor::new_with_fake_time().unwrap(); let mut connector = TestEnvConnector::new(None).add_classified_addrs(Class::Blackholed, fail_addrs.clone()); let mut fut = happy_eye...
Rust
0
ge; pub use self::mapper::*; pub use self::virtual_address_allocator::*; use core::{ ops::{Deref, DerefMut}, fmt, }; use super::*; use kernel_config::memory::{RECURSIVE_P4_INDEX}; use kernel_config::memory::{KERNEL_TEXT_P4_INDEX, KERNEL_HEAP_P4_INDEX, KERNEL_STACK_P4_INDEX}; /// A root (P4) page table. /// ...
Rust
0
yers = num_hidden_layers self.num_attention_heads = num_attention_heads self.hidden_act = hidden_act self.intermediate_size = intermediate_size self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_positio...
Python
1
import cv2 #opencv import time #delay import imutils #resize cam = cv2.VideoCapture(0) #cam id time.sleep(1) firstFrame=None area = 500 while True: _,img = cam.read() #read from the camera text = "Normal" img = imutils.resize(img, width=1000) #resize grayImg = cv2.cvtColor(img, cv2.COLOR_BGR2...
Python
1
12744ebb0f770d5c41d99189f9457495747bf11050 | // height | 4 | 10(0x0a000000) | // Issue/Transfer/Burn | 4 | 'Transfer'(0x01000000) | // txid | 32 | 59abe954...
Rust
0
from typing import TYPE_CHECKING, Dict import gradio as gr from .chatbot import create_chat_box if TYPE_CHECKING: from gradio.components import Component from ..engine import Engine def create_infer_tab(engine: "Engine") -> Dict[str, "Component"]: input_elems = engine.manager.get_base_elems() ele...
Python
1
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import argparse import re import sys class OOVIndexError(IndexError): def __init__(self, pos, source_seq, target_...
Python
1
"); config.include("zstd/lib/dictBuilder/"); } if cfg!(feature = "zlib") { config.define("ZLIB", Some("1")); config.include("zlib/"); } if cfg!(feature = "bzip2") { config.define("BZIP2", Some("1")); config.include("bzip2/"); } config.include("."); ...
Rust
0
success=False, message=error_msg, latency_ms=latency, capabilities=[] ) async def disconnect_server(self, server_id: str, user_id: str) -> bool: """断开MCP服务器连接 - 完全隔离版本,绝不影响其他服务器""" server = await self.repository.get_user_server...
Python
1
Name>, value: Local<Value>, ) -> MaybeBool { unsafe { v8__Object__CreateDataProperty(self, &*context, &*key, &*value) } } pub fn get<'a>( &self, scope: &mut impl ToLocal<'a>, context: Local<Context>, key: Local<Value>, ) -> Option<Local<'a, Value>> { unsafe { let ptr = v8__Obj...
Rust
0
#%% packages import requests import urllib.request from pathlib import Path #%% def get_dog_images(breed, count=100, type='train'): available_breeds = ['affenpinscher', 'african', 'airedale', 'akita', 'appenzeller', 'australian', 'basenji', 'beagle', 'bluetick', 'borzoi', 'bouvier', 'boxer', 'brabancon', 'briard',...
Python
1
params) # Train with early stopping callbacks = [EarlyStopping(patience=5, restore_best_weights=True)] model.fit( X_train_fold, y_train_fold, batch_size=params['batch_size'], epochs=20, # Reduced for tuning ...
Python
1
::format`]-compatible string literal, followed by a /// sequence of generator type names. The `{}`s in the string literal will be /// replaced by sampled data from each of the given generators. /// /// The macro will generate a /// [`Distribution`][`rand::distributions::Distribution`] and /// [`Display`][`std::fmt::Dis...
Rust
0
matching(self): text_matches = second_holmes_manager_coref.match( document_text='Richard Hudson made an announcement') self.assertEqual(len(text_matches), 1) self.assertEqual(text_matches[0]['word_matches'][0]['match_type'], 'entity_embedding') if version.parse(second_hol...
Python
1
} impl TestNode { pub fn new( id: &'static str, records: Arc<Mutex<CallRecords>>, reject: bool, priority: usize, ) -> Self { Self { id, records, rejected: reject, called: false, priority, } } } #[as...
Rust
0
from typing import Dict from rio_tiler.types import ColorMapType viirs_colormaps: Dict[str, ColorMapType] = { "viirs-10a1": [ ((0, 25), (43, 140, 190, 255)), ((25, 50), (116, 169, 207, 255)), ((50, 75), (189, 201, 225, 255)), ((75, 100), (241, 238, 246, 255)), ((101, 255), ...
Python
1
(Kind::Water, -3.0), (Kind::Labor, -1.0), (Kind::Fertilizer, -2.0), (Kind::FreshAir, 3.0), (Kind::Leisure, 2.0), (Kind::Community, 2.0), (Kind::Tourist, 2.0), ]); available.add_structure( "Botanical Garden", vec![ (Kind::Water, -3.0), ...
Rust
0
fn main() { let x = @3u; assert x.foo() == ~"@3"; }// Copyright 2021 iliana destroyer of worlds <<EMAIL>> // SPDX-License-Identifier: MIT-0 #![deny(rust_2018_idioms)] #![warn(clippy::pedantic)] use bytes::{Buf, Bytes}; use chrono::{DateTime, FixedOffset, Utc}; use minreq::{Method, Request}; use serde::{Deser...
Rust
0
preface the Command Status Wrapper on the buffer. pub const D_CSW_SIGNATURE: u32 = 0x5342_5355; } impl BufferPullable for CommandStatusWrapper { fn pull_from_buffer<B: AsRef<[u8]>>(buffer: B) -> Result<Self, ScsiError> { let buffer = buffer.as_ref(); let signature = LE::read_u32(buffer); ...
Rust
0
read_f64::<B>().unwrap(); let g = match buffer.read_i32::<B>().unwrap() { 0 => Enum::A, 1 => Enum::B, 2 => Enum::C, 3 => Enum::D, _ => panic!(), }; Foo { a, b, c, d, e, ...
Rust
0
shape) return dets[0] def ctdet_post_process(dets, c, s, h, w, num_classes): # dets: batch x max_dets x dim # return 1-based class det dict ret = [] # c, s, h, w = c[0], s[0], h[0], w[0] # to do # print(dets.shape) # (1, 100, 6) # print(c) for i in range(dets.shape[0]): top_preds = ...
Python
1
pub use super::plugin::TilesetPlugin; pub use super::tileset::*; } <filename>src/board.rs /// # Board draws itself. use std::io::Write; use termion::cursor; use super::cell::Cell; /// Empty char for default. const EMPTY: char = ' '; /// Top-left corner const TL: char = '╔'; /// Top-right corner const TR: char = '╗...
Rust
0
from ReminderRecords import * from RecordDataEntryMain import * from tkinter import * class NewRecordButton(Frame): def __init__(self, master, records:ReminderRecords, update_class): super().__init__(master) self.records = records self.update_class = update_class self.add_button = B...
Python
1
+ 'a>, } impl<'a, Output> BoxedParser<'a, Output> { fn new<P>(parser: P) -> Self where P: Parser<'a, Output> + 'a, { BoxedParser {parser: Box::new(parser)} } } impl<'a, Output> Parser<'a, Output> for BoxedParser<'a, Output> { fn parse(&self, input: &'a str) -> ParseResult<'a, Outp...
Rust
0
() as u64 }) }; /// The cube is assumed to have U/D faces pointing on U/D (or swapped). static ref LR: SequenceSolver<RouxLrSignature> = { let gen_set = vec![ "U", "M2", "M U2 M", "M U2 M'", "M' U2 M'", "M' U2 M", ] .into_iter() .map(|...
Rust
0
r indicating that the parser has committed to this parse. If a /// parser after this fails, other parser alternatives will not be /// attempted (`CommitErr` will be returned) Commit(T), /// Constructor indicating that the parser has not committed to this parse. /// If a parser after this fails, othe...
Rust
0
); //! Nanomsg-next-generation listeners. //! //! A listener is the object that is responsible for accepting incoming //! connections. A given listener can have many connections to multiple clients //! simultaneously. //! Directly creating a listener object is only necessary when one wishes to //! configure the liste...
Rust
0
`key` to verify cookies retrieved from the child jar. Any retrievals /// from the child jar will be made from the parent jar. /// /// # Example /// /// ```rust /// use cookie::{Cookie, CookieJar, Key}; /// /// // Generate a secure key. /// let key = Key::generate(); /// /// ...
Rust
0
he candlestick for the stock ''' budget = budget * leverage df = self.open_downloaded_stock(name) if risk_to_reward_ratio > 2: warnings.warn(f"Don't be greedy with risk to reward ratio of {risk_to_reward_ratio}. Stick to system") # delta = 0.0008 if df.l...
Python
1
("gb"); // let mut emulator = mode = match args.next() // .map(|x| x.to_lowercase().as_str()) // { // Some("gb") => GB::new((), cartridge), // Some("cgb") => CGB::new((), cartridge), // _ => unimplemented!() // }; Ok(()) } <reponame>nbrendler/rust-tetris<gh_stars>0 use ...
Rust
0
ithm::PS384 => "PS384".to_owned(), Algorithm::PS512 => "PS512".to_owned(), Algorithm::EdDSA => "EdDSA".to_owned(), } } } /// A key to use for signing and verifying. pub struct Key { val: Vec<u8>, pub alg: Algorithm, } impl AsRef<[u8]> for Key { #[inline] fn as_ref(&...
Rust
0
vs $V_{DS}$") plt.tight_layout() plt.show() # Figure 3 (Specific current density) fig, ax = plt.subplots(1, 3, figsize=(15, 5)) ax[0].plot(UDS, Js, VDS, JS, '*') ax[0].set_ylabel(r"$J_S$ [A/m$^2$]") ...
Python
1
btree_map::Entry<'a, K, Shield<V>> where K: Ord, V: Default, { fn ensure_valid(self) -> &'a mut V { self.or_insert_with(Default::default).ensure_valid() } } <filename>benches/comparison.rs<gh_stars>100-1000 //! See how `rust-decimal` performs compared to native floating numbers. use crit...
Rust
0
import _signal from _signal import * from enum import IntEnum as _IntEnum _globals = globals() _IntEnum._convert_( 'Signals', __name__, lambda name: name.isupper() and (name.startswith('SIG') and not name.startswith('SIG_')) or name.startswith('CTRL_')) _IntEnum._c...
Python
1
''' Given a folder of raw data, this script will clean the data by removing all the pages that are not interesting. It will also save the cleaned data to a new folder. ''' import os import json import numpy as np import pandas as pd from copy import deepcopy from tqdm import tqdm if __name__ == "__main__": #raw_...
Python
1
ER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //! CPU-Features info. More detailed/in-depth functionality about the CPU //! like specific instructions like AVX on x86. use derive_more::Display...
Rust
0
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. //! DKG Prometheus metrics definition use prometheus::{registe...
Rust
0
import tkinter class GuiCanvas: def __init__(self, inf_canv, image, width=1920, height=1080): self.infinite_canvas = inf_canv self.master = tkinter.Tk() # self.master.attributes("-fullscreen", True) self.label = tkinter.Label(self.master, bg='white', width=width, height=height) ...
Python
1
import torch from torch.types import _dtype from typing import Optional, Any import functools import logging logger = logging.getLogger(__name__) def autocast_decorator(autocast_instance, func): @functools.wraps(func) def decorate_autocast(*args, **kwargs): with autocast_instance: return func(*args, **k...
Python
1
ateConversionQuality_Low: oboe_SampleRateConversionQuality = 2; #[doc = " Fastest conversion but may not sound great."] #[doc = " This may be implemented using bilinear interpolation."] pub const oboe_SampleRateConversionQuality_Medium: oboe_SampleRateConversionQuality = 3; #[doc = " Fastest conversion but may not soun...
Rust
0
Transform` which only applies to 2D and only allows rotations by multiples of 90 degrees. Args: tmatr: translational matrix (if ``None``, use a unity matrix) shift: added shift (if ``None``, use a zero shift) rigid: if ``True``, only allow orthogonal transforms, i.e., no scaling """ ...
Python
1
for_shape( tileshape=tileshape, dataset_shape=ds.shape, ) for p in ds.get_partitions(): for t in p.get_tiles(tiling_scheme=tiling_scheme): pass def test_offset_smaller_than_image_count(lt_ctx): sync_offset = -286 with pytest.raises(Exception) as e: lt_ctx....
Python
1
let mut ng = next_generator::DefaultNextGenerator::new(rand_gen_ng); let next = ng.next(); let gbg = garbage_block_generator::HoritetoGarbageBlockGenerator::new(rand_gen_gbg); let params = TetrisParams::default(); GameMaster { field: field::Field::new(height, width), ...
Rust
0
def help(): print("Usage: python3 convert.py <input_file> [output_file]") print("\nConverts the data file input_file with old formatting to the new input format.") print("If output_file is not specified, the newly created file is named new_input_file.") print("The new file is created in the directory where the scri...
Python
1
_json::Value; use std::env; use std::fs::File; use std::path::{Path, PathBuf}; use std::io::prelude::*; use log::{error, debug, warn}; use std::str::FromStr; use fern; use reqwest; use reqwest::blocking::Client; mod lib; /// # The nextcloud prometheus exporter /// * loads the xml status page exposed by a nextcloud ...
Rust
0
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
Python
1
num = input("Введите четырехзначное число: ") print(f"{num[3] + num[2] + num[1] + num[0]}") print(f"{int(num[2] + num[3] + num[0] + num[1])}") num_pro1 = str(int(num) // 100) num_pro2 = str(int(num) % 100) print(num_pro2 + num_pro1)
Python
1
onst GL_REG_20_ATI: u32 = 35125; pub const GL_REG_21_ATI: u32 = 35126; pub const GL_REG_22_ATI: u32 = 35127; pub const GL_REG_23_ATI: u32 = 35128; pub const GL_REG_24_ATI: u32 = 35129; pub const GL_REG_25_ATI: u32 = 35130; pub const GL_REG_26_ATI: u32 = 35131; pub const GL_REG_27_ATI: u32 = 35132; pub const GL_REG_28_A...
Rust
0
x4, x4); let z1 = z + z; // acos let z3 = self.cmp_lt(f32x8::ZERO).blend(f32x8::PI - z1, z1); let z4 = f32x8::FRAC_PI_2 - z.flip_signs(self); let acos = big.blend(z3, z4); acos } #[inline] #[must_use] #[allow(non_upper_case_globals)] pub fn sin_cos(self) -> (Self, Self) { // Ba...
Rust
0
e(false), ), vec!["deps", "deployments"], noop_complete!(), IntoIter::new([]), |matches, env, writer| { let (request, _response_body) = match &env.namespace { Some(ns) => apps_api::Deployment::list_namespaced_deployment(ns, Default::default())?, None => apps_api::...
Rust
0
td::{DepsMut, Env, MessageInfo, Response}; use valkyrie::common::ContractResult; use valkyrie::governance::execute_msgs::ContractConfigInitMsg; use super::states::ContractConfig; use valkyrie::utils::make_response; pub fn instantiate( deps: DepsMut, env: Env, _info: MessageInfo, msg: ContractConfigIn...
Rust
0
// TryParseIp::try_parse_ip(*self) // } // } impl TryParseIp for Name { /// Always returns none for Name, it assumes something that is already a name, wants to be a name fn try_parse_ip(&self) -> Option<RData> { None } } impl<'a, T> TryParseIp for &'a T where T: TryParseIp + ?Size...
Rust
0
u64, minimum_amount_out: u64, ) -> ProgramResult { let rebalance_assets: Vec<RebalanceAsset> = rebalance_asset_from_account_infos(ctx.remaining_accounts)?; // prematurely return if there are no rebalance operations to perform if rebalance_assets.len() == 0 { return Ok(()); } /...
Rust
0
p::with_capacity(3); testnet_addresses.insert(FundingStreamReceiver::Ecc, FUNDING_STREAM_ECC_ADDRESSES_TESTNET.iter().map(|a| a.to_string()).collect()); testnet_addresses.insert(FundingStreamReceiver::ZcashFoundation, FUNDING_STREAM_ZF_ADDRESSES_TESTNET.iter().map(|a| a.to_string()).collect()); ...
Rust
0
XSIZE, YSIZE> { assert!(XSIZE == 5); assert!(YSIZE == 5); let n = *self as usize; if n > pendolino::PRINTABLE_START && n < pendolino::PRINTABLE_START + pendolino::PRINTABLE_COUNT { frame_5x5(&pendolino::PENDOLINO3[n - pendolino::PRINTABLE_START]) ...
Rust
0
] Unauthorized, #[error("bad request")] BadRequest, #[error("api error code {0}: {1}")] Api(u16, String), #[error("reqwest error")] Reqwest(reqwest::Error), } impl From<reqwest::Error> for Error { fn from(e: reqwest::Error) -> Self { match e.status() { Some(code) if...
Rust
0
} pub fn set_nonblocking(&self, value: bool) -> anyhow::Result<()> { Ok(self.socket.set_nonblocking(value)?) } pub fn set_timeout(&self, value: Option<Duration>) -> anyhow::Result<()> { self.socket.set_read_timeout(value)?; self.socket.set_write_timeout(value)?; Ok(()) ...
Rust
0
from typing import List, Dict import requests from . import Engine from .. import DeliveryNotMade class MailgunDeliveryEngine(Engine): def __init__(self, api_key, domain_name): self.api_key = api_key self.domain_name = domain_name self._requests = requests def send_simple_message(se...
Python
1