How to execute an async function in actix-web?

Question: There is an async connect() function as below.
use actix_web::client::Client;
use futures::compat::Future01CompatExt;
use futures::future::{FutureExt, TryFutureExt};

pub async fn connect() {
    let request = Client::default().get("https://www.google.com").send();

    // compat() converts a v0.1 futures::future::Future<Item = T, Error = E>
    // into a std::future::Future<Output = Result<T, E>>.
    let result = request.compat().await;

    if let Err(e) = result {
        println!("{:?}", e);
        return;
    }
    if let Ok(response) = result {
        println!("{:?}", response);
        return;
    }
}

First I tried to execute connect() by futures::executor::ThreadPool::run. It would panic because actix_web::client::Client must be used in actix framework context.
How to execute connect() in actix context?
I tried code below as well. it does not compile.
let future03 = async {
    connect().await;
};
let future01 = future03.unit_error().boxed().compat();
actix::Arbiter::spawn(future01);

It ends with an compiliation error.
error[E0277]: `(dyn futures::future::Future<Item = awc::response::ClientResponse, Error = actix_http::client::error::SendRequestError> + 'static)` cannot be sent between threads safely
  --> src/main.rs:29:42
   |
29 |     let future01 = future03.unit_error().boxed().compat();
   |                                          ^^^^^ `(dyn futures::future::Future<Item = awc::response::ClientResponse, Error = actix_http::client::error::SendRequestError> + 'static)` cannot be sent between threads safely
   |
   = help: the trait `std::marker::Send` is not implemented for `(dyn futures::future::Future<Item = awc::response::ClientResponse, Error = actix_http::client::error::SendRequestError> + 'static)`
   = note: required because of the requirements on the impl of `std::marker::Send` for `std::ptr::Unique<(dyn futures::future::Future<Item = awc::response::ClientResponse, Error = actix_http::client::error::SendRequestError> + 'static)>`
   = note: required because it appears within the type `std::boxed::Box<(dyn futures::future::Future<Item = awc::response::ClientResponse, Error = actix_http::client::error::SendRequestError> + 'static)>`
   = note: required because it appears within the type `futures::future::map::Map<std::boxed::Box<(dyn futures::future::Future<Item = awc::response::ClientResponse, Error = actix_http::client::error::SendRequestError> + 'static)>, [closure@DefId(150:269 ~ awc[6b54]::request[0]::{{impl}}[0]::send_body[0]::{{closure}}[1]) 0:bool]>`
   = note: required because it appears within the type `futures::future::either::Either<futures::future::map_err::MapErr<tokio_timer::timeout::Timeout<futures::future::map::Map<std::boxed::Box<(dyn futures::future::Future<Item = awc::response::ClientResponse, Error = actix_http::client::error::SendRequestError> + 'static)>, [closure@DefId(150:269 ~ awc[6b54]::request[0]::{{impl}}[0]::send_body[0]::{{closure}}[1]) 0:bool]>>, [closure@DefId(150:272 ~ awc[6b54]::request[0]::{{impl}}[0]::send_body[0]::{{closure}}[3])]>, futures::future::map::Map<std::boxed::Box<(dyn futures::future::Future<Item = awc::response::ClientResponse, Error = actix_http::client::error::SendRequestError> + 'static)>, [closure@DefId(150:269 ~ awc[6b54]::request[0]::{{impl}}[0]::send_body[0]::{{closure}}[1]) 0:bool]>>`
   = note: required because it appears within the type `futures::future::either::Either<futures::future::result_::FutureResult<awc::response::ClientResponse<actix_http::encoding::decoder::Decoder<actix_http::payload::Payload>>, actix_http::client::error::SendRequestError>, futures::future::either::Either<futures::future::map_err::MapErr<tokio_timer::timeout::Timeout<futures::future::map::Map<std::boxed::Box<(dyn futures::future::Future<Item = awc::response::ClientResponse, Error = actix_http::client::error::SendRequestError> + 'static)>, [closure@DefId(150:269 ~ awc[6b54]::request[0]::{{impl}}[0]::send_body[0]::{{closure}}[1]) 0:bool]>>, [closure@DefId(150:272 ~ awc[6b54]::request[0]::{{impl}}[0]::send_body[0]::{{closure}}[3])]>, futures::future::map::Map<std::boxed::Box<(dyn futures::future::Future<Item = awc::response::ClientResponse, Error = actix_http::client::error::SendRequestError> + 'static)>, [closure@DefId(150:269 ~ awc[6b54]::request[0]::{{impl}}[0]::send_body[0]::{{closure}}[1]) 0:bool]>>>`
   = note: required because it appears within the type `impl futures::future::Future`
   = note: required because it appears within the type `impl futures::future::Future`
   = note: required because it appears within the type `{impl futures::future::Future, futures_util::compat::compat01as03::Compat01As03<impl futures::future::Future>, ()}`
   = note: required because it appears within the type `[static generator@src/main.rs:5:24: 20:2 {impl futures::future::Future, futures_util::compat::compat01as03::Compat01As03<impl futures::future::Future>, ()}]`
   = note: required because it appears within the type `std::future::GenFuture<[static generator@src/main.rs:5:24: 20:2 {impl futures::future::Future, futures_util::compat::compat01as03::Compat01As03<impl futures::future::Future>, ()}]>`
   = note: required because it appears within the type `impl core::future::future::Future`
   = note: required because it appears within the type `impl core::future::future::Future`
   = note: required because it appears within the type `{impl core::future::future::Future, ()}`
   = note: required because it appears within the type `[static generator@src/main.rs:26:26: 28:6 {impl core::future::future::Future, ()}]`
   = note: required because it appears within the type `std::future::GenFuture<[static generator@src/main.rs:26:26: 28:6 {impl core::future::future::Future, ()}]>`
   = note: required because it appears within the type `impl core::future::future::Future`
   = note: required because it appears within the type `futures_util::future::unit_error::UnitError<impl core::future::future::Future>`

error[E0277]: `std::rc::Rc<std::cell::RefCell<actix_http::h1::payload::Inner>>` cannot be sent between threads safely
  --> src/main.rs:29:42
   |
29 |     let future01 = future03.unit_error().boxed().compat();
   |                                          ^^^^^ `std::rc::Rc<std::cell::RefCell<actix_http::h1::payload::Inner>>` cannot be sent between threads safely
   |
   = help: within `futures_util::future::unit_error::UnitError<impl core::future::future::Future>`, the trait `std::marker::Send` is not implemented for `std::rc::Rc<std::cell::RefCell<actix_http::h1::payload::Inner>>`
   = note: required because it appears within the type `actix_http::h1::payload::Payload`
   = note: required because it appears within the type `actix_http::payload::Payload<actix_http::encoding::decoder::Decoder<actix_http::payload::Payload>>`
   = note: required because it appears within the type `awc::response::ClientResponse<actix_http::encoding::decoder::Decoder<actix_http::payload::Payload>>`
   = note: required because it appears within the type `std::result::Result<awc::response::ClientResponse<actix_http::encoding::decoder::Decoder<actix_http::payload::Payload>>, actix_http::client::error::SendRequestError>`
   = note: required because it appears within the type `std::option::Option<std::result::Result<awc::response::ClientResponse<actix_http::encoding::decoder::Decoder<actix_http::payload::Payload>>, actix_http::client::error::SendRequestError>>`
   = note: required because it appears within the type `futures::future::result_::FutureResult<awc::response::ClientResponse<actix_http::encoding::decoder::Decoder<actix_http::payload::Payload>>, actix_http::client::error::SendRequestError>`
   = note: required because it appears within the type `futures::future::either::Either<futures::future::result_::FutureResult<awc::response::ClientResponse<actix_http::encoding::decoder::Decoder<actix_http::payload::Payload>>, actix_http::client::error::SendRequestError>, futures::future::either::Either<futures::future::map_err::MapErr<tokio_timer::timeout::Timeout<futures::future::map::Map<std::boxed::Box<(dyn futures::future::Future<Item = awc::response::ClientResponse, Error = actix_http::client::error::SendRequestError> + 'static)>, [closure@DefId(150:269 ~ awc[6b54]::request[0]::{{impl}}[0]::send_body[0]::{{closure}}[1]) 0:bool]>>, [closure@DefId(150:272 ~ awc[6b54]::request[0]::{{impl}}[0]::send_body[0]::{{closure}}[3])]>, futures::future::map::Map<std::boxed::Box<(dyn futures::future::Future<Item = awc::response::ClientResponse, Error = actix_http::client::error::SendRequestError> + 'static)>, [closure@DefId(150:269 ~ awc[6b54]::request[0]::{{impl}}[0]::send_body[0]::{{closure}}[1]) 0:bool]>>>`
   = note: required because it appears within the type `impl futures::future::Future`
   = note: required because it appears within the type `impl futures::future::Future`
   = note: required because it appears within the type `{impl futures::future::Future, futures_util::compat::compat01as03::Compat01As03<impl futures::future::Future>, ()}`
   = note: required because it appears within the type `[static generator@src/main.rs:5:24: 20:2 {impl futures::future::Future, futures_util::compat::compat01as03::Compat01As03<impl futures::future::Future>, ()}]`
   = note: required because it appears within the type `std::future::GenFuture<[static generator@src/main.rs:5:24: 20:2 {impl futures::future::Future, futures_util::compat::compat01as03::Compat01As03<impl futures::future::Future>, ()}]>`
   = note: required because it appears within the type `impl core::future::future::Future`
   = note: required because it appears within the type `impl core::future::future::Future`
   = note: required because it appears within the type `{impl core::future::future::Future, ()}`
   = note: required because it appears within the type `[static generator@src/main.rs:26:26: 28:6 {impl core::future::future::Future, ()}]`
   = note: required because it appears within the type `std::future::GenFuture<[static generator@src/main.rs:26:26: 28:6 {impl core::future::future::Future, ()}]>`
   = note: required because it appears within the type `impl core::future::future::Future`
   = note: required because it appears within the type `futures_util::future::unit_error::UnitError<impl core::future::future::Future>`

error[E0277]: `(dyn actix_http::error::ResponseError + 'static)` cannot be sent between threads safely
  --> src/main.rs:29:42
   |
29 |     let future01 = future03.unit_error().boxed().compat();
   |                                          ^^^^^ `(dyn actix_http::error::ResponseError + 'static)` cannot be sent between threads safely
   |
   = help: the trait `std::marker::Send` is not implemented for `(dyn actix_http::error::ResponseError + 'static)`
   = note: required because of the requirements on the impl of `std::marker::Send` for `std::ptr::Unique<(dyn actix_http::error::ResponseError + 'static)>`
   = note: required because it appears within the type `std::boxed::Box<(dyn actix_http::error::ResponseError + 'static)>`
   = note: required because it appears within the type `actix_http::error::Error`
   = note: required because it appears within the type `actix_http::client::error::SendRequestError`
   = note: required because it appears within the type `std::result::Result<awc::response::ClientResponse<actix_http::encoding::decoder::Decoder<actix_http::payload::Payload>>, actix_http::client::error::SendRequestError>`
   = note: required because it appears within the type `std::option::Option<std::result::Result<awc::response::ClientResponse<actix_http::encoding::decoder::Decoder<actix_http::payload::Payload>>, actix_http::client::error::SendRequestError>>`
   = note: required because it appears within the type `futures::future::result_::FutureResult<awc::response::ClientResponse<actix_http::encoding::decoder::Decoder<actix_http::payload::Payload>>, actix_http::client::error::SendRequestError>`
   = note: required because it appears within the type `futures::future::either::Either<futures::future::result_::FutureResult<awc::response::ClientResponse<actix_http::encoding::decoder::Decoder<actix_http::payload::Payload>>, actix_http::client::error::SendRequestError>, futures::future::either::Either<futures::future::map_err::MapErr<tokio_timer::timeout::Timeout<futures::future::map::Map<std::boxed::Box<(dyn futures::future::Future<Item = awc::response::ClientResponse, Error = actix_http::client::error::SendRequestError> + 'static)>, [closure@DefId(150:269 ~ awc[6b54]::request[0]::{{impl}}[0]::send_body[0]::{{closure}}[1]) 0:bool]>>, [closure@DefId(150:272 ~ awc[6b54]::request[0]::{{impl}}[0]::send_body[0]::{{closure}}[3])]>, futures::future::map::Map<std::boxed::Box<(dyn futures::future::Future<Item = awc::response::ClientResponse, Error = actix_http::client::error::SendRequestError> + 'static)>, [closure@DefId(150:269 ~ awc[6b54]::request[0]::{{impl}}[0]::send_body[0]::{{closure}}[1]) 0:bool]>>>`
   = note: required because it appears within the type `impl futures::future::Future`
   = note: required because it appears within the type `impl futures::future::Future`
   = note: required because it appears within the type `{impl futures::future::Future, futures_util::compat::compat01as03::Compat01As03<impl futures::future::Future>, ()}`
   = note: required because it appears within the type `[static generator@src/main.rs:5:24: 20:2 {impl futures::future::Future, futures_util::compat::compat01as03::Compat01As03<impl futures::future::Future>, ()}]`
   = note: required because it appears within the type `std::future::GenFuture<[static generator@src/main.rs:5:24: 20:2 {impl futures::future::Future, futures_util::compat::compat01as03::Compat01As03<impl futures::future::Future>, ()}]>`
   = note: required because it appears within the type `impl core::future::future::Future`
   = note: required because it appears within the type `impl core::future::future::Future`
   = note: required because it appears within the type `{impl core::future::future::Future, ()}`
   = note: required because it appears within the type `[static generator@src/main.rs:26:26: 28:6 {impl core::future::future::Future, ()}]`
   = note: required because it appears within the type `std::future::GenFuture<[static generator@src/main.rs:26:26: 28:6 {impl core::future::future::Future, ()}]>`
   = note: required because it appears within the type `impl core::future::future::Future`
   = note: required because it appears within the type `futures_util::future::unit_error::UnitError<impl core::future::future::Future>`

