Does the topmost DNS name, ., point to an actual server?

Question: In the DNS system, everything stems from .. So the top-level domains like .com can also be written as .com.. For example, example.com is short for example.com..
But as I can't perform any sort of look up on . I'm wondering if it actually points to a real machine somewhere. Does it?
Comment: Why do you say "I can't perform any sort of look up on ."? As demonstrated by the answer, it is perfectly possible.
Comment: @bortzmeyer Yes it is. I learned about dig from the answer.
Answer: Kind of.  The DNS root has root nameservers, which have NS records, so you could actually do a query like this:
falcon@akira ~ $ dig in ns .

; <<>> DiG 9.8.0 <<>> in ns .
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 31632
;; flags: qr rd ra; QUERY: 1, ANSWER: 13, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;.                              IN      NS

;; ANSWER SECTION:
.                       21026   IN      NS      g.root-servers.net.
.                       21026   IN      NS      k.root-servers.net.
.                       21026   IN      NS      c.root-servers.net.
.                       21026   IN      NS      b.root-servers.net.
.                       21026   IN      NS      d.root-servers.net.
.                       21026   IN      NS      f.root-servers.net.
.                       21026   IN      NS      m.root-servers.net.
.                       21026   IN      NS      h.root-servers.net.
.                       21026   IN      NS      a.root-servers.net.
.                       21026   IN      NS      j.root-servers.net.
.                       21026   IN      NS      l.root-servers.net.
.                       21026   IN      NS      i.root-servers.net.
.                       21026   IN      NS      e.root-servers.net.

;; Query time: 0 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Sat Oct 20 12:15:07 2012
;; MSG SIZE  rcvd: 228

This data normally comes from what are called glue records, stored in a file on individual DNS servers; when the DNS server goes to resolve a name; this is also how a DNS server gets the address of one to query it.
Those root servers have information on where to find nameservers for the various TLDs, which in turn have information on where to find nameservers for individual domains.
There is not, and likely will never be, an A, AAAA, MX, or other such record for the DNS root ., so querying on that data will of course never succeed.  Likewise, though there are name servers (the root servers above) that are authoritative for ., it does not refer to an actual host.
For more on that topic, have a look at how recursive DNS name resolution works.  It is quite simple: essentially, a DNS server starts at the root, queries one of the root servers, asks for the record it wants, and gets a referral with an NS record instead.  It keeps doing this until it finds the authoritative server for the name it is querying, which is actually able to answer.  This process is expensive, so many nameservers cache this response for the TTL (in this example, 21026 seconds).
Comment: That 20126s is what remains of the TTL on the server you're querying; if you repeat the query a few seconds later, you should see those numbers dropping in real time.  If you direct the query to, eg, `a.root-servers.net`, you'll get the raw TTL, which is a somewhat larger figure.


Using RViennaCL for matrix multiplication

Question: I'm a newbie using the RViennaCL package, trying to do GPU matrix multiplication.
Trying a simple case I created a cpp file inside the src folder within the package I created (gpuUtils), with this code:
#include "viennacl/ocl/backend.hpp"
#include "viennacl/linalg/prod.hpp"
#include "viennacl/tools/random.hpp"
#include "viennacl/matrix.hpp"

//' PU matrix multiplication
//'
//' @export
// [[Rcpp::export]]
SEXP matMult(){

  viennacl::tools::uniform_random_numbers<float> randomNumber;

  viennacl::matrix<float> vcl_A(400, 400);
  viennacl::matrix<float> vcl_B(400, 400);

  for (unsigned int i = 0; i < vcl_A.size1(); ++i)
    for (unsigned int j = 0; j < vcl_A.size2(); ++j)
      vcl_A(i,j) = randomNumber();
  for (unsigned int i = 0; i < vcl_B.size1(); ++i)
    for (unsigned int j = 0; j < vcl_B.size2(); ++j)
      vcl_B(i,j) = randomNumber();
  viennacl::matrix<float> vcl_C = viennacl::linalg::prod(vcl_A, vcl_B);
  return Rcpp::wrap(vcl_C);
}

Then I build the package:
$ R CMD build gpuUtils
* checking for file 'gpuUtils/DESCRIPTION' ... OK
* preparing 'gpuUtils':
* checking DESCRIPTION meta-information ... OK
* cleaning src
* checking for LF line-endings in source and make files and shell scripts
* checking for empty or unneeded directories
* building 'gpuUtils_0.0.0.9000.tar.gz'

But when trying to install it I get:
$ R CMD INSTALL gpuUtils_0.0.0.9000.tar.gz
* installing to library '/home/usr/R'
* installing *source* package 'gpuUtils' ...
** libs
g++  -I/opt/ohpc/pub/libs/gnu7/R/3.4.2/lib64/R/include -DNDEBUG -I/usr/local/cuda-9.0/include/ -I"/home/usr/R/Rcpp/include" -I"/home/usr/R/RViennaCL/include" -I/usr/local/include   -fpic  -g -O2  -c gpuUtils.cpp -o gpuUtils.o
In file included from /home/usr/R/Rcpp/include/RcppCommon.h:195:0,
                 from /home/usr/R/Rcpp/include/Rcpp.h:27,
                 from /home/usr/R/RViennaCL/include/viennacl/ocl/forwards.h:29,
                 from /home/usr/R/RViennaCL/include/viennacl/ocl/context.hpp:36,
                 from /home/usr/R/RViennaCL/include/viennacl/ocl/backend.hpp:26,
                 from gpuUtils.cpp:1:
/home/usr/R/Rcpp/include/Rcpp/internal/wrap.h: In instantiation of 'SEXPREC* Rcpp::internal::wrap_dispatch_unknown_iterable(const T&, Rcpp::traits::false_type) [with T = viennacl::matrix<float, viennacl::row_major>; SEXP = SEXPREC*; Rcpp::traits::false_type = Rcpp::traits::integral_constant<bool, false>]':
/home/usr/R/Rcpp/include/Rcpp/internal/wrap.h:732:43:   required from 'SEXPREC* Rcpp::internal::wrap_dispatch_unknown(const T&, Rcpp::traits::false_type) [with T = viennacl::matrix<float, viennacl::row_major>; SEXP = SEXPREC*; Rcpp::traits::false_type = Rcpp::traits::integral_constant<bool, false>]'
/home/usr/R/Rcpp/include/Rcpp/internal/wrap.h:770:41:   required from 'SEXPREC* Rcpp::internal::wrap_dispatch_eigen(const T&, Rcpp::traits::false_type) [with T = viennacl::matrix<float, viennacl::row_major>; SEXP = SEXPREC*; Rcpp::traits::false_type = Rcpp::traits::integral_constant<bool, false>]'
/home/usr/R/Rcpp/include/Rcpp/internal/wrap.h:787:39:   required from 'SEXPREC* Rcpp::internal::wrap_dispatch_unknown_importable(const T&, Rcpp::traits::false_type) [with T = viennacl::matrix<float, viennacl::row_major>; SEXP = SEXPREC*; Rcpp::traits::false_type = Rcpp::traits::integral_constant<bool, false>]'
/home/usr/R/Rcpp/include/Rcpp/internal/wrap.h:807:52:   required from 'SEXPREC* Rcpp::internal::wrap_dispatch(const T&, Rcpp::traits::wrap_type_unknown_tag) [with T = viennacl::matrix<float, viennacl::row_major>; SEXP = SEXPREC*]'
/home/usr/R/Rcpp/include/Rcpp/internal/wrap_end.h:30:38:   required from 'SEXPREC* Rcpp::wrap(const T&) [with T = viennacl::matrix<float, viennacl::row_major>; SEXP = SEXPREC*]'
gpuUtils.cpp:25:26:   required from here
/home/usr/R/Rcpp/include/Rcpp/internal/wrap.h:523:17: error: static assertion failed: cannot convert type to SEXP
                 static_assert(!sizeof(T), "cannot convert type to SEXP");
                 ^~~~~~~~~~~~~
make: *** [gpuUtils.o] Error 1
ERROR: compilation failed for package 'gpuUtils'
* removing '/home/usr/R/gpuUtils'
* restoring previous '/home/usr/R/gpuUtils'

Which indicates that viennacl::matrix need its own wrap function to be written.
So I tried to follow this very nice vignette for custom templating as and wrap functions within Rcpp, adapting it to the viennacl::matrix case.
Here's my cpp code:
#include <RcppCommon.h>
#include "viennacl/ocl/backend.hpp"
#include "viennacl/matrix.hpp"

// [[Rcpp::plugins("cpp11")]]
// Provide Forward Declarations
namespace Rcpp {
  namespace traits{
    // Setup non-intrusive extension via template specialization for
    // 'viennacl' class

    // Support for wrap
    template <typename T> SEXP wrap(const viennacl::matrix<T> & obj);

    // Support for as<T>
    template <typename T> class Exporter< viennacl::matrix<T> >;
  }
}

#include <Rcpp.h>

// Define template specializations for as<> and wrap
namespace Rcpp {

  namespace traits{

  // Defined wrap case
  template <typename T> SEXP wrap(const viennacl::matrix<T> & obj){
    const int RTYPE = Rcpp::traits::r_sexptype_traits<T>::rtype ;

    return Rcpp::Matrix< RTYPE >(obj.begin(), obj.end());
  };

  // Defined as< > case
  template<typename T> class Exporter< viennacl::matrix<T> > {
    typedef typename viennacl::matrix<T> OUT ;

    // Convert the type to a valid rtype.
    const static int RTYPE = Rcpp::traits::r_sexptype_traits< T >::rtype ;
    Rcpp::Matrix<RTYPE> mat;

    public:
      Exporter(SEXP x) : mat(x) {
        if (TYPEOF(x) != RTYPE)
          throw std::invalid_argument("Wrong R type for mapped 2D array");
      }
      OUT get() {

       // Need to figure out a way to perhaps do a pointer pass?
        OUT x(mat.size());

        std::copy(mat.begin(), mat.end(), mat.begin());

        return x;
      }
    };
  }
}

//' viennacl matrix templating
//'
//' @export
// [[Rcpp::export]]
void matTemplate(Rcpp::NumericMatrix in_mat){
  viennacl::matrix<double> viennacl_mat = Rcpp::as< viennacl::matrix<double> >(in_mat);
  Rcpp::NumericMatrix out_mat = Rcpp::wrap(viennacl_mat);
}

Builds fine:
$ R CMD build gpuUtils
* checking for file 'gpuUtils/DESCRIPTION' ... OK
* preparing 'gpuUtils':
* checking DESCRIPTION meta-information ... OK
* cleaning src
* checking for LF line-endings in source and make files and shell scripts
* checking for empty or unneeded directories
* building 'gpuUtils_0.0.0.9000.tar.gz'

But still getting the same error:
$ R CMD INSTALL gpuUtils_0.0.0.9000.tar.gz
* installing to library '/home/usr/R'
* installing *source* package 'gpuUtils' ...
** libs
g++  -I/opt/ohpc/pub/libs/gnu7/R/3.4.2/lib64/R/include -DNDEBUG -I/usr/local/cuda-9.0/include/ -I"/home/usr/R/Rcpp/include" -I"/home/usr/R/RViennaCL/include" -I/usr/local/include   -fpic  -g -O2  -c gpuUtils.cpp -o gpuUtils.o
In file included from /home/usr/R/Rcpp/include/RcppCommon.h:195:0,
                 from gpuUtils.cpp:1:
/home/usr/R/Rcpp/include/Rcpp/internal/wrap.h: In instantiation of 'SEXPREC* Rcpp::internal::wrap_dispatch_unknown_iterable(const T&, Rcpp::traits::false_type) [with T = viennacl::matrix<double, viennacl::row_major>; SEXP = SEXPREC*; Rcpp::traits::false_type = Rcpp::traits::integral_constant<bool, false>]':
/home/usr/R/Rcpp/include/Rcpp/internal/wrap.h:732:43:   required from 'SEXPREC* Rcpp::internal::wrap_dispatch_unknown(const T&, Rcpp::traits::false_type) [with T = viennacl::matrix<double, viennacl::row_major>; SEXP = SEXPREC*; Rcpp::traits::false_type = Rcpp::traits::integral_constant<bool, false>]'
/home/usr/R/Rcpp/include/Rcpp/internal/wrap.h:770:41:   required from 'SEXPREC* Rcpp::internal::wrap_dispatch_eigen(const T&, Rcpp::traits::false_type) [with T = viennacl::matrix<double, viennacl::row_major>; SEXP = SEXPREC*; Rcpp::traits::false_type = Rcpp::traits::integral_constant<bool, false>]'
/home/usr/R/Rcpp/include/Rcpp/internal/wrap.h:787:39:   required from 'SEXPREC* Rcpp::internal::wrap_dispatch_unknown_importable(const T&, Rcpp::traits::false_type) [with T = viennacl::matrix<double, viennacl::row_major>; SEXP = SEXPREC*; Rcpp::traits::false_type = Rcpp::traits::integral_constant<bool, false>]'
/home/usr/R/Rcpp/include/Rcpp/internal/wrap.h:807:52:   required from 'SEXPREC* Rcpp::internal::wrap_dispatch(const T&, Rcpp::traits::wrap_type_unknown_tag) [with T = viennacl::matrix<double, viennacl::row_major>; SEXP = SEXPREC*]'
/home/usr/R/Rcpp/include/Rcpp/internal/wrap_end.h:30:38:   required from 'SEXPREC* Rcpp::wrap(const T&) [with T = viennacl::matrix<double, viennacl::row_major>; SEXP = SEXPREC*]'
gpuUtils.cpp:68:56:   required from here
/home/usr/R/Rcpp/include/Rcpp/internal/wrap.h:523:17: error: static assertion failed: cannot convert type to SEXP
                 static_assert(!sizeof(T), "cannot convert type to SEXP");
                 ^~~~~~~~~~~~~
make: *** [gpuUtils.o] Error 1
ERROR: compilation failed for package 'gpuUtils'
* removing '/home/usr/R/gpuUtils'
* restoring previous '/home/usr/R/gpuUtils'

Comment: The line `// [[Rcpp::depends(RViennaCL)]]` is for `cppFunction()`, it is not used for package building.  Look more closely at the Rcpp Attributes vignette -- you probably want `LinkingTo: RViennaCL`.
Comment: Removing the `// [[Rcpp::depends(RViennaCL)]]` line doesn't make a difference. I do have `LinkingTo: RViennaCL` in my 'DESCRIPTION' file
Comment: In the second example you are missing the `typedef float ScalarType` from line 77 in the example.
Comment: ... and more importantly in both examples the import of `viennacl/matrix.hpp`.
Comment: Thanks a lot. I've updated my post accordingly.
Comment: A simpler approach for GPU matrix multiplication would be to use the `tensorflow` R library.
Comment: In case you have not seen my updated answer: I fear it will be difficult to use RViennaCL since it already includes Rcpp.h.
Answer: Short answer: yes. RViennaCl only provides the ViennaCl headers but no as() and wrap() functions for communication between R and C++ data structures. And the gpuR package, which uses RViennaCl, uses a different approach by exposing suitable objects to R with appropriate functions acting on these objects. Of course, you can use these objects to do matrix multiplication on the GPU.
So you would have to write these functions yourself if you are interested in communication between R and ViennaCl data structures. This is not a simple task, though, since RViennaCL patches the ViennaCL headers to include Rcpp.h (e.g. https://github.com/cdeterman/RViennaCL/blob/master/inst/include/viennacl/ocl/backend.hpp#L29). This makes it impossible to use the usual extension mechanisms as you are trying above. I think it would be sufficient for RViennaCL to include RcppCommon.h, this way making extensions possible. But I have not tried that. I have filed https://github.com/cdeterman/RViennaCL/issues/4 for this.
Instead of writing as() and wrap() for ViennaCL you could also combine available converters with a package that converts to and from R data structures. So in a package that uses LinkingTo: Rcpp, RViennaCL, RcppEigen this function works for me:
#define VIENNACL_HAVE_EIGEN
#include <RcppEigen.h>
#include <viennacl/ocl/backend.hpp>
#include <viennacl/matrix.hpp>

//' viennacl matrix crossprod
//'
//' @export
// [[Rcpp::export]]
Eigen::MatrixXd vclCrossprod(const Eigen::MatrixXd &in_densematrix){
  int rows = in_densematrix.rows();
  int cols = in_densematrix.cols();

  viennacl::matrix<double>  viennacl_densematrix(rows, cols);
  viennacl::copy(in_densematrix,  viennacl_densematrix);
  viennacl::matrix<double> viennacl_result = viennacl::linalg::prod(
    viennacl::trans(viennacl_densematrix),
    viennacl_densematrix);

  Eigen::MatrixXd eigen_result(cols, cols);
  viennacl::copy(viennacl_result,  eigen_result);
  return eigen_result;
}

However, for the examples I tried, this approach is not really efficient. This might change if you are doing something more complicated than matrix multiplication.
Alternatively you could try RcppArrayFire, which I am working on, if you are mainly interested in GPGPU and not ViennaCl in particular.


C# Validate User against the MS Active Directory Server using System.DirectoryServices.Protocols

Question: I want to authenticate User against the MS Active Directory Server.
As there is two namespaces available for doing that I want to go with System.DirectoryServices.Protocols.
Current I am validating the User using following code
var valid = false;

var credentials = new NetworkCredential("user01", "password01");
var serverId = new LdapDirectoryIdentifier("192.168.1.21:389");

var conn = new LdapConnection(serverId, credentials);

try
{
    conn.Bind();
    valid = true;
}
catch
{
}

Above code is validating User correctly but It is also validating against the Old Password.
How Can I get rid this?
I have checked following Questions
Validate a username and password against Active Directory?
Why does Active Directory validate last password?
Answer: The highest voted answer in the second question you linked to has everything you need to know. The only way an old password is ever allowed is if NTLM is the authentication mechanism used. If you want to prevent that, you have to tell it to only use Kerberos and not NTLM:
var conn = new LdapConnection(serverId, credentials, AuthType.Kerberos);

I saw your comment on that answer, saying that with that, all authentication fails, even with the right password. That just means that Kerberos authentication isn't working. That's a whole other troubleshooting mess. If the server you are running this on is joined to the same (or trusted) domain as the user you are authenticating, then there really is no reason Kerberos shouldn't work. But if the server is outside of the domain, it can be troublesome to set up Kerberos.
Here's some reading on that:

Kerberos Troubleshooting
Troubleshooting Kerberos Authentication problems – Name resolution issues

Or you might decide to just ignore this and let it use NTLM. It only allows an old password for 1 hour after the change anyway.


Matching inner and outer solutions gives me zero

Question: I'm looking to find inner and outer solutions to this ODE and to do some matching $$\epsilon \ddot y + (1+t) \dot y = 0 \;\;\;\;\; y(0) = 0 \;\; \dot y (0) = \frac1\epsilon$$
So I understand I need to convert to a new time variable $\tau = \frac t\epsilon$ ($\dot y$ and $y'$ are $\frac{dy}{dt}$ and $\frac{dy}{d\tau}$ respectively), which I plug in to get
$$y''+(1+\epsilon \tau)y' =0 \;\;\;\;\; y(0) = 0 \;\; y' (0) = 1$$
So if I plug in $y^i=y_0^i + \epsilon y_1^i$ to the $\tau$ equation and solve I get $y^i = 1-e^{-\tau}+\epsilon(1-e^{-\tau}(1-\tau-\frac{\tau^2}2))$.
When I plug in $y^o=y_0^o + \epsilon y_1^o$ to the $t$ equation and solve ignoring the boundary conditions I just get a constant. So $y^o = c+\epsilon d$.
Now to apply Van Dyke matching rules. Express $y^i$ in terms of t to get $y^{io}=1-e^{-\epsilon t}+\epsilon(1-e^{-\epsilon t})$ plus higher order terms. $1-e^{-\epsilon t}$ goes to zero, so the whole thing is zero. $y^{oi}=y^{o}$ since it's constant, so equating $y^{oi}=y^{io}$ I just get zero.
Something seems wrong. Is zero really the best approximation available here? Where did I go wrong?
Comment: Oh I see. My variable name typos led to the wrong way substitution when writing $y^i$ in terms of $t$. I should have $e^{-\frac t\epsilon}$ which goes to zero not one.
Answer: Your inner solution is in $τ$, it should read
$$
y^i(τ) = 1-e^{-τ}+ϵ\Bigl(1-e^{-τ}\bigl(1-τ-\frac{τ^2}2\bigr)\Bigr).
$$
Then the matching rules tell you to equate $y^i(\infty)$ with $y^o(0)$ which gives the constant function $y^o(t)=1+ϵ$.
As $e^{-τ}τ^2\le 4e^{-τ/2}$ the difference to the constant will be lower than second order in $ϵ$ for $τ>-2\lnϵ$ or $t>2ϵ|\lnϵ|$.

(Correction mar30) After trying to validate that formula graphically and recomputing, you must have made some sign errors in the inner solution. The correct solution should read
$$
y^i(τ)=1-e^{-τ}-ϵ\Bigl(1-e^{-τ}\bigl(1+τ+\tfrac12τ^2\bigr)\Bigr)
$$
giving the constant for the outer solution as $y^i(∞)=1-ϵ\equiv y^o$. The numerical solution has an asymptote close to but below  $1-ϵ+3ϵ^2$. (The next order boundary is above $1-ϵ+3ϵ^2-20ϵ^3$.)
For $ϵ=0.1$ the following diagram shows the numerical solution, the above first-order approximation and the bounds for the asymptote.
Comment: What do you mean by "equate $y^i(\infty)$ with $y^o(0)$"? I should be equating the inner in terms of the outer with the outer in terms of the inner, no? So like $1-e^{-\frac t \epsilon}+\epsilon(1-e^{-\frac t\epsilon}(1-\frac t\epsilon-\frac{t^2}{2\epsilon^2}))=c+\epsilon d$. Why are you getting $\infty$ and $0$?
Comment: There is no practical difference between $e^{-1/ϵ}=O(ϵ^k)$ for any $k\in\Bbb N$ and $0$. This is actually already true at $t\sim ϵ^{1-\alpha}$ for any small positive $\alpha$. So for instance on $t\in [\sqrtϵ,1]$, there is no relevant difference between $y^i(t/ϵ)$ and $1+ϵ$. Try it out, draw these functions.
Comment: Added a correction, there were sign errors in the inner solution, the corrected first order asymptote is $1-ϵ$. Visualization confirms this.
Answer: So far so good, I can see how you come up with the time scale change to the new variable $\tau$ which leads to the following differential equation (DE) :
$y'' + (1 + \epsilon \tau)y' = 0\quad y(0)=0\quad y'(0) = 1\quad$
which agrees with your DE.
I have not checked the rest to see if there are any errors though.
Comment: I thought the y terms would get an extra $\frac1\epsilon$ per derivative. So it'd be $\epsilon \frac{y''}{\epsilon^2} + (1 + \epsilon \tau)\frac{y'}{\epsilon} = 0$ and then just multiply through by $\epsilon$ to clear the denominators. Why do you think there is an extra epsilon in the first term but not the second? Can you [edit] to show how you know this is the correct new equation?
Comment: Is it not the case that $\frac{d^2y}{dt^2}=\frac1{\epsilon^2}\frac{d^2y}{d\tau^2}$ and $\frac{dy}{dt}=\frac1{\epsilon}\frac{dy}{d\tau}$, just like in this answer http://math.stackexchange.com/a/1238312/285185 only using $t=\epsilon\tau$ instead of $x=\kappa t$? Over there it says $\frac{d^2y}{dx^2} = \frac{1}{\kappa^2} \frac{d^2y}{dt^2}$ Is that answer wrong?
Comment: Additional epsilon(s) should be found upstairs not downstairs as you divide by epsilon, you should multiply by an epsilon for each derivative wrt new variable tau! :)


