Maximum likelihood estimation for mixed Poisson and Gaussian data

Question: Background
I've been doing a little bit of work lately on maximum likelihood estimation (MLE), for cases where the data is normally-distributed and also for cases where the data is Poisson distributed. For these two cases, the likelihood $L$ is given by:
$$
L\left ( \mathbf{a} \right ) = \prod_{i} \mathrm{P}\left ( c_{i};m_{\mathbf{a}}\left ( x_{i} \right ) \right )
$$
Following the notation and steps of the first reference below, $\mathrm{P}\left ( c_{i};m_{\mathbf{a}}\left ( x_{i} \right ) \right )$ is the probability that a measurement gives $c_{i}$ if the true value is given by the model $m_{\mathbf{a}}\left ( x_{i} \right )$, where $\mathbf{a}$ is the set of parameters for the model.
For the two different distributions, the reference gives:
$$
L_{G}\left ( \mathbf{a} \right ) = \prod_{i} \frac{1}{\sqrt{2\pi \sigma_{i} ^{2}}} \mathrm{e}^{-\frac{\left ( c_{i}-m_{\mathbf{a}}\left ( x_{i} \right ) \right )^{2}}{2\sigma_{i} ^{2}}}
$$
for Gaussian distributed data, and
$$
L_{P}\left ( \mathbf{a} \right ) = \prod_{i} \frac{\left [m_{\mathbf{a}}\left ( x_{i} \right )\right ]^{c_{i}}}{c_{i}!}\mathrm{e}^{-m_{\mathbf{a}}\left ( x_{i} \right )}
$$
for Poisson-distributed data.
I'm happy following the subsequent steps to get a likelihood ratio test out. The steps involve calculating the negative-log of the likelihood, then finding a ratio based on maximising $L$ for a given model with respect to the global maximum of the likelihood $L$, i.e.
$$
\frac{\mathrm{max}_{\mathbf{a}}\;L(\mathbf{c}|m_{\mathbf{a}})}{\mathrm{max}\;L(\mathbf{c}|\mathbf{m})}
$$
Edit
This question is related: What is distribution of $Z = X + Y$ where $X$ is Poisson distributed and $Y$ is normally distributed?
Question
I'm comfortable with the MLE for Gaussian and Poisson data. The scenario I'm interested in is for mixed Poisson-Gaussian data. An example might be photons arriving at a detector, which will exhibit Poisson noise, and the signal from the detector then subsequently being corrupted by Gaussian noise (e.g. thermal noise in the electronics). The noise model is then a mix of Poisson and Gaussian noise.
What I want to do is test whether a Poisson, Gaussian or mixed model is most appropriate for various parameters (I don't necessarily know whether the Poisson data can be approximated by a Gaussian by the way, hence the question - it's what I'm trying to test!).
What would an appropriate likelihood function $L$ be? Is it just a sum of the Poisson and Gaussian likelihoods? If so, the log-likelihood will be a bit tricky to simplify, I believe?
I'm sure I'm missing something with this problem, I just haven't been able to make the leap from the two cases described above (I should add that it's been a bit of time since I did statistics in any serious depth). Any help much appreciated!
References
For this problem, I've been following the paper "Comparison of maximum likelihood estimation and chi-square statistics applied to counting experiments" by T. Hauschild and M. Jentschel (2001).
Link and
DOI: 10.1016/S0168-9002(00)00756-7
Comment: How likely are your Poisson counts to be small?
Comment: It does help, in that it rules out just dropping straight to normal approximation to the Poisson. How small is the Gaussian noise likely to be? $\sigma \approx 1$, $\sigma>1$, $\sigma<1$?
Comment: by "mix" you appear to mean 'convolution' (sum of independent random variables, if I understand right). *Mixed* in statistics means something else.
Comment: Thanks! Also useful. This (small Poisson mean, small $\sigma$) is the most interesting case (though also perhaps in the 'may you live in interesting times' sense).
Comment: If you have a good estimate of the parameters already (perhaps initially obtained by doing the rounding at halves), you can round toward the value that gives the higher local probability.
Comment: It's actually just a convolution of a (very large sample from) a Poisson with small mean and a Gaussian with 0 mean and small variance. In this case I simulated a Poisson with a small mean and a Gaussian with a smaller variance than I wanted and then did a kernel density estimate (another Gaussian convolution, making the effective variance larger). Unfortunately in searching in my session (which was still running), trying to find the exact values I used, I just now managed to delete them instead. Still I could make a new one if you need code (it was done in R). ... (ctd)
Comment: (ctd) ... What I could (and likely should) have done was just do a kde with a larger bandwidth (the RMS of the s.d. in the Gaussian sample and the bandwidth I used above) on a large sample from a Poisson. There are other ways to get a similar image - for example, a numerical convolution of a Poisson and a Gaussian, say via FFT.
Comment: @Glen_b - good question. They're more likely to be small than not, if that helps?! I'm conducting this exercise to understand at what point just a Gaussian model becomes appropriate. It's a bit like high Poisson noise in an image, where each pixel has subsequently had a little bit of Gaussian noise added.
Comment: I'll check and confirm!
Comment: Likely that $\sigma < 1$
Comment: If $\sigma<0.15$ or so, you should probably just round the values to integers and treat as Poisson (but round all negatives up); alternatively there's a slightly more sophisticated version than splitting at $0.5$ but it won't make a lot of difference. Above that $\sigma$, you would need to treat the [density](http://i.imgur.com/RE7aPYj.png) more carefully.
Comment: What's the "more sophisticated version", out of interest?
Comment: Ah ok, I see what you mean. How did you generate the density image you linked to? I don't seem to be able to repeat it.
Comment: (ctd again:) ... The difference of any of these approaches from any of the others would not be visually distinguishable; it's about convenience, really.
Comment: Ok, I understand much better now - thanks for your help!
Answer: I think it is not a mixture distribution, because you actually have a sum of two noises, not a sum of two weighted probability densities.
For the sum of the two noises, you would have to assume that they are independent (while they are probably more likely positively correlated).
Then you can model the joint distribution of $Z=X+Y$ as:
$f(z)=\int_{-\infty}^{\infty}f(z-y)p(y)dy$
where f and p as densities for the Normal and Poisson respectively. I suspect this has only numerical solution, and you may then numerically maximize the Likelihood function of this density:
$\max_\theta \sum_{i=1}^{n} f(z_i|\theta)$
(also see pg.7/20 http://www.dartmouth.edu/~chance/teaching_aids/books_articles/probability_book/Chapter7.pdf)
In my opinion you may aswell fit each noise separately as you assume them independent anyways.
You may aswell assume a mixture distribution though and fit it to the distribution (you may assume any density by the way and fit it), then you would need to optimize or choose the weights aswell:
$f(z=x+y)=w_1f(x)+w_2p(y)$, with $w_1+w_2=1$.
Comment: Thanks for the reply - it's been a little while since I did statistics in this much depth - would you be able to clarify the joint distribution in terms of my likelihood functions? Thanks again!
Comment: The joint distribution cannot be directly related to the above Likelihoodfunctions or the Ratio respectively, because as I wrote it is not in closed form. Your model is separately fitting two univariate distributions, this is not the same as simultaneously fitting a bivariate joint distribution.
Comment: Sorry, yes, have read through the chapter you linked to and I understand better now. Thank you!


vmware remove partition from datastore

Question: I got a datastore which consists of 2 partitions on different hdds. I freed enough space to store everything in the datastore on the first hdd.
How can I move all data to the first partition and remove the second one from the datastore?
Answer: An extent can never be removed from a datastore.  See here.
To get the single partition into a datastore by itself, you'll need to move all VMs off the datastore temporarily, destroy and re-create it as a new datastore, then move the VMs back.

vmware remove partition from datastore


PHP Checkif two arrays have the same keys and same count of keys

Question: I'm trying to match 2 arrays that look like below.
$system = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$public = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);

My problem is, I need the array keys of both arrays to be the same value and same count.
Which means:
// passes - both arrays have the same key values and same counts of each key
$system = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$public = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);

// fails - $public does not have 'blue' => 1
$system = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$public = array('red' => 2, 'green' => 3, 'purple' => 4);

