text
string
label_name
string
labels
int64
} impl<T: AuthShare> Sub for AuthAdditiveShare<T> { type Output = Self; #[inline] fn sub(mut self, other: Self) -> Self { self.epsilon -= other.epsilon; self.value -= other.value; self.mac -= other.mac; self } } impl<T: AuthShare> SubAssign for AuthAdditiveShare<T> { ...
Rust
0
NotFound => "Tile not found during lookup", } ) } } impl std::error::Error for TileSetError {} <reponame>chevdor/jsonrpc //! JSON-RPC websocket client implementation. use std::collections::VecDeque; use std::future::Future; use std::pin::Pin; use std::task::{Context, Poll}; use crate::{RpcChan...
Rust
0
pub struct Source<T> { pub file_id: HirFileId,<|> pub ast: T, } impl<T> Source<T> { pub fn map<F: FnOnce(T) -> U, U>(self, f: F) -> Source<U> { Source { file_id: self.file_id, ast: f(self.ast) } } } "##, r##" pub struct AstId<N: AstNode> { file_id: HirFileId, file_ast_id: ...
Rust
0
:Control { left: Rc::new(KaramelAstType::Primative(Rc::new(KaramelPrimative::Number(10000000.0)))), operator: KaramelOperatorType::GreaterThan, right: Rc::new(KaramelAstType::Binary { left: Rc::new(KaramelAstType::Primative(Rc::new(KaramelPrimative::Number(1024.0)))), ope...
Rust
0
_frame_end_time: f64) -> super::aabb::AABB { return self.aabb; } } <filename>src/concurrency/atomic_protection.rs use std::sync::atomic::{AtomicU64, Ordering}; use std::thread::yield_now; const SENTINEL_VALUE: u64 = 1 << 60; pub struct AtomicProtectingSpinlock { /// tracks who is holding the spinlock...
Rust
0
OUNTER_NAME).await.unwrap(); let _response = first_client.inc(DEFAULT_COUNTER_NAME).await.unwrap(); let _response = first_client.inc(DEFAULT_COUNTER_NAME).await.unwrap(); info!("Sleep for 2 sec...."); sleep(Duration::from_millis(2000)).await; second.kill().await.unwrap(); ...
Rust
0
# Code generated by Lark OpenAPI. from typing import Any, Optional, Union, Dict, List, Set, IO, Callable, Type from lark_oapi.core.construct import init class QueryRecentChangeJobFamilyResponseBody(object): _types = { "job_family_ids": List[str], "page_token": str, "has_more": bool, ...
Python
1
from flask import Flask, render_template, request, jsonify, session from dotenv import load_dotenv from openai import OpenAI import os load_dotenv() app = Flask(__name__) app.secret_key = os.getenv("FLASK_SECRET_KEY", "dev-secret-change-me") # Inisialisasi OpenAI client (gunakan OPENAI_API_KEY dari .env) client = Op...
Python
1
t test_client, asset_id.clone())?; assert_eq!(new_value, prev_value + 1); prev_value = new_value; // ISI just to create a new block let sample_isi = SetKeyValueBox::new(account_id.clone(), Name::new("key")?, String::from("value")); test_client.submit(sample_isi)?; ...
Rust
0
from django.core.management.base import BaseCommand from telegram_bot.bot import run_bot class Command(BaseCommand): help = "Запуск Telegram-бота" def handle(self, *args, **kwargs): self.stdout.write("Запуск Telegram-бота...") run_bot()
Python
1
5 g7f)NTrmessage/delivery-statusmessagercontent-transfer-encoding8bit7bitrbinary--cp>URT5(dg[RU[T55$)N startswith boundaryendREmatchlen)rC separators r"...
Python
1
rt!(!prod.by_identity.is_empty()); Ok(()) } } use crate::utils::{get_trait_def_id, paths, span_lint, span_lint_and_help}; use if_chain::if_chain; use rustc_hir::def_id::DefId; use rustc_hir::{Expr, ExprKind, StmtKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; use rustc_middle::ty:...
Rust
0
eprehenderit in voluptate velit {{ $num }} cillum dolore eu fugiat nulla pariatur. {% end -%} Excepteur sint occaecat cupidatat non {{ $str }}, sunt in culpa qui officia deserunt mollit anim id est {{ $num }}. "); let mut scn = Scanner::new::<VecDeque<char>>(text.chars().collect()); scn.scan_all().unw...
Rust
0
nsive # Full comprehensive demo """ ) parser.add_argument( "--module", choices=["gans", "llm", "vision", "explainable"], help="Run specific module demonstration" ) parser.add_argument( "--comprehensive", action="store_true", help="Run...
Python
1
from apps.common.tests.test_base import BaseApiTestCase class AccountChangeLanguageMutationTestCase(BaseApiTestCase): AUTO_CREATE_USERS = True ALWAYS_LOGIN_USER = True MUTATION = """ mutation changeLanguage( $languageCode: LanguageEnum! ) { changeLanguage( ...
Python
1
othing*/ } Err(err) => { warn!("[process_conn - 33] {:?}", err); return; } } match serde_json::from_slice(buf.borrow_mut()) { Ok(message) => { info!("{:?}", &message); client.sender.send(message); } Err(err) => warn!("[proce...
Rust
0
m = valid.confusion_matrix(&dataset)?; assert!(cm.accuracy() > 0.9); Ok(()) } #[test] fn test_convoluted_rings_classification() -> Result<()> { let records = generate_convoluted_rings(10); let targets = (0..20).map(|x| x < 10).collect::<Array1<_>>(); let dataset = (...
Rust
0
can be // found in the LICENSE file. use fidl_fuchsia_data as fdata; pub trait DictionaryExt { fn find(&self, key: &str) -> Option<&fdata::Value>; } impl DictionaryExt for fdata::Dictionary { fn find(&self, key: &str) -> Option<&fdata::Value> { for entry in self.entries.iter() { if entry...
Rust
0
from dataclasses import dataclass from bokeh.models.callbacks import CustomJS @dataclass(frozen=True) class ScenarioTabLoadingJSCode: """JS when loading simulation in the scenario tab.""" @classmethod def get_js_code(cls) -> CustomJS: """Get js code.""" return CustomJS( args=...
Python
1
impl KsFc { fn receive_value(&mut self) -> crate::Result<f64> { self.receive() .and_then(|data| into_text(data)) .and_then(|text| { parse::<f64>(&text).map_err(|e| e.into()) .map(|v| { if v >= ERROR_VALUE { None } el...
Rust
0
l_upsample) - (starting_frame * temporal_upsample) if face_length_in_frames <= min_frames_for_face: # print(f"Skipping video as {face_length_in_frames} < {min_frames_for_face} frames for this face" # f"From {(starting_frame * temporal_upsample)} minus {((ending_frame + 1) * tempora...
Python
1
/// Returns the values of the `METRIC_RESPONSE_SIZE` histograms' `count` /// field for all label values. pub fn response_size_counts(&self) -> MetricVec<u64> { fetch_histogram_vec_count(&self.metrics, METRIC_RESPONSE_SIZE) } } impl Default for EndpointTestFixture { fn default() -> Endpoin...
Rust
0
funcs.get(func_index as usize)?; exact_step(operands, frames, &func.args[..], &func.result[..])?; } CallIndirect(index) => { let _ = mod_ctx.tables.get(0)?; let func = mod_ctx.types.get(index as usize)?; pop_expected(operands, frames, Operand::Exact(Int(I32)))?; exact_step(operands, frames, &func.ar...
Rust
0
nfo) )] #[cfg_attr(feature = "with-serde", derive(serde::Serialize, serde::Deserialize))] pub enum ReceiptV2 { /// Legacy receipt type Legacy(EIP658ReceiptData), /// EIP-2930 receipt type EIP2930(EIP2930ReceiptData), } impl Encodable for ReceiptV2 { fn rlp_append(&self, s: &mut RlpStream) { match self { Self...
Rust
0
crate) max_operations: Option<NonZeroU64>, /// Maximum number of modules allowed to load. pub(crate) max_modules: Option<NonZeroU64>, } impl Default for Engine { fn default() -> Self { // Create the new scripting Engine let mut engine = Self { packages: Default::default(), ...
Rust
0
Win32_Networking_WinSock\"`*"] pub const NetworkConnectivityLevelHintUnknown: NL_NETWORK_CONNECTIVITY_LEVEL_HINT = 0i32; #[doc = "*Required features: `\"Win32_Networking_WinSock\"`*"] pub const NetworkConnectivityLevelHintNone: NL_NETWORK_CONNECTIVITY_LEVEL_HINT = 1i32; #[doc = "*Required features: `\"Win32_Networking_...
Rust
0
} #[test] fn check_cl_contract_version() { check_package_version(&*CL_CONTRACT, CL_CONTRACT_TOML_URL); } #[test] #[ignore] fn check_cl_types_version() { check_package_version(&*CL_TYPES, CL_TYPES_TOML_URL); } #[test] #[ignore] fn check_cl_engine_test_suppo...
Rust
0
PY_NO_CYTHON", "").lower() in ["true", "yes", "y", "1"]: have_cython_functions = False elif optimize(OptimizationFlag.default): try: from ..linalg import _npc_helper _npc_helper_module = _npc_helper have_cython_functions = True ...
Python
1
Header, MetadataBlockType, StreamInfo}; use symphonia_utils_xiph::flac::metadata::{read_comment_block, read_picture_block}; /// The expected size of the first FLAC header packet. const OGG_FLAC_HEADER_PACKET_SIZE: usize = 51; /// The major version number of the supported OGG-FLAC mapping. const OGG_FLAC_MAPPING_MAJOR...
Rust
0
baseMipLevel: 0, levelCount: 1, baseArrayLayer: image_barrier_data.layer_index, layerCount: image_barrier_data.layers_count, }, }; unsafe { vkCmdPipelineBarrier.unwrap()( command_buffer, image_barrier_data.src_stage_mask, ...
Rust
0
# # Emails configuration and templates used when a task order is created, CUSTOMIZE... # from . import env EMAIL_TIMEOUT = 3 # seconds EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = env('EMAIL_HOST', 'smtp.gmail.com') EMAIL_USE_TLS = env.bool('EMAIL_USE_TLS', True) EMAIL_PORT = env.i...
Python
1
", inode=file_num )) # break the hard links for file_num in range(len(files)): files_list.append(backup.ConcreteFile( "", f"SysContainerDomain-../../../../../../../../var/.backup.i/var/root/Library/Preferences/temp{file_num}", owner=501...
Python
1
Transition": "0x42", "blockReward": "0x100", "daoHardforkTransition": "0x08", "daoHardforkBeneficiary": "0xabcabcabcabcabcabcabcabcabcabcabcabcabca", "daoHardforkAccounts": [ "0x304a554a310c7e546dfe434669c62820b7d83490", "<KEY>", "0xfe24cdd8648121a43a7c86d289be4dd2951ed49f", "0x17802...
Rust
0
import certifi import contextvars import functools from elasticsearch_async import AsyncElasticsearch from elasticsearch import Elasticsearch from elasticsearch.connection.http_urllib3 import create_ssl_context from elasticsearch.connection import Connection def get_connection(func): @property @functools.wra...
Python
1
} Err(Error::new(ErrorKind::NotFound, filename)) } } #[derive(Debug)] pub struct File { // name: String, // hash: Hash, block: Block, sector_offsets: Vec<u32>, sector_checksums: Vec<u32>, file_key: u32, } impl File { pub fn size(&self) -> usize { self.block.unpacked_si...
Rust
0
_FLAG_DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; const GdiCompatible = DXGI_SWAP_CHAIN_FLAG_DXGI_SWAP_CHAIN_FLAG_GDI_COMPATIBLE; const RestrictedContent = DXGI_SWAP_CHAIN_FLAG_DXGI_SWAP_CHAIN_FLAG_RESTRICTED_CONTENT; const RestrictSharedResourceDriver = DXGI_SWAP_CHAIN_FLAG_DXGI_SWAP_CHAIN_FLAG_RES...
Rust
0
>(&udata1.ne_vals.val1_u8).unwrap(); off += ne_bytes[off..].decast::<u8>(&udata1.ne_vals.val2_u8).unwrap(); off += ne_bytes[off..].decast::<u16>(&udata1.ne_vals.val_u16).unwrap(); off += ne_bytes[off..].decast::<u32>(&udata1.ne_vals.val_u32).unwrap(); off += ne_bytes[off..].decast::<u64>(&udata1.ne_vals...
Rust
0
vec![ vec![ vec![0], vec![1], vec![2] ], vec![ vec![0,1], vec![0,2], vec![1,2] ], vec![ vec![0,1,2] ] ...
Rust
0
ngles[:, 0] - gt_angles[:, 0])) * 180 / np.pi, roll_mae=np.mean(np.abs(angles[:, 1] - gt_angles[:, 1])) * 180 / np.pi ) print_log(str(metrics), logger=logger) return metrics def _evaluate_layout(self, results, logger): gt_layouts = [DepthInstance3DBoxes( x['l...
Python
1
, Char(u64), VarChar(u64), Decimal, SmallInt(i16), Integer(i32), BigInt(i64), Real, DoublePrecision, Time, TimeWithTimeZone, Timestamp, TimestampWithTimeZone, Date, Interval, } impl SqlType { pub fn validate_and_serialize(&self, value: &str) -> Result<Vec<u8>...
Rust
0
rget['target_weight'].shape == (2, num_joints, 1) collect = Collect( keys=['img', 'target', 'target_weight'], meta_keys=[ 'image_file', 'center', 'scale', 'rotation', 'bbox_score', 'flip_pairs' ]) results_final = collect(results_target) assert 'img_size' not ...
Python
1
tch size, number of clusters] Output: KL loss cSs|Sr )r1r2rrr<lambda>rYz.BrainNetworkTransformer.loss.<locals>.<lambda>cSs|duSr rr[rrrr\rYN)listfilterr@rHr5)rrUZ...
Python
1
wer bound is '{curr_bounds[0]}' and the upper bound is '{curr_bounds[1]}'" ) def filter(self, sentence): doc = self.nlp(sentence) contained_speech_tags = doc.count_by(spacy.attrs.IDS["POS"]) human_readable_tags = {} for pos, count in contained_speech_tags.items(): ...
Python
1
TreeInfo::InMem(in_mem_info) => match in_mem_info { InMemSubTreeInfo::Empty => Either::A( InMemSubTreeInfo::create_leaf_with_update(self.updates[0], self.generation), ), InMemSubTreeInfo::Leaf { key, .. } => Either::or( ...
Rust
0
return self.best_open_score class ROCScore(Metric): def __init__(self, dist_sync_on_step=False): super().__init__(dist_sync_on_step=dist_sync_on_step) self.add_state("y_trues", default=[], dist_reduce_fx="cat") self.add_state("y_scores", default=[], dist_reduce_fx="cat") sel...
Python
1
Binary) -> OwnedBinary { let hash = xxh3::xxh3_128_with_secret(data.as_slice(), secret.as_slice()); let mut binary = OwnedBinary::new(16).unwrap(); let _ = binary.as_mut_slice().write_all(&hash.to_be_bytes()); binary } rustler::init!( "xxh3", [ new, new_with_seed, new_w...
Rust
0
("{0}")] Backend(#[from] backend::Error), #[error("Tokio error: {0}")] Tokio(#[from] tokio::io::Error), } use super::*; use rand::distributions::Alphanumeric; use rand::Rng; use std::collections::HashMap; use uuid::Uuid; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub enum GenMethod { ...
Rust
0
let s = s / t; t = s * s; let t2 = t * t; let t4 = t2 * t2; let t8 = t4 * t4; let t16 = t8 * t8; let u = F64x::poly19( t, t2, t4, t8, t16, ...
Rust
0
} } pub fn SetDlgItemText (&self,nID:c_int,lpszString: &str) -> bool { self.assert_window(); let s = lpszString.to_c_u16(); unsafe{user32::SetDlgItemTextW(self.0, nID, s.as_ptr()) == TRUE} } // #ipub fndef _ATL_NO_HOSTING //ATLPREFAST_SUPPRESS(6387) //HRESULT GetDlgControl(c_int n...
Rust
0
def set(self, _min: float, _max: float): self.min_percentage = _min self.max_percentage = _max self.redraw() def color_change(self, *_): colors = Sty().colors self.min_handle_base_color = colors.primary self.max_handle_base_color = Color(colors.primary).reverse()...
Python
1
mand = command.to_ascii_uppercase(); if !valid_commands.contains(&command) { return Err(AppError::InvalidCommandErr.to_str(Some(&valid_commands))); } Ok(command) } #[cfg(test)] mod tests { use super::*; #[test] fn test_is_command_valid() { let command: [&str; 4] = ["p", "...
Rust
0
Skill::WaterDash | Skill::Flap => true, }, Item::Shard(shard) => match shard { Shard::Overcharge | Shard::Wingclip | Shard::Magnet | Shard::Splinter | Shard::Reckless | Shard...
Rust
0
Show help. -v --version Show version. -b --bound N Number of intergers to check for primality. -c --count N Number of primes to generate. -m --method METHOD Method used to generate the primes [default: eratosthenes]. -f --format FORMAT Format used to print the prime...
Rust
0
debug!("Done linking folders."); Ok(()) } /// Gets all files relative from `folder` fn get_relative_files(folder: &PathBuf) -> HashSet<PathBuf> { let mut relative_files = HashSet::new(); let walker = WalkDir::new(&folder).into_iter(); for entry in walker { // Ignore invalid permissioned f...
Rust
0
(i, num) in array.iter() .enumerate() .filter(|&(_, num)| num.is_finite()) { let new_num = num + 0.5; assert_eq!(array.ord_subset_binary_search_rev(&new_num), Err(i)); } } #[test] fn binary_search_by_key_err() { fn key_function(el: &f64) -> f64 { (el - 13.0).recip() } let mut array = TEST_ARRAY; array...
Rust
0
from pathlib import Path from core._shared.infrastructure.storage.abstract_storage import AbstractStorage class LocalStorage(AbstractStorage): TMP_BUCKET = "/tmp/codeflix-storage" def __init__(self, bucket: str = TMP_BUCKET): self.bucket = Path(bucket) if not self.bucket.exists(): ...
Python
1
unwrap_or_default(), bin.as_bytes()) } } } /// # Getters. impl<'a> Command<'a> { #[must_use] /// # Bin (cmd). const fn bin(&self) -> &'a str { self.bin } #[must_use] /// # Description. const fn description(&self) -> &'a str { self.description } #[must_use] /// # Name. const fn name(&self) -> &'a str { se...
Rust
0
World) { let net_message_event_rid = world .write_resource::<EventChannel<NetMessageEvent>>() .register_reader(); world.insert(net_message_event_rid); } struct SetupParams { session_status: SessionStatus, input_event: Option<InputEvent<ControlBindings>>, ...
Rust
0
self.form.rb_turbulence_energy.setEnabled(0) if self.result_object.Mesh: self.MeshObject = self.result_object.Mesh else: FreeCAD.Console.PrintError('no Mesh object found in ResultObject {}'.format(self.result_object.Name)) """ ...
Python
1
U\[{devicenum}\]\s*: ' vbios = search(device + r'VBIOS version: (.*?)$', rocm_smi) if rocm_smi_found else "no rocm-smi" gpuid = search(device + r'GPU ID: (.*?)$', rocm_smi) if rocm_smi_found else "no rocm-smi" deviceinfo = search(device + r'Card ser...
Python
1
nents //! via `push` or `extend` than it is to add the components one-by-one after creating the entity. //! //! # Accessing components //! //! The fastest way to access a large number of entities' components is via [queries](../query/index.html). //! //! The entry API also allows access to an individual entity's compon...
Rust
0
# -*- coding: utf-8 -*- import unittest import util from tmdbv3api import Configuration class ConfigurationTests(unittest.TestCase): def setUp(self): self.tmdb = util.setup() self.configuration = Configuration() def test_api_configuration(self): info = self.configuration.api_configu...
Python
1
#print('InterpolatedUnivariateSpline with k = 1 (linear) differs from the other two, but only very little of the order of 1e-16') #------------------- # Test if perhaps interpolation from 5 nm to 1 nm was done using a cubic interpolation: # compare_cmfs(np.round(cmf_1931_2_cie[:,20:-50],digits), np.rou...
Python
1
; //} #[test] fn test_sha256() { let mut hasher = Sha256::new(); hasher.input(b"hello world"); let result = hasher.result(); assert_eq!( result[..], hex!("b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9")[..] ); let m...
Rust
0
def extract_resources(unidad_aprendizaje): """Extrae los recursos educativos de la unidad de aprendizaje.""" resources = [] # Asegurar que estamos accediendo correctamente al JSON if not unidad_aprendizaje or "unidad_aprendizaje" not in unidad_aprendizaje: raise ValueError(" Error: `unidad_...
Python
1
import numpy as np from pymoo.util.misc import cdist from pymoo.util.ref_dirs.misc import project_onto_unit_simplex_recursive from pymoo.util.reference_direction import ReferenceDirectionFactory, sample_on_unit_simplex, \ select_points_with_maximum_distance, get_partition_closest_to_points, UniformReferenceDirec...
Python
1
] embeddings = batch_encode_texts(real_texts) print(f" ✅ 成功编码 {len(embeddings)} 个真实文本") # 计算文本之间的相似度矩阵 print("\n 相似度矩阵:") print(" ", end="") for i in range(len(real_texts)): print(f"文本{i+1:2d}", end=" ") print() ...
Python
1
0].span(), "help"))?; Ok(Self { name, short, help }) } } impl OptionGroupConfig { fn missing(span: Span, item_name: &'static str) -> Error { Error::new( span, &format!( "required option group configuration is missing or invalid: '{}'", item...
Rust
0
#!/usr/bin/env python from vtkmodules.vtkCommonCore import ( vtkLookupTable, vtkPoints, ) from vtkmodules.vtkCommonTransforms import vtkThinPlateSplineTransform from vtkmodules.vtkIOImage import vtkBMPReader from vtkmodules.vtkImagingCore import ( vtkImageBlend, vtkImageMapToColors, vtkImageReslice,...
Python
1
feats = torch.cat(feats, dim=1).squeeze(-1) fusion = self.fusion_block(feats) return fusion def forward_final_feat(self, pts, features=None): return self.forward(pts, features) def forward_cls_feat(self, pts, features=None): fusion = self.forward_final_feat(pts, feature...
Python
1
Msg> { div![ class![ C.bg_white, C.border, C.border_b, C.border_t, C.mt_24, C.rounded_lg, C.shadow, ], div![ class![C.flex, C.justify_between, C.px_6, C._mb_px, C.bg_gray_200], h3![cla...
Rust
0
erations = vec![Operation::RpPerm]; let aux_table_trace = build_trace(&stack, operations); let expected_len = 8; validate_hasher_trace(&aux_table_trace, 0, expected_len); } #[test] fn bitwise_aux_trace() { // --- single bitwise operation with no stack manipulation ------------------------------------ ...
Rust
0
std::error::Error; use rustc::hir; use rustc::mir::interpret::ConstEvalErr; use rustc::mir; use rustc::ty::{self, TyCtxt, Instance}; use rustc::ty::layout::{LayoutOf, Primitive, TyLayout, Size}; use rustc::ty::subst::Subst; use rustc_data_structures::indexed_vec::{IndexVec, Idx}; use syntax::ast::Mutability; use syn...
Rust
0
self._cur.execute("CREATE TABLE DBVERSION(" "VERSION TEXT NOT NULL)") self._cur.execute("INSERT INTO DBVERSION VALUES(%s)", (self.dbversion,)) self._con.commit() except Exception: # pragma: no cover self._con.roll...
Python
1
from flask import Blueprint from User.controller import create_user, get_all_users, get_user_by_id, update_user, delete_user, sign_in_user, log_in_user user_bp = Blueprint('user', __name__) # Đăng ký các route cho API user_bp.route('/users', methods=['POST'])(create_user) # Tạo người dùng user_bp.route('/us...
Python
1
_3.clone()).unwrap(); pool.run_until(async move { loop { match src_3_swarm.select_next_some().await { SwarmEvent::Dialing(_) => {} SwarmEvent::ConnectionEstablished { peer_id, .. } if peer_id == dst_peer_id => { break } ...
Rust
0
import struct def decode(fig, blob_id, scale, style_override_table): network = bytes(fig["blobs"][blob_id]["bytes"]) i = 0 num_vertices = struct.unpack("<I", network[i : i + 4])[0] i += 4 num_segments = struct.unpack("<I", network[i : i + 4])[0] i += 4 num_regions = struct.unpack("<I", ne...
Python
1
chat_message.is_file = True chat_message.file_name = f.name chat_message.file_size = f.size chat_message.file = folder + "/" + file_name chat_message.save() ChatMessageSubscription.broadcast(group=ChatMessageSubscription.name.format(kwargs['pk']), ...
Python
1
ic str; } <reponame>timgates42/inclavare-containers<gh_stars>100-1000 use clap::{App, Arg}; use serde_json::Value; use std::fs::File; use std::io::prelude::*; use configureProvider::configure_provider_service_client::ConfigureProviderServiceClient; use configureProvider::{ExportPolicyRequest, ExportPolicyResponse}; us...
Rust
0
/// Creates an iterator that yields elements as long as the predicate returns true. /// Additionally, it includes the first element that returns false, after which no further /// elements will be yielded. /// /// This can be useful if, for example, you would like to read a stream until the first e...
Rust
0
_records = [] interval_start_time = records[0].unix # Initialize the start time of the first interval interval_values = [] for record in records: # If the current record is within the same interval, add it to the interval_values list if record.unix < interval_st...
Python
1
TIM { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Advertising packet interval defines the time interval in between two ADV_xxx packet sent (value in us)\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u16)] pub enum ADVINT_A { #[d...
Rust
0
rules.iter() { rules_keys.push(key.clone().to_string()); rules_values.push(val.clone()); } let mut table = vec![vec![1; rules.len()]; rules.len()]; for i in 0..rules.len() { for ticket in tickets { for j in 0..ticket.unassigned_fields.len() { if !in_ran...
Rust
0
he default function if empty, /// and returns mutable references to the key and value in the entry. /// /// # Examples /// /// ```ignore /// use halfbrown::VecMap; /// /// let mut map: VecMap<&strtring> = VecMap::new(); /// /// map.raw_entry_mut().from_key("poneyland").or_insert_...
Rust
0
n(fundamentals)) * 1e12, # Dummy market caps index=fundamentals.index ) return create_institutional_grade_factors(fundamentals, market_caps) else: return pd.DataFrame() if __name__ == "__main__": # Run test test_factors = test_stable_factor_engineering() print(...
Python
1
class Solution: def strStr(self, haystack: str, needle: str) -> int: if not needle: # Handle the case where needle is empty return 0 i = 0 # Initialize i indexStart = -1 j = 0 while i < len(haystack): # Match characters and check if...
Python
1
RaisesRegexp(ValueError, ("Received if_metageneration " "argument with no " "if_generation argument")): k.set_xml_acl(acl, if_metageneration=123) with self.assertRaisesRegexp(GSResponseError, VERSION...
Python
1
u32) -> bool { (d & 0xbf20fc00) == 0x0e205c00 } pub const fn is_SMAX_asimdsame_only(d: u32) -> bool { (d & 0xbf20fc00) == 0x0e206400 } pub const fn is_SMIN_asimdsame_only(d: u32) -> bool { (d & 0xbf20fc00) == 0x0e206c00 } pub const fn is_SABD_asimdsame_only(d: u32) -> bool { (d & 0xbf20fc00) == 0x0e...
Rust
0
b_legend = matplotlib.lines.Line2D([0], [0], marker='o', color=legend_color, label=b_label, markerfacecolor=b_color, markersize=matplotlib.rcParams['lines.markersize'] * 1.3) handles = [] i...
Python
1
let current_wakers = mem::take(&mut self.wakers_map); for (id, mut pending) in current_wakers.into_iter() { let room = self.check_map.get(&id).unwrap()(); let room = std::cmp::min(room, pending.len()); for waker in pending.drain(0..room) { woke += 1; ...
Rust
0
ted_stack = ( cause_metadata.translated_stack + (translated_stack[-1],)) self.cause_message = cause_metadata.cause_message def get_message(self): """Returns the message for the underlying exception.""" all_paths = tuple(fi.filename for fi in self.translated_stack) if len(all_paths) > 1:...
Python
1
import torch import torch.nn as nn import hydra from omegaconf import DictConfig class RF(nn.Module): def __init__( self, backbones: DictConfig, ln=False, device: str = 'cpu', ): super(RF, self).__init__() self.model = hydra.utils.instantiate(ba...
Python
1
Configure as GPIO19 value."] GPIO19, #[doc = "SCARD serial clock value."] SCCLK, #[doc = "Configure as the ANATEST1 I/O signal value."] ANATEST1, #[doc = "Configure as the UART1 RX input signal value."] UART1RX, #[doc = "Configure as the PDM I2S bit clock input signal value."] I2SBCL...
Rust
0
# Import a bunch of models from sklearn.linear_model import LinearRegression from sklearn.svm import SVR from sklearn.neighbors import KNeighborsRegressor from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import GradientBoostingRegressor from sklearn.gaussian_process import GaussianProcessRegressor f...
Python
1
# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring import numpy as np from PySDM import Builder from PySDM.backends import CPU from PySDM.environments import Box from PySDM.physics import si from PySDM.products.displacement import AveragedTerminalVelocity T = 300 * si.K dt =...
Python
1
d_csv(filepath) row = df['from'].values col = df['to'].values weight = df['cost'].values if symmetric: row, col = np.concatenate([row, col]), np.concatenate([col, row]) weight = np.concatenate([weight, weight]) adj = sp.coo_matrix((weight, (row, col)), shape=(num_nodes...
Python
1
import typer import panoctagon.ufc.app as ufc import panoctagon.one.one as one app = typer.Typer() app.add_typer(ufc.app, name="ufc") app.add_typer(one.app, name="one") if __name__ == "__main__": app()
Python
1
checked_sub(zero), Some(Signed5Bit::MIN)); // Test the basics: 2-1=1 let two: Signed5Bit = Signed5Bit::try_from(2_i8).unwrap(); assert_eq!(two.checked_sub(one), Some(one)); assert_eq!(two.checked_sub(two), Some(zero)); // Verify that we correctly detect overflow assert_eq!(Signed5Bit::MIN.chec...
Rust
0
!( n2i(0.1, 0.5).pow(n2i(-2.5, -0.1)), n2i(1.0717734625362931, 316.2277660168379) ); assert_eq2!( n2i(0.1, 0.5).pow(n2i(f64::NEG_INFINITY, -0.1)), n2i(1.0717734625362931, f64::INFINITY) ); assert_eq2!(n2i(0.1, 0.5).pow(n2i(-1.0, -1.0)), n2i(2.0, 10.0)); assert_eq2!( ...
Rust
0
_A) -> Self { match variant { APPROTECT_A::DISABLED => false, APPROTECT_A::ENABLED => true, } } } #[doc = "Reader of field `APPROTECT`"] pub type APPROTECT_R = crate::R<bool, APPROTECT_A>; impl APPROTECT_R { #[doc = r"Get enumerated values variant"] #[inline(always)] ...
Rust
0