Techniques in Bending String, Electric Guitar

Question: When I bend the string, my fingers pressing on the bended string always easily go under the upper string. I think part of the issue is that my strings are quite high, but after fixing the height down a little bit, I still can't make it completely right. And I saw in some tutorial videos one almost presses on two strings and bend them all up, though they actually only ought to bend the lower string. Is that right way to do it?
Comment: How high is your string action? Pushing a finger under a string should be almost impossible on a properly adjusted guitar.
Comment: @Peteris: well, it's about 3mm at 12th fret. It's fine when dealing with 8th fret but slipping  does happen at 12th or higher frets.
Comment: @Tim: Sorry about the confusion, I actually means while bending B string, G string slips over my fingers. And it seems that in the tutorial, one catches B and G strings and bend them up though he wants to play a single note on B string.
Answer: If you bend the thin E string, I can't see any other way than that the B and sometimes G string will also follow in the same movement. They are not making a sound since they are not touching the frets. So the tutorial videos are showing the correct way of doing it.
Comment: I think he's saying that the B or G string is slipping over his fingers while bending the high E. But the "upper" and "lower" terms seem very confusing to me.
Comment: @luserdroog: That's how I understood the situation. I interpret the question to be "should adjacent strings be included when bending a single note (sufficiently far)". The answer is yes.
Comment: Ok. I interpreted it as "how to avoid the slipping": a problem I've had myself (and I don't know the answer). But re-reading, he doesn't appear to actually say that.
Comment: @luserdroog: You mean that you lose the grip of the string with the note being bent?
Comment: No, what happens is the adjacent strings get on top of my fingernail and slide over the top of my fingers. My fingertips and the string I'm trying to bend *dive* under the next strings. It's often a sign that my left-hand fingernails are too long, but not always. I can usually overcome it with more practice, but it still happens to me after 20+ years of playing.
Comment: @luserdroog: Sounds like you might start your bends with your fingers too perpendicular to the fretboard. If you try the "thumb over the neck"-technique (á la Hendrix) you will be forced to have the fingers more parallel to the fretboard, and the flesh of your fingertips should catch the other strings.
Comment: I think that's it exactly. In the piece where it keeps happening, though, I'm trying to bend the B-string 4th-fret up to E while the E-string is ringing. So I can't go too horizontal without damping the E-string. Catch-22.
Comment: @luserdroog: Tricky stuff. An alternative could be to bend the G string at the 8th fret down instead, but there might of course be other things preventing that.
Comment: The only time to worry is when the adjacent string goes between the nail and the finger flesh. The Chinese apparently used this as a torture.
Comment: @MeaningfulUsername,@luser droog: Sorry about the confusion, actually I should have broken the question into two parts. Firstly, I have a problem about how to avoid G string sliding over my fingers while bending B string. Moreover, I wonder wether it is right  to catch both both B and G strings and bend them up( not to catch only B string, bend it up, and simultaneously push up G string using the very top of your fingertips) if you only want to play a single note on B string.
Comment: @user10179: To avoid the string sliding over your finger, try to have your left hand thumb on top of the neck instead of behind. Then your fingers will be more parallel to the fretboard, and you should avoid sliding under. The added benefit is that you easily catch the G string with the flesh of your fingertip, without it touching a fret. In this way the G string will make no sound.
Answer: First of all adjust the action/height on your electric guitar , this link may help you or you can just google it . For your second issue, suppose that you want to bend 8th fret of second string (this note is G ) if you full bend it (not 1/2) you would hear A note (the next note after G) . During bending of any note your left hand finger (if you are right handed) maybe touches the upper string or maybe not ! you should bend the note to reach the frequency of the next note , that's the point. Because you didn't picked upper string (in our example third string=G) it shouldn't make any noise. hope it helps...
Answer: Don't think it is really an issue. Sometimes adjacent strings are pushed too, so they bend as well, silently. Sometimes the adjacent string goes over the bent string as its pushed underneath.Does it really matter? If people like Hendrix had spent (wasted) their time thinking 'is this the correct way to do it' we'd still be in the dark ages.Whatever works best for the individual is best.No-one should have the right to state on the internet: 'This is the proper way to do this'when trying to show the world how THEY do it. But the internet seems to be the new Bible.
Comment: Well, if this technique worked fine, I doubt it would have been material for a question here. We make progress since we can use past experience. To throw that away and tell a beginner that "all techniques are good, bro" is not productive to me. Especially this technique which I can't see how it could work. If someone asks if he should start playing guitar with his hands or feet, the answer should be with the hands if they work, although a guitar has been played to good effect with the feet. "Whatever works for you is awesome" is not the best advice. Potentially better ways should be shown.
Comment: If the nail slips under the string, it might cause unwanted noise when the finger is retracted. That could be a reason for avoiding it. I have never seen anyone use this technique successfully, so in my experience that is not the way to do it.
Comment: You let the B string slide over your finger when you're bending the thin E string? A technique without value is not worth honing, in my mind. I would not recommend anyone to hold their pick with the middle finger either, even if EVH managed to produce great results that way. If someone new to the instrument asks, I think it is valid to recommend the most used approaches. Sliding the string over the finger while bending is not one of those.
Comment: I do it whenever necessary. It's not a problem. Any technique that can be honed is worthwhile working on. Generally only use it when a big bend is needed.If it doesn't work for you, then you won't use it.My actions are very low, and strings very light, so make your own conclusions.
Comment: It is not being advocated any more highly than any other technique. I am trying to make the point that any way of achieving a result is valid.We are all different and will never all reach the same goal in the same way.There is no 'textbook'. My pupils are given many, many strategies, in order that they find their own way. My ways are only best for ME.Although others may find mileage in them...


Javascript : how to get value from a Script Tag

Question: I am trying to get the following value from the script below
Use this field to store the Account to which the Opportunity is related

i can get to this script tag by using :
document.getElementsByTagName('tbody')[6].getElementsByTagName('script')[1];

