text
string
label_name
string
labels
int64
of the indices. Here, we will swap the levels column-wise, but levels can be swapped row-wise in a similar manner. Note that column-wise is the default behaviour. By not supplying any arguments for i and j, we swap the last and second to last indices. >>> df.swaplevel() ...
Python
1
import os import shutil def create_directory(folder:str,filename:str): dir = f"app/media/{folder}" if not os.path.exists(dir): os.makedirs(dir) os.path.join(dir, filename) def select_install(input): create_directory("MyBash","bash.sh") m...
Python
1
IdsByPatron::<T>::mutate(who, |ids| remove_from_vec(ids, subscription_id)); SubscriptionIdsBySpace::mutate(space_id, |ids| remove_from_vec(ids, subscription_id)); Ok(()) } pub(crate) fn filter_subscriptions_by_plan( subscription_id: SubscriptionId, plan_id: SubscriptionPlanId ...
Rust
0
Error), #[error("Could not determine horizontal position with least fuel usage ({0})")] DetermineHorizontalPositionWithLeastFuelUsage( #[from] DetermineHorizontalPositionWithLeastFuelUsageError, ), } pub fn determine_horizontal_position_with_least_fuel_usage( horizontal_crab_positions: &str, ...
Rust
0
# 根据市场选择接口 if ts_code.endswith('.SH') or ts_code.endswith('.SZ'): # A股实时行情 df = ak.stock_zh_a_spot_em() match = df[df['代码'] == stock_code] if match.empty: logger.warning(f"未找到股票代码: {s...
Python
1
, LeafletPage, Media, LeadArtist, Artist, Conductor, Band, Composer, Lyricist, RecordingLocation, DuringRecording, DuringPerformance, MovieScreenCapture, BrightColouredFish, Illustration, BandLogotype...
Rust
0
} _ => panic!("unexpected payload"), } } // Send some events down the wire. Waiting until the first notifications are in // to ensure the event handler has been initialized. let log_event = Event::new_empty_log(); let metric_event = Event::from(Metric::new( id.to_string(...
Rust
0
import sys,os from platform import system import time VER = 2 try: if sys.version_info >= (3,0): VER = 3 from urllib.request import urlopen from urllib.error import URLError else: input = raw_input from urllib2 import urlopen from urllib2 import URLError except:...
Python
1
import cupy as cp import cupyx.scipy.sparse as cusparse import cupyx.scipy.sparse.linalg as cusparse_linalg def eigsh_gpu(H, ROI, k=6, which='SA', maxiter=None, tol=1e-20): """ 使用 GPU 计算稀疏矩阵的前 k 个特征值和特征向量,并归一化特征向量(向量化实现)。 参数: H: scipy.sparse 矩阵(稀疏矩阵,CSR 格式)。 ROI: 计算积分时的区域坐标点数组。 k:...
Python
1
#!/usr/bin/env python # Copyright (C) 2015 Job Snijders <job@instituut.net> # # This file is part of IRR Explorer # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the abo...
Python
1
import numpy as np import protos.localization_protos_pb2 as loc_protos def read_feature(feature_filename): f = open(feature_filename, "rb") feature_proto = loc_protos.Feature() feature_proto.ParseFromString(f.read()) f.close() return np.array(feature_proto.values) def write_feature(filename, pr...
Python
1
tr(e)}), 500 # =========================== # (১১) টেক্সট ➡️ উত্তর # =========================== @app.route('/text-to-answer', methods=['POST']) def text_to_answer(): data = request.json question = data.get("question", "") language = data.get("language", "bangla") if not question: return js...
Python
1
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from project.sendmail import generate_credentials db = SQLAlchemy() # setup flask-login def setup_login_manager(app): login_manager = LoginManager() login_manager.login_view = 'auth.login' login_manager.in...
Python
1
), ) ExecExpressionWithValue( 0x0009, 0x05, ( (Expr.GetChrWork, 0x9, 0x4), (Expr.PushLong, 0xB4), Expr.Div, Expr.Nop, Expr.Return, ), ) If( ( (Expr.GetChrWork, 0x9, 0x4), (Expr....
Python
1
_binary() .with_args(&[file.path().to_str().unwrap()]) .succeeds() .unwrap(); } #[test] fn test_files_multiple_invalid() { let mut file1: NamedTempFile = NamedTempFile::new().unwrap(); write!(file1, "{{ \"foo\": \"bar\"").unwrap(); let file1_path = file1.path().to_str().unwrap(); ...
Rust
0
SIGHASH_ALL = 1 SIGHASH_NONE = 2 SIGHASH_SINGLE = 3 SIGHASH_FORKID = 0x40 SIGHASH_ANYONECANPAY = 0x80 VERIFY_NONE = 0 # Evaluate P2SH subscripts (softfork safe, BIP16). VERIFY_P2SH = (1 << 0) # Passing a non-strict-DER signature or one with undefined hashtype to a checksig # operation causes script failure. Evaluati...
Python
1
x80\xb6;\xe2\ \xbb\xe9e\xd4\xa2\xd7\xb6\xabEk\xa6\xc5\xf2\xae\xd5\xfb\ \xdfJ\xc2\xf1o\xc7\xdb\x0b\x0d{\xfb/M\xb5\xb8\xbf\ \xbc\xe5\x9b\xc8\x8c\xb2\xafn[\xa0\xe6\xa7\xd2\xf5K\x8d\ f\xe9[R\xf3l\xd7\xf8m\xff\x00\x8a\xa3\xdd~\x82\ \x95y\xb8\xad,\x8c\xdf\x8c\x96\xba\xf6\xb1ugk\xe1\ \x9f\xf9x}\xb7WR\xc8v@=\x94\x1eN*\xc4\ \xb...
Python
1
w(); let pg_pool = controller::connect(&config).await.unwrap(); core::logging::setup(&config)?; let private_key = rand::thread_rng().gen::<[u8; 32]>(); HttpServer::new(move || { App::new() .data(pg_pool.clone()) .wrap(actix_web::middleware::Compress::new(ContentEncodin...
Rust
0
#!/usr/bin/python # -*- encoding: utf-8 -*- import torch import numpy as np from PIL import Image def pdist_torch(emb1, emb2): ''' compute the eucilidean distance matrix between embeddings1 and embeddings2 using gpu ''' m, n = emb1.shape[0], emb2.shape[0] emb1_pow = torch.pow(emb1, 2).sum(dim...
Python
1
ntSpec = serde_json::from_slice(&font_spec_bytes).expect("malformed font spec file"); let font_path = font_spec_path.parent().unwrap().join(font_spec.font_path); println!("Loading font: {}", font_path.display()); let font_face = freetype .new_face(font_path, 0) .expect("failed to cre...
Rust
0
>() { Ok(v) => buses.push(v), Err(_) => {}, } } let next_time = get_next_time(time, &buses); RetType::U128(((next_time.0-time) * next_time.1) as u128) } /// Problem #13, part 2 pub fn problem_132(input: Vec<String>) -> RetType { // Build our m and p let buses_str:...
Rust
0
gent test: import store_agent from typing import Annotated from typing_extensions import TypedDict from langgraph.graph import StateGraph, START, END from langgraph.graph.message import add_messages from langgraph.prebuilt import ToolNode, tools_condition from langchain_core.messages import HumanMessage, SystemMessag...
Python
1
import lista_tarefas as lt def remove_tarefa(): """Remove a tarefa da lista de tarefas""" print('\033[31m============================================\033[31m') print(lt.todas_tarefas) tarefa = input('\033[33m Digite a tarefa que deseja remover: \033[33m') if tarefa != '': lt.todas_tare...
Python
1
from dataclasses import dataclass, field from typing import List, Optional, Dict, Any import uuid import re @dataclass class ContactLog: id: str = field(default_factory=lambda: str(uuid.uuid4())) operator: str = "" start_time: int = 0 # timestamp UTC end_time: int = 0 # timestamp UTC contacts: L...
Python
1
ype == 'confidence': snr_lsb = norm_param[3][0] snr_msb = norm_param[3][1] snr_range = snr_msb - snr_lsb elif last_channel_type == 'velocity': velocity_lsb = norm_param[3][0] velocity_msb = norm_param[3][1] velocity_range = velocity_msb - velocity_lsb else: ...
Python
1
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # File : __init__.py # Author : Jiayuan Mao # Email : maojiayuan@gmail.com # Date : 03/04/2018 # # This file is part of Jacinle. # Distributed under terms of the MIT license. from sklearn.naive_bayes import GaussianNB, MultinomialNB, BernoulliNB from .hybrid_nb impo...
Python
1
config = TradingConfig(rolling_options=rolling_options) # 验证阈值为0的配装选项保持不变(表示总是启用快速售卖) assert config.rolling_options[0]["fast_sell_threshold"] == 0 assert config.rolling_options[1]["fast_sell_threshold"] == 0 def test_negative_threshold_reset_to_zero(self): """测试负数阈值重置为0的逻辑""" ...
Python
1
Name { } } impl Component for ComponentName { fn render(ctx: &mut GraphicsContext) { } } // And with Peaches macros component!(ComponentName(some_prop: String, some_optional_prop: Option<String>) => { let (name, set_name) = use_state!(String, "some name"); let (age, set_age) = use_state!(f32, 2...
Rust
0
from keystore_module import KDFModule, ChecksumModule, CipherModule from keystore import CryptoKeystore from secrets import randbits def scrypt_test(): scrypt_params = { 'salt': randbits(256).to_bytes(32, 'big'), 'key_len': 32, 'N': 2**18, 'r': 8, 'p': 1, } aes_par...
Python
1
eam: &mut crate::TokenStream) { self.impl_.into_tokens(context, stream); self.path.into_tokens(context, stream); self.open.into_tokens(context, stream); self.functions.into_tokens(context, stream); self.close.into_tokens(context, stream); } } <gh_stars>0 mod base; mod blockch...
Rust
0
xb9\ \xf3\xc7VuX\xdc\xe8{\xecCQ\xad\xabP\xd7\xaf\ \xae\x1f\xddk])<xz&\xce\x8b5\x17\xb9\xf1\ \xe3D\xd5<\xbd\xf1\x1f\xf8M\xaf\x19y2\xe9\xf2\x95\ F\x10\xe4K\x8c\x93\x0d\xe1\xf3 {\xcf>\xa3\xdaK\ SM\x91\xe2\xf2#B\x8bqI\xc7oj\xb2\x8b\xc4\ \xa3iU\xa6\xbc\xf8Y\xc9\xbcR\x9ar\x9c\x9c\xa4\xfa\ \xb6\xf2u~\xe3y\xdb\x9a\xb7\xf9\xa5_...
Python
1
arg),+>($($arg),*) }; } // BUILDING BLOCK, could be moved inside dispatch! with @prefix trick. // disp_expand!(func, (rt_type1, [u32, iu64]), [(rt_type2, [i32, i64]), (rt_type3, [f32, f64])], (), (arg1, arg2)) // disp_expand!(func, (rt_type2, [i32, i64]), [(rt_type3, [i32, i64])], (u32), (arg1, arg2)) // disp_expa...
Rust
0
} // Collect all vtables let vtbl_regex = vtbl_regex()?; let vtbls = vtbl_regex .captures_iter(header) .filter(|c| c["trait"] == c["trait2"]) .map(|c| Vtable::new(c["trait"].to_string(), &c["functions"], "CGlueC")) .collect::<Result<Vec<_>>>()?; let mut vtbls_map = Ha...
Rust
0
TlsBackend { #[cfg(feature = "default-tls")] { TlsBackend::Default } #[cfg(all(feature = "rustls-tls", not(feature = "default-tls")))] { TlsBackend::Rustls } } } #[cfg(feature = "rustls-tls")] pub(crate) struct NoVerifier; #[cfg(feature = "rustls-tls")] impl ServerCertVerifier fo...
Rust
0
""" Write a function to convert tuple string to integer tuple. assert tuple_str_int("(7, 8, 9)") == (7, 8, 9) """ def tuple_str_int(s): return tuple(map(int, s[1:-1].split(', '))) def test_tuple_str_int(): assert tuple_str_int("(7, 8, 9)") == (7, 8, 9) /python/leetcode/easy/136_single_number.py """ Given a no...
Python
1
recent_vouchers_epoch_root_hash: String, most_recent_notices_epoch_root_hash: String, pending_input_count: String, taint_status_json: serde_json::Value, ) -> Result<()> { let timestamp = SystemTime::now(); sql_query("INSERT INTO \"EpochStatuses\" VALUES ($1, $2, $3, $4, $5, ...
Rust
0
ing}@update.com')).union(newInsertCustomersDf) else: upsertDf = df.filter(f'restaurantid in {sListids}').withColumn('Email', lit(f'updated_{dateString}@update.com')).union(newInsertRestaurantsDf) return upsertDf # COMMAND ---------- # create the timestamp for this run dateString = datetime.datetime.no...
Python
1
# state.py from config import ENDPOINTS # Store last query time for each source (global, for all modules) last_run: dict[str, float] = {source: 0.0 for source in ENDPOINTS}
Python
1
while True: try: peso = float (input("Ingrese su peso:")) if peso <= 0: print("El peso debe ser mayor a 0") else: break except ValueError: print("El peso debe ser un numero") while True: try: altura = float(input("Ingrese s...
Python
1
pub input: Input<f32>, /// Clamp as user boundary conditions of [`Frame`]. pub clamp: Clamp<f32>, /// Frame wrt camera eye and target. pub frame: Frame<f32>, /// Reset frame wrt camera eye and target. pub reset: Frame<f32>, /// Scene wrt enclosing viewing frustum. pub scene: Scene<f32>, image: Image<f32>, f...
Rust
0
import json from pyrogram.types import CallbackQuery from pyrobot import WARN_DATA_ID from pyrobot.pyrobot import PyroBot async def remove_warn(client: PyroBot, c_q: CallbackQuery, user_id: str, warner: int): chat_id = str(c_q.message.chat.id) if chat_id not in client.warndatastore: client.warndata...
Python
1
message_create: event_counter.with_label_values(&["MessageCreate"]), message_delete: event_counter.with_label_values(&["MessageDelete"]), message_delete_bulk: event_counter.with_label_values(&["MessageDeleteBulk"]), message_update: event_counter.with_label_values(&["Me...
Rust
0
200); let _id: IdResponse<WorkflowId> = test::read_body_json(res).await; } #[tokio::test] async fn register_invalid_method() { check_allowed_http_methods(register_test_helper, &[Method::POST]).await; } #[tokio::test] async fn register_missing_header() { let ctx = InMe...
Rust
0
import sys import matplotlib.pyplot as plt from collections import defaultdict import utils as utils def genScatterPlot(houses:list, data_course1:list, data_course2:list, course1:str, course2:str): data_houses1 = defaultdict(list) data_houses2 = defaultdict(list) min_length = min(len(houses), len(data_course1), le...
Python
1
# Copyright (c) Mathias Kaerlev 2012. # This file is part of Anaconda. # Anaconda 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 version 3 of the License, or # (at your option) any later version. # ...
Python
1
elsen har kun en visuell effekt.''', 'url': 'https://www.finn.no/recommerce/forsale/item/373940998' }, '248292079': { 'heading': '''PowerColor Red Dragon Radeon™ RX 570 4GB - Nytt kort''', 'description': '''Nytt skjermkort / grafikkort selges.PowerColor Red Dragon Radeon™ RX 570 4GB.Har ...
Python
1
import json from transformers import AutoTokenizer import numpy as np import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] def get_token_distribution(file_path, tokenizer): input_num_tokens, outout_num_tokens = [], [] with open(file_path, "r", encoding="utf-8") as r: for line in...
Python
1
import numpy as np # class buat embedding token jadi vektor class TokenEmbedding: def __init__(self, vocab_size, embed_dim, seed=42): np.random.seed(seed) self.vocab_size = vocab_size self.embed_dim = embed_dim # bikin weight matrix random, pake distribusi normal self.weight...
Python
1
, # so a file named "default.css" will overwrite the builtin "default.css". #html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and da...
Python
1
"""Global configurations""" import os class GlobalConfig: """ Store some global constants. See also python/sglang/srt/managers/schedule_batch.py::global_server_args_dict, which stores many global runtime arguments as well. """ def __init__(self): # Verbosity level # 0: do no...
Python
1
if prev_file_path else "", ) print( TAG, "Total number of docs in corpus:", len(tf_idf), "( " + paint("++" + str(len(tf_idf) - prev_corpus_length), "g") + " )" if prev_file_path else "", ) # dump if a dir-path is given if dump_path: ...
Python
1
#!/usr/bin/env python3 # # import modules # import configparser import sys import os import time from pprint import pprint from plexapi.server import PlexServer # # Sanity check CLI arguments and assign them to readable variable names # if len(sys.argv) != 2: print(f"Usage: {os.path.basename(__file__)} <pattern mat...
Python
1
def fibonacci_iterative(n): """ Returns the n-th Fibonacci number using iteration. """ if n < 0: raise ValueError("Input should be a non-negative integer.") a, b = 0, 1 for _ in range(n): a, b = b, a + b return a def fibonacci_recursive(n, memo={}): """ Returns the n...
Python
1
::parse_str("afbd338e-881b-4557-8764-52e259885ca3").unwrap(), hostname: "10.0.3.207".to_string(), status: State::PeerInCluster, }, Peer { uuid: Uuid::parse_str("fa3b031a-c4ef-43c5-892d-4b909bc5cd5d").unwrap(), hostname: "10.0.3.208".to_string(), ...
Rust
0
name: "chinese-traditional" }; /// default italian dictionary as provided by the /// [BIP39 standard](https://github.com/bitcoin/bips/blob/master/bip-0039/bip-0039-wordlists.md#italian) /// pub const ITALIAN : DefaultDictionary = DefaultDictionary { words: include!("bip39_italian.t...
Rust
0
''' Utilizar el fichero csv: company_sales_data.csv Lee los datos de ventas de los productos crema facial y lavado de cara y muéstralos mediante el gráfico de barras. El gráfico de barras debe mostrar el número de unidades vendidas por mes para cada producto. Añade una barra distinta para cada producto en el mismo gráf...
Python
1
Data::Struct(ref data) => match data.fields { syn::Fields::Named(ref fields) => { let recurse = fields.named.iter().map(|f| { let name = &f.ident; quote_spanned! {f.span() => #name: self.#name.swap_remove(index), ...
Rust
0
28::from(self.sbox.apply((output >> (4 * j)) & 0xf)) << (4 * j); } // Add round key output = tmp ^ round_keys[19]; for i in 0..19 { // Linear layer output = self.linear_layer_inv(output); // Apply S-box let mut tmp = 0; for ...
Rust
0
ilar_segments.append({ 'text1_segment': segment1, 'text2_segment': segment2, 'length': length, 'position1': i, 'position2': j }) # Trier par longueur décroissante ...
Python
1
import os from docx import Document # Rutas RUTA_ENTRADA = './data/libros/recetas/' RUTA_SALIDA = './data/recetas_raw/' def extraer_texto_docx(nombre_archivo): try: ruta_docx = os.path.join(RUTA_ENTRADA, nombre_archivo) doc = Document(ruta_docx) texto = "\n".join([p.text for p in doc.parag...
Python
1
was handled!"); } Frame::Close { payload } => { if let Some(payload) = payload { println!("Gateway closed with code {}: {}", payload.0, payload.1); }; return Ok(()); } _ =...
Rust
0
n_rate_rpc(DOT), Some(Rate::from_inner(466_666_666_666_666_667)) ); assert_eq!(get_pool_utilization_rate_rpc(ETH), Some(Rate::zero())); System::set_block_number(100); // Utilization rate grows with time as interest is accrued assert_eq!( get_pool_utilization_rate_rpc(DOT), Some(Rate::from_in...
Rust
0
def running_key_cipher(text, key, shift): """ Encrypts or decrypts the text using the running key cipher. """ result = "" key_index = 0 for char in text: if char.isalpha(): # Calculate the shift for the character shift_value = ord(key[key_index % len(key)].upper()...
Python
1
onse, ContractError> { let lp_token = addr_validate_to_lower(deps.api, lp_token.as_str())?; let beneficiary = addr_validate_to_lower(deps.api, beneficiary.as_str())?; let mut response = Response::new().add_attribute("Action", "Deposit"); let mut user = USER_INFO .load(deps.storage, (&lp_token,...
Rust
0
placeholder='', ) seed = gr.Slider( label='Seed', minimum=1, maximum=100000, value=0, step=1 ) run_button = gr.Button('Generate') with gr.Column(): result = gr.Gall...
Python
1
>]) { let left = left.iter().collect::<HashSet<_>>(); let right = right.iter().collect::<HashSet<_>>(); assert_eq!(left, right); } #[test] fn returns_expected() { let truth = Solution::permute(vec![1,2,3]); let expected = vec![ vec![1,2,3], ve...
Rust
0
_assign(entry, mem_ty.pat as u64, 7, 0, 1); entry = mask_assign(entry, global as u64, 8, 0, 1); entry = mask_assign(entry, xd as u64, 63, 0, 1); Self(entry) } } /// The third level page table #[repr(align(4096))] #[derive(Clone, Copy)] pub struct PTable { pub entries: [PTEntry; PTE_NUM]...
Rust
0
import numpy as np import time import datetime def check_value(inds, val): # Check to see if an array is a single element equaling a particular value # Good for pre-processing inputs in a function if(np.array(inds).size == 1): if(inds == val): return True return False def flatten...
Python
1
urce]: pass class topics(ResourceCollection): @classmethod def all(cls) -> List['Topic']: pass @classmethod def filter(cls, NextToken: str = None) -> List['Topic']: pass @classmethod def iterator(cls) -> ResourceCollection: pass @class...
Python
1
, y1)) as f32) / ((max(x1, x0) - min(x0, x1)) as f32); if m < 1.0 { for x in x0..=x1 { let y = ((x - x0) as f32) * m + (y0 as f32); self.draw_pixel(x, y as u16, color); } } else { for y in y0..=y1 { ...
Rust
0
from enum import Enum SPEAK_SERVICE = "/hri/speech/speak" STT_SERVICE_NAME = "/hri/speech/STT" HOTWORD_SERVICE_NAME = "/hri/speech/hotword_service" KEYWORD_TOPIC = "/hri/speech/kws" WAKEWORD_TOPIC = "/hri/speech/oww" USEFUL_AUDIO_TOPIC = "/hri/speech/useful_audio" COMMAND_INTERPRETER_SERVICE = "/hri/nlp/command_interp...
Python
1
i[^x]\n\n[^x]: A footnote here\n // }; // let html: String = markdown_to_html(text, &ComrakOptions::default()); // let html: String = markdown_to_html(text, &COMRAK_OPTIONS); // html let flash = process_flash(flash_opt); let cr_options = ComrakOptions { ext_header_ids: So...
Rust
0
# coding: utf-8 """ codebeamer swagger API No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 3.0 Generated by OpenAPI Generator (https://openapi-generator.tech) Do not edit the class manually. """ # no...
Python
1
from pymtl import * from lizard.util.rtl.interface import UseInterface from lizard.core.rtl.messages import CsrMsg, OpClass, CsrFunc from lizard.core.rtl.frontend.sub_decoder import SubDecoderInterface, GenDecoder, PayloadGeneratorInterface, compose_decoders from lizard.core.rtl.frontend.imm_decoder import ImmType from...
Python
1
import sys from typing import TYPE_CHECKING if sys.version_info < (3, 7) or TYPE_CHECKING: from ._symbol import SymbolValidator from ._size import SizeValidator from ._outliercolor import OutliercolorValidator from ._opacity import OpacityValidator from ._line import LineValidator from ._color ...
Python
1
binding: 1, resource: BindingResource::Sampler(&sampler), }, ], }); Texture { bind_group } } } #[allow(dead_code)] pub struct Renderer { pipeline: RenderPipeline, uniform_buffer: Buffer, uniform_bind_group: BindGroup, te...
Rust
0
ze]; 22usize]; } extern "C" { pub fn mj_activate( filename: *const ::std::os::raw::c_char, ) -> ::std::os::raw::c_int; } extern "C" { pub fn mj_deactivate(); } extern "C" { pub fn mj_certQuestion(question: *mut mjtNum); } extern "C" { pub fn mj_certAnswer(question: *const mjtNum, answer: *mu...
Rust
0
# Copyright Allo authors. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import os import json import pytest import allo import numpy as np from allo.ir.types import int32, float32 import allo.ir.types as T def gramschmidt_np(A, Q, R): M = A.shape[0] N = A.shape[1] for k in range(N): ...
Python
1
# -*- coding: utf-8 -*- """ Created on Tue Dec 24 15:32:43 2019 @author: zixing.mei """ from sklearn.metrics import roc_auc_score as AUC import pandas as pd import numpy as np class Tra_learn3ft (object): """ 一种多模型融合的Tradaboost变体 使用三个模型同时进行样本筛选,目的是减小variance clfA 模型A ...
Python
1
as crate::jmorecfg_h::JCOEF; j += 1 } i += 2 as libc::c_int } dst_blk_x = dst_blk_x.wrapping_add(1) } } else { /* Just copy row ...
Rust
0
------",inline=False) amount = resource_mag(user_id,'DOM') * random.randint(20,60) gain_resource(user_id,'BUS_rs',amount) dockclose.add_field(name="❖ 工作結算",value=f"• 商業<:INC:1375507210448277595>{amount}") dockclose.set_author(name="海港特殊事件-結算") return dockclose...
Python
1
doc = " and K_FOREVER."] #[doc = ""] #[doc = " @retval 0 Message received."] #[doc = " @retval -ENOMSG Returned without waiting."] #[doc = " @retval -EAGAIN Waiting period timed out."] #[doc = " @req K-MBOX-002"] pub fn k_mbox_get( mbox: *mut k_mbox, rx_msg: *mut k...
Rust
0
::new(Mutex::new(HashMap::new())); let seen_warn2 = seen_warn.clone(); let filter = filter::filter_fn(move |meta| { *seen_warn .lock() .unwrap() .entry(*meta.level()) .or_insert(0usize) += 1; meta.level() <= &Level::WARN }); let seen_warn =...
Rust
0
from collections.abc import Callable import jax import optax import tqdm from jaxtyping import Array, Float, PyTree def tune( kernel: Callable, X: Float[Array, "N D"], y: Float[Array, "N"], num_epochs: int, params: PyTree, ) -> PyTree: "Convenience function for training a GP." def object...
Python
1
[LATIN CAPITAL LETTER I WITH OGONEK] '\u{0130}' | // İ [LATIN CAPITAL LETTER I WITH DOT ABOVE] '\u{0196}' | // Ɩ [LATIN CAPITAL LETTER IOTA] '\u{0197}' | // Ɨ [LATIN CAPITAL LETTER I WITH STROKE] '\u{01CF}' | // Ǐ [LATIN CAPITAL LETTER I WITH CARON] '\u{0208}' | // Ȉ [LATIN...
Rust
0
n, x=input().split() n=int(n) x=int(x) num_list = list(map(int, input().split())) for i in num_list: if i<x: print(i)
Python
1
max_norm > 0: grads, norm = optim.clip_grad_norm(grads, self.args.max_norm) if self.accumulated_grads is None: self.accumulated_grads = grads else: self.accumulated_grads = tree_map(mx.add, self.accumulated_grads, grads) if self.state.step % self.args.grad_a...
Python
1
''' 1 anaconda ( Comes with Python ) 2 Python + pycharm 相关的库: xlrd pandas numpy scipy sklearn matplotlib 等 安装方法: 在cmd命令行(win+r) 输入 pip install 库名 例子 : pip install pandas 即可安装pandas库 anaconda 一般应该不用另外安装 基本都自带了 3 超实用函数 : help() 万物皆可help 4 项目流程及知识点 读取数据 处理数据 模型选取 模型建立 模型预测 ...
Python
1
3d.ndim == 2: hist_3d, all_edges = np.histogramdd(data_3d, bins=bin_n, density=True) bin_x, bin_y, bin_z = bin_n, bin_n, bin_n x_edges, y_edges, z_edges = all_edges[:] else: warning(f'Wrong number of dimensions for desnity plot. Got {data_3d.ndim}, need 2 or 3') return None ...
Python
1
(|token| m.token_range_map.get(&token)) .or_else(|| { node.first_node(|node| node.node() == Node::Name) .and_then(|name| { name.first_token(|token| token.token() == Token::Ident) ...
Rust
0
e\n' assert importable(100, alias='memo', source=True) == 'memo = 100\n' assert importable(add, builtin=True, source=False) == 'from %s import add\n' % __name__ assert importable(squared, builtin=True, source=False) == 'from %s import squared\n' % __name__ assert importable(Foo, builtin=True, source=False) == '...
Python
1
arg_list_value) { // Can simplify this to a single MIR opt Some(PartialPrint::Constant(message)) => { b.push(span, OpKind::Panic(message)); Err(Error::Diverged) } // Still contains variables. Simplify the arguments. Some(partial_print) => Ok(BuildOutcome:...
Rust
0
/------------ Integer ------------------------------------------------------- /// A BER encoded integer. /// /// As integers are variable length in BER, this type is just a simple wrapper /// atop the underlying `Bytes` value containing the raw content. A value of /// this type is a signed integer. If a value is defin...
Rust
0
import spacy from spacy.matcher import PhraseMatcher from spacy.tokens import Span import json with open("exercises/de/countries.json", encoding="utf8") as f: COUNTRIES = json.loads(f.read()) with open("exercises/de/country_text.txt", encoding="utf8") as f: TEXT = f.read() nlp = spacy.load("de_core_news_sm") ...
Python
1
$target, file!(), line!(), ); }; } #[doc(hidden)] #[cfg(not(feature = "enabled"))] #[macro_export] macro_rules! scope_time { ($target:literal) => {}; } <gh_stars>10-100 use anyhow::Result; #[tokio::main] async fn main() -> Result<()> { // Please set API_KEY, API_SECRET...
Rust
0
import json from redis.typing import EncodableT from .errors import ( Tile38Error, Tile38IdNotFoundError, Tile38KeyNotFoundError, Tile38NotCaughtUpError, Tile38PathNotFoundError, ) def parse_response( response: bytes | memoryview | str | int | float | list[EncodableT] ...
Python
1
) label = np.array([1]) pred_mask = prompt_process.point_prompt(points=point, pointlabel=label) elif len(prompt) == 4: pred_mask = prompt_process.box_prompt(bbox=prompt.tolist()) if len(pred_mask) == 0: # no mask predicted current_m...
Python
1
t("?????",R.shape[0],R.shape[1]) X_list=[] for u in vec_v: # print(u) table0=table1establish(num=k+6,mode=0) table1=table1establish(num=k+6, mode=1) x_vec=SampleX(k=k,u=u) X_list.append(x_vec) z_vec=cp.hstack(tuple(X_list)) # z_vec=vector(ZZ,z_vec) # print("=...
Python
1
.and_then(|b| client.block_hash(BlockId::Number(b))) } <gh_stars>0 use std::ops::Range; use std::sync::Arc; use crate::kvm::hypervisor::memory::PhysMem; use crate::page_math::huge_page_size; use crate::page_table::{ self, PageTable, PageTableFlags, PageTableIteratorValue, PhysAddr, VirtMem, }; use crate::tracer::...
Rust
0
) = indy::did::create_and_store_my_did(wallet.handle, "{}").wait().unwrap(); indy::pairwise::create_pairwise(wallet.handle, DID_TRUSTEE, &did, None).wait().unwrap(); let ec = indy::pairwise::list_pairwise(INVALID_WALLET_HANDLE).wait().unwrap_err(); assert_eq!(ec.error_code, ErrorCode::WalletInv...
Rust
0