file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
lib.rs
// 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 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 the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. //! This library demonstrates a minimal usage of Rust's C data interface to pass //! arrays from and to Python. use std::error; use std::fmt; use std::sync::Arc; use pyo3::exceptions::PyOSError; use pyo3::wrap_pyfunction; use pyo3::{libc::uintptr_t, prelude::*}; use arrow2::array::{Array, Int64Array}; use arrow2::ffi; use arrow2::{array::PrimitiveArray, compute}; use arrow2::{datatypes::DataType, error::ArrowError}; type ArrayRef = Arc<dyn Array>; /// an error that bridges ArrowError with a Python error #[derive(Debug)] enum PyO3ArrowError { ArrowError(ArrowError), } impl fmt::Display for PyO3ArrowError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { PyO3ArrowError::ArrowError(ref e) => e.fmt(f), } } } impl error::Error for PyO3ArrowError { fn source(&self) -> Option<&(dyn error::Error + 'static)> { match *self { // The cause is the underlying implementation error type. Is implicitly // cast to the trait object `&error::Error`. This works because the // underlying type already implements the `Error` trait. PyO3ArrowError::ArrowError(ref e) => Some(e), } } } impl From<ArrowError> for PyO3ArrowError { fn from(err: ArrowError) -> PyO3ArrowError { PyO3ArrowError::ArrowError(err) } } impl From<PyO3ArrowError> for PyErr { fn from(err: PyO3ArrowError) -> PyErr { PyOSError::new_err(err.to_string()) } } fn to_rust(ob: PyObject, py: Python) -> PyResult<ArrayRef> { // prepare a pointer to receive the Array struct let array = Arc::new(ffi::create_empty()); let (array_ptr, schema_ptr) = array.references(); // make the conversion through PyArrow's private API // this changes the pointer's memory and is thus unsafe. In particular, `_export_to_c` can go out of bounds ob.call_method1( py, "_export_to_c", (array_ptr as uintptr_t, schema_ptr as uintptr_t), )?; Ok(ffi::try_from(array).map_err(PyO3ArrowError::from)?.into()) } fn to_py(array: ArrayRef, py: Python) -> PyResult<PyObject> { let array_ptr = ffi::export_to_c(array).map_err(PyO3ArrowError::from)?; let (array_ptr, schema_ptr) = array_ptr.references(); let pa = py.import("pyarrow")?; let array = pa.getattr("Array")?.call_method1( "_import_from_c", (array_ptr as uintptr_t, schema_ptr as uintptr_t), )?; Ok(array.to_object(py)) } /// Returns `array + array` of an int64 array. #[pyfunction] fn double(array: PyObject, py: Python) -> PyResult<PyObject> { // import let array = to_rust(array, py)?; // perform some operation let array = array.as_any().downcast_ref::<Int64Array>().ok_or_else(|| { PyO3ArrowError::ArrowError(ArrowError::Ffi("Expects an int64".to_string())) })?;
// export to_py(array, py) } /// calls a lambda function that receives and returns an array /// whose result must be the array multiplied by two #[pyfunction] fn double_py(lambda: PyObject, py: Python) -> PyResult<bool> { // create let array = Arc::new(PrimitiveArray::<i64>::from(vec![Some(1), None, Some(3)]).to(DataType::Int64)); let expected = Arc::new(PrimitiveArray::<i64>::from(vec![Some(2), None, Some(6)]).to(DataType::Int64)) as ArrayRef; // to py let array = to_py(array, py)?; let array = lambda.call1(py, (array,))?; let array = to_rust(array, py)?; Ok(array == expected) } /// Returns the substring #[pyfunction] fn substring(array: PyObject, start: i64, py: Python) -> PyResult<PyObject> { // import let array = to_rust(array, py)?; // substring let array = compute::substring::substring(array.as_ref(), start, &None) .map_err(PyO3ArrowError::from)? .into(); // export to_py(array, py) } /// Returns the concatenate #[pyfunction] fn concatenate(array: PyObject, py: Python) -> PyResult<PyObject> { // import let array = to_rust(array, py)?; // concat let array = compute::concat::concatenate(&[array.as_ref(), array.as_ref()]) .map_err(PyO3ArrowError::from)? .into(); // export to_py(array, py) } /// Converts to rust and back to python #[pyfunction] fn round_trip(array: PyObject, py: Python) -> PyResult<PyObject> { // import let array = to_rust(array, py)?; // export to_py(array, py) } /// Converts to rust and back to python #[pyfunction] fn import_primitive(array: PyObject, py: Python) -> PyResult<bool> { let array = to_rust(array, py)?; let expected = Arc::new(PrimitiveArray::<i64>::from(vec![Some(2), None, Some(6)]).to(DataType::Int64)) as ArrayRef; Ok(array == expected) } /// Converts to rust and back to python #[pyfunction] fn export_primitive(py: Python) -> PyResult<PyObject> { let array = Arc::new(PrimitiveArray::<i64>::from(vec![Some(2), None, Some(6)]).to(DataType::Int64)) as ArrayRef; let array = to_py(array, py)?; Ok(array) } #[pyfunction] fn total_allocated_bytes() -> PyResult<isize> { Ok(arrow2::total_allocated_bytes()) } #[pymodule] fn arrow_pyarrow_integration_testing(_py: Python, m: &PyModule) -> PyResult<()> { m.add_wrapped(wrap_pyfunction!(total_allocated_bytes))?; m.add_wrapped(wrap_pyfunction!(export_primitive))?; m.add_wrapped(wrap_pyfunction!(import_primitive))?; m.add_wrapped(wrap_pyfunction!(double))?; m.add_wrapped(wrap_pyfunction!(double_py))?; m.add_wrapped(wrap_pyfunction!(substring))?; m.add_wrapped(wrap_pyfunction!(concatenate))?; m.add_wrapped(wrap_pyfunction!(round_trip))?; Ok(()) }
let array = compute::arithmetics::basic::add::add(&array, &array).map_err(PyO3ArrowError::from)?; let array = Arc::new(array);
apps.py
from django.apps import AppConfig
class MycrudappConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'mycrudApp'
hmc.py
import numpy as np from ..arraystep import Competence from pymc3_ext.vartypes import discrete_types from pymc3_ext.step_methods.hmc.integration import IntegrationError from pymc3_ext.step_methods.hmc.base_hmc import BaseHMC, HMCStepData, DivergenceInfo __all__ = ['HamiltonianMC'] def unif(step_size, elow=.85, ehigh=1.15): return np.random.uniform(elow, ehigh) * step_size class HamiltonianMC(BaseHMC): R"""A sampler for continuous variables based on Hamiltonian mechanics. See NUTS sampler for automatically tuned stopping time and step size scaling. """ name = 'hmc' default_blocked = True generates_stats = True stats_dtypes = [{ 'step_size': np.float64, 'n_steps': np.int64, 'tune': np.bool, 'step_size_bar': np.float64, 'accept': np.float64, 'diverging': np.bool, 'energy_error': np.float64, 'energy': np.float64, 'max_energy_error': np.float64, 'path_length': np.float64, 'accepted': np.bool, 'model_logp': np.float64, }] def __init__(self, vars=None, path_length=2., **kwargs): """Set up the Hamiltonian Monte Carlo sampler. Parameters ---------- vars : list of theano variables path_length : float, default=2 total length to travel step_rand : function float -> float, default=unif A function which takes the step size and returns an new one used to randomize the step size at each iteration. step_scale : float, default=0.25 Initial size of steps to take, automatically scaled down by 1/n**(1/4). scaling : array_like, ndim = {1,2} The inverse mass, or precision matrix. One dimensional arrays are interpreted as diagonal matrices. If `is_cov` is set to True, this will be interpreded as the mass or covariance matrix. is_cov : bool, default=False Treat the scaling as mass or covariance matrix. potential : Potential, optional An object that represents the Hamiltonian with methods `velocity`, `energy`, and `random` methods. It can be specified instead of the scaling matrix. target_accept : float, default 0.65 Adapt the step size such that the average acceptance probability across the trajectories are close to target_accept. Higher values for target_accept lead to smaller step sizes. Setting this to higher values like 0.9 or 0.99 can help with sampling from difficult posteriors. Valid values are between 0 and 1 (exclusive). Default of 0.65 is from (Beskos et. al. 2010, Neal 2011). See Hoffman and Gelman's "The No-U-Turn
k : float, default .75 Parameter for dual averaging for step size adaptation. Values between 0.5 and 1 (exclusive) are admissible. Higher values correspond to slower adaptation. t0 : float > 0, default 10 Parameter for dual averaging. Higher values slow initial adaptation. adapt_step_size : bool, default=True Whether step size adaptation should be enabled. If this is disabled, `k`, `t0`, `gamma` and `target_accept` are ignored. model : pymc3.Model The model **kwargs : passed to BaseHMC """ kwargs.setdefault('step_rand', unif) kwargs.setdefault('target_accept', 0.65) super().__init__(vars, **kwargs) self.path_length = path_length def _hamiltonian_step(self, start, p0, step_size): n_steps = max(1, int(self.path_length / step_size)) energy_change = -np.inf state = start div_info = None try: for _ in range(n_steps): state = self.integrator.step(step_size, state) except IntegrationError as e: div_info = DivergenceInfo('Divergence encountered.', e, state) else: if not np.isfinite(state.energy): div_info = DivergenceInfo( 'Divergence encountered, bad energy.', None, state) energy_change = start.energy - state.energy if np.abs(energy_change) > self.Emax: div_info = DivergenceInfo( 'Divergence encountered, large integration error.', None, state) accept_stat = min(1, np.exp(energy_change)) if div_info is not None or np.random.rand() >= accept_stat: end = start accepted = False else: end = state accepted = True stats = { 'path_length': self.path_length, 'n_steps': n_steps, 'accept': accept_stat, 'energy_error': energy_change, 'energy': state.energy, 'accepted': accepted, 'model_logp': state.model_logp, } return HMCStepData(end, accept_stat, div_info, stats) @staticmethod def competence(var, has_grad): """Check how appropriate this class is for sampling a random variable.""" if var.dtype in discrete_types or not has_grad: return Competence.INCOMPATIBLE return Competence.COMPATIBLE
Sampler: Adaptively Setting Path Lengths in Hamiltonian Monte Carlo" section 3.2 for details. gamma : float, default .05
rewrite_service.rs
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { crate::rewrite_manager::{CommitError, RewriteManager}, anyhow::{anyhow, Error}, async_lock::RwLock, fidl_fuchsia_pkg_rewrite::{ EditTransactionRequest, EditTransactionRequestStream, EngineRequest, EngineRequestStream, RuleIteratorRequest, RuleIteratorRequestStream, }, fidl_fuchsia_pkg_rewrite_ext::Rule, fuchsia_async as fasync, fuchsia_syslog::{fx_log_err, fx_log_info, fx_log_warn}, fuchsia_url::pkg_url::PkgUrl, fuchsia_zircon::Status, futures::prelude::*, std::{convert::TryInto, sync::Arc}, }; const LIST_CHUNK_SIZE: usize = 100; #[derive(Debug, Clone)] pub struct RewriteService { state: Arc<RwLock<RewriteManager>>, } impl RewriteService { pub fn new(state: Arc<RwLock<RewriteManager>>) -> Self { RewriteService { state } } pub async fn handle_client(&mut self, mut stream: EngineRequestStream) -> Result<(), Error> { while let Some(request) = stream.try_next().await? { match request { EngineRequest::List { iterator, control_handle: _control_handle } => { let iterator = iterator.into_stream()?; self.serve_list(iterator).await; } EngineRequest::ListStatic { iterator, control_handle: _control_handle } => { let iterator = iterator.into_stream()?; self.serve_list_static(iterator).await; } EngineRequest::StartEditTransaction { transaction, control_handle: _control_handle, } => { let transaction = transaction.into_stream()?; self.serve_edit_transaction(transaction).await; } EngineRequest::TestApply { url, responder } => { responder.send( &mut self .handle_test_apply(url.as_str()) .await .map(|url| url.to_string()) .map_err(|e| e.into_raw()), )?; } } } Ok(()) } pub(self) async fn handle_test_apply(&self, url: &str) -> Result<PkgUrl, Status> { let url = url.parse::<PkgUrl>().map_err(|e| { fx_log_err!("client provided invalid URL ({:?}): {:#}", url, anyhow!(e)); Status::INVALID_ARGS })?; let rewritten = self.state.read().await.rewrite(&url); Ok(rewritten) } pub(self) async fn serve_list(&mut self, stream: RuleIteratorRequestStream) { let rules = self.state.read().await.list().cloned().collect(); Self::serve_rule_iterator(rules, stream); } pub(self) async fn serve_list_static(&mut self, stream: RuleIteratorRequestStream) { let rules = self.state.read().await.list_static().cloned().collect(); Self::serve_rule_iterator(rules, stream); } pub(self) async fn serve_edit_transaction(&mut self, mut stream: EditTransactionRequestStream) { fx_log_info!("opening rewrite transaction"); let state = self.state.clone(); let mut transaction = state.read().await.transaction(); fasync::Task::spawn( async move { while let Some(request) = stream.try_next().await? { match request { EditTransactionRequest::ListDynamic { iterator, control_handle: _control_handle, } => { let rules = transaction.list_dynamic().cloned().collect(); let iterator = iterator.into_stream()?; Self::serve_rule_iterator(rules, iterator); } EditTransactionRequest::ResetAll { control_handle: _control_handle } => { transaction.reset_all(); } EditTransactionRequest::Add { rule, responder } => { let mut response = match rule.try_into() { Ok(rule) => { transaction.add(rule); Ok(()) } Err(_) => Err(Status::INVALID_ARGS.into_raw()), }; responder.send(&mut response)?; } EditTransactionRequest::Commit { responder } => { let mut response = match state.write().await.apply(transaction).await { Ok(()) => { fx_log_info!("rewrite transaction committed"); Ok(()) } Err(CommitError::TooLate) => { fx_log_warn!("rewrite transaction out of date"); Err(Status::UNAVAILABLE.into_raw()) } Err(CommitError::DynamicConfigurationDisabled) => { fx_log_err!("rewrite transaction failed, dynamic configuration is disabled"); Err(Status::ACCESS_DENIED.into_raw()) } }; responder.send(&mut response)?; return Ok(()); } } } fx_log_info!("rewrite transaction dropped"); Ok(()) } .unwrap_or_else(|e: Error| { fx_log_err!("while serving rewrite rule edit transaction: {:#}", anyhow!(e)) }), ).detach() } fn serve_rule_iterator(rules: Vec<Rule>, mut stream: RuleIteratorRequestStream) { let mut rules = rules.into_iter().map(|rule| rule.into()).collect::<Vec<_>>(); fasync::Task::spawn( async move { let mut iter = rules.iter_mut().peekable(); while let Some(request) = stream.try_next().await? { let RuleIteratorRequest::Next { responder } = request; match iter.peek() { Some(_) => { responder.send(&mut iter.by_ref().take(LIST_CHUNK_SIZE))?; } None => { responder.send(&mut vec![].into_iter())?; return Ok(()); } } } Ok(()) } .unwrap_or_else(|e: fidl::Error| { fx_log_err!("while serving rewrite rule iterator: {:#}", anyhow!(e)) }), ) .detach(); } } #[cfg(test)] mod tests { use { super::*, crate::rewrite_manager::{ tests::{make_rule_config, temp_path_into_proxy_and_path}, RewriteManagerBuilder, Transaction, }, fidl::endpoints::{create_proxy, create_proxy_and_stream}, fidl_fuchsia_pkg_rewrite::{ EditTransactionMarker, EditTransactionProxy, RuleIteratorMarker, }, }; macro_rules! rule { ($host_match:expr => $host_replacement:expr, $path_prefix_match:expr => $path_prefix_replacement:expr) => { fidl_fuchsia_pkg_rewrite_ext::Rule::new( $host_match.to_owned(), $host_replacement.to_owned(), $path_prefix_match.to_owned(), $path_prefix_replacement.to_owned(), ) .unwrap() }; } /// Given the future of a FIDL API call, wait for it to complete, and assert that it /// successfully returns the given Result<(),[`fuchsia_zircon::Status`]>. macro_rules! assert_yields_result { ($expr:expr, $result:expr) => { assert_eq!($expr.await.unwrap().map_err(Status::from_raw), $result); }; } async fn collect_iterator<F, I, O>(mut next: impl FnMut() -> F) -> Vec<O> where F: Future<Output = Result<Vec<I>, fidl::Error>>, I: TryInto<O>, <I as TryInto<O>>::Error: std::fmt::Debug, { let mut res = Vec::new(); loop { let more = next().await.unwrap(); if more.is_empty() { break; } res.extend(more.into_iter().map(|item| item.try_into().unwrap())); } res } async fn list_rules(state: Arc<RwLock<RewriteManager>>) -> Vec<Rule> { let (iterator, request_stream) = create_proxy_and_stream::<RuleIteratorMarker>().unwrap(); RewriteService::new(state).serve_list(request_stream).await; collect_iterator(move || iterator.next()).await } async fn list_static_rules(state: Arc<RwLock<RewriteManager>>) -> Vec<Rule> { let (iterator, request_stream) = create_proxy_and_stream::<RuleIteratorMarker>().unwrap(); RewriteService::new(state).serve_list_static(request_stream).await; collect_iterator(move || iterator.next()).await } fn transaction_list_dynamic_rules( client: &EditTransactionProxy, ) -> impl Future<Output = Vec<Rule>> { let (iterator, request_stream) = create_proxy::<RuleIteratorMarker>().unwrap(); client.list_dynamic(request_stream).unwrap(); collect_iterator(move || iterator.next()) } #[fasync::run_singlethreaded(test)] async fn test_list() { let dynamic_rules = vec![ rule!("fuchsia.com" => "fuchsia.com", "/rolldice" => "/rolldice"), rule!("fuchsia.com" => "fuchsia.com", "/rolldice/" => "/rolldice/"), ]; let path = make_rule_config(dynamic_rules.clone()); let (dynamic_config_dir, dynamic_config_file) = temp_path_into_proxy_and_path(&path); let static_rules = vec![ rule!("fuchsia.com" => "static.fuchsia.com", "/3" => "/3"), rule!("fuchsia.com" => "static.fuchsia.com", "/4" => "/4"), ]; let state = Arc::new(RwLock::new( RewriteManagerBuilder::new(dynamic_config_dir, dynamic_config_file) .await .unwrap() .static_rules(static_rules.clone()) .build(), )); let mut expected = dynamic_rules; expected.extend(static_rules); assert_eq!(list_rules(state.clone()).await, expected); } #[fasync::run_singlethreaded(test)] async fn test_list_static() { let path = make_rule_config(vec![ rule!("fuchsia.com" => "dynamic.fuchsia.com", "/1" => "/1"), rule!("fuchsia.com" => "dynamic.fuchsia.com", "/2" => "/2"), ]); let (dynamic_config_dir, dynamic_config_file) = temp_path_into_proxy_and_path(&path); let static_rules = vec![ rule!("fuchsia.com" => "static.fuchsia.com", "/3" => "/3"), rule!("fuchsia.com" => "static.fuchsia.com", "/4" => "/4"), ]; let state = Arc::new(RwLock::new( RewriteManagerBuilder::new(dynamic_config_dir, dynamic_config_file) .await .unwrap() .static_rules(static_rules.clone()) .build(), )); assert_eq!(list_static_rules(state.clone()).await, static_rules); } #[fasync::run_singlethreaded(test)] async fn test_reset_all() { let rules = vec![ rule!("fuchsia.com" => "fuchsia.com", "/rolldice" => "/rolldice"), rule!("fuchsia.com" => "fuchsia.com", "/rolldice/" => "/rolldice/"), ]; let path = make_rule_config(rules.clone()); let (dynamic_config_dir, dynamic_config_file) = temp_path_into_proxy_and_path(&path); let state = Arc::new(RwLock::new( RewriteManagerBuilder::new(dynamic_config_dir, dynamic_config_file) .await .unwrap() .build(), )); let mut service = RewriteService::new(state.clone()); let (client, request_stream) = create_proxy_and_stream::<EditTransactionMarker>().unwrap(); service.serve_edit_transaction(request_stream).await; client.reset_all().unwrap(); assert_yields_result!(client.commit(), Ok(())); assert_eq!(state.read().await.transaction(), Transaction::new(vec![], 1)); } #[fasync::run_singlethreaded(test)] async fn test_transaction_list_dynamic() { let dynamic_rules = vec![ rule!("fuchsia.com" => "fuchsia.com", "/rolldice" => "/rolldice"), rule!("fuchsia.com" => "fuchsia.com", "/rolldice/" => "/rolldice/"), ]; let path = make_rule_config(dynamic_rules.clone()); let (dynamic_config_dir, dynamic_config_file) = temp_path_into_proxy_and_path(&path); let static_rules = vec![rule!("fuchsia.com" => "static.fuchsia.com", "/" => "/")]; let state = Arc::new(RwLock::new( RewriteManagerBuilder::new(dynamic_config_dir, dynamic_config_file) .await .unwrap() .static_rules(static_rules) .build(), )); let mut service = RewriteService::new(state.clone()); let (client, request_stream) = create_proxy_and_stream::<EditTransactionMarker>().unwrap(); service.serve_edit_transaction(request_stream).await; // The transaction should list all dynamic rules. assert_eq!(transaction_list_dynamic_rules(&client).await, dynamic_rules.clone()); // Start a list call, but don't drain it yet. let pending_list = transaction_list_dynamic_rules(&client); // Remove all dynamic rules and ensure the transaction lists no rules. client.reset_all().unwrap(); assert_eq!(transaction_list_dynamic_rules(&client).await, vec![]); assert_yields_result!(client.commit(), Ok(())); // Ensure the list call from earlier lists the dynamic rules available at the time the // iterator was created. assert_eq!(pending_list.await, dynamic_rules); } #[fasync::run_singlethreaded(test)] async fn test_concurrent_edit() { let rules = vec![ rule!("fuchsia.com" => "fuchsia.com", "/rolldice" => "/rolldice"), rule!("fuchsia.com" => "fuchsia.com", "/rolldice/" => "/rolldice/"), ]; let path = make_rule_config(rules.clone()); let (dynamic_config_dir, dynamic_config_file) = temp_path_into_proxy_and_path(&path); let state = Arc::new(RwLock::new( RewriteManagerBuilder::new(dynamic_config_dir, dynamic_config_file) .await .unwrap() .build(), )); let mut service = RewriteService::new(state.clone()); let client1 = { let (client, request_stream) = create_proxy_and_stream::<EditTransactionMarker>().unwrap(); service.serve_edit_transaction(request_stream).await; client }; let client2 = { let (client, request_stream) = create_proxy_and_stream::<EditTransactionMarker>().unwrap(); service.serve_edit_transaction(request_stream).await; client }; client1.reset_all().unwrap(); client2.reset_all().unwrap(); let rule = rule!("fuchsia.com" => "fuchsia.com", "/foo" => "/foo"); assert_yields_result!(client1.add(&mut rule.clone().into()), Ok(())); assert_yields_result!(client1.commit(), Ok(())); assert_yields_result!(client2.commit(), Err(Status::UNAVAILABLE)); assert_eq!(state.read().await.transaction(), Transaction::new(vec![rule], 1),); let client2 = { let (client, request_stream) = create_proxy_and_stream::<EditTransactionMarker>().unwrap(); service.serve_edit_transaction(request_stream).await; client }; client2.reset_all().unwrap(); assert_yields_result!(client2.commit(), Ok(())); assert_eq!(state.read().await.transaction(), Transaction::new(vec![], 2)); } #[fasync::run_singlethreaded(test)] async fn test_concurrent_list_and_edit() { let path = make_rule_config(vec![]); let (dynamic_config_dir, dynamic_config_file) = temp_path_into_proxy_and_path(&path); let state = Arc::new(RwLock::new( RewriteManagerBuilder::new(dynamic_config_dir, dynamic_config_file) .await .unwrap() .build(), )); let mut service = RewriteService::new(state.clone()); assert_eq!(list_rules(state.clone()).await, vec![]); let edit_client = { let (client, request_stream) = create_proxy_and_stream::<EditTransactionMarker>().unwrap(); service.serve_edit_transaction(request_stream).await; client }; let rule = rule!("fuchsia.com" => "devhost.fuchsia.com", "/" => "/"); assert_yields_result!(edit_client.add(&mut rule.clone().into()), Ok(())); assert_eq!(list_rules(state.clone()).await, vec![]); let long_list_call = { let (client, request_stream) = create_proxy_and_stream::<RuleIteratorMarker>().unwrap(); service.serve_list(request_stream).await; client }; assert_yields_result!(edit_client.commit(), Ok(())); assert_eq!(long_list_call.next().await.unwrap(), vec![]); assert_eq!(list_rules(state.clone()).await, vec![rule]); } #[fasync::run_singlethreaded(test)] async fn test_rewrite() { let path = make_rule_config(vec![]); let (dynamic_config_dir, dynamic_config_file) = temp_path_into_proxy_and_path(&path); let static_rules = vec![ rule!("fuchsia.com" => "fuchsia.com", "/old/" => "/new/"), rule!("fuchsia.com" => "devhost", "/rolldice" => "/rolldice"), rule!("fuchsia.com" => "fuchsia.com", "/identity" => "/identity"), ]; let state = Arc::new(RwLock::new( RewriteManagerBuilder::new(dynamic_config_dir, dynamic_config_file) .await .unwrap() .static_rules(static_rules.clone()) .build(), )); let service = RewriteService::new(state.clone()); for (url, rewritten) in &[ ("fuchsia-pkg://fuchsia.com/old/a", "fuchsia-pkg://fuchsia.com/new/a"), ("fuchsia-pkg://fuchsia.com/rolldice", "fuchsia-pkg://devhost/rolldice"), ("fuchsia-pkg://fuchsia.com/identity", "fuchsia-pkg://fuchsia.com/identity"), ] { assert_eq!(service.handle_test_apply(url).await, Ok(rewritten.parse().unwrap())); } for url in &[ "fuchsia-pkg://subdomain.fuchsia.com/unmatcheddomain", "fuchsia-pkg://devhost/unmatcheddomain", "fuchsia-pkg://fuchsia.com/new/unmatcheddir", ] { assert_eq!(service.handle_test_apply(url).await, Ok(url.parse().unwrap())); } } #[fasync::run_singlethreaded(test)] async fn test_rewrite_rejects_invalid_inputs() { let path = make_rule_config(vec![]); let (dynamic_config_dir, dynamic_config_file) = temp_path_into_proxy_and_path(&path); let state = Arc::new(RwLock::new( RewriteManagerBuilder::new(dynamic_config_dir, dynamic_config_file) .await .unwrap() .build(), )); let service = RewriteService::new(state.clone()); for url in &["not-fuchsia-pkg://fuchsia.com/test", "fuchsia-pkg://fuchsia.com/a*"] { assert_eq!(service.handle_test_apply(url).await, Err(Status::INVALID_ARGS)); } } #[fasync::run_singlethreaded(test)] async fn test_concurrent_rewrite_and_edit() { let path = make_rule_config(vec![rule!("fuchsia.com" => "fuchsia.com", "/a" => "/b")]); let (dynamic_config_dir, dynamic_config_file) = temp_path_into_proxy_and_path(&path); let state = Arc::new(RwLock::new( RewriteManagerBuilder::new(dynamic_config_dir, dynamic_config_file) .await .unwrap() .build(), )); let mut service = RewriteService::new(state.clone()); let (edit_client, request_stream) = create_proxy_and_stream::<EditTransactionMarker>().unwrap(); service.serve_edit_transaction(request_stream).await; let replacement_rule = rule!("fuchsia.com" => "fuchsia.com", "/a" => "/c"); edit_client.reset_all().unwrap(); assert_yields_result!(edit_client.add(&mut replacement_rule.into()), Ok(())); // Pending transaction does not affect apply call. assert_eq!( service.handle_test_apply("fuchsia-pkg://fuchsia.com/a").await, Ok("fuchsia-pkg://fuchsia.com/b".parse().unwrap()) ); assert_yields_result!(edit_client.commit(), Ok(())); // New rule set now applies. assert_eq!( service.handle_test_apply("fuchsia-pkg://fuchsia.com/a").await, Ok("fuchsia-pkg://fuchsia.com/c".parse().unwrap()) ); } #[fasync::run_singlethreaded(test)] async fn test_enables_amber_source() { let path = make_rule_config(vec![]); let (dynamic_config_dir, dynamic_config_file) = temp_path_into_proxy_and_path(&path); let state = Arc::new(RwLock::new( RewriteManagerBuilder::new(dynamic_config_dir, dynamic_config_file) .await .unwrap() .build(), )); let mut service = RewriteService::new(state.clone()); let (client, request_stream) = create_proxy_and_stream::<EditTransactionMarker>().unwrap(); service.serve_edit_transaction(request_stream).await; let rules = vec![ rule!("example.com" => "wrong_host.fuchsia.com", "/" => "/"), rule!("fuchsia.com" => "correct.fuchsia.com", "/" => "/"), rule!("fuchsia.com" => "wrong_priority.fuchsia.com", "/" => "/"), rule!("fuchsia.com" => "wrong_match.fuchsia.com", "/foo/" => "/"), rule!("fuchsia.com" => "wrong_replacement.fuchsia.com", "/" => "/bar/"), ]; for rule in rules.into_iter().rev() { assert_yields_result!(client.add(&mut rule.into()), Ok(())); } assert_yields_result!(client.commit(), Ok(())); // Adding a duplicate of the currently enabled source is a no-op. let (client, request_stream) = create_proxy_and_stream::<EditTransactionMarker>().unwrap(); service.serve_edit_transaction(request_stream).await; let rule = rule!("fuchsia.com" => "correct.fuchsia.com", "/" => "/"); assert_yields_result!(client.add(&mut rule.into()), Ok(())); assert_yields_result!(client.commit(), Ok(())); // Adding a different entry with higher priority enables the new source. let (client, request_stream) = create_proxy_and_stream::<EditTransactionMarker>().unwrap(); service.serve_edit_transaction(request_stream).await; let rule = rule!("fuchsia.com" => "correcter.fuchsia.com", "/" => "/"); assert_yields_result!(client.add(&mut rule.into()), Ok(())); assert_yields_result!(client.commit(), Ok(())); } #[fasync::run_singlethreaded(test)] async fn test_disables_amber_sources() { let rules = vec![rule!("fuchsia.com" => "enabled.fuchsia.com", "/" => "/")]; let path = make_rule_config(rules); let (dynamic_config_dir, dynamic_config_file) = temp_path_into_proxy_and_path(&path); let state = Arc::new(RwLock::new( RewriteManagerBuilder::new(dynamic_config_dir, dynamic_config_file) .await .unwrap() .build(), )); let mut service = RewriteService::new(state.clone()); let (client, request_stream) = create_proxy_and_stream::<EditTransactionMarker>().unwrap(); service.serve_edit_transaction(request_stream).await; client.reset_all().unwrap(); assert_yields_result!(client.commit(), Ok(())); // Edits that don't change the enabled source are a no-op. let (client, request_stream) = create_proxy_and_stream::<EditTransactionMarker>().unwrap(); service.serve_edit_transaction(request_stream).await; client.reset_all().unwrap(); assert_yields_result!(client.commit(), Ok(())); } #[fasync::run_singlethreaded(test)] async fn
() { let state = Arc::new(RwLock::new( RewriteManagerBuilder::new(None, Option::<&str>::None).await.unwrap().build(), )); let mut service = RewriteService::new(state); let (client, request_stream) = create_proxy_and_stream::<EditTransactionMarker>().unwrap(); service.serve_edit_transaction(request_stream).await; let status = Status::from_raw(client.commit().await.unwrap().unwrap_err()); assert_eq!(status, Status::ACCESS_DENIED); } }
test_transaction_commit_fails_if_no_dynamic_rules_path
genesis.go
package types import ( "bytes" "encoding/json" "errors" "fmt" "os" "time" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/internal/jsontypes" tmbytes "github.com/tendermint/tendermint/libs/bytes" tmtime "github.com/tendermint/tendermint/libs/time" ) const ( // MaxChainIDLen is a maximum length of the chain ID. MaxChainIDLen = 50 ) //------------------------------------------------------------ // core types for a genesis definition // NOTE: any changes to the genesis definition should // be reflected in the documentation: // docs/tendermint-core/using-tendermint.md // GenesisValidator is an initial validator. type GenesisValidator struct { Address Address PubKey crypto.PubKey Power int64 Name string } type genesisValidatorJSON struct { Address Address `json:"address"` PubKey json.RawMessage `json:"pub_key"` Power int64 `json:"power,string"` Name string `json:"name"` } func (g GenesisValidator) MarshalJSON() ([]byte, error) { pk, err := jsontypes.Marshal(g.PubKey) if err != nil { return nil, err } return json.Marshal(genesisValidatorJSON{ Address: g.Address, PubKey: pk, Power: g.Power, Name: g.Name, }) } func (g *GenesisValidator) UnmarshalJSON(data []byte) error { var gv genesisValidatorJSON if err := json.Unmarshal(data, &gv); err != nil { return err } if err := jsontypes.Unmarshal(gv.PubKey, &g.PubKey); err != nil { return err } g.Address = gv.Address g.Power = gv.Power g.Name = gv.Name return nil } // GenesisDoc defines the initial conditions for a tendermint blockchain, in particular its validator set. type GenesisDoc struct { GenesisTime time.Time `json:"genesis_time"` ChainID string `json:"chain_id"` InitialHeight int64 `json:"initial_height,string"` ConsensusParams *ConsensusParams `json:"consensus_params,omitempty"` Validators []GenesisValidator `json:"validators,omitempty"` AppHash tmbytes.HexBytes `json:"app_hash"` AppState json.RawMessage `json:"app_state,omitempty"` } // SaveAs is a utility method for saving GenensisDoc as a JSON file. func (genDoc *GenesisDoc) SaveAs(file string) error { genDocBytes, err := json.MarshalIndent(genDoc, "", " ") if err != nil { return err } return os.WriteFile(file, genDocBytes, 0644) // nolint:gosec } // ValidatorHash returns the hash of the validator set contained in the GenesisDoc func (genDoc *GenesisDoc) ValidatorHash() []byte { vals := make([]*Validator, len(genDoc.Validators)) for i, v := range genDoc.Validators { vals[i] = NewValidator(v.PubKey, v.Power) } vset := NewValidatorSet(vals) return vset.Hash() } // ValidateAndComplete checks that all necessary fields are present // and fills in defaults for optional fields left empty func (genDoc *GenesisDoc) ValidateAndComplete() error { if genDoc.ChainID == "" { return errors.New("genesis doc must include non-empty chain_id") } if len(genDoc.ChainID) > MaxChainIDLen { return fmt.Errorf("chain_id in genesis doc is too long (max: %d)", MaxChainIDLen) } if genDoc.InitialHeight < 0 { return fmt.Errorf("initial_height cannot be negative (got %v)", genDoc.InitialHeight) } if genDoc.InitialHeight == 0 { genDoc.InitialHeight = 1 } if genDoc.ConsensusParams == nil { genDoc.ConsensusParams = DefaultConsensusParams() } else if err := genDoc.ConsensusParams.ValidateConsensusParams(); err != nil { return err } for i, v := range genDoc.Validators { if v.Power == 0 { return fmt.Errorf("the genesis file cannot contain validators with no voting power: %v", v) } if len(v.Address) > 0 && !bytes.Equal(v.PubKey.Address(), v.Address) { return fmt.Errorf("incorrect address for validator %v in the genesis file, should be %v", v, v.PubKey.Address()) } if len(v.Address) == 0 { genDoc.Validators[i].Address = v.PubKey.Address() } } if genDoc.GenesisTime.IsZero() { genDoc.GenesisTime = tmtime.Now() } return nil } //------------------------------------------------------------ // Make genesis state from file // GenesisDocFromJSON unmarshalls JSON data into a GenesisDoc. func GenesisDocFromJSON(jsonBlob []byte) (*GenesisDoc, error) { genDoc := GenesisDoc{} err := json.Unmarshal(jsonBlob, &genDoc) if err != nil { return nil, err } if err := genDoc.ValidateAndComplete(); err != nil
return &genDoc, err } // GenesisDocFromFile reads JSON data from a file and unmarshalls it into a GenesisDoc. func GenesisDocFromFile(genDocFile string) (*GenesisDoc, error) { jsonBlob, err := os.ReadFile(genDocFile) if err != nil { return nil, fmt.Errorf("couldn't read GenesisDoc file: %w", err) } genDoc, err := GenesisDocFromJSON(jsonBlob) if err != nil { return nil, fmt.Errorf("error reading GenesisDoc at %s: %w", genDocFile, err) } return genDoc, nil }
{ return nil, err }
event-handler.js
/** * --------------------------------------------------------------------------
* Bootstrap (v4.3.1): dom/event-handler.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * -------------------------------------------------------------------------- */ import { getjQuery } from '../util/index' import { defaultPreventedPreservedOnDispatch } from './polyfill' /** * ------------------------------------------------------------------------ * Constants * ------------------------------------------------------------------------ */ const $ = getjQuery() const namespaceRegex = /[^.]*(?=\..*)\.|.*/ const stripNameRegex = /\..*/ const stripUidRegex = /::\d+$/ const eventRegistry = {} // Events storage let uidEvent = 1 const customEvents = { mouseenter: 'mouseover', mouseleave: 'mouseout' } const nativeEvents = [ 'click', 'dblclick', 'mouseup', 'mousedown', 'contextmenu', 'mousewheel', 'DOMMouseScroll', 'mouseover', 'mouseout', 'mousemove', 'selectstart', 'selectend', 'keydown', 'keypress', 'keyup', 'orientationchange', 'touchstart', 'touchmove', 'touchend', 'touchcancel', 'pointerdown', 'pointermove', 'pointerup', 'pointerleave', 'pointercancel', 'gesturestart', 'gesturechange', 'gestureend', 'focus', 'blur', 'change', 'reset', 'select', 'submit', 'focusin', 'focusout', 'load', 'unload', 'beforeunload', 'resize', 'move', 'DOMContentLoaded', 'readystatechange', 'error', 'abort', 'scroll' ] /** * ------------------------------------------------------------------------ * Private methods * ------------------------------------------------------------------------ */ function getUidEvent(element, uid) { return (uid && `${uid}::${uidEvent++}`) || element.uidEvent || uidEvent++ } function getEvent(element) { const uid = getUidEvent(element) element.uidEvent = uid eventRegistry[uid] = eventRegistry[uid] || {} return eventRegistry[uid] } function bootstrapHandler(element, fn) { return function handler(event) { if (handler.oneOff) { EventHandler.off(element, event.type, fn) } return fn.apply(element, [event]) } } function bootstrapDelegationHandler(element, selector, fn) { return function handler(event) { const domElements = element.querySelectorAll(selector) for (let { target } = event; target && target !== this; target = target.parentNode) { for (let i = domElements.length; i--;) { if (domElements[i] === target) { if (handler.oneOff) { EventHandler.off(element, event.type, fn) } return fn.apply(target, [event]) } } } // To please ESLint return null } } function findHandler(events, handler, delegationSelector = null) { const uidEventList = Object.keys(events) for (let i = 0, len = uidEventList.length; i < len; i++) { const event = events[uidEventList[i]] if (event.originalHandler === handler && event.delegationSelector === delegationSelector) { return event } } return null } function normalizeParams(originalTypeEvent, handler, delegationFn) { const delegation = typeof handler === 'string' const originalHandler = delegation ? delegationFn : handler // allow to get the native events from namespaced events ('click.bs.button' --> 'click') let typeEvent = originalTypeEvent.replace(stripNameRegex, '') const custom = customEvents[typeEvent] if (custom) { typeEvent = custom } const isNative = nativeEvents.indexOf(typeEvent) > -1 if (!isNative) { typeEvent = originalTypeEvent } return [delegation, originalHandler, typeEvent] } function addHandler(element, originalTypeEvent, handler, delegationFn, oneOff) { if (typeof originalTypeEvent !== 'string' || !element) { return } if (!handler) { handler = delegationFn delegationFn = null } const [delegation, originalHandler, typeEvent] = normalizeParams(originalTypeEvent, handler, delegationFn) const events = getEvent(element) const handlers = events[typeEvent] || (events[typeEvent] = {}) const previousFn = findHandler(handlers, originalHandler, delegation ? handler : null) if (previousFn) { previousFn.oneOff = previousFn.oneOff && oneOff return } const uid = getUidEvent(originalHandler, originalTypeEvent.replace(namespaceRegex, '')) const fn = delegation ? bootstrapDelegationHandler(element, handler, delegationFn) : bootstrapHandler(element, handler) fn.delegationSelector = delegation ? handler : null fn.originalHandler = originalHandler fn.oneOff = oneOff fn.uidEvent = uid handlers[uid] = fn element.addEventListener(typeEvent, fn, delegation) } function removeHandler(element, events, typeEvent, handler, delegationSelector) { const fn = findHandler(events[typeEvent], handler, delegationSelector) if (!fn) { return } element.removeEventListener(typeEvent, fn, Boolean(delegationSelector)) delete events[typeEvent][fn.uidEvent] } function removeNamespacedHandlers(element, events, typeEvent, namespace) { const storeElementEvent = events[typeEvent] || {} Object.keys(storeElementEvent) .forEach(handlerKey => { if (handlerKey.indexOf(namespace) > -1) { const event = storeElementEvent[handlerKey] removeHandler(element, events, typeEvent, event.originalHandler, event.delegationSelector) } }) } const EventHandler = { on(element, event, handler, delegationFn) { addHandler(element, event, handler, delegationFn, false) }, one(element, event, handler, delegationFn) { addHandler(element, event, handler, delegationFn, true) }, off(element, originalTypeEvent, handler, delegationFn) { if (typeof originalTypeEvent !== 'string' || !element) { return } const [delegation, originalHandler, typeEvent] = normalizeParams(originalTypeEvent, handler, delegationFn) const inNamespace = typeEvent !== originalTypeEvent const events = getEvent(element) const isNamespace = originalTypeEvent.charAt(0) === '.' if (typeof originalHandler !== 'undefined') { // Simplest case: handler is passed, remove that listener ONLY. if (!events || !events[typeEvent]) { return } removeHandler(element, events, typeEvent, originalHandler, delegation ? handler : null) return } if (isNamespace) { Object.keys(events) .forEach(elementEvent => { removeNamespacedHandlers(element, events, elementEvent, originalTypeEvent.slice(1)) }) } const storeElementEvent = events[typeEvent] || {} Object.keys(storeElementEvent) .forEach(keyHandlers => { const handlerKey = keyHandlers.replace(stripUidRegex, '') if (!inNamespace || originalTypeEvent.indexOf(handlerKey) > -1) { const event = storeElementEvent[keyHandlers] removeHandler(element, events, typeEvent, event.originalHandler, event.delegationSelector) } }) }, trigger(element, event, args) { if (typeof event !== 'string' || !element) { return null } const typeEvent = event.replace(stripNameRegex, '') const inNamespace = event !== typeEvent const isNative = nativeEvents.indexOf(typeEvent) > -1 let jQueryEvent let bubbles = true let nativeDispatch = true let defaultPrevented = false let evt = null if (inNamespace && $) { jQueryEvent = $.Event(event, args) $(element).trigger(jQueryEvent) bubbles = !jQueryEvent.isPropagationStopped() nativeDispatch = !jQueryEvent.isImmediatePropagationStopped() defaultPrevented = jQueryEvent.isDefaultPrevented() } if (isNative) { evt = document.createEvent('HTMLEvents') evt.initEvent(typeEvent, bubbles, true) } else { evt = new CustomEvent(event, { bubbles, cancelable: true }) } // merge custom informations in our event if (typeof args !== 'undefined') { Object.keys(args) .forEach(key => { Object.defineProperty(evt, key, { get() { return args[key] } }) }) } if (defaultPrevented) { evt.preventDefault() if (!defaultPreventedPreservedOnDispatch) { Object.defineProperty(evt, 'defaultPrevented', { get: () => true }) } } if (nativeDispatch) { element.dispatchEvent(evt) } if (evt.defaultPrevented && typeof jQueryEvent !== 'undefined') { jQueryEvent.preventDefault() } return evt } } export default EventHandler
main.rs
use anyhow::Context; use clap::{App, Arg, SubCommand}; use identity::Identity; use log::debug; use std::net::SocketAddr; use storage::{encrypted::EncryptedStorage, zdb::Zdb}; use tokio::runtime::Builder; use tonic::transport::Server; #[macro_use] extern crate anyhow; #[macro_use] extern crate log; mod acl; mod auth; mod database; mod explorer; mod identity; mod peer; mod rest; mod rpc; mod storage; const MEAT_DIR: &str = ".bcdb-meta"; fn main() -> Result<(), Box<dyn std::error::Error>> { let mut runtime = Builder::default() .threaded_scheduler() .core_threads(num_cpus::get()) .enable_all() .thread_stack_size(10 * 1024 * 1024) //set stack size to 10MB .build() .unwrap(); runtime.block_on(async { match entry().await { Ok(_) => {} Err(err) => { eprintln!("{}", err); std::process::exit(1); } }; }); Ok(()) } async fn entry() -> Result<(), Box<dyn std::error::Error>> { let meta_dir = match dirs::home_dir() { Some(p) => p.join(".bcdb-meta"), None => std::path::PathBuf::from(MEAT_DIR), }; let matches = App::new("bcdb") .arg( Arg::with_name("zdb") .help("local zdb port") .long("zdb") .short("z") .takes_value(true) .default_value("9900"), ) .arg( Arg::with_name("grpc") .help("listen on address for grpc api") .long("grpc") .short("g") .takes_value(true) .default_value("0.0.0.0:50051"), ) .arg( Arg::with_name("rest") .help("listen unix socket for rest api") .long("rest") .short("r") .takes_value(true) .default_value("/tmp/bcdb.sock"), ) .arg( Arg::with_name("meta") .help("directory where metadata is stored") .long("meta") .short("m") .takes_value(true) .default_value(meta_dir.to_str().unwrap_or(MEAT_DIR)), ) .arg( Arg::with_name("debug") .help("enable debug logging") .long("debug") .short("d") .takes_value(false), ) .arg( Arg::with_name("id") .help("threebot ID for this bcdb instance") .long("threebot-id") .short("id") .required_unless("seed-file") .conflicts_with("seed-file") .takes_value(true), ) .arg( Arg::with_name("seed") .help("mnemonic of the seed to be used for the identity") .long("seed") .short("s") .takes_value(true) .env("SEED") .conflicts_with("seed-file") .required_unless("seed-file"), ) .arg( Arg::with_name("seed-file") .help("path to the file containing the mnemonic") .long("seed-file") .takes_value(true) .required_unless("seed") .env("seed-file"), ) .arg( Arg::with_name("explorer") .help("explorer URL for phonebook entries validations") .long("explorer") .takes_value(true) .default_value("https://explorer.devnet.grid.tf/explorer/"), ) .arg( Arg::with_name("peers-file") .help("path to file with peers list, otherwise use explorer") .long("peers-file") .takes_value(true) .required(false) .env("PEERS_FILE"), ) .subcommand( SubCommand::with_name("rebuild") .about("rebuild index from zdb") .arg( Arg::with_name("from") .long("from") .short("f") .help("only rebuild index with records after given timestamp") .takes_value(true) .required(false), ), ) .get_matches(); let level = if matches.is_present("debug") { log::Level::Debug } else { log::Level::Info }; simple_logger::init_with_level(level).unwrap(); let identity = if matches.is_present("seed") { let bot_id: u32 = matches.value_of("id").unwrap().parse()?; Identity::from_mnemonic(bot_id, matches.value_of("seed").unwrap())? } else { Identity::from_identity_file(matches.value_of("seed-file").unwrap())? }; // for some reason a byte slice does not implement fmt::LowerHex or fmt::UpperHex so manually // show the bytes info!( "Starting server with identity, id: {}, and public-key: {}", identity.id(), identity.public_key() ); debug!("Using identity private key as symmetric encryption key for zdb data"); let zdb = Zdb::new(matches.value_of("zdb").unwrap().parse()?); // use sqlite meta data factory, to build a sqlite index let index = database::index::SqliteIndexBuilder::new(matches.value_of("meta").unwrap())? .build("metadata") .await?; // intercept the index to also store the metadata in zdb as well let index = database::index::MetaInterceptor::new( index, EncryptedStorage::new(identity.as_sk_bytes(), zdb.collection("metadata")), ); if let Some(matches) = matches.subcommand_matches("rebuild") { let mut index = index; let from = match matches.value_of("from") { Some(s) => Some( s.parse() .context("failed to parse 'from' value expecting timestamp")?, ), None => None, }; index.rebuild(from).await?; return Ok(()); }
// the acl_store let acl_store = acl::ACLStorage::new(EncryptedStorage::new( identity.as_sk_bytes(), zdb.collection("acl"), )); let db = database::BcdbDatabase::new( EncryptedStorage::new(identity.as_sk_bytes(), zdb.collection("objects")), index, acl_store.clone(), ); let peers = if matches.is_present("peers-file") { peer::Either::A(peer::PeersFile::new( matches.value_of("peers-file").unwrap(), )?) } else { peer::Either::B(explorer::Explorer::new(matches.value_of("explorer"))?) }; // tracker cache peers from the given source, and validate their identity let tracker = peer::Tracker::new(std::time::Duration::from_secs(20 * 60), 1000, peers); let db = peer::Router::new(identity.clone(), db, tracker.clone()); let interceptor = auth::Authenticator::new(tracker, identity.clone()); let acl_interceptor = interceptor.clone(); let bcdb_service = rpc::BcdbService::new(db.clone()); //acl api let acl_service = rpc::AclService::new(acl_store.clone()); //identity api let identity_service = rpc::IdentityService::new(identity.clone()); let grpc_address: SocketAddr = matches.value_of("grpc").unwrap().parse()?; let rest_address: String = matches.value_of("rest").unwrap().into(); tokio::spawn(async move { match rest::run(db, acl_store, rest_address).await { Ok(_) => {} Err(err) => { error!("failed to start rest api: {}", err); std::process::exit(1); } } }); Server::builder() .add_service(rpc::BcdbServer::with_interceptor( bcdb_service, move |request| interceptor.authenticate_blocking(request), )) .add_service(rpc::AclServer::with_interceptor( acl_service, move |request| acl_interceptor.authenticate_blocking(request), )) .add_service(rpc::IdentityServer::new(identity_service)) .serve(grpc_address) .await?; Ok(()) }
starter_code.py
class Solution: def canCross(self, stones: List[int]) -> bool:
links.go
// Copyright (C) 2017 Google Inc. // // 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 the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gles import ( "context" "github.com/google/gapid/gapis/resolve" "github.com/google/gapid/gapis/service/path" ) // objects returns the path to the Objects field of the currently bound // context, and the context at p. func objects(ctx context.Context, p path.Node) (*path.Field, *Context, error) { if cmdPath := path.FindCommand(p); cmdPath != nil { cmd, err := resolve.Cmd(ctx, cmdPath) if err != nil { return nil, nil, err } thread := cmd.Thread() stateObj, err := resolve.State(ctx, cmdPath.StateAfter()) if err != nil { return nil, nil, err } state := stateObj.(*State) context, ok := state.Contexts[thread] if !ok { return nil, nil, nil } return state.objectsRoot(cmdPath, thread), context, nil } return nil, nil, nil } // sharedObjects returns the path to the Objects.Shared field of the currently bound // context, and the context at p. func sharedObjects(ctx context.Context, p path.Node) (*path.Field, *Context, error) { if cmdPath := path.FindCommand(p); cmdPath != nil { cmd, err := resolve.Cmd(ctx, cmdPath) if err != nil { return nil, nil, err } thread := cmd.Thread() stateObj, err := resolve.State(ctx, cmdPath.StateAfter()) if err != nil { return nil, nil, err } state := stateObj.(*State) context, ok := state.Contexts[thread] if !ok { return nil, nil, nil } return state.objectsRoot(cmdPath, thread).Field("Shared"), context, nil } return nil, nil, nil } // Link returns the link to the attribute vertex array in the state block. // If nil, nil is returned then the path cannot be followed. func (o AttributeLocation) Link(ctx context.Context, p path.Node) (path.Node, error) { i, c, err := objects(ctx, p) if i == nil { return nil, err } if !c.Bound.VertexArray.VertexAttributeArrays.Contains(o) { return nil, nil } return i. Field("VertexArrays"). MapIndex(c.Bound.VertexArray.GetID()). Field("VertexAttributeArrays"). MapIndex(o), nil } // Link returns the link to the buffer object in the state block. // If nil, nil is returned then the path cannot be followed. func (o BufferId) Link(ctx context.Context, p path.Node) (path.Node, error) { i, c, err := sharedObjects(ctx, p) if i == nil || !c.Objects.Shared.Buffers.Contains(o) { return nil, err } return i.Field("Buffers").MapIndex(o), nil } // Link returns the link to the framebuffer object in the state block. // If nil, nil is returned then the path cannot be followed. func (o FramebufferId) Link(ctx context.Context, p path.Node) (path.Node, error) { i, c, err := objects(ctx, p) if i == nil || !c.Objects.Framebuffers.Contains(o) { return nil, err } return i.Field("Framebuffers").MapIndex(o), nil } // Link returns the link to the program in the state block. // If nil, nil is returned then the path cannot be followed. func (o ProgramId) Link(ctx context.Context, p path.Node) (path.Node, error) { i, c, err := sharedObjects(ctx, p) if i == nil || !c.Objects.Shared.Programs.Contains(o) { return nil, err } return i.Field("Programs").MapIndex(o), nil } // Link returns the link to the query object in the state block. // If nil, nil is returned then the path cannot be followed. func (o QueryId) Link(ctx context.Context, p path.Node) (path.Node, error) { i, c, err := objects(ctx, p) if i == nil || !c.Objects.Queries.Contains(o) { return nil, err } return i.Field("Queries").MapIndex(o), nil } // Link returns the link to the renderbuffer object in the state block. // If nil, nil is returned then the path cannot be followed. func (o RenderbufferId) Link(ctx context.Context, p path.Node) (path.Node, error) { i, c, err := sharedObjects(ctx, p) if i == nil || !c.Objects.Shared.Renderbuffers.Contains(o) { return nil, err } return i.Field("Renderbuffers").MapIndex(o), nil } // Link returns the link to the shader object in the state block. // If nil, nil is returned then the path cannot be followed. func (o ShaderId) Link(ctx context.Context, p path.Node) (path.Node, error) { i, c, err := sharedObjects(ctx, p) if i == nil || !c.Objects.Shared.Shaders.Contains(o) { return nil, err } return i.Field("Shaders").MapIndex(o), nil } // Link returns the link to the texture object in the state block. // If nil, nil is returned then the path cannot be followed. func (o TextureId) Link(ctx context.Context, p path.Node) (path.Node, error) { i, c, err := sharedObjects(ctx, p) if i == nil || !c.Objects.Shared.Textures.Contains(o) { return nil, err } return i.Field("Textures").MapIndex(o), nil } // Link returns the link to the uniform in the state block. // If nil, nil is returned then the path cannot be followed. func (o UniformLocation) Link(ctx context.Context, p path.Node) (path.Node, error) { i, c, err := sharedObjects(ctx, p) if i == nil { return nil, err } cmd, err := resolve.Cmd(ctx, path.FindCommand(p)) if err != nil { return nil, err } var program ProgramId switch cmd := cmd.(type) { case *GlGetActiveUniform: program = cmd.Program case *GlGetUniformLocation: program = cmd.Program default: program = c.Bound.Program.GetID() } prog, ok := c.Objects.Shared.Programs[program] if !ok || !prog.Uniforms.Contains(o) { return nil, nil } return i. Field("Programs").
} // Link returns the link to the vertex array in the state block. // If nil, nil is returned then the path cannot be followed. func (o VertexArrayId) Link(ctx context.Context, p path.Node) (path.Node, error) { i, c, err := objects(ctx, p) if i == nil || !c.Objects.VertexArrays.Contains(o) { return nil, err } return i.Field("VertexArrays").MapIndex(o), nil } // Link returns the link to the transform feedback in the state block. // If nil, nil is returned then the path cannot be followed. func (o TransformFeedbackId) Link(ctx context.Context, p path.Node) (path.Node, error) { i, c, err := objects(ctx, p) if i == nil || !c.Objects.TransformFeedbacks.Contains(o) { return nil, err } return i.Field("TransformFeedbacks").MapIndex(o), nil }
MapIndex(program). Field("Uniforms"). MapIndex(o), nil
listing15.go
package main import ( "fmt" "sync" "sync/atomic" "time" ) var ( shutdown int64 wg sync.WaitGroup ) func main() { wg.Add(2) go doWork("A") go doWork("B") time.Sleep(1 * time.Second) fmt.Println("Shutdown Now") atomic.StoreInt64(&shutdown, 1) wg.Wait() } func doWork(name string)
{ defer wg.Done() for { fmt.Printf("Doing %s Work\n", name) time.Sleep(250 * time.Microsecond) if atomic.LoadInt64(&shutdown) == 1 { fmt.Printf("Shutting %s down\n", name) break } } }
config.go
package config import ( "crypto/tls" "flag" "fmt" "io/ioutil" "net/http" "os" "sort" "strconv" "strings" "time" "gopkg.in/yaml.v2" log "github.com/sirupsen/logrus" "github.com/prometheus/client_golang/prometheus" "github.com/zalando/skipper" "github.com/zalando/skipper/dataclients/kubernetes" "github.com/zalando/skipper/eskip" "github.com/zalando/skipper/net" "github.com/zalando/skipper/proxy" "github.com/zalando/skipper/swarm" ) type Config struct { ConfigFile string // generic: Address string `yaml:"address"` EnableTCPQueue bool `yaml:"enable-tcp-queue"` ExpectedBytesPerRequest int `yaml:"expected-bytes-per-request"` MaxTCPListenerConcurrency int `yaml:"max-tcp-listener-concurrency"` MaxTCPListenerQueue int `yaml:"max-tcp-listener-queue"` IgnoreTrailingSlash bool `yaml:"ignore-trailing-slash"` Insecure bool `yaml:"insecure"` ProxyPreserveHost bool `yaml:"proxy-preserve-host"` DevMode bool `yaml:"dev-mode"` SupportListener string `yaml:"support-listener"` DebugListener string `yaml:"debug-listener"` CertPathTLS string `yaml:"tls-cert"` KeyPathTLS string `yaml:"tls-key"` StatusChecks *listFlag `yaml:"status-checks"` PrintVersion bool `yaml:"version"` MaxLoopbacks int `yaml:"max-loopbacks"` DefaultHTTPStatus int `yaml:"default-http-status"` PluginDir string `yaml:"plugindir"` LoadBalancerHealthCheckInterval time.Duration `yaml:"lb-healthcheck-interval"` ReverseSourcePredicate bool `yaml:"reverse-source-predicate"` RemoveHopHeaders bool `yaml:"remove-hop-headers"` RfcPatchPath bool `yaml:"rfc-patch-path"` MaxAuditBody int `yaml:"max-audit-body"` EnableBreakers bool `yaml:"enable-breakers"` Breakers breakerFlags `yaml:"breaker"` EnableRatelimiters bool `yaml:"enable-ratelimits"` Ratelimits ratelimitFlags `yaml:"ratelimits"` EnableRouteLIFOMetrics bool `yaml:"enable-route-lifo-metrics"` MetricsFlavour *listFlag `yaml:"metrics-flavour"` FilterPlugins *pluginFlag `yaml:"filter-plugin"` PredicatePlugins *pluginFlag `yaml:"predicate-plugin"` DataclientPlugins *pluginFlag `yaml:"dataclient-plugin"` MultiPlugins *pluginFlag `yaml:"multi-plugin"` // logging, metrics, tracing: EnablePrometheusMetrics bool `yaml:"enable-prometheus-metrics"` OpenTracing string `yaml:"opentracing"` OpenTracingInitialSpan string `yaml:"opentracing-initial-span"` OpenTracingExcludedProxyTags string `yaml:"opentracing-excluded-proxy-tags"` OpentracingLogFilterLifecycleEvents bool `yaml:"opentracing-log-filter-lifecycle-events"` OpentracingLogStreamEvents bool `yaml:"opentracing-log-stream-events"` OpentracingBackendNameTag bool `yaml:"opentracing-backend-name-tag"` MetricsListener string `yaml:"metrics-listener"` MetricsPrefix string `yaml:"metrics-prefix"` EnableProfile bool `yaml:"enable-profile"` DebugGcMetrics bool `yaml:"debug-gc-metrics"` RuntimeMetrics bool `yaml:"runtime-metrics"` ServeRouteMetrics bool `yaml:"serve-route-metrics"` ServeRouteCounter bool `yaml:"serve-route-counter"` ServeHostMetrics bool `yaml:"serve-host-metrics"` ServeHostCounter bool `yaml:"serve-host-counter"` ServeMethodMetric bool `yaml:"serve-method-metric"` ServeStatusCodeMetric bool `yaml:"serve-status-code-metric"` BackendHostMetrics bool `yaml:"backend-host-metrics"` AllFiltersMetrics bool `yaml:"all-filters-metrics"` CombinedResponseMetrics bool `yaml:"combined-response-metrics"` RouteResponseMetrics bool `yaml:"route-response-metrics"` RouteBackendErrorCounters bool `yaml:"route-backend-error-counters"` RouteStreamErrorCounters bool `yaml:"route-stream-error-counters"` RouteBackendMetrics bool `yaml:"route-backend-metrics"` RouteCreationMetrics bool `yaml:"route-creation-metrics"` MetricsUseExpDecaySample bool `yaml:"metrics-exp-decay-sample"` HistogramMetricBucketsString string `yaml:"histogram-metric-buckets"` HistogramMetricBuckets []float64 `yaml:"-"` DisableMetricsCompat bool `yaml:"disable-metrics-compat"` ApplicationLog string `yaml:"application-log"` ApplicationLogLevel log.Level `yaml:"-"` ApplicationLogLevelString string `yaml:"application-log-level"` ApplicationLogPrefix string `yaml:"application-log-prefix"` ApplicationLogJSONEnabled bool `yaml:"application-log-json-enabled"` AccessLog string `yaml:"access-log"` AccessLogDisabled bool `yaml:"access-log-disabled"` AccessLogJSONEnabled bool `yaml:"access-log-json-enabled"` AccessLogStripQuery bool `yaml:"access-log-strip-query"` SuppressRouteUpdateLogs bool `yaml:"suppress-route-update-logs"` // route sources: EtcdUrls string `yaml:"etcd-urls"` EtcdPrefix string `yaml:"etcd-prefix"` EtcdTimeout time.Duration `yaml:"etcd-timeout"` EtcdInsecure bool `yaml:"etcd-insecure"` EtcdOAuthToken string `yaml:"etcd-oauth-token"` EtcdUsername string `yaml:"etcd-username"` EtcdPassword string `yaml:"etcd-password"` InnkeeperURL string `yaml:"innkeeper-url"` InnkeeperAuthToken string `yaml:"innkeeper-auth-token"` InnkeeperPreRouteFilters string `yaml:"innkeeper-pre-route-filters"` InnkeeperPostRouteFilters string `yaml:"innkeeper-post-route-filters"` RoutesFile string `yaml:"routes-file"` InlineRoutes string `yaml:"inline-routes"` AppendFilters *defaultFiltersFlags `yaml:"default-filters-append"` PrependFilters *defaultFiltersFlags `yaml:"default-filters-prepend"` SourcePollTimeout int64 `yaml:"source-poll-timeout"` WaitFirstRouteLoad bool `yaml:"wait-first-route-load"` // Kubernetes: KubernetesIngress bool `yaml:"kubernetes"` KubernetesInCluster bool `yaml:"kubernetes-in-cluster"` KubernetesURL string `yaml:"kubernetes-url"` KubernetesHealthcheck bool `yaml:"kubernetes-healthcheck"` KubernetesHTTPSRedirect bool `yaml:"kubernetes-https-redirect"` KubernetesHTTPSRedirectCode int `yaml:"kubernetes-https-redirect-code"` KubernetesIngressClass string `yaml:"kubernetes-ingress-class"` KubernetesRouteGroupClass string `yaml:"kubernetes-routegroup-class"` WhitelistedHealthCheckCIDR string `yaml:"whitelisted-healthcheck-cidr"` KubernetesPathModeString string `yaml:"kubernetes-path-mode"` KubernetesPathMode kubernetes.PathMode `yaml:"-"` KubernetesNamespace string `yaml:"kubernetes-namespace"` KubernetesEnableEastWest bool `yaml:"enable-kubernetes-east-west"` KubernetesEastWestDomain string `yaml:"kubernetes-east-west-domain"` KubernetesEastWestRangeDomains *listFlag `yaml:"kubernetes-east-west-range-domains"` KubernetesEastWestRangePredicatesString string `yaml:"kubernetes-east-west-range-predicates"` KubernetesEastWestRangePredicates []*eskip.Predicate `yaml:"-"` // Default filters DefaultFiltersDir string `yaml:"default-filters-dir"` // Auth: EnableOAuth2GrantFlow bool `yaml:"enable-oauth2-grant-flow"` OauthURL string `yaml:"oauth-url"` OauthScope string `yaml:"oauth-scope"` OauthCredentialsDir string `yaml:"oauth-credentials-dir"` Oauth2AuthURL string `yaml:"oauth2-auth-url"` Oauth2TokenURL string `yaml:"oauth2-token-url"` Oauth2RevokeTokenURL string `yaml:"oauth2-revoke-token-url"` Oauth2TokeninfoURL string `yaml:"oauth2-tokeninfo-url"` Oauth2TokeninfoTimeout time.Duration `yaml:"oauth2-tokeninfo-timeout"` Oauth2SecretFile string `yaml:"oauth2-secret-file"` Oauth2ClientID string `yaml:"oauth2-client-id"` Oauth2ClientSecret string `yaml:"oauth2-client-secret"` Oauth2ClientIDFile string `yaml:"oauth2-client-id-file"` Oauth2ClientSecretFile string `yaml:"oauth2-client-secret-file"` Oauth2AuthURLParameters mapFlags `yaml:"oauth2-auth-url-parameters"` Oauth2CallbackPath string `yaml:"oauth2-callback-path"` Oauth2TokenintrospectionTimeout time.Duration `yaml:"oauth2-tokenintrospect-timeout"` Oauth2AccessTokenHeaderName string `yaml:"oauth2-access-token-header-name"` Oauth2TokeninfoSubjectKey string `yaml:"oauth2-tokeninfo-subject-key"` Oauth2TokenCookieName string `yaml:"oauth2-token-cookie-name"` WebhookTimeout time.Duration `yaml:"webhook-timeout"` OidcSecretsFile string `yaml:"oidc-secrets-file"` CredentialPaths *listFlag `yaml:"credentials-paths"` CredentialsUpdateInterval time.Duration `yaml:"credentials-update-interval"` // TLS client certs ClientKeyFile string `yaml:"client-tls-key"` ClientCertFile string `yaml:"client-tls-cert"` Certificates []tls.Certificate `yaml:"-"` // TLS version TLSMinVersion string `yaml:"tls-min-version"` // API Monitoring ApiUsageMonitoringEnable bool `yaml:"enable-api-usage-monitoring"` ApiUsageMonitoringRealmKeys string `yaml:"api-usage-monitoring-realm-keys"` ApiUsageMonitoringClientKeys string `yaml:"api-usage-monitoring-client-keys"` ApiUsageMonitoringDefaultClientTrackingPattern string `yaml:"api-usage-monitoring-default-client-tracking-pattern"` ApiUsageMonitoringRealmsTrackingPattern string `yaml:"api-usage-monitoring-realms-tracking-pattern"` // connections, timeouts: WaitForHealthcheckInterval time.Duration `yaml:"wait-for-healthcheck-interval"` IdleConnsPerHost int `yaml:"idle-conns-num"` CloseIdleConnsPeriod time.Duration `yaml:"close-idle-conns-period"` BackendFlushInterval time.Duration `yaml:"backend-flush-interval"` ExperimentalUpgrade bool `yaml:"experimental-upgrade"` ExperimentalUpgradeAudit bool `yaml:"experimental-upgrade-audit"` ReadTimeoutServer time.Duration `yaml:"read-timeout-server"` ReadHeaderTimeoutServer time.Duration `yaml:"read-header-timeout-server"` WriteTimeoutServer time.Duration `yaml:"write-timeout-server"` IdleTimeoutServer time.Duration `yaml:"idle-timeout-server"` MaxHeaderBytes int `yaml:"max-header-bytes"` EnableConnMetricsServer bool `yaml:"enable-connection-metrics"` TimeoutBackend time.Duration `yaml:"timeout-backend"` KeepaliveBackend time.Duration `yaml:"keepalive-backend"` EnableDualstackBackend bool `yaml:"enable-dualstack-backend"` TlsHandshakeTimeoutBackend time.Duration `yaml:"tls-timeout-backend"` ResponseHeaderTimeoutBackend time.Duration `yaml:"response-header-timeout-backend"` ExpectContinueTimeoutBackend time.Duration `yaml:"expect-continue-timeout-backend"` MaxIdleConnsBackend int `yaml:"max-idle-connection-backend"` DisableHTTPKeepalives bool `yaml:"disable-http-keepalives"` // swarm: EnableSwarm bool `yaml:"enable-swarm"` // redis based SwarmRedisURLs *listFlag `yaml:"swarm-redis-urls"` SwarmRedisPassword string `yaml:"swarm-redis-password"` SwarmRedisHashAlgorithm string `yaml:"swarm-redis-hash-algorithm"` SwarmRedisDialTimeout time.Duration `yaml:"swarm-redis-dial-timeout"` SwarmRedisReadTimeout time.Duration `yaml:"swarm-redis-read-timeout"` SwarmRedisWriteTimeout time.Duration `yaml:"swarm-redis-write-timeout"` SwarmRedisPoolTimeout time.Duration `yaml:"swarm-redis-pool-timeout"` SwarmRedisMinConns int `yaml:"swarm-redis-min-conns"` SwarmRedisMaxConns int `yaml:"swarm-redis-max-conns"` // swim based SwarmKubernetesNamespace string `yaml:"swarm-namespace"` SwarmKubernetesLabelSelectorKey string `yaml:"swarm-label-selector-key"` SwarmKubernetesLabelSelectorValue string `yaml:"swarm-label-selector-value"` SwarmPort int `yaml:"swarm-port"` SwarmMaxMessageBuffer int `yaml:"swarm-max-msg-buffer"` SwarmLeaveTimeout time.Duration `yaml:"swarm-leave-timeout"` SwarmStaticSelf string `yaml:"swarm-static-self"` SwarmStaticOther string `yaml:"swarm-static-other"` } const ( // TLS defaultMinTLSVersion = "1.2" // environment keys: redisPasswordEnv = "SWARM_REDIS_PASSWORD" ) func NewConfig() *Config { cfg := new(Config) cfg.MetricsFlavour = commaListFlag("codahale", "prometheus") cfg.StatusChecks = commaListFlag() cfg.FilterPlugins = newPluginFlag() cfg.PredicatePlugins = newPluginFlag() cfg.DataclientPlugins = newPluginFlag() cfg.MultiPlugins = newPluginFlag() cfg.CredentialPaths = commaListFlag() cfg.SwarmRedisURLs = commaListFlag() cfg.AppendFilters = &defaultFiltersFlags{} cfg.PrependFilters = &defaultFiltersFlags{} cfg.KubernetesEastWestRangeDomains = commaListFlag() flag.StringVar(&cfg.ConfigFile, "config-file", "", "if provided the flags will be loaded/overwritten by the values on the file (yaml)") // generic: flag.StringVar(&cfg.Address, "address", ":9090", "network address that skipper should listen on") flag.BoolVar(&cfg.EnableTCPQueue, "enable-tcp-queue", false, "enable the TCP listener queue") flag.IntVar(&cfg.ExpectedBytesPerRequest, "expected-bytes-per-request", 50*1024, "bytes per request, that is used to calculate concurrency limits to buffer connection spikes") flag.IntVar(&cfg.MaxTCPListenerConcurrency, "max-tcp-listener-concurrency", 0, "sets hardcoded max for TCP listener concurrency, normally calculated based on available memory cgroups with max TODO") flag.IntVar(&cfg.MaxTCPListenerQueue, "max-tcp-listener-queue", 0, "sets hardcoded max queue size for TCP listener, normally calculated 10x concurrency with max TODO:50k") flag.BoolVar(&cfg.IgnoreTrailingSlash, "ignore-trailing-slash", false, "flag indicating to ignore trailing slashes in paths when routing") flag.BoolVar(&cfg.Insecure, "insecure", false, "flag indicating to ignore the verification of the TLS certificates of the backend services") flag.BoolVar(&cfg.ProxyPreserveHost, "proxy-preserve-host", false, "flag indicating to preserve the incoming request 'Host' header in the outgoing requests") flag.BoolVar(&cfg.DevMode, "dev-mode", false, "enables developer time behavior, like ubuffered routing updates") flag.StringVar(&cfg.SupportListener, "support-listener", ":9911", "network address used for exposing the /metrics endpoint. An empty value disables support endpoint.") flag.StringVar(&cfg.DebugListener, "debug-listener", "", "when this address is set, skipper starts an additional listener returning the original and transformed requests") flag.StringVar(&cfg.CertPathTLS, "tls-cert", "", "the path on the local filesystem to the certificate file(s) (including any intermediates), multiple may be given comma separated") flag.StringVar(&cfg.KeyPathTLS, "tls-key", "", "the path on the local filesystem to the certificate's private key file(s), multiple keys may be given comma separated - the order must match the certs") flag.Var(cfg.StatusChecks, "status-checks", "experimental URLs to check before reporting healthy on startup") flag.BoolVar(&cfg.PrintVersion, "version", false, "print Skipper version") flag.IntVar(&cfg.MaxLoopbacks, "max-loopbacks", proxy.DefaultMaxLoopbacks, "maximum number of loopbacks for an incoming request, set to -1 to disable loopbacks") flag.IntVar(&cfg.DefaultHTTPStatus, "default-http-status", http.StatusNotFound, "default HTTP status used when no route is found for a request") flag.StringVar(&cfg.PluginDir, "plugindir", "", "set the directory to load plugins from, default is ./") flag.DurationVar(&cfg.LoadBalancerHealthCheckInterval, "lb-healthcheck-interval", 0, "use to set the health checker interval to check healthiness of former dead or unhealthy routes") flag.BoolVar(&cfg.ReverseSourcePredicate, "reverse-source-predicate", false, "reverse the order of finding the client IP from X-Forwarded-For header") flag.BoolVar(&cfg.RemoveHopHeaders, "remove-hop-headers", false, "enables removal of Hop-Headers according to RFC-2616") flag.BoolVar(&cfg.RfcPatchPath, "rfc-patch-path", false, "patches the incoming request path to preserve uncoded reserved characters according to RFC 2616 and RFC 3986") flag.IntVar(&cfg.MaxAuditBody, "max-audit-body", 1024, "sets the max body to read to log in the audit log body") flag.BoolVar(&cfg.EnableBreakers, "enable-breakers", false, enableBreakersUsage) flag.Var(&cfg.Breakers, "breaker", breakerUsage) flag.BoolVar(&cfg.EnableRatelimiters, "enable-ratelimits", false, enableRatelimitsUsage) flag.Var(&cfg.Ratelimits, "ratelimits", ratelimitsUsage) flag.BoolVar(&cfg.EnableRouteLIFOMetrics, "enable-route-lifo-metrics", false, "enable metrics for the individual route LIFO queues") flag.Var(cfg.MetricsFlavour, "metrics-flavour", "Metrics flavour is used to change the exposed metrics format. Supported metric formats: 'codahale' and 'prometheus', you can select both of them") flag.Var(cfg.FilterPlugins, "filter-plugin", "set a custom filter plugins to load, a comma separated list of name and arguments") flag.Var(cfg.PredicatePlugins, "predicate-plugin", "set a custom predicate plugins to load, a comma separated list of name and arguments") flag.Var(cfg.DataclientPlugins, "dataclient-plugin", "set a custom dataclient plugins to load, a comma separated list of name and arguments") flag.Var(cfg.MultiPlugins, "multi-plugin", "set a custom multitype plugins to load, a comma separated list of name and arguments") // logging, metrics, tracing: flag.BoolVar(&cfg.EnablePrometheusMetrics, "enable-prometheus-metrics", false, "*Deprecated*: use metrics-flavour. Switch to Prometheus metrics format to expose metrics") flag.StringVar(&cfg.OpenTracing, "opentracing", "noop", "list of arguments for opentracing (space separated), first argument is the tracer implementation") flag.StringVar(&cfg.OpenTracingInitialSpan, "opentracing-initial-span", "ingress", "set the name of the initial, pre-routing, tracing span") flag.StringVar(&cfg.OpenTracingExcludedProxyTags, "opentracing-excluded-proxy-tags", "", "set tags that should be excluded from spans created for proxy operation. must be a comma-separated list of strings.") flag.BoolVar(&cfg.OpentracingLogFilterLifecycleEvents, "opentracing-log-filter-lifecycle-events", true, "enables the logs for request & response filters' lifecycle events that are marking start & end times.") flag.BoolVar(&cfg.OpentracingLogStreamEvents, "opentracing-log-stream-events", true, "enables the logs for events marking the times response headers & payload are streamed to the client") flag.BoolVar(&cfg.OpentracingBackendNameTag, "opentracing-backend-name-tag", false, "enables an additional tracing tag that contains a backend name for a route when it's available (e.g. for RouteGroups) (default false)") flag.StringVar(&cfg.MetricsListener, "metrics-listener", ":9911", "network address used for exposing the /metrics endpoint. An empty value disables metrics iff support listener is also empty.") flag.StringVar(&cfg.MetricsPrefix, "metrics-prefix", "skipper.", "allows setting a custom path prefix for metrics export") flag.BoolVar(&cfg.EnableProfile, "enable-profile", false, "enable profile information on the metrics endpoint with path /pprof") flag.BoolVar(&cfg.DebugGcMetrics, "debug-gc-metrics", false, "enables reporting of the Go garbage collector statistics exported in debug.GCStats") flag.BoolVar(&cfg.RuntimeMetrics, "runtime-metrics", true, "enables reporting of the Go runtime statistics exported in runtime and specifically runtime.MemStats") flag.BoolVar(&cfg.ServeRouteMetrics, "serve-route-metrics", false, "enables reporting total serve time metrics for each route") flag.BoolVar(&cfg.ServeRouteCounter, "serve-route-counter", false, "enables reporting counting metrics for each route. Has the route, HTTP method and status code as labels. Currently just implemented for the Prometheus metrics flavour") flag.BoolVar(&cfg.ServeHostMetrics, "serve-host-metrics", false, "enables reporting total serve time metrics for each host") flag.BoolVar(&cfg.ServeHostCounter, "serve-host-counter", false, "enables reporting counting metrics for each host. Has the route, HTTP method and status code as labels. Currently just implemented for the Prometheus metrics flavour") flag.BoolVar(&cfg.ServeMethodMetric, "serve-method-metric", true, "enables the HTTP method as a domain of the total serve time metric. It affects both route and host splitted metrics") flag.BoolVar(&cfg.ServeStatusCodeMetric, "serve-status-code-metric", true, "enables the HTTP response status code as a domain of the total serve time metric. It affects both route and host splitted metrics") flag.BoolVar(&cfg.BackendHostMetrics, "backend-host-metrics", false, "enables reporting total serve time metrics for each backend") flag.BoolVar(&cfg.AllFiltersMetrics, "all-filters-metrics", false, "enables reporting combined filter metrics for each route") flag.BoolVar(&cfg.CombinedResponseMetrics, "combined-response-metrics", false, "enables reporting combined response time metrics") flag.BoolVar(&cfg.RouteResponseMetrics, "route-response-metrics", false, "enables reporting response time metrics for each route") flag.BoolVar(&cfg.RouteBackendErrorCounters, "route-backend-error-counters", false, "enables counting backend errors for each route") flag.BoolVar(&cfg.RouteStreamErrorCounters, "route-stream-error-counters", false, "enables counting streaming errors for each route") flag.BoolVar(&cfg.RouteBackendMetrics, "route-backend-metrics", false, "enables reporting backend response time metrics for each route") flag.BoolVar(&cfg.RouteCreationMetrics, "route-creation-metrics", false, "enables reporting for route creation times") flag.BoolVar(&cfg.MetricsUseExpDecaySample, "metrics-exp-decay-sample", false, "use exponentially decaying sample in metrics") flag.StringVar(&cfg.HistogramMetricBucketsString, "histogram-metric-buckets", "", "use custom buckets for prometheus histograms, must be a comma-separated list of numbers") flag.BoolVar(&cfg.DisableMetricsCompat, "disable-metrics-compat", false, "disables the default true value for all-filters-metrics, route-response-metrics, route-backend-errorCounters and route-stream-error-counters") flag.StringVar(&cfg.ApplicationLog, "application-log", "", "output file for the application log. When not set, /dev/stderr is used") flag.StringVar(&cfg.ApplicationLogLevelString, "application-log-level", "INFO", "log level for application logs, possible values: PANIC, FATAL, ERROR, WARN, INFO, DEBUG") flag.StringVar(&cfg.ApplicationLogPrefix, "application-log-prefix", "[APP]", "prefix for each log entry") flag.BoolVar(&cfg.ApplicationLogJSONEnabled, "application-log-json-enabled", false, "when this flag is set, log in JSON format is used") flag.StringVar(&cfg.AccessLog, "access-log", "", "output file for the access log, When not set, /dev/stderr is used") flag.BoolVar(&cfg.AccessLogDisabled, "access-log-disabled", false, "when this flag is set, no access log is printed") flag.BoolVar(&cfg.AccessLogJSONEnabled, "access-log-json-enabled", false, "when this flag is set, log in JSON format is used") flag.BoolVar(&cfg.AccessLogStripQuery, "access-log-strip-query", false, "when this flag is set, the access log strips the query strings from the access log") flag.BoolVar(&cfg.SuppressRouteUpdateLogs, "suppress-route-update-logs", false, "print only summaries on route updates/deletes") // route sources: flag.StringVar(&cfg.EtcdUrls, "etcd-urls", "", "urls of nodes in an etcd cluster, storing route definitions") flag.StringVar(&cfg.EtcdPrefix, "etcd-prefix", "/skipper", "path prefix for skipper related data in etcd") flag.DurationVar(&cfg.EtcdTimeout, "etcd-timeout", time.Second, "http client timeout duration for etcd") flag.BoolVar(&cfg.EtcdInsecure, "etcd-insecure", false, "ignore the verification of TLS certificates for etcd") flag.StringVar(&cfg.EtcdOAuthToken, "etcd-oauth-token", "", "optional token for OAuth authentication with etcd") flag.StringVar(&cfg.EtcdUsername, "etcd-username", "", "optional username for basic authentication with etcd") flag.StringVar(&cfg.EtcdPassword, "etcd-password", "", "optional password for basic authentication with etcd") flag.StringVar(&cfg.InnkeeperURL, "innkeeper-url", "", "API endpoint of the Innkeeper service, storing route definitions") flag.StringVar(&cfg.InnkeeperAuthToken, "innkeeper-auth-token", "", "fixed token for innkeeper authentication") flag.StringVar(&cfg.InnkeeperPreRouteFilters, "innkeeper-pre-route-filters", "", "filters to be prepended to each route loaded from Innkeeper") flag.StringVar(&cfg.InnkeeperPostRouteFilters, "innkeeper-post-route-filters", "", "filters to be appended to each route loaded from Innkeeper") flag.StringVar(&cfg.RoutesFile, "routes-file", "", "file containing route definitions") flag.StringVar(&cfg.InlineRoutes, "inline-routes", "", "inline routes in eskip format") flag.Int64Var(&cfg.SourcePollTimeout, "source-poll-timeout", int64(3000), "polling timeout of the routing data sources, in milliseconds") flag.Var(cfg.AppendFilters, "default-filters-append", "set of default filters to apply to append to all filters of all routes") flag.Var(cfg.PrependFilters, "default-filters-prepend", "set of default filters to apply to prepend to all filters of all routes") flag.BoolVar(&cfg.WaitFirstRouteLoad, "wait-first-route-load", false, "prevent starting the listener before the first batch of routes were loaded") // Kubernetes: flag.BoolVar(&cfg.KubernetesIngress, "kubernetes", false, "enables skipper to generate routes for ingress resources in kubernetes cluster") flag.BoolVar(&cfg.KubernetesInCluster, "kubernetes-in-cluster", false, "specify if skipper is running inside kubernetes cluster") flag.StringVar(&cfg.KubernetesURL, "kubernetes-url", "", "kubernetes API base URL for the ingress data client; requires kubectl proxy running; omit if kubernetes-in-cluster is set to true") flag.BoolVar(&cfg.KubernetesHealthcheck, "kubernetes-healthcheck", true, "automatic healthcheck route for internal IPs with path /kube-system/healthz; valid only with kubernetes") flag.BoolVar(&cfg.KubernetesHTTPSRedirect, "kubernetes-https-redirect", true, "automatic HTTP->HTTPS redirect route; valid only with kubernetes") flag.IntVar(&cfg.KubernetesHTTPSRedirectCode, "kubernetes-https-redirect-code", 308, "overrides the default redirect code (308) when used together with -kubernetes-https-redirect") flag.StringVar(&cfg.KubernetesIngressClass, "kubernetes-ingress-class", "", "ingress class regular expression used to filter ingress resources for kubernetes") flag.StringVar(&cfg.KubernetesRouteGroupClass, "kubernetes-routegroup-class", "", "route group class regular expression used to filter route group resources for kubernetes") flag.StringVar(&cfg.WhitelistedHealthCheckCIDR, "whitelisted-healthcheck-cidr", "", "sets the iprange/CIDRS to be whitelisted during healthcheck") flag.StringVar(&cfg.KubernetesPathModeString, "kubernetes-path-mode", "kubernetes-ingress", "controls the default interpretation of Kubernetes ingress paths: <kubernetes-ingress|path-regexp|path-prefix>") flag.StringVar(&cfg.KubernetesNamespace, "kubernetes-namespace", "", "watch only this namespace for ingresses") flag.BoolVar(&cfg.KubernetesEnableEastWest, "enable-kubernetes-east-west", false, "*Deprecated*: use kubernetes-east-west-range feature. Enables east-west communication, which automatically adds routes for Ingress objects with hostname <name>.<namespace>.skipper.cluster.local") flag.StringVar(&cfg.KubernetesEastWestDomain, "kubernetes-east-west-domain", "", "*Deprecated*: use kubernetes-east-west-range feature. Sets the east-west domain, defaults to .skipper.cluster.local") flag.Var(cfg.KubernetesEastWestRangeDomains, "kubernetes-east-west-range-domains", "set the the cluster internal domains for east west traffic. Identified routes to such domains will include the -kubernetes-east-west-range-predicates") flag.StringVar(&cfg.KubernetesEastWestRangePredicatesString, "kubernetes-east-west-range-predicates", "", "set the predicates that will be appended to routes identified as to -kubernetes-east-west-range-domains") // Auth: flag.BoolVar(&cfg.EnableOAuth2GrantFlow, "enable-oauth2-grant-flow", false, "enables OAuth2 Grant Flow filter") flag.StringVar(&cfg.OauthURL, "oauth-url", "", "OAuth2 URL for Innkeeper authentication") flag.StringVar(&cfg.OauthScope, "oauth-scope", "", "the whitespace separated list of oauth scopes") flag.StringVar(&cfg.OauthCredentialsDir, "oauth-credentials-dir", "", "directory where oauth credentials are stored: client.json and user.json") flag.StringVar(&cfg.Oauth2AuthURL, "oauth2-auth-url", "", "sets the OAuth2 Auth URL to redirect the requests to when login is required") flag.StringVar(&cfg.Oauth2TokenURL, "oauth2-token-url", "", "the url where the access code should be exchanged for the access token") flag.StringVar(&cfg.Oauth2RevokeTokenURL, "oauth2-revoke-token-url", "", "the url where the access and refresh tokens can be revoked when logging out") flag.StringVar(&cfg.Oauth2TokeninfoURL, "oauth2-tokeninfo-url", "", "sets the default tokeninfo URL to query information about an incoming OAuth2 token in oauth2Tokeninfo filters") flag.StringVar(&cfg.Oauth2SecretFile, "oauth2-secret-file", "", "sets the filename with the encryption key for the authentication cookie and grant flow state stored in secrets registry") flag.StringVar(&cfg.Oauth2ClientID, "oauth2-client-id", "", "sets the OAuth2 client id of the current service, used to exchange the access code") flag.StringVar(&cfg.Oauth2ClientSecret, "oauth2-client-secret", "", "sets the OAuth2 client secret associated with the oauth2-client-id, used to exchange the access code") flag.StringVar(&cfg.Oauth2ClientIDFile, "oauth2-client-id-file", "", "sets the path of the file containing the OAuth2 client id of the current service, used to exchange the access code") flag.StringVar(&cfg.Oauth2ClientSecretFile, "oauth2-client-secret-file", "", "sets the path of the file containing the OAuth2 client secret associated with the oauth2-client-id, used to exchange the access code") flag.StringVar(&cfg.Oauth2CallbackPath, "oauth2-callback-path", "", "sets the path where the OAuth2 callback requests with the authorization code should be redirected to") flag.DurationVar(&cfg.Oauth2TokeninfoTimeout, "oauth2-tokeninfo-timeout", 2*time.Second, "sets the default tokeninfo request timeout duration to 2000ms") flag.DurationVar(&cfg.Oauth2TokenintrospectionTimeout, "oauth2-tokenintrospect-timeout", 2*time.Second, "sets the default tokenintrospection request timeout duration to 2000ms") flag.Var(&cfg.Oauth2AuthURLParameters, "oauth2-auth-url-parameters", "sets additional parameters to send when calling the OAuth2 authorize or token endpoints as key-value pairs") flag.StringVar(&cfg.Oauth2AccessTokenHeaderName, "oauth2-access-token-header-name", "", "sets the access token to a header on the request with this name") flag.StringVar(&cfg.Oauth2TokeninfoSubjectKey, "oauth2-tokeninfo-subject-key", "uid", "sets the access token to a header on the request with this name") flag.StringVar(&cfg.Oauth2TokenCookieName, "oauth2-token-cookie-name", "oauth2-grant", "sets the name of the cookie where the encrypted token is stored") flag.DurationVar(&cfg.WebhookTimeout, "webhook-timeout", 2*time.Second, "sets the webhook request timeout duration") flag.StringVar(&cfg.OidcSecretsFile, "oidc-secrets-file", "", "file storing the encryption key of the OID Connect token") flag.Var(cfg.CredentialPaths, "credentials-paths", "directories or files to watch for credentials to use by bearerinjector filter") flag.DurationVar(&cfg.CredentialsUpdateInterval, "credentials-update-interval", 10*time.Minute, "sets the interval to update secrets") // TLS client certs flag.StringVar(&cfg.ClientKeyFile, "client-tls-key", "", "TLS Key file for backend connections, multiple keys may be given comma separated - the order must match the certs") flag.StringVar(&cfg.ClientCertFile, "client-tls-cert", "", "TLS certificate files for backend connections, multiple keys may be given comma separated - the order must match the keys") // TLS version flag.StringVar(&cfg.TLSMinVersion, "tls-min-version", defaultMinTLSVersion, "minimal TLS Version to be used in server, proxy and client connections") // API Monitoring: flag.BoolVar(&cfg.ApiUsageMonitoringEnable, "enable-api-usage-monitoring", false, "enables the apiUsageMonitoring filter") flag.StringVar(&cfg.ApiUsageMonitoringRealmKeys, "api-usage-monitoring-realm-keys", "", "name of the property in the JWT payload that contains the authority realm") flag.StringVar(&cfg.ApiUsageMonitoringClientKeys, "api-usage-monitoring-client-keys", "sub", "comma separated list of names of the properties in the JWT body that contains the client ID") flag.StringVar(&cfg.ApiUsageMonitoringDefaultClientTrackingPattern, "api-usage-monitoring-default-client-tracking-pattern", "", "*Deprecated*: set `client_tracking_pattern` directly on filter") flag.StringVar(&cfg.ApiUsageMonitoringRealmsTrackingPattern, "api-usage-monitoring-realms-tracking-pattern", "services", "regular expression used for matching monitored realms (defaults is 'services')") // Default filters: flag.StringVar(&cfg.DefaultFiltersDir, "default-filters-dir", "", "path to directory which contains default filter configurations per service and namespace (disabled if not set)") // Connections, timeouts: flag.DurationVar(&cfg.WaitForHealthcheckInterval, "wait-for-healthcheck-interval", (10+5)*3*time.Second, "period waiting to become unhealthy in the loadbalancer pool in front of this instance, before shutdown triggered by SIGINT or SIGTERM") // kube-ingress-aws-controller default flag.IntVar(&cfg.IdleConnsPerHost, "idle-conns-num", proxy.DefaultIdleConnsPerHost, "maximum idle connections per backend host") flag.DurationVar(&cfg.CloseIdleConnsPeriod, "close-idle-conns-period", proxy.DefaultCloseIdleConnsPeriod, "sets the time interval of closing all idle connections. Not closing when 0") flag.DurationVar(&cfg.BackendFlushInterval, "backend-flush-interval", 20*time.Millisecond, "flush interval for upgraded proxy connections") flag.BoolVar(&cfg.ExperimentalUpgrade, "experimental-upgrade", false, "enable experimental feature to handle upgrade protocol requests") flag.BoolVar(&cfg.ExperimentalUpgradeAudit, "experimental-upgrade-audit", false, "enable audit logging of the request line and the messages during the experimental web socket upgrades") flag.DurationVar(&cfg.ReadTimeoutServer, "read-timeout-server", 5*time.Minute, "set ReadTimeout for http server connections") flag.DurationVar(&cfg.ReadHeaderTimeoutServer, "read-header-timeout-server", 60*time.Second, "set ReadHeaderTimeout for http server connections") flag.DurationVar(&cfg.WriteTimeoutServer, "write-timeout-server", 60*time.Second, "set WriteTimeout for http server connections") flag.DurationVar(&cfg.IdleTimeoutServer, "idle-timeout-server", 60*time.Second, "set IdleTimeout for http server connections") flag.IntVar(&cfg.MaxHeaderBytes, "max-header-bytes", http.DefaultMaxHeaderBytes, "set MaxHeaderBytes for http server connections") flag.BoolVar(&cfg.EnableConnMetricsServer, "enable-connection-metrics", false, "enables connection metrics for http server connections") flag.DurationVar(&cfg.TimeoutBackend, "timeout-backend", 60*time.Second, "sets the TCP client connection timeout for backend connections") flag.DurationVar(&cfg.KeepaliveBackend, "keepalive-backend", 30*time.Second, "sets the keepalive for backend connections") flag.BoolVar(&cfg.EnableDualstackBackend, "enable-dualstack-backend", true, "enables DualStack for backend connections") flag.DurationVar(&cfg.TlsHandshakeTimeoutBackend, "tls-timeout-backend", 60*time.Second, "sets the TLS handshake timeout for backend connections") flag.DurationVar(&cfg.ResponseHeaderTimeoutBackend, "response-header-timeout-backend", 60*time.Second, "sets the HTTP response header timeout for backend connections") flag.DurationVar(&cfg.ExpectContinueTimeoutBackend, "expect-continue-timeout-backend", 30*time.Second, "sets the HTTP expect continue timeout for backend connections") flag.IntVar(&cfg.MaxIdleConnsBackend, "max-idle-connection-backend", 0, "sets the maximum idle connections for all backend connections") flag.BoolVar(&cfg.DisableHTTPKeepalives, "disable-http-keepalives", false, "forces backend to always create a new connection") // Swarm: flag.BoolVar(&cfg.EnableSwarm, "enable-swarm", false, "enable swarm communication between nodes in a skipper fleet") flag.Var(cfg.SwarmRedisURLs, "swarm-redis-urls", "Redis URLs as comma separated list, used for building a swarm, for example in redis based cluster ratelimits.\nUse "+redisPasswordEnv+" environment variable or 'swarm-redis-password' key in config file to set redis password") flag.StringVar(&cfg.SwarmRedisHashAlgorithm, "swarm-redis-hash-algorithm", "", "sets hash algorithm to be used in redis ring client to find the shard <jump|mpchash|rendezvous|rendezvousVnodes>, defaults to github.com/go-redis/redis default") flag.DurationVar(&cfg.SwarmRedisDialTimeout, "swarm-redis-dial-timeout", net.DefaultDialTimeout, "set redis client dial timeout") flag.DurationVar(&cfg.SwarmRedisReadTimeout, "swarm-redis-read-timeout", net.DefaultReadTimeout, "set redis socket read timeout") flag.DurationVar(&cfg.SwarmRedisWriteTimeout, "swarm-redis-write-timeout", net.DefaultWriteTimeout, "set redis socket write timeout") flag.DurationVar(&cfg.SwarmRedisPoolTimeout, "swarm-redis-pool-timeout", net.DefaultPoolTimeout, "set redis get connection from pool timeout") flag.IntVar(&cfg.SwarmRedisMinConns, "swarm-redis-min-conns", net.DefaultMinConns, "set min number of connections to redis") flag.IntVar(&cfg.SwarmRedisMaxConns, "swarm-redis-max-conns", net.DefaultMaxConns, "set max number of connections to redis") flag.StringVar(&cfg.SwarmKubernetesNamespace, "swarm-namespace", swarm.DefaultNamespace, "Kubernetes namespace to find swarm peer instances") flag.StringVar(&cfg.SwarmKubernetesLabelSelectorKey, "swarm-label-selector-key", swarm.DefaultLabelSelectorKey, "Kubernetes labelselector key to find swarm peer instances") flag.StringVar(&cfg.SwarmKubernetesLabelSelectorValue, "swarm-label-selector-value", swarm.DefaultLabelSelectorValue, "Kubernetes labelselector value to find swarm peer instances") flag.IntVar(&cfg.SwarmPort, "swarm-port", swarm.DefaultPort, "swarm port to use to communicate with our peers") flag.IntVar(&cfg.SwarmMaxMessageBuffer, "swarm-max-msg-buffer", swarm.DefaultMaxMessageBuffer, "swarm max message buffer size to use for member list messages") flag.DurationVar(&cfg.SwarmLeaveTimeout, "swarm-leave-timeout", swarm.DefaultLeaveTimeout, "swarm leave timeout to use for leaving the memberlist on timeout") flag.StringVar(&cfg.SwarmStaticSelf, "swarm-static-self", "", "set static swarm self node, for example 127.0.0.1:9001") flag.StringVar(&cfg.SwarmStaticOther, "swarm-static-other", "", "set static swarm all nodes, for example 127.0.0.1:9002,127.0.0.1:9003") return cfg } func (c *Config) Parse() error { flag.Parse() // check if arguments were correctly parsed. if len(flag.Args()) != 0 { return fmt.Errorf("invalid arguments: %s", flag.Args()) } configKeys := make(map[string]interface{}) if c.ConfigFile != "" { yamlFile, err := ioutil.ReadFile(c.ConfigFile) if err != nil { return fmt.Errorf("invalid config file: %v", err) } err = yaml.Unmarshal(yamlFile, c) if err != nil { return fmt.Errorf("unmarshalling config file error: %v", err) } _ = yaml.Unmarshal(yamlFile, configKeys) flag.Parse() } checkDeprecated(configKeys, "enable-prometheus-metrics", "api-usage-monitoring-default-client-tracking-pattern", "enable-kubernetes-east-west", "kubernetes-east-west-domain", ) logLevel, err := log.ParseLevel(c.ApplicationLogLevelString) if err != nil { return err } kubernetesPathMode, err := kubernetes.ParsePathMode(c.KubernetesPathModeString) if err != nil { return err } kubernetesEastWestRangePredicates, err := eskip.ParsePredicates(c.KubernetesEastWestRangePredicatesString) if err != nil { return fmt.Errorf("invalid east-west-range-predicates: %w", err) } histogramBuckets, err := c.parseHistogramBuckets() if err != nil { return err } c.ApplicationLogLevel = logLevel c.KubernetesPathMode = kubernetesPathMode c.KubernetesEastWestRangePredicates = kubernetesEastWestRangePredicates c.HistogramMetricBuckets = histogramBuckets if c.ClientKeyFile != "" && c.ClientCertFile != "" { certsFiles := strings.Split(c.ClientCertFile, ",") keyFiles := strings.Split(c.ClientKeyFile, ",") var certificates []tls.Certificate for i := range keyFiles { certificate, err := tls.LoadX509KeyPair(certsFiles[i], keyFiles[i]) if err != nil { return fmt.Errorf("invalid key/cert pair: %v", err) } certificates = append(certificates, certificate) } c.Certificates = certificates } c.parseEnv() return nil } func (c *Config) ToOptions() skipper.Options { var eus []string if len(c.EtcdUrls) > 0 { eus = strings.Split(c.EtcdUrls, ",") } var whitelistCIDRS []string if len(c.WhitelistedHealthCheckCIDR) > 0 { whitelistCIDRS = strings.Split(c.WhitelistedHealthCheckCIDR, ",") } options := skipper.Options{ // generic: Address: c.Address, StatusChecks: c.StatusChecks.values, EnableTCPQueue: c.EnableTCPQueue, ExpectedBytesPerRequest: c.ExpectedBytesPerRequest, MaxTCPListenerConcurrency: c.MaxTCPListenerConcurrency, MaxTCPListenerQueue: c.MaxTCPListenerQueue, IgnoreTrailingSlash: c.IgnoreTrailingSlash, DevMode: c.DevMode, SupportListener: c.SupportListener, DebugListener: c.DebugListener, CertPathTLS: c.CertPathTLS, KeyPathTLS: c.KeyPathTLS, MaxLoopbacks: c.MaxLoopbacks, DefaultHTTPStatus: c.DefaultHTTPStatus, LoadBalancerHealthCheckInterval: c.LoadBalancerHealthCheckInterval, ReverseSourcePredicate: c.ReverseSourcePredicate, MaxAuditBody: c.MaxAuditBody, EnableBreakers: c.EnableBreakers, BreakerSettings: c.Breakers, EnableRatelimiters: c.EnableRatelimiters, RatelimitSettings: c.Ratelimits, EnableRouteLIFOMetrics: c.EnableRouteLIFOMetrics, MetricsFlavours: c.MetricsFlavour.values, FilterPlugins: c.FilterPlugins.values, PredicatePlugins: c.PredicatePlugins.values, DataClientPlugins: c.DataclientPlugins.values, Plugins: c.MultiPlugins.values, PluginDirs: []string{skipper.DefaultPluginDir}, // logging, metrics, tracing: EnablePrometheusMetrics: c.EnablePrometheusMetrics, OpenTracing: strings.Split(c.OpenTracing, " "), OpenTracingInitialSpan: c.OpenTracingInitialSpan, OpenTracingExcludedProxyTags: strings.Split(c.OpenTracingExcludedProxyTags, ","), OpenTracingLogStreamEvents: c.OpentracingLogStreamEvents, OpenTracingLogFilterLifecycleEvents: c.OpentracingLogFilterLifecycleEvents, MetricsListener: c.MetricsListener, MetricsPrefix: c.MetricsPrefix, EnableProfile: c.EnableProfile, EnableDebugGcMetrics: c.DebugGcMetrics, EnableRuntimeMetrics: c.RuntimeMetrics, EnableServeRouteMetrics: c.ServeRouteMetrics, EnableServeRouteCounter: c.ServeRouteCounter, EnableServeHostMetrics: c.ServeHostMetrics, EnableServeHostCounter: c.ServeHostCounter, EnableServeMethodMetric: c.ServeMethodMetric, EnableServeStatusCodeMetric: c.ServeStatusCodeMetric, EnableBackendHostMetrics: c.BackendHostMetrics, EnableAllFiltersMetrics: c.AllFiltersMetrics, EnableCombinedResponseMetrics: c.CombinedResponseMetrics, EnableRouteResponseMetrics: c.RouteResponseMetrics, EnableRouteBackendErrorsCounters: c.RouteBackendErrorCounters, EnableRouteStreamingErrorsCounters: c.RouteStreamErrorCounters, EnableRouteBackendMetrics: c.RouteBackendMetrics, EnableRouteCreationMetrics: c.RouteCreationMetrics, MetricsUseExpDecaySample: c.MetricsUseExpDecaySample, HistogramMetricBuckets: c.HistogramMetricBuckets, DisableMetricsCompatibilityDefaults: c.DisableMetricsCompat, ApplicationLogOutput: c.ApplicationLog, ApplicationLogPrefix: c.ApplicationLogPrefix, ApplicationLogJSONEnabled: c.ApplicationLogJSONEnabled, AccessLogOutput: c.AccessLog, AccessLogDisabled: c.AccessLogDisabled, AccessLogJSONEnabled: c.AccessLogJSONEnabled, AccessLogStripQuery: c.AccessLogStripQuery, SuppressRouteUpdateLogs: c.SuppressRouteUpdateLogs, // route sources: EtcdUrls: eus, EtcdPrefix: c.EtcdPrefix, EtcdWaitTimeout: c.EtcdTimeout, EtcdInsecure: c.EtcdInsecure, EtcdOAuthToken: c.EtcdOAuthToken, EtcdUsername: c.EtcdUsername, EtcdPassword: c.EtcdPassword, InnkeeperUrl: c.InnkeeperURL, InnkeeperAuthToken: c.InnkeeperAuthToken, InnkeeperPreRouteFilters: c.InnkeeperPreRouteFilters, InnkeeperPostRouteFilters: c.InnkeeperPostRouteFilters, WatchRoutesFile: c.RoutesFile, InlineRoutes: c.InlineRoutes, DefaultFilters: &eskip.DefaultFilters{ Prepend: c.PrependFilters.filters, Append: c.AppendFilters.filters,
// Kubernetes: Kubernetes: c.KubernetesIngress, KubernetesInCluster: c.KubernetesInCluster, KubernetesURL: c.KubernetesURL, KubernetesHealthcheck: c.KubernetesHealthcheck, KubernetesHTTPSRedirect: c.KubernetesHTTPSRedirect, KubernetesHTTPSRedirectCode: c.KubernetesHTTPSRedirectCode, KubernetesIngressClass: c.KubernetesIngressClass, KubernetesRouteGroupClass: c.KubernetesRouteGroupClass, WhitelistedHealthCheckCIDR: whitelistCIDRS, KubernetesPathMode: c.KubernetesPathMode, KubernetesNamespace: c.KubernetesNamespace, KubernetesEnableEastWest: c.KubernetesEnableEastWest, KubernetesEastWestDomain: c.KubernetesEastWestDomain, KubernetesEastWestRangeDomains: c.KubernetesEastWestRangeDomains.values, KubernetesEastWestRangePredicates: c.KubernetesEastWestRangePredicates, // API Monitoring: ApiUsageMonitoringEnable: c.ApiUsageMonitoringEnable, ApiUsageMonitoringRealmKeys: c.ApiUsageMonitoringRealmKeys, ApiUsageMonitoringClientKeys: c.ApiUsageMonitoringClientKeys, ApiUsageMonitoringRealmsTrackingPattern: c.ApiUsageMonitoringRealmsTrackingPattern, // Default filters: DefaultFiltersDir: c.DefaultFiltersDir, // Auth: EnableOAuth2GrantFlow: c.EnableOAuth2GrantFlow, OAuthUrl: c.OauthURL, OAuthScope: c.OauthScope, OAuthCredentialsDir: c.OauthCredentialsDir, OAuth2AuthURL: c.Oauth2AuthURL, OAuth2TokenURL: c.Oauth2TokenURL, OAuth2RevokeTokenURL: c.Oauth2RevokeTokenURL, OAuthTokeninfoURL: c.Oauth2TokeninfoURL, OAuthTokeninfoTimeout: c.Oauth2TokeninfoTimeout, OAuth2SecretFile: c.Oauth2SecretFile, OAuth2ClientID: c.Oauth2ClientID, OAuth2ClientSecret: c.Oauth2ClientSecret, OAuth2ClientIDFile: c.Oauth2ClientIDFile, OAuth2ClientSecretFile: c.Oauth2ClientSecretFile, OAuth2CallbackPath: c.Oauth2CallbackPath, OAuthTokenintrospectionTimeout: c.Oauth2TokenintrospectionTimeout, OAuth2AuthURLParameters: c.Oauth2AuthURLParameters.values, OAuth2AccessTokenHeaderName: c.Oauth2AccessTokenHeaderName, OAuth2TokeninfoSubjectKey: c.Oauth2TokeninfoSubjectKey, OAuth2TokenCookieName: c.Oauth2TokenCookieName, WebhookTimeout: c.WebhookTimeout, OIDCSecretsFile: c.OidcSecretsFile, CredentialsPaths: c.CredentialPaths.values, CredentialsUpdateInterval: c.CredentialsUpdateInterval, // connections, timeouts: WaitForHealthcheckInterval: c.WaitForHealthcheckInterval, IdleConnectionsPerHost: c.IdleConnsPerHost, CloseIdleConnsPeriod: c.CloseIdleConnsPeriod, BackendFlushInterval: c.BackendFlushInterval, ExperimentalUpgrade: c.ExperimentalUpgrade, ExperimentalUpgradeAudit: c.ExperimentalUpgradeAudit, ReadTimeoutServer: c.ReadTimeoutServer, ReadHeaderTimeoutServer: c.ReadHeaderTimeoutServer, WriteTimeoutServer: c.WriteTimeoutServer, IdleTimeoutServer: c.IdleTimeoutServer, MaxHeaderBytes: c.MaxHeaderBytes, EnableConnMetricsServer: c.EnableConnMetricsServer, TimeoutBackend: c.TimeoutBackend, KeepAliveBackend: c.KeepaliveBackend, DualStackBackend: c.EnableDualstackBackend, TLSHandshakeTimeoutBackend: c.TlsHandshakeTimeoutBackend, ResponseHeaderTimeoutBackend: c.ResponseHeaderTimeoutBackend, ExpectContinueTimeoutBackend: c.ExpectContinueTimeoutBackend, MaxIdleConnsBackend: c.MaxIdleConnsBackend, DisableHTTPKeepalives: c.DisableHTTPKeepalives, // swarm: EnableSwarm: c.EnableSwarm, // redis based SwarmRedisURLs: c.SwarmRedisURLs.values, SwarmRedisPassword: c.SwarmRedisPassword, SwarmRedisHashAlgorithm: c.SwarmRedisHashAlgorithm, SwarmRedisDialTimeout: c.SwarmRedisDialTimeout, SwarmRedisReadTimeout: c.SwarmRedisReadTimeout, SwarmRedisWriteTimeout: c.SwarmRedisWriteTimeout, SwarmRedisPoolTimeout: c.SwarmRedisPoolTimeout, SwarmRedisMinIdleConns: c.SwarmRedisMinConns, SwarmRedisMaxIdleConns: c.SwarmRedisMaxConns, // swim based SwarmKubernetesNamespace: c.SwarmKubernetesNamespace, SwarmKubernetesLabelSelectorKey: c.SwarmKubernetesLabelSelectorKey, SwarmKubernetesLabelSelectorValue: c.SwarmKubernetesLabelSelectorValue, SwarmPort: c.SwarmPort, SwarmMaxMessageBuffer: c.SwarmMaxMessageBuffer, SwarmLeaveTimeout: c.SwarmLeaveTimeout, // swim on localhost for testing SwarmStaticSelf: c.SwarmStaticSelf, SwarmStaticOther: c.SwarmStaticOther, } if c.PluginDir != "" { options.PluginDirs = append(options.PluginDirs, c.PluginDir) } if c.Insecure { options.ProxyFlags |= proxy.Insecure } if c.ProxyPreserveHost { options.ProxyFlags |= proxy.PreserveHost } if c.RemoveHopHeaders { options.ProxyFlags |= proxy.HopHeadersRemoval } if c.RfcPatchPath { options.ProxyFlags |= proxy.PatchPath } if c.Certificates != nil && len(c.Certificates) > 0 { options.ClientTLS = &tls.Config{ Certificates: c.Certificates, MinVersion: c.getMinTLSVersion(), } } return options } func (c *Config) getMinTLSVersion() uint16 { tlsVersionTable := map[string]uint16{ "1.3": tls.VersionTLS13, "13": tls.VersionTLS13, "1.2": tls.VersionTLS12, "12": tls.VersionTLS12, "1.1": tls.VersionTLS11, "11": tls.VersionTLS11, "1.0": tls.VersionTLS10, "10": tls.VersionTLS10, } if v, ok := tlsVersionTable[c.TLSMinVersion]; ok { return v } log.Infof("No valid minimal TLS version confiured (set to '%s'), fallback to default: %s", c.TLSMinVersion, defaultMinTLSVersion) return tlsVersionTable[defaultMinTLSVersion] } func (c *Config) parseHistogramBuckets() ([]float64, error) { if c.HistogramMetricBucketsString == "" { return prometheus.DefBuckets, nil } var result []float64 thresholds := strings.Split(c.HistogramMetricBucketsString, ",") for _, v := range thresholds { bucket, err := strconv.ParseFloat(strings.TrimSpace(v), 64) if err != nil { return nil, fmt.Errorf("unable to parse histogram-metric-buckets: %v", err) } result = append(result, bucket) } sort.Float64s(result) return result, nil } func (c *Config) parseEnv() { // Set Redis password from environment variable if not set earlier (configuration file) if c.SwarmRedisPassword == "" { c.SwarmRedisPassword = os.Getenv(redisPasswordEnv) } } func checkDeprecated(configKeys map[string]interface{}, options ...string) { flagKeys := make(map[string]bool) flag.Visit(func(f *flag.Flag) { flagKeys[f.Name] = true }) for _, name := range options { _, ck := configKeys[name] _, fk := flagKeys[name] if ck || fk { f := flag.Lookup(name) log.Warnf("%s: %s", f.Name, f.Usage) } } }
}, SourcePollTimeout: time.Duration(c.SourcePollTimeout) * time.Millisecond, WaitFirstRouteLoad: c.WaitFirstRouteLoad,
GLN.py
from tests.util import pick_ray from pyrosetta import Pose from pyrosetta.rosetta.core.import_pose import pose_from_pdbstring name = "GLN" contents = """ ATOM 1 N ALA A 1 0.000 0.000 0.000 1.00 0.00 N ATOM 2 CA ALA A 1 1.458 0.000 0.000 1.00 0.00 C ATOM 3 C ALA A 1 2.009 1.420 0.000 1.00 0.00 C ATOM 4 O ALA A 1 1.251 2.390 0.000 1.00 0.00 O ATOM 5 CB ALA A 1 1.988 -0.773 -1.199 1.00 0.00 C ATOM 6 1H ALA A 1 -0.334 -0.943 -0.000 1.00 0.00 H ATOM 7 2H ALA A 1 -0.334 0.471 0.816 1.00 0.00 H ATOM 8 3H ALA A 1 -0.334 0.471 -0.816 1.00 0.00 H ATOM 9 HA ALA A 1 1.797 -0.490 0.913 1.00 0.00 H ATOM 10 1HB ALA A 1 3.078 -0.764 -1.185 1.00 0.00 H ATOM 11 2HB ALA A 1 1.633 -1.802 -1.154 1.00 0.00 H ATOM 12 3HB ALA A 1 1.633 -0.307 -2.117 1.00 0.00 H ATOM 13 N GLN A 2 3.332 1.536 0.000 1.00 0.00 N ATOM 14 CA GLN A 2 3.988 2.839 0.000 1.00 0.00 C ATOM 15 C GLN A 2 5.504 2.693 0.000 1.00 0.00 C ATOM 16 O GLN A 2 6.030 1.580 0.000 1.00 0.00 O ATOM 17 CB GLN A 2 3.542 3.663 1.211 1.00 0.00 C ATOM 18 CG GLN A 2 2.545 2.955 2.113 1.00 0.00 C ATOM 19 CD GLN A 2 2.200 1.564 1.615 1.00 0.00 C ATOM 20 OE1 GLN A 2 2.707 1.116 0.583 1.00 0.00 O ATOM 21 NE2 GLN A 2 1.333 0.873 2.346 1.00 0.00 N ATOM 22 H GLN A 2 3.899 0.700 0.000 1.00 0.00 H ATOM 23 HA GLN A 2 3.702 3.361 -0.913 1.00 0.00 H ATOM 24 1HB GLN A 2 4.412 3.926 1.812 1.00 0.00 H ATOM 25 2HB GLN A 2 3.086 4.592 0.870 1.00 0.00 H ATOM 26 1HG GLN A 2 2.975 2.864 3.111 1.00 0.00 H ATOM 27 2HG GLN A 2 1.627 3.541 2.153 1.00 0.00 H ATOM 28 1HE2 GLN A 2 1.066 -0.050 2.067 1.00 0.00 H ATOM 29 2HE2 GLN A 2 0.945 1.275 3.176 1.00 0.00 H ATOM 30 N ALA A 3 6.202 3.823 0.000 1.00 0.00 N ATOM 31 CA ALA A 3 7.660 3.823 0.000 1.00 0.00 C ATOM 32 C ALA A 3 8.211 5.243 0.000 1.00 0.00 C ATOM 33 O ALA A 3 8.260 5.868 1.023 1.00 0.00 O ATOM 34 OXT ALA A 3 8.596 5.737 -1.023 1.00 0.00 O ATOM 35 CB ALA A 3 8.190 3.050 -1.199 1.00 0.00 C ATOM 36 H ALA A 3 5.710 4.705 -0.000 1.00 0.00 H ATOM 37 HA ALA A 3 7.999 3.333 0.913 1.00 0.00 H ATOM 38 1HB ALA A 3 9.280 3.059 -1.185 1.00 0.00 H ATOM 39 2HB ALA A 3 7.835 2.021 -1.154 1.00 0.00 H ATOM 40 3HB ALA A 3 7.835 3.516 -2.117 1.00 0.00 H TER """ pose = Pose() pose_from_pdbstring(pose, contents) n_rays = { 1: pick_ray(pose.residue(1), "1H", "N"), 2: pick_ray(pose.residue(2), "H", "N"), 3: pick_ray(pose.residue(3), "H", "N") } c_rays = { 1: pick_ray(pose.residue(1), "O", "C"), 2: pick_ray(pose.residue(2), "O", "C"), 3: pick_ray(pose.residue(3), "O", "C") } sc_donor = { 2: [ pick_ray(pose.residue(2), "1HE2", "NE2"), pick_ray(pose.residue(2), "2HE2", "NE2")
} sc_acceptor = { 2: [ pick_ray(pose.residue(2), "OE1", "CD") ] } cat_pi = [ ]
]
Slicer.py
#! /usr/bin/env python3 # -*- coding: utf-8 -*- import sys from common.Utilities import get_code, error_exit from ast import ASTGenerator import Extractor import Oracle import Logger import Filter import Emitter def slice_code_from_trace(diff_info, trace_list, path_a, path_b): Logger.trace(__name__ + ":" + sys._getframe().f_code.co_name, locals()) # print(diff_info) for diff_loc in diff_info: source_file, start_line = diff_loc.split(":") source_file = source_file.replace(path_a, path_b) skip_lines = list()
start_line, end_line = diff_loc_info['new-lines'] line_numbers = set(range(int(start_line), int(end_line) + 1)) # print(line_numbers) for line_number in line_numbers: # print(line_number) loc_id = source_file + ":" + str(line_number) if loc_id not in trace_list: if Oracle.is_declaration_line(source_file, line_number): skip_lines.append(line_number) if Oracle.is_loc_in_if_cond(source_file, line_number): continue statement = get_code(source_file, line_number) # print(statement) # if "if" in statement: # continue if "}" in statement: continue if "{" in statement: continue skip_lines.append(line_number) # print(skip_lines) diff_loc_info['skip-lines'] = skip_lines diff_info[diff_loc] = diff_loc_info # print(diff_info) return diff_info def slice_skipped_diff_locs(diff_info): Logger.trace(__name__ + ":" + sys._getframe().f_code.co_name, locals()) filtered_diff_info = dict() for diff_loc in diff_info: diff_loc_info = diff_info[diff_loc] if 'new-lines' in diff_loc_info.keys(): start_line, end_line = diff_loc_info['new-lines'] line_numbers = set(range(int(start_line), int(end_line) + 1)) skip_lines = diff_loc_info['skip-lines'] if set(line_numbers) == set(skip_lines): continue ast_script = diff_loc_info['ast-script'] if not ast_script: continue filtered_diff_info[diff_loc] = diff_loc_info if not filtered_diff_info: error_exit("no AST changes to be transplanted") return filtered_diff_info def slice_ast_script(diff_info, project_path_a, project_path_b, trace_list): Logger.trace(__name__ + ":" + sys._getframe().f_code.co_name, locals()) filtered_diff_info = dict() for diff_loc in diff_info: diff_loc_info = diff_info[diff_loc] # print(diff_loc) # print(diff_loc_info) Emitter.special("\t" + diff_loc) skip_lines = diff_loc_info['skip-lines'] # print(skip_lines) ast_script = diff_loc_info['ast-script'] operation = diff_loc_info['operation'] # print(ast_script) source_path_a, line_number_a = diff_loc.split(":") source_path_b = str(source_path_a).replace(project_path_a, project_path_b) try: ast_map_a = ASTGenerator.get_ast_json(source_path_a) ast_map_b = ASTGenerator.get_ast_json(source_path_b) except: continue if ast_map_a is None or ast_map_b is None: continue filtered_ast_script = Filter.filter_ast_script_by_skip_line(ast_script, ast_map_a, ast_map_b, skip_lines, operation ) # print(filtered_ast_script) filtered_ast_script = Filter.filter_ast_script_by_node_type(filtered_ast_script, ast_map_a, ast_map_b, trace_list, source_path_b ) # print(filtered_ast_script) diff_loc_info['ast-script'] = filtered_ast_script filtered_diff_info[diff_loc] = diff_loc_info # print(filtered_ast_script) return filtered_diff_info def slice_function_calls(diff_info, sym_path_list, path_a, path_b): Logger.trace(__name__ + ":" + sys._getframe().f_code.co_name, locals()) for diff_loc in diff_info: source_file, start_line = diff_loc.split(":") source_file = source_file.replace(path_a, path_b) diff_loc_info = diff_info[diff_loc] skip_lines = diff_loc_info['skip-lines'] if 'new-lines' in diff_loc_info.keys(): function_call_node_list = Extractor.extract_function_call_list(source_file, start_line) start_line, end_line = diff_loc_info['new-lines'] line_numbers = set(range(int(start_line), int(end_line) + 1)) for line_number in line_numbers: loc_id = source_file + ":" + str(line_number) if line_number in function_call_node_list.keys(): # print(loc_id) # print(skip_lines) if not Oracle.is_function_important(source_file, function_call_node_list[line_number], sym_path_list ): skip_lines.append(line_number) # print(skip_lines) diff_loc_info['skip-lines'] = skip_lines diff_info[diff_loc] = diff_loc_info return diff_info def slice_redundant_patches(diff_info, suspicious_locs): Logger.trace(__name__ + ":" + sys._getframe().f_code.co_name, locals()) filtered_diff_info = dict() inserted_similar_loc_list = list() for diff_loc in diff_info: source_path, start_line = diff_loc.split(":") source_file = source_path.split("/")[-1] patch_loc = source_file + ":" + start_line if patch_loc in suspicious_locs.keys(): bug_reason = suspicious_locs[patch_loc] # print(patch_loc) similar_loc_list = list() for suspicious_loc in suspicious_locs: if suspicious_locs[suspicious_loc] == bug_reason: similar_loc_list.append(suspicious_loc) # print(similar_loc_list) redundant = False for similar_loc in similar_loc_list: if similar_loc in inserted_similar_loc_list: redundant = True break # print(redundant) if not redundant: filtered_diff_info[diff_loc] = diff_info[diff_loc] inserted_similar_loc_list.append(patch_loc) else: filtered_diff_info[diff_loc] = diff_info[diff_loc] return filtered_diff_info
diff_loc_info = diff_info[diff_loc] # print(diff_loc) if 'new-lines' in diff_loc_info.keys():
exceptions.py
""" geonames/exceptions ~~~~~~~~~~~~~~~~~~~ """ from . import base def ignore_foreign_key_constraint(db, options, record: base.T, exception: Exception) -> bool:
def ignore_unique_key_constraint(db, options, record: base.T, exception: Exception) -> bool: return 'UNIQUE constraint failed' in str(exception)
return 'FOREIGN KEY constraint failed' in str(exception)
utils.py
# Licensed to Modin Development Team under one or more contributor license agreements. # See the NOTICE file distributed with this work for additional information regarding # copyright ownership. The Modin Development Team licenses this file to you 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 # the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific language # governing permissions and limitations under the License. import pytest import numpy as np import math import pandas from pandas.testing import ( assert_series_equal, assert_frame_equal, assert_index_equal, assert_extension_array_equal, ) import modin.pandas as pd from modin.utils import to_pandas from modin.config import TestDatasetSize, TrackFileLeaks from io import BytesIO import os from string import ascii_letters import csv import psutil import functools random_state = np.random.RandomState(seed=42) DATASET_SIZE_DICT = { "Small": (2 ** 2, 2 ** 3), "Normal": (2 ** 6, 2 ** 8), "Big": (2 ** 7, 2 ** 12), } # Size of test dataframes NCOLS, NROWS = DATASET_SIZE_DICT.get(TestDatasetSize.get(), DATASET_SIZE_DICT["Normal"]) # Range for values for test data RAND_LOW = 0 RAND_HIGH = 100 # Directory for storing I/O operations test data IO_OPS_DATA_DIR = os.path.join(os.path.dirname(__file__), "io_tests_data") # Input data and functions for the tests # The test data that we will test our code against test_data = { # "empty_data": {}, # "columns_only": {"col1": [], "col2": [], "col3": [], "col4": [], "col5": []}, "int_data": { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): random_state.randint( RAND_LOW, RAND_HIGH, size=(NROWS) ) for i in range(NCOLS) }, "float_nan_data": { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): [ x if (j % 4 == 0 and i > NCOLS // 2) or (j != i and i <= NCOLS // 2) else np.NaN for j, x in enumerate( random_state.uniform(RAND_LOW, RAND_HIGH, size=(NROWS)) ) ] for i in range(NCOLS) }, # "int_float_object_data": { # "col3": [1, 2, 3, 4], # "col4": [4, 5, 6, 7], # "col1": [8.0, 9.4, 10.1, 11.3], # "col2": ["a", "b", "c", "d"], # }, # "datetime_timedelta_data": { # "col3": [ # np.datetime64("2010"), # np.datetime64("2011"), # np.datetime64("2011-06-15T00:00"), # np.datetime64("2009-01-01"), # ], # "col4": [ # np.datetime64("2010"), # np.datetime64("2011"), # np.datetime64("2011-06-15T00:00"), # np.datetime64("2009-01-01"), # ], # "col1": [ # np.timedelta64(1, "M"), # np.timedelta64(2, "D"), # np.timedelta64(3, "Y"), # np.timedelta64(20, "D"), # ], # "col2": [ # np.timedelta64(1, "M"), # np.timedelta64(2, "D"), # np.timedelta64(3, "Y"), # np.timedelta64(20, "D"), # ], # }, # "all_data": { # "col3": 1.0, # "col4": np.datetime64("2011-06-15T00:00"), # "col5": np.array([3] * 4, dtype="int32"), # "col1": "foo", # "col2": True, # }, } # See details in #1403 test_data["int_data"]["index"] = test_data["int_data"].pop( "col{}".format(int(NCOLS / 2)) ) for col in test_data["float_nan_data"]: for row in range(NROWS // 2): if row % 16 == 0: test_data["float_nan_data"][col][row] = np.NaN test_data_values = list(test_data.values()) test_data_keys = list(test_data.keys()) test_bool_data = { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): random_state.choice( [True, False], size=(NROWS) ) for i in range(NCOLS) } test_data_resample = { "data": {"A": range(12), "B": range(12)}, "index": pandas.date_range("31/12/2000", periods=12, freq="H"), } test_data_with_duplicates = { "no_duplicates": { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): range(NROWS) for i in range(NCOLS) }, "all_duplicates": { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): [ float(i) for _ in range(NROWS) ] for i in range(NCOLS) }, "some_duplicates": { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): [ i if j % 7 == 0 else x for j, x in enumerate(range(NROWS)) ] for i in range(NCOLS) }, "has_name_column": { "name": ["one", "two", "two", "three"], "col1": [1, 2, 2, 3], "col3": [10, 20, 20, 3], "col7": [100, 201, 200, 300], }, "str_columns": { "col_str{}".format(int((i - NCOLS / 2) % NCOLS + 1)): [ "s" + str(x % 5) for x in range(NROWS) ] for i in range(NCOLS) }, } test_data_with_duplicates["float_nan"] = test_data["float_nan_data"] test_data_small = { "small": { "col0": [1, 2, 3, 4], "col1": [8.0, 9.4, 10.1, 11.3], "col2": [4, 5, 6, 7], } } test_data_diff_dtype = { "int_col": [-5, 2, 7, 16], "float_col": [np.NaN, -9.4, 10.1, np.NaN], "str_col": ["a", np.NaN, "c", "d"], "bool_col": [False, True, True, False], } test_data_small_values = list(test_data_small.values()) test_data_small_keys = list(test_data_small.keys()) test_data_with_duplicates_values = list(test_data_with_duplicates.values()) test_data_with_duplicates_keys = list(test_data_with_duplicates.keys()) test_data_categorical = { "ordered": pandas.Categorical(list("testdata"), ordered=True), "unordered": pandas.Categorical(list("testdata"), ordered=False), } test_data_categorical_values = list(test_data_categorical.values()) test_data_categorical_keys = list(test_data_categorical.keys()) numeric_dfs = [ "empty_data", "columns_only", "int_data", "float_nan_data", "with_index_column", ] no_numeric_dfs = ["datetime_timedelta_data"] # String test data test_string_data = { "separator data": [ "abC|DeF,Hik", "234,3245.67", "gSaf,qWer|Gre", "asd3,4sad|", np.NaN, ] } test_string_data_values = list(test_string_data.values()) test_string_data_keys = list(test_string_data.keys()) # List of strings test data test_string_list_data = {"simple string": [["a"], ["CdE"], ["jDf"], ["werB"]]} test_string_list_data_values = list(test_string_list_data.values()) test_string_list_data_keys = list(test_string_list_data.keys()) string_seperators = {"empty sep": "", "comma sep": ",", "None sep": None} string_sep_values = list(string_seperators.values()) string_sep_keys = list(string_seperators.keys()) string_na_rep = {"None na_rep": None, "- na_rep": "-", "nan na_rep": np.NaN} string_na_rep_values = list(string_na_rep.values()) string_na_rep_keys = list(string_na_rep.keys()) join_type = {"left": "left", "right": "right", "inner": "inner", "outer": "outer"} join_type_keys = list(join_type.keys()) join_type_values = list(join_type.values()) # Test functions for applymap test_func = { "plus one": lambda x: x + 1, "convert to string": lambda x: str(x), "square": lambda x: x * x, "identity": lambda x: x, "return false": lambda x: False, } test_func_keys = list(test_func.keys()) test_func_values = list(test_func.values()) numeric_test_funcs = ["plus one", "square"] # Test functions for query query_func = { "col1 < col2": "col1 < col2", "col3 > col4": "col3 > col4", "col1 == col2": "col1 == col2", "(col2 > col1) and (col1 < col3)": "(col2 > col1) and (col1 < col3)", } query_func_keys = list(query_func.keys()) query_func_values = list(query_func.values()) # Test agg functions for apply, agg, and aggregate agg_func = { "sum": "sum", "df sum": lambda df: df.sum(), "str": str, "sum mean": ["sum", "mean"], "sum df sum": ["sum", lambda df: df.sum()], "should raise TypeError": 1, } agg_func_keys = list(agg_func.keys()) agg_func_values = list(agg_func.values()) # For this sort of parameters pandas throws an exception. # See details in pandas issue 36036. agg_func_except = { "sum sum": ["sum", "sum"], } agg_func_except_keys = list(agg_func_except.keys()) agg_func_except_values = list(agg_func_except.values()) numeric_agg_funcs = ["sum mean", "sum sum", "sum df sum"] udf_func = { "return self": lambda df: lambda x, *args, **kwargs: type(x)(x.values), "change index": lambda df: lambda x, *args, **kwargs: pandas.Series( x.values, index=np.arange(-1, len(x.index) - 1) ), "return none": lambda df: lambda x, *args, **kwargs: None, "return empty": lambda df: lambda x, *args, **kwargs: pandas.Series(), "access self": lambda df: lambda x, other, *args, **kwargs: pandas.Series( x.values, index=other.index ), } udf_func_keys = list(udf_func.keys()) udf_func_values = list(udf_func.values()) # Test q values for quantiles quantiles = { "0.25": 0.25, "0.5": 0.5, "0.75": 0.75, "0.66": 0.66, "0.01": 0.01, "list": [0.25, 0.5, 0.75, 0.66, 0.01], } quantiles_keys = list(quantiles.keys()) quantiles_values = list(quantiles.values()) # Test indices for get, set_index, __contains__, insert indices = { "col1": "col1", "col2": "col2", "A": "A", "B": "B", "does not exist": "does not exist", } indices_keys = list(indices.keys()) indices_values = list(indices.values()) # Test functions for groupby apply groupby_apply_func = {"sum": lambda df: df.sum(), "negate": lambda df: -df} groupby_apply_func_keys = list(groupby_apply_func.keys()) groupby_apply_func_values = list(groupby_apply_func.values()) # Test functions for groupby agg groupby_agg_func = {"min": "min", "max": "max"} groupby_agg_func_keys = list(groupby_agg_func.keys()) groupby_agg_func_values = list(groupby_agg_func.values()) # Test functions for groupby transform groupby_transform_func = { "add 4": lambda df: df + 4, "negatie and minus 10": lambda df: -df - 10, } groupby_transform_func_keys = list(groupby_transform_func.keys()) groupby_transform_func_values = list(groupby_transform_func.values()) # Test functions for groupby pipe groupby_pipe_func = {"sum": lambda df: df.sum()} groupby_pipe_func_keys = list(groupby_pipe_func.keys()) groupby_pipe_func_values = list(groupby_pipe_func.values()) # END Test input data and functions # Parametrizations of common kwargs axis = { "over_rows_int": 0, "over_rows_str": "rows", "over_columns_int": 1, "over_columns_str": "columns", } axis_keys = list(axis.keys()) axis_values = list(axis.values()) bool_arg = {"True": True, "False": False, "None": None} bool_arg_keys = list(bool_arg.keys()) bool_arg_values = list(bool_arg.values()) int_arg = {"-5": -5, "-1": -1, "0": 0, "1": 1, "5": 5} int_arg_keys = list(int_arg.keys()) int_arg_values = list(int_arg.values()) # END parametrizations of common kwargs json_short_string = """[{"project": "modin"}]""" json_long_string = """{ "quiz": { "sport": { "q1": { "question": "Which one is correct team name in NBA?", "options": [ "New York Bulls", "Los Angeles Kings", "Golden State Warriros", "Huston Rocket" ], "answer": "Huston Rocket" } }, "maths": { "q1": { "question": "5 + 7 = ?", "options": [ "10", "11", "12", "13" ], "answer": "12" }, "q2": { "question": "12 - 8 = ?", "options": [ "1", "2", "3", "4" ], "answer": "4" } } } }""" json_long_bytes = BytesIO(json_long_string.encode(encoding="UTF-8")) json_short_bytes = BytesIO(json_short_string.encode(encoding="UTF-8")) # Text encoding types encoding_types = [ "ascii", "utf_32", "utf_32_be", "utf_32_le", "utf_16", "utf_16_be", "utf_16_le", "utf_7", "utf_8", "utf_8_sig", ] # raising of this exceptions can be caused by unexpected behavior # of I/O operation test, but can passed by eval_io function since # the type of this exceptions are the same io_ops_bad_exc = [TypeError, FileNotFoundError] # Files compression to extension mapping COMP_TO_EXT = {"gzip": "gz", "bz2": "bz2", "xz": "xz", "zip": "zip"} def categories_equals(left, right): assert (left.ordered and right.ordered) or (not left.ordered and not right.ordered) assert_extension_array_equal(left, right) def
(df1, df2): if not hasattr(df1, "select_dtypes"): if isinstance(df1, pandas.CategoricalDtype): return categories_equals(df1, df2) elif isinstance(getattr(df1, "dtype"), pandas.CategoricalDtype) and isinstance( getattr(df1, "dtype"), pandas.CategoricalDtype ): return categories_equals(df1.dtype, df2.dtype) else: return True categories_columns = df1.select_dtypes(include="category").columns for column in categories_columns: assert_extension_array_equal( df1[column].values, df2[column].values, check_dtype=False, ) def df_equals(df1, df2): """Tests if df1 and df2 are equal. Args: df1: (pandas or modin DataFrame or series) dataframe to test if equal. df2: (pandas or modin DataFrame or series) dataframe to test if equal. Returns: True if df1 is equal to df2. """ # Gets AttributError if modin's groupby object is not import like this from modin.pandas.groupby import DataFrameGroupBy groupby_types = (pandas.core.groupby.DataFrameGroupBy, DataFrameGroupBy) # The typing behavior of how pandas treats its index is not consistent when the # length of the DataFrame or Series is 0, so we just verify that the contents are # the same. if ( hasattr(df1, "index") and hasattr(df2, "index") and len(df1) == 0 and len(df2) == 0 ): if type(df1).__name__ == type(df2).__name__: if hasattr(df1, "name") and hasattr(df2, "name") and df1.name == df2.name: return if ( hasattr(df1, "columns") and hasattr(df2, "columns") and df1.columns.equals(df2.columns) ): return assert False if isinstance(df1, (list, tuple)) and all( isinstance(d, (pd.DataFrame, pd.Series, pandas.DataFrame, pandas.Series)) for d in df1 ): assert isinstance(df2, type(df1)), "Different type of collection" assert len(df1) == len(df2), "Different length result" return (df_equals(d1, d2) for d1, d2 in zip(df1, df2)) # Convert to pandas if isinstance(df1, (pd.DataFrame, pd.Series)): df1 = to_pandas(df1) if isinstance(df2, (pd.DataFrame, pd.Series)): df2 = to_pandas(df2) if isinstance(df1, pandas.DataFrame) and isinstance(df2, pandas.DataFrame): if (df1.empty and not df2.empty) or (df2.empty and not df1.empty): assert False, "One of the passed frames is empty, when other isn't" elif df1.empty and df2.empty and type(df1) != type(df2): assert ( False ), f"Empty frames have different types: {type(df1)} != {type(df2)}" if isinstance(df1, pandas.DataFrame) and isinstance(df2, pandas.DataFrame): assert_frame_equal( df1, df2, check_dtype=False, check_datetimelike_compat=True, check_index_type=False, check_column_type=False, check_categorical=False, ) df_categories_equals(df1, df2) elif isinstance(df1, pandas.Index) and isinstance(df2, pandas.Index): assert_index_equal(df1, df2) elif isinstance(df1, pandas.Series) and isinstance(df2, pandas.Series): assert_series_equal(df1, df2, check_dtype=False, check_series_type=False) elif isinstance(df1, groupby_types) and isinstance(df2, groupby_types): for g1, g2 in zip(df1, df2): assert g1[0] == g2[0] df_equals(g1[1], g2[1]) elif ( isinstance(df1, pandas.Series) and isinstance(df2, pandas.Series) and df1.empty and df2.empty ): assert all(df1.index == df2.index) assert df1.dtypes == df2.dtypes elif isinstance(df1, pandas.core.arrays.numpy_.PandasArray): assert isinstance(df2, pandas.core.arrays.numpy_.PandasArray) assert df1 == df2 elif isinstance(df1, np.recarray) and isinstance(df2, np.recarray): np.testing.assert_array_equal(df1, df2) else: if df1 != df2: np.testing.assert_almost_equal(df1, df2) def modin_df_almost_equals_pandas(modin_df, pandas_df): df_categories_equals(modin_df._to_pandas(), pandas_df) modin_df = to_pandas(modin_df) if hasattr(modin_df, "select_dtypes"): modin_df = modin_df.select_dtypes(exclude=["category"]) if hasattr(pandas_df, "select_dtypes"): pandas_df = pandas_df.select_dtypes(exclude=["category"]) difference = modin_df - pandas_df diff_max = difference.max() if isinstance(diff_max, pandas.Series): diff_max = diff_max.max() assert ( modin_df.equals(pandas_df) or diff_max < 0.0001 or (all(modin_df.isna().all()) and all(pandas_df.isna().all())) ) def df_is_empty(df): """Tests if df is empty. Args: df: (pandas or modin DataFrame) dataframe to test if empty. Returns: True if df is empty. """ assert df.size == 0 and df.empty assert df.shape[0] == 0 or df.shape[1] == 0 def arg_keys(arg_name, keys): """Appends arg_name to the front of all values in keys. Args: arg_name: (string) String containing argument name. keys: (list of strings) Possible inputs of argument. Returns: List of strings with arg_name append to front of keys. """ return ["{0}_{1}".format(arg_name, key) for key in keys] def name_contains(test_name, vals): """Determines if any string in vals is a substring of test_name. Args: test_name: (string) String to determine if contains substrings. vals: (list of strings) List of substrings to test for. Returns: True if a substring in vals is in test_name, else False. """ return any(val in test_name for val in vals) def check_df_columns_have_nans(df, cols): """Checks if there are NaN values in specified columns of a dataframe. :param df: Dataframe to check. :param cols: One column name or list of column names. :return: True if specified columns of dataframe contains NaNs. """ return ( pandas.api.types.is_list_like(cols) and ( any(isinstance(x, str) and x in df.columns and df[x].hasnans for x in cols) or any( isinstance(x, pd.Series) and x._parent is df and x.hasnans for x in cols ) ) ) or ( not pandas.api.types.is_list_like(cols) and cols in df.columns and df[cols].hasnans ) def eval_general( modin_df, pandas_df, operation, comparator=df_equals, __inplace__=False, check_exception_type=True, raising_exceptions=None, check_kwargs_callable=True, md_extra_kwargs=None, **kwargs, ): if raising_exceptions: assert ( check_exception_type ), "if raising_exceptions is not None or False, check_exception_type should be True" md_kwargs, pd_kwargs = {}, {} def execute_callable(fn, inplace=False, md_kwargs={}, pd_kwargs={}): try: pd_result = fn(pandas_df, **pd_kwargs) except Exception as pd_e: if check_exception_type is None: return None with pytest.raises(Exception) as md_e: # repr to force materialization repr(fn(modin_df, **md_kwargs)) if check_exception_type: assert isinstance(md_e.value, type(pd_e)) if raising_exceptions: assert not isinstance( md_e.value, tuple(raising_exceptions) ), f"not acceptable exception type: {md_e.value}" else: md_result = fn(modin_df, **md_kwargs) return (md_result, pd_result) if not __inplace__ else (modin_df, pandas_df) for key, value in kwargs.items(): if check_kwargs_callable and callable(value): values = execute_callable(value) # that means, that callable raised an exception if values is None: return else: md_value, pd_value = values else: md_value, pd_value = value, value md_kwargs[key] = md_value pd_kwargs[key] = pd_value if md_extra_kwargs: assert isinstance(md_extra_kwargs, dict) md_kwargs.update(md_extra_kwargs) values = execute_callable( operation, md_kwargs=md_kwargs, pd_kwargs=pd_kwargs, inplace=__inplace__ ) if values is not None: comparator(*values) def eval_io( fn_name, comparator=df_equals, cast_to_str=False, check_exception_type=True, raising_exceptions=io_ops_bad_exc, check_kwargs_callable=True, modin_warning=None, md_extra_kwargs=None, *args, **kwargs, ): """Evaluate I/O operation outputs equality check. Parameters ---------- fn_name: str I/O operation name ("read_csv" for example). comparator: obj Function to perform comparison. cast_to_str: bool There could be some missmatches in dtypes, so we're casting the whole frame to `str` before comparison. See issue #1931 for details. check_exception_type: bool Check or not exception types in the case of operation fail (compare exceptions types raised by Pandas and Modin). raising_exceptions: Exception or list of Exceptions Exceptions that should be raised even if they are raised both by Pandas and Modin (check evaluated only if `check_exception_type` passed as `True`). modin_warning: obj Warning that should be raised by Modin. md_extra_kwargs: dict Modin operation specific kwargs. """ def applyier(module, *args, **kwargs): result = getattr(module, fn_name)(*args, **kwargs) if cast_to_str: result = result.astype(str) return result def call_eval_general(): eval_general( pd, pandas, applyier, check_exception_type=check_exception_type, raising_exceptions=raising_exceptions, check_kwargs_callable=check_kwargs_callable, md_extra_kwargs=md_extra_kwargs, *args, **kwargs, ) if modin_warning: with pytest.warns(modin_warning): call_eval_general() else: call_eval_general() def eval_io_from_str(csv_str: str, unique_filename: str, **kwargs): """Evaluate I/O operation outputs equality check by using `csv_str` data passed as python str (csv test file will be created from `csv_str`). Parameters ---------- csv_str: str Test data for storing to csv file. unique_filename: str csv file name. """ try: with open(unique_filename, "w") as f: f.write(csv_str) eval_io( filepath_or_buffer=unique_filename, fn_name="read_csv", **kwargs, ) finally: if os.path.exists(unique_filename): try: os.remove(unique_filename) except PermissionError: pass def create_test_dfs(*args, **kwargs): post_fn = kwargs.pop("post_fn", lambda df: df) return map( post_fn, [pd.DataFrame(*args, **kwargs), pandas.DataFrame(*args, **kwargs)] ) def generate_dfs(): df = pandas.DataFrame( { "col1": [0, 1, 2, 3], "col2": [4, 5, 6, 7], "col3": [8, 9, 10, 11], "col4": [12, 13, 14, 15], "col5": [0, 0, 0, 0], } ) df2 = pandas.DataFrame( { "col1": [0, 1, 2, 3], "col2": [4, 5, 6, 7], "col3": [8, 9, 10, 11], "col6": [12, 13, 14, 15], "col7": [0, 0, 0, 0], } ) return df, df2 def generate_multiindex_dfs(axis=1): def generate_multiindex(index): return pandas.MultiIndex.from_tuples( [("a", x) for x in index.values], names=["name1", "name2"] ) df1, df2 = generate_dfs() df1.axes[axis], df2.axes[axis] = map( generate_multiindex, [df1.axes[axis], df2.axes[axis]] ) return df1, df2 def generate_multiindex(elements_number, nlevels=2, is_tree_like=False): def generate_level(length, nlevel): src = ["bar", "baz", "foo", "qux"] return [src[i % len(src)] + f"-{nlevel}-{i}" for i in range(length)] if is_tree_like: for penalty_level in [0, 1]: lvl_len_f, lvl_len_d = math.modf( round(elements_number ** (1 / (nlevels - penalty_level)), 12) ) if lvl_len_d >= 2 and lvl_len_f == 0: break if lvl_len_d < 2 or lvl_len_f != 0: raise RuntimeError( f"Can't generate Tree-like MultiIndex with lenght: {elements_number} and number of levels: {nlevels}" ) lvl_len = int(lvl_len_d) result = pd.MultiIndex.from_product( [generate_level(lvl_len, i) for i in range(nlevels - penalty_level)], names=[f"level-{i}" for i in range(nlevels - penalty_level)], ) if penalty_level: result = pd.MultiIndex.from_tuples( [("base_level", *ml_tuple) for ml_tuple in result], names=[f"level-{i}" for i in range(nlevels)], ) return result.sort_values() else: base_level = ["first"] * (elements_number // 2 + elements_number % 2) + [ "second" ] * (elements_number // 2) primary_levels = [generate_level(elements_number, i) for i in range(1, nlevels)] arrays = [base_level] + primary_levels return pd.MultiIndex.from_tuples( list(zip(*arrays)), names=[f"level-{i}" for i in range(nlevels)] ).sort_values() def generate_none_dfs(): df = pandas.DataFrame( { "col1": [0, 1, 2, 3], "col2": [4, 5, None, 7], "col3": [8, 9, 10, 11], "col4": [12, 13, 14, 15], "col5": [None, None, None, None], } ) df2 = pandas.DataFrame( { "col1": [0, 1, 2, 3], "col2": [4, 5, 6, 7], "col3": [8, 9, 10, 11], "col6": [12, 13, 14, 15], "col7": [0, 0, 0, 0], } ) return df, df2 def get_unique_filename( test_name: str = "test", kwargs: dict = {}, extension: str = "csv", data_dir: str = IO_OPS_DATA_DIR, suffix: str = "", debug_mode=False, ): """Returns unique file name with specified parameters. Parameters ---------- test_name: str name of the test for which the unique file name is needed. kwargs: list of ints Unique combiantion of test parameters for creation of unique name. extension: str Extension of unique file. data_dir: str Data directory where test files will be created. suffix: str String to append to the resulted name. debug_mode: bool Get unique filename containing kwargs values. Otherwise kwargs values will be replaced with hash equivalent. Returns ------- Unique file name. """ suffix_part = f"_{suffix}" if suffix else "" extension_part = f".{extension}" if extension else "" if debug_mode: # shortcut if kwargs parameter are not provided if len(kwargs) == 0 and extension == "csv" and suffix == "": return os.path.join(data_dir, (test_name + suffix_part + f".{extension}")) assert "." not in extension, "please provide pure extension name without '.'" prohibited_chars = ['"', "\n"] non_prohibited_char = "np_char" char_counter = 0 kwargs_name = dict(kwargs) for key, value in kwargs_name.items(): for char in prohibited_chars: if isinstance(value, str) and char in value or callable(value): kwargs_name[key] = non_prohibited_char + str(char_counter) char_counter += 1 parameters_values = "_".join( [ str(value) if not isinstance(value, (list, tuple)) else "_".join([str(x) for x in value]) for value in kwargs_name.values() ] ) return os.path.join( data_dir, test_name + parameters_values + suffix_part + extension_part ) else: import uuid return os.path.join(data_dir, uuid.uuid1().hex + suffix_part + extension_part) def get_random_string(): random_string = "".join( random_state.choice([x for x in ascii_letters], size=10).tolist() ) return random_string def insert_lines_to_csv( csv_name: str, lines_positions: list, lines_type: str = "blank", encoding: str = None, **csv_reader_writer_params, ): """Insert lines to ".csv" file. Parameters ---------- csv_name: str ".csv" file that should be modified. lines_positions: list of ints Lines postions that sghould be modified (serial number of line - begins from 0, ends in <rows_number> - 1). lines_type: str Lines types that should be inserted to ".csv" file. Possible types: "blank" - empty line without any delimiters/separators, "bad" - lines with len(lines_data) > cols_number encoding: str Encoding type that should be used during file reading and writing. """ cols_number = len(pandas.read_csv(csv_name, nrows=1).columns) if lines_type == "blank": lines_data = [] elif lines_type == "bad": cols_number = len(pandas.read_csv(csv_name, nrows=1).columns) lines_data = [x for x in range(cols_number + 1)] else: raise ValueError( f"acceptable values for parameter are ['blank', 'bad'], actually passed {lines_type}" ) lines = [] dialect = "excel" with open(csv_name, "r", encoding=encoding, newline="") as read_file: try: dialect = csv.Sniffer().sniff(read_file.read()) read_file.seek(0) except Exception: dialect = None reader = csv.reader( read_file, dialect=dialect if dialect is not None else "excel", **csv_reader_writer_params, ) counter = 0 for row in reader: if counter in lines_positions: lines.append(lines_data) else: lines.append(row) counter += 1 with open(csv_name, "w", encoding=encoding, newline="") as write_file: writer = csv.writer( write_file, dialect=dialect if dialect is not None else "excel", **csv_reader_writer_params, ) writer.writerows(lines) def _get_open_files(): """ psutil open_files() can return a lot of extra information that we can allow to be different, like file position; for simplicity we care about path and fd only. """ return sorted((info.path, info.fd) for info in psutil.Process().open_files()) def check_file_leaks(func): """ A decorator that ensures that no *newly* opened file handles are left after decorated function is finished. """ if not TrackFileLeaks.get(): return func @functools.wraps(func) def check(*a, **kw): fstart = _get_open_files() try: return func(*a, **kw) finally: leaks = [] for item in _get_open_files(): try: fstart.remove(item) except ValueError: # ignore files in /proc/, as they have nothing to do with # modin reading any data (and this is what we care about) if not item[0].startswith("/proc/"): leaks.append(item) assert ( not leaks ), f"Unexpected open handles left for: {', '.join(item[0] for item in leaks)}" return check def dummy_decorator(): """A problematic decorator that does not use `functools.wraps`. This introduces unwanted local variables for inspect.currentframe. This decorator is used in test_io to test `read_csv` and `read_table` """ def wrapper(method): def wrapped_function(self, *args, **kwargs): result = method(self, *args, **kwargs) return result return wrapped_function return wrapper def generate_dataframe(row_size=NROWS, additional_col_values=None): dates = pandas.date_range("2000", freq="h", periods=row_size) data = { "col1": np.arange(row_size) * 10, "col2": [str(x.date()) for x in dates], "col3": np.arange(row_size) * 10, "col4": [str(x.time()) for x in dates], "col5": [get_random_string() for _ in range(row_size)], "col6": random_state.uniform(low=0.0, high=10000.0, size=row_size), } if additional_col_values is not None: assert isinstance(additional_col_values, (list, tuple)) data.update( { "col7": random_state.choice(additional_col_values, size=row_size), } ) return pandas.DataFrame(data) def _make_csv_file(filenames): def _csv_file_maker( filename, row_size=NROWS, force=True, delimiter=",", encoding=None, compression="infer", additional_col_values=None, remove_randomness=False, add_blank_lines=False, add_bad_lines=False, add_nan_lines=False, thousands_separator=None, decimal_separator=None, comment_col_char=None, quoting=csv.QUOTE_MINIMAL, quotechar='"', doublequote=True, escapechar=None, line_terminator=None, ): if os.path.exists(filename) and not force: pass else: df = generate_dataframe(row_size, additional_col_values) if remove_randomness: df = df[["col1", "col2", "col3", "col4"]] if add_nan_lines: for i in range(0, row_size, row_size // (row_size // 10)): df.loc[i] = pandas.Series() if comment_col_char: char = comment_col_char if isinstance(comment_col_char, str) else "#" df.insert( loc=0, column="col_with_comments", value=[char if (x + 2) == 0 else x for x in range(row_size)], ) if thousands_separator: for col_id in ["col1", "col3"]: df[col_id] = df[col_id].apply( lambda x: f"{x:,d}".replace(",", thousands_separator) ) df["col6"] = df["col6"].apply( lambda x: f"{x:,f}".replace(",", thousands_separator) ) filename = ( f"{filename}.{COMP_TO_EXT[compression]}" if compression != "infer" else filename ) df.to_csv( filename, sep=delimiter, encoding=encoding, compression=compression, index=False, decimal=decimal_separator if decimal_separator else ".", line_terminator=line_terminator, quoting=quoting, quotechar=quotechar, doublequote=doublequote, escapechar=escapechar, ) csv_reader_writer_params = { "delimiter": delimiter, "doublequote": doublequote, "escapechar": escapechar, "lineterminator": line_terminator if line_terminator else os.linesep, "quotechar": quotechar, "quoting": quoting, } if add_blank_lines: insert_lines_to_csv( csv_name=filename, lines_positions=[ x for x in range(5, row_size, row_size // (row_size // 10)) ], lines_type="blank", encoding=encoding, **csv_reader_writer_params, ) if add_bad_lines: insert_lines_to_csv( csv_name=filename, lines_positions=[ x for x in range(6, row_size, row_size // (row_size // 10)) ], lines_type="bad", encoding=encoding, **csv_reader_writer_params, ) filenames.append(filename) return df return _csv_file_maker def teardown_test_file(test_path): if os.path.exists(test_path): # PermissionError can occure because of issue #2533 try: os.remove(test_path) except PermissionError: pass def teardown_test_files(test_paths: list): for path in test_paths: teardown_test_file(path) def sort_index_for_equal_values(series, ascending=False): if series.index.dtype == np.float64: # HACK: workaround for pandas bug: # https://github.com/pandas-dev/pandas/issues/34455 series.index = series.index.astype("str") res = series.groupby(series, sort=False).apply( lambda df: df.sort_index(ascending=ascending) ) if res.index.nlevels > series.index.nlevels: # Sometimes GroupBy adds an extra level with 'by' to the result index. # GroupBy is very inconsistent about when it's doing this, so that's # why this clumsy if-statement is used. res.index = res.index.droplevel(0) res.name = series.name return res
df_categories_equals
trapsin.py
import keyboard from utils.custom_mouse import mouse from char import IChar from pather import Pather from logger import Logger from screen import convert_abs_to_monitor, convert_screen_to_abs, grab from config import Config from utils.misc import wait, rotate_vec, unit_vector import random from pather import Location, Pather import numpy as np class Trapsin(IChar): def __init__(self, skill_hotkeys: dict, pather: Pather): Logger.info("Setting up Trapsin") super().__init__(skill_hotkeys) self._pather = pather def pre_buff(self): if Config().char["cta_available"]: self._pre_buff_cta() if self._skill_hotkeys["fade"]: keyboard.send(self._skill_hotkeys["fade"]) wait(0.1, 0.13) mouse.click(button="right") wait(self._cast_duration) if self._skill_hotkeys["shadow_warrior"]: keyboard.send(self._skill_hotkeys["shadow_warrior"]) wait(0.1, 0.13) mouse.click(button="right") wait(self._cast_duration) if self._skill_hotkeys["burst_of_speed"]: keyboard.send(self._skill_hotkeys["burst_of_speed"]) wait(0.1, 0.13)
def _left_attack(self, cast_pos_abs: tuple[float, float], spray: int = 10): keyboard.send(Config().char["stand_still"], do_release=False) if self._skill_hotkeys["skill_left"]: keyboard.send(self._skill_hotkeys["skill_left"]) for _ in range(4): x = cast_pos_abs[0] + (random.random() * 2*spray - spray) y = cast_pos_abs[1] + (random.random() * 2*spray - spray) cast_pos_monitor = convert_abs_to_monitor((x, y)) mouse.move(*cast_pos_monitor) mouse.press(button="left") wait(0.2, 0.3) mouse.release(button="left") keyboard.send(Config().char["stand_still"], do_press=False) def _right_attack(self, cast_pos_abs: tuple[float, float], spray: float = 10): keyboard.send(self._skill_hotkeys["lightning_sentry"]) x = cast_pos_abs[0] + (random.random() * 2 * spray - spray) y = cast_pos_abs[1] + (random.random() * 2 * spray - spray) cast_pos_monitor = convert_abs_to_monitor((x, y)) mouse.move(*cast_pos_monitor) def atk(num: int): for _ in range(num): mouse.press(button="right") wait(0.20) mouse.release(button="right") wait(0.15) atk(4) keyboard.send(self._skill_hotkeys["death_sentry"]) atk(1) def kill_pindle(self) -> bool: atk_len = max(1, int(Config().char["atk_len_pindle"] / 2)) pindle_pos_abs = convert_screen_to_abs(Config().path["pindle_end"][0]) cast_pos_abs = [pindle_pos_abs[0] * 0.9, pindle_pos_abs[1] * 0.9] for _ in range(atk_len): self._right_attack(cast_pos_abs, 11) self._left_attack(cast_pos_abs, 11) # Move to items wait(self._cast_duration, self._cast_duration + 0.2) if self.capabilities.can_teleport_natively: self._pather.traverse_nodes_fixed("pindle_end", self) else: self._pather.traverse_nodes((Location.A5_PINDLE_SAFE_DIST, Location.A5_PINDLE_END), self, force_tp=True) return True def kill_eldritch(self) -> bool: atk_len = max(1, int(Config().char["atk_len_eldritch"] / 2)) eld_pos_abs = convert_screen_to_abs(Config().path["eldritch_end"][0]) cast_pos_abs = [eld_pos_abs[0] * 0.9, eld_pos_abs[1] * 0.9] for _ in range(atk_len): self._right_attack(cast_pos_abs, 90) self._left_attack(cast_pos_abs, 90) # Move to items wait(self._cast_duration, self._cast_duration + 0.2) if self.capabilities.can_teleport_natively: self._pather.traverse_nodes_fixed("eldritch_end", self) else: self._pather.traverse_nodes((Location.A5_ELDRITCH_SAFE_DIST, Location.A5_ELDRITCH_END), self, timeout=0.6, force_tp=True) return True def kill_shenk(self) -> bool: atk_len = max(1, int(Config().char["atk_len_shenk"] / 2)) shenk_pos_abs = self._pather.find_abs_node_pos(149, grab()) if shenk_pos_abs is None: shenk_pos_abs = convert_screen_to_abs(Config().path["shenk_end"][0]) cast_pos_abs = [shenk_pos_abs[0] * 0.9, shenk_pos_abs[1] * 0.9] for _ in range(atk_len): self._right_attack(cast_pos_abs, 90) self._left_attack(cast_pos_abs, 90) # Move to items wait(self._cast_duration, self._cast_duration + 0.2) self._pather.traverse_nodes((Location.A5_SHENK_SAFE_DIST, Location.A5_SHENK_END), self, timeout=1.4, force_tp=True) return True def kill_nihlathak(self, end_nodes: list[int]) -> bool: # Find nilhlatak position atk_len = max(1, int(Config().char["atk_len_nihlathak"] / 2)) for i in range(atk_len): nihlathak_pos_abs = self._pather.find_abs_node_pos(end_nodes[-1], grab()) if nihlathak_pos_abs is None: return False cast_pos_abs = np.array([nihlathak_pos_abs[0] * 0.9, nihlathak_pos_abs[1] * 0.9]) self._left_attack(cast_pos_abs, 90) self._right_attack(cast_pos_abs, 90) # Do some tele "dancing" after each sequence if i < atk_len - 1: rot_deg = random.randint(-10, 10) if i % 2 == 0 else random.randint(170, 190) tele_pos_abs = unit_vector(rotate_vec(cast_pos_abs, rot_deg)) * 100 pos_m = convert_abs_to_monitor(tele_pos_abs) self.pre_move() self.move(pos_m) # Move to items wait(self._cast_duration, self._cast_duration + 0.2) self._pather.traverse_nodes(end_nodes, self, timeout=0.8) return True if __name__ == "__main__": import os import keyboard keyboard.add_hotkey('f12', lambda: Logger.info('Force Exit (f12)') or os._exit(1)) keyboard.wait("f11") from config import Config from char import Trapsin pather = Pather() char = Trapsin(Config().trapsin, Config().char, pather)
mouse.click(button="right") wait(self._cast_duration)
test_securetty.py
# Copyright 2016 Canonical Limited. # # This file is part of charm-helpers. # # charm-helpers is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License version 3 as # published by the Free Software Foundation. # # charm-helpers is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. from unittest import TestCase from charms_hardening.host.checks import securetty class SecureTTYTestCase(TestCase): def
(self): audits = securetty.get_audits() self.assertEqual(1, len(audits)) audit = audits[0] self.assertTrue(isinstance(audit, securetty.TemplatedFile)) self.assertEqual('/etc/securetty', audit.paths[0])
test_securetty
entities.go
// ENTITIES section package entity import ( "github.com/ma2ma/godxf/format" ) // Entities represents ENTITIES section. type Entities []Entity // New creates a new Entities. func New() Entities
// WriteTo writes ENTITIES data to formatter. func (es Entities) WriteTo(f format.Formatter) { f.WriteString(0, "SECTION") f.WriteString(2, "ENTITIES") for _, e := range es { e.Format(f) } f.WriteString(0, "ENDSEC") } // Add adds a new entity to ENTITIES section. func (es Entities) Add(e Entity) Entities { es = append(es, e) return es } // SetHandle sets handles to each entity. func (es Entities) SetHandle(v *int) { for _, e := range es { e.SetHandle(v) } }
{ e := make([]Entity, 0) return e }
mode-ejs.js
define("ace/mode/ejs",["require","exports","module","ace/lib/oop","ace/mode/html_highlight_rules","ace/mode/javascript_highlight_rules","ace/tokenizer","ace/mode/html","ace/mode/javascript","ace/mode/css","ace/mode/ruby"],function(e,t,n){var r=e("../lib/oop"),i=e("./html_highlight_rules").HtmlHighlightRules,s=e("./javascript_highlight_rules").JavaScriptHighlightRules,o=function(e,t){i.call(this),e||(e="(?:<%|<\\?|{{)"),t||(t="(?:%>|\\?>|}})");for(var n in this.$rules)this.$rules[n].unshift({token:"markup.list.meta.tag",regex:e+"(?![>}])[-=]?",push:"ejs-start"});this.embedRules(s,"ejs-"),this.$rules["ejs-start"].unshift({token:"markup.list.meta.tag",regex:"-?"+t,next:"pop"},{token:"comment",regex:"//.*?"+t,next:"pop"}),this.$rules["ejs-no_regex"].unshift({token:"markup.list.meta.tag",regex:"-?"+t,next:"pop"},{token:"comment",regex:"//.*?"+t,next:"pop"}),this.normalizeRules()};r.inherits(o,i),t.EjsHighlightRules=o;var r=e("../lib/oop"),u=e("../tokenizer").Tokenizer,a=e("./html").Mode,f=e("./javascript").Mode,l=e("./css").Mode,c=e("./ruby").Mode,h=function(){a.call(this),this.HighlightRules=o,this.createModeDelegates({"js-":f,"css-":l,"ejs-":f})};r.inherits(h,a),function(){this.$id="ace/mode/ejs"}.call(h.prototype),t.Mode=h}),define("ace/mode/html_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/css_highlight_rules","ace/mode/javascript_highlight_rules","ace/mode/xml_highlight_rules"],function(e,t,n){var r=e("../lib/oop"),i=e("../lib/lang"),s=e("./css_highlight_rules").CssHighlightRules,o=e("./javascript_highlight_rules").JavaScriptHighlightRules,u=e("./xml_highlight_rules").XmlHighlightRules,a=i.createMap({a:"anchor",button:"form",form:"form",img:"image",input:"form",label:"form",option:"form",script:"script",select:"form",textarea:"form",style:"style",table:"table",tbody:"table",td:"table",tfoot:"table",th:"table",tr:"table"}),f=function(){u.call(this),this.addRules({attributes:[{include:"space"},{token:"entity.other.attribute-name",regex:"[-_a-zA-Z0-9:]+"},{token:"keyword.operator.separator",regex:"=",push:[{include:"space"},{token:"string",regex:"[^<>='\"`\\s]+",next:"pop"},{token:"empty",regex:"",next:"pop"}]},{include:"string"}],tag:[{token:function(e,t){var n=a[t];return["meta.tag.punctuation.begin","meta.tag.name"+(n?"."+n:"")]},regex:"(<)([-_a-zA-Z0-9:]+)",next:"start_tag_stuff"},{token:function(e,t){var n=a[t];return["meta.tag.punctuation.begin","meta.tag.name"+(n?"."+n:"")]},regex:"(</)([-_a-zA-Z0-9:]+)",next:"end_tag_stuff"}],start_tag_stuff:[{include:"attributes"},{token:"meta.tag.punctuation.end",regex:"/?>",next:"start"}],end_tag_stuff:[{include:"space"},{token:"meta.tag.punctuation.end",regex:">",next:"start"}]}),this.embedTagRules(s,"css-","style"),this.embedTagRules(o,"js-","script"),this.constructor===f&&this.normalizeRules()};r.inherits(f,u),t.HtmlHighlightRules=f}),define("ace/mode/css_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(e,t,n){var r=e("../lib/oop"),i=e("../lib/lang"),s=e("./text_highlight_rules").TextHighlightRules,o=t.supportType="animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|pointer-events|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index",u=t.supportFunction="rgb|rgba|url|attr|counter|counters",a=t.supportConstant="absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero",f=t.supportConstantColor="aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow",l=t.supportConstantFonts="arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace",c=t.numRe="\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))",h=t.pseudoElements="(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b",p=t.pseudoClasses="(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b",d=function(){var e=this.createKeywordMapper({"support.function":u,"support.constant":a,"support.type":o,"support.constant.color":f,"support.constant.fonts":l},"text",!0);this.$rules={start:[{token:"comment",regex:"\\/\\*",push:"comment"},{token:"paren.lparen",regex:"\\{",push:"ruleset"},{token:"string",regex:"@.*?{",push:"media"},{token:"keyword",regex:"#[a-z0-9-_]+"},{token:"variable",regex:"\\.[a-z0-9-_]+"},{token:"string",regex:":[a-z0-9-_]+"},{token:"constant",regex:"[a-z0-9-_]+"},{caseInsensitive:!0}],media:[{token:"comment",regex:"\\/\\*",push:"comment"},{token:"paren.lparen",regex:"\\{",push:"ruleset"},{token:"string",regex:"\\}",next:"pop"},{token:"keyword",regex:"#[a-z0-9-_]+"},{token:"variable",regex:"\\.[a-z0-9-_]+"},{token:"string",regex:":[a-z0-9-_]+"},{token:"constant",regex:"[a-z0-9-_]+"},{caseInsensitive:!0}],comment:[{token:"comment",regex:"\\*\\/",next:"pop"},{defaultToken:"comment"}],ruleset:[{token:"paren.rparen",regex:"\\}",next:"pop"},{token:"comment",regex:"\\/\\*",push:"comment"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:["constant.numeric","keyword"],regex:"("+c+")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)"},{token:"constant.numeric",regex:c},{token:"constant.numeric",regex:"#[a-f0-9]{6}"},{token:"constant.numeric",regex:"#[a-f0-9]{3}"},{token:["punctuation","entity.other.attribute-name.pseudo-element.css"],regex:h},{token:["punctuation","entity.other.attribute-name.pseudo-class.css"],regex:p},{token:["support.function","string","support.function"],regex:"(url\\()(.*)(\\))"},{token:e,regex:"\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*"},{caseInsensitive:!0}]},this.normalizeRules()};r.inherits(d,s),t.CssHighlightRules=d}),define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"],function(e,t,n){var r=e("../lib/oop"),i=e("./doc_comment_highlight_rules").DocCommentHighlightRules,s=e("./text_highlight_rules").TextHighlightRules,o=function(){var e=this.createKeywordMapper({"variable.language":"Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|Namespace|QName|XML|XMLList|ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|SyntaxError|TypeError|URIError|decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|isNaN|parseFloat|parseInt|JSON|Math|this|arguments|prototype|window|document",keyword:"const|yield|import|get|set|break|case|catch|continue|default|delete|do|else|finally|for|function|if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|__parent__|__count__|escape|unescape|with|__proto__|class|enum|extends|super|export|implements|private|public|interface|package|protected|static","storage.type":"const|let|var|function","constant.language":"null|Infinity|NaN|undefined","support.function":"alert","constant.language.boolean":"true|false"},"identifier"),t="case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void",n="[a-zA-Z\\$_¡-￿][a-zA-Z\\d\\$_¡-￿]*\\b",r="\\\\(?:x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|[0-2][0-7]{0,2}|3[0-6][0-7]?|37[0-7]?|[4-7][0-7]?|.)";this.$rules={no_regex:[{token:"comment",regex:"\\/\\/",next:"line_comment"},i.getStartRule("doc-start"),{token:"comment",regex:/\/\*/,next:"comment"},{token:"string",regex:"'(?=.)",next:"qstring"},{token:"string",regex:'"(?=.)',next:"qqstring"},{token:"constant.numeric",regex:/0[xX][0-9a-fA-F]+\b/},{token:"constant.numeric",regex:/[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/},{token:["storage.type","punctuation.operator","support.function","punctuation.operator","entity.name.function","text","keyword.operator"],regex:"("+n+")(\\.)(prototype)(\\.)("+n+")(\\s*)(=)",next:"function_arguments"},{token:["storage.type","punctuation.operator","entity.name.function","text","keyword.operator","text","storage.type","text","paren.lparen"],regex:"("+n+")(\\.)("+n+")(\\s*)(=)(\\s*)(function)(\\s*)(\\()",next:"function_arguments"},{token:["entity.name.function","text","keyword.operator","text","storage.type","text","paren.lparen"],regex:"("+n+")(\\s*)(=)(\\s*)(function)(\\s*)(\\()",next:"function_arguments"},{token:["storage.type","punctuation.operator","entity.name.function","text","keyword.operator","text","storage.type","text","entity.name.function","text","paren.lparen"],regex:"("+n+")(\\.)("+n+")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()",next:"function_arguments"},{token:["storage.type","text","entity.name.function","text","paren.lparen"],regex:"(function)(\\s+)("+n+")(\\s*)(\\()",next:"function_arguments"},{token:["entity.name.function","text","punctuation.operator","text","storage.type","text","paren.lparen"],regex:"("+n+")(\\s*)(:)(\\s*)(function)(\\s*)(\\()",next:"function_arguments"},{token:["text","text","storage.type","text","paren.lparen"],regex:"(:)(\\s*)(function)(\\s*)(\\()",next:"function_arguments"},{token:"keyword",regex:"(?:"+t+")\\b",next:"start"},{token:["punctuation.operator","support.function"],regex:/(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/},{token:["punctuation.operator","support.function.dom"],regex:/(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/},{token:["punctuation.operator","support.constant"],regex:/(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/},{token:["storage.type","punctuation.operator","support.function.firebug"],regex:/(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/},{token:e,regex:n},{token:"keyword.operator",regex:/--|\+\+|[!$%&*+\-~]|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=/,next:"start"},{token:"punctuation.operator",regex:/\?|\:|\,|\;|\./,next:"start"},{token:"paren.lparen",regex:/[\[({]/,next:"start"},{token:"paren.rparen",regex:/[\])}]/},{token:"keyword.operator",regex:/\/=?/,next:"start"},{token:"comment",regex:/^#!.*$/}],start:[i.getStartRule("doc-start"),{token:"comment",regex:"\\/\\*",next:"comment_regex_allowed"},{token:"comment",regex:"\\/\\/",next:"line_comment_regex_allowed"},{token:"string.regexp",regex:"\\/",next:"regex"},{token:"text",regex:"\\s+|^$",next:"start"},{token:"empty",regex:"",next:"no_regex"}],regex:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)"},{token:"string.regexp",regex:"/[sxngimy]*",next:"no_regex"},{token:"invalid",regex:/\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/},{token:"constant.language.escape",regex:/\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/},{token:"constant.language.delimiter",regex:/\|/},{token:"constant.language.escape",regex:/\[\^?/,next:"regex_character_class"},{token:"empty",regex:"$",next:"no_regex"},{defaultToken:"string.regexp"}],regex_character_class:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)"},{token:"constant.language.escape",regex:"]",next:"regex"},{token:"constant.language.escape",regex:"-"},{token:"empty",regex:"$",next:"no_regex"},{defaultToken:"string.regexp.charachterclass"}],function_arguments:[{token:"variable.parameter",regex:n},{token:"punctuation.operator",regex:"[, ]+"},{token:"punctuation.operator",regex:"$"},{token:"empty",regex:"",next:"no_regex"}],comment_regex_allowed:[{token:"comment",regex:"\\*\\/",next:"start"},{defaultToken:"comment"}],comment:[{token:"comment",regex:"\\*\\/",next:"no_regex"},{defaultToken:"comment"}],line_comment_regex_allowed:[{token:"comment",regex:"$|^",next:"start"},{defaultToken:"comment"}],line_comment:[{token:"comment",regex:"$|^",next:"no_regex"},{defaultToken:"comment"}],qqstring:[{token:"constant.language.escape",regex:r},{token:"string",regex:"\\\\$",next:"qqstring"},{token:"string",regex:'"|$',next:"no_regex"},{defaultToken:"string"}],qstring:[{token:"constant.language.escape",regex:r},{token:"string",regex:"\\\\$",next:"qstring"},{token:"string",regex:"'|$",next:"no_regex"},{defaultToken:"string"}]},this.embedRules(i,"doc-",[i.getEndRule("no_regex")])};r.inherits(o,s),t.JavaScriptHighlightRules=o}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(e,t,n){var r=e("../lib/oop"),i=e("./text_highlight_rules").TextHighlightRules,s=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc.tag",regex:"\\bTODO\\b"},{defaultToken:"comment.doc"}]}};r.inherits(s,i),s.getStartRule=function(e){return{token:"comment.doc",regex:"\\/\\*(?=\\*)",next:e}},s.getEndRule=function(e){return{token:"comment.doc",regex:"\\*\\/",next:e}},t.DocCommentHighlightRules=s}),define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(e,t,n){var r=e("../lib/oop"),i=e("./text_highlight_rules").TextHighlightRules,s=function(e){this.$rules={start:[{token:"punctuation.string.begin",regex:"<\\!\\[CDATA\\[",next:"cdata"},{token:["punctuation.instruction.begin","keyword.instruction"],regex:"(<\\?)(xml)(?=[\\s])",next:"xml_declaration"},{token:["punctuation.instruction.begin","keyword.instruction"],regex:"(<\\?)([-_a-zA-Z0-9]+)",next:"instruction"},{token:"comment",regex:"<\\!--",next:"comment"},{token:["punctuation.doctype.begin","meta.tag.doctype"],regex:"(<\\!)(DOCTYPE)(?=[\\s])",next:"doctype"},{include:"tag"},{include:"reference"}],xml_declaration:[{include:"attributes"},{include:"instruction"}],instruction:[{token:"punctuation.instruction.end",regex:"\\?>",next:"start"}],doctype:[{include:"space"},{include:"string"},{token:"punctuation.doctype.end",regex:">",next:"start"},{token:"xml-pe",regex:"[-_a-zA-Z0-9:]+"},{token:"punctuation.begin",regex:"\\[",push:"declarations"}],declarations:[{token:"text",regex:"\\s+"},{token:"punctuation.end",regex:"]",next:"pop"},{token:["punctuation.begin","keyword"],regex:"(<\\!)([-_a-zA-Z0-9]+)",push:[{token:"text",regex:"\\s+"},{token:"punctuation.end",regex:">",next:"pop"},{include:"string"}]}],cdata:[{token:"string.end",regex:"\\]\\]>",next:"start"},{token:"text",regex:"\\s+"},{token:"text",regex:"(?:[^\\]]|\\](?!\\]>))+"}],comment:[{token:"comment",regex:"-->",next:"start"},{defaultToken:"comment"}],tag:[{token:["meta.tag.punctuation.begin","meta.tag.name"],regex:"(<)((?:[-_a-zA-Z0-9]+:)?[-_a-zA-Z0-9]+)",next:[{include:"attributes"},{token:"meta.tag.punctuation.end",regex:"/?>",next:"start"}]},{token:["meta.tag.punctuation.begin","meta.tag.name"],regex:"(</)((?:[-_a-zA-Z0-9]+:)?[-_a-zA-Z0-9]+)",next:[{include:"space"},{token:"meta.tag.punctuation.end",regex:">",next:"start"}]}],space:[{token:"text",regex:"\\s+"}],reference:[{token:"constant.language.escape",regex:"(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)"},{token:"text",regex:"&"}],string:[{token:"string",regex:"'",push:"qstring_inner"},{token:"string",regex:'"',push:"qqstring_inner"}],qstring_inner:[{token:"string",regex:"'",next:"pop"},{include:"reference"},{defaultToken:"string"}],qqstring_inner:[{token:"string",regex:'"',next:"pop"},{include:"reference"},{defaultToken:"string"}],attributes:[{token:"entity.other.attribute-name",regex:"(?:[-_a-zA-Z0-9]+:)?[-_a-zA-Z0-9]+"},{token:"keyword.operator.separator",regex:"="},{include:"space"},{include:"string"}]},this.constructor===s&&this.normalizeRules()};(function(){this.embedTagRules=function(e,t,n){this.$rules.tag.unshift({token:["meta.tag.punctuation.begin","meta.tag.name."+n],regex:"(<)("+n+")",next:[{include:"space"},{include:"attributes"},{token:"meta.tag.punctuation.end",regex:"/?>",next:t+"start"}]}),this.$rules[n+"-end"]=[{include:"space"},{token:"meta.tag.punctuation.end",regex:">",next:"start",onMatch:function(e,t,n){return n.splice(0),this.token}}],this.embedRules(e,t,[{token:["meta.tag.punctuation.begin","meta.tag.name."+n],regex:"(</)("+n+")",next:n+"-end"},{token:"string.begin",regex:"<\\!\\[CDATA\\["},{token:"string.end",regex:"\\]\\]>"}])}}).call(i.prototype),r.inherits(s,i),t.XmlHighlightRules=s}),define("ace/mode/html",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript","ace/mode/css","ace/tokenizer","ace/mode/html_highlight_rules","ace/mode/behaviour/html","ace/mode/folding/html","ace/mode/html_completions"],function(e,t,n){var r=e("../lib/oop"),i=e("./text").Mode,s=e("./javascript").Mode,o=e("./css").Mode,u=e("../tokenizer").Tokenizer,a=e("./html_highlight_rules").HtmlHighlightRules,f=e("./behaviour/html").HtmlBehaviour,l=e("./folding/html").FoldMode,c=e("./html_completions").HtmlCompletions,h=function(){this.HighlightRules=a,this.$behaviour=new f,this.$completer=new c,this.createModeDelegates({"js-":s,"css-":o}),this.foldingRules=new l};r.inherits(h,i),function(){this.blockComment={start:"<!--",end:"-->"},this.getNextLineIndent=function(e,t,n){return this.$getIndent(t)},this.checkOutdent=function(e,t,n){return!1},this.getCompletions=function(e,t,n,r){return this.$completer.getCompletions(e,t,n,r)},this.$id="ace/mode/html"}.call(h.prototype),t.Mode=h}),define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(e,t,n){var r=e("../lib/oop"),i=e("./text").Mode,s=e("../tokenizer").Tokenizer,o=e("./javascript_highlight_rules").JavaScriptHighlightRules,u=e("./matching_brace_outdent").MatchingBraceOutdent,a=e("../range").Range,f=e("../worker/worker_client").WorkerClient,l=e("./behaviour/cstyle").CstyleBehaviour,c=e("./folding/cstyle").FoldMode,h=function(){this.HighlightRules=o,this.$outdent=new u,this.$behaviour=new l,this.foldingRules=new c};r.inherits(h,i),function(){this.lineCommentStart="//",this.blockComment={start:"/*",end:"*/"},this.getNextLineIndent=function(e,t,n){var r=this.$getIndent(t),i=this.getTokenizer().getLineTokens(t,e),s=i.tokens,o=i.state;if(s.length&&s[s.length-1].type=="comment")return r;if(e=="start"||e=="no_regex"){var u=t.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/);u&&(r+=n)}else if(e=="doc-start"){if(o=="start"||o=="no_regex")return"";var u=t.match(/^\s*(\/?)\*/);u&&(u[1]&&(r+=" "),r+="* ")}return r},this.checkOutdent=function(e,t,n){return this.$outdent.checkOutdent(t,n)},this.autoOutdent=function(e,t,n){this.$outdent.autoOutdent(t,n)},this.createWorker=function(e){var t=new f(["ace"],"ace/mode/javascript_worker","JavaScriptWorker");return t.attachToDocument(e.getDocument()),t.on("jslint",function(t){e.setAnnotations(t.data)}),t.on("terminate",function(){e.clearAnnotations()}),t},this.$id="ace/mode/javascript"}.call(h.prototype),t.Mode=h}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(e,t,n){var r=e("../range").Range,i=function(){};(function(){this.checkOutdent=function(e,t){return/^\s+$/.test(e)?/^\s*\}/.test(t):!1},this.autoOutdent=function(e,t){var n=e.getLine(t),i=n.match(/^(\s*\})/);if(!i)return 0;var s=i[1].length,o=e.findMatchingBracket({row:t,column:s});if(!o||o.row==t)return 0;var u=this.$getIndent(e.getLine(o.row));e.replace(new r(t,0,t,s-1),u)},this.$getIndent=function(e){return e.match(/^\s*/)[0]}}).call(i.prototype),t.MatchingBraceOutdent=i}),define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"],function(e,t,n){var r=e("../../lib/oop"),i=e("../behaviour").Behaviour,s=e("../../token_iterator").TokenIterator,o=e("../../lib/lang"),u=["text","paren.rparen","punctuation.operator"],a=["text","paren.rparen","punctuation.operator","comment"],f=0,l=-1,c="",h=0,p=-1,d="",v="",m=function(){m.isSaneInsertion=function(e,t){var n=e.getCursorPosition(),r=new s(t,n.row,n.column);if(!this.$matchTokenType(r.getCurrentToken()||"text",u)){var i=new s(t,n.row,n.column+1);if(!this.$matchTokenType(i.getCurrentToken()||"text",u))return!1}return r.stepForward(),r.getCurrentTokenRow()!==n.row||this.$matchTokenType(r.getCurrentToken()||"text",a)},m.$matchTokenType=function(e,t){return t.indexOf(e.type||e)>-1},m.recordAutoInsert=function(e,t,n){var r=e.getCursorPosition(),i=t.doc.getLine(r.row);this.isAutoInsertedClosing(r,i,c[0])||(f=0),l=r.row,c=n+i.substr(r.column),f++},m.recordMaybeInsert=function(e,t,n){var r=e.getCursorPosition(),i=t.doc.getLine(r.row);this.isMaybeInsertedClosing(r,i)||(h=0),p=r.row,d=i.substr(0,r.column)+n,v=i.substr(r.column),h++},m.isAutoInsertedClosing=function(e,t,n){return f>0&&e.row===l&&n===c[0]&&t.substr(e.column)===c},m.isMaybeInsertedClosing=function(e,t){return h>0&&e.row===p&&t.substr(e.column)===v&&t.substr(0,e.column)==d},m.popAutoInsertedClosing=function(){c=c.substr(1),f--},m.clearMaybeInsertedClosing=function(){h=0,p=-1},this.add("braces","insertion",function(e,t,n,r,i){var s=n.getCursorPosition(),u=r.doc.getLine(s.row);if(i=="{"){var a=n.getSelectionRange(),f=r.doc.getTextRange(a);if(f!==""&&f!=="{"&&n.getWrapBehavioursEnabled())return{text:"{"+f+"}",selection:!1};if(m.isSaneInsertion(n,r))return/[\]\}\)]/.test(u[s.column])||n.inMultiSelectMode?(m.recordAutoInsert(n,r,"}"),{text:"{}",selection:[1,1]}):(m.recordMaybeInsert(n,r,"{"),{text:"{",selection:[1,1]})}else if(i=="}"){var l=u.substring(s.column,s.column+1);if(l=="}"){var c=r.$findOpeningBracket("}",{column:s.column+1,row:s.row});if(c!==null&&m.isAutoInsertedClosing(s,u,i))return m.popAutoInsertedClosing(),{text:"",selection:[1,1]}}}else{if(i=="\n"||i=="\r\n"){var p="";m.isMaybeInsertedClosing(s,u)&&(p=o.stringRepeat("}",h),m.clearMaybeInsertedClosing());var l=u.substring(s.column,s.column+1);if(l==="}"){var d=r.findMatchingBracket({row:s.row,column:s.column+1},"}");if(!d)return null;var v=this.$getIndent(r.getLine(d.row))}else{if(!p)return;var v=this.$getIndent(u)}var g=v+r.getTabString();return{text:"\n"+g+"\n"+v+p,selection:[1,g.length,1,g.length]}}m.clearMaybeInsertedClosing()}}),this.add("braces","deletion",function(e,t,n,r,i){var s=r.doc.getTextRange(i);if(!i.isMultiLine()&&s=="{"){var o=r.doc.getLine(i.start.row),u=o.substring(i.end.column,i.end.column+1);if(u=="}")return i.end.column++,i;h--}}),this.add("parens","insertion",function(e,t,n,r,i){if(i=="("){var s=n.getSelectionRange(),o=r.doc.getTextRange(s);if(o!==""&&n.getWrapBehavioursEnabled())return{text:"("+o+")",selection:!1};if(m.isSaneInsertion(n,r))return m.recordAutoInsert(n,r,")"),{text:"()",selection:[1,1]}}else if(i==")"){var u=n.getCursorPosition(),a=r.doc.getLine(u.row),f=a.substring(u.column,u.column+1);if(f==")"){var l=r.$findOpeningBracket(")",{column:u.column+1,row:u.row});if(l!==null&&m.isAutoInsertedClosing(u,a,i))return m.popAutoInsertedClosing(),{text:"",selection:[1,1]}}}}),this.add("parens","deletion",function(e,t,n,r,i){var s=r.doc.getTextRange(i);if(!i.isMultiLine()&&s=="("){var o=r.doc.getLine(i.start.row),u=o.substring(i.start.column+1,i.start.column+2);if(u==")")return i.end.column++,i}}),this.add("brackets","insertion",function(e,t,n,r,i){if(i=="["){var s=n.getSelectionRange(),o=r.doc.getTextRange(s);if(o!==""&&n.getWrapBehavioursEnabled())return{text:"["+o+"]",selection:!1};if(m.isSaneInsertion(n,r))return m.recordAutoInsert(n,r,"]"),{text:"[]",selection:[1,1]}}else if(i=="]"){var u=n.getCursorPosition(),a=r.doc.getLine(u.row),f=a.substring(u.column,u.column+1);if(f=="]"){var l=r.$findOpeningBracket("]",{column:u.column+1,row:u.row});if(l!==null&&m.isAutoInsertedClosing(u,a,i))return m.popAutoInsertedClosing(),{text:"",selection:[1,1]}}}}),this.add("brackets","deletion",function(e,t,n,r,i){var s=r.doc.getTextRange(i);if(!i.isMultiLine()&&s=="["){var o=r.doc.getLine(i.start.row),u=o.substring(i.start.column+1,i.start.column+2);if(u=="]")return i.end.column++,i}}),this.add("string_dquotes","insertion",function(e,t,n,r,i){if(i=='"'||i=="'"){var s=i,o=n.getSelectionRange(),u=r.doc.getTextRange(o);if(u!==""&&u!=="'"&&u!='"'&&n.getWrapBehavioursEnabled())return{text:s+u+s,selection:!1};var a=n.getCursorPosition(),f=r.doc.getLine(a.row),l=f.substring(a.column-1,a.column);if(l=="\\")return null;var c=r.getTokens(o.start.row),h=0,p,d=-1;for(var v=0;v<c.length;v++){p=c[v],p.type=="string"?d=-1:d<0&&(d=p.value.indexOf(s));if(p.value.length+h>o.start.column)break;h+=c[v].value.length}if(!p||d<0&&p.type!=="comment"&&(p.type!=="string"||o.start.column!==p.value.length+h-1&&p.value.lastIndexOf(s)===p.value.length-1)){if(!m.isSaneInsertion(n,r))return;return{text:s+s,selection:[1,1]}}if(p&&p.type==="string"){var g=f.substring(a.column,a.column+1);if(g==s)return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(e,t,n,r,i){var s=r.doc.getTextRange(i);if(!i.isMultiLine()&&(s=='"'||s=="'")){var o=r.doc.getLine(i.start.row),u=o.substring(i.start.column+1,i.start.column+2);if(u==s)return i.end.column++,i}})};r.inherits(m,i),t.CstyleBehaviour=m}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(e,t,n){var r=e("../../lib/oop"),i=e("../../range").Range,s=e("./fold_mode").FoldMode,o=t.FoldMode=function(e){e&&(this.foldingStartMarker=new RegExp(this.foldingStartMarker.source.replace(/\|[^|]*?$/,"|"+e.start)),this.foldingStopMarker=new RegExp(this.foldingStopMarker.source.replace(/\|[^|]*?$/,"|"+e.end)))};r.inherits(o,s),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(e,t,n,r){var i=e.getLine(n),s=i.match(this.foldingStartMarker);if(s){var o=s.index;if(s[1])return this.openingBracketBlock(e,s[1],n,o);var u=e.getCommentFoldRange(n,o+s[0].length,1);return u&&!u.isMultiLine()&&(r?u=this.getSectionRange(e,n):t!="all"&&(u=null)),u}if(t==="markbegin")return;var s=i.match(this.foldingStopMarker);if(s){var o=s.index+s[0].length;return s[1]?this.closingBracketBlock(e,s[1],n,o):e.getCommentFoldRange(n,o,-1)}},this.getSectionRange=function(e,t){var n=e.getLine(t),r=n.search(/\S/),s=t,o=n.length;t+=1;var u=t,a=e.getLength();while(++t<a){n=e.getLine(t);var f=n.search(/\S/);if(f===-1)continue;if(r>f)break;var l=this.getFoldWidgetRange(e,"all",t);if(l){if(l.start.row<=s)break;if(l.isMultiLine())t=l.end.row;else if(r==f)break}u=t}return new i(s,o,u,e.getLine(u).length)}}.call(o.prototype)}),define("ace/mode/css",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/css_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/behaviour/css","ace/mode/folding/cstyle"],function(e,t,n){var r=e("../lib/oop"),i=e("./text").Mode,s=e("../tokenizer").Tokenizer,o=e("./css_highlight_rules").CssHighlightRules,u=e("./matching_brace_outdent").MatchingBraceOutdent,a=e("../worker/worker_client").WorkerClient,f=e("./behaviour/css").CssBehaviour,l=e("./folding/cstyle").FoldMode,c=function(){this.HighlightRules=o,this.$outdent=new u,this.$behaviour=new f,this.foldingRules=new l};r.inherits(c,i),function(){this.foldingRules="cStyle",this.blockComment={start:"/*",end:"*/"},this.getNextLineIndent=function(e,t,n){var r=this.$getIndent(t),i=this.getTokenizer().getLineTokens(t,e).tokens;if(i.length&&i[i.length-1].type=="comment")return r;var s=t.match(/^.*\{\s*$/);return s&&(r+=n),r},this.checkOutdent=function(e,t,n){return this.$outdent.checkOutdent(t,n)},this.autoOutdent=function(e,t,n){this.$outdent.autoOutdent(t,n)},this.createWorker=function(e){var t=new a(["ace"],"ace/mode/css_worker","Worker");return t.attachToDocument(e.getDocument()),t.on("csslint",function(t){e.setAnnotations(t.data)}),t.on("terminate",function(){e.clearAnnotations()}),t},this.$id="ace/mode/css"}.call(c.prototype),t.Mode=c}),define("ace/mode/behaviour/css",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle","ace/token_iterator"],function(e,t,n){var r=e("../../lib/oop"),i=e("../behaviour").Behaviour,s=e("./cstyle").CstyleBehaviour,o=e("../../token_iterator").TokenIterator,u=function(){this.inherit(s),this.add("colon","insertion",function(e,t,n,r,i){if(i===":"){var s=n.getCursorPosition(),u=new o(r,s.row,s.column),a=u.getCurrentToken();a&&a.value.match(/\s+/)&&(a=u.stepBackward());if(a&&a.type==="support.type"){var f=r.doc.getLine(s.row),l=f.substring(s.column,s.column+1);if(l===":")return{text:"",selection:[1,1]};if(!f.substring(s.column).match(/^\s*;/))return{text:":;",selection:[1,1]}}}}),this.add("colon","deletion",function(e,t,n,r,i){var s=r.doc.getTextRange(i);if(!i.isMultiLine()&&s===":"){var u=n.getCursorPosition(),a=new o(r,u.row,u.column),f=a.getCurrentToken();f&&f.value.match(/\s+/)&&(f=a.stepBackward());if(f&&f.type==="support.type"){var l=r.doc.getLine(i.start.row),c=l.substring(i.end.column,i.end.column+1);if(c===";")return i.end.column++,i}}}),this.add("semicolon","insertion",function(e,t,n,r,i){if(i===";"){var s=n.getCursorPosition(),o=r.doc.getLine(s.row),u=o.substring(s.column,s.column+1);if(u===";")return{text:"",selection:[1,1]}}})};r.inherits(u,s),t.CssBehaviour=u}),define("ace/mode/behaviour/html",["require","exports","module","ace/lib/oop","ace/mode/behaviour/xml","ace/mode/behaviour/cstyle","ace/token_iterator"],function(e,t,n){function a(e,t){var n=e.type.split(".");return t.split(".").every(function(e){return n.indexOf(e)!==-1})}var r=e("../../lib/oop"),i=e("../behaviour/xml").XmlBehaviour,s=e("./cstyle").CstyleBehaviour,o=e("../../token_iterator").TokenIterator,u=["area","base","br","col","command","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],f=function(){this.inherit(i),this.add("autoclosing","insertion",function(e,t,n,r,i){if(i==">"){var s=n.getCursorPosition(),f=new o(r,s.row,s.column),l=f.getCurrentToken();if(l&&a(l,"string")&&f.getCurrentTokenColumn()+l.value.length>s.column)return;var c=!1;if(!l||!a(l,"meta.tag")&&(!a(l,"text")||!l.value.match("/"))){do l=f.stepBackward();while(l&&(a(l,"string")||a(l,"keyword.operator")||a(l,"entity.attribute-name")||a(l,"text")))}else c=!0;if(!l||!a(l,"meta.tag.name")||f.stepBackward().value.match("/"))return;var h=l.value;if(c)var h=h.substring(0,s.column-l.start);if(u.indexOf(h)!==-1)return;return{text:"></"+h+">",selection:[1,1]}}})};r.inherits(f,i),t.HtmlBehaviour=f}),define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle","ace/token_iterator"],function(e,t,n){function u(e,t)
var n=e.type.split(".");return t.split(".").every(function(e){return n.indexOf(e)!==-1})}var r=e("../../lib/oop"),i=e("../behaviour").Behaviour,s=e("./cstyle").CstyleBehaviour,o=e("../../token_iterator").TokenIterator,a=function(){this.inherit(s,["string_dquotes"]),this.add("autoclosing","insertion",function(e,t,n,r,i){if(i==">"){var s=n.getCursorPosition(),a=new o(r,s.row,s.column),f=a.getCurrentToken();if(f&&u(f,"string")&&a.getCurrentTokenColumn()+f.value.length>s.column)return;var l=!1;if(!f||!u(f,"meta.tag")&&(!u(f,"text")||!f.value.match("/"))){do f=a.stepBackward();while(f&&(u(f,"string")||u(f,"keyword.operator")||u(f,"entity.attribute-name")||u(f,"text")))}else l=!0;if(!f||!u(f,"meta.tag.name")||a.stepBackward().value.match("/"))return;var c=f.value;if(l)var c=c.substring(0,s.column-f.start);return{text:"></"+c+">",selection:[1,1]}}}),this.add("autoindent","insertion",function(e,t,n,r,i){if(i=="\n"){var s=n.getCursorPosition(),o=r.getLine(s.row),u=o.substring(s.column,s.column+2);if(u=="</"){var a=this.$getIndent(o),f=a+r.getTabString();return{text:"\n"+f+"\n"+a,selection:[1,f.length,1,f.length]}}}})};r.inherits(a,i),t.XmlBehaviour=a}),define("ace/mode/folding/html",["require","exports","module","ace/lib/oop","ace/mode/folding/mixed","ace/mode/folding/xml","ace/mode/folding/cstyle"],function(e,t,n){var r=e("../../lib/oop"),i=e("./mixed").FoldMode,s=e("./xml").FoldMode,o=e("./cstyle").FoldMode,u=t.FoldMode=function(){i.call(this,new s({area:1,base:1,br:1,col:1,command:1,embed:1,hr:1,img:1,input:1,keygen:1,link:1,meta:1,param:1,source:1,track:1,wbr:1,li:1,dt:1,dd:1,p:1,rt:1,rp:1,optgroup:1,option:1,colgroup:1,td:1,th:1}),{"js-":new o,"css-":new o})};r.inherits(u,i)}),define("ace/mode/folding/mixed",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode"],function(e,t,n){var r=e("../../lib/oop"),i=e("./fold_mode").FoldMode,s=t.FoldMode=function(e,t){this.defaultMode=e,this.subModes=t};r.inherits(s,i),function(){this.$getMode=function(e){typeof e!="string"&&(e=e[0]);for(var t in this.subModes)if(e.indexOf(t)===0)return this.subModes[t];return null},this.$tryMode=function(e,t,n,r){var i=this.$getMode(e);return i?i.getFoldWidget(t,n,r):""},this.getFoldWidget=function(e,t,n){return this.$tryMode(e.getState(n-1),e,t,n)||this.$tryMode(e.getState(n),e,t,n)||this.defaultMode.getFoldWidget(e,t,n)},this.getFoldWidgetRange=function(e,t,n){var r=this.$getMode(e.getState(n-1));if(!r||!r.getFoldWidget(e,t,n))r=this.$getMode(e.getState(n));if(!r||!r.getFoldWidget(e,t,n))r=this.defaultMode;return r.getFoldWidgetRange(e,t,n)}}.call(s.prototype)}),define("ace/mode/folding/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/range","ace/mode/folding/fold_mode","ace/token_iterator"],function(e,t,n){var r=e("../../lib/oop"),i=e("../../lib/lang"),s=e("../../range").Range,o=e("./fold_mode").FoldMode,u=e("../../token_iterator").TokenIterator,a=t.FoldMode=function(e){o.call(this),this.voidElements=e||{}};r.inherits(a,o),function(){this.getFoldWidget=function(e,t,n){var r=this._getFirstTagInLine(e,n);return r.closing?t=="markbeginend"?"end":"":!r.tagName||this.voidElements[r.tagName.toLowerCase()]?"":r.selfClosing?"":r.value.indexOf("/"+r.tagName)!==-1?"":"start"},this._getFirstTagInLine=function(e,t){var n=e.getTokens(t),r="";for(var s=0;s<n.length;s++){var o=n[s];o.type.lastIndexOf("meta.tag",0)===0?r+=o.value:r+=i.stringRepeat(" ",o.value.length)}return this._parseTag(r)},this.tagRe=/^(\s*)(<?(\/?)([-_a-zA-Z0-9:!]*)\s*(\/?)>?)/,this._parseTag=function(e){var t=e.match(this.tagRe),n=0;return{value:e,match:t?t[2]:"",closing:t?!!t[3]:!1,selfClosing:t?!!t[5]||t[2]=="/>":!1,tagName:t?t[4]:"",column:t[1]?n+t[1].length:n}},this._readTagForward=function(e){var t=e.getCurrentToken();if(!t)return null;var n="",r;do if(t.type.lastIndexOf("meta.tag",0)===0){if(!r)var r={row:e.getCurrentTokenRow(),column:e.getCurrentTokenColumn()};n+=t.value;if(n.indexOf(">")!==-1){var i=this._parseTag(n);return i.start=r,i.end={row:e.getCurrentTokenRow(),column:e.getCurrentTokenColumn()+t.value.length},e.stepForward(),i}}while(t=e.stepForward());return null},this._readTagBackward=function(e){var t=e.getCurrentToken();if(!t)return null;var n="",r;do if(t.type.lastIndexOf("meta.tag",0)===0){r||(r={row:e.getCurrentTokenRow(),column:e.getCurrentTokenColumn()+t.value.length}),n=t.value+n;if(n.indexOf("<")!==-1){var i=this._parseTag(n);return i.end=r,i.start={row:e.getCurrentTokenRow(),column:e.getCurrentTokenColumn()},e.stepBackward(),i}}while(t=e.stepBackward());return null},this._pop=function(e,t){while(e.length){var n=e[e.length-1];if(!t||n.tagName==t.tagName)return e.pop();if(this.voidElements[t.tagName])return;if(this.voidElements[n.tagName]){e.pop();continue}return null}},this.getFoldWidgetRange=function(e,t,n){var r=this._getFirstTagInLine(e,n);if(!r.match)return null;var i=r.closing||r.selfClosing,o=[],a;if(!i){var f=new u(e,n,r.column),l={row:n,column:r.column+r.tagName.length+2};while(a=this._readTagForward(f)){if(a.selfClosing){if(!o.length)return a.start.column+=a.tagName.length+2,a.end.column-=2,s.fromPoints(a.start,a.end);continue}if(a.closing){this._pop(o,a);if(o.length==0)return s.fromPoints(l,a.start)}else o.push(a)}}else{var f=new u(e,n,r.column+r.match.length),c={row:n,column:r.column};while(a=this._readTagBackward(f)){if(a.selfClosing){if(!o.length)return a.start.column+=a.tagName.length+2,a.end.column-=2,s.fromPoints(a.start,a.end);continue}if(!a.closing){this._pop(o,a);if(o.length==0)return a.start.column+=a.tagName.length+2,s.fromPoints(a.start,c)}else o.push(a)}}}}.call(a.prototype)}),define("ace/mode/html_completions",["require","exports","module","ace/token_iterator"],function(e,t,n){function f(e,t){var n=e.type.split(".");return t.split(".").every(function(e){return n.indexOf(e)!==-1})}function l(e,t){var n=new r(e,t.row,t.column),i=n.getCurrentToken();if(!i||!f(i,"tag")&&(!f(i,"text")||!i.value.match("/")))do i=n.stepBackward();while(i&&(f(i,"string")||f(i,"operator")||f(i,"attribute-name")||f(i,"text")));if(i&&f(i,"tag.name")&&!n.stepBackward().value.match("/"))return i.value}var r=e("../token_iterator").TokenIterator,i=["accesskey","class","contenteditable","contextmenu","dir","draggable","dropzone","hidden","id","lang","spellcheck","style","tabindex","title","translate"],s=["onabort","onblur","oncancel","oncanplay","oncanplaythrough","onchange","onclick","onclose","oncontextmenu","oncuechange","ondblclick","ondrag","ondragend","ondragenter","ondragleave","ondragover","ondragstart","ondrop","ondurationchange","onemptied","onended","onerror","onfocus","oninput","oninvalid","onkeydown","onkeypress","onkeyup","onload","onloadeddata","onloadedmetadata","onloadstart","onmousedown","onmousemove","onmouseout","onmouseover","onmouseup","onmousewheel","onpause","onplay","onplaying","onprogress","onratechange","onreset","onscroll","onseeked","onseeking","onselect","onshow","onstalled","onsubmit","onsuspend","ontimeupdate","onvolumechange","onwaiting"],o=i.concat(s),u={html:["manifest"],head:[],title:[],base:["href","target"],link:["href","hreflang","rel","media","type","sizes"],meta:["http-equiv","name","content","charset"],style:["type","media","scoped"],script:["charset","type","src","defer","async"],noscript:["href"],body:["onafterprint","onbeforeprint","onbeforeunload","onhashchange","onmessage","onoffline","onpopstate","onredo","onresize","onstorage","onundo","onunload"],section:[],nav:[],article:["pubdate"],aside:[],h1:[],h2:[],h3:[],h4:[],h5:[],h6:[],header:[],footer:[],address:[],main:[],p:[],hr:[],pre:[],blockquote:["cite"],ol:["start","reversed"],ul:[],li:["value"],dl:[],dt:[],dd:[],figure:[],figcaption:[],div:[],a:["href","target","ping","rel","media","hreflang","type"],em:[],strong:[],small:[],s:[],cite:[],q:["cite"],dfn:[],abbr:[],data:[],time:["datetime"],code:[],"var":[],samp:[],kbd:[],sub:[],sup:[],i:[],b:[],u:[],mark:[],ruby:[],rt:[],rp:[],bdi:[],bdo:[],span:[],br:[],wbr:[],ins:["cite","datetime"],del:["cite","datetime"],img:["alt","src","height","width","usemap","ismap"],iframe:["name","src","height","width","sandbox","seamless"],embed:["src","height","width","type"],object:["param","data","type","height","width","usemap","name","form","classid"],param:["name","value"],video:["src","autobuffer","autoplay","loop","controls","width","height","poster"],audio:["src","autobuffer","autoplay","loop","controls"],source:["src","type","media"],track:["kind","src","srclang","label","default"],canvas:["width","height"],map:["name"],area:["shape","coords","href","hreflang","alt","target","media","rel","ping","type"],svg:[],math:[],table:["summary"],caption:[],colgroup:["span"],col:["span"],tbody:[],thead:[],tfoot:[],tr:[],td:["headers","rowspan","colspan"],th:["headers","rowspan","colspan","scope"],form:["accept-charset","action","autocomplete","enctype","method","name","novalidate","target"],fieldset:["disabled","form","name"],legend:[],label:["form","for"],input:["type","accept","alt","autocomplete","checked","disabled","form","formaction","formenctype","formmethod","formnovalidate","formtarget","height","list","max","maxlength","min","multiple","pattern","placeholder","readonly","required","size","src","step","width","files","value"],button:["autofocus","disabled","form","formaction","formenctype","formmethod","formnovalidate","formtarget","name","value","type"],select:["autofocus","disabled","form","multiple","name","size"],datalist:[],optgroup:["disabled","label"],option:["disabled","selected","label","value"],textarea:["autofocus","disabled","form","maxlength","name","placeholder","readonly","required","rows","cols","wrap"],keygen:["autofocus","challenge","disabled","form","keytype","name"],output:["for","form","name"],progress:["value","max"],meter:["value","min","max","low","high","optimum"],details:["open"],summary:[],command:["type","label","icon","disabled","checked","radiogroup","command"],menu:["type","label"],dialog:["open"]},a=Object.keys(u),c=function(){};(function(){this.getCompletions=function(e,t,n,r){var i=t.getTokenAt(n.row,n.column);return i?f(i,"tag.name")||i.value=="<"&&f(i,"text")?this.getTagCompletions(e,t,n,r):f(i,"text")||f(i,"attribute-name")?this.getAttributeCompetions(e,t,n,r):[]:[]},this.getTagCompletions=function(e,t,n,r){var i=a;return r&&(i=i.filter(function(e){return e.indexOf(r)===0})),i.map(function(e){return{value:e,meta:"tag"}})},this.getAttributeCompetions=function(e,t,n,r){var i=l(t,n);if(!i)return[];var s=o;return i in u&&(s=s.concat(u[i])),r&&(s=s.filter(function(e){return e.indexOf(r)===0})),s.map(function(e){return{caption:e,snippet:e+'="$0"',meta:"attribute"}})}}).call(c.prototype),t.HtmlCompletions=c}),define("ace/mode/ruby",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/ruby_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/mode/folding/coffee"],function(e,t,n){var r=e("../lib/oop"),i=e("./text").Mode,s=e("../tokenizer").Tokenizer,o=e("./ruby_highlight_rules").RubyHighlightRules,u=e("./matching_brace_outdent").MatchingBraceOutdent,a=e("../range").Range,f=e("./folding/coffee").FoldMode,l=function(){this.HighlightRules=o,this.$outdent=new u,this.foldingRules=new f};r.inherits(l,i),function(){this.lineCommentStart="#",this.getNextLineIndent=function(e,t,n){var r=this.$getIndent(t),i=this.getTokenizer().getLineTokens(t,e),s=i.tokens;if(s.length&&s[s.length-1].type=="comment")return r;if(e=="start"){var o=t.match(/^.*[\{\(\[]\s*$/),u=t.match(/^\s*(class|def)\s.*$/),a=t.match(/.*do(\s*|\s+\|.*\|\s*)$/),f=t.match(/^\s*(if|else)\s*/);if(o||u||a||f)r+=n}return r},this.checkOutdent=function(e,t,n){return/^\s+end$/.test(t+n)||/^\s+}$/.test(t+n)||/^\s+else$/.test(t+n)},this.autoOutdent=function(e,t,n){var r=this.$getIndent(t.getLine(n)),i=t.getTabString();r.slice(-i.length)==i&&t.remove(new a(n,r.length-i.length,n,r.length))},this.$id="ace/mode/ruby"}.call(l.prototype),t.Mode=l}),define("ace/mode/ruby_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(e,t,n){var r=e("../lib/oop"),i=e("./text_highlight_rules").TextHighlightRules,s=t.constantOtherSymbol={token:"constant.other.symbol.ruby",regex:"[:](?:[A-Za-z_]|[@$](?=[a-zA-Z0-9_]))[a-zA-Z0-9_]*[!=?]?"},o=t.qString={token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},u=t.qqString={token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},a=t.tString={token:"string",regex:"[`](?:(?:\\\\.)|(?:[^'\\\\]))*?[`]"},f=t.constantNumericHex={token:"constant.numeric",regex:"0[xX][0-9a-fA-F](?:[0-9a-fA-F]|_(?=[0-9a-fA-F]))*\\b"},l=t.constantNumericFloat={token:"constant.numeric",regex:"[+-]?\\d(?:\\d|_(?=\\d))*(?:(?:\\.\\d(?:\\d|_(?=\\d))*)?(?:[eE][+-]?\\d+)?)?\\b"},c=function(){var e="abort|Array|assert|assert_equal|assert_not_equal|assert_same|assert_not_same|assert_nil|assert_not_nil|assert_match|assert_no_match|assert_in_delta|assert_throws|assert_raise|assert_nothing_raised|assert_instance_of|assert_kind_of|assert_respond_to|assert_operator|assert_send|assert_difference|assert_no_difference|assert_recognizes|assert_generates|assert_response|assert_redirected_to|assert_template|assert_select|assert_select_email|assert_select_rjs|assert_select_encoded|css_select|at_exit|attr|attr_writer|attr_reader|attr_accessor|attr_accessible|autoload|binding|block_given?|callcc|caller|catch|chomp|chomp!|chop|chop!|defined?|delete_via_redirect|eval|exec|exit|exit!|fail|Float|flunk|follow_redirect!|fork|form_for|form_tag|format|gets|global_variables|gsub|gsub!|get_via_redirect|host!|https?|https!|include|Integer|lambda|link_to|link_to_unless_current|link_to_function|link_to_remote|load|local_variables|loop|open|open_session|p|print|printf|proc|putc|puts|post_via_redirect|put_via_redirect|raise|rand|raw|readline|readlines|redirect?|request_via_redirect|require|scan|select|set_trace_func|sleep|split|sprintf|srand|String|stylesheet_link_tag|syscall|system|sub|sub!|test|throw|trace_var|trap|untrace_var|atan2|cos|exp|frexp|ldexp|log|log10|sin|sqrt|tan|render|javascript_include_tag|csrf_meta_tag|label_tag|text_field_tag|submit_tag|check_box_tag|content_tag|radio_button_tag|text_area_tag|password_field_tag|hidden_field_tag|fields_for|select_tag|options_for_select|options_from_collection_for_select|collection_select|time_zone_select|select_date|select_time|select_datetime|date_select|time_select|datetime_select|select_year|select_month|select_day|select_hour|select_minute|select_second|file_field_tag|file_field|respond_to|skip_before_filter|around_filter|after_filter|verify|protect_from_forgery|rescue_from|helper_method|redirect_to|before_filter|send_data|send_file|validates_presence_of|validates_uniqueness_of|validates_length_of|validates_format_of|validates_acceptance_of|validates_associated|validates_exclusion_of|validates_inclusion_of|validates_numericality_of|validates_with|validates_each|authenticate_or_request_with_http_basic|authenticate_or_request_with_http_digest|filter_parameter_logging|match|get|post|resources|redirect|scope|assert_routing|translate|localize|extract_locale_from_tld|caches_page|expire_page|caches_action|expire_action|cache|expire_fragment|expire_cache_for|observe|cache_sweeper|has_many|has_one|belongs_to|has_and_belongs_to_many",t="alias|and|BEGIN|begin|break|case|class|def|defined|do|else|elsif|END|end|ensure|__FILE__|finally|for|gem|if|in|__LINE__|module|next|not|or|private|protected|public|redo|rescue|retry|return|super|then|undef|unless|until|when|while|yield",n="true|TRUE|false|FALSE|nil|NIL|ARGF|ARGV|DATA|ENV|RUBY_PLATFORM|RUBY_RELEASE_DATE|RUBY_VERSION|STDERR|STDIN|STDOUT|TOPLEVEL_BINDING",r="$DEBUG|$defout|$FILENAME|$LOAD_PATH|$SAFE|$stdin|$stdout|$stderr|$VERBOSE|$!|root_url|flash|session|cookies|params|request|response|logger|self",i=this.$keywords=this.createKeywordMapper({keyword:t,"constant.language":n,"variable.language":r,"support.function":e,"invalid.deprecated":"debugger"},"identifier");this.$rules={start:[{token:"comment",regex:"#.*$"},{token:"comment",regex:"^=begin(?:$|\\s.*$)",next:"comment"},{token:"string.regexp",regex:"[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"},o,u,a,{token:"text",regex:"::"},{token:"variable.instance",regex:"@{1,2}[a-zA-Z_\\d]+"},{token:"support.class",regex:"[A-Z][a-zA-Z_\\d]+"},s,f,l,{token:"constant.language.boolean",regex:"(?:true|false)\\b"},{token:i,regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"punctuation.separator.key-value",regex:"=>"},{stateName:"heredoc",onMatch:function(e,t,n){var r=e[2]=="-"?"indentedHeredoc":"heredoc",i=e.split(this.splitRegex);return n.push(r,i[3]),[{type:"constant",value:i[1]},{type:"string",value:i[2]},{type:"support.class",value:i[3]},{type:"string",value:i[4]}]},regex:"(<<-?)(['\"`]?)([\\w]+)(['\"`]?)",rules:{heredoc:[{onMatch:function(e,t,n){return e===n[1]?(n.shift(),n.shift(),this.next=n[0]||"start","support.class"):(this.next="","string")},regex:".*$",next:"start"}],indentedHeredoc:[{token:"string",regex:"^ +"},{onMatch:function(e,t,n){return e===n[1]?(n.shift(),n.shift(),this.next=n[0]||"start","support.class"):(this.next="","string")},regex:".*$",next:"start"}]}},{regex:"$",token:"empty",next:function(e,t){return t[0]==="heredoc"||t[0]==="indentedHeredoc"?t[0]:e}},{token:"keyword.operator",regex:"!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"},{token:"paren.lparen",regex:"[[({]"},{token:"paren.rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:"^=end(?:$|\\s.*$)",next:"start"},{token:"comment",regex:".+"}]},this.normalizeRules()};r.inherits(c,i),t.RubyHighlightRules=c}),define("ace/mode/folding/coffee",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode","ace/range"],function(e,t,n){var r=e("../../lib/oop"),i=e("./fold_mode").FoldMode,s=e("../../range").Range,o=t.FoldMode=function(){};r.inherits(o,i),function(){this.getFoldWidgetRange=function(e,t,n){var r=this.indentationBlock(e,n);if(r)return r;var i=/\S/,o=e.getLine(n),u=o.search(i);if(u==-1||o[u]!="#")return;var a=o.length,f=e.getLength(),l=n,c=n;while(++n<f){o=e.getLine(n);var h=o.search(i);if(h==-1)continue;if(o[h]!="#")break;c=n}if(c>l){var p=e.getLine(c).length;return new s(l,a,c,p)}},this.getFoldWidget=function(e,t,n){var r=e.getLine(n),i=r.search(/\S/),s=e.getLine(n+1),o=e.getLine(n-1),u=o.search(/\S/),a=s.search(/\S/);if(i==-1)return e.foldWidgets[n-1]=u!=-1&&u<a?"start":"","";if(u==-1){if(i==a&&r[i]=="#"&&s[i]=="#")return e.foldWidgets[n-1]="",e.foldWidgets[n+1]="","start"}else if(u==i&&r[i]=="#"&&o[i]=="#"&&e.getLine(n-2).search(/\S/)==-1)return e.foldWidgets[n-1]="start",e.foldWidgets[n+1]="","";return u!=-1&&u<i?e.foldWidgets[n-1]="start":e.foldWidgets[n-1]="",i<a?"start":""}}.call(o.prototype)})
{
nmtf_core.py
"""Non-negative matrix and tensor factorization core functions """ # Author: Paul Fogel # License: MIT # Jan 4, '20 from typing import Tuple import numpy as np from .nmtf_utils import EPSILON, sparse_opt import logging logger = logging.getLogger(__name__) # TODO (pcotte): typing # TODO (pcotte): docstrings (with parameters and returns) def ntf_stack(m, mmis, n_blocks): """Unfold tensor M for future use with NMF """ n, p = m.shape mmis = mmis.astype(np.int) n_mmis = mmis.shape[0] n_blocks = int(n_blocks) mstacked = np.zeros((int(n * p / n_blocks), n_blocks)) if n_mmis > 0: mmis_stacked = np.zeros((int(n * p / n_blocks), n_blocks)) else: mmis_stacked = np.array([]) for i_block in range(0, n_blocks): for j in range(0, int(p / n_blocks)): i1 = j * n i2 = i1 + n mstacked[i1:i2, i_block] = m[:, int(i_block * p / n_blocks + j)] if n_mmis > 0: mmis_stacked[i1:i2, i_block] = mmis[:, int(i_block * p / n_blocks + j)] return mstacked, mmis_stacked def ntf_solve( m, mmis, mt0, mw0, mb0, nc, tolerance, log_iter, status0, max_iterations, nmf_fix_user_lhe, nmf_fix_user_rhe, nmf_fix_user_bhe, nmf_sparse_level, ntf_unimodal, ntf_smooth, ntf_left_components, ntf_right_components, ntf_block_components, n_blocks, nmf_priors, my_status_box, ): """Interface to: - NTFSolve_simple """ if len(nmf_priors) > 0: n_nmf_priors, nc = nmf_priors.shape else: n_nmf_priors = 0 if n_nmf_priors > 0: nmf_priors[nmf_priors > 0] = 1 return ntf_solve_simple( m=m, mmis=mmis, mt0=mt0, mw0=mw0, mb0=mb0, nc=nc, tolerance=tolerance, log_iter=log_iter, status0=status0, max_iterations=max_iterations, nmf_fix_user_lhe=nmf_fix_user_lhe, nmf_fix_user_rhe=nmf_fix_user_rhe, nmf_fix_user_bhe=nmf_fix_user_bhe, nmf_sparse_level=nmf_sparse_level, ntf_unimodal=ntf_unimodal, ntf_smooth=ntf_smooth, ntf_left_components=ntf_left_components, ntf_right_components=ntf_right_components, ntf_block_components=ntf_block_components, n_blocks=n_blocks, nmf_priors=nmf_priors, my_status_box=my_status_box, ) def ntf_solve_simple( m, mmis, mt0, mw0, mb0, nc, tolerance, log_iter, status0, max_iterations, nmf_fix_user_lhe, nmf_fix_user_rhe, nmf_fix_user_bhe, nmf_sparse_level, ntf_unimodal, ntf_smooth, ntf_left_components, ntf_right_components, ntf_block_components, n_blocks, nmf_priors, my_status_box, ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, float, int]: """ Estimate NTF matrices (HALS) Parameters ---------- m: Input matrix mmis: Define missing values (0 = missing cell, 1 = real cell) mt0: Initial left hand matrix mw0: Initial right hand matrix mb0: Initial block hand matrix nc: NTF rank tolerance: Convergence threshold log_iter: Log results through iterations status0: Initial displayed status to be updated during iterations max_iterations: Max iterations nmf_fix_user_lhe: = 1 => fixed left hand matrix columns nmf_fix_user_rhe: = 1 => fixed right hand matrix columns nmf_fix_user_bhe: = 1 => fixed block hand matrix columns nmf_sparse_level: sparsity level (as defined by Hoyer); +/- = make RHE/LHe sparse ntf_unimodal: Apply Unimodal constraint on factoring vectors ntf_smooth: Apply Smooth constraint on factoring vectors ntf_left_components: Apply Unimodal/Smooth constraint on left hand matrix ntf_right_components: Apply Unimodal/Smooth constraint on right hand matrix ntf_block_components: Apply Unimodal/Smooth constraint on block hand matrix n_blocks: Number of NTF blocks nmf_priors: Elements in mw that should be updated (others remain 0) my_status_box Returns ------- Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, float, int]\n * mt: Left hand matrix\n * mw: Right hand matrix\n * mb: Block hand matrix\n * diff: objective cost\n * cancel_pressed\n Reference --------- a. Cichocki, P.H.a.N. Anh-Huym, Fast local algorithms for large scale nonnegative matrix and tensor factorizations, IEICE Trans. Fundam. Electron. Commun. Comput. Sci. 92 (3) (2009) 708–721. """ cancel_pressed = 0 n, p0 = m.shape n_mmis = mmis.shape[0] nc = int(nc) n_blocks = int(n_blocks) p = int(p0 / n_blocks) nxp = int(n * p) nxp0 = int(n * p0) mt = np.copy(mt0) mw = np.copy(mw0) mb = np.copy(mb0) # step_iter = math.ceil(MaxIterations/10) step_iter = 1 pbar_step = 100 * step_iter / max_iterations id_blockp = np.arange(0, (n_blocks - 1) * p + 1, p) a = np.zeros(n) b = np.zeros(p) c = np.zeros(n_blocks) alpha = np.zeros(nc) # Compute Residual tensor mfit = np.zeros((n, p0)) for k in range(0, nc): if n_blocks > 1: for i_block in range(0, n_blocks): mfit[:, id_blockp[i_block]: id_blockp[i_block] + p] += ( mb[i_block, k] * np.reshape(mt[:, k], (n, 1)) @ np.reshape(mw[:, k], (1, p)) ) else: mfit[:, id_blockp[0]: id_blockp[0] + p] += np.reshape(mt[:, k], (n, 1)) @ np.reshape(mw[:, k], (1, p)) denomt = np.zeros(n) denomw = np.zeros(p) denom_block = np.zeros((n_blocks, nc)) mt2 = np.zeros(n) mw2 = np.zeros(p) mt_mw = np.zeros(nxp) denom_cutoff = 0.1 if n_mmis > 0: mres = (m - mfit) * mmis else: mres = m - mfit my_status_box.init_bar() # Loop cont = 1 i_iter = 0 diff0 = 1.0e99 mpart = np.zeros((n, p0)) if abs(nmf_sparse_level) < 1: alpha[0] = nmf_sparse_level * 0.8 else: alpha[0] = nmf_sparse_level percent_zeros = 0 iter_sparse = 0 while (cont > 0) & (i_iter < max_iterations): for k in range(0, nc): ( n_blocks, mpart, id_blockp, p, mb, k, mt, n, mw, n_mmis, mmis, mres, nmf_fix_user_lhe, denomt, mw2, denom_cutoff, alpha, ntf_unimodal, ntf_left_components, ntf_smooth, a, nmf_fix_user_rhe, denomw, mt2, ntf_right_components, b, nmf_fix_user_bhe, mt_mw, nxp, denom_block, ntf_block_components, c, mfit, nmf_priors, ) = ntf_update( n_blocks=n_blocks, mpart=mpart, id_blockp=id_blockp, p=p, mb=mb, k=k, mt=mt, n=n, mw=mw, n_mmis=n_mmis, mmis=mmis, mres=mres, nmf_fix_user_lhe=nmf_fix_user_lhe, denomt=denomt, mw2=mw2, denom_cutoff=denom_cutoff, alpha=alpha, ntf_unimodal=ntf_unimodal, ntf_left_components=ntf_left_components, ntf_smooth=ntf_smooth, a=a, nmf_fix_user_rhe=nmf_fix_user_rhe, denomw=denomw, mt2=mt2, ntf_right_components=ntf_right_components, b=b, nmf_fix_user_bhe=nmf_fix_user_bhe, mt_mw=mt_mw, nxp=nxp, denom_block=denom_block, ntf_block_components=ntf_block_components, c=c, mfit=mfit, nmf_priors=nmf_priors, ) if i_iter % step_iter == 0: # Check convergence diff = np.linalg.norm(mres) ** 2 / nxp0 if (diff0 - diff) / diff0 < tolerance: cont = 0 else: if diff > diff0: my_status_box.my_print(f"{status0} Iter: {i_iter} MSR does not improve") diff0 = diff Status = f"{status0} Iteration: {i_iter}" if nmf_sparse_level != 0: Status = f"{Status} ; Achieved sparsity: {round(percent_zeros, 2)}; alpha: {round(alpha[0], 2)}" if log_iter == 1: my_status_box.my_print(Status) my_status_box.update_status(status=Status) my_status_box.update_bar(step=pbar_step) if my_status_box.cancel_pressed: cancel_pressed = 1 return np.array([]), mt, mw, mb, mres, cancel_pressed if log_iter == 1: my_status_box.my_print(status0 + " Iter: " + str(i_iter) + " MSR: " + str(diff)) i_iter += 1 if cont == 0 or i_iter == max_iterations or (cont == 0 and abs(nmf_sparse_level) == 1): if 0 < nmf_sparse_level < 1: sparse_test = np.zeros((nc, 1)) percent_zeros0 = percent_zeros for k in range(0, nc): sparse_test[k] = np.where(mw[:, k] == 0)[0].size percent_zeros = np.mean(sparse_test) / p if percent_zeros < percent_zeros0: iter_sparse += 1 else: iter_sparse = 0 if (percent_zeros < 0.99 * nmf_sparse_level) & (iter_sparse < 50): alpha[0] *= min(1.05 * nmf_sparse_level / percent_zeros, 1.1) if alpha[0] < 1: i_iter = 0 cont = 1 elif 0 > nmf_sparse_level > -1: sparse_test = np.zeros((nc, 1)) percent_zeros0 = percent_zeros for k in range(0, nc): sparse_test[k] = np.where(mt[:, k] == 0)[0].size percent_zeros = np.mean(sparse_test) / n if percent_zeros < percent_zeros0: iter_sparse += 1 else: iter_sparse = 0 if (percent_zeros < 0.99 * abs(nmf_sparse_level)) & (iter_sparse < 50): alpha[0] *= min(1.05 * abs(nmf_sparse_level) / percent_zeros, 1.1) if abs(alpha[0]) < 1: i_iter = 0 cont = 1 elif abs(alpha[0]) == 1: if alpha[0] == -1: for k in range(0, nc): if np.max(mt[:, k]) > 0: hhi = int( np.round( (np.linalg.norm(mt[:, k], ord=1) / (np.linalg.norm(mt[:, k], ord=2) + EPSILON)) ** 2, decimals=0, ) ) alpha[k] = -1 - (n - hhi) / (n - 1) else: alpha[k] = 0 else: for k in range(0, nc): if np.max(mw[:, k]) > 0: hhi = int( np.round( (np.linalg.norm(mw[:, k], ord=1) / (np.linalg.norm(mw[:, k], ord=2) + EPSILON)) ** 2, decimals=0, ) ) alpha[k] = 1 + (p - hhi) / (p - 1) else: alpha[k] = 0 if alpha[0] <= -1: alpha_real = -(alpha + 1) # noinspection PyTypeChecker alpha_min = min(alpha_real) for k in range(0, nc): # noinspection PyUnresolvedReferences alpha[k] = min(alpha_real[k], 2 * alpha_min) alpha[k] = -alpha[k] - 1 else: alpha_real = alpha - 1 alpha_min = min(alpha_real) for k in range(0, nc): alpha[k] = min(alpha_real[k], 2 * alpha_min) alpha[k] = alpha[k] + 1 i_iter = 0 cont = 1 diff0 = 1.0e99 for k in range(0, nc): hhi = np.round((np.linalg.norm(mt[:, k], ord=1) / np.linalg.norm(mt[:, k], ord=2)) ** 2, decimals=0) logger.info(f"component: {k}, left hhi: {hhi}") hhi = np.round((np.linalg.norm(mw[:, k], ord=1) / np.linalg.norm(mw[:, k], ord=2)) ** 2, decimals=0) logger.info(f"component: {k} right hhi: {hhi}") if (n_mmis > 0) & (nmf_fix_user_bhe == 0): mb *= denom_block # TODO (pcotte): mt and mw can be not yet referenced: fix that return np.array([]), mt, mw, mb, diff, cancel_pressed def ntf_update( n_blocks, mpart, id_blockp, p, mb, k, mt, n, mw, n_mmis, mmis, mres,
nmf_fix_user_lhe, denomt, mw2, denom_cutoff, alpha, ntf_unimodal, ntf_left_components, ntf_smooth, a, nmf_fix_user_rhe, denomw, mt2, ntf_right_components, b, nmf_fix_user_bhe, mt_mw, nxp, denom_block, ntf_block_components, c, mfit, nmf_priors, ): """Core updating code called by NTFSolve_simple & NTF Solve_conv Input: All variables in the calling function used in the function Output: Same as Input """ if len(nmf_priors) > 0: n_nmf_priors, nc = nmf_priors.shape else: n_nmf_priors = 0 # Compute kth-part if n_blocks > 1: for i_block in range(0, n_blocks): mpart[:, id_blockp[i_block]: id_blockp[i_block] + p] = ( mb[i_block, k] * np.reshape(mt[:, k], (n, 1)) @ np.reshape(mw[:, k], (1, p)) ) else: mpart[:, id_blockp[0]: id_blockp[0] + p] = np.reshape(mt[:, k], (n, 1)) @ np.reshape(mw[:, k], (1, p)) if n_mmis > 0: mpart *= mmis mpart += mres if nmf_fix_user_bhe > 0: norm_bhe = True if nmf_fix_user_rhe == 0: norm_lhe = True norm_rhe = False else: norm_lhe = False norm_rhe = True else: norm_bhe = False norm_lhe = True norm_rhe = True if (nmf_fix_user_lhe > 0) & norm_lhe: norm = np.linalg.norm(mt[:, k]) if norm > 0: mt[:, k] /= norm if (nmf_fix_user_rhe > 0) & norm_rhe: norm = np.linalg.norm(mw[:, k]) if norm > 0: mw[:, k] /= norm if (nmf_fix_user_bhe > 0) & norm_bhe & (n_blocks > 1): norm = np.linalg.norm(mb[:, k]) if norm > 0: mb[:, k] /= norm if nmf_fix_user_lhe == 0: # Update Mt mt[:, k] = 0 if n_blocks > 1: for i_block in range(0, n_blocks): mt[:, k] += mb[i_block, k] * mpart[:, id_blockp[i_block]: id_blockp[i_block] + p] @ mw[:, k] else: mt[:, k] += mpart[:, id_blockp[0]: id_blockp[0] + p] @ mw[:, k] if n_mmis > 0: denomt[:] = 0 mw2[:] = mw[:, k] ** 2 if n_blocks > 1: for i_block in range(0, n_blocks): # Broadcast missing cells into Mw to calculate Mw.T * Mw denomt += mb[i_block, k] ** 2 * mmis[:, id_blockp[i_block]: id_blockp[i_block] + p] @ mw2 else: denomt += mmis[:, id_blockp[0]: id_blockp[0] + p] @ mw2 denomt /= np.max(denomt) denomt[denomt < denom_cutoff] = denom_cutoff mt[:, k] /= denomt mt[mt[:, k] < 0, k] = 0 if alpha[0] < 0: if alpha[0] <= -1: if (alpha[0] == -1) & (np.max(mt[:, k]) > 0): t_threshold = mt[:, k] hhi = int( np.round( (np.linalg.norm(t_threshold, ord=1) / (np.linalg.norm(t_threshold, ord=2) + EPSILON)) ** 2, decimals=0, ) ) t_rank = np.argsort(t_threshold) t_threshold[t_rank[0: n - hhi]] = 0 else: mt[:, k] = sparse_opt(mt[:, k], -alpha[k] - 1, False) else: mt[:, k] = sparse_opt(mt[:, k], -alpha[0], False) if (ntf_unimodal > 0) & (ntf_left_components > 0): # Enforce unimodal distribution tmax = np.argmax(mt[:, k]) for i in range(tmax + 1, n): mt[i, k] = min(mt[i - 1, k], mt[i, k]) for i in range(tmax - 1, -1, -1): mt[i, k] = min(mt[i + 1, k], mt[i, k]) if (ntf_smooth > 0) & (ntf_left_components > 0): # Smooth distribution a[0] = 0.75 * mt[0, k] + 0.25 * mt[1, k] a[n - 1] = 0.25 * mt[n - 2, k] + 0.75 * mt[n - 1, k] for i in range(1, n - 1): a[i] = 0.25 * mt[i - 1, k] + 0.5 * mt[i, k] + 0.25 * mt[i + 1, k] mt[:, k] = a if norm_lhe: norm = np.linalg.norm(mt[:, k]) if norm > 0: mt[:, k] /= norm if nmf_fix_user_rhe == 0: # Update Mw mw[:, k] = 0 if n_blocks > 1: for i_block in range(0, n_blocks): mw[:, k] += mpart[:, id_blockp[i_block]: id_blockp[i_block] + p].T @ mt[:, k] * mb[i_block, k] else: mw[:, k] += mpart[:, id_blockp[0]: id_blockp[0] + p].T @ mt[:, k] if n_mmis > 0: denomw[:] = 0 mt2[:] = mt[:, k] ** 2 if n_blocks > 1: for i_block in range(0, n_blocks): # Broadcast missing cells into Mw to calculate Mt.T * Mt denomw += mb[i_block, k] ** 2 * mmis[:, id_blockp[i_block]: id_blockp[i_block] + p].T @ mt2 else: denomw += mmis[:, id_blockp[0]: id_blockp[0] + p].T @ mt2 denomw /= np.max(denomw) denomw[denomw < denom_cutoff] = denom_cutoff mw[:, k] /= denomw mw[mw[:, k] < 0, k] = 0 if alpha[0] > 0: if alpha[0] >= 1: if (alpha[0] == 1) & (np.max(mw[:, k]) > 0): w_threshold = mw[:, k] hhi = int( np.round( (np.linalg.norm(w_threshold, ord=1) / (np.linalg.norm(w_threshold, ord=2) + EPSILON)) ** 2, decimals=0, ) ) w_rank = np.argsort(w_threshold) w_threshold[w_rank[0: p - hhi]] = 0 else: mw[:, k] = sparse_opt(mw[:, k], alpha[k] - 1, False) else: mw[:, k] = sparse_opt(mw[:, k], alpha[0], False) if (ntf_unimodal > 0) & (ntf_right_components > 0): # Enforce unimodal distribution wmax = np.argmax(mw[:, k]) for j in range(wmax + 1, p): mw[j, k] = min(mw[j - 1, k], mw[j, k]) for j in range(wmax - 1, -1, -1): mw[j, k] = min(mw[j + 1, k], mw[j, k]) if (ntf_smooth > 0) & (ntf_right_components > 0): # Smooth distribution b[0] = 0.75 * mw[0, k] + 0.25 * mw[1, k] b[p - 1] = 0.25 * mw[p - 2, k] + 0.75 * mw[p - 1, k] for j in range(1, p - 1): b[j] = 0.25 * mw[j - 1, k] + 0.5 * mw[j, k] + 0.25 * mw[j + 1, k] mw[:, k] = b if n_nmf_priors > 0: mw[:, k] = mw[:, k] * nmf_priors[:, k] if norm_rhe: norm = np.linalg.norm(mw[:, k]) if norm > 0: mw[:, k] /= norm if nmf_fix_user_bhe == 0: # Update Mb mb[:, k] = 0 mt_mw[:] = np.reshape((np.reshape(mt[:, k], (n, 1)) @ np.reshape(mw[:, k], (1, p))), nxp) for i_block in range(0, n_blocks): mb[i_block, k] = np.reshape(mpart[:, id_blockp[i_block]: id_blockp[i_block] + p], nxp).T @ mt_mw if n_mmis > 0: mt_mw[:] = mt_mw[:] ** 2 for i_block in range(0, n_blocks): # Broadcast missing cells into Mb to calculate Mb.T * Mb denom_block[i_block, k] = ( np.reshape(mmis[:, id_blockp[i_block]: id_blockp[i_block] + p], (1, nxp)) @ mt_mw ) maxdenom_block = np.max(denom_block[:, k]) denom_block[denom_block[:, k] < denom_cutoff * maxdenom_block] = denom_cutoff * maxdenom_block mb[:, k] /= denom_block[:, k] mb[mb[:, k] < 0, k] = 0 if (ntf_unimodal > 0) & (ntf_block_components > 0): # Enforce unimodal distribution bmax = np.argmax(mb[:, k]) for i_block in range(bmax + 1, n_blocks): mb[i_block, k] = min(mb[i_block - 1, k], mb[i_block, k]) for i_block in range(bmax - 1, -1, -1): mb[i_block, k] = min(mb[i_block + 1, k], mb[i_block, k]) if (ntf_smooth > 0) & (ntf_block_components > 0): # Smooth distribution c[0] = 0.75 * mb[0, k] + 0.25 * mb[1, k] c[n_blocks - 1] = 0.25 * mb[n_blocks - 2, k] + 0.75 * mb[n_blocks - 1, k] for i_block in range(1, n_blocks - 1): c[i_block] = 0.25 * mb[i_block - 1, k] + 0.5 * mb[i_block, k] + 0.25 * mb[i_block + 1, k] mb[:, k] = c if norm_bhe: norm = np.linalg.norm(mb[:, k]) if norm > 0: mb[:, k] /= norm # Update residual tensor mfit[:, :] = 0 if n_blocks > 1: for i_block in range(0, n_blocks): mfit[:, id_blockp[i_block]: id_blockp[i_block] + p] += ( mb[i_block, k] * np.reshape(mt[:, k], (n, 1)) @ np.reshape(mw[:, k], (1, p)) ) else: mfit[:, id_blockp[0]: id_blockp[0] + p] += np.reshape(mt[:, k], (n, 1)) @ np.reshape(mw[:, k], (1, p)) if n_mmis > 0: mres[:, :] = (mpart - mfit) * mmis else: mres[:, :] = mpart - mfit return ( n_blocks, mpart, id_blockp, p, mb, k, mt, n, mw, n_mmis, mmis, mres, nmf_fix_user_lhe, denomt, mw2, denom_cutoff, alpha, ntf_unimodal, ntf_left_components, ntf_smooth, a, nmf_fix_user_rhe, denomw, mt2, ntf_right_components, b, nmf_fix_user_bhe, mt_mw, nxp, denom_block, ntf_block_components, c, mfit, nmf_priors, )
timeit.py
import time import logging logger = logging.getLogger(__name__) def timeit(method): def timed(*args, **kw): ts = time.time() result = method(*args, **kw) te = time.time() if 'log_time' in kw: name = kw.get('log_name', method.__name__.upper()) kw['log_time'][name] = int((te - ts) * 1000) else:
logger.warning('%r %2.2f ms' % (method.__name__, (te - ts) * 1000)) return result return timed
purefb_s3user.py
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2018, Simon Dodsley ([email protected]) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: purefb_s3user version_added: '2.8' short_description: Create or delete FlashBlade Object Store account users description: - Create or delete object store account users on a Pure Stoage FlashBlade. author: - Pure Storage Ansible Team (@sdodsley) <[email protected]> options: state: description: - Create or delete object store account user default: present choices: [ absent, present ] type: str name: description: - The name of object store user type: str account: description: - The name of object store account associated with user type: str access_key: description: - Create secret access key. - Key can be exposed using the I(debug) module type: bool default: true extends_documentation_fragment: - purestorage.fb ''' EXAMPLES = r''' - name: Crrate object store user (with access ID and key) foo in account bar purefb_s3user: name: foo account: bar fb_url: 10.10.10.2 api_token: e31060a7-21fc-e277-6240-25983c6c4592 debug: var: ansible_facts.fb_s3user - name: Delete object store user foo in account bar purefb_s3user: name: foo account: bar state: absent fb_url: 10.10.10.2 api_token: e31060a7-21fc-e277-6240-25983c6c4592 ''' RETURN = r''' ''' HAS_PURITY_FB = True try: from purity_fb import ObjectStoreAccessKey except ImportError: HAS_PURITY_FB = False from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.pure import get_blade, purefb_argument_spec MIN_REQUIRED_API_VERSION = '1.3' def get_s3acc(module, blade): """Return Object Store Account or None""" s3acc = None accts = blade.object_store_accounts.list_object_store_accounts() for acct in range(0, len(accts.items)): if accts.items[acct].name == module.params['account']: s3acc = accts.items[acct] return s3acc def get_s3user(module, blade): """Return Object Store Account or None""" full_user = module.params['account'] + "/" + module.params['name'] s3user = None s3users = blade.object_store_users.list_object_store_users() for user in range(0, len(s3users.items)): if s3users.items[user].name == full_user: s3user = s3users.items[user] return s3user def update_s3user(module, blade): """Update Object Store User""" changed = False s3user_facts = {} user = module.params['account'] + "/" + module.params['name'] if module.params['access_key']: try: result = blade.object_store_access_keys.create_object_store_access_keys( object_store_access_key=ObjectStoreAccessKey(user={'name': user})) s3user_facts['fb_s3user'] = {'user': user, 'access_key': result.items[0].secret_access_key, 'access_id': result.items[0].name} except Exception: delete_s3user(module, blade) module.fail_json(msg='Object Store User {0}: Creation failed'.format(user)) changed = True module.exit_json(changed=changed, ansible_facts=s3user_facts) def create_s3user(module, blade): """Create Object Store Account""" s3user_facts = {} changed = False user = module.params['account'] + "/" + module.params['name'] try: blade.object_store_users.create_object_store_users(names=[user]) if module.params['access_key']: try: result = blade.object_store_access_keys.create_object_store_access_keys( object_store_access_key=ObjectStoreAccessKey(user={'name': user})) s3user_facts['fb_s3user'] = {'user': user, 'access_key': result.items[0].secret_access_key, 'access_id': result.items[0].name} except Exception: delete_s3user(module, blade) module.fail_json(msg='Object Store User {0}: Creation failed'.format(user)) changed = True except Exception: module.fail_json(msg='Object Store User {0}: Creation failed'.format(user)) module.exit_json(changed=changed, ansible_facts=s3user_facts) def delete_s3user(module, blade):
def main(): argument_spec = purefb_argument_spec() argument_spec.update(dict( name=dict(required=True, type='str'), account=dict(required=True, type='str'), access_key=dict(default='true', type='bool'), state=dict(default='present', choices=['present', 'absent']), )) module = AnsibleModule(argument_spec, supports_check_mode=False) if not HAS_PURITY_FB: module.fail_json(msg='purity_fb sdk is required for this module') state = module.params['state'] blade = get_blade(module) versions = blade.api_version.list_versions().versions if MIN_REQUIRED_API_VERSION not in versions: module.fail_json(msg='FlashBlade REST version not supported. Minimum version required: {0}'.format(MIN_REQUIRED_API_VERSION)) s3acc = get_s3acc(module, blade) if not s3acc: module.fail_json(msg='Object Store Account {0} does not exist'.format(module.params['account'])) s3user = get_s3user(module, blade) if state == 'absent' and s3user: delete_s3user(module, blade) elif state == 'present' and s3user: update_s3user(module, blade) elif not s3user and state == 'present': create_s3user(module, blade) else: module.exit_json(changed=False) if __name__ == '__main__': main()
"""Delete Object Store Account""" changed = False user = module.params['account'] + "/" + module.params['name'] try: blade.object_store_users.delete_object_store_users(names=[user]) changed = True except Exception: module.fail_json(msg='Object Store Account {0}: Deletion failed'.format(module.params['name'])) module.exit_json(changed=changed)
index.js
import React, { PropTypes } from 'react'; import pubsub from 'pubsub-js' import { Link } from 'react-router'; import AppTable from 'components/AppTable'; import AppButton from 'components/AppButton' import InputNumberField from 'components/Form/InputNumberField' import {resolveDataSource, publishEvents, resolveFetch,resolveDataSourceCallback} from 'utils/componentUtil' import {reduxForm, Field, FieldArray} from 'redux-form/immutable'; import { fromJS } from 'immutable'; import Immutable from 'immutable' import {Row, Col} from 'antd' import TextField from 'components/Form/TextField'
export class DicModifyModal extends React.PureComponent { constructor(props) { super(props); resolveFetch({ fetch: { id: "dic", data: "selectedRows" } }).then(function (rows) { debugger console.log(rows) pubsub.publish("@@form.init", {id: "DicModifyModal", data: rows[0]}) }) } componentWillMount() { } componentDidMount() { // pubsub.publish('orderRepealModal-table-11.laterData',{}) } componentWillUnmount() { } componentWillReceiveProps(nextProps) { } render() { return ( <form> <Row> <Col span={12}> <Field config={{ enabled: true, id: "code", label: "字典", //标签名称 labelSpan: 8, //标签栅格比例(0-24) wrapperSpan: 16, //输入框栅格比例(0-24) form: "DicModifyModal", showRequiredStar: true, //是否显示必填星号 placeholder: "请输入编码" }} component={TextField} name="code" /> </Col> <Col span={12}> <Field config={{ enabled: true, id: "name", label: "字典名称", //标签名称 labelSpan: 8, //标签栅格比例(0-24) wrapperSpan: 16, //输入框栅格比例(0-24) form: "DicModifyModal", showRequiredStar: true, //是否显示必填星号 placeholder: "请输入名称" }} component={TextField} name="name" /> </Col> </Row> <Row> <Col span={12}> <Field config={{ enabled: true, id: "description", label: "说明", //标签名称 labelSpan: 8, //标签栅格比例(0-24) wrapperSpan: 16, //输入框栅格比例(0-24) form: "DicModifyModal", showRequiredStar: true, //是否显示必填星号 placeholder: "请输入说明" }} component={TextField} name="description" /> </Col> </Row> <Row> <Col span={6} offset={20}> {/*取消按钮*/} <AppButton config={{ id: "orderRepealModal-btn-3", title: "取消", type:"default", size:"large", visible: true, enabled: true, subscribes: [ { event: "orderRepealModal-btn-3.click", pubs:[{ event: "modifyDicPage.onCancel", }] } ] }} /> {/*确定按钮*/} <AppButton config={{ id: "orderRepealModal-btn-2", title: "确定", type:"primary", size:"large", visible: true, enabled: true, subscribes: [ { event: "orderRepealModal-btn-2.click", pubs:[ { event: "orderRepealModal-btn-2.expression", meta: { expression: ` console.log("删除111222"); resolveFetch({fetch:{id:"DicModifyModal",data:"@@formValues"}}).then(function (value) { // console.log(value); let formValue = {code:value.code,name:value.name,description:value.description} //let params = {} let dataSource= { type: "api", method: "POST", url: "/sm/dictionaryEnum/modify.action?id="+value.gid }; resolveDataSourceCallback( { dataSource:dataSource,eventPayload:formValue,dataContext:formValue }, function(res){ //me.setState({dataSource:res.data}) }, function(){ } ) }); ` } }, { event: "dic.loadData", }, { event: "modifyDicPage.onCancel", } ] } ] }} /> </Col> </Row> </form> ); } } DicModifyModal.propTypes = { }; export default reduxForm({ form: "DicModifyModal", })(DicModifyModal);
interp.go
package interp import ( "bytes" "context" "crypto/md5" "embed" "encoding/base64" "encoding/hex" "errors" "fmt" "io" "io/fs" "io/ioutil" "math/big" "path" "strconv" "strings" "time" "github.com/mitchellh/mapstructure" "github.com/wader/fq/internal/ansi" "github.com/wader/fq/internal/bitioextra" "github.com/wader/fq/internal/colorjson" "github.com/wader/fq/internal/ctxstack" "github.com/wader/fq/internal/gojqextra" "github.com/wader/fq/internal/ioextra" "github.com/wader/fq/internal/mathextra" "github.com/wader/fq/internal/pos" "github.com/wader/fq/pkg/bitio" "github.com/wader/fq/pkg/decode" "github.com/wader/fq/pkg/registry" "github.com/wader/gojq" ) //go:embed interp.jq //go:embed internal.jq //go:embed eval.jq //go:embed options.jq //go:embed ansi.jq //go:embed binary.jq //go:embed decode.jq //go:embed funcs.jq //go:embed grep.jq //go:embed args.jq //go:embed query.jq //go:embed repl.jq //go:embed help.jq //go:embed formats.jq var builtinFS embed.FS var initSource = `include "@builtin/interp";` var functionRegisterFns []func(i *Interp) []Function func init() { functionRegisterFns = append(functionRegisterFns, func(i *Interp) []Function { return []Function{ {"_readline", 0, 1, nil, i._readline}, {"_eval", 1, 2, nil, i._eval}, {"_stdin", 0, 1, nil, i.makeStdioFn("stdin", i.os.Stdin())}, {"_stdout", 0, 0, nil, i.makeStdioFn("stdout", i.os.Stdout())}, {"_stderr", 0, 0, nil, i.makeStdioFn("stderr", i.os.Stderr())}, {"_extkeys", 0, 0, i._extKeys, nil}, {"_exttype", 0, 0, i._extType, nil}, {"_global_state", 0, 1, i.makeStateFn(i.state), nil}, {"history", 0, 0, i.history, nil}, {"_display", 1, 1, nil, i._display}, {"_can_display", 0, 0, i._canDisplay, nil}, {"_print_color_json", 0, 1, nil, i._printColorJSON}, {"_is_completing", 0, 1, i._isCompleting, nil}, } }) } type valueError struct { v interface{} } func (v valueError) Error() string { return fmt.Sprintf("error: %v", v.v) } func (v valueError) Value() interface{} { return v.v } type compileError struct { err error what string filename string pos pos.Pos } func (ce compileError) Value() interface{} { return map[string]interface{}{ "error": ce.err.Error(), "what": ce.what, "filename": ce.filename, "line": ce.pos.Line, "column": ce.pos.Column, } } func (ce compileError) Error() string { filename := ce.filename if filename == "" { filename = "expr" } return fmt.Sprintf("%s:%d:%d: %s: %s", filename, ce.pos.Line, ce.pos.Column, ce.what, ce.err.Error()) } var ErrEOF = io.EOF var ErrInterrupt = errors.New("Interrupt") // gojq errors can implement this to signal exit code type Exiter interface { ExitCode() int } // gojq halt_error uses this type IsEmptyErrorer interface { IsEmptyError() bool } type Terminal interface { Size() (int, int) IsTerminal() bool } type Input interface { fs.File Terminal } type Output interface { io.Writer Terminal } type Platform struct { OS string Arch string } type ReadlineOpts struct { Prompt string CompleteFn func(line string, pos int) (newLine []string, shared int) } type OS interface { Platform() Platform Stdin() Input Stdout() Output Stderr() Output InterruptChan() chan struct{} Args() []string Environ() []string ConfigDir() (string, error) // FS.File returned by FS().Open() can optionally implement io.Seeker FS() fs.FS Readline(opts ReadlineOpts) (string, error) History() ([]string, error) } type FixedFileInfo struct { FName string FSize int64 FMode fs.FileMode FModTime time.Time FIsDir bool FSys interface{} } func (ffi FixedFileInfo) Name() string { return ffi.FName } func (ffi FixedFileInfo) Size() int64 { return ffi.FSize } func (ffi FixedFileInfo) Mode() fs.FileMode { return ffi.FMode } func (ffi FixedFileInfo) ModTime() time.Time { return ffi.FModTime } func (ffi FixedFileInfo) IsDir() bool { return ffi.FIsDir } func (ffi FixedFileInfo) Sys() interface{} { return ffi.FSys } type FileReader struct { R io.Reader FileInfo FixedFileInfo } func (rf FileReader) Stat() (fs.FileInfo, error) { return rf.FileInfo, nil } func (rf FileReader) Read(p []byte) (int, error) { return rf.R.Read(p) } func (FileReader) Close() error { return nil } type Value interface { gojq.JQValue ExtType() string ExtKeys() []string } type Display interface { Display(w io.Writer, opts Options) error } type JQValueEx interface { JQValueToGoJQEx(optsFn func() Options) interface{} } func valuePath(v *decode.Value) []interface{} { var parts []interface{} for v.Parent != nil { switch vv := v.Parent.V.(type) { case *decode.Compound: if vv.IsArray { parts = append([]interface{}{v.Index}, parts...) } else { parts = append([]interface{}{v.Name}, parts...) } } v = v.Parent } return parts } func valuePathExprDecorated(v *decode.Value, d Decorator) string { parts := []string{"."} for i, p := range valuePath(v) { switch p := p.(type) { case string: if i > 0 { parts = append(parts, ".") } parts = append(parts, d.ObjectKey.Wrap(p)) case int: indexStr := strconv.Itoa(p) parts = append(parts, fmt.Sprintf("%s%s%s", d.Index.F("["), d.Number.F(indexStr), d.Index.F("]"))) } } return strings.Join(parts, "") } type iterFn func() (interface{}, bool) func (i iterFn) Next() (interface{}, bool) { return i() } type loadModule struct { init func() ([]*gojq.Query, error) load func(name string) (*gojq.Query, error) } func (l loadModule) LoadInitModules() ([]*gojq.Query, error) { return l.init() } func (l loadModule) LoadModule(name string) (*gojq.Query, error) { return l.load(name) } func toString(v interface{}) (string, error) { switch v := v.(type) { case string: return v, nil case gojq.JQValue: return toString(v.JQValueToGoJQ()) default: b, err := toBytes(v) if err != nil { return "", fmt.Errorf("value can't be a string") } return string(b), nil } } func toBigInt(v interface{}) (*big.Int, error) { switch v := v.(type) { case int: return new(big.Int).SetInt64(int64(v)), nil case float64: return new(big.Int).SetInt64(int64(v)), nil case *big.Int: return v, nil default: return nil, fmt.Errorf("value is not a number") } } func toBytes(v interface{}) ([]byte, error) { switch v := v.(type) { default: br, err := toBitReader(v) if err != nil { return nil, fmt.Errorf("value is not bytes") } buf := &bytes.Buffer{} if _, err := bitioextra.CopyBits(buf, br); err != nil { return nil, err } return buf.Bytes(), nil } } func queryErrorPosition(expr string, v error) pos.Pos { var offset int if tokIf, ok := v.(interface{ Token() (string, int) }); ok { //nolint:errorlint _, offset = tokIf.Token() } if offset >= 0 { return pos.NewFromOffset(expr, offset) } return pos.Pos{} } type Variable struct { Name string Value interface{} } type Function struct { Name string MinArity int MaxArity int Fn func(interface{}, []interface{}) interface{} IterFn func(interface{}, []interface{}) gojq.Iter } type RunMode int const ( ScriptMode RunMode = iota REPLMode CompletionMode ) type evalInstance struct { ctx context.Context output io.Writer isCompleting bool includeSeen map[string]struct{} } type Interp struct { registry *registry.Registry os OS initQuery *gojq.Query includeCache map[string]*gojq.Query interruptStack *ctxstack.Stack // global state, is ref as Interp is cloned per eval state *interface{} // new for each eval, other values are copied by value evalInstance evalInstance } func New(os OS, registry *registry.Registry) (*Interp, error) { var err error i := &Interp{ os: os, registry: registry, } i.includeCache = map[string]*gojq.Query{} i.initQuery, err = gojq.Parse(initSource) if err != nil { return nil, fmt.Errorf("init:%s: %w", queryErrorPosition(initSource, err), err) } // TODO: refactor ctxstack have a CancelTop and return c context to Stop? i.interruptStack = ctxstack.New(func(stopCh chan struct{}) { select { case <-stopCh: return case <-os.InterruptChan(): return } }) i.state = new(interface{}) return i, nil } func (i *Interp) Stop() { // TODO: cancel all run instances? i.interruptStack.Stop() } func (i *Interp) Main(ctx context.Context, output Output, versionStr string) error { var args []interface{} for _, a := range i.os.Args() { args = append(args, a) } platform := i.os.Platform() input := map[string]interface{}{ "args": args, "version": versionStr, "os": platform.OS, "arch": platform.Arch, } iter, err := i.EvalFunc(ctx, input, "_main", nil, EvalOpts{output: output}) if err != nil { fmt.Fprintln(i.os.Stderr(), err) return err } for { v, ok := iter.Next() if !ok { break } switch v := v.(type) { case error: if emptyErr, ok := v.(IsEmptyErrorer); ok && emptyErr.IsEmptyError() { //nolint:errorlint // no output } else if errors.Is(v, context.Canceled) { // ignore context cancel here for now, which means user somehow interrupted the interpreter // TODO: handle this inside interp.jq instead but then we probably have to do nested // eval and or also use different contexts for the interpreter and reading/decoding } else { fmt.Fprintln(i.os.Stderr(), v) } return v case [2]interface{}: fmt.Fprintln(i.os.Stderr(), v[:]...) default: // TODO: can this happen? fmt.Fprintln(i.os.Stderr(), v) } } return nil } func (i *Interp) _readline(c interface{}, a []interface{}) gojq.Iter { if i.evalInstance.isCompleting { return gojq.NewIter() } var opts struct { Promopt string `mapstructure:"prompt"` Complete string `mapstructure:"complete"` Timeout float64 `mapstructure:"timeout"` } if len(a) > 0 { _ = mapstructure.Decode(a[0], &opts) } expr, err := i.os.Readline(ReadlineOpts{ Prompt: opts.Promopt, CompleteFn: func(line string, pos int) (newLine []string, shared int) { completeCtx := i.evalInstance.ctx if opts.Timeout > 0 { var completeCtxCancelFn context.CancelFunc completeCtx, completeCtxCancelFn = context.WithTimeout(i.evalInstance.ctx, time.Duration(opts.Timeout*float64(time.Second))) defer completeCtxCancelFn() } names, shared, err := func() (newLine []string, shared int, err error) { // c | opts.Complete(line; pos) vs, err := i.EvalFuncValues( completeCtx, c, opts.Complete, []interface{}{line, pos}, EvalOpts{ output: ioextra.DiscardCtxWriter{Ctx: completeCtx}, isCompleting: true, }, ) if err != nil { return nil, pos, err } if len(vs) < 1 { return nil, pos, fmt.Errorf("no values") } v := vs[0] if vErr, ok := v.(error); ok { return nil, pos, vErr } // {abc: 123, abd: 123} | complete(".ab"; 3) will return {prefix: "ab", names: ["abc", "abd"]} var result struct { Names []string `mapstructure:"names"` Prefix string `mapstructure:"prefix"` } _ = mapstructure.Decode(v, &result) if len(result.Names) == 0 { return nil, pos, nil } sharedLen := len(result.Prefix) return result.Names, sharedLen, nil }() // TODO: how to report err? _ = err return names, shared }, }) if errors.Is(err, ErrInterrupt) { return gojq.NewIter(valueError{"interrupt"}) } else if errors.Is(err, ErrEOF) { return gojq.NewIter(valueError{"eof"}) } else if err != nil { return gojq.NewIter(err) } return gojq.NewIter(expr) } func (i *Interp) _eval(c interface{}, a []interface{}) gojq.Iter { var err error expr, err := toString(a[0]) if err != nil { return gojq.NewIter(fmt.Errorf("expr: %w", err)) } var filenameHint string if len(a) >= 2 { filenameHint, err = toString(a[1]) if err != nil { return gojq.NewIter(fmt.Errorf("filename hint: %w", err)) } } iter, err := i.Eval(i.evalInstance.ctx, c, expr, EvalOpts{ filename: filenameHint, output: i.evalInstance.output, }) if err != nil { return gojq.NewIter(err) } return iter } func (i *Interp) _extKeys(c interface{}, a []interface{}) interface{} { if v, ok := c.(Value); ok { var vs []interface{} for _, s := range v.ExtKeys() { vs = append(vs, s) } return vs } return nil } func (i *Interp) _extType(c interface{}, a []interface{}) interface{} { if v, ok := c.(Value); ok { return v.ExtType() } return gojqextra.Typeof(c) } func (i *Interp) makeStateFn(state *interface{}) func(c interface{}, a []interface{}) interface{} { return func(c interface{}, a []interface{}) interface{} { if len(a) > 0 { *state = a[0] } return *state } } func (i *Interp) makeStdioFn(name string, t Terminal) func(c interface{}, a []interface{}) gojq.Iter { return func(c interface{}, a []interface{}) gojq.Iter { switch { case len(a) == 1: if i.evalInstance.isCompleting { return gojq.NewIter("") } r, ok := t.(io.Reader) if !ok { return gojq.NewIter(fmt.Errorf("%s is not readable", name)) } l, ok := gojqextra.ToInt(a[0]) if !ok { return gojq.NewIter(gojqextra.FuncTypeError{Name: name, V: a[0]}) } buf := make([]byte, l) n, err := io.ReadFull(r, buf) s := string(buf[0:n]) vs := []interface{}{s} switch { case errors.Is(err, io.EOF), errors.Is(err, io.ErrUnexpectedEOF): vs = append(vs, valueError{"eof"}) default: vs = append(vs, err) } return gojq.NewIter(vs...) case c == nil: w, h := t.Size() return gojq.NewIter(map[string]interface{}{ "is_terminal": t.IsTerminal(), "width": w, "height": h, }) default: if i.evalInstance.isCompleting { return gojq.NewIter() } w, ok := t.(io.Writer) if !ok { return gojq.NewIter(fmt.Errorf("%v: it not writeable", c)) } if _, err := fmt.Fprint(w, c); err != nil { return gojq.NewIter(err) } return gojq.NewIter() } } } func (i *Interp) history(c interface{}, a []interface{}) interface{} { hs, err := i.os.History() if err != nil { return err } var vs []interface{} for _, s := range hs { vs = append(vs, s) } return vs } func (i *Interp) _display(c interface{}, a []interface{}) gojq.Iter { opts := i.Options(a[0]) switch v := c.(type) { case Display: if err := v.Display(i.evalInstance.output, opts); err != nil { return gojq.NewIter(err) } return gojq.NewIter() default: return gojq.NewIter(fmt.Errorf("%+#v: not displayable", c)) } } func (i *Interp) _canDisplay(c interface{}, a []interface{}) interface{} { _, ok := c.(Display) return ok } func (i *Interp) _printColorJSON(c interface{}, a []interface{}) gojq.Iter { opts := i.Options(a[0]) cj, err := i.NewColorJSON(opts) if err != nil { return gojq.NewIter(err) } if err := cj.Marshal(c, i.evalInstance.output); err != nil { return gojq.NewIter(err) } return gojq.NewIter() } func (i *Interp) _isCompleting(c interface{}, a []interface{}) interface{} { return i.evalInstance.isCompleting } type pathResolver struct { prefix string open func(filename string) (io.ReadCloser, string, error) } func (i *Interp) lookupPathResolver(filename string) (pathResolver, error) { configDir, err := i.os.ConfigDir() if err != nil { return pathResolver{}, err } resolvePaths := []pathResolver{ { "@builtin/", func(filename string) (io.ReadCloser, string, error) { f, err := builtinFS.Open(filename) return f, "@builtin/" + filename, err }, }, { "@config/", func(filename string) (io.ReadCloser, string, error) { p := path.Join(configDir, filename) f, err := i.os.FS().Open(p) return f, p, err }, }, { "", func(filename string) (io.ReadCloser, string, error) { if path.IsAbs(filename) { f, err := i.os.FS().Open(filename) return f, filename, err } // TODO: jq $ORIGIN for _, includePath := range append([]string{"./"}, i.includePaths()...) { p := path.Join(includePath, filename) if f, err := i.os.FS().Open(path.Join(includePath, filename)); err == nil { return f, p, nil } } return nil, "", &fs.PathError{Op: "open", Path: filename, Err: fs.ErrNotExist} }, }, } for _, p := range resolvePaths { if strings.HasPrefix(filename, p.prefix) { return p, nil } } return pathResolver{}, fmt.Errorf("could not resolve path: %s", filename) } type EvalOpts struct { filename string output io.Writer isCompleting bool } func (i *Interp) Eval(ctx context.Context, c interface{}, expr string, opts EvalOpts) (gojq.Iter, error) { gq, err := gojq.Parse(expr) if err != nil { p := queryErrorPosition(expr, err) return nil, compileError{ err: err, what: "parse", filename: opts.filename, pos: p, } } // make copy of interp and give it its own eval context ci := *i ni := &ci ni.evalInstance = evalInstance{ includeSeen: map[string]struct{}{}, } var variableNames []string var variableValues []interface{} for k, v := range i.slurps() { variableNames = append(variableNames, "$"+k) variableValues = append(variableValues, v) } var funcCompilerOpts []gojq.CompilerOption for _, frFn := range functionRegisterFns { for _, f := range frFn(ni) { if f.IterFn != nil { funcCompilerOpts = append(funcCompilerOpts, gojq.WithIterFunction(f.Name, f.MinArity, f.MaxArity, f.IterFn)) } else { funcCompilerOpts = append(funcCompilerOpts, gojq.WithFunction(f.Name, f.MinArity, f.MaxArity, f.Fn)) } } } compilerOpts := append([]gojq.CompilerOption{}, funcCompilerOpts...) compilerOpts = append(compilerOpts, gojq.WithEnvironLoader(ni.os.Environ)) compilerOpts = append(compilerOpts, gojq.WithVariables(variableNames)) compilerOpts = append(compilerOpts, gojq.WithModuleLoader(loadModule{ init: func() ([]*gojq.Query, error) { return []*gojq.Query{i.initQuery}, nil }, load: func(name string) (*gojq.Query, error) { if err := ctx.Err(); err != nil { return nil, err } var filename string // support include "nonexisting?" to ignore include error var isTry bool if strings.HasSuffix(name, "?") { isTry = true filename = name[0 : len(name)-1] } else { filename = name } filename = filename + ".jq" pr, err := i.lookupPathResolver(filename) if err != nil { return nil, err } // skip if this eval instance has already included the file if _, ok := ni.evalInstance.includeSeen[filename]; ok { return &gojq.Query{Term: &gojq.Term{Type: gojq.TermTypeIdentity}}, nil } ni.evalInstance.includeSeen[filename] = struct{}{} // return cached version if file has already been parsed if q, ok := ni.includeCache[filename]; ok { return q, nil } filenamePart := strings.TrimPrefix(filename, pr.prefix) f, absPath, err := pr.open(filenamePart) if err != nil { if !isTry { return nil, err } f = io.NopCloser(&bytes.Buffer{}) } defer f.Close() b, err := io.ReadAll(f) if err != nil { return nil, err } s := string(b) q, err := gojq.Parse(s) if err != nil { p := queryErrorPosition(s, err) return nil, compileError{ err: err, what: "parse", filename: absPath, pos: p, } } // not identity body means it returns something, threat as dynamic include if q.Term.Type != gojq.TermTypeIdentity { gc, err := gojq.Compile(q, funcCompilerOpts...) if err != nil
iter := gc.RunWithContext(context.Background(), nil) var vs []interface{} for { v, ok := iter.Next() if !ok { break } if err, ok := v.(error); ok { return nil, err } vs = append(vs, v) } if len(vs) != 1 { return nil, fmt.Errorf("dynamic include: must output one string, got: %#v", vs) } s, sOk := vs[0].(string) if !sOk { return nil, fmt.Errorf("dynamic include: must be string, got %#v", s) } q, err = gojq.Parse(s) if err != nil { p := queryErrorPosition(s, err) return nil, compileError{ err: err, what: "parse", filename: filenamePart, pos: p, } } } // TODO: some better way of handling relative includes that // works with @builtin etc basePath := path.Dir(name) for _, qi := range q.Imports { rewritePath := func(base, includePath string) string { if strings.HasPrefix(includePath, "@") || path.IsAbs(includePath) { return includePath } return path.Join(base, includePath) } if qi.IncludePath != "" { qi.IncludePath = rewritePath(basePath, qi.IncludePath) } if qi.ImportPath != "" { qi.ImportPath = rewritePath(basePath, qi.ImportPath) } } i.includeCache[filename] = q return q, nil }, })) gc, err := gojq.Compile(gq, compilerOpts...) if err != nil { p := queryErrorPosition(expr, err) return nil, compileError{ err: err, what: "compile", filename: opts.filename, pos: p, } } output := opts.output if opts.output == nil { output = ioutil.Discard } runCtx, runCtxCancelFn := i.interruptStack.Push(ctx) ni.evalInstance.ctx = runCtx ni.evalInstance.output = ioextra.CtxWriter{Writer: output, Ctx: runCtx} // inherit or maybe set ni.evalInstance.isCompleting = i.evalInstance.isCompleting || opts.isCompleting iter := gc.RunWithContext(runCtx, c, variableValues...) iterWrapper := iterFn(func() (interface{}, bool) { v, ok := iter.Next() // gojq ctx cancel will not return ok=false, just cancelled error if !ok { runCtxCancelFn() } else if _, ok := v.(error); ok { runCtxCancelFn() } return v, ok }) return iterWrapper, nil } func (i *Interp) EvalFunc(ctx context.Context, c interface{}, name string, args []interface{}, opts EvalOpts) (gojq.Iter, error) { var argsExpr []string for i := range args { argsExpr = append(argsExpr, fmt.Sprintf("$_args[%d]", i)) } argExpr := "" if len(argsExpr) > 0 { argExpr = "(" + strings.Join(argsExpr, ";") + ")" } trampolineInput := map[string]interface{}{ "input": c, "args": args, } // _args to mark variable as internal and hide it from completion // {input: ..., args: [...]} | .args as {args: $_args} | .input | name[($_args[0]; ...)] trampolineExpr := fmt.Sprintf(". as {args: $_args} | .input | %s%s", name, argExpr) iter, err := i.Eval(ctx, trampolineInput, trampolineExpr, opts) if err != nil { return nil, err } return iter, nil } func (i *Interp) EvalFuncValues(ctx context.Context, c interface{}, name string, args []interface{}, opts EvalOpts) ([]interface{}, error) { iter, err := i.EvalFunc(ctx, c, name, args, opts) if err != nil { return nil, err } var vs []interface{} for { v, ok := iter.Next() if !ok { break } vs = append(vs, v) } return vs, nil } type Options struct { Depth int `mapstructure:"depth"` ArrayTruncate int `mapstructure:"array_truncate"` Verbose bool `mapstructure:"verbose"` Width int `mapstructure:"width"` DecodeProgress bool `mapstructure:"decode_progress"` Color bool `mapstructure:"color"` Colors map[string]string `mapstructure:"colors"` ByteColors []struct { Ranges [][2]int `mapstructure:"ranges"` Value string `mapstructure:"value"` } `mapstructure:"byte_colors"` Unicode bool `mapstructure:"unicode"` RawOutput bool `mapstructure:"raw_output"` REPL bool `mapstructure:"repl"` RawString bool `mapstructure:"raw_string"` JoinString string `mapstructure:"join_string"` Compact bool `mapstructure:"compact"` BitsFormat string `mapstructure:"bits_format"` LineBytes int `mapstructure:"line_bytes"` DisplayBytes int `mapstructure:"display_bytes"` AddrBase int `mapstructure:"addrbase"` SizeBase int `mapstructure:"sizebase"` Decorator Decorator BitsFormatFn func(br bitio.ReaderAtSeeker) (interface{}, error) } func bitsFormatFnFromOptions(opts Options) func(br bitio.ReaderAtSeeker) (interface{}, error) { switch opts.BitsFormat { case "md5": return func(br bitio.ReaderAtSeeker) (interface{}, error) { d := md5.New() if _, err := bitioextra.CopyBits(d, br); err != nil { return "", err } return hex.EncodeToString(d.Sum(nil)), nil } case "base64": return func(br bitio.ReaderAtSeeker) (interface{}, error) { b := &bytes.Buffer{} e := base64.NewEncoder(base64.StdEncoding, b) if _, err := bitioextra.CopyBits(e, br); err != nil { return "", err } e.Close() return b.String(), nil } case "truncate": // TODO: configure return func(br bitio.ReaderAtSeeker) (interface{}, error) { b := &bytes.Buffer{} if _, err := bitioextra.CopyBits(b, bitio.NewLimitReader(br, 1024*8)); err != nil { return "", err } return b.String(), nil } case "string": return func(br bitio.ReaderAtSeeker) (interface{}, error) { b := &bytes.Buffer{} if _, err := bitioextra.CopyBits(b, br); err != nil { return "", err } return b.String(), nil } case "snippet": fallthrough default: return func(br bitio.ReaderAtSeeker) (interface{}, error) { b := &bytes.Buffer{} e := base64.NewEncoder(base64.StdEncoding, b) if _, err := bitioextra.CopyBits(e, bitio.NewLimitReader(br, 256*8)); err != nil { return "", err } e.Close() brLen, err := bitioextra.Len(br) if err != nil { return nil, err } return fmt.Sprintf("<%s>%s", mathextra.Bits(brLen).StringByteBits(opts.SizeBase), b.String()), nil } } } func (i *Interp) lookupState(key string) interface{} { if i.state == nil { return nil } m, ok := (*i.state).(map[string]interface{}) if !ok { return nil } return m[key] } func (i *Interp) includePaths() []string { pathsAny, ok := i.lookupState("include_paths").([]interface{}) if !ok { panic("include_paths not slice") } var paths []string for _, pathAny := range pathsAny { path, ok := pathAny.(string) if !ok { panic("path not string") } paths = append(paths, path) } return paths } func (i *Interp) slurps() map[string]interface{} { slurpsAny, _ := i.lookupState("slurps").(map[string]interface{}) return slurpsAny } func (i *Interp) Options(v interface{}) Options { var opts Options _ = mapstructure.Decode(v, &opts) opts.ArrayTruncate = mathextra.MaxInt(0, opts.ArrayTruncate) opts.Depth = mathextra.MaxInt(0, opts.Depth) opts.AddrBase = mathextra.ClampInt(2, 36, opts.AddrBase) opts.SizeBase = mathextra.ClampInt(2, 36, opts.SizeBase) opts.LineBytes = mathextra.MaxInt(0, opts.LineBytes) opts.DisplayBytes = mathextra.MaxInt(0, opts.DisplayBytes) opts.Decorator = decoratorFromOptions(opts) opts.BitsFormatFn = bitsFormatFnFromOptions(opts) return opts } func (i *Interp) NewColorJSON(opts Options) (*colorjson.Encoder, error) { indent := 2 if opts.Compact { indent = 0 } return colorjson.NewEncoder( opts.Color, false, indent, func(v interface{}) interface{} { if v, ok := toValue(func() Options { return opts }, v); ok { return v } panic(fmt.Sprintf("toValue not a JQValue value: %#v", v)) }, colorjson.Colors{ Reset: []byte(ansi.Reset.SetString), Null: []byte(opts.Decorator.Null.SetString), False: []byte(opts.Decorator.False.SetString), True: []byte(opts.Decorator.True.SetString), Number: []byte(opts.Decorator.Number.SetString), String: []byte(opts.Decorator.String.SetString), ObjectKey: []byte(opts.Decorator.ObjectKey.SetString), Array: []byte(opts.Decorator.Array.SetString), Object: []byte(opts.Decorator.Object.SetString), }, ), nil }
{ return nil, err }
xgboost.go
package xgb import ( "github.com/sudachen/go-ml/fu" "github.com/sudachen/go-ml/xgb/capi" "runtime" "unsafe" ) func LibVersion() fu.VersionType { return capi.LibVersion } type xgbinstance struct { handle unsafe.Pointer features []string // names of features predicts string // name of predicted value
capi.Close(x.handle) x.handle = nil return }
} func (x *xgbinstance) Close() (_ error) { runtime.SetFinalizer(x, nil)
index.js
export function createArrayFromObject(obj) { const newArray = []; for (let prop in obj) { if (obj.hasOwnProperty(prop)) { newArray.push(obj[prop]); } } return newArray; } // Given an array return and object where the key can be specified and the entire item at index // is the property. export function createObjectFromArray(arr, k = 'id') { if (!arr || arr.length === 0) { return {}; } // Create an object from each item in the array - using the id as key to match. const objects = arr.map((d) => { return { [d[k]]: d } }); // Merge the objects into 1. return Object.assign(...objects); } // Generate guid for use as id export function generateGuid() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } export function getRandomColor() { const letters = '0123456789ABCDEF'; let color = '#'; for (let i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; }
export function getRandomNamedColor() { const colors = ["red", "orange", "yellow", "olive", "green", "teal", "blue", "violet", "purple", "pink", "brown", "grey", "black"]; const randomIndex = Math.floor(Math.random() * colors.length); return colors[randomIndex]; }
return color; }
gruntChordSeq.js
module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), watch: { scripts: { files: ['Gruntfile.js', 'LJS.js', 'modules/**/*.js', 'modules/**/*.html', 'utils/**/*.js', '*.js'], tasks: 'default', options: { spawn: false, }, }, }, requirejs: { compile: { options: { baseUrl: ".", paths: { jquery: 'empty:', jquery_autocomplete: 'empty:', qunit: 'empty:', vexflow: 'empty:', Midijs: 'empty:', text: 'external-libs/require-text', pubsub: 'empty:', jsPDF: 'empty:', mustache: 'empty:' }, cjsTranslate: true, //findNestedDependencies: true, optimize: "none", // "uglify2", "none" /*modules: [ { name: 'leadsheet', include: ['modules/main'] }, { name: 'viewer', include: ['modules/core/src/main', 'modules/core/src/LSViewer'] } ],*/ name: "ChordSeq", //name: "build/LeadsheetJS-0.1.0.min.js", //name: "samples/simpleInterface/interface", // include: ['modules/**/*.js', '!modules/core/src/SongModel.old.js'], out: "build/chordseq-<%= pkg.version %>.min.js", // exclude: ["jquery, jquery_autocomplete, qunit, vexflow_helper, vexflow, Midijs, pubsub, jsPDF, mustache, bootstrap"], fileExclusionRegExp: /\.git/, /*done: function(done, output) { var duplicates = require('rjs-build-analysis').duplicates(output); if (duplicates.length > 0) { grunt.log.subhead('Duplicates found in requirejs build:'); grunt.log.warn(duplicates); return done(new Error('r.js built duplicate modules, please check the excludes option.')); } done(); }*/ } } }, qunit: { all: ['tests/test.html'] },
}); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-requirejs'); grunt.loadNpmTasks('grunt-contrib-qunit'); // grunt.loadNpmTasks('grunt-jsdoc'); // grunt.loadNpmTasks('grunt-umd'); // Default task(s). grunt.registerTask('all', ['requirejs', 'jsdoc']); grunt.registerTask('default', ['requirejs']); };
mod.rs
use swc_common::{BytePos, Span}; use swc_css_ast::*; use super::{input::ParserInput, Ctx, Grammar, PResult, Parser}; use crate::{ error::{Error, ErrorKind}, Parse, }; #[cfg(test)] mod tests; impl<I> Parser<I> where I: ParserInput, { /// Parse value as <declaration-value>. pub(super) fn parse_declaration_value(&mut self) -> PResult<Vec<Value>> { let mut value = vec![]; let mut balance_stack: Vec<Option<char>> = vec![]; // The <declaration-value> production matches any sequence of one or more // tokens, so long as the sequence does not contain ... loop { match cur!(self) { // ... <bad-string-token>, <bad-url-token>, tok!("bad-string") | tok!("bad-url") => { break; } // ... unmatched <)-token>, <]-token>, or <}-token>, tok!(")") | tok!("]") | tok!("}") => { let value = match cur!(self) { tok!(")") => ')', tok!("]") => ']', tok!("}") => '}', _ => { unreachable!(); } }; let balance_close_type = match balance_stack.pop() { Some(v) => v, None => None, }; if Some(value) != balance_close_type { break; } } tok!("function") | tok!("(") | tok!("[") | tok!("{") => { let value = match cur!(self) { tok!("function") | tok!("(") => ')', tok!("[") => ']', tok!("{") => '}', _ => { unreachable!(); } }; balance_stack.push(Some(value)); } // ... or top-level <semicolon-token> tokens tok!(";") => { if balance_stack.is_empty() { break; } } // ... or <delim-token> tokens with a value of "!" tok!("!") => { if balance_stack.is_empty() { break; } } _ => {} } let token = self.input.bump()?; match token { Some(token) => value.push(Value::PreservedToken(token)), None => break, } } Ok(value) } /// Parse value as <any-value>. pub(super) fn parse_any_value(&mut self) -> PResult<Vec<TokenAndSpan>> { let mut tokens = vec![]; let mut balance_stack: Vec<Option<char>> = vec![]; // The <any-value> production matches any sequence of one or more tokens, // so long as the sequence ... loop { match cur!(self) { // ... <bad-string-token>, <bad-url-token>, tok!("bad-string") | tok!("bad-url") => { break; } // ... unmatched <)-token>, <]-token>, or <}-token>, tok!(")") | tok!("]") | tok!("}") => { let value = match cur!(self) { tok!(")") => ')', tok!("]") => ']', tok!("}") => '}', _ => { unreachable!(); } }; let balance_close_type = match balance_stack.pop() { Some(v) => v, None => None, }; if Some(value) != balance_close_type { break; } } tok!("function") | tok!("(") | tok!("[") | tok!("{") => { let value = match cur!(self) { tok!("function") | tok!("(") => ')', tok!("[") => ']', tok!("{") => '}', _ => { unreachable!(); } }; balance_stack.push(Some(value)); } _ => {} } let token = self.input.bump()?; match token { Some(token) => tokens.push(token), None => break, } } Ok(tokens) } pub(super) fn parse_one_value_inner(&mut self) -> PResult<Value> { // TODO remove me self.input.skip_ws()?; let span = self.input.cur_span()?; match cur!(self) { tok!(",") => return Ok(Value::Delimiter(self.parse()?)), tok!("/") => return Ok(Value::Delimiter(self.parse()?)), tok!(";") => return Ok(Value::Delimiter(self.parse()?)), tok!("string") => return Ok(Value::Str(self.parse()?)), tok!("url") => return Ok(Value::Url(self.parse()?)), Token::Function { value, .. } => { if &*value.to_ascii_lowercase() == "url" || &*value.to_ascii_lowercase() == "src" { return Ok(Value::Url(self.parse()?)); } return Ok(Value::Function(self.parse()?)); } tok!("percentage") => return Ok(Value::Percentage(self.parse()?)), tok!("dimension") => return Ok(Value::Dimension(self.parse()?)), tok!("number") => return Ok(Value::Number(self.parse()?)), Token::Ident { value, .. } => { if value.starts_with("--") { return Ok(Value::DashedIdent(self.parse()?)); } else if &*value.to_ascii_lowercase() == "u" && peeked_is_one_of!(self, "+", "number", "dimension") { return Ok(Value::Urange(self.parse()?)); } return Ok(Value::Ident(self.parse()?)); } tok!("[") => { let ctx = Ctx { grammar: Grammar::DeclarationValue, ..self.ctx }; let block = self.with_ctx(ctx).parse_as::<SimpleBlock>()?; return Ok(Value::SimpleBlock(block)); } tok!("(") => { let ctx = Ctx { grammar: Grammar::DeclarationValue, ..self.ctx }; let block = self.with_ctx(ctx).parse_as::<SimpleBlock>()?; return Ok(Value::SimpleBlock(block)); } tok!("{") => { let ctx = Ctx { grammar: Grammar::DeclarationValue, ..self.ctx }; let block = self.with_ctx(ctx).parse_as::<SimpleBlock>()?; return Ok(Value::SimpleBlock(block)); } tok!("#") => return Ok(Value::Color(Color::HexColor(self.parse()?))), _ => {} } Err(Error::new(span, ErrorKind::Expected("Declaration value"))) } pub fn parse_simple_block(&mut self, ending: char) -> PResult<SimpleBlock> { let start_pos = self.input.last_pos()? - BytePos(1); let mut simple_block = SimpleBlock { span: Default::default(), name: Default::default(), value: vec![], }; loop { match cur!(self) { tok!("}") if ending == '}' => { self.input.bump()?; let ending_pos = self.input.last_pos()?; simple_block.span = swc_common::Span::new(ending_pos, start_pos, Default::default()); simple_block.name = '{'; return Ok(simple_block); } tok!(")") if ending == ')' => { self.input.bump()?; let ending_pos = self.input.last_pos()?; simple_block.span = swc_common::Span::new(ending_pos, start_pos, Default::default()); simple_block.name = '('; return Ok(simple_block); } tok!("]") if ending == ']' => { self.input.bump()?; let ending_pos = self.input.last_pos()?; simple_block.span = swc_common::Span::new(ending_pos, start_pos, Default::default()); simple_block.name = '['; return Ok(simple_block); } _ => { let token = self.input.bump()?.unwrap(); simple_block .value .push(ComponentValue::Value(Value::PreservedToken(token))); } } } } pub fn parse_component_value(&mut self) -> PResult<Value> { match cur!(self) { tok!("[") => Ok(Value::SimpleBlock(self.parse_simple_block(']')?)), tok!("(") => Ok(Value::SimpleBlock(self.parse_simple_block(')')?)), tok!("{") => Ok(Value::SimpleBlock(self.parse_simple_block('}')?)), tok!("function") => Ok(Value::Function(self.parse()?)), _ => { let token = self.input.bump()?; match token { Some(t) => Ok(Value::PreservedToken(t)), _ => { unreachable!(); } } } } } } impl<I> Parse<Delimiter> for Parser<I> where I: ParserInput, { fn parse(&mut self) -> PResult<Delimiter> { let span = self.input.cur_span()?; if !is_one_of!(self, ",", "/", ";") { return Err(Error::new( span, ErrorKind::Expected("',', '/' or ';' delim token"), )); } match cur!(self) { tok!(",") => { bump!(self); return Ok(Delimiter { span: span!(self, span.lo), value: DelimiterValue::Comma, }); } tok!("/") => { bump!(self); return Ok(Delimiter { span: span!(self, span.lo), value: DelimiterValue::Solidus, }); } tok!(";") => { bump!(self); return Ok(Delimiter { span: span!(self, span.lo), value: DelimiterValue::Semicolon, }); } _ => { unreachable!(); } } } } impl<I> Parse<Number> for Parser<I> where I: ParserInput, { fn parse(&mut self) -> PResult<Number> { let span = self.input.cur_span()?; if !is!(self, Number) { return Err(Error::new(span, ErrorKind::ExpectedNumber)); } let value = bump!(self); match value { Token::Number { value, raw, .. } => Ok(Number { span, value, raw }), _ => { unreachable!() } } } } impl<I> Parse<CustomIdent> for Parser<I> where I: ParserInput, { fn parse(&mut self) -> PResult<CustomIdent> { let span = self.input.cur_span()?; if !is!(self, Ident) { return Err(Error::new(span, ErrorKind::Expected("Ident"))); } match bump!(self) { Token::Ident { value, raw } => { match &*value.to_ascii_lowercase() { "initial" | "inherit" | "unset" | "revert" | "default" => { return Err(Error::new( span, ErrorKind::InvalidCustomIdent(stringify!(value)), )); } _ => {} } Ok(CustomIdent { span, value, raw }) } _ => { unreachable!() } } } } impl<I> Parse<DashedIdent> for Parser<I> where I: ParserInput, { fn parse(&mut self) -> PResult<DashedIdent> { let span = self.input.cur_span()?; if !is!(self, Ident) { return Err(Error::new(span, ErrorKind::Expected("Ident"))); } match bump!(self) { Token::Ident { value, raw } => { if !value.starts_with("--") { return Err(Error::new( span, ErrorKind::Expected("'--' at the start of dashed-ident"), )); } Ok(DashedIdent { span, value, raw }) } _ => { unreachable!() } } } } impl<I> Parse<Ident> for Parser<I> where I: ParserInput, { fn
(&mut self) -> PResult<Ident> { let span = self.input.cur_span()?; if !is!(self, Ident) { return Err(Error::new(span, ErrorKind::Expected("Ident"))); } match bump!(self) { Token::Ident { value, raw } => Ok(Ident { span, value, raw }), _ => { unreachable!() } } } } impl<I> Parse<Dimension> for Parser<I> where I: ParserInput, { fn parse(&mut self) -> PResult<Dimension> { let span = self.input.cur_span()?; if !is!(self, Dimension) { return Err(Error::new(span, ErrorKind::Expected("dimension token"))); } match cur!(self) { Token::Dimension { unit, .. } => { match unit { // <length> unit if is_length_unit(unit) => Ok(Dimension::Length(self.parse()?)), // <angle> unit if is_angle_unit(unit) => Ok(Dimension::Angle(self.parse()?)), // <time> unit if is_time_unit(unit) => Ok(Dimension::Time(self.parse()?)), // <frequency> unit if is_frequency_unit(unit) => Ok(Dimension::Frequency(self.parse()?)), // <resolution> unit if is_resolution_unit(unit) => Ok(Dimension::Resolution(self.parse()?)), // <flex> unit if is_flex_unit(unit) => Ok(Dimension::Flex(self.parse()?)), _ => Ok(Dimension::UnknownDimension(self.parse()?)), } } _ => { unreachable!() } } } } impl<I> Parse<Length> for Parser<I> where I: ParserInput, { fn parse(&mut self) -> PResult<Length> { let span = self.input.cur_span()?; if !is!(self, Dimension) { return Err(Error::new(span, ErrorKind::Expected("dimension token"))); } match bump!(self) { Token::Dimension { value, raw_value, unit, raw_unit, .. } => { // TODO validate let unit_len = raw_unit.len() as u32; Ok(Length { span, value: Number { value, raw: raw_value, span: swc_common::Span::new( span.lo, span.hi - BytePos(unit_len), Default::default(), ), }, unit: Ident { span: swc_common::Span::new( span.hi - BytePos(unit_len), span.hi, Default::default(), ), value: unit, raw: raw_unit, }, }) } _ => { unreachable!() } } } } impl<I> Parse<Angle> for Parser<I> where I: ParserInput, { fn parse(&mut self) -> PResult<Angle> { let span = self.input.cur_span()?; if !is!(self, Dimension) { return Err(Error::new(span, ErrorKind::Expected("dimension token"))); } match bump!(self) { Token::Dimension { value, raw_value, unit, raw_unit, .. } => { if !is_angle_unit(&unit) { return Err(Error::new( span, ErrorKind::Expected("'deg', 'grad', 'rad' or 'turn' units"), )); } let unit_len = raw_unit.len() as u32; Ok(Angle { span, value: Number { value, raw: raw_value, span: swc_common::Span::new( span.lo, span.hi - BytePos(unit_len), Default::default(), ), }, unit: Ident { span: swc_common::Span::new( span.hi - BytePos(unit_len), span.hi, Default::default(), ), value: unit, raw: raw_unit, }, }) } _ => { unreachable!() } } } } impl<I> Parse<Time> for Parser<I> where I: ParserInput, { fn parse(&mut self) -> PResult<Time> { let span = self.input.cur_span()?; if !is!(self, Dimension) { return Err(Error::new(span, ErrorKind::Expected("dimension token"))); } match bump!(self) { Token::Dimension { value, raw_value, unit, raw_unit, .. } => { if !is_time_unit(&unit) { return Err(Error::new(span, ErrorKind::Expected("'s' or 'ms' units"))); } let unit_len = raw_unit.len() as u32; Ok(Time { span, value: Number { value, raw: raw_value, span: swc_common::Span::new( span.lo, span.hi - BytePos(unit_len), Default::default(), ), }, unit: Ident { span: swc_common::Span::new( span.hi - BytePos(unit_len), span.hi, Default::default(), ), value: unit, raw: raw_unit, }, }) } _ => { unreachable!() } } } } impl<I> Parse<Frequency> for Parser<I> where I: ParserInput, { fn parse(&mut self) -> PResult<Frequency> { let span = self.input.cur_span()?; if !is!(self, Dimension) { return Err(Error::new(span, ErrorKind::Expected("dimension token"))); } match bump!(self) { Token::Dimension { value, raw_value, unit, raw_unit, .. } => { if !is_frequency_unit(&unit) { return Err(Error::new(span, ErrorKind::Expected("'Hz' or 'kHz' units"))); } let unit_len = raw_unit.len() as u32; Ok(Frequency { span, value: Number { value, raw: raw_value, span: swc_common::Span::new( span.lo, span.hi - BytePos(unit_len), Default::default(), ), }, unit: Ident { span: swc_common::Span::new( span.hi - BytePos(unit_len), span.hi, Default::default(), ), value: unit, raw: raw_unit, }, }) } _ => { unreachable!() } } } } impl<I> Parse<Resolution> for Parser<I> where I: ParserInput, { fn parse(&mut self) -> PResult<Resolution> { let span = self.input.cur_span()?; if !is!(self, Dimension) { return Err(Error::new(span, ErrorKind::Expected("dimension token"))); } match bump!(self) { Token::Dimension { value, raw_value, unit, raw_unit, .. } => { if !is_resolution_unit(&unit) { return Err(Error::new( span, ErrorKind::Expected("'dpi', 'dpcm', 'dppx' or 'x' units"), )); } let unit_len = raw_unit.len() as u32; Ok(Resolution { span, value: Number { value, raw: raw_value, span: swc_common::Span::new( span.lo, span.hi - BytePos(unit_len), Default::default(), ), }, unit: Ident { span: swc_common::Span::new( span.hi - BytePos(unit_len), span.hi, Default::default(), ), value: unit, raw: raw_unit, }, }) } _ => { unreachable!() } } } } impl<I> Parse<Flex> for Parser<I> where I: ParserInput, { fn parse(&mut self) -> PResult<Flex> { let span = self.input.cur_span()?; if !is!(self, Dimension) { return Err(Error::new(span, ErrorKind::Expected("dimension token"))); } match bump!(self) { Token::Dimension { value, raw_value, unit, raw_unit, .. } => { if !is_flex_unit(&unit) { return Err(Error::new(span, ErrorKind::Expected("'fr' unit"))); } let unit_len = raw_unit.len() as u32; Ok(Flex { span, value: Number { value, raw: raw_value, span: swc_common::Span::new( span.lo, span.hi - BytePos(unit_len), Default::default(), ), }, unit: Ident { span: swc_common::Span::new( span.hi - BytePos(unit_len), span.hi, Default::default(), ), value: unit, raw: raw_unit, }, }) } _ => { unreachable!() } } } } impl<I> Parse<UnknownDimension> for Parser<I> where I: ParserInput, { fn parse(&mut self) -> PResult<UnknownDimension> { let span = self.input.cur_span()?; if !is!(self, Dimension) { return Err(Error::new(span, ErrorKind::Expected("dimension token"))); } match bump!(self) { Token::Dimension { value, raw_value, unit, raw_unit, .. } => { let unit_len = raw_unit.len() as u32; Ok(UnknownDimension { span, value: Number { value, raw: raw_value, span: swc_common::Span::new( span.lo, span.hi - BytePos(unit_len), Default::default(), ), }, unit: Ident { span: swc_common::Span::new( span.hi - BytePos(unit_len), span.hi, Default::default(), ), value: unit, raw: raw_unit, }, }) } _ => { unreachable!() } } } } impl<I> Parse<HexColor> for Parser<I> where I: ParserInput, { fn parse(&mut self) -> PResult<HexColor> { let span = self.input.cur_span()?; if !is!(self, "#") { return Err(Error::new(span, ErrorKind::Expected("hash token"))); } match bump!(self) { Token::Hash { value, raw, .. } => Ok(HexColor { span, value, raw }), _ => { unreachable!() } } } } impl<I> Parse<Percentage> for Parser<I> where I: ParserInput, { fn parse(&mut self) -> PResult<Percentage> { let span = self.input.cur_span()?; if !is!(self, Percentage) { return Err(Error::new(span, ErrorKind::Expected("percentage token"))); } match bump!(self) { Token::Percentage { value, raw } => { let value = Number { span: swc_common::Span::new(span.lo, span.hi - BytePos(1), Default::default()), value, raw, }; Ok(Percentage { span, value }) } _ => { unreachable!() } } } } impl<I> Parse<Str> for Parser<I> where I: ParserInput, { fn parse(&mut self) -> PResult<Str> { let span = self.input.cur_span()?; if !is!(self, "string") { return Err(Error::new(span, ErrorKind::Expected("string token"))); } match bump!(self) { Token::String { value, raw } => Ok(Str { span, value, raw }), _ => { unreachable!() } } } } impl<I> Parse<Url> for Parser<I> where I: ParserInput, { fn parse(&mut self) -> PResult<Url> { let span = self.input.cur_span()?; if !is_one_of!(self, Url, Function) { return Err(Error::new(span, ErrorKind::Expected("url or function"))); } match bump!(self) { Token::Url { name, raw_name, value, raw_value, before, after, } => { let name_length = raw_name.len() as u32; let name = Ident { span: swc_common::Span::new( span.lo, span.lo + BytePos(name_length), Default::default(), ), value: name, raw: raw_name, }; let value = Some(UrlValue::Raw(UrlValueRaw { span: swc_common::Span::new( span.lo + BytePos(name_length + 1), span.hi - BytePos(1), Default::default(), ), before, after, value, raw: raw_value, })); Ok(Url { span: span!(self, span.lo), name, value, modifiers: None, }) } Token::Function { value: function_name, raw: raw_function_name, } => { if &*function_name.to_ascii_lowercase() != "url" && &*function_name.to_ascii_lowercase() != "src" { return Err(Error::new(span, ErrorKind::Expected("'url' or 'src' name"))); } let name = Ident { span: swc_common::Span::new(span.lo, span.hi - BytePos(1), Default::default()), value: function_name, raw: raw_function_name, }; self.input.skip_ws()?; let value = match cur!(self) { tok!("string") => Some(UrlValue::Str(self.parse()?)), _ => None, }; self.input.skip_ws()?; let mut modifiers = vec![]; loop { if is!(self, ")") { break; } match cur!(self) { tok!("ident") => { modifiers.push(UrlModifier::Ident(self.parse()?)); } tok!("function") => { modifiers.push(UrlModifier::Function(self.parse()?)); } _ => { let span = self.input.cur_span()?; return Err(Error::new(span, ErrorKind::Expected("ident or function"))); } } self.input.skip_ws()?; } expect!(self, ")"); Ok(Url { span: span!(self, span.lo), name, value, modifiers: Some(modifiers), }) } _ => { unreachable!() } } } } impl<I> Parse<Function> for Parser<I> where I: ParserInput, { fn parse(&mut self) -> PResult<Function> { let span = self.input.cur_span()?; let ident = match bump!(self) { Token::Function { value, raw } => (value, raw), _ => { unreachable!() } }; let lowercased_name = &*ident.0.to_ascii_lowercase(); let name = Ident { span: swc_common::Span::new(span.lo, span.hi - BytePos(1), Default::default()), value: ident.0, raw: ident.1, }; // Create a function with its name equal to the value of the current input token // and with its value initially set to an empty list. let mut function = Function { span: Default::default(), name, value: vec![], }; // Repeatedly consume the next input token and process it as follows: loop { // <EOF-token> // This is a parse error. Return the function. if is!(self, EOF) { break; } match cur!(self) { // <)-token> // Return the function. tok!(")") => { bump!(self); break; } // anything else // Reconsume the current input token. Consume a component value and append the // returned value to the function’s value. _ => { let state = self.input.state(); match lowercased_name { "calc" | "sin" | "cos" | "tan" | "asin" | "acos" | "atan" | "sqrt" | "exp" | "abs" | "sign" => { self.input.skip_ws()?; let calc_sum = Value::CalcSum(self.parse()?); function.value.push(calc_sum); self.input.skip_ws()?; } "min" | "max" | "hypot" => { self.input.skip_ws()?; let calc_sum = Value::CalcSum(self.parse()?); function.value.push(calc_sum); loop { self.input.skip_ws()?; if is!(self, ",") { function.value.push(Value::Delimiter(self.parse()?)); } else { break; } self.input.skip_ws()?; let calc_sum = Value::CalcSum(self.parse()?); function.value.push(calc_sum); } } "clamp" => { self.input.skip_ws()?; let calc_sum = Value::CalcSum(self.parse()?); function.value.push(calc_sum); self.input.skip_ws()?; if is!(self, ",") { function.value.push(Value::Delimiter(self.parse()?)); } else { let span = self.input.cur_span()?; return Err(Error::new( span, ErrorKind::Expected("',' delim token"), )); } self.input.skip_ws()?; let calc_sum = Value::CalcSum(self.parse()?); function.value.push(calc_sum); self.input.skip_ws()?; if is!(self, ",") { function.value.push(Value::Delimiter(self.parse()?)); } else { let span = self.input.cur_span()?; return Err(Error::new( span, ErrorKind::Expected("',' delim token"), )); } self.input.skip_ws()?; let calc_sum = Value::CalcSum(self.parse()?); function.value.push(calc_sum); self.input.skip_ws()?; } "round" => { self.input.skip_ws()?; if is!(self, "ident") { // TODO improve me let rounding_strategy = Value::Ident(self.parse()?); function.value.push(rounding_strategy); self.input.skip_ws()?; if is!(self, ",") { function.value.push(Value::Delimiter(self.parse()?)); } else { let span = self.input.cur_span()?; return Err(Error::new( span, ErrorKind::Expected("',' delim token"), )); } self.input.skip_ws()?; } let calc_sum = Value::CalcSum(self.parse()?); function.value.push(calc_sum); self.input.skip_ws()?; if is!(self, ",") { function.value.push(Value::Delimiter(self.parse()?)); } else { let span = self.input.cur_span()?; return Err(Error::new( span, ErrorKind::Expected("',' delim token"), )); } self.input.skip_ws()?; let calc_sum = Value::CalcSum(self.parse()?); function.value.push(calc_sum); self.input.skip_ws()?; } "mod" | "rem" | "atan2" | "pow" => { self.input.skip_ws()?; let calc_sum = Value::CalcSum(self.parse()?); function.value.push(calc_sum); self.input.skip_ws()?; if is!(self, ",") { function.value.push(Value::Delimiter(self.parse()?)); } else { let span = self.input.cur_span()?; return Err(Error::new( span, ErrorKind::Expected("',' delim token"), )); } self.input.skip_ws()?; let calc_sum = Value::CalcSum(self.parse()?); function.value.push(calc_sum); self.input.skip_ws()?; } "log" => { self.input.skip_ws()?; let calc_sum = Value::CalcSum(self.parse()?); function.value.push(calc_sum); self.input.skip_ws()?; if is!(self, ",") { function.value.push(Value::Delimiter(self.parse()?)); self.input.skip_ws()?; let calc_sum = Value::CalcSum(self.parse()?); function.value.push(calc_sum); self.input.skip_ws()?; } } _ => { let parsed = self.parse_one_value_inner(); let value = match parsed { Ok(value) => { self.input.skip_ws()?; value } Err(err) => { self.errors.push(err); self.input.reset(&state); self.parse_component_value()? } }; function.value.push(value); } }; } } } function.span = span!(self, span.lo); return Ok(function); } } // <urange> = // u '+' <ident-token> '?'* | // u <dimension-token> '?'* | // u <number-token> '?'* | // u <number-token> <dimension-token> | // u <number-token> <number-token> | // u '+' '?'+ impl<I> Parse<Urange> for Parser<I> where I: ParserInput, { fn parse(&mut self) -> PResult<Urange> { let span = self.input.cur_span()?; let mut urange = String::new(); // should start with `u` or `U` match cur!(self) { Token::Ident { value, .. } if &*value.to_ascii_lowercase() == "u" => { let ident = match bump!(self) { Token::Ident { value, .. } => value, _ => { unreachable!(); } }; urange.push_str(&ident); } _ => { return Err(Error::new(span, ErrorKind::Expected("'u' ident token"))); } }; match cur!(self) { // u '+' <ident-token> '?'* // u '+' '?'+ Token::Delim { value } if *value == '+' => { let plus = match bump!(self) { Token::Delim { value } => value, _ => { unreachable!(); } }; urange.push(plus); if is!(self, Ident) { let ident = match bump!(self) { Token::Ident { value, .. } => value, _ => { unreachable!(); } }; urange.push_str(&ident); loop { if !is!(self, "?") { break; } let question = match bump!(self) { Token::Delim { value } => value, _ => { unreachable!(); } }; urange.push(question); } } else { let question = match bump!(self) { Token::Delim { value } if value == '?' => value, _ => { return Err(Error::new(span, ErrorKind::Expected("'?' delim token"))); } }; urange.push(question); loop { if !is!(self, "?") { break; } let question = match bump!(self) { Token::Delim { value } => value, _ => { unreachable!(); } }; urange.push(question); } } } // u <number-token> '?'* // u <number-token> <dimension-token> // u <number-token> <number-token> tok!("number") => { let number = match bump!(self) { Token::Number { raw, .. } => raw, _ => { unreachable!(); } }; urange.push_str(&number); match cur!(self) { tok!("?") => { let question = match bump!(self) { Token::Delim { value } => value, _ => { unreachable!(); } }; urange.push(question); loop { if !is!(self, "?") { break; } let question = match bump!(self) { Token::Delim { value } => value, _ => { unreachable!(); } }; urange.push(question); } } tok!("dimension") => { let dimension = match bump!(self) { Token::Dimension { raw_value, raw_unit, .. } => (raw_value, raw_unit), _ => { unreachable!(); } }; urange.push_str(&dimension.0); urange.push_str(&dimension.1); } tok!("number") => { let number = match bump!(self) { Token::Number { raw, .. } => raw, _ => { unreachable!(); } }; urange.push_str(&number); } _ => {} } } // u <dimension-token> '?'* tok!("dimension") => { let dimension = match bump!(self) { Token::Dimension { raw_value, raw_unit, .. } => (raw_value, raw_unit), _ => { unreachable!(); } }; urange.push_str(&dimension.0); urange.push_str(&dimension.1); loop { if !is!(self, "?") { break; } let question = match bump!(self) { Token::Delim { value } => value, _ => { unreachable!(); } }; urange.push(question); } } _ => { return Err(Error::new( span, ErrorKind::Expected("dimension, number or '?' delim token"), )); } } return Ok(Urange { span: span!(self, span.lo), value: urange.into(), }); } } impl<I> Parse<CalcSum> for Parser<I> where I: ParserInput, { fn parse(&mut self) -> PResult<CalcSum> { let start = self.input.cur_span()?.lo; let mut expressions = vec![]; let calc_product = CalcProductOrOperator::Product(self.parse()?); let mut end = match calc_product { CalcProductOrOperator::Product(ref calc_product) => calc_product.span.hi, _ => { unreachable!(); } }; expressions.push(calc_product); loop { self.input.skip_ws()?; match cur!(self) { tok!("+") | tok!("-") => { let operator = CalcProductOrOperator::Operator(self.parse()?); expressions.push(operator); self.input.skip_ws()?; let calc_product = CalcProductOrOperator::Product(self.parse()?); end = match calc_product { CalcProductOrOperator::Product(ref calc_product) => calc_product.span.hi, _ => { unreachable!(); } }; expressions.push(calc_product); } _ => { break; } } } Ok(CalcSum { span: Span::new(start, end, Default::default()), expressions, }) } } impl<I> Parse<CalcProduct> for Parser<I> where I: ParserInput, { fn parse(&mut self) -> PResult<CalcProduct> { let start = self.input.cur_span()?.lo; let mut expressions = vec![]; let calc_value = CalcValueOrOperator::Value(self.parse()?); let mut end = match calc_value { CalcValueOrOperator::Value(ref calc_value) => match calc_value { CalcValue::Number(item) => item.span.hi, CalcValue::Percentage(item) => item.span.hi, CalcValue::Constant(item) => item.span.hi, CalcValue::Sum(item) => item.span.hi, CalcValue::Function(item) => item.span.hi, CalcValue::Dimension(item) => match item { Dimension::Length(item) => item.span.hi, Dimension::Angle(item) => item.span.hi, Dimension::Time(item) => item.span.hi, Dimension::Frequency(item) => item.span.hi, Dimension::Resolution(item) => item.span.hi, Dimension::Flex(item) => item.span.hi, Dimension::UnknownDimension(item) => item.span.hi, }, }, _ => { unreachable!(); } }; expressions.push(calc_value); loop { self.input.skip_ws()?; match cur!(self) { tok!("*") | tok!("/") => { let operator = CalcValueOrOperator::Operator(self.parse()?); expressions.push(operator); self.input.skip_ws()?; let calc_value = CalcValueOrOperator::Value(self.parse()?); end = match calc_value { CalcValueOrOperator::Value(ref calc_value) => match calc_value { CalcValue::Number(item) => item.span.hi, CalcValue::Percentage(item) => item.span.hi, CalcValue::Constant(item) => item.span.hi, CalcValue::Sum(item) => item.span.hi, CalcValue::Function(item) => item.span.hi, CalcValue::Dimension(item) => match item { Dimension::Length(item) => item.span.hi, Dimension::Angle(item) => item.span.hi, Dimension::Time(item) => item.span.hi, Dimension::Frequency(item) => item.span.hi, Dimension::Resolution(item) => item.span.hi, Dimension::Flex(item) => item.span.hi, Dimension::UnknownDimension(item) => item.span.hi, }, }, _ => { unreachable!(); } }; expressions.push(calc_value); } _ => { break; } } } Ok(CalcProduct { span: Span::new(start, end, Default::default()), expressions, }) } } impl<I> Parse<CalcOperator> for Parser<I> where I: ParserInput, { fn parse(&mut self) -> PResult<CalcOperator> { let span = self.input.cur_span()?; match cur!(self) { tok!("+") => { bump!(self); Ok(CalcOperator { span: span!(self, span.lo), value: CalcOperatorType::Add, }) } tok!("-") => { bump!(self); Ok(CalcOperator { span: span!(self, span.lo), value: CalcOperatorType::Sub, }) } tok!("*") => { bump!(self); Ok(CalcOperator { span: span!(self, span.lo), value: CalcOperatorType::Mul, }) } tok!("/") => { bump!(self); Ok(CalcOperator { span: span!(self, span.lo), value: CalcOperatorType::Div, }) } _ => { let span = self.input.cur_span()?; return Err(Error::new( span, ErrorKind::Expected("'+', '-', '*' or '/' delim tokens"), )); } } } } impl<I> Parse<CalcValue> for Parser<I> where I: ParserInput, { fn parse(&mut self) -> PResult<CalcValue> { match cur!(self) { tok!("number") => Ok(CalcValue::Number(self.parse()?)), tok!("dimension") => Ok(CalcValue::Dimension(self.parse()?)), tok!("percentage") => Ok(CalcValue::Percentage(self.parse()?)), Token::Ident { value, .. } => { match &*value.to_ascii_lowercase() { "e" | "pi" | "infinity" | "-infinity" | "nan" => {} _ => { let span = self.input.cur_span()?; return Err(Error::new( span, ErrorKind::Expected( "'e', 'pi', 'infinity', '-infinity' or 'NaN', ident tokens", ), )); } } Ok(CalcValue::Constant(self.parse()?)) } tok!("(") => { let span = self.input.cur_span()?; expect!(self, "("); self.input.skip_ws()?; let mut calc_sum_in_parens: CalcSum = self.parse()?; self.input.skip_ws()?; expect!(self, ")"); calc_sum_in_parens.span = span!(self, span.lo); Ok(CalcValue::Sum(calc_sum_in_parens)) } tok!("function") => Ok(CalcValue::Function(self.parse()?)), _ => { let span = self.input.cur_span()?; return Err(Error::new( span, ErrorKind::Expected( "'number', 'dimension', 'percentage', 'ident', '(' or 'function' tokens", ), )); } } } } fn is_length_unit(unit: &str) -> bool { matches!( &*unit.to_ascii_lowercase(), "em" | "rem" | "ex" | "rex" | "cap" | "rcap" | "ch" | "rch" | "ic" | "ric" | "lh" | "rlh" | // Viewport-percentage Lengths "vw" | "svw" | "lvw" | "dvw" | "vh" | "svh" | "lvh" | "dvh" | "vi" | "svi" | "lvi" | "dvi" | "vb" | "svb" | "lvb" | "dvb" | "vmin" | "svmin" | "lvmin" | "dvmin" | "vmax" | "svmax" | "lvmax" | "dvmax" | // Absolute lengths "cm" | "mm" | "q" | "in" | "pc" | "pt" | "px" | "mozmm" ) } fn is_angle_unit(unit: &str) -> bool { matches!(&*unit.to_ascii_lowercase(), "deg" | "grad" | "rad" | "turn") } fn is_time_unit(unit: &str) -> bool { matches!(&*unit.to_ascii_lowercase(), "s" | "ms") } fn is_frequency_unit(unit: &str) -> bool { matches!(&*unit.to_ascii_lowercase(), "hz" | "khz") } fn is_resolution_unit(unit: &str) -> bool { matches!(&*unit.to_ascii_lowercase(), "dpi" | "dpcm" | "dppx" | "x") } fn is_flex_unit(unit: &str) -> bool { matches!(&*unit.to_ascii_lowercase(), "fr") }
parse
update-count.js
import fp from 'fastify-plugin' import { Readable } from 'readable-stream' // In some cases you might need a custom plugin only in a specific // part of yoru application. As we saw before, every plugin that needs // or could be shared with the entire application should live inside // the top level `/plugins` directory. In this case since we need this // plugin to operate only in the `/redirect` scope, we will define it here. // As you can see, the redirect plugin lives inside a folder instead of a file, // what is the difference? `fastify-autoload` will automatically load every file // inside the `/routes` folder, or every folder that contains an `index.js` file. // In this way we have just created a specifc scope for our redirect logic that // will not be shared with other plugins of your application. // Thanks encapsulation! :rocket: // This plugin defines a bulk updater instance that we will use // for updating the visit count of our redirects. You could use // a single update db call for each redirect as well, but the // performances will suffer a bit more. // By using a bulk indexer we accumulate update operations and // we flush every now and then, in a fire and forget fashion. async function
(fastify, opts) { const { elastic, indices } = fastify // To create a "infinite update loop" with the Elasticsearch // bulk helper you need to create a readable stream instance. const updateCountStream = new Readable({ objectMode: true, read (size) {} }) // https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/client-helpers.html#_bulk_helper const updateCountUpdater = elastic.helpers.bulk({ datasource: updateCountStream, flushBytes: 1000000, flushInterval: 5000, onDocument (doc) { return [{ update: { _index: indices.SHORTURL, _id: doc.id } }, { doc: undefined, script: { lang: 'painless', source: 'ctx._source.count += 1' } }] }, onDrop (doc) { fastify.log.warn(doc, 'dropped redirect analytics record') } }) updateCountUpdater.catch(err => { fastify.log.error(err, 'updateCountUpdater throwed an error') process.exit(1) }) // This onClose hook will be executed before the onClose's Elasticsearch // hook, because onClose hooks are executed in LIFO. This guranteees us // that we will not lose data or see unwanted exceptions while closing. fastify.addHook('onClose', (instance, done) => { updateCountStream.push(null) updateCountUpdater.then(() => done()) }) // Writing to a stream is a sync operation fastify.decorate('updateCount', id => { updateCountStream.push({ id }) }) } export default fp(updateCount, { name: 'update-count' // dependencies: ['elasticsearch'] })
updateCount
k3d.go
package k3d import ( "context" "errors" "fmt" "os" "os/exec" "path" "strings" "time" "github.com/sirupsen/logrus" "github.com/traefik/mesh/integration/try" "github.com/traefik/mesh/pkg/k8s" corev1 "k8s.io/api/core/v1" kubeerror "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) var ( k3sImage = "rancher/k3s" k3sVersion = "v1.18.6-k3s1" ) // DockerImage holds the configuration of a Docker image. type DockerImage struct { Name string Local bool } // ClusterOptions holds the configuration of the cluster. type ClusterOptions struct { Cmd []string Images []DockerImage } // ClusterOptionFunc mutates the given ClusterOptions. type ClusterOptionFunc func(opts *ClusterOptions) // WithoutTraefik tells k3d to not start a k3s cluster with Traefik already installed in. func WithoutTraefik() func(opts *ClusterOptions) { return func(opts *ClusterOptions) { opts.Cmd = append(opts.Cmd, "--k3s-server-arg", "--no-deploy=traefik") } } // WithoutCoreDNS tells k3d to not start a k3s cluster with CoreDNS already installed in. func WithoutCoreDNS() func(opts *ClusterOptions) { return func(opts *ClusterOptions) { opts.Cmd = append(opts.Cmd, "--k3s-server-arg", "--no-deploy=coredns") } } // WithImages tells k3d to import the given image. Images which are tagged a local won't be pull locally before being // imported. func WithImages(images ...DockerImage) func(opts *ClusterOptions) { return func(opts *ClusterOptions) { opts.Images = append(opts.Images, images...) } } // Cluster is a k3s cluster. type Cluster struct { logger logrus.FieldLogger workingDir string Client k8s.Client Name string } // NewCluster creates a new k3s cluster using the given configuration. func NewCluster(logger logrus.FieldLogger, masterURL string, name string, opts ...ClusterOptionFunc) (*Cluster, error) { clusterOpts := ClusterOptions{ Images: []DockerImage{ {Name: "rancher/coredns-coredns:1.6.3"}, }, } for _, opt := range opts { opt(&clusterOpts) } workingDir, err := os.Getwd() if err != nil { return nil, fmt.Errorf("unable to get working directory: %w", err) } if err = pullDockerImages(logger, clusterOpts.Images); err != nil { return nil, fmt.Errorf("unable to pull docker images: %w", err) } if err = createCluster(logger, name, clusterOpts.Cmd); err != nil { return nil, fmt.Errorf("unable to create k3s cluster: %d", err) } if err = importDockerImages(logger, name, clusterOpts.Images); err != nil { return nil, fmt.Errorf("unable to import docker images in the cluster: %w", err) } var client k8s.Client client, err = createK8sClient(logger, name, masterURL) if err != nil
if err = waitClusterReady(client); err != nil { return nil, err } return &Cluster{ logger: logger, workingDir: workingDir, Client: client, Name: name, }, nil } // Stop stops the cluster. func (c *Cluster) Stop(logger logrus.FieldLogger) error { cmd := exec.Command("k3d", "cluster", "delete", c.Name) cmd.Env = os.Environ() logger.Infof("Stopping k3s cluster %q...", c.Name) if err := cmd.Run(); err != nil { return fmt.Errorf("unable to stop cluster: %w", err) } return nil } // CreateNamespace creates a new namespace. func (c *Cluster) CreateNamespace(logger logrus.FieldLogger, name string) error { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() namespace := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{Name: name}, } logger.Infof("Creating namespace %q...", name) _, err := c.Client.KubernetesClient().CoreV1().Namespaces().Create(ctx, namespace, metav1.CreateOptions{}) if err != nil { return fmt.Errorf("unable to create namespace %q: %w", name, err) } return nil } // Apply applies the given directory/file on the cluster. func (c *Cluster) Apply(logger logrus.FieldLogger, resourcesPath string) error { opts := []string{ "apply", "-f", path.Join(c.workingDir, resourcesPath), } logger.Infof("Applying %q...", resourcesPath) cmd := exec.Command("kubectl", opts...) cmd.Env = os.Environ() output, err := cmd.CombinedOutput() if err != nil { logger.WithError(err).Errorf("unable to apply resources: %s", string(output)) return err } return nil } // Delete deletes from the cluster the resources declared in the given directory/file. func (c *Cluster) Delete(logger logrus.FieldLogger, resourcesPath string) { opts := []string{ "delete", "-f", path.Join(c.workingDir, resourcesPath), "--force", "--grace-period=0", } logger.Infof("Delete %q...", resourcesPath) cmd := exec.Command("kubectl", opts...) cmd.Env = os.Environ() output, err := cmd.CombinedOutput() if err != nil { logger.WithError(err).Errorf("unable to delete resources: %s", string(output)) } } // WaitReadyDeployment waits for the given deployment to be ready. func (c *Cluster) WaitReadyDeployment(name, namespace string, timeout time.Duration) error { err := try.Retry(func() error { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() d, err := c.Client.KubernetesClient().AppsV1().Deployments(namespace).Get(ctx, name, metav1.GetOptions{}) if err != nil { if kubeerror.IsNotFound(err) { return fmt.Errorf("deployment %q has not been yet created", name) } return fmt.Errorf("unable get deployment %q in namespace %q: %v", name, namespace, err) } if d.Status.UpdatedReplicas == *(d.Spec.Replicas) && d.Status.Replicas == *(d.Spec.Replicas) && d.Status.AvailableReplicas == *(d.Spec.Replicas) && d.Status.ObservedGeneration >= d.Generation { return nil } return errors.New("deployment not ready") }, timeout) if err != nil { return fmt.Errorf("deployment %q in namespace %q is not ready: %w", name, namespace, err) } return nil } // WaitReadyDaemonSet waits for the given daemonset to be ready. func (c *Cluster) WaitReadyDaemonSet(name, namespace string, timeout time.Duration) error { err := try.Retry(func() error { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() d, err := c.Client.KubernetesClient().AppsV1().DaemonSets(namespace).Get(ctx, name, metav1.GetOptions{}) if err != nil { if kubeerror.IsNotFound(err) { return fmt.Errorf("daemonset %q has not been yet created", name) } return fmt.Errorf("unable get daemonset %q in namespace %q: %v", name, namespace, err) } if d.Status.NumberReady == d.Status.DesiredNumberScheduled { return nil } return errors.New("daemonset not ready") }, timeout) if err != nil { return fmt.Errorf("daemonset %q in namespace %q is not ready: %w", name, namespace, err) } return nil } // WaitReadyPod waits for the given pod to be ready. func (c *Cluster) WaitReadyPod(name, namespace string, timeout time.Duration) error { err := try.Retry(func() error { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() pod, err := c.Client.KubernetesClient().CoreV1().Pods(namespace).Get(ctx, name, metav1.GetOptions{}) if err != nil { if kubeerror.IsNotFound(err) { return fmt.Errorf("pod %q has not been yet created", name) } return fmt.Errorf("unable get pod %q in namespace %q: %v", name, namespace, err) } if !isPodReady(pod) { return errors.New("pod is not ready") } return nil }, timeout) if err != nil { return fmt.Errorf("pod %q in namespace %q is not ready: %w", name, namespace, err) } return nil } func isPodReady(pod *corev1.Pod) bool { for _, condition := range pod.Status.Conditions { if condition.Type == corev1.PodReady { return condition.Status == corev1.ConditionTrue } } return false } func createCluster(logger logrus.FieldLogger, clusterName string, cmdOpts []string) error { logger.Infof("Creating k3d cluster %s...", clusterName) opts := []string{ "cluster", "create", clusterName, "--no-lb", "--api-port", "8443", "--agents", "1", "--image", fmt.Sprintf("%s:%s", k3sImage, k3sVersion), "--wait", "--timeout", "30s", } cmd := exec.Command("k3d", append(opts, cmdOpts...)...) cmd.Env = os.Environ() output, err := cmd.CombinedOutput() if err != nil { logger.WithError(err).Errorf("unable to create cluster: %s", string(output)) return err } return nil } func pullDockerImages(logger logrus.FieldLogger, images []DockerImage) error { for _, image := range images { if image.Local { continue } logger.Infof("Pulling image %q...", image.Name) cmd := exec.Command("docker", "pull", image.Name) cmd.Env = os.Environ() output, err := cmd.CombinedOutput() if err != nil { logger.WithError(err).Errorf("unable to pull image %q: %s", image.Name, string(output)) return err } } return nil } func importDockerImages(logger logrus.FieldLogger, clusterName string, images []DockerImage) error { args := []string{ "image", "import", "--cluster", clusterName, } for _, image := range images { args = append(args, image.Name) } logger.Info("Importing images...") cmd := exec.Command("k3d", args...) cmd.Env = os.Environ() output, err := cmd.CombinedOutput() if err != nil { logger.WithError(err).Errorf("unable to import images: %s", string(output)) return err } return nil } func createK8sClient(logger logrus.FieldLogger, clusterName, masterURL string) (k8s.Client, error) { cmd := exec.Command("k3d", "kubeconfig", "write", clusterName) cmd.Env = os.Environ() output, err := cmd.CombinedOutput() if err != nil { return nil, fmt.Errorf("unable to retrieve kubeconfig for cluster %q: %w", clusterName, err) } kubeConfigPath := strings.TrimSuffix(string(output), "\n") logger.Info("Creating kubernetes client...") var client k8s.Client err = try.Retry(func() error { client, err = k8s.NewClient(logger, masterURL, kubeConfigPath) if err != nil { return fmt.Errorf("unable to create clients: %v", err) } if _, err = client.KubernetesClient().Discovery().ServerVersion(); err != nil { return fmt.Errorf("unable to get server version: %v", err) } return nil }, 30*time.Second) if err != nil { return nil, fmt.Errorf("unable to create kubernetes client: %w", err) } logger.Infof("Setting new KUBECONFIG path: %q...", kubeConfigPath) err = os.Setenv("KUBECONFIG", kubeConfigPath) if err != nil { return nil, fmt.Errorf("unable to set KUBECONFIG path: %w", err) } return client, nil } func waitClusterReady(client k8s.Client) error { err := try.Retry(func() error { _, _, err := client.KubernetesClient().Discovery().ServerGroupsAndResources() return err }, 60*time.Second) if err != nil { return fmt.Errorf("timed out waiting for the cluster to be ready: %w", err) } return nil }
{ return nil, fmt.Errorf("unable to create kubernetes client: %w", err) }
utils.py
from django.db.models import Q from django.core.exceptions import ValidationError from settings.local import people_who_need_to_know_about_failures from settings.local import inventorys_email from email.mime.text import MIMEText import ipaddr import smtplib import re import urllib # http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html # Prevent this case http://people.mozilla.com/~juber/public/t1_t2_scenario.txt # TODO, put this in a try accept and always unlock things def locked_function(lock_name, timeout=10): def decorator(f): def new_function(*args, **kwargs): from django.db import connection cursor = connection.cursor() cursor.execute( "SELECT GET_LOCK('{lock_name}', {timeout});".format( lock_name=lock_name, timeout=timeout ) ) ret = f(*args, **kwargs) cursor.execute( "SELECT RELEASE_LOCK('{lock_name}');".format( lock_name=lock_name ) ) return ret return new_function return decorator def fail_mail(content, subject='Inventory is having issues.', to=people_who_need_to_know_about_failures, from_=inventorys_email): """Send email about a failure.""" if not to: return msg = MIMEText(content) msg['Subject'] = subject msg['From'] = inventorys_email # msg['To'] = to s = smtplib.SMTP('localhost') s.sendmail(from_, to, msg.as_string()) s.quit() class IPFilterSet(object): """The IPFilterSet expects that all IPFilters added to it are of the same type. This might be useful later. """ def __init__(self): self.ipfs = [] def add(self, ipf): self.ipfs.append(ipf) def pprint(self): for ipf in self.ipfs: print ipf def pprint_intersect(self): for intersect in self.calc_intersect(): print intersect def calc_intersect(self): """ This is where the magic comes from. Given a list of IPFilter objects, figure the ranges that are common to all the IPFilters, and create a new list of IPFilter objects that represent this range. """ def trim(self, r, rs, ip_type): if not (rs and r): return r r1 = rs[0] rx = self.intersect(r, r1, ip_type) return self.trim(rx, rs[1:], ip_type) def intersect(self, r1, r2, ip_type): """ Cases: * Subset or equal * Left intersect * Right intersect * No intersect """ if r1.start > r2.end: return None # We have intersection somewhere. if r1.end == r2.end and r1.start == r1.end: # r1 is subset of r2 # Low High # r1 |---------| # r2 |---------| # rx |---------| return r1 if r1.start > r2.start and r1.end < r2.end: # r1 is subset of r2 # Low High # r1 |-------| # r2 |---------| # rx |---------| return r1 if r1.start > r2.start and r1.end > r2.start: # Low High # r1 |---------| # r2 |---------| # rx |------| return IPFilter(None, ip_type, r1.start_upper, r1.start_lower, r2.end_upper, r2.end_lower) if r1.start < r2.start and r1.end < r2.end: # Low High # r1 |---------| # r2 |---------| # rx |------| return IPFilter(None, ip_type, r2.start_upper, r2.start_lower, r1.end_upper, r1.end_lower) class IPFilter(object): def __init__(self, start, end, ip_type, object_=None): self.object_ = object_ # The composite object (it can be None) self.ip_type = ip_type self.start, self.end, self.Q = start_end_filter(start, end, ip_type) def __str__(self): return "{0} -- {1}".format(self.start, self.end) def __repr__(self):
def start_end_filter(start, end, ip_type): ip_type = ip_type if ip_type == '6': IPKlass = ipaddr.IPv6Address elif ip_type == '4': IPKlass = ipaddr.IPv4Address istart = IPKlass(start) iend = IPKlass(end) if int(istart) > int(iend): raise ValidationError("start cannot be greater than end") start_upper, start_lower = one_to_two(int(istart)) end_upper, end_lower = one_to_two(int(iend)) # Equal uppers. Lower must be within. if start_upper == end_upper: q = Q(ip_upper=start_upper, ip_lower__gte=start_lower, ip_lower__lte=end_lower, ip_type=ip_type) else: q = Q(ip_upper__gt=start_upper, ip_upper__lt=end_upper, ip_type=ip_type) return istart, iend, q def overlap(r1, r2, ip_type=None, cast_to_int=False): if cast_to_int: if ip_type == '4': IP = ipaddr.IPv4Address elif ip_type == '6': IP = ipaddr.IPv6Address else: raise Exception('Not using overlap right. Missing ip_type') to_int = lambda r: (int(IP(r[0])), int(IP(r[1]))) return _overlap(to_int(r1), to_int(r2)) else: return _overlap(r1, r2) def _overlap(r1, r2): # Make r1 always larger than r2 size = lambda r: abs(r[0] - r[1]) if size(r1) > size(r2): (r1_start, r1_end), (r2_start, r2_end) = r1, r2 else: # They could be the same size (r1_start, r1_end), (r2_start, r2_end) = r2, r1 if r1_start > r2_end or r1_end < r2_start: # no overlap return None if r1_start <= r2_start and r1_end >= r2_end: # r2 is subset of r1 or equal # Low High # r1 |---------| # r2 |-------| # rx |---------| # OR # Low High # r1 |---------| # r2 |---------| # rx |---------| return r2 if r1_start >= r2_start and r1_end >= r2_end: # Low High # r1 |-----------| # r2 |---------| # rx |------| return r1_start, r2_end if r1_start <= r2_start and r1_end <= r2_end: # Low High # r1 |-----------| # r2 |---------| # rx |------| return r2_start, r1_end def networks_to_Q(networks): """Take a list of network objects and compile a Q that matches any object that exists in one of those networks.""" q = Q(pk__lt=-1) for network in networks: network.update_ipf() q = q | network.ipf.Q return q def two_to_four(start, end): start_upper = start >> 64 start_lower = start & (1 << 64) - 1 end_upper = end >> 64 end_lower = end & (1 << 64) - 1 return start_upper, start_lower, end_upper, end_lower def one_to_two(ip): return (ip >> 64, ip & (1 << 64) - 1) def two_to_one(upper, lower): return long(upper << 64) + long(lower) def four_to_two(start_upper, start_lower, end_upper, end_lower): start = (start_upper << 64) + start_lower end = (end_upper << 64) + end_lower return start, end def int_to_ip(ip, ip_type): """A wrapper that converts a 32 or 128 bit integer into human readable IP format.""" if ip_type == '6': IPKlass = ipaddr.IPv6Address elif ip_type == '4': IPKlass = ipaddr.IPv4Address return str(IPKlass(ip)) def ip_to_int(ip, ip_type): """A wrapper that converts a string to 32 or 128 bit integer""" if ip_type == '6': IPKlass = ipaddr.IPv6Address elif ip_type == '4': IPKlass = ipaddr.IPv4Address return int(IPKlass(ip)) def resolve_ip_type(ip_str): if ip_str.find(':') > -1: Klass = ipaddr.IPv6Network ip_type = '6' elif ip_str.find('.') > -1: Klass = ipaddr.IPv4Network ip_type = '4' else: Klass = None ip_type = None return ip_type, Klass def to_a(text, obj, use_absolute_url=True): if use_absolute_url: return "<a href='{0}'>{1}</a>".format(obj.get_absolute_url(), text) else: return "<a href='{0}'>{1}</a>".format(obj, text) def create_key_index(kvs): index = {} for kv in kvs: index[kv['key']] = kv return index def mozillian(name): return "https://mozillians.org/en-US/search/?q={0}".format( urllib.quote_plus(name) ) def mozillian_a(name): return "<a href='{0}'>{1}</a>".format(mozillian(re.escape(name)), name)
return str(self)
lemonbar.rs
use super::data::*; pub struct LemonbarFormatter { escape: bool, } impl Formatter for LemonbarFormatter { fn format(&mut self, data: &Format) -> String { match *data { Format::UnescapedStr(ref s) => s.clone(), Format::Str(ref s) => if self.escape { s.replace("%", "%%") } else { s.to_owned() }, Format::Concat(ref fs) => fs.iter().map(|f| self.format(f)).fold("".to_owned(), |a, b| a + &b),
Format::Align(ref a, ref f) => format!("{}{}", match *a { Alignment::Left => "%{l}", Alignment::Center => "%{c}", Alignment::Right => "%{r}", }, self.format(f)), Format::FgColor(ref c, ref f) => format!("%{{F{}}}{}%{{F-}}", c, self.format(f)), Format::BgColor(ref c, ref f) => format!("%{{B{}}}{}%{{B-}}", c, self.format(f)), Format::NoSeparator(ref f) => self.format(f), Format::Padding(_, ref f) => self.format(f), Format::Clickable(ref act, ref f) => match act { &ClickAction::ShellCommand(ref mb, ref a) => format!("%{{A{}:{}:}}{}%{{A}}", mouse_button(mb), a.replace(":", "\\:"), self.format(f)), _ => self.format(f), // TODO } } } } fn mouse_button(mb: &MouseButton) -> usize { match *mb { MouseButton::Left => 1, MouseButton::Middle => 2, MouseButton::Right => 3, } } impl LemonbarFormatter { pub fn new() -> LemonbarFormatter { LemonbarFormatter { escape: true } } /// Turn off escaping for e.g. lemonbar-xft pub fn new_noescape() -> LemonbarFormatter { LemonbarFormatter { escape: false } } }
connectionMonitor.ts
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** import * as pulumi from "@pulumi/pulumi"; import * as inputs from "../../types/input"; import * as outputs from "../../types/output"; import * as utilities from "../../utilities"; /** * Information about the connection monitor. */ export class
extends pulumi.CustomResource { /** * Get an existing ConnectionMonitor resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, opts?: pulumi.CustomResourceOptions): ConnectionMonitor { return new ConnectionMonitor(name, undefined as any, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure-nextgen:network/v20180401:ConnectionMonitor'; /** * Returns true if the given object is an instance of ConnectionMonitor. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is ConnectionMonitor { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === ConnectionMonitor.__pulumiType; } /** * Determines if the connection monitor will start automatically once created. */ public readonly autoStart!: pulumi.Output<boolean | undefined>; /** * Describes the destination of connection monitor. */ public readonly destination!: pulumi.Output<outputs.network.v20180401.ConnectionMonitorDestinationResponse>; public /*out*/ readonly etag!: pulumi.Output<string | undefined>; /** * Connection monitor location. */ public readonly location!: pulumi.Output<string | undefined>; /** * Monitoring interval in seconds. */ public readonly monitoringIntervalInSeconds!: pulumi.Output<number | undefined>; /** * The monitoring status of the connection monitor. */ public /*out*/ readonly monitoringStatus!: pulumi.Output<string | undefined>; /** * Name of the connection monitor. */ public /*out*/ readonly name!: pulumi.Output<string>; /** * The provisioning state of the connection monitor. */ public /*out*/ readonly provisioningState!: pulumi.Output<string | undefined>; /** * Describes the source of connection monitor. */ public readonly source!: pulumi.Output<outputs.network.v20180401.ConnectionMonitorSourceResponse>; /** * The date and time when the connection monitor was started. */ public /*out*/ readonly startTime!: pulumi.Output<string | undefined>; /** * Connection monitor tags. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; /** * Connection monitor type. */ public /*out*/ readonly type!: pulumi.Output<string>; /** * Create a ConnectionMonitor resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: ConnectionMonitorArgs, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; if (!(opts && opts.id)) { if (!args || args.connectionMonitorName === undefined) { throw new Error("Missing required property 'connectionMonitorName'"); } if (!args || args.destination === undefined) { throw new Error("Missing required property 'destination'"); } if (!args || args.networkWatcherName === undefined) { throw new Error("Missing required property 'networkWatcherName'"); } if (!args || args.resourceGroupName === undefined) { throw new Error("Missing required property 'resourceGroupName'"); } if (!args || args.source === undefined) { throw new Error("Missing required property 'source'"); } inputs["autoStart"] = args ? args.autoStart : undefined; inputs["connectionMonitorName"] = args ? args.connectionMonitorName : undefined; inputs["destination"] = args ? args.destination : undefined; inputs["location"] = args ? args.location : undefined; inputs["monitoringIntervalInSeconds"] = args ? args.monitoringIntervalInSeconds : undefined; inputs["networkWatcherName"] = args ? args.networkWatcherName : undefined; inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined; inputs["source"] = args ? args.source : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["etag"] = undefined /*out*/; inputs["monitoringStatus"] = undefined /*out*/; inputs["name"] = undefined /*out*/; inputs["provisioningState"] = undefined /*out*/; inputs["startTime"] = undefined /*out*/; inputs["type"] = undefined /*out*/; } else { inputs["autoStart"] = undefined /*out*/; inputs["destination"] = undefined /*out*/; inputs["etag"] = undefined /*out*/; inputs["location"] = undefined /*out*/; inputs["monitoringIntervalInSeconds"] = undefined /*out*/; inputs["monitoringStatus"] = undefined /*out*/; inputs["name"] = undefined /*out*/; inputs["provisioningState"] = undefined /*out*/; inputs["source"] = undefined /*out*/; inputs["startTime"] = undefined /*out*/; inputs["tags"] = undefined /*out*/; inputs["type"] = undefined /*out*/; } if (!opts) { opts = {} } if (!opts.version) { opts.version = utilities.getVersion(); } const aliasOpts = { aliases: [{ type: "azure-nextgen:network/latest:ConnectionMonitor" }, { type: "azure-nextgen:network/v20171001:ConnectionMonitor" }, { type: "azure-nextgen:network/v20171101:ConnectionMonitor" }, { type: "azure-nextgen:network/v20180101:ConnectionMonitor" }, { type: "azure-nextgen:network/v20180201:ConnectionMonitor" }, { type: "azure-nextgen:network/v20180601:ConnectionMonitor" }, { type: "azure-nextgen:network/v20180701:ConnectionMonitor" }, { type: "azure-nextgen:network/v20180801:ConnectionMonitor" }, { type: "azure-nextgen:network/v20181001:ConnectionMonitor" }, { type: "azure-nextgen:network/v20181101:ConnectionMonitor" }, { type: "azure-nextgen:network/v20181201:ConnectionMonitor" }, { type: "azure-nextgen:network/v20190201:ConnectionMonitor" }, { type: "azure-nextgen:network/v20190401:ConnectionMonitor" }, { type: "azure-nextgen:network/v20190601:ConnectionMonitor" }, { type: "azure-nextgen:network/v20190701:ConnectionMonitor" }, { type: "azure-nextgen:network/v20190801:ConnectionMonitor" }, { type: "azure-nextgen:network/v20190901:ConnectionMonitor" }, { type: "azure-nextgen:network/v20191101:ConnectionMonitor" }, { type: "azure-nextgen:network/v20191201:ConnectionMonitor" }, { type: "azure-nextgen:network/v20200301:ConnectionMonitor" }, { type: "azure-nextgen:network/v20200401:ConnectionMonitor" }, { type: "azure-nextgen:network/v20200501:ConnectionMonitor" }, { type: "azure-nextgen:network/v20200601:ConnectionMonitor" }, { type: "azure-nextgen:network/v20200701:ConnectionMonitor" }] }; opts = opts ? pulumi.mergeOptions(opts, aliasOpts) : aliasOpts; super(ConnectionMonitor.__pulumiType, name, inputs, opts); } } /** * The set of arguments for constructing a ConnectionMonitor resource. */ export interface ConnectionMonitorArgs { /** * Determines if the connection monitor will start automatically once created. */ readonly autoStart?: pulumi.Input<boolean>; /** * The name of the connection monitor. */ readonly connectionMonitorName: pulumi.Input<string>; /** * Describes the destination of connection monitor. */ readonly destination: pulumi.Input<inputs.network.v20180401.ConnectionMonitorDestination>; /** * Connection monitor location. */ readonly location?: pulumi.Input<string>; /** * Monitoring interval in seconds. */ readonly monitoringIntervalInSeconds?: pulumi.Input<number>; /** * The name of the Network Watcher resource. */ readonly networkWatcherName: pulumi.Input<string>; /** * The name of the resource group containing Network Watcher. */ readonly resourceGroupName: pulumi.Input<string>; /** * Describes the source of connection monitor. */ readonly source: pulumi.Input<inputs.network.v20180401.ConnectionMonitorSource>; /** * Connection monitor tags. */ readonly tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; }
ConnectionMonitor
watch.go
package main import ( "crypto/tls" "errors" "log" "net/http" "net/url" "sync" "sync/atomic" "time" ) var success int32 var fail int32 var total int32 var clientNum = 5000 var wg = sync.WaitGroup{} var client = &http.Client{} var start time.Time func main() { u := "http://127.0.0.1:30110/v1/default/kie/kv?label=app:default&label=env:test&wait=5m" req, err := http.NewRequest("GET", u, nil) if err != nil { log.Panic(err) return } uri, err := url.Parse(u) if err != nil { log.Panic(err) } wg.Add(clientNum) client = &http.Client{ Timeout: 1 * time.Minute, } if uri.Scheme == "https" { client.Transport = &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, }, } } for n := 0; n < clientNum; n++ { go func() { defer wg.Done() err = watch(req) if err != nil { atomic.AddInt32(&fail, 1) return } atomic.AddInt32(&success, 1) if total == 0 { start = time.Now() atomic.AddInt32(&total, 1) } }() } wg.Wait() duration := time.Since(start) log.Printf("success %d", success) log.Printf("fail %d", fail) log.Printf("takes %s", duration.String()) } func watch(req *http.Request) error
{ res, err := client.Do(req) if err != nil { log.Println(err) return err } defer res.Body.Close() if res.Status != "200 OK" { log.Println(res.Status) return errors.New("not OK") } return nil }
triangular.rs
extern crate ndarray; #[macro_use] extern crate ndarray_linalg; use ndarray::*; use ndarray_linalg::*; fn test1d<A, Sa, Sb>(uplo: UPLO, a: &ArrayBase<Sa, Ix2>, b: &ArrayBase<Sb, Ix1>, tol: A::Real) where A: Scalar, Sa: Data<Elem = A>, Sb: DataMut<Elem = A> + DataOwned, { println!("a = {:?}", a); println!("b = {:?}", b); let x = a.solve_triangular(uplo, Diag::NonUnit, b).unwrap(); println!("x = {:?}", &x); let b_ = a.dot(&x); println!("Ax = {:?}", &b_); assert_close_l2!(&b_, b, tol); } fn test2d<A, Sa, Sb>(uplo: UPLO, a: &ArrayBase<Sa, Ix2>, b: &ArrayBase<Sb, Ix2>, tol: A::Real) where A: Scalar, Sa: Data<Elem = A>, Sb: DataMut<Elem = A> + DataOwned + DataClone, { println!("a = {:?}", a); println!("b = {:?}", b); let x = a.solve_triangular(uplo, Diag::NonUnit, b).unwrap(); println!("x = {:?}", &x); let b_ = a.dot(&x); println!("Ax = {:?}", &b_); assert_close_l2!(&b_, b, tol); } #[test] fn triangular_1d_upper() { let n = 3; let b: Array1<f64> = random(n); let a: Array2<f64> = random((n, n)).into_triangular(UPLO::Upper); test1d(UPLO::Upper, &a, &b, 1e-7); } #[test] fn triangular_1d_lower()
#[test] fn triangular_1d_upper_t() { let n = 3; let b: Array1<f64> = random(n); let a: Array2<f64> = random((n, n).f()).into_triangular(UPLO::Upper); test1d(UPLO::Upper, &a, &b, 1e-7); } #[test] fn triangular_1d_lower_t() { let n = 3; let b: Array1<f64> = random(n); let a: Array2<f64> = random((n, n).f()).into_triangular(UPLO::Lower); test1d(UPLO::Lower, &a, &b, 1e-7); } #[test] fn triangular_2d_upper() { let b: Array2<f64> = random((3, 4)); let a: Array2<f64> = random((3, 3)).into_triangular(UPLO::Upper); test2d(UPLO::Upper, &a, &b, 1e-7); } #[test] fn triangular_2d_lower() { let b: Array2<f64> = random((3, 4)); let a: Array2<f64> = random((3, 3)).into_triangular(UPLO::Lower); test2d(UPLO::Lower, &a, &b, 1e-7); } #[test] fn triangular_2d_lower_t() { let b: Array2<f64> = random((3, 4)); let a: Array2<f64> = random((3, 3).f()).into_triangular(UPLO::Lower); test2d(UPLO::Lower, &a, &b, 1e-7); } #[test] fn triangular_2d_upper_t() { let b: Array2<f64> = random((3, 4)); let a: Array2<f64> = random((3, 3).f()).into_triangular(UPLO::Upper); test2d(UPLO::Upper, &a, &b, 1e-7); } #[test] fn triangular_2d_upper_bt() { let b: Array2<f64> = random((3, 4).f()); let a: Array2<f64> = random((3, 3)).into_triangular(UPLO::Upper); test2d(UPLO::Upper, &a, &b, 1e-7); } #[test] fn triangular_2d_lower_bt() { let b: Array2<f64> = random((3, 4).f()); let a: Array2<f64> = random((3, 3)).into_triangular(UPLO::Lower); test2d(UPLO::Lower, &a, &b, 1e-7); } #[test] fn triangular_2d_lower_t_bt() { let b: Array2<f64> = random((3, 4).f()); let a: Array2<f64> = random((3, 3).f()).into_triangular(UPLO::Lower); test2d(UPLO::Lower, &a, &b, 1e-7); } #[test] fn triangular_2d_upper_t_bt() { let b: Array2<f64> = random((3, 4).f()); let a: Array2<f64> = random((3, 3).f()).into_triangular(UPLO::Upper); test2d(UPLO::Upper, &a, &b, 1e-7); }
{ let n = 3; let b: Array1<f64> = random(n); let a: Array2<f64> = random((n, n)).into_triangular(UPLO::Lower); test1d(UPLO::Lower, &a, &b, 1e-7); }
2019-10-23-setDefaultNotificationValues.ts
import { registerMigration, fillDefaultValues } from './migrationUtils'; import { Notifications } from '../../lib/collections/notifications/collection';
name: "setDefaultNotificationValues", dateWritten: "2019-10-23", idempotent: true, action: async () => { await fillDefaultValues({ collection: Notifications, fieldName: "emailed", }); await fillDefaultValues({ collection: Notifications, fieldName: "waitingForBatch", }); }, });
registerMigration({
xyz.py
""" This module reads and writes xyz files. """ import os import numpy as np def
(file_location): # Open an xyz file and return symbols and coordinates. xyz_file = np.genfromtxt(fname=file_location, skip_header=2, dtype='unicode') symbols = xyz_file[:,0] coords = (xyz_file[:,1:]) coords = coords.astype(np.float) return symbols, coords def write_xyz(file_location, symbols, coordinates): # Write an xyz file given a file location, symbols, and coordinates. num_atoms = len(symbols) with open(file_location, 'w+') as f: f.write('{}\n'.format(num_atoms)) f.write('XYZ file\n') for i in range(num_atoms): f.write('{}\t{}\t{}\t{}\n'.format(symbols[i], coordinates[i,0], coordinates[i,1], coordinates[i,2]))
open_xyz
recover_test.go
package chanbackup import ( "bytes" "fmt" "net" "testing" "github.com/btgsuite/btgd/btcec" ) type mockChannelRestorer struct { fail bool callCount int
func (m *mockChannelRestorer) RestoreChansFromSingles(...Single) error { if m.fail { return fmt.Errorf("fail") } m.callCount++ return nil } type mockPeerConnector struct { fail bool callCount int } func (m *mockPeerConnector) ConnectPeer(node *btcec.PublicKey, addrs []net.Addr) error { if m.fail { return fmt.Errorf("fail") } m.callCount++ return nil } // TestUnpackAndRecoverSingles tests that we're able to properly unpack and // recover a set of packed singles. func TestUnpackAndRecoverSingles(t *testing.T) { t.Parallel() keyRing := &mockKeyRing{} // First, we'll create a number of single chan backups that we'll // shortly back to so we can begin our recovery attempt. numSingles := 10 backups := make([]Single, 0, numSingles) var packedBackups PackedSingles for i := 0; i < numSingles; i++ { channel, err := genRandomOpenChannelShell() if err != nil { t.Fatalf("unable make channel: %v", err) } single := NewSingle(channel, nil) var b bytes.Buffer if err := single.PackToWriter(&b, keyRing); err != nil { t.Fatalf("unable to pack single: %v", err) } backups = append(backups, single) packedBackups = append(packedBackups, b.Bytes()) } chanRestorer := mockChannelRestorer{} peerConnector := mockPeerConnector{} // Now that we have our backups (packed and unpacked), we'll attempt to // restore them all in a single batch. // If we make the channel restore fail, then the entire method should // as well chanRestorer.fail = true err := UnpackAndRecoverSingles( packedBackups, keyRing, &chanRestorer, &peerConnector, ) if err == nil { t.Fatalf("restoration should have failed") } chanRestorer.fail = false // If we make the peer connector fail, then the entire method should as // well peerConnector.fail = true err = UnpackAndRecoverSingles( packedBackups, keyRing, &chanRestorer, &peerConnector, ) if err == nil { t.Fatalf("restoration should have failed") } chanRestorer.callCount-- peerConnector.fail = false // Next, we'll ensure that if all the interfaces function as expected, // then the channels will properly be unpacked and restored. err = UnpackAndRecoverSingles( packedBackups, keyRing, &chanRestorer, &peerConnector, ) if err != nil { t.Fatalf("unable to recover chans: %v", err) } // Both the restorer, and connector should have been called 10 times, // once for each backup. if chanRestorer.callCount != numSingles { t.Fatalf("expected %v calls, instead got %v", numSingles, chanRestorer.callCount) } if peerConnector.callCount != numSingles { t.Fatalf("expected %v calls, instead got %v", numSingles, peerConnector.callCount) } // If we modify the keyRing, then unpacking should fail. keyRing.fail = true err = UnpackAndRecoverSingles( packedBackups, keyRing, &chanRestorer, &peerConnector, ) if err == nil { t.Fatalf("unpacking should have failed") } // TODO(roasbeef): verify proper call args } // TestUnpackAndRecoverMulti tests that we're able to properly unpack and // recover a packed multi. func TestUnpackAndRecoverMulti(t *testing.T) { t.Parallel() keyRing := &mockKeyRing{} // First, we'll create a number of single chan backups that we'll // shortly back to so we can begin our recovery attempt. numSingles := 10 backups := make([]Single, 0, numSingles) for i := 0; i < numSingles; i++ { channel, err := genRandomOpenChannelShell() if err != nil { t.Fatalf("unable make channel: %v", err) } single := NewSingle(channel, nil) backups = append(backups, single) } multi := Multi{ StaticBackups: backups, } var b bytes.Buffer if err := multi.PackToWriter(&b, keyRing); err != nil { t.Fatalf("unable to pack multi: %v", err) } // Next, we'll pack the set of singles into a packed multi, and also // create the set of interfaces we need to carry out the remainder of // the test. packedMulti := PackedMulti(b.Bytes()) chanRestorer := mockChannelRestorer{} peerConnector := mockPeerConnector{} // If we make the channel restore fail, then the entire method should // as well chanRestorer.fail = true err := UnpackAndRecoverMulti( packedMulti, keyRing, &chanRestorer, &peerConnector, ) if err == nil { t.Fatalf("restoration should have failed") } chanRestorer.fail = false // If we make the peer connector fail, then the entire method should as // well peerConnector.fail = true err = UnpackAndRecoverMulti( packedMulti, keyRing, &chanRestorer, &peerConnector, ) if err == nil { t.Fatalf("restoration should have failed") } chanRestorer.callCount-- peerConnector.fail = false // Next, we'll ensure that if all the interfaces function as expected, // then the channels will properly be unpacked and restored. err = UnpackAndRecoverMulti( packedMulti, keyRing, &chanRestorer, &peerConnector, ) if err != nil { t.Fatalf("unable to recover chans: %v", err) } // Both the restorer, and connector should have been called 10 times, // once for each backup. if chanRestorer.callCount != numSingles { t.Fatalf("expected %v calls, instead got %v", numSingles, chanRestorer.callCount) } if peerConnector.callCount != numSingles { t.Fatalf("expected %v calls, instead got %v", numSingles, peerConnector.callCount) } // If we modify the keyRing, then unpacking should fail. keyRing.fail = true err = UnpackAndRecoverMulti( packedMulti, keyRing, &chanRestorer, &peerConnector, ) if err == nil { t.Fatalf("unpacking should have failed") } // TODO(roasbeef): verify proper call args }
}
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::SourceLocationKey; use fixture_tests::Fixture; use graphql_ir::{build, Program}; use graphql_syntax::parse_executable; use graphql_text_printer::print_operation; use graphql_transforms::{inline_fragments, skip_redundant_nodes}; use std::sync::Arc; use test_schema::{get_test_schema, get_test_schema_with_extensions}; pub fn
(fixture: &Fixture<'_>) -> Result<String, String> { let source_location = SourceLocationKey::standalone(fixture.file_name); let parts: Vec<_> = fixture.content.split("%extensions%").collect(); let mut printed = if let [base, extensions] = parts.as_slice() { let ast = parse_executable(base, source_location).unwrap(); let schema = get_test_schema_with_extensions(extensions); let ir = build(&schema, &ast.definitions).unwrap(); let program = Program::from_definitions(Arc::clone(&schema), ir); let next_program = skip_redundant_nodes(&inline_fragments(&program)); next_program .operations() .map(|def| print_operation(&schema, def)) .collect::<Vec<_>>() } else { let schema = get_test_schema(); let ast = parse_executable(fixture.content, source_location).unwrap(); let ir = build(&schema, &ast.definitions).unwrap(); let program = Program::from_definitions(Arc::clone(&schema), ir); let next_program = skip_redundant_nodes(&inline_fragments(&program)); next_program .operations() .map(|def| print_operation(&schema, def)) .collect::<Vec<_>>() }; printed.sort(); Ok(printed.join("\n\n")) }
transform_fixture
tesseract_ocr_evaluation_local.py
import glob import uuid import json import requests import copy,time import os import cv2 import numpy as np from time import sleep import pandas as pd import logging from collections import Counter import pytesseract from pytesseract import Output #from pytesseract import pytesseract from difflib import SequenceMatcher from io import StringIO from dynamic_adjustment import coord_adjustment import ast from leven import levenshtein from horizontal_merging import horzontal_merging ocr_level = "LINE" text_processing = True REJECT_FILTER = 2 #crop_factor= 5 #crop_factor_y= 4 crop_factor= 5 crop_factor_y= 0 crop_save = True digitization = True vis_thresh=0.90 LANG_MAPPING = { "en" : ["Latin","eng"], "kn" : ['Kannada',"kan"], "gu": ["guj"], "or": ["ori"], "hi" : ["Devanagari","hin","eng"], "bn" : ["Bengali","ben"], "mr": ["Devanagari","hin","eng"], "ta": ['Tamil',"tam"], "te" : ["Telugu","tel"], "ml" :["Malayalam"], "ma" :["Marathi"] } #path = '/home/ubuntu/tesseract_evaluation/data/' #output_path = '/home/ubuntu/tesseract_evaluation/result/' #output_path_boxes= '/home/ubuntu/tesseract_evaluation/test_word_boxes/' #base_path = '/home/ubuntu/tesseract_evaluation/test_word_boxes/' path = '/home/naresh/Tarento/testing_document_processor/test_pipeline/data/' output_path = '/home/naresh/Tarento/testing_document_processor/test_pipeline/result/' output_path_boxes= '/home/naresh/Tarento/testing_document_processor/test_word_boxes/' base_path= '/home/naresh/Tarento/testing_document_processor/test_word_boxes/' psms = [6,7,8,9,10,11] token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6ImRoaXJhai5kYWdhQHRhcmVudG8uY29tIiwicGFzc3dvcmQiOiJiJyQyYiQxMiRuTXdNcHpCVlBXVVUvSlVLWXBKYWkuQUd2SUNJalJVcUdIbnBPenRzai5VRU55emlSZmk1TyciLCJleHAiOjE2MTk3Njg2NjN9.14IL5_kw83F5gxjUMSw6kCDLYQhjAg306AwJj0DsxWc' word_url = "https://auth.anuvaad.org/anuvaad-etl/wf-manager/v1/workflow/async/initiate" google_url = "https://auth.anuvaad.org/anuvaad-etl/wf-manager/v1/workflow/async/initiate" layout_url = "https://auth.anuvaad.org/anuvaad-etl/wf-manager/v1/workflow/async/initiate" segmenter_url = "https://auth.anuvaad.org/anuvaad-etl/wf-manager/v1/workflow/async/initiate" bs_url ="https://auth.anuvaad.org/anuvaad-etl/wf-manager/v1/workflow/jobs/search/bulk" evaluator_url = "https://auth.anuvaad.org/anuvaad-etl/document-processor/evaluator/v0/process" #evaluator_url = 'http://0.0.0.0:5001/anuvaad-etl/document-processor/evaluator/v0/process' download_url ="https://auth.anuvaad.org/download/" upload_url = 'https://auth.anuvaad.org/anuvaad-api/file-uploader/v0/upload-file' headers = { 'auth-token' :token } class Draw: def __init__(self,input_json,save_dir,regions,prefix='',color= (255,0,0),thickness=5): self.json = input_json self.save_dir = save_dir self.regions = regions self.prefix = prefix self.color = color self.thickness=thickness if self.prefix == 'seg': #print('drawing children') self.draw_region_children() else: self.draw_region__sub_children() def get_coords(self,page_index): return self.json['outputs'][0]['pages'][page_index][self.regions] def get_page_count(self): return(self.json['outputs'][0]['page_info']) def get_page(self,page_index): page_path = self.json['outputs'][0]['page_info'][page_index] page_path = page_path.split('upload')[1]#'/'.join(page_path.split('/')[1:]) #print(page_path) return download_file(download_url,headers,page_path,f_type='image') def draw_region(self): font = cv2.FONT_HERSHEY_SIMPLEX for page_index in range(len(self.get_page_count())) : nparr = np.frombuffer(self.get_page(page_index), np.uint8) image = cv2.imdecode(nparr, cv2.IMREAD_COLOR) for region in self.get_coords(page_index) : ground = region['boundingBox']['vertices'] pts = [] for pt in ground: pts.append([int(pt['x']) ,int(pt['y'])]) cv2.polylines(image, [np.array(pts)],True, self.color, self.thickness) if 'class' not in region.keys(): region['class'] = 'TEXT' cv2.putText(image, str(region['class']), (pts[0][0],pts[0][1]), font, 2, (0,125,255), 3, cv2.LINE_AA) image_path = os.path.join(self.save_dir , '{}_{}_{}.png'.format(self.regions,self.prefix,page_index)) cv2.imwrite(image_path , image) def draw_region_children(self): font = cv2.FONT_HERSHEY_SIMPLEX fontScale = 2 thickness =3 for page_index in range(len(self.get_page_count())) : nparr = np.frombuffer(self.get_page(page_index), np.uint8) image = cv2.imdecode(nparr, cv2.IMREAD_COLOR) for region_index,region in enumerate(self.get_coords(page_index)) : try: ground = region['boundingBox']['vertices'] pts = [] for pt in ground: pts.append([int(pt['x']) ,int(pt['y'])]) #print(pts) region_color = (0 ,0,125+ 130*(region_index/ len(self.get_coords(page_index)))) cv2.polylines(image, [np.array(pts)],True, region_color, self.thickness) cv2.putText(image, str(region_index), (pts[0][0],pts[0][1]), font, fontScale, region_color, thickness, cv2.LINE_AA) for line_index, line in enumerate(region['children']): ground = line['boundingBox']['vertices'] pts = [] for pt in ground: pts.append([int(pt['x']) ,int(pt['y'])]) line_color = (125 + 130*(region_index/ len(self.get_coords(page_index))) ,0,0) cv2.polylines(image, [np.array(pts)],True, line_color, self.thickness -2) cv2.putText(image, str(line_index), (pts[0][0],pts[0][1]), font, fontScale, line_color, thickness, cv2.LINE_AA) except Exception as e: print(str(e)) print(region) image_path = os.path.join(self.save_dir , '{}_{}.png'.format(self.prefix,page_index)) cv2.imwrite(image_path , image) def draw_region__sub_children(self):
# # google vision pipeline def google_ocr_v15(url,headers,pdf_name): file = { "files": [ { "locale": "hi", "path": pdf_name, "type": "pdf", "config":{ "OCR": { "option": "HIGH_ACCURACY", "language": "hi", "top_correction":"True", "craft_word": "True", "craft_line": "True", } }} ], "workflowCode": "WF_A_FCWDLDBSOD15GV" } res = requests.post(url,json=file,headers=headers) return res.json() def upload_file(pdf_file,headers,url): #url = 'https://auth.anuvaad.org/anuvaad-api/file-uploader/v0/upload-file' files = [ ('file',(open(pdf_file,'rb')))] response = requests.post(url, headers=headers, files=files) return response.json() def download_file(download_url,headers,outputfile,f_type='json'): download_url =download_url+str(outputfile) res = requests.get(download_url,headers=headers) if f_type == 'json': return res.json() else : return res.content def save_json(path,res): with open(path, "w", encoding='utf8') as write_file: json.dump(res, write_file,ensure_ascii=False ) def bulk_search(job_id,bs_url,headers): bs_request = { "jobIDs": [job_id], "taskDetails":"true" } print(job_id) res = requests.post(bs_url,json=bs_request,headers=headers, timeout = 10000) print(res.json()) while(1): in_progress = res.json()['jobs'][0]['status'] if in_progress == 'COMPLETED': outputfile = res.json()['jobs'][0]['output'][0]['outputFile'] print(in_progress) return outputfile break sleep(0.5) print(in_progress) res = requests.post(bs_url,json=bs_request,headers=headers, timeout = 10000) def execute_module(module,url,input_file,module_code,pdf_dir,overwirte=True , draw=True): output_path = os.path.join(pdf_dir,'{}.json'.format(module_code)) if os.path.exists(output_path) and not overwirte: print(' loading *****************{}'.format(module_code )) with open(output_path,'r') as wd_file : response = json.load(wd_file) wf_res = pdf_dir + '/{}_wf.json'.format(module_code) with open(wf_res,'r') as wd_file : json_file = json.load(wd_file) #json_file = upload_file(output_path,headers,upload_url)['data'] else : if module_code in ['wd','gv']: res = upload_file(input_file,headers,upload_url) print('upload response **********', res) pdf_name = res['data'] response = module(url,headers,pdf_name) else : response = module(url,headers,input_file) if 'eval' in module_code : json_file = response['outputFile'] response = download_file(download_url,headers,json_file) save_json(output_path,response) return json_file,response print(' response *****************{} {}'.format(module_code ,response )) job_id = response['jobID'] json_file = bulk_search(job_id,bs_url,headers) save_json(pdf_dir + '/{}_wf.json'.format(module_code),json_file) print('bulk search response **************',json_file ) response = download_file(download_url,headers,json_file) save_json(output_path,response) if draw : if module_code in ['wd','gv']: Draw(response,pdf_dir,regions='lines',prefix=module_code) else : Draw(response,pdf_dir,regions='regions',prefix=module_code) return json_file,response def evaluate__and_save_input(pdf_files,output_dir,headers,word_url,layout_url,download_url,upload_url,bs_url): word_responses = {} layout_responses = {} segmenter_responses = [] for pdf in pdf_files: #try : pdf_name = pdf.split('/')[-1].split('.')[0] print(pdf , ' is being processed') pdf_output_dir = os.path.join(output_dir,pdf_name) os.system('mkdir -p "{}"'.format(pdf_output_dir)) wd_json,_ = execute_module(google_ocr_v15,word_url,input_file=pdf,module_code='gv',pdf_dir=pdf_output_dir,overwirte=False , draw=False) def main(path,headers,word_url,layout_url,download_url,upload_url,bs_url): pdf_names = glob.glob(path + '/*.pdf') return evaluate__and_save_input(pdf_names,output_path,headers,word_url,layout_url,download_url,upload_url,bs_url) if digitization: main(path,headers,word_url,layout_url,download_url,upload_url,bs_url) def bound_coordinate(corrdinate,max): if corrdinate < 0 : corrdinate = 0 if corrdinate > max: corrdinate = max - 2 return int(corrdinate) def get_image_from_box(image, box, height=140): #box = data['box'] #scale = np.sqrt((box[1, 1] - box[2, 1])**2 + (box[0, 1] - box[3, 1])**2) / height #print("scale is ",scale) #w = int(np.sqrt((box[0, 0] - box[1, 0])**2 + (box[2, 0] - box[3, 0])**2) / scale) w = max(abs(box[0, 0] - box[1, 0]),abs(box[2, 0] - box[3, 0])) height = max(abs(box[0, 1] - box[3, 1]),abs(box[1, 1] - box[2, 1])) pts1 = np.float32(box) #w=2266-376 pts2 = np.float32([[0, 0], [int(w), 0],[int(w),int(height)],[0,int(height)]]) M = cv2.getPerspectiveTransform(pts1, pts2) result_img = cv2.warpPerspective(image,M,(int(w), int(height))) #flags=cv2.INTER_NEAREST return result_img def process_dfs(temp_df): temp_df = temp_df[temp_df.text.notnull()] text = "" conf=0 temp_dict1 = [] for index, row in temp_df.iterrows(): temp_dict2 = {} conf = conf + row["conf"] temp_dict2["text"]=row['text'] temp_dict2["conf"]=row['conf'] text = text +" "+ str(row['text']) temp_dict1.append(temp_dict2) return text,temp_dict1 def process_dfs_updated(temp_df,language,psm_val,image): temp_df = temp_df[temp_df.text.notnull()] text = "" conf=0 temp_dict1 = [] if len(temp_df)>0: for index, row in temp_df.iterrows(): temp_dict2 = {} org_conf = row["conf"] org_text = row['text'] flag = True if row["conf"]<50: print(row["top"],row["height"],row["left"],row["width"]) crop_image = image[ int(row["top"]):int(row["top"]+row["height"]), int(row["left"]):int(row["left"]+row["width"])] for psm in psms: df2 = pytesseract.image_to_data(crop_image,config='--psm '+str(psm), lang=LANG_MAPPING[language][0],output_type=Output.DATAFRAME) temp_df2 = df2[df2.text.notnull()] if len(temp_df2)>0: new_conf = temp_df2.iloc[0].conf if org_conf<new_conf: org_conf = new_conf org_text = temp_df2.iloc[0].text if flag: print("old text", row['text']) print("new text", org_text) conf = conf + org_conf temp_dict2["text"]=org_text temp_dict2["conf"]=org_conf text = text +" "+ str(org_text) temp_dict1.append(temp_dict2) return text,temp_dict1 def check_psm(path,coord,language,mode_height,save_base_path,psm_val,org_score,org_text,line_text,org_conf): for psm in psms: text,conf_dict = get_text(path,coord,language,mode_height,save_base_path,psm) if text_processing: text_list = text.split() text = " ".join(text_list) score,message,match_count = seq_matcher(text,line_text) if score==1.0 or score==1: org_score = score org_text = text org_conf = conf_dict break elif score>org_score: org_score =score org_text = text org_conf = conf_dict return org_text, org_conf,org_score def get_text(path,coord,language,mode_height,save_base_path,psm_val): #try: path = path.split('upload')[1] image = download_file(download_url,headers,path,f_type='image') nparr = np.frombuffer(image, np.uint8) image = cv2.imdecode(nparr, cv2.IMREAD_COLOR) #image = cv2.imread("/home/naresh/crop.jpeg",0) height, width,channel = image.shape # left = bound_coordinate(coord[0] , width) # top = bound_coordinate(coord[1],height ) # right = bound_coordinate(coord[2] ,width) # bottom = bound_coordinate(coord[3], height) # region_width = abs(right-left) # region_height = abs(bottom-top) # if left==right==top==bottom==0 or region_width==0 or region_height==0: # return "" crop_image = get_image_from_box(image, coord, height=abs(coord[0,1]-coord[2,1])) #crop_image = image[ top:bottom, left:right] #crop_image_cv = image[ coord[0,1]:coord[2,1], coord[0,0]:coord[1,0]] save_path = save_base_path+"/"+"_psm_pers"+str(psm_val)+"--"+str(uuid.uuid4()) + '.jpg' if crop_save: cv2.imwrite(save_path,crop_image) #if abs(bottom-top) > 3*mode_height: #print(LANG_MAPPING[language][0]) if abs(coord[1,1]-coord[2,1])>mode_height: #text = pytesseract.image_to_string(crop_image,config='--psm 6', lang=LANG_MAPPING[language][1]) dfs = pytesseract.image_to_data(crop_image,config='--psm 6', lang=LANG_MAPPING[language][0],output_type=Output.DATAFRAME) #text,conf_dict = process_dfs(dfs) text,conf_dict = process_dfs_updated(dfs,language,6,crop_image) else: #text = pytesseract.image_to_string(crop_image,config='--psm '+str(psm_val), lang=LANG_MAPPING[language][1]) dfs = pytesseract.image_to_data(crop_image,config='--psm '+str(psm_val), lang=LANG_MAPPING[language][0],output_type=Output.DATAFRAME) #text,conf_dict = process_dfs(dfs) text,conf_dict = process_dfs_updated(dfs,language,psm_val,crop_image) return text,conf_dict #except: #print("xxxxxxxxxxxxxxxxxxxxxxxxxx",coord) #print([0.0]) #return "",[0.0] def merger_text(line): text = "" word_count=0 for word_idx, word in enumerate(line['regions']): if "text" in word.keys() and word["text"].replace(" ", "") != "": text = text+" "+ word["text"] word_count=word_count+1 return text, word_count def get_coord(bbox): temp_box = [] temp_box_cv = [] temp_box.append([bbox["boundingBox"]['vertices'][0]['x'],bbox["boundingBox"]['vertices'][0]['y']]) temp_box.append([bbox["boundingBox"]['vertices'][1]['x'],bbox["boundingBox"]['vertices'][1]['y']]) temp_box.append([bbox["boundingBox"]['vertices'][2]['x'],bbox["boundingBox"]['vertices'][2]['y']]) temp_box.append([bbox["boundingBox"]['vertices'][3]['x'],bbox["boundingBox"]['vertices'][3]['y']]) temp_box_cv.append(bbox["boundingBox"]['vertices'][0]['x']) temp_box_cv.append(bbox["boundingBox"]['vertices'][0]['y']) temp_box_cv.append(bbox["boundingBox"]['vertices'][2]['x']) temp_box_cv.append(bbox["boundingBox"]['vertices'][2]['y']) temp_box = np.array(temp_box) return temp_box,temp_box_cv def frequent_height(page_info): text_height = [] if len(page_info) > 0 : for idx, level in enumerate(page_info): coord_crop,coord = get_coord(level) if len(coord)!=0: text_height.append(abs(coord[3]-coord[1])) occurence_count = Counter(text_height) return occurence_count.most_common(1)[0][0] else : return 0 def remove_space(a): return a.replace(" ", "") def seq_matcher(tgt_text,gt_text): tgt_text = remove_space(tgt_text) gt_text = remove_space(gt_text) score = SequenceMatcher(None, gt_text, tgt_text).ratio() mismatch_count = levenshtein(tgt_text, gt_text) match_count = abs(len(gt_text)-mismatch_count) score = match_count/len(gt_text) # matchs = list(SequenceMatcher(None, gt_text, tgt_text).get_matching_blocks()) # match_count=0 ## match_lis = [] # for match in matchs: # match_count = match_count + match.size message = {"ground":True,"input":True} if score==0.0: if len(gt_text)>0 and len(tgt_text)==0: message['input'] = "text missing in tesseract" if len(gt_text)==0 and len(tgt_text)>0: message['ground'] = "text missing in google vision" if score==1.0 and len(gt_text)==0 and len(tgt_text)==0: message['ground'] = "text missing in google vision" message['input'] = "text missing in tesseract" return score,message,match_count def count_mismatch_char(gt ,tgt) : count=0 gt_count = len(gt) for i,j in zip(gt,tgt): if i==j: count=count+1 mismatch_char = abs(gt_count-count) return mismatch_char def correct_region(region): box = region['boundingBox']['vertices'] tmp=0 region['boundingBox']= {'vertices' : [{'x':box[0]['x']-crop_factor,'y':box[0]['y']-crop_factor_y},\ {'x':box[1]['x']+crop_factor+tmp,'y':box[1]['y']-crop_factor_y},\ {'x':box[2]['x']+crop_factor+tmp,'y':box[2]['y']+crop_factor_y},\ {'x':box[3]['x']-crop_factor,'y': box[3]['y']+crop_factor_y}]} return region def sort_line(line): line['regions'].sort(key=lambda x: x['boundingBox']['vertices'][0]['x'],reverse=False) return line def cell_ocr_word(lang, page_path, line,save_base_path,mode_height): cell_text ="" conf_dicts=[] #updated_lines = horzontal_merging(line['regions']) dynamic_line = coord_adjustment(page_path,line['regions'] ,save_base_path) for word_idx, word in enumerate(dynamic_line): word = correct_region(word) coord_crop, coord = get_coord(word) if len(coord)!=0 and abs(coord_crop[1,1]-coord_crop[2,1]) > REJECT_FILTER : text,conf_dict = get_text(page_path, coord_crop, lang,mode_height,save_base_path,8) cell_text = cell_text +" " +text conf_dicts.extend(conf_dict) return cell_text,conf_dicts def cell_text_ocr(lang, page_path, line,save_base_path,mode_height): cell_text ="" cell_regions = [] #updated_lines = horzontal_merging(line['regions']) for word_idx, word in enumerate(line['regions']): word = correct_region(word) coord_crop, coord = get_coord(word) if len(coord)!=0 and abs(coord_crop[1,1]-coord_crop[2,1]) > REJECT_FILTER : text,conf_dict = get_text(page_path, coord_crop, lang,mode_height,save_base_path,8) cell_text = cell_text +" " +text return cell_text def cell_ocr(lang, page_path, line,save_base_path,mode_height,psm): text ="" cell_google_text = "" conf_dicts = [] updated_lines = horzontal_merging(line['regions']) dynamic_line = coord_adjustment(page_path,updated_lines ,save_base_path) for updated_line in dynamic_line: line_text = updated_line['text'] cell_google_text= cell_google_text + " "+line_text corrected_line = correct_region(updated_line) coord_crop, coord = get_coord(corrected_line) if len(coord)!=0 and abs(coord_crop[1,1]-coord_crop[2,1]) > REJECT_FILTER : tess_text,conf_dict = get_text(page_path, coord_crop, lang,mode_height,save_base_path,psm) text = text + " " + tess_text conf_dicts.extend(conf_dict) return cell_google_text,text,conf_dicts def text_extraction(df,lang, page_path, regions,save_base_path): final_score = 0 total_words = 0 total_lines = 0 total_chars = 0 total_match_chars = 0 for idx, level in enumerate(regions): mode_height = frequent_height(level['regions']) if ocr_level=="WORD": for line_idx, line in enumerate(level['regions']): #word_regions = coord_adjustment(page_path, line['regions'],save_base_path) for word_idx, word in enumerate(line['regions']): word = correct_region(word) coord_crop, coord = get_coord(word) word_text = word['text'] if len(word_text)>0 and len(coord)!=0 and abs(coord_crop[1,1]-coord_crop[2,1]) > REJECT_FILTER : text,conf_dict = get_text(page_path, coord_crop, lang,mode_height,save_base_path,8) if text_processing: text_list = text.split() text = " ".join(text_list) score,message,match_count = seq_matcher(text,word['text']) final_score = final_score+score total_words = total_words+1 total_chars = total_chars+len(remove_space(word['text'])) total_match_chars= total_match_chars+match_count word['char_match'] = match_count word['tess_text'] = text word['conf_dict'] = conf_dict word['score'] = score word['message'] = message columns = word.keys() df2 = pd.DataFrame([word],columns=columns) df = df.append(df2, ignore_index=True) elif len(word_text)>0: score,message,match_count = seq_matcher("",word['text']) word['char_match'] = match_count word['tess_text'] = " " word['conf_dict'] = None word['score'] = score word['message'] = message columns = word.keys() df2 = pd.DataFrame([word],columns=columns) df = df.append(df2, ignore_index=True) if ocr_level=="LINE": lines_adjusted = coord_adjustment(page_path, level['regions'],save_base_path) for line_idx, line_org in enumerate(lines_adjusted): line_sorted = copy.deepcopy(sort_line(line_org)) line_text,total_word = merger_text(line_sorted) line = copy.deepcopy(correct_region(line_sorted)) psm = 7 if total_word<2: #print(line_text) psm=8 coord_crop, coord = get_coord(line) print("line text",line_text) if len(remove_space(line_text))>0 and len(coord)!=0 and abs(coord_crop[1,1]-coord_crop[2,1]) > REJECT_FILTER : if 'class' in line.keys() and line['class']=="CELL": line_text,text,conf_dict = cell_ocr(lang, page_path, line,save_base_path,mode_height,psm) elif 'class' in line.keys() and line['class']=="CELL_TEXT": text,conf_dict = cell_ocr_word(lang, page_path, line,save_base_path,mode_height) else: text,conf_dict = get_text(page_path, coord_crop, lang,mode_height,save_base_path,psm) if text_processing: text_list = text.split() text = " ".join(text_list) score,message,match_count = seq_matcher(text,line_text) #if score < 1.0: #text, conf_dict,score = check_psm(page_path,coord_crop,lang,mode_height,save_base_path,psm,score,text,line_text,conf_dict) final_score = final_score+score total_lines = total_lines+1 total_chars = total_chars+len(remove_space(line_text)) total_match_chars= total_match_chars+match_count line['char_match'] = match_count line['tess_text'] = text line['text'] = line_text line['conf_dict'] = conf_dict line['score'] = score line['message'] = message columns = line.keys() df2 = pd.DataFrame([line],columns=columns) df = df.append(df2, ignore_index=True) elif len(remove_space(line_text))>0: score,message,match_count = seq_matcher("",line_text) line['char_match'] = match_count line['tess_text'] = " " line['conf_dict'] = None line['text'] = line_text line['score'] = score line['message'] = message columns = line.keys() df2 = pd.DataFrame([line],columns=columns) df = df.append(df2, ignore_index=True) #return regions,final_score/total_words,df,total_chars,total_match_chars return regions,final_score/total_lines,df,total_chars,total_match_chars json_files_path = glob.glob(output_path+"/*/gv.json") def tesseract(json_files): output = [] dfs =[] for json_file in json_files: file_name = json_file.split('/')[-1].split('.json')[0] pdf_name = json_file.split('/')[-2] print("file name--------------------->>>>>>>>>>>>>>>>>>",pdf_name) if not os.path.exists(base_path+pdf_name): os.mkdir(base_path+pdf_name) save_base_path = base_path+pdf_name with open(json_file,'r+') as f: data = json.load(f) columns = ["page_path","page_data","file_eval_info"] final_df = pd.DataFrame(columns=columns) Draw(data,save_base_path,regions='regions') lang = data['outputs'][0]['config']['OCR']['language'] total_page = len(data['outputs'][0]['pages']) file_score = 0; total_chars_file = 0 file_data = []; total_match_chars_file = 0 page_paths = [] page_data_counts = [] for idx,page_data in enumerate(data['outputs'][0]['pages']): t1 = time.time() print("processing started for page no. ",idx) page_path = page_data['path'] regions = page_data['regions'][1:] df = pd.DataFrame() regions,score,df,total_chars,total_match_chars = text_extraction(df,lang, page_path, regions,save_base_path) file_score = file_score + score total_chars_file =total_chars_file +total_chars total_match_chars_file = total_match_chars_file+total_match_chars file_data.append(df.to_csv()) page_paths.append(page_path) char_details = {"total_chars":total_chars,"total_match_chars":total_match_chars} page_data_counts.append(char_details) data['outputs'][0]['pages'][idx]["regions"][1:] = copy.deepcopy(regions) t2 = t1+time.time() print("processing completed for page in {}".format(t2)) file_eval_info = {"total_chars":total_chars_file,"total_match_chars":total_match_chars_file,"score":total_match_chars_file/total_chars_file} print(file_eval_info) final_df["page_path"] = page_paths final_df["page_data"] = file_data final_df["file_eval_info"] = [file_eval_info]*len(page_paths) print("file level evaluation result------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>",file_eval_info) data['outputs'][0]['score'] = file_score/total_page with open(save_base_path+"/"+file_name+".json", 'w') as outfile: json.dump(data, outfile) final_df.to_csv(save_base_path+"/"+file_name+'.csv') return output,final_df output,dfs = tesseract(json_files_path) def draw_thresh_box(df,path,page_index,save_path): path = path.split('upload')[1] image = download_file(download_url,headers,path,f_type='image') nparr = np.frombuffer(image, np.uint8) image = cv2.imdecode(nparr, cv2.IMREAD_COLOR) font = cv2.FONT_HERSHEY_SIMPLEX color= (255,0,0);thickness=5 df =df.reset_index() for row in df.iterrows(): row2 = row[1].to_dict() boxes = row2['boundingBox'] boxes2 = ast.literal_eval(boxes) ground = boxes2['vertices'] pts = [] for pt in ground: pts.append([int(pt['x']) ,int(pt['y'])]) cv2.polylines(image, [np.array(pts)],True, color, thickness) cv2.putText(image, str(row2['text']), (pts[0][0],pts[0][1]), font, 2, (0,0,255), 2, cv2.LINE_AA) cv2.putText(image, str(row2['tess_text']), (pts[1][0],pts[1][1]), font, 2, (0,255,0), 2, cv2.LINE_AA) image_path = os.path.join(save_path , '{}.png'.format(page_index)) cv2.imwrite(image_path , image) def visualize_results(df_paths,thresh): for df_path in glob.glob(df_paths+"*/*.csv"): save_path = base_path + df_path.split('/')[-2]+"/" df = pd.read_csv(df_path) for idx,(page_path,page_data) in enumerate(zip(df['page_path'],df['page_data'])): df_string = StringIO(page_data) page_df = pd.read_csv(df_string, sep=",") filtered_df = page_df[page_df['score']<thresh] draw_thresh_box(filtered_df,page_path,idx,save_path) visualize_results(base_path,vis_thresh)
for page_index in range(len(self.get_page_count())) : nparr = np.frombuffer(self.get_page(page_index), np.uint8) image = cv2.imdecode(nparr, cv2.IMREAD_COLOR) font = cv2.FONT_HERSHEY_SIMPLEX fontScale = 2 # Blue color in BGR color = (0 ,255,0) # Line thickness of 2 px thickness = 3 # Using cv2.putText() method for region_index,region in enumerate(self.get_coords(page_index)) : try: ground = region['boundingBox']['vertices'] pts = [] for pt in ground: pts.append([int(pt['x']) ,int(pt['y'])]) #print(pts) region_color = (0,0,255) cv2.polylines(image, [np.array(pts)],True, region_color, self.thickness) for line_index, line in enumerate(region['regions']): ground = line['boundingBox']['vertices'] pts = [] for pt in ground: pts.append([int(pt['x'])-1 ,int(pt['y']) -1 ]) line_color = (255,0,0) cv2.polylines(image, [np.array(pts)],True, line_color, self.thickness -2) cv2.putText(image, str(line_index), (pts[0][0],pts[0][1]), font, fontScale, (255,0,0), thickness, cv2.LINE_AA) for word_index, word in enumerate(line['regions']): ground = word['boundingBox']['vertices'] pts = [] for pt in ground: pts.append([int(pt['x']) -3,int(pt['y'])-3]) word_color = (0,255,0) cv2.polylines(image, [np.array(pts)],True, word_color, self.thickness -2) cv2.putText(image, str(word_index), (pts[0][0],pts[0][1]), font, fontScale-1,(0,255,0), thickness, cv2.LINE_AA) except Exception as e: print(str(e)) print(region) #print(self.prefix) image_path = os.path.join(self.save_dir , '{}_{}_{}.png'.format(self.prefix,self.regions,page_index)) cv2.imwrite(image_path , image)
common.rs
use hyper::header::HeaderValue; use hyper::{header, Body, Response, StatusCode}; use ini::Ini; use log::*; use serde_json::{json, Map, Value}; use std::collections::HashMap; use std::fmt::Debug; use std::path::Path; use std::process; /* * Constants and static variables */ pub const STUB_VTPM: bool = false; pub const STUB_IMA: bool = true; pub const TPM_DATA_PCR: usize = 16; pub const IMA_PCR: usize = 10; pub static RSA_PUBLICKEY_EXPORTABLE: &'static str = "rsa placeholder"; pub static TPM_TOOLS_PATH: &'static str = "/usr/local/bin/"; pub static IMA_ML_STUB: &'static str = "../scripts/ima/ascii_runtime_measurements"; pub static IMA_ML: &'static str = "/sys/kernel/security/ima/ascii_runtime_measurements"; pub static KEY: &'static str = "secret"; pub static WORK_DIR: &'static str = "/tmp"; // Secure mount of tpmfs (False is generally used for development environments) pub static MOUNT_SECURE: bool = true; /* * Input: config file location (e.g. /etc/keylime.conf), [section] and key * Return: Returns the matched key * * Example call: * let port = common::config_get("/etc/keylime.conf""general","cloudagent_port"); */ pub fn config_get(conf_name: &str, section: &str, key: &str) -> String { let conf = match Ini::load_from_file(conf_name) { Ok(conf) => conf, Err(_error) => { error!("Error: unable to read config file: {} ", conf_name); process::exit(1); } }; let section = match conf.section(Some(section.to_owned())) { Some(section) => section, None => { error!( "Cannot find section called {} within file {}", section, conf_name ); process::exit(1) } }; let value = match section.get(key) { Some(value) => value, None => { error!("Cannot find key value {} within file {}", key, conf_name); process::exit(1) } }; return value.clone(); } /* * Input: Response status code * Response result status * Json output content * * Return: HTTP Respnose struct * * convert the input into HTTP Response struct with json output formatting. * Follow original python-keylime echo_json_response() output structure. But * there are two difference between this response json content and the * original echo_json_response() response json content. * 1. The serde_json crate sorts keys in alphebetic order, which is * different than the python version response structure. * 2. There is no space in the json content, but python version response * content contains white space in between keys. */ pub fn set_response_content( code: i32, status: &str, results: Map<String, Value>, response: &mut Response<Body>, ) -> Result<(), Box<i32>> { let integerated_result = json!({ "status": status, "code": code, "results": results, }); match serde_json::to_string(&integerated_result) { Ok(s) => { // Dereferencing apply here because it needs to derefer the variable // so it can assign the new value to it. But changing the headers // doesn't require dereference is because that it uses the returned // header reference and update it instead of changing it, so no // dereference is needed in this case. *response.body_mut() = s.into(); response.headers_mut().insert( header::CONTENT_TYPE, HeaderValue::from_static("application/json"), ); Ok(()) } Err(e) => { error!("Failed to convert Json to string for Response body, error {}.", e); Err(Box::new(-1)) } } } /* * Input: URL string * * Ouput: Map contains the request type and content in the request * * Convert a api resquest path to a map that contains the key and value, which * are the requested function and content given in pair from the original url. * Same implementation as the original python version get_resrful_parameters() * function. */ pub fn get_restful_parameters(urlstring: &str) -> HashMap<&str, &str> { let mut parameters = HashMap::new(); let list: Vec<&str> = urlstring.split('/').collect(); // error hanlding, empty url if list.len() <= 0 { return parameters; } // capture the version number let (_, right) = list[1].split_at(1); parameters.insert("api_version", right); // starting from the second element, which is the first requested function for x in 2..(list.len() - 1) { parameters.insert(list[x], list[x + 1]); } parameters } /* * Input: path directory to be changed owner to root * Return: Result contains execution result * - directory name for successful execution * - -1 code for failure execution. * * If privilege requirement is met, change the owner of the path to root * This function is unsafely using libc. Result is returned indicating * execution result. */ pub fn chownroot(path: String) -> Result<String, i32> { unsafe { // check privilege if libc::geteuid() != 0 { error!("Privilege level unable to change ownership to root for file: {}", path); return Err(-1); } // change directory owner to root if libc::chown(path.as_bytes().as_ptr() as *const i8, 0, 0) != 0 { error!("Failed to change file {} owner.", path); return Err(-1); } info!("Changed file {} owner to root.", path); Ok(path) } } /* * Input: error message * Error (Option) * Return: integrated error message string * * A error message helper funciton to integrate error message with error * information. Integrate the error message and error into a single error * message string. Error could be None. Message is return as a Err<> for * error handling Result<>. */ pub fn emsg<T, E>(message: &str, error: Option<T>) -> Result<E, Box<String>> where T: Debug, { match error { Some(e) => Err(Box::new(format!("{} Error, {:?}.", message, e))), None => Err(Box::new(message.to_string())), } } // Unit Testing #[cfg(test)]
use super::*; // Test the get_restful_parameters function with a given sampel url #[test] fn test_get_restful_parameters() { let mut map = HashMap::new(); map.insert("verify", "pubkey"); map.insert("api_version", "2"); // Map content "{"api_version": "v2", "verify": "pubkey"}" assert_eq!( get_restful_parameters("127.0.0.1:1337/v2/verify/pubkey"), map ); } #[test] fn test_set_response_content() { let mut my_res: Response<Body> = Response::new("nothing".into()); assert!( set_response_content(0, "Ok", Map::new(), &mut my_res).is_ok() ); } #[test] fn test_config_get_parameters_exist() { let result = config_get("keylime.conf", "general", "cloudagent_port"); assert_eq!(result, "9002"); } }
mod tests {
transaction-selectaddress.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { IonicModule } from '@ionic/angular'; import { TransactionSelectaddressPageRoutingModule } from './transaction-selectaddress-routing.module'; import { TransactionSelectaddressPage } from './transaction-selectaddress.page'; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, TransactionSelectaddressPageRoutingModule ], declarations: [TransactionSelectaddressPage] }) export class
{}
TransactionSelectaddressPageModule
utils.ts
import { Injectable, PLATFORM_ID, Inject } from '@angular/core'; import { isPlatformBrowser } from '@angular/common'; import { Observable } from 'rxjs'; import ResizeObserver from 'resize-observer-polyfill'; /** *@hidden */ export function cloneArray(array: any[], deep?: boolean) { const arr = []; if (!array) { return arr; } let i = array.length; while (i--) { arr[i] = deep ? cloneValue(array[i]) : array[i]; } return arr; } /** * Doesn't clone leaf items * @hidden */ export function cloneHierarchicalArray(array: any[], childDataKey: any): any[] { const result: any[] = []; if (!array) { return result; } for (const item of array) { const clonedItem = cloneValue(item); if (Array.isArray(item[childDataKey])) { clonedItem[childDataKey] = cloneHierarchicalArray(clonedItem[childDataKey], childDataKey); } result.push(clonedItem); } return result; } /** * Deep clones all first level keys of Obj2 and merges them to Obj1 * @param obj1 Object to merge into * @param obj2 Object to merge from * @returns Obj1 with merged cloned keys from Obj2 * @hidden */ export function mergeObjects(obj1: {}, obj2: {}): any { if (!isObject(obj1)) { throw new Error(`Cannot merge into ${obj1}. First param must be an object.`); } if (!isObject(obj2)) { return obj1; } for (const key of Object.keys(obj2)) { obj1[key] = cloneValue(obj2[key]); } return obj1; } /** * Creates deep clone of provided value. * Supports primitive values, dates and objects. * If passed value is array returns shallow copy of the array. * @param value value to clone * @returns Deep copy of provided value *@hidden */ export function cloneValue(value: any): any { if (isDate(value)) { return new Date(value.getTime()); } if (Array.isArray(value)) { return [...value]; } if (value instanceof Map || value instanceof Set) { return value; } if (isObject(value)) { const result = {}; for (const key of Object.keys(value)) { result[key] = cloneValue(value[key]); } return result; } return value; } /** * Checks if provided variable is Object * @param value Value to check * @returns true if provided variable is Object *@hidden */ export function isObject(value: any): boolean { return value && value.toString() === '[object Object]'; } /** * Checks if provided variable is Date * @param value Value to check * @returns true if provided variable is Date *@hidden */ export function
(value: any) { return Object.prototype.toString.call(value) === '[object Date]'; } /** * Checks if the two passed arguments are equal * Currently supports date objects * @param obj1 * @param obj2 * @returns: `boolean` * @hidden */ export function isEqual(obj1, obj2): boolean { if (isDate(obj1) && isDate(obj2)) { return obj1.getTime() === obj2.getTime(); } return obj1 === obj2; } /** *@hidden */ export const enum KEYCODES { ENTER = 13, SPACE = 32, ESCAPE = 27, LEFT_ARROW = 37, UP_ARROW = 38, RIGHT_ARROW = 39, DOWN_ARROW = 40, F2 = 113, TAB = 9, CTRL = 17, Z = 90, Y = 89, X = 88, BACKSPACE = 8, DELETE = 46, INPUT_METHOD = 229 } /** *@hidden */ export const enum KEYS { ENTER = 'Enter', SPACE = ' ', SPACE_IE = 'Spacebar', ESCAPE = 'Escape', ESCAPE_IE = 'Esc', LEFT_ARROW = 'ArrowLeft', LEFT_ARROW_IE = 'Left', UP_ARROW = 'ArrowUp', UP_ARROW_IE = 'Up', RIGHT_ARROW = 'ArrowRight', RIGHT_ARROW_IE = 'Right', DOWN_ARROW = 'ArrowDown', DOWN_ARROW_IE = 'Down', F2 = 'F2', TAB = 'Tab' } /** *@hidden * Returns the actual size of the node content, using Range * ```typescript * let range = document.createRange(); * let column = this.grid.columnList.filter(c => c.field === 'ID')[0]; * * let size = getNodeSizeViaRange(range, column.cells[0].nativeElement); * ``` */ export function getNodeSizeViaRange(range: Range, node: any): number { let overflow = null; if (!isFirefox()) { overflow = node.style.overflow; // we need that hack - otherwise content won't be measured correctly in IE/Edge node.style.overflow = 'visible'; } range.selectNodeContents(node); const width = range.getBoundingClientRect().width; if (!isFirefox()) { // we need that hack - otherwise content won't be measured correctly in IE/Edge node.style.overflow = overflow; } return width; } /** *@hidden * Returns the actual size of the node content, using Canvas * ```typescript * let ctx = document.createElement('canvas').getContext('2d'); * let column = this.grid.columnList.filter(c => c.field === 'ID')[0]; * * let size = valToPxlsUsingCanvas(ctx, column.cells[0].nativeElement); * ``` */ export function getNodeSizeViaCanvas(canvas2dCtx: any, node: any): number { const s = this.grid.document.defaultView.getComputedStyle(node); // need to set the font to get correct width canvas2dCtx.font = s.fontSize + ' ' + s.fontFamily; return canvas2dCtx.measureText(node.textContent).width; } /** *@hidden */ export function isIE(): boolean { return navigator.appVersion.indexOf('Trident/') > 0; } /** *@hidden */ export function isEdge(): boolean { const edgeBrowser = /Edge[\/\s](\d+\.\d+)/.test(navigator.userAgent); return edgeBrowser; } /** *@hidden */ export function isFirefox(): boolean { const firefoxBrowser = /Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent); return firefoxBrowser; } /** * @hidden */ @Injectable({ providedIn: 'root' }) export class PlatformUtil { public isBrowser: boolean = isPlatformBrowser(this.platformId); public isIOS = this.isBrowser && /iPad|iPhone|iPod/.test(navigator.userAgent) && !('MSStream' in window); constructor(@Inject(PLATFORM_ID) private platformId: Object) { } } /** * @hidden */ export function isLeftClick(event: PointerEvent) { return event.button === 0; } /** @hidden */ export function isNavigationKey(key: string): boolean { return [ 'down', 'up', 'left', 'right', 'arrowdown', 'arrowup', 'arrowleft', 'arrowright', 'home', 'end', 'space', 'spacebar', ' ' ].indexOf(key) !== -1; } /** *@hidden */ export function flatten(arr: any[]) { let result = []; arr.forEach(el => { result.push(el); if (el.children) { const children = Array.isArray(el.children) ? el.children : el.children.toArray(); result = result.concat(flatten(children)); } }); return result; } export interface CancelableEventArgs { /** * Provides the ability to cancel the event. */ cancel: boolean; } export interface IBaseEventArgs { /** * Provides reference to the owner component. */ owner?: any; } export interface CancelableBrowserEventArgs extends CancelableEventArgs { /** Browser event */ event?: Event; } export const NAVIGATION_KEYS = new Set([ 'down', 'up', 'left', 'right', 'arrowdown', 'arrowup', 'arrowleft', 'arrowright', 'home', 'end', 'space', 'spacebar', ' ' ]); export const ROW_EXPAND_KEYS = new Set('right down arrowright arrowdown'.split(' ')); export const ROW_COLLAPSE_KEYS = new Set('left up arrowleft arrowup'.split(' ')); export const SUPPORTED_KEYS = new Set([...Array.from(NAVIGATION_KEYS), 'tab', 'enter', 'f2', 'escape', 'esc']); /** * @hidden * @internal * * Creates a new ResizeObserver on `target` and returns it as an Observable. * Run the resizeObservable outside angular zone, because it patches the MutationObserver which causes an infinite loop. * Related issue: https://github.com/angular/angular/issues/31712 */ export function resizeObservable(target: HTMLElement): Observable<ResizeObserverEntry[]> { return new Observable((observer) => { const instance = new ResizeObserver((entries: ResizeObserverEntry[]) => { observer.next(entries); }); instance.observe(target); const unsubscribe = () => instance.disconnect(); return unsubscribe; }); }
isDate
inputmask.date.extensions.js
/*! * inputmask.date.extensions.js * https://github.com/RobinHerbots/Inputmask * Copyright (c) 2010 - 2017 Robin Herbots * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) * Version: 3.3.11 */ !function (factory) { "function" == typeof define && define.amd ? define(["./dependencyLibs/inputmask.dependencyLib", "./inputmask"], factory) : "object" == typeof exports ? module.exports = factory(require("./dependencyLibs/inputmask.dependencyLib"), require("./inputmask")) : factory(window.dependencyLib || jQuery, window.Inputmask); }(function ($, Inputmask) { function isLeapYear(year) { return isNaN(year) || 29 === new Date(year, 2, 0).getDate(); } return Inputmask.extendAliases({ "dd/mm/yyyy": { mask: "1/2/y", placeholder: "dd/mm/yyyy", regex: { val1pre: new RegExp("[0-3]"), val1: new RegExp("0[1-9]|[12][0-9]|3[01]"), val2pre: function (separator) { var escapedSeparator = Inputmask.escapeRegex.call(this, separator); return new RegExp("((0[1-9]|[12][0-9]|3[01])" + escapedSeparator + "[01])"); }, val2: function (separator) { var escapedSeparator = Inputmask.escapeRegex.call(this, separator); return new RegExp("((0[1-9]|[12][0-9])" + escapedSeparator + "(0[1-9]|1[012]))|(30" + escapedSeparator + "(0[13-9]|1[012]))|(31" + escapedSeparator + "(0[13578]|1[02]))"); } }, leapday: "29/02/", separator: "/", yearrange: { minyear: 1900, maxyear: 2099 }, isInYearRange: function (chrs, minyear, maxyear) { if (isNaN(chrs)) return !1; var enteredyear = parseInt(chrs.concat(minyear.toString().slice(chrs.length))), enteredyear2 = parseInt(chrs.concat(maxyear.toString().slice(chrs.length))); return !isNaN(enteredyear) && (minyear <= enteredyear && enteredyear <= maxyear) || !isNaN(enteredyear2) && (minyear <= enteredyear2 && enteredyear2 <= maxyear); }, determinebaseyear: function (minyear, maxyear, hint) { var currentyear = new Date().getFullYear(); if (minyear > currentyear) return minyear; if (maxyear < currentyear) { for (var maxYearPrefix = maxyear.toString().slice(0, 2), maxYearPostfix = maxyear.toString().slice(2, 4); maxyear < maxYearPrefix + hint;) maxYearPrefix--; var maxxYear = maxYearPrefix + maxYearPostfix; return minyear > maxxYear ? minyear : maxxYear; } if (minyear <= currentyear && currentyear <= maxyear) { for (var currentYearPrefix = currentyear.toString().slice(0, 2); maxyear < currentYearPrefix + hint;) currentYearPrefix--; var currentYearAndHint = currentYearPrefix + hint; return currentYearAndHint < minyear ? minyear : currentYearAndHint; } return currentyear; }, onKeyDown: function (e, buffer, caretPos, opts) { var $input = $(this); if (e.ctrlKey && e.keyCode === Inputmask.keyCode.RIGHT) { var today = new Date(); $input.val(today.getDate().toString() + (today.getMonth() + 1).toString() + today.getFullYear().toString()), $input.trigger("setvalue"); } }, getFrontValue: function (mask, buffer, opts) { for (var start = 0, length = 0, i = 0; i < mask.length && "2" !== mask.charAt(i); i++) { var definition = opts.definitions[mask.charAt(i)]; definition ? (start += length, length = definition.cardinality) : length++; } return buffer.join("").substr(start, length); }, postValidation: function (buffer, currentResult, opts) { var dayMonthValue, year, bufferStr = buffer.join(""); return 0 === opts.mask.indexOf("y") ? (year = bufferStr.substr(0, 4), dayMonthValue = bufferStr.substring(4, 10)) : (year = bufferStr.substring(6, 10), dayMonthValue = bufferStr.substr(0, 6)), currentResult && (dayMonthValue !== opts.leapday || isLeapYear(year)); }, definitions: { "1": { validator: function (chrs, maskset, pos, strict, opts) { var isValid = opts.regex.val1.test(chrs); return strict || isValid || chrs.charAt(1) !== opts.separator && -1 === "-./".indexOf(chrs.charAt(1)) || !(isValid = opts.regex.val1.test("0" + chrs.charAt(0))) ? isValid : (maskset.buffer[pos - 1] = "0", { refreshFromBuffer: { start: pos - 1, end: pos }, pos: pos, c: chrs.charAt(0) }); }, cardinality: 2, prevalidator: [{ validator: function (chrs, maskset, pos, strict, opts) { var pchrs = chrs; isNaN(maskset.buffer[pos + 1]) || (pchrs += maskset.buffer[pos + 1]); var isValid = 1 === pchrs.length ? opts.regex.val1pre.test(pchrs) : opts.regex.val1.test(pchrs); if (isValid && maskset.validPositions[pos] && (opts.regex.val2(opts.separator).test(chrs + maskset.validPositions[pos].input) || (maskset.validPositions[pos].input = "0" === chrs ? "1" : "0")), !strict && !isValid) { if (isValid = opts.regex.val1.test(chrs + "0")) return maskset.buffer[pos] = chrs, maskset.buffer[++pos] = "0", { pos: pos, c: "0" }; if (isValid = opts.regex.val1.test("0" + chrs)) return maskset.buffer[pos] = "0", pos++, { pos: pos }; } return isValid; }, cardinality: 1 }] }, "2": { validator: function (chrs, maskset, pos, strict, opts) { var frontValue = opts.getFrontValue(maskset.mask, maskset.buffer, opts); -1 !== frontValue.indexOf(opts.placeholder[0]) && (frontValue = "01" + opts.separator); var isValid = opts.regex.val2(opts.separator).test(frontValue + chrs); return strict || isValid || chrs.charAt(1) !== opts.separator && -1 === "-./".indexOf(chrs.charAt(1)) || !(isValid = opts.regex.val2(opts.separator).test(frontValue + "0" + chrs.charAt(0))) ? isValid : (maskset.buffer[pos - 1] = "0", { refreshFromBuffer: { start: pos - 1, end: pos }, pos: pos, c: chrs.charAt(0) }); }, cardinality: 2, prevalidator: [{ validator: function (chrs, maskset, pos, strict, opts) { isNaN(maskset.buffer[pos + 1]) || (chrs += maskset.buffer[pos + 1]); var frontValue = opts.getFrontValue(maskset.mask, maskset.buffer, opts); -1 !== frontValue.indexOf(opts.placeholder[0]) && (frontValue = "01" + opts.separator); var isValid = 1 === chrs.length ? opts.regex.val2pre(opts.separator).test(frontValue + chrs) : opts.regex.val2(opts.separator).test(frontValue + chrs); return isValid && maskset.validPositions[pos] && (opts.regex.val2(opts.separator).test(chrs + maskset.validPositions[pos].input) || (maskset.validPositions[pos].input = "0" === chrs ? "1" : "0")), strict || isValid || !(isValid = opts.regex.val2(opts.separator).test(frontValue + "0" + chrs)) ? isValid : (maskset.buffer[pos] = "0", pos++, { pos: pos }); }, cardinality: 1 }] }, y: { validator: function (chrs, maskset, pos, strict, opts) { return opts.isInYearRange(chrs, opts.yearrange.minyear, opts.yearrange.maxyear); }, cardinality: 4, prevalidator: [{ validator: function (chrs, maskset, pos, strict, opts) { var isValid = opts.isInYearRange(chrs, opts.yearrange.minyear, opts.yearrange.maxyear); if (!strict && !isValid) { var yearPrefix = opts.determinebaseyear(opts.yearrange.minyear, opts.yearrange.maxyear, chrs + "0").toString().slice(0, 1); if (isValid = opts.isInYearRange(yearPrefix + chrs, opts.yearrange.minyear, opts.yearrange.maxyear)) return maskset.buffer[pos++] = yearPrefix.charAt(0), { pos: pos }; if (yearPrefix = opts.determinebaseyear(opts.yearrange.minyear, opts.yearrange.maxyear, chrs + "0").toString().slice(0, 2), isValid = opts.isInYearRange(yearPrefix + chrs, opts.yearrange.minyear, opts.yearrange.maxyear)) return maskset.buffer[pos++] = yearPrefix.charAt(0), maskset.buffer[pos++] = yearPrefix.charAt(1), { pos: pos }; } return isValid; }, cardinality: 1 }, { validator: function (chrs, maskset, pos, strict, opts) { var isValid = opts.isInYearRange(chrs, opts.yearrange.minyear, opts.yearrange.maxyear); if (!strict && !isValid) { var yearPrefix = opts.determinebaseyear(opts.yearrange.minyear, opts.yearrange.maxyear, chrs).toString().slice(0, 2); if (isValid = opts.isInYearRange(chrs[0] + yearPrefix[1] + chrs[1], opts.yearrange.minyear, opts.yearrange.maxyear)) return maskset.buffer[pos++] = yearPrefix.charAt(1), { pos: pos }; if (yearPrefix = opts.determinebaseyear(opts.yearrange.minyear, opts.yearrange.maxyear, chrs).toString().slice(0, 2), isValid = opts.isInYearRange(yearPrefix + chrs, opts.yearrange.minyear, opts.yearrange.maxyear)) return maskset.buffer[pos - 1] = yearPrefix.charAt(0), maskset.buffer[pos++] = yearPrefix.charAt(1), maskset.buffer[pos++] = chrs.charAt(0), { refreshFromBuffer: { start: pos - 3, end: pos }, pos: pos }; } return isValid; }, cardinality: 2 }, { validator: function (chrs, maskset, pos, strict, opts) { return opts.isInYearRange(chrs, opts.yearrange.minyear, opts.yearrange.maxyear); }, cardinality: 3 }] } }, insertMode: !1, autoUnmask: !1 }, "mm/dd/yyyy": { placeholder: "mm/dd/yyyy", alias: "dd/mm/yyyy", regex: { val2pre: function (separator) { var escapedSeparator = Inputmask.escapeRegex.call(this, separator); return new RegExp("((0[13-9]|1[012])" + escapedSeparator + "[0-3])|(02" + escapedSeparator + "[0-2])"); }, val2: function (separator) { var escapedSeparator = Inputmask.escapeRegex.call(this, separator); return new RegExp("((0[1-9]|1[012])" + escapedSeparator + "(0[1-9]|[12][0-9]))|((0[13-9]|1[012])" + escapedSeparator + "30)|((0[13578]|1[02])" + escapedSeparator + "31)"); }, val1pre: new RegExp("[01]"), val1: new RegExp("0[1-9]|1[012]") }, leapday: "02/29/", onKeyDown: function (e, buffer, caretPos, opts) { var $input = $(this); if (e.ctrlKey && e.keyCode === Inputmask.keyCode.RIGHT) { var today = new Date(); $input.val((today.getMonth() + 1).toString() + today.getDate().toString() + today.getFullYear().toString()), $input.trigger("setvalue"); } } }, "yyyy/mm/dd": { mask: "y/1/2", placeholder: "yyyy/mm/dd", alias: "mm/dd/yyyy", leapday: "/02/29", onKeyDown: function (e, buffer, caretPos, opts) { var $input = $(this); if (e.ctrlKey && e.keyCode === Inputmask.keyCode.RIGHT) { var today = new Date(); $input.val(today.getFullYear().toString() + (today.getMonth() + 1).toString() + today.getDate().toString()), $input.trigger("setvalue"); } } }, "dd.mm.yyyy": { mask: "1.2.y", placeholder: "dd.mm.yyyy", leapday: "29.02.", separator: ".", alias: "dd/mm/yyyy" }, "dd-mm-yyyy": { mask: "1-2-y", placeholder: "dd-mm-yyyy", leapday: "29-02-", separator: "-", alias: "dd/mm/yyyy" }, "mm.dd.yyyy": { mask: "1.2.y", placeholder: "mm.dd.yyyy", leapday: "02.29.", separator: ".", alias: "mm/dd/yyyy" }, "mm-dd-yyyy": { mask: "1-2-y", placeholder: "mm-dd-yyyy", leapday: "02-29-", separator: "-", alias: "mm/dd/yyyy" }, "yyyy.mm.dd": { mask: "y.1.2", placeholder: "yyyy.mm.dd", leapday: ".02.29", separator: ".", alias: "yyyy/mm/dd" }, "yyyy-mm-dd": { mask: "y-1-2", placeholder: "yyyy-mm-dd", leapday: "-02-29", separator: "-", alias: "yyyy/mm/dd" }, datetime: { mask: "1/2/y h:s", placeholder: "dd/mm/yyyy hh:mm", alias: "dd/mm/yyyy", regex: { hrspre: new RegExp("[012]"), hrs24: new RegExp("2[0-4]|1[3-9]"), hrs: new RegExp("[01][0-9]|2[0-4]"), ampm: new RegExp("^[a|p|A|P][m|M]"), mspre: new RegExp("[0-5]"), ms: new RegExp("[0-5][0-9]") }, timeseparator: ":", hourFormat: "24", definitions: { h: { validator: function (chrs, maskset, pos, strict, opts) { if ("24" === opts.hourFormat && 24 === parseInt(chrs, 10)) return maskset.buffer[pos - 1] = "0", maskset.buffer[pos] = "0", { refreshFromBuffer: { start: pos - 1, end: pos }, c: "0" }; var isValid = opts.regex.hrs.test(chrs); if (!strict && !isValid && (chrs.charAt(1) === opts.timeseparator || -1 !== "-.:".indexOf(chrs.charAt(1))) && (isValid = opts.regex.hrs.test("0" + chrs.charAt(0)))) return maskset.buffer[pos - 1] = "0", maskset.buffer[pos] = chrs.charAt(0), pos++, { refreshFromBuffer: { start: pos - 2, end: pos }, pos: pos, c: opts.timeseparator }; if (isValid && "24" !== opts.hourFormat && opts.regex.hrs24.test(chrs)) { var tmp = parseInt(chrs, 10); return 24 === tmp ? (maskset.buffer[pos + 5] = "a", maskset.buffer[pos + 6] = "m") : (maskset.buffer[pos + 5] = "p", maskset.buffer[pos + 6] = "m"), (tmp -= 12) < 10 ? (maskset.buffer[pos] = tmp.toString(), maskset.buffer[pos - 1] = "0") : (maskset.buffer[pos] = tmp.toString().charAt(1), maskset.buffer[pos - 1] = tmp.toString().charAt(0)), { refreshFromBuffer: { start: pos - 1, end: pos + 6 }, c: maskset.buffer[pos] }; } return isValid; }, cardinality: 2, prevalidator: [{ validator: function (chrs, maskset, pos, strict, opts) { var isValid = opts.regex.hrspre.test(chrs); return strict || isValid || !(isValid = opts.regex.hrs.test("0" + chrs)) ? isValid : (maskset.buffer[pos] = "0", pos++, { pos: pos }); }, cardinality: 1 }] }, s: { validator: "[0-5][0-9]", cardinality: 2, prevalidator: [{ validator: function (chrs, maskset, pos, strict, opts) { var isValid = opts.regex.mspre.test(chrs); return strict || isValid || !(isValid = opts.regex.ms.test("0" + chrs)) ? isValid : (maskset.buffer[pos] = "0", pos++, { pos: pos }); }, cardinality: 1 }] }, t: { validator: function (chrs, maskset, pos, strict, opts) { return opts.regex.ampm.test(chrs + "m"); }, casing: "lower", cardinality: 1 } }, insertMode: !1, autoUnmask: !1 }, datetime12: { mask: "1/2/y h:s t\\m", placeholder: "dd/mm/yyyy hh:mm xm", alias: "datetime", hourFormat: "12" }, "mm/dd/yyyy hh:mm xm": { mask: "1/2/y h:s t\\m", placeholder: "mm/dd/yyyy hh:mm xm", alias: "datetime12", regex: { val2pre: function (separator) { var escapedSeparator = Inputmask.escapeRegex.call(this, separator); return new RegExp("((0[13-9]|1[012])" + escapedSeparator + "[0-3])|(02" + escapedSeparator + "[0-2])"); }, val2: function (separator) { var escapedSeparator = Inputmask.escapeRegex.call(this, separator); return new RegExp("((0[1-9]|1[012])" + escapedSeparator + "(0[1-9]|[12][0-9]))|((0[13-9]|1[012])" + escapedSeparator + "30)|((0[13578]|1[02])" + escapedSeparator + "31)"); }, val1pre: new RegExp("[01]"), val1: new RegExp("0[1-9]|1[012]") }, leapday: "02/29/", onKeyDown: function (e, buffer, caretPos, opts) { var $input = $(this); if (e.ctrlKey && e.keyCode === Inputmask.keyCode.RIGHT) { var today = new Date(); $input.val((today.getMonth() + 1).toString() + today.getDate().toString() + today.getFullYear().toString()), $input.trigger("setvalue"); } } }, "hh:mm t": { mask: "h:s t\\m", placeholder: "hh:mm xm", alias: "datetime", hourFormat: "12" }, "h:s t": { mask: "h:s t\\m", placeholder: "hh:mm xm", alias: "datetime", hourFormat: "12" }, "hh:mm:ss": { mask: "h:s:s", placeholder: "hh:mm:ss", alias: "datetime", autoUnmask: !1 }, "hh:mm": { mask: "h:s", placeholder: "hh:mm", alias: "datetime", autoUnmask: !1 }, date: { alias: "dd/mm/yyyy" }, "mm/yyyy": { mask: "1/y", placeholder: "mm/yyyy", leapday: "donotuse", separator: "/", alias: "mm/dd/yyyy" }, shamsi: {
val2pre: function (separator) { var escapedSeparator = Inputmask.escapeRegex.call(this, separator); return new RegExp("((0[1-9]|1[012])" + escapedSeparator + "[0-3])"); }, val2: function (separator) { var escapedSeparator = Inputmask.escapeRegex.call(this, separator); return new RegExp("((0[1-9]|1[012])" + escapedSeparator + "(0[1-9]|[12][0-9]))|((0[1-9]|1[012])" + escapedSeparator + "30)|((0[1-6])" + escapedSeparator + "31)"); }, val1pre: new RegExp("[01]"), val1: new RegExp("0[1-9]|1[012]") }, yearrange: { minyear: 1300, maxyear: 1499 }, mask: "y/1/2", leapday: "/12/30", placeholder: "yyyy/mm/dd", alias: "mm/dd/yyyy", clearIncomplete: !0 }, "yyyy-mm-dd hh:mm:ss": { mask: "y-1-2 h:s:s", placeholder: "yyyy-mm-dd hh:mm:ss", alias: "datetime", separator: "-", leapday: "-02-29", regex: { val2pre: function (separator) { var escapedSeparator = Inputmask.escapeRegex.call(this, separator); return new RegExp("((0[13-9]|1[012])" + escapedSeparator + "[0-3])|(02" + escapedSeparator + "[0-2])"); }, val2: function (separator) { var escapedSeparator = Inputmask.escapeRegex.call(this, separator); return new RegExp("((0[1-9]|1[012])" + escapedSeparator + "(0[1-9]|[12][0-9]))|((0[13-9]|1[012])" + escapedSeparator + "30)|((0[13578]|1[02])" + escapedSeparator + "31)"); }, val1pre: new RegExp("[01]"), val1: new RegExp("0[1-9]|1[012]") }, onKeyDown: function (e, buffer, caretPos, opts) { } } }), Inputmask; });
regex: {
find_one_and_replace.go
// Copyright (C) MongoDB, Inc. 2017-present. // // 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 package driver import ( "context" "time" "github.com/rentiansheng/bk_bson/bson/bsoncodec" "github.com/rentiansheng/bk_bsonmongo/options" "github.com/rentiansheng/bk_bsonmongo/writeconcern" "github.com/rentiansheng/bk_bson/x/bsonx" "github.com/rentiansheng/bk_bsonx/mongo/driver/session" "github.com/rentiansheng/bk_bsonx/mongo/driver/topology" "github.com/rentiansheng/bk_bsonx/mongo/driver/uuid" "github.com/rentiansheng/bk_bsonx/network/command" "github.com/rentiansheng/bk_bsonx/network/description" "github.com/rentiansheng/bk_bsonx/network/result" ) // FindOneAndReplace handles the full cycle dispatch and execution of a FindOneAndReplace command against the provided // topology. func FindOneAndReplace( ctx context.Context, cmd command.FindOneAndReplace, topo *topology.Topology, selector description.ServerSelector, clientID uuid.UUID, pool *session.Pool, retryWrite bool, registry *bsoncodec.Registry, opts ...*options.FindOneAndReplaceOptions, ) (result.FindAndModify, error) { ss, err := topo.SelectServer(ctx, selector) if err != nil { return result.FindAndModify{}, err } // If no explicit session and deployment supports sessions, start implicit session. if cmd.Session == nil && topo.SupportsSessions() { cmd.Session, err = session.NewClientSession(pool, clientID, session.Implicit) if err != nil { return result.FindAndModify{}, err } defer cmd.Session.EndSession() } ro := options.MergeFindOneAndReplaceOptions(opts...) if ro.BypassDocumentValidation != nil { cmd.Opts = append(cmd.Opts, bsonx.Elem{"byapssDocumentValidation", bsonx.Boolean(*ro.BypassDocumentValidation)}) } if ro.Collation != nil { if ss.Description().WireVersion.Max < 5 { return result.FindAndModify{}, ErrCollation } cmd.Opts = append(cmd.Opts, bsonx.Elem{"collation", bsonx.Document(ro.Collation.ToDocument())}) } if ro.MaxTime != nil { cmd.Opts = append(cmd.Opts, bsonx.Elem{"maxTimeMS", bsonx.Int64(int64(*ro.MaxTime / time.Millisecond))}) } if ro.Projection != nil { maxElem, err := interfaceToElement("fields", ro.Projection, registry) if err != nil
cmd.Opts = append(cmd.Opts, maxElem) } if ro.ReturnDocument != nil { cmd.Opts = append(cmd.Opts, bsonx.Elem{"new", bsonx.Boolean(*ro.ReturnDocument == options.After)}) } if ro.Sort != nil { sortElem, err := interfaceToElement("sort", ro.Sort, registry) if err != nil { return result.FindAndModify{}, err } cmd.Opts = append(cmd.Opts, sortElem) } if ro.Upsert != nil { cmd.Opts = append(cmd.Opts, bsonx.Elem{"upsert", bsonx.Boolean(*ro.Upsert)}) } // Execute in a single trip if retry writes not supported, or retry not enabled if !retrySupported(topo, ss.Description(), cmd.Session, cmd.WriteConcern) || !retryWrite { if cmd.Session != nil { cmd.Session.RetryWrite = false // explicitly set to false to prevent encoding transaction number } return findOneAndReplace(ctx, cmd, ss, nil) } cmd.Session.RetryWrite = retryWrite cmd.Session.IncrementTxnNumber() res, originalErr := findOneAndReplace(ctx, cmd, ss, nil) // Retry if appropriate if cerr, ok := originalErr.(command.Error); ok && cerr.Retryable() { ss, err := topo.SelectServer(ctx, selector) // Return original error if server selection fails or new server does not support retryable writes if err != nil || !retrySupported(topo, ss.Description(), cmd.Session, cmd.WriteConcern) { return result.FindAndModify{}, originalErr } return findOneAndReplace(ctx, cmd, ss, cerr) } return res, originalErr } func findOneAndReplace( ctx context.Context, cmd command.FindOneAndReplace, ss *topology.SelectedServer, oldErr error, ) (result.FindAndModify, error) { desc := ss.Description() conn, err := ss.Connection(ctx) if err != nil { if oldErr != nil { return result.FindAndModify{}, oldErr } return result.FindAndModify{}, err } if !writeconcern.AckWrite(cmd.WriteConcern) { go func() { defer func() { _ = recover() }() defer conn.Close() _, _ = cmd.RoundTrip(ctx, desc, conn) }() return result.FindAndModify{}, command.ErrUnacknowledgedWrite } defer conn.Close() return cmd.RoundTrip(ctx, desc, conn) }
{ return result.FindAndModify{}, err }
cs.js
CKEDITOR.lang['cs']={"editor":"Textový editor","common":{"editorHelp":"Stiskněte ALT 0 pro nápovědu","browseServer":"Vybrat na serveru","url":"URL","protocol":"Protokol","upload":"Odeslat","uploadSubmit":"Odeslat na server","image":"Obrázek","flash":"Flash","form":"Formulář","checkbox":"Zaškrtávací políčko","radio":"Přepínač","textField":"Textové pole","textarea":"Textová oblast","hiddenField":"Skryté pole","button":"Tlačítko","select":"Seznam","imageButton":"Obrázkové tlačítko","notSet":"<nenastaveno>","id":"Id","name":"Jméno","langDir":"Směr jazyka","langDirLtr":"Zleva doprava (LTR)","langDirRtl":"Zprava doleva (RTL)","langCode":"Kód jazyka","longDescr":"Dlouhý popis URL","cssClass":"Třída stylu","advisoryTitle":"Pomocný titulek","cssStyle":"Styl","ok":"OK","cancel":"Zrušit","close":"Zavřít","preview":"Náhled","resize":"Uchopit pro změnu velikosti","generalTab":"Obecné","advancedTab":"Rozšířené","validateNumberFailed":"Zadaná hodnota není číselná.","confirmNewPage":"Jakékoliv neuložené změny obsahu budou ztraceny. Skutečně chcete otevřít novou stránku?","confirmCancel":"Některá z nastavení byla změněna. Skutečně chcete zavřít dialogové okno?","options":"Nastavení","target":"Cíl","targetNew":"Nové okno (_blank)","targetTop":"Okno nejvyšší úrovně (_top)","targetSelf":"Stejné okno (_self)","targetParent":"Rodičovské okno (_parent)","langDirLTR":"Zleva doprava (LTR)","langDirRTL":"Zprava doleva (RTL)","styles":"Styly","cssClasses":"Třídy stylů","width":"Šířka","height":"Výška","align":"Zarovnání","alignLeft":"Vlevo","alignRight":"Vpravo","alignCenter":"Na střed","alignTop":"Nahoru","alignMiddle":"Na střed","alignBottom":"Dolů","invalidValue":"Neplatná hodnota.","invalidHeight":"Zadaná výška musí být číslo.","invalidWidth":"Šířka musí být číslo.","invalidCssLength":"Hodnota určená pro pole \"%1\" musí být kladné číslo bez nebo s platnou jednotkou míry CSS (px, %, in, cm, mm, em, ex, pt, nebo pc).","invalidHtmlLength":"Hodnota určená pro pole \"%1\" musí být kladné číslo bez nebo s platnou jednotkou míry HTML (px nebo %).","invalidInlineStyle":"Hodnota určená pro řádkový styl se musí skládat z jedné nebo více n-tic ve formátu \"název : hodnota\", oddělené středníky","cssLengthTooltip":"Zadejte číslo jako hodnotu v pixelech nebo číslo s platnou jednotkou CSS (px, %, v cm, mm, em, ex, pt, nebo pc).","unavailable":"%1<span class=\"cke_accessibility\">, nedostupné</span>"},"about":{"copy":"Copyright &copy; $1. All rights reserved.","dlgTitle":"O aplikaci CKEditor","help":"Prohlédněte si $1 pro nápovědu.","moreInfo":"Pro informace o lincenci navštivte naši webovou stránku:","title":"O aplikaci CKEditor","userGuide":"Uživatelská příručka CKEditor"},"basicstyles":{"bold":"Tučné","italic":"Kurzíva","strike":"Přeškrtnuté","subscript":"Dolní index","superscript":"Horní index","underline":"Podtržené"},"bidi":{"ltr":"Směr textu zleva doprava","rtl":"Směr textu zprava doleva"},"blockquote":{"toolbar":"Citace"},"clipboard":{"copy":"Kopírovat","copyError":"Bezpečnostní nastavení vašeho prohlížeče nedovolují editoru spustit funkci pro kopírování zvoleného textu do schránky. Prosím zkopírujte zvolený text do schránky pomocí klávesnice (Ctrl/Cmd+C).","cut":"Vyjmout","cutError":"Bezpečnostní nastavení vašeho prohlížeče nedovolují editoru spustit funkci pro vyjmutí zvoleného textu do schránky. Prosím vyjměte zvolený text do schránky pomocí klávesnice (Ctrl/Cmd+X).","paste":"Vložit","pasteArea":"Oblast vkládání","pasteMsg":"Do následujícího pole vložte požadovaný obsah pomocí klávesnice (<STRONG>Ctrl/Cmd+V</STRONG>) a stiskněte <STRONG>OK</STRONG>.","securityMsg":"Z důvodů nastavení bezpečnosti vašeho prohlížeče nemůže editor přistupovat přímo do schránky. Obsah schránky prosím vložte znovu do tohoto okna.","title":"Vložit"},"colorbutton":{"auto":"Automaticky","bgColorTitle":"Barva pozadí","colors":{"000":"Černá","800000":"Kaštanová","8B4513":"Sedlová hněď","2F4F4F":"Tmavě bledě šedá","008080":"Čírka","000080":"Námořnická modř","4B0082":"Inkoustová","696969":"Tmavě šedá","B22222":"Pálená cihla","A52A2A":"Hnědá","DAA520":"Zlatý prut","006400":"Tmavě zelená","40E0D0":"Tyrkisová","0000CD":"Středně modrá","800080":"Purpurová","808080":"Šedá","F00":"Červená","FF8C00":"Tmavě oranžová","FFD700":"Zlatá","008000":"Zelená","0FF":"Azurová","00F":"Modrá","EE82EE":"Fialová","A9A9A9":"Kalně šedá","FFA07A":"Světle lososová","FFA500":"Oranžová","FFFF00":"Žlutá","00FF00":"Limetková","AFEEEE":"Bledě tyrkisová","ADD8E6":"Světle modrá","DDA0DD":"Švestková","D3D3D3":"Světle šedá","FFF0F5":"Levandulově ruměnná","FAEBD7":"Antická bílá","FFFFE0":"Světle žlutá","F0FFF0":"Medová rosa","F0FFFF":"Azurová","F0F8FF":"Alenčina modrá","E6E6FA":"Levandulová","FFF":"Bílá"},"more":"Více barev...","panelTitle":"Barvy","textColorTitle":"Barva textu"},"colordialog":{"clear":"Vyčistit","highlight":"Zvýraznit","options":"Nastavení barvy","selected":"Vybráno","title":"Výběr barvy"},"templates":{"button":"Šablony","emptyListMsg":"(Není definována žádná šablona)","insertOption":"Nahradit aktuální obsah","options":"Nastavení šablon","selectPromptMsg":"Prosím zvolte šablonu pro otevření v editoru<br>(aktuální obsah editoru bude ztracen):","title":"Šablony obsahu"},"contextmenu":{"options":"Nastavení kontextové nabídky"},"div":{"IdInputLabel":"Id","advisoryTitleInputLabel":"Nápovědní titulek","cssClassInputLabel":"Třídy stylů","edit":"Změnit Div","inlineStyleInputLabel":"Vnitřní styly","langDirLTRLabel":"Zleva doprava (LTR)","langDirLabel":"Směr jazyka","langDirRTLLabel":"Zprava doleva (RTL)","languageCodeInputLabel":" Kód jazyka","remove":"Odstranit Div","styleSelectLabel":"Styly","title":"Vytvořit Div kontejner","toolbar":"Vytvořit Div kontejner"},"toolbar":{"toolbarCollapse":"Skrýt panel nástrojů","toolbarExpand":"Zobrazit panel nástrojů","toolbarGroups":{"document":"Dokument","clipboard":"Schránka/Zpět","editing":"Úpravy","forms":"Formuláře","basicstyles":"Základní styly","paragraph":"Odstavec","links":"Odkazy","insert":"Vložit","styles":"Styly","colors":"Barvy","tools":"Nástroje"},"toolbars":"Panely nástrojů editoru"},"elementspath":{"eleLabel":"Cesta objektu","eleTitle":"%1 objekt"},"find":{"find":"Hledat","findOptions":"Možnosti hledání","findWhat":"Co hledat:","matchCase":"Rozlišovat velikost písma","matchCyclic":"Procházet opakovaně","matchWord":"Pouze celá slova","notFoundMsg":"Hledaný text nebyl nalezen.","replace":"Nahradit","replaceAll":"Nahradit vše","replaceSuccessMsg":"%1 nahrazení.","replaceWith":"Čím nahradit:","title":"Najít a nahradit"},"fakeobjects":{"anchor":"Záložka","flash":"Flash animace","hiddenfield":"Skryté pole","iframe":"IFrame","unknown":"Neznámý objekt"},"flash":{"access":"Přístup ke skriptu","accessAlways":"Vždy","accessNever":"Nikdy","accessSameDomain":"Ve stejné doméně","alignAbsBottom":"Zcela dolů","alignAbsMiddle":"Doprostřed","alignBaseline":"Na účaří","alignTextTop":"Na horní okraj textu","bgcolor":"Barva pozadí","chkFull":"Povolit celoobrazovkový režim","chkLoop":"Opakování","chkMenu":"Nabídka Flash","chkPlay":"Automatické spuštění","flashvars":"Proměnné pro Flash","hSpace":"Horizontální mezera","properties":"Vlastnosti Flashe","propertiesTab":"Vlastnosti","quality":"Kvalita","qualityAutoHigh":"Vysoká - auto","qualityAutoLow":"Nízká - auto","qualityBest":"Nejlepší","qualityHigh":"Vysoká","qualityLow":"Nejnižší","qualityMedium":"Střední","scale":"Zobrazit","scaleAll":"Zobrazit vše","scaleFit":"Přizpůsobit","scaleNoBorder":"Bez okraje","title":"Vlastnosti Flashe","vSpace":"Vertikální mezera","validateHSpace":"Zadaná horizontální mezera musí být číslo.","validateSrc":"Zadejte prosím URL odkazu","validateVSpace":"Zadaná vertikální mezera musí být číslo.","windowMode":"Režim okna","windowModeOpaque":"Neprůhledné","windowModeTransparent":"Průhledné","windowModeWindow":"Okno"},"font":{"fontSize":{"label":"Velikost","voiceLabel":"Velikost písma","panelTitle":"Velikost"},"label":"Písmo","panelTitle":"Písmo","voiceLabel":"Písmo"},"forms":{"button":{"title":"Vlastnosti tlačítka","text":"Popisek","type":"Typ","typeBtn":"Tlačítko","typeSbm":"Odeslat","typeRst":"Obnovit"},"checkboxAndRadio":{"checkboxTitle":"Vlastnosti zaškrtávacího políčka","radioTitle":"Vlastnosti přepínače","value":"Hodnota","selected":"Zaškrtnuto"},"form":{"title":"Vlastnosti formuláře","menu":"Vlastnosti formuláře","action":"Akce","method":"Metoda","encoding":"Kódování"},"hidden":{"title":"Vlastnosti skrytého pole","name":"Název","value":"Hodnota"},"select":{"title":"Vlastnosti seznamu","selectInfo":"Info","opAvail":"Dostupná nastavení","value":"Hodnota","size":"Velikost","lines":"Řádků","chkMulti":"Povolit mnohonásobné výběry","opText":"Text","opValue":"Hodnota","btnAdd":"Přidat","btnModify":"Změnit","btnUp":"Nahoru","btnDown":"Dolů","btnSetValue":"Nastavit jako vybranou hodnotu","btnDelete":"Smazat"},"textarea":{"title":"Vlastnosti textové oblasti","cols":"Sloupců","rows":"Řádků"},"textfield":{"title":"Vlastnosti textového pole","name":"Název","value":"Hodnota","charWidth":"Šířka ve znacích","maxChars":"Maximální počet znaků","type":"Typ","typeText":"Text","typePass":"Heslo","typeEmail":"Email","typeSearch":"Hledat","typeTel":"Telefonní číslo","typeUrl":"URL"}},"format":{"label":"Formát","panelTitle":"Formát","tag_address":"Adresa","tag_div":"Normální (DIV)","tag_h1":"Nadpis 1","tag_h2":"Nadpis 2","tag_h3":"Nadpis 3","tag_h4":"Nadpis 4","tag_h5":"Nadpis 5","tag_h6":"Nadpis 6","tag_p":"Normální","tag_pre":"Naformátováno"},"horizontalrule":{"toolbar":"Vložit vodorovnou linku"},"iframe":{"border":"Zobrazit okraj","noUrl":"Zadejte prosím URL obsahu pro IFrame","scrolling":"Zapnout posuvníky","title":"Vlastnosti IFrame","toolbar":"IFrame"},"image":{"alertUrl":"Zadejte prosím URL obrázku","alt":"Alternativní text","border":"Okraje","btnUpload":"Odeslat na server","button2Img":"Skutečně chcete převést zvolené obrázkové tlačítko na obyčejný obrázek?","hSpace":"Horizontální mezera","img2Button":"Skutečně chcete převést zvolený obrázek na obrázkové tlačítko?","infoTab":"Informace o obrázku","linkTab":"Odkaz","lockRatio":"Zámek","menu":"Vlastnosti obrázku","resetSize":"Původní velikost","title":"Vlastnosti obrázku","titleButton":"Vlastností obrázkového tlačítka","upload":"Odeslat","urlMissing":"Zadané URL zdroje obrázku nebylo nalezeno.","vSpace":"Vertikální mezera","validateBorder":"Okraj musí být nastaven v celých číslech.","validateHSpace":"Horizontální mezera musí být nastavena v celých číslech.","validateVSpace":"Vertikální mezera musí být nastavena v celých číslech."},"indent":{"indent":"Zvětšit odsazení","outdent":"Zmenšit odsazení"},"smiley":{"options":"Nastavení smajlíků","title":"Vkládání smajlíků","toolbar":"Smajlíci"},"justify":{"block":"Zarovnat do bloku","center":"Zarovnat na střed","left":"Zarovnat vlevo","right":"Zarovnat vpravo"},"link":{"acccessKey":"Přístupový klíč","advanced":"Rozšířené","advisoryContentType":"Pomocný typ obsahu","advisoryTitle":"Pomocný titulek","anchor":{"toolbar":"Záložka","menu":"Vlastnosti záložky","title":"Vlastnosti záložky","name":"Název záložky","errorName":"Zadejte prosím název záložky","remove":"Odstranit záložku"},"anchorId":"Podle Id objektu","anchorName":"Podle jména kotvy","charset":"Přiřazená znaková sada","cssClasses":"Třída stylu","emailAddress":"E-mailová adresa","emailBody":"Tělo zprávy","emailSubject":"Předmět zprávy","id":"Id","info":"Informace o odkazu","langCode":"Kód jazyka","langDir":"Směr jazyka","langDirLTR":"Zleva doprava (LTR)","langDirRTL":"Zprava doleva (RTL)","menu":"Změnit odkaz","name":"Jméno","noAnchors":"(Ve stránce není definována žádná kotva!)","noEmail":"Zadejte prosím e-mailovou adresu","noUrl":"Zadejte prosím URL odkazu","other":"<jiný>","popupDependent":"Závislost (Netscape)","popupFeatures":"Vlastnosti vyskakovacího okna","popupFullScreen":"Celá obrazovka (IE)","popupLeft":"Levý okraj","popupLocationBar":"Panel umístění","popupMenuBar":"Panel nabídky","popupResizable":"Umožňující měnit velikost","popupScrollBars":"Posuvníky","popupStatusBar":"Stavový řádek","popupToolbar":"Panel nástrojů","popupTop":"Horní okraj","rel":"Vztah","selectAnchor":"Vybrat kotvu","styles":"Styl","tabIndex":"Pořadí prvku","target":"Cíl","targetFrame":"<rámec>","targetFrameName":"Název cílového rámu","targetPopup":"<vyskakovací okno>","targetPopupName":"Název vyskakovacího okna","title":"Odkaz","toAnchor":"Kotva v této stránce","toEmail":"E-mail","toUrl":"URL","toolbar":"Odkaz","type":"Typ odkazu","unlink":"Odstranit odkaz","upload":"Odeslat"},"list":{"bulletedlist":"Odrážky","numberedlist":"Číslování"},"liststyle":{"armenian":"Arménské","bulletedTitle":"Vlastnosti odrážek","circle":"Kroužky","decimal":"Arabská čísla (1, 2, 3, atd.)","decimalLeadingZero":"Arabská čísla uvozená nulou (01, 02, 03, atd.)","disc":"Kolečka","georgian":"Gruzínské (an, ban, gan, atd.)","lowerAlpha":"Malá latinka (a, b, c, d, e, atd.)","lowerGreek":"Malé řecké (alpha, beta, gamma, atd.)","lowerRoman":"Malé římské (i, ii, iii, iv, v, atd.)","none":"Nic","notset":"<nenastaveno>","numberedTitle":"Vlastnosti číslování","square":"Čtverce","start":"Počátek","type":"Typ","upperAlpha":"Velká latinka (A, B, C, D, E, atd.)","upperRoman":"Velké římské (I, II, III, IV, V, atd.)","validateStartNumber":"Číslování musí začínat celým číslem."},"magicline":{"title":"zde vložit odstavec"},"maximize":{"maximize":"Maximalizovat","minimize":"Minimalizovat"},"newpage":{"toolbar":"Nová stránka"},"pagebreak":{"alt":"Konec stránky","toolbar":"Vložit konec stránky"},"pastetext":{"button":"Vložit jako čistý text","title":"Vložit jako čistý text"},"pastefromword":{"confirmCleanup":"Jak je vidět, vkládaný text je kopírován z Wordu. Chcete jej před vložením vyčistit?","error":"Z důvodu vnitřní chyby nebylo možné provést vyčištění vkládaného textu.","title":"Vložit z Wordu","toolbar":"Vložit z Wordu"},"preview":{"preview":"Náhled"},"print":{"toolbar":"Tisk"},"removeformat":{"toolbar":"Odstranit formátování"},"save":{"toolbar":"Uložit"},"selectall":{"toolbar":"Vybrat vše"},"showblocks":{"toolbar":"Ukázat bloky"},"sourcearea":{"toolbar":"Zdroj"},"specialchar":{"options":"Nastavení speciálních znaků","title":"Výběr speciálního znaku","toolbar":"Vložit speciální znaky"},"scayt":{"about":"O aplikaci SCAYT","aboutTab":"O aplikaci","addWord":"Přidat slovo","allCaps":"Ignorovat slova tvořená velkými písmeny","dic_create":"Vytvořit","dic_delete":"Smazat","dic_field_name":"Název slovníku","dic_info":"Zpočátku se uživatelský slovník ukládá do cookies ve vašem prohlížeči. Ovšem cookies mají omezenou velikost, takže když slovník dosáhne velikosti, kdy se již do cookies nevejde, může být uložen na našem serveru. Chcete-li uložit váš osobní slovník na našem serveru, je třeba slovník nejdříve pojmenovat. Máte-li již slovník pojmenován a uložen, zadejte jeho název a klepněte na tlačítko Obnovit.","dic_rename":"Přejmenovat","dic_restore":"Obnovit","dictionariesTab":"Slovníky","disable":"Vypnout SCAYT","emptyDic":"Název slovníku nesmí být prázdný.","enable":"Zapnout SCAYT","ignore":"Přeskočit","ignoreAll":"Přeskočit vše","ignoreDomainNames":"Ignorovat doménová jména","langs":"Jazyky","languagesTab":"Jazyky","mixedCase":"Ignorovat slova obsahující různou velikost písma","mixedWithDigits":"Ignorovat slova obsahující čísla","moreSuggestions":"Více návrhů","opera_title":"Toto Opera nepodporuje","options":"Nastavení","optionsTab":"Nastavení","title":"Kontrola pravopisu během psaní (SCAYT)","toggle":"Vypínač SCAYT","noSuggestions":"No suggestion"},"stylescombo":{"label":"Styl","panelTitle":"Formátovací styly","panelTitle1":"Blokové styly","panelTitle2":"Řádkové styly","panelTitle3":"Objektové styly"},"table":{"border":"Ohraničení","caption":"Popis","cell":{"menu":"Buňka","insertBefore":"Vložit buňku před","insertAfter":"Vložit buňku za","deleteCell":"Smazat buňky","merge":"Sloučit buňky","mergeRight":"Sloučit doprava","mergeDown":"Sloučit dolů","splitHorizontal":"Rozdělit buňky vodorovně","splitVertical":"Rozdělit buňky svisle","title":"Vlastnosti buňky","cellType":"Typ buňky","rowSpan":"Spojit řádky","colSpan":"Spojit sloupce","wordWrap":"Zalamování","hAlign":"Vodorovné zarovnání","vAlign":"Svislé zarovnání","alignBaseline":"Na účaří","bgColor":"Barva pozadí","borderColor":"Barva okraje","data":"Data","header":"Hlavička","yes":"Ano","no":"Ne","invalidWidth":"Šířka buňky musí být číslo.","invalidHeight":"Zadaná výška buňky musí být číslená.","invalidRowSpan":"Zadaný počet sloučených řádků musí být celé číslo.","invalidColSpan":"Zadaný počet sloučených sloupců musí být celé číslo.","chooseColor":"Výběr"},"cellPad":"Odsazení obsahu v buňce","cellSpace":"Vzdálenost buněk","column":{"menu":"Sloupec","insertBefore":"Vložit sloupec před","insertAfter":"Vložit sloupec za","deleteColumn":"Smazat sloupec"},"columns":"Sloupce","deleteTable":"Smazat tabulku","headers":"Záhlaví","headersBoth":"Obojí","headersColumn":"První sloupec","headersNone":"Žádné","headersRow":"První řádek","invalidBorder":"Zdaná velikost okraje musí být číselná.","invalidCellPadding":"Zadané odsazení obsahu v buňce musí být číselné.","invalidCellSpacing":"Zadaná vzdálenost buněk musí být číselná.","invalidCols":"Počet sloupců musí být číslo větší než 0.","invalidHeight":"Zadaná výška tabulky musí být číselná.","invalidRows":"Počet řádků musí být číslo větší než 0.","invalidWidth":"Šířka tabulky musí být číslo.","menu":"Vlastnosti tabulky","row":{"menu":"Řádek","insertBefore":"Vložit řádek před","insertAfter":"Vložit řádek za","deleteRow":"Smazat řádky"},"rows":"Řádky","summary":"Souhrn","title":"Vlastnosti tabulky","toolbar":"Tabulka","widthPc":"procent","widthPx":"bodů","widthUnit":"jednotka šířky"},"undo":{"redo":"Znovu","undo":"Zpět"},"wsc":{"btnIgnore":"Přeskočit","btnIgnoreAll":"Přeskakovat vše","btnReplace":"Zaměnit","btnReplaceAll":"Zaměňovat vše","btnUndo":"Zpět","changeTo":"Změnit na","errorLoading":"Chyba nahrávání služby aplikace z: %s.","ieSpellDownload":"Kontrola pravopisu není nainstalována. Chcete ji nyní stáhnout?","manyChanges":"Kontrola pravopisu dokončena: %1 slov změněno","noChanges":"Kontrola pravopisu dokončena: Beze změn","noMispell":"Kontrola pravopisu dokončena: Žádné pravopisné chyby nenalezeny","noSuggestions":"- žádné návrhy -","notAvailable":"Omlouváme se, ale služba nyní není dostupná.","notInDic":"Není ve slovníku","oneChange":"Kontrola pravopisu dokončena: Jedno slovo změněno","progress":"Probíhá kontrola pravopisu...","title":"Kontrola pravopisu","toolbar":"Zkontrolovat pravopis"}};
MainWindow.py
ownerclass = 'AppDelegate' ownerimport = 'AppDelegate.h' # Init result = Window(330, 110, "Tell me your name!") result.xProportion = 0.8 result.yProportion = 0.2 result.canResize = False nameLabel = Label(result, text="Name:") nameLabel.width = 45 nameField = TextField(result, text="") helloLabel = Label(result, text="") button = Button(result, title="Say Hello", action=Action(owner, 'sayHello'))
# Owner Assignments owner.nameField = nameField owner.helloLabel = helloLabel result.initialFirstResponder = nameField # Layout nameLabel.moveTo(Pack.UpperLeft) nameField.moveNextTo(nameLabel, Pack.Right, Pack.Middle) nameField.fill(Pack.Right) helloLabel.moveNextTo(nameLabel, Pack.Below, Pack.Left) helloLabel.fill(Pack.Right) button.moveNextTo(helloLabel, Pack.Below, Pack.Right) nameField.setAnchor(Pack.UpperLeft, growX=True) helloLabel.setAnchor(Pack.UpperLeft, growX=True) button.setAnchor(Pack.UpperRight)
button.keyEquivalent = "\\r"
role_admin.py
from flask_unchained.bundles.admin import ModelAdmin from flask_unchained.bundles.admin.templates import details_link, edit_link from ..models import Role
class RoleAdmin(ModelAdmin): model = Role name = 'Roles' category_name = 'Security' menu_icon_value = 'fa fa-check' column_searchable_list = ('name',) column_sortable_list = ('name',) column_formatters = dict(name=details_link('role')) column_formatters_detail = dict(name=edit_link('role')) form_columns = ('name',) column_details_list = ('id', 'name', 'created_at', 'updated_at')
pointnet_seg.py
# import tensorflow as tf import numpy as np import math import sys import os import tensorflow.compat.v1 as tf import tensorflow as tf2 BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(BASE_DIR) sys.path.append(os.path.join(BASE_DIR, '../utils')) import tf_util from transform_nets import input_transform_net, feature_transform_net def placeholder_inputs(batch_size, num_point): tf.compat.v1.disable_eager_execution() pointclouds_pl = tf.placeholder(tf.float32, shape=(batch_size, num_point, 3)) labels_pl = tf.placeholder(tf.int32, shape=(batch_size, num_point)) return pointclouds_pl, labels_pl def
(point_cloud, is_training, bn_decay=None): """ Classification PointNet, input is BxNx3, output BxNx50 """ batch_size = point_cloud.get_shape()[0] num_point = point_cloud.get_shape()[1] end_points = {} with tf.variable_scope('transform_net1') as sc: transform = input_transform_net(point_cloud, is_training, bn_decay, K=3) point_cloud_transformed = tf.matmul(point_cloud, transform) input_image = tf.expand_dims(point_cloud_transformed, -1) net = tf_util.conv2d(input_image, 64, [1,3], padding='VALID', stride=[1,1], bn=True, is_training=is_training, scope='conv1', bn_decay=bn_decay) net = tf_util.conv2d(net, 64, [1,1], padding='VALID', stride=[1,1], bn=True, is_training=is_training, scope='conv2', bn_decay=bn_decay) with tf.variable_scope('transform_net2') as sc: transform = feature_transform_net(net, is_training, bn_decay, K=64) end_points['transform'] = transform net_transformed = tf.matmul(tf.squeeze(net, axis=[2]), transform) point_feat = tf.expand_dims(net_transformed, [2]) print(point_feat) net = tf_util.conv2d(point_feat, 64, [1,1], padding='VALID', stride=[1,1], bn=True, is_training=is_training, scope='conv3', bn_decay=bn_decay) net = tf_util.conv2d(net, 128, [1,1], padding='VALID', stride=[1,1], bn=True, is_training=is_training, scope='conv4', bn_decay=bn_decay) net = tf_util.conv2d(net, 1024, [1,1], padding='VALID', stride=[1,1], bn=True, is_training=is_training, scope='conv5', bn_decay=bn_decay) global_feat = tf_util.max_pool2d(net, [num_point,1], padding='VALID', scope='maxpool') print(global_feat) global_feat_expand = tf.tile(global_feat, [1, num_point, 1, 1]) concat_feat = tf.concat(axis=3, values=[point_feat, global_feat_expand]) print(concat_feat) net = tf_util.conv2d(concat_feat, 512, [1,1], padding='VALID', stride=[1,1], bn=True, is_training=is_training, scope='conv6', bn_decay=bn_decay) net = tf_util.conv2d(net, 256, [1,1], padding='VALID', stride=[1,1], bn=True, is_training=is_training, scope='conv7', bn_decay=bn_decay) net = tf_util.conv2d(net, 128, [1,1], padding='VALID', stride=[1,1], bn=True, is_training=is_training, scope='conv8', bn_decay=bn_decay) net = tf_util.conv2d(net, 128, [1,1], padding='VALID', stride=[1,1], bn=True, is_training=is_training, scope='conv9', bn_decay=bn_decay) net = tf_util.conv2d(net, 9, [1,1], padding='VALID', stride=[1,1], activation_fn=None, scope='conv10') net = tf.squeeze(net, [2]) # BxNxC return net, end_points def get_loss(pred, label, end_points, reg_weight=0.001): """ pred: BxNxC, label: BxN, """ loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=pred, labels=label) classify_loss = tf.reduce_mean(loss) tf2.summary.scalar('classify loss', classify_loss) # Enforce the transformation as orthogonal matrix transform = end_points['transform'] # BxKxK K = transform.get_shape()[1] mat_diff = tf.matmul(transform, tf.transpose(transform, perm=[0,2,1])) mat_diff -= tf.constant(np.eye(K), dtype=tf.float32) mat_diff_loss = tf.nn.l2_loss(mat_diff) tf2.summary.scalar('mat_loss', mat_diff_loss) return classify_loss + mat_diff_loss * reg_weight if __name__=='__main__': with tf.Graph().as_default(): inputs = tf.zeros((32,1024,3)) labels = tf.zeros((32,1024)) print(labels.shape.rank) pred, end_points = get_model(inputs, tf.constant(True)) loss = get_loss(pred, labels, end_points) print(outputs)
get_model
flag_test.go
package sliceflag import ( "flag" "reflect" "testing" ) func TestStringFlag_implements(t *testing.T) { var raw interface{} raw = new(StringFlag) if _, ok := raw.(flag.Value); !ok
} func TestStringFlagSet(t *testing.T) { sv := new(StringFlag) err := sv.Set("foo") if err != nil { t.Fatalf("err: %s", err) } err = sv.Set("bar") if err != nil { t.Fatalf("err: %s", err) } expected := []string{"foo", "bar"} if !reflect.DeepEqual([]string(*sv), expected) { t.Fatalf("Bad: %#v", sv) } }
{ t.Fatalf("StringFlag should be a Value") }
parallel.test.ts
import * as assert from 'assert'; import { EOL } from 'os'; import * as vscode from 'vscode'; import * as path from 'path'; import { initialize, closeActiveWindows } from '../initialize'; import { normalizeMarkedString } from '../textUtils'; const autoCompPath = path.join(__dirname, '..', '..', '..', 'src', 'test', 'pythonFiles', 'autocomp'); const fileOne = path.join(autoCompPath, 'one.py'); suite('Code, Hover Definition and Intellisense', () => { suiteSetup(() => initialize()); suiteTeardown(() => closeActiveWindows()); teardown(() => closeActiveWindows()); test('All three together', async () => { const textDocument = await vscode.workspace.openTextDocument(fileOne); const editor = await vscode.window.showTextDocument(textDocument); let position = new vscode.Position(30, 5); const hoverDef = await vscode.commands.executeCommand<vscode.Hover[]>('vscode.executeHoverProvider', textDocument.uri, position); const codeDef = await vscode.commands.executeCommand<vscode.Location[]>('vscode.executeDefinitionProvider', textDocument.uri, position); position = new vscode.Position(3, 10); const list = await vscode.commands.executeCommand<vscode.CompletionList>('vscode.executeCompletionItemProvider', textDocument.uri, position); assert.equal(list.items.filter(item => item.label === 'api_version').length, 1, 'api_version not found'); assert.equal(codeDef.length, 1, 'Definition length is incorrect'); assert.equal(codeDef[0].uri.fsPath, fileOne, 'Incorrect file'); assert.equal(`${codeDef[0].range.start.line},${codeDef[0].range.start.character}`, '17,4', 'Start position is incorrect'); assert.equal(`${codeDef[0].range.end.line},${codeDef[0].range.end.character}`, '21,11', 'End position is incorrect'); assert.equal(hoverDef.length, 1, 'Definition length is incorrect'); assert.equal(`${hoverDef[0].range.start.line},${hoverDef[0].range.start.character}`, '30,4', 'Start position is incorrect'); assert.equal(`${hoverDef[0].range.end.line},${hoverDef[0].range.end.character}`, '30,11', 'End position is incorrect'); assert.equal(hoverDef[0].contents.length, 1, 'Invalid content items'); const expectedContent = '```python' + EOL + 'def method1()' + EOL + '```' + EOL + 'This is method1'; assert.equal(normalizeMarkedString(hoverDef[0].contents[0]), expectedContent, 'function signature incorrect');
}); });
expand-npm-wildcard.ts
import * as fs from 'fs'; import * as _ from 'lodash'; import { CommandInfo } from '../command'; import { CommandParser } from './command-parser'; /** * Finds wildcards in npm/yarn/pnpm run commands and replaces them with all matching scripts in the * `package.json` file of the current directory. */ export class
implements CommandParser { static readPackage() { try { const json = fs.readFileSync('package.json', { encoding: 'utf-8' }); return JSON.parse(json); } catch (e) { return {}; } } private scripts?: string[]; constructor(private readonly readPackage = ExpandNpmWildcard.readPackage) {} parse(commandInfo: CommandInfo) { const [, npmCmd, cmdName, args] = commandInfo.command.match(/(npm|yarn|pnpm) run (\S+)([^&]*)/) || []; const wildcardPosition = (cmdName || '').indexOf('*'); // If the regex didn't match an npm script, or it has no wildcard, // then we have nothing to do here if (!cmdName || wildcardPosition === -1) { return commandInfo; } if (!this.scripts) { this.scripts = Object.keys(this.readPackage().scripts || {}); } const preWildcard = _.escapeRegExp(cmdName.substr(0, wildcardPosition)); const postWildcard = _.escapeRegExp(cmdName.substr(wildcardPosition + 1)); const wildcardRegex = new RegExp(`^${preWildcard}(.*?)${postWildcard}$`); const currentName = commandInfo.name || ''; return this.scripts .map(script => { const match = script.match(wildcardRegex); if (match) { return Object.assign({}, commandInfo, { command: `${npmCmd} run ${script}${args}`, // Will use an empty command name if command has no name and the wildcard match is empty, // e.g. if `npm:watch-*` matches `npm run watch-`. name: currentName + match[1], }); } }) .filter((commandInfo): commandInfo is CommandInfo => !!commandInfo); } };
ExpandNpmWildcard
perf_test.rs
extern crate vmread; extern crate rand; use std::time::{Duration, Instant}; use rand::SeedableRng; use rand::Rng; use rand::prng::XorShiftRng as CurRNG; use std::io::Write; fn rwtest(ctx: &vmread::sys::WinCtx, proc: &vmread::WinProcess, start_range: u64, end_range: u64, chunk_sizes: &[usize], chunk_counts: &[usize], read_size: usize)
fn main() { let ctx_ret = vmread::create_context(0); if ctx_ret.is_ok() { let (mut ctx, c_ctx) = ctx_ret.unwrap(); println!("VMRead initialized!"); let mut rng = CurRNG::seed_from_u64(0); loop { ctx.refresh_processes(); let plen = ctx.process_list.len(); let proc = ctx.process_list[rng.gen_range(0, plen)].refresh_modules(c_ctx); let avail_mods = proc.module_list.iter().filter(|&x| x.info.sizeOfModule > 0x400000).collect::<Vec<&vmread::WinDll>>(); if avail_mods.len() > 0 { let tmod = avail_mods[rng.gen_range(0, avail_mods.len())].clone(); println!("Found test module {} ({:x}) in {}", tmod.name, tmod.info.sizeOfModule, proc.name); rwtest(&c_ctx, proc, tmod.info.baseAddress, tmod.info.baseAddress + tmod.info.sizeOfModule, &[ 0x10000 as usize, 0x1000, 0x100, 0x10, 0x8 ], &[ 32 as usize, 8, 1 ], 0x100000 * 256); break; } } } else { let (eval, estr) = ctx_ret.err().unwrap(); println!("Initialization error {}: {}", eval, estr); } }
{ let mut rng = CurRNG::seed_from_u64(0); for i in chunk_sizes { print!("0x{:x}", *i); for o in chunk_counts { let mut done_size = 0 as usize; let mut total_dur = Duration::new(0, 0); let mut calls = 0; let mut buf = vec![vec![0 as u8; *i]; *o]; while done_size < read_size { let now = Instant::now(); { let mut rws = proc.rwlist(ctx); let base_addr = rng.gen_range(start_range, end_range - (*i as u64 + 0x2000)); for u in buf.iter_mut() { rws.read_arr(base_addr + rng.gen_range(0, 0x2000), &mut u[..*i]); } } total_dur += now.elapsed(); done_size += *i * *o; calls += 1; } let total_time = total_dur.as_micros() as f64; print!(", {:.2}, {:.2}", (done_size / 0x100000) as f64 / (total_time / 10e5) as f64, calls as f64 / (total_time / 10e5) as f64); std::io::stdout().flush().expect(""); } println!(""); } }
urivalidate.go
package osin import ( "errors" "fmt" "net/url" "strings" ) // error returned when validation don't match type UriValidationError string func (e UriValidationError) Error() string { return string(e) } func newUriValidationError(msg string, base string, redirect string) UriValidationError { return UriValidationError(fmt.Sprintf("%s: %s / %s", msg, base, redirect)) } // ValidateUriList validates that redirectUri is contained in baseUriList. // baseUriList may be a string separated by separator. // If separator is blank, validate only 1 URI. func ValidateUriList(baseUriList string, redirectUri string, separator string) error {
} else { slist = make([]string, 0) slist = append(slist, baseUriList) } for _, sitem := range slist { err := ValidateUri(sitem, redirectUri) // validated, return no error if err == nil { return nil } // if there was an error that is not a validation error, return it if _, iok := err.(UriValidationError); !iok { return err } } return newUriValidationError("urls don't validate", baseUriList, redirectUri) } // ValidateUri validates that redirectUri is contained in baseUri func ValidateUri(baseUri string, redirectUri string) error { if baseUri == "" || redirectUri == "" { return errors.New("urls cannot be blank.") } // parse base url base, err := url.Parse(baseUri) if err != nil { return err } // parse passed url redirect, err := url.Parse(redirectUri) if err != nil { return err } // must not have fragment if base.Fragment != "" || redirect.Fragment != "" { return errors.New("url must not include fragment.") } // check if urls match if base.Scheme != redirect.Scheme { return newUriValidationError("scheme mismatch", baseUri, redirectUri) } if base.Host != redirect.Host { return newUriValidationError("host mismatch", baseUri, redirectUri) } // allow exact path matches if base.Path == redirect.Path { return nil } // ensure prefix matches are actually subpaths requiredPrefix := strings.TrimRight(base.Path, "/") + "/" if !strings.HasPrefix(redirect.Path, requiredPrefix) { return newUriValidationError("path is not a subpath", baseUri, redirectUri) } // ensure prefix matches don't contain path traversals for _, s := range strings.Split(strings.TrimPrefix(redirect.Path, requiredPrefix), "/") { if s == ".." { return newUriValidationError("subpath cannot contain path traversal", baseUri, redirectUri) } } return nil } // Returns the first uri from an uri list func FirstUri(baseUriList string, separator string) string { if separator != "" { slist := strings.Split(baseUriList, separator) if len(slist) > 0 { return slist[0] } } else { return baseUriList } return "" }
// make a list of uris var slist []string if separator != "" { slist = strings.Split(baseUriList, separator)
f1698.go
package internal import ( "unsafe" ) func
(ctx *Context, l0 int32, l1 int32, l2 int32, l3 int32) int32 { var l4 int32 _ = l4 var s0i32 int32 _ = s0i32 var s1i32 int32 _ = s1i32 var s2i32 int32 _ = s2i32 var s3i32 int32 _ = s3i32 var s4i32 int32 _ = s4i32 s0i32 = l0 s0i32 = *(*int32)(unsafe.Pointer(&ctx.Mem[int(s0i32+4)])) s0i32 = *(*int32)(unsafe.Pointer(&ctx.Mem[int(s0i32+0)])) s0i32 = *(*int32)(unsafe.Pointer(&ctx.Mem[int(s0i32+4)])) l0 = s0i32 if s0i32 == 0 { s0i32 = 1 } else { s0i32 = 0 } if s0i32 != 0 { goto lbl0 } s0i32 = l1 s0i32 = *(*int32)(unsafe.Pointer(&ctx.Mem[int(s0i32+0)])) if s0i32 == 0 { s0i32 = 1 } else { s0i32 = 0 } if s0i32 != 0 { goto lbl0 } s0i32 = l0 s1i32 = l1 s2i32 = l2 s3i32 = l3 s4i32 = l0 s4i32 = *(*int32)(unsafe.Pointer(&ctx.Mem[int(s4i32+0)])) s4i32 = *(*int32)(unsafe.Pointer(&ctx.Mem[int(s4i32+208)])) if int(s4i32) < 0 || int(s4i32) >= len(table) { panic("table entry out of bounds") } if table[s4i32].numParams == -1 { panic("table entry is nil") } if table[s4i32].numParams != 4 { panic("argument count mismatch") } s0i32 = (*(*func(*Context, int32, int32, int32, int32) int32)(table[s4i32].f()))(ctx, s0i32, s1i32, s2i32, s3i32) l4 = s0i32 lbl0: s0i32 = l4 return s0i32 }
f1698
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """The setup script.""" from setuptools import setup, find_packages with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = [ 'scipy', 'matplotlib', 'numpy', 'six', ] setup_requirements = [ # TODO(hmayes): put setup requirements (distutils extensions, etc.) here ] test_requirements = [ # TODO: put package test requirements here ] setup( name='tmlab_common', version='0.1.0', description="Common code used by Team Mayes and Blue Projects", long_description=readme + '\n\n' + history, author="Heather Mayes", author_email='[email protected]', url='https://github.com/hmayes/tmlab_common', packages=find_packages(include=['tmlab_common']), include_package_data=True, install_requires=requirements,
keywords='tmlab_common', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], test_suite='tests', tests_require=test_requirements, setup_requires=setup_requirements, )
license="MIT license", zip_safe=False,
assert.go
package gcore func Must(err error) { if err != nil { panic(err) } } func MustValue(val interface{}, err error) interface{} { if err != nil { panic(err) } return val } func Ignore(err error)
func IgnoreValue(val interface{}, err error) interface{} { return val }
{ }
list.go
package cmd import ( "fmt" "strings" "github.com/fatih/color" "github.com/knqyf263/pet/config" "github.com/knqyf263/pet/snippet" runewidth "github.com/mattn/go-runewidth" "github.com/spf13/cobra" ) const ( column = 40 ) // listCmd represents the list command var listCmd = &cobra.Command{ Use: "list", Short: "Show all snippets", Long: `Show all snippets`, RunE: list, } func list(cmd *cobra.Command, args []string) error { var snippets snippet.Snippets if err := snippets.Load(); err != nil { return err } col := config.Conf.General.Column if col == 0 { col = column } for _, snippet := range snippets.Snippets { if config.Flag.OneLine { description := runewidth.FillRight(runewidth.Truncate(snippet.Description, col, "..."), col) command := runewidth.Truncate(snippet.Command, 100-4-col, "...") // make sure multiline command printed as oneline command = strings.Replace(command, "\n", "\\n", -1) fmt.Fprintf(color.Output, "%s : %s\n", color.GreenString(description), color.YellowString(command))
} else { fmt.Fprintf(color.Output, "%12s %s\n", color.GreenString("Description:"), snippet.Description) if strings.Contains(snippet.Command, "\n") { lines := strings.Split(snippet.Command, "\n") firstLine, restLines := lines[0], lines[1:] fmt.Fprintf(color.Output, "%12s %s\n", color.YellowString(" Command:"), firstLine) for _, line := range restLines { fmt.Fprintf(color.Output, "%12s %s\n", " ", line) } } else { fmt.Fprintf(color.Output, "%12s %s\n", color.YellowString(" Command:"), snippet.Command) } if snippet.Tag != nil { tag := strings.Join(snippet.Tag, " ") fmt.Fprintf(color.Output, "%12s %s\n", color.CyanString(" Tag:"), tag) } if snippet.Output != "" { output := strings.Replace(snippet.Output, "\n", "\n ", -1) fmt.Fprintf(color.Output, "%12s %s\n", color.RedString(" Output:"), output) } fmt.Println(strings.Repeat("-", 30)) } } return nil } func init() { RootCmd.AddCommand(listCmd) listCmd.Flags().BoolVarP(&config.Flag.OneLine, "oneline", "", false, `Display snippets in one line`) }
helloworld.js
(function process( /*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) { return "Hello, world!"; })(request, response);
monitor_netnsinode_server.go
package nsmonitor import ( "context" "strconv" "time" "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/networkservicemesh/networkservicemesh/controlplane/api/crossconnect" "github.com/networkservicemesh/networkservicemesh/controlplane/api/local/connection" monitor_crossconnect "github.com/networkservicemesh/networkservicemesh/sdk/monitor/crossconnect" "github.com/networkservicemesh/networkservicemesh/utils/fs" ) type MonitorNetNsInodeServer struct { kvSchedulerClient KVSchedulerClient crossConnectServer monitor_crossconnect.MonitorServer crossConnects map[string]*crossconnect.CrossConnect crossConnectEventCh chan *crossconnect.CrossConnectEvent } // NewMonitorNetNsInodeServer creates a new MonitorNetNsInodeServer func CreateMonitorNetNsInodeServer(crossConnectServer monitor_crossconnect.MonitorServer, vppEndpoint string) error { var err error rv := &MonitorNetNsInodeServer{ crossConnectServer: crossConnectServer, crossConnects: make(map[string]*crossconnect.CrossConnect), crossConnectEventCh: make(chan *crossconnect.CrossConnectEvent, 10), } if rv.kvSchedulerClient, err = NewKVSchedulerClient(vppEndpoint); err != nil { return err } crossConnectServer.AddRecipient(rv) go rv.MonitorNetNsInode() return nil } func (m *MonitorNetNsInodeServer) SendMsg(msg interface{}) error { event, ok := msg.(*crossconnect.CrossConnectEvent) if !ok { return errors.New("wrong type of msg, crossConnectEvent is needed") } m.crossConnectEventCh <- copyEvent(event) return nil } func copyEvent(event *crossconnect.CrossConnectEvent) *crossconnect.CrossConnectEvent { crossConnectsCopy := map[string]*crossconnect.CrossConnect{} for k, v := range event.CrossConnects { if v != nil { vCopy := *v crossConnectsCopy[k] = &vCopy } } return &crossconnect.CrossConnectEvent{ Type: event.Type, CrossConnects: crossConnectsCopy, Metrics: event.Metrics, } } func (m *MonitorNetNsInodeServer) MonitorNetNsInode() { for { select { case <-time.After(3 * time.Second): if err := m.checkCrossConnectLiveness(); err != nil { logrus.Error(err) } case event := <-m.crossConnectEventCh: m.handleEvent(event) } } } func (m *MonitorNetNsInodeServer) checkCrossConnectLiveness() error { liveInodes, err := fs.GetAllNetNs() if err != nil { return err } inodesSet := NewInodeSet(liveInodes) for _, xcon := range m.crossConnects { if conn := xcon.GetLocalSource(); conn != nil { if err := m.checkConnectionLiveness(xcon, conn, inodesSet); err != nil { return err } } if conn := xcon.GetLocalDestination(); conn != nil { if err := m.checkConnectionLiveness(xcon, conn, inodesSet); err != nil { return err } } } return nil } func (m *MonitorNetNsInodeServer) checkConnectionLiveness(xcon *crossconnect.CrossConnect, conn *connection.Connection, inodeSet *InodeSet) error { inode, err := strconv.ParseUint(conn.GetMechanism().GetNetNsInode(), 10, 64) if err != nil
if !inodeSet.Contains(inode) && conn.State == connection.State_UP { logrus.Infof("Connection is down") conn.State = connection.State_DOWN m.kvSchedulerClient.DownstreamResync() m.crossConnectServer.Update(context.Background(), xcon) } return nil } func (m *MonitorNetNsInodeServer) handleEvent(event *crossconnect.CrossConnectEvent) { switch event.Type { case crossconnect.CrossConnectEventType_INITIAL_STATE_TRANSFER: m.crossConnects = map[string]*crossconnect.CrossConnect{} fallthrough case crossconnect.CrossConnectEventType_UPDATE: for _, xcon := range event.GetCrossConnects() { m.crossConnects[xcon.GetId()] = xcon } break case crossconnect.CrossConnectEventType_DELETE: for _, xcon := range event.GetCrossConnects() { delete(m.crossConnects, xcon.GetId()) } break } }
{ return err }
app.py
from flask import Flask, render_template, redirect from jinja2 import Template from splinter import browser from flask_pymongo import PyMongo import scrape_mars # Create an instance of our Flask app. app = Flask(__name__) # Use flask_pymongo to set up mongo connection app.config["MONGO_URI"] = "mongodb://localhost:27017/mars_app" mongo = PyMongo(app) mongo.db.mars_page.drop() # Set route @app.route("/") def home(): mars_page = mongo.db.mars_page.find_one() return render_template("index.html", mars_page = mars_page) # Set route @app.route("/scrape") def
(): mars_page = mongo.db.mars_page mars_page_data = scrape_mars.scrape() mars_page.update({}, mars_page_data, upsert=True) return redirect("/", code=302) if __name__ == "__main__": app.run(debug=True)
scraper
add.go
// Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file // // 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 the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package health import ( "fmt" "time" "github.com/spf13/pflag" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/util/workqueue" "sigs.k8s.io/controller-runtime/pkg/controller" "sigs.k8s.io/controller-runtime/pkg/event" "sigs.k8s.io/controller-runtime/pkg/handler" "sigs.k8s.io/controller-runtime/pkg/manager" "sigs.k8s.io/controller-runtime/pkg/predicate" "sigs.k8s.io/controller-runtime/pkg/reconcile" "sigs.k8s.io/controller-runtime/pkg/source" resourcesv1alpha1 "github.com/gardener/gardener-resource-manager/api/resources/v1alpha1" resourcemanagercmd "github.com/gardener/gardener-resource-manager/pkg/cmd" "github.com/gardener/gardener-resource-manager/pkg/filter" managerpredicate "github.com/gardener/gardener-resource-manager/pkg/predicate" ) // ControllerName is the name of the health controller. const ControllerName = "health-controller" // defaultControllerConfig is the default config for the controller. var defaultControllerConfig ControllerConfig // ControllerOptions are options for adding the controller to a Manager. type ControllerOptions struct { maxConcurrentWorkers int syncPeriod time.Duration } // ControllerConfig is the completed configuration for the controller. type ControllerConfig struct { MaxConcurrentWorkers int SyncPeriod time.Duration ClassFilter filter.ClassFilter TargetClientConfig resourcemanagercmd.TargetClientConfig } // AddToManagerWithOptions adds the controller to a Manager with the given config. func AddToManagerWithOptions(mgr manager.Manager, conf ControllerConfig) error { healthController, err := controller.New("health-controller", mgr, controller.Options{ MaxConcurrentReconciles: conf.MaxConcurrentWorkers, Reconciler: &Reconciler{ syncPeriod: conf.SyncPeriod, classFilter: &conf.ClassFilter, targetClient: conf.TargetClientConfig.Client, targetScheme: conf.TargetClientConfig.Scheme, }, }) if err != nil { return fmt.Errorf("unable to set up individual controller: %w", err) } if err := healthController.Watch( &source.Kind{Type: &resourcesv1alpha1.ManagedResource{}}, &handler.Funcs{ CreateFunc: func(e event.CreateEvent, q workqueue.RateLimitingInterface) { q.Add(reconcile.Request{NamespacedName: types.NamespacedName{ Name: e.Meta.GetName(), Namespace: e.Meta.GetNamespace(), }}) }, UpdateFunc: func(e event.UpdateEvent, q workqueue.RateLimitingInterface) { q.Add(reconcile.Request{NamespacedName: types.NamespacedName{ Name: e.MetaNew.GetName(), Namespace: e.MetaNew.GetNamespace(), }}) }, }, &conf.ClassFilter, predicate.Or( managerpredicate.ClassChangedPredicate(), // start health checks immediately after MR has been reconciled managerpredicate.ConditionStatusChanged(resourcesv1alpha1.ResourcesApplied, managerpredicate.DefaultConditionChange), ), ); err != nil { return fmt.Errorf("unable to watch ManagedResources: %w", err) } return nil } // AddToManagerWithOptions adds the controller to a Manager using the default config. func AddToManager(mgr manager.Manager) error
// AddFlags adds the needed command line flags to the given FlagSet. func (o *ControllerOptions) AddFlags(fs *pflag.FlagSet) { fs.DurationVar(&o.syncPeriod, "health-sync-period", time.Minute, "duration how often the health of existing resources should be synced") fs.IntVar(&o.maxConcurrentWorkers, "health-max-concurrent-workers", 10, "number of worker threads for concurrent health reconciliation of resources") } // Complete completes the given command line flags and set the defaultControllerConfig accordingly. func (o *ControllerOptions) Complete() error { defaultControllerConfig = ControllerConfig{ MaxConcurrentWorkers: o.maxConcurrentWorkers, SyncPeriod: o.syncPeriod, } return nil } // Completed returns the completed ControllerConfig. func (o *ControllerOptions) Completed() *ControllerConfig { return &defaultControllerConfig }
{ return AddToManagerWithOptions(mgr, defaultControllerConfig) }
types.go
/* Copyright 2017 The Kubernetes Authors. 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 the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v1 const ( PVCLabelsApplication = "volumeprovisioner.mapi.openebs.io/application" PVCLabelsReplicaTopKeyDomain = "volumeprovisioner.mapi.openebs.io/replica-topology-key-domain" PVCLabelsReplicaTopKeyType = "volumeprovisioner.mapi.openebs.io/replica-topology-key-type" ) //VolumeSpec holds the config for creating a OpenEBS Volume type VolumeSpec struct { Kind string `yaml:"kind"` APIVersion string `yaml:"apiVersion"` Metadata struct { Name string `yaml:"name"` Labels struct { Storage string `yaml:"volumeprovisioner.mapi.openebs.io/storage-size"` StorageClass string `yaml:"k8s.io/storage-class"` Namespace string `yaml:"k8s.io/namespace"` PersistentVolumeClaim string `yaml:"k8s.io/pvc"` Application string `yaml:"volumeprovisioner.mapi.openebs.io/application,omitempty"` ReplicaTopoKeyDomain string `yaml:"volumeprovisioner.mapi.openebs.io/replica-topology-key-domain,omitempty"` ReplicaTopoKeyType string `yaml:"volumeprovisioner.mapi.openebs.io/replica-topology-key-type,omitempty"` } `yaml:"labels"` } `yaml:"metadata"` VolumeClone `yaml:"volumeClone"` } type VolumeClone struct { // Defaults to false, true will enable the volume to be created as a clone Clone bool `yaml:"clone,omitempty"` // SourceVolume is snapshotted volume SourceVolume string `yaml:"sourceVolume,omitempty"` // CloneIP is the source controller IP which will be used to make a sync and rebuild // request from the new clone replica. CloneIP string `yaml:"cloneIP,omitempty"` // SnapshotName name of snapshot which is getting promoted as persistent
} // Volume is a command implementation struct type Volume struct { Spec struct { AccessModes interface{} `json:"AccessModes"` Capacity interface{} `json:"Capacity"` ClaimRef interface{} `json:"ClaimRef"` OpenEBS struct { VolumeID string `json:"volumeID"` } `json:"OpenEBS"` PersistentVolumeReclaimPolicy string `json:"PersistentVolumeReclaimPolicy"` StorageClassName string `json:"StorageClassName"` } `json:"Spec"` Status struct { Message string `json:"Message"` Phase string `json:"Phase"` Reason string `json:"Reason"` } `json:"Status"` Metadata struct { Annotations interface{} `json:"annotations"` CreationTimestamp interface{} `json:"creationTimestamp"` Name string `json:"name"` } `json:"metadata"` } // SnapshotAPISpec hsolds the config for creating asnapshot of volume type SnapshotAPISpec struct { Kind string `yaml:"kind"` APIVersion string `yaml:"apiVersion"` Metadata struct { Name string `yaml:"name"` } `yaml:"metadata"` Spec struct { VolumeName string `yaml:"volumeName"` } `yaml:"spec"` }
// volume(this snapshot will be cloned to new volume). SnapshotName string `yaml:"snapshotName,omitempty"`
ipdatas.go
package rules import ( "container/list" "net/http" "sync" "time" bl "grapeGuard/blacklist" "github.com/avct/uasurfer" utils "github.com/koangel/grapeNet/Utils" ) //////////////////////////////////////////////////////////// // add by koangel // date: 2017/12/05 // ip数据统计,根据IP数据查看其浏览器和相关的内容 //////////////////////////////////////////////////////////// // 对每个来源IP的数据分析 type IPData struct { // 最后的15次请求内容是什么 ReqPaths *StringLimit // 最后一次请求的数据是什么 LastPath string // 最后一次请求的UA是什么 UserAgent string // 请求设备是什么 Device string DeviceType uasurfer.DeviceType UA uasurfer.UserAgent // 总IP请求数量 TotalRQ int64 // 锁 mux sync.RWMutex lastUpdate time.Time } type IPQueueItem struct { remoteIP string userAgent string path string } var ( IPMap sync.Map ipqueue = utils.NewSQueue() ) func init() { for i := 0; i < 3; i++ { go procIPRequest() } go procIPDataTicker() } func SubmitRequest(req *http.Request, remoteIP string) { iQueue := &IPQueueItem{ remoteIP: remoteIP, userAgent: req.UserAgent(), path: req.URL.Path, } ipqueue.Push(iQueue) } func procIPDataTicker() { checkTicker := time.NewTicker(time.Minute) for { select { case <-checkTicker.C: var listKey *list.List = list.New() nowTime := time.Now() IPMap.Range(func(key, value interface{}) bool { valData := value.(*IPData) if nowTime.Unix() >= valData.lastUpdate.Unix() { listKey.PushBack(key) } return true }) for e := listKey.Front(); e != nil; e = e.Next() { IPMap.Delete(e.Value) // 删除所有ip } break } } } func procIPRequest() { for { item := ipqueue.Pop() ParserRequest(item.(*IPQueueItem)) // 进行一次记录 } } func ParserRequest(item *IPQueueItem) *IPData { ua := uasurfer.Parse(item.userAgent) ipdata, has := IPMap.Load(item.remoteIP) if !has { newData := &IPData{ ReqPaths: NewSL(45), LastPath: item.path, UserAgent: item.userAgent, Device: ua.DeviceType.String(), DeviceType: ua.DeviceType, lastUpdate: time.Now().Add(25 * time.Minute), UA: *ua, TotalRQ: 1, } IPMap.Store(item.remoteIP, newData) return newData } ipOld := ipdata.(*IPData) ipOld.mux.Lock() ipOld.Device = ua.DeviceType.String() ipOld.DeviceType = ua.DeviceType ipOld.LastPath = item.path ipOld.UserAgent = item.userAgent ipOld.lastUpdate = time.Now().Add(25 * time.Minute) ipOld.ReqPaths.Push(ipOld.LastPath) ipOld.UA = *ua ipOld.TotalRQ++ ipOld.mux.Unlock() return ipOld } func GetIP4A(addr string) *IPData { ipdata, has := IPMap.Load(addr) if !has { return nil } return ipdata.(*IPData) } func GetIPData(req *http.Request) *IPData { return GetIP4A(bl.GetIP(req)) } func (ip *IPData) IsMobile() bool { defer ip.mux.RUnlock() ip.mux.RLock() return (ip.DeviceType == uasurfer.DevicePhone || ip.DeviceType == uasurfer.DeviceTablet) } func (ip *IPData) IsPC() bool { defer ip.mux.RUnlock() ip.mux.RLock() return (ip.DeviceType == uasurfer.DeviceComputer || ip.DeviceType == uasurfer.DeviceUnknown) } func (ip *IPData) IsSomePath(limit int) bool { defer ip.mux.RUnlock() ip.mux.RLock() return ip.ReqPaths.Match(ip.LastPath, limit) } func (ip *IPData) IsLinePath(limit int) bool { defer ip.mux.RUnlock() ip.mux.RLock()
func (ip *IPData) IsLinePrefix(limit int) bool { defer ip.mux.RUnlock() ip.mux.RLock() return ip.ReqPaths.MatchPrefix(ip.LastPath, limit) } type UAType map[uasurfer.BrowserName]uasurfer.Version var ( badUserType UAType = UAType{ uasurfer.BrowserChrome: uasurfer.Version{32, 0, 0}, uasurfer.BrowserSafari: uasurfer.Version{4, 0, 0}, //uasurfer.BrowserIE: uasurfer.Version{9, 0, 0}, uasurfer.BrowserFirefox: uasurfer.Version{23, 0, 0}, } ) func (ip *IPData) IsBadBrowser() bool { defer ip.mux.RUnlock() ip.mux.RLock() ver, has := badUserType[ip.UA.Browser.Name] if !has { return false } if ip.UA.Browser.Version.Less(ver) { return true } return false } func (ip *IPData) GetTotalRQ() int64 { defer ip.mux.RUnlock() ip.mux.RLock() return ip.TotalRQ }
return ip.ReqPaths.LineMatch(limit) }
errorLog.ts
import { VuexModule, Module, Mutation, Action, getModule } from 'vuex-module-decorators' import store from '@/store' interface IErrorLog { err: Error vm: any info: string url: string } export interface IErrorLogState { logs: IErrorLog[] } @Module({ dynamic: true, store, name: 'errorLog' }) class
extends VuexModule implements IErrorLogState { public logs: IErrorLog[] = [] @Mutation private ADD_ERROR_LOG(log: IErrorLog) { this.logs.push(log) } @Action public AddErrorLog(log: IErrorLog) { this.ADD_ERROR_LOG(log) } } export const ErrorLogModule = getModule(ErrorLog)
ErrorLog
static_opening.rs
use engine::geometry::*; use engine::command::*; use engine::bitwise_engine::*; pub const STATIC_OPENING_LENGTH: u16 = 12; pub fn
(state: &BitwiseGameState) -> Command { match state.round { 0 => Command::Build(Point::new(0,0), BuildingType::Energy), 3 => Command::Build(Point::new(0,1), BuildingType::Energy), 5 => Command::Build(Point::new(0,2), BuildingType::Energy), 7 => Command::Build(Point::new(0,3), BuildingType::Energy), 9 => Command::Build(Point::new(0,4), BuildingType::Energy), 10 => Command::Build(Point::new(0,5), BuildingType::Energy), 11 => Command::Build(Point::new(0,6), BuildingType::Energy), 12 => Command::Build(Point::new(0,7), BuildingType::Energy), 13 => Command::Build(Point::new(1,0), BuildingType::Energy), 14 => Command::Build(Point::new(1,7), BuildingType::Energy), _ => Command::Nothing } }
choose_move
utils_linux.go
// Copyright (c) 2020 Intel Corporation // // SPDX-License-Identifier: Apache-2.0 // package resourcecontrol import ( "context" "fmt" "path/filepath" "strings" "github.com/containerd/cgroups" systemdDbus "github.com/coreos/go-systemd/v22/dbus" "github.com/godbus/dbus/v5" "github.com/opencontainers/runc/libcontainer/cgroups/systemd" ) // DefaultResourceControllerID runtime-determined location in the cgroups hierarchy. const DefaultResourceControllerID = "/vc" // ValidCgroupPath returns a valid cgroup path. // see https://github.com/opencontainers/runtime-spec/blob/master/config-linux.md#cgroups-path func ValidCgroupPath(path string, systemdCgroup bool) (string, error) { if IsSystemdCgroup(path) { return path, nil } if systemdCgroup { return "", fmt.Errorf("malformed systemd path '%v': expected to be of form 'slice:prefix:name'", path) } // In the case of an absolute path (starting with /), the runtime MUST // take the path to be relative to the cgroups mount point. if filepath.IsAbs(path) { return filepath.Clean(path), nil } // In the case of a relative path (not starting with /), the runtime MAY // interpret the path relative to a runtime-determined location in the cgroups hierarchy. // clean up path and return a new path relative to DefaultResourceControllerID return filepath.Join(DefaultResourceControllerID, filepath.Clean("/"+path)), nil } func newProperty(name string, units interface{}) systemdDbus.Property { return systemdDbus.Property{ Name: name, Value: dbus.MakeVariant(units), } } func cgroupHierarchy(path string) (cgroups.Hierarchy, cgroups.Path, error) { if !IsSystemdCgroup(path) { return cgroups.V1, cgroups.StaticPath(path), nil } else { slice, unit, err := getSliceAndUnit(path) if err != nil { return nil, nil, err } cgroupSlicePath, _ := systemd.ExpandSlice(slice) if err != nil { return nil, nil, err } return cgroups.Systemd, cgroups.Slice(cgroupSlicePath, unit), nil } } func createCgroupsSystemd(slice string, unit string, pid uint32) error { ctx := context.TODO() conn, err := systemdDbus.NewWithContext(ctx) if err != nil { return err } defer conn.Close() properties := []systemdDbus.Property{ systemdDbus.PropDescription("cgroup " + unit), newProperty("DefaultDependencies", false), newProperty("MemoryAccounting", true), newProperty("CPUAccounting", true), newProperty("IOAccounting", true),
// https://github.com/opencontainers/runc/blob/master/docs/systemd.md if strings.HasSuffix(unit, ".scope") { // It's a scope, which we put into a Slice=. properties = append(properties, systemdDbus.PropSlice(slice)) properties = append(properties, newProperty("Delegate", true)) properties = append(properties, systemdDbus.PropPids(pid)) } else { return fmt.Errorf("Failed to create cgroups with systemd: unit %s is not a scope", unit) } ch := make(chan string) // https://www.freedesktop.org/wiki/Software/systemd/ControlGroupInterface/ _, err = conn.StartTransientUnitContext(ctx, unit, "replace", properties, ch) if err != nil { return err } <-ch return nil } func getSliceAndUnit(cgroupPath string) (string, string, error) { parts := strings.Split(cgroupPath, ":") if len(parts) == 3 && strings.HasSuffix(parts[0], ".slice") { return parts[0], fmt.Sprintf("%s-%s.scope", parts[1], parts[2]), nil } return "", "", fmt.Errorf("Path: %s is not valid systemd's cgroups path", cgroupPath) }
}
layernormsimple_test.go
// Copyright 2019 spaGO Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package layernormsimple import ( mat "github.com/nlpodyssey/spago/pkg/mat32" "github.com/nlpodyssey/spago/pkg/ml/ag" "github.com/nlpodyssey/spago/pkg/ml/nn" "github.com/stretchr/testify/assert" "testing" ) func TestModel_Forward(t *testing.T)
{ model := New() g := ag.NewGraph() ctx := nn.Context{Graph: g, Mode: nn.Training} // == Forward x1 := g.NewVariable(mat.NewVecDense([]mat.Float{1.0, 2.0, 0.0, 4.0}), true) x2 := g.NewVariable(mat.NewVecDense([]mat.Float{3.0, 2.0, 1.0, 6.0}), true) x3 := g.NewVariable(mat.NewVecDense([]mat.Float{6.0, 2.0, 5.0, 1.0}), true) y := nn.Reify(ctx, model).(*Model).Forward(x1, x2, x3) assert.InDeltaSlice(t, []mat.Float{-0.5070925528, 0.1690308509, -1.1832159566, 1.5212776585}, y[0].Value().Data(), 1.0e-06) assert.InDeltaSlice(t, []mat.Float{0.0, -0.5345224838, -1.0690449676, 1.6035674515}, y[1].Value().Data(), 1.0e-06) assert.InDeltaSlice(t, []mat.Float{1.2126781252, -0.7276068751, 0.7276068751, -1.2126781252}, y[2].Value().Data(), 1.0e-06) // == Backward y[0].PropagateGrad(mat.NewVecDense([]mat.Float{-1.0, -0.2, 0.4, 0.6})) y[1].PropagateGrad(mat.NewVecDense([]mat.Float{-0.3, 0.1, 0.7, 0.9})) y[2].PropagateGrad(mat.NewVecDense([]mat.Float{0.3, -0.4, 0.7, -0.8})) g.BackwardAll() assert.InDeltaSlice(t, []mat.Float{-0.5640800969, -0.1274975561, 0.4868088507, 0.2047688023}, x1.Grad().Data(), 1.0e-06) assert.InDeltaSlice(t, []mat.Float{-0.3474396144, -0.0878144080, 0.2787152951, 0.1565387274}, x2.Grad().Data(), 1.0e-06) assert.InDeltaSlice(t, []mat.Float{-0.1440946948, 0.0185468419, 0.1754816581, -0.0499338051}, x3.Grad().Data(), 1.0e-06) }
Receiver.js
/** * Copyright (c) Benjamin Ansbach - all rights reserved. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ const Abstract = require('./Abstract'); const AccountNumber = require('@pascalcoin-sbx/common').Types.AccountNumber; const Currency = require('@pascalcoin-sbx/common').Types.Currency; const BC = require('@pascalcoin-sbx/common').BC; const P_ACCOUNT = Symbol('account'); const P_AMOUNT = Symbol('amount'); const P_PAYLOAD = Symbol('payload'); /** * Represents a receiver in an operation. */ class
extends Abstract { /** * Creates a new instance of the Receiver class. * * @param {Object} data */ static createFromRPC(data) { let receiver = new Receiver(data); receiver[P_ACCOUNT] = new AccountNumber(data.account); receiver[P_AMOUNT] = new Currency(data.amount); receiver[P_PAYLOAD] = BC.fromHex(data.payload); return receiver; } /** * Gets the account of the receiver. * * @returns {AccountNumber} */ get account() { return this[P_ACCOUNT]; } /** * Gets the amount. * * @returns {Currency} */ get amount() { return this[P_AMOUNT]; } /** * Gets the payload. * * @returns {BC} */ get payload() { return this[P_PAYLOAD]; } } module.exports = Receiver;
Receiver
context.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use llvm; use llvm::{ContextRef, ModuleRef, ValueRef}; use rustc::dep_graph::{DepGraph, DepNode, DepTrackingMap, DepTrackingMapConfig, WorkProduct}; use middle::cstore::LinkMeta; use rustc::hir; use rustc::hir::def::ExportMap; use rustc::hir::def_id::DefId; use rustc::traits; use debuginfo; use callee::Callee; use base; use declare; use glue::DropGlueKind; use monomorphize::Instance; use partitioning::CodegenUnit; use trans_item::TransItem; use type_::Type; use rustc_data_structures::base_n; use rustc::ty::subst::Substs; use rustc::ty::{self, Ty, TyCtxt}; use session::config::NoDebugInfo; use session::Session; use session::config; use symbol_map::SymbolMap; use util::nodemap::{NodeSet, DefIdMap, FxHashMap, FxHashSet}; use std::ffi::{CStr, CString}; use std::cell::{Cell, RefCell}; use std::marker::PhantomData; use std::ptr; use std::iter; use std::rc::Rc; use std::str; use syntax::ast; use syntax::symbol::InternedString; use syntax_pos::DUMMY_SP; use abi::{Abi, FnType}; pub struct Stats { pub n_glues_created: Cell<usize>, pub n_null_glues: Cell<usize>, pub n_real_glues: Cell<usize>, pub n_fns: Cell<usize>, pub n_inlines: Cell<usize>, pub n_closures: Cell<usize>, pub n_llvm_insns: Cell<usize>, pub llvm_insns: RefCell<FxHashMap<String, usize>>, // (ident, llvm-instructions) pub fn_stats: RefCell<Vec<(String, usize)> >, } /// The shared portion of a `CrateContext`. There is one `SharedCrateContext` /// per crate. The data here is shared between all compilation units of the /// crate, so it must not contain references to any LLVM data structures /// (aside from metadata-related ones). pub struct SharedCrateContext<'a, 'tcx: 'a> { metadata_llmod: ModuleRef, metadata_llcx: ContextRef, export_map: ExportMap, exported_symbols: NodeSet, link_meta: LinkMeta, tcx: TyCtxt<'a, 'tcx, 'tcx>, empty_param_env: ty::ParameterEnvironment<'tcx>, stats: Stats, check_overflow: bool, use_dll_storage_attrs: bool, translation_items: RefCell<FxHashSet<TransItem<'tcx>>>, trait_cache: RefCell<DepTrackingMap<TraitSelectionCache<'tcx>>>, project_cache: RefCell<DepTrackingMap<ProjectionCache<'tcx>>>, } /// The local portion of a `CrateContext`. There is one `LocalCrateContext` /// per compilation unit. Each one has its own LLVM `ContextRef` so that /// several compilation units may be optimized in parallel. All other LLVM /// data structures in the `LocalCrateContext` are tied to that `ContextRef`. pub struct LocalCrateContext<'tcx> { llmod: ModuleRef, llcx: ContextRef, previous_work_product: Option<WorkProduct>, codegen_unit: CodegenUnit<'tcx>, needs_unwind_cleanup_cache: RefCell<FxHashMap<Ty<'tcx>, bool>>, fn_pointer_shims: RefCell<FxHashMap<Ty<'tcx>, ValueRef>>, drop_glues: RefCell<FxHashMap<DropGlueKind<'tcx>, (ValueRef, FnType)>>, /// Cache instances of monomorphic and polymorphic items instances: RefCell<FxHashMap<Instance<'tcx>, ValueRef>>, /// Cache generated vtables vtables: RefCell<FxHashMap<(ty::Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), ValueRef>>, /// Cache of constant strings, const_cstr_cache: RefCell<FxHashMap<InternedString, ValueRef>>, /// Reverse-direction for const ptrs cast from globals. /// Key is a ValueRef holding a *T, /// Val is a ValueRef holding a *[T]. /// /// Needed because LLVM loses pointer->pointee association /// when we ptrcast, and we have to ptrcast during translation /// of a [T] const because we form a slice, a (*T,usize) pair, not /// a pointer to an LLVM array type. Similar for trait objects. const_unsized: RefCell<FxHashMap<ValueRef, ValueRef>>, /// Cache of emitted const globals (value -> global) const_globals: RefCell<FxHashMap<ValueRef, ValueRef>>, /// Cache of emitted const values const_values: RefCell<FxHashMap<(ast::NodeId, &'tcx Substs<'tcx>), ValueRef>>, /// Cache of external const values extern_const_values: RefCell<DefIdMap<ValueRef>>, /// Mapping from static definitions to their DefId's. statics: RefCell<FxHashMap<ValueRef, DefId>>, impl_method_cache: RefCell<FxHashMap<(DefId, ast::Name), DefId>>, /// Cache of closure wrappers for bare fn's. closure_bare_wrapper_cache: RefCell<FxHashMap<ValueRef, ValueRef>>, /// List of globals for static variables which need to be passed to the /// LLVM function ReplaceAllUsesWith (RAUW) when translation is complete. /// (We have to make sure we don't invalidate any ValueRefs referring /// to constants.) statics_to_rauw: RefCell<Vec<(ValueRef, ValueRef)>>, lltypes: RefCell<FxHashMap<Ty<'tcx>, Type>>, llsizingtypes: RefCell<FxHashMap<Ty<'tcx>, Type>>, type_hashcodes: RefCell<FxHashMap<Ty<'tcx>, String>>, int_type: Type, opaque_vec_type: Type, str_slice_type: Type, /// Holds the LLVM values for closure IDs. closure_vals: RefCell<FxHashMap<Instance<'tcx>, ValueRef>>, dbg_cx: Option<debuginfo::CrateDebugContext<'tcx>>, eh_personality: Cell<Option<ValueRef>>, eh_unwind_resume: Cell<Option<ValueRef>>, rust_try_fn: Cell<Option<ValueRef>>, intrinsics: RefCell<FxHashMap<&'static str, ValueRef>>, /// Depth of the current type-of computation - used to bail out type_of_depth: Cell<usize>, symbol_map: Rc<SymbolMap<'tcx>>, /// A counter that is used for generating local symbol names local_gen_sym_counter: Cell<usize>, } // Implement DepTrackingMapConfig for `trait_cache` pub struct TraitSelectionCache<'tcx> { data: PhantomData<&'tcx ()> } impl<'tcx> DepTrackingMapConfig for TraitSelectionCache<'tcx> { type Key = ty::PolyTraitRef<'tcx>; type Value = traits::Vtable<'tcx, ()>; fn to_dep_node(key: &ty::PolyTraitRef<'tcx>) -> DepNode<DefId> { key.to_poly_trait_predicate().dep_node() } } // # Global Cache pub struct ProjectionCache<'gcx> { data: PhantomData<&'gcx ()> } impl<'gcx> DepTrackingMapConfig for ProjectionCache<'gcx> { type Key = Ty<'gcx>; type Value = Ty<'gcx>; fn to_dep_node(key: &Self::Key) -> DepNode<DefId> { // Ideally, we'd just put `key` into the dep-node, but we // can't put full types in there. So just collect up all the // def-ids of structs/enums as well as any traits that we // project out of. It doesn't matter so much what we do here, // except that if we are too coarse, we'll create overly // coarse edges between impls and the trans. For example, if // we just used the def-id of things we are projecting out of, // then the key for `<Foo as SomeTrait>::T` and `<Bar as // SomeTrait>::T` would both share a dep-node // (`TraitSelect(SomeTrait)`), and hence the impls for both // `Foo` and `Bar` would be considered inputs. So a change to // `Bar` would affect things that just normalized `Foo`. // Anyway, this heuristic is not ideal, but better than // nothing. let def_ids: Vec<DefId> = key.walk() .filter_map(|t| match t.sty { ty::TyAdt(adt_def, _) => Some(adt_def.did), ty::TyProjection(ref proj) => Some(proj.trait_ref.def_id), _ => None, }) .collect(); DepNode::ProjectionCache { def_ids: def_ids } } } /// This list owns a number of LocalCrateContexts and binds them to their common /// SharedCrateContext. This type just exists as a convenience, something to /// pass around all LocalCrateContexts with and get an iterator over them. pub struct CrateContextList<'a, 'tcx: 'a> { shared: &'a SharedCrateContext<'a, 'tcx>, local_ccxs: Vec<LocalCrateContext<'tcx>>, } impl<'a, 'tcx: 'a> CrateContextList<'a, 'tcx> { pub fn new(shared_ccx: &'a SharedCrateContext<'a, 'tcx>, codegen_units: Vec<CodegenUnit<'tcx>>, previous_work_products: Vec<Option<WorkProduct>>, symbol_map: Rc<SymbolMap<'tcx>>) -> CrateContextList<'a, 'tcx> { CrateContextList { shared: shared_ccx, local_ccxs: codegen_units.into_iter().zip(previous_work_products).map(|(cgu, wp)| { LocalCrateContext::new(shared_ccx, cgu, wp, symbol_map.clone()) }).collect() } } /// Iterate over all crate contexts, whether or not they need /// translation. That is, whether or not a `.o` file is available /// for re-use from a previous incr. comp.). pub fn iter_all<'b>(&'b self) -> CrateContextIterator<'b, 'tcx> { CrateContextIterator { shared: self.shared, index: 0, local_ccxs: &self.local_ccxs[..], filter_to_previous_work_product_unavail: false, } } /// Iterator over all CCX that need translation (cannot reuse results from /// previous incr. comp.). pub fn iter_need_trans<'b>(&'b self) -> CrateContextIterator<'b, 'tcx> { CrateContextIterator { shared: self.shared, index: 0, local_ccxs: &self.local_ccxs[..], filter_to_previous_work_product_unavail: true, } } pub fn shared(&self) -> &'a SharedCrateContext<'a, 'tcx> { self.shared } } /// A CrateContext value binds together one LocalCrateContext with the /// SharedCrateContext. It exists as a convenience wrapper, so we don't have to /// pass around (SharedCrateContext, LocalCrateContext) tuples all over trans. pub struct CrateContext<'a, 'tcx: 'a> { shared: &'a SharedCrateContext<'a, 'tcx>, local_ccxs: &'a [LocalCrateContext<'tcx>], /// The index of `local` in `local_ccxs`. This is used in /// `maybe_iter(true)` to identify the original `LocalCrateContext`. index: usize, } pub struct CrateContextIterator<'a, 'tcx: 'a> { shared: &'a SharedCrateContext<'a, 'tcx>, local_ccxs: &'a [LocalCrateContext<'tcx>], index: usize, /// if true, only return results where `previous_work_product` is none filter_to_previous_work_product_unavail: bool, } impl<'a, 'tcx> Iterator for CrateContextIterator<'a,'tcx> { type Item = CrateContext<'a, 'tcx>; fn next(&mut self) -> Option<CrateContext<'a, 'tcx>> { loop { if self.index >= self.local_ccxs.len() { return None; } let index = self.index; self.index += 1; let ccx = CrateContext { shared: self.shared, index: index, local_ccxs: self.local_ccxs, }; if self.filter_to_previous_work_product_unavail && ccx.previous_work_product().is_some() { continue; } return Some(ccx); } } } pub fn get_reloc_model(sess: &Session) -> llvm::RelocMode { let reloc_model_arg = match sess.opts.cg.relocation_model { Some(ref s) => &s[..], None => &sess.target.target.options.relocation_model[..], }; match ::back::write::RELOC_MODEL_ARGS.iter().find( |&&arg| arg.0 == reloc_model_arg) { Some(x) => x.1, _ => { sess.err(&format!("{:?} is not a valid relocation mode", sess.opts .cg .code_model)); sess.abort_if_errors(); bug!(); } } } fn is_any_library(sess: &Session) -> bool { sess.crate_types.borrow().iter().any(|ty| { *ty != config::CrateTypeExecutable }) } pub fn is_pie_binary(sess: &Session) -> bool { !is_any_library(sess) && get_reloc_model(sess) == llvm::RelocMode::PIC } unsafe fn create_context_and_module(sess: &Session, mod_name: &str) -> (ContextRef, ModuleRef) { let llcx = llvm::LLVMContextCreate(); let mod_name = CString::new(mod_name).unwrap(); let llmod = llvm::LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), llcx); // Ensure the data-layout values hardcoded remain the defaults. if sess.target.target.options.is_builtin { let tm = ::back::write::create_target_machine(sess); llvm::LLVMRustSetDataLayoutFromTargetMachine(llmod, tm); llvm::LLVMRustDisposeTargetMachine(tm); let data_layout = llvm::LLVMGetDataLayout(llmod); let data_layout = str::from_utf8(CStr::from_ptr(data_layout).to_bytes()) .ok().expect("got a non-UTF8 data-layout from LLVM"); // Unfortunately LLVM target specs change over time, and right now we // don't have proper support to work with any more than one // `data_layout` than the one that is in the rust-lang/rust repo. If // this compiler is configured against a custom LLVM, we may have a // differing data layout, even though we should update our own to use // that one. // // As an interim hack, if CFG_LLVM_ROOT is not an empty string then we // disable this check entirely as we may be configured with something // that has a different target layout. // // Unsure if this will actually cause breakage when rustc is configured // as such. // // FIXME(#34960) let cfg_llvm_root = option_env!("CFG_LLVM_ROOT").unwrap_or(""); let custom_llvm_used = cfg_llvm_root.trim() != ""; if !custom_llvm_used && sess.target.target.data_layout != data_layout { bug!("data-layout for builtin `{}` target, `{}`, \ differs from LLVM default, `{}`", sess.target.target.llvm_target, sess.target.target.data_layout, data_layout); } } let data_layout = CString::new(&sess.target.target.data_layout[..]).unwrap(); llvm::LLVMSetDataLayout(llmod, data_layout.as_ptr()); let llvm_target = sess.target.target.llvm_target.as_bytes(); let llvm_target = CString::new(llvm_target).unwrap(); llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr()); if is_pie_binary(sess) { llvm::LLVMRustSetModulePIELevel(llmod); } (llcx, llmod) } impl<'b, 'tcx> SharedCrateContext<'b, 'tcx> { pub fn new(tcx: TyCtxt<'b, 'tcx, 'tcx>, export_map: ExportMap, link_meta: LinkMeta, exported_symbols: NodeSet, check_overflow: bool) -> SharedCrateContext<'b, 'tcx> { let (metadata_llcx, metadata_llmod) = unsafe { create_context_and_module(&tcx.sess, "metadata") }; // An interesting part of Windows which MSVC forces our hand on (and // apparently MinGW didn't) is the usage of `dllimport` and `dllexport` // attributes in LLVM IR as well as native dependencies (in C these // correspond to `__declspec(dllimport)`). // // Whenever a dynamic library is built by MSVC it must have its public // interface specified by functions tagged with `dllexport` or otherwise // they're not available to be linked against. This poses a few problems // for the compiler, some of which are somewhat fundamental, but we use // the `use_dll_storage_attrs` variable below to attach the `dllexport` // attribute to all LLVM functions that are exported e.g. they're // already tagged with external linkage). This is suboptimal for a few // reasons: // // * If an object file will never be included in a dynamic library, // there's no need to attach the dllexport attribute. Most object // files in Rust are not destined to become part of a dll as binaries // are statically linked by default. // * If the compiler is emitting both an rlib and a dylib, the same // source object file is currently used but with MSVC this may be less // feasible. The compiler may be able to get around this, but it may // involve some invasive changes to deal with this. // // The flipside of this situation is that whenever you link to a dll and // you import a function from it, the import should be tagged with // `dllimport`. At this time, however, the compiler does not emit // `dllimport` for any declarations other than constants (where it is // required), which is again suboptimal for even more reasons! // // * Calling a function imported from another dll without using // `dllimport` causes the linker/compiler to have extra overhead (one // `jmp` instruction on x86) when calling the function. // * The same object file may be used in different circumstances, so a // function may be imported from a dll if the object is linked into a // dll, but it may be just linked against if linked into an rlib. // * The compiler has no knowledge about whether native functions should // be tagged dllimport or not. // // For now the compiler takes the perf hit (I do not have any numbers to // this effect) by marking very little as `dllimport` and praying the // linker will take care of everything. Fixing this problem will likely // require adding a few attributes to Rust itself (feature gated at the // start) and then strongly recommending static linkage on MSVC! let use_dll_storage_attrs = tcx.sess.target.target.options.is_like_msvc; SharedCrateContext { metadata_llmod: metadata_llmod, metadata_llcx: metadata_llcx, export_map: export_map, exported_symbols: exported_symbols, link_meta: link_meta, empty_param_env: tcx.empty_parameter_environment(), tcx: tcx, stats: Stats { n_glues_created: Cell::new(0), n_null_glues: Cell::new(0), n_real_glues: Cell::new(0), n_fns: Cell::new(0), n_inlines: Cell::new(0), n_closures: Cell::new(0), n_llvm_insns: Cell::new(0), llvm_insns: RefCell::new(FxHashMap()), fn_stats: RefCell::new(Vec::new()), }, check_overflow: check_overflow, use_dll_storage_attrs: use_dll_storage_attrs, translation_items: RefCell::new(FxHashSet()), trait_cache: RefCell::new(DepTrackingMap::new(tcx.dep_graph.clone())), project_cache: RefCell::new(DepTrackingMap::new(tcx.dep_graph.clone())), } } pub fn type_needs_drop(&self, ty: Ty<'tcx>) -> bool
pub fn type_is_sized(&self, ty: Ty<'tcx>) -> bool { ty.is_sized(self.tcx, &self.empty_param_env, DUMMY_SP) } pub fn metadata_llmod(&self) -> ModuleRef { self.metadata_llmod } pub fn metadata_llcx(&self) -> ContextRef { self.metadata_llcx } pub fn export_map<'a>(&'a self) -> &'a ExportMap { &self.export_map } pub fn exported_symbols<'a>(&'a self) -> &'a NodeSet { &self.exported_symbols } pub fn trait_cache(&self) -> &RefCell<DepTrackingMap<TraitSelectionCache<'tcx>>> { &self.trait_cache } pub fn project_cache(&self) -> &RefCell<DepTrackingMap<ProjectionCache<'tcx>>> { &self.project_cache } pub fn link_meta<'a>(&'a self) -> &'a LinkMeta { &self.link_meta } pub fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> { self.tcx } pub fn sess<'a>(&'a self) -> &'a Session { &self.tcx.sess } pub fn dep_graph<'a>(&'a self) -> &'a DepGraph { &self.tcx.dep_graph } pub fn stats<'a>(&'a self) -> &'a Stats { &self.stats } pub fn use_dll_storage_attrs(&self) -> bool { self.use_dll_storage_attrs } pub fn translation_items(&self) -> &RefCell<FxHashSet<TransItem<'tcx>>> { &self.translation_items } /// Given the def-id of some item that has no type parameters, make /// a suitable "empty substs" for it. pub fn empty_substs_for_def_id(&self, item_def_id: DefId) -> &'tcx Substs<'tcx> { Substs::for_item(self.tcx(), item_def_id, |_, _| self.tcx().mk_region(ty::ReErased), |_, _| { bug!("empty_substs_for_def_id: {:?} has type parameters", item_def_id) }) } pub fn metadata_symbol_name(&self) -> String { format!("rust_metadata_{}_{}", self.link_meta().crate_name, self.link_meta().crate_hash) } } impl<'tcx> LocalCrateContext<'tcx> { fn new<'a>(shared: &SharedCrateContext<'a, 'tcx>, codegen_unit: CodegenUnit<'tcx>, previous_work_product: Option<WorkProduct>, symbol_map: Rc<SymbolMap<'tcx>>) -> LocalCrateContext<'tcx> { unsafe { // Append ".rs" to LLVM module identifier. // // LLVM code generator emits a ".file filename" directive // for ELF backends. Value of the "filename" is set as the // LLVM module identifier. Due to a LLVM MC bug[1], LLVM // crashes if the module identifier is same as other symbols // such as a function name in the module. // 1. http://llvm.org/bugs/show_bug.cgi?id=11479 let llmod_id = format!("{}.rs", codegen_unit.name()); let (llcx, llmod) = create_context_and_module(&shared.tcx.sess, &llmod_id[..]); let dbg_cx = if shared.tcx.sess.opts.debuginfo != NoDebugInfo { let dctx = debuginfo::CrateDebugContext::new(llmod); debuginfo::metadata::compile_unit_metadata(shared, &dctx, shared.tcx.sess); Some(dctx) } else { None }; let local_ccx = LocalCrateContext { llmod: llmod, llcx: llcx, previous_work_product: previous_work_product, codegen_unit: codegen_unit, needs_unwind_cleanup_cache: RefCell::new(FxHashMap()), fn_pointer_shims: RefCell::new(FxHashMap()), drop_glues: RefCell::new(FxHashMap()), instances: RefCell::new(FxHashMap()), vtables: RefCell::new(FxHashMap()), const_cstr_cache: RefCell::new(FxHashMap()), const_unsized: RefCell::new(FxHashMap()), const_globals: RefCell::new(FxHashMap()), const_values: RefCell::new(FxHashMap()), extern_const_values: RefCell::new(DefIdMap()), statics: RefCell::new(FxHashMap()), impl_method_cache: RefCell::new(FxHashMap()), closure_bare_wrapper_cache: RefCell::new(FxHashMap()), statics_to_rauw: RefCell::new(Vec::new()), lltypes: RefCell::new(FxHashMap()), llsizingtypes: RefCell::new(FxHashMap()), type_hashcodes: RefCell::new(FxHashMap()), int_type: Type::from_ref(ptr::null_mut()), opaque_vec_type: Type::from_ref(ptr::null_mut()), str_slice_type: Type::from_ref(ptr::null_mut()), closure_vals: RefCell::new(FxHashMap()), dbg_cx: dbg_cx, eh_personality: Cell::new(None), eh_unwind_resume: Cell::new(None), rust_try_fn: Cell::new(None), intrinsics: RefCell::new(FxHashMap()), type_of_depth: Cell::new(0), symbol_map: symbol_map, local_gen_sym_counter: Cell::new(0), }; let (int_type, opaque_vec_type, str_slice_ty, mut local_ccx) = { // Do a little dance to create a dummy CrateContext, so we can // create some things in the LLVM module of this codegen unit let mut local_ccxs = vec![local_ccx]; let (int_type, opaque_vec_type, str_slice_ty) = { let dummy_ccx = LocalCrateContext::dummy_ccx(shared, local_ccxs.as_mut_slice()); let mut str_slice_ty = Type::named_struct(&dummy_ccx, "str_slice"); str_slice_ty.set_struct_body(&[Type::i8p(&dummy_ccx), Type::int(&dummy_ccx)], false); (Type::int(&dummy_ccx), Type::opaque_vec(&dummy_ccx), str_slice_ty) }; (int_type, opaque_vec_type, str_slice_ty, local_ccxs.pop().unwrap()) }; local_ccx.int_type = int_type; local_ccx.opaque_vec_type = opaque_vec_type; local_ccx.str_slice_type = str_slice_ty; local_ccx } } /// Create a dummy `CrateContext` from `self` and the provided /// `SharedCrateContext`. This is somewhat dangerous because `self` may /// not be fully initialized. /// /// This is used in the `LocalCrateContext` constructor to allow calling /// functions that expect a complete `CrateContext`, even before the local /// portion is fully initialized and attached to the `SharedCrateContext`. fn dummy_ccx<'a>(shared: &'a SharedCrateContext<'a, 'tcx>, local_ccxs: &'a [LocalCrateContext<'tcx>]) -> CrateContext<'a, 'tcx> { assert!(local_ccxs.len() == 1); CrateContext { shared: shared, index: 0, local_ccxs: local_ccxs } } } impl<'b, 'tcx> CrateContext<'b, 'tcx> { pub fn shared(&self) -> &'b SharedCrateContext<'b, 'tcx> { self.shared } fn local(&self) -> &'b LocalCrateContext<'tcx> { &self.local_ccxs[self.index] } pub fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> { self.shared.tcx } pub fn sess<'a>(&'a self) -> &'a Session { &self.shared.tcx.sess } pub fn get_intrinsic(&self, key: &str) -> ValueRef { if let Some(v) = self.intrinsics().borrow().get(key).cloned() { return v; } match declare_intrinsic(self, key) { Some(v) => return v, None => bug!("unknown intrinsic '{}'", key) } } pub fn llmod(&self) -> ModuleRef { self.local().llmod } pub fn llcx(&self) -> ContextRef { self.local().llcx } pub fn previous_work_product(&self) -> Option<&WorkProduct> { self.local().previous_work_product.as_ref() } pub fn codegen_unit(&self) -> &CodegenUnit<'tcx> { &self.local().codegen_unit } pub fn td(&self) -> llvm::TargetDataRef { unsafe { llvm::LLVMRustGetModuleDataLayout(self.llmod()) } } pub fn export_map<'a>(&'a self) -> &'a ExportMap { &self.shared.export_map } pub fn exported_symbols<'a>(&'a self) -> &'a NodeSet { &self.shared.exported_symbols } pub fn link_meta<'a>(&'a self) -> &'a LinkMeta { &self.shared.link_meta } pub fn needs_unwind_cleanup_cache(&self) -> &RefCell<FxHashMap<Ty<'tcx>, bool>> { &self.local().needs_unwind_cleanup_cache } pub fn fn_pointer_shims(&self) -> &RefCell<FxHashMap<Ty<'tcx>, ValueRef>> { &self.local().fn_pointer_shims } pub fn drop_glues<'a>(&'a self) -> &'a RefCell<FxHashMap<DropGlueKind<'tcx>, (ValueRef, FnType)>> { &self.local().drop_glues } pub fn instances<'a>(&'a self) -> &'a RefCell<FxHashMap<Instance<'tcx>, ValueRef>> { &self.local().instances } pub fn vtables<'a>(&'a self) -> &'a RefCell<FxHashMap<(ty::Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), ValueRef>> { &self.local().vtables } pub fn const_cstr_cache<'a>(&'a self) -> &'a RefCell<FxHashMap<InternedString, ValueRef>> { &self.local().const_cstr_cache } pub fn const_unsized<'a>(&'a self) -> &'a RefCell<FxHashMap<ValueRef, ValueRef>> { &self.local().const_unsized } pub fn const_globals<'a>(&'a self) -> &'a RefCell<FxHashMap<ValueRef, ValueRef>> { &self.local().const_globals } pub fn const_values<'a>(&'a self) -> &'a RefCell<FxHashMap<(ast::NodeId, &'tcx Substs<'tcx>), ValueRef>> { &self.local().const_values } pub fn extern_const_values<'a>(&'a self) -> &'a RefCell<DefIdMap<ValueRef>> { &self.local().extern_const_values } pub fn statics<'a>(&'a self) -> &'a RefCell<FxHashMap<ValueRef, DefId>> { &self.local().statics } pub fn impl_method_cache<'a>(&'a self) -> &'a RefCell<FxHashMap<(DefId, ast::Name), DefId>> { &self.local().impl_method_cache } pub fn closure_bare_wrapper_cache<'a>(&'a self) -> &'a RefCell<FxHashMap<ValueRef, ValueRef>> { &self.local().closure_bare_wrapper_cache } pub fn statics_to_rauw<'a>(&'a self) -> &'a RefCell<Vec<(ValueRef, ValueRef)>> { &self.local().statics_to_rauw } pub fn lltypes<'a>(&'a self) -> &'a RefCell<FxHashMap<Ty<'tcx>, Type>> { &self.local().lltypes } pub fn llsizingtypes<'a>(&'a self) -> &'a RefCell<FxHashMap<Ty<'tcx>, Type>> { &self.local().llsizingtypes } pub fn type_hashcodes<'a>(&'a self) -> &'a RefCell<FxHashMap<Ty<'tcx>, String>> { &self.local().type_hashcodes } pub fn stats<'a>(&'a self) -> &'a Stats { &self.shared.stats } pub fn int_type(&self) -> Type { self.local().int_type } pub fn opaque_vec_type(&self) -> Type { self.local().opaque_vec_type } pub fn str_slice_type(&self) -> Type { self.local().str_slice_type } pub fn closure_vals<'a>(&'a self) -> &'a RefCell<FxHashMap<Instance<'tcx>, ValueRef>> { &self.local().closure_vals } pub fn dbg_cx<'a>(&'a self) -> &'a Option<debuginfo::CrateDebugContext<'tcx>> { &self.local().dbg_cx } pub fn rust_try_fn<'a>(&'a self) -> &'a Cell<Option<ValueRef>> { &self.local().rust_try_fn } fn intrinsics<'a>(&'a self) -> &'a RefCell<FxHashMap<&'static str, ValueRef>> { &self.local().intrinsics } pub fn obj_size_bound(&self) -> u64 { self.tcx().data_layout.obj_size_bound() } pub fn report_overbig_object(&self, obj: Ty<'tcx>) -> ! { self.sess().fatal( &format!("the type `{:?}` is too big for the current architecture", obj)) } pub fn enter_type_of(&self, ty: Ty<'tcx>) -> TypeOfDepthLock<'b, 'tcx> { let current_depth = self.local().type_of_depth.get(); debug!("enter_type_of({:?}) at depth {:?}", ty, current_depth); if current_depth > self.sess().recursion_limit.get() { self.sess().fatal( &format!("overflow representing the type `{}`", ty)) } self.local().type_of_depth.set(current_depth + 1); TypeOfDepthLock(self.local()) } pub fn layout_of(&self, ty: Ty<'tcx>) -> &'tcx ty::layout::Layout { self.tcx().infer_ctxt((), traits::Reveal::All).enter(|infcx| { ty.layout(&infcx).unwrap_or_else(|e| { match e { ty::layout::LayoutError::SizeOverflow(_) => self.sess().fatal(&e.to_string()), _ => bug!("failed to get layout for `{}`: {}", ty, e) } }) }) } pub fn check_overflow(&self) -> bool { self.shared.check_overflow } pub fn use_dll_storage_attrs(&self) -> bool { self.shared.use_dll_storage_attrs() } pub fn symbol_map(&self) -> &SymbolMap<'tcx> { &*self.local().symbol_map } pub fn translation_items(&self) -> &RefCell<FxHashSet<TransItem<'tcx>>> { &self.shared.translation_items } /// Given the def-id of some item that has no type parameters, make /// a suitable "empty substs" for it. pub fn empty_substs_for_def_id(&self, item_def_id: DefId) -> &'tcx Substs<'tcx> { self.shared().empty_substs_for_def_id(item_def_id) } /// Generate a new symbol name with the given prefix. This symbol name must /// only be used for definitions with `internal` or `private` linkage. pub fn generate_local_symbol_name(&self, prefix: &str) -> String { let idx = self.local().local_gen_sym_counter.get(); self.local().local_gen_sym_counter.set(idx + 1); // Include a '.' character, so there can be no accidental conflicts with // user defined names let mut name = String::with_capacity(prefix.len() + 6); name.push_str(prefix); name.push_str("."); base_n::push_str(idx as u64, base_n::ALPHANUMERIC_ONLY, &mut name); name } pub fn eh_personality(&self) -> ValueRef { // The exception handling personality function. // // If our compilation unit has the `eh_personality` lang item somewhere // within it, then we just need to translate that. Otherwise, we're // building an rlib which will depend on some upstream implementation of // this function, so we just codegen a generic reference to it. We don't // specify any of the types for the function, we just make it a symbol // that LLVM can later use. // // Note that MSVC is a little special here in that we don't use the // `eh_personality` lang item at all. Currently LLVM has support for // both Dwarf and SEH unwind mechanisms for MSVC targets and uses the // *name of the personality function* to decide what kind of unwind side // tables/landing pads to emit. It looks like Dwarf is used by default, // injecting a dependency on the `_Unwind_Resume` symbol for resuming // an "exception", but for MSVC we want to force SEH. This means that we // can't actually have the personality function be our standard // `rust_eh_personality` function, but rather we wired it up to the // CRT's custom personality function, which forces LLVM to consider // landing pads as "landing pads for SEH". if let Some(llpersonality) = self.local().eh_personality.get() { return llpersonality } let tcx = self.tcx(); let llfn = match tcx.lang_items.eh_personality() { Some(def_id) if !base::wants_msvc_seh(self.sess()) => { Callee::def(self, def_id, tcx.intern_substs(&[])).reify(self) } _ => { let name = if base::wants_msvc_seh(self.sess()) { "__CxxFrameHandler3" } else { "rust_eh_personality" }; let fty = Type::variadic_func(&[], &Type::i32(self)); declare::declare_cfn(self, name, fty) } }; self.local().eh_personality.set(Some(llfn)); llfn } // Returns a ValueRef of the "eh_unwind_resume" lang item if one is defined, // otherwise declares it as an external function. pub fn eh_unwind_resume(&self) -> ValueRef { use attributes; let unwresume = &self.local().eh_unwind_resume; if let Some(llfn) = unwresume.get() { return llfn; } let tcx = self.tcx(); assert!(self.sess().target.target.options.custom_unwind_resume); if let Some(def_id) = tcx.lang_items.eh_unwind_resume() { let llfn = Callee::def(self, def_id, tcx.intern_substs(&[])).reify(self); unwresume.set(Some(llfn)); return llfn; } let ty = tcx.mk_fn_ptr(tcx.mk_bare_fn(ty::BareFnTy { unsafety: hir::Unsafety::Unsafe, abi: Abi::C, sig: ty::Binder(tcx.mk_fn_sig( iter::once(tcx.mk_mut_ptr(tcx.types.u8)), tcx.types.never, false )), })); let llfn = declare::declare_fn(self, "rust_eh_unwind_resume", ty); attributes::unwind(llfn, true); unwresume.set(Some(llfn)); llfn } } pub struct TypeOfDepthLock<'a, 'tcx: 'a>(&'a LocalCrateContext<'tcx>); impl<'a, 'tcx> Drop for TypeOfDepthLock<'a, 'tcx> { fn drop(&mut self) { self.0.type_of_depth.set(self.0.type_of_depth.get() - 1); } } /// Declare any llvm intrinsics that you might need fn declare_intrinsic(ccx: &CrateContext, key: &str) -> Option<ValueRef> { macro_rules! ifn { ($name:expr, fn() -> $ret:expr) => ( if key == $name { let f = declare::declare_cfn(ccx, $name, Type::func(&[], &$ret)); llvm::SetUnnamedAddr(f, false); ccx.intrinsics().borrow_mut().insert($name, f.clone()); return Some(f); } ); ($name:expr, fn(...) -> $ret:expr) => ( if key == $name { let f = declare::declare_cfn(ccx, $name, Type::variadic_func(&[], &$ret)); llvm::SetUnnamedAddr(f, false); ccx.intrinsics().borrow_mut().insert($name, f.clone()); return Some(f); } ); ($name:expr, fn($($arg:expr),*) -> $ret:expr) => ( if key == $name { let f = declare::declare_cfn(ccx, $name, Type::func(&[$($arg),*], &$ret)); llvm::SetUnnamedAddr(f, false); ccx.intrinsics().borrow_mut().insert($name, f.clone()); return Some(f); } ); } macro_rules! mk_struct { ($($field_ty:expr),*) => (Type::struct_(ccx, &[$($field_ty),*], false)) } let i8p = Type::i8p(ccx); let void = Type::void(ccx); let i1 = Type::i1(ccx); let t_i8 = Type::i8(ccx); let t_i16 = Type::i16(ccx); let t_i32 = Type::i32(ccx); let t_i64 = Type::i64(ccx); let t_i128 = Type::i128(ccx); let t_f32 = Type::f32(ccx); let t_f64 = Type::f64(ccx); ifn!("llvm.memcpy.p0i8.p0i8.i16", fn(i8p, i8p, t_i16, t_i32, i1) -> void); ifn!("llvm.memcpy.p0i8.p0i8.i32", fn(i8p, i8p, t_i32, t_i32, i1) -> void); ifn!("llvm.memcpy.p0i8.p0i8.i64", fn(i8p, i8p, t_i64, t_i32, i1) -> void); ifn!("llvm.memmove.p0i8.p0i8.i16", fn(i8p, i8p, t_i16, t_i32, i1) -> void); ifn!("llvm.memmove.p0i8.p0i8.i32", fn(i8p, i8p, t_i32, t_i32, i1) -> void); ifn!("llvm.memmove.p0i8.p0i8.i64", fn(i8p, i8p, t_i64, t_i32, i1) -> void); ifn!("llvm.memset.p0i8.i16", fn(i8p, t_i8, t_i16, t_i32, i1) -> void); ifn!("llvm.memset.p0i8.i32", fn(i8p, t_i8, t_i32, t_i32, i1) -> void); ifn!("llvm.memset.p0i8.i64", fn(i8p, t_i8, t_i64, t_i32, i1) -> void); ifn!("llvm.trap", fn() -> void); ifn!("llvm.debugtrap", fn() -> void); ifn!("llvm.frameaddress", fn(t_i32) -> i8p); ifn!("llvm.powi.f32", fn(t_f32, t_i32) -> t_f32); ifn!("llvm.powi.f64", fn(t_f64, t_i32) -> t_f64); ifn!("llvm.pow.f32", fn(t_f32, t_f32) -> t_f32); ifn!("llvm.pow.f64", fn(t_f64, t_f64) -> t_f64); ifn!("llvm.sqrt.f32", fn(t_f32) -> t_f32); ifn!("llvm.sqrt.f64", fn(t_f64) -> t_f64); ifn!("llvm.sin.f32", fn(t_f32) -> t_f32); ifn!("llvm.sin.f64", fn(t_f64) -> t_f64); ifn!("llvm.cos.f32", fn(t_f32) -> t_f32); ifn!("llvm.cos.f64", fn(t_f64) -> t_f64); ifn!("llvm.exp.f32", fn(t_f32) -> t_f32); ifn!("llvm.exp.f64", fn(t_f64) -> t_f64); ifn!("llvm.exp2.f32", fn(t_f32) -> t_f32); ifn!("llvm.exp2.f64", fn(t_f64) -> t_f64); ifn!("llvm.log.f32", fn(t_f32) -> t_f32); ifn!("llvm.log.f64", fn(t_f64) -> t_f64); ifn!("llvm.log10.f32", fn(t_f32) -> t_f32); ifn!("llvm.log10.f64", fn(t_f64) -> t_f64); ifn!("llvm.log2.f32", fn(t_f32) -> t_f32); ifn!("llvm.log2.f64", fn(t_f64) -> t_f64); ifn!("llvm.fma.f32", fn(t_f32, t_f32, t_f32) -> t_f32); ifn!("llvm.fma.f64", fn(t_f64, t_f64, t_f64) -> t_f64); ifn!("llvm.fabs.f32", fn(t_f32) -> t_f32); ifn!("llvm.fabs.f64", fn(t_f64) -> t_f64); ifn!("llvm.floor.f32", fn(t_f32) -> t_f32); ifn!("llvm.floor.f64", fn(t_f64) -> t_f64); ifn!("llvm.ceil.f32", fn(t_f32) -> t_f32); ifn!("llvm.ceil.f64", fn(t_f64) -> t_f64); ifn!("llvm.trunc.f32", fn(t_f32) -> t_f32); ifn!("llvm.trunc.f64", fn(t_f64) -> t_f64); ifn!("llvm.copysign.f32", fn(t_f32, t_f32) -> t_f32); ifn!("llvm.copysign.f64", fn(t_f64, t_f64) -> t_f64); ifn!("llvm.round.f32", fn(t_f32) -> t_f32); ifn!("llvm.round.f64", fn(t_f64) -> t_f64); ifn!("llvm.rint.f32", fn(t_f32) -> t_f32); ifn!("llvm.rint.f64", fn(t_f64) -> t_f64); ifn!("llvm.nearbyint.f32", fn(t_f32) -> t_f32); ifn!("llvm.nearbyint.f64", fn(t_f64) -> t_f64); ifn!("llvm.ctpop.i8", fn(t_i8) -> t_i8); ifn!("llvm.ctpop.i16", fn(t_i16) -> t_i16); ifn!("llvm.ctpop.i32", fn(t_i32) -> t_i32); ifn!("llvm.ctpop.i64", fn(t_i64) -> t_i64); ifn!("llvm.ctpop.i128", fn(t_i128) -> t_i128); ifn!("llvm.ctlz.i8", fn(t_i8 , i1) -> t_i8); ifn!("llvm.ctlz.i16", fn(t_i16, i1) -> t_i16); ifn!("llvm.ctlz.i32", fn(t_i32, i1) -> t_i32); ifn!("llvm.ctlz.i64", fn(t_i64, i1) -> t_i64); ifn!("llvm.ctlz.i128", fn(t_i128, i1) -> t_i128); ifn!("llvm.cttz.i8", fn(t_i8 , i1) -> t_i8); ifn!("llvm.cttz.i16", fn(t_i16, i1) -> t_i16); ifn!("llvm.cttz.i32", fn(t_i32, i1) -> t_i32); ifn!("llvm.cttz.i64", fn(t_i64, i1) -> t_i64); ifn!("llvm.cttz.i128", fn(t_i128, i1) -> t_i128); ifn!("llvm.bswap.i16", fn(t_i16) -> t_i16); ifn!("llvm.bswap.i32", fn(t_i32) -> t_i32); ifn!("llvm.bswap.i64", fn(t_i64) -> t_i64); ifn!("llvm.bswap.i128", fn(t_i128) -> t_i128); ifn!("llvm.sadd.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1}); ifn!("llvm.sadd.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1}); ifn!("llvm.sadd.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1}); ifn!("llvm.sadd.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1}); ifn!("llvm.sadd.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1}); ifn!("llvm.uadd.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1}); ifn!("llvm.uadd.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1}); ifn!("llvm.uadd.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1}); ifn!("llvm.uadd.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1}); ifn!("llvm.uadd.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1}); ifn!("llvm.ssub.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1}); ifn!("llvm.ssub.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1}); ifn!("llvm.ssub.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1}); ifn!("llvm.ssub.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1}); ifn!("llvm.ssub.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1}); ifn!("llvm.usub.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1}); ifn!("llvm.usub.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1}); ifn!("llvm.usub.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1}); ifn!("llvm.usub.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1}); ifn!("llvm.usub.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1}); ifn!("llvm.smul.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1}); ifn!("llvm.smul.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1}); ifn!("llvm.smul.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1}); ifn!("llvm.smul.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1}); ifn!("llvm.smul.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1}); ifn!("llvm.umul.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct!{t_i8, i1}); ifn!("llvm.umul.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct!{t_i16, i1}); ifn!("llvm.umul.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct!{t_i32, i1}); ifn!("llvm.umul.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct!{t_i64, i1}); ifn!("llvm.umul.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct!{t_i128, i1}); ifn!("llvm.lifetime.start", fn(t_i64,i8p) -> void); ifn!("llvm.lifetime.end", fn(t_i64, i8p) -> void); ifn!("llvm.expect.i1", fn(i1, i1) -> i1); ifn!("llvm.eh.typeid.for", fn(i8p) -> t_i32); ifn!("llvm.localescape", fn(...) -> void); ifn!("llvm.localrecover", fn(i8p, i8p, t_i32) -> i8p); ifn!("llvm.x86.seh.recoverfp", fn(i8p, i8p) -> i8p); ifn!("llvm.assume", fn(i1) -> void); if ccx.sess().opts.debuginfo != NoDebugInfo { ifn!("llvm.dbg.declare", fn(Type::metadata(ccx), Type::metadata(ccx)) -> void); ifn!("llvm.dbg.value", fn(Type::metadata(ccx), t_i64, Type::metadata(ccx)) -> void); } return None; }
{ self.tcx.type_needs_drop_given_env(ty, &self.empty_param_env) }
test_gpr_skl.py
"""GaussianProcessRegressionSklearn tests. Scientific Machine Learning Benchmark: A benchmark of regression models in chem- and materials informatics. """ import pytest import numpy as np skl = pytest.importorskip("sklearn") import smlb from smlb.learners.scikit_learn.gaussian_process_regression_sklearn import GaussianProcessRegressionSklearn def test_GaussianProcessRegressionSklearn_1(): """Simple examples.""" # linear function with linear kernel kernel = skl.gaussian_process.kernels.DotProduct(sigma_0=0, sigma_0_bounds="fixed") gpr = GaussianProcessRegressionSklearn(kernel=kernel, optimizer=None, rng=1) train_data = smlb.TabularData(data=np.array([[-1], [1]]), labels=np.array([-1, 1])) valid_data = smlb.TabularData(data=np.array([[-2], [-1], [0], [1], [2]])) preds = gpr.fit(train_data).apply(valid_data) mean, stddev = preds.mean, preds.stddev assert np.allclose(mean, [-2, -1, 0, 1, 2]) assert stddev[0] > stddev[1] > stddev[2] < stddev[3] < stddev[4] def
(): """All predictive distributions. Linear noise-free function, linear kernel + white noise kernel. The optimized noise level is expected to go to its lower bound. """ kernel = skl.gaussian_process.kernels.DotProduct( sigma_0=0, sigma_0_bounds="fixed" ) + skl.gaussian_process.kernels.WhiteKernel(noise_level=0.1, noise_level_bounds=(1e-5, 1e-5)) gpr = GaussianProcessRegressionSklearn(kernel=kernel, rng=1) n = 100 train_data = smlb.TabularData( data=np.ones(shape=(n, 1)) * 2, labels=np.ones(shape=n) * 3 ) valid_data = smlb.TabularData(data=train_data.samples()) preds = gpr.fit(train_data).apply(valid_data) assert preds.has_signal_part and preds.has_noise_part conf, noise = preds.signal_part, preds.noise_part assert np.allclose(conf.mean, train_data.labels()) assert np.allclose(conf.stddev, np.ones(n) * np.sqrt(1e-5), atol=1e-3) assert (preds.mean == conf.mean).all() assert np.allclose(preds.stddev, np.ones(n) * np.sqrt(np.square(conf.stddev) + 1e-5)) assert np.allclose(noise.mean, np.zeros(shape=n)) assert np.allclose(noise.stddev, np.sqrt(1e-5)) def test_GaussianProcessRegressionSklearn_3(): """All predictive distributions. Linear noisy function, linear kernel + white noise kernel. The optimized noise level is expected to go to its true value. """ kernel = skl.gaussian_process.kernels.DotProduct( sigma_0=0, sigma_0_bounds="fixed" ) + skl.gaussian_process.kernels.WhiteKernel(noise_level=1, noise_level_bounds=(1e-5, 1e5)) gpr = GaussianProcessRegressionSklearn(kernel=kernel, rng=1) n, nlsd = 100, 0.5 data = smlb.TabularData(data=np.ones(shape=(n, 1)) * 2, labels=np.ones(shape=n) * 3) data = smlb.LabelNoise(noise=smlb.NormalNoise(stddev=nlsd, rng=1)).fit(data).apply(data) preds = gpr.fit(data).apply(data) assert preds.has_signal_part and preds.has_noise_part conf, noise = preds.signal_part, preds.noise_part assert np.allclose(conf.mean, np.ones(n) * 3, atol=1e-1) assert np.allclose(conf.stddev, np.ones(n) * nlsd, atol=1e-1) assert (preds.mean == conf.mean).all() assert np.allclose(preds.stddev, np.sqrt(np.square(conf.stddev) + np.square(nlsd)), atol=1e-1) assert np.allclose(noise.mean, np.zeros(shape=n)) assert np.allclose(noise.stddev, nlsd, atol=1e-1)
test_GaussianProcessRegressionSklearn_2
inviter.py
import json from vcx.api.connection import Connection from utils import init_vcx, run_coroutine_in_new_loop from connection import BaseConnection class Inviter(BaseConnection): async def start(self): await init_vcx() print("Create a connection to alice and print out the invite details") connection_ = await Connection.create('alice') await connection_.connect('{"use_public_did": true}') await connection_.update_state() details = await connection_.invite_details(False) print("**invite details**") print(json.dumps(details)) print("******************") self.connection_data = await connection_.serialize() connection_.release() return json.dumps(details)
def connect(self): run_coroutine_in_new_loop(self.update_state)
file1.go
package level1
func file1Func() bool { return true }
models.py
from django.db import models from django.utils import timezone category_choices = ( ("Essential Services Pass", "Essential Services Pass"), ("Emergency Services Pass", "Emergency Services Pass"),
) subcategory_choices = ( ("ATM/Banking", "ATM/Banking"), ("Delivery Worker", "Delivery Worker"), ("Fruit/Vegetable Vendor","Fruit/Vegetable Vendor"), ("Govt Officials","Govt Officials"), ("Grocery Vendor","Grocery Vendor"), ("Milk Vendor","Milk Vendor"), ("Health Worker","Health Worker"), ("IT/Tele Communication","IT/Tele Communication"), ("Municipal Services","Municipal Services"), ("Power/Electricity","Power/Electricity"), ("Sanitation","Sanitation"), ("Businessman","Businessman"), ) # Create your models here. class PassModel(models.Model): district=models.CharField(max_length=20,null=True) name=models.CharField(max_length=200,null=True) email=models.CharField(max_length=200,null=True) vehiclenumber=models.CharField(max_length=200,null=True) phonenumber=models.CharField(max_length=10,null=True) aadharcardnumber=models.CharField(max_length=12,null=True) address=models.CharField(max_length=200,null=True) reason=models.CharField(max_length=200,null=True) issuedate=models.DateTimeField(default=timezone.now) passcategory=models.CharField(max_length=30,choices = category_choices) subcategory=models.CharField(max_length=30,choices = subcategory_choices) attachphoto=models.ImageField(upload_to='profile_pics') attachidproof=models.ImageField(upload_to='id_proof') uniquenumber=models.CharField(max_length=10000,default=201301) checked=models.BooleanField(default=0)
create.go
package create import ( "strings" "github.com/AlecAivazis/survey/v2" "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/ankitpokhrel/jira-cli/api" "github.com/ankitpokhrel/jira-cli/internal/cmdcommon" "github.com/ankitpokhrel/jira-cli/internal/cmdutil" "github.com/ankitpokhrel/jira-cli/internal/query" "github.com/ankitpokhrel/jira-cli/pkg/jira" "github.com/ankitpokhrel/jira-cli/pkg/surveyext" ) const ( helpText = `Create an epic in a given project with minimal information.` examples = `$ jira epic create # Create epic in the configured project $ jira epic create -n"Epic epic" -s"Everything" -yHigh -lbug -lurgent -b"Bug description" # Create epic in another project $ jira epic create -pPRJ -n"Amazing epic" -yHigh -s"New Bug" -b$'Bug description\n\nSome more text'` ) // NewCmdCreate is a create command. func NewCmdCreate() *cobra.Command
// SetFlags sets flags supported by create command. func SetFlags(cmd *cobra.Command) { cmdcommon.SetCreateFlags(cmd, "Epic") } //nolint:gocyclo // TODO: Reduce cyclomatic complexity. func create(cmd *cobra.Command, _ []string) { server := viper.GetString("server") project := viper.GetString("project") params := parseFlags(cmd.Flags()) client := api.Client(jira.Config{Debug: params.debug}) cc := createCmd{ client: client, params: params, } if cc.isNonInteractive() { cc.params.noInput = true if cc.isMandatoryParamsMissing() { cmdutil.Failed( "Params `--summary` and `--name` is mandatory when using a non-interactive mode", ) } } qs := cc.getQuestions() if len(qs) > 0 { ans := struct{ Name, Summary, Body, Action string }{} err := survey.Ask(qs, &ans) cmdutil.ExitIfError(err) if params.name == "" { params.name = ans.Name } if params.summary == "" { params.summary = ans.Summary } if params.body == "" { params.body = ans.Body } } // TODO: Remove duplicates with issue/create. if !params.noInput { answer := struct{ Action string }{} for answer.Action != cmdcommon.ActionSubmit { err := survey.Ask([]*survey.Question{cmdcommon.GetNextAction()}, &answer) cmdutil.ExitIfError(err) switch answer.Action { case cmdcommon.ActionCancel: cmdutil.Failed("Action aborted") case cmdcommon.ActionMetadata: ans := struct{ Metadata []string }{} err := survey.Ask(cmdcommon.GetMetadata(), &ans) cmdutil.ExitIfError(err) if len(ans.Metadata) > 0 { qs = cmdcommon.GetMetadataQuestions(ans.Metadata) ans := struct { Priority string Labels string Components string }{} err := survey.Ask(qs, &ans) cmdutil.ExitIfError(err) if ans.Priority != "" { params.priority = ans.Priority } if len(ans.Labels) > 0 { params.labels = strings.Split(ans.Labels, ",") } if len(ans.Components) > 0 { params.components = strings.Split(ans.Components, ",") } } } } } key, err := func() (string, error) { s := cmdutil.Info("Creating an epic...") defer s.Stop() resp, err := client.CreateV2(&jira.CreateRequest{ Project: project, IssueType: jira.IssueTypeEpic, Name: params.name, Summary: params.summary, Body: params.body, Priority: params.priority, Labels: params.labels, Components: params.components, EpicFieldName: viper.GetString("epic.field"), }) if err != nil { return "", err } return resp.Key, nil }() cmdutil.ExitIfError(err) cmdutil.Success("Epic created\n%s/browse/%s", server, key) if params.assignee != "" { user, err := api.ProxyUserSearch(client, &jira.UserSearchOptions{ Query: params.assignee, Project: project, }) if err != nil || len(user) == 0 { cmdutil.Failed("Unable to find assignee") } if err = api.ProxyAssignIssue(client, key, user[0], jira.AssigneeDefault); err != nil { cmdutil.Failed("Unable to set assignee: %s", err.Error()) } } if web, _ := cmd.Flags().GetBool("web"); web { err := cmdutil.Navigate(server, key) cmdutil.ExitIfError(err) } } func (cc *createCmd) getQuestions() []*survey.Question { var qs []*survey.Question if cc.params.name == "" { qs = append(qs, &survey.Question{ Name: "name", Prompt: &survey.Input{Message: "Epic name"}, Validate: survey.Required, }) } if cc.params.summary == "" { qs = append(qs, &survey.Question{ Name: "summary", Prompt: &survey.Input{Message: "Summary"}, Validate: survey.Required, }) } var defaultBody string if cc.params.template != "" || cmdutil.StdinHasData() { b, err := cmdutil.ReadFile(cc.params.template) if err != nil { cmdutil.Failed("Error: %s", err) } defaultBody = string(b) } if cc.params.noInput { cc.params.body = defaultBody return qs } if cc.params.body == "" { qs = append(qs, &survey.Question{ Name: "body", Prompt: &surveyext.JiraEditor{ Editor: &survey.Editor{ Message: "Description", Default: defaultBody, HideDefault: true, AppendDefault: true, }, BlankAllowed: true, }, }) } return qs } type createCmd struct { client *jira.Client issueTypes []*jira.IssueType params *createParams } func (cc *createCmd) isNonInteractive() bool { return cmdutil.StdinHasData() || cc.params.template == "-" } func (cc *createCmd) isMandatoryParamsMissing() bool { return cc.params.summary == "" || cc.params.name == "" } type createParams struct { name string summary string body string priority string assignee string labels []string components []string template string noInput bool debug bool } func parseFlags(flags query.FlagParser) *createParams { name, err := flags.GetString("name") cmdutil.ExitIfError(err) summary, err := flags.GetString("summary") cmdutil.ExitIfError(err) body, err := flags.GetString("body") cmdutil.ExitIfError(err) priority, err := flags.GetString("priority") cmdutil.ExitIfError(err) assignee, err := flags.GetString("assignee") cmdutil.ExitIfError(err) labels, err := flags.GetStringArray("label") cmdutil.ExitIfError(err) components, err := flags.GetStringArray("component") cmdutil.ExitIfError(err) template, err := flags.GetString("template") cmdutil.ExitIfError(err) noInput, err := flags.GetBool("no-input") cmdutil.ExitIfError(err) debug, err := flags.GetBool("debug") cmdutil.ExitIfError(err) return &createParams{ name: name, summary: summary, body: body, priority: priority, assignee: assignee, labels: labels, components: components, template: template, noInput: noInput, debug: debug, } }
{ return &cobra.Command{ Use: "create", Short: "Create an epic in a project", Long: helpText, Example: examples, Run: create, } }
orderDetails.js
const Sequelize = require('sequelize') const db = require('../db') const OrderDetail = db.define('orderDetail', { name: { type: Sequelize.STRING, allowNull: false }, price: { type: Sequelize.INTEGER, allowNull: false, validate: {
min: 0 } }, quantity: { type: Sequelize.INTEGER, allowNull: false, validate: { min: 0 } } }) module.exports = OrderDetail
window.min.js
/*! * global/window.min.js * https://github.com/RobinHerbots/Inputmask * Copyright (c) 2010 - 2017 Robin Herbots
*/ "function"==typeof define&&define.amd?define(function(){return window}):"object"==typeof exports&&(module.exports=window);
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) * Version: 3.3.8-5
get_ping.go
// Code generated by go-swagger; DO NOT EDIT. package ping // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the generate command import ( "net/http" middleware "github.com/go-openapi/runtime/middleware" ) // GetPingHandlerFunc turns a function with the right signature into a get ping handler type GetPingHandlerFunc func(GetPingParams, interface{}) middleware.Responder // Handle executing the request and returning a response func (fn GetPingHandlerFunc) Handle(params GetPingParams, principal interface{}) middleware.Responder { return fn(params, principal) } // GetPingHandler interface for that can handle valid get ping params type GetPingHandler interface { Handle(GetPingParams, interface{}) middleware.Responder } // NewGetPing creates a new http.Handler for the get ping operation func
(ctx *middleware.Context, handler GetPingHandler) *GetPing { return &GetPing{Context: ctx, Handler: handler} } /*GetPing swagger:route GET /ping ping getPing Ping Harbor to check if it's alive. This API simply replies a pong to indicate the process to handle API is up, disregarding the health status of dependent components. */ type GetPing struct { Context *middleware.Context Handler GetPingHandler } func (o *GetPing) ServeHTTP(rw http.ResponseWriter, r *http.Request) { route, rCtx, _ := o.Context.RouteInfo(r) if rCtx != nil { r = rCtx } var Params = NewGetPingParams() uprinc, aCtx, err := o.Context.Authorize(r, route) if err != nil { o.Context.Respond(rw, r, route.Produces, route, err) return } if aCtx != nil { r = aCtx } var principal interface{} if uprinc != nil { principal = uprinc } if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params o.Context.Respond(rw, r, route.Produces, route, err) return } res := o.Handler.Handle(Params, principal) // actually handle the request o.Context.Respond(rw, r, route.Produces, route, res) }
NewGetPing
issue-95307.rs
// edition:2018 // Regression test for #95307. // The ICE occurred on all the editions, specifying edition:2018 to reduce diagnostics. pub trait C { async fn new() -> [u8; _]; //~^ ERROR: functions in traits cannot be declared `async` //~| ERROR: using `_` for array lengths is unstable //~| ERROR: in expressions, `_` can only be used on the left-hand side of an assignment } fn main()
{}
validation.js
module.exports = {
cmdName: name => /^[a-z][a-z0-9\-_]{2,}$/i.test(name) && name.indexOf('-') !== -1, uiName: name => /^[a-z][a-z0-9]+$/i.test(name) || 'The name can only contain alphanumeric characters and cannot start with a number', routeName: name => /^[a-z]+$/i.test(name) || 'The name can only contain alphabetic characters', };
folder-edit.directive.spec.ts
/*! * @license * Copyright 2019 Alfresco Software, Ltd. * * 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 the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { Component } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { MatDialog } from '@angular/material/dialog'; import { By } from '@angular/platform-browser'; import { Subject, of } from 'rxjs'; import { ContentService, setupTestBed } from '@alfresco/adf-core'; import { FolderEditDirective } from './folder-edit.directive'; import { Node } from '@alfresco/js-api'; import { ContentTestingModule } from '../testing/content.testing.module'; import { TranslateModule } from '@ngx-translate/core'; @Component({ template: '<div [adf-edit-folder]="folder" (success)="success($event)" title="edit-title"></div>' }) class
{ folder = {}; public successParameter: Node = null; success(node: Node) { this.successParameter = node; } } describe('FolderEditDirective', () => { let fixture: ComponentFixture<TestComponent>; let element; let dialog: MatDialog; let contentService: ContentService; let dialogRefMock; const event = { type: 'click', preventDefault: () => null }; setupTestBed({ imports: [ TranslateModule.forRoot(), ContentTestingModule ], declarations: [ TestComponent ] }); beforeEach(() => { fixture = TestBed.createComponent(TestComponent); element = fixture.debugElement.query(By.directive(FolderEditDirective)); dialog = TestBed.inject(MatDialog); contentService = TestBed.inject(ContentService); }); beforeEach(() => { dialogRefMock = { afterClosed: (val) => of(val), componentInstance: { error: new Subject<any>(), success: new Subject<Node>() } }; spyOn(dialog, 'open').and.returnValue(dialogRefMock); }); it('should not emit folderEdit event when input value is undefined', async () => { spyOn(dialogRefMock, 'afterClosed').and.returnValue(of(null)); spyOn(contentService.folderEdit, 'next'); fixture.detectChanges(); await fixture.whenStable(); element.nativeElement.click(); expect(contentService.folderEdit.next).not.toHaveBeenCalled(); }); it('should emit success event with node if the folder creation was successful', async () => { fixture.detectChanges(); const testNode = <Node> {}; element.triggerEventHandler('click', event); dialogRefMock.componentInstance.success.next(testNode); fixture.detectChanges(); await fixture.whenStable(); expect(fixture.componentInstance.successParameter).toBe(testNode); }); it('should open the dialog with the proper title', async () => { fixture.detectChanges(); element.triggerEventHandler('click', event); await fixture.whenStable(); expect(dialog.open).toHaveBeenCalledWith(jasmine.any(Function), { data: { folder: jasmine.any(Object), editTitle: 'edit-title' }, width: jasmine.any(String) }); }); });
TestComponent
is_valid.py
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
np = ak.nplike.NumpyMetadata.instance() def is_valid(array, exception=False): pass # """ # Args: # array (#ak.Array, #ak.Record, #ak.layout.Content, #ak.layout.Record, #ak.ArrayBuilder, #ak.layout.ArrayBuilder): # Array or record to check. # exception (bool): If True, validity errors raise exceptions. # Returns True if there are no errors and False if there is an error. # Checks for errors in the structure of the array, such as indexes that run # beyond the length of a node's `content`, etc. Either an error is raised or # the function returns a boolean. # See also #ak.validity_error. # """ # out = validity_error(array, exception=exception) # return out is None
from __future__ import absolute_import import awkward as ak
tool.py
from coldtype.geometry.rect import Rect def
(inputs, defaults): defaults["rect"] = [ Rect(1080, 1080), lambda xs: Rect([int(x) for x in xs.split(",")])] defaults["preview_only"] = [False, bool] defaults["log"] = [False, bool] parsed = {} if not isinstance(inputs, dict): for input in inputs: k, v = input.split("=") parsed[k] = v else: parsed = {**inputs} out = {} for k, v in defaults.items(): if k in ["w", "h"]: out[k] = v defaults[k] = [v, int] else: out[k] = v[0] if k not in parsed and len(v) > 2: raise Exception(v[2]) for k, v in parsed.items(): if k in defaults: if defaults[k][0] is None and v is None: pass else: if isinstance(v, str): if defaults[k][1] == bool: out[k] = bool(eval(v)) else: out[k] = defaults[k][1](v) else: if k == "rect": out[k] = Rect(v) else: out[k] = v else: print(f"> key {k} not recognized") return out
parse_inputs
model_test.go
package csv2dynamo import ( "github.com/google/go-cmp/cmp" "reflect" "testing" ) func TestCopy(t *testing.T) { d := DynamoInput{ DynamoData{ Key: "SKey", Type: "S", Val: "", }, } cp := d.Copy() if diff := cmp.Diff(d, cp); diff != "" { t.Fatalf("copied obj mismatch (-data +copy):\n%s", diff) } if reflect.ValueOf(d).Pointer() == reflect.ValueOf(cp).Pointer() { t.Fatalf("Copy is not shallow copy") } } func Test_DynamoInput_ToJsonString(t *testing.T) { tests := []struct { name string in DynamoInput execute bool want string }{ { name: `single value "S"`, in: DynamoInput{ DynamoData{ Key: `key_S"`, Type: `"S"`, Val: "val_S", }, }, execute: false, want: `'{"key_S":{"S":"val_S"}}'`, }, { name: `single value "N"`, in: DynamoInput{ DynamoData{ Key: `key_N"`, Type: `"N"`, Val: "1", }, }, execute: false, want: `'{"key_N":{"N":"1"}}'`, }, { name: `single value "BOOL"`, in: DynamoInput{ DynamoData{ Key: `key_BOOL"`, Type: `"BOOL"`, Val: "true", }, }, execute: false, want: `'{"key_BOOL":{"BOOL":true}}'`, }, { name: `multiple value`, in: DynamoInput{ DynamoData{ Key: `key_S"`, Type: `"S"`, Val: "val_S", }, DynamoData{ Key: `key_N"`, Type: `"N"`, Val: "1", }, DynamoData{ Key: `key_BOOL"`, Type: `"BOOL"`, Val: "true", }, DynamoData{ Key: `empty"`, Type: `"S"`, Val: "", }, }, execute: false, want: `'{"key_S":{"S":"val_S"},"key_N":{"N":"1"},"key_BOOL":{"BOOL":true}}'`, }, { name: `output for dirext execute`, in: DynamoInput{ DynamoData{ Key: `key_S"`, Type: `"S"`, Val: "val_S", }, DynamoData{ Key: `key_N"`, Type: `"N"`, Val: "1", }, DynamoData{ Key: `key_BOOL"`, Type: `"BOOL"`, Val: "true", }, }, execute: true, want: `{"key_S":{"S":"val_S"},"key_N":{"N":"1"},"key_BOOL":{"BOOL":true}}`, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := tt.in.ToJsonString(tt.execute) if diff := cmp.Diff(got, tt.want); diff != "" { t.Errorf("json string mismatch (-got +want):\n%s", diff)
} }) } }
modules.py
import base64 import hashlib import json import logging import os import shutil import tempfile from collections import defaultdict from threading import Lock from uuid import uuid4 from bottle import response, static_file from weavelib.exceptions import BadArguments from weavelib.rpc import RPCClient, find_rpc from weavelib.rpc import RPCServer, ServerAPI, ArgParameter, get_rpc_caller logger = logging.getLogger(__name__) def get_required_argument(obj, key): try: return obj[key] except KeyError: raise BadArguments(key) def jsonify_response(code, result): response.status = code response.content_type = 'application/json' if int(code / 100) == 2: return json.dumps({"status": "ok", "data": result}) elif int(code / 100) in (4, 5): return json.dumps({"status": "error", "message": result}) return json.dumps(result) class BaseHTTPModule(object): def transform_response(self, code, response): response.status = code if int(code / 100) == 2: return response elif int(code / 100) == 4: return "Client Error {}: {}".format(code, response) elif int(code / 100) == 5: return "Internal Error {}: {}".format(code, response) class RPCModule(BaseHTTPModule): def __init__(self, service): self.service = service self.clients = {} self.clients_lock = Lock() def start(self): pass def stop(self): with self.clients_lock: for client in self.clients.values(): client.stop() def get_registrations(self): return [("POST", "", self.handle_rpc)] def handle_rpc(self, body): app_url = get_required_argument(body, 'app_url') rpc_name = get_required_argument(body, 'rpc_name') api_name = get_required_argument(body, 'api_name') args = get_required_argument(body, 'args') with self.clients_lock: client = self.clients.get((app_url, rpc_name), None) if not client: rpc_info = find_rpc(self.service, app_url, rpc_name) with self.clients_lock: client = self.clients.get((app_url, rpc_name), None) if not client: client = RPCClient(self.service.get_connection(), rpc_info, self.service.get_auth_token()) client.start() self.clients[(app_url, rpc_name)] = client response = client[api_name](*args, _block=True) return response def transform_response(self, code, response): return jsonify_response(code, response) class StaticFileModule(BaseHTTPModule): def __init__(self, service): self.base_dir = tempfile.mkdtemp() self.rpc = RPCServer("static_files", "HTTP Registry", [ ServerAPI("register", "Register a resource.", [ ArgParameter("filename", "File name.", str), ArgParameter("content", "Base64 content", str), ], self.register), ServerAPI("unregister", "Unregister a resource", [ ArgParameter("filename", "File name", str) ], self.unregister), ], service) self.pseudo_app_id_map = defaultdict(lambda: str(uuid4())) self.pseudo_app_id_map_lock = Lock() def start(self): logger.info("Using base dir for HTTP: %s", self.base_dir) self.rpc.start() def stop(self): self.rpc.stop() shutil.rmtree(self.base_dir) def get_registrations(self):
("GET", "/", lambda x: self.handle_static(x, "/index.html")), ("GET", "<path:path>", self.handle_static), ] def url_to_app_id(self, app_url): return hashlib.md5(app_url.encode('utf-8')).hexdigest() def register(self, filename, content): decoded = base64.b64decode(content) app_info = get_rpc_caller() app_id = self.url_to_app_id(app_info["app_url"]) pseudo_id = self.get_pseudo_app_id(app_id) rel_path = os.path.join("apps", pseudo_id, filename.lstrip('/')) full_path = self.get_absolute_path(rel_path, filename) self.write_file(full_path, decoded) return rel_path def unregister(self, filename): app_info = get_rpc_caller() app_id = self.url_to_app_id(app_info["app_url"]) pseudo_id = self.get_pseudo_app_id(app_id) rel_path = os.path.join("apps", pseudo_id, filename.lstrip('/')) full_path = self.get_absolute_path(rel_path, filename) if os.path.isdir(full_path): shutil.rmtree(full_path) elif os.path.isfile(full_path): os.unlink(full_path) def write_file(self, full_path, content): try: os.makedirs(os.path.dirname(full_path)) except: pass with open(full_path, "wb") as out: out.write(content) def get_absolute_path(self, rel_path, filename): full_path = os.path.join(self.base_dir, rel_path) norm_path = os.path.normpath(full_path) if norm_path.startswith(self.base_dir): return norm_path raise BadArguments(filename) def handle_static(self, params, path): return static_file(path, root=os.path.join(self.base_dir)) def transform_response(self, code, result): return result def get_pseudo_app_id(self, app_id): with self.pseudo_app_id_map_lock: return self.pseudo_app_id_map[app_id]
return [
EnableUserService.js
const AppError = require('../../../../../shared/errors/AppError'); const usersRepository = require('../../repositories/UsersRepository') class
{ constructor() { } async execute(user) { const foundUser = await usersRepository.searchByUser(user) if (!foundUser) { throw new AppError(404, `The user ${user} does not exists!`); }; const userAccountControl = 512 const enableUser = await usersRepository.enable(foundUser.dn, { userAccountControl }); if (!enableUser) { throw new AppError(500, `The user ${user} cannot be enable!`); }; return enableUser } } module.exports = new EnableUserService;
EnableUserService
test_unsteady_ring_vortex_lattice_method_static_geometry.py
"""This is a testing case for the unsteady ring vortex lattice method solver with static geometry. Based on an equivalent XFLR5 testing case, the expected output for this case is: CL: 0.588 CDi: 0.011 Cm: -0.197 Note: The expected output was created using XFLR5's inviscid VLM2 analysis type, which is a ring vortex lattice method solver. The geometry in this case is static. Therefore the results of this unsteady solver should converge to be close to XFLR5's static result. This module contains the following classes: TestUnsteadyRingVortexLatticeMethodStaticGeometry: This is a class for testing the unsteady ring vortex lattice method solver on static geometry. This module contains the following exceptions: None This module contains the following functions: None """ import unittest import pterasoftware as ps from tests.integration.fixtures import solver_fixtures class TestUnsteadyRingVortexLatticeMethodStaticGeometry(unittest.TestCase): """This is a class for testing the unsteady ring vortex lattice method solver on static geometry. This class contains the following public methods: setUp: This method sets up the test. tearDown: This method tears down the test. test_method: This method tests the solver's output. This class contains the following class attributes: None Subclassing: This class is not meant to be subclassed. """ def setUp(self): """This method sets up the test. :return: None """
# Create the unsteady method solver. self.unsteady_ring_vortex_lattice_method_validation_solver = ( solver_fixtures.make_unsteady_ring_vortex_lattice_method_validation_solver_with_static_geometry() ) def tearDown(self): """This method tears down the test. :return: None """ del self.unsteady_ring_vortex_lattice_method_validation_solver def test_method(self): """This method tests the solver's output. :return: None """ # Run the solver. self.unsteady_ring_vortex_lattice_method_validation_solver.run( prescribed_wake=True ) this_solver = self.unsteady_ring_vortex_lattice_method_validation_solver this_airplane = this_solver.current_airplanes[0] # Calculate the percent errors of the output. c_di_expected = 0.011 c_di_calculated = this_airplane.total_near_field_force_coefficients_wind_axes[0] c_di_error = abs(c_di_calculated - c_di_expected) / c_di_expected c_l_expected = 0.588 c_l_calculated = this_airplane.total_near_field_force_coefficients_wind_axes[2] c_l_error = abs(c_l_calculated - c_l_expected) / c_l_expected c_m_expected = -0.197 c_m_calculated = this_airplane.total_near_field_moment_coefficients_wind_axes[1] c_m_error = abs(c_m_calculated - c_m_expected) / c_m_expected # Set the allowable percent error. allowable_error = 0.10 ps.output.animate( unsteady_solver=self.unsteady_ring_vortex_lattice_method_validation_solver, show_wake_vortices=True, show_delta_pressures=True, keep_file=False, ) ps.output.plot_results_versus_time( unsteady_solver=self.unsteady_ring_vortex_lattice_method_validation_solver ) # Assert that the percent errors are less than the allowable error. self.assertTrue(abs(c_di_error) < allowable_error) self.assertTrue(abs(c_l_error) < allowable_error) self.assertTrue(abs(c_m_error) < allowable_error)
trillian_map_api.pb.gw.go
// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. // source: trillian_map_api.proto /* Package trillian is a reverse proxy. It translates gRPC into RESTful JSON APIs. */ package trillian import ( "context" "io" "net/http" "github.com/golang/protobuf/proto" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/grpc-ecosystem/grpc-gateway/utilities" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/status" ) var _ codes.Code var _ io.Reader var _ status.Status var _ = runtime.String var _ = utilities.NewDoubleArray var ( filter_TrillianMap_GetLastInRangeByRevision_0 = &utilities.DoubleArray{Encoding: map[string]int{"map_id": 0, "revision": 1}, Base: []int{1, 1, 2, 0, 0}, Check: []int{0, 1, 1, 2, 3}} ) func request_TrillianMap_GetLastInRangeByRevision_0(ctx context.Context, marshaler runtime.Marshaler, client TrillianMapClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq GetLastInRangeByRevisionRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["map_id"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "map_id") } protoReq.MapId, err = runtime.Int64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "map_id", err) } val, ok = pathParams["revision"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "revision") } protoReq.Revision, err = runtime.Int64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "revision", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_TrillianMap_GetLastInRangeByRevision_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.GetLastInRangeByRevision(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func request_TrillianMap_GetSignedMapRoot_0(ctx context.Context, marshaler runtime.Marshaler, client TrillianMapClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq GetSignedMapRootRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["map_id"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "map_id") } protoReq.MapId, err = runtime.Int64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "map_id", err) } msg, err := client.GetSignedMapRoot(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func request_TrillianMap_GetSignedMapRootByRevision_0(ctx context.Context, marshaler runtime.Marshaler, client TrillianMapClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq GetSignedMapRootByRevisionRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["map_id"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "map_id") } protoReq.MapId, err = runtime.Int64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "map_id", err) } val, ok = pathParams["revision"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "revision") } protoReq.Revision, err = runtime.Int64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "revision", err) } msg, err := client.GetSignedMapRootByRevision(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err
func request_TrillianMap_InitMap_0(ctx context.Context, marshaler runtime.Marshaler, client TrillianMapClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq InitMapRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["map_id"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "map_id") } protoReq.MapId, err = runtime.Int64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "map_id", err) } msg, err := client.InitMap(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } // RegisterTrillianMapHandlerFromEndpoint is same as RegisterTrillianMapHandler but // automatically dials to "endpoint" and closes the connection when "ctx" gets done. func RegisterTrillianMapHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { conn, err := grpc.Dial(endpoint, opts...) if err != nil { return err } defer func() { if err != nil { if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } return } go func() { <-ctx.Done() if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } }() }() return RegisterTrillianMapHandler(ctx, mux, conn) } // RegisterTrillianMapHandler registers the http handlers for service TrillianMap to "mux". // The handlers forward requests to the grpc endpoint over "conn". func RegisterTrillianMapHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterTrillianMapHandlerClient(ctx, mux, NewTrillianMapClient(conn)) } // RegisterTrillianMapHandlerClient registers the http handlers for service TrillianMap // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "TrillianMapClient". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "TrillianMapClient" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in // "TrillianMapClient" to call the correct interceptors. func RegisterTrillianMapHandlerClient(ctx context.Context, mux *runtime.ServeMux, client TrillianMapClient) error { mux.Handle("GET", pattern_TrillianMap_GetLastInRangeByRevision_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_TrillianMap_GetLastInRangeByRevision_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_TrillianMap_GetLastInRangeByRevision_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_TrillianMap_GetSignedMapRoot_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_TrillianMap_GetSignedMapRoot_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_TrillianMap_GetSignedMapRoot_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_TrillianMap_GetSignedMapRootByRevision_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_TrillianMap_GetSignedMapRootByRevision_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_TrillianMap_GetSignedMapRootByRevision_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_TrillianMap_InitMap_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_TrillianMap_InitMap_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_TrillianMap_InitMap_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } var ( pattern_TrillianMap_GetLastInRangeByRevision_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5}, []string{"v1beta1", "maps", "map_id", "roots", "revision", "leaves"}, "last_in_range")) pattern_TrillianMap_GetSignedMapRoot_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3}, []string{"v1beta1", "maps", "map_id", "roots"}, "latest")) pattern_TrillianMap_GetSignedMapRootByRevision_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"v1beta1", "maps", "map_id", "roots", "revision"}, "")) pattern_TrillianMap_InitMap_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"v1beta1", "maps", "map_id"}, "init")) ) var ( forward_TrillianMap_GetLastInRangeByRevision_0 = runtime.ForwardResponseMessage forward_TrillianMap_GetSignedMapRoot_0 = runtime.ForwardResponseMessage forward_TrillianMap_GetSignedMapRootByRevision_0 = runtime.ForwardResponseMessage forward_TrillianMap_InitMap_0 = runtime.ForwardResponseMessage )
}
transformer.py
# File : transformer.py # Author : Zhengkun Tian # Email : [email protected] import logging import torch import torch.nn as nn from otrans.module.pos import MixedPositionalEncoding, RelPositionalEncoding from otrans.module.ffn import PositionwiseFeedForward from otrans.module.attention import MultiHeadedSelfAttention, MultiHeadedSelfAttentionWithRelPos logger = logging.getLogger(__name__) class TransformerEncoderLayer(nn.Module):
class TransformerEncoder(nn.Module): def __init__(self, d_model=256, n_heads=4, d_ff=2048, n_blocks=6, pos_dropout=0.0, slf_attn_dropout=0.0, ffn_dropout=0.0, residual_dropout=0.1, normalize_before=False, concat_after=False, relative_positional=False, activation='relu'): super(TransformerEncoder, self).__init__() self.normalize_before = normalize_before self.relative_positional = relative_positional if self.relative_positional: self.pos_emb = RelPositionalEncoding(d_model, pos_dropout) else: self.pos_emb = MixedPositionalEncoding(d_model, pos_dropout) self.blocks = nn.ModuleList([ TransformerEncoderLayer( n_heads, d_model, d_ff, slf_attn_dropout, ffn_dropout, residual_dropout=residual_dropout, normalize_before=normalize_before, concat_after=concat_after, relative_positional=relative_positional, activation=activation) for _ in range(n_blocks) ]) if self.normalize_before: self.norm = nn.LayerNorm(d_model) def forward(self, inputs, mask): enc_output, pos = self.pos_emb(inputs) enc_output.masked_fill_(~mask.unsqueeze(2), 0.0) attn_weights = {} for i, block in enumerate(self.blocks): enc_output, attn_weight = block(enc_output, mask.unsqueeze(1), pos) attn_weights['enc_block_%d' % i] = attn_weight if self.normalize_before: enc_output = self.norm(enc_output) return enc_output, mask, attn_weights def inference(self, inputs, mask, cache=None): enc_output, pos = self.pos_emb.inference(inputs) enc_output.masked_fill_(~mask.unsqueeze(2), 0.0) attn_weights = {} new_caches = [] for i, block in enumerate(self.blocks): enc_output, new_cache, attn_weight = block.inference(enc_output, mask.unsqueeze(1), pos, cache) attn_weights['enc_block_%d' % i] = attn_weight new_caches.append(new_cache) if self.normalize_before: enc_output = self.norm(enc_output) return enc_output, mask, new_caches, attn_weights
def __init__(self, n_heads, d_model, d_ff, slf_attn_dropout, ffn_dropout, residual_dropout, normalize_before=False, concat_after=False, relative_positional=False, activation='relu'): super(TransformerEncoderLayer, self).__init__() self.relative_positional = relative_positional if self.relative_positional: self.slf_attn = MultiHeadedSelfAttentionWithRelPos(n_heads, d_model, slf_attn_dropout) else: self.slf_attn = MultiHeadedSelfAttention(n_heads, d_model, slf_attn_dropout) self.feed_forward = PositionwiseFeedForward(d_model, d_ff, ffn_dropout, activation) self.norm1 = nn.LayerNorm(d_model) self.norm2 = nn.LayerNorm(d_model) self.dropout1 = nn.Dropout(residual_dropout) self.dropout2 = nn.Dropout(residual_dropout) self.normalize_before = normalize_before self.concat_after = concat_after if self.concat_after: self.concat_linear = nn.Linear(d_model * 2, d_model) def forward(self, x, mask, pos=None): if self.normalize_before: x = self.norm1(x) residual = x if self.relative_positional: slf_attn_out, slf_attn_weights = self.slf_attn(x, mask, pos) else: slf_attn_out, slf_attn_weights = self.slf_attn(x, mask) if self.concat_after: x = residual + self.concat_linear(torch.cat((x, slf_attn_out), dim=-1)) else: x = residual + self.dropout1(slf_attn_out) if not self.normalize_before: x = self.norm1(x) if self.normalize_before: x = self.norm2(x) residual = x x = residual + self.dropout2(self.feed_forward(x)) if not self.normalize_before: x = self.norm2(x) return x, {'slf_attn_weights': slf_attn_weights} def inference(self, x, mask, pos=None, cache=None): if self.normalize_before: x = self.norm1(x) residual = x if self.relative_positional: slf_attn_out, slf_attn_weights, new_cache = self.slf_attn.inference(x, mask, cache, pos) else: slf_attn_out, slf_attn_weights, new_cache = self.slf_attn.inference(x, mask, cache) if self.concat_after: x = residual + self.concat_linear(torch.cat((x, slf_attn_out), dim=-1)) else: x = residual + slf_attn_out if not self.normalize_before: x = self.norm1(x) if self.normalize_before: x = self.norm2(x) residual = x x = residual + self.feed_forward(x) if not self.normalize_before: x = self.norm2(x) return x, new_cache, {'slf_attn_weights': slf_attn_weights}
decoder.rs
use core::{ pin::Pin, task::{Context, Poll}, }; use std::io::Result; use crate::{codec::Decode, util::PartialBuffer}; use futures_core::ready; use pin_project_lite::pin_project; use tokio_03::io::{AsyncBufRead, AsyncRead, ReadBuf}; #[derive(Debug)] enum State { Decoding, Flushing, Done, Next, } pin_project! { #[derive(Debug)] pub struct Decoder<R, D: Decode> { #[pin] reader: R, decoder: D, state: State, multiple_members: bool, } } impl<R: AsyncBufRead, D: Decode> Decoder<R, D> { pub fn new(reader: R, decoder: D) -> Self { Self { reader, decoder, state: State::Decoding, multiple_members: false, } } pub fn get_ref(&self) -> &R { &self.reader } pub fn get_mut(&mut self) -> &mut R { &mut self.reader } pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut R> { self.project().reader } pub fn into_inner(self) -> R { self.reader } pub fn multiple_members(&mut self, enabled: bool) { self.multiple_members = enabled; } fn do_poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, output: &mut PartialBuffer<&mut [u8]>, ) -> Poll<Result<()>> { let mut this = self.project(); loop { *this.state = match this.state { State::Decoding => { let input = ready!(this.reader.as_mut().poll_fill_buf(cx))?; if input.is_empty() { // Avoid attempting to reinitialise the decoder if the reader // has returned EOF. *this.multiple_members = false; State::Flushing } else { let mut input = PartialBuffer::new(input); let done = this.decoder.decode(&mut input, output)?; let len = input.written().len(); this.reader.as_mut().consume(len); if done { State::Flushing } else { State::Decoding } } } State::Flushing => { if this.decoder.finish(output)? { if *this.multiple_members { this.decoder.reinit()?; State::Next } else { State::Done } } else { State::Flushing } } State::Done => State::Done, State::Next => { let input = ready!(this.reader.as_mut().poll_fill_buf(cx))?; if input.is_empty() { State::Done } else { State::Decoding } } }; if let State::Done = *this.state { return Poll::Ready(Ok(())); } if output.unwritten().is_empty() { return Poll::Ready(Ok(())); } } } } impl<R: AsyncBufRead, D: Decode> AsyncRead for Decoder<R, D> { fn
( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<Result<()>> { if buf.remaining() == 0 { return Poll::Ready(Ok(())); } let mut output = PartialBuffer::new(buf.initialize_unfilled()); match self.do_poll_read(cx, &mut output)? { Poll::Pending if output.written().is_empty() => Poll::Pending, _ => { let len = output.written().len(); buf.advance(len); Poll::Ready(Ok(())) } } } }
poll_read
test_plot.py
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2017, Anaconda, Inc. All rights reserved. # # Powered by the Bokeh Development Team. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- import pytest ; pytest #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Standard library imports import time # Bokeh imports from bokeh.layouts import column from bokeh.models import Button, Plot, Range1d #----------------------------------------------------------------------------- # Tests #----------------------------------------------------------------------------- pytest_plugins = ( "bokeh._testing.plugins.project", ) @pytest.mark.integration @pytest.mark.selenium class Test_Plot(object): def test_inner_dims_trigger_on_dynamic_add(self, bokeh_server_page): data = {} def modify_doc(doc): p1 = Plot(plot_height=400, plot_width=400, x_range=Range1d(0, 1), y_range=Range1d(0, 1), min_border=10) p2 = Plot(plot_height=400, plot_width=400, x_range=Range1d(0, 1), y_range=Range1d(0, 1), min_border=10) button = Button(css_classes=['foo']) layout = column(p1, button) def cb(event): if p2 not in layout.children:
button.on_event('button_click', cb) def iw(attr, old, new): data['iw'] = (old, new) def ih(attr, old, new): data['ih'] = (old, new) p2.on_change('inner_width', iw) p2.on_change('inner_height', ih) doc.add_root(layout) page = bokeh_server_page(modify_doc) button = page.driver.find_element_by_css_selector('.foo .bk-btn') button.click() # updates can take some time time.sleep(0.5) assert data['iw'][0] is None assert isinstance(data['iw'][1], int) assert data['iw'][1]< 400 assert data['ih'][0] is None assert isinstance(data['ih'][1], int) assert data['ih'][1] < 400 # XXX (bev) disabled until https://github.com/bokeh/bokeh/issues/7970 is resolved #assert page.has_no_console_errors()
layout.children = [p1, button, p2]
connectivitycertscontroller.go
package main import ( "os" "github.com/kyma-project/kyma/components/connectivity-certs-controller/internal/certificates" "github.com/kyma-project/kyma/components/connectivity-certs-controller/internal/connectorservice" "github.com/kyma-project/kyma/components/connectivity-certs-controller/internal/controller/certificaterequest" "github.com/kyma-project/kyma/components/connectivity-certs-controller/internal/secrets" "github.com/kyma-project/kyma/components/connectivity-certs-controller/pkg/apis/applicationconnector/v1alpha1" "github.com/pkg/errors" "k8s.io/client-go/kubernetes" log "github.com/sirupsen/logrus" restclient "k8s.io/client-go/rest" _ "k8s.io/client-go/plugin/pkg/client/auth/gcp" "sigs.k8s.io/controller-runtime/pkg/client/config" "sigs.k8s.io/controller-runtime/pkg/manager" "sigs.k8s.io/controller-runtime/pkg/runtime/signals" ) func main() { log.Info("Starting Certificates Manager.") options := parseArgs() log.Infof("Options: %s", options) // Get a config to talk to the apiserver log.Info("Setting up client for manager") cfg, err := config.GetConfig() if err != nil { log.Error(err, "Unable to set up client config")
} // Create a new Cmd to provide shared dependencies and start components log.Info("Setting up manager") mgr, err := manager.New(cfg, manager.Options{}) if err != nil { log.Error(err, "Unable to set up overall controller manager") os.Exit(1) } log.Info("Registering Components.") secretsRepository, err := newSecretsRepository(options.namespace) if err != nil { log.Errorf("Failed to initialize secret repository, %s", err.Error()) return } // Setup Scheme for all resources log.Info("Setting up scheme") if err := v1alpha1.AddToScheme(mgr.GetScheme()); err != nil { log.Error(err, "Unable add APIs to scheme") os.Exit(1) } csrProvider := certificates.NewCSRProvider(options.clusterCertificatesSecret, options.caCertificatesSecret, secretsRepository) certPreserver := certificates.NewCertificatePreserver(options.clusterCertificatesSecret, options.caCertificatesSecret, secretsRepository) connectorClient := connectorservice.NewConnectorClient(csrProvider) // Setup Certificate Request Controller log.Info("Setting up controller") if err := certificaterequest.InitCertificatesRequestController(mgr, options.appName, connectorClient, certPreserver); err != nil { log.Error(err, "Unable to register controllers to the manager") os.Exit(1) } // Start the Cmd log.Info("Starting the Cmd.") if err := mgr.Start(signals.SetupSignalHandler()); err != nil { log.Error(err, "Unable to run the manager") os.Exit(1) } } func newSecretsRepository(namespace string) (secrets.Repository, error) { k8sConfig, err := restclient.InClusterConfig() if err != nil { return nil, errors.Wrap(err, "Failed to read in cluster Kubernetes config") } coreClientset, err := kubernetes.NewForConfig(k8sConfig) if err != nil { return nil, errors.Wrap(err, "Failed to initialize core clientset") } sei := coreClientset.CoreV1().Secrets(namespace) return secrets.NewRepository(sei), nil }
os.Exit(1)
test_qmc.py
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # 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 the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import pytest from scipy.stats import norm import pennylane as qml from pennylane.templates.subroutines.qmc import ( QuantumMonteCarlo, _make_V, _make_Z, func_to_unitary, make_Q, probs_to_unitary, ) from pennylane.wires import Wires class TestProbsToUnitary: """Tests for the probs_to_unitary function""" def test_invalid_distribution_sum_to_not_one(self): """Test if a ValueError is raised when a distribution that does not sum to one is input""" p = np.ones(4) with pytest.raises(ValueError, match="A valid probability distribution of non-negative"): probs_to_unitary(p) def test_invalid_distribution_negative(self): """Test if a ValueError is raised when a distribution with a negative value is input""" p = [2, 0, 0, -1] with pytest.raises(ValueError, match="A valid probability distribution of non-negative"): probs_to_unitary(p) ps = [ [0.46085261032920616, 0.5391473896707938], [0.2111821738452515, 0.4235979103670337, 0.36521991578771484], [0.3167916924190049, 0.2651843704361695, 0.1871934980886578, 0.23083043905616774], [0.8123242419241959, 0.07990911578859018, 0.07983919018902215, 0.027927452098191852], ] @pytest.mark.parametrize("p", ps) def test_fixed_examples(self, p): """Test if the correct unitary is returned for fixed input examples. A correct unitary has its first column equal to the square root of the distribution and satisfies U @ U.T = U.T @ U = I.""" unitary = probs_to_unitary(p) assert np.allclose(np.sqrt(p), unitary[:, 0]) assert np.allclose(unitary @ unitary.T, np.eye(len(unitary))) assert np.allclose(unitary.T @ unitary, np.eye(len(unitary))) class TestFuncToUnitary: """Tests for the func_to_unitary function""" def test_not_bounded_func(self): """Test if a ValueError is raised if a function that evaluates outside of the [0, 1] interval is provided""" func = lambda i: np.sin(i) with pytest.raises(ValueError, match="func must be bounded within the interval"): func_to_unitary(func, 8) def test_example(self): """Test for a fixed example if the returned unitary maps input states to the expected output state as well as if the unitary satisfies U @ U.T = U.T @ U = I.""" M = 8 func = lambda i: np.sin(i) ** 2 r = func_to_unitary(func, M) for i in range(M): # The control qubit is the last qubit, so we have to look at every other term # using [::2]. output_state = r[::2][i] output_0 = output_state[::2] output_1 = output_state[1::2] assert np.allclose(output_0[i], np.sqrt(1 - func(i))) assert np.allclose(output_1[i], np.sqrt(func(i))) assert np.allclose(r @ r.T, np.eye(2 * M)) assert np.allclose(r.T @ r, np.eye(2 * M)) def test_example_with_pl(self): """Test for a fixed example if the returned unitary behaves as expected when used within a PennyLane circuit, i.e., so that the probability of the final control wire encodes the function.""" wires = 3 M = 2**wires func = lambda i: np.sin(i) ** 2 r = func_to_unitary(func, M) dev = qml.device("default.qubit", wires=(wires + 1)) @qml.qnode(dev) def apply_r(input_state): qml.QubitStateVector(input_state, wires=range(wires)) qml.QubitUnitary(r, wires=range(wires + 1)) return qml.probs(wires) for i, state in enumerate(np.eye(M)): p = apply_r(state)[1] assert np.allclose(p, func(i)) def test_V(): """Test for the _make_V function""" dim = 4 V_expected = -np.eye(dim) V_expected[1, 1] = V_expected[3, 3] = 1 V = _make_V(dim) assert np.allclose(V, V_expected) def test_Z():
def test_Q(): """Test for the make_Q function using a fixed example""" A = np.array( [ [0.85358423 - 0.32239299j, -0.12753659 + 0.38883306j], [0.39148136 - 0.11915985j, 0.34064316 - 0.84646648j], ] ) R = np.array( [ [ 0.45885289 + 0.03972856j, 0.2798685 - 0.05981098j, 0.64514642 - 0.51555038j, 0.11015177 - 0.10877695j, ], [ 0.19407005 - 0.35483005j, 0.29756077 + 0.80153453j, -0.19147104 + 0.0507968j, 0.15553799 - 0.20493631j, ], [ 0.35083011 - 0.20807392j, -0.27602911 - 0.13934692j, 0.11874165 + 0.34532609j, -0.45945242 - 0.62734969j, ], [ -0.11379919 - 0.66706921j, -0.21120956 - 0.2165113j, 0.30133006 + 0.23367271j, 0.54593491 + 0.08446372j, ], ] ) Q_expected = np.array( [ [ -0.46513201 - 1.38777878e-17j, -0.13035515 - 2.23341802e-01j, -0.74047856 + 7.08652160e-02j, -0.0990036 - 3.91977176e-01j, ], [ 0.13035515 - 2.23341802e-01j, 0.46494302 + 0.00000000e00j, 0.05507901 - 1.19182067e-01j, -0.80370146 - 2.31904873e-01j, ], [ -0.74047856 - 7.08652160e-02j, -0.05507901 - 1.19182067e-01j, 0.62233412 - 2.77555756e-17j, -0.0310774 - 2.02894077e-01j, ], [ 0.0990036 - 3.91977176e-01j, -0.80370146 + 2.31904873e-01j, 0.0310774 - 2.02894077e-01j, -0.30774091 + 2.77555756e-17j, ], ] ) Q = make_Q(A, R) assert np.allclose(Q, Q_expected) class TestQuantumMonteCarlo: """Tests for the QuantumMonteCarlo template""" @staticmethod def func(i): return np.sin(i) ** 2 def test_non_flat(self): """Test if a ValueError is raised when a non-flat array is input""" p = np.ones((4, 1)) / 4 with pytest.raises(ValueError, match="The probability distribution must be specified as a"): QuantumMonteCarlo(p, self.func, range(3), range(3, 5)) def test_wrong_size_p(self): """Test if a ValueError is raised when a probability distribution is passed whose length cannot be mapped to qubits""" p = np.ones(5) / 5 with pytest.raises(ValueError, match="The probability distribution must have a length"): QuantumMonteCarlo(p, self.func, range(3), range(3, 5)) def test_unexpected_target_wires_number(self): """Test if a ValueError is raised when the number of target wires is incompatible with the expected number of target wires inferred from the length of the input probability distribution""" p = np.ones(4) / 4 with pytest.raises( ValueError, match="The probability distribution of dimension 4 requires" " 3 target wires", ): QuantumMonteCarlo(p, self.func, range(4), range(4, 6)) def test_expected_circuit(self): """Test if the circuit applied when using the QMC template is the same as the expected circuit for a fixed example""" p = np.ones(4) / 4 target_wires, estimation_wires = Wires(range(3)), Wires(range(3, 5)) op = QuantumMonteCarlo(p, self.func, target_wires, estimation_wires) tape = op.expand() # Do expansion in two steps to avoid also decomposing the first QubitUnitary queue_before_qpe = tape.operations[:2] # 2-qubit decomposition has 10 operations, and after is a 3-qubit gate so start at 11 queue_after_qpe = tape.expand().operations[11:] A = probs_to_unitary(p) R = func_to_unitary(self.func, 4) assert len(queue_before_qpe) == 2 assert queue_before_qpe[0].name == "QubitUnitary" assert queue_before_qpe[1].name == "QubitUnitary" assert np.allclose(queue_before_qpe[0].matrix, A) assert np.allclose(queue_before_qpe[1].matrix, R) assert queue_before_qpe[0].wires == target_wires[:-1] assert queue_before_qpe[1].wires == target_wires Q = make_Q(A, R) with qml.tape.QuantumTape() as qpe_tape: qml.QuantumPhaseEstimation(Q, target_wires, estimation_wires) qpe_tape = qpe_tape.expand() assert len(queue_after_qpe) == len(qpe_tape.operations) assert all(o1.name == o2.name for o1, o2 in zip(queue_after_qpe, qpe_tape.operations)) assert all( np.allclose(o1.matrix, o2.matrix) for o1, o2 in zip(queue_after_qpe, qpe_tape.operations) ) assert all(o1.wires == o2.wires for o1, o2 in zip(queue_after_qpe, qpe_tape.operations)) def test_expected_value(self): """Test that the QuantumMonteCarlo template can correctly estimate the expectation value following the example in the usage details""" m = 5 M = 2**m xmax = np.pi xs = np.linspace(-xmax, xmax, M) probs = np.array([norm().pdf(x) for x in xs]) probs /= np.sum(probs) func = lambda i: np.cos(xs[i]) ** 2 estimates = [] for n in range(4, 11): N = 2**n target_wires = range(m + 1) estimation_wires = range(m + 1, n + m + 1) dev = qml.device("default.qubit", wires=(n + m + 1)) @qml.qnode(dev) def circuit(): qml.QuantumMonteCarlo( probs, func, target_wires=target_wires, estimation_wires=estimation_wires ) return qml.probs(estimation_wires) phase_estimated = np.argmax(circuit()[: int(N / 2)]) / N mu_estimated = (1 - np.cos(np.pi * phase_estimated)) / 2 estimates.append(mu_estimated) exact = 0.432332358381693654 # Check that the error is monotonically decreasing for i in range(len(estimates) - 1): err1 = np.abs(estimates[i] - exact) err2 = np.abs(estimates[i + 1] - exact) assert err1 >= err2 assert np.allclose(estimates[-1], exact, rtol=1e-3) def test_expected_value_custom_wires(self): """Test that the QuantumMonteCarlo template can correctly estimate the expectation value following the example in the usage details when the wires have custom labels""" m = 5 M = 2**m xmax = np.pi xs = np.linspace(-xmax, xmax, M) probs = np.array([norm().pdf(x) for x in xs]) probs /= np.sum(probs) func = lambda i: np.cos(xs[i]) ** 2 n = 10 N = 2**n target_wires = [0, "a", -1.1, -10, "bbb", 1000] estimation_wires = ["bob", -3, 42, "penny", "lane", 247, "straw", "berry", 5.5, 6.6] dev = qml.device("default.qubit", wires=target_wires + estimation_wires) @qml.qnode(dev) def circuit(): qml.QuantumMonteCarlo( probs, func, target_wires=target_wires, estimation_wires=estimation_wires ) return qml.probs(estimation_wires) phase_estimated = np.argmax(circuit()[: int(N / 2)]) / N mu_estimated = (1 - np.cos(np.pi * phase_estimated)) / 2 exact = 0.432332358381693654 assert np.allclose(mu_estimated, exact, rtol=1e-3) def test_id(self): """Tests that the id attribute can be set.""" xs = np.linspace(-np.pi, np.pi, 2**5) probs = np.array([norm().pdf(x) for x in xs]) probs /= np.sum(probs) func = lambda i: np.cos(xs[i]) ** 2 target_wires = [0, "a", -1.1, -10, "bbb", 1000] estimation_wires = ["bob", -3, 42, "penny", "lane", 247, "straw", "berry", 5.5, 6.6] template = qml.QuantumMonteCarlo( probs, func, target_wires=target_wires, estimation_wires=estimation_wires, id="a" ) assert template.id == "a"
"""Test for the _make_Z function""" dim = 4 Z_expected = -np.eye(dim) Z_expected[0, 0] = 1 Z = _make_Z(dim) assert np.allclose(Z, Z_expected)
index.js
"use strict"; var enhanceComponent_1 = require("./enhanceComponent"); exports.enhanceComponent = enhanceComponent_1["default"];
main.go
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. // License: https://creativecommons.org/licenses/by-nc-sa/4.0/ // Lissajous generates GIF animations of random Lissajous figures. package main import ( "image" "image/color" "image/gif" "io" "math" "math/rand" "os" ) //!-main // Packages not needed by version in book. import ( "log" "net/http" "time" ) //!+main const ( bgIndex = 0 // first color in palette fgStartIndex = 1 // next color in palette ) func main() { //!-main // The sequence of images is deterministic unless we seed // the pseudo-random number generator using the current time. // Thanks to Randall McPherson for pointing out the omission. rand.Seed(time.Now().UTC().UnixNano()) if len(os.Args) > 1 && os.Args[1] == "web" { //!+http handler := func(w http.ResponseWriter, r *http.Request) { lissajous(w) } http.HandleFunc("/", handler) //!-http log.Fatal(http.ListenAndServe("localhost:8000", nil)) return } //!+main lissajous(os.Stdout) } func lissajous(out io.Writer) {
//!-main
const ( cycles = 5 // number of complete x oscillator revolutions res = 0.001 // angular resolution size = 100 // image canvas covers [-size..+size] nframes = 64 // number of animation frames delay = 8 // delay between frames in 10ms units ) palette := []color.Color{ color.Black, color.RGBA{0xFF, 0x00, 0x00, 0xFF}, color.RGBA{0x00, 0xFF, 0x00, 0xFF}, color.RGBA{0x00, 0x00, 0xFF, 0xFF}, } freq := rand.Float64() * 3.0 // relative frequency of y oscillator anim := gif.GIF{LoopCount: nframes} phase := 0.0 // phase difference for i := 0; i < nframes; i++ { rect := image.Rect(0, 0, 2*size+1, 2*size+1) img := image.NewPaletted(rect, palette) for t := 0.0; t < cycles*2*math.Pi; t += res { x := math.Sin(t) y := math.Sin(t*freq + phase) colorIdx := uint8(math.Mod(float64(fgStartIndex+i), 3.0)) + 1 img.SetColorIndex(size+int(x*size+0.5), size+int(y*size+0.5), colorIdx) } phase += 0.1 anim.Delay = append(anim.Delay, delay) anim.Image = append(anim.Image, img) } gif.EncodeAll(out, &anim) // NOTE: ignoring encoding errors }
group_data.py
from sys import maxsize class Group: def __init__(self, name=None, header=None, footer=None, id=None):
def __repr__(self): return "%s:%s" % (self.id, self.name) def __eq__(self, other): return (self.id is None or other.id is None or self.id == other.id) and self.name == other.name def id_or_max(self): if self.id: return int(self.id) else: return maxsize
self.name = name self.header = header self.footer = footer self.id = id
closure.py
def func():
f = func() f()
x = 2 def say(): print x return say
rich-text-editor.ts
import { Component, ModuleDeclaration, EventHandler, Complex, Browser, EmitType, addClass, select, detach } from '@syncfusion/ej2-base'; import { Property, NotifyPropertyChanges, INotifyPropertyChanged, formatUnit, L10n, closest } from '@syncfusion/ej2-base'; import { setStyleAttribute, Event, removeClass, print as printWindow, attributes } from '@syncfusion/ej2-base'; import { isNullOrUndefined as isNOU, compile, append, extend, debounce, isBlazor } from '@syncfusion/ej2-base'; import { Touch as EJ2Touch, TapEventArgs } from '@syncfusion/ej2-base'; import { getScrollableParent, BeforeOpenEventArgs, BeforeCloseEventArgs } from '@syncfusion/ej2-popups'; import { RichTextEditorModel } from './rich-text-editor-model'; import * as events from '../base/constant'; import * as classes from '../base/classes'; import { Render } from '../renderer/render'; import { ViewSource } from '../renderer/view-source'; import { IRenderer, IFormatter, PrintEventArgs, ActionCompleteEventArgs, ActionBeginEventArgs, ImageDropEventArgs } from './interface'; import { IExecutionGroup, executeGroup, CommandName, ResizeArgs, StatusArgs, ToolbarStatusEventArgs } from './interface'; import { BeforeQuickToolbarOpenArgs, ChangeEventArgs, AfterImageDeleteEventArgs, PasteCleanupArgs } from './interface'; import { ILinkCommandsArgs, IImageCommandsArgs, BeforeSanitizeHtmlArgs, ITableCommandsArgs, ExecuteCommandOption } from './interface'; import { ServiceLocator } from '../services/service-locator'; import { RendererFactory } from '../services/renderer-factory'; import { RenderType, ToolbarType, DialogType } from './enum'; import { EditorMode } from './../../common/types'; import { Toolbar } from '../actions/toolbar'; import { ExecCommandCallBack } from '../actions/execute-command-callback'; import { KeyboardEvents, KeyboardEventArgs } from '../actions/keyboard'; import { FontFamilyModel, FontSizeModel, FontColorModel, FormatModel, BackgroundColorModel, NumberFormatListModel, BulletFormatListModel } from '../models/models'; import { ToolbarSettingsModel, IFrameSettingsModel, ImageSettingsModel, TableSettingsModel } from '../models/models'; import { QuickToolbarSettingsModel, InlineModeModel, PasteCleanupSettingsModel, FileManagerSettingsModel } from '../models/models'; import { ToolbarSettings, ImageSettings, QuickToolbarSettings, FontFamily, FontSize, Format, NumberFormatList, BulletFormatList } from '../models/toolbar-settings'; import { FileManagerSettings } from '../models/toolbar-settings'; import { TableSettings, PasteCleanupSettings } from '../models/toolbar-settings'; import { FontColor, BackgroundColor } from '../models/toolbar-settings'; import { IFrameSettings } from '../models/iframe-settings'; import { InlineMode } from '../models/inline-mode'; import { Link } from '../renderer/link-module'; import { Image } from '../renderer/image-module'; import { Table } from '../renderer/table-module'; import { Count } from '../actions/count'; import { HtmlEditor } from '../actions/html-editor'; import { MarkdownEditor } from '../actions/markdown-editor'; import { defaultLocale } from '../models/default-locale'; import { setAttributes } from '../actions/html-attributes'; import { BaseToolbar } from '../actions/base-toolbar'; import { QuickToolbar } from '../actions/quick-toolbar'; import { FullScreen } from '../actions/full-screen'; import { PasteCleanup } from '../actions/paste-clean-up'; import * as CONSTANT from '../../common/constant'; import { IHtmlKeyboardEvent } from '../../editor-manager/base/interface'; import { dispatchEvent, getEditValue, isIDevice, decode, isEditableValueEmpty } from '../base/util'; import { DialogRenderer } from '../renderer/dialog-renderer'; import { SelectedEventArgs, RemovingEventArgs, UploadingEventArgs, BeforeUploadEventArgs } from '@syncfusion/ej2-inputs'; import { Resize } from '../actions/resize'; import { FileManager } from '../actions/file-manager'; import { EditorManager } from '../../editor-manager'; /** * Represents the Rich Text Editor component. * ```html * <textarea id="rte"></textarea> * <script> * var rteObj = new RichTextEditor(); * rteObj.appendTo("#rte"); * </script> * ``` */ @NotifyPropertyChanges export class
extends Component<HTMLElement> implements INotifyPropertyChanged { private placeHolderWrapper: HTMLElement; private scrollParentElements: HTMLElement[]; private cloneValue: string; private onFocusHandler: EventListenerOrEventListenerObject; private onBlurHandler: EventListenerOrEventListenerObject; private onResizeHandler: EventListenerOrEventListenerObject; private timeInterval: number; private idleInterval: number; private touchModule: EJ2Touch; private defaultResetValue: string = null; private isResizeInitialized: boolean = false; /** * @hidden * @deprecated */ public isFocusOut: boolean = false; /** * @hidden * @deprecated */ public inputElement: HTMLElement; /** * @hidden * @deprecated */ public isRTE: boolean = false; /** * @hidden * @deprecated */ public isBlur: boolean = true; /** * @hidden * @deprecated */ public renderModule: Render; /** * @hidden * @deprecated */ public contentModule: IRenderer; /** * @hidden * @deprecated */ public serviceLocator: ServiceLocator; /** * The `toolbarModule` is used to manipulate ToolBar items and its action in the RichTextEditor. * * @hidden * @deprecated */ public toolbarModule: Toolbar; /** * @hidden * @deprecated */ public imageModule: Image; /** * @hidden * @deprecated */ public tableModule: Table; /** * @hidden * @deprecated */ public fullScreenModule: FullScreen; /** * @hidden * @deprecated */ public resizeModule: Resize; /** * @hidden * @deprecated */ public pasteCleanupModule: PasteCleanup; /** * @hidden * @deprecated */ public sourceCodeModule: ViewSource; /** * @hidden * @deprecated */ public linkModule: Link; /** * @hidden * @deprecated */ public markdownEditorModule: MarkdownEditor; /** * @hidden * @deprecated */ public htmlEditorModule: HtmlEditor; /** * @hidden * @deprecated */ public quickToolbarModule: QuickToolbar; /** * @hidden * @deprecated */ public countModule: Count; /** * @hidden * @deprecated */ public fileManagerModule: FileManager; public needsID: boolean = true; /** * Specifies the group of items aligned horizontally in the toolbar as well as defined the toolbar rendering type. * By default, toolbar is float at the top of the RichTextEditor. * When you scroll down, the toolbar will scroll along with the page on Rich Text Editor with the specified offset value. * * enable: set boolean value to show or hide the toolbar. * * enableFloating: Set Boolean value to enable or disable the floating toolbar. * Preserves the toolbar at top of the Rich Text Editor on scrolling. * * type: it has two possible options * 1. Expand: Hide the overflowing toolbar items in the next row. Click the expand arrow to view overflowing toolbar items * 2. MultiRow: The toolbar overflowing items wrapped in the next row. * * items: Specifies the array of items aligned horizontally in the toolbar. * > | and - can insert a vertical and horizontal separator lines in the toolbar. * * itemConfigs: Modify the default toolbar item configuration like icon class. * * > By default, The toolbar is rendered with scrollable in mobile devices and does not support the toolbar type. * * {% codeBlock src='rich-text-editor/toolbar-settings/index.md' %}{% endcodeBlock %} * * @default * { * enable: true, * enableFloating: true, * type: ToolbarType.Expand, * items: ['Bold', 'Italic', 'Underline', '|', 'Formats', 'Alignments', 'OrderedList', * 'UnorderedList', '|', 'CreateLink', 'Image', '|', 'SourceCode', 'Undo', 'Redo'], * itemConfigs: {} * } */ @Complex<ToolbarSettingsModel>({}, ToolbarSettings) public toolbarSettings: ToolbarSettingsModel; /** * Specifies the items to be rendered in quick toolbar based on the target element. * * It has following fields: * * enable - set boolean value to show or hide the quick toolbar * * actionOnScroll - it has two possible options * 1. hide: The quickToolbar is closed when the parent element is scrolled. * 2. none: The quickToolbar cannot be closed even the parent element is scrolled. * * link - Specifies the items to be rendered in quick toolbar based on link element such as `Open`, `Edit`, and `UnLink`. * * image - Specifies the items to be rendered in quick toolbar based on image element such as 'Replace', * 'Align', 'Caption', 'Remove', 'InsertLink', 'Display', 'AltText', 'Dimension'. * * text - Specifies the items to be rendered in quick toolbar based on text element such as 'Cut', 'Copy', 'Paste'. * * {% codeBlock src='rich-text-editor/quick-toolbar-settings/index.md' %}{% endcodeBlock %} * * @default * { * enable: true, * actionOnScroll: 'hide', * link: ['Open', 'Edit', 'UnLink'], * image: ['Replace', 'Align', 'Caption', 'Remove', '-', 'InsertLink', 'Display', 'AltText', 'Dimension'], * } */ @Complex<QuickToolbarSettingsModel>({}, QuickToolbarSettings) public quickToolbarSettings: QuickToolbarSettingsModel; /** * Specifies the pasting options in Rich Text Editor component and control with the following properties. * * prompt - Set boolean value to enable or disable the prompt when pasting. * * deniedAttrs - Specifies the attributes to restrict when pasting in RTE. * * allowedStyleProps - Specifies the allowed style properties when pasting in RTE. * * deniedTags - Specifies the tags to restrict when pasting in RTE. * * keepFormat - Set boolean value to keep or remove the from when pasting. * * plainText - Set boolean value to paste as plain text or not. * * {% codeBlock src='rich-text-editor/paste-cleanup-settings/index.md' %}{% endcodeBlock %} * * @default * { * prompt: false, * deniedAttrs: null, * allowedStyleProps: ['background', 'background-color', 'border', 'border-bottom', 'border-left', 'border-radius', * 'border-right', 'border-style', 'border-top', 'border-width', 'clear', 'color', 'cursor', * 'direction', 'display', 'float', 'font', 'font-family', 'font-size', 'font-weight', 'font-style', * 'height', 'left', 'line-height', 'margin', 'margin-top', 'margin-left', * 'margin-right', 'margin-bottom', 'max-height', 'max-width', 'min-height', 'min-width', * 'overflow', 'overflow-x', 'overflow-y', 'padding', 'padding-bottom', 'padding-left', 'padding-right', * 'padding-top', 'position', 'right', 'table-layout', 'text-align', 'text-decoration', 'text-indent', * 'top', 'vertical-align', 'visibility', 'white-space', 'width'], * deniedTags: null, * keepFormat: true, * plainText: false * } */ @Complex<PasteCleanupSettingsModel>({}, PasteCleanupSettings) public pasteCleanupSettings: PasteCleanupSettingsModel; /** * Specifies the items to be rendered in an iframe mode, and it has the following properties. * * enable - Set Boolean value to enable, the editors content is placed in an iframe and isolated from the rest of the page. * * attributes - Custom style to be used inside the iframe to display content. This style is added to the iframe body. * * resources - we can add both styles and scripts to the iframe. * 1. styles[] - An array of CSS style files to inject inside the iframe to display content * 2. scripts[] - An array of JS script files to inject inside the iframe * * {% codeBlock src='rich-text-editor/iframe-settings/index.md' %}{% endcodeBlock %} * * @default * { * enable: false, * attributes: null, * resources: { styles: [], scripts: [] } * } */ @Complex<IFrameSettingsModel>({}, IFrameSettings) public iframeSettings: IFrameSettingsModel; /** * Specifies the image insert options in Rich Text Editor component and control with the following properties. * * allowedTypes - Specifies the extensions of the image types allowed to insert on bowering and * passing the extensions with comma separators. For example, pass allowedTypes as .jpg and .png. * * display - Sets the default display for an image when it is inserted in to the RichTextEditor. * Possible options are: 'inline' and 'block'. * * width - Sets the default width of the image when it is inserted in the RichTextEditor. * * saveFormat - Specifies the format to store the image in the Rich Text Editor (Base64 or Blob). * > If you want to insert a lot of tiny images in the editor and don't want a specific physical location for * saving images, you can opt to save format as Base64. * * height - Sets the default height of the image when it is inserted in the RichTextEditor. * * saveUrl - Specifies the service URL of save action that will receive the uploaded files and save them in the server. * * path - Specifies the path of the location to store the images and refer it to display the images. * * {% codeBlock src='rich-text-editor/insert-image-settings/index.md' %}{% endcodeBlock %} * * @default * { * allowedTypes: ['.jpeg', '.jpg', '.png'], * display: 'inline', * width: 'auto', * height: 'auto', * saveFormat: 'Blob' * saveUrl: null, * path: null, * } */ @Complex<ImageSettingsModel>({}, ImageSettings) public insertImageSettings: ImageSettingsModel; /** * Specifies the table insert options in Rich Text Editor component and control with the following properties. * * styles - Class name should be appended by default in table element. * It helps to design the table in specific CSS styles always when inserting in editor. * * width - Sets the default width of the table when it is inserted in the RichTextEditor. * * minWidth - Sets the default minWidth of the table when it is inserted in the RichTextEditor. * * maxWidth - Sets the default maxWidth of the table when it is inserted in the RichTextEditor. * * resize - To enable resize the table. * * {% codeBlock src='rich-text-editor/table-settings/index.md' %}{% endcodeBlock %} * * @default * { * width: '100%', * styles: [{ text: 'Dashed Borders', class: 'e-dashed-borders', command: 'Table', subCommand: 'Dashed' }, * { text: 'Alternate Rows', class: 'e-alternate-rows', command: 'Table', subCommand: 'Alternate' }], * resize: true, * minWidth: 0, * maxWidth: null, * } */ @Complex<TableSettingsModel>({}, TableSettings) public tableSettings: TableSettingsModel; /** * Preserves the toolbar at the top of the Rich Text Editor on scrolling and * specifies the offset of the floating toolbar from documents top position * * @default 0 */ @Property(0) public floatingToolbarOffset: number; /** * Enable or disable the inline edit mode. * * enable - set boolean value to enable or disable the inline edit mode. * * onSelection - If its set to true, upon selecting the text, the toolbar is opened in inline. * If its set to false, upon clicking to the target element, the toolbar is opened. * * {% codeBlock src='rich-text-editor/inline-mode/index.md' %}{% endcodeBlock %} * * @default * { * enable: false, * onSelection: true * } */ @Complex<InlineModeModel>({}, InlineMode) public inlineMode: InlineModeModel; /** * Specifies the image manager options in Rich Text Editor component and control with the following properties. * * enable - set boolean value to enable or disable the image manager. * * ajaxSettings - Specifies the AJAX settings of the image manager. * * contextMenuSettings - Specifies the context menu settings of the image manager. * * navigationPaneSettings - Specifies the navigation pane settings of the image manager. * * toolbarSettings - Specifies the group of items aligned horizontally in the toolbar. * * uploadSettings - Specifies the upload settings for the image manager. * * @default * { * enable: false, * path: '/', * ajaxSettings: { getImageUrl: null, url: null, uploadUrl: null }, * contextMenuSettings: { * visible: true, * file: ['Open', '|', 'Cut', 'Copy', '|', 'Delete', 'Rename', '|', 'Details'], * folder: ['Open', '|', 'Cut', 'Copy', 'Paste', '|', 'Delete', 'Rename', '|', 'Details'], * layout: ['SortBy', 'View', 'Refresh', '|', 'Paste', '|', 'NewFolder', 'Upload', '|', 'Details', '|', 'SelectAll'] * }, * navigationPaneSettings: { * visible: true, * items: [ * 'NewFolder', 'Upload', 'Cut', 'Copy', 'Paste', 'Delete', 'Download', * 'Rename', 'SortBy', 'Refresh', 'Selection', 'View', 'Details' * ] * }, * toolbarSettings: { visible: true, items: ['Upload', 'NewFolder'] }, * uploadSettings: { autoUpload: true, minFileSize: 0, maxFileSize: 30000000, allowedExtensions: '', autoClose: false } * } */ @Complex<FileManagerSettingsModel>({}, FileManagerSettings) public fileManagerSettings: FileManagerSettingsModel; /** * Specifies the width of the RichTextEditor. * * @default '100%' */ @Property('100%') public width: string | number; /** * Enables or disables the persisting component's state between page reloads. * If enabled, the value of Rich Text Editor is persisted * * {% codeBlock src='rich-text-editor/enable-persistence/index.md' %}{% endcodeBlock %} * * @default false. */ @Property(false) public enablePersistence: boolean; /** * Enables or disables the resizing option in the editor. * If enabled, the Rich Text Editor can be resized by dragging the resize icon in the bottom right corner. * * {% codeBlock src='rich-text-editor/enable-resize/index.md' %}{% endcodeBlock %} * * @default false. */ @Property(false) public enableResize: boolean; /** * Allows additional HTML attributes such as title, name, etc., and * It will be accepts n number of attributes in a key-value pair format. * * @default {}. */ @Property({}) public htmlAttributes: { [key: string]: string }; /** * Specifies the placeholder for the RichTextEditor’s content used when the Rich Text Editor body is empty. * * @default null. */ @Property(null) public placeholder: string; /** * Enables or disables the auto-save option which performs the save action while in the idle state after typed content. * If enabled, the Rich Text Editor will save the content on idle state with `saveInterval` property's value. * The change event will be triggered if the content has changed from the last saved state. * * @default false. */ @Property(false) public autoSaveOnIdle: boolean; /** * The user interactions on the component are disabled, when set to true. * * @default false. */ @Property(false) public readonly: boolean; /** * Specifies a value that indicates whether the component is enabled or not. * * {% codeBlock src='rich-text-editor/enabled/index.md' %}{% endcodeBlock %} * * @default true. */ @Property(true) public enabled: boolean; /** * Defines whether to allow the cross-scripting site or not. * * @default true */ @Property(true) public enableHtmlSanitizer: boolean; /** * specifies the value whether the source code is displayed with encoded format. * * @default false. */ @Property(false) public enableHtmlEncode: boolean; /** * Specifies a value that indicates whether the xhtml is enabled or not. * * @default false. */ @Property(false) public enableXhtml: boolean; /** * Specifies the height of the Rich Text Editor component. * * @default "auto" */ @Property('auto') public height: string | number; /** * Specifies the CSS class name appended with the root element of the RichTextEditor. * One or more custom CSS classes can be added to a RichTextEditor. * * @default null */ @Property(null) public cssClass: string; /** * Specifies the value displayed in the RichTextEditor's content area and it should be string. * The content of Rich Text Editor can be loaded with dynamic data such as database, AJAX content, and more. * * {% codeBlock src='rich-text-editor/value/index.md' %}{% endcodeBlock %} * * @default null */ @Property(null) public value: string; /** * Specifies the count of undo history which is stored in undoRedoManager. * * {% codeBlock src='rich-text-editor/undo-redo-steps/index.md' %}{% endcodeBlock %} * * @default 30 */ @Property(30) public undoRedoSteps: number; /** * Specifies the interval value in milliseconds that store actions in undoRedoManager. The minimum value is 300 milliseconds. * * @default 300 */ @Property(300) public undoRedoTimer: number; /** * Specifies the editing mode of the RichTextEditor. * * - `HTML` - Render Rich Text Editor as HTML editor using &lt;IFRAME&gt; element or content editable &lt;div&gt; element * or &lt;textarea&gt; element. * * - `Markdown` - Render Rich Text Editor as markdown editor using &lt;textarea&gt;. * * @default 'HTML' */ @Property('HTML') public editorMode: EditorMode; /** * Customizes the key actions in RichTextEditor. * For example, when using German keyboard, the key actions can be customized using these shortcuts. * * {% codeBlock src='rich-text-editor/keyconfig/index.md' %}{% endcodeBlock %} * * @default null */ @Property(null) public keyConfig: { [key: string]: string }; /** * Sets Boolean value to enable or disable the display of the character counter. * * {% codeBlock src='rich-text-editor/show-char-count/index.md' %}{% endcodeBlock %} * * @default false */ @Property(false) public showCharCount: boolean; /** * Allows the tab key action in the Rich Text Editor content. * * {% codeBlock src='rich-text-editor/enable-tab-key/index.md' %}{% endcodeBlock %} * * @default false */ @Property(false) public enableTabKey: boolean; /** * Enable `enableAutoUrl` to accept the given URL (relative or absolute) without validating the URL for hyperlinks, otherwise * the given URL will automatically convert to absolute path URL by prefixing `https://` for hyperlinks. * * {% codeBlock src='rich-text-editor/enable-autourl/index.md' %}{% endcodeBlock %} * * @default false */ @Property(false) public enableAutoUrl: boolean; /** * Specifies the maximum number of characters allowed in the Rich Text Editor component. * * {% codeBlock src='rich-text-editor/max-length/index.md' %}{% endcodeBlock %} * * @default -1 */ @Property(-1) public maxLength: number; /** * Predefine the collection of paragraph styles along with quote and code style that populate in format dropdown from the toolbar. * * {% codeBlock src='rich-text-editor/format/index.md' %}{% endcodeBlock %} * * @default * { * default: 'Paragraph', * width: '65px', * types: [ * { text: 'Paragraph' }, * { text: 'Code' }, * { text: 'Quotation' }, * { text: 'Heading 1' }, * { text: 'Heading 2' }, * { text: 'Heading 3' }, * { text: 'Heading 4' }, * { text: 'Heading 5' }, * { text: 'Heading 6' } * ] * } */ @Complex<FormatModel>({}, Format) public format: FormatModel; /** * Predefine the advanced list types that populate in the numberFormatList dropdown list from the toolbar. * * @default * { * types: [ * { text: 'None', value: 'none' }, * { text: 'Number', value: 'decimal' }, * { text: 'Lower Greek', value: 'lowerGreek' }, * { text: 'Lower Roman', value: 'lowerRoman' }, * { text: 'Upper Alpha', value: 'upperAlpha' }, * { text: 'Lower Alpha', value: 'lowerAlpha' }, * { text: 'Upper Roman', value: 'upperRoman' }, * ] * } */ @Complex<NumberFormatListModel>({}, NumberFormatList) public numberFormatList: NumberFormatListModel; /** * Predefine the advanced list types that populate in the bulletFormatList dropdown list from the toolbar. * * @default * { * types: [ * { text: 'None', value: 'none' }, * { text: 'Disc', value: 'disc' }, * { text: 'Circle', value: 'circle' }, * { text: 'Square', value: 'square' } * ] * } */ @Complex<BulletFormatListModel>({}, BulletFormatList) public bulletFormatList: BulletFormatListModel; /** * Predefine the font families that populate in font family dropdown list from the toolbar. * * {% codeBlock src='rich-text-editor/font-family/index.md' %}{% endcodeBlock %} * * @default * { * default: 'Segoe UI', * width: '65px', * items: [ * { text: 'Segoe UI', value: 'Segoe UI' }, * { text: 'Arial', value: 'Arial,Helvetica,sans-serif' }, * { text: 'Courier New', value: 'Courier New,Courier,monospace' }, * { text: 'Georgia', value: 'Georgia,serif' }, * { text: 'Impact', value: 'Impact,Charcoal,sans-serif' }, * { text: 'Lucida Console', value: 'Lucida Console,Monaco,monospace' }, * { text: 'Tahoma', value: 'Tahoma,Geneva,sans-serif' }, * { text: 'Times New Roman', value: 'Times New Roman,Times,serif' }, * { text: 'Trebuchet MS', value: 'Trebuchet MS,Helvetica,sans-serif' }, * { text: 'Verdana', value: 'Verdana,Geneva,sans-serif' } * ] * } */ @Complex<FontFamilyModel>({}, FontFamily) public fontFamily: FontFamilyModel; /** * Predefine the font sizes that populate in font size dropdown list from the toolbar. * * {% codeBlock src='rich-text-editor/font-size/index.md' %}{% endcodeBlock %} * * @default * { * default: '10', * width: '35px', * items: [ * { text: '8', value: '8pt' }, * { text: '10', value: '10pt' }, * { text: '12', value: '12pt' }, * { text: '14', value: '14pt' }, * { text: '18', value: '18pt' }, * { text: '24', value: '24pt' }, * { text: '36', value: '36pt' } * ] * } */ @Complex<FontSizeModel>({}, FontSize) public fontSize: FontSizeModel; /** * Predefine the color palette that can be rendered for font color toolbar command . * * {% codeBlock src='rich-text-editor/font-color/index.md' %}{% endcodeBlock %} * * @default * { * columns: 10, * colorCode: { * 'Custom': [ * '', '#000000', '#e7e6e6', '#44546a', '#4472c4', '#ed7d31', '#a5a5a5', '#ffc000', '#70ad47', '#ff0000', * '#f2f2f2', '#808080', '#cfcdcd', '#d5dce4', '#d9e2f3', '#fbe4d5', '#ededed', '#fff2cc', '#e2efd9', '#ffcccc', * '#d9d9d9', '#595959', '#aeaaaa', '#acb9ca', '#b4c6e7', '#f7caac', '#dbdbdb', '#ffe599', '#c5e0b3', '#ff8080', * '#bfbfbf', '#404040', '#747070', '#8496b0', '#8eaadb', '#f4b083', '#c9c9c9', '#ffd966', '#a8d08d', '#ff3333', * '#a6a6a6', '#262626', '#3b3838', '#323e4f', '#2f5496', '#c45911', '#7b7b7b', '#bf8f00', '#538135', '#b30000', * '#7f7f7f', '#0d0d0d', '#161616', '#212934', '#1f3763', '#823b0b', '#525252', '#7f5f00', '#375623', '#660000'] * } * } */ @Complex<FontColorModel>({}, FontColor) public fontColor: FontColorModel; /** * Predefine the color palette that can be rendered for background color (text highlighted color) toolbar command. * * {% codeBlock src='rich-text-editor/background-color/index.md' %}{% endcodeBlock %} * * @default * { * columns: 5, * colorCode: { * 'Custom': ['#ffff00', '#00ff00', '#00ffff', '#ff00ff', '#0000ff', '#ff0000', * '#000080', '#008080', '#008000', '#800080', '#800000', '#808000', * '#c0c0c0', '#000000', ''] * } * } */ @Complex<BackgroundColorModel>({}, BackgroundColor) public backgroundColor: BackgroundColorModel; /** * Accepts the template design and assigns it as RichTextEditor’s content. * The built-in template engine which provides options to compile template string into a executable function. * For EX: We have expression evolution as like ES6 expression string literals * * {% codeBlock src='rich-text-editor/value-template/index.md' %}{% endcodeBlock %} * * @default null */ @Property(null) public valueTemplate: string; /** * Specifies the saveInterval in milliseconds for autosave the value. * The change event will be triggered if the content was changed from the last saved interval. * * {% codeBlock src='rich-text-editor/save-interval/index.md' %}{% endcodeBlock %} * * @default 10000 */ @Property(10000) public saveInterval: number; /** * Triggers before command execution using toolbar items or executeCommand method. * If you cancel this event, the command cannot be executed. * Set the cancel argument to true to cancel the command execution. * * @event 'actionBegin' * @blazorProperty 'OnActionBegin' */ @Event() public actionBegin: EmitType<ActionBeginEventArgs>; /** * Triggers after command execution using toolbar items or executeCommand method. * * @event 'actionComplete' * @blazorProperty 'OnActionComplete' */ @Event() public actionComplete: EmitType<ActionCompleteEventArgs>; /** * Event triggers when the dialog is being opened. * If you cancel this event, the dialog remains closed. * Set the cancel argument to true to cancel the open of a dialog. * * @event 'object' * @blazorProperty 'OnDialogOpen' * @blazorType Syncfusion.EJ2.Blazor.Popups.BeforeOpenEventArgs */ @Event() public beforeDialogOpen: EmitType<BeforeOpenEventArgs>; /** * Event triggers when a dialog is opened. * * @event 'object' * @blazorProperty 'DialogOpened' * @blazorType DialogOpenEventArgs */ @Event() public dialogOpen: EmitType<Object>; /** * Event triggers when the dialog is being closed. * If you cancel this event, the dialog remains opened. * Set the cancel argument to true to prevent closing a dialog. * * @event 'object' * @blazorProperty 'OnDialogClose' * @blazorType Syncfusion.EJ2.Blazor.Popups.BeforeOpenEventArgs */ @Event() public beforeDialogClose: EmitType<BeforeCloseEventArgs>; /** * Event triggers after the dialog has been closed. * * @event 'object' * @blazorProperty 'DialogClosed' * @blazorType DialogCloseEventArgs */ @Event() public dialogClose: EmitType<Object>; /** * Event triggers when the quick toolbar is being opened. * * @event 'object' * @blazorProperty 'OnQuickToolbarOpen' */ @Event() public beforeQuickToolbarOpen: EmitType<BeforeQuickToolbarOpenArgs>; /** * Event triggers when a quick toolbar is opened. * * @event 'object' * @blazorProperty 'QuickToolbarOpened' * @blazorType QuickToolbarEventArgs */ @Event() public quickToolbarOpen: EmitType<Object>; /** * Event triggers after the quick toolbar has been closed. * * @event 'object' * @blazorProperty 'QuickToolbarClosed' * @blazorType QuickToolbarEventArgs */ @Event() public quickToolbarClose: EmitType<Object>; /** * This event is deprecated and no longer works. Use `updatedToolbarStatus` event to get the undo and redo status. * * @deprecated * @event 'object' */ @Event() private toolbarStatusUpdate: EmitType<Object>; /** * Triggers when the toolbar items status is updated. * * @event 'object' * @blazorType ToolbarUpdateEventArgs */ @Event() private updatedToolbarStatus: EmitType<ToolbarStatusEventArgs>; /** * Event triggers when the image is selected or dragged into the insert image dialog. * * @event 'object' * @blazorProperty 'OnImageSelected' */ @Event() public imageSelected: EmitType<SelectedEventArgs>; /** * Event triggers before the image upload process. * * @event 'beforeImageUpload' */ @Event() public beforeImageUpload: EmitType<BeforeUploadEventArgs>; /** * Event triggers when the selected image begins to upload in the insert image dialog. * * @event 'object' * @blazorProperty 'OnImageUploading' */ @Event() public imageUploading: EmitType<UploadingEventArgs>; /** * Event triggers when the image is successfully uploaded to the server side. * * @event 'object' * @blazorProperty 'OnImageUploadSuccess' * @blazorType ImageSuccessEventArgs */ @Event() public imageUploadSuccess: EmitType<Object>; /** * Event triggers when there is an error in the image upload. * * @event 'object' * @blazorProperty 'OnImageUploadFailed' * @blazorType ImageFailedEventArgs */ @Event() public imageUploadFailed: EmitType<Object>; /** * Event triggers when the selected image is cleared from the insert image dialog. * * @event 'object' * @blazorProperty 'OnImageRemoving' */ @Event() public imageRemoving: EmitType<RemovingEventArgs>; /** * Event triggers when the selected image is cleared from the Rich Text Editor Content. * * @event 'object' * @blazorProperty 'OnImageDelete' */ @Event() public afterImageDelete: EmitType<AfterImageDeleteEventArgs>; /** * Triggers when the Rich Text Editor is rendered. * * @event 'object' * @blazorProperty 'Created' */ @Event() public created: EmitType<Object>; /** * Triggers when the Rich Text Editor is destroyed. * * @event 'object' * @blazorProperty 'Destroyed' * @blazorType DestroyedEventArgs */ @Event() public destroyed: EmitType<Object>; /** * Event triggers before sanitize the value. It's only applicable to editorMode as `HTML`. * * @event 'object' * @blazorProperty 'OnSanitizeHtml' */ @Event() public beforeSanitizeHtml: EmitType<BeforeSanitizeHtmlArgs>; /** * Triggers when Rich Text Editor is focused out. * * @event 'object' * @blazorType BlurEventArgs */ @Event() public blur: EmitType<Object>; /** * Triggers when Rich Text Editor Toolbar items is clicked. * * @event 'object' * @blazorProperty 'OnToolbarClick' * @blazorType ToolbarClickEventArgs */ @Event() public toolbarClick: EmitType<Object>; /** * Triggers when Rich Text Editor is focused in * * @event 'object' * @blazorType FocusEventArgs */ @Event() public focus: EmitType<Object>; /** * Triggers only when Rich Text Editor is blurred and changes are done to the content. * * @event 'object' * @blazorProperty 'ValueChange' */ @Event() public change: EmitType<ChangeEventArgs>; /** * Triggers only when resizing the image. * * @event 'object' * @blazorProperty 'Resizing' */ @Event() public resizing: EmitType<ResizeArgs>; /** * Triggers only when start resize the image. * * @event 'object' * @blazorProperty 'OnResizeStart' */ @Event() public resizeStart: EmitType<ResizeArgs>; /** * Triggers only when stop resize the image. * * @event 'object' * @blazorProperty 'OnResizeStop' */ @Event() public resizeStop: EmitType<ResizeArgs>; /** * Triggers before cleanup the copied content. * * @event 'object' */ @Event() public beforePasteCleanup: EmitType<PasteCleanupArgs>; /** * Triggers after cleanup the copied content. * * @event 'object' */ @Event() public afterPasteCleanup: EmitType<object>; /** * Triggers before drop the image. * * @event 'object' * @blazorProperty 'OnImageDrop' */ @Event() public beforeImageDrop: EmitType<ImageDropEventArgs>; /** * Customize keyCode to change the key value. * * {% codeBlock src='rich-text-editor/formatter/index.md' %}{% endcodeBlock %} * * @default null * @blazorType object */ @Property(null) public formatter: IFormatter; public keyboardModule: KeyboardEvents; public localeObj: L10n; public valueContainer: HTMLTextAreaElement; private originalElement: HTMLElement; private clickPoints: { [key: string]: number }; private initialValue: string; public constructor(options?: RichTextEditorModel, element?: string | HTMLElement) { super(options, <HTMLElement | string>element); } /** * To provide the array of modules needed for component rendering * * @returns {ModuleDeclaration[]} - specifies the declaration. * @hidden * @deprecated */ public requiredModules(): ModuleDeclaration[] { const modules: ModuleDeclaration[] = []; if (this.toolbarSettings.enable) { modules.push( { member: 'toolbar', args: [this, this.serviceLocator] } ); modules.push({ member: 'link', args: [this, this.serviceLocator] }); modules.push({ member: 'table', args: [this, this.serviceLocator] }); modules.push({ member: 'image', args: [this, this.serviceLocator] }); if (this.quickToolbarSettings.enable) { modules.push( { member: 'quickToolbar', args: [this, this.serviceLocator] } ); } } if (this.showCharCount) { modules.push( { member: 'count', args: [this, this.serviceLocator] } ); } if (this.editorMode === 'Markdown') { modules.push( { member: 'markdownEditor', args: [this, this.serviceLocator] } ); } if (this.editorMode === 'HTML') { modules.push( { member: 'htmlEditor', args: [this, this.serviceLocator] } ); modules.push( { member: 'pasteCleanup', args: [this, this.serviceLocator] } ); } if (this.fileManagerSettings.enable) { modules.push( { member: 'fileManager', args: [this, this.serviceLocator] } ); } if (this.enableResize) { modules.push( { member: 'resize', args: [this] } ); } return modules; } private updateEnable(): void { if (this.enabled) { removeClass([this.element], classes.CLS_DISABLED); this.element.setAttribute('aria-disabled', 'false'); if (!isNOU(this.htmlAttributes.tabindex)) { this.inputElement.setAttribute('tabindex', this.htmlAttributes.tabindex); } else { this.inputElement.setAttribute('tabindex', '0'); } } else { if (this.getToolbar()) { removeClass(this.getToolbar().querySelectorAll('.' + classes.CLS_ACTIVE), classes.CLS_ACTIVE); removeClass([this.getToolbar()], [classes.CLS_TB_FLOAT, classes.CLS_TB_ABS_FLOAT]); } addClass([this.element], classes.CLS_DISABLED); this.element.tabIndex = -1; this.element.setAttribute('aria-disabled', 'true'); this.inputElement.setAttribute('tabindex', '-1'); } } /** * setEnable method * * @returns {void} * @hidden * @deprecated */ public setEnable(): void { this.updateEnable(); // eslint-disable-next-line (this.enabled) ? this.eventInitializer() : this.unWireEvents(); } /** * For internal use only - Initialize the event handler; * * @returns {void} * @hidden * @private */ protected preRender(): void { this.onBlurHandler = this.blurHandler.bind(this); this.onFocusHandler = this.focusHandler.bind(this); this.onResizeHandler = this.resizeHandler.bind(this); this.clickPoints = { clientX: 0, clientY: 0 }; this.initialValue = this.value; this.serviceLocator = new ServiceLocator; this.initializeServices(); this.setContainer(); this.persistData(); setStyleAttribute(this.element, { 'width': formatUnit(this.width) }); attributes(this.element, { role: 'application' }); } private persistData (): void { if (this.enablePersistence && this.originalElement.tagName === 'TEXTAREA') { this.element.id = this.originalElement.id + '_wrapper'; const data: string = window.localStorage.getItem(this.getModuleName() + this.element.id); if (!(isNOU(data) || (data === ''))) { this.setProperties(JSON.parse(data), true); } } } private setContainer(): void { this.originalElement = this.element.cloneNode(true) as HTMLElement; if (this.value === null || this.valueTemplate !== null) { this.setValue(); } if (this.element.hasAttribute('tabindex')) { this.htmlAttributes = { 'tabindex': this.element.getAttribute('tabindex') }; this.element.removeAttribute('tabindex'); } if (!this.isBlazor()) { this.element.innerHTML = ''; } const invalidAttr: string[] = ['class', 'style', 'id', 'ejs-for']; const htmlAttr: { [key: string]: string } = {}; for (let a: number = 0; a < this.element.attributes.length; a++) { if (invalidAttr.indexOf(this.element.attributes[a].name) === -1 && !(/^data-val/.test(this.element.attributes[a].name))) { // data-val for asp.net core data annotation validation. htmlAttr[this.element.attributes[a].name] = this.element.getAttribute(this.element.attributes[a].name); } } extend(htmlAttr, this.htmlAttributes, htmlAttr); this.setProperties({ htmlAttributes: htmlAttr }, true); if (!isNOU(this.htmlAttributes.id)) { this.element.id = this.htmlAttributes.id; } if (this.element.tagName === 'TEXTAREA') { const rteOuterWrapper: HTMLElement = this.createElement('div', { className: this.element.getAttribute('class') }) as HTMLElement; if (!this.isBlazor()) { this.element.innerHTML = ''; } this.element.parentElement.insertBefore(rteOuterWrapper, this.element); if (isBlazor()) { rteOuterWrapper.appendChild(this.element); this.valueContainer = this.createElement('textarea', { id: this.element.id + '-value' }) as HTMLTextAreaElement; } else { this.valueContainer = this.element as HTMLTextAreaElement; } removeClass([this.valueContainer], this.element.getAttribute('class').split(' ')); if (this.isBlazor()) { addClass([this.element], classes.CLS_RTE_HIDDEN); } this.element = rteOuterWrapper; } else { this.valueContainer = this.createElement('textarea', { id: this.getID() + '-value' }) as HTMLTextAreaElement; } this.valueContainer.name = this.getID(); addClass([this.valueContainer], classes.CLS_RTE_HIDDEN); this.element.appendChild(this.valueContainer); } /** * getPersistData method * * @returns {void} * @hidden * @deprecated */ public getPersistData(): string { return this.addOnPersist(['value']); } /** * Focuses the Rich Text Editor component * * @returns {void} * @public */ public focusIn(): void { if (this.enabled) { this.inputElement.focus(); this.focusHandler({} as FocusEvent); } } /** * Blurs the Rich Text Editor component * * @returns {void} * @public */ public focusOut(): void { if (this.enabled) { this.inputElement.blur(); this.blurHandler({} as FocusEvent); } } /** * Selects all the content in RichTextEditor * * @returns {void} * @public */ public selectAll(): void { this.notify(events.selectAll, {}); } /** * Selects a content range or an element * * @param {Range} range - Specify the range which you want to select within the content. * The method used to select a particular sentence or word or entire document. * * @returns {void} * @public */ public selectRange(range: Range): void { this.notify(events.selectRange, { range: range }); } /** * Retrieves the HTML markup content from currently selected content of RichTextEditor. * * @returns {void} * @public */ public getSelection(): string { let str: string = ''; this.notify(events.getSelectedHtml, { callBack: (txt: string): void => { str = txt; } }); return str; } /** * Executes the commands * * @returns {void} * @param {CommandName} commandName - Specifies the name of the command to be executed. * @param {string | HTMLElement | ILinkCommandsArgs | IImageCommandsArgs} value - Specifies the value that you want to execute. * @param {ExecuteCommandOption} option - specifies the command option * @public */ public executeCommand( commandName: CommandName, value?: string | HTMLElement | ILinkCommandsArgs | IImageCommandsArgs | ITableCommandsArgs, option?: ExecuteCommandOption): void { value = this.htmlPurifier(commandName, value); if (this.editorMode === 'HTML') { const range: Range = this.getRange(); if (this.iframeSettings.enable) { this.formatter.editorManager.nodeSelection.Clear(this.element.ownerDocument); } const toFocus: boolean = (this.iframeSettings.enable && range.startContainer === this.inputElement) ? true : !this.inputElement.contains(range.startContainer); if (toFocus) { this.focusIn(); } } const tool: IExecutionGroup = executeGroup[commandName]; if (option && option.undo) { if (option.undo && this.formatter.getUndoRedoStack().length === 0) { this.formatter.saveData(); } } this.formatter.editorManager.execCommand( tool.command, tool.subCommand ? tool.subCommand : (value ? value : tool.value), null, null, (value ? value : tool.value), (value ? value : tool.value) ); if (option && option.undo) { this.formatter.saveData(); this.formatter.enableUndo(this); } this.setPlaceHolder(); this.notify(events.contentChanged, {}); } private htmlPurifier( command: CommandName, value?: string | HTMLElement | ILinkCommandsArgs | IImageCommandsArgs | ITableCommandsArgs): string { if (this.editorMode === 'HTML') { switch (command) { case 'insertHTML': if (this.enableHtmlSanitizer) { if (typeof value === 'string') { value = this.htmlEditorModule.sanitizeHelper(value); } else { value = this.htmlEditorModule.sanitizeHelper((value as HTMLElement).outerHTML); } } break; case 'insertTable': if (isNOU((value as { [key: string]: object }).width)) { (value as { [key: string]: object }).width = { minWidth: this.tableSettings.minWidth, maxWidth: this.tableSettings.maxWidth, width: this.tableSettings.width }; } break; case 'insertImage': { const temp: HTMLElement = this.createElement('img', { attrs: { src: (value as IImageCommandsArgs).url as string } }); let imageValue: string = temp.outerHTML; if (this.enableHtmlSanitizer) { imageValue = this.htmlEditorModule.sanitizeHelper(temp.outerHTML); } let url: string = (imageValue !== '' && (this.createElement('div', { innerHTML: imageValue }).firstElementChild).getAttribute('src')) || null; url = !isNOU(url) ? url : ''; (value as IImageCommandsArgs).url = url; if (isNOU((value as { [key: string]: object }).width)) { (value as { [key: string]: object }).width = { minWidth: this.insertImageSettings.minWidth, maxWidth: this.insertImageSettings.maxWidth, width: this.insertImageSettings.width }; } if (isNOU((value as { [key: string]: object }).height)) { (value as { [key: string]: object }).height = { minHeight: this.insertImageSettings.minHeight, maxHeight: this.insertImageSettings.maxHeight, height: this.insertImageSettings.height }; } break; } case 'createLink': { const tempNode: HTMLElement = this.createElement('a', { attrs: { href: (value as ILinkCommandsArgs).url as string } }); let linkValue: string = tempNode.outerHTML; if (this.enableHtmlSanitizer) { linkValue = this.htmlEditorModule.sanitizeHelper(tempNode.outerHTML); } let href: string = (linkValue !== '' && (this.createElement('div', { innerHTML: linkValue }).firstElementChild).getAttribute('href')) || null; href = !isNOU(href) ? href : ''; (value as ILinkCommandsArgs).url = href; break; } } } return value as string; } private encode(value: string): string { const divNode: HTMLElement = this.createElement('div'); divNode.innerText = value.trim(); // eslint-disable-next-line return divNode.innerHTML.replace(/<br\s*[\/]?>/gi, '\n'); } /** * For internal use only - To Initialize the component rendering. * * @returns {void} * @private * @deprecated */ protected render(): void { if (this.value && !this.valueTemplate) { this.setProperties({ value: this.serializeValue(this.value) }, true); } this.renderModule = new Render(this, this.serviceLocator); this.sourceCodeModule = new ViewSource(this, this.serviceLocator); this.notify(events.initialLoad, {}); this.trigger(events.load); this.RTERender(); // eslint-disable-next-line const execCommandCallBack: ExecCommandCallBack = new ExecCommandCallBack(this); this.notify(events.initialEnd, {}); if (this.enableXhtml) { this.setProperties({ value: this.getXhtml() }, true); } if (this.toolbarSettings.enable && this.toolbarSettings.type === 'Expand' && !isNOU(this.getToolbar()) && (this.toolbarSettings.items.indexOf('Undo') > -1 && this.toolbarSettings.items.indexOf('Redo') > -1)) { this.disableToolbarItem(['Undo', 'Redo']); } this.setContentHeight(); if (this.value !== null) { if (!this.isBlazor()) { this.valueContainer.defaultValue = this.value; } else { this.defaultResetValue = this.value; } } // eslint-disable-next-line (!this.enabled) ? this.unWireEvents() : this.eventInitializer(); this.renderComplete(); } /** * For internal use only - Initialize the event handler * * @returns {void} * @private * @deprecated * @hidden */ protected eventInitializer(): void { this.wireEvents(); } /** * For internal use only - keydown the event handler; * * @param {KeyboardEvent} e - specifies the event. * @returns {void} * @private * @deprecated * @hidden */ public keyDown(e: KeyboardEvent): void { this.notify(events.keyDown, { member: 'keydown', args: e }); this.restrict(e); if (this.editorMode === 'HTML' && ((e.which === 8 && e.code === 'Backspace') || (e.which === 46 && e.code === 'Delete'))) { const range: Range = this.getRange(); const startNode: Element = range.startContainer.nodeName === '#text' ? range.startContainer.parentElement : range.startContainer as Element; if (closest(startNode, 'pre') && (e.which === 8 && range.startContainer.textContent.charCodeAt(range.startOffset - 1) === 8203) || (e.which === 46 && range.startContainer.textContent.charCodeAt(range.startOffset) === 8203)) { const regEx: RegExp = new RegExp(String.fromCharCode(8203), 'g'); const pointer: number = e.which === 8 ? range.startOffset - 1 : range.startOffset; range.startContainer.textContent = range.startContainer.textContent.replace(regEx, ''); this.formatter.editorManager.nodeSelection.setCursorPoint( this.contentModule.getDocument(), range.startContainer as Element, pointer); } else if ((e.code === 'Backspace' && e.which === 8) && range.startContainer.textContent.charCodeAt(0) === 8203 && range.collapsed) { const parentEle: Element = range.startContainer.parentElement; let index: number; let i: number; for (i = 0; i < parentEle.childNodes.length; i++) { if (parentEle.childNodes[i] === range.startContainer) { index = i; } } let bool: boolean = true; const removeNodeArray: number[] = []; for (i = index; i >= 0; i--) { if (parentEle.childNodes[i].nodeType === 3 && parentEle.childNodes[i].textContent.charCodeAt(0) === 8203 && bool) { removeNodeArray.push(i); } else { bool = false; } } if (removeNodeArray.length > 0) { for (i = removeNodeArray.length - 1; i > 0; i--) { parentEle.childNodes[removeNodeArray[i]].textContent = ''; } } this.formatter.editorManager.nodeSelection.setCursorPoint( this.contentModule.getDocument(), range.startContainer as Element, range.startOffset); } } if (this.formatter.getUndoRedoStack().length === 0) { this.formatter.saveData(); } if ((e as KeyboardEventArgs).action !== 'insert-link' && ((e as KeyboardEventArgs).action && (e as KeyboardEventArgs).action !== 'paste' && (e as KeyboardEventArgs).action !== 'space' || e.which === 9 || (e.code === 'Backspace' && e.which === 8))) { this.formatter.process(this, null, e); switch ((e as KeyboardEventArgs).action) { case 'toolbar-focus': if (this.toolbarSettings.enable) { // eslint-disable-next-line let selector: string = '.e-toolbar-item[aria-disabled="false"][title] [tabindex]'; (this.toolbarModule.baseToolbar.toolbarObj.element.querySelector(selector) as HTMLElement).focus(); } break; case 'escape': (this.contentModule.getEditPanel() as HTMLElement).focus(); break; } } if (!isNOU(this.placeholder)) { if ((!isNOU(this.placeHolderWrapper)) && (this.inputElement.textContent.length !== 1)) { this.placeHolderWrapper.style.display = 'none'; } else { this.setPlaceHolder(); } } this.autoResize(); } private keyUp(e: KeyboardEvent): void { this.notify(events.keyUp, { member: 'keyup', args: e }); if (e.code === 'KeyX' && e.which === 88 && e.keyCode === 88 && e.ctrlKey && (this.inputElement.innerHTML === '' || this.inputElement.innerHTML === '<br>')) { this.inputElement.innerHTML = getEditValue('<p><br></p>', this); } const allowedKeys: boolean = e.which === 32 || e.which === 13 || e.which === 8 || e.which === 46; if (((e.key !== 'shift' && !e.ctrlKey) && e.key && e.key.length === 1 || allowedKeys) || (this.editorMode === 'Markdown' && ((e.key !== 'shift' && !e.ctrlKey) && e.key && e.key.length === 1 || allowedKeys)) && !this.inlineMode.enable) { this.formatter.onKeyHandler(this, e); } if (this.inputElement && this.inputElement.textContent.length !== 0 || this.element.querySelectorAll('.e-toolbar-item.e-active').length > 0) { this.notify(events.toolbarRefresh, { args: e }); } if (!isNOU(this.placeholder)) { this.setPlaceHolder(); } } /** * @param {string} value - specifies the value. * @returns {void} * @hidden * @deprecated */ public serializeValue(value: string): string { if (this.editorMode === 'HTML' && !isNOU(value)) { if (this.enableHtmlEncode) { value = this.htmlEditorModule.sanitizeHelper(decode(value)); value = this.encode(value); } else { value = this.htmlEditorModule.sanitizeHelper(value); } } return value; } /** * This method will clean up the HTML against cross-site scripting attack and return the HTML as string. * It's only applicable to editorMode as `HTML`. * * @param {string} value - Specifies the value that you want to sanitize. * @returns {string} - specifies the the string value */ public sanitizeHtml(value: string): string { return this.serializeValue(value); } /** * updateValue method * * @param {string} value - specifies the string value. * @returns {void} * @hidden * @deprecated */ public updateValue(value?: string): void { if (isNOU(value)) { const inputVal: string = this.inputElement.innerHTML; this.setProperties({ value: isEditableValueEmpty(inputVal) ? null : inputVal }); } else { this.setProperties({ value: value }); } } private triggerEditArea(e: MouseEvent | TouchEvent): void { if (!isIDevice()) { this.notify(events.editAreaClick, { member: 'editAreaClick', args: e }); } else { const touch: Touch = <Touch>((e as TouchEvent).touches ? (e as TouchEvent).changedTouches[0] : e); if (this.clickPoints.clientX === touch.clientX && this.clickPoints.clientY === touch.clientY) { this.notify(events.editAreaClick, { member: 'editAreaClick', args: e }); } } } private notifyMouseUp(e: MouseEvent | TouchEvent): void { const touch: Touch = <Touch>((e as TouchEvent).touches ? (e as TouchEvent).changedTouches[0] : e); this.notify(events.mouseUp, { member: 'mouseUp', args: e, touchData: { prevClientX: this.clickPoints.clientX, prevClientY: this.clickPoints.clientY, clientX: touch.clientX, clientY: touch.clientY } }); if (this.inputElement && ((this.editorMode === 'HTML' && this.inputElement.textContent.length !== 0) || (this.editorMode === 'Markdown' && (this.inputElement as HTMLTextAreaElement).value.length !== 0))) { this.notify(events.toolbarRefresh, { args: e }); } this.triggerEditArea(e); } private mouseUp(e: MouseEvent | TouchEvent): void { if (this.quickToolbarSettings.showOnRightClick && Browser.isDevice) { const target: Element = e.target as Element; const closestTable: Element = closest(target, 'table'); if (target && target.nodeName === 'A' || target.nodeName === 'IMG' || (target.nodeName === 'TD' || target.nodeName === 'TH' || target.nodeName === 'TABLE' || (closestTable && this.contentModule.getEditPanel().contains(closestTable)))) { return; } } this.notifyMouseUp(e); if (e.detail === 3) { const range: Range = this.getRange(); const selection: Selection = (this.formatter.editorManager as EditorManager).domNode.getSelection(); if (/\s+$/.test(selection.toString())) { if (!isNOU(range.startContainer.parentElement) && (!isNOU(range.startContainer.parentElement.nextSibling) && (range.startContainer.parentElement.nextSibling.nodeType !== 3 || /\s+$/.test(range.startContainer.parentElement.nextSibling.textContent)) || range.startOffset === range.endOffset) || range.startContainer.parentElement.tagName.toLocaleLowerCase() === 'li') { range.setStart(range.startContainer, range.startOffset); range.setEnd(range.startContainer, range.startContainer.textContent.length); } } } } /** * @param {Function} module - specifies the module function. * @returns {void} * @hidden * @deprecated */ public ensureModuleInjected(module: Function): boolean { return this.getInjectedModules().indexOf(module) >= 0; } /** * @returns {void} * @hidden * @deprecated */ public onCopy(): void { this.contentModule.getDocument().execCommand('copy', false, null); } /** * @returns {void} * @hidden * @deprecated */ public onCut(): void { this.contentModule.getDocument().execCommand('cut', false, null); } /** * @param {KeyboardEvent} e - specifies the keyboard event. * @returns {void} * @hidden * @deprecated */ public onPaste(e?: KeyboardEvent | ClipboardEvent): void { const evenArgs: { [key: string]: Object } = { originalEvent: e, cancel: false, requestType: 'Paste' }; this.trigger(events.actionBegin, evenArgs, (pasteArgs: { [key: string]: Object }) => { const currentLength: number = this.getText().trim().length; const selectionLength: number = this.getSelection().length; const pastedContentLength: number = (isNOU(e as ClipboardEvent) || isNOU((e as ClipboardEvent).clipboardData)) ? 0 : (e as ClipboardEvent).clipboardData.getData('text/plain').length; const totalLength: number = (currentLength - selectionLength) + pastedContentLength; if (this.editorMode === 'Markdown') { if (!(this.maxLength === -1 || totalLength <= this.maxLength)) { e.preventDefault(); } return; } if (!pasteArgs.cancel && this.inputElement.contentEditable === 'true' && (this.maxLength === -1 || totalLength <= this.maxLength)) { if (!isNOU(this.pasteCleanupModule)) { this.notify(events.pasteClean, { args: e as ClipboardEvent }); } else { const args: Object = { requestType: 'Paste', editorMode: this.editorMode, event: e }; let value: string = null; let htmlValue: boolean = false; if (e && !isNOU((e as ClipboardEvent).clipboardData)) { value = (e as ClipboardEvent).clipboardData.getData('text/plain'); htmlValue = (e as ClipboardEvent).clipboardData.getData('text/html').indexOf('MsoNormal') > 0; } const file: File = e && (e as ClipboardEvent).clipboardData && (e as ClipboardEvent).clipboardData.items.length > 0 ? (e as ClipboardEvent).clipboardData.items[0].getAsFile() : null; if (value !== null) { this.notify(events.paste, { file: file, args: e, text: value, isWordPaste: htmlValue }); } setTimeout(() => { this.formatter.onSuccess(this, args); }, 0); } } else { e.preventDefault(); } }); } /** * @param {string} action - specifies the string value. * @param {MouseEvent} event - specifies the event. * @returns {void} * @hidden * @deprecated */ public clipboardAction(action: string, event: MouseEvent | KeyboardEvent): void { switch (action.toLowerCase()) { case 'cut': this.onCut(); this.formatter.onSuccess(this, { requestType: 'Cut', editorMode: this.editorMode, event: event }); break; case 'copy': this.onCopy(); this.formatter.onSuccess(this, { requestType: 'Copy', editorMode: this.editorMode, event: event }); break; case 'paste': this.onPaste(event as KeyboardEvent); break; } } /** * Destroys the component (detaches/removes all event handlers, attributes, classes, and empties the component element). * * @returns {void} */ public destroy(): void { if (this.isDestroyed || !this.isRendered) { return; } if (this.element.offsetParent === null && !isNOU(this.toolbarModule)) { this.toolbarModule.destroy(); return; } this.notify(events.destroy, {}); this.destroyDependentModules(); if (!isNOU(this.timeInterval)) { clearInterval(this.timeInterval); this.timeInterval = null; } this.unWireEvents(); if (this.originalElement.tagName === 'TEXTAREA') { if (isBlazor()) { detach(this.valueContainer); this.valueContainer = this.element.querySelector('.e-blazor-hidden.e-control.e-richtexteditor'); } this.element.parentElement.insertBefore(this.valueContainer, this.element); this.valueContainer.id = this.getID(); this.valueContainer.removeAttribute('name'); detach(this.element); if (this.originalElement.innerHTML.trim() !== '') { if (!isBlazor()) { this.valueContainer.value = this.originalElement.innerHTML.trim(); this.setProperties({ value: (!isNOU(this.initialValue) ? this.initialValue : null) }, true); } } else { this.valueContainer.value = !this.isBlazor() ? this.valueContainer.defaultValue : this.defaultResetValue; } this.element = this.valueContainer; for (let i: number = 0; i < this.originalElement.classList.length; i++) { addClass([this.element], this.originalElement.classList[i]); } removeClass([this.element], classes.CLS_RTE_HIDDEN); } else { if (this.originalElement.innerHTML.trim() !== '') { this.element.innerHTML = this.originalElement.innerHTML.trim(); this.setProperties({ value: (!isNOU(this.initialValue) ? this.initialValue : null) }, true); } else { this.element.innerHTML = ''; } } if (this.placeholder && this.placeHolderWrapper) { this.placeHolderWrapper = null; } if (!isNOU(this.cssClass)) { const allClassName: string[] = this.cssClass.split(' '); for (let i: number = 0; i < allClassName.length; i++) { if (allClassName[i].trim() !== '') { removeClass([this.element], allClassName[i]); } } } this.removeHtmlAttributes(); this.removeAttributes(); super.destroy(); this.isRendered = false; if (this.enablePersistence) { window.localStorage.removeItem(this.getModuleName() + this.element.id); } } private removeHtmlAttributes(): void { if (this.htmlAttributes) { const keys: string[] = Object.keys(this.htmlAttributes); for (let i: number = 0; i < keys.length && this.element.hasAttribute(keys[i]); i++) { this.element.removeAttribute(keys[i]); } } } private removeAttributes(): void { if (!this.enabled) { removeClass([this.element], classes.CLS_DISABLED); } if (this.enableRtl) { removeClass([this.element], classes.CLS_RTL); } if (this.readonly) { removeClass([this.element], classes.CLS_RTE_READONLY); } if (this.element.style.width !== '' && this.originalElement.style.width === '') { this.element.style.removeProperty('width'); } if (this.element.style.height !== '' && this.originalElement.style.height === '') { this.element.style.removeProperty('height'); } this.element.removeAttribute('aria-disabled'); this.element.removeAttribute('role'); this.element.removeAttribute('tabindex'); } private destroyDependentModules(): void { /* destroy dependent modules */ this.renderModule.destroy(); this.formatter.editorManager.undoRedoManager.destroy(); this.sourceCodeModule.destroy(); } /** * Returns the HTML or Text inside the RichTextEditor. * * @returns {Element} - specifies the element. */ public getContent(): Element { if (this.iframeSettings.enable && isBlazor()) { return this.inputElement; } else { return this.contentModule.getPanel(); } } /** * Returns the text content as string. * * @returns {string} - specifies the string value. */ public getText(): string { return this.contentModule.getText(); } /** * Returns the html value of the selected content as string. * * @returns {string} - specifies the string value. */ public getSelectedHtml(): string { let range: Range; const wrapperElm: HTMLElement = this.createElement('div'); const selection: Selection = this.contentModule.getDocument().getSelection(); if (selection.rangeCount > 0) { range = selection.getRangeAt(0); const selectedHtml: DocumentFragment = range.cloneContents(); wrapperElm.appendChild(selectedHtml); } return wrapperElm.innerHTML; } /** * It shows the inline quick toolbar * * @returns {void} */ public showInlineToolbar(): void { if (this.inlineMode.enable) { const currentRange: Range = this.getRange(); const targetElm: HTMLElement = currentRange.endContainer.nodeName === '#text' ? currentRange.endContainer.parentElement : currentRange.endContainer as HTMLElement; const x: number = currentRange.getClientRects()[0].left; const y: number = currentRange.getClientRects()[0].top; this.quickToolbarModule.showInlineQTBar(x, y, (targetElm as HTMLElement)); } } /** * It hides the inline quick toolbar * * @returns {void} */ public hideInlineToolbar(): void { this.quickToolbarModule.hideInlineQTBar(); } /** * For internal use only - Get the module name. * * @returns {void} * @private * @deprecated */ protected getModuleName(): string { return 'richtexteditor'; } /** * Called internally if any of the property value changed. * * @param {RichTextEditorModel} newProp - specifies the the property. * @param {RichTextEditorModel} oldProp - specifies the old property. * @returns {void} * @hidden * @deprecated */ public onPropertyChanged(newProp: RichTextEditorModel, oldProp: RichTextEditorModel): void { for (const prop of Object.keys(newProp)) { switch (prop) { case 'value': { const nVal: string = newProp[prop]; const val: string = this.editorMode === 'HTML' ? getEditValue(nVal, this) : nVal; if (!isNOU(nVal) && nVal !== '') { this.value = this.serializeValue(((this.enableHtmlEncode) ? this.encode(decode(val)) : val)); } this.updatePanelValue(); this.setPlaceHolder(); this.notify(events.xhtmlValidation, { module: 'XhtmlValidation', newProp: newProp, oldProp: oldProp }); if (this.enableXhtml) { this.setProperties({ value: this.getXhtml() }, true); } if (this.showCharCount) { this.countModule.refresh(); } break; } case 'valueTemplate': this.setValue(); if (this.showCharCount) { this.countModule.refresh(); } break; case 'width': this.setWidth(newProp[prop]); if (this.toolbarSettings.enable) { this.toolbarModule.refreshToolbarOverflow(); this.resizeHandler(); } break; case 'height': this.setHeight(newProp[prop]); this.setContentHeight(); this.autoResize(); break; case 'readonly': this.setReadOnly(false); break; case 'cssClass': this.element.classList.remove(oldProp[prop]); this.setCssClass(newProp[prop]); break; case 'enabled': this.setEnable(); break; case 'enableRtl': this.updateRTL(); break; case 'placeholder': this.placeholder = newProp[prop]; this.setPlaceHolder(); break; case 'htmlAttributes': setAttributes(this.htmlAttributes, this, false, false); break; case 'iframeSettings': { const frameSetting: IFrameSettingsModel = oldProp[prop]; if (frameSetting.resources) { const iframe: HTMLDocument = this.contentModule.getDocument(); const header: HTMLHeadElement = iframe.querySelector('head'); let files: Element[]; if (frameSetting.resources.scripts) { files = <NodeListOf<Element> & Element[]>header.querySelectorAll('.' + classes.CLS_SCRIPT_SHEET); this.removeSheets(files); } if (frameSetting.resources.styles) { files = <NodeListOf<Element> & Element[]>header.querySelectorAll('.' + classes.CLS_STYLE_SHEET); this.removeSheets(files); } } this.setIframeSettings(); break; } case 'locale': super.refresh(); break; case 'inlineMode': this.notify(events.modelChanged, { module: 'quickToolbar', newProp: newProp, oldProp: oldProp }); this.setContentHeight(); break; case 'toolbarSettings': this.notify(events.modelChanged, { module: 'toolbar', newProp: newProp, oldProp: oldProp }); this.setContentHeight(); break; case 'maxLength': if (this.showCharCount) { this.countModule.refresh(); } break; case 'showCharCount': if (newProp[prop] && this.countModule) { this.countModule.renderCount(); } else if (newProp[prop] === false && this.countModule) { this.countModule.destroy(); } break; case 'enableHtmlEncode': this.updateValueData(); this.updatePanelValue(); this.setPlaceHolder(); if (this.showCharCount) { this.countModule.refresh(); } break; case 'undoRedoSteps': case 'undoRedoTimer': this.formatter.editorManager.observer.notify(CONSTANT.MODEL_CHANGED, { newProp: newProp, oldProp: oldProp }); break; case 'enableXhtml': this.notify(events.xhtmlValidation, { module: 'XhtmlValidation', newProp: newProp, oldProp: oldProp }); break; case 'quickToolbarSettings': // eslint-disable-next-line newProp.quickToolbarSettings.showOnRightClick ? this.wireContextEvent() : this.unWireContextEvent(); this.notify(events.modelChanged, { newProp: newProp, oldProp: oldProp }); break; default: this.notify(events.modelChanged, { newProp: newProp, oldProp: oldProp }); break; } } } /** * @hidden * @returns {void} * @deprecated */ public updateValueData(): void { if (this.enableHtmlEncode) { this.setProperties({ value: this.encode(decode(this.inputElement.innerHTML)) }, true); } else { this.setProperties({ value: /<[a-z][\s\S]*>/i.test(this.inputElement.innerHTML) ? this.inputElement.innerHTML : decode(this.inputElement.innerHTML) }); } } private removeSheets(srcList: Element[]): void { let i: number; for (i = 0; i < srcList.length; i++) { detach(srcList[i]); } } private updatePanelValue(): void { let value: string = this.value; value = (this.enableHtmlEncode && this.value) ? decode(value) : value; const getTextArea: HTMLInputElement = this.element.querySelector('.e-rte-srctextarea') ; if (value) { if (getTextArea && getTextArea.style.display === 'block') { getTextArea.value = this.value; } if (this.valueContainer) { this.valueContainer.value = (this.enableHtmlEncode) ? this.value : value; } if (this.editorMode === 'HTML' && this.inputElement && this.inputElement.innerHTML.trim() !== value.trim()) { this.inputElement.innerHTML = value; } else if (this.editorMode === 'Markdown' && this.inputElement && (this.inputElement as HTMLTextAreaElement).value.trim() !== value.trim()) { (this.inputElement as HTMLTextAreaElement).value = value; } } else { if (getTextArea && getTextArea.style.display === 'block') { getTextArea.value = ''; } if (this.editorMode === 'HTML') { this.inputElement.innerHTML = '<p><br/></p>'; } else { (this.inputElement as HTMLTextAreaElement).value = ''; } if (this.valueContainer) { this.valueContainer.value = ''; } } if (this.showCharCount) { this.countModule.refresh(); } } private setHeight(height: string | number): void { if (height !== 'auto') { this.element.style.height = formatUnit(height); } else { this.element.style.height = 'auto'; } if (this.toolbarSettings.type === 'Expand' && (typeof (this.height) === 'string' && this.height.indexOf('px') > -1 || typeof (this.height) === 'number')) { this.element.classList.add(classes.CLS_RTE_FIXED_TB_EXPAND); } else { this.element.classList.remove(classes.CLS_RTE_FIXED_TB_EXPAND); } } /** * setPlaceHolder method * * @returns {void} * @hidden * @deprecated */ public setPlaceHolder(): void { if (this.inputElement && this.placeholder && this.iframeSettings.enable !== true) { if (this.editorMode !== 'Markdown') { if (!this.placeHolderWrapper) { this.placeHolderWrapper = this.createElement('span', { className: 'rte-placeholder e-rte-placeholder' }); if (this.inputElement) { this.inputElement.parentElement.insertBefore(this.placeHolderWrapper, this.inputElement); } attributes(this.placeHolderWrapper, { 'style': 'font-size: 14px; padding: 16px; margin-left: 0px; margin-right: 0px;' }); } this.placeHolderWrapper.innerHTML = this.placeholder; if (this.inputElement.textContent.length === 0 && !isNOU(this.inputElement.firstChild) && this.inputElement.firstChild.nodeName === 'P' && !isNOU(this.inputElement.firstChild.firstChild) && this.inputElement.firstChild.firstChild.nodeName === 'BR' && this.inputElement.innerHTML !== '<p><br></p><p><br></p>') { this.placeHolderWrapper.style.display = 'block'; } else { this.placeHolderWrapper.style.display = 'none'; } } else { this.inputElement.setAttribute('placeholder', this.placeholder); } } } private setWidth(width: string | number): void { if (width !== 'auto') { setStyleAttribute(this.element, { 'width': formatUnit(this.width) }); } else { this.element.style.width = 'auto'; } } private setCssClass(cssClass: string): void { if (!isNOU(cssClass)) { const allClassName: string[] = cssClass.split(' '); for (let i: number = 0; i < allClassName.length; i++) { if (allClassName[i].trim() !== '') { this.element.classList.add(allClassName[i]); } } } } private updateRTL(): void { this.notify(events.rtlMode, { enableRtl: this.enableRtl }); if (this.enableRtl) { this.element.classList.add(classes.CLS_RTL); } else { this.element.classList.remove(classes.CLS_RTL); } } private updateReadOnly(): void { this.notify(events.readOnlyMode, { editPanel: this.inputElement, mode: this.readonly }); } /** * setReadOnly method * * @param {boolean} initial - specifies the boolean value * @returns {void} * @hidden * @deprecated */ public setReadOnly(initial?: boolean): void { this.updateReadOnly(); if (!initial) { if (this.readonly && this.enabled) { this.unbindEvents(); } else if (this.enabled) { this.bindEvents(); } } } /** * By default, prints all the pages of the RichTextEditor. * * @returns {void} */ public print(): void { let printWind: Window; const printArgs: PrintEventArgs = { element: this.inputElement, requestType: 'print', cancel: false }; this.trigger(events.actionBegin, printArgs, (printingArgs: PrintEventArgs) => { printWind = window.open('', 'print', 'height=' + window.outerHeight + ',width=' + window.outerWidth); if (Browser.info.name === 'msie') { printWind.resizeTo(screen.availWidth, screen.availHeight); } printWind = printWindow(this.inputElement, printWind); if (!printingArgs.cancel) { const actionArgs: ActionCompleteEventArgs = { requestType: 'print' }; this.trigger(events.actionComplete, actionArgs); } }); } /** * Refresh the view of the editor. * * @returns {void} * @public */ public refreshUI(): void { this.renderModule.refresh(); } /** * Shows the Rich Text Editor component in full-screen mode. * * @returns {void} */ public showFullScreen(): void { this.fullScreenModule.showFullScreen(); } /** * Enables the give toolbar items in the Rich Text Editor component. * * @returns {void} * @param {string | string[]} items - Specifies the single or collection of items * @param {boolean} muteToolbarUpdate enable/disables the toolbar item status in RichTextEditor. * that you want to be enable in Rich Text Editor’s Toolbar. * * @public */ public enableToolbarItem(items: string | string[], muteToolbarUpdate?: boolean): void { this.toolbarModule.enableTBarItems(this.getBaseToolbarObject(), items, true, muteToolbarUpdate); } /** * Disables the given toolbar items in the Rich Text Editor component. * * @returns {void} * @param {string | string[]} items - Specifies the single or collection of items * @param {boolean} muteToolbarUpdate enable/disables the toolbar item status in RichTextEditor. * that you want to be disable in Rich Text Editor’s Toolbar. * * @public */ public disableToolbarItem(items: string | string[], muteToolbarUpdate?: boolean): void { this.toolbarModule.enableTBarItems(this.getBaseToolbarObject(), items, false, muteToolbarUpdate); } /** * Removes the give toolbar items from the Rich Text Editor component. * * @returns {void} * @param {string | string[]} items - Specifies the single or collection of items * that you want to be remove from Rich Text Editor’s Toolbar. * * @public */ public removeToolbarItem(items: string | string[]): void { this.toolbarModule.removeTBarItems(items); } /** * Get the selected range from the RichTextEditor's content. * * @returns {void} * @public * @deprecated */ public getRange(): Range { return this.formatter.editorManager.nodeSelection.getRange(this.contentModule.getDocument()); } private initializeServices(): void { this.serviceLocator.register('rendererFactory', new RendererFactory); this.serviceLocator.register('rteLocale', this.localeObj = new L10n(this.getModuleName(), defaultLocale, this.locale)); this.serviceLocator.register('dialogRenderObject', new DialogRenderer(this)); } private RTERender(): void { const rendererFactory: RendererFactory = this.serviceLocator.getService<RendererFactory>('rendererFactory'); this.contentModule = rendererFactory.getRenderer(RenderType.Content); this.fullScreenModule = new FullScreen(this); this.renderModule.render(); this.inputElement = <HTMLElement>this.contentModule.getEditPanel(); this.setHeight(this.height); setAttributes(this.htmlAttributes, this, false, true); if (this.iframeSettings) { this.setIframeSettings(); } this.setCssClass(this.cssClass); this.updateEnable(); this.setPlaceHolder(); this.updateRTL(); this.updateReadOnly(); this.updatePanelValue(); if (this.enableHtmlEncode && !isNOU(this.value)) { this.setProperties({ value: this.encode(decode(this.value)) }); } } private setIframeSettings(): void { if (this.iframeSettings.resources) { const styleSrc: string[] = this.iframeSettings.resources.styles; const scriptSrc: string[] = this.iframeSettings.resources.scripts; if (this.iframeSettings.resources.scripts.length > 0) { this.InjectSheet(true, scriptSrc); } if (this.iframeSettings.resources.styles.length > 0) { this.InjectSheet(false, styleSrc); } } if (this.iframeSettings.attributes) { setAttributes(this.iframeSettings.attributes, this, true, false); } } private InjectSheet(scriptSheet: boolean, srcList: string[]): void { try { if (srcList && srcList.length > 0) { const iFrame: HTMLDocument = this.contentModule.getDocument(); const target: HTMLElement = iFrame.querySelector('head'); for (let i: number = 0; i < srcList.length; i++) { if (scriptSheet) { const scriptEle: HTMLScriptElement = this.createScriptElement(); scriptEle.src = srcList[i]; target.appendChild(scriptEle); } else { const styleEle: HTMLLinkElement = this.createStyleElement(); styleEle.href = srcList[i]; target.appendChild(styleEle); } } } } catch (e) { return; } } private createScriptElement(): HTMLScriptElement { const scriptEle: HTMLScriptElement = this.createElement('script', { className: classes.CLS_SCRIPT_SHEET }) as HTMLScriptElement; scriptEle.type = 'text/javascript'; return scriptEle; } private createStyleElement(): HTMLLinkElement { const styleEle: HTMLLinkElement = this.createElement('link', { className: classes.CLS_STYLE_SHEET }) as HTMLLinkElement; styleEle.rel = 'stylesheet'; return styleEle; } private isBlazor(): boolean { return (!isBlazor() ? false : true); } private setValue(): void { if (this.valueTemplate) { if (typeof this.valueTemplate === 'string') { this.setProperties({ value: this.valueTemplate }); } else { const compiledString: Function = compile(this.valueTemplate); const compiledTemplate: Element[] = compiledString({}); for (let i: number = 0; i < compiledTemplate.length; i++) { const item: Element = compiledTemplate[i] as Element; append([item], this.element); } this.setProperties({ value: this.element.innerHTML.trim() }); } } else { // eslint-disable-next-line const innerHtml: string = !isNOU(this.element.innerHTML) && this.element.innerHTML.replace(/<(\/?|\!?)(!--!--)>/g, '').trim(); if (innerHtml !== '') { if (this.element.tagName === 'TEXTAREA') { this.setProperties({ value: decode(innerHtml) }); } else { this.setProperties({ value: innerHtml }); } } } } private updateResizeFlag(): void { this.isResizeInitialized = true; } /** * Image max width calculation method * * @returns {void} * @hidden * @deprecated */ public getInsertImgMaxWidth(): string | number { const maxWidth: string | number = this.insertImageSettings.maxWidth; // eslint-disable-next-line const imgPadding: number = 12 const imgResizeBorder: number = 2; const editEle: HTMLElement = this.contentModule.getEditPanel() as HTMLElement; const eleStyle: CSSStyleDeclaration = window.getComputedStyle(editEle); const editEleMaxWidth: number = editEle.offsetWidth - (imgPadding + imgResizeBorder + parseFloat(eleStyle.paddingLeft.split('px')[0]) + parseFloat(eleStyle.paddingRight.split('px')[0]) + parseFloat(eleStyle.marginLeft.split('px')[0]) + parseFloat(eleStyle.marginRight.split('px')[0])); return isNOU(maxWidth) ? editEleMaxWidth : maxWidth; } /** * setContentHeight method * * @param {string} target - specifies the target value. * @param {boolean} isExpand - specifies the bollean value. * @returns {void} * @hidden * @deprecated */ public setContentHeight(target?: string, isExpand?: boolean): void { let heightValue: string; let topValue: number = 0; let rteHeightPercent: string; const heightPercent: boolean = typeof (this.height) === 'string' && this.height.indexOf('%') > -1; const cntEle: HTMLElement = (this.sourceCodeModule.getPanel() && this.sourceCodeModule.getPanel().parentElement.style.display === 'block') ? this.sourceCodeModule.getPanel().parentElement : <HTMLElement>this.contentModule.getPanel(); let rteHeight: number = this.element.offsetHeight; if (rteHeight === 0 && this.height !== 'auto' && !this.getToolbar()) { rteHeight = parseInt(this.height as string, 10); if (heightPercent) { rteHeightPercent = this.height as string; } } const tbHeight: number = this.getToolbar() ? this.toolbarModule.getToolbarHeight() : 0; const rzHandle: HTMLElement = this.element.querySelector('.' + classes.CLS_RTE_RES_HANDLE) as HTMLElement; const rzHeight: number = this.enableResize ? (!isNOU(rzHandle) ? (rzHandle.offsetHeight + 8) : 0) : 0; const expandPopHeight: number = this.getToolbar() ? this.toolbarModule.getExpandTBarPopHeight() : 0; if (this.toolbarSettings.type === ToolbarType.Expand && isExpand && target !== 'preview') { heightValue = (this.height === 'auto' && rzHeight === 0) ? 'auto' : rteHeight - (tbHeight + expandPopHeight + rzHeight) + 'px'; topValue = (!this.toolbarSettings.enableFloating) ? expandPopHeight : 0; } else { if (this.height === 'auto' && !(this.element.classList.contains('e-rte-full-screen')) && !this.isResizeInitialized) { heightValue = 'auto'; } else { heightValue = heightPercent && rteHeightPercent ? rteHeightPercent : rteHeight - (tbHeight + rzHeight) + 'px'; } } if (target !== 'windowResize') { if (this.iframeSettings.enable) { if (heightValue !== 'auto') { setStyleAttribute(cntEle, { height: heightValue, marginTop: topValue + 'px' }); } } else { setStyleAttribute(cntEle, { height: heightValue, marginTop: topValue + 'px' }); } } if (this.iframeSettings.enable && target === 'sourceCode') { const codeElement: HTMLElement = <HTMLElement>select('.' + classes.CLS_RTE_CONTENT, this.element); setStyleAttribute(codeElement, { height: heightValue, marginTop: topValue + 'px' }); } if (this.toolbarSettings.enableFloating && this.getToolbar() && !this.inlineMode.enable) { const tbWrapHeight: string = (isExpand ? (tbHeight + expandPopHeight) : tbHeight) + 'px'; setStyleAttribute(this.getToolbar().parentElement, { height: tbWrapHeight }); } if (rzHeight === 0) { this.autoResize(); } } /** * Retrieves the HTML from RichTextEditor. * * @returns {void} * @public */ public getHtml(): string { return this.serializeValue(this.contentModule.getEditPanel().innerHTML); } /** * Retrieves the Rich Text Editor's XHTML validated HTML content when `enableXhtml` property is enabled. * * @returns {void} * @public */ public getXhtml(): string { let currentValue: string = this.value; if (!isNOU(currentValue) && this.enableXhtml) { currentValue = this.htmlEditorModule.xhtmlValidation.selfEncloseValidation(currentValue); } return currentValue; } /** * Shows the source HTML/MD markup. * * @returns {void} * @public */ public showSourceCode(): void { if (this.readonly) { return; } this.notify(events.sourceCode, {}); } /** * Returns the maximum number of characters in the Rich Text Editor. * * @returns {void} * @public */ public getCharCount(): number { const htmlText : string = this.editorMode === 'Markdown' ? (this.inputElement as HTMLTextAreaElement).value.trim() : (this.inputElement as HTMLTextAreaElement).textContent.trim(); let htmlLength: number; if (this.editorMode !== 'Markdown' && htmlText.indexOf('\u200B') !== -1) { htmlLength = htmlText.replace(/\u200B/g, '').length; } else { htmlLength = htmlText.length; } return htmlLength; } /** * Show the dialog in the Rich Text Editor. * * @param {DialogType} type - specifies the dialog type. * @returns {void} * @public */ public showDialog(type: DialogType): void { if (type === DialogType.InsertLink) { this.notify(events.showLinkDialog, {}); } else if (type === DialogType.InsertImage) { this.notify(events.showImageDialog, {}); } else if (type === DialogType.InsertTable) { this.notify(events.showTableDialog, {}); } } /** * Close the dialog in the Rich Text Editor. * * @param {DialogType} type - specifies the dialog type. * @returns {void} * @public */ public closeDialog(type: DialogType): void { if (type === DialogType.InsertLink) { this.notify(events.closeLinkDialog, {}); } else if (type === DialogType.InsertImage) { this.notify(events.closeImageDialog, {}); } else if (type === DialogType.InsertTable) { this.notify(events.closeTableDialog, {}); } } /** * @returns {void} * @hidden * @deprecated */ public getBaseToolbarObject(): BaseToolbar { let tbObj: BaseToolbar; if (this.inlineMode.enable && (!Browser.isDevice || isIDevice())) { tbObj = this.quickToolbarModule && this.quickToolbarModule.getInlineBaseToolbar(); } else { tbObj = this.toolbarModule && this.toolbarModule.getBaseToolbar(); } return tbObj; } /** * @returns {void} * @hidden * @deprecated */ public getToolbar(): HTMLElement { return this.toolbarModule ? <HTMLElement>this.toolbarModule.getToolbarElement() : null; } /** * @returns {void} * @hidden * @deprecated */ public getToolbarElement(): Element { return this.toolbarModule && this.toolbarModule.getToolbarElement(); } /** * @returns {void} * getID method * * @hidden * @deprecated */ public getID(): string { return (this.originalElement.tagName === 'TEXTAREA' ? this.valueContainer.id : this.element.id); } private mouseDownHandler(e: MouseEvent | TouchEvent): void { const touch: Touch = <Touch>((e as TouchEvent).touches ? (e as TouchEvent).changedTouches[0] : e); addClass([this.element], [classes.CLS_FOCUS]); this.preventDefaultResize(e as MouseEvent); this.notify(events.mouseDown, { args: e }); this.clickPoints = { clientX: touch.clientX, clientY: touch.clientY }; } private preventImgResize(e: FocusEvent | MouseEvent): void { if ((e.target as HTMLElement).nodeName.toLocaleLowerCase() === 'img') { e.preventDefault(); } } /** * preventDefaultResize method * * @param {FocusEvent} e - specifies the event. * @returns {void} * @hidden * @deprecated */ // eslint-disable-next-line public preventDefaultResize(e: FocusEvent | MouseEvent): void { if (Browser.info.name === 'msie') { this.contentModule.getEditPanel().addEventListener('mscontrolselect', this.preventImgResize); } else if (Browser.info.name === 'mozilla') { this.contentModule.getDocument().execCommand('enableObjectResizing', false, 'false'); this.contentModule.getDocument().execCommand('enableInlineTableEditing', false, 'false'); } } // eslint-disable-next-line private defaultResize(e: FocusEvent): void { if (Browser.info.name === 'msie') { this.contentModule.getEditPanel().removeEventListener('mscontrolselect', this.preventImgResize); } else if (Browser.info.name === 'mozilla') { this.contentModule.getDocument().execCommand('enableObjectResizing', true, 'true'); this.contentModule.getDocument().execCommand('enableInlineTableEditing', true, 'true'); } } private resizeHandler(): void { let isExpand: boolean = false; if (!document.body.contains(this.element)) { document.defaultView.removeEventListener('resize', this.onResizeHandler, true); return; } if (this.toolbarSettings.enable && !this.inlineMode.enable) { this.toolbarModule.refreshToolbarOverflow(); isExpand = this.toolbarModule.baseToolbar.toolbarObj.element.classList.contains(classes.CLS_EXPAND_OPEN); } this.setContentHeight('windowResize', isExpand); this.notify(events.windowResize, null); } private scrollHandler(e: Event): void { this.notify(events.scroll, { args: e }); } private contentScrollHandler(e: Event): void { this.notify(events.contentscroll, { args: e }); } private focusHandler(e: FocusEvent): void { if ((!this.isRTE || this.isFocusOut)) { this.isRTE = this.isFocusOut ? false : true; this.isFocusOut = false; addClass([this.element], [classes.CLS_FOCUS]); if (this.editorMode === 'HTML') { this.cloneValue = (this.inputElement.innerHTML === '<p><br></p>') ? null : this.enableHtmlEncode ? this.encode(decode(this.inputElement.innerHTML)) : this.inputElement.innerHTML; } else { this.cloneValue = (this.inputElement as HTMLTextAreaElement).value === '' ? null : (this.inputElement as HTMLTextAreaElement).value; } const active: Element = document.activeElement; if (active === this.element || active === this.getToolbarElement() || active === this.contentModule.getEditPanel() || ((this.iframeSettings.enable && active === this.contentModule.getPanel()) && e.target && !(e.target as HTMLElement).classList.contains('e-img-inner') && (e.target && (e.target as HTMLElement).parentElement && !(e.target as HTMLElement).parentElement.classList.contains('e-img-wrap'))) || closest(active, '.e-rte-toolbar') === this.getToolbarElement()) { (this.contentModule.getEditPanel() as HTMLElement).focus(); if (!isNOU(this.getToolbarElement())) { this.getToolbarElement().setAttribute('tabindex', '-1'); const items: NodeList = this.getToolbarElement().querySelectorAll('[tabindex="0"]'); for (let i: number = 0; i < items.length; i++) { (items[i] as HTMLElement).setAttribute('tabindex', '-1'); } } } this.preventDefaultResize(e); this.trigger('focus', { event: e, isInteracted: Object.keys(e).length === 0 ? false : true }); if (!isNOU(this.saveInterval) && this.saveInterval > 0 && !this.autoSaveOnIdle) { this.timeInterval = setInterval(this.updateValueOnIdle.bind(this), this.saveInterval); } EventHandler.add(document, 'mousedown', this.onDocumentClick, this); } if (!isNOU(this.getToolbarElement())) { const toolbarItem: NodeList = this.getToolbarElement().querySelectorAll('input,select,button,a,[tabindex]'); for (let i: number = 0; i < toolbarItem.length; i++) { if ((!(toolbarItem[i] as HTMLElement).classList.contains('e-rte-dropdown-btn') && !(toolbarItem[i] as HTMLElement).classList.contains('e-insert-table-btn')) && (!(toolbarItem[i] as HTMLElement).hasAttribute('tabindex') || (toolbarItem[i] as HTMLElement).getAttribute('tabindex') !== '-1')) { (toolbarItem[i] as HTMLElement).setAttribute('tabindex', '-1'); } } } } private getUpdatedValue(): string { let value: string; if (!isNOU(this.tableModule)) { this.tableModule.removeResizeElement(); } const getTextArea: HTMLInputElement = this.element.querySelector('.e-rte-srctextarea') ; if (this.editorMode === 'HTML') { value = (this.inputElement.innerHTML === '<p><br></p>') ? null : this.enableHtmlEncode ? this.encode(decode(this.inputElement.innerHTML)) : this.inputElement.innerHTML; if (getTextArea && getTextArea.style.display === 'block') { value = getTextArea.value; } } else { value = (this.inputElement as HTMLTextAreaElement).value === '' ? null : (this.inputElement as HTMLTextAreaElement).value; } return value; } private updateValueOnIdle(): void { if (!isNOU(this.tableModule) && !isNOU(this.inputElement.querySelector('.e-table-box.e-rbox-select'))) { return; } this.setProperties({ value: this.getUpdatedValue() }, true); this.valueContainer.value = this.value; this.invokeChangeEvent(); } private updateIntervalValue(): void { clearTimeout(this.idleInterval); this.idleInterval = setTimeout(this.updateValueOnIdle.bind(this), 0); } private updateStatus(e: StatusArgs): void { if (!isNOU(e.html) || !isNOU(e.markdown)) { const status: { [key: string]: boolean } = this.formatter.editorManager.undoRedoManager.getUndoStatus(); const eventArgs: ToolbarStatusEventArgs = { undo: status.undo, redo: status.redo, html: e.html, markdown: e.markdown }; this.trigger(events.updatedToolbarStatus, eventArgs); } } private onDocumentClick(e: MouseEvent): void { const target: HTMLElement = <HTMLElement>e.target; const rteElement: Element = closest(target, '.' + classes.CLS_RTE); if (!this.element.contains(e.target as Node) && document !== e.target && rteElement !== this.element && !closest(target, '[aria-owns="' + this.getID() + '"]')) { this.isBlur = true; this.isRTE = false; } this.notify(events.docClick, { args: e }); if (e.detail > 3) { e.preventDefault(); } } private blurHandler(e: FocusEvent): void { let trg: Element = e.relatedTarget as Element; if (trg) { const rteElement: Element = closest(trg, '.' + classes.CLS_RTE); if (rteElement && rteElement === this.element) { this.isBlur = false; if (trg === this.getToolbarElement()) { trg.setAttribute('tabindex', '-1'); } } else if (closest(trg, '[aria-owns="' + this.getID() + '"]')) { this.isBlur = false; } else { this.isBlur = true; trg = null; } } if (this.isBlur && isNOU(trg)) { removeClass([this.element], [classes.CLS_FOCUS]); this.notify(events.focusChange, {}); const value: string = this.getUpdatedValue(); this.setProperties({ value: value }); this.notify(events.toolbarRefresh, { args: e, documentNode: document }); this.invokeChangeEvent(); this.isFocusOut = true; this.isBlur = false; dispatchEvent(this.valueContainer, 'focusout'); this.defaultResize(e); this.trigger('blur', { event: e, isInteracted: Object.keys(e).length === 0 ? false : true }); if (!isNOU(this.timeInterval)) { clearInterval(this.timeInterval); this.timeInterval = null; } EventHandler.remove(document, 'mousedown', this.onDocumentClick); } else { this.isRTE = true; } } /** * invokeChangeEvent method * * @returns {void} * @hidden * @deprecated */ private contentChanged(): void { if (this.autoSaveOnIdle) { if (!isNOU(this.saveInterval)) { clearTimeout(this.timeInterval); this.timeInterval = setTimeout(this.updateIntervalValue.bind(this), this.saveInterval); } } } /** * invokeChangeEvent method * * @returns {void} * @hidden * @deprecated */ public invokeChangeEvent(): void { let currentValue: string; if (this.enableXhtml) { currentValue = this.getXhtml(); } else { currentValue = this.value; } const eventArgs: ChangeEventArgs = { value: currentValue }; if (this.value !== this.cloneValue) { this.trigger('change', eventArgs); this.cloneValue = this.value; } } /** * @returns {void} * @hidden * @deprecated */ public wireScrollElementsEvents(): void { this.scrollParentElements = getScrollableParent(this.element); for (const element of this.scrollParentElements) { EventHandler.add(element, 'scroll', this.scrollHandler, this); } if (!this.iframeSettings.enable) { EventHandler.add(this.contentModule.getPanel(), 'scroll', this.contentScrollHandler, this); } } private wireContextEvent(): void { if (this.quickToolbarSettings.showOnRightClick) { EventHandler.add(this.inputElement, 'contextmenu', this.contextHandler, this); if (Browser.isDevice) { this.touchModule = new EJ2Touch(this.inputElement, { tapHold: this.touchHandler.bind(this), tapHoldThreshold: 500 }); } } } private unWireContextEvent(): void { EventHandler.remove(this.inputElement, 'contextmenu', this.contextHandler); if (Browser.isDevice && this.touchModule) { this.touchModule.destroy(); } } /** * @returns {void} * @hidden * @deprecated */ public unWireScrollElementsEvents(): void { this.scrollParentElements = getScrollableParent(this.element); for (const element of this.scrollParentElements) { EventHandler.remove(element, 'scroll', this.scrollHandler); } if (!this.iframeSettings.enable) { EventHandler.remove(this.contentModule.getPanel(), 'scroll', this.contentScrollHandler); } } private touchHandler(e: TapEventArgs): void { this.notifyMouseUp(e.originalEvent); this.triggerEditArea(e.originalEvent); } private contextHandler(e: MouseEvent): void { const closestElem: Element = closest((e.target as HTMLElement), 'a, table, img'); if (this.inlineMode.onSelection === false || (!isNOU(closestElem) && this.inputElement.contains(closestElem) && (closestElem.tagName === 'IMG' || closestElem.tagName === 'TABLE' || closestElem.tagName === 'A'))) { e.preventDefault(); } } private resetHandler(): void { const defaultValue: string = this.valueContainer.defaultValue.trim(); this.setProperties({ value: defaultValue === '' ? null : (this.isBlazor() ? this.defaultResetValue : defaultValue) }); } /** * @returns {void} * @hidden * @deprecated */ public autoResize(): void { if (this.height === 'auto') { if (this.editorMode === 'Markdown') { setTimeout(() => { this.setAutoHeight(this.inputElement); }, 0); } else if (this.iframeSettings.enable) { const iframeElement: HTMLIFrameElement = this.element.querySelector('#' + this.getID() + '_rte-view'); setTimeout(() => { this.setAutoHeight(iframeElement); }, 100); this.inputElement.style.overflow = 'hidden'; } } else { this.inputElement.style.overflow = null; } } private setAutoHeight(element: HTMLElement): void { if (!isNOU(element)) { element.style.height = ''; element.style.height = this.inputElement.scrollHeight + 'px'; element.style.overflow = 'hidden'; } } private wireEvents(): void { this.element.addEventListener('focusin', this.onFocusHandler, true); this.element.addEventListener('focusout', this.onBlurHandler, true); this.on(events.contentChanged, this.contentChanged, this); this.on(events.resizeInitialized, this.updateResizeFlag, this); this.on(events.updateTbItemsStatus, this.updateStatus, this); if (this.readonly && this.enabled) { return; } this.bindEvents(); } private restrict(e: MouseEvent | KeyboardEvent): void { if (this.maxLength >= 0 ) { const element: string = this.editorMode === 'Markdown' ? this.contentModule.getText() : ((e as MouseEvent).currentTarget as HTMLElement).textContent.trim(); const array: number[] = [8, 16, 17, 37, 38, 39, 40, 46, 65]; let arrayKey: number; for (let i: number = 0; i <= array.length - 1; i++) { if ((e as MouseEvent).which === array[i]) { if ((e as MouseEvent).ctrlKey && (e as MouseEvent).which === 65) { return; } else if ((e as MouseEvent).which !== 65) { arrayKey = array[i]; return; } } } if ((element.length >= this.maxLength && this.maxLength !== -1) && (e as MouseEvent).which !== arrayKey) { (e as MouseEvent).preventDefault(); } } } private bindEvents(): void { this.keyboardModule = new KeyboardEvents(this.inputElement, { keyAction: this.keyDown.bind(this), keyConfigs: { ...this.formatter.keyConfig, ...this.keyConfig }, eventName: 'keydown' }); const formElement: Element = closest(this.valueContainer, 'form'); if (formElement) { EventHandler.add(formElement, 'reset', this.resetHandler, this); } EventHandler.add(this.inputElement, 'keyup', this.keyUp, this); EventHandler.add(this.inputElement, 'paste', this.onPaste, this); EventHandler.add(this.inputElement, Browser.touchEndEvent, debounce(this.mouseUp, 30), this); EventHandler.add(this.inputElement, Browser.touchStartEvent, this.mouseDownHandler, this); this.wireContextEvent(); this.formatter.editorManager.observer.on(CONSTANT.KEY_DOWN_HANDLER, this.editorKeyDown, this); this.element.ownerDocument.defaultView.addEventListener('resize', this.onResizeHandler, true); if (this.iframeSettings.enable) { EventHandler.add(this.inputElement, 'focusin', this.focusHandler, this); EventHandler.add(this.inputElement, 'focusout', this.blurHandler, this); EventHandler.add(this.inputElement.ownerDocument, 'scroll', this.contentScrollHandler, this); EventHandler.add(this.inputElement.ownerDocument, Browser.touchStartEvent, this.onIframeMouseDown, this); } this.wireScrollElementsEvents(); } private onIframeMouseDown(e: MouseEvent): void { this.isBlur = false; this.notify(events.iframeMouseDown, e); } private editorKeyDown(e: IHtmlKeyboardEvent): void { switch (e.event.action) { case 'copy': this.onCopy(); break; case 'cut': this.onCut(); break; } if (e.callBack && (e.event.action === 'copy' || e.event.action === 'cut' || e.event.action === 'delete')) { e.callBack({ requestType: e.event.action, editorMode: 'HTML', event: e.event }); } } private unWireEvents(): void { this.element.removeEventListener('focusin', this.onFocusHandler, true); this.element.removeEventListener('focusout', this.onBlurHandler, true); this.off(events.contentChanged, this.contentChanged); this.off(events.resizeInitialized, this.updateResizeFlag); this.off(events.updateTbItemsStatus, this.updateStatus); if (this.readonly && this.enabled) { return; } this.unbindEvents(); } private unbindEvents(): void { if (this.keyboardModule) { this.keyboardModule.destroy(); } const formElement: Element = closest(this.valueContainer, 'form'); if (formElement) { EventHandler.remove(formElement, 'reset', this.resetHandler); } EventHandler.remove(this.inputElement, 'keyup', this.keyUp); EventHandler.remove(this.inputElement, 'paste', this.onPaste); EventHandler.remove(this.inputElement, Browser.touchEndEvent, debounce(this.mouseUp, 30)); EventHandler.remove(this.inputElement, Browser.touchStartEvent, this.mouseDownHandler); this.unWireContextEvent(); if (this.formatter) { this.formatter.editorManager.observer.off(CONSTANT.KEY_DOWN_HANDLER, this.editorKeyDown); } this.element.ownerDocument.defaultView.removeEventListener('resize', this.onResizeHandler, true); if (this.iframeSettings.enable) { EventHandler.remove(this.inputElement, 'focusin', this.focusHandler); EventHandler.remove(this.inputElement, 'focusout', this.blurHandler); EventHandler.remove(this.inputElement.ownerDocument, 'scroll', this.contentScrollHandler); EventHandler.remove(this.inputElement.ownerDocument, Browser.touchStartEvent, this.onIframeMouseDown); } this.unWireScrollElementsEvents(); } }
RichTextEditor
anonymous_pro.gen.go
package fonts // name: "Anonymous Pro" // designer: "Mark Simonson" // license: "OFL" // category: "MONOSPACE" // date_added: "2010-12-15" // fonts { // name: "Anonymous Pro" // style: "normal" // weight: 400 // filename: "AnonymousPro-Regular.ttf" // post_script_name: "AnonymousPro-Regular" // full_name: "Anonymous Pro Regular" // copyright: "Copyright (c) Mark Simonson 2009-2010. All rights reserved." // } // fonts { // name: "Anonymous Pro" // style: "italic" // weight: 400 // filename: "AnonymousPro-Italic.ttf" // post_script_name: "AnonymousPro-Italic" // full_name: "Anonymous Pro Italic" // copyright: "Copyright (c) Mark Simonson 2009-2010. All rights reserved." // } // fonts { // name: "Anonymous Pro" // style: "normal" // weight: 700 // filename: "AnonymousPro-Bold.ttf" // post_script_name: "AnonymousPro-Bold" // full_name: "Anonymous Pro Bold" // copyright: "Copyright (c) Mark Simonson 2009-2010. All rights reserved." // } // fonts { // name: "Anonymous Pro" // style: "italic" // weight: 700 // filename: "AnonymousPro-BoldItalic.ttf" // post_script_name: "AnonymousPro-BoldItalic" // full_name: "Anonymous Pro Bold Italic" // copyright: "Copyright (c) Mark Simonson 2009-2010. All rights reserved." // }
// subsets: "menu" const AnonymousProRegular = `@font-face { font-family: 'Anonymous Pro'; font-style: normal; font-weight: 400; src: local('Anonymous Pro Regular'), local('AnonymousPro-Regular'), url('data:font/woff2;base64,d09GMgABAAAAAESEABAAAAAAmHgAAEQiAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmAWi2AAgx4ILgmCYREQCoKEVIHweAuDMgAShngBNgIkA4MyBCAFgyIHg2cMgSsbzItH0E1MZPxQVedkADVm6i4r6PlRCGwcEBBv5xoVNZOTOg3x//9/XtIhQxN0AJR2tar7/rOyeThS0aJ6DKOoTLxnUjvYUGhYcJxXpGaaqrHh7FJ/wdhwb7VXMulQ4YKTCSXbnrXhORtNzBqd1D934yuFH6hcQUa+ScUl1pJKLzFUzLRXaUmlmx8lVXEJSo/BdCddZAXb71Bhwk3KZtKXwlBQ2G+MSUHuH8rUiPjiak1v7qaSmcMF2/HBj/CxOeekMzNTcD5Zxb9dFo8DvXceGREcERGNsqEpGezXhbWLKX/9GNxq/sfkiIh4cGPgUF69q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mrVsO8P97dCl5199+g0bMWrchMntcdBmtsDhQ7Rg0bIVq9as27Bpy649pTGb3KXvazZ6pvzqnbd+N+kXr/3oB2/85Ocu+CvFYl/Ks5n/uup0eXvCWnuVzX3kVC9ysHO9oRHb+EC1+lW4MeN5Lj5aMjBxdaYA0UKBkx2RwsX0sqRjRLTDccE35FsIsy3gTFSkeLy0s8Rkbh4Ge9MM0xNs8wIAAAA=') format('woff2'); }`; const AnonymousProItalic = `@font-face { font-family: 'Anonymous Pro'; font-style: italic; font-weight: 400; src: local('Anonymous Pro Italic'), local('AnonymousPro-Italic'), url('data:font/woff2;base64,d09GMgABAAAAADqIABAAAAAAgMAAADooAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmAWi2AAgx4ILgmCYREQCoHVJIHAbwuDMgAShngBNgIkA4MyBCAFgxoHg2cMgSsbu3M3op1/kVENshtIf4223lN3RiGwcQCFGd0ZiQg2DgRCfDX4//9PTCpjaFNY2gCg6tz+fzNGprJ1jdbnsm4bveHR0iFMj8QJMbUf/nbW6Q8hYRCSaYn7VSXqPgWHu+jeEXg/0xKTYYQ7pwQhSJOOPI3XRmw2r0gnKx3Woyj9ZmLR5b24l7/5UC93YzWy8uSFP+n1K0q7sfQ2egGc4Yxf+3P/P19ckoSSpN1W7xAfyBx0ol7zyRwDJUlO4ol0v+Vrs44BIwa2Jn1RssSedJkWzipnwRp94luSUHLZ8IJIdxUfobFPckmfT2f5Z4T2Emp1l4zsJQIZnlc6AHIInC6nAHWEFc0RQZuOoEtmsKkmCyFtNBDTjFjIK+BV0jVeTZ79/B69MZC79qVXWbhrFX8TdrtatrZfA/CggzTAu63PPM8zQ8DBUDMkIyLChSIutogIL0QkRERkiICI+iQiIiJTQSVHzlLzxNaypba33Vjd1faum/ZH90fO4UISDLZ7Ps8pRlC79qaAAq9JOY4ssChIKXqyv++dZuFvRrKtEtmtSwijnY2liwx0gM57VjLF3/jyWzx2jwi78gYKBHeR/+e5aPfvNtzxEAMZ5CjCQUw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oP48reme5+gUYass5B6OPMfoFFrP9aIVB7Ai5Nya4nnqePZXDuvgaYyyfLg4GRblrXPx972WVP9ADd7aNfFf6eY1AvXTz9VWY//sY3Ed+wn/SrbdbvU2L5Bssoy8JIQa+SpRN3TuqDHjmjirwAPST95BzzJJk9g9KjYr2LZKEuJ7lQiYc7A1bdbAPbHN+1hKg0MmSwN+gILET0xA0WIeKV/2cc+EqT4EBZ7pQ5GMd/tI6PRxHxml7vdRUDBkr6J4BRXQ1s7ew9HCzNwZYLPf0tzeC8dkdTtXi9lD7OTMAUSCIl5yDQkj8Yb2aO3LA6zsRJIJ5yfkSsuOFYy2hj3Y2SWanKL3DukstLYQO+ZV84rV7mg6TkjCIb9UyGOnVqoIvDKtP+dkIQ/VXhv15iQB8b50OF5/7TVYBff/U/V3CIygGE6QlIxmgCAwBAqDI5AoNAaLwxOIJDKFSqMzmCw2h8vjC4QisUQqkyuUKrVGq9MbgCAwBAqDI5AoNAaLwxOIJDKFSqMzmCw2xykujy8QisTGJqZm5haWVtY2tncQf2CnSVQChW7uAoVe3vDyZPqTqTQ6g8lic7g8vkAkllNU0tBE3NbR1dM3MTULAZZW1ja2dvbzsi7v2dU9gnn5YbB4AnEGl6ZM3Vq2oKisMgHLqpu/9qC1dPVYWKH+kZPZaLXYdA4GWysbO3u49vSmtbW1fbXy0NPbNntrHuSosHMarSA7dWdd+/T+ntqifOgV+3yRnq6fXv7V4a6aoqTJKC45DCNlKcoYINUyc9J8k7BvWfJoM2mqmTypK2XbqEvDUS1itoWd77JWwTHnCgA=') format('woff2'); }`; const AnonymousPro700 = `@font-face { font-family: 'Anonymous Pro'; font-style: normal; font-weight: 700; src: local('Anonymous Pro Bold'), local('AnonymousPro-Bold'), url('data:font/woff2;base64,d09GMgABAAAAAD8IABAAAAAAjxAAAD6oAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmAWi2AAgx4IMAmCYREQCoHxeIHdXQuDMgAShngBNgIkA4MyBCAFgwoHg2cMgTUbJYIn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sScyfZCLTxOoOcpr4T91d2eQ4X4V3TFoSc7GEsiifV3Y2srJoDvA5WuLle54TTooQe0DI27rACruxo6x9FaculZ1G0UzsOYm4HKmBPCq6626xg0MZXM1phfSYgFCXYIaDr9mRUBoAdy0hmxZKjbWAP9OM4fO8DIbKJOk3TaqF5Ne2SoiD71dsSCgwwSx2zOdfIgVvGAS7rEbTTzH6rnJspMrxI0ZUkSZA5wr0kjRQuOwGh79wwZ++1h5NeC8QpI3V+dKhM8yaovHCovLbzRXRFt1c8GTrzTWVtt3ckOpBxcnN/f5CuyTXJlqYmFWzKKOlYxMl03iJEvWkZFEhSn9l69tq68NlUYoVPrtV8l5GFSmUL1ETPR0ZxUhbcxXNQJqKo15cAqaJMdHVDLUdodKnmW9CZqJXXaR85r+8EjUGYhHLRSAJ0noy6JfpZNSZzpfjfKsyNSSf5bKurW5TXR2oPWY9r+sv/k+H/4OgBJwPsWmROvb8gIdRnKQiywtZVnXTdv1mGKd52e7WPTUAESaUcSGVNtZlOcNyvCBKsqJqumFatuN6fhBGcZJmeVFWddN2/TBO82K5Wm+2TkIHfVrdWFxvXu3V4vXmNPynv2HZjuv5QRjFSZoX1WK5P5zOl+vt/YnM4VrNUcccd8JJp5x2Zg3mby+45Eqt4ZrrbouKSUhKrevczq7kvFpUUlFdVfnHDU0tbT19Bxiu+lFr+YlF43EEC5QV3BJCILv2WTft9nw7Slv4+vTujCHkOFXrJSd0qe8fbl3tk+ub5WHxzPkhQf3UNs3aAVOtickuybKwnXouO4llgIx45Gh/KmAq5wvTo4RVTlej0dXr6hpgEiG/hKK4NTk1i/rnENZQBgA=') format('woff2'); }`; const AnonymousPro700italic = `@font-face { font-family: 'Anonymous Pro'; font-style: italic; font-weight: 700; src: local('Anonymous Pro Bold Italic'), local('AnonymousPro-BoldItalic'), url('data:font/woff2;base64,d09GMgABAAAAADeAABAAAAAAe6QAADcgAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmAWi2AAgx4IMAmCYREQCoHKWI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1z3yt2v3u/rkkG6PL4AQTGcICkhLWLErEQqkyuUKrVGq9MbrG2MJrPF1s7ewdEpg75/7l08eGRGdOkyZMqSjSFHrjxMLGwcXDx8AvmECogUEisiUUyqBKiUTBm51SDlFCooVVKpolZNo4ZWbcaPrlOvgUHjTrWiGGYWM+ltbGbS13LQ8M3kAgACBgEFA4eAhIKGgYVHQEJFw8HFJyAkIqagpJpkOy0dPQMjE3PdLffXzsk9g6N8QsIiYho11QfT1VoDzDdRpy49evXpN2DQkGFjxl3H5IjFmXwx7zd/+sNfXtv0gzXLVq3bCBNomTA6N5dFNUPTp0z8vh2uYgU7xfsyQ+x0F5M72+eyq7PxUQFOxr4RrK48Dp50PSpzeudChqMs6XlATFjvmoMjbfEtIxDuXPaJ+NO8U4jzKSnfaMy36O3YHzv2GSdjZwMzkKGoewUA') format('woff2'); }`;
// subsets: "cyrillic" // subsets: "greek" // subsets: "latin" // subsets: "latin-ext"
jsoneditor.js
/*var json = { "string": "foo", "number": 5, "array": [1, 2, 3], "object": { "property": "value", "subobj": { "arr": ["foo", "ha"], "numero": 1 } } };*/ function printJSON() { $('#json').val(JSON.stringify(json)); } function updateJSON(data) { json = data; printJSON(); } function
(path) { $('#path').text(path); } $(document).ready(function() { $('#rest > button').click(function() { var url = $('#rest-url').val(); $.ajax({ url: url, dataType: 'jsonp', jsonp: $('#rest-callback').val(), success: function(data) { json = data; $('#editor').jsonEditor(json, { change: updateJSON, propertyclick: showPath }); printJSON(); }, error: function() { alert('Something went wrong, double-check the URL and callback parameter.'); } }); }); $('#json').change(function() { var val = $('#json').val(); if (val) { try { json = JSON.parse(val); } catch (e) { alert('Error in parsing json. ' + e); } } else { json = {}; } $('#editor').jsonEditor(json, { change: updateJSON, propertyclick: showPath }); }); $('#expander').click(function() { var editor = $('#editor'); editor.toggleClass('expanded'); $(this).text(editor.hasClass('expanded') ? 'Collapse' : 'Expand all'); }); printJSON(); $('#editor').jsonEditor(json, { change: updateJSON, propertyclick: showPath }); });
showPath