Can you please let me know.
Many thanks.
Comment: let us see the website that you're trying this code on.
Comment: There is a property called `innerHTML`;
Comment: Without knowing the prototype for the sfdcPage, it's hard to give a better option. You can get the content of the script (if it's a part of the page, as opposed to being a linked-to script) by using it's innerText member. i.e `document.getElementsByTagName('tbody')[6].getElementsByTagName('script')[1].innerText` From there, you could just grab all of the text between the 3rd and 4th `'` characters. indexOf and substr will do that for you.
Answer: I would not recommend putting script tags within your tables, etc. In other words, I wouldn't mix script tags with other content-related HTML like that. If you want to store little bits of info like that in your HTML for the purpose of JS, I'd use data attributes instead.
The simple answer to your question though is to just use the innerHTML or innerText property as follows:
document.getElementsByTagName('tbody')[6].getElementsByTagName('script')[1].innerHTML;

Answer: Use innerHtml as
document.getElementsByTagName('tbody')[6].
    getElementsByTagName('script')[1].
       innerHtml;

OR
Set an id to get script content as below example

fiddle
Answer: There are lots of ways to do this. One solution....
 var scrs = document.getElementsByTagName('script');
 var newscr = "";
 for (var i=0; i<scrs.length; i++) {
    newscr = scrs[i].innerHtml.replace('sfdcPage.setHelp(', 'myfunction(');
    if (newscr != scrs[i].innerHtml) {
       eval(newscr);
    }
 }

(although parsing / rewriting the javascript is an ugly hack - if it's your code then your reading then you should know what you put in there).


Type mismatch with multiple criteria Application.Match VBA

Question: I am trying to run a multiple criteria match function on VBA but keep getting a mismatch error despite setting the outcome variable place as Variant.
Sub AutoFactura()

Dim WS As Worksheet
Dim WF As Worksheet
Dim WP As Worksheet
Dim Rng As Range
Dim Codi As Range
Dim Ara As Range
Dim CopyRange As Range
Dim r1 As Range, r2 As Range
Dim i As Integer
Dim p As Integer
Dim PA As Range
Dim pacient As String, F As String
Dim place As Variant

Set WS = Sheets("Agenda")
'Desfiltrar Agenda
On Error Resume Next
WS.ShowAllData
On Error GoTo 0

'Definir worksheets i trobar últimes files i columnes de cada worksheet
Set WF = Sheets("Factura")
Set WP = Sheets("Pacients")
LRP = WP.Cells(Rows.Count, 1).End(xlUp).Row

'definir ranges per multiple criteria match
Set r1 = WS.Range("C2:C5000")
Set r2 = WS.Range("G2:G5000")
F = "F"

i = 1
p = 2

So now I want to get the row number of pacients that satisfies two conditions. I tried
 For p = 2 To LRP
    WP.Activate
    Range("L" & p).Select
    pacient = Range("B" & p)
    Do While Range("O" & p).Value = True
        With Application
            place = .Match(1, (r1 = pacient) * (r2 <> F), 0)
        End With
        If Not IsError(place) Then
        putuns = place + 1
        WS.Activate
        Range("J" & putuns).Select
        ActiveCell.FormulaR1C1 = "=IF(RC[-3]=""F"",0,1)"
        Range("J" & putuns + 1).Select
        ActiveCell.FormulaR1C1 = "=IF(AND(RC[-7] =R" & putuns & "C3, MONTH(RC[-8])=MONTH(R" & putuns & "C2),RC[-3] <> ""F""),1,"""")"
        Range("J" & putuns + 1).Select
        Selection.Copy
        Range("J" & putuns + 1 & ":J5000").Select
        ActiveSheet.Paste
        End If

But place is always a type mismatch. Any idea on how to solve this?
The message error writes (r1 = pacient) = 'type mismatch'. I am looking for a string in a range, but this should be fine, right?
Thank you
Comment: @RedHare Application.Match doesn't appear with intellisense. There is a difference with Application.WorksheetFunction.Match - [see here](https://stackoverflow.com/questions/27302794/application-match-gives-type-mismatch/27302888#27302888)
Comment: There appears to be some lines missing from the end of the code like `Loop` and  `Next p`
Comment: Yes, but it was not to post all the code. It is not the root of the problem
Comment: There is no Application.Match Function in my Excel
There is a Application.WorksheetFunction.Match and this returns a double not a string
Comment: uups I always forget the deprecated? methods. Strangely it is not even shown in the object explorer even if hidden elements are shown. Yes you can get old as a cow but still learning :-) Tanks for the hint.
Answer: Try using the Evaluate method instead . . .
With Application
    place = .Evaluate("MATCH(1,(" & r1.Address(external:=True) & "=""" & pacient & """)*(" & r2.Address(external:=True) & "<>""" & F & """),0)")
End With

The string passed to the Evaluate method will resolve to something like this (depending on the workbook name, sheet name, and value returned by pacient)...
MATCH(1,([Book1.xlsm]Sheet1!$C$2:$C$5000="X")*([Book1.xlsm]Sheet1!$G$2:$G$5000<>"F"),0)

The Evaluate method then evaluates the string, and returns a value.  Note that there's a 255 character limit.  For additional information, have a look at the following link...
Application.Evaluate Method
Comment: I have added additional information to my post.  Please see my edited post.
Comment: In your original code, you had `(r1 = pacient) * (r2 <> F)` as your lookup array, which is neither a range object nor an array.  It has to be evaluated in order to result in an array, which `application.match` cannot resolve.
Comment: It works! Can you explain? Thank you so much
Comment: I see, but then why a more traditional match like ```place = .Match(pacient, r1, 0)``` works and does not return the same mismatch error?
Comment: That's because it's using the proper syntax.  You have the lookup value `pacient`, the lookup array `r1`, and the match type `0`.  The lookup array must be a range object or an array.
Comment: It's clear now, thank you!


Display data based on year and week number

Question: I am developing an application where the administrator types a Datetime as searching terms to match stamp dates in the database.
I need to change it so the search criteria can be based on year and week number. The scenario is the user enter year and week number in the GetWeekStamp View, which after they post redirects to Stampings view where they display the data based on the entered year and week number.
Model 1:
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Aviato.Models
{
    public partial class Stamping
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        [Required]
        public int UserId { get; set; }

        [Required]
        [DataType(DataType.DateTime)]
        public DateTime Timestamp { get; set; }

        [Required]
        [StringLength(3)]
        public string StampingType { get; set; }

        public virtual User User { get; set; }
    }
}

Model 2:
using System;
using System.Collections.Generic;
using Aviato.Models;

namespace Aviato.ViewModel
{
    public class StampingModel
    {
    public List<Stamping> Stampings { get; set; }
    public DateTime Timestamp { get; set; }
    }
}

View (GetWeekStamp):
@model Aviato.Models.Stamping
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

Ange Datum

(ÅÅÅÅ-MM--DD)

    @Html.EditorFor(model => model.Timestamp, new { htmlAttributes = new { @class = "form-control" } })

    <input type="submit" value="Välj" class="btn btn-default">

        @Html.ActionLink("Tillbaka", "Index")

}

View(Stampings)
@model Aviato.ViewModel.StampingModel
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

Instämplingar

Du har valt: @firstname.lastname@example.comfirstname.lastname@example.com

                @Html.DisplayNameFor(model => model.Stampings[0].Timestamp)

                @Html.DisplayNameFor(model => model.Stampings[0].StampingType)

        @foreach (var item in Model.Stampings)
        {

                    @Html.DisplayFor(model => item.Timestamp)

                    @Html.DisplayFor(model => item.StampingType)

        }

        @Html.ActionLink("Tillbaka", "GetWeekStamp")

}

Controller:
public ActionResult GetWeekStamp()
{
    return View();
}

[HttpPost]
public ActionResult GetWeekStamp(Stamping model)
{
    return RedirectToAction("Stampings", new { model.Timestamp });
}

public ActionResult Stampings(Stamping model)
{
    var startTime = model.Timestamp;
    var endTime = model.Timestamp.AddDays(1);
    var userId = (int)Session["userId"];

    var stampings = _db.Stampings.Where(s => s.Timestamp >= startTime && s.Timestamp <= endTime)
        .Where(s => s.UserId == userId).ToList();

    var stampingModel = new StampingModel();

    stampingModel.Stampings = stampings;
    stampingModel.Timestamp = model.Timestamp;

    return View(stampingModel);
}

I have found this Converter class here in Stack, but I am not sure what to do with it...
Class:
public class DateConverter
{
    public static DateTime FirstDateOfWeek(int year, int weekOfYear)
    {
        var jan1 = new DateTime(year, 1, 1);
        var daysOffset = DayOfWeek.Thursday - jan1.DayOfWeek;
        var firstThursday = jan1.AddDays(daysOffset);
        var cal = CultureInfo.CurrentCulture.Calendar;
        var firstWeek = cal.GetWeekOfYear(firstThursday, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
        var weekNum = weekOfYear;

        if (firstWeek <= 1)
        {
            weekNum -= 1;
        }

        var result = firstThursday.AddDays(weekNum * 7);

        return result.AddDays(-3);
    }
}

Answer: you can get week number using extension method like this:
public static int GetWeekNumber(this DateTime dateTime)
{
    CultureInfo currentCulture = CultureInfo.CurrentCulture;

    return currentCulture.Calendar.GetWeekOfYear(dateTime, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}

to get a year from DateTime just use:
var datetime = DateTime.Now; //i'm using Now, but you can use the one from Timestamp ...
var year = datetime.Year;

Answer: You need to create a model for GetWeekStamp view
using System;
using System.Collections.Generic;
using Aviato.Models;

namespace Aviato.ViewModel
{
    public class GetWeekStampModel
    {
        public int Year { get; set; }
        public int WeekNo { get; set; }
    }
}

then change GetWeekStamp view code to this so user can enter the year and week number
@model Aviato.ViewModel.GetWeekStampModel
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

Year

    @Html.EditorFor(model => model.Year, new { htmlAttributes = new { @class = "form-control" } })

Week No

    @Html.EditorFor(model => model.WeekNo, new { htmlAttributes = new { @class = "form-control" } })

    <input type="submit" value="Välj" class="btn btn-default">

        @Html.ActionLink("Tillbaka", "Index")

}

then in GetWeekStamp controller post action method, pass the entered year and week number to Stampings view
[HttpPost]
public ActionResult GetWeekStamp(GetWeekStampModel model)
{
    return RedirectToAction("Stampings", new { year = model.Year, weekNo = model.WeekNo });
}

The Timestamp property in StampingModel class should be removed and two new properties Year and WeekNo should be added
using System;
using System.Collections.Generic;
using Aviato.Models;

namespace Aviato.ViewModel
{
    public class StampingModel
    {
        public List<Stamping> Stampings { get; set; }
        public int Year { get; set; }
        public int WeekNo { get; set; }
    }
}

in Stampings controller get action method you can calculate the first date of the week based on year and weekNo using your FirstDateOfWeek method above, then use the results as the startTime and set endTime to six days after startTime
public ActionResult Stampings(int year, int weekNo)
{
    var startTime = DateConverter.FirstDateOfWeek(year, weekNo);
    var endTime = startTime.AddDays(6);
    var userId = (int)Session["userId"];

    var stampings = _db.Stampings.Where(s => s.Timestamp >= startTime && s.Timestamp <= endTime)
        .Where(s => s.UserId == userId).ToList();

    var stampingModel = new StampingModel();

    stampingModel.Stampings = stampings;
    stampingModel.Year = year;
    stampingModel.WeekNo = weekNo;

    return View(stampingModel);
}

Finally change this part in Stampings view

Du har valt: @firstname.lastname@example.comemail@example.com

to this

Du har valt: @email@example.com

Comment: So by this, the user can choose a year and week and see all its stampings based on that date?
Comment: Are you saying that if the input from the user is let's say `2014` and `40`, then the view should return all records with `Timestamp` between 30 September 2014 and 5 October 2014?
Comment: That is correct, all the data which is stored for that specific date. All the columns in the database shall be displayed!

And I can actually say that it did not work...
Comment: Please check the updated answer, I think it's what you're looking for.
Comment: And how shall I display it in the view??

I mean, I have to change it from 1 textbox to 2 to start with...
Comment: Sorry I think I misunderstood, in which view do you want to display records? and where does the user input the year and the week number?
Comment: The user input year and week in the GetWeekStamp View, which after they post redirects to Stampings where they display that input data...
Comment: I have updated the answer, please check and let me know if you have any questions.
Comment: So Iv'e implemented these changes. But the Method: "FirstDateOfWeek" has 1 parameter(s) bus is invoked with 2 argument(s)
Comment: You don't need to change `FirstDateOfWeek` method, use the one you already have in the question.


How to create Table Dynamically with existing table fields in mysql

Question: Currently i'm using the table sample1. how can i create table sample2 with sample1's field dynamically?
Comment: Please explain your question neatly. Read the rules of SO first.
Comment: How can we possibly give an answer with the information you've provided?
Comment: Are you sure its the right way to do, what you are trying??
Answer: You can do this way.
CREATE TABLE `sample2` SELECT * FROM `sample1`;

Another alternative is
If table structure is the same then you can use:
INSERT INTO `sample2` SELECT * FROM `sample1`;

Answer: If you are using Phpmyadmin follow these steps

Select table
go to (tab) Operations > Copy table to (database.table):
Comment: No don't want to do it manually. I want to do it in dynamically.. Thanks


SELECT on same table for Multiple key value pairs

Question: I have a table like
id keyword_id value   category_id asset_id
 1          2 abc.jpg        4424      479
 2          3 Jpeg           4424      479
 3          4 400*600        4424      479
 4          2 def.jpg        4424      603
 5          3 Jpeg           4424      603
 6          4 500*700        4424      603

I want to fetch values depending on multiple pairs like (keyword id = 3 and value like '%Jpeg%') And (keyword id = 2 and value like '%abc%').
This should return only one value with asset_id 479 because it meets both the criteria.
I am running a query like
SELECT DISTINCT asset_id FROM asset_keyword_table where category_id = 4424
AND (( keyword_id = 2 AND value LIKE '%abc%') AND ( keyword_id = 3 AND
value LIKE '%Jpeg%'));

But EXPLAIN this query returns Impossible WHERE clause.
What is the way to get this working.
This query is generated by BE code so blocks likes this can be many -
( keyword_id = 2 AND value LIKE '%abc%')

depending on user input. And the blocks separated by AND or OR is also determined by User. Using aliases is not possible because there is no limit on the number of blocks.
Can anyone help?
Comment: You have to use `OR` instead of `AND`: `(( keyword_id = 2 AND value LIKE '%abc%') OR ( keyword_id = 3 AND value LIKE '%Jpeg%'));`
Comment: OR or AND is determined from input. Or will return 2 results with asset_id = 479 and asset_id = 603, I want only asset_id that match both the condition
Comment: You can try nested queries: `SELECT DISTINCT Asset_ID FROM asset_keyword_table WHERE ( category_id = 4424 AND keyword_id = 2 AND value LIKE '%abc%' ) AND ( Asset_ID in ( SELECT DISTINCT Asset_ID FROM asset_keyword_table WHERE category_id = 4424 AND keyword_id = 3 AND value LIKE '%Jpeg%' ))   ... OR Asset_ID in ...`
Comment: This seems to be working..
Comment: Okay great, I've added my comment as an answer.
Answer: You need to filter the total number of rows that match with your condition.
SELECT  Asset_ID
FROM    asset_keyword_table
WHERE   category_id = 4424
        AND
        (( keyword_id = 2 AND value LIKE '%abc%')
        OR (keyword_id = 3 AND value LIKE '%Jpeg%'))
GROUP   BY Asset_ID
HAVING  COUNT(*) = 2 -- number of rows that matched the condition

Here's a Demo.
Comment: What if i receive a request for the following from the input

    `SELECT DISTINCT asset_id FROM asset_keyword_table where category_id = 4424
