text
string
label_name
string
labels
int64
33_935_835, -0.504_400_557]; const Q: [f32; 2] = [0.560_363_004_e+1, -0.554_846_723_e+1]; const A: [f32; 2] = [0., f32::consts::FRAC_PI_4]; const B: [f32; 2] = [f32::consts::FRAC_PI_2, f32::consts::FRAC_PI_4]; /// Arcsine /// /// Input: /// x - floating point value /// acosine - indicates acos calculation /// /...
Rust
0
Fitting logistic regression on {len(train_features)} slides") print(f" Evaluating on {len(test_features)} slides") NUM_C = 2 COST = (train_features.shape[1] * NUM_C) / 100 clf = LogisticRegression(C=COST, max_iter=10000, verbose=0, ra...
Python
1
) ] ) # Dynamic ranges cannot overlap anything (no ranges or IPs). unused = await services.v3subnet_utilization.get_ipranges_available_for_dynamic_range( subnet_id=subnet.id, exclude_ip_range_id=existing_iprange_id ...
Python
1
def solve(grid): h, w = len(grid), len(grid[0]) vis = [[False]*w for _ in range(h)] comps = [] for i in range(h): for j in range(w): if grid[i][j] == 3 and not vis[i][j]: q = [(i,j)] vis[i][j] = True pts = [] for x,y in ...
Python
1
) # calculate the dimension at each scale dim_scales = [int(dim_out / (2 ** i)) for i in range(1, num_scales)] dim_scales = [*dim_scales, dim_out - sum(dim_scales)] self.convs = nn.ModuleList([]) for kernel, dim_scale in zip(kernel_sizes, dim_scales): self.convs.app...
Python
1
KeyStroke ) )); assert_eq! (unsafe { & ( * ( 0 as * const _SIMPLE_INPUT_INTERFACE ) ) . WaitForKey as * const _ as usize } , 16usize , concat ! ( "Alignment of field: " , stringify ! ( _SIMPLE_INPUT_INTERFACE ) , "::" , stringify ! ( WaitForKey ) )); }...
Rust
0
from openai import AzureOpenAI class RelatedWorkEvaluation: def __init__(self, client=None): """ Initialize with Azure OpenAI client Assumes environment variables or direct credentials are set up """ self.client = client or AzureOpenAI( azure_endpoint="https://a...
Python
1
Some(sleep_impl)); } let client = builder.build(); Self { handle: std::sync::Arc::new(Handle { client, conf }), } } } use std::env; use std::time::Duration; use anyhow::Context; use atty; use clap::{Clap, AppSettings}; use edgedb_client::Builder; use crate::credentials...
Rust
0
#[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `HOST_SLC0_TOHOST_BIT6_INT_ENA` writer - "] pub struct HOST_SLC0_TOHOST_BIT6_INT_ENA_W<'a> { w: &'a mut W, } impl<'a> HOST_SLC0_TOHOST_BIT6_INT_ENA_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub...
Rust
0
p.set_leader_process(process.clone()); pgrp.add_new_process(process); Ok(pgrp) } // Create a new process group with given pid pub fn new_with_pid(pid: pid_t) -> Result<Self> { let leader_process = table::get_process(pid)?; Self::new(leader_process) } // Remove proce...
Rust
0
sim, " INSERT INTO inventory (product_id, email, count) VALUES (2, 'my_email_2', 35), (3, 'my_email_3', 45), (4, 'my_email_4', 55); DELETE FROM inventory WHERE product_id % 2 = 0; INSERT INTO inventory (product_id, email, count) V...
Rust
0
{ if !msg.author.bot; if let Ok(mut guard) = bot::QUIZ.lock(); then { let ans = executors::prob(ctx, &msg, bot::Lang::En); *guard = bot::Status::Holding(ans.clone(), bot::Lang::En, Instant::now()); } } Ok(()) } #[command] pub fn ja(ctx: &mut Context, msg...
Rust
0
self.areaRubberband4.setToGeometry(QgsGeometry.fromPolyline(points4), None) else: point1 = QgsPoint(self.areaEnd.x(), self.areaStart.y()) point2 = QgsPoint(self.areaStart.x(), self.areaEnd.y()) points1 = [self.areaStart, point1] points2 =...
Python
1
et_program_info_log(&shader_program) .unwrap_or_else(|| String::from("Unknown error occurred when creating program object"))) } else { Ok(shader_program) } } fn compile_shader(context: &GL, shader_type: u32, source: &str) -> Result<WebGlShader, String> { // TODO LEFT OFF "Initializing...
Rust
0
wMessage("✅ FBWA moduna geçildi") QTimer.singleShot(2000, self.custom_flight_step_3) else: self.abort_custom_flight("❌ FBWA mode değişikliği başarısız!") def custom_flight_step_3(self): """Adım 3: GUIDED Pistten kalkış - DÜZELTME""" if not self.flight_active: ...
Python
1
after file-access")) .keep_left() .map(|x| FileAccess::Read.at(x.pos())) } // AS <ws+> expression // AS ( expression ) fn parse_file_number_p<R>() -> impl Parser<R, Output = ExpressionNode> where R: Reader<Item = char, Err = QError> + HasLocation + 'static, { ...
Rust
0
import abc from pydantic.main import BaseModel from storage.storage.storage_interface import Pageable, DataPage class TopicStorageInterface(abc.ABC): @abc.abstractmethod def topic_data_insert_one(self, one: any, topic_name: str) -> tuple: pass @abc.abstractmethod def topic_data_insert_(self...
Python
1
set to `Execution`. The execution with the properties as described in the [get single execution](https://docs.camunda.org/manual/7.14/reference/rest/execution/get/) method. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MessageCorrelationResultWithVariableDto { /// Indicates if the messag...
Rust
0
from torch.nn import Module, AdaptiveAvgPool3d, Sequential, Linear, ReLU, Sigmoid, Conv3d, BatchNorm3d, ModuleList, \ MaxPool3d, init from torch.nn.modules.utils import _triple class SELayer(Module): """ 1.squeeze: 全局池化 (batch,channel,height,width) -> (batch,channel,1,1) ==> (batch,channel) 2.excitati...
Python
1
let long_k = k.to_usize().unwrap(); if mea == mea_mat[long_i][long_k] + mea_mat[long_k + 1][long_j] { pos_pair_stack.push((i, k)); pos_pair_stack.push((k + T::one(), j)); break; } } } } mea_css.ea = mea_mat[0][sa_len.to_usize().unwrap() - 1]; mea_css } ...
Rust
0
_derive; #[macro_use] extern crate dotenv; extern crate chrono; extern crate postgres; #[macro_use] extern crate rocket; extern crate rocket_contrib; use rocket_contrib::json::{Json}; mod db; mod ds; mod params; use rocket::request::Form; extern crate rocket_cors; use rocket_cors::*; use std::fs::DirBuilder; fn mai...
Rust
0
"""Tests for the bob_emploi.importer.job_offers_change.""" from os import path import unittest from bob_emploi.frontend.api import job_pb2 from bob_emploi.data_analysis.importer import job_offers_changes from bob_emploi.data_analysis.lib import mongo class JobOffersEvolutionImporterTestCase(unittest.TestCase): ...
Python
1
= Stream::new(); let mapped_stream_ = mapped_stream.new_same(); self.observe(move |sig| { if let Some(ref mapped_sig) = f(sig) { mapped_stream_.send(mapped_sig); } }); mapped_stream } /// Filter the signals flowing out of a stream with a predicate. pub fn filter<F>(&self, p...
Rust
0
.len() { // 左項をキャリーダウン。 for i in 0..long_num.numbers.len() { if i == 0 { // 一の位に変化なし。 } else if i == long_num.numbers.len() - 1 { // 最上位は1減る。 long_num.add_figure(i, -1); ...
Rust
0
import requests, json, time, math from scipy import stats import csv ''' ahr999囤币指标: 计算方式:ahr999指标 =(比特币价格/200日定投成本)*(比特币价格/指数增长估值)。 其中指数成长估值为币价和币龄的拟合结果,本指数拟合方法为每月对历史数据进行拟合。 指标说明:该指标由微博用户ahr999创建,辅助比特币定投用户结合择机策略做出投资决策。 该指标隐含了比特币短期定投的收益率及比特币价格与预期估值的偏离度。 从长期来看,比特币价格与区块高度呈现出一定的正相关,同时借助定投方式的优势,短期定投成本大都位于比特币价格之下。 因此,当比...
Python
1
from redux.pipe import Pipe import pyami.fft # Two threads doing power at the same time may be causing trouble. # Make a thread lock to prevent this. import threading import sys powerlock = threading.Lock() sys.stderr.write('**power thread lock in effect') pyami.fft.calculator.stashing_on = False class Power(Pipe): ...
Python
1
tring = RawOsStr::from_str("\u{F6}"); test(|| string.index(1..2)); test(|| string.index(0..1)); test(|| string.index(1..)); test(|| string.index(0..=0)); test(|| string.index(..1)); test(|| string.index(..=0)); test(|| string.split_at(1)); #[track_caller] fn test<F, R>(f: F) whe...
Rust
0
with_capacity.capacity()); }// Helper macro to execute a system call that returns an `io::Result`. // // Macro must be defined before any modules that uses them. cfg_os_poll! { mod selector; pub(crate) use self::selector::{event, Event, Events, Selector}; mod waker; pub(crate) use self::waker::Waker; ...
Rust
0
# encoding: utf-8 """ """ import typing as _t from .node_dict_add_any import StringConstructorDictAddAny from .node_dict_add_string import StringConstructorDictAddString from .node_dict_key_extract import StringConstructorDictExtractString from .node_dict_from_text import StringConstructorDictFromText from .node_dict...
Python
1
rn "C" { pub fn DAQmxResetAOFuncGenOffset( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, ) -> int32; } extern "C" { pub fn DAQmxGetAOFuncGenSquareDutyCycle( taskHandle: TaskHandle, channel: *const ::std::os::raw::c_char, data: *mut float64, ) -> ...
Rust
0
ing_WinInet'*"] pub const INTERNET_OPTION_HIBERNATE_INACTIVE_WORKER_THREADS: u32 = 91u32; #[doc = "*Required features: 'Win32_Networking_WinInet'*"] pub const INTERNET_OPTION_HSTS: u32 = 157u32; #[doc = "*Required features: 'Win32_Networking_WinInet'*"] pub const INTERNET_OPTION_HTTP_09: u32 = 191u32; #[doc = "*Require...
Rust
0
{ Ok(acc) => acc["code_hash"].as_str().unwrap_or("0"), Err(e) => { debug!("get_account_code_hash failed: {}", e); "0" } }; Ok(( answer_id, json!({ "code_hash": format!("0x{}", code_hash_str) }), )) } ...
Rust
0
from rest_framework import serializers from .models import AIConfig class AIConfigSerializer(serializers.ModelSerializer): api_key = serializers.CharField(help_text='密钥明文返回') class Meta: model = AIConfig fields = [ 'id', 'name', 'provider', 'model', 'enabled', 'is_default', 'prior...
Python
1
let mut b: Vec<u8> = digit.bytes().filter(|b| sample_4.contains(b)).collect(); b.sort_unstable(); let b = b.len() == 3; if b {5} else{2} } } ,6 => { let mut c: Vec<u8> = digit.bytes().filter(|b| sampl...
Rust
0
}\n" ); test!( index_unit_conversions, "a {\n color: index(1px 1in 1cm, 96px);\n}\n", "a {\n color: 2;\n}\n" ); test!( zip_three, "a {\n color: zip(1px 1px 3px, solid dashed solid, red green blue);\n}\n", "a {\n color: 1px solid red, 1px dashed green, 3px solid blue;\n}\n" ); test!( zip_...
Rust
0
in_sel_cfg](gpio_func110_in_sel_cfg) module"] pub type GPIO_FUNC110_IN_SEL_CFG = crate::Reg<u32, _GPIO_FUNC110_IN_SEL_CFG>; #[allow(missing_docs)] #[doc(hidden)] pub struct _GPIO_FUNC110_IN_SEL_CFG; #[doc = "`read()` method returns [gpio_func110_in_sel_cfg::R](gpio_func110_in_sel_cfg::R) reader structure"] impl crate::...
Rust
0
% PEM_HEADER) if not pem_cert_string.strip().endswith(PEM_FOOTER): raise ValueError("Invalid PEM encoding; must end with %s" % PEM_FOOTER) d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)] return base64.decodestring(d) def get_server_certificate (addr, ssl_versi...
Python
1
# -*- coding: utf-8 -*- SYSTEM_PROMPT = """# 角色 您是专业的阿里巴巴云数据库运营助手,专注于为客户提供高效的数据库技术支持和解决方案。您的目标是通过清晰的问题分解、深刻的结果反思和精确的时间计算,帮助客户快速解决问题。 ## 技能 ### 技能 1:问题分解与分析 - 深入拆解用户问题,识别核心需求及相关的潜在步骤/命令。 - 提供明确的任务分解,确保每一步都对最终解决方案有所贡献。 - 当需要用户澄清需求或者需要用户确认行动时,利用工具 interaction 和用户进行沟通,沟通时请完整输出需要确认的内容,避免内容丢失。 - 任务分解必须符合逻辑推理,确保每个步骤都能有效地解决...
Python
1
at(cartridge, address + 1)), 0xD5 => OpCode::PUSH_DE, 0xD6 => OpCode::SUB_d8(d8::at(cartridge, address + 1)), 0xD7 => OpCode::RST_10H, 0xD8 => OpCode::RET_C, 0xD9 => OpCode::RETI, 0xDA => OpCode::JP_C_a16(a16::at(cartridge, address + 1)), ...
Rust
0
完成: 成功融合 {successful_merges} 个Agent帖子,{len(orphaned_agents)} 个孤儿帖子") # 如果有孤儿Agent帖子,可以选择添加到根级别或者创建一个特殊的根节点 if orphaned_agents: print(f"[数据融合] 处理 {len(orphaned_agents)} 个孤儿Agent帖子") # 这里可以根据需要决定如何处理孤儿帖子 # 暂时添加到原始帖子列表的末尾 for orphan in orphaned_agent...
Python
1
import random Lessons = 52 #Это не шутка, в году примерно 52 урока , ориентируясь на шаг если что class Student: def __init__(self, name, age, grades, money): self.name = name self.age = age self.grades = grades self.money = money def average_grade(self): result = int(...
Python
1
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns def calculate_bias_metric(df): # Calculate the average WER for each Model and Style combination average_wer = df.groupby(['Model', 'Style'])['WER'].mean().reset_index() average_wer.rename(columns={'WER': 'Average_W...
Python
1
, str_true=str_true, normalize=True) if progressbar: pbar.update(1) if is_new_epoch: break cer_mean /= (len(dataset)) wer_mean /= (len(dataset)) # TODO: Fix this return cer_mean, w...
Python
1
push_to_vec(&mut print, &[0, 1, 2]); push_to_vec(&mut alpha, &[3, 4, 5, 6]); } 8 => { push_to_vec(&mut print, &[0, 1, 2, 3, 4, 5, 6]); } 9 => { push_to_vec(&mut print, &[0, 1, 2, 3, 5, 6]); push_to_vec(&mut alpha, &[4]); }...
Rust
0
976-02-23 #Record 6 : 000330 OP2012 160 0.75 1982-01-01 1983-02-01 000330 #>>000330,WING, ,LEE,LEE,2103,1976-02-23 #Record 7 : 000320 OP2011 140 0.75 1982-01-01 1983-02-01 000320 #>>000320,RAMLAL,V,MEHTA,MEHTA,9990,1965-07-07 #Record 8 : 000320 OP2011 150 0.25 1982-01-01 1983-02-01 000320 #>>000320...
Python
1
P_FIFO2_RXFDC_L_SPEC>, #[doc = "0x1bc - "] pub sep_fifo2_rxfdc_h: crate::Reg<sep_fifo2_rxfdc_h::SEP_FIFO2_RXFDC_H_SPEC>, #[doc = "0x1c0 - "] pub sep_fifo0_txfd: crate::Reg<sep_fifo0_txfd::SEP_FIFO0_TXFD_SPEC>, _reserved57: [u8; 0x04], #[doc = "0x1c8 - "] pub sep_fifo3_rxfd: crate::Reg<sep_fi...
Rust
0
ose_list = self._get_coffee_to_choose(day) # from one_dragon.utils import debug_utils # screen = debug_utils.get_debug_image('424905412-5c9df2d3-186d-4be5-a610-865553fd6adb') area = self.ctx.screen_loader.get_area('咖啡店', '咖啡列表') part = cv2_utils.crop_image_only(self.last_screenshot, are...
Python
1
import xml.etree.ElementTree as ET import csv import datetime from collections import defaultdict def find_atco_with_no_naptan_and_grouped_by_type(file_path): """ Find ATCO codes that have no associated NaPTAN codes in the NaPTAN XML file, and group them by stop type. Args: file_path (str): Path t...
Python
1
(self.X_train) for ivec in range(self.nvec): k1 = Constant(gprinfo[ivec]['k1__constant_value']) k2 = RBF(gprinfo[ivec]['k2__length_scale']) kivec = k1 * k2 alpha = 1e-10 ynorm = True self.__GPR[ivec] = GaussianProcessRegressor(self.X_...
Python
1
import supybot.conf as conf import supybot.registry as registry from supybot import ircutils import re def configure(advanced): # This will be called by supybot to configure this module. advanced is # a bool that specifies whether the user identified himself as an advanced # user or not. You should effec...
Python
1
eref(), A_FEW); assert_eq!(Nbstr::from_str(A_FEW).deref(), A_FEW); assert_eq!(Nbstr::from(A_FEW.to_string()).deref(), A_FEW); } #[test] fn into() { let l1: &str = &Box::<str>::from(Nbstr::from("str".to_string().into_boxed_str())); assert_eq!(l1, "str"); let l2: &str = &String::from(Nbstr::from("str"...
Rust
0
ContentFormat::YAML => serde_yaml::to_string(&json)?, ContentFormat::TEXT => String::from(content), } } ContentFormat::YAML => { let yaml: serde_yaml::Value = serde_yaml::from_str(content) .map_err(|e| Error::new(e).context("Unable to par...
Rust
0
""" Advanced Uncertainty Quantification Module Enhanced uncertainty analysis with epistemic/aleatoric decomposition, uncertainty-guided active learning, and automatic DFT validation workflow. Author: lunazhang Date: 2023 """ import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from t...
Python
1
for each layer/level combination. for level in range.levels.clone() { for layer in range.layers.clone() { barrier.u.Subresource = target.calc_subresource(level as _, layer as _, 0); raw_barriers.push(bar...
Rust
0
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
Python
1
fn new(device: &wgpu::Device, mesh: &Mesh) -> Self { let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("Index Buffer"), contents: bytemuck::cast_slice(mesh.indices.as_slice()), usage: wgpu::BufferUsages::INDEX, }); l...
Rust
0
: remove it with native event support PollEvent::Waker => todo!(), } }); } } #[cfg(test)] mod tests { use super::*; use std::time::{Duration}; lazy_static::lazy_static! { static ref TIMEOUT: Duration = Duration::from_millis(1000); } #[test] fn c...
Rust
0
order_id: order_id.into(), } } } #[derive(Deserialize, Serialize, Debug, Clone, Shrinkwrap)] #[shrinkwrap(mutable)] pub struct GetOrderStateResponse(pub Order); impl Request for GetOrderStateRequest { const METHOD: &'static str = "private/get_order_state"; type Response = GetOrderStateResponse; } ...
Rust
0
from rest_framework import generics, permissions, status from rest_framework.response import Response from rest_framework.authtoken.models import Token from rest_framework.permissions import AllowAny from rest_framework.views import APIView from django.contrib.auth.models import User from django.contrib.auth import aut...
Python
1
""" Simulation of a logit model =========================== Example of simulation with a logit model :author: Michel Bierlaire, EPFL :date: Sun Apr 9 17:13:23 2023 """ import biogeme.biogeme as bio from biogeme import models from biogeme.expressions import Beta, Derive # %% # See the data processing script: :re...
Python
1
let socket = TcpSocket::bind("127.0.0.1:2000").unwrap(); let addr = socket.local_addr().unwrap(); drop(socket); let timeout = Duration::from_secs(1); let e = TcpSocket::connect_timeout(&addr, timeout).unwrap_err(); assert!(e.kind() == io::ErrorKind::ConnectionRefused || ...
Rust
0
group_tree: GroupTree, } /// The message that is send by the list view. #[derive(Clone, Debug)] pub enum ListMessage { /// Change the search to the new value. SearchInput(String), /// Go pack to the parent group. Back, /// Edit the currently selected group. EditGroup, /// Message that is se...
Rust
0
ility; // use crate::spaceship::equipment::Beam; // pub struct SEE {} // impl SEE { // /// 葉で駒を取ったら、取り返されるのも考慮しないとな☆(^~^) // /// // /// 価値の低い駒から順に使って、取りに行けだぜ☆(^~^) // pub fn go(_game: &Game, _adr: &Square) -> Value { // // // この駒☆(^~^) // // let mut current_target_piece = game.position....
Rust
0
ored_room}B{digit_1}0{digit_2}") return f"room_{digit_1}_{digit_2}" elif colored_room == "训练室": logger.debug("训练室B305") return "train" elif colored_room == "加工站": logger.debug("加工站B105") return "factory" white_room = ["central", "dormit...
Python
1
u64, /// Trader euro balance pub balance_eur: u64, /// ? pub display: bool, /// Trader discount pub discount: i64, /// Trader discount expiry pub discount_end: i64, /// ? pub buyer_up: bool, /// Trader currency pub currency: Currency, /// Resupply time pub supply...
Rust
0
me = yield rep = outcome.get_result() if rep.when == "call": full_name, test_file, test_name = get_current_test() #print("adding to all_test_result list:" + test_file) test_name_msg = f"{test_name}_msg" for key, value in all_test_results.items(): #filename = key + "...
Python
1
# Generated by Django 2.1.1 on 2020-08-25 03:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user', '0006_profile_skipped_data_at'), ] operations = [ migrations.AlterField( model_name='institution', name='type...
Python
1
; } #[tokio::test] async fn test_echo() { let (tx0, rx0) = channel!(Message, 1024); let (tx1, mut rx1) = channel!(Message, 1024); let channels = pipe_channels!(rx0, [tx1]); let config = config!(EchoConfig); let pipe = mapper!("echo"); let f1 = populate_messag...
Rust
0
ox cleanup and verification to every test. As the mox unit testing class is being constructed (MoxTestBase or a subclass), this metaclass will modify all test functions to call the CleanUpMox method of the test class after they finish. This means that unstubbing and verifying will happen for every test with no...
Python
1
, pub(crate) unmanaged: Stack, pub(crate) tag: String, pub screen: usize, pub visible: bool, pub(crate) layout: Box<dyn Layout>, } impl Default for Workspace { fn default() -> Self { Self { managed: Stack::default(), unmanaged: Stack::default(), tag: ...
Rust
0
import copy import matplotlib.pyplot as plt import numpy as np from .core import get_features_from_model from spacetorch.datasets import floc from spacetorch.maps.it_map import ITMap from spacetorch.models.positions import LayerPositions from spacetorch.paths import CACHE_DIR from spacetorch.types import RN18Layer fr...
Python
1
from django.contrib import admin from .models import Job @admin.register(Job) class JobAdmin(admin.ModelAdmin): list_display = ('title', 'company', 'location', 'job_type', 'experience_level', 'posted_by', 'is_active', 'created_at') list_filter = ('is_active', 'job_type', 'experience_level', 'created_at') s...
Python
1
.params.iter().map(|p| p.render()).collect::<String>(); if !params.is_empty() { format!("\\{}{{{}}}", self.m.clone(), params) } else { format!("\\{}", self.m.clone()) } } } pub struct Text<S: AsRef<str>>(S); impl<S: AsRef<str>> Element for Text<S> { fn render(&s...
Rust
0
[derive(SystemParam)] pub struct StageContext<'a> { pub surfaces: Query<'a, (Entity, &'static Surface)>, pub respawn_points: Query<'a, &'static mut RespawnPoint>, } impl<'a> StageContext<'a> { pub fn surface(&self, entity: Entity) -> &Surface { self.surfaces.get(entity).expect("Missing surface.").1...
Rust
0
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from config import DB_URL from database.models import Base engine = create_engine(DB_URL) SessionLocal = sessionmaker(bind=engine) def init_db(): Base.metadata.create_all(bind=engine)
Python
1
f.read()).strip() self.assertMultiLineEqual(printed, self.true_nodenames_nopropflags, msg = "Couldn't read and parse tree from string properly when node names and non-propagating flags provided.") def test_newick_read_tree_labeledroot(self): ''' Test parsing a tree w/ a labele...
Python
1
import secrets import random import string from django.contrib.auth.hashers import make_password from django.core.mail import send_mail from django.shortcuts import get_object_or_404, redirect, render from django.urls import reverse_lazy, reverse from django.views.generic import CreateView, UpdateView from users.for...
Python
1
class Solution: def minPathSum(self, grid: List[List[int]]) -> int: # Dijkstra's Algorithm version m, n = len(grid), len(grid[0]) heap = [(grid[0][0], 0, 0)] min_sum = [[float("inf")] * n for _ in range(m)] # print(min_sum) while heap: cur_sum, cur_r, cur...
Python
1
""" Semantic Chat Interface with Vector Search and Retrieval This module provides a chat interface enhanced with semantic search, vector databases, and intelligent information retrieval. Features: - Semantic search capabilities - Vector database integration - Context-aware retrieval - Knowledge base q...
Python
1
format!( "{} {}", "EXAMPLES:".yellow(), pairs .iter() .map(|(a, b)| format!("{}\n {}", format!("# {}", a).dimmed(), b)) .collect::<Vec<String>>() .join("\n\n "), ) } pub fn split_pair(pair: &str, sep: char) -> Option<(&str, &str...
Rust
0
umper::copy_from_process( config.blamed_thread, app_memory.ptr as *mut libc::c_void, app_memory.length, )?; let section = MemoryArrayWriter::write_bytes(buffer, &data_copy); let desc = MDMemoryDescriptor { start_of_memory_range: app_memory.ptr as ...
Rust
0
command"), |_, input| { let expression = &input[1..]; vec![ResultElement { text: expression.to_owned(), action: Box::new(NoAction {}), }] }, ); let commands = vec![calculation_command, find_co...
Rust
0
from parametros import PROBABILIDAD_EVENTO, PUBLICO_EXITO, PUBLICO_INICIAL, \ PUBLICO_TERREMOTO, AFINIDAD_OLA_CALOR, \ AFINIDAD_LLUVIA, PUBLICO_OLA_CALOR from random import random, choice class DCCPalooza: def __init__(self): self.artista_actual = None ...
Python
1
text = input("Type your message") my_text = text.split() cypher_text = [] cypher_word = [] for word in my_text: for letter in word: cypher_word += chr(ord(letter) + 3) cypher_text.append(''.join(cypher_word)) cypher_word = [] enchr = " ".join(cypher_text) print(f"Encrypted text is {enchr}")
Python
1
ain_layout = QtWidgets.QVBoxLayout() main_layout.addWidget(combo) main_layout.addWidget(main_splitter) # And finally our main widget to show main_widget = QtWidgets.QWidget() main_widget.setLayout(main_layout) main_widget.setWindowTitle( f"Synapse Data Recording - {data_file}" ) #...
Python
1
2), Some((2, 2))); /// assert_eq!(queue.pop(), Some((4,4))); /// assert_eq!(queue.pop(), Some((3,3))); /// // There is no 2 /// assert_eq!(queue.pop(), Some((1,1))); /// assert_eq!(queue.pop(), Some((0,0))); /// assert_eq!(queue.remove_entry(&10), None); /// ``` /// /// ### Time comp...
Rust
0
## ## MOD HAvsFunc (e1fcce2b4645ed4acde9192606d00bcac1b5c9e5) ## 变更源帧率 ################################################## def FPS_CHANGE( input : vs.VideoNode, fps_in : float = 24.0, fps_out : float = 60.0, vs_t : int = vs_thd_dft, ) -> vs.VideoNode : func_name = "FPS_CHANGE" if not isinstance(input, vs.VideoNo...
Python
1
remove_site(&self, station_num: StationNumber) -> Result<(), BufkitDataErr> { let station_num: u32 = station_num.into(); self.db_conn.execute( "DELETE FROM download WHERE station_num = ?1", &[&station_num], )?; Ok(()) } pub fn is_auto_downloaded(&self,...
Rust
0
[self.1..new].copy_from_slice(buf); self.1 = new; Ok(l) } #[inline] fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl<'a> fmt::Write for StackWriter<'a> { #[inline] fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> { if !s.is_empty() { ...
Rust
0
l_bytes > 0: # Always show current percentage self.progress_bar.setFormat(f"{percent}%") def _on_log_updated(self, message): """Handle log updates from worker thread""" self.log_text.append(message) def _on_installation_finished(self, result): """Handle ...
Python
1
captures_in_function() { // Functions may be captured as well. let program = r#" add = |x, y| x + y; foo = |a| add(a, 5); add = 0; foo(-3) "#; let return_value = evaluate(&mut Environment::new(), program); assert_eq!(return_value, Value::Prim(2.0)); } #[test] fn capt...
Rust
0
, account_path: audit_path_after, balance_value: Some(balance_after), balance_subtree_path: audit_balance_path_after, }, }, args: OperationArguments { atp_address: Some(Fr::zero()), amount...
Rust
0
key = validate_block_key(block)?; let address = validate_account_address(address)?; match client.get_account(address, key) { Ok(Some(account)) => Ok(f(account)), Ok(None) => Ok(Value::Null), Err(error) => { error!("{}", error); Err(Error::internal_error()) ...
Rust
0
import time from tools import constants, paths, utils from launchers.sandbox import Sandbox BAKE_ARGS = ['--minimal-timestamp'] def scenario_basic_call(): """ a private tezos network, initialized with network parameters and some accounts. """ with Sandbox(paths.TEZOS_HOME, constants.IDENTITIES) as san...
Python
1
pub(crate) vertical: TextOverflow, } /// In the case that we do overflow the rectangle (in any direction), /// we need to now re-calculate the positions for the words (because of the reduced available /// space that is now taken up by the scrollbars). #[derive(Debug, Copy, Clone)] pub(crate) struct TextOverflowPass2 {...
Rust
0
an target " "value, neighbors truncated; and if shorter than target " "value, neighbors are padded with -1's.") # Enforce argument naming convention. for action in group._group_actions: prefix = action.dest.split("_")[0] assert prefix == "retro", \ ...
Python
1
from markitdowngui.utils.translations import get_translation, get_available_languages, TRANSLATIONS def test_get_translation_english(): """Test retrieving a standard English translation.""" assert get_translation('en', 'app_title') == "MarkItDown GUI Wrapper" def test_get_translation_chinese(): """Test re...
Python
1
onfig["json_path"]) processed_ids = set() if os.path.exists(os.path.join(config["output_dir"], config["result_files"]["full"])): with open(os.path.join(config["output_dir"], config["result_files"]["full"]), 'r', encoding='utf-8') as f: for line in f: data = json.loads(li...
Python
1
PartialEq, ::prost::Message)] pub struct GetOperatorResponse { #[prost(message, optional, tag = "1")] pub header: ::std::option::Option<ResponseHeader>, #[prost(uint64, tag = "2")] pub region_id: u64, #[prost(bytes, tag = "3")] pub desc: std::vec::Vec<u8>, #[prost(enumeration = "OperatorStat...
Rust
0
* tmp1 * tmp1; let res0 = minor0 * det; let res1 = minor1 * det; let res2 = minor2 * det; let res3 = minor3 * det; let mut m = m; m[0] = res0.to_array(); m[1] = res1.to_array(); m[2] = res2.to_array(); m[3] = res3.to_array(); Some(Matrix4x4(m)) } #[cfg(test)] #[rustfmt::ski...
Rust
0