error[E0277]: `(dyn futures::stream::Stream<Error = actix_http::error::PayloadError, Item = bytes::bytes::Bytes> + 'static)` cannot be sent between threads safely
  --> src/main.rs:29:42
   |
29 |     let future01 = future03.unit_error().boxed().compat();
   |                                          ^^^^^ `(dyn futures::stream::Stream<Error = actix_http::error::PayloadError, Item = bytes::bytes::Bytes> + 'static)` cannot be sent between threads safely
   |
   = help: the trait `std::marker::Send` is not implemented for `(dyn futures::stream::Stream<Error = actix_http::error::PayloadError, Item = bytes::bytes::Bytes> + 'static)`
   = note: required because of the requirements on the impl of `std::marker::Send` for `std::ptr::Unique<(dyn futures::stream::Stream<Error = actix_http::error::PayloadError, Item = bytes::bytes::Bytes> + 'static)>`
   = note: required because it appears within the type `std::boxed::Box<(dyn futures::stream::Stream<Error = actix_http::error::PayloadError, Item = bytes::bytes::Bytes> + 'static)>`
   = note: required because it appears within the type `actix_http::payload::Payload`
   = note: required because it appears within the type `actix_http::encoding::decoder::Decoder<actix_http::payload::Payload>`
   = note: required because it appears within the type `actix_http::payload::Payload<actix_http::encoding::decoder::Decoder<actix_http::payload::Payload>>`
   = note: required because it appears within the type `awc::response::ClientResponse<actix_http::encoding::decoder::Decoder<actix_http::payload::Payload>>`
   = note: required because it appears within the type `std::result::Result<awc::response::ClientResponse<actix_http::encoding::decoder::Decoder<actix_http::payload::Payload>>, actix_http::client::error::SendRequestError>`
   = note: required because it appears within the type `std::option::Option<std::result::Result<awc::response::ClientResponse<actix_http::encoding::decoder::Decoder<actix_http::payload::Payload>>, actix_http::client::error::SendRequestError>>`
   = note: required because it appears within the type `futures::future::result_::FutureResult<awc::response::ClientResponse<actix_http::encoding::decoder::Decoder<actix_http::payload::Payload>>, actix_http::client::error::SendRequestError>`
   = note: required because it appears within the type `futures::future::either::Either<futures::future::result_::FutureResult<awc::response::ClientResponse<actix_http::encoding::decoder::Decoder<actix_http::payload::Payload>>, actix_http::client::error::SendRequestError>, futures::future::either::Either<futures::future::map_err::MapErr<tokio_timer::timeout::Timeout<futures::future::map::Map<std::boxed::Box<(dyn futures::future::Future<Item = awc::response::ClientResponse, Error = actix_http::client::error::SendRequestError> + 'static)>, [closure@DefId(150:269 ~ awc[6b54]::request[0]::{{impl}}[0]::send_body[0]::{{closure}}[1]) 0:bool]>>, [closure@DefId(150:272 ~ awc[6b54]::request[0]::{{impl}}[0]::send_body[0]::{{closure}}[3])]>, futures::future::map::Map<std::boxed::Box<(dyn futures::future::Future<Item = awc::response::ClientResponse, Error = actix_http::client::error::SendRequestError> + 'static)>, [closure@DefId(150:269 ~ awc[6b54]::request[0]::{{impl}}[0]::send_body[0]::{{closure}}[1]) 0:bool]>>>`
   = note: required because it appears within the type `impl futures::future::Future`
   = note: required because it appears within the type `impl futures::future::Future`
   = note: required because it appears within the type `{impl futures::future::Future, futures_util::compat::compat01as03::Compat01As03<impl futures::future::Future>, ()}`
   = note: required because it appears within the type `[static generator@src/main.rs:5:24: 20:2 {impl futures::future::Future, futures_util::compat::compat01as03::Compat01As03<impl futures::future::Future>, ()}]`
   = note: required because it appears within the type `std::future::GenFuture<[static generator@src/main.rs:5:24: 20:2 {impl futures::future::Future, futures_util::compat::compat01as03::Compat01As03<impl futures::future::Future>, ()}]>`
   = note: required because it appears within the type `impl core::future::future::Future`
   = note: required because it appears within the type `impl core::future::future::Future`
   = note: required because it appears within the type `{impl core::future::future::Future, ()}`
   = note: required because it appears within the type `[static generator@src/main.rs:26:26: 28:6 {impl core::future::future::Future, ()}]`
   = note: required because it appears within the type `std::future::GenFuture<[static generator@src/main.rs:26:26: 28:6 {impl core::future::future::Future, ()}]>`
   = note: required because it appears within the type `impl core::future::future::Future`
   = note: required because it appears within the type `futures_util::future::unit_error::UnitError<impl core::future::future::Future>`

error[E0277]: `(dyn std::any::Any + 'static)` cannot be sent between threads safely
  --> src/main.rs:29:42
   |
29 |     let future01 = future03.unit_error().boxed().compat();
   |                                          ^^^^^ `(dyn std::any::Any + 'static)` cannot be sent between threads safely
   |
   = help: the trait `std::marker::Send` is not implemented for `(dyn std::any::Any + 'static)`
   = note: required because of the requirements on the impl of `std::marker::Send` for `std::ptr::Unique<(dyn std::any::Any + 'static)>`
   = note: required because it appears within the type `std::boxed::Box<(dyn std::any::Any + 'static)>`
   = note: required because it appears within the type `(std::any::TypeId, std::boxed::Box<(dyn std::any::Any + 'static)>)`
   = note: required because of the requirements on the impl of `std::marker::Send` for `hashbrown::raw::RawTable<(std::any::TypeId, std::boxed::Box<(dyn std::any::Any + 'static)>)>`
   = note: required because it appears within the type `hashbrown::map::HashMap<std::any::TypeId, std::boxed::Box<(dyn std::any::Any + 'static)>>`
   = note: required because it appears within the type `actix_http::extensions::Extensions`
   = note: required because of the requirements on the impl of `std::marker::Send` for `std::cell::RefCell<actix_http::extensions::Extensions>`
   = note: required because it appears within the type `actix_http::message::ResponseHead`
   = note: required because it appears within the type `awc::response::ClientResponse<actix_http::encoding::decoder::Decoder<actix_http::payload::Payload>>`
   = note: required because it appears within the type `std::result::Result<awc::response::ClientResponse<actix_http::encoding::decoder::Decoder<actix_http::payload::Payload>>, actix_http::client::error::SendRequestError>`
   = note: required because it appears within the type `std::option::Option<std::result::Result<awc::response::ClientResponse<actix_http::encoding::decoder::Decoder<actix_http::payload::Payload>>, actix_http::client::error::SendRequestError>>`
   = note: required because it appears within the type `futures::future::result_::FutureResult<awc::response::ClientResponse<actix_http::encoding::decoder::Decoder<actix_http::payload::Payload>>, actix_http::client::error::SendRequestError>`
   = note: required because it appears within the type `futures::future::either::Either<futures::future::result_::FutureResult<awc::response::ClientResponse<actix_http::encoding::decoder::Decoder<actix_http::payload::Payload>>, actix_http::client::error::SendRequestError>, futures::future::either::Either<futures::future::map_err::MapErr<tokio_timer::timeout::Timeout<futures::future::map::Map<std::boxed::Box<(dyn futures::future::Future<Item = awc::response::ClientResponse, Error = actix_http::client::error::SendRequestError> + 'static)>, [closure@DefId(150:269 ~ awc[6b54]::request[0]::{{impl}}[0]::send_body[0]::{{closure}}[1]) 0:bool]>>, [closure@DefId(150:272 ~ awc[6b54]::request[0]::{{impl}}[0]::send_body[0]::{{closure}}[3])]>, futures::future::map::Map<std::boxed::Box<(dyn futures::future::Future<Item = awc::response::ClientResponse, Error = actix_http::client::error::SendRequestError> + 'static)>, [closure@DefId(150:269 ~ awc[6b54]::request[0]::{{impl}}[0]::send_body[0]::{{closure}}[1]) 0:bool]>>>`
   = note: required because it appears within the type `impl futures::future::Future`
   = note: required because it appears within the type `impl futures::future::Future`
   = note: required because it appears within the type `{impl futures::future::Future, futures_util::compat::compat01as03::Compat01As03<impl futures::future::Future>, ()}`
   = note: required because it appears within the type `[static generator@src/main.rs:5:24: 20:2 {impl futures::future::Future, futures_util::compat::compat01as03::Compat01As03<impl futures::future::Future>, ()}]`
   = note: required because it appears within the type `std::future::GenFuture<[static generator@src/main.rs:5:24: 20:2 {impl futures::future::Future, futures_util::compat::compat01as03::Compat01As03<impl futures::future::Future>, ()}]>`
   = note: required because it appears within the type `impl core::future::future::Future`
   = note: required because it appears within the type `impl core::future::future::Future`
   = note: required because it appears within the type `{impl core::future::future::Future, ()}`
   = note: required because it appears within the type `[static generator@src/main.rs:26:26: 28:6 {impl core::future::future::Future, ()}]`
   = note: required because it appears within the type `std::future::GenFuture<[static generator@src/main.rs:26:26: 28:6 {impl core::future::future::Future, ()}]>`
   = note: required because it appears within the type `impl core::future::future::Future`
   = note: required because it appears within the type `futures_util::future::unit_error::UnitError<impl core::future::future::Future>`

error: aborting due to 5 previous errors

I am still learning Rust. Please can anyone help? appreciated.
Rust version : 1.39 nightly
[dependencies]
actix = "0.8.3"
actix-web = "1.0.5"

# https://rust-lang-nursery.github.io/futures-rs/blog/2019/04/18/compatibility-layer.html
# Rust's futures ecosystem is currently split in two:
# On the one hand we have the vibrant ecosystem built around firstname.lastname@example.com with its many libraries working on stable Rust
# and on the other hand there's std::future ecosystem with support for the ergonomic and powerful async/await language feature.
# To bridge the gap between these two worlds we have introduced a compatibility layer as part of the email@example.com extension to std::future.
[dependencies.futures-preview]
version = "0.3.0-alpha.18"
default-features = false
features = ["compat", "async-await", "nightly"]

Answer: let future01 = future03.unit_error().boxed_local().compat();

boxed_local() wraps the future in a Box, pinning it.
Similar to boxed(), but without the Send requirement.


What is the name for numbers using a comma for a decimal separator versus a dot