// should fail - $public has 2 'blue' => 1
$system = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$public = array('blue' => 1, 'blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);

I've tried using array_diff_keys, array_diff and other php functions, but none can catch extra keys with the same value (i.e. if 'blue' => 1, is repeated it still passes)
What's a good way to solve this?
Comment: Your last `$public` array is invalid, you can't have two `blue` keys in an array. If you `var_export(array('blue' => 1, 'blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4))` you will get `array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4)`
Comment: @SougataBose why did you delete your answer it is correct...
Comment: this problem can't fix by php, this is just how php behave, php gets the last value of distinct key
Answer: When you write two values with same key in PHP, the second one will overwrite the value from the first (and this is not an error). Below is what I did on the PHP interactive CLI (run it with php -a):
php > $x = ["x" => 1, "x" => 2, "y" => 2];
php > var_dump($x);
array(2) {
  ["x"]=>
  int(2)
  ["y"]=>
  int(2)
}

So array_diff seems to be working correctly. You are just expecting PHP to behave in a different way than it actually does!


Will this force a reinitialize in Merge Replication Topology?

Question: I need to add a couple of columns to a table that is a part of a replication set.  It is not a constraint coulumn or a part of any article filters and it allows NULL.  I have a pretty good idea that I can run this --> <code>ALTER TABLE tblPlanDomain ADD ReportWageES VARCHAR (100) NULL
</code>
and NOT force all my clients to reinitialize but I was hoping for some reassurance.  Can anyone verify this one way or the other for me?
Thanks,

Edit: Addtnl Info
This is what I am talking about --> http://msdn.microsoft.com/en-us/library/ms151870.aspx
It would seem, based on that, that the answer to my question is NO but I would still like a human confirmation.
Answer: nah the schema changes will be replicated. It won't force the subscription to re-initalize. The clients are all sql server 2005, right?
You should probably check that replication schema changes are set to true for the publication.
I also tested this in my lab environment on sql server 2005 to be sure.  You should really set one up, instead of relying on other persons.
Comment: setup another instance on the same box & you can have another subscriber :)
Comment: Yes they are all 2005's and I am replicating schema changes.  I agree, about the lab enviro, I am just having difficulty simulating our subscribers.  I have a "Stage" Publisher/Distributor that houses the same data but I am the only subscriber and even that kind of sucks since I have to `DELETE` all my local DB's every time I switch from one enviro to another.  Due to the fact that the DB's have the same name.  Maybe I could create a couple of VM subscribers.  Thanks for the confirmation though, much appreciated!
Answer: With MERGE replication, I believe this will force a reinitialization of the subscription.  This is not the case for transactional or snapshot replication.
See http://msdn.microsoft.com/en-us/library/ms188063.aspx
Comment: @Brian Knight: I am confused...that article is talking about partitioning my publication using a stored procedure.  I would just like to add a non identity column to a table and not have it cause a reinitialize.  See my Edit for a link.


Connection between the category-theoretic limit and the limit of a sequence or function in analysis (calculus)

Question: This may be a repeated question, but I want to make it clear.
I am learning basic category theory by myself and came across the concepts of limits and colimits. I understand, for example, the colimit of a sequence of decreasing sets indexed by the category of natural numbers with orders as morphisms is their intersection.
But since the word "limit" originally came from analysis with the classical epsilon-delta definition, I wonder what the connection between the two kinds of limit (category-theoretical limit and limit in analysis) is? Also,
can we give a new definition of the limit of a sequence or function (epsilon-delta definition) USING the category-theoretical one?
I would appreciate any help.
Comment: This could be useful: https://math.stackexchange.com/questions/60590/category-theoretic-limit-related-to-topological-limit , although it uses the language of filters in the more general setting of topological limits.
Comment: @whatsappcar Thank you. But I'm wondering whether there are neater explanations?
Answer: If you regard a partially ordered set $X$ as a category with an arrow $x \rightarrow y$ iff $x \leq y$, then the limit of a diagram in $X$ amounts to the infimum of the corresponding subset. Likewise the colimit of a diagram becomes the supremum.
This doesn't quite answer your question. The problem is that from this perspective limit and colimit are inherently directed constructions (the smallest / largest thing satisfying some property) while an analytic limit of a sequence is in some sense undirected (a point, which is arbitrarily close to the sequence).
I believe one can remedy this by considering $[0,\infty]$-enriched categories (a categorification of metric spaces) and weighted limits, but I don't think this will help you in understanding categorical limits.


linear interpolation based on look up tables in R (Finding the Age Lower bound and Upper bound)

Question: I have two data sets, For example:
# First data:
Age<-c(2,2.1,2.2,3.4,3.5,4.2,4.7,4.8,5,5.6,NA, 5.9, NA)
df1<-data.frame(Age)
# Second data:
Age2<-seq(2,20,0.25)
Mspline<-rnorm(73)
df2<-data.frame(Age2, Mspline)

For each value of age in the first data set, I need to find the right value of Mspline (linear interpolation) based on the second data set by the following formula:
Suppose your age in the first data set is 4.8, so the lower bound and upper bound of this age is 4.75 and 5 (these are the two closest values in Age2). Then, the value of Mspline for this age would be:*
Age2      Mspline     Sspline
4.75    -0.0769      0.1592
5       -0.0752      0.1535
Mspline = -0.0769 + ((4.8-4.75)/0.25)·(-0.0752 - (-0.0769)) = -0.0766

Mspline at your age= Mspline of lower bound of age+ ((your age-lower bound age)/0.25)*(Mspline of lower bound of age)-(Mspline of upper bound of age)

I was wondeing how I can make this function in R?
Answer: Here's a function that implements the formula as I understand it:
Age<-c(2,2.1,2.2,3.4,3.5,4.2,4.7,4.8,5,5.6,NA, 5.9, NA)

# Second data:
Age2<-seq(2,20,0.25)
Mspline<-rnorm(73)

res <- lapply(1:length(Age), \(x){
  lwr_ind <- max(which(Age2 <= Age[x]))
  upr_ind <- min(which(Age2 >= Age[x]))
  data.frame(Age = Age[x],
             Mspline = Mspline[lwr_ind] + ((Age[x]-Age2[lwr_ind])/0.25)*(Mspline[lwr_ind] - Mspline[upr_ind]))
})

res <- do.call(rbind, res)
res
#>    Age     Mspline
#> 1  2.0 -0.48510574
#> 2  2.1 -0.45222184
#> 3  2.2 -0.41933793
#> 4  3.4 -1.05075284
#> 5  3.5  1.03415440
#> 6  4.2  0.90388824
#> 7  4.7  1.05441685
#> 8  4.8 -1.86696649
#> 9  5.0 -0.60582730
#> 10 5.6 -0.76802820
#> 11  NA          NA
#> 12 5.9  0.09647946
#> 13  NA          NA

Created on 2022-10-19 by the reprex package (v2.0.1)
The remaining question is whether you're trying to do something with the missing values (NA).  The missing values in Age continue to be missing in the result above.
Comment: thank you so much, Could you please modify the code inorder to add the estimated value as a new coloumn to the first data. First data include the value of age and their estimated Mspline


Aligning input box inside panel body with the use of css grid

Question: I have created a login using css grid layout. I want to implement a form input box inside the panel body. However, the input box not respecting inside the panel body. The input box was overflow outside the panel body. For some reason, the code is working with regular css. I just want to implement css grid and i'm not sure about to go about this.
Thanks for any help.
Here is the fiddle.

https://jsfiddle.net/80fc325h/
Comment: Share relevant code.
Comment: Put some code here, so we can what do you have problem
Answer: Just use *{box-sizing: border-box} It will be updated. Hope it is helpful to you. Kindly check the snippet. As CSS3 box-sizing property allows us to include the padding and border in an element's total width and height.

body {
 margin: 0;
 font-size: 13px;
 color: #222;
 background-color: #f5f5f5;
}

* {
  box-sizing:border-box;
}

.text-right{
 text-align: right;
}
/*--------------------------------------------------------------
style:
--------------------------------------------------------------*/
.login-wrapper{
 display:grid;
  grid-template-columns:1fr;
  width: 50%;
  margin: 0 auto;
}

.content{
 display:grid;
  grid-template-columns:1fr;
  border:1px solid red;
}

.panel {
  background-color: #fff;
  border: 1px solid #dbd9d9;
  border-radius: 4px;
  -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .05);
  box-shadow: 0 1px 1px rgba(0, 0, 0, .05);
}
.panel-body {
  padding: 15px;
}
.panel-heading {
  text-align: center;
  padding: 5px 10px;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
}
.panel-title {
  margin-top: 0;
  margin-bottom: 0;
  color: inherit;
}
.panel-footer {
  padding: 10px 15px;
  background-color: #fff;
  border-top: 1px solid #dbd9d9;
}

/*--------------------------------------------------------------
Form:
--------------------------------------------------------------*/
.form-control {
  display: block;
  width: 100%;
  height: 34px;
  padding: 6px 12px;
  line-height: 1.42857143;
  color: #555;
  background-color: #fff;
  background-image: none;
  border: 1px solid #ccc;
  border-radius: 4px;
}
.form-control:focus {
  outline: 0;
}
.form-control::-moz-placeholder {
  color: #999;
  opacity: 1;
}
.form-control:-ms-input-placeholder {
  color: #999;
}
.form-control::-webkit-input-placeholder {
  color: #999;
}
.form-control::-ms-expand {
  background-color: transparent;
  border: 0;
}
.input-sm {
  height: 29px;
  padding: 5px 10px;
  font-size: 12px;
  line-height: 1.5;
  border-radius: 3px;
}
.has-feedback {
  position: relative;
}
.has-feedback .form-control {
  padding-right: 42.5px;
}
.form-control-feedback {
  position: absolute;
  top: 0;
  right: 0;
  z-index: 2;
  display: block;
  width: 34px;
  height: 34px;
  line-height: 34px;
  text-align: center;
  pointer-events: none;
}
.has-error .help-block,
.has-error .control-label,
.has-error .radio,
.has-error .checkbox,
.has-error .radio-inline,
.has-error .checkbox-inline,
.has-error.radio label,
.has-error.checkbox label,
.has-error.radio-inline label,
.has-error.checkbox-inline label {
  color: #f44336;
}
.has-error .form-control {
  border-color: #f44336;
}
.has-error .form-control:focus {
  border-color: #f44336;
}
.has-error .input-group-addon {
  color: #f44336;
  background-color: #f2dede;
  border-color: #f44336;
}
.has-error .form-control-feedback {
  color: #f44336;
}
.has-feedback label ~ .form-control-feedback {
  top: 25px;
}
.has-feedback label.sr-only ~ .form-control-feedback {
  top: 0;
}

.input-group {
  position: relative;
  display: table;
  border-collapse: separate;
}

.input-group .form-control {
  position: relative;
  z-index: 2;
  float: left;
  width: 100%;
  margin-bottom: 0;
}
.input-group .form-control:focus {
  z-index: 3;
}

.input-group-addon,
.input-group-btn,
.input-group .form-control {
  display: table-cell;
}

.input-group-addon,
.input-group-btn {
  width: 1%;
  white-space: nowrap;
  vertical-align: middle;
}
.input-group-addon {
  padding: 6px 12px;
  font-weight: normal;
  line-height: 1;
  color: #555;
  text-align: center;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 4px;
}
.input-group-addon.input-sm {
  padding: 5px 10px;
  font-size: 12px;
  border-radius: 3px;
}
.input-group-addon.input-lg {
  padding: 10px 16px;
  font-size: 18px;
  border-radius: 6px;
}
.input-group-addon input[type="radio"],
.input-group-addon input[type="checkbox"] {
  margin-top: 0;
}
.input-group .form-control:first-child,
.input-group-addon:first-child,
.input-group-btn:first-child > .btn,
.input-group-btn:first-child > .btn-group > .btn,
.input-group-btn:first-child > .dropdown-toggle,
.input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle),
.input-group-btn:last-child > .btn-group:not(:last-child) > .btn {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}
.input-group-addon:first-child {
  border-right: 0;
}
.input-group .form-control:last-child,
.input-group-addon:last-child,
.input-group-btn:last-child > .btn,
.input-group-btn:last-child > .btn-group > .btn,
.input-group-btn:last-child > .dropdown-toggle,
.input-group-btn:first-child > .btn:not(:first-child),
.input-group-btn:first-child > .btn-group:not(:first-child) > .btn {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}
.input-group-addon:last-child {
  border-left: 0;
}

label {
  display: inline-block;
  max-width: 100%;
  font-size: 13px;
  margin-bottom: 5px;
}
input:focus{
  outline:none!important;
}
.form-control-feedback i{
  margin-top: -5px;
}
.form-group{
  margin-bottom: 10px;
}

.footer-section{
 background-color: #e9ecef;
 display: grid;
 border-top: 1px solid #d8dadd;
 grid-template-columns:1fr;
 font-size: 11px;
 text-align: center;
}

/* ==========================================================================
   Button Scripts
   ========================================================================== */
.btn{
  display: inline-block;
  margin-bottom: 0;
  font-weight: 400;
  text-align: center;
  vertical-align: middle;
  touch-action: manipulation;
  cursor: pointer;
  border: 1px solid transparent;
  white-space: nowrap;
  padding: 3px 10px;
  line-height: 1.5384616;
  border-radius: 3px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none
}
.btn:focus{
  outline: none;
}

.btndrk-orange{
 background-color: #ec8b02;
 color:#fff;
}

                          <input type="text" class="form-control" name="username" id="username" autocomplete="off" placeholder="Username">

                            <input type="password" class="form-control" name="password" id="password" autocomplete="off" placeholder="Password">

       <button type="button" class="btn">LOGIN</button>

Comment: thank you Anmol for the quick fixed. Really appreciate. its working, accepted answer. thnks
Comment: @Rye thanks a lot. Please upvote and mark so others can follow it too.
Comment: Done. thnks again.
Answer: Use display flex not display table on your input group.
Comment: thnks also. its working, however the icon on the left side is broke. Not aligning properly to input box


Convergence of series $\sum_{k=1}^\infty (\frac{1+k^2}{1+k^3})^2$

Question: Given the series
$$
\sum_{k=1}^\infty (\frac{1+k^2}{1+k^3})^2,
$$
can I conclude from
$$
\begin{align}
\sum_{k=1}^\infty (\frac{1+k^2}{1+k^3})^2
&=\sum_{k=1}^\infty (\frac{1+k^2}{1+k^3})(\frac{1+k^2}{1+k^3})\\
&\leq\sum_{k=1}^\infty (\frac{k^2+k^2}{1+k^3})(\frac{k^2+k^2}{1+k^3})\\
&\leq\sum_{k=1}^\infty (\frac{2k^2}{k^3})(\frac{2k^2}{k^3})\\
&=\sum_{k=1}^\infty (\frac{2}{k})(\frac{2}{k})\\
&=\sum_{k=1}^\infty (\frac{2}{k^2}),
\end{align}
$$
that  $\sum_{k=1}^\infty (\frac{1+k^2}{1+k^3})^2$ must converge since  $\sum_{k=1}^\infty (\frac{2}{k^2})$ converges and the above estimations are valid?
Comment: Yes, that is a correct argument.  You could shorten it a bit by using $\frac{1+k^2}{1+k^3}\le \frac 1{k^3}+\frac 1k$ then $\left(\frac 1{k^3}+\frac 1k\right)^2\le \frac 3{k^3}+\frac 1{k^2}$, but your argument is good as-is.
Answer: Yes, it is correct, except that after the final $=$ sign you should get $\sum_{k=1}^\infty\frac4{k^2}$.
Besides, note that the inequality$$\frac{1+k^2}{1+k^3}\leqslant\frac2k\tag1$$is equivalent to $k+k^3\leqslant2+2k^3$, which, in turn, is equivalent to $k\leqslant2+k^3$, which is true, since you actually have $k\leqslant k^3$ for each natural $k$. So, this gives you another way of proving $(1)$.
Comment: Oh yeah, you're obviously right! Thanks for your reply.


Firefox e IE não encontram fonte

Question: Tenho um site wordpress onde instalei duas fontes: Calibri e Castlet.
No Chrome funciona corretamente, mas no Firefox ele reconhece apenas a Calibri.
O site é esse: http://plengenharia.syswebapp.com.br/
No Css:
@font-face {
font-family: Calibri;
src: url("wp-includes\fonts\calibri.ttf") format('truetype'), src: local("Calibri"), url("wp-includes\fonts\calibri.eot"), url("wp-includes\fonts\calibri.eot?#iefix") format('embedded-opentype'), url('wp-includes\fonts\calibri.woff') format('woff');
}

@font-face {
font-family: Castlet;
src: url("wp-includes\fonts\Castlet.ttf") format('truetype'), src: local("Castlet"), url("wp-includes\fonts\Castlet.eot"), url("wp-includes\fonts\Castlet.eot?#iefix") format('embedded-opentype'), url('wp-includes\fonts\Castlet.woff') format('woff');
}

Comment: Veja **[aqui](http://pt.stackoverflow.com/questions/3458/font-face-n%C3%A3o-funciona-no-firefox-mas-no-ie-e-no-chrome-funcionam)** se esta resposta lhe resolve o problema. Visto que é semelhante a pergunta..
Comment: Afinal, a fonte não é encontrada (404) ou o browser acusa problema na fonte (não renderiza, utiliza outra fonte, etc)? Quais versões de browser testou? O IE, por exemplo, até hoje não tem suporte total a fontes TTF e OTF.
Comment: Se o erro fosse `404` nao deveria dar no chrome, por isso pode excluir essa opção ..
Comment: Meu Firefox mostra a fonte perfeitamente (ao menos não vejo diferenças do Firefox e Chrome). Questões com links externos devem ser evitadas, pois nem sempre é possível reproduzir o problema em páginas que está havendo modificações.
Comment: Rafaella [esta outra pergunta/resposta resolve o seu problema](http://pt.stackoverflow.com/questions/3458/font-face-n%c3%a3o-funciona-no-firefox-mas-no-ie-e-no-chrome-funcionam)?
Comment: Veja se isso ajuda

http://pt.stackoverflow.com/questions/3458/font-face-n%C3%A3o-funciona-no-firefox-mas-no-ie-e-no-chrome-funcionam
Answer: seu erro está em repetir o "src:".. esse é o name do atributo, tenta deixar assim:
src: url(...)..., url(...)...

se perceber nos 2 exemplos vc repete o src: 2x
Comment: Você tem toda razão, que falta de atenção nossa (hehehe) +1 espero que aceitem a sua resposta
Answer: A tua regra de CSS at-rule, a @font-face, encontra-se com declarações incorretas, motivo pelo qual não é interpretada por alguns navegadores.
Formatação correta
@font-face {
    font-family: 'Calibri';
    src:
        local('Calibri'),
        url('wp-includes/fonts/calibri.ttf');
    src:
        url('wp-includes/fonts/calibri.eot'),
        url('wp-includes/fonts/calibri.eot?#iefix') format('embedded-opentype'),
        url('wp-includes/fonts/calibri.woff') format('woff'),
        url('wp-includes/fonts/calibri.ttf') format('truetype');
}

Explicação

Especificar a pesquisa por "fonte local" antes de qualquer outro endereço:
src:
    local('Calibri'),                       /* local */
    url('wp-includes/fonts/calibri.ttf');   /* remoto */

De notar que esta declaração deve terminar com ; e não com ,.
Especificar as origens para os outros ficheiros pela ordem mais provável de utilização e numa declaração separada:
src:
    url('wp-includes/fonts/calibri.eot'),
    url('wp-includes/fonts/calibri.eot?#iefix') format('embedded-opentype'),
    url('wp-includes/fonts/calibri.woff') format('woff'),
    url('wp-includes/fonts/calibri.ttf') format('truetype');

Estando a programar em servidores Windows ou em servidores Linux, a inclinação da barra nos endereços web é sempre /:
"http://www.example.com/fonts/minhaFonte.eot"

Não absolutamente necessário para o teu caso em particular, mas os nomes das famílias de fontes devem estar envolvidos por ' ou " para uma correta interpretação por parte dos navegadores:
W3C CSS Fonts Module Level 3 - Family Name Value

Os nomes das famílias de fonte que não sejam os genéricos tem que estar como uma string citada, ou seja, dentro de ' ou ". Alternativamente se não dentro de aspas ou plicas, devem estar como uma sequência de um ou mais identificadores.

No teu caso isto acaba por ser irrelevante por ser uma palavra única Calibri, mas fica a nota para futuros leitores.

Relacionado
Para estes casos, podemos recorrer ao gerador de web-font presente no web-site FontSquirrel que trata de gerar os ficheiros adequados para cada navegador, bem como a folha de estilos com tudo pronto a utilizar no nosso web-site.
Answer: A primeira sugestão é corrigir as barras, já que URLs usam /.
src: url("wp-includes/fonts/Castlet.ttf") format('truetype'), src: local("Castlet"), url("wp-includes/fonts/Castlet.eot"), url("wp-includes/fonts/Castlet.eot?#iefix") format('embedded-opentype'), url('wp-includes/fonts/Castlet.woff') format('woff');

A segunda coisa que eu observaria é o conteúdo dessas tags url(). O caminho é relativo à localização do arquivo CSS (W3: http://www.w3.org/TR/REC-CSS1/#url).
Algo como
url("/wp-includes/fonts/Castlet.eot")

ou (de preferência)
url("http://plengenharia.syswebapp.com.br/wp-includes/fonts/Castlet.eot")

pode resolver seu problema.

Firefox e IE não encontram fonte


Wiring 1 humbucker, 2 singles, 1 tone knob with YKE switch

Question: So I got this cheap used guitar (Invasion brand). It has H+S+S setup, two knobs and a 5-way pickup switch.
Currently it's wired like this:

As you can see, it's not wired properly (the humbucker is not connected to anything). If possible, it must be connected like shown in the table («Desired coil connection») where «B/2» singnifies a single coil of the humbucker.
That YKE pickup switch works like shown in the table.

Switch position ↓   /   Pole connection →
2+3 (N)
1+3 (M)
7+3 (B?)
5+4 (?)
6+4 (?)
Desired coil connection

1
On

On

N

2
On
On

On

N + M

3

On

On
M

4

On
On

On
M + B/2

5

On

B/2 + B/2

Now the humbucker has 3 wires coming out of it: red, white and metal. I don't know what are they connected to, I can only suppose the metal one has to be connected to ground. I have measured the resistance between those wires:

Wire 1
Wire 2
R, kOhm

Red
Metal
12.6

White
Metal
6.5

Red
White
6.5

Given this information, how do I connect the humbucker? I suppose pole 6 of the switch must be used somehow.
Comment: What's the brand and model of the humbucker? There are two possible reasons for three conductor wiring on a humbucker and only one of them is coil tap/split
Comment: The resistance measurements say it's wired for coil split
Comment: the humbucker "metal" wire is likely to be earth so should connect to a pot body or pin 8 of the switch. The white orphan wire, is that likely to have been once connected to the white humbucker wire?  perhaps this helps https://www.pinterest.com/pin/166703623690869995/
Answer: If the table is correct, connecting the metal wire to ground, red wire to 7 and white wire to 6 should work.
The resistance measurements tell that there are two parts that are wired between metal-white and white-red. These are the humbucker coils. Modern humbuckers designed to work with any wiring scheme would have separate pair of wires for each coil and one extra wire for ground to allow wiring coils in parallel and for phase reversal, but with this one coil tap is the only option.
When red is connected to 7 and white to 6, position 5 would connect only 7 (both coils in series) to tone circuit. In position 4 the 6+4 connection would short circuit one coil and the other coil would be now between 7 and ground. The 1+3 and 7+3 connections connect the single coil and half humbucker to tone circuit in parallel.
BTW, the picture has neck pickup connected to 1 and middle to 2 and the table has them the other way round. Other strange detail is that 5-4 is connected both for position 1 and 2. If it was just 2 or 2 and 3, it would work for splitting neck humbucker for position 2, but I have no idea what this configuration could be used for.


how to find probalility that a student misses at least one test if he/she is absent twice?

Question:
The probability that a teacher will give an unannounced test during any class is $\dfrac15$. If a student is absent twice then probability that he/she misses at least one test is
$\\ \hspace{5cm}$ a) $\dfrac23\ \quad $ b) $\dfrac45\ \quad$c) $\dfrac7{25}\ \quad $d) $\dfrac9{25}\ $

My attempt:
Probability of attending first test & missing $2$nd test $=\dfrac45\times\dfrac15=\dfrac4{25}$
Probability of missing first test & attending $2$nd test $=\dfrac15\times\dfrac45=\dfrac4{25}$
Probability of missing both the tests $=\dfrac15\times\dfrac15=\dfrac1{25}$
Total probability of missing at least one test $=\dfrac4{25}+\dfrac4{25}+\dfrac1{25}=\dfrac9{25}$
Can somebody please help me if I am wrong? Thanks.
Comment: Yes, you are correct. Notice, a simple method is $$P_{\text{ Missing atleast one test }} = 1- P_{\text{ Missing no test }} = 1-(\frac{4}{5})^2=\frac{9}{25}$$
Answer: Questions with "at least" are often great candidates for using the complement. That is: $$P_{\text{ Event A occurs }} = 1 - P_{\text{ Event A does not occur }}$$
So, $P_{\text{ miss at least 1 test }} = 1 - P_{\text{ miss no tests }}$ giving us:
$$\begin{align*} P_{\text{ miss no tests }} & = P_{\text{ no test on day 1 AND no test on day 2 }}\\
& = P_{\text{ no test on day 1 }} \times P_{\text{ no test on day 2 }}\\
& = \frac{4}{5} \times \frac{4}{5}\\
& = \frac{16}{25}\end{align*}$$
So, $$P_{\text{ miss at least 1 test }} = 1 - P_{\text{ miss no tests }}
= 1 - \frac{16}{25}
= \frac{9}{25}$$
Answer: Another way to see this is that the probability of the student missing at least one test is the probability of missing test 1 + the probability of missing test 2 - the probability of them missing both tests.
The student has $\frac15 $chance of missing the first test, and $\frac15 $ chance of missing the second test. If you add them up you're left with $\frac 25$. HOWEVER there is a case that is being counted twice: It could happen that the student misses test 1 AND test 2. That case is being counted both when the student misses test 1 and when the student misses test 2. So now we have to substract this case once
The chance of a test happening on two consecutive days is $(\frac 15)^2 = \frac {1} {25}$.
So the answer is $\frac 25 - \frac {1} {25} = \frac {9} {25}$
The general case for this is $$P(A \cup B) = P(A) + P(B) - P(A \cap B)$$


How can I tell if the text was truncated when I copy a text into an input box with a maxlength attribute

Question: HTML input element has a maxlength attribute, which prevents inputting a text longer than the maxlength . Upon pasting a text into the input box, if the text is longer than the maxlength, it will be truncated to the exact length of maxlength. How can I tell if the text was truncated or not please?
Thanks.
Answer: Assuming you want to know if the length of the value of an input element is the same as the maxlength of that element, you could do something like this (using JQuery).
<code>var $el =  $("#myInputElement")
var l = $el.val().length;
var ms = $el.attr("maxlength");
var m = parseInt(ms, 10);

// at this point m and l are maxlength and actual length
</code>
This however is not the same as a truncated value, it may simply be that exact length.
If you want to know if a user is still writing after reaching the maxlength, you could use look at the keyup event and whether or not the input is focused. However, to compare the clipboard with your input, you might have to resort to Flash.
In short, there is no good solution.
Comment: @WawaBrother as I explained earlier, there is no way to actually know if the user intended to input more text. I guess you could get rid of the maxlength attribute, then truncate using javascript instead. That way you would get the whole text, and be able to know when you truncate
Comment: I am wiling to use JavaScript. However, what I want to know is, when the input length is exactly the maxlength, whether the text was copied form a longer text somewhere else. Probably not comparing the length before sending the form, hopefully I can know it immediately after the text being pasted. Yes, we are sure that if the length is smaller, it must not be truncated. How about when the length is exactly the maxlength?
Comment: @WawaBrother updated answer with your clarification, someone downvoted for me being too slow though!
Comment: thanks for your answer. Well, I was surprised to see such a quick downvote as well. Not me, must be someone else. :)
Comment: @WawaBrother please tell me if you need any clarifications, however I tried that in JSFIddle and it worked fine
Comment: No I don't. However your answer doesn't solve my problem. I am more interested in the case when a text longer than maxlength is being truncated.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/18428/discussion-between-wawabrother-and-eakron)


An instrument I don't recognize (photo included)

Question: I'm not sure if this is a proper question to ask here so sorry in advance.
The other day I was in Barcelona and saw a guy playing a plucked string instrument that had the size of a viola.
Its body resembled a capsule in shape and its neck was cylindrical. I can't remember how many strings it had but the timbre was quite round and the pitch was between that of a guitar and a bass. I attached a crude drawing based on my memory.
Can someone maybe give me a hint on what it might be? It could be of Spanish or catalan origin.
Edit: Thanks for the comment! (I don't have enough reputation to reply yet) I know this is quite an ambiguous question, but I remembered I had taken a photo of it:
I don't know if this makes the question clearer. Anyway, if it got voted down to -1 or below I will delete it.
Comment: Btw, if this is off-topic as a question, there's a chat room here where you could still ask it. You need a reputation score of 20 to participate, but that's pretty easy to do.
Comment: Welcome. Like the pic., but feel that this kind of question isn't beat suited on this site. We'll see.
Comment: Hi! There's some difference of opinion on whether ["what kind of instrument is this](https://music.meta.stackexchange.com/q/2443/78419) should be on-topic here; in fact, it's mentioned as *not* covered [here](https://music.stackexchange.com/help/on-topic). But even for those inclined to view this as on-topic, I'm afraid there just isn't enough to go on here. There are many, many plucked string instruments, even many with capsule-shaped bodies. If you can stumble across an actual photo, or tell more about the performance circumstances, you might have a better chance.
Comment: @Tim The trend on the site is identification questions about instrument are off-topic.  If we want there to be exceptions, we need to hash them out on meta so it doesn't seem arbitrary what we allow and what we don't.
Comment: Take a look at a Sintir/guembri some have circular necks
Comment: @Dom - hardly just 'voting to close', but 'actually closing'. Had it been a question about a run of the mill instrument, I may have agreed, but I expect the vast majority of us have never seen one, let alone played one, or knew about tuning, etc. I have a feeling there should be room for this kind of question, without prejudice.
Comment: I found this online but there is no information on the instrument itself, it is just part of a photo gallery. Scroll to image #13  https://www.madineurope.eu/en/trainings/escuela-de-violeria-de-zaragoza-manufacturing-of-spanish-guitar-plucked-and-bowed-string-instruments/
Comment: @JohnBelzaguy by opening that image in a new tab and viewing the filename, I could see that it is called a *Vihuela de arco*, a bowed instrument.  Searching for that led me to the Wikipedia article [Vielle](https://en.wikipedia.org/wiki/Vielle).  Probably not the plucked, electrified instrument in the question photo.
Comment: @Theodore Perhaps not but it could also possibly be that same type of instrument being held like a guitar, amplified and plucked. The OP's photo is very blurred but it does appear to show a violin/viola/cello style bridge,
Comment: @Theodore Upon looking more closely at your wiki article, the second picture shows 3 musicians, Two playing vielle and one playing citole, which looks similar and is played plucked in a guitar position. Maybe it is a modern version of that. https://en.wikipedia.org/wiki/Citole
Comment: @Yorik I think we have a winner, you!
Comment: @Yorik I agree! One [photo on the Sintir page](https://en.wikipedia.org/wiki/Sintir#/media/File:Nuru_Kane_Guimbri.jpg) on Wikiedia even shows an electrified version.
Comment: I'm voting to close this question because instrument identification is off-topic.
Answer: It's a sintir, gimbri/guimbri/guembri/hajhuj. Usually with three strings, top and bottom tuned one octave apart, the middle tuned to a fourth above the lowest, which is used as a drone. It seems it doesn't matter what notes - it's the intervals that are important.
The tuning method is unusual. No pegs, but cords wrapped around the neck (cylindrical), which slide up and down to tension the strings. The bridge is cambered, but nowhere near the radius of the neck. The soundboard is rather like a banjo - animal skin usually camel, so N.African generally.
The one pictured looks like a well adapted one, with a pup, probably piezzo, so the instrument can be amplified.

An instrument I don’t recognize (photo included)


How can I estimate the tail of a distribution with a truncated distribution?

Question: The broadband speed data I'm working with have all values over 30Mbps placed into a >30 category. The distribution is thus truncated. This leads to the final column in the histogram below being a catch-all for any values above this point. I've been advised to remove the final column. I'm tyring to develop a multilevel model which uses a variety of economic and socio economic varaibles at the postcode level and above.
Can anyone suggest a method to help me smooth out this spike in the distribution please? Is it possible to estimate the distribution of this variable above this cut off point?

Edit: After removing the final column of the distribution and log transforming the data, I still end up with a distribution like the histigram below. Can anyone advise any techniques on how I could better deal with this truncated distribution please?
Answer: If one looks at that histogram (conventionally, not "histograph") and has the information that "over 30" is just lumped together, the mind can doodle and imagine it smoothed out somehow. Perhaps the pattern of frequencies in the values just above looks roughly exponential.... Except: There isn't a spell straight from Hogwarts that can just fix what was broken in data production or collection.

What else do you want to do if you manage to do this? Answers will depend on what you say.
There should be more context than you give, and it's got to be important. What are these values? Is any value above 30 possible in principle? Is there an upper limit on what is physically (biologically, economically, etc.) possible? I doubt that any person with a lot of statistical experience would feel that there will be an answer to the question, independent of subject-matter knowledge. If there's some theory for the form of the tail of the distribution, or other datasets on the same variable, they might help a bit, but the territory is still dangerous.
Is there no other information on these cases? Perhaps there is scope for more kind of multiple imputation using other variables as predictors. But, if you follow that road, expect to do a lot of reading, a lot of computing, and to have to think quite differently about your data. (In particular, no method can infallibly provide correct values when none was collected in the first place.)
If you were to smooth that out, what's the implication? That the values over 30 get assigned different values? Which gets assigned what? That's got to be arbitrary, but see #3 again.
Plenty of fields use special methods when values are censored or truncated at an upper (or lower) limit. The best strategy might to work with the limit, not to try to fudge beyond it.
It is usually impractical, but any short list still has to mention that the ideal possibility is to go out again and get better data.
In some problems of this kind, one answer is to fit a truncated gamma, or truncated lognormal, or some other brand-name distribution, truncated. But in your case it is already apparent from the bimodality that no simple distribution is a good candidate. Except (see #2 again) there just may be an idea that your distribution is a mixture and can be modelled as such.


Create a new sheet in a Google Sheets with Google Apps Script

Question: How to create a new sheet in a Google Sheets with Google Apps Script?
I know it seems obvious but I just want to create a new sheet with a specific name.
Answer: Surprisingly I didn't find any clear and quick answer.
So here is my code:
function onOpen() {
    var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
    var yourNewSheet = activeSpreadsheet.getSheetByName("Name of your new sheet");

    if (yourNewSheet != null) {
        activeSpreadsheet.deleteSheet(yourNewSheet);
    }

    yourNewSheet = activeSpreadsheet.insertSheet();
    yourNewSheet.setName("Name of your new sheet");
}

Finally, note that this new sheet will be automatically the active one.
Comment: The code is ok but you probably dont want it on onOpen. If you want to create it on user-demand create a menu.
Comment: I was opening a post because every time I create a new sheet using a script the Spreadsheet stops working after a while. Does it happen to you?
Comment: Yes you're right, this is exactly what I did just after that!
Comment: Hum nope sorry, never happened!
Answer: I'd recommend this method.
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.insertSheet('My New Sheet');

Where 'My New Sheet' is the name you want it to be.
Answer: Here is a simple example:
var name = (new Date()).toLocaleDateString();
SpreadsheetApp.getActiveSpreadsheet().insertSheet(name);

Answer: Here's the way I did it...
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var newSheet = activeSpreadsheet.insertSheet();
newSheet.setName("whatever");

Comment: How's that better than the earlier answers?
Answer: I have been looking at the answers and although they answer the question of how to create a sheet and give it a name, none shows how to make that name variable by passing it as a parameter
This is an example of a function passing a variable to the createNewSheet function:
(The function that has to be executed is setNameAndCreateSheet)
function createNewSheet(sheetName){
  // The sheetName parameter has to be passed to the function when it's called
  let activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  let newSheet = activeSpreadsheet.insertSheet();
  newSheet.setName(sheetName); // We sheet will be called as the string of the parameter
}

function setNameAndCreateSheet(){
  // This will get the email of the user executing the script
  const userEmail = Session.getEffectiveUser().getEmail();

  // This will get the current date
  const date = Utilities.formatDate(new Date(), "GMT-3", "dd/MM/yyyy");

  // We are making the string that will be passed to the createNewSheet function
  const sheetName = date + " - " + userEmail;
  // sheetName will return something like: "04/11/2021 - firstname.lastname@example.com"

  // This will execute the function that creates the sheet, and the name will be settled to the parameter passed (sheetName)
  createNewSheet(sheetName);
}

In this example, the parameter passed to the createNewSheet function is the concatenation of these two strings (date - useremail), but it could be anything.
Answer: This function does that with more options, where you can select:

The new sheet name
Add the sheet to which spreadsheet
After (or before) which sheet (index or name)
Choose to add a counter or delete if the new name is already used before.

function addSheet(shName, ss, aftr, bfr, delMode) {
  var sh = null;
  // Define the optional argument ss (Spreadsheet) if missing
  if (ss == null) ss = SpreadsheetApp.getActiveSpreadsheet();
  // If no new name is given, use "Sheet" and deactivate delete mode
  if (shName == null) {
    delMode = null
    shName = "Sheet"
  }

  if (delMode == null) {
    // If delete mode is inactive, use a counter if the name already exists (like "Sheet (2)")
    var n = 1;
    var nShName = shName;
    while (ss.getSheetByName(nShName) != null) {
      n += 1;
      nShName = shName + ' (' + n + ')';
    }
    shName = nShName;
  } else {
    // otherwise, delete on sight!
    sh = ss.getSheetByName(shName);
    if (sh != null) ss.deleteSheet(sh);
  }
  // Where to add the new sheet:
  if (aftr == null) {
    if (bfr == null) {
      // If both after and before arguments are missing, add the new sheet to the end of sheets list.
      n = ss.getSheets().length;
      // Uncomment the next one if you want it to be added after the active sheet
      // n = ss.getActiveSheet().getIndex();
    } else if (typeof(bfr) == 'string') {
      // If before argument was given as string (Sheet name), try to find it.
      n = getSheetOrder(bfr) - 1
    } else {
      // otherwise use the given number
      n = bfr - 1
    }
  } else if (typeof(aftr) == 'string') {
    // If after argument was give as string (Sheet name), try to find it.
    n = getSheetOrder(aftr);
  } else {
    // otherwise use the given number
    n = aftr;
  }
  // Note: if both after and bfr are given, bfr is ignored.

  // Fix the case where only before argument is gevin as a string,but no sheet with that name is found
  if (n < 0) n = 0;
  // Fix the case where the numbers given were too high
  if (n > ss.getSheets().length) n = ss.getSheets().length;
  // Do the action!
  return ss.insertSheet(shName, n);
}

function getSheetOrder(shName, ss) {
  // returns 0 if sheet is missing, or the sheet index if found.
  if (ss == null) ss = SpreadsheetApp.getActiveSpreadsheet();
  const sh = ss.getSheetByName(shName);
  if (sh == null) return 0;
  return sh.getIndex();
}

Tests:
addSheet() adds a sheet named "Sheet" (or "Sheet (2)", "Sheet (3)",...) to the end of the file (or after the active sheet if you edit the code)
addSheet("My Sheet", null, 3, null, 1) adds a sheet names "My Sheet" after the third sheet in the active spreadsheet, and deletes the old sheet with the same name if found.


Map not displaying while working in ASP.NET/C#

Question: I'm using sample code to display map based on locations in the sample database. That works fine.
Sample code Link

If I try to use this code in local and try to display the locations which are in my database, that doesn't work.

Html Code

    <title></title>

    <form id="form1" runat="server">
     <asp:HiddenField ID="hfLat" runat="server" />
    <asp:HiddenField ID="hfLon" runat="server" />
    <asp:Label  Text="Name" runat="server"></asp:Label>
        <asp:TextBox ID="txtname" runat="server"></asp:TextBox>

        <asp:Label Text="Description" runat="server"></asp:Label>
        <asp:TextBox ID="txtdescription" runat="server" TextMode="MultiLine"></asp:TextBox>
    <asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
    </form>

PageLoad
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            DataTable dt = this.GetData("select  * from FindLocation");
            rptMarkers.DataSource = dt;
            rptMarkers.DataBind();
        }
    }

GetData
private DataTable GetData(string query)
    {

        SqlCommand cmd = new SqlCommand(query);
        using (SqlConnection con = new SqlConnection(conString))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;

                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    return dt;
                }
            }
        }
    }

Insert Query
protected void btnSave_Click(object sender, EventArgs e)
    {
        string latitude = hfLat.Value;
        string longitude = hfLon.Value;
        string Name = string.Empty;
        string Description = string.Empty;

        using (SqlConnection conn = new SqlConnection(conString))
        {
            using (SqlCommand cmdd = new SqlCommand("Insert into FindLocation(Name,Latitude,Longitude,Description)VALUES(@Name,@Latitude,@Longitude,@Description)"))
            {
                cmdd.Parameters.AddWithValue("@Name", txtname.Text);
                cmdd.Parameters.AddWithValue("@Latitude", latitude);
                cmdd.Parameters.AddWithValue("@Longitude", longitude);
                cmdd.Parameters.AddWithValue("@Description", txtdescription.Text);
                cmdd.Connection = conn;
                conn.Open();
                cmdd.ExecuteNonQuery();
                conn.Close();
            }
        }

    }

Comment: Check for console errors.
Comment: first try to display the map in a plain html page.
Comment: No error sir @Majid
Comment: i tried but not working @sachin
Comment: then you should first start from there and fix that problem before looking into getting the markers right.
Comment: am sorry for that misunderstanding html is working fine @sachin
Answer: First of all you made a double call to the google API

(1)
(2)
so remove (2) from your code.
Second you mention in (1) url &callback=initMap so either change that to LoadMap or change LoadMap function name to initMap
Comment: @IvinRaj Pelase try once please and Two call to the same map API always gives conflict error on browser console.I have checked your code in my PC and found console error as confliction.
Comment: Okay sure sir I will @PranavPatel
Comment: Not working sir i think database issue @Pranav Patel
Comment: in this same code try to do same with static value like static markers value and check either value formatting issue or what?
Comment: I've found the mistake Sir @Pranav Patel.Whenever I use '(apostrophe) in the description text box (Example: I'm), an error has occurred.Once I remove, everything works fine, so I guess '(apostrophe) shouldn't be used in the description.
Answer: I've found the mistake Sir @Pranav Patel.Whenever I use '(apostrophe) in the description text box (Example: I'm), an error has occurred.Once I remove, everything works fine, so I guess '(apostrophe) shouldn't be used in the description.
Comment: ok Ivin but not you have to escape those character in `"description": '<%# Eval("Description") %>'` to make it fully work
Answer: Object reference not set to an instance of an object
string conString = ConfigurationManager.ConnectionSteings[constr]. ConnectionString;


CONSULTA DATATABLE CODEIGNITER - INNER JOIN

Question: Olá!
Estou utilizando dataTable no codeigniter e realizando uma consulta através do campo search
Vendo a consulta abaixo, funciona bem quando se trata de consulta dentro da mesma tabela tb_pagamento.
Agora quero consultar o nome do operador nesta mesma query. Porem, na tabela tb_pagamento só tenho o ID do operador (operador_id), onde o nome do operador encontra-se na tabela tb_operador
tb_operador
'id'
'nome'
Veja a consulta:
var $tabela      = 'tb_pagamento';
var $tb_operador = 'tb_operador';

var $column_order = array('id', 'empresa', null);
var $column_search = array('id', 'empresa', 'nome_cliente', 'dt_pagamento', 'valor_pagamento', 'operador_id');
var $order = array('id' => 'asc');

private function get_query() {
    $this->db->from($this->tabela);
    $i = 0;
    foreach ($this->column_search as $item) {
        if($_POST['search']['value']) {
            if($i === 0) {
                $this->db->group_start();
                $this->db->like($item, $_POST['search']['value']);
            } else {
                $this->db->or_like($item, $_POST['search']['value']);
            }
            if(count($this->column_search) - 1 == $i){
                $this->db->group_end();
            }
        }
        $i++;
    }

    if(isset($_POST['order'])) {
        $this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
    } else if(isset($this->order)) {
        $order = $this->order;
        $this->db->order_by(key($order), $order[key($order)]);
    }
}

Answer: Faz desse jeito aqui na sua classe Model, já tive esse problema e resolvi com isso.
private function _get_datatables_query($term = '') {

    $column = array('p.nome', 'p.cargo', 'f.datap', 'f.datav', 'f.status', 'f.fatura_id');
    $this->db->select('*');
    $this->db->from('pessoa as c');
    $this->db->where('f.pessoa_id = p.id');
    $this->db->join('fatura as f', 'f.pessoa_id  = p.id', 'left');
    $this->db->like('p.nome', $term);
    $this->db->or_like('f.datap', $term);
    $this->db->or_like('f.datav', $term);
    $this->db->or_like('f.status', $term);

    if (isset($_REQUEST['order'])) { // here order processing
        $this->db->order_by($column[$_REQUEST['order']['0']['column']], $_REQUEST['order']['0']['dir']);
    } else if (isset($this->order)) {
        $order = $this->order;
        $this->db->order_by(key($order), $order[key($order)]);
    }
}

function get_datatables() {
    $term = $_REQUEST['search']['value'];
    $this->_get_datatables_query($term);
    if ($_REQUEST['length'] != -1)
        $this->db->limit($_REQUEST['length'], $_REQUEST['start']);
    $query = $this->db->get();
    return $query->result();
}

function count_filtered() {
    $term = $_REQUEST['search']['value'];
    $this->_get_datatables_query($term);
    $query = $this->db->get();
    return $query->num_rows();
}

public function count_all() {
    $this->db->from($this->table);
    return $this->db->count_all_results();
}

Comment: Realmente funcionou, obrigado.


How to add email address in header (from field) in wp_mail

Question: I have created contact us form for users where user can add their email address and name. I wish to add these name and email address field in wp_mail headers.
I am using following code.
$headers = 'From: My Name <email@example.com>' . "\r\n";
wp_mail($to, $subjects, $message, $headers); // not working
wp_mail($to, $subjects, $message ); // working
I think this happening is because my From: address doesn't match to the domain i'm  sending the email from. But is there any way for me to accomplish above using wp_mail.
I am getting following debugging information using smtp debug

2017-02-12 13:48:40 CLIENT -> SERVER: QUIT
2017-02-12 13:48:40 SMTP -> get_lines(): $data is ""
2017-02-12 13:48:40 SMTP -> get_lines(): $str is  "* ..* Service closing transmission channel
                                      "
2017-02-12 13:48:40 SERVER -> CLIENT: * ..* Service closing transmission channel
2017-02-12 13:48:40 Connection: closed
Answer: Try this:
$headers = array(
  'From: My Name <email@example.com>'
);
$headers = implode( PHP_EOL, $headers );
wp_mail( $to, $subjects, $message, $headers );

PHP_EOL will add the proper line break based on the system it's on (where \r\n is for Windows, \n is for Unix). Using implode() will make sure it's only added if needed. In this case, you're only sending one header so the line break isn't neaded anyways. But if you want to send more headers:
$headers = array(
  'Bcc: email@example.com',
  'From: My Name <email@example.com>',
  'Reply-To: email@example.com'
);
$headers = implode( PHP_EOL, $headers );
wp_mail( $to, $subjects, $message, $headers );

Comment: Hi Joe thanks for reply.  I tried your code but i am receiving same error. I from email i wish to set may be anything like gmail,rediffmail, or any other and my server email address is from another domain. may be this is causing issue. if you have any input on this please share.
Comment: Are you using any SMTP plugin or authentication? The `wp_mail` code I provided is correct assuming those variables are set; so, the issue is somewhere further down the line.


OOP Design Player and AI Controlled Unit. dynamic_cast?

Question: Lets say I have a Actor type, which can be any placeable object on my Game Level.
I also have Unit which is a child class of Actor. A Unit can be either a player or a AI controlled hero.
And Unit also got 2 child classes: Player (the player) and Hero (AI controlled unit).
In the Unit class, there will be movement info, rotation, and other general settings which will be needed for both Player and Hero. In the child classes AI will have different and more functions than the player.
Right now I'm facing the following problem:
A function only accepts Actor as parameter (e.g. OnOverlap(Actor a*))
but OnOverlap() should only do something if it is a Unit class (hero or player).
Therefore I would need something like instanceof() from Java in C++.
A workaround would be either to use dynamic_cast, but I'm not sure if thats a good idea for performance. Or use virtual, but this won't work when Hero has more functions than Player.
Or should I attempt a whole new OOP design?
Comment: Use virtual, that's what it's for.  I don't follow your logic that it "won't work" if hero has more functions than pkayer.  With OOP sometimes you will use virtual, and sometimes (hopefully rarely) you have to downcast, using something like `dynamic_cast`
Comment: my engine actually provides a "GetClass" method:
if (unit->GetClass()->IsChildOf(APlayerCharacter::StaticClass()))
but i'm still curious for other solutions :>
Answer: I'd say that a dynamic_cast is code smell. Not necessary bad per se, but a sign that something might be going wrong with your design.
One of the important concepts in OOP is polymorphism: the idea that objects behave differently depending on their type, and that this behavior is encapsulated, hidden behind an interface. If you explicitely check the type of an object to change the logic you want to apply to it, then you're violating polymorphism.
Now virtual methods aren't that great either, they indeed incur runtime costs, and can sometimes bring too much complexity to the table. C++ makes virtual methods the exception, not the default, I believe for these very reasons.
One thing you should know is that virtual methods are only one kind of polymorphism, called dynamic polymorphism. There's another way to get different behaviors depending on a type that is less impeding for the runtime: static polymorphism, AKA template metaprogramming. But this isn't really helping on the complexity side.
Now what you really should do in this case is treat separate things separately. You probably want to have this OnOverlap() method on Units for a reason: let's say you're doing collision check on Units only, not all Actors. Then maintain a separate list of Units, and have that OnOverlap() method non-virtual on the Unit class. Thinking this way is often key.
Comment: At the moment the OnOverlap function is used for a Mesh. These function is predefined by my Engine, where the parameter must but the parent function "Actor". So if any Actor collides with the Mesh, the function is called. In this case for me i see no other solution, than getting the instance of the Actor object to know if its a player of just something else
Comment: @Sleicreider If this is your custom engine, I don't see what prevents you from changing `OnOverlap()`'s signature? If you can't for some reason, a workaround is to make sure you call this on `Units` only (once again, by having a dedicated list) and use a good'ol `static_cast`. If you do that, make sure you check the type at least in debug builds.
Comment: But yeah, this works in some cases, but doesn't in others, YMMV. Sometimes polymorphism *is* the solution.
Answer: This technique is called Run-Time Type Information (RTTI), and checking if the output of a dynamic_cast is NULL is a valid implementation.
Another method is to #include <typeinfo> and use typeid(*a).name() to get the string name of a's type.
Answer: The need to use dynamic_cast is often (though not always) a sign that you have a design flaw. In this case, I think you do.
Without further comment on the overall design of the architecture you've described, I would say using virtual methods is the right approach. Have OnOverlap takes it's actor and call an OnOverlapped method on the actor, perhaps giving it a pointer to the thing executing the initial OnOverlap method (it's not clear from your question what that is(*)).
void X::OnOverlap (Actor * actor) {
  actor->OnOverlapped(this);
}

OnOverlapped is itself virtual. This allows you to "do the right thing" in the case of an actor unit, but do nothing or some other default behavior everywhere else. You are correct that in this case that means you can only work with the public API of Actor. You'd have to move anything requiring Player's additional methods into the Player implementation of OnOverlapped. If you really think you cannot do that for some reason, you should perhaps consider an alternative design at a higher level (and may need to edit your question to provide more details about your architecture).
(*) My initial read of your question made me think OnOverlap is not a method of Actor already; that it was part of something unrelated. If it is part of Actor, you may be instead interested in a pattern called double dispatch, which can be used for this sort of "collision handling" type of problem, and is also a technique using dynamic dispatch (virtual)).
Answer:
These function is predefined by my Engine, where the parameter must
  but the parent function "Actor". So if any Actor collides with the
  Mesh, the function is called. In this case for me i see no other
  solution, than getting the instance of the Actor object to know if its
  a player of just something else

A simple virtual function in the Actor base class can be a noop. Override it in Unit class, and specialize it even more in Hero and Player if needed. Non-Unit Actor's will call an empty method. Cleaner than RTTI and the instanceof idiom.
It is ok to have a default base implementation that expects to be overridden by specialized descendants. That is the point of abstract base classes, except in this case you are providing a default implementation that does nothing. The idea is that you are dispatching the "DoCollision" message (a virtual function in C++). You don't care which classes handle it or how. Just that the object has the DoCollision compile-time "interface" and that you dispatched it correctly.
Comment: Ok, but for the `Hero` and `Player` class? Ofc they share some functions which will do different things, therefore I would use `abstract` functions in `Unit`, but if `Hero` has an additional function, I would need to know if the `Unit` is a `Hero` to use this special function and then `cast` the `Unit` to `Hero
Comment: No, you don't have to cast it, you can call the special function from Hero's DoCollision function.


