text
string
label_name
string
labels
int64
OptionalKernelFn<Args>>::Output>, { self.kernel_instance_opt().unwrap() } } impl OptionalKernelFn<()> for () { type Output = (); fn call_optionally(&self, _: ()) -> Self::Output { () } fn has_instance(&self) -> bool { false } fn kernel_instance_opt(&self) -> Option<KernelI...
Rust
0
//! # } //! # fn main() { //! # run().unwrap(); //! # } //! ``` //! //! # Features //! //! This library requires the standard library (`no_std` is currently not //! supported). //! //! [`byteorder`]: https://docs.rs/byteorder //! [`Endian`]: trait.Endian.html //! [`Endianness`]: enum.Endianness.html //! [`ByteOrdered`]...
Rust
0
from app import app # Si necesitas referenciar la app, puedes hacerlo from dash import html layout = html.Div([ html.H1("Bienvenido a la Página Principal"), html.Div([ html.Div([ html.A([ html.Img( src='/assets/VILDOZA.png', style={ ...
Python
1
))?); } { let snapshot = track!(storage.journal_snapshot())?; assert_eq!(snapshot.unreleased_head, 0); assert_eq!(snapshot.head, 0); assert_eq!(snapshot.tail, 2100); } track!(storage.journal_gc())?; { let snapshot = tra...
Rust
0
# my_cache_manager/cache_manager_factory.py import os from .adapters.redis_cache_manager import RedisCacheManager from .adapters.memcached_cache_manager import MemcachedCacheManager class CacheManagerFactory: _cache_manager_instance = None @classmethod def get_cache_manager(cls, backend: str = None, hos...
Python
1
BcastPkts/s", tag = "NetworkField::InBcast", class = "NetworkField::Ip" )] #[blink("NetworkModel$ip_ext.get_in_bcast_pkts_per_sec")] pub in_bcast_pkts_per_sec: Option<u64>, #[bttr( title = "IpOutBcastPkts/s", tag = "NetworkField::OutBcast", class = "NetworkField::...
Rust
0
", height); io::stdout().flush().await?; let block = self .node_service .get_block(height) .await? .ok_or_else(|| anyhow!("Error in db, block not found at height {}", height))?; let prev_block = self .n...
Rust
0
ed_output) @slow def test_simple_generate_cuda_kernels_mid(self): expected_output = "Hello my name is John and I am a\n\nI am a single father of a beautiful daughter. I am a" input_ids = self.tokenizer("Hello my name is", return_tensors="ms").input_ids model = MambaForCausalLM.from_pre...
Python
1
s figuring out platform differences.) * Allow channel unsubscription. * Allow callers to reset the signal mask? (Seems hard.) * Support Windows. */ #![deny(missing_docs)] extern crate bit_set; #[macro_use] extern crate chan; #[macro_use] extern crate lazy_static; extern crate libc; use std::collections::HashMap; use ...
Rust
0
cmd_result = pending .add_executor_result(executor_result) .expect("there should be a command result"); // handle the previous command result let (target, cmd) = simulation .forward_to_client(cmd_result) .expect("there should a new submit"); let...
Rust
0
# -*- coding: utf-8 -*- """資料整合系統資料庫模型 此模組定義了資料整合系統所需的新資料表模型,擴展現有的資料庫架構, 支援多元化的台股資料類型。 主要資料表: - DividendInfo: 股利資訊 - ImportantNews: 重要公告 - ChipData: 籌碼面資料 - FundamentalData: 基本面資料 - DataSourceStatus: 資料來源狀態 - DataQualityLog: 資料品質日誌 Example: 使用資料模型: ```python from src.database.models.integration_models im...
Python
1
ot = root.borrow(); helper(root.left.as_deref(), root.val) && helper(root.right.as_deref(), root.val) }) } /// 968. 监控二叉树 https://leetcode-cn.com/problems/binary-tree-cameras/ struct State { directly: u32, indirectly: u32, children_only: u32, } pub fn min_camera_cover(root: Option<Rc<RefCell<T...
Rust
0
from collections import deque class TopologicalSorter: def __init__(self, graph_representation="edges"): # Default to edges self.graph_type = graph_representation self.graph = None # Graph will be set later self.visited = None self.stack = None def sort(self, graph_data): #...
Python
1
d::ffi::CString; #[derive(Serialize, Deserialize, PartialEq, Debug)] pub struct LogData { pub cond_list: Vec<CondStmtBase>, pub tags: HashMap<u32, Vec<TagSeg>>, pub magic_bytes: HashMap<usize, (Vec<u8>, Vec<u8>)>, pub load_paths: HashSet<CString>, } impl LogData { pub fn new() -> Self { Se...
Rust
0
# -*- coding: utf-8 -*- # Copyright 2023 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...
Python
1
(Label)] struct T(#[route(S)] Nil, #[route(K)] Channel); #[derive(Message)] enum Label { Ready(Ready), Copy(Copy), } struct Ready; struct Copy(i32); #[session] type Source = Receive<K, Ready, Send<K, Copy, Receive<K, Ready, Send<K, Copy, End>>>>; #[session] #[rustfmt::skip] type Kernel = Send<S, Ready, Rece...
Rust
0
works with one column at a time")) } if !data_property.releasable { data_property.assert_is_not_aggregated()?; } Ok(ValueProperties::Array(ArrayProperties { num_records: Some(1), num_columns: Some(1), nullity: false, releasab...
Rust
0
DARK_BLUE: RGB8 = RGB8 { r: 0x00, g: 0x00, b: 0x8B }; pub const MIDNIGHT_BLUE: RGB8 = RGB8 { r: 0x19, g: 0x19, b: 0x70 }; pub const LAVENDER: RGB8 = RGB8 { r: 0xE6, g: 0xE6, b: 0xFA }; pub const THISTLE: RGB8 = RGB8 { r: 0xD8, g: 0xBF, b: 0xD8 }; pub const PL...
Rust
0
# 1417 - [Job Adv] (Lv.30) Path of the Cleric darkMarble = 4031013 job = "Cleric" monster = "Zombie Lupin" sm.setSpeakerID(1032001) # Grendel the Really Old sm.sendNext("You wish to become a #b"+ job +"#k?\r\n" "A #b"+ job +"#k is specialised in supporting spells and uses #bholy magic#k to defeat their en...
Python
1
ion_batch = model(next_state_batch) model.train() y_batch = torch.cat( tuple(reward if done else reward + opt.gamma * prediction for reward, done, prediction in zip(reward_batch, done_batch, next_prediction_batch)))[:, None] optimizer.zero_grad() loss = cr...
Python
1
} edges.push((n - 1, 0)); Graph::new(n, &edges) } extern crate rand; use rand::rngs::StdRng; use rand::{Rng, SeedableRng}; fn gnp<R: Rng>(n: usize, p: f64, rng: &mut R) -> Graph { let mut edges = Vec::new(); for i in 0..n { for j in 0..i { if rng.gen_bool(p) { ...
Rust
0
# Copyright (C) 2023-present The Project Contributors # # 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 o...
Python
1
field is `SACIV_0`"] #[inline(always)] pub fn is_saciv_0(&self) -> bool { *self == SACIV1_A::SACIV_0 } #[doc = "Checks if the value of the field is `SACIV_2`"] #[inline(always)] pub fn is_saciv_2(&self) -> bool { *self == SACIV1_A::SACIV_2 } #[doc = "Checks if the value o...
Rust
0
"🛑 Killed system TTS processes matching '{pattern}'") # returncode 1 means no processes found, which is fine except Exception as e: print(f"❌ Failed to kill system TTS pattern '{pattern}': {e}") success = False return success ...
Python
1
::protobuf::Message>::default_instance() } } impl DeleteIdentityResponse { pub fn new() -> DeleteIdentityResponse { ::std::default::Default::default() } } impl ::protobuf::Message for DeleteIdentityResponse { fn is_initialized(&self) -> bool { true } fn merge_from(&mut self, i...
Rust
0
'================================================') logger.info(f'Unreachable links ({len(unreachable_results)}):') for match_tuple, reason in unreachable_results: logger.info(' > Source: ' + match_tuple.source) logger.info(' Name: ' + match_tuple.name) logger.inf...
Python
1
from sortedcontainers import SortedList class MovieRentingSystem: def __init__(self, n: int, entries: List[List[int]]): self.unrented = collections.defaultdict( SortedList) # {movie: (price, shop)} self.shopAndMovieToPrice = {} # {(shop, movie): price} self.rented = SortedList() # (price, sho...
Python
1
import boto3 dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('heydevops') print(table.creation_date_time) table.update_item( Key={ 'username': 'henry', 'last_name': 'kumah' }, UpdateExpression='SET age = :val1', ExpressionAttributeValues={ ':val1': 26 } )
Python
1
at attempts to call this method when the peripheral is already /// enabled will not compile. /// /// Consumes this instance of `SPI` and returns another instance that has /// its `State` type parameter set to [`Enabled`]. /// /// # Examples /// /// Please refer to the [module documentati...
Rust
0
quire&channel_binding=require" logger.info(f"🗄️ Using database: {os.getenv('DATABASE_URL')[:50]}...") # Test psycopg2 import try: import psycopg2 logger.info("✅ psycopg2 import successful") except ImportError as e: logger.error(f"❌ p...
Python
1
MessageType::ErrorMessage), 5 => Ok(MessageType::MultiHopChannelTransactionRequest), 6 => Ok(MessageType::RouterMessage), _ => bail!("no such type"), } } } #[derive(Clone, Debug, Eq, PartialEq)] pub struct BalanceQueryRequest { pub local_addr: AccountAddress, pub...
Rust
0
")); repo_dir.push("repos"); for request in receiver { match request { MetricsRequest::StartAnalysis { repo_url } => { match metrics.refresh(&repo_url, &repo_dir).await { Ok(()) => info!("analyze finished successfuly"), Err(e) => { ...
Rust
0
""" Fields to support various HTML5 input types. """ from ..widgets import html5 as widgets from . import core __all__ = ( 'DateField', 'DateTimeField', 'DateTimeLocalField', 'DecimalField', 'DecimalRangeField', 'EmailField', 'IntegerField', 'IntegerRangeField', 'SearchField', 'TelField', 'URLField', ) c...
Python
1
e loading is finished. By default retun *data*.''' return data class DataProviders(dict): proxies = {} def load(self, symbols, start=None, end=None, loader=None, logger=None, backend=None, **kwargs): loader = loader or settings.default_loader or TimeSerieLoader backend =...
Python
1
import streamlit as st def app(): st.title("Home") st.write("Welcome to the main application! Select a feature from the sidebar.")
Python
1
ns"], storage_options=dict(chunks=chunk_size, overwrite=True), compute=True, metadata={}, ) def get_voxel_size_from_zarr(zarr_group: zarr.Group) -> float: """Extract voxel size from OME-Zarr coordinate transformations. Args: zarr_group: The zarr group containing OME-Zarr m...
Python
1
from launch import LaunchDescription, actions, condition, conditions from launch.actions import DeclareLaunchArgument, ExecuteProcess, TimerAction from launch.conditions import IfCondition from launch.substitutions import LaunchConfiguration, PythonExpression from launch_ros.actions import Node def generate_launch_des...
Python
1
dia=int(input()) mes=int(input()) anho=int(input()) esBisiesto=(anho % 4 == 0 and not(anho % 100 == 0)) or (anho % 400 == 0) if(dia==31 and mes==12): dia=1 mes=1 anho=anho+1 elif ((mes==4 or mes==6 or mes== 9 or mes==11) and dia==30): dia=1 mes=mes+1 elif((mes==1 or mes==3 or mes== 5 or mes==7 or m...
Python
1
"""Intrinio Financial Attributes Model.""" from datetime import datetime from typing import Any, Dict, List, Optional from dateutil.relativedelta import relativedelta from openbb_core.provider.abstract.fetcher import Fetcher from openbb_core.provider.standard_models.financial_attributes import ( FinancialAttribut...
Python
1
###################################################################### ############################# Plotting ############################### ###################################################################### fig, ax = newfig(1.0, 0.6) ax.axis('off') ######## Row 2: Pressure ###...
Python
1
direction = r.direction(); origin.x = self.cos_theta * r.origin().x - self.sin_theta * r.origin().z; origin.z = self.sin_theta * r.origin().x + self.cos_theta * r.origin().z; direction.x = self.cos_theta * r.direction().x - self.sin_theta * r.direction().z; direction.z = self.sin_thet...
Rust
0
from fastapi import APIRouter, HTTPException from app.core.user import auth_backend, fastapi_users from app.schemas.user import UserCreate, UserRead, UserUpdate from constants import METHOD_NOT_ALLOWED_CODE router = APIRouter() router.include_router( fastapi_users.get_auth_router(auth_backend), prefix='/auth...
Python
1
class WeatherDataFetcher: def fetch_weather_data(self, city): print(f"Fetching weather data for {city}...") weather_data = { "New York": {"temperature": 70, "condition": "Sunny", "humidity": 50, "city": "New York"}, "London": {"temperature": 60, "condition": "Cloudy", "humidi...
Python
1
eturn self._player_instance.current_imperial, self._player_instance.total_earned_imperial, self._player_instance.max_imperial def GetBalthazarData(self): return self._player_instance.current_balth, self._player_instance.total_earned_balth, self._player_instance.max_balth def GetActiveTitleID(s...
Python
1
gv[1] g.write('#ifndef BITCOIN_CHAINPARAMSSEEDS_H\n') g.write('#define BITCOIN_CHAINPARAMSSEEDS_H\n') g.write('/**\n') g.write(' * List of fixed seed nodes for the bitcoin network\n') g.write(' * AUTOGENERATED by contrib/seeds/generate-seeds.py\n') g.write(' *\n') g.write(' * Each line conta...
Python
1
op_fn: F) where F: Fn(&mut OpState, Value, &mut [ZeroCopyBuf]) -> Result<Value, AnyError> + 'static, { rt.register_op(name, metrics_op(json_op_sync(op_fn))); } /// Helper for extracting the commonly used state. Used for sync ops. pub fn global_state(state: &OpState) -> Arc<GlobalState> { state.borrow::<Arc<G...
Rust
0
stringStyle.EPYDOC), ] def _to_parser_style( style: Optional[DocStrStyle]) -> docstring_parser.DocstringStyle: """Returns parser style from DocStrStyle.""" if style is None: return docstring_parser.DocstringStyle.AUTO for s, ps in _PARSER_STYLE_MAPPING: if style == s: return ps raise ValueEr...
Python
1
import json from typing import Any class PlayerFigures: def __init__(self, figures_start: int = 5, figures_maximum: int = 10) -> None: assert 0 <= figures_start <= figures_maximum and figures_maximum > 0 self._figures_maximum = figures_maximum self._total_figures: int = figures_start ...
Python
1
StdCombined, /// Catches all output lines from STDOUT and STDERR separately. There is also a /// "STDCOMBINED" vector, but the order is not 100% correct. It's only approximately correct /// on a best effort base. If between each STDOUT/STDERR-alternating output is ≈100µs /// (a few thousand cycles) i...
Rust
0
println!(); println!("The Lightsaber build is successfully complete! You can now run this build in a CPU"); println!("emulator, QEMU for example; or boot it on a real computer by writing the files to a"); println!("USB drive. Please note that the computer MUST have support for UEFI."); Ok(utils::E...
Rust
0
e::input::CancelSpotFleetRequestsInput, ) -> Result<smithy_http::body::SdkBody, std::convert::Infallible> { let mut out = String::new(); #[allow(unused_mut)] let mut writer = smithy_query::QueryWriter::new(&mut out, "CancelSpotFleetRequests", "2016-11-15"); #[allow(unused_mut)] let mut scope...
Rust
0
# -*- coding: utf-8 -*- # =============================================================== # # Copyright (C) 2024 Beike, Inc. All Rights Reserved. # # @Create Author : luxu # @Create Time : 2024/7/30 # @Description : # # =============================================================== DEFAULT_SETTINGS =...
Python
1
_to_filename(self, filename=None): if filename is None: # pragma: no cover filename = self._filename # Prepare create_new = True read_only = False keep_cache_in_memory = False # Open the file # todo: Set flags at close func with self._fi as ...
Python
1
, Self::Output), Self::Error> { self.0 .apply(inp) .and_then( |(left, out1)| self.1 .apply(left) .map(|(left, out2)| (left, (out1, out2))) ) } } pub struct Or<A, B>(pub(crate) A, pub(cr...
Rust
0
:") print(" Understanding which models handle different types of content") # Find models with vision vision_models = get_models_with_capability("vision") print(f"\n 👁️ Vision-capable models: {len(vision_models)}") # Find models with audio audio_models = get_models_with_capability("audio"...
Python
1
import tkinter as tk def addNums(): # callback function try: firstNum = float(entry1.get()) secondNum = float(entry2.get()) total = firstNum + secondNum # result_label.config(text=total, fg="black") var_result.set(total) result_label.config(fg="black") except Val...
Python
1
_user_trigger_t, ) -> bool; } extern "C" { pub fn iox_notification_info_get_subscriber_origin(self_: iox_notification_info_t) -> iox_sub_t; } extern "C" { pub fn iox_notification_info_get_user_trigger_origin( self_: iox_notification_info_t, ) -> iox_user_trigger_t; } extern "C" { pub...
Rust
0
ion, name="application_meter") infrastructure_pm = PowerMeter(infrastructure.nodes(), name="infrastructure_meter", measurement_interval=1) # Run simulation env.process(power_domain.run(env)) env.process(application_pm.run(env)) env.process(infrastructure_pm.run(env)) env.run(until=121) # run t...
Python
1
.where( dbm.Task.status.not_in( [ *TaskStatus.complete(), TaskStatus.scraper_completed, TaskStatus.cancel_requested, ] ), dbm.Task.updated_at <= ago, dbm.Worker.last_seen > ag...
Python
1
showlegend=False, ) ) # Update layout for better visualization fig.update_layout( title=f"Shades of {color_name.capitalize()}", xaxis={"visible": False, "showticklabels": False}, # Hide x-axis yaxis={"visible": False, "showticklabels": False}, # Hide y-axis p...
Python
1
#!/usr/bin/env python # Test the PIO Reader using native binary PIO files from vtkmodules.vtkCommonCore import vtkLookupTable from vtkmodules.vtkFiltersHyperTree import vtkHyperTreeGridGeometry from vtkmodules.vtkIOPIO import vtkPIOReader from vtkmodules.vtkParallelCore import vtkMultiProcessController from vtkmodule...
Python
1
nge(args.num_trials): train_acc, validation_acc, test_acc, energy = Experiment(args=args, dataset=dataset).run() train_accuracies.append(train_acc) validation_accuracies.append(validation_acc) test_accuracies.append(test_acc) energies.append(energy) print("trial:", trial)...
Python
1
from os import getenv from src.config.config import load_downloader_config, load_indexer_config from src.downloader.download import download_account_workflows_and_actions from src.indexer.index import index_downloaded_workflows_and_actions def init_integration_env(): load_integration_tests_config() download_a...
Python
1
manager_v1 } wl_list_init(&mut (*manager).outputs); let mut layout_output: *mut wlr_output_layout_output = 0 as *mut wlr_output_layout_output; layout_output = ((*layout).outputs.next as *mut libc::c_char).offset(-16) as *mut wlr_output_layout_output; while &mut (*layout_o...
Rust
0
use container::uidmap::{get_max_uidmap, map_users}; pub trait Wrapper { fn new(root: Option<&str>, settings: &Settings) -> Self; fn workdir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Self; fn max_uidmap(&mut self) -> &mut Self; fn map_users_for(&mut self, container: &Container, settings: &Settings) ...
Rust
0
of the microfacets in the sense that it returns the probability of a // microfacet being oriented in the 'half' direction. Alternatively this can be seen as // determining the surface area of the microfacets being oriented in the half direction // relativ to the surface area of the macro surface. Therefore...
Rust
0
#!/usr/bin/env python3 import os import sys import shutil import hashlib import glob, os.path ROM_NAME = "test.gba" SRC = './src' GRAPHICS = './graphics' ASSEMBLY = './assembly' STRINGS = './strings' BUILD = './build' def PutFileNameInRightFormat(filename): filename = filename.split('/') newFileName = "" if fil...
Python
1
m): rng = random.PRNGKey(456) sim_length = 100 lag_order = 2 y = jnp.zeros(sim_length + lag_order) y = y.at[0].set(50.0) y = y.at[1].set(51.0) return lag_order, rng, y @app.cell def _(Predictive, ar_price_model, lag_order, random, rng, y): prior_predictive = Predictive(model=ar_price_m...
Python
1
"""Netlify function wrapper for the Flask app.""" import os import sys # Ensure the bundled webapp package is on the import path sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'webapp'))) from webapp.app import app from aws_lambda_wsgi import response def handler(event, context): return...
Python
1
import airflow from airflow.models import DAG from airflow.operators.python_operator import PythonOperator from src.models.initial_model_functions import load_preprocess, fit_model PATH_STREAM_SAMPLE = "/data/stream_sample.p" PATH_TEST_SET = "/data/test_set.p" INITIAL_MODEL_PATH = "/models/current_model/initial_mode...
Python
1
flushopt ")? } if self.clwb() { write!(f, "clwb ")? } if self.avx512_pf() { write!(f, "avx512_pf ")? } if self.avx512_er() { write!(f, "avx512_er ")? } if self.avx512_cd() { write!(f, "avx512_cd ")? } if self.sha() { write!(f, "sha ")? } if self.avx512_bw() { write!(f, "a...
Rust
0
(glyph_positions, n_glyph_pos as usize); let mut total_adv = Vector2D::zero(); let mut glyphs = Vec::new(); let scale = style.size / (font.font.metrics().units_per_em as f32); for (glyph, pos) in glyph_infos.iter().zip(glyph_positions.iter()) { //println!("{:?} {:?}", glyph, ...
Rust
0
= "alloc")] pub fn transmute_vec<S: TriviallyTransmutable, T: TriviallyTransmutable>(mut vec: Vec<S>) -> Result<Vec<T>, Error<'static, S, T>> { if align_of::<S>() != align_of::<T>() || size_of::<S>() != size_of::<T>() { return Err(IncompatibleVecTargetError::new(vec).into()); } unsafe { let...
Rust
0
from car import Car car_1 = Car("Chevy","Corvette",2021,"blue") car_2 = Car("Ford", "Mustang", 2022, "red") #Car.wheels = 2 can change entire car_1.wheels = 2 print(car_2.make) print(car_2.model) print(car_2.year) print(car_2.color) print(car_1.wheels) print(car_2.wheels) car_2.drive() car_2.stop()
Python
1
ated >= self.limit: self.limit = random_repeat_limit() self.repeated = 0 self.users.clear() return True return False async def do_interrupt(self, ss: Session): # noqa: ARG002 if config.leaf_interrupt_continue: self.last_msg = None ...
Python
1
import os os.environ['CUDA_VISIBLE_DEVICES'] = '0,1,2,3' def _infer_model(pt_engine, system=None, messages=None, audios=None): seed_everything(42) request_config = RequestConfig(max_tokens=128, temperature=0) if messages is None: messages = [] if system is not None: messages +...
Python
1
Readable for STATUSCLK_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [statusclk::W](W) writer structure"] impl crate::Writable for STATUSCLK_SPEC { type Writer = W; } #[doc = "`reset()` method sets STATUSCLK to value 0x06"] impl crate::Resettable for STATUSCLK_SPEC { #[inline(always)] ...
Rust
0
"Rcpss", "Rcr", "Rdfsbase", "Rdgsbase", "Rdmsr", "Rdpid", "Rdpkru", "Rdpmc", "Rdpru", "Rdrand", "Rdseed", "Rdsspd", "Rdsspq", "Rdtsc", "Rdtscp", "ReservedNop", "Ret", "Retf", "Rol", "Ror", "Rorx", "Roundpd", "Roundps", "Roundsd", "Roundss", "Rsm", "Rsqrtps", "Rsqrtss", "Rstorssp", "Sahf",...
Rust
0
print("\nInterrupted by user") break def main(): """Main function""" jsonl_file = "/home/u-ril/sangyun/parsed_coordinates.jsonl" print("2D Image Point to Robot Movement System") print("=" * 50) # Check if file exists if not os.path.exists(jsonl_file): ...
Python
1
ec<u8> { self.bytes.clone() } /// /// Convert bits into array of colors /// pub fn as_rgba(&self) -> Vec<Rgba> { let mut pixels = Vec::new(); let step = self.bit_depth.get_step_counter(); // figure out how much padding is on each row // this is needed because...
Rust
0
pacesRepoMachinesForAuthenticatedUserError::Status403(crate::adapters::to_json_async(github_response).await?)), 404 => Err(CodespacesRepoMachinesForAuthenticatedUserError::Status404(crate::adapters::to_json_async(github_response).await?)), code => Err(CodespacesRepoMachinesForAuthenticat...
Rust
0
ard) { let r = Display::CombineInto { a: TilePos::from_usize_index(a, bo.size), b: TilePos::from_usize_index(b, bo.size), target: TilePos::from_usize_index(target, bo.size) }; v.push(r); } fn display_move(v: &mut Vec<Display>, f: usize, t: usize, b: &Board) { let r = Display::Mo...
Rust
0
ates the number of unique pairs available per bin, discarding duplicated (inverted) pairs. """ nr_of_unique_pairs_per_bin = [] for bin_idx in tqdm(range(selected_pairs_per_bin_matrix.shape[0]), desc="Determining number of available pairs per bin"): inchikey_indexes_1, pair_sa...
Python
1
# Floyd Warshall Algorithm # Optimal Solution (using in-place) class Solution: def shortest_distance(self, matrix): n = len(matrix) # Number of vertices in the graph # Initialize the matrix: # Set -1 to infinity (inf) to indicate no direct path between nodes # Set diagon...
Python
1
let bytes = match { self.arx.lock().unwrap().recv() } { Ok(line) => line, Err(_) => return, }; let message = Record { key: (), partition: -1, topic: &self.config.topic, value: bytes, }; ...
Rust
0
from django.db.models import CharField, BooleanField from open.core.betterself.constants import BetterSelfResourceConstants from open.utilities.models import BaseModelWithUserGeneratedContent class Activity(BaseModelWithUserGeneratedContent): """ Users will probably put stuff like "Ate Breakfast", but ideall...
Python
1
# Problem link - https://www.geeksforgeeks.org/problems/minimum-swaps-required-to-bring-all-elements-less-than-or-equal-to-k-together4847/1 # Solution - https://www.youtube.com/watch?v=0Hkh1cjnBNA def min_swaps_for_k_together(arr, k): """ Overall time complexity is O(n) and overall space complexity is O(1...
Python
1
import logging import os import tempfile import pytest from dotenv import dotenv_values from s3prl.dataio.corpus.librispeech import LibriSpeech from s3prl.dataio.encoder.tokenizer import load_tokenizer from s3prl.dataio.encoder.vocabulary import generate_vocab SAMPLE = "GOOD MORNING MY FRIEND" def is_same_vocab(vo...
Python
1
::Io(ref err) => write!(f, "{}", err), ErrorImpl::ParseIntError(ref err) => write!(f, "{}", err), ErrorImpl::ParseFloatError(ref err) => write!(f, "{}", err), ErrorImpl::ParseBoolError(ref err) => write!(f, "{}", err), ErrorImpl::FromUtf8Error(ref err) => write!(f, "{}", ...
Rust
0
date_rating() called"); debug!("Updating {}", self); self.rating = Some(rating); self.save(pool).await?; Ok(()) } pub fn rating(&self) -> Option<i16> { trace!("User::rating() called"); self.rating } } impl fmt::Display for User { fn fmt(&self, f: &mut fm...
Rust
0
from fastapi import FastAPI import uvicorn app = FastAPI() @app.get("/welcome") def welcome(): return {"message" : "Hi John Welcome Man!"} if __name__ == "__main__": uvicorn.run("main:app" , host="0.0.0.0" , port=7000 , reload=True)
Python
1
import math import torch import torch.nn.functional as F from torch.distributions.multivariate_normal import MultivariateNormal as MVN class LSampler(): def __init__(self, device, dataset='CelebA', mvn_path=None): self.device = device self.dataset = dataset data2name = {'CelebA': 'celeba...
Python
1
let api: fn(RP, RP, RP) -> RP = unsafe { lib.symbol(name) }.map_err(|err| err.to_string())?; Ok(api( get_param(params, 0), get_param(params, 1), get_param(params, 2), )) } 4 => { let api: fn(...
Rust
0
olygon {position, nvec: _, dir1, dir2} => distance_polygon(&1.0, r, position, dir1, dir2), Shape::Parallelogram {position, nvec: _, dir1, dir2} => distance_polygon(&2.0, r, position, dir1, dir2), } } } pub fn method_moller(l: &Flt, p0: &Position3, d1: &Direction3, d2: &Direction3, p: &Posi...
Rust
0
ateNeg::kernel(t2, tt, ((669, 9), (8867, 14), (3135, 13))); // 669/512 = Sin[3*Pi/8] + Cos[3*Pi/8] = 1.3065629648763766 // 8867/16384 = Sin[3*Pi/8] - Cos[3*Pi/8] = 0.5411961001461969 // 3135/8192 = Cos[3*Pi/8] = 0.3826834323650898 let (ts, t3) = RotateAdd::kernel(ts, t3, ((669, 9), (8867, 1...
Rust
0
""" Test Time Pooling (Average-Max Pool) Hacked together by / Copyright 2020 Ross Wightman """ import logging from torch import nn import torch.nn.functional as F from .adaptive_avgmax_pool import adaptive_avgmax_pool2d _logger = logging.getLogger(__name__) class TestTimePoolHead(nn.Module): def __init__(sel...
Python
1
from unittest.mock import patch import pytest from cdp_agentkit_core.actions.transfer import ( TransferInput, transfer, ) MOCK_AMOUNT = "0.01" MOCK_ASSET_ID = "usdc" MOCK_DESTINATION = "example.eth" MOCK_GASLESS = True def test_transfer_input_model_valid(): """Test that TransferInput accepts valid para...
Python
1
"""Test module with an optional dependency that may be missing.""" class ExampleClass: pass
Python
1
#!/usr/bin/env python from vtkmodules.vtkCommonDataModel import ( vtkPlane, vtkSphere, ) from vtkmodules.vtkFiltersCore import ( vtkCutter, vtkExecutionTimer, vtkFlyingEdgesPlaneCutter, ) from vtkmodules.vtkFiltersModeling import vtkOutlineFilter from vtkmodules.vtkImagingHybrid import vtkSampleFunc...
Python
1
tting # past commands the $PATH changes we made may not be respected if [ -n "${{BASH:-}}" -o -n "${{ZSH_VERSION:-}}" ] ; then hash -r 2> /dev/null fi if [ -n "${{_OLD_VIRTUAL_PS1:-}}" ] ; then PS1="${{_OLD_VIRTUAL_PS1:-}}" export PS1 unset _OLD_VIRTUAL_PS1 fi u...
Rust
0