Question: I am curious to know if there is a specific name for numbers that use a comma for a decimal separator and a dot for a thousands separator as opposed to numbers that are the reverse.
For example: 4.048,5 vs 4,048.5
Comment: I don't see any reason why there would be a specific name, it just depends on your country.
Comment: The only time I saw this reversal of notation was in the French-language  section of a pamphlet on the use of a slide rule I bought (in the Stone Age.) I assumed it was a matter of  national style.
Answer: There's a name for the symbol used to separate the integer part from the fractional part: it's called the decimal mark. Not sure if there's a terminology for the numbers that use a particular convention for the decimal mark. Besides the two examples you cite, the Wikipedia article mentions several other 'styles' for displaying numbers.
Comment: Or more generally, allowing for other bases, a *radix point* (even when it's a comma).


Trigonometric inequality with absolute value

Question: I want to show the following. Assume $n>2$. Then, for each $b=1,\ldots,n$, there exists some $a\in\{2,3,\ldots,n\}$ such that
$$\left|\cos\left(\frac{\pi}{2n}\left(a-1\right)(2b-1)\right) \right| \geqslant \frac{1}{\sqrt{2}}.$$
I've checked this inequality holds for $b=1$ (it is very simple), but don't know how to proceed to show the above systematically for each $b=2,\ldots,n$ and $n>2$.
Answer: First suppose $2b-1$ is relatively prime to $2n$.  Then there exists some $c\in\{1,\dots,2n-1\}$ such that $c(2b-1)$ is $1$ mod $2n$.  Moreover, we have $c\neq n$ since $n$ is not relatively prime to $2n$.  If $c<n$, let $a=c+1$, and if $c>n$, let $a=(2n-c)+1$.  In either case, we have $a\in\{2,\dots,n\}$ and $(a-1)(2b-1)$ is $\pm1$ mod $2n$.  For some integer $k$ we then have $$\cos\left(\frac{\pi}{2n}(a-1)(2b-1)\right)=\cos\left(\pm\frac{\pi}{2n}+k\pi\right)=(-1)^k\cos\left(\frac{\pi}{2n}\right).$$  Since $n>2$, $0<\frac{\pi}{2n}\leq\frac{\pi}{4}$ and it follows that $$\cos\left(\frac{\pi}{2n}\right)\geq\frac{1}{\sqrt{2}}.$$
Now suppose $2b-1$ is not relatively prime to $2n$.  Since $2b-1$ is odd, $\gcd(2b-1,2n)>2$ and $c=\frac{2n}{\gcd(2b-1,2n)}<n$ satisfies $c(2b-1)=2kn$ for some integer $k$.  Again letting $a=c+1$, we have $$\cos\left(\frac{\pi}{2n}(a-1)(2b-1)\right)=\cos(k\pi)=(-1)^k.$$
Comment: Thanks for your reply, Eric. In the first case ($2b-1$ and $2n$ are relatively prime), how do you conclude that the set to which $c$ may belong is exactly $\{1,\ldots,n-1\}$?
Comment: Oops, I've fixed that.  If $c$ is too big, you can just negate it mod $2n$.
Comment: (1) Yes, but I don't know what you're trying to accomplish.  Why would you want $c(2b-1)$ to be of the form $d+k2n$?  If $d$ is large, that may not make the cosine large.  (Specifically, it will fail to work if $d=2n/3$.)
Comment: (2) My goal is to make the cosine large (in absolute value), so I want $\frac{\pi}{2n}c(2b-1)$ to be close to a multiple of $\pi$, so I want $c(2b-1)$ to be close to a multiple of $2n$.  Choosing $c=2n/d$ makes $c(2b-1)$ not just close to a multiple of $2n$ but equal to a multiple of $2n$.


Raspberry Pi 4 yocto, rpi-basic-image.bb: Unable to determine endianness for architecture 'INVALID'

Question: I'm trying to build core-image-minimal for raspberrypi4-64 on the zeus branch
and I had to create the file sanity.conf and I'm getting this errors:
<code>fstrati$ bitbake -c cleanall core-image-minimal
Loading cache: 100% Time: 0:00:00
Loaded 28 entries from dependency cache.
ERROR: rpi-basic-image.bb: Unable to determine endianness for architecture 'INVALID'
ERROR: rpi-basic-image.bb: Please add your architecture to siteinfo.bbclass
ERROR: rpi-hwup-image.bb: Unable to determine endianness for architecture 'INVALID'
ERROR: rpi-hwup-image.bb: Please add your architecture to siteinfo.bbclass
ERROR: Failed to parse recipe: rpi-hwup-image.bb
ERROR: vte_0.56.3.bb: Unable to determine endianness for architecture 'INVALID'
ERROR: vte_0.56.3.bb: Please add your architecture to siteinfo.bbclass
</code>
I don't understand why core-image-minimal is using such deprecated recipes.
do I need to switch to the master branch?
Forgive me if this is a dumb question...
Comment: It seems my MACHINE configuration was wrong.

I tried with MACHINE ?= "raspberrypi4-64" instead and everything went fine.
Comment: There's no dumb question. What did you set for you MACHINE variable ?
Comment: BB_NUMBER_THREADS = "2"
# Also, make can be passed flags so it run parallel threads e.g.:
PARALLEL_MAKE = "-j 2"
MACHINE ?= "raspberrypi4-64.conf"
Comment: `fstrati@fstrati-HP-Laptop-15-db0xxx:/media/fstrati/Bkp20191226/yocto_try/poky$ inxi
CPU~Dual core AMD A9-9425 RADEON R5 5 COMPUTE CORES 2C+3G (-MCP-) speed/max~1937/3100 MHz Kernel~5.0.0-37-generic x86_64 Up~16:26 Mem~4276.3/7500.6MB HDD~1500.3GB(7.6% used) Procs~323 Client~Shell inxi~2.3.56
`
Comment: `System:    Host: fstrati-HP-Laptop-15-db0xxx Kernel: 5.0.0-37-generic x86_64 bits: 64 Desktop: Gnome 3.28.4
           Distro: Ubuntu 18.04.3 LTS
Machine:   Device: laptop System: HP product: HP Laptop 15-db0xxx v: Type1ProductConfigId serial: N/A
           Mobo: HP model: 84AC v: 85.20 serial: N/A UEFI: Insyde v: F.11 date: 08/20/2018`
Answer:
It seems my MACHINE configuration was wrong. I tried with MACHINE ?= "raspberrypi4-64" instead and everything went fine.

Removing conf resolved issue for me as well.


mongodb map reduce to get uniques by date/day

Question: trying to group by date and number
my document
 { "_id" : ObjectId("4f956dee76ddb26752026e8f"), "request" : "default", "options" : "1", "keyword" : "somekey", "number" : "5b234b79-4d70-437e-8eef-32a2941af40a", "date" : "20120423200446", "time" : 1335193066 }

my query
map = "function() { var date = new Date(this.time * 1000); var key = date.getFullYear() + date.getMonth() + date.getDate(); emit({day : key, number: this.number}, {count: 1}); }"

reduce = "function(key, values) { var count = 0; values.forEach(function(v) { count += v['count']; }); return {count: count}; }"

db.txtweb.mapReduce(map, reduce, {out: "pageview_results"});

my error
uncaught exception: map reduce failed:{ "errmsg" : "ns doesn't exist", "ok" : 0 }

I cannot figure out whats wrong, but I think it is do something with the date functionality.
Any ideas.
Answer: ns doesn't exist means that you're accessing a non-existent database or collection. Check their names
Script below group this.amount by day (without time)
     db.payments.mapReduce(
             function() {
                 var k = new Date(this.payment_time);
                 k.setMinutes(0);
                 k.setSeconds(0);
                 k.setMilliseconds(0);
                 emit(k, this.amount);
             },
             function (key, vals) {
                 var total = 0;
                 for (var i = 0; i < vals.length; i++) {
                     total += vals[i];
                 }
                 return total;
             },
             {
              out : {merge : "resultName" }
             }
     );
    }
};

Comment: ns doesn't exist means that you're accessing a non-existent database or collection. Check their names... This was the issue. Thanks
Comment: I get the below error when i try to run it in nodejs     error: MongoError: exception: map invoke failed: JS Error: ReferenceError: clone
 is not defined nofile_b:1
Comment: Yes. Clone is used to avoid modification of original date object. I skipped implementation of clone function.  You can use this instead - new Date(this.getTime());
Answer: This happens mostly when you run a script and forgot to select the database
use your_database_name;

Note the line to select the database.


Create groups based on multiple DateTime comparison

Question: I am attempting to create a column based and populate it with a valued based on the comparison of one date column with three other date columns.
An example of the DataFrame df is shown below. All dates shown are already converted to pd.to_datetime, which resulted in a number of NaT values as the individual has not progressed
    1st_date     2nd_date        3rd_date     action_date
    2015-10-05   NaT             NaT          2015-12-03
    2015-02-27   2015-03-14      2015-03-15   2015-04-08
    2015-03-07   2015-03-27      2015-03-28   2015-03-27
    2015-01-05   2015-01-20      2015-01-21   2015-05-20
    2015-01-05   2015-01-20      2015-01-21   2015-09-16
    2015-05-23   2015-06-18      2015-06-19   2015-07-01
    2015-03-03   NaT             NaT          2015-07-23
    2015-03-03   NaT             NaT          2015-11-14
    2015-06-05   2015-06-19      2015-06-20   2015-10-24
    2015-10-08   2015-10-21      2015-10-22   2015-12-22

I am attempting to create a fifth column containing the result (or group) of the comparison of the action_date column with the previous three date columns 1st_date, 2nd_date, 3rd_date.
I am attempting to populate a fifth column called action_group with the a string assigning each date to a group.
Pseudo-code for the potential function (and expected output) is as : if action_date > 1st_date and < 2nd_date then action_group = '1st_action_group'
The same comparison is needed for action_date, 2nd_date and 3rd_date, which would result in an output of 2nd_action_group in the action_group column.
Finally if action_date is greater than 3rd_date, action_group would be assigned a value of 3rd_action_group.
An example of the expected output is shown below.
1st_date     2nd_date        3rd_date     action_date  action_group
2015-10-05   NaT             NaT          2015-12-03   1st_action_group
2015-02-27   2015-03-14      2015-03-15   2015-04-08   3rd_action_group
2015-03-07   2015-03-27      2015-03-28   2015-03-27   2nd_action_group
2015-01-05   2015-01-20      2015-01-21   2015-05-20   3rd_action_group
2015-01-05   2015-01-20      2015-01-21   2015-09-16   3rd_action_group
2015-05-23   2015-06-18      2015-06-19   2015-07-01   3rd_action_group
2015-03-03   NaT             NaT          2015-07-23   1st_action_group
2015-03-03   NaT             NaT          2015-11-14   1st_action_group
2015-06-05   2015-06-19      2015-06-20   2015-10-24   3rd_action_group
2015-10-08   2015-10-21      2015-10-22   2015-12-22   3rd_action_group

Any assistance that anyone could provide would be greatly appreciated.
Answer: df['action_group'] = np.where(df['action_date']>df['3rd_date'],
                              '3rd_action_group',
                               np.where(((df['action_date'] >= df['2nd_date'])&(df['action_date']<df['3rd_date'])),
                                          '2nd_action_group',
                                          '1st_action_group'))

You can just stack 2 np.where's to get your desired results.
    1st_date    2nd_date    3rd_date    action_date action_group
0   2015-10-05     NaT          NaT     2015-12-03  1st_action_group
1   2015-02-27  2015-03-14  2015-03-15  2015-04-08  3rd_action_group
2   2015-03-07  2015-03-27  2015-03-28  2015-03-27  2nd_action_group
3   2015-01-05  2015-01-20  2015-01-21  2015-05-20  3rd_action_group
4   2015-01-05  2015-01-20  2015-01-21  2015-09-16  3rd_action_group
5   2015-05-23  2015-06-18  2015-06-19  2015-07-01  3rd_action_group
6   2015-03-03     NaT          NaT     2015-07-23  1st_action_group
7   2015-03-03     NaT          NaT     2015-11-14  1st_action_group
8   2015-06-05  2015-06-19  2015-06-20  2015-10-24  3rd_action_group
9   2015-10-08  2015-10-21  2015-10-22  2015-12-22  3rd_action_group

Comment: Using `np.select` may be better than nested `np.where` ?


Populate html dropdown menu form database

Question: I want to populate a dropdown menu from a database. I've already tried some methods but none of them works fine. My code looks like this:
<?php

$pdo = new PDO('mysql:host=1***7;dbname=databasename', 'username', 'password');

$sql = "SELECT user FROM users where tip='tip1'";

$stmt = $pdo->prepare($sql);

$stmt->execute();

$users = $stmt->fetchAll();

?>

<select>
    <?php foreach($users as $user): ?>
        <option value="<?= $user['user']; ?>"></option>
    <?php endforeach; ?>
</select>

I usually can see the dropdown menu,but no items are displayed like in the picture below.
Comment: You assign only value... try this: ``
Comment: look at your HTML source; what do you see?
Comment: ...well there you go. Guess what you didn't do?
Answer: You forgot to echo inside option <option value="<?= $user['user']; ?>"><?= $user['user']; ?></option>
<select>
    <?php foreach($users as $user): ?>
        <option value="<?= $user['user']; ?>"><?= $user['user']; ?></option>
    <?php endforeach; ?>