AND (( keyword_id = 2 AND value LIKE '%abc%') AND ( keyword_id = 3 AND
value LIKE '%Jpeg%') OR (keyword_id = 4 AND
value LIKE '%200%'));`
Since code is BE generated
Comment: it won't work. all rows will be return as long as it will much to **any** of your condition above and not all.
Answer: Nested queries should give you the desired result:
SELECT DISTINCT asset_id FROM asset_keyword_table WHERE
( category_id = 4424 AND keyword_id = 2 AND value LIKE '%abc%' )
AND asset_id IN
( SELECT DISTINCT asset_id FROM asset_keyword_table WHERE
   category_id = 4424 AND keyword_id = 3 AND value LIKE '%Jpeg%' )
/*  OR asset_id IN
( SELECT DISTINCT asset_id FROM asset_keyword_table WHERE
   category_id = 4424 AND keyword_id = 4 AND value LIKE '%500%' ) */

SQL Fiddle


Analytically solving sampling with or without replacement after Poisson/Negative binomial

Question: Short version
I am trying to analytically solve/approximate the composite likelihood that results from independent Poisson draws and further sampling with or without replacement (I don't really care which one). I want to use the likelihood with MCMC (Stan), so I need the solution only up to a constant term. Ultimately, I want to model a process where the initial draws are from neg. binomial distribution, but I think I will be able to get there with a solution for the Poisson case.
It is well possible that the solution is not feasible (I don't understand the math enough to be able to tell whether this is a simple or very difficult problem). I am thus also interested in approximations, negative results or intuition why the problem is probably intractable (e.g. comparing to a known hard problem). Links to useful papers/theorems/tricks that will help me move forward are good answers even if their connection to the problem at hand is not fully worked out.
Formal statement
More formally, first $Y = (y_1, ..., y_N), y_n \sim Pois(\lambda_n)$ is drawn independently and then I sample $k$ items at random from all of $Y$ to get $Z = (z_1,...,z_N)$. I.e. I draw $k$ coloured balls from an urn where the amount of balls of color $n$ is drawn from $Pois(\lambda_n)$. Here, $k$ is assumed known and fixed and we condition on $\sum_n y_n \geq k$. Technically the sampling is done without replacement, but assuming sampling with replacement should not be a big deal.
I have tried two approaches to solve for sampling without replacement (as this seemed to be the easier case due to some terms cancelling out), but got stuck with both. The likelihood when sampling without replacement is:
$$
P(Z = (z_1, ..., z_N) | \Lambda = (\lambda_1, ..., \lambda_N)) = \frac{
\sum_{Y;\forall n: y_n \geq z_n} \left( \frac{\prod_{n=1}^N{y_n \choose z_n}}{ {\sum_{n=1}^N y_n} \choose k}
\prod_{n=1}^N Poisson(y_n |\lambda_n)
\right)
}{
P(\sum_n y_n \geq k|\Lambda)
}
$$
EDIT: The "attempted solutions section was removed as the solution in the answer does not build on them (and is way better)
Answer:
The case without replacement
If you have $n$ independent Poisson distributed variables
$$Y_i \sim \text{Pois$(\lambda_i)$}$$
and condition on
$$\sum_{j=i}^n Y_j = K$$
then
$$\lbrace Y_i \rbrace \sim \text{Multinom} \left(K,\left(\frac{\lambda_i}{\sum_{j=1}^n \lambda_j} \right)\right)$$

So you could fill your urn with the $n$ times $Y_i$ colored balls like first drawing the value for the total $K$ (which is Poisson distributed cutoff by the condition $K \geq k$) and then fill the urn with $K$ balls according to the multinomial distribution.
This filling of the urn with $K$ balls, according to a multinomial distribution, is equivalent to drawing for each ball independently the color from the categorical distribution. Then you can consider the first $k$ balls that have been added to the urn as defining the random sample $\lbrace Z_i \rbrace$ (when this sample is drawn without replacement) and the distribution for this is just another multinomial distributed vector:
$$\lbrace Z_i \rbrace \sim \text{Multinom} \left(k,\left(\frac{\lambda_i}{\sum_{j=1}^n \lambda_j} \right)\right)$$
simulation
<code>##### simulating sample process for 3 variables #######

# settings
set.seed(1)
k = 10
lambda = c(4, 4, 4)
trials = 1000000

# observed counts table
Ocounts = array(0, dim = c(k+1, k+1, k+1))

for (i in c(1:trials)) {
  # draw poisson with limit sum(n) >= k
  repeat {
    Y = rpois(3,lambda)
    if (sum(Y) >= k) {break}
  }
  # setup urn
  urn <- c(rep(1, Y[1]), rep(2, Y[2]), rep(3, Y[3]))
  # draw from urn
  s <- sample(urn, k, replace=0)
  Z = c(sum(s==1),sum(s==2),sum(s==3))
  Ocounts[Z[1]+1, Z[2]+1, Z[3]+1] = Ocounts[Z[1]+1, Z[2]+1, Z[3]+1] + 1
}

# comparison
observed = rep(0, 0.5*k*(k+1))
expected = rep(0, 0.5*k*(k+1))
t = 1

for (z1 in c(0:k)) {
  for (z2 in c(0:(k-z1))) {
    z3 = k-z1-z2
    observed[t] = Ocounts[z1+1, z2+1, z3+1]
    expected[t] = trials*dmultinom(c(z1, z2, z3), prob=lambda)
    t = t+1
  }
}

plot(observed,expected)
x2 <- sum((observed-expected)^2/expected)
pvalue <- 1-pchisq(x2, 66-1)
</code>
results
<code>> # results from chi-sq test
> x2
[1] 75.49286
> pvalue
[1] 0.1754805
</code>
Negative binomial
The arguments would work the same for the case of a negative binomial distribution which results (under certain conditions) into a Dirichlet-multinomial distribution.
Below is an example simulation
<code>##### simulating sample process for 3 variables #######

# dirichlet multinomial for vectors of size 3
ddirmultinom =  function(x1,x2,x3,p1,p2,p3) {
  (factorial(x1+x2+x3)*gamma(p1+p2+p3)/gamma(x1+x2+x3+p1+p2+p3))/
  (factorial(x1)*gamma(p1)/gamma(x1+p1))/
  (factorial(x2)*gamma(p2)/gamma(x2+p2))/
  (factorial(x3)*gamma(p3)/gamma(x3+p3))
}

# settings
set.seed(1)
k = 10
theta = 1
lambda = c(4,4,4)
trials = 1000000

# calculating negative binomials pars
means = lambda
vars = lambda*(1+theta)

ps = (vars-means)/(vars)
rs = means^2/(vars-means)

# observed counts table
Ocounts = array(0, dim = c(k+1,k+1,k+1))

for (i in c(1:trials)) {
  # draw poisson with limit sum(n) >= k
  repeat {
    Y = rnbinom(3,rs,ps)
    if (sum(Y) >= k) {break}
  }
  # setup urn
  urn <- c(rep(1,Y[1]),rep(2,Y[2]),rep(3,Y[3]))
  # draw from urn
  s <- sample(urn,k,replace=0)
  Z = c(sum(s==1),sum(s==2),sum(s==3))
  Ocounts[Z[1]+1,Z[2]+1,Z[3]+1] = Ocounts[Z[1]+1,Z[2]+1,Z[3]+1] + 1
}

# comparison
observed = rep(0,0.5*k*(k+1))
expected = rep(0,0.5*k*(k+1))
t = 1

for (z1 in c(0:k)) {
  for (z2 in c(0:(k-z1))) {
    z3 = k-z1-z2
    observed[t]=Ocounts[z1+1,z2+1,z3+1]
    expected[t]=trials*ddirmultinom(z1,z2,z3,lambda[1]/theta,lambda[2]/theta,lambda[3]/theta)
    t = t+1
  }
}

plot(observed,expected)
x2 <- sum((observed-expected)^2/expected)
pvalue <- 1-pchisq(x2,66-1)

# results from chi-sq test
x2
pvalue
</code>
Comment: Thanks for the answer. I've tried this approach already and I have two issues a) don't see why conditioning on the sum is the same as resampling (mathematically) and b) my (admittedly limited) simulated data from Poisson + resampling could not be fit well with multinomial distribution. Could you elaborate more on why conditioning and resampling would be the same?
Comment: Turns out I also messed up the second simulation. It seems to work for the DM case as well.
Comment: Oh, on further reading, I think I see your point. Maybe I just made a stupid mistake with the simulations, will go check.
Comment: I use two steps. **1)** filling the urn with $Y_i$ coloured balls by drawing $Y_i$ from independent Poisson distributions, is equivalent to filling the urn by drawing a total $\sum Y_i = K$ from the Poisson distribution and then the $Y_i$ from a multinomial distribution. **2)** drawing a subset of balls from an urn filled with coloured balls whose numbers are defined by a multinomial distribution, is equivalent to anoter multiniomial distribution (intuition, you can see the urn as being filled with for the color of each ball a draw from the categorical distribution).
Comment: Yes, there was a bug in my simulation code :-) Thanks for the help! You are correct and I also understand the step in your reasoning that I didn't see previously. I am trying to understand why the same relation does not hold for neg. binomial and Dirichlet multinomial distribution. (assuming the NB variables have constant Fano factors, conditioning on their sum I get DM) - because "sampling without replacement from multinomial" is multinomial, but "sampling without replacement from DM" is not DM (is that reasoning correct in your view?)
Comment: I would guess that the *separate* steps would work but not together. So 1) the conditioned neg.binomial results in DM (according to your https://stats.stackexchange.com/questions/45318/conditional-on-the-total-what-is-the-distribution-of-negative-binomials/354433#354433). and 2) subsampling from the DM based urn is also a DM. ....... But, would you get the same parameters in the DM for different values of K?
Comment: You actually do get the same parameters of the DM for different $K$. But the problem might be that in the multinomial pmf, $K$ only affects the normalization constant, while in the DM $K$ interacts with the other parameters.
Comment: I will do another simulation to test my intuition. I don't see why the same argments as in the answer would not work the same for negative-binomial and Dirichlet-multinomial. Did your experimental simulations use 'without replacement'?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/81114/discussion-between-martin-modrak-and-martijn-weterings).


Windows remote access server (PPTP) advertised routes

Question: How does a routing and remote access server pick up routes to advertise to clients, and where can a list of routes being provided be reviewed?
One of our users is reporting that the server is advertising a route which is valid, but has never been entered in the static routes section of the RRAS server, or told/provided to them at any time.  In fact the static route section is currently empty.
RIP is not configured at this time, so its not coming from there that I can tell.
we are using PPTP, not l2tp.
Answer: There is no way to push routes from a PPTP server. The connection is established and configured using IPCP, the PPP Internet Protocol Control Protocol defined in RFC 1332. In fact, its very name ("Point to Point") implies that you won't find any support for routing.
Which routes are available depend entirely on the client-side configuration. There are three different ways to configure the client.

Use default gateway on remote network. This allows you to access all remote networks, but prevents you from accessing local networks.
Class-based route addition. If you aren't using method #1, then most clients will set up a route based on the IP address of the PPTP adapter.
For Windows clients, you can use CMAK to configure a connection profile and deploy that to your VPN clients. Essentially you are creating a script to add custom routes when the PPTP connection is open.
Comment: It appears that at least the windows VPN client will issue a DHCPINFORM request after the VPN connection has been established. DHCP Option 121 (https://tools.ietf.org/html/rfc3442) can be used to inform the client of additional routes.
Comment: I can confirm that a SHCP Option 121 can be used for pushing static routes to clients.
Answer: Part of the pptp exchange can include a route.  You can also configure windows to download a route-file which can have as many custom routes as you want.  Honestly, I would not suggest using PPTP in a production environment, as it has some known security flaws and is not as reliable as L2TP over IPSEC.
Comment: So where are the routes in the exchange identified?  Ive never specified any.
Comment: It should really only have a route to all networks attached to the VPN server... (local networks) or one default route that covers everything.


Find order-preserving bijection between two sets

Question: $$A:= (-1,0) \cup\left\{ \frac {1}{n} \,\Big\vert\, n \in \mathbb N \right\} \cup\left\{ 2- {\frac {1}{n} \,\Big\vert\, n \in \mathbb N}\right\} \cup (2,3)$$
$$B:=  (-1,0) \cup \left\{ 2- \frac {1}{n} \,\Big\vert\, n \in \mathbb N\right\} \cup (2,3)$$
with $\leq$ order of $\mathbb R$
Is $A$ isomorphic to $B$ ?
Cant find an isomorphism.
Any help please ?
Comment: Hi, welcome to MSE! Please include any of your attempts at solving the problem, or more detail about what exactly is giving you trouble.
Comment: Thanks! I got the solution for this !
Answer: Hint
Those sets are not order isomorphic.
By contradiction, suppose that $\phi : A \to B$ is an order isomorphism, and consider $\phi(1)$.
Derive a contradiction for each possible case $\phi(1) \in (-1,0)$, $\phi(1) \in \{ 2- \frac {1}{n} \mid n \in \mathbb N\}$ and $\phi(1) \in (2,3)$ by considering $\phi\left(\frac{1}{2}\right)$.
Comment: If i take $\phi\left(\frac{1}{2}\right)=x \in (-1,0)$ and $\phi(1) =y \in (-1,0)$ so exist $ x<z<y $ that $\phi(\frac{1}{2}) \leq \phi(z)$ . Contradiction ? (My example for $\phi(1) \in (-1,0)$)
Comment: Correct. In that case $z \in (x,y) \subseteq (-1,0) \subseteq B$ won't have a preimage in $A$ under $\phi$.


Football Field Size

Question: Just the other day I was talking to a colleague and he was telling me soccer fields can differ in size, up to 20 meters in width.
Can somebody give me the exact word on this?
Answer: According to IFAB Laws of the Game, the width of the field can be between 45 to 90 meters and must be smaller then its length.
The full rule:
Dimensions

Law 1 – the field of play
The length of the touch line must be greater than the length of the goal line.
Length (touch line):

minimum 90 m (100 yds)
maximum 120 m (130 yds)

Width (goal line):

minimum 45 m (50 yds)
maximum 90 m (100 yds)

All lines must be of the same width, which must be not more than 12 cm
  (5 ins).

International matches
For international matches, the following dimensions are needed:

Length

minimum 100 m (110 yds)
maximum 110 m (120 yds)

Width (goal line):

minimum 64 m (70 yds)
maximum 75 m (80 yds)

Football Field Size


Istio on GKE - Admission webhook not working to inject sidecar-porxy

Question: I have been trying to set up Istio on my existing GKE cluster.
I hev followed the steps mentioned on the Istio website for the installation - prerequisite.
https://istio.io/latest/docs/setup/platform-setup/gke/
I have a private cluster so I added the firewall rule mention in the prerequisite.
gke-aiq-kubernetes-0a227ee8-all               default  INGRESS    1000      tcp,udp,icmp,esp,ah,sctp            False
gke-aiq-kubernetes-0a227ee8-master            default  INGRESS    1000      tcp:10250,tcp:443,tcp:15017         False
gke-aiq-kubernetes-0a227ee8-vms               default  INGRESS    1000      tcp:1-65535,udp:1-65535,icmp        False

and then install the istio with the demo profile.
istioctl install --set profile=demo

and then verify the intallation
istioctl verify-install

Which says everything is succeeded.
I labeled by namecpace "instio-inject=enabled" so that I will automatically get the sidecar porxy injected.
But when I trying to deploy something in the namespace I am getting following error:
Error from server (InternalError): error when creating "pod-pending.yaml": Internal error occurred: failed calling webhook "sidecar-injector.istio.io": Post https://istiod.istio-system.svc:443/inject?timeout=30s: context deadline exceeded

What I understand from this is that there is some connectivity issue, but I am not sure how to debug this.
I tried the debugging page from istio:
https://github.com/istio/istio/wiki/Troubleshooting-Istio#diagnostics
and after running the command:
kubectl get --raw /api/v1/namespaces/istio-system/services/https:istiod:https-webhook/proxy/inject -v4

I am conformend that this is connectivity issue:
t -v5
I1113 23:20:11.241079   40356 helpers.go:199] server response object: [{
  "metadata": {},
  "status": "Failure",
  "message": "the server is currently unable to handle the request",
  "reason": "ServiceUnavailable",
  "details": {
    "causes": [
      {
        "reason": "UnexpectedServerResponse",
        "message": "Error trying to reach service: 'dial tcp 10.48.3.25:15017: i/o timeout'"
      }
    ]
  },
  "code": 503
}]
F1113 23:20:11.241367   40356 helpers.go:114] Error from server (ServiceUnavailable): the server is currently unable to handle the request

Need help, I am new to GKE.
Answer: I figured out the issue.
I have 7 different GCP projects configured with my gcloud profile and I was in a different project while running the gcloud command. (all gke clusters have the same name)
Steps from the command line:
I logged in to the GCP UI from the browser search the firewall under VPC and opened the ports manually there and it worked.
gcloud compute firewall-rules list --filter="name~gke-<clustername>-[0-9a-z]*-master"

Then get the firewall rule name.
gcloud compute firewall-rules update <firewall rule name> --allow tcp:10250,tcp:443,tcp:15017

The idea here is to add the tcp:15017 which is required by the admission hook.


Using seq() and ifelse in a for loop

Question: I'm trying to make the following "sequence":
0.0025,0.005, 0.010, 0.015, 0.020, 0.025, 0.030, 0.035, 0.040, 0.045, 0.050, 0.055, 0.060

As you can see, after the first value 0.0025, the values increase by 0.0025 and then continuously by 0.005. So after the second value of 0.005, it is essentially a sequence increasing by 0.005. Which I thought I could use seq() in.
What I thought would work would be:
    matrix1 <- matrix("", nrow = 1, ncol = 13)
    m <-  for (i in 1:length(matrix1){

    matrix1[,i] <- ifelse(i == 1, 0.0025, ifelse(i == 2, 0.005, seq(0.01,    0.05, by = 0.005)))
}

This however gives me the following result:
     [,1]     [,2]    [,3]   [,4]   [,5]   [,6]   [,7]   [,8]   [,9]   [,10]  [,11]  [,12]  [,13]
[1,] "0.0025" "0.005" "0.01" "0.01" "0.01" "0.01" "0.01" "0.01" "0.01" "0.01" "0.01" "0.01" "0.01"

Which is not what I want.
Any suggestions?
Comment: `c(0.0025, seq(0.005, 0.06, by=0.005))`?
Answer: If the question is really about using a for loop, then I'd rather use if and else statements:
n <- 13
x1 <- vector("numeric", 13)
for (i in 1:n) {
  if (i==1) {
    x1[i] <- 0.0025
  } else {
    x1[i] <- 0.005 + (i-2)*0.005
  }
}

... because ifelse is meant to be applied on vectors :
j <- 1:n
x2 <- ifelse(j == 1, 0.0025, 0.005 + (j-2)*0.005)

But there are so many other ways to get the required result! My favorite is
x3 <- c(0.0025, seq(0.005, 0.06, by=0.005))

because when you read it aloud, you really create a vector for which", after the first value 0.0025, the values increase by 0.0025 and then continuously by 0.005."
Comment: Or `c(0.0025, 0.005*(1:12))` instead of the `ifelse`
Comment: Or `c(0.0025, seq(0.005, by = 0.005, length = 12)` in case you have the length of the vector rather than it's endpoint.

Using seq() and ifelse in a for loop


How many reverse proxies (nginx, haproxy) is too many?

Question: I'm setting up a HA (high availability) cluster using nginx, haproxy & apache.
I've been reading great things about nginx and haproxy. People tend to choose one or the other but I like both. Haproxy is more flexible for load balancing than nginx's simple round robin (even with the upstream-fair patch). But I'd like to keep nginx for redirecting non-https to https among other things right at the point of entry to the cluster.
On the other hand, nginx is a lot faster for serving static contents and would reduce the load on the powerful apache which loves to eat a lot of RAM!
Here is my planned setup:
Load balancer: nginx listens on port 80/443 and proxy_forwards to haproxy on 8080 on the same server to load balance between the multiple nodes.
Nodes: nginx on the node listens to requests coming from haproxy on 8080, if the content is static, serve it. But if it's a backend script (in my case PHP), proxy forward to apache2 on the same node server listenning on a different port number.
Technically this setup works but my concerns are whether having the requests going through several proxies is going to slow down requests? Most of the requests will be PHP requests as the backends are services (which means groing from nginx -> haproxy -> nginx -> apache).
Thoughts?
Cheers
Answer: From a purely performance perspective, let benchmarking make these decisions for you rather than assuming -- using a tool like httperf is invaluable when making architecture changes.
From an architectural philosophy perspective, I'm a little curious why you have both nginx and apache on the application servers. Nginx blazes at static content and efficiently handles most backend frameworks/technologies (Rails, PHP via FastFCGI, etc), so I would drop the final Apache layer. Once again, this comes from a limited understanding of the technologies that you're using, so you may have a need for it that I'm not anticipating (but if that's the case, you could always drop nginx on the app servers and just use apache -- it's not THAT bad at static content when configured properly).
Currently, I use nginx -> haproxy on load balancing servers and nginx on the app servers with much success. As Willy Tarreau stated, nginx and haproxy are a very fast combination, so I wouldn't worry about the speed of having both on the front-end, but keep in mind that adding additional layers increases complexity as well as the number of points of failure.
Answer: Your setup is more and more common. You don't have to worry. Both nginx and haproxy are extremely fast to process and forward HTTP requests. Both combine very well together and do their job very well. No need to choose. Install them both and be happy. That way you will deliver static files very quickly and also ensure smooth scaling of your dynamic servers.
Don't worry for the number of proxies. The problem is often "can I use a proxy". Sometimes it's not practical. If you can have one, you can have two or three. Many complex architectures involve up to 5-6 levels of proxies and still scale very well. You should just be careful about one thing : do not install more of such proxies on a single machine than this machine has of CPU cores, or the proxies will have to share their CPU time under high loads, which will increase response times. But for this to happen with nginx and haproxy on a machine, this would mean loads of tens of thousands of requests per second, which is not everyone's problem of the day.
Also, avoid mixing single-threaded proxies with massively multi-threaded/multi-process software such as apache, java, etc on the same system.
Once you take these rules into account, simply draw the architecture that suits your needs, put names on the boxes, combine them in a sane way and install them.
Answer: Remember complexity can be just as much (if not more) of an impediment to scaling as code/design.  As you scatter your implimentation details across more and more services and config-files you create something that is more difficult to scale out, has more of a learning curve to anyone new to the team, requires more software/packages to manage, complicates troubleshooting with more potential failure points, etc.   Setting up a 4-proxy-layer stack for a site that would have been fine with just-apache or just-nginx is basically the sysadmin version of "premature optimization".
Answer: Why not use Varnish?  That way you combine caching, proxying and loadbalancing into one application and it's a hell of a lot neater from an architecture point of view.
The scale-out scaling is pretty phenomenal.  There's also the advantage that the load balancer can make more intelligent decisions based on the actual health of the nodes.
The configuration file will allow you to examine the headers and make decisions about where to serve static and dynamic content from.
If you're really predicting to be serving a LOT of static content, perhaps shunting most of that onto a CDN would be a cost effective solution?
Comment: Varnish doesn't do HTTPS, so you would still need something in front of it to terminate that. Nginx would be a good choice. stunnel or stud could also do it; i don't know how their performance compares to Nginx's, and they don't send an X-Forwarded-For header.
Comment: I'd be very interested to read a comparison of HAProxy and Varnish for load-balancing. I'd like to be able to make an informed choice between {Nginx,stud}/Varnish/HAProxy and {Nginx,stud}/Varnish.
Comment: @Tom Anderson, If you can wait, I could probably write one. Might take me a couple of weeks.
Comment: A kind offer! I should add that i am not facing this choice right now, but it's something i am conscious i don't have the information to make sensible choices about in the future. This seems to be a really tough area to benchmark.
Comment: No comparison yet? It's been some weeks :)
Answer: Update for 2020, this is the standard recommended setup that you should encounter for PHP applications.
<code>LOAD BALANCER              SERVER A
   haproxy   -+--------->   nginx   -+---> /app/ ------> PHP application
              |                      |
              |                      +---> /static/ ---> local files
              |
              |
              |            SERVER B
              +--------->   nginx   -+---> /app/ ------> PHP application
                                     |
                                     +---> /static/ ---> local files
</code>
This serves the application and the static files from multiple hosts, each host is identical. nginx can run PHP applications (over fastcgi) and serve local files.
If it's an old PHP application it might be designed with Apache in mind in place of nginx. It's fine. Apache too can run PHP applications (cgi, fastcgi or mod_php) and serve local files.
It's possible to migrate from Apache to nginx but that's not necessarily worthwhile for legacy systems. Apache is a pain to build and configure but if it's already running it's not an issue. Apache is not performant but PHP is much slower and the bottleneck will always be the app.
In front, this needs a layer of load balancers to distribute traffic between the servers. Usually one of HAProxy, AWS ALB, F5 or CloudFlare.
It's possible to add an infinite amount of layers in-between but it gives no benefits. The original question is outdated in its concerns. All these software have been supporting SSL for almost a decade, the setup can run SSL end-to-end. Local files are served efficiently thanks to sendfile(), added to the Linux kernel a while ago.
Answer: "Technically this setup works but my concerns are whether having the requests going through several proxies is going to slow down requests?"
Yes, but not by much especially if you pay attention to the networking side of your scaled-out system. That has to be robust.
Generally, to be able to gain scale-out and spread work over many machines, you must usually sacrifice some performance over some or all of the individual machines. It's inevitable and usually something not worth worrying about (beyond the testing you should always do to ensure performance of the whole is sucking wind). Optimizing the parts is not necessarily the best way to optimize the whole.


Organising 3 dimensional data for Matplotlib 2D plot

Question: I am analysing network graph connectedness, measuring in_degrees and out_degrees of all nodes.
I am seeking to show the results as shown in this video at 02:00
As you can see the lecturer has plotted in_degrees on the x-axis and out_degrees on the y-axis. The colour scale represents the number of nodes which have those x,y characteristics. His example is simple with a minimum of 0 and a maximum of 3 on each axis.
I have produced data in the format of
<code>Counter({(0, 0): 7, (1, 3): 2, (19, 0): 2, (0, 2): 2,
etc.
(27, 42): 1, (25, 43): 1, (26, 36): 1, (23, 46): 1})
</code>
The data could run to 5,000 or so nodes. The counter object above is unsorted.
My example above takes the form
<code>{(in_degree, out_degree): count, (in_degree, out_degree): count, etc. }
</code>
So, you can see there are 7 nodes with 0 in_degrees and 0 out_degrees, 2 nodes with 1 in_degree and 3 out degrees ..... and finally 1 node with 23 in_degrees and 46 out_degrees.
I am trying to work out how to get this into a state to plot it, using something like this example.
How should I arrange my data for plotting - and how do I work out bin sizes dynamically when I don't know the upper limits for x and y axes?
Any pointers, not necessarily solutions, would be welcomed please!
Answer: Here is an example to obtain a heat-map graph using the count data:
<code>%matplotlib inline
import matplotlib.pylab as plt

import numpy as np

data = {(0, 0): 7, (1, 3): 2, (19, 0): 2, (0, 2): 2,
        (3, 3): 2, (2, 3): 6, (8, 6): 2, (9, 4): 2,
        (10, 12): 1, (15, 13): 1, (16, 16): 1, (13, 15): 1}

# Create an empty array:
max_x = max( xy[0] for xy in data.keys() )
max_y = max( xy[1] for xy in data.keys() )

count_grid = np.zeros((max_x+1, max_y+1))

# Populate the array:
for xy, count in data.items():
    x, y = xy
    count_grid[x, y] = count

# Plot
plt.pcolor(count_grid); plt.colorbar()
plt.xlabel('x'); plt.ylabel('y'); plt.title('count');
</code>
Which gives this graph:
Comment: Thank you @xdze2 that's great - and works well.

I discovered that I had over-processed my data and keeping it as a list of tuples (rather than as a counter which counted value pairs) would have been easier to solve. But your answer fits the bill perfectly to the question which I posed! Thank you.


Site build fails due to Format() not being available on Type toml.LocalDate

Question: When I am building a site on Hugo using a pipeline, the build constantly fails with the following error:
Error: Error building site:
failed to render pages: render of "home" failed: execute of template failed: template: index.html:22:11: executing "main" at <partial "session-dates.html" .>:
error calling partial: "/github/workspace/layouts/partials/session-dates.html:4:20":
execute of template failed: template: partials/session-dates.html:4:20:
executing "partials/session-dates.html" at <.Site.Params.current_startDate.Format>: can't evaluate field Format in type toml.LocalDate

The error is happening on the current_startDate, and current_endDate values, where it's saying there is no Format function available for the type. The config is:
baseURL = "..."
languageCode = "en-us"
title = "..."
summaryLength = 20
relativeURLs = true

[params]
    current_startDate = 2021-10-10
    current_endDate   = 2021-12-04

Then the template code is:

            {{ .Site.Params.current_startDate.Format "January 2, 2006" }} —
            {{ .Site.Params.current_endDate.Format "January 2, 2006" }}

            {{ .Site.Params.current_startDate.Format "01/02/06" }} —
            {{ .Site.Params.current_endDate.Format "01/02/06" }}

I have tried looking at the docs and other examples and the configuration seems to be correct, so I assume there is something obvious I am missing.
Comment: @gopher so what format needs to be used in order to do this then? Does it need to be the full date type like `2021-10-10T14:15:59-06:00`?
Answer: If anyone else is running into this issue, for some reason specifically on the pipeline https://github.com/chabad360/hugo-gh-pages this doesn't work. When testing locally the original format I had works for both building and previewing at the command line.
The fix is to give the full datetime format, so for my example above that is:
baseURL = "..."
languageCode = "en-us"
title = "..."
summaryLength = 20
relativeURLs = true

[params]
    current_startDate = 2021-10-10T14:15:59-06:00
    current_endDate   = 2021-12-04T14:15:59-06:00

This configuration builds as expected locally, and in the pipeline.


Remove Ordered/Unordered Bullets while copy pasting in text box

Question: While copy pasting a text from MS Word to html textbox, the bullet appends in the text box. How to remove it using Jquery/Javascript ?
Comment: What did you try so far?
Comment: i copied a text in a list from a word doc, and paste it in the html textbox. I used the below code to allow only alphanumeric while pasting a value in text box. but the above bullets is represented as "o" character. so it couldnt be restricted.

$("#CustomerId").on("paste", function (e) {
    // access the clipboard using the api
    var pastedData = e.originalEvent.clipboardData.getData('text');
    $("#CustomerId").val(pastedData.replace(/[^A-Z0-9]/ig, ""));
    e.preventDefault();
});
Comment: I updated my answer to also check for 'o' followed by spaces
Answer: There are many ways to remove the unwanted characters from a textbox. One way is to use regualr expression to filter out any non-alphanumberic characters from that value field and put the filtered value back into the textbox, replacing/overwriting the old value.

$('#my_textbox').keyup(function() {
  //this code will be triggered after each keystroke inside the textbox
  // alternatively, you may want to only trigger it after blur/change/etc

  var cleaned = $(this).val().replace(/^\s*[o\W]\s+/g, '');
  //removes any letter 'o' followed by spaces
  //removes any non-alphanumeric followed by spaces

  $(this).val(cleaned);
});

Paste something here with a bullet point

<input type="text" id="my_textbox">


jQuery Mobile: .animate({scrollTop}) doesn't work after fixing page transitions

Question: jsFiddle links are at the bottom.
I have a Phonegap app that I have created with jQuery Mobile. The page transitions were really choppy and inconsistent in the native iOS app until I found this solution. It made my scrolling not so great, so I made a few changes per this follow-up article.
After the first solution and still after I implemented the second solution, the following code stopped working for me in my app:
$('html, body').animate({scrollTop: $('#specificID').offset().top}, 2500);

The above code scrolls the user down the page over 2.5 seconds to the DIV with the ID of specificID.
I have tried multiple things, but nothing seems to work:
$('#container').animate({scrollTop: $('#specificID').offset().top}, 2500);
$('html, body, #container').animate({scrollTop: $('#specificID').offset().top}, 2500);
$('.scrollable').animate({scrollTop: $('#specificID').offset().top}, 2500);
$(".scrollable").animate({ scrollTop: $("#specificID").scrollTop() }, 2500);

So, here is how I adjusted my jquery mobile code to fix the page transitions:
1. I wrapped [data-role="page"] DIV with container DIV

2. I added the following Javascript
$(document).one('mobileinit', function () {
  // Setting #container div as a jqm pageContainer
  $.mobile.pageContainer = $('#container');

  // Setting default page transition to slide
  $.mobile.defaultPageTransition = 'slide';
});

3. I added the following CSS
body {
    margin: 0;
}
div#container {
    position: absolute;
    width: 100%;
    top: 0;
    bottom: 0;
}
div[data-role="header"] {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
}
div[data-role="content"] {
    position: absolute;
    top: 41px;
    bottom: 0;
    left: 0;
    right: 0;
}
.scrollable {
    overflow-y: scroll;
    -webkit-overflow-scrolling: touch;
}
/* iOS specific fix, don't use it on Android devices */
 .scrollable > * {
    -webkit-transform: translateZ(0px);
}

I setup three jsFiddles to show this:

Plain jQuery - scrollTop working: http://jsfiddle.net/pxJcD/1/
Transition Fix - scrollTop NOT working: http://jsfiddle.net/ytqke/3/
Transition Fix w/ Native Scrolling - scrollTop NOT working: http://jsfiddle.net/nrxMj/2/

The last jsFiddle is the solution that I am using and the one that I need to work. I provided the second one to show that the scrollTop functionality stopped before any of the native scrolling changes I made. Any thoughts on what I can do to be able to scroll down the page using javascript?
I'm using jQuery 1.8.2, jQuery Mobile 1.2.0, and Phonegap 2.2.0 (via Build).
Thank you for any help you can offer.
Comment: Although I didn't go read your question deeply, I might add that a scroll animation works on document(ready), as long as the page is not cached. In other words you might need a unique uri so that jqm will reload the page.
Answer: In your CSS, you have set your container's position property to Absolute.
Remove your div#container
It should work.
http://jsfiddle.net/nrxMj/16/
Comment: When I was building a Mobile site, I had the same problem with scrollTop, so I used $.mobile.silentScroll(position) instead. http://jquerymobile.com/demos/1.0rc2/docs/api/methods.html
Comment: Thank you for your response. I see that it is working in the jsFiddle, but unfortunately it doesn't seem to be working that way inside the app. I know that it is hard to troubleshoot a native-app problem. Removing the `#container` CSS rules didn't create any problems with the page display or page transitions, but the scrollTop is still not working. I will study what you have proposed in more detail and see if there is something else I can do. In the meantime, if you or anyone else has any other thoughts - that would be great!


What does Snares mean in Hip-Hop, how is it different from Bars?

Question: I am new to rap music, trying to make my own verse. (I think of Verse as 16 bars, correct me if I'm wrong).
I was going through a producer on YouTube (The Video) where he mentioned "Snares" in close context with counting bars in a beat.
At about 0:38 he says:

…usually the two and the four are where the snares fall.

Can anyone explain me what does a snare mean? I think of 1 bar as counting 1, 2, 3, 4 and repeating the beat (Again correct me if I'm wrong)...
Thank you for help...
Comment: "Snare" refers to "snare drum; he mentions it to help you find the beat, saying that it often falls on beats 2 and 4. Note that there is a lot in this video that is about the way things "usually" are. There's no rule that verses have to be 16 bars; in "Gangsta's Paradise" they're 12, 12, and 8. But yes, your definition of "bar" is correct: Counting "1, 2, 3, 4" is one bar (at least, in the "4 count" that's most common).
Comment: I think this [tongue-in-cheek tweet](https://twitter.com/Komaniecki_R/status/1631835811497771009) is relevant here _"Snare (classical/jazz): A snare drum; Snare (pop [music]): Literally any percussive sound that occurs consistently on 2 and 4"_
Answer: It would be nice if you gave a timestamp or if you quoted what he mentioned about snares.
Without addressing the video: A snare is a kind of drum, derived from the military marching drums, which feature a band of metal cords at the bottom head. This gives a snaring sound, that's why it is called snare. The snare is one of the three principal components of a drum kit: The snare, the kick and the high hats.
In a standard rock style drum beat usually the high hats would keep the time, that is they play continuous notes (usually eighths). The kick usually goes on the strong beats (1,3 in common time, 1 in half time, 1,2,3,4 in double time) and the snare on the weak beats (2,4 in common time, 3 in half time 1+,2+,3+,4+ in double time).
This means it is common practice in many types of drum beat to put an accented snare on the weak beats, which I suppose is what this videos tries to make you listen for when counting bars.
Comment: 'Gives a snaring sound' - I'm intrigued.
Comment: ["Snare"](https://www.etymonline.com/word/snare) likely comes from the Dutch word for "string", not a preexisting word for a sound like a snare drum makes.
Comment: @Tim:  What other type of sound would you expect it to give?  :-)
Comment: @MichaelSeifert - a 'snarey' sound!
Answer: A snare is a snare drum. It is the piece of a typical drum kit that is most often played on the second and fourth beats of a 4/4 time rock, pop, rap, hip-hop, R&B, etc. song.
The snare has a high, dry sound - a little bit like a burst of noise.
Here's a short video that introduces the drum kit, starting with the snare:

Even though most rap and hip hop uses synthesized or sampled drums, it will probably help you a lot to learn the basics of acoustic drum kits, because beats are still based on the fundamentals of acoustic drum kit playing.
Answer: Bars are measures that music is divided into. Snares are sounds made by the snare drum. Not really related as such. However...
Music in 4/4 time (the most commonly used) is divided into 4 beats in each bar, and a live drummer would hit the snare drum (the one in between his knees) at certain points within those bars. The most often used points are beats 2 and 4 - the places where most people might clap along.
The more emphasised beats are usually 1 and 3 and those are represented by the bass, or kick drum. The largest drum in a drum kit. The snare drum is so-called as it has snares, or a strainer, underneath. They're simply a dozen or so wires slung under the resonator skin, pulled tight up to it. These rattle when the drum is played, making a different sound from the various tomtoms. (They also rattle annoyingly when the rest of the band don't want them to!).
So, there may be two snares played in each bar, on beats 2 and 4, at the drummer's discretion. The two terms are really only related as such.
Answer: P.S.: In the video

every 2 or 4 snares the rapper changes topic

only holds when the drummer plays a "boring" rhythm, see below. It may fit well, being the best choice to make musically, but you can spice things up every now and then, see below.

To add to already great answers a few remarks from a drummer.
Yes, you can play the snare on 2 and 4, while e.g. the kick drum is played on 1 and 3. That's widely used. Depending on the context in can become a bit boring, both for the audience and the drummer.
You should also listen to the HiHat (2 cymbals, which can be separated or closed), which might be mentioned in your video. On a traditional set it sounds like tik-tik-tik-tik or chick-chick-chick-chick, depending on how you operate in mechanically. In Hip-Hop the sound may be replaced by sth electronic, BUT the function is the same: to convey the relevant time division, which can be 1,2,3,4, 1,+,2,+3,+,4,+ etc. Once you can hear it, it's easier to relate the rest.
How does a bored drummer vary the snare rhythm? There are many options. I like to play the first 2 beats of a 4/4 bar uncomplicated (like just one hit on 2), and vary the snares rhythm during beats 3 and 4. A few examples:

skip the snare beat on 4 an shift it to the 4+
skip the snare beat on 4 and play earlier on 3+
play a series of so called ghost notes mixed with one or two real snare hits using the 16-th divisions (ghost notes are sort of soft strokes)

This creates very different feels. Rhythmically you may have listened to it in other songs. Wrt. the "boring one" and my 3 examples:

the simple parts in "We will rock you" (Queen) // a great song !
the 3 examples you can hear in many songs from the Red Hot Chili Peppers // also a touch of Funk music

Musically it may help to perceive the rhythms from the drum set as just another voice, very much like a singer, or better from a background choir. The can calm down (simple 1 2 3 4 rhythm), or contrast what was jsut sung or played.
Example - read out loud to get the rhythm, all in 1 bar:

"We will, we will" (1 2 3 4)
"I came (hm) too late" (1 2 3+ 4+)
"You are (normal) a great hip-hop writer (faster i.e. with a finer time division)"

Which of these syllables you emphasize by assigning it to a stroke on the snare is up to your taste.
Answer: In hip-hop music, a "snare" is a type of drum sound that typically falls on the second and fourth beats of a measure.
On "bars" refer to the rhythmic structure of a rap verse or a section of a song. In hip-hop, bars are typically made up of a set number of syllables or beats, usually four, that are repeated throughout the song. The term "bars" is derived from the idea that these sections can be separated into "bars" of music, each containing a set number of beats.


Convex game implies the Shapley value is in the (non-empty) core. Does the converse hold?

Question: Namely, if the game is non-convex then Shapley value is not in the core?
Answer: No, of course not.  The non-convexity might only involve strategies that are so bad nobody would ever want to use them.


R raster recognizing black color raster image

Question: The code below produces two boxes on my image. I am planning to analyze pixels within those boxes further.
I want to put a condition that if along an edge of a box, there is a black color  (or a similar color such as grey) pixel then don't proceed. How can i specify such condition?
In below example, in the case of the red square I don't want to proceed further as it has black pixels at the top right hand corner. While I would like to proceed in the case of green square as it doesn't have a black color pixel along it's edge.
library(raster)
r1 <- brick(system.file("external/rlogo.grd", package="raster"))
x <- crop(r1, extent(0,50,0,50))
plotRGB(x)
plot(extent(c(0,20,0,20)), lwd=2, col="red", add=TRUE)
plot(extent(c(21,35,0,10)), lwd=2, col="Green", add=TRUE)

Answer: That is not very well defined as in this case color is made of RGB values. But here is a general solution that you could adapt. I 'flatten' these to a single channel by taking the average, and then test for the smallest value being below a threshold (white is 255, 255, 255 in RGB, black is 0,0,0) at the boundary
proceed <- function(f, e, threshold) {
    lns <- as(as(e, 'SpatialPolygons'), 'SpatialLines')
    v <- unlist(extract(f, lns))
    ifelse( min(v, na.rm=TRUE) < threshold, FALSE, TRUE)
}

# flat <- mean(x) # not sophisticated see
# http://stackoverflow.com/questions/687261/converting-rgb-to-grayscale-intensity
flat <- sum(x * c(0.2989, 0.5870, 0.1140))
proceed(flat, extent(c(0,20,0,20)), 100)
proceed(flat, extent(c(21,35,0,10)), 100)

(much improved after seeing jbaums' solution; which is now gone)
Comment: No. mean(x) would by clearer, so I have made that edit
Comment: It uses the cell below.
`library(raster); r <- raster(nc=2, nr=2, xmn=0, xmx=2, ymn=0, ymx=2); values(r) <- 1:4; line <- spLines(rbind(c(0,1), c(2,1))); extract(r, line)`
Comment: We're dancing around each other a bit here ;). I like that you've wrapped into a function, so I'll delete. Any reason you're using `calc(x, mean)` instead of `mean`? (I might also suggest removing the `ifelse` - could change to `min(v, na.rm=TRUE) >= threshold`, or `all(v >= threshold, na.rm=TRUE)`).
Comment: Out of curiosity, which cells' values are extracted if the `SpatialLines` fall along cell boundaries?
Comment: Guys, thanks for answering my questions over last few days...if black or similar color is not a good condition then would it be easier if i change my constraint to say that if pixels on an edge has more than 1 color then ignore the square to which that square belongs?