How can I move certain words/phrases in the title of a Lilypond score vertically?

Question: In the title section of a Lilypond score, I would like a certain word to be placed further down than the rest of the text (in my specific case, I'm using a font for a certain word where the font makes it look like the word is placed higher up than the other words).
<code>title = \markup
    {
        "I want"
        "THIS"
        "word to be further down"
    }
</code>
Answer: It looks like there is a raise keyword that might do the trick:
<code>\markup {
  C
  \small
  \bold
  \raise #1.0
  9/7+
}
</code>
Comment: That did the trick! I used it together with negative values to *lower* the text.


Create dynamic strings inside a for loop to generate multiple strings

Question: I'm working on a Python(3.6) project in which I need to create some strings on the base of some input parameters.
Here's my code:
def generate_multi_svc_config(data):
    no_of_svc = int(data['configuration']['no_of_svc'])
    deployments = ''''''
    services = ''''''
    for var in list(range(1, no_of_svc + 1)):
        services = services + '''\n
apiVersion: v1
kind: Service
metadata:
  name: {}
  labels:
    app: {}
spec:
  ports:
  - port: {}
    name: {}
  selector:
    app: {}
---
'''.format(data['configuration']['svc' + str(var)]['name'],
           data['configuration']['svc' + str(var)]['name'],
           data['configuration']['svc' + str(var)]['versions']['v1']['port']['port'],
           data['configuration']['svc' + str(var)]['versions']['v1']['port']['name'],
           data['configuration']['svc' + str(var)]['name'])
        print(services)
        deployments = deployments + '''\n
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: {}
  labels:
    #Project ID
    app: {}
spec:
  #Run two instances of our application
  replicas: {}
  template:
    metadata:
      labels:
        app: {}
    spec:
      #Container details
      containers:
        - name: {}
          image: {}
          imagePullPolicy: Always
          #Ports to expose
          ports:
          - containerPort: {}
            name: {}
---
'''.format(data['configuration']['svc' + str(var)]['name'] + '-' + 'v1',
           data['configuration']['svc' + str(var)]['name'],
           data['configuration']['svc' + str(var)]['replicas'],
           data['configuration']['svc' + str(var)]['name'],
           data['configuration']['svc' + str(var)]['name'],
           data['configuration']['svc' + str(var)]['versions']['v1']['image'],
           data['configuration']['svc' + str(var)]['versions']['v1']['port']['port'],
           data['configuration']['svc' + str(var)]['versions']['v1']['port']['name'])
    print(deployments)

So, when I pass no_of_svc = 2 it should create 2 service strings and 2 deployments string.
But it created the first entry in services for twice and all others for once.
I don't know why it's creating the first service string twice?
Here's the example output:
apiVersion: v1
kind: Service
metadata:
  name: ratings
  labels:
    app: ratings
spec:
  ports:
  - port: 8080
    name: ratings-port
  selector:
    app: ratings
---

apiVersion: v1
kind: Service
metadata:
  name: ratings
  labels:
    app: ratings
spec:
  ports:
  - port: 8080
    name: ratings-port
  selector:
    app: ratings
---

apiVersion: v1
kind: Service
metadata:
  name: reviews
  labels:
    app: reviews
spec:
  ports:
  - port: 8081
    name: reviews-port
  selector:
    app: reviews
---

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: ratings-v1
  labels:
    #Project ID
    app: ratings
spec:
  #Run two instances of our application
  replicas: 3
  template:
    metadata:
      labels:
        app: ratings
    spec:
      #Container details
      containers:
        - name: ratings
          image: gcr.io/ml001-208807/node-app:0.0.1
          imagePullPolicy: Always
          #Ports to expose
          ports:
          - containerPort: 8080
            name: ratings-port
---

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: reviews-v1
  labels:
    #Project ID
    app: reviews
spec:
  #Run two instances of our application
  replicas: 2
  template:
    metadata:
      labels:
        app: reviews
    spec:
      #Container details
      containers:
        - name: reviews
          image: gcr.io/ml001-208807/node-app1:0.0.1
          imagePullPolicy: Always
          #Ports to expose
          ports:
          - containerPort: 8081
            name: reviews-port
---

Comment: Those large multiline strings really make your code hard to read. Move them to some module-level constants. Might also help readability to define `tmp = data['configuration']['svc' + str(var)]`.
Comment: .... then you might notice that the `print(deployments)` line is _outside_ of the loop, while `print(services)` is inside. Could this be the problem?
Comment: both are inside the loop!
Comment: Nope, they are not. Check the indentation. Also, this explains why the services are printed repeatedly, but the deployments are not
Comment: Also, note that I rolled back your question; as I said, chaning the code in your question invalidates all the answers. If you want to provide updated, do so _below_ your original code.
Answer: Because on each iteration you're printing an actual content of services variable, that, in turn, contents currently formed service alongside all previously added.
Simply put, your loop works like this:
no_of_svc = 2
services = ''
for var in range(1, no_of_svc + 1):
    services += "{} service\n".format(var)
    print(services)

So, on the second iteration, services contains first and second service. As a result, the first service has been printed on both iterations.
If you need to save all values to the services variable as a string, simply print only current value before appending:
no_of_svc = 2
services = ''
for var in range(1, no_of_svc + 1):
    service = "service {}\n".format(var)
    print(service)
    services += service

Comment: @AbdulRehman Nope, you did not. You just changed `services = services + ...` to `services += ...`, which is exactly the same thing. Also, please do NOT change the code in your question. If you want to provide an update, do so BELOW your original code, otherwise you invalidate all the existing answers and comments.
Comment: Hi @OlegRybalchenko, I have changed my code according to your solution but still the first `service`  created twice.
Comment: So, what I need to change? please!
Comment: Hi @tobias_k, now I have updated my code, does it indented correctly?
Comment: @AbdulRehman No, you moved _both_ print statements _inside_ the loop instead of outside.
Answer: The problem seems to be that you append to services and deployments in each iteration of the loop, but while you print deployments only at the end, you print services in each iteration of the loop, hence printing the entry that was added in the first iteration twice.
Due to the large multiline-strings this is hard to see in your original code. I suggest extracting those strings to some constants on module-level to make the loop body much easier to read. Also, you can define some temporary variable to shorten the repeated dict lookup:
template1 = '''\n
apiVersion: v1
... more lines ...
    app: {}
---
'''
template2 = '''\n
apiVersion: extensions/v1beta1
... more lines ...
            name: {}
---
'''
def generate_multi_svc_config(data):
    no_of_svc = int(data['configuration']['no_of_svc'])
    deployments = ''
    services = ''
    for var in list(range(1, no_of_svc + 1)):
        d = data['configuration']['svc' + str(var)]
        services += template1.format(d['name'],
           d['name'],
           d['versions']['v1']['port']['port'],
           d['versions']['v1']['port']['name'],
           d['name'])
        deployments += template2.format(d['name'] + '-' + 'v1',
           d['name'],
           d['replicas'],
           d['name'],
           d['name'],
           d['versions']['v1']['image'],
           d['versions']['v1']['port']['port'],
           d['versions']['v1']['port']['name'])
    print(services) # <- move this line here, outside the loop
    print(deployments)

Also, if you want to insert certain values at multiple places in your template string, you can use placeholders like {0} or {1}, so you don't have to pass d["name"] three times.
>>> template = "first {0} second {1} first again {0}"
>>> template.format("foo", "bar")
'first foo second bar first again foo'


What is a balk?

Question: I am a casual baseball fan, and by that I mean exclusively watching through Jomboy breakdown videos.
In a recent video Manager WANTS a balk to be called, a breakdown, he starts off with saying:

We've got another balk breakdown. "Did he balk?" "Did he not balk?" "What's a balk?" "What are all these rules?"

I'm exactly in line with these exclamations - I'm not even sure what a balk is. Something to do with actions the pitcher isn't allowed to do before or during a pitch?
In the video, the play involves the pitcher stepping behind the plate, chasing after a runner, and then a bunch of passes in an attempt to tag the runner. After the play finishes, the opposing coach exclaims, "He balked!" seemingly in an attempt to invalidate the tag.
I searched for "balk" on YouTube and came up with this discussion of another play What constitutes a balk? where they explain what constitutes a balk, but they talk about terms like breaking hands, clearing the rubber, and overall this seems like a more refined discussion once you already understand what a balk is.
In a way that a casual baseball fan could appreciate, what is a balk? When would a pitcher want to balk? When would a pitcher want to avoid a balk?
If I can take it a step further, what motivated the balk rule in baseball - what kind of behavior is it trying to prevent?
Comment: There's a great copypasta poking fun at how inscrutable the balk rule is for a lot of people: https://www.reddit.com/r/copypasta/comments/cil904/do_not_do_a_balk_please/
Comment: (completely irrelevant so probably will and should get deleted, but: Jon Bois also makes great baseball videos on youtube, and people tweet weird baseball happenings at him with the phrase "watching baseball" so this search always has good stuff in it https://twitter.com/search?q=jon_bois%20watching%20baseball&src=typed_query )
Comment: @crass_sandwich This is the correct answer.
Answer: Balk
From MLB.com

A balk occurs when a pitcher makes an illegal motion on the mound that the umpire deems to be deceitful to the runner(s).

Exactly what constitutes a balk is summed up in section 8 of the MLB rules, which describes a legal pitching delivery.

Section 8 PDF.
I would describe a balk as faking a pitch to draw the runner off base and attempt a pick-off.  Note that the actual balk rules (standard secondary school rules) are more complicated than that.  For example, it is also a balk to fake a pick-off and then throw the pitch.  The exact opposite of the more common form.  Which is why they talk about illegal motion and deceit.
Baserunning
I'll step back and explain some baseball on the theory that people who don't know what a balk is may not know how baserunning works.  This may or may not be known to the asker already.  Anyone who is confident that they understand how baserunning, particularly stolen bases, works may skip this.  But I would like to get to a base understanding.
When a runner is on base (first, second, or third), the runner may stop touching the base and take a "lead" on running to the next base.  A pitcher may throw to the current or next base to "pick off" the runner.  If the runner is "tagged" (touched by someone holding the ball) while not touching the base, the runner is out.
It is not uncommon for a runner to start in motion as the pitcher is throwing the pitch.  This has some risks.

If the runner starts too soon, the pitcher can pick off the runner rather than pitch.
If the batter hits the ball and a fielder catches it on the fly (not on a bounce), the batter is out and the runner needs to return to the original base.  If a defensive player tags either the base or the runner before the runner returns to the base, the runner is out as well.
If the batter does not make contact with the ball, the catcher may throw the ball to try to catch the runner off base.  If the runner is tagged while off base, the runner is out.  This is called "caught stealing".

The advantage of going in motion early is that it allows the runner to go farther if the batter hits the ball such that it is fielded after a bounce.  For example, a runner might be able to score from second base on a single (the hitter is only able to reach first base), because the runner doesn't have to drop the bat, start in motion, and begins with a lead.  And of course, a "stolen base" is when the hitter does not make contact and the defensive team can't tag the runner before the runner reaches the next base.  So two ways early motion may help the baserunner.
Why?
If pitchers could balk legally, then they should balk whenever there is a baserunner.  So before every pitch, they should fake a pick-off move until the runner is moving back to the base.  Then, while the runner is moving back to the base, they should throw the pitch.  Apparently the people who were setting the rules for baseball in 1898 found games played that way to be boring (or possibly ungentlemanly, as John Bollinger suggests).  So they made the balk rule against such behavior.
Over time, the balk rule has evolved into its modern form which prescribes how a pitcher may pitch or attempt to pick off a runner.  An observant runner may rely on certain motions indicating the start of the pitch and start in motion without worrying about the pitcher attempting a pick-off.
An alternative would be to take away the pitcher's ability to pick off runners.  But in that case, the runner could just move almost to the next base.  Which would increase the risks of a line out or fly ball but otherwise overwhelmingly favor the offensive team.
You might suggest that an alternative would be to require the runner to stay on the base rather than take a lead (or within a fixed distance).  Then there would be no pick-off move and no need for a balk rule.  But enforcing that would have been annoying, particularly before instant replay.  Coaches/pitchers would be constantly complaining about runners who started running too early and it would be hard for the runners to know exactly when they could leave the base.  Basically it would tend to lead to a lot of rules lawyering, which most people don't find fun.
By contrast, a balk happens before the play starts and is dependent only on the behavior of the pitcher.  And of course at that time, everyone would be looking at the pitcher to see when play starts.  So it's easier to enforce rules on the pitcher.
As stands, the possibility of a pick-off or a stolen base adds excitement to the game.  Balk rules are a necessary evil for that excitement.
Comment: I'm looking forward to your explanation of the _infield fly rule_ :-)
Comment: It should not be overlooked that baseball was originally conceived (and is till sometimes referred to) as a "gentleman's game".  Deceptive behavior is contrary to that ethos.  I'm inclined to think that that has more to do with the original motivation for the balk rules than any judgement about how exciting gameplay would be one way *vs.* the other.
Comment: Minor nitpick in the baserunning section:  "If the fielder gets the ball to another defensive player who <...>" should just say "If any defensive player <...>". If the first baseman catches the ball on the fly, they don't need to get the ball to a different player in order to get the runner out, they can do it themselves.
Answer: The ELI5 version of this:
A pitcher is required to do certain things in a certain way when they are in the process of releasing a pitch.  If they do not do them in the right order, or if they start doing them and get to a certain point but then stop, it is a balk.
That is because the runner may rely on the pitcher doing those things in order to determine when to start running on a steal attempt (or "runners going" situation, like 2 outs 3-2 count runner on first). If the pitcher does not do the things they are required to do, or starts to do them and then stops too late in the sequence, then it misleads  the runner.
Comment: Note - I think the accepted answer is very good and much more thorough; I add this just because it seems like it may be useful to have a simplified version.

What is a balk?


Need Help to Disable Download from a URL

Question: Is there a way to disable a user from downloading a file from a URL?
For example I have a link:
wow.mywebsitedomain.com/templates/filename.svg
I want to disable the user from downloading the filename.svg
These svg files are not just an image, they are editable designs that I have spent countless hours on each. No, I do not care if someone does a screenprint or gets a png etc, as those are not scalable, editable, vector files.
When the user clicks on a png thumbnail my actual link opens my online design editor to allow the user to customize these files, then save to my server, then purchase printed media, and they are not allowed to download any files.
I tried putting the actual files into a password protected folder on my server, but they do not open properly, and I do not want the user to have password access to this folder.
Essentially I need the link to be accessible, just not show the actual link for someone to copy and open/save/download etc.
Hopefully there is a simple solution for a non-programmer with basic html skills?
Thanks
Answer: If they can view it, they can download it. End of story. If you only want them to see a PNG, make a PNG from it and put that up
Answer: Your can do things like "disabling right-click" and stuff - it may prevent some users from downloading your file, BUT basically you cannot prevent a file which is downloaded and interpreted by the browser from being downloaded to a user's hard drive.
This is not only true for SVGs, but also for music, videos, etc.
Instead, you can convert your SVG file to a PNG on server-side, and show only the PNG to the user. Note that you have the possibility to create PNGs of different sizes on the fly - dependent on the request, user's screen resolution, etc. You can also implement caching of the generated PNGs if needed.
On how to create a PNG from SVG in PHP read here:
Convert SVG image to PNG with PHP
You can choose other raster image format, of course.
Comment: Converting to a PNG is not an option, as the SVG is the file that the user dynamically live edits the file, like doing a t-shirt design, then saves.    Is there a way to MASK the url, but still let it open the file, kinda like:

before: wow.mywebsitedomain.com/templates/filename.svg

after: wow.mywebsitedomain.com/7yXg43d3

???
Comment: Do I understand your web-application correctly?
You have a base-design (created by you), which a user may customize - i.e. modify to his/her own needs. Then he submits the modified design to the server, which processes the order.
You want that base design not to be available for download.
Am I right?
Comment: i have a code to disable right click on the thumbnails, but this is not helpful.  When the user clicks on the thumbnail, the link is to open the svg file in the web application and the link displays the actual folder etc of the file, and it can easily be copied and downloaded directly.  So to mask that link somehow to make this not possible.  Also when viewing the source code, the links is easily visible.
Comment: As I said in my answer, if they can view it, they can download it. If it's transferred to their web browser, they can save it. There is simply no way around this. If they have caching turned on, then every file they view gets saved on the hard drive already.
Comment: There actually is a way around it, but the way around is to use some sort of client-side technology (Silverlight, Flash, or a browser plugin or something of that sort) and encrypt the file and transfer it encrypted. That doesn't make it unhackable, but it brings it beyond the ability of most users to get the file. But this requires your web app to be written in the client technology. It can't be HTML/Javascript based.
Comment: One solution you may consider - generate the part which the user cannot customize as png on the fly, and let the user "draw over" the base design, so that your server accepts only user-drawn part and merges it with the base design. This however limits the customizability of base design...
Comment: From what I have heard, PHP is a script that resides on the server and is not easily referenced.  Would it be possible to write the html hyper links with a script that then links directly to a php file on my server, then the php file actually opens the file without revealing the file location?  The web application that I am using is this: code.google.com/p/svg-edit/
Comment: Hiding location is not the way to go, because a file can be saved without knowing its location, if it is opened and processed by browser. You have three ways - generate PNGs (at least partially, with base only), or use client-side technology like Java applet or Silverlight as Pete suggested... or make clear that the SVGs are copyrighted, include licence on your site and hope that your users respect intellectual property... You may start with the third option (licence+copyright notice) and launch your site, and then work on other options.
Comment: thank you all for the suggestions. I will look into the client side options.  Not sure where to start and what would be the least intrusive for a site user?
Comment: flash/flex is _probably_ the least intrusive, only iPhone/iPad users may have problems with it.
Answer: My understanding is; if you can see it, you can download it,


String to Date migration from Spark 2.0 to 3.0 gives Fail to recognize 'EEE MMM dd HH:mm:ss zzz yyyy' pattern in the DateTimeFormatter

Question: I have a date string from a source in the format 'Fri May 24 00:00:00 BST 2019' that I would convert to a date and store in my dataframe as '2019-05-24' using code like my example which works for me under spark 2.0
from pyspark.sql.functions import to_date, unix_timestamp, from_unixtime
df = spark.createDataFrame([("Fri May 24 00:00:00 BST 2019",)], ['date_str'])
df2 = df.select('date_str', to_date(from_unixtime(unix_timestamp('date_str', 'EEE MMM dd HH:mm:ss zzz yyyy'))).alias('date'))
df2.show(1, False)

In my sandbox environment I've updated to spark 3.0 and now get the following error for the above code, is there a new method of doing this in 3.0 to convert my string to a date

: org.apache.spark.SparkUpgradeException: You may get a different
result due to the upgrading of Spark 3.0: Fail to recognize 'EEE MMM
dd HH:mm:ss zzz yyyy' pattern in the DateTimeFormatter.

You can set spark.sql.legacy.timeParserPolicy to LEGACY to restore the
behavior before Spark 3.0.
You can form a valid datetime pattern with the guide from
https://spark.apache.org/docs/latest/sql-ref-datetime-pattern.html
Comment: According to the docs you linked to, you can't use 'E' for parsing date strings only for formatting date values >>> "Symbols of 'E', 'F', 'q' and 'Q' can only be used for datetime formatting, e.g. date_format. They are not allowed used for datetime parsing, e.g. to_timestamp." it's the very last thing on the page! Guess you'll have to enable legacy parsing
Answer: If you want to use the legacy format in a newer version of spark(>3), you need to set spark.conf.set("spark.sql.legacy.timeParserPolicy","LEGACY") or
spark.sql("set spark.sql.legacy.timeParserPolicy=LEGACY"), which will resolve the issue.
Answer: Thanks for responses, excellent advice, for the moment I'll be going with the LEGACY setting.  I have a workaround with Spark 3.0 by substringing out the EEE element but I've noticed a bug with how BST timezone converts incorrectly offseting by 10 hours while under LEGACY it correctly remains the same as I'm currently in BST zone.  I can do something with this but will wait till the clocks change in the autumn to confirm.
spark.sql("set spark.sql.legacy.timeParserPolicy=LEGACY")
df = spark.createDataFrame([('Fri May 24 00:00:00 BST 2019',)], ['mydate'])
df = df.select('mydate',
                to_timestamp(df.mydate.substr(5, 28), 'MMM dd HH:mm:ss zzz yyyy').alias('datetime'),
                to_timestamp(df.mydate, 'EEE MMM dd HH:mm:ss zzz yyyy').alias('LEGACYdatetime')
               ).show(1, False)

df = spark.createDataFrame([('Fri May 24 00:00:00 GMT 2019',)], ['mydate'])
df = df.select('mydate',
                to_timestamp(df.mydate.substr(5, 28), 'MMM dd HH:mm:ss zzz yyyy').alias('datetime'),
                to_timestamp(df.mydate, 'EEE MMM dd HH:mm:ss zzz yyyy').alias('LEGACYdatetime')
               ).show(1, False)

spark.sql("set spark.sql.legacy.timeParserPolicy=CORRECTED")
df = spark.createDataFrame([('Fri May 24 00:00:00 BST 2019',)], ['mydate'])
df = df.select('mydate',
                to_timestamp(df.mydate.substr(5, 28), 'MMM dd HH:mm:ss zzz yyyy').alias('datetime')
               ).show(1, False)

df = spark.createDataFrame([('Fri May 24 00:00:00 GMT 2019',)], ['mydate'])
df = df.select('mydate',
                to_timestamp(df.mydate.substr(5, 28), 'MMM dd HH:mm:ss zzz yyyy').alias('datetime')
               ).show(1, False)

+----------------------------+-------------------+-------------------+
|mydate                      |datetime           |LEGACYdatetime     |
+----------------------------+-------------------+-------------------+
|Fri May 24 00:00:00 BST 2019|2019-05-24 00:00:00|2019-05-24 00:00:00|
+----------------------------+-------------------+-------------------+

+----------------------------+-------------------+-------------------+
|mydate                      |datetime           |LEGACYdatetime     |
+----------------------------+-------------------+-------------------+
|Fri May 24 00:00:00 GMT 2019|2019-05-24 01:00:00|2019-05-24 01:00:00|
+----------------------------+-------------------+-------------------+

+----------------------------+-------------------+
|mydate                      |datetime           |
+----------------------------+-------------------+
|Fri May 24 00:00:00 BST 2019|2019-05-23 14:00:00|
+----------------------------+-------------------+

+----------------------------+-------------------+
|mydate                      |datetime           |
+----------------------------+-------------------+
|Fri May 24 00:00:00 GMT 2019|2019-05-24 01:00:00|
+----------------------------+-------------------+

Comment: you do know you can change your system's date, right?
Answer: The difference between the Legacy and the current version of Spark is subtle
for example:
spark.sql("set spark.sql.legacy.timeParserPolicy=EXCEPTION")

df = spark.createDataFrame([('12/25/2019 01:30:00 PM',),], ['Christmas'])
df.select(to_timestamp(col('Christmas'),'MM/dd/yyyy hh:mm:ss a')).show()

Outputs the following:
+----------------------------------------------+
|to_timestamp(Christmas, MM/dd/yyyy hh:mm:ss a)|
+----------------------------------------------+
|                           2019-12-25 13:30:00|
+----------------------------------------------+

However
spark.sql("set spark.sql.legacy.timeParserPolicy=EXCEPTION")

df = spark.createDataFrame([('12/25/2019 01:30:00 PM',),], ['Christmas'])
df.select(to_timestamp(col('Christmas'),'MM/dd/yyyy hh:mm:ss aa')).show()

Will raise a SparkUpgradeException
Notice we have 'aa' in the time format not just one.
According to Java Docs, which is what the to_timestamp function uses,  'aa' was always wrong, I guess the earlier version of Spark was more lenient.
So either fix the date formats or set the timeParserPolicy to 'LEGACY' as Shivam suggested.
Answer: Parsing/formatting of timestamp/date strings. This effects on CSV/JSON datasources and on the unix_timestamp, date_format, to_unix_timestamp, from_unixtime, to_date, to_timestamp functions when patterns specified by users is used for parsing and formatting. In Spark 3.0, we define our own pattern strings in Datetime Patterns for Formatting and Parsing, which is implemented via DateTimeFormatter under the hood. New implementation performs strict checking of its input. For example, the 2015-07-22 10:00:00 timestamp cannot be parse if pattern is yyyy-MM-dd because the parser does not consume whole input. Another example is the 31/01/2015 00:00 input cannot be parsed by the dd/MM/yyyy hh:mm pattern because hh supposes hours in the range 1-12. In Spark version 2.4 and below, java.text.SimpleDateFormat is used for timestamp/date string conversions, and the supported patterns are described in SimpleDateFormat. The old behavior can be restored by setting spark.sql.legacy.timeParserPolicy to LEGACY
So,Adding this spark config to your code will fix this issue :
spark.conf.set("spark.sql.legacy.timeParserPolicy","LEGACY")


Drush pm-update: How can I stop it from trying to update more recent dev releases?

Question: I'm using drush 5 to update the modules on my site.  Usually it works great.  However, when I have downloaded a dev release, even if there is no more recent point release it tries to update the dev release module to the last official "point" release.
For example, I have heartbeat-dev installed (2012-Mar-20).  Yet when I run the drush up command, it prompts me to update to heartbeat 1.0 (2011-Jun-25).
If there is a newer dev release, I want to update to that.  If there is a newer point release, I want to update to that.  But if I have a dev release and the point release is older, I don't want to update.  How can I do this?
I've been handling this manually but as the number of modules on my site grows it's getting harder to keep track of which to update and which not to update...
Answer: Basically, this sounds like a bug that should be addressed in the drush issue queue.  I'm guessing this is recent; it used to be that Drush would never go from dev to stable unless you used pm-download.  Now it is being a bit overzealous.
As a workaround, you can use the --lock option to stop Drush from updating the module at all (drush pm-update --lock=heartbeat), but this will also exclude newer dev releases as well.
Comment: I'll look into filing a bug report then.  But perhaps there is something wrong with my setup... I rolled back to Drush 4.5 and I had the same problem.  In fact, as far as I can remember I've also had this problem with Drush (user since v.3).
Comment: I located the source of the error-- On one module, the release notes information was wrong.  On another module, the version number of the dev number was wrong.  This lead me to my mistaken conclusion that drush was at issue.