text
string
label_name
string
labels
int64
example I'll show is the upper method. Lets take a look at the documentation. # <codecell> str.upper? # <markdowncell> # So we can use it to upper-caseify a string. # <codecell> fullName.upper() # <markdowncell> # You have to use the parenthesis at the end because upper is a method of the string class. # # F...
Python
1
import builtins from infra.userportal.functions.topology import RivUserPortalFunctionSet from infra.userportal.states.interfaces import RivStateMachineConstruct from infra.interfaces import IVpcRivStack from constructs import Construct from aws_cdk import ( aws_stepfunctions as sf, aws_stepfunctions_tasks as sft, )...
Python
1
", word); } for (idx, sense) in item.senses.iter().enumerate() { if !sense.parts_of_speech.is_empty() { println!("\x1b[31;1m{}\x1b[0m", sense.parts_of_speech.join(", ")); } println!(" \x1b[32;1m{}. {}\x1b[0m", idx+1, sense.engl...
Rust
0
gl.uniform1ui(location, v0)) }) } #[unwind_aborts] pub(crate) extern "system" fn uniform1uiv( location: GLint, count: GLsizei, value: *const GLuint, ) -> () { try_with_context((), |cx| { let location = cx.uniforms.get_active_obj_nullable(location)?; let value = user_array(1 * count,...
Rust
0
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, Table, TableStyle from reportlab.lib.pagesizes import A4 from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib import colors import os def generate_pdf_report(df, outpath='outputs/mental_health_report.pdf'): os.makedirs(o...
Python
1
keys: keys.iter(), marker: PhantomData, }) } } }; } impl_multi_fetch!(MessageId, Message, TREE_MESSAGE_ID_TO_MESSAGE); impl_multi_fetch!(MessageId, MessageMetadata, TREE_MESSAGE_ID_TO_METADATA); impl_multi_fetch!(OutputId, CreatedOutput, TREE_...
Rust
0
ktm >> 24) & 0xFF, day=(zktm >> 16) & 0xFF, hour=(zktm >> 8) & 0xFF, minute=zktm & 0xFF ) @staticmethod def datetime_to_zktimemoment(dt: datetime) -> int: """Encode time moment in datetime object into a 4-byte integer used in a device as annual time moment representation. Year and ...
Python
1
and yield the token that best fits the input. /// Returns Ok(Some(...)) if a token was lexed, /// Ok(None) if the source stream was exhausted, /// or Err(...) if an error occurred. fn lex_one_token(&mut self) -> Result<Option<Token>, LexError> { // First off, get rid of all whitespace s...
Rust
0
Ident { name: 60, ctxt: 0 }, Use => Ident { name: 61, ctxt: 0 }, While => Ident { name: 62, ctxt: 0 }, Continue => Ident { name: 64, ctxt: 0 }, Proc => Ident { name: 65, ctxt: 0 }, Alignof => Ident { name: 70, ctxt: 0 }, B...
Rust
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np from scipy import signal import copy def randRange(x1, x2, integer): y = np.random.uniform(low=x1, high=x2, size=(1,)) if integer: y = int(y) return y def normWav(x,always): if always: x = x/np.amax(abs(x)) elif np...
Python
1
obj_radius=0.025, pad_success_thresh=0.06, xz_thresh=0.005, high_density=True ) if tcp_to_obj < 0.035 and tcp_opened > 0 and \ obj[2] - 0.01 > self.obj_init_pos[2]: object_grasped = 1 reward = reward_utils.hamacher_product(object...
Python
1
The heartache, and the thousand natural shocks /// That flesh is heir to. 'Tis a consummation /// Devoutly to be wish'd. To die- to sleep. /// To sleep- perchance to dream: ay, there's the rub! /// For in that sleep of death what dreams may come /// When we have shuffled off this mortal coil, /// Must give us pause. T...
Rust
0
_proc().unwrap().name.clone(); scheduler.schedule(); tui.debug(format!("{:05}: Switching context: {} -> {}", clock_tick, prev_proc_name, scheduler.current_proc().unwrap().name)); tui.debug(format!("{:05}: {} was waiting {} clock ticks", clock_tick, scheduler.current_proc().unwrap().name, schedul...
Rust
0
to_le_bytes())?; writer.write_all(&self.data)?; Ok(()) } pub fn serialize_as_vec(&self) -> Vec<u8> { let mut v = Vec::new(); self.serialize(&mut v).unwrap(); v } pub fn serialize_as_value(&self) -> Value { Value::owned(self.serialize_as_vec().into_boxed_...
Rust
0
tesIO() plt.savefig('results/{}_predict.eps'.format(name),dpi=300) # img_array = np.asarray(Image.open(buffer)) # # print(dir(writer.add_image)) # writer.add_image("UMAP_P",img_array,step,dataformats='HWC') # plt.close() # buffer.close() def process_ts(ts,eta=1): #Ma...
Python
1
context: federal-context apiVersion: v1 clusters: - cluster: api-version: v1 server: http://cow.org:8080 name: cow-cluster - cluster: certificate-authority: path/to/my/cafile server: https://horse.org:4443 name: horse-cluster - cluster: insecure-skip-tls-verify: true server: https://pig.org:...
Rust
0
oint = OutPoint::from_str( "1d239c9299a7e350e3ae6e5fb4068f13b4e01fe188a0d0533f6555aad6b17b0a:0", ) .unwrap(); let vault_prevout = VaultPrevout::new(deposit_outpoint); let feebump_prevout = FeeBumpPrevout::new(feebump_outpoint); // All the txouts created in all trans...
Rust
0
let batch2 = build_table_i32(("a2", &vec![30]), ("b1", &vec![5]), ("c2", &vec![90])); let schema = batch1.schema(); let right = Arc::new( MemoryExec::try_new(&[vec![batch1], vec![batch2]], schema, None).unwrap(), ); let on = vec![( Column::new_...
Rust
0
debug_assert!(self.cur().is_some()); let mut first = true; let mut has_escape = false; let mut word = { // Optimize for idents without escpae let s = self.input.uncons_while(|c| { if c.is_ident_part() { return true; ...
Rust
0
# Copyright 2009 by Peter Cock & Cymon J. Cox. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. """Alignment command line tool wrappers.""" __docformat__ = "epytext en" # Don't ...
Python
1
分数。 # micro_batch["responses"]: 真实的下一个 token,也就是我们的标签 (labels)。 # NOTE(dotv): logprobs_from_logits - 从模型输出到损失计算, 这个函数会从 logits 中抽取出 labels 对应位置的分数。然后对 logits 在 vocab_size 维度上做 log_softmax 操作,将其转换为对数概率。最终返回 labels 对应的那个对数概率值,即 log P(correct_token | context)。这个值就是我们之前讨论的 log_prob,它...
Python
1
both a parser ([parse_term]) and serializer ([serialize_term]). //! //! //! * IR Textual format //! * It's s-expressions. //! * `N`: natural number //! * `I`: integer (arbitrary-precision) //! * `X`: identifier //! * regex: `[^()0-9#; \t\n\f][^(); \t\n\f#]*` //! * Sort `S`: //! * `bool` //! * `f3...
Rust
0
import sys import os import os.path as p import click from ..shared_vars import (pandoctools_user, pandoctools_user_data, pandoctools_core, PandotoolsError, bash_cygpath) def main(basename: str, fallback_basename: str=None) -> str: """ Returns Unix style absolute path to the file by...
Python
1
import numpy as np import matplotlib.pyplot as plt from PIL import Image def fft_1d_manual(signal): """1D Fourier dönüşümünü manuel olarak hesaplar.""" N = len(signal) result = np.zeros(N, dtype=complex) for k in range(N): result[k] = np.sum(signal * np.exp(-2j * np.pi * k * np.arange(N) / N)) ...
Python
1
SockAddr> = MaybeUninit::uninit(); let mut length = size_of::<SA::SysSockAddr>() as socklen_t; if unsafe { libc::getpeername(socket.as_raw_fd(), saddr.as_mut_ptr() as *mut _, &mut length) } == -1 { return Err(Error::last_os_error()); }; if length != size_of::<SA::SysSockAddr>() as socklen_t { ...
Rust
0
-lang.org/core/cmp/trait.Eq.html) implementation which calls [`keys_eqv`](enum.Val.html#method.keys_eqv) rather than [`eq`](enum.Val.html#method.try_eq). */ //this seems limited and insufficiently general (e.g. can't use a Root<Obj> as a HashMap key), //so i'm going to hide it for now #[doc(hidden)] #[derive(...
Rust
0
"""" 使用现有模型训练 """ # ImageNet 训练集100G+,且不支持公开访问 # train_data = torchvision.datasets.ImageNet("../data_image_net", split='train', download=True, # transform=torchvision.transforms.ToTensor()) import torchvision from torch import nn from torch.utils.data import DataLoader vgg16...
Python
1
import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator ARANGE = np.linspace(0.05, 10.05, 401) class Radius: def __init__(self, radius: float, eps: float) -> None: self.radius = radius self.eps = eps # Radii repulsive force def repulsion(lhs: Radius, rhs...
Python
1
# # 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, software # distributed under ...
Python
1
"ignore", category=DeprecationWarning, module=r".*passive_env_checker") env = DummyVecEnv([lambda: gym.make("CartPole-v1")]) env.seed(seed=0) monitor_env = VecMonitor(env) model = PPO("MlpPolicy", monitor_env, verbose=1, n_steps=64, device="cpu") model.learn(total_timesteps=250) # No warnings b...
Python
1
= Unit.query.get(pu.unit_id) if not unit: continue year = get_year(pu.row) if year is None: continue col_index = get_column_index(pu.row, pu.col) if 1 <= col_index <= 8: year_cols[year][col_index].append( {"id": unit.id, "name"...
Python
1
xception as e: logger.error(f"Erro ao obter analytics: {e}") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Erro ao obter analytics: {str(e)}" ) # --- Funções auxiliares para análise --- def analyze_feedback_patterns(feedback_data: List...
Python
1
ue::Record(ref scope) => pretty_record(Doc::concat( scope.unsafe_pattern.unsafe_patterns.iter().map( |&(ref label, _, Embed(ref term))| { parens( Doc::as_string(label) .append(Doc::space()) ...
Rust
0
if applicant.email.is_empty() { event!(Level::WARN, "applicant has an empty email: {:?}", applicant); return Ok(HttpResponseAccepted("ok".to_string())); } // We do not need to add one to the end of the columns to get the column where the email sent verification is // because google she...
Rust
0
E_REUSE) => { OutOfBandHandshakeReuse::deserialize(value) .map(|msg| A2AMessage::OutOfBandHandshakeReuse(msg)) .map_err(de::Error::custom) } (MessageFamilies::OutOfBand, A2AMessage::OUT_OF_BAND_HANDSHAKE_REUSE_ACCEPTED) => { ...
Rust
0
es >= min_successes: logger.info(f"✅ Test passed with {successes} successful attempts.") return successful_result finally: # Cancel any outstanding tasks that are still running for task in tasks: if n...
Python
1
e * 0.2; state.ymove *= 0.8; moving = true; } if state.xzoom.abs() > 1e-3 { frame.x.view.scale_around(state.cursor.x, 2f32.powf(state.xzoom * 0.2)); frame.x.view -= frame.x.view.0.min(0.0); state.xzoom *= 0.8; moving = true; } if state.yzoom.abs() > 1e-3 { frame.y.view.scale_around(state.cursor.y, 2f3...
Rust
0
Identifier>, CaptureKind, Mutability, Option<P<Pat>>), Lit(P<Expr>), Struct(Path, Vec<FieldPat>, bool), TupleStruct(Path, Vec<P<Pat>>, Option<usize>), Path(Path), Tuple(Vec<P<Pat>>, Option<usize>), Box(P<Pat>), Ref(P<Pat>, Mutability), Range(P<Expr>, P<Expr>, RangeLimits), Slice(Vec<...
Rust
0
nn.BatchNorm1d(num_classes), # nn.Softmax(), ) def forward(self, x: Tensor) -> Tensor: x = self.seq_blocks(x) x = torch.flatten(x, start_dim=1, end_dim=-1) return self.seq_blocks_1(x) # Getters -------------------------------------------------------------------...
Python
1
eValue) where V: Visit<'ast> + ?Sized, { v.visit_path(&node.path); tokens_helper(v, &node.eq_token.spans); v.visit_lit(&node.lit); } #[cfg(feature = "full")] pub fn visit_method_turbofish<'ast, V>(v: &mut V, node: &'ast MethodTurbofish) where V: Visit<'ast> + ?Sized, { tokens_helper(v, &node.col...
Rust
0
import torch from mmdet.cv_core.ops.nms import batched_nms def multiclass_nms(multi_bboxes, multi_scores, score_thr, nms_cfg, max_num=-1, score_factors=None): """NMS for multi-class bboxes. Args: multi_bbox...
Python
1
a cell for its signature. let rando1 = Keypair::new(); let tx = Transaction::system_move(&rando0, rando1.pubkey(), 1, bank.last_id(), 0); assert_eq!(bank.process_transaction(&tx), Ok(())); // Finally, return the transaction to the benchmark. tx }) ...
Rust
0
'error': error_msg, 'content': '抱歉,处理您的问题时遇到了技术问题,请稍后重试。' } def build_prompt(self, question: str, context: str) -> str: """ 构建RAG提示词 Args: question: 用户问题 context: 检索到的相关文档内容 Returns: str: 构建好...
Python
1
#read n numbers and find the sum of odd and even numbers seperately n=int(input("How many number do you want to enter :")) o=[] even=[] odd=[] for i in range(0,n): ask=int(input("Enter the number :")) o.append(ask) if (o[i])%2==0: even.append(o[i]) else : odd.append(o[i]) print('Sum o...
Python
1
primitives = render_rx.recv().ok(); } if let Some(primitives) = primitives { eprintln!("Rendering."); draw(&display, &mut renderer, &image_map, &primitives); } last_update = std::time::Instant::now(); } } fn draw(display: &glium::Display, renderer: ...
Rust
0
# -*- coding: utf-8 -*- import os from dotenv import load_dotenv import re load_dotenv() # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.dja...
Python
1
parse: MwParse, } /// Returns a list of pages that transclude the template indicating a marker. pub async fn get_transcluding_pages() -> Result<Vec<MwPageInfo>, Box<dyn std::error::Error>> { let mut pages: Vec<MwPageInfo> = vec![]; let client = Client::default(); let mut request_url = "https://librewi...
Rust
0
if self._add_output_and_check('layer4', x, outputs, output_layers): return outputs x = self.avgpool(x) x = x.view(x.size(0), -1) x = self.fc(x) if self._add_output_and_check('fc', x, outputs, output_layers): return outputs if len(output_layers) ...
Python
1
tResponse { success: bool, response: String } #[post("/", format = "application/json", data = "<contract_payload>")] fn execute_contract(contract_payload: Json<ContractPayload>) -> Json<ContractResponse> { Json(ContractResponse { success: true, response: "Cake".to_string() }) } fn main...
Rust
0
# Scrapy settings for olx project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://docs.scrapy.org/en/latest/topics/settings.html # https://docs.scrapy.org/en/latest/topics/downloader-middleware.htm...
Python
1
and labels for all images. Args: outputs: (np.ndarray) dimension batch_size x 6 - log softmax output of the model labels: (np.ndarray) dimension batch_size, where each element is a value in [0, 1, 2, 3, 4, 5] Returns: (float) accuracy in [0,1] """ outputs = np.argmax(outputs, axis=1) ...
Python
1
""" С клавиатуры вводится два числа K и N. Квадратная матрица А(N,N), состоящая из 4-х равных по размерам подматриц, B,C,D,E заполняется случайным образом целыми числами в интервале [-10,10]. Для отладки использовать не случайное заполнение, а целенаправленное. Вид матрицы А: Для ИСТд-13 D Е С В Для простоты все и...
Python
1
+ ("req" if is_req else "evt") + "_" + item.attrib["name"] ) for_export = is_exportable(func_name, export_list) if for_export: write_f...
Python
1
# Copyright 2024 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
if allGPU == False: X_batch = X_batch.to(device).float() y_batch = y_batch.to(device).float() # Forward pass outputs = model(X_batch, edge_index, edge_weight) # Calculate loss loss = masked_mae_loss((outputs *...
Python
1
# Discussion 4: Tree Recursion # Q1: Insect Combinatorics def paths(m, n): """Return the number of paths from one corner of an M by N grid to the opposite corner. >>> paths(2, 2) 2 >>> paths(5, 7) 210 >>> paths(117, 1) 1 >>> paths(1, 157) 1 """ "*** YOUR CODE HERE ***" ...
Python
1
ter = PrettyPrint::new(); for i in list { printer.print_item(&i); printer.append("\n"); } writeln!(out, "{}", printer.take()).unwrap(); } for (list, name) in files.iter().skip(1).zip(opts.input) { writeln!(out, "/* file: {} */", name).unwrap(); if...
Rust
0
9479177387814 # sqrt(0.5) = 0.7071067811865475 t_u = (p.upper_bound - p.loc) * 0.7071067811865475 / (p.scale + 1e-30) t_l = (p.lower_bound - p.loc) * 0.7071067811865475 / (p.scale + 1e-30) upper = c1 * torch.erf(t_u) + (c3 * t_u + c2) * torch.exp(-t_u * t_u) lower = c1 * torch.erf(t_l) + (c3 * t_l...
Python
1
::walreceiver; use crate::CheckpointConfig; use metrics::{register_histogram_vec, HistogramVec}; use postgres_ffi::xlog_utils::to_pg_timestamp; use postgres_ffi::pg_constants; // Wrapped in libpq CopyData enum PagestreamFeMessage { Exists(PagestreamExistsRequest), Nblocks(PagestreamNblocksRequest), GetPag...
Rust
0
uNumOfTXBuffers: u32, pub uNumOfRXBuffers: u32, pub uOpModeCapability: u32, } impl ::core::marker::Copy for DOT11_OPERATION_MODE_CAPABILITY {} impl ::core::clone::Clone for DOT11_OPERATION_MODE_CAPABILITY { fn clone(&self) -> Self { *self } } #[doc = "*Required features: 'Win32_NetworkManagemen...
Rust
0
# ADAPTED FROM https://pytorch.org/vision/main/_modules/torchvision/models/segmentation/deeplabv3.html # noqa E501 # and https://discuss.pytorch.org/t/how-to-modify-deeplabv3-and-fcn-models-for-grayscale-images/52688 # noqa E501 import torch from mmv_im2im.utils.misc import parse_config_func_without_params class N...
Python
1
break; } } } <filename>src/core_graphics/geometry/cg_vector.rs use super::CGFloat; /// A two-dimensional vector. /// /// See [documentation](https://developer.apple.com/documentation/coregraphics/cgvector). #[repr(C)] #[derive(Copy, Clone, Debug, Default, PartialOrd, PartialEq)] pub struct CGVe...
Rust
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import itertools import os from gen_elemwise_utils import ARITIES, DTYPES, MODES def main(): parser = argparse.ArgumentParser( description="generate elemwise impl files", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) ...
Python
1
notify user about that, no permission will be ask. /// Reason: Nothing will be done with the funds until user will go forward manually /// Return: option ack message pub fn swap_income_message<'a, L, C, K>( wallet_inst: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>, keychain_mask: Option<&SecretKey>, swap_message: &s...
Rust
0
# -*- coding: utf-8 -*- # AwesomeTTS text-to-speech add-on for Anki # Copyright (C) 2010-Present Anki AwesomeTTS Development Team # # This program 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 versi...
Python
1
#!/usr/bin/env python # Copyright 2022 Shanghai Jiao Tong University (Authors: Wangyou Zhang) # Apache 2.0 import argparse import random from collections import defaultdict from pathlib import Path from split_train_dev import int_or_float_or_numstr, split_train_dev, split_train_dev_v2 def get_parser(): """Argu...
Python
1
let mut ring_buffer = VariableSizeRingBuffer::new(3); ring_buffer.new_entry::<u8>().unwrap(); let entry = ring_buffer.consume::<u16>(); assert!(entry.is_err()); assert_eq!(entry, Err(Error::new(ErrorCode::SizeMismatch, ""))); } #[test] fn push_two_different_and_consume() { let mut ring_buffe...
Rust
0
{29fc}'), ('\u{2e22}', '\u{2e22}'), ('\u{2e24}', '\u{2e24}'), ('\u{2e26}', '\u{2e26}'), ('\u{2e28}', '\u{2e28}'), ('\u{2e42}', '\u{2e42}'), ('\u{3008}', '\u{3008}'), ('\u{300a}', '\u{300a}'), ('\u{300c}', '\u{300c}'), ('\u{300e}', '\u{300e}'), ('\u{3010}', '\u{3010}'), ('\u{3014}', '\u{3...
Rust
0
&'a [u8], usize), GltfLoadingError> { let view = accessor .view() .ok_or(GltfLoadingError::SparseAccessorUnsupported)?; let stride = view.stride().unwrap_or(accessor.size()); if stride < accessor.size() { tracing::error!( "Accessor '{}' with size '{}' is bound to view '{...
Rust
0
(f, "{}", self.name) } } fn two_elements_of<I, T>(mut iter: I) -> Option<(T, T)> where I: Iterator<Item = T>, { let first = iter.next(); let second = iter.next(); match (first, second) { (Some(first), Some(second)) => Some((first, second)), _ => None, } } <filename>crates/flowi...
Rust
0
}; cur_txn.events.push(event); }, 'R' => { let w_txnid = bytes2long(&buf[i .. i+8]); i = i + 8; let w_wid = bytes2long(&buf[i .. i+8]); i = i + 8; let key = bytes2long(&buf[i .. i+8]); ...
Rust
0
from django import template from django.conf import settings from django.templatetags.static import static import re register = template.Library() mapping = """8-) 8) cool :'( cry :D :-D grin =) happy :-| :| neutral :( :-( sad :) :-) smile :P :-P tongue :S :-S weird ;) ;-) wink :O :-O woot""" d = [] for emoticons, n...
Python
1
#link -> https://www.codewars.com/kata/5d9f95424a336600278a9632 def powers(n): result = [] power = 1 while n > 0: if n & power: result.append(power) n -= power power <<= 1 return sorted(result) print(powers(6)) print(powers(10)) print(powers(1)) print(pow...
Python
1
import numpy as np import copy class LinearBaseline: def __init__(self, env_spec, inp_dim=None, inp='obs', reg_coeff=1e-5): self.inp = inp self._reg_coeff = reg_coeff self._coeffs = None def _features(self, paths): if self.inp == 'env_features': o = np.concatenate(...
Python
1
from __future__ import annotations from abqpy.decorators import abaqus_class_doc, abaqus_method_doc from ..UtilityAndView.abaqusConstants import ( DEFAULT_MODEL, ON, Boolean, SymbolicConstant, ) from .Leaf import Leaf @abaqus_class_doc class LeafFromNodeVarRange(Leaf): """The LeafFromNodeVarRang...
Python
1
import socket import random import unittest class TestUnittestAssertions(unittest.TestCase): def testSocket(self): server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = "127.0.0.1" port = 9999 + random.randint(0, 1000) + 1 print("port:", port) server.bind((host,...
Python
1
terator for AdapterIter<'a, F> { type Item = Adapter; fn next(&mut self) -> Option<Adapter> { let result = self.factory.enum_adapter(self.adapter); self.adapter += 1; result } } <reponame>Bombfuse/kira<gh_stars>0 use std::sync::Arc; use crate::{ error::CommandError, manager::comm...
Rust
0
BoundDir set_fInvertPostBoundDir[18..19], fLinkStringBefore set_fLinkStringBefore[19..20], fLinkStringAfter set_fLinkStringAfter[20..21], fNeutralOverride set_fNeutralOverride[21..22], fNumericOverride set_fNumericOverride[22..23], fLegacyBidiClass set_fLegacyBidiClass[23..24], fMergeNeutralItem...
Rust
0
lingua_thai_language_model::THAI_TESTDATA_DIRECTORY; use lingua_tsonga_language_model::TSONGA_TESTDATA_DIRECTORY; use lingua_tswana_language_model::TSWANA_TESTDATA_DIRECTORY; use lingua_turkish_language_model::TURKISH_TESTDATA_DIRECTORY; use lingua_ukrainian_language_model::UKRAINIAN_TESTDATA_DIRECTORY; use lingua_urd...
Rust
0
{pool.name || pool.address.substring(0, 8)}...</strong><br> liquidity_trend: ${pool.liquidity_trend} | trade_volume_24h_trend: ${pool.trade_volume_24h_trend} | fees_24h_trend: ${pool.fees_24h_trend} | fees_ho...
Python
1
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # import argparse import numpy import torch import torch.nn.functional as F import matplotlib.pyplot as plt from torch.au...
Python
1
from dataclasses import dataclass from datetime import datetime from typing import Dict, List @dataclass class MessageStats: total_messages: int = 0 user_messages: int = 0 assistant_messages: int = 0 average_response_time: float = 0.0 last_message_time: datetime = None class ConversationStats:...
Python
1
tures :: { StreamExt , channel::mpsc::{ unbounded, UnboundedSender } , }, }; type ConnMap = HashMap<SocketAddr, Connection>; struct Connection { nick : Arc<RwLock<String>> , sid : usize , tx : UnboundedSender<ServerMsg> , } st...
Rust
0
: ident) => { let mut drft_lookup = DrftLookup::new(N); let mut data = vec![0.; 32]; drft_lookup.$func(&mut data); let mut original_drft_lookup = original_smallft::drft_lookup { n: 0, trigcache: null_mut(), splitcache: null_mut(), }; ...
Rust
0
import pytest @pytest.mark.usefixtures("dataLoad") class TestExample2: def test_editProfile(self, dataLoad): print(dataLoad[0]) print(dataLoad[1])
Python
1
ions to define unit types. #[derive(Debug, Clone, Copy)] enum Inch {} #[derive(Debug, Clone, Copy)] enum Mm {} /// `Length` is a type with phantom type parameter `Unit`, /// and is not generic over the length type (that is `f64`). /// /// `f64` already implements the `Clone` and `Copy` ...
Rust
0
""" the configuration of the simulation parameters """ import functions as f import numpy as np class Config: def __init__(self): # Base Station self.n_k_level = 20 self.n_antennas = f.get_codebook().shape[0] # number of transmit antennas self.codebook_size = f.get_codebook().sh...
Python
1
} else if !use_iter && self.solver.is_iter() { self.solver = Solver::svds(n + m + p); } } /// Starts to solve a optimization problem by primal-dual interior-point method. /// /// Returns `Ok` with optimal \\(x, \\lambda, \\nu\\) concatenated vector /// or `Err` with...
Rust
0
..InitOptions::default()}) .expect("Failed to create display"); let height = canvas.height() - 1; let width = canvas.width() - 1; let mut events = VecDeque::new(); canvas.set_color_ansi(&AnsiColor::White, &AnsiColor::Blue); canvas.draw_line(0, 0, width, 0, ' '); canvas...
Rust
0
.0f, // space 0.90625, 0.0449f, // texture -208.0f, 200.0f, 0.0f, // space 0.09375f, 0.0449f); // texture // draw the peak indicator light (56x58) if (State->mPeak > 0) { bindTexture(NAMED_PFBackground, 0, NAMED_Tvumeter_peak_o...
Rust
0
import argparse from pathlib import Path import torch from spacetorch.datasets import DatasetRegistry from spacetorch.feature_saver import FeatureSaver from spacetorch.paths import FEATURE_DIR import vonenet def get_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser() parser.add_argument...
Python
1
from_bits(data[offset + 4]), f32::from_bits(data[offset + 5]), ] } fn load_map_transforms(data: &[u32], offset: usize) -> [[f32; 6]; 4] { [ load_f32_6(data, offset), load_f32_6(data, offset + 6), load_f32_6(data, offset + 12), load_f32_6(data, offset + 18), ] } <file...
Rust
0
""" Function: Show searching error curves for spike metrics. Author: Jianing Li, lijianing@pku.edu.cn, Peking University, Apr. 1st, 2019. """ import numpy as np import pickle from matplotlib import pyplot as pl # load noise ratio steps. noise_ratio_steps = open('../datasets/search_moving_target/noise_ratio_steps.pkl...
Python
1
number=3, type=FieldDescriptorProto.TYPE_MESSAGE, type_name='.tensorflow.contrib.proto.TestValue', label=FieldDescriptorProto.LABEL_OPTIONAL) fn = os.path.join(self.get_temp_dir(), 'descriptor.pb') with open(fn, 'wb') as f: f.write(set_proto.SerializeToString()) return f...
Python
1
size) -> &Self::Output { &self.as_bitslice()[cursor] } } impl<O, T> Index<Range<usize>> for BitVec<O, T> where O: BitOrder, T: BitStore, { type Output = BitSlice<O, T>; fn index(&self, range: Range<usize>) -> &Self::Output { &self.as_bitslice()[range] } } impl<O, T> IndexMut<Range<usize>> for BitVec<O, T> ...
Rust
0
# Cutsence for Sengoku Era Questline | Honnou-ji : Precinct of Honnou-ji (811000011) # Author: Tiger PRINCESS_NO = 9000435 AYAME = 9130100 sm.lockInGameUI(True) sm.hideUser(True) sm.removeEscapeButton() sm.blind(1, 255, 0, 0) sm.sendDelay(1200) sm.setSpeakerID(PRINCESS_NO) sm.flipDialogue() sm.sendNext("Your next ...
Python
1
} particles.len() } #[cfg(test)] mod test { use super::*; use vectors::V3; const TWO_PARTICLES_INPUT: &str = "p=< 3,0,0>, v=< 2,0,0>, a=<-1,0,0> p=< 4,0,0>, v=< 0,0,0>, a=<-2,0,0>"; #[test] fn test_parse() { assert_eq!( "< 4,3,-1>".parse::<V3>...
Rust
0
.dds", 0x070B_3C3F, 0xE770_B945), (r"textures\tx_b_n_breton_f_h03.dds", 0x070B_3C3F, 0xE770_BD45), (r"textures\tx_b_n_breton_m_h02.dds", 0x070B_3C3F, 0xE770_E145), (r"textures\tx_b_n_breton_m_h03.dds", 0x070B_3C3F, 0xE770_E545), (r"textures\tx_b_n_breton_m_h00.dds", 0x070B_3C3F, 0xE770_E945), (...
Rust
0
srWindow.Bottom - info.srWindow.Top) as usize, ), // (info.srWindow.Right - info.srWindow.Left + 1) } } fn get_console_mode(handle: HANDLE) -> Result<DWORD> { let mut original_mode = 0; check!(consoleapi::GetConsoleMode(handle, &mut original_mode)); Ok(original_mode) } #[cfg(not(test))] pub ty...
Rust
0
import math # Öklid mesafesi hesaplayan fonksiyon def euclideanDistance(point1, point2): x1, y1 = point1 x2, y2 = point2 return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) # Kullanıcıdan noktaları alma points = [] n = int(input("Kaç tane nokta gireceksiniz? ")) for _ in range(n): x, y = map(float, inp...
Python
1