text
string
label_name
string
labels
int64
velocity: *mut Vector); fn Actor_GetRotation(p_actor: usize, result: *mut Rotator); fn Actor_SetRotation(p_actor: usize, rotation: *mut Rotator); fn Actor_SetTorque(p_actor: usize, torq: *mut Vector); fn Actor_Stop(p_actor: usize); fn Actor_GetAngularVelocity(p_actor: usize, result: *mut Vector); ...
Rust
0
r(MAX); (*min_admin <= admin_level) && (admin_level <= *max_admin) } fn extract_way_ids_from_relation(relation: &Relation) -> Vec<WayId> { relation.refs.iter().filter_map(|r| r.member.way()).collect() } fn replace_way_id_with_node_ids( way_ids: &[WayId], way_id_to_node_ids: &HashMap<WayId, Vec<NodeId...
Rust
0
let mip_data: Vec<Result<(MipDataIndexed, Option<Palette>), String>> = directory .par_iter() .zip(mip_textures.par_iter()) .map(|(entry, miptex)| { println!("Reading mipdata for entry: {:?}", entry); let mut wad_file = match File::open(wad_file) { Ok(wad_...
Rust
0
from openai.types.chat import ChatCompletionMessage from openai.types.chat.chat_completion_message_tool_call import ( ChatCompletionMessageToolCall, Function, ) from typing import List, Callable, Union, Optional, Any # Third-party imports from pydantic import BaseModel # AgentFunction = Union[str, Callable[[]...
Python
1
from tkinter import * from tkinter import ttk def convert(): conn = conn_type.get() r0 = 0 r1 = int(r1_entry.get()) r2 = int(r2_entry.get()) if conn == 'cons': r0 = r1 + r2 else: r0 = (r1 * r2) / (r1 + r2) r0_label['text'] = str(round(r0, 2)) root = Tk() root.geometry('200x250') root.title('Resistance'...
Python
1
""" ``` /* * Crea un programa que calcule quien gana más partidas al piedra, * papel, tijera, lagarto, spock. * - El resultado puede ser: "Player 1", "Player 2", "Tie" (empate) * - La función recibe un listado que contiene pares, representando cada jugada. * - El par puede contener combinaciones de "🗿" (piedra), ...
Python
1
from unittest.mock import patch from enforce_typing import enforce_types from pytest import approx from pdr_backend.subgraph.subgraph_consume_so_far import get_consume_so_far_per_contract from pdr_backend.util.time_types import UnixTimeS SAMPLE_CONTRACT_DATA = [ { "user": {"id": "0xff8dcdfc0a76e031c7203...
Python
1
::YGAlignBaseline, Align::SpaceBetween => internal::YGAlign::YGAlignSpaceBetween, Align::SpaceAround => internal::YGAlign::YGAlignSpaceAround, } } } impl From<internal::YGAlign> for Align { fn from(a: internal::YGAlign) -> Align { match a { internal::YGAlign::YGAlignAuto => Align::Auto, internal::YGA...
Rust
0
report.append("## 🔧 Functions Needing Refactoring") report.append("") for func in metrics.function_metrics['functions_over_50_lines'][:5]: report.append(f"- **{func['name']}** ({func['lines']} lines)") report.append(f" - File: `{func['file']}:{func['start_line']...
Python
1
client supports Team authentication. /// Team authentication works by adding a `Authorization: Bearer <TOKEN>` header, and optionally a /// `Dropbox-API-Select-Admin` or `Dropbox-API-Select-User` header. pub trait TeamAuthClient: HttpClient {} /// Marker trait to indicate that a HTTP client supports App authenticatio...
Rust
0
available_bin_sections, } } /// The free [`BinSection`]s within the [`TargetBin`] that rectangles can still be placed into. pub fn available_bin_sections(&self) -> &Vec<BinSection> { &self.available_bin_sections } /// Remove the section that was just split by a placed r...
Rust
0
/// .to_owned(); /// /// assert_eq!( /// query.to_string(MysqlQueryBuilder), /// r#"SELECT `character`, `size_w`, `size_h` FROM `character` WHERE `character`.`size_w` > 2"# /// ); /// assert_eq!( /// query.to_string(PostgresQueryBuilder), /// r#"SELECT "character",...
Rust
0
loop { if i < max_marching_steps { break; } let dist = scene_sdf(eye + depth * dir); if dist < epsilon { return depth; } depth += dist; if depth >= end { return end; } i += 1; } end } #[allow(unuse...
Rust
0
"""7. Faça um Programa que calcule a área de um quadrado, em seguida mostre o dobro desta área para o usuário.""" lado = float(input('Informe de um quadrado: ')) dobro = (lado**2) * 2 area = lado**2 print(f'O dobro área do quadrado informado é de {dobro}')
Python
1
name="suvrodip" first_character= name[0] second_character= name[1] third_character= name[:] fourth_character= name[-2] print(first_character) print(second_character) print(third_character) print(fourth_character,"\n") full_name = "suvrodip chakroborty" print(full_name) slice_full_name = full_name[0:8] # its mean 0 to ...
Python
1
from langchain_community.tools.interaction.tool import StdInInquireTool __all__ = ["StdInInquireTool"]
Python
1
ns.header == "xproto"; let is_send_event = is_xproto && request_def.name == "SendEvent"; if let Some(ref doc) = request_def.doc { generator.emit_doc(doc, out); } let mut derives = Derives::all(); generator.filter_derives_for_fields(&mut derives, &request_def.fields.borrow(), true); let...
Rust
0
not success: self.grNode.setToolTip("Graph evaluation failed") self.markInvalid() return False self.markDirty(False) self.markInvalid(False) self.grNode.setToolTip("") return success def getShaderInputs(self): sockets = self.i...
Python
1
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file './misleep/gui/uis/about.ui' # # Created by: PyQt5 UI code generator 5.15.10 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 im...
Python
1
compress(c: &mut Criterion) { c.bench_function("RistrettoPoint compression", |b| { let B = &constants::RISTRETTO_BASEPOINT_POINT; b.iter(|| B.compress()) }); } fn decompress(c: &mut Criterion) { c.bench_function("RistrettoPoint decompression", |b| { ...
Rust
0
{"data":{"updateOneA":{"id":"507f1f77bcf86cd799439011","list_field":["507f191e810c19729de860ea","61cd963c5488078418a9f125","61cd96565488078418a9f126","61cd96605488078418a9f127"]}}}"### ); // push 2 Ok(()) } } <gh_stars>1-10 use criterion::{black_box, criterion_group, criterion_main, Criter...
Rust
0
compatibleFrequency : mismatch between dtype and freq NT is_periodzdtype must be PeriodDtypez&specified freq and dtype are different)rr)rVr+rrcr!rrNrNrOras   (tuple[npt.NDArray[np.int64], BaseOffset]cCst|jtjr |jjd...
Python
1
mut BTH_LE_GATT_SERVICE; ENUM!{enum BTH_LE_GATT_DESCRIPTOR_TYPE { CharacteristicExtendedProperties, CharacteristicUserDescription, ClientCharacteristicConfiguration, ServerCharacteristicConfiguration, CharacteristicFormat, CharacteristicAggregateFormat, CustomDescriptor, }} pub type PBTH_LE_...
Rust
0
ranked_docs = index_and_rank(corpus, query) return ranked_docs # def run_rag(urls: List[str], query: str) -> List[Dict[str, str]]: # # Use multiprocessing to chunk URLs in parallel # with Pool(processes=min(cpu_count(), len(urls))) as pool: # chunks_list = pool.map(intelligent_chunking, urls) ...
Python
1
d == "interactive": interactive_mode(agent) # elif args.command == "query": # handle_query(args, agent) elif args.command == "collect": handle_collect(args, agent) elif args.command == "analyze": handle_analyze(args, agent) else: # This should not happen due to 'r...
Python
1
<Event>, } <filename>frontend/src/pages.rs<gh_stars>0 pub mod home; pub mod login;use std::fmt; #[derive(Copy, Clone, Eq)] pub union Piece { pub parts: [u16; 4], pub full: u64, } impl Piece { pub const fn uninit() -> Piece { Piece { full: 0 } } #[inline] pub fn shift_right(&mut self, ...
Rust
0
eturn None types.append(analyzed) return items, types, True def fail_typeddict_arg( self, message: str, context: Context ) -> tuple[str, list[str], list[Type], bool, list[TypeVarLikeType], bool]: self.fail(message, context) return "", [], [], True, [], False def...
Python
1
rk: self.get_network()?, key: sk, }, None, Some(false), ) .map_err(rpc_err_to_manager_err)?; Ok(sk) } fn get_secret_key_for_pubkey(&self, pubkey: &PublicKey) -> Result<SecretKey, ManagerError> { let b_p...
Rust
0
/// /// ``` /// extern crate elf_utils; /// /// use byteorder::LittleEndian; /// use elf_utils::Elf32; /// use elf_utils::section_hdr::SectionHdrData; /// use elf_utils::section_hdr::SectionPos; /// use elf_utils::section_hdr; /// /// const SECTION_HDR_CONTENTS: [SectionHdrData<Elf32, u32, u32, u32, u32, /// ...
Rust
0
import os os.environ["STREAMLIT_SERVER_FILE_WATCHER_TYPE"] = "none" import streamlit as st import pandas as pd from analyzer import analyze_sentiment, analyze_emotion, analyze_sentiment_with_tracking from explainability import highlight_words from utils import detect_language, export_results, export_pdf from dashboard ...
Python
1
senha = '1234' c = 0 s =0 while s != senha: s = input('Digite a senha: ') if s == senha: print('Bem vindo ao sistema!') break elif c == 3: print('Fim das tentativas!') if c != 3: c += 1 print('') break
Python
1
import torch from torch import nn from torch.nn import functional as F from attention import SelfAttention class VAE_Attention_Block(nn.Module): """ VAE Attention Block Args: x: (convolved images) torch.Tensor of shape (batch_size, features, height, width) features=channels=512: int Ret...
Python
1
jvm_spec), # TODO: This needs to be set for complex types 'children': [] } jvm_field = _jvm_field(json.dumps(spec)) # Create VectorSchemaRoot jvm_fields = jpype.JClass('java.util.ArrayList')() jvm_fields.add(jvm_field) jvm_vectors = jpype.JClass('java.util.ArrayList')() jvm_...
Python
1
#!/usr/bin/env python """ Copyright (c) 2006-2024 sqlmap developers (https://sqlmap.org/) See the file 'LICENSE' for copying permission """ from lib.core.data import logger from plugins.generic.enumeration import Enumeration as GenericEnumeration class Enumeration(GenericEnumeration): def getBanner(self): ...
Python
1
import numpy as np import os, sys # Constants alpha = 1e-2 nonzero_ratio = 0.15 FILE = "../01_RANDOM_QP.txt" # Variables n = 5 random_seed = 0 if __name__ == "__main__": # Read n and random_seed from the command line if len(sys.argv) > 1: n = int(sys.argv[1]) if len(sys.argv) > 2: random...
Python
1
# -*- coding: utf-8 -*- """ proxy.py ~~~~~~~~ ⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on Network monitoring, controls & Application development, testing, debugging. :copyright: (c) 2013-present by Abhinav Singh and contributors. :license: BSD, see LICENSE...
Python
1
# Copyright (c) 2024, RoboVerse community # SPDX-License-Identifier: BSD-3-Clause from dataclasses import dataclass from typing import List @dataclass class RobotConfig: """Robot configuration parameters""" robot_ip_list: List[str] token: str conn_type: str enable_video: bool decode_lidar: bo...
Python
1
{ lo = thresh } else { distoachieved = if layno == 0 as libc::c_int as libc::c_uint { (*tcd_tile).distolayer[0 as libc::c_int as usize] } else { (cumdisto[layno.wrapping_sub(1 as libc::c_int as libc::c_uint) as usize]) ...
Rust
0
pPartnerDeviceId": pagpPartnerDeviceId, "pagpPartnerLearnMethod": pagpPartnerLearnMethod, "pagpPartnerPortPriority": pagpPartnerPortPriority, "pagpPartnerIfIndex": pagpPartnerIfIndex, "pagpPartnerGroupCapability": pagpPartnerGroupCapability, "pagpPartnerGroupIfIndex": pagpPartnerGroup...
Python
1
# Copyright (c) Dec 22, 2014 CareerMonk Publications and others. # E-Mail : info@careermonk.com # Creation Date : 2014-01-10 06:15:46 # Last modification : 2008-10-31 # by : Narasimha Karumanchi # Book Title : Data Structures And Algorithmic Thinking With Python # Warranty ...
Python
1
as *const AioFsync as *const libc::aiocb ); let mut rbuf = []; let aior = AioRead::new(666, 0, &mut rbuf, 0, sev); assert_eq!( aior.as_ref() as *const libc::aiocb, &aior as *const AioRead as *const libc::aiocb ); let wbuf = []; let aiow ...
Rust
0
eval_program(&p).unwrap()), Err(e) => println!("Parser error: {}", e), } print!(">> "); output.flush().unwrap(); } } <gh_stars>100-1000 use rune_tests::*; macro_rules! test_op { ($ty:ty => $lhs:literal $op:tt $rhs:literal = $result:literal) => {{ let program = format...
Rust
0
rustlsify(key: Vec<u8>, cert: Vec<u8>) -> CertifiedKey { CertifiedKey::new( vec![rustls::Certificate(cert)], Arc::new( rustls::sign::any_ecdsa_type(&PrivateKey(key)) .map_err(|_| anyhow!("unsupport private key type")) .unwrap(), ...
Rust
0
assert_eq!( unsafe { &(*(::std::ptr::null::<bam1_t>())).m_data as *const _ as usize }, 68usize, concat!( "Offset of field: ", stringify!(bam1_t), "::", stringify!(m_data) ) ); } impl bam1_t { #[inline] pub fn mempolicy(&sel...
Rust
0
bytes::randombytes; use super::*; const BENCH_SIZES: [usize; 14] = [0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]; #[bench] fn bench_hash(b: &mut test::Bencher) { let ms: Vec<Vec<u8>> = BENCH_SIZES.iter().map(|s| { randombytes(*s)...
Rust
0
), borrowed_fd(new_dirfd), c_str(new_path), )) } } #[cfg(not(target_os = "redox"))] pub(crate) fn statat(dirfd: BorrowedFd<'_>, path: &CStr, flags: AtFlags) -> io::Result<Stat> { // 32-bit and mips64 Linux: `struct stat64` is not y2038 compatible; use // `statx`. #[cfg(a...
Rust
0
# -*- coding: UTF-8 -*- ''' @Project : torch_clustering @File : __init__.py @Author : Zhizhong Huang from Fudan University @Homepage: https://hzzone.github.io/ @Email : zzhuang19@fudan.edu.cn @Date : 2022/10/19 12:21 PM ''' from .kmeans.kmeans import PyTorchKMeans from .faiss_kmeans import FaissKMeans from ...
Python
1
""" Test credit card numbers """ from pii_manager import PiiEnum from pii_manager.api import PiiManager TEST = [ # A valid credit card number ( "El número de la tarjeta de crédito es 4273 9666 4581 5642", "El número de la tarjeta de crédito es <CREDIT_CARD>", ), # Without spaces (...
Python
1
import streamlit as st from crewai import Agent, Task, Crew, Process from langchain.tools import Tool from langchain.utilities import SerpAPIWrapper from tavily import TavilyClient from openai import OpenAI import time import base64 import tenacity from openai import OpenAIError # API 키를 st.secrets에서 가져옵니다 SERPAPI_API...
Python
1
// we use the thread keyring from a new thread for this purpose to avoid // affecting the application calling PAM. let handle = thread::spawn(move || { read_key_thread(&ring, desc) }); let res = handle.join().unwrap(); res.map_err(Into::into) } fn auth(pamh: Pam, _flags: PamFlag, args: ...
Rust
0
_embedded_hal::I2cdev; use pwm_pca9685::{Address, Channel, Pca9685}; use std::{thread, time}; pub fn map(x: i64, in_min: i64, in_max: i64, out_min: i64, out_max: i64) -> i64 { let val = (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; val } /// It is a Controller object /// Controller class (...
Rust
0
############################################################ # # Assign04 for CS525, Fall, 2024 # It is due Monday, the 21st of October, 2024 # Note that the due time is always 11:59pm of # the due date unless specified otherwise. # ############################################################ ##########################...
Python
1
device_state, remote_ips) } } } #[cfg(test)] mod tests { use alloc::vec; use net_types::{ ip::{AddrSubnet, SubnetEither}, Witness, }; use packet::{Buf, InnerPacketBuilder, ParseBuffer}; use packet_formats::{ ip::IpPacket, ipv4::{Ipv4OnlyMeta, Ipv4Packet,...
Rust
0
d_segmentation_labels[1].tolist() word_norm_op_labels = torch.full((num_examples, max_seq_length), IGNORE_INDEX, dtype=torch.long) word_norm_op_labels[0, 1] = WORD_NORM_OP_TAGS.index("K") # 花 word_norm_op_labels[0, 2] = WORD_NORM_OP_TAGS.index("K") # 咲 word_norm_op_labels[0, 3] = WORD_NORM_OP_TAGS.in...
Python
1
""" Output module for REMAG """ import os from tqdm import tqdm from loguru import logger from .utils import ContigHeaderMapper def save_clusters_as_fasta(clusters_df, fragments_dict, args): """Save clusters as FASTA files and return valid bin IDs.""" bins_dir = os.path.join(args.output, "bins") os.make...
Python
1
); } for i in (0..500).rev() { let ind = rng.gen_range(0, i + 1); tree.remove(ind); } tree.clear(); }); } #[bench] fn vec_insert_delete_random_1000(bencher: &mut Bencher) { let mut rng = StdRng::seed_from_u64(0); bencher.iter(|| { let mut v...
Rust
0
qOp {})); result.push(Box::new(ge::GeOp {})); result.push(Box::new(gt::GtOp {})); result.push(Box::new(is_between::IsBetweenOp {})); result.push(Box::new(le::LeOp {})); result.push(Box::new(lt::LtOp {})); result.push(Box::new(neq::NeqOp {})); result } <gh_stars>1-10 use crate::Time; use chro...
Rust
0
if tv_count >= 5: # 增加到5个电视剧 break # 最终随机打乱所有推荐 if recommendations: random.shuffle(recommendations) recommendations = recommendations[:8] # 限制为8个推荐,2行每行4个 # 如果API调用失败,返回默认推荐 if not recommendations: recommendat...
Python
1
} pub fn unicode_value_out_of_range(value: u64) -> DmntkError { LexerError::UnicodeValueOutOfRange(value).into() } pub fn unicode_surrogate_out_of_range(value: u64) -> DmntkError { LexerError::UnicodeSurrogateOutOfRange(value).into() } pub fn unicode_conversion_failed(value: u64) -> DmntkError { ...
Rust
0
mp1, p2_in); res[i].p2_ = _mm_add_ps( res[i].p2_, _mm_mul_ps(tmp2, _mm_shuffle_ps(p2_in, p2_in, 120 /* 1, 3, 2, 0 */)), ); res[i].p2_ = _mm_add_ps( res[i].p2_, _mm_mul_ps(tmp3, _mm_shuffle_ps(...
Rust
0
match msg.member(&ctx).await { Ok(member) => match member.permissions(&ctx).await { Ok(perm) => match perm.administrator() { true => Ok(()), false => Err(Reason::User("Not an administrator".to_string())), }, Err(e) => Err(Reason::User(e.to_...
Rust
0
D", "error": str(e)} # Final summary logger.info("\n" + "="*80) logger.info("🏁 MULTI-MODEL EXPERIMENT COMPLETE (PHASE 2 FIXED TENSORS)") logger.info("="*80) for model_type, results in overall_results.items(): verdict = results.get("verdict", "UNKNOWN") logger.info(f"{model...
Python
1
rn np.sum(p) - L # Define bounds for power outputs bounds = [(p_min[i], p_max[i]) if x_sol[i] == '1' else (0, 0) for i in range(nb_units)] # Initial guess: even distribution of L among active units num_active_units = len(active_units) initial_guess = [0] * nb_units if num_active_units > 0: ...
Python
1
, _ => false, }), { let client = client.clone(); move |s| { story_view::add_story_view_layer(s, &client, "show_hn", true, 0, None, false); } }, ); s.set_on_post_event( EventTrigger::from_fn(|e| match e { ...
Rust
0
# 82. Find Longest Word in File def find_longest_word(file_path: str): try: with open(file_path, 'r') as file: words = file.read().split() longest_word = max(words, key=len) print(longest_word) except FileNotFoundError: print("File not found.") find_longest_wo...
Python
1
''' Created on 11.01.2012 @author: thomas ''' from scikits.audiolab import Sndfile,Format def sndreader(sf,blksz=2**16): if blksz < 0: blksz = sf.nframes if sf.channels > 1: channels = lambda s: s.T else: channels = lambda s: s.reshape((1,-1)) for offs in xrange(0,sf.nframes,...
Python
1
SIONS__", "--expt-relaxed-constexpr", "--expt-extended-lambda", ] + generator_flag, }, ) ) setup( name="unicore", version=version, description="DP Technology's Core AI Framework", url="https://github.com/dpte...
Python
1
} fn parse_incdec_full(bytes: &[u8]) -> DecodeResult { check_length(bytes, 1)?; let b = bytes[0]; let reg = get_fullreg(bytes[0] >> 4, true); let inc = b & 0x8 == 0; Ok(Instruction { cmd: Command::IncDecFull { reg, inc }, cycles: 8, alt_cycles: None, encoding: byt...
Rust
0
scheduler = JobScheduler::new(); scheduler.add(Job::new(commit_schedule.parse().unwrap(), || { let client_id = rand::random(); let mut client = Clerk::new(&servers, client_id); info!("commit"); client.commit(); })); scheduler.add(Job::new(merge_schedule.parse().unwrap(), |...
Rust
0
assert_eq!(::std::mem::align_of::<_VAEncSequenceParameterBufferHEVC__bindgen_ty_2__bindgen_ty_1>() , 4usize); } impl Clone for _VAEncSequenceParameterBufferHEVC__bindgen_ty_2__bindgen_ty_1 { fn clone(&self) -> Self { *self } } impl _VAEncSequenceParameterBufferHEVC__bindgen_ty_2__bindgen_ty_1 { ...
Rust
0
ntinue # don't dig where you've already dug self.dig(r, c) # if our initial dig didn't hit a bomb, we *shouldn't* hit a bomb here return True def __str__(self): # this is a magic function where if you call print on this object, # it'll print out what this function ...
Python
1
config .lookup("output.kafka_ssl_cert_path") .map(|x| x.as_str() .expect("output.kafka_ssl_cert_path must be a string") ).map(|x| String::from(x)); let ssl_key_path = config .lookup("output.kafka_ssl_key_path") .map(|x| x.as_str() ...
Rust
0
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ Description: These plugins define various translation engines to use when translating text. The idea is to expose a semi-uniform interface. These plugins assume the data will be input as either a single string or as a batch. Batches are a single Python list where each ...
Python
1
import time import requests from starknet_py.net.signer.stark_curve_signer import KeyPair from starknet_py.net.full_node_client import FullNodeClient from starknet_py.common import int_from_bytes from starknet_py.net.account.account import Account from src.config.constants import STARKNET_FULLNODE_RPC_URL, STARKNET_C...
Python
1
# Copyright (C) 2018-2025 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # # tanh paddle model generator # import numpy as np from save_model import saveModel import paddle import sys data_type = 'float32' def tanh(name:str, x): paddle.enable_static() with paddle.static.program_guard(paddle.sta...
Python
1
import os from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app_settings.settings") application = get_asgi_application() import logging # Configure logging logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", handler...
Python
1
os, bit| *bit); /// /// assert_eq!(iter.next().unwrap(), bits![0, 0, 1]); /// assert_eq!(iter.next().unwrap(), bits![0, 1]); /// assert!(iter.next().is_none()); /// ``` /// /// [`.split()`]: Self::split /// [`.split_inclusive_mut()`]: Self::split_inclusive_mut pub fn split_inclusive<F>(&self, pred: F) -> Split...
Rust
0
uide = vec2(vel.x.signum(), 0.0); let vel_angle = vel_guide.angle_normalized(*vel / vel_magnitude); if vel_angle >= BALL_MAX_VEL_DEVIATION_ANGLE { let sign = vel_guide.angle_sign(*vel); *vel = vel_guide.rotated(BALL_MAX_VEL_DEVIATION_ANGLE * sign) * vel_magnitude; } } ...
Rust
0
buffer = String::new(); // let mut content_length: Option<usize> = None; // // loop { // buffer.clear(); // let _result = reader.read_line(&mut buffer); // // // eprintln!("got message {} {}", buffer, buffer.trim().is_empty()); // match &buffer { // s if s.trim().is_empty()...
Rust
0
m.add_class::<digraph::PyDiGraph>()?; m.add_class::<graph::PyGraph>()?; m.add_wrapped(wrap_pymodule!(generators))?; Ok(()) } #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } } <gh_stars>1-10 #[cfg(feature = "sni")] fn main() -> Result<(), Box<dyn std::error::Erro...
Rust
0
) except GeneratorExit: pass class OnsetTestDataset(torch.utils.data.Dataset): def __init__( self, score_base_path: Path, audio_base_path: Path, live_ids: List[int], device: str = None, diff_type: int = 30, with_beats: bool = True, ...
Python
1
L, "threadId" UUID NOT NULL, "value" INT NOT NULL, "comment" TEXT, FOREIGN KEY ("threadId") REFERENCES threads("id") ON DELETE CASCADE );""" ) )...
Python
1
art)] /// To start the Wasm application, wasm_bindgen runs this functions pub fn wasm_bindgen_start() -> Result<(), JsValue> { // Initialize debugging for when/if something goes wrong. console_error_panic_hook::set_once(); // write the app version just for debug purposes debug_write(&format!( "n...
Rust
0
gits[mask] labels = labels[mask] with torch.no_grad(): logits_on_labels = torch.gather( logits, dim=-1, index=labels.unsqueeze(-1) ).squeeze(-1) logits_diff = logits - logits_on_labels.unsqueeze(-1) if self.h_function == "linear": ...
Python
1
""" Testing events package. This package provides implementations for Testing HCI events. """ from .testing_events import ( # Event classes LoopbackCommandEvent, # Helper functions loopback_command, ) # Re-export everything to make public API cleaner __all__ = [ # Event classes 'Loopback...
Python
1
//self.next_innovation_num += 1; self.next_innovation_num } pub fn get_neuron_id(&self, inv: i32) -> i32 { self.innovs[inv as usize].neuron_id } pub fn _flush(&mut self) { self.innovs.clear(); } } //-------------------------------------------------------// //---基因组---...
Rust
0
ccount_ai - Liqor MangoAccount /// 4. `[signer]` liqor_ai - Liqor Account /// 5. `[]` root_bank_ai - RootBank /// 6. `[writable]` node_bank_ai - NodeBank /// 7. `[writable]` vault_ai - ? /// 8. `[writable]` dao_vault_ai - DAO Vault /// 9. `[]` signer_ai - Group Signer Account /// 10. `[]` pe...
Rust
0
erbatim into the output documentation file #[derive(Debug, Default, Serialize, Deserialize)] pub struct TextBlock { /// The source text pub text: Vec<String>, } /// A `Transclusion` is a reference to another file that should be pulled into the source #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] p...
Rust
0
from .. import IconBase class IconCircleGauge(IconBase): class_name = "lucide lucide-circle-gauge" svg_data = { "attrs": { "width": "24", "height": "24", "view_box": "0 0 24 24", "fill": "none", "stroke": "currentColor", "stroke_width": "2", "stroke_...
Python
1
} controlled_next_nodes.push(n); } if controlled_next_nodes.len() == 0 { debug!("No valid next states"); return controlled_next_nodes; } let next_nodes = (0..cmp::min(args.beam_width, controlled_next_nodes.len())) .map(|i| controlled_next_nodes[i].clone()) ...
Rust
0
AVStreamInternal { _unused: [u8; 0], } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct AVStream { pub index: ::std::os::raw::c_int, pub id: ::std::os::raw::c_int, pub codec: *mut AVCodecContext, pub priv_data: *mut ::std::os::raw::c_void, pub time_base: AVRational, pub start_time: i64, ...
Rust
0
w_id = record.id + "_" + name record.id = new_id new_records.append(record) unique_species.update(seen_species) if len(new_records) >= self.min_species: names_og[name] = new_records self.num_selected_ogs += 1 ...
Python
1
import logging import requests from utils.parser import extract_content logging.basicConfig(level=logging.INFO) class Groq: def __init__(self, token: str): self.token = token self.url = "https://api.groq.com/v1/request_manager/text_completion" self.logger = logging.getLogger(__name__) ...
Python
1
# --8<-- [start:setup] from datetime import date, datetime import polars as pl # --8<-- [end:setup] # --8<-- [start:df] df = pl.read_csv("docs/assets/data/apple_stock.csv", try_parse_dates=True) df = df.sort("Date") print(df) # --8<-- [end:df] # --8<-- [start:group_by] annual_average_df = df.group_by_dynamic("Date"...
Python
1
import asyncio from contextlib import asynccontextmanager import time from typing import AsyncIterator class SilenceObserver: """ This class is helpful for actions that happen in the background, with no urgency. Additionally, we might have urgent tasks that are competing for some shared resource. Sil...
Python
1
let mut x = vec![0; b.bytes as usize]; b.iter(|| rng.fill_bytes(x.as_mut_slice())) } <gh_stars>0 use std::str::FromStr; use pathfinding::directed::astar::astar; struct Map { raw_map: Vec<Vec<usize>>, height: usize, width: usize, } impl FromStr for Map { type Err = (); fn from_str(s: &str)...
Rust
0
, "uie"), UTVEC = (4101, "utvec"), USCRATCH = (4160, "uscratch"), UEPC = (4161, "uepc"), UCAUSE = (4162, "ucause"), UTVAL = (4163, "utval"), UIP = (4164, "uip"), FFLAGS = (4097, "fflags"), FRM = (4098, "frm"), FCSR = (4099, "fcsr"), CYCLE = (7168, "cycle"), TIME = (7169, "tim...
Rust
0
sender_subnet_id, own_subnet_type, log, ); }); } #[test] fn create_canister_same_subnets_on_nns() { with_test_replica_logger(|log| { let own_subnet_type = SubnetType::System; let sender = canister_test_id(7); let nns_subnet_id = subnet_test_id(1); ...
Rust
0
pub fn has_xcb_input_get_device_motion_events_sizeof(&self) -> bool { has_sym!(self, xcb_input_get_device_motion_events_sizeof) } /// Sends a `Input::GetDeviceMotionEvents` request (checked). /// /// This request generates a reply. You must either discard it with /// [`discard_reply`] or ...
Rust
0
0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x31, 0x32, 0x33, 0x34]; static PIN_1234_SHA1: &[u8] = &[0x71, 0x10, 0xed, 0xa4, 0xd0, 0x9e, 0x06, 0x2a, 0xa5, 0xe4, 0xa3, 0x90, 0xb0, 0xa5, 0x72, 0xac, 0x0d, 0...
Rust
0