</select>


Solve a system of two congruences with modules not pairwise coprime

Question: I have the following system of congruences:
$\left \{ \begin{array}{rcl} x & \equiv & 225 & \mbox{ (mod 250) } \\ x & \equiv & 150 & \mbox{ (mod 1225) } \end{array} \right .$
Since $\gcd(250, 1225) \ne 1$ the Chinese Remainder Theorem is not applicable.
I have tried to calculate the prime factors of both $250$ and $1225$ and I rewritten the system like this and try to obtain modules pairwise coprime:
$250 = 2 \cdot 5 \cdot 5 \cdot 5 \\ 1225 = 5 \cdot 5 \cdot 7 \cdot 7$
$\left \{ \begin{array}{rcl} x & \equiv & 225 & \mbox{ (mod 2) } \\ x & \equiv & 225 & \mbox{ (mod 5) } \\ x & \equiv & 225 & \mbox{ (mod 5) } \\ x & \equiv & 225 & \mbox{ (mod 5) } \\ x & \equiv & 150 & \mbox{ (mod 5) } \\ x & \equiv & 150 & \mbox{ (mod 5) } \\ x & \equiv & 150 & \mbox{ (mod 7) } \\ x & \equiv & 150 & \mbox{ (mod 7) } \end{array} \right .$
since
$x \equiv 225 \mbox{ (mod 5) } \iff x \equiv 0 \mbox{ (mod 5) }$ and the same for
$x \equiv 150 \mbox{ (mod 5) } \iff x \equiv 0 \mbox{ (mod 5) }$
I have reduced the system as the following:
$\left \{ \begin{array}{rcl} x & \equiv & 1 & \mbox{ (mod 2) } \\ x & \equiv & 3 & \mbox{ (mod 7) }  \end{array} \right .$
and I have applied the Chinese Remainder Theorem:
$M = 2 \cdot 7 = 14 \\ M_1 = \frac{14}{2} = 7 \\ M_2 = \frac{14}{7} = 2$
the auxiliary system is:
$\left \{ \begin{array}{rcl} 7x & \equiv & 1 & \mbox{ (mod 2) } \\ 2x & \equiv & 1 & \mbox{ (mod 7) }  \end{array} \right . \iff \left \{ \begin{array}{rcl} x & \equiv & 1 & \mbox{ (mod 2) } \\ x & \equiv & 4 & \mbox{ (mod 7) }  \end{array} \right .$
$x = 7 \cdot 1 \cdot 1 + 2 \cdot 4 \cdot 3 = 31 \equiv 3 \mbox{ (mod 14) }$
Another way I tried is to consider this equation, but I don't know how to proceed:
$225 + 250h = 150 + 1225k$
Please, can you give me any suggestions? Many thanks!
Answer: $x \equiv 225 \pmod {250}$ so $x=25(9+10j)$ for some $j \in \mathbb{Z} $.
$x \equiv 150 \pmod {1225}$ so $x=25(6+49k)$ for some $k \in \mathbb{Z} $. So we need to find $y$ satisfying
\begin{eqnarray*}
y \equiv 9 \pmod {10} \\
y \equiv 6 \pmod {49}
\end{eqnarray*}
$10$ and $49$ are coprime so we can use the Chinese remainder theorem. We have $y=349$ and $x=8725$.


Compute spectral/projection-valued measures explicitly?

Question: Spectral/projection-valued measures have very handy applications theoretically, but I got stuck when asked to compute explicitly certain projection-valued measures. Let's focus on the following:

Let $ N: {\mathcal{L}^{2}}([0,1]) \to {\mathcal{L}^{2}}([0,1]) $ be the normal operator defined by
  $$
\forall f \in {\mathcal{L}^{2}}([0,1]),\forall t \in [0,1]: \quad [N(f)](t) \stackrel{\text{def}}{=} t \cdot f(t).
$$
  What is the projection-valued measure corresponding to $ N $?

As $ \sigma(N) = [0,1] $, we need a projection-valued measure $ P $ supported on $ [0,1] $. Theoretically, it should be defined just by
$$
P(E) = {\chi_{E}}(N),
$$
where $ \chi_{E} $ is the characteristic function of $ E \subseteq [0,1] $ and $ {\chi_{E}}(N) $ is obtained via the Borel functional calculus of $ N $.
However, to find $ {\chi_{E}}(N) $, we need to find a sequence of polynomial functions converging to $ \chi_{E} $, which is not an easy job.
I somehow feel that the projection-valued measure is given simply by $ P(E) = {\chi_{E}}(N) $, but I am not sure.
Can someone give a hint on how to compute the spectral/projection-valued measure explicitly?
Thanks!
Comment: You can't explicitly compute this projection since you don't have explicit description of Borel sets.
Comment: @Hui Yu: It is not true that every bounded Borel-measurable function on a complete metric space is the pointwise limit of a sequence of polynomial functions. This is because the pointwise limit of a sequence of continuous functions on a metric space, if such a limit exists, must be continuous on a dense set of points. You can prove this using the Baire Category Theorem.
Comment: @Hui Yu: Hence, $ \chi_{[0,1] \cap \mathbb{Q}} $ cannot be the pointwise limit of a sequence of polynomial functions. Instead of pointwise convergence, one can ask for pointwise convergence *almost everywhere*. This is possible by Lusin's Theorem.
Comment: @Norbert: Strange. The Borel subsets are staring at me right in my face. Are they not just the usual Borel subsets of $ [0,1] $?
Comment: @HaskellCurry Borel sets are of very complicated structure. You can use intersection (finite or countable), complementation, union (finite or countable) and other operations to construct Borel sets. But even after applying them countable amount of times you will not get all the Borel sets. You must make this procedure up to $\omega_1$ oridinal to cover the whole variety of Borel sets. This is what I meant when I said that structure of Borel sets is complicated.
Answer: Here is a solution that illustrates how one gets his/her hands dirty with spectral measures. We fix some notation first.

Let $ \mathcal{C}([0,1]) $ denote the space of all continuous functions from $ [0,1] $ to $ \mathbb{C} $.
Let $ {\mathcal{B}_{b}}([0,1]) $ denote the space of all bounded Borel-measurable functions from $ [0,1] $ to $ \mathbb{C} $.

The following lemma will serve as our workhorse.

Lemma Let $ \mu $ be a finite positive Borel measure on $ [0,1] $. Then every $ \varphi \in {\mathcal{B}_{b}}([0,1]) $ is the $ \mu $-a.e. pointwise limit of a bounded sequence $ (\psi_{n})_{n \in \mathbb{N}} $ in $ \mathcal{C}([0,1]) $.

Proof: Using Lusin's Theorem (cf. Theorem 2.24 of Rudin's Real and Complex Analysis, Third Edition), we can inductively create a sequence $ (E_{n})_{n \in \mathbb{N}} $ of Borel subsets of $ [0,1] $ such that for all $ n \in \mathbb{N} $,
(1) $ \mu(E_{n}) < \dfrac{1}{2^{n}} $ and
(2) there exists a $ \psi_{n} \in \mathcal{C}([0,1]) $ satisfying
$$
\| \psi_{n} \|_{\infty} \leq \| \varphi \|_{\infty} \quad \text{and} \quad \varphi|_{[0,1] \setminus E_{n}} = {\psi_{n}}|_{[0,1] \setminus E_{n}}.
$$
We now show that $ (\psi_{n})_{n \in \mathbb{N}} $ meets the necessary requirements. By (2), the boundedness of $ (\psi_{n})_{n \in \mathbb{N}} $ is ensured. From (1), we obtain $ \displaystyle \sum_{n=1}^{\infty} \mu(E_{n}) < \infty $; it follows that almost every $ x \in [0,1] $ lies in $ [0,1] \setminus E_{n} $ for all $ n \in \mathbb{N} $ sufficiently large. Therefore, $ \displaystyle \lim_{n \to \infty} {\psi_{n}}(x) = \varphi(x) $ for almost every $ x \in [0,1] $. This completes the proof. $ \quad \spadesuit $
Let $ P $ be the spectral decomposition of $ N $, which is a projection-valued measure defined on the Borel subsets of $ \sigma(N) = [0,1] $. To each $ \varphi \in {\mathcal{B}_{b}}([0,1]) $, there corresponds a bounded linear operator $ T(\varphi) $ that is uniquely determined by the condition
$$
\forall f,g \in {L^{2}}([0,1]): \quad \langle [T(\varphi)](f),g \rangle = \int_{[0,1]} \varphi ~ d{P_{f,g}},
$$
where $ P_{f,g} $ is the complex Borel measure on $ [0,1] $ defined by
$$
{P_{f,g}}(E) \stackrel{\text{def}}{=} \langle [P(E)](f),g \rangle
$$
for all Borel subsets $ E $ of $ [0,1] $. We then have the following result (click here for a proof).

Theorem The mapping $ \varphi \longmapsto T(\varphi) $ is a unital *-homomorphism from $ {\mathcal{B}_{b}}([0,1]) $ to $ B({L^{2}}([0,1])) $.

Note that $ T(\varphi) $ is commonly denoted by $ \varphi(N) $.
Let $ E $ be a Borel-measurable subset of $ [0,1] $. Then $ \chi_{E} \in {\mathcal{B}_{b}}([0,1]) $ and
\begin{align}
\forall f,g \in {L^{2}}([0,1]): \quad
\langle [T(\chi_{E})](f),g \rangle &= \int_{[0,1]} \chi_{E} ~ d{P_{f,g}} \\
                                   &= {P_{f,g}}(E) \\
                                   &= \langle [P(E)](f),g \rangle.
\end{align}
We thus obtain $ {\chi_{E}}(N) = T(\chi_{E}) = P(E) $.
Fix $ f \in {L^{2}}([0,1]) $. Notice that $ P_{f,f} $ is a finite positive Borel measure on $ [0,1] $. By the lemma, there exists a bounded sequence $ (\psi_{n})_{n \in \mathbb{N}} $ in $ \mathcal{C}([0,1]) $ that converges pointwise $ P_{f,f} $-a.e. to $ \chi_{E} $. Using the theorem, we get
\begin{align}
   \forall n \in \mathbb{N}: \quad \| [T(\chi_{E})](f) - [T(\psi_{n})](f) \|^{2}
&= \| [T(\chi_{E}) - T(\psi_{n})](f) \|^{2} \\
&= \| [T(\chi_{E} - \psi_{n})](f) \|^{2} \\
&= \langle [T(\chi_{E} - \psi_{n})](f),[T(\chi_{E} - \psi_{n})](f) \rangle \\
&= \left\langle [T(\chi_{E} - \psi_{n})]^{*} [T(\chi_{E} - \psi_{n})](f),f \right\rangle \\
&= \left\langle \left[ T \left( \overline{\chi_{E} - \psi_{n}} \right) \right][T(\chi_{E} - \psi_{n})](f),f \right\rangle \\
&= \left\langle \left[ T \left( \overline{\chi_{E} - \psi_{n}} (\chi_{E} - \psi_{n}) \right) \right](f),f \right\rangle \\
&= \left\langle \left[ T \left( |\chi_{E} - \psi_{n}|^{2} \right) \right](f),f \right\rangle \\
&= \int_{[0,1]} |\chi_{E} - \psi_{n}|^{2} ~ d{P_{f,f}}.
\end{align}
The Dominated Convergence Theorem then yields
$$
0 = \lim_{n \to \infty} \int_{[0,1]} |\chi_{E} - \psi_{n}|^{2} ~ d{P_{f,f}} = \lim_{n \to \infty} \| [T(\chi_{E})](f) - [T(\psi_{n})](f) \|^{2}.
$$
Therefore,
\begin{align}
   [T(\chi_{E})](f)
&= \lim_{n \to \infty} [T(\psi_{n})](f) \\
&= \lim_{n \to \infty} \psi_{n} \cdot f \quad (\text{By the Continuous Functional Calculus.}) \\
&= \chi_{E} \cdot f. \quad (\text{By the Dominated Convergence Theorem again.})
\end{align}
Conclusion: For all $ f \in {L^{2}}([0,1]) $, we have $ [{\chi_{E}}(N)](f) = [P(E)](f) = \chi_{E} \cdot f $.


Using Entity metadata wrappers to change field value under hook_node_insert()

Question: I am trying to change a field value inside both hook_node_insert() and hook_node_update() using EMW. It actually changes the original $node object that is passed to these hook functions but the change doesn't get saved at the end.
function mymodule_node_insert($node) {
  if (!_is_dynamic_type($node->type))
    return;

  $messagew = entity_metadata_wrapper('message', message_create('post', array('uid' => $node->uid)));

  //copy terms
  $nodew = entity_metadata_wrapper('node', $node);
  //below loads a full taxonomy term
  $nodew->field_hidden_type = taxonomy_term_machine_name_load('event', 'hidden_type');

  $messagew->field_hidden_type = $nodew->field_hidden_type->value();//this actually works
  $messagew->save();
}

There are a few questions near to this one actually, but none of them addresses this precisely. This one for example is a very good explanation of the mechanism but its suggestion it not use.
Here, one should not use $nodew->save(), because it causes infinite loop. I also played a little with module weight, that does not help either.
I also tried to change another entity reference field. No use.
I don't want to go with field_attach_update() because it is old-fashioned.
Comment: Try [`hook_node_presave()`](https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_presave/7)
Comment: Thank you @Clive. I am about to implement this. Everything points to this direction.
Answer: The method you are using the save the field isn't ideal.
For setting the field values you should use the set() function provided by the EntityMetadataWrapper class.
function mymodule_node_insert($node) {
  if (!_is_dynamic_type($node->type))
    return;

  $messagew = entity_metadata_wrapper('message', message_create('post', array('uid' => $node->uid)));

  //copy terms
  $nodew = entity_metadata_wrapper('node', $node);
  //below loads a full taxonomy term
  $nodew->field_hidden_type = taxonomy_term_machine_name_load('event', 'hidden_type');

  $messagew->field_hidden_type->set($nodew->field_hidden_type->value());
  $messagew->save();
}

On a side note, I see that there is not check on the node type, or any other parameters in the implementation of  hook_node_insert. Note that it will get triggered every time a node of any content type is created.
Comment: thank you for the suggestion. `set()` and `=` are both same and `=` is preffered on account of code readibility. Pleaser refer to [http://www.mediacurrent.com/blog/entity-metadata-wrapper](http://www.mediacurrent.com/blog/entity-metadata-wrapper). Also, the first line calls a custom check function. I deleted lots of lines for better readibility.


Is every group $G$ a subgroup of index $2$ of some $\tilde G$?

Question: Let $(G,f)$ be a group (so $f$ stands for the group operation), $H\lneq G$ and $\complement_GH:=G\setminus H$. Then:
\begin{alignat}{1}
&f(H,H)\subseteq H \\
&f(H,\complement_GH)\subseteq\complement_GH \\
&f(\complement_GH,H)\subseteq\complement_GH \\
&[G:H]=2 \Rightarrow f(\complement_GH,\complement_GH)\subseteq H \\
\tag 1
\end{alignat}
Reminiscent of this fact, I wonder whether a supergroup of $G$ can be built up, say $\tilde G$, such that $[\tilde G:G]=2$. Namely:

Is every group $G$ a subgroup of index $2$ of some $\tilde G$?

I think that's true, based on the following.

Let $G$ be a group and $X_G$ a set such that:

$X_G\cap G=\emptyset$;
there is a bijection $\alpha\colon X_G\to G$.

Let's define $\tilde G:=G\cup X_G$ and $\cdot : \tilde G\times\tilde G \to \tilde G$ by:

\begin{alignat}{1}
&a)\space g\cdot h:=gh, \space\forall g,h \in G \\
&b)\space g\cdot x:=\alpha^{-1}(g\alpha(x)), \space\forall g \in G, x\in X_G \\
&c)\space x\cdot g:=\alpha^{-1}(\alpha(x)g), \space\forall g \in G, x\in X_G \\
&d)\space x\cdot y:=\alpha(x)\alpha(y), \space\forall x,y\in X_G \\
\tag 2
\end{alignat}

Associativity

It holds in $G$ by definition. Besides, $\forall g,h \in G, \forall x \in X_G$:
\begin{alignat}{1}
(g\cdot h)\cdot x &= (gh)\cdot x \\
&= \alpha^{-1}(gh\alpha(x)) \\
\end{alignat}
and
\begin{alignat}{1}
g\cdot (h\cdot x) &= \alpha^{-1}(g\alpha(h\cdot x)) \\
&= \alpha^{-1}(g\alpha(\alpha^{-1}(h\alpha(x)))) \\
&= \alpha^{-1}(gh\alpha(x)) \\
\end{alignat}
whence:
$$g\cdot (h\cdot x) = (g\cdot h)\cdot x \tag 3$$
Likewise, $\forall g,h \in G, \forall x \in X_G$:
\begin{alignat}{1}
(g\cdot x)\cdot h &= \alpha^{-1}(\alpha(g\cdot x)h) \\
&= \alpha^{-1}(\alpha(\alpha^{-1}(g\alpha(x)))h) \\
&= \alpha^{-1}(g\alpha(x)h) \\
\end{alignat}
and
\begin{alignat}{1}
g\cdot (x\cdot h) &= \alpha^{-1}(g\alpha(x\cdot h)) \\
&= \alpha^{-1}(g\alpha(\alpha^{-1}(\alpha(x)h))) \\
&= \alpha^{-1}(g\alpha(x)h) \\
\end{alignat}
whence:
$$g\cdot (x\cdot h) = (g\cdot x)\cdot h \tag 4$$
Furthermore, $\forall g \in G, \forall x,y \in X_G$:
\begin{alignat}{1}
(g\cdot x)\cdot y &= \alpha(g\cdot x)\alpha(y)\\
&= \alpha(\alpha^{-1}(g\alpha(x)))\alpha(y)\\
&= g\alpha(x)\alpha(y)\\
&= g(\alpha(x)\alpha(y))\\
&= g\cdot(\alpha(x)\alpha(y))\\
&= g\cdot(x\cdot y)\\
\tag 5
\end{alignat}
Finally, $\forall x,y,z \in X_G$:
\begin{alignat}{1}
(x\cdot y)\cdot z &= (\alpha(x)\alpha(y))\alpha(z)\\
&= \alpha(x)(\alpha(y)\alpha(z)) \\
&= x\cdot(y\cdot z) \\
\tag 6
\end{alignat}

Unit

Note that:

by $(2$-$b)$: $\space$ $e\cdot x=\alpha^{-1}(e\alpha(x))=\alpha^{-1}(\alpha(x))=x, \space\forall x \in X_G$
by $(2$-$c)$: $\space$ $x\cdot e=\alpha^{-1}(\alpha(x)e)=\alpha^{-1}(\alpha(x))=x, \space\forall x \in X_G$

and $e$ serves as unit throughout $\tilde G$.

Inverses

Let's define:
$$x^{-1}:= \alpha^{-1}(\alpha(x)^{-1}), \forall x \in X_G \tag 7$$
Therefore, by $(2$-$d)$ and $(7)$:

$\space$ $x\cdot x^{-1}=\alpha(x)\alpha(x^{-1})=\alpha(x)\alpha(\alpha^{-1}(\alpha(x)^{-1}))=\alpha(x)\alpha(x)^{-1}=e, \space\forall x \in X_G$

and $x^{-1}$ serves as inverse of the element $x \in X_G$.

Seemingly, $\tilde G$, endowed with the operation $(2)$, is indeed a group, and $[\tilde G:G]=2$.
Comment: It seems correct to me. Actually, what you have constructed is $G\times (\mathbf{Z}/2\mathbf{Z})$ in which $G$ may be embedded via $g\mapsto (g,0)$. Nevertheless, you have been careful enough, so that $\widetilde{G}$ *really* contains $G$...
Comment: It seems okay to me.
Comment: @PaulPlummer Up to isomorphism, yes. I guess that the OP wants a real inclusion of sets.
Comment: @TMO. Yes, correct.
Comment: Maybe I missed something from your question, but wouldn't just taking a direct product with the cyclic group of order 2 work for your question?
Answer: Why not take $\tilde G = G \times \mathbb{Z}/2 \mathbb{Z}$?
Comment: No problem, your effort was excellent and I gave you a +1.
Comment: Yes, now I got aware of that, thanks. The only I can notice, is that $G$ is not a subset of your (and other commentors') $\tilde G$. Anyway, I admit that my question didn't mention that.
Answer: Your proof seems fine to me.

An alternative proof is via group presentations.
If $G$ has as a presentation
$$\langle X\mid R\rangle,$$
then, for any symbol $\xi\notin G$, since $\Bbb Z_2$ has as a presentation
$$\langle \xi\mid \xi^2\rangle,$$
the group $G\times \Bbb Z_2$ has as a presentation
$$\langle X\cup\{\xi\}\mid R\cup\{\xi^2\}\cup\{ x\xi=\xi x\mid x\in X\}\rangle.$$
Then $G$ is a subgroup of $G\times\Bbb Z_2$ with index two.
Comment: Thank you, Shaun. As pointed out in my comment to Nicky's answer, the only difference is that $G$ is a subset of "my" $\tilde G$, while it's not of yours, though this was not a constraint in my question. I note that just for the records.


Escoder extensão .php através do arquivo .htaccess

Question: Estou usando o seguinte código em um servidor web, da hostgator, mas não consigo esconder a extensão .php. Como resolver isso?
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

Comment: Você está fazendo isso no localhost? usando qual servidor wamp?
Comment: Você verificou se o `rewrite_module` esta ativo?
Comment: Então, parece que esse código RewriteEngine on ativa, de acordo com um tutorial que li
Comment: Estou fazendo em um servidor web, da hostgator
Comment: [a resposta pra nao ter que mudar todas as paginas ou arquivos esta no link](https://pt.stackoverflow.com/a/248772/17590)
Answer: RewriteEngine On

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) $1\\.php [L]

Claro que isso não impedirá do usuário digitar diretamente na URL. /arquivo.php
Exemplo de uso.
Você tem uma página http://foo.bar/home.php, então poderá acessar como http://foo.bar/home
Comment: Funcionou!
Na verdade estava pensando que a função simplesmente escondia a extensão.
Tirei as extensões de alguns links que direcionam para as páginas e deu certo, não exibe mais a extensão, só que no site tem mais de 200 links para eliminar a extensão de cada um...


Descobrir qual o digito verificador de um CNPJ

Question: Tenho uma classe onde eu consigo descobrir se o CNPJ digitado pelo usuário é valido ou não.
O que eu gostaria de fazer, e que não estou conseguindo, é mostrar para o usuário quais são os dois últimos dígitos válidos que ele deveria digitar.
Por exemplo:
MessageBox("CNPJ inválido, o Digito Verificador correto seria: "+DV);

Gostaria de fazer isso para o CNPJ e CPF.
O método de validação do CNPJ é o seguinte:
public bool ValidaCNPJ(string vrCNPJ)
    {
        int nrDig;
        string CNPJ = vrCNPJ.Replace(".", "");
        CNPJ = CNPJ.Replace("/", "");
        CNPJ = CNPJ.Replace("-", "");

        string ftmt = "6543298765432";
        int[] digitos = new int[14];
        int[] soma = new int[2];
        soma[0] = 0;
        soma[1] = 0;
        int[] resultado = new int[2];
        resultado[0] = 0;
        resultado[1] = 0;
        bool[] CNPJOk = new bool[2];
        CNPJOk[0] = false;
        CNPJOk[1] = false;

        try
        {
            for (nrDig = 0; nrDig < 14; nrDig++)
            {
                digitos[nrDig] = int.Parse(
                 CNPJ.Substring(nrDig, 1));
                if (nrDig <= 11)
                    soma[0] += (digitos[nrDig] *
                    int.Parse(ftmt.Substring(
                      nrDig + 1, 1)));
                if (nrDig <= 12)
                    soma[1] += (digitos[nrDig] *
                    int.Parse(ftmt.Substring(
                      nrDig, 1)));
            }

            for (nrDig = 0; nrDig < 2; nrDig++)
            {
                resultado[nrDig] = (soma[nrDig] % 11);
                if ((resultado[nrDig] == 0) || (resultado[nrDig] == 1))
                    CNPJOk[nrDig] = (
                    digitos[12 + nrDig] == 0);

                else
                    CNPJOk[nrDig] = (
                    digitos[12 + nrDig] == (
                    11 - resultado[nrDig]));

            }

            return (CNPJOk[0] && CNPJOk[1]);
        }
        catch
        {
            return false;
        }

    }

Método para validar CPF
public bool ValidaCpf(string cpf)
{

    int[] multiplicador1 = new int[9] { 10, 9, 8, 7, 6, 5, 4, 3, 2 };
    int[] multiplicador2 = new int[10] { 11, 10, 9, 8, 7, 6, 5, 4, 3, 2 };
    string tempCpf;
    string digito;

    int soma;
    int resto;

    cpf = cpf.Trim();
    cpf = cpf.Replace(".", "").Replace("-", "");

    if (cpf.Length != 11)
    {
        return false;
    }
    tempCpf = cpf.Substring(0, 9);

    soma = 0;

    for (int i = 0; i < 9; i++)
    {
        soma += int.Parse(tempCpf[i].ToString()) * (multiplicador1[i]);
    }
    resto = soma % 11;

    if (resto < 2)
    {
        resto = 0;
    }
    else
    {
        resto = 11 - resto;
    }

    digito = resto.ToString();
    tempCpf = tempCpf + digito;
    int soma2 = 0;

    for (int i = 0; i < 10; i++)
    {
        soma2 += int.Parse(tempCpf[i].ToString()) * multiplicador2[i];
    }

    resto = soma2 % 11;

    if (resto < 2)
    {
        resto = 0;
    }
    else
    {
        resto = 11 - resto;
    }

    digito = digito + resto.ToString();
    return cpf.EndsWith(digito);
}

Comment: Não entendo por que quer dar essa informação ao utilizador. Os dígitos de verificação servem para confirmar se não houve engano ao digitar qualquer um dos dígitos do CNPJ e não apenas os dois últimos. Aquilo que me parece que está a sugerir é querer dizer ao utilizador para alterar os últimos dois dígitos. O CNPJ será válido mas de certeza não será o do utilizador.
Comment: Sim @ramaral, gostaria de dizer para o usuario alterar os dois ultimos digitos, mas pensei em dizer para ele quais seria os corretos.
Claro que assim o cara vai poder burlar o sistema com o cnpj que não existe, mas é so uma opção amais que gostaria de disponibilizar para ele. E de aprendizagem tambem!
Comment: @EmersonMoraes, você fala em toda pergunta em CNPJ, mas seu exemplo é de CPF, recomendo substituir onde você cita CNPJ por CPF, ou vice-versa.
Comment: Desculpa @Fernando, acabei copiando o codigo errado. Vou colocar o de CNPJ tbm!
Answer: Resolvi responder porque a resposta aceita não faz o CNPJ como pedido na pergunta, e ambas são ineficientes, ainda que certas, fora que são copiadas de um código amplamente usado, mas que deveriam citar a fonte (nem me arrisco dizer qual é). Eu sei que é um código mais complexo, mas ele pode ser usado onde precisa executar em grande quantidade sem problemas.
Reforço o que já foi dito que a intenção da pergunta não é boa.
using static System.Console;
using System;

(var ok, var digitos) = ValidarCnpj("12345678901234");
if (!ok) WriteLine($"Dígitos finais corretos seriam {digitos}");
(ok, digitos) = ValidarCnpj("12.345.678.9012-34");
if (!ok) WriteLine($"Dígitos finais corretos seriam {digitos}");

static (bool, string) ValidarCnpj(string cnpj) {
    if (cnpj.Length < 14) return (false, "");
    Span<int> digitos = stackalloc int[14];
    for (int i = 0, j = 0; i < 14; j++) if (char.IsDigit(cnpj[j])) digitos[i++] = cnpj[j] - 48;
    int soma = 0, soma2 = 0;
    for (var i = 0; i < 4; i++) {
        soma += digitos[i] * (5 - i);
        soma2 += digitos[i] * (6 - i);
    }
    soma2 += digitos[4] * 2;
    for (var i = 4; i < 11; i++) {
        soma += digitos[i] * (13 - i);
        soma2 += digitos[i + 1] * (13 - i);
    }
    soma += digitos[11] * 2;
    var resto = soma % 11;
    var dv = digitos[12];
    digitos[12] = resto < 2 ? 0 : 11 - resto;
    soma2 += digitos[12] * 2;
    var ok = digitos[12] == dv;
    resto = soma2 % 11;
    dv = digitos[13];
    digitos[13] = resto < 2 ? 0 : 11 - resto;
    return (ok && digitos[13] == dv, string.Concat(digitos[12], digitos[13]));
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Com ultra otimização:
using static System.Console;
using System;

(var ok, var digitos) = ValidarCnpj("12345678901234");
if (!ok) WriteLine($"Dígitos finais corretos seriam {digitos}");
(ok, digitos) = ValidarCnpj("12.345.678.9012-34");
if (!ok) WriteLine($"Dígitos finais corretos seriam {digitos}");

static (bool, string) ValidarCnpj(string cnpj) {
    if (cnpj.Length < 14) return (false, "");
    Span<int> digitos = stackalloc int[14];
    for (int i = 0, j = 0; i < 14; j++) if (char.IsDigit(cnpj[j])) digitos[i++] = cnpj[j] - 48;
    int soma = 0, soma2 = 0;
    soma += digitos[0] * 5;
    soma2 += digitos[0] * 6;
    soma += digitos[1] * 4;
    soma2 += digitos[1] * 5;
    soma += digitos[2] * 3;
    soma2 += digitos[2] * 4;
    soma += digitos[3] * 2;
    soma2 += digitos[3] * 3;
    soma += digitos[4] * 9;
    soma2 += digitos[4] * 2;
    soma += digitos[5] * 8;
    soma2 += digitos[5] * 9;
    soma += digitos[6] * 7;
    soma2 += digitos[6] * 8;
    soma += digitos[7] * 6;
    soma2 += digitos[7] * 7;
    soma += digitos[8] * 5;
    soma2 += digitos[8] * 6;
    soma += digitos[9] * 4;
    soma2 += digitos[9] * 5;
    soma += digitos[10] * 3;
    soma2 += digitos[10] * 4;
    soma += digitos[11] * 2;
    soma2 += digitos[11] * 3;
    var resto = soma % 11;
    var dv = digitos[12];
    digitos[12] = resto < 2 ? 0 : 11 - resto;
    soma2 += digitos[12] * 2;
    var ok = digitos[12] == dv;
    resto = soma2 % 11;
    dv = digitos[13];
    digitos[13] = resto < 2 ? 0 : 11 - resto;
    return (ok && digitos[13] == dv, string.Concat(digitos[12], digitos[13]));
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Dá para otimizar mais. Pode não compensar fazer o unroll manual. Há casos que ganha de um lado e perde de outro.
Answer: Apenar de não ver muita utilidade na sua implementação final, como citado dos comentários de @ramaral, vou lhe ajudar no problema em si.
Você pode utilizar os parâmetros out do C#, para recuperar do método de validação os dígitos verificadores, onde a implementação, seria algo assim (há comentários nas linhas alteradas):
// adicione o paramêtro out string dv
public bool ValidaCpf(string cpf, out string dv)
{
    int[] multiplicador1 = new int[9] { 10, 9, 8, 7, 6, 5, 4, 3, 2 };
    int[] multiplicador2 = new int[10] { 11, 10, 9, 8, 7, 6, 5, 4, 3, 2 };
    string tempCpf;
    string digito;

    int soma;
    int resto;

    cpf = cpf.Trim();
    cpf = cpf.Replace(".", "").Replace("-", "");

    if (cpf.Length != 11)
    {
        // adicione essa linha, onde você seta o parâmetro out dv, com null, para fins de compilação, já que não há valor a ser adicionado, ou se acha melhor pode adicionar qualquer outro valor default.
        dv = null;
        return false;
    }
    tempCpf = cpf.Substring(0, 9);

    soma = 0;

    for (int i = 0; i < 9; i++)
    {
        soma += int.Parse(tempCpf[i].ToString()) * (multiplicador1[i]);
    }
    resto = soma % 11;

    if (resto < 2)
    {
        resto = 0;
    }
    else
    {
        resto = 11 - resto;
    }

    digito = resto.ToString();
    tempCpf = tempCpf + digito;
    int soma2 = 0;

    for (int i = 0; i < 10; i++)
    {
        soma2 += int.Parse(tempCpf[i].ToString()) * multiplicador2[i];
    }

    resto = soma2 % 11;

    if (resto < 2)
    {
        resto = 0;
    }
    else
    {
        resto = 11 - resto;
    }

    digito = digito + resto.ToString();

    // adicione essa linha, onde você seta o parâmetro out dv, com o digito verificador valido
    dv = digito;
    return cpf.EndsWith(digito);
}

Onde um exemplo de utilização seria esse:
public void TestUtilizacao()
{
    string dv = null;
    string cpf = "12345678901";
    if(ValidaCpf(cpf, out dv))
    {
        MessageBox.Show("CPF valido");
    }else
    {
        MessageBox.Show("CPF inválido, o Digito Verificador correto seria: " + dv);
    }
}

O resultado do teste de utilização seria "CPF inválido, o Digito Verificador correto seria: 09".
Comment: consegui os dois... O CNPJ é a mesma base de como vc fez o CPF. Muito obrigado pela ajuda xD
Comment: O CNPJ é a mesma coisa neh...?
Comment: @EmersonMoraes, sim mesma ideia, só não identifiquei seu digito verificados no seu método de validação de CNPJ. (Ele me parece um pouco enrolado, hehe)
Answer: public static bool IsCnpj(string cnpj)
    {
        int[] multiplicador1 = new int[12] {5,4,3,2,9,8,7,6,5,4,3,2};
        int[] multiplicador2 = new int[13] {6,5,4,3,2,9,8,7,6,5,4,3,2};
        int soma;
        int resto;
        string digito;
        string tempCnpj;

        cnpj = cnpj.Trim();
        cnpj = cnpj.Replace(".", "").Replace("-", "").Replace("/", "");

        if (cnpj.Length != 14)
           return false;

        tempCnpj = cnpj.Substring(0, 12);

        soma = 0;
        for(int i=0; i<12; i++)
           soma += int.Parse(tempCnpj[i].ToString()) * multiplicador1[i];

        resto = (soma % 11);
        if ( resto < 2)
           resto = 0;
        else
           resto = 11 - resto;

        digito = resto.ToString();

        tempCnpj = tempCnpj + digito;
        soma = 0;
        for (int i = 0; i < 13; i++)
           soma += int.Parse(tempCnpj[i].ToString()) * multiplicador2[i];

        resto = (soma % 11);
        if (resto < 2)
            resto = 0;
        else
           resto = 11 - resto;

        digito = digito + resto.ToString();

        if cnpj.Right(2) <> digito
           MsgBox("CNPJ inválido, o Digito Verificador correto seria: "+digito);

        return cnpj.EndsWith(digito);
    }


Probability density function of transformed variable

Question: Suppose $X$ is a random variable that is uniformly distributed, and $f$ is a function such as $f:\mathbb{R}\rightarrow[-a, a]$ where $a$ is some constant.
How do I find the probability density function of $f(X)$? The function $f$ is not monotonic but can be assumed to be continuous and differentiable.
Comment: Is $f$ monotonic?
Comment: No, it would not be a monotonic function.
Comment: Continuous? Piecewise continuous? Do you have a specific example in mind for $f$?
Comment: Continuous and differentiable
Answer: Suppose that for each $z \in [-a.a]$, the equation
$f(x) = z$ has a finite number
of solutions  in whatever interval $X$ happens to be uniformly distributed on, and that of these solutions, the derivative
$\frac{\mathrm df(x)}{\mathrm dx}$ of $f(x)$ is
nonzero only at $x_1, x_2, \ldots, x_n$. Note that $n$
might be different for different $z$'s and there might
be no solutions at all in some cases.
Then, for each $z$ in $[-a,a]$,
$$f_Z(z) = \sum_{i=1}^n \frac{f_X(x_i)}{\left|\frac{\mathrm df(x)}{\mathrm dx}\right|_{x=x_i}} = \sum_{i=1}^n \frac{c}{\left|\frac{\mathrm df(x)}{\mathrm dx}\right|_{x=x_i}}\tag{1}$$
where $c$ is the common value of the pdf of $X$ at all points in
the interval on which $X$ is uniformly distributed.
It might look like the right side of $(1)$ does not depend on $z$
at all, but it does so depend. Remember that the values of the
$x_i$ (as well as their number!) depends on what $z$ you have chosen
(that is, they are functions of $z$).
Answer: You've given very general conditions, so I can only offer a very general answer:
If $X \sim P_X$ then we know that
$$P(f(X)\leq z) = P_X(X \in f^{-1}([0,z]))=\frac{Leb(f^{-1}([0,z]) \cap \mathbf{range}\; X)}{Leb(\mathbf{range}\; X)}$$
Where $Leb$ is the Lebesgue measure, $\mathbf{range}\; X$ is the range of $X$ and $x \in f^{-1}(z)$ is the (possibly non-compact) inverse-image of $f$ applied to the set $[0,z]$.
Answer: Distribution is uniform. And the range for $x$ is $-a$ to $+a$. And the uniform distribution is defined as $f(x) = 1/(b-a)$ where  $a<x<b$  i.e. upper limit is $b$ and lower limit is $a$. In your situation, lower limit is $-a$ and upper limit is $+a$ so the pdf will be $f(x)=1/(a-(-a)) = 1/(a+a) =1/(2a)$ where $x$ takes value from $-a$ to $+a$. And $f(x) = 0$ otherwise.
Comment: This obviously false with such a modest restrictions on $f$.
Comment: Distribution is uniform. And the range for x is -a to +a. And the uniform distribution is defined as f(x) = 1/(b-a) where  a<x<b  i.e. upper limit is b and lower limit is a. In your situation, lower limit is -a and upper limit is +a so the pdf will be   f(x)=1/(a-(-a)) = 1/(a+a) =1/(2a)   where x takes value from -a to +a. And ***f(x) = 0*** otherwise.
Comment: Your answer was not being displayed correctly because it was not formatted appropriately; somehow, the HTM/whatever parser was choking on the math notation. Typesetting as MathJax corrected this. Please use MathJax formatting to avoid this problem in the future. A tutorial can be found here. http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference


Mesmo conjunto de caracteres gerando hashs diferentes após conversão com MD5()

Question: Olá, estou criando um sistema que possui uma área de inscrição do usuário no sistema. Na parte da senha eu utilizo md5() para transformar os caracteres em Hash.
Só que eu estou notando o seguinte, as vezes eu insiro um conjunto de caracteres e o mesmo conjunto de caracteres está sendo armazenados e exibidos com hashes(não sei se é esse o plural) diferente.
Por exemplo: O conjunto de caracteres 505987.
No Banco de Dados ele me dá o seguinte hash:

Agora se eu der uma echo desse campo no meu PHP dá a seguinte saída:

Gostaria de saber se isso é normal ?
E gostaria de saber também se eu fosse talvez fazer um comparativo entre esses dois dados em algum momento, poderia dar erro ou passaria de boa.
Pode um mesmo conjunto de caracteres terem Hashes diferentes ?
Desculpem se não consegui ser claro.
ATUALIZANDO: Parece que quando eu digito no form gera um Hash direferente do que quando eu faço uma consulta no banco, pego esse campo que possui o hash armazenado e armazeno em uma variável e depois exibo essa variável.
Comment: Algoritmos de hash são aplicado a bits.. se vocês fizer hash de um número inteiro ou de uma string que representa este número, os resultados serão diferentes pois a representação deste valores em bits são diferentes. Dito isso, a maneira como strings são convertidas em bits depende do encoding. Seria legal você checar se o tipo de dados é o mesmo. :)
Answer: Uma valor deve mapear apenas para um campo de hash, porém um hash pode apontar para várias senhas.
Por exemplo, o hash de uma senha como "vi7700" pode ser igual a um hash de uma senha como "d3f3q8", porém um texto só aponta para um hash.
No seu caso, o hash que está armazenado no banco de dados é o correto, então tenha certeza que ao criar uma hash você está limpando os espaços vazios, use o trim para isso.
Rodando aqui na minha máquina o seguinte código
<?php

 if(md5('505987') == 'b969d7036923881b0cb18539a7b15e7c'){
    echo "Elas são iguais";
 }

O resultado foi o esperado.
Comment: Tomara que o trim resolva. Vou tentar fazer amanhã e te dou um feedback.
Comment: O trim não era o problema, @Hítalo. Mas mesmo assim agradeço pela ajuda.
Answer: Neste caso utilize o trim() ou str_replace() nas aspas simples e duplas.
Um adendo, notei que está utilizando MD5() como senha

Na parte da senha eu utilizo md5()

O correto neste caso é utilizar-se de um salt, adicionar um valor de controle nas senhas para que o hash não retorne a senha direto, pois há diversos sites que utilizam Rainbow Tables ou Hash Tables que podem quebrar MD5 facilmente.
Dê uma pesquisada no conceito para melhor utilização.


onclick the second time round click

Question: not sure if this is possible keeping the code simple, but im trying to make it so that i have an image, when you clicked it, it goes to a new image. then when you click that image, it goes back to the original image.
my code is:
function save_data()
{
if ( document.images.save.src == "saved.png") document.images.save.src="save.png";
if (document.images.save.src == "save.png") document.images.save.src="saved.png";
}

Comment: what's the problem with what you have?
Answer: It can be simplified.
Using
`

You can do
function save_data(img)
{
  img.src = /saved/i.test(img.src) ? 'save.png' : 'saved.png';
}

If this doesn't work, it may have to do with the fact that saved.png is not in the path the html is in. So try it with a full URL:
function save_data(img)
{
  var imgpath = 'http://yoursite.com/imgpath/';
  img.src = imgpath + (/saved/i.test(img.src) ? 'save.png' : 'saved.png');
}

A note: it may be better to assign the click handler unobtrusively (see also this SO question)
Comment: Yes, this is a more elegant solution.
Answer: if ( document.images.save.src == "saved.png") - this won't work, because .src returns the full path to the image, not just the filename. For example, http://site.com/path/images/saved.png.
Try matching substrings instead.
function save_data()
{
if ( document.images.save.src.indexOf("saved.png") != -1) document.images.save.src="save.png";
if (document.images.save.src.indexOf("save.png") != -1) document.images.save.src="saved.png";
}

onclick the second time round click


Filter the nodes by language output by the view

Question: Before I have i18n module and some modules that does the translations but we decided to stop doing translation but still preserve the translated nodes.
After disabling translation modules my views which are using content negotiation says "Broken/Invalid handler" so I removed this filter.
Now all the views are using nodequeue which has a bunch of multilingual nodes.
My question is, how can I filter views to display nodes based on page language. I mean I want to display english articles only when I'm in English pages, korean articles when viewing Korean pages, japanese articles when viewing Japanese pages, etc.
Ex. nodes(eng) for English pages, nodes(korean) for Korean pages, nodes(japanese) for Japanese pages, and nodes(chinese) when in Chinese pages
Answer: one work around is to re-enable the i18n module, to access the filter again, then use some hooks ( like hook_form) to hide and set the default values for the i18n options in the node form if you want to remove those options from the user interface.


How much does Google Apps Script overlap with ECMAscript 5?

Question: I'm starting to incorporate more and more "advanced" Javascript features into Google Apps Script. But I see on Wikipedia that GAS does not include the whole ECMAscript functionality..
What isn't included?
** Update from comment below:
It looks like every aspect of the language that doesn't relate to client side features such as the DOM and the window object is available
Comment: read [this](https://developers.google.com/apps-script/guides/services/#basic_javascript_features)
Comment: It's javascript, so, yeah
Comment: Thanks. This means that asynchronous code would be fine?
Answer: Starting May 2020, Google Apps Script is supported by the V8 runtime which takes advantage of modern ECMAScript.
Here's a list of V8 syntax examples. Please note that ES6 Modules are not yet supported at the time of writing (2020/05/31).
If your script is not yet taking advantage of V8 you can always migrate it to V8.


unix join not working: file is not sorted (and they are!!!)

Question: I have been trying to do a unix join but it doesn't seem to work. I have two files, they are both sorted, the first column on both is a number.
The problem seems to be in the order in which the join is being executed (and how it reads the attribute).
The error output is:
<code>join: tags.csv:34: is not sorted: 109,1219,Alfred,Hitchcock,1165555288
join: users.csv:800: is not sorted: 10,F,35,1,95370,1009,5,979168267
</code>
So I have a 109 value in the line 34 of the tags file and a 10 value in the 800th line of users file. So, it seems to be comparing 10 vs 109 (like trimming) but it gives a error saying it's not sorted.
I have tried changing the order of the files in the join execution, but no luck.
Has anyone experienced something like this?
Comment: Add the command you are running to your question. Also post some samples lines (like first 5 or 10) from both files and post your desired output from it.
Comment: Are you specifying `-t ,`?
Comment: How do you know they're sorted? Try `sort -c` on both files.
Answer: I´ll mention another answer i found searching for the same problem:
"If you are sure you properly sorted your input files and their lines can be paired, you can avoid the above error by running join --nocheck-order file1.txt file2.txt"
This worked for me. Anyway, there are another answers there.
Thanks to @Yoav Weiss https://unix.stackexchange.com/questions/12942/join-file-2-not-in-sorted-order


Android resource compilation failed (Android Studio ver. 3.2.1)

Question: Anyone facing this issue? Can anyone also help to resolve this?
Android resource compilation failed
Output:/Users/alvinlee/AndroidStudioProjects/Testing/app/build/intermediates/incremental/mergeDebugResources/merged.dir/values/values.xml:1797: error: <item> inner element must either be a resource reference or empty.

Command: /Users/alvinlee/.gradle/caches/transforms-1/files-1.1/aapt2-3.2.1-4818971-osx.jar/2b76bad4c2fb4c47c9afdc1612d6e963/aapt2-3.2.1-4818971-osx/aapt2 compile --legacy \
    -o \
    /Users/alvinlee/AndroidStudioProjects/Testing/app/build/intermediates/res/merged/debug \
    /Users/alvinlee/AndroidStudioProjects/Testing/app/build/intermediates/incremental/mergeDebugResources/merged.dir/values/values.xml
Daemon:  AAPT2 aapt2-3.2.1-4818971-osx Daemon #0

Answer: please check the file you have been made values.xml
an inner element must either be a resource reference or When declaring id in resources, the body should be empty
like this:-
<item
    type="id"
    name="id_name" />


Finding the limit of roots products $(\sqrt{2}-\sqrt[3]{2})(\sqrt{2}-\sqrt[4]{2})(\sqrt{2}-\sqrt[5]{2})\cdot \cdot \cdot (\sqrt{2}-\sqrt[n]{2})$

Question: I need to find:

$$
\lim_{n \to \infty } (\sqrt{2}-\sqrt[3]{2})(\sqrt{2}-\sqrt[4]{2})(\sqrt{2}-\sqrt[5]{2})\cdot \cdot \cdot (\sqrt{2}-\sqrt[n]{2})
$$

So far, I think that $0<\sqrt{2}-\sqrt[n]{2}<1$, and it seems to me that the limit will approach zero but I can't figure how to show it mathematically.
Comment: Similar question: http://math.stackexchange.com/questions/551301/find-the-limit-without-using-the-squeezing-principle
Answer: $$(\sqrt{2}-\sqrt[3]{2})(\sqrt{2}-\sqrt[4]{2})(\sqrt{2}-\sqrt[5]{2})\cdot \cdot \cdot (\sqrt{2}-\sqrt[n]{2}) \leq (\sqrt{2}-1)^{n-2} $$ and clearly
$$\lim_{n \to \infty } (\sqrt{2}-1)^{n-2} =0$$
since $0<(\sqrt{2}-1)<1$
so by the comparison test we win.
Comment: Sorry, it seems I got my inequalities messed up, it is fixed now. For whatever reason my sleep-deprived mind had trouble realizing it needed to make the terms being subtracted as small as possible not as big as possible.
Comment: Its Ok @PVAL. It happens to all of us quite a few times :)
Comment: how did you think about $(\sqrt{2}-1)^{n-2}$?
Comment: I saw that each term in the product was less than some given number $<1$ , so I tried (unsuccessfully at first) to come up with a number that worked. The $n-2$ is really just from counting the number of terms.
Comment: Got it. thanks a lot!
Comment: very nice!thax..
Answer: $(\sqrt{2}-\sqrt[3]{2})(\sqrt{2}-\sqrt[4]{2})(\sqrt{2}-\sqrt[5]{2})\cdot \cdot \cdot (\sqrt{2}-\sqrt[n]{2}) \leq (\sqrt{2}-1)^{n-2}$, done.
Comment: How did you come up with the inequality?


Should I use an average ECDF?

Question: This relates to a previous question of mine which didn't gain many responses, perhaps because it wasn't very clear nd well written. I hope this time I will be more accurate and get your much appreciated assistance.
I am analyzing results of a biological experiment. The results given as a single value ( non-negative integer) per genomic position. I am interested in valleys, or local minimam over this series of values.
I wish to control the false positives rate and get the significance for each local minima. I can shuffle the raw data which was used to produce the data.
So what I do is to shuffle the raw data, create the new series of values,search for all local minima and keep their values.
Now, I have something like this:
data_set  local_minima_values
=============================
true_data 4 9 1 27 12 0 0 2 5 32 0 1 5 70 2
sim_1 14 25 94 59 32
sim_2 52 0 14 74 82 12 54
...

Note the number of local minima naturally varies between simulations.
So, my idea was to calculate an ECDF for each simulation and then combine those ECDFs into a single "average ECDF" which represents the null hypothesis. Then, I can assign a p-value for each local minima from the true data, and see how significant ('surprising') it is.
My questions are:

Does this make sense?
How do I create an average ECDF? I can't just merge the values from all simulation together and get and ECDF for this merged set, since the number of minima found in each simulation differs, and I think all simulations should have the same contribution to the average ECDF, or am I wrong?
How should I take the number of simulations (shuffles) into account?

Thanks,
Dave
p.s. I'm working with R.
Comment: I could suggest "Randomization, Bootstrap and Monte Carlo Methods in Biology" by Manly. http://www.amazon.com/Randomization-Bootstrap-Methods-Biology-Statistical/dp/1584885416/ref=sr_1_1?ie=UTF8&qid=1288995733&sr=8-1
Answer: David, before discussing the implementation, I'd discuss question #1. I think the approach "makes sense", if you mean by this that the approach is intuitive. However, from the perspective of bootstrapping, the approach probably won't work. One well-known failure of bootstrap is in fact in the case of maxima and minima. The intuition behind this is that the estimators for these statistics have very large variance: a nonparametric approach based on the empirical distribution doesn't help estimate these statistics. Most approaches are parametric. If interested I can suggest references on the latter.
A reference on the failure of boostrap for extremal statistics is Efron and Tibshirani's very own "An Introduction to the Bootstrap". Check page 81.
Answer: To average the ECDFs, I'd do something like:
impute_resolution = 1e3
values_to_impute = seq(
    min(my_data$true_data)
    , max(my_data$true_data)
    , length.out = impute_resoluton
)

ecdfs = matrix(NA,nrow=length(values_to_impute))

for(i in 1:(ncol(my_data)-1)){ #assumes column 1 is true_data
    this_ecdf = ecdf(my_data[,i+1])
    ecdfs[i,] = this_ecdf(values_to_impute)
}

mean_ecdf = colMeans(ecdfs)
plot(
    x = values_to_impute
    , y = mean_ecdf
    , type = 'l'
)

Should I use an average ECDF?


How to use t() function with node_load in custom drupal module?

Question: I am using a custom module for my site, and I am using node_load to get the field value of type "long text" field and field of value of type "text".
Something like this
$com_types = "".$ucom->node_title."";
How should I translate $ucom->node_title ?
t() function does not translate variables.
Thanks
Answer: Node translation should be done at the node level.  the t() function is for labeling elements of the interface and theme things.
You should look at multi-language node translation modules,  this link is helpful
You'd first want to use something like this:  https://api.drupal.org/api/drupal/modules!translation!translation.module/function/translation_node_get_translations/7
It'll let you get the NIDs of the translated versions of the node you want,  then you can use node_load() to get the translated version.
Comment: I am performing node_load so how can I do that on node level or did you mean get the translated version of node and then I should do node_load ?
Comment: @MohitWadhwa  more detail added in an edit.
Comment: Though, exactly your recommendation on drupal API did not solve my problem but yeah it gave me a way.
I appreciate your help.
So Thanks.


Como salvar em um único vetor, classes bases e derivadas?

Question: Tenho um trabalho em C++, e preciso gravar em um único vetor, uma classe base, e duas derivadas. Como fazer fazer esse vetor?
Answer: Esse tipo de problema é solucionado através de um indireção. Quando você tem um ponteiro para o objeto fica fácil lidar com isso porque o vetor só terá os ponteiros, então não importa se ele tem o objeto base ou qualquer dos derivados. A única exigência é que o objeto apontado seja do tipo base ou derivado dele, só por questão de segurança de tipo e não poder colocar um pão em um vetor de animais.
Se não quer usar indireção aí complica. De forma fácil e natural não tem como. Teria que criar um mecanismo para tratar isso manualmente, e duvido que compense. Você terá que guardar em cada elemento do vetor o objeto e de que tipo ele é, e lidar com cada elemento de acordo com o tipo. Sem isso corre o risco de pegar um objeto como se fosse outro com uma estrutura inadequada. Esse fenômeno é chamado de slicing. Para o vetor ter tamanho fixo ele adotará o tamanho do tipo base, se o tipo derivado for maior, o excesso será descartado. Nem tente.
Comment: Fiquei em dúvida da interpretação exata do que seria o _slicing_ nesse caso. Abri uma pergunta sobre o assunto: https://pt.stackoverflow.com/q/286437/64969


Finding the area of the overlap of two quarter-circles in a square

Question: I am trying to find the area in the overlap of two quarter-circles that are in a $10 \times 10$ square, as somewhat-crudely drawn below:

In this problem I was given a square of side length $10$, with two quarter circles going through the center of the square, meeting at the corners of the square.
So, I found the diagonal of the square, $10 \sqrt 2$, and I reasoned that this is the distance from one end of the quarter circle to the other.
I realized this formed a $45^\circ-45^\circ-90^\circ$ triangle when placed inside of a circle, and two circles' radii compose the legs of the triangle and $10 \sqrt 2$ is the length of the hypotenuse. Thus, the radius of each circle had to be $10.$
Thus, the area of each circle (as a whole) would be given by $\pi 10^2 = 100\pi$, and dividing by $4$ gave the area of each quarter circle to be $25\pi$ (totalling to $50 \pi$ for both).
This simply isn't possible, the area of two quarter circle cannot be $50 \pi$ since it wouldn't fit inside of the square, which has an area of $100$.
Therefore this problem must be impossible, but apparently it's solvable, please show me how to solve it.
Comment: $25\pi\approx78.54<100$
Comment: This might be a great question, but it's hard to tell without a good image.
Comment: How could they overlap?
Comment: It is supposed to go through the centre, so the radius is $5\sqrt 2$ instead of $10\sqrt 2$.
Comment: How is the radius 5*2^1/2 ? If 10*2^1/2 is the distance between the ends of the quarter circle, then the radii of the full circle would be 10, which led me to conclude the area of the quarter circle would be 25pi.
Comment: @ OP - For reference I modified your question's text to have some better formatting, to have a less crude image that embeds, and to fix some wording/fill in some details to make what you're trying to say a bit clearer. Feel free to [edit] the text yourself if I somehow made an error. Also, as far as the fancy math formatting goes, you might find [this reference/tutorial on MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference?noredirect=1&lq=1) useful. It's how we do all of the fancier math text on this site.
Comment: Do u need area of leaf shape in blue color ?
Hint :Do u know the formula of area of lens is $$R^2\theta+r^2\alpha-2\triangle$$
Answer: Firstly, to remove any doubts, you are correct so far in that:

The radius of the circle is $10$ (though you kind of went about this in a roundabout method)
The diagonal is $10\sqrt{2}$
The square has area $100$
The area of each quarter-circle is $25\pi$ for a total of $50\pi$

However, you forget that they overlap. This means that while the quarter circles sum to $50\pi$ in area, some of it just doesn't matter, since the other circle is already covering up that bit of space. (If you've ever heard of the inclusion-exclusion principle for stuff like probabilities and counting problems, it has a very similar feel to it.) Consider the below picture, which only has one of the circles in it. Imagine rotating a copy of this square $180^\circ$ and superimposing it on itself: you obviously end up with the original picture you have, but with overlap:

In fact, it is the area of the overlap you are tasked to find. That overlap is the blue area in the picture below:

With the picture color-coded like this, it should not be difficult to convince you that
$$\text{(The blue area)} = \text{(The square's area)} - \text{(The two bits of green area)}$$
In a similar vein, the first picture should show you that the area of one portion of the green area can be obtained by taking the square, and subtracting the area of the quarter circle. Double that for the green area, and subtract that from the area of the square. Then you have your result, the area of the overlapping region.
Comment: +1 for a careful geometric analysis that leaves some work for the OP.
Answer: A hint at one possible solution method:
The image below is a quarter circle with half a square (the triangle) marked on it.

What area is left if you subtract half the square from the quarter circle?
Answer: Let A = {points bounded in the quadrant using the upper-left corner as center}. n(A) = the area occupied by A and it is a known value.
B = {points bounded in the quadrant using the lower-right corner as center}. n(B) is similarly defined.
$n(A \cup B) = ?$ , which is also a known value and $n(A \cap B) $ is the value to be determined. Find it by "the inclusion-exclusion principle".


Python NoneType _getitem_ error

Question: I'm working with a pice of software written in python from US CERT to do some fuzzing. Included in the software is a minimizer.py tool which is designed to be ran against certain test cases that cause crashes in order to determine exactly which byte mutations are causing the crash.
However when attempting to run the tool it's spitting an error at me. Google searches for both the tool and the error are drawing a blank. Attempting to troubleshoot it myself with limited python experience is not helping either. Any ideas on whats causing the error so I can fix it and get the tool working?
command line options being used are: minimizer.py --stringmode
The error output is as follows:
Traceback (most recent call last):
File "C:\FOE2\tools\minimize.py", line 234, in <module>
main()
File "C:\FOE2\tools\minimize.py", line 183, in main
config = Config(cfg_file).config
File "C:\FOE2\certfuzz\campaign\config\__init__.py", line 76, in __init__
self._set_derived_options()
File "C:\FOE2\certfuzz\campaign\config\foe_config.py", line 93, in _set_derived_options
t = Template(self.config['target']['cmdline_template'])
TypeError: 'NoneType' object has no attribute '__getitem__'

Segments of code from both of the files in last two lines of error are:
__init__.py:
 def __init__(self, config_file):
    self.file = config_file
    self.config = None

    self.load()
    self._set_derived_options()

    self.validations = []
    self._add_validations()
    self.validate()

def _set_derived_options(self):
    pass

And then from foe_config_.py (added the preceding lines of code just in case they are relevant.):
class Config(ConfigBase):
  def _add_validations(self):
    self.validations.append(self._validate_debugger_timeout_exceeds_runner)

  def _set_derived_options(self):
    # interpolate program name
    # add quotes around $SEEDFILE
    t = Template(self.config['target']['cmdline_template'])
    #self.config['target']['cmdline_template'] = t.safe_substitute(PROGRAM=self.config['target']['program'])
    self.config['target']['cmdline_template'] = t.safe_substitute(PROGRAM=quoted(self.config['target']['program']), SEEDFILE=quoted('$SEEDFILE'))

Answer: It's hard to tell from the code you posted, but it looks like __init__ sets self.config to None.  Then it calls _set_derived_options which uses self.config here:
t = Template(self.config['target']['cmdline_template'])

But self.config hasn't changed from being None.  You wouldn't expect None['target'] to give you anything (other than an Exception), but I think that is essentially what you're doing here.
Comment: +1. The other possibility is that you _did_ set `self.config` to a `dict` (or maybe a `defaultdict` that returns `None` for missing keys, or…), but `self.config['target']` itself is `None`, which would cause the same error. If you want to check that, break up your code, e.g.: `target = self.config['target']`, `template = target['cmdline_template']`, `t = Template(template)`. That will tell you which one is failing. And give you an opportunity to `print` or `log` each value in the line before you use it.
Comment: Sweet thanks for pointing that out, I looked in __init__ and the class defining that function required a config file to be passed when being initiated. Changed command line paramters to include --config= and worked like a charm. Thanks a bunch!
Comment: @Stev0 -- Presumably that's what `self.load()` is responsible for -- I see it now.

Python NoneType _getitem_ error


amp-form error Trust for 'submit' (2) insufficient (min: 3).

Question: I dont edit code.
Can't send it suddenly since yesterday.
Amp-html Update trust levels for existing actions to spec
<form id="myform" class="p3 hide-inputs" method="post" action-xhr="/vote" target="_blank">

<input type="radio" name="vote" value="up" on="change:myform.submit">GOOD 1

<input type="radio" name="vote" value="down" on="change:myform.submit">BAD 0
</form>

> error.js:151 Trust for 'submit' (2) insufficient (min: 3).
> Ud    @   error.js:151 f.error    @   log.js:214
> Hg.satisfiesTrust @   action-impl.js:164 Ug   @   action-impl.js:502
> f.trigger @   action-impl.js:435 (anonymous)  @   action-impl.js:259

Answer: I used your code in html page. One error is the following:
"action-xhr" "must start with "https://" or "//" or be relative and served from either https or from localhost. Invalid value:" "/vote"

so, try to change action-xhr="/vote" in action-xhr="//www.yoursite.com/vote"