Combine Async and Option monads

Question: In writing some code that works with a lot of nested async workflows lately I've found a pattern emerging that smells to me. A simple example:
let flip f x y = f y x
let slowInc x = async {
    do! Async.Sleep 500
    printfn "Here you go, %d" x
}

let verboseFun inp = async {
    match List.tryFind (flip (>) 3) inp with
    | Some x -> do! slowInc x
    | _ -> ()
}

verboseFun [1..5] |> Async.RunSynchronously

The 'verboseFun' to me seems verbose but I can't think of a way to combine the Option and Async monads so it can be rewritten without the pattern match. I was thinking something like
let terseFun inp = async {
    inp
    |> List.tryFind (flip (>) 3)
    |> Option.iterAsync slowInc
}

It just seemed to me that it's highly likely I just don't know what building blocks are available to achieve this.
EDIT: Extra clarification after Tomas' answer.
I was trying to adapt what would be trivial to me if everything was synchronous, e.g.,
let terseFun inp =
    inp
    |> List.tryFind (flip (>) 3)
    |> Option.iter someSideEffectFunciton

to become part of nested async workflows. Originally I was thinking "just chuck a do! in there" so came up with
let terseFun inp = async {
    inp
    |> List.tryFind (flip (>) 3)
    |> Option.iter (fun x -> async { do! someSideEffectFunciton x })
    |> ignore
}

But it immediately smelled wrong to me because VS started demanding the ignore.
Hope this helps clarify.
Comment: A more generic solution involves using Monad Transformers, though in F# they are not straightforward, you can have a look at FsControl in https://github.com/gmpl/FsControl/blob/master/FsControl.Core/Samples/Haskell.fsx#L638
Answer: The ExtCore library has a bunch of helper functions that let you work with asynchronous computations that return optional values, i.e. of type Async<'T option> and it even defines asyncMaybe computation builder for working with them.
I have not used it extensively, but from a few simple experiments I did, it looks like it is not as nicely integrated with the rest of F#'s async functionality as it perhaps could be, but if you want to go in this direction, ExtCore is probably the best library around.
The following is using the iter function from AsyncMaybe.Array (source is here). It is a bit ugly, because I had to make slowInc be of type Async<unit option>, but it is pretty close to what you asked for:
let slowInc x = async {
    do! Async.Sleep 500
    printfn "Here you go, %d" x
    return Some ()
}

let verboseFun inp =
  inp
  |> List.tryFind (fun x -> 3 > x)
  |> Array.ofSeq
  |> AsyncMaybe.Array.iter slowInc
  |> Async.Ignore

Aside, I also removed your flip function, because this is not generally recommended style in F# (it tends to make code cryptic).
That said, I think you don't really need an entire ExtCore library. It is hard to see what is your general pattern from just one example you posted, but if all your code snippets look similar to the one you posted, you can just define your own asyncIter function and then use it elsewhere:
let asyncIter f inp = async {
  match inp with
  | None -> ()
  | Some v -> do! f v }

let verboseFun inp =
   inp
   |> List.tryFind (fun x -> x > 3)
   |> asyncIter slowInc

The great thing about F# is that it is really easy to write these abstractions yourself and make them so that they exactly match your needs :-)

Combine Async and Option monads


Using K-fold cross validation to select a model's parameters

Question: I think I understand completely the concept of cross validation, but there is one aspect I've never seen detailed. Let's assume I have a logistic regression model with four parameters I want to train. I perform k-fold cross validation with k, let's say, 5, over my training data, and it yields 5 different sets of four values with 5 different associated error values. How should I then select which model to use? A weighted combination of the five models? The best one? What is the standard approach to do so and (if there is any) what are its mathematical foundations?
Thank you very much in advance.
Answer: Cross-validation just gives you an estimate of your out-of-sample risk. It doesn't produce a better model. To get the most precise estimate of your coefficients, you should use all of your data.
Answer: Actually, I've already understood how to do so. Just in case someone stumbles upon this question: cross validation can serve as a parameter tuning tool.To tune a model's parameters using K-fold cross validation you train and test each model K times against the K possible data combinations and average their out-of-sample error. The one that gets the best result will be the model that (probably) generalizes better.
Comment: I'm concerned about the last sentence. How do we know that the parameters trained on the fold with the lowest error generalizes the best?


metric on clustering of correlation matrix using silhouette score

Question: Given a correlation matrix $A_n$, a metric $\|\cdot \|_2$ and a clustering $k$, you can calculate the silhouette score (https://scikit-learn.org/stable/modules/generated/sklearn.metrics.silhouette_samples.html). Then define a $score = silhouette.mean/silhouette.std$. If you have two different clustering's $k_1$ and $k_1$ s.t. $score(k_1)$ < $score(k_2)$ will it be true that $score(k_1) < score(k2)$ when $A_n$ is embedded inside any $A_m$ where $n<m$?
Answer: It is easy to se that - choose 4 points on the real line such that they form 2 clusters. In $\mathbb{R}^2$ choose a $y$ and choose an element in each of the clusters. Choose $-y$ for the other 2 elements. Make $y$ sufficiently large and you get the opposite clustering.
edit - proof:
Let the distance between cluster 1 and cluster 2 in $\mathbb{R}$ be $r$. Let $x_1$, $x_2$ belong to cluster 1.  Let $x_3$ and $x_4$ belong to cluster 2.
In $\mathbb{R}^2$ choose $y>r$ then also $2y > r$ and choose points $x_1'=(x_1, y)$, $x_2'=(x_2,-y)$, $x_3'=(x_3, y)$ and $x_4'=(x_4, -y)$
$\implies 0 < || x_1' - x_3' ||  < ||x_1' - x_2' || = || x_1' - x_3' + x_3' - x_2' || \le || x_1' - x_3'|| + || x_3' - x_2' ||  = r + 2y
\Leftrightarrow 0 < r < 2y \le r + 2y$
Also:
$0 < || x_1' - x_3' ||  < ||x_1' - x_4' || = || x_1' - x_3' + x_3' - x_4' || \le || x_1' - x_3'|| + || x_3' - x_4' || = r + 2y $


How to show some fields with data using fetchAll in zend framework?

Question: In a table say users i have 5 fields i want to show 3 fields with all data using fetchAll in zend framework. how to do that ?
My code is
<code>$astrology = new Application_Model_DbTable_Astrology();
$row = $astrology->fetchAll($astrology->select());
$rowArray = $row->toArray();
</code>
i want to show id,user_name,create_date field ..
Comment: are these database fields or just columns in an HTML table?
Answer: Use $astrology->select()->from($tablename, array(columns)); You can specify fields in from method
http://framework.zend.com/manual/en/zend.db.select.html


Perl Inserting at incremented points in a sequence

Question: I have a problem I am hoping someone could help with.
Using the following...
 my @sequence = (1..9);
 my $newSequence = join " - ", @sequence;

...I can print a hyphen seperated sequence of numbers 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9
The thing I am having problem with, and do not quite know the best logical way to solve, is a loop to increment the position of a variable string in the number sequence on each iteration (to produce the kind of output shown below).
my $varString = "DOG"

The output I am looking to achieve:
DOG - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9
1 - DOG - 3 - 4 - 5 - 6 - 7 - 8 - 9
1 - 2 - DOG - 4 - 5 - 6 - 7 - 8 - 9
1 - 2 - 3 - DOG - 5 - 6 - 7 - 8 - 9
1 - 2 - 3 - 4 - DOG - 6 - 7 - 8 - 9
1 - 2 - 3 - 4 - 5 - DOG - 7 - 8 - 9
1 - 2 - 3 - 4 - 5 - 6 - DOG - 8 - 9
1 - 2 - 3 - 4 - 5 - 6 - 7 - DOG - 9
1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - DOG

What would be the best way to go about doing this?
Your help with this would be much appreciated, many thanks
Comment: Insert at 0+0, then at 10+1, then at 20+2... in other words, you'll have two counters, one that is incremented in tens, the other in ones.  Or even one counter that increments by one each time, and insert at `$c*10+$c`, for example.
Answer: Am I missing something? Surely this is all that is required.
use strict;
use warnings;

my @sequence = 1 .. 9;

for my $i (0 .. $#sequence) {
  my @newseq = @sequence;
  $newseq[$i] = 'DOG';
  print join(' - ', @newseq), "\n";
}

output
DOG - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9
1 - DOG - 3 - 4 - 5 - 6 - 7 - 8 - 9
1 - 2 - DOG - 4 - 5 - 6 - 7 - 8 - 9
1 - 2 - 3 - DOG - 5 - 6 - 7 - 8 - 9
1 - 2 - 3 - 4 - DOG - 6 - 7 - 8 - 9
1 - 2 - 3 - 4 - 5 - DOG - 7 - 8 - 9
1 - 2 - 3 - 4 - 5 - 6 - DOG - 8 - 9
1 - 2 - 3 - 4 - 5 - 6 - 7 - DOG - 9
1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - DOG

Update
Here's an alternative for people who are preoccupied about increasing the idle time time of their CPU. I offer it because it is clearer as well as faster than either solution presented so far. The output is identical.
use strict;
use warnings;

my @sequence = 1 .. 9;

for my $i (0 .. $#sequence) {
  local $sequence[$i] = 'DOG';
  my $s = join(' - ', @sequence);
}

Comment: @gbtimmon: The way it works is *code*, (*run*, *optimize* if necessary)*. Not *optimize*, *code*, *run*
Comment: You are copying a lot of arrays for no reason there.
Comment: @gbtimmon I challenge you to do better. The above code does roughly *O(n²)* `SV` copies (the array copy), and `O(n²)` `SV*` copies (`@newseq` elements as arguments for `join` on the stack), plus some irrelevant linear factors. I can't access chorobas solution because I don't know how slicing is implemented, but if the ranges in the slice produce `SV`s, then we are definitively in the same complexity.
Comment: @Borodin \*Rolls eyes\* That make sense for developing large processes and programs when complexity is high and you are trying to keep the development complexity to a minimum. Writing simple functions like this that unoptimized is just lazy. An equally easy (but optimized) solution is on this page already and easy to find. If it does not take very much extra brain power to start optimized, why not do it?
Comment: @gbtimmon: I am sorry about your eye problem, but I completely disagree. Optimizing *everything* will take substantially more time than it saves unless the data you are dealing with is enormous. Laziness is famously a virtue when it comes to programming, and high-level languages themselves are a product of that laziness. You shouldn't even consider using Perl if you look for anything other than the most clear solution.
Comment: Again laziness is a virtue in the right context. You should know -- just because someone else said something in a clever way does not make it universally true so stop quoting quipy sayings at me. You are right optimizing everything will take substantially more time, but coding without understanding the implications of what you are doing is a good way to write bad code.  And the difference between what choroba suggested and what you suggested is someone taking the time to think about what is actually being done, that is all.
Comment: @gbtimmon: Yours is a very old-fashioned way of working. I'm afraid you couldn't be more wrong, but I am sure you aren't going to be persuaded otherwise so I shall say no more.
Comment: Im sorry you feel insulted, but there is nothing 'old fashioned' about what I suggest. I'm just going by the basics I learned in my (rather recent) software design classes, and 5 years experience in the field.
Answer: A solution using array slices:
#!/usr/bin/perl
use warnings;
use strict;
use feature qw(say);

my $size = 9;
my @sequence = 1 .. $size;
for my $pos (0 .. $size - 1) {
    say join ' - ', @sequence[ 0 .. $pos - 1 ],
                    'DOG',
                    @sequence[ $pos + 1 .. $size - 1 ];
}


How to configure non-admin accounts to install updates of non-microsoft applications using Active Directory?

Question: How to configure non-admin users to allow them to install updates for Java and Adobe Acrobat Reader (or any other application which may need such privileges) without needing for administrator password on Windows 7. Updates for Microsoft products install without problems.
This can be Active Directory (Windows 2003) solution, or computer based (employable through GPO or login script).
Edit:
Just to add some information. I know Secunia offers Secunia CSI that integrates with WSUS and allows other software updates deployed thru it. But it's pay software which is something I would like to avoid.
Also giving an admin/power-user rights is not something i want to have since then it opens up additional security holes.
Answer: Package the updates as MSI with your favourite packager (if they're not already in a suitable MSI format) and deploy them using Active Directory's built-in deployer. This will not require any administrative rights on the clients. It can become tedious though, there's where patch management and software distribution suites come into play.
Also as a side note, Power User is basically the same as Administrator when it comes to security, so it's not really any better than Administrator.
Comment: +1 for MSI/GPO software deployment. However I must take issue with "Power User is basically the same as Administrator". I'd personally turn that round and say 'Power User is basically the same as a standard user', which it is, because the only difference is that a power user has modify access to a few areas of the file system and registry that standard users normally only have read access to. Administrator has way more rights that a power user. Most software can be installed with power user rights though, with exception to anything that attempts to alter or create services.
Comment: Thanks ^^ Well, most local elevation exploits works fine as Power User, that's why I'm bundling it in the "no go" zone. It might be true though that it prevents "normal" users from changing too much stuff, I wouldn't know, but installing software is definitely a scary part that easily lead to a compromised system in my opinion.
Answer: I set their systems to be managed in AD and then I just right click the machine name, click on manage, and then temporarily change their permissions. I give them 2-4 hours to do what they need to, and then I set it back.
You can set up group policy and apply it to a new OU and put their computers in there.  The only problem is that I am unable to do so with Windows 7 users.  I manually have to touch the local gp on their machines. I put it as part of my build checklist or change the gp when I am working on their system.
Apparently, I will be able to set it up for the W7 machines when replacing my DC with Windows 2008 R2.
My two cents.
Comment: It's a nice idea but it also means I will have to trust them which makes it a bit of pain :-)
Answer: Well, you really do need to give the person doing this admin rights on each local PC. You might get by with power user rights (depending on the software that needs updating), but it's unlikely.
Here is how I would approach this...
Create user account(s) on your domain for the people that are going to do this work, create a group called something like 'Local Admin Rights', add all the new accounts to the group.
Using Active Directory Users and Computers, create a policy on the computers' containers, and implement a restricted groups policy to force the domain group 'Local Admin Rights' to be a member of each computers 'Administrators' group. - take care to place the policy so that it only affects the computers you are interested in (i.e. take care to avoid this server taking effect on your servers).
Comment: Well it's not what I look for. I used to have all people admins on their computers and it was working fine but they installed some stuff i didn't wanted, and did some unwanted things. So i would prefer to keep them simple users with ability to install updates to software I specify. I do know about Secunia offering an add-on to WSUS but it's pay solution.
Comment: Ah okay. I somehow got the impression you wanted tech staff to be able to install software on all desktop PCs. We deploy almost all our software (and updates) via the method Oskar describes.


Longitudinal measures mixed model in lmer in R

Question: I would like to build a mixed model using the lme4 package in R.
The study design is like this: We have measured the change in a variable over time in mice under different Diets. The mice under different diets are different, not the same. We would like to see which condition (Diet) causes a significant change in the variable compared to control diet. The structure of the data can be seen below:
'data.frame':   784 obs. of  4 variables:
 $ SampleID: Factor w/ 98 levels "Mice234",..: 1 1 1 1 1 1 1 1 2 2 ...
 $ Time: int  7 9 11 13 15 17 19 21 7 9 ...
 $ variable   : num  NA 20.2 21.5 22.9 23 25.2 26.9 NA 19 22.2 ...
 $ Diet    : Factor w/ 9 levels "Diet1","Diet2",..: 7 7 7 7 7 7 7 7 9 9 ...

I have built up following model with Time as a fixed effect and Diet and ID as a random effect.
lmer(variable ~ Time + Diet + (1 | SampleID) + (1 | Diet), data =data, REML = FALSE)

I ran the model and this is the output:
    Linear mixed model fit by REML ['lmerMod']
Formula: variable ~ Time + Diet + (1 | SampleID) + (1 | Diet)
   Data: data

REML criterion at convergence: 2235.4

Scaled residuals:
    Min      1Q  Median      3Q     Max
-4.9157 -0.4709  0.0202  0.4695  3.8323

Random effects:
 Groups   Name        Variance Std.Dev.
 SampleID (Intercept) 2.595    1.611
 Diet     (Intercept) 1.824    1.351
 Residual             1.849    1.360
Number of obs: 588, groups:  SampleID, 98; Diet, 9

Fixed effects:
                 Estimate Std. Error t value
(Intercept)       17.2153     1.6107  10.688
Time           0.4499     0.0147  30.606
Diet1    -0.3610     2.1598  -0.167
Diet2  -1.9533     2.1330  -0.916
Diet3            19.7461     2.1891   9.020
Diet4  -1.3082     2.1795  -0.600
Diet5  -1.5830     2.2020  -0.719
Diet6    -2.7308     2.1145  -1.291
Diet7         19.7525     2.2125   8.927
Diet8    -1.4892     2.1795  -0.683

coefs <- data.frame(coef(summary(m)))
coefs$p.z <- 2 * (1 - pnorm(abs(coefs$t.value)))
coefs
                   Estimate Std..Error    t.value       p.z
(Intercept)      17.2153100  1.6107440 10.6878002 0.0000000
Time          0.4499233  0.0147007 30.6055728 0.0000000
Diet1   -0.3609887  2.1598318 -0.1671374 0.8672619
Diet2 -1.9533316  2.1329930 -0.9157703 0.3597874
Diet3           19.7460769  2.1891371  9.0200274 0.0000000
Diet4 -1.3081610  2.1795476 -0.6001984 0.5483740
Diet5 -1.5829868  2.2019821 -0.7188918 0.4722076
Diet6   -2.7307647  2.1145054 -1.2914437 0.1965499
Diet7        19.7525431  2.2125545  8.9274831 0.0000000
Diet8   -1.4891979  2.1794666 -0.6832855 0.4944265

Is my model correct based on my question? I can see that diet3 and diet7 have a significant effect over time on the variable, but how I could compare these two diets against the control diet (i.e. Diet2).
Comment: You do not get coefficients for Diet because you did not include it in the model.
Answer: First of all, I would add time in the random effects, since each animal will have a different pattern of evolution through time, thus having a different slope. At the same time, I would not add the diet as random effect.
I would try the following model:
ml1 <- lmer(variable ~ Time * Diet + (Time | SampleID), data = data)

This would allow to:

ascertain if there is an effect of Diet in the longitudal evolution of the variable;
while taking into account that each animal may have a different slope in time.

Hope this helps
Comment: The random slopes and intercepts model has a a lot of parameters to estimate.  I would fit a serial correlation longitudinal model with no random slopes or intercepts.  See [here](https://fharrell.com/post/re).
Comment: @FrankHarrell, the random slopes model has only an extra two parameters than the random-intercept one and allows for serial correlation. In fact, random effects are very powerful for longitudinal data, allowing you to model the serial correlations flexibly.
Comment: Dimitris that's not quite right.  These models can be unstable and convergence can be difficult because they are estimating 2cn parameters not 2 parameters, where n is the number of animals and c is some number between 0 and 1.  If the variance of the random intercepts or the random slopes is not tiny then c is closer to 1.  When you solve for the effective number of parameters estimated (2cn) you'll often be surprised.  c is a function of the two variances.
Comment: Random effects models are most needed when one wants to estimate trajectories of individual animals.  If the interest is only in group-level effects then random effects models can be an overkill.  In addition, the correlation pattern induced by random slopes models is very hard to justify when compared to observed correlation patterns in the raw data.
Comment: @FrankHarell What you say about the extra number of parameters to be estimated is new for me. I have always thought there would be just two additional parameters, a variance of the random time effect and the covariance of the random time and random intercept. If e.g. you would compare the deviances of (1) a model with only a random intercept and (2) a model with random intercept and random time effect, the number nr. of degrees of freedom would be 2, pointing to the two extra parameters. Why is this then? Or to put it different: where do the 2n extra (given that c=1 say) parameters come from?


Probability of a machine throwing up balls

Question: A machine can throw n balls of different color up in the air. The probability of throwing up r balls is directly proportional to r. If it is given that a particular ball is the first to be thrown up in the air, then what is the probability that all the balls have been thrown up by the machine.
Answer:$\frac{2}{n+1}$
I have no idea on how to even begin solving this problem and any suggestions or solutions would be highly appreciated.
Answer: Let one of the colors be red and let $R$ be the event that the first ball is red. Let $n$ be the event that $n$ balls are thrown.
Then the probability the the red ball is first given that all $n$ are thrown up must be $$P(R|n)= \frac{1}{n}$$ by symmetry. Similarly, for any number $1\le j \le n$ of balls thrown, by symmetry the probability the red ball is first must be $1/n$ so $$P(R|i) = \frac{1}{n}$$ for all $i.$
By Bayes, we have $$ P(n|R) = \frac{P(R|n)P(n)}{\sum_{i}P(R|i)P(i)} = \frac{P(n)}{\sum_{i=1}^n P(i)}= P(n).$$
So the probability that there are $n$ balls thrown given that the first is red is the same as the probabilty there are $n$ balls thrown. (Which you can compute by normalizing $P(n)\propto n$ is $2/(n+1)$. To do this set $P(i) = \alpha i$ and fix $\alpha$ so that $\sum_{i=1}^n P(i) = 1$.)
When you think about it, this makes sense. The fact that the red ball is first gives you no additional information about $n$.


Data sharing - SQLite vs Shared Memory IPC

Question: I would like to get your opinion regarding a design implementation for data sharing.
I am working on Linux embedded device (mips 200 Mhz) and I want to have some sort of data sharing between multiple processes which can either read or write multiple parameters at once.
This data holds ~200 string parameters which are updated every second.
Process may access to data around ~10 times in 1 second.
I would very much like to try and make the design efficient (CPU / Mem).
This data is not required to be persistent and will be recreated every reboot.
Currently, I am considering two options:

Using shard memory IPC (SHM) + semaphore (locking on all SHM).
To use SQLite memory based DB.

For either option, I will supply a C interface library which will perform all the logic of DB operation.
For SHM, this mean locking/unlocking the semaphore and access the parameters which can be referred as an indexed array.
For SQLite, my library will be a wrapper for the SQLite interface library, so the process will not have to know SQL syntax, (some parsing should be done for queries and reply).
I believe that shared memory is more efficient:
No need to use and parse SQL, and it is accessed as an array.
Saying that, there are some pros as well for using SQLite:
Already working and debugged (DB level).
Add flexibility.
Used widely in many embedded systems.
Getting to the point,
Performance wise, I have no experience with SQLite, I would appreciate if you can share your opinions and experience.
Thanks
Comment: Well, what are the *requirements*? SHM (exposes "raw bits", direct) is entirely different from a DBMS (exposes "information", ACID, etc.) Also, SQLite *relies on file locks* and write-write/write-read contention is one of SQLite's "weak spots"; the behavior/semantics of when the locks are obtained is well-documened on the site.
Comment: There are other (faster, but not necessarily relational) DB systems - aka BDB style - that may a better fit, and are also well tested. They can have far less overhead than SQLite, which can make a difference on "very slow" (as in todays standards) systems.
Comment: (I would likely start with SHM or a [BDB-style DB](http://en.wikipedia.org/wiki/Berkeley_DB). The former will allow fine-grained/custom locking if needed, but is just a tad more work. I wouldn't worry about performance of the latter; performance numbers will tell you if you should [have], but getting it working is *far* more important at this stage.)
Comment: Generally, the requirements are to collect different parameters from the device (stored at different locations kernel/ other core/ files etc…)
This will be done with collecting process/es (writing the data)
Then to be able to expose the data in one central location and a single API.
The data should be accessed easily by processes such as web-UI etc...
Comment: For "easily processed", a DBD-style DB wins over SHM hands-down for writing and reading key-value pairs :) Now, SQLite (with it's SQL syntax, although it is possible to use SQLite over the official BDB these days, for a $$$, I believe) has the ultimate advantage *if doing relational queries*. If key-value pairs suffice in a [self managed] hierarchal model, then relational queries gain little.
Comment: Thanks pst, I will take a look on your idea of BDB style.
Answer: SQLite's in-memory databases cannot be shared between processes, but you could put the DB file into tmpfs.
However, SQLite does not do any synchronization between processes. It does lock the DB file to prevent update conflicts, but if one process finds the file already locked, it just waits for a random amount of time.
For efficient communication between processes, you need to use a mechanism like SHM/semaphores or pipes.
Comment: "SQLite does not do any synchronization between processes. It does lock the DB file to prevent update conflicts" This is a contradiction: A lock on a file that two processes access is a form of synchronization between those processes. Also I believe locking is at the table level "if one process finds the file already locked, it just waits for a random amount of time" This sounds highly unlikely, I think SQLite asks to be notified by the OS when the lock is release.
Comment: The locking [is done on the file level](https://www.sqlite.org/lockingv3.html), not on the process level; this means that even two connections in the same process will use file locking. See the [default busy handler](https://github.com/LuaDist/libsqlite/blob/master/src/main.c#L859): there is no unlock notification. Table locking is used only with shared-cache mode, i.e., when two connections in the same process agree to share their accesses to the same database.


A simple one. Is this a folder, or a php/py file, with a hidden extension

Question: So what does 9gag have for each of it's posts? A gag folder with thousands of single-file folders, or is it just a php (or py... I didn't check) file with a hidden extension?
Here is the link:

http://9gag.com/gag/a7LQzWw

BTW, I didn't choose the post by it's hilariousness :) Just a random post :)
Oh, and if it's a single file, isn't it memory consuming to have separate files for every post? Thank you for any replies :)
Comment: What's hilarious in this?
Comment: check out mod_rewrite to see what it does.http://net.tutsplus.com/tutorials/other/a-deeper-look-at-mod_rewrite-for-apache/
Comment: That is just routing - the internal logic is up to their implementation, but of course it does not reflect their filesystem structure.
Comment: +1 since -1 is not necessary for being curious. Can imagine that 'What have you tried?' is not really relevant here.
Comment: @Mr.Alien I quote myself: "BTW, I didn't choose the post by it's hilariousness :)" - I didn't search for a one having a funny pic... just a random one
Answer: This is all assumption based off the URL and other sites that host large amounts of content in a similar fashion.
It's most likely an MVC (model, view, controller) web application, I can't tell what language. They'll be using some form of dispatching/routing (Apache's mod_rewrite for example) to get all requests through some common code.
9gag.com is the server. /gag/ is the 'controller', this controller has been coded to then know that the next part of the URL is the post/image ID. So it grabs the ID from the URL (or dispatcher already did this and passed the ID to the controller) and uses it to look up the content from a database (the model) and inserts it into a generic template (view).


Area of triangle given two medians and one side.

Question: In triangle $ABC$,point $D$ is the midpoint of $BC$and point $E$ is the midpoint of $AC$.If $AD=6$,$BE=9$,and $AC=10$ then find the area of triangle $ABC$.
I've solved this problem in two ways:
$1)$ by constructing the third median and calculating the area of one of the triangle determined by the intersection of the medians then multipy by six.
$2)$ by calculating the lengths of the other two unknown sides and then applying Heron's Formula.
Now what i am asking is if someone can come up with another solution based on geometric methods.
P.S:you may ask the why of this question and the answer would be that i like to see many creative solutions to one problem,and see what is the most beautiful one.
Thanks in advance
Answer: Let $BE$ amd $AD$ meet at G, the centroid. It is a well-known property of the centroid that it divides a median in the ratio $2:1$. Therefore $AG=4$ and $GE=3$. Therefore $AEG$ is a $3-4-5$ i.e. right-angled triangle whose area is $6$. Therefore the total area is $36$
Comment: a typo maybe ,$GE=3$
Comment: @chenbai.thanks for spotting that!
Answer: I think @David Quinn's answer is excellent and to the point, but it may be difficult for our novice readers to understand. Therefore, I'd like to give a detailed answer, which can be easy to understand by highschoolers. Following image shows the detailed data given by the question:

As shown in the image, $AC = 10$, $AD = 6$, and $BE = 9$. Since $D$ and $E$ are midpoints of $BC$ and $AC$, $AE = CE = 5$. Suppose $AD$ and $BE$ crossed at point $G$. Then, if you extend $CG$ until it meets $AB$ at point $F$, then point $F$ would be the midpoint of $AB$ (a property of triangle and G is called the center of gravity of the triangle). Thus, $$\frac{AG}{GD} = \frac{BG}{GE} = \frac{CG}{GF} = \frac{2}{1}$$
Since $AD = 6$ and $BE = 9$, $AG = 4$, $GD = 2$, $BG = 6$, and $GE = 3$. Thus, $\triangle AGE$ is a pythagorean triangle $(AG^2 + GE^2 = 4^2 + 3^2 = 5^2 = AE^2)$, hence $AD$ and $BE$ are perpendicular to each other.
If the area of $\triangle AGE$ is $\alpha$, then $\alpha = \frac12 \cdot 4 \cdot3 = 6$. Let's consider the 6 triangles around point $G$. If the area of a triangle is $A_\triangle$, then:
$$A_{\triangle AGE} = A_{\triangle CGE} = \alpha = 6 \qquad A_{\triangle BGD} = A_{\triangle CGD} = \beta \qquad A_{\triangle AGF} = A_{\triangle BGF} = \gamma $$
Since $A_{\triangle ABE} = A_{\triangle CBE}$, $2 \beta + \alpha = 2 \gamma + \alpha$, and hence, $ \beta =  \gamma $. Similarly, considering $A_{\triangle ABD} = A_{\triangle ACD}$, you can show that $ \alpha =  \gamma $. Therefore, $ \alpha =  \beta =  \gamma = 6$. Accordingly,
$$A_{\triangle ABC} = 2\alpha +  2\beta + 2\gamma = 6 \times \alpha = 36$$


Standard error of estimate and standard error of coefficient

Question: I am doing self-study/review of the above mentioned topics. I am a little bit confused with these two terms. Are they the same thing? If not, could you please show me the formula?
Comment: As far as I'm concerned, the standard error of a coefficient is well defined (I assume you know what that is), but "standard error of regression" looks like an imprecise term to me and I wouldn't use that term. Can't remember having seen it either. The regression is the whole thing, not a single estimator of something of which one could compute a standard error. Can you quote the context of where you've seen "standard error of regression"?
Comment: If "standard error of regression" and "standard error of estimate" refer to the same thing (and you'd have to read the "manual" to be sure), then they both refer to the estimate of the conditional standard deviation of the regression model.  That is quite a different thing than the standard error of a coefficient estimate. As I noted in my answer, the latter is the estimate of the standard deviation of the sampling distribution of the estimate, the former is an estimate itself.
Comment: @BigBendRegion Hi! Just noticed your comment. Thank you. Would it be clearer if any of you write equations (estimate of the conditional standard deviation of the regression model &  standard error of a coefficient estimate) to the answer? I think they will help other users as well if anybody has the same question.
Comment: Sure. $s.e.(\hat \theta)=\{\hat Var(\hat \theta) \}^{0.5}$.
Comment: And the regression "model standard error" that is reported by some software (including R, egads), is really $\hat \sigma = \{\sum_i(y_i - \hat y_i)^2/(n -k -1)\}^{0.5}$, which is an estimate of the model parameter $\sigma = \{Var(Y | X=x)\}^{0.5}$.
Comment: The difference is that the former refers to a sampling distribution of an estimated parameter, and the latter refers to the actual potentially observable data.
Comment: @BigBendRegion Thank you :)
Comment: @Lewian Hi! Thanks for the comment. I saw the term of "standard error of regression" from one blog. I just checked again,  it says "Standard error of regression also called as Standard error of estimate".  So, can you explain in a simple way the difference between Standard error of coefficient and standard error of estimate. Thank you!
Comment: They are the same thing, the coefficient is estimated and hence also often called estimate
Comment: @stefgehrig Thanks :) Was confused with those terms
Comment: Chances are stefgehrig is right, however in general if a blog author uses imprecise terminology, it is up to them to explain it, not to us. ("Standard error of estimate" is imprecise as well as long as they don't say estimate of what.)
Comment: @Lewian Ah, ok :D thanks!
Answer: The term "standard error" is used by EXCEL to denote the residual root mean square. It is also used by R (egads!) in the term "Residual standard error" to denote the same thing. It is probably used by other software, too.
Use of "standard error" to refer to the estimated conditional standard deviation of the regression model is bad statistical practice. It is also bad for statistics education. Since "standard error" is most commonly thought of as an estimate of the standard deviation of the sampling distribution of a parameter estimate, the term "standard error" as a reference to the estimate of a regression model parameter (and not its sampling distribution) should be abandoned. It would be just like calling an estimated $\beta$ in regression a "standard error" because both are estimates of parameters, not estimates of the sampling distribution of parameter estimates.
Hey R developers! Can you change "Residual standard error" to, say "root mean square error"?  If the problem is with the word "mean" because of the df adjustment, then how about "Est condl sdev"?
Comment: Yes, indeed. If we were to always have "standard error" refer to the estimated standard deviation of the sampling distribution of a  parameter estimate, then much confusion would vanish.
Comment: I'm glad to hear it isn't just me who saw that in R and though, "I'm pretty sure this isn't what standard error usually means."
Comment: @BigBendRegion. Thanks! There are too many sources on the web. standard error, standard error of estimate, standard error of intercept, Standard error of coefficient, standard error of slope... It makes people confusing...


best empirical macro/micro F1 score?

Question: In the following presentation it's said that "0.5 to 0.55 (micro) F1 score is best for multilabel classification problems"
I tried to investigate this statement but couldn't find the source.
Does anyone know if there is more to it?
Answer: On an extremely easy data set, anything but a F1 of 1.0 is a failure. ;-)
On a data set, where $l$ labels are assigned at random with the same probability, precision and recall of much more than $1/l$ are either due to chance or due to cheating.
Real data will of course be somewhere inbetween.
Now here is the catch: if you have a balanced, binary classification problem, and answer at random. You have a chance of 50% to get the values right, so on a balanced, binary classiciation problem, F1 of 0.5 is the expected performance of a random classifier. So any result around 0.5 is useless. This does, however, not generalize to balanced multiclass problems!
So maybe that was the statement where that number came from: 0.5 on a binary problem is random; but 0.5 on a 100-class problem can be pretty good (if it is a balanced, difficult data set without issues such as duplicates etc.). The statement probably never was 0.5 is "best".
So since a random result is expected to achieve $1/l$ as F1-measure, you could define an adjusted F1 measure that is less sensitive to the class size:
$$adjF1_l:=\frac{F1 - 1/l}{1 - 1/l}$$
But this equation assumes that all classes are equally frequent, so it is not a general purpose thing.
Comment: I refer to your last paragraph: by now I also think that this person wasn't referring to a special book/paper/survey etc. and just wanted to express, that the 0.5-55 range is "fine" for these kind of problems. His slides can be easily misunderstood, because the phrase "is tops" [is this even grammatically correct?]  implies that there is some kind of cap. His statement "literature says if you do best practices you should be able to get 0.5 - 0.55"  doesn't imply that this is the best possible value. I think it boils down to what I said in the beginning
Answer: I think you're missing the context here: He says that results reported in the literature on this task (multi-label document categorization) are typically around 0.5-0.55, but the Kaggle leaderboard had some people reporting results that were much higher (~0.8).  He then discusses why (the test set contained copies of training examples) and how he built a system that used that information, plus other data, which performed really well.
He doesn't mention where he got that "typical" range from, but it's not totally unreasonable. This paper by T .Rubin et al. reports pretty similar F1 values in Table 8, but the numbers in this comparison of two systems are a bit higher.
There's nothing magical about 0.5. Depending on the task, a number much less than 0.5 might be a cause for celebration or even something like 0.95 might be disappointing.

best empirical macro/micro F1 score?


BIRT - Failed to load the JNI shared Library (JDK)

Question: I am unable to run BIRT.exe an Business intelligence reporting tool, it's throwing error as specified below in the image:

Tried fixing this watching the below video :
https://www.youtube.com/watch?v=QETYeZzl6kA
Which stated jvm.dll needs to copied from :
C:\Program Files\Java\jre1.8.0_45\bin\server

to C:\Program Files\Java\jdk1.8.0_45\jre\bin\server directory. But still unsuccessful.
JDK version : jdk1.8.0_45
BIRT version : birt-report-designer-all-in-one-3_7_2
Please assist me to solve this issue
Comment: Since you have a native `.EXE` which tries to load a JVM-specific `.DLL`, you should check whether the architecture of the executable program and the JVM match, i.e. that you don't try to let a 32 Bit program use a 64 Bit JVM or vice versa…
Comment: Yeah, to avoid this conflict i have installed both 32bit and 64bit jdk. Also changed the Environmental variable path to 32bit and tried if that will work, but it was unsuccessful. And later just cross checked with `java -version`. It was still showing 64bit instead of 32bit which got changed in path variable. Any clues w.r.to this?
Comment: Well, I don't know which variable you changed…
Answer: Latest version of jdk i.e version 8 has problems with BIRT. So i downgraded to version 7 and everything working fine.
Answer: The trick is to link it with 86-bit version of java. You can have it on PATH, but in order to make modern apps happy, just create a symbolic link:
cd to birt's dir and run something like this:
mklink /D jre "C:\Program Files (x86)\Java\jre1.8.0_191"

and yes, jre 8 works fine for me.


Element of odd order

Question: Let $x$ be an element of finite order $n$ in a group $G$.
I want to show that if the order $n$ is odd  then $x^i\neq x^{-i}$ for all $i=1,2,..,n-1$.
I think that a way to prove this would be to show that if  $x^i= x^{-i}$, then $i=n$, which is a contradiction.
Can anyone help me get started?
Comment: It's not really a proof by contradiction you'll have, rather a proof by contraposition.
Comment: You are right, thanks.
Answer: Hint:
If $x^i=x^{-i}$ then $x^{2i}=e$ so that $n\mid 2i$. If $n$ is odd then this leads to $n\mid i$.
Comment: Thank you for the answer. If $n \vert i$ then i is a multiple of n, and then we must have $i\geq n$. Is that correct?
Comment: More to the point: it leads to $i\notin\{1,\dots,n-1\}$.
Comment: Glad to help. You are very welcome.

Element of odd order


Drupal adding an include

Question: I am using the Zen theme, what I could like to do is effectly add a php include for a header area. This is common code so a block will not really do.
I have html.tpl.php which is added automatically to each page is there anyway to add custom chunks to every page for example myheader.tpl.php
Comment: Create a file with the code you want to include and `include_once` it into the template file.
Comment: is that it? not a more drupal way
Comment: You should tell us more about what you are trying to achieve - what does your common header code display or perform - if you want us to tell you how one would achieve that with Drupal.
Comment: I just want a common bit of code, it does not really do anything and does not need to be edited by users
Answer: You can try module_load_include

Loads a module include file.

Parameters
$type: The include file's type (file extension).
$module: The module to which the include file belongs.
$name: (optional) The base file name (without the $type extension). If omitted, $module is used; i.e., resulting in "$module.$type" by default.
Examples:
  // Load node.admin.inc from the node module.
  module_load_include('inc', 'node', 'node.admin');
  // Load content_types.inc from the node module.
  module_load_include('inc', 'node', 'content_types');

Answer: You rarely (probably never) want to pull in arbitrary PHP into a template. Generally you want all your processing to have happened before you reach this stage. The theme files should be 100% focused on generating markup.
If you are looking to do some processing on every page, you can use template_process_html(). Generally this is used to alter page variables before final render, or to add CSS and JS based on information from previous operations.
If you are looking to provide some output, you can add another region to your theme (or use a block in an existing region, but you've already passed over that concept).

Drupal adding an include


Error installing rails (no write Permissions)

Question: When attempting to install rails, I get the following:
$ gem install ruby
Fetching: ruby-0.1.0.gem (100%)
ERROR:  While executing gem ... (Gem::FilePermissionError)
You don't have write permissions for the /Library/Ruby/Gems/1.8 directory.

I installed ruby 1.9.3 with rbenv and set it to the global version:
rbenv global 1.9.3-p448

So I'm not sure why it's trying to access the system version...?
Comment: I'd recommend using https://rvm.io/ for managing a separate Ruby version.
Comment: if you run `which ruby` what do you get?
Comment: I get 1.8, the pre-installed system version
Answer: Fixed it by adding the following to .bash_profile:
export PATH="$HOME/.rbenv/bin:$PATH"

Also, this line is needed too (though it was already there):
eval "$(rbenv init -)"

For info on modifying bash_profile, see:
http://redfinsolutions.com/blog/creating-bashprofile-your-mac


Is it allowed to play a cricket match without positioning any fielder as a wicket keeper?

Question: In a cricket match , there are total 11 players which we called as playing eleven who will be there fielding and batting for a side.
There are different positions on which the fielders can be placed such as a gully,slip,third man etc.
In a standard cricket match we can remove fielder from slip and put him at the gully or anywhere else we want(of course within and according the ICC rules for fielding positions).

My question is can we remove a wicket keeper from his position leaving
  his field blank(no one behind the stumps) and make him field at the
  slip?
Is it required to have a wicket keeper behind the stumps every time?
Is there any rule?
Answer: There is no requirement to have a wicket-keeper at all times. However, according to Law 40.1:

If by his actions and positioning it is apparent to the umpires that he will not be able to discharge his duties as a wicket-keeper, he shall forfeit this right and also the right to be recognised as a wicket-keeper

He will therefore not be allowed to keep wearing keeping pads and gloves in his new position.
Mike Brearley once placed the keeper David Bairstow on the boundary for the final ball of the innings, when the opposition needed three runs off the last delivery.
Answer: Yes its allowed, and someone has done it now!
During Worcestershire's stint in the field, their captain Daryl Mitchell asked wicketkeeper Ben Cox to ditch his gloves and pads and become an extra fielder - leaving no one behind the stumps.
The ploy developed as an extension of MS Dhoni's decision to stand back to the spinners while keeping for India in the Test series in England last summer.
The umpires, after consultation, allowed it. "In a game when you're trying to stop the opposition scoring, it's a legitimate tactic," Steve Rhodes, the Worcestershire director of cricket, said.
Moeen's second over - the 16th of the innings - saw Cox remove gloves and pads and go to fly-slip, with no one standing up to the stumps. Umpires Nick Cook and Graham Lloyd conferred at length and allowed play to continue, with Mitchell persisting in the tactic for the spinners from thereon.
More here: Worcestershire ditch keeper


How does mounting a server in a rack work?

Question: I am setting up a lab for learning purposes. I don't have a rack yet, but I just purchased a Supermicro 2U enclosure on eBay with some rails.
How does it work with connecting the server to the rack? I've got no experience with rack mounted equipment, and I haven't bought a rack yet. I want to make sure I don't mix the wrong types of equipment.
Answer: Generally all 19" 4 post racks will work with all 4 post rails, if they're both "square hole universal".  You may need to buy the nuts and bolts separately.  I say generally, because I've occasionally seen oddball equipment.
Some racks will have tapped screw holes, I've seen several difference screw sizes in the past.  I always seem to have the wrong screw size handy too.
Many rails designed for square hole, will not fit in tapped hole racks.  Most rails for tapped screw holes will work with square holes racks.
I can't tell from the supermicro rail kit (on ebay, or their website) as to what kind of rails they use.
Comment: Perfect! I guess that means I'll just wait to buy the rails later.
Comment: Telco racks, and Rackable tend to be the ones with Tapped Holes.. Some telco racks are also weird in that they have the support in the middle, rather than front/back.
Comment: I know this is late to the party, but I wanted to add that the SuperMicro rails don't require screws or cage nuts or anything, they just slot into the square-holed racks and use gravity + server weight for fixing in place.
Comment: ^ this is true in general for the newer SuperMicro rails, which is likely what the OP has.  But, the older rails are "normal".
Answer: Rails are tricky things.  I suggest.. that for the time being, you buy some rack shelves.  They're more versatile, and you can always just rest the server on the shelf.
It looks like the server and the rails come from the same seller, so perhaps the smart play would be to email him/her and ask?
Comment: Thanks Tom, I didn't really think about shelves...that would do the trick :) I'm not worried about pulling the server out at home. I checked with the seller and the rails came off of the same server. The problem is I don't have a rack yet, so I wasn't sure how the rail to rack connection worked. Shelves do seem like a much easier route though.


Centos KVM Host OS not passing all network traffic Guest OS

Question: I'm running KVM on Centos 5.  I have a guest OS, ubuntu 10.04, that has Snort 2.9 installed on it.  The guest OS has (2) nic's, eth0 and eth1.  One nic, eth0, is configured with an IP and can be accessed from the network that the host OS is on.  The 2nd nic has no IP, and is used to receive mirrored traffic from a Cisco switch.  On the host OS side, a tcpdump on br1, which is the bridge interface used for the guest OS running Snort, does see the mirrored traffic from the switch.  But a tcpdump run on eth1 of the guest OS, which is the interface that's monitored by Snort, only sees broadcast or cdp packets from the switch.  A tcpdump run on eth0 of the guest OS does show the mirrored traffic from the switch.
Any ideas?
Comment: Try checking for a KVM setting to allow the guest to use promiscuous mode.
Comment: devicenull, I found the KVM setting to put an interface into promiscuous mode, but it didn't work.  I applied the setting to the bridge interface, br1, and ran a tcpdump on both eth0 and eth1 of the guest os, and saw only broadcast or cdp traffic. Also, I was mistaken about eth0 on the guest os.  This interface is only seeing broadcast traffic, or traffic for snort, since snort is currently configured to monitor eth0.
Answer: I don't know if this will help but I just ran into a similar problem while troubleshooting keepalived on two Linux KVM guests each running Ubuntu 10.04. I found that while running tcpdump -i eth1 would see the multicast addresses (which is a different subnet then the IP assigned to the NIC) but if I ran tcpdump -i any it wouldn't. I did some further testing of tcpdump while monitoring dmesg and found when I used the eth1 device on tcpdump it would put the NIC into promiscuous but when using the "any" device, neither eth0 or eth1 entered promiscuous. This contrary to how it's handled on a physical host where "any" puts all NIC's into promiscuous or at least on the hosts I tested with.
I ran the command ip link set eth1 promisc on and then when I used the "any" device, it was now able to see the traffic. This applied equally to eth0 however I know the traffic I wanted wasn't coming there so I only did this to test. You can save this for the host by editing /etc/network/interfaces and adding a line beginning with "post-up " followed by the command you just used and this ensures the device enters promiscuous when the best is booted.
I don't believe a NIC would normally need to in promiscuous to see multicast traffic but in this case with the KVM guest it seems that was the case and it appears if the device is not set to promiscuous then it only sees IP packets on a subnet with the same IP as the NIC if not in promiscuous. Snort uses libpcap, the same library as tcpdump IIRC and if it's trying to set promiscuous via the any interface then it seems it's not succeeding where it should. I don't believe keepalive requires promiscuous under normal circumstances but in this case it seems to be the only way to see the multicast traffic.
Hope this helps.
Answer: After a longer search I found this very simple/easy solution - if you know it:
http://adamdoupe.com/blog/2010/10/22/configuring-linux-bridge-to-act-as-a-hub/
brctl setageing <bridgename> 0

Comment: https://techglimpse.com/convert-linux-bridge-hub-vm-interospection/


How to notate syncopations in measures that starts with slashes

Question: (Apologies in advance for possibly incorrect terminology. Also, I'm fairly new to slash notation.)
I am writing a chord sheet for my band. I use slash notation and explicitly specify important rhythms/syncopations using rhythmic slashes. However, I am unsure how to notate a syncopated final 8th note in a measure that is otherwise just filled with slashes (no specific rhythm). Or more generally, notating syncopations when the part of the measure up to the syncopation has no specific rhythm and is therefore filled with slashes.
For example, in the image below, I do not want the crossed-out 8th notes, because they should not be emphasized; only the final 8th note in each measure (where the chord changes) should be emphasized by the band.

Are there good ways to notate this?
I tried making the first of the two 8th notes invisible, but that leaves an unseemly gap. I may be able to reduce it, but I'm concerned that it may not be a clear way to notate what I'm after.

I have also considered using a pause for the first of the two 8th notes, though that may give the impression that the band should not play on that beat, which is wrong.
Comment: In case you don't want a pause on the fourth beat, as in your first example, then I suggest that you put a dot on the third beat.
Comment: Just to be clear - did you want the 1st beat of every bar *played* or *pushed*?
Answer: Here's four possibilities.   What would YOU play if you saw each of them?
The last one is the least specific, showing the anticipated chord change without implying a set rhythm for therest of the bar.
Comment: I think the last one is what I'm looking for. Thanks! Now to find out how to do that in MuseScore...
Comment: Did you miss what he actually asked for - he didn't show the chord being 'pushed' (as in your ties)? although that's *might* be what he really wanted!
Answer: Here's my preferred way to show that a chord is to be "pushed". I write a tied eight note in front of the chord symbol:

How to do that in MuseScore 3
In MuseScore 3.6.2, you can add an eighth note and tie in front of a chord symbol with the Special Characters window, which you can open by pressing F2 while editing the chord symbol.

To get the chord symbol to align the way you want, you'll have to attach it to the last slash note of the previous bar instead of the first slash note of the next bar.
In MuseScore 2?
In MuseScore 2, I couldn't get the F2 Special Characters window to add the symbols to a chord symbol. But you could add a normal staff text by pressing Ctrl/Cmd-T and add the push symbols as a separate text element.
How to do that in Sibelius 6
In Sibelius 6, you can do the "push" symbol very nicely with Legacy Chord Symbols and with custom entries added to the Word Menus.

To add the push symbol to a chord symbol, right-click on the chord symbol when editing it, and you get the context menu from which you can select the extra symbol that you added in Preferences / Word Menus / Chords (standard).
Comment: That's simple, elegant, and very helpfully explained. Thanks!


por que não consigo chama uma função pelo input type="submit"?

Question: Olá, estou tendo o seguinte problema: quando uso o input type="submit", o formulário valida os dados porém não executa a função, já quando uso o input type="button", ele chama normalmente a função.
Por que isso acontece? Estou chamando a função de forma errada? Segue o código

function calcular() {
  var nome = document.getElementById('userName');
  var peso = document.getElementById('peso');
  var altura = document.getElementById('altura');
  var imcAtual = document.getElementById('imcAtual');
  var imcIdeal = document.getElementById('imcIdeal');
  var pesoIdeal = document.getElementById('pesoIdeal');
  var perder = document.getElementById('perder');
  var res = document.getElementById('resultado');

  Number(peso.value);
  Number(altura.value);
  var imcAt = peso.value / ((altura.value / 100) * (altura.value / 100));

  document.getElementById('resultScreen').style.display = 'block';
  var sau = document.getElementById('saudacoes');
  sau.innerHTML = `Hola, ${nome.value}!`;
  imcAtual.innerHTML = `Seu IMC atual é de ${imcAt.toFixed(2)}`;
  if (imcAt < 18.5) {
    res.innerHTML = 'Você está abaixo do peso';
  } else if (imcAt < 24.9) {
    res.innerHTML = 'Você está com o peso normal :D';
  } else if (imcAt < 29.9) {
    res.innerHTML = 'Você está com sobrepeso';
  } else if (imcAt < 34.9) {
    res.innerHTML = 'Você está com obesidade grau 1';
  } else if (imcAt < 39.9) {
    res.innerHTML = 'Você está com obesidade grau 2';
  }
  imcIdeal.innerHTML = `O IMC Ideal é entre 18,5 e 24,9`;
}

  <form>
    <fieldset id="dados-usuario">
      <input type="text" required name="userName" id="userName" placeholder="Digite seu nome" />
      <input type="number" required min="1" max="250" name="peso" id="peso" placeholder="Digite seu peso" />
      <input type="number" required min="1" max="250" name="altura" id="altura" placeholder="digite sua altura sem vírgulas" />
    </fieldset>
    <fieldset>
      <input type="submit" name="enviar" id="enviar" value="Calcular IMC" onclick="calcular()">
    </fieldset>
  </form>

Peso ideal segundo o seu sexo e altura

Comment: `submit` serve para submeter o formulário. Se não quer que isso aconteça, não use. Claro que usar `onsubmit` e `preventDefault`, como já indicado, "funciona", mas isso me parece um contorno para um problema que não existiria se vc usasse o tipo correto (no caso, `button`). Então em vez de dar essa volta, prefira usar a coisa certa para cada função. Se não quer submeter o formulário, use o `button`, que como você mesmo já percebeu, funciona corretamente sem precisar de artifícios.
Answer: Utilize o button=submit mesmo. Porém você não poderá chamar a função no botão, pois a função neste cenário é submeter o formulário. Logo intercepte a submissão do formulário com a propriedade "onsubmit".
Exemplo:
<form onsubmit="calcular(event)">
  Enter name: <input type="text">
  <input type="submit">
</form>

Então capture o evento de submissão do form, e previna ele de submeter, e então ele devera apenas chamar a sua função.
function calcular(e) {
  e.preventDefault();
  /* Restante da sua função */
  return false;
}

O e.preventDefault(); previne que formulário seja submetido (atualização da página). Espero ter sido claro, fique à vontade para perguntar.
Comment: Funcionou, o problema era apenas a falta do e.preventDefault(). Salvou minha vida, estava a 3 dias tendo esse problema :D Obrigado.
Answer: Só complementando a resposta do @fweydson, você pode manter o seu código como está, apenas adicione o código para evitar que o formulário seja submetido como demonstrado na outra resposta, adicionando o event.preventDefault() para o evento onsubmit:
<form onsubmit="event.preventDefault()">

Veja abaixo o seu código funcionando com o trecho de código acima adicionado ao form:

function calcular() {
  var nome = document.getElementById('userName');
  var peso = document.getElementById('peso');
  var altura = document.getElementById('altura');
  var imcAtual = document.getElementById('imcAtual');
  var imcIdeal = document.getElementById('imcIdeal');
  var pesoIdeal = document.getElementById('pesoIdeal');
  var perder = document.getElementById('perder');
  var res = document.getElementById('resultado');

  Number(peso.value);
  Number(altura.value);
  var imcAt = peso.value / ((altura.value / 100) * (altura.value / 100));

  document.getElementById('resultScreen').style.display = 'block';
  var sau = document.getElementById('saudacoes');
  sau.innerHTML = `Hola, ${nome.value}!`;
  imcAtual.innerHTML = `Seu IMC atual é de ${imcAt.toFixed(2)}`;
  if (imcAt < 18.5) {
    res.innerHTML = 'Você está abaixo do peso';
  } else if (imcAt < 24.9) {
    res.innerHTML = 'Você está com o peso normal :D';
  } else if (imcAt < 29.9) {
    res.innerHTML = 'Você está com sobrepeso';
  } else if (imcAt < 34.9) {
    res.innerHTML = 'Você está com obesidade grau 1';
  } else if (imcAt < 39.9) {
    res.innerHTML = 'Você está com obesidade grau 2';
  }
  imcIdeal.innerHTML = `O IMC Ideal é entre 18,5 e 24,9`;
}

  <form onsubmit="event.preventDefault()">
    <fieldset id="dados-usuario">
      <input type="text" required name="userName" id="userName" placeholder="Digite seu nome" />
      <input type="number" required min="1" max="250" name="peso" id="peso" placeholder="Digite seu peso" />
      <input type="number" required min="1" max="250" name="altura" id="altura" placeholder="digite sua altura sem vírgulas" />
    </fieldset>
    <fieldset>
      <input type="submit" name="enviar" id="enviar" value="Calcular IMC" onclick="calcular()">
    </fieldset>
  </form>

Peso ideal segundo o seu sexo e altura

Comment: Funcionou, adicionei só o onsubmit mesmo, vocês salvaram minha pele rs valeu!!


Difficult Trombone passage

Question: I am currently putting the finishing touches on a brass trio I am composing. After meticulously checking every note and every phrase, I realized the technical difficulty of the opening 4 measures of the piece for F Trigger Trombone:

The difficulty stems from slide positioning:

The Db can only be played in position 5
The C can only be played in position 6 or T2.5
The Bb can only be played in position 1 or T3

The musicians that will be performing this piece are collegiate performance majors, so a good deal of technical proficiency is expected of them. However, since I do not personally play the Trombone I am not sure if this passage would be too difficult to expect of a college level player.
Could any trombonists clarify for me if this would be too difficult?
Thanks a million!
Edit: tempo is at dotted quarter = 80
Comment: Please provide an approximate metronome marking!
Comment: As someone who plays the entire brass family but is kinda sloppy at trombone slide positions, I think this is totally fine.
Comment: Just a note, the C would be in position 6 or T1, not T2.5. At this speed I wouldn't have much trouble even without a trigger, but with the trigger the C and Bb would be in the same position, and thus possibly even easier: 5–T1–1. If in the end you decide it sounds too rough or messy, bringing it up an octave would make it a total cinch to play, but I don't think it's too bad as written.
Answer: This depends on the speed of the piece. The technical problems of playing those positions are pretty inconsequential even on a straight (no valves) trombone at slower tempi (dotted quarter = 60). At faster tempi (ca. Dotted quarter = 120) this would be more difficult but doable by a "college student" standard. Compare this passage to some of the standard orchestral excerpts undergraduates routinely are assigned to study and you'll find this is not very difficult in comparison.
What might make this a difficult passage to play for a "college student" standard might be more the repeated Bbs at a very fast tempo. This would necessitate a multiple tonguing technique that might be odd to a less experienced player, especially as it is repeated with no break for 4 bars. This would also make it difficult to find a good spot to breathe,  which would be harder particularly if the passage were loud. Much like I mentioned before though, at slower tempo these problems would not be considerations. Normally I would inquire this information before answering, but I think the additional perspective could help your (and others) writing by providing what would make the passage difficult.
Comment: That seems like a pretty reasonable tempo to me.  I wouldn't be worried about it. Another good resource is the tromboneforum.org.  Composers/arrangers frequently stop by to ask similar questions, should you ever have another question about low brass writing.
Comment: wow sorry forgot to include speed... its at [dotted quarter = 80]
Answer: Speaking as a college trombone player, this passage should be able to be played without much trouble.  What the player will need to do is play the Db in 5, the C in 6 and the Bbs in the first measure in trigger flat 3rd, then in 1st on the second measure.  So the positions would be: (5 6 Tb3 Tb3 1 1 1) (5 6 Tb3 Tb3 1 1 1) (5 6 Tb3 5 5 6 Tb3 5) (5 6 Tb3 6 5 6 6 2).
With an F-attachment there's not much the trombone can't play.
Happy Composing!
Answer: At dotted quarter = 80 this is perfectly playable, with or without a F trigger.  Trombonists, particularly bass trombonists, put in a lot of practice to develop agility in this register.  This wouldn't be considered a particularly hard exercise.
Answer: It's not impossible to play, but there will definitely be some griping. Could you change the key up a half-step? 4-5-7 is definitely easier than 5-6-1.
Comment: It could be 5-6-t2.  But, really, it's no problem in either key, with or without trigger. We can play scales a lot faster than that.
Comment: True, and with collegiate-level players it won't be an issue, especially at 80bpm. If it were high school or a community group, it would generate comments within the section. :)

Difficult Trombone passage


Is the bound $\Gamma(\alpha, x) \leq \tfrac{3}{2} e^{-x} (x + \alpha )^{\alpha - 1}$ valid for all $x > 0$ and $\alpha \geq 0$?

Question: Recall the incomplete Gamma function, which is defined as
$$
\Gamma(\alpha, x) = \int_x^\infty t^{\alpha - 1} e^{-t} \, dt.
$$

My question is whether or not
$$
\Gamma(\alpha, x) \leq \frac{3}{2}(x + \alpha)^{\alpha - 1} e^{-x}
$$
holds for all $x > 0$ and any $\alpha \geq 0 $.

Below, I prove it holds for all integers $\alpha \geq 0$.
Indeed, integration by parts gives
$$
\Gamma(\alpha, x) = x^{\alpha - 1} e^{-x} + (\alpha - 1)\Gamma(\alpha- 1, x).
$$
In particular, using the fact that $\Gamma(1, x) = \int_x^\infty e^{-t} \, dt = e^{-x}$, it can be verified that for all integers $k \geq 0$, that
$$
e^x \Gamma(k + 1, x) = \sum_{j=0}^k x^k (k-j)! \binom{k}{j} \leq \sum_{j=0}^k x^k k^{k-j} \binom{k}{j} = (x + k)^k.
$$
Or stated otherwise, for all $x > 0$,
$$
\Gamma(\alpha, x) \leq e^{-x} (x + \alpha - 1)^{\alpha - 1} \leq \frac{3}{2} e^{-x} (x + \alpha)^{\alpha - 1} \quad \mbox{for any}~\alpha \in \{1, 2, 3, \dots\}.
$$
Moreover, the bound above can also trivially be verified at $\alpha = 0$.
Answer: Some thoughts. (A rigorous proof for (1) and (2) is required.)
Let
$$F(x) := \frac{3}{2}(x + \alpha)^{\alpha - 1} \mathrm{e}^{-x} - \int_x^\infty t^{\alpha - 1} \mathrm{e}^{-t} \, \mathrm{d} t.$$
We have
\begin{align*}
 F'(x) &= -\frac32(x + \alpha)^{\alpha - 2}\mathrm{e}^{-x}(1 + x) + x^{\alpha - 1} \mathrm{e}^{- x}\\
 &= - \frac{\mathrm{e}^{-x} x^{\alpha}(1 + x)}{(x + \alpha)^2}\left( \frac32\left(1 + \frac{\alpha}{x}\right)^{\alpha} - \frac{(x+\alpha)^2}{x(1 + x)}\right).
\end{align*}
We split into three cases.
Case 1. $\alpha \ge 1$ and $x > 0$
By Bernoulli inequality,
we have
$$\frac32\left(1 + \frac{\alpha}{x}\right)^{\alpha} - \frac{(x+\alpha)^2}{x(1 + x)} \ge 1\cdot \left(1 + \frac{\alpha}{x}\cdot \alpha\right) - \frac{(x+\alpha)^2}{x(1 + x)}
= \frac{(\alpha - 1)^2}{1 + x}\ge 0.$$
Thus, $F'(x) \le 0$ on $(0, \infty)$.
Also, we have $F(\infty) = 0$.
Thus, $F(x) \ge 0$ for all $x > 0$.
Case 2. $0 \le \alpha < 1$ and $x > 1$
By Bernoulli inequality,
we have $$\left(1 + \frac{\alpha}{x}\right)^{\alpha} = \frac{\left(1 + \frac{\alpha}{x}\right)}{\left(1 + \frac{\alpha}{x}\right)^{1 - \alpha}} \ge \frac{\left(1 + \frac{\alpha}{x}\right)}{1 + \frac{\alpha}{x}\cdot (1 - \alpha)},$$
and
$$\frac32\left(1 + \frac{\alpha}{x}\right)^{\alpha} - \frac{(x+\alpha)^2}{x(1 + x)}
\ge \frac32 \cdot \frac{\left(1 + \frac{\alpha}{x}\right)}{1 + \frac{\alpha}{x}\cdot (1 - \alpha)} - \frac{(x+\alpha)^2}{x(1 + x)} \ge 0.$$
Thus, $F'(x) \le 0$ on $(1, \infty)$.
Also, we have $F(\infty) = 0$.
Thus, $F(x) \ge 0$ for all $x > 1$.
Case 3. $0 \le \alpha < 1$ and $0 < x \le 1$
Using $\mathrm{e}^{-t} \ge 1 - t$ and the Bernoulli inequality, we have
\begin{align*}
 \int_x^\infty t^{\alpha - 1} \mathrm{e}^{-t} \, \mathrm{d} t
 &= \int_0^\infty t^{\alpha - 1} \mathrm{e}^{-t} \, \mathrm{d} t - \int_0^x t^{\alpha - 1} \mathrm{e}^{-t} \, \mathrm{d} t\\
 &\le \int_0^\infty t^{\alpha - 1} \mathrm{e}^{-t} \, \mathrm{d} t - \int_0^x t^{\alpha - 1} (1 - t) \, \mathrm{d} t\\
 &= \Gamma(\alpha) - \left( \frac{1}{\alpha} x^\alpha - \frac{1}{\alpha + 1}x^{\alpha + 1}\right)\\
 &= \Gamma(\alpha) - \frac{x}{x^{1 - \alpha}} \left(\frac{1}{\alpha} - \frac{x}{\alpha + 1}\right)\\
 &\le \Gamma(\alpha) - \frac{x}{1 + (x - 1)(1 - \alpha)} \left(\frac{1}{\alpha} - \frac{x}{\alpha + 1}\right).
\end{align*}
It suffices to prove that
$$f(x) := \frac{3}{2}(x + \alpha)^{\alpha - 1} \mathrm{e}^{-x} - \Gamma(\alpha) + \frac{x}{1 + (x - 1)(1 - \alpha)} \left(\frac{1}{\alpha} - \frac{x}{\alpha + 1}\right) \ge 0.$$
We have
\begin{align*}
 f'(x) &= \frac{(1 - x)(1 + \alpha + x - \alpha x)}{(\alpha + 1)(\alpha + x - \alpha x)^2} - \frac32 (x + \alpha)^{\alpha - 2}\mathrm{e}^{-x}(1 + x)\\
 &\le \frac{(1 - x)(1 + \alpha + x - \alpha x)}{(\alpha + 1)(\alpha + x - \alpha x)^2} - \frac32 (x + \alpha)^{\alpha - 2}(1 - x)(1 + x)\\
 &= (1 - x)\left(\frac{1 + \alpha + x - \alpha x}{(\alpha + 1)(\alpha + x - \alpha x)^2} - \frac32 (x + \alpha)^{\alpha - 2}(1 + x)\right)\\
 &\le 0 \tag{1}
\end{align*}
where we use $\mathrm{e}^{-x} \ge 1 - x$.
Also, we have
$$f(1) = \frac32 (\alpha + 1)^{\alpha - 1}\mathrm{e}^{-1} - \Gamma(\alpha) + \frac{1}{\alpha} - \frac{1}{\alpha + 1} > 0. \tag{2}$$
Thus, $f(x) \ge 0$ for all $0 < x \le 1$.


continuing congruence equation

Question: How do you solve this congruence equation?
$$3\equiv -4a\pmod {13}$$

What I did was :
Applying symmetry property
$$ -4a\equiv 3\pmod {13} $$ Since gcd(13,4) = 1 we multiply both sides by inverse of $4\pmod {13}$
$$-a\equiv30\pmod{13}$$
$$a\equiv-30\pmod{13}$$
How can I continue from this point?
$ a + 30 = 13k$ doesn't help me.
Comment: You are almost done, you just need to simplify $-30\pmod{13}$.
Comment: You could directly use the inverse of $-4$, which is $3$.
Comment: $-30\equiv -17...\bmod 13$. just keep going until you get a number in between $0$ and $12$.
Answer: What I didn't know was that $-30\pmod{13} =9 $ is not equal to $30\pmod{13}=4$

So we can write the above expression as
$$ a\equiv9\pmod{13}$$
$$ a = 9$$
Answer: more handy solution:
3 = -4a (mod 13)
9 = -12a (mod 13)
9 = a (mod 13)     <--i think you could figure it out.
so , a = 9, 21,......

continuing congruence equation


GCC changes less than to less than or equal to

Question: I have the following simple program that I'm using to refresh my memory of GDB (which I haven't touched for many years).
#include <stdio.h>

int main()
{
  int i;

  for (i = 0; i < 10; i++)
  {
    printf("Hello World\n");
  }

  return 0;
}

I compile this with gcc -g for-test.c -o for-test. Based on the man page, I don't expect any optimisations to be used, since I haven't specified any.
When I load this into GDB and run disassemble main, the i < 10 comparison generates the following:
cmp    DWORD PTR [rbp-0x4],0x9
jle    0x4004fe

This seems to have effectively changed a comparison of i < 10 to i <= 9. Given that these are integer comparisons, there shouldn't be a difference, but I was wondering if there is any reason why GCC outputs this assembly, instead of comparing against 10 and jumping if less than (JL)?
Edit: This is on a machine with a 64-bit processor, running Ubuntu with GCC 4.6.3 and GDB  7.4-2012.04.
Comment: Perhaps that's how it normalizes comparisons..
Comment: Both ways are 100% identical (same behaviour, same code size, same speed on every CPU). I don't know about GCC's internals so I can't guess why it did this. More interesting is that I don't think you've enabled optimisation (otherwise it'd be using a register instead of a local variable for `i`).
Comment: If there were any chance of the two not being the same, it would not do it without optimisation. e.g. `if (a + 1 > 1)` will be simplified to `if (a > 0)` with optimisation, but it's potentially unsafe, so won't be done otherwise.
Answer: There shouldn't be a difference in execution speed. I think gcc generally emits jle for such comparisions and does it for consistency in the generated assembly.
Comment: That does seem to be the case. Interestingly, I tried the same code in clang and the result was the opposite - it would convert a 'continue loop if less than' to 'break loop if greater than or equal to'. I'm not sure why the two compilers have chosen different routes, or if one is inherently more efficient than the other.
Answer: Compilers are allowed to perform optimizations as long as the observable behavior is same. This is known as the As-If rule. Since the observable behavior for both the cases is same, the compiler is allowed to generate the assembly code in either of the two. This is true even if you do not have any optimizations enabled.
Comment: +1. It could even unroll the loop (it actually does that with `-O3`). And, perhaps, even print a single string that's 10 copies of the original.
Comment: This isn't really an optimisation though, unless comparing against 9 and jumping if less than or equal to is faster (or more memory efficient, or some other measure) than comparing against 10 and jumping if less than.
Answer: It isn't effective optimization, just another way to write the same. Compiling with -O flag generates much more complex optimizations.


search query in sqlite

Question: I have a table with one field as name.The values in this fields are

kiran-(ki-ran).txt,
arun-(ar-un-ki-ran).txt,
aby-(ki-ran-aby).txt

How i can search the values excatly matching ki-ran(inside bracket) from this values so i can get only kiran-(ki-ran).txt
i have used LIKE ('%ki-ran%') But it is showing all the values.Thanks in advance
Answer: Your LIKE clause should look like LIKE '%(ki-ran)%'.

search query in sqlite


Cleveland Cavaliers championship bonus

Question: Do the Cavs players get some sort of bonus compensation from the team and / or the NBA?
What about the coaching staff and owners?
If so, do you know how much this bonus is?
As a data point, way back, in the 1990s when the Knicks made it to the eastern conference finals (John Starks, Patrick Ewing, Charles Oakley and others) each player got around 100k bonus, which was reported by the local news.
Answer: The NBA sets aside a playoff's pool of money as a bonus to teams for their performance.
Last year that figure was at $13 million with a maximum of $8 million that can go to any team. This year the prize money seems confirmed. If you were to divide that figure equally to all players in the team that would equate to each player receiving a maximum over $500,000.
This is the source
If the players divide the prize money in percentage of thier wage the bonus can be very different and here you can find a simulation on Warriors players (made before the end of the season)
Individual players may then have economic advantages with successive contracts, but in this case it is not about bonuses.

Cleveland Cavaliers championship bonus


About Match Objects in python

Question: I'm fairly new to python and am trying to run the below code:
import re

start([default])

email = 'email@example.com'

m = re.search('kit',email)

print m.group()

But i keep getting the following error:
start([default])

NameError: name 'start' is not defined

Can anyone please let me know what exactly is happening over here?
Comment: Yeah, the error message is quite clear: you are using a variable, `start` that you haven't defined yet. For that matter, `default` hasn't been defined either. Only you can say what you are trying to do there, though...
Comment: What the heck did you expect `start([default])` to do?
Answer: As people have said in the comments, this error message means exactly what it says - you never defined start.
I'd strongly suggest reading this article on how to debug small programs.
Comment: Sure Thank You for the responses! I will look into the article.

About Match Objects in python


If I plan to run a stepwise multiple regression, should I examine VIF in the final model, or of all variables before using the stepwise approach?

Question: Suppose I have ten predictors that I want to use to predict Y. I plan to run a multiple regression using stepwise selection. My question is, should I assess colinearity in the final model (i.e., examine VIF of the variables that make it into the model)? Or should I first simply run a multiple regression with all ten variables and examine colinearity when all ten are in the model?
Comment: The first question is why you plan to use stepwise selection in the first place. [This superb answer](http://stats.stackexchange.com/a/20856/28500), among many others on this site, explains the substantial drawbacks. Please explain more about what you are trying to accomplish in your work; there is almost certainly a better solution than stepwise selection.
Comment: Possible duplicate of [Algorithms for automatic model selection](https://stats.stackexchange.com/questions/20836/algorithms-for-automatic-model-selection)
Comment: @mkt But this is an interesting question and in his comment, the OP says he is looking into LAR. So ... what to do? Maybe a new question is needed.
Comment: @PeterFlom I'm fine with leaving open since your answer covers the stepwise problem and also addresses the interesting portion (+1). Would perhaps be nice for the LAR part to be edited into the question, but I'm not sure if that is best left to the OP.
Comment: Okay, I am looking into Least Angle Regression as a model selection procedure. But this is a separate issue. I'm still hoping to get an answer to my original question: should I evaluate colinearity among all possible predictors or just those that make it into the model?
Comment: I'm voting to close this as a duplicate of the thread EdM recommends above because I think the critique it makes is the best answer to this question. Answering the specific question raised here is merely tinkering with a bad method, when the best way forward is to use a different one.
Comment: I voted to leave this open for now, but I could be convinced to change my mind.
Answer: Per the comments - if you plan to run stepwise regression, you should probably change your plans.
But, suppose (as you indicate in a comment) that you are going to use LAR. Then the question is whether looking at collinearity first is a good idea. I would say yes. Collinearity is going to affect the standard errors of your parameter estimates and that will affect all sorts of things. If there is substantial collinearity, then you might want to apply your variable selection method to a different model - such as ridge regression. Or you might want to remove one or more variables from the data set. Or something else.


Are these two equivalent forms for the likelihood of a Poisson point process?

Question: I have a Poisson point process in a bounded region $W$. I'm trying to calculate the likelihood of observing a particular set of points within $W$. I'm told that there are two equivalent forms of likelihood:
$$L(\cdot) = \left( \prod_{i=1}^{n} \lambda(x_i) \right) e^{-\int_W \lambda(u) \, du},$$
which is, apparently, "the more general one" (and the one that I was familiar with as being the correct likelihood), and
$$L(\cdot) = \frac{\left( \int_W \lambda(u) du \right)^N e^{-\int_W \lambda(u) du}}{N!} \times \prod_{i=1}^{N} \lambda(u_i),$$
which I have never seen before, but, apparently, accounts for the occurrence of exactly $N$ points. The problem here is that, as I understand it, assuming we're taking the likelihood of some parameter given some set of points, the first form of likelihood already accounts for the probability of the occurrence of exactly $N$ points, no?
Are these two equivalent forms for the likelihood of a Poisson point process? Or is the first one the correct likelihood, and the second one something else (or even just nonsense)?
Comment: Please explain the extra variables that appear in the formulas: the $x_i$ at top (which are not in the left hand side) and the $u_i$ at the bottom (ditto).  How are they related? And is $N=n$?
Comment: @whuber The $x_i$ are the points/occurrences, $N$ is the total number of points/occurrences, and $\mu$ is the position/location in $W$. I guess the lower $u_i$ should be $x_i$.
Comment: Well, once you rectify those inconsistencies, you will readily see the two expressions for $L$ are related by a constant of proportionality.  But I don't see any references to "$\mu$" anywhere and it's unclear what you consider the likelihood to be a function of.
Answer: I would consider only the first one as being the likelihood of a Poisson point process. It is unclear what the second expression is aiming at.
Point processes are complex and so is the formulation of their likelihood. The tricky part is that the number of points is random, so we cannot think of the likelihood as a "usual" $\mathbb{R}^n \to \mathbb{R}$ mapping. This would restrict us to a fixed dimension $n$. Rather it is intuitive to see it as a collection of mappings, one for each $n \in \mathbb{N}$, where $n$ is the number of points materializing. Then the likelihood of a realization is determined by first counting the total number of points and then plugging in the locations of these points into the respective function.
It is common to choose the components of such a likelihood as the Janossy densities $j_n : \mathbb{R}^n \to \mathbb{R}$ (see my reference, chapter 5 and 7 for a detailed definition). Basically, the value $j_n (x_1, \ldots, x_n) $ encodes the likelihood of $n$ points materializing, one of them in each of the locations $x_1, \ldots, x_n$. For a Poisson point process with intensity $\lambda$ the $n$-th Janossy density is given by
$$
j_n (x_1, \ldots, x_n) = \left( \prod_{i=1}^{n} \lambda(x_i) \right) e^{-\int_W \lambda(u) \, du},
$$
which is the first expression in your question. Thus it is commonly referred to as the likelihood of a Poisson point process.
Reference:
Daley, D. J. and Vere-Jones, D. (2003). An introduction to the theory of point processes. Volume I, Springer, New York.


Extra fields in Search page

Question: Is a module available that can add a particular field on the search page?  I'd like for user's to see an image-field if applicable.
Answer: You can use Display Suite module to create custom view mode for search results.

Extra fields in Search page


Shortest method for string to boolean conversion in this scenario

Question: I have 4 possible [string] values for an input parameter - "0", "1", "false", "true".
These possible values need to be converted to boolean. With "0" mapping to false and "1" mapping to true and the strings "false" and "true" to respective booleans.
What would be the shortest and optimal way to do this?
Comment: Voting -1 as this question for "shortest and optimal" may have only opinion based answers, you don't provide any measurable scenario and it falls into the http://stackoverflow.com/help/dont-ask category
Answer: You could include str == "1":
foreach(string str in new[]{ "0", "1", "false", "true"})
{
    bool isTrue;
    isTrue = Boolean.TryParse(str, out isTrue) || str == "1";
    Console.WriteLine(isTrue);
}

For what it's worth, an extension method:
public static bool ParseBool(this string input, bool oneIsTrue = true)
{
    bool b;
    return (oneIsTrue && input == "1") || bool.TryParse(input, out b);
}

// ...
foreach(string str in new[]{ "0", "1", "false", "true", "True", "TRUE"})
{
    Console.WriteLine(str.ParseBool());
}

Comment: That's entirely different than the foreach from your original answer ;) But what's with the `out b` reference?
Comment: @Moriarty: The extension is equivalent to the `foreach`, isn't it? I've added the extension just because OP was asking for the shortest code. There isnn't anything shorter than `str.ParseBool()`. The `out` is necessary to use `bool.TryParse`. It's an `out` parameter.
Answer: I think this should do:
//string value is stored in str
boolean bool = (str.equals("0")||str.equals("false"))?false:true;

Answer: Try this simple one.
string[] ar = { "0", "1", "true", "false" };
var boolArray = ar.Select(x => (x=="1"||x=="true")?true:false).ToArray();


Difference between a limit and accumulation point?

Question: What is the exact difference between a limit point and an accumulation point?
An accumulation point of a set is a point, every neighborhood of which has infinitely many points of the set. Alternatively, it has a sequence of DISTINCT terms converging to it?
Whereas a limit point simply has a sequence which converges to it? i.e. something like $(1)^n$ which is a constant sequence.
Is this the right idea? As much detail and intuition as possible would be greatly appreciated.
Comment: [Difference Between Limit Point and Accumulation Point?](http://math.stackexchange.com/questions/374859/difference-between-limit-point-and-accumulation-point)
Answer: The difference is very simple.
1) As you wrote: an accumulation point of a set is a point, every neighborhood of which contains infinitely many points of the set.
2) But a limit point is a special accumulation point. No matter how small neighborhood you choose, all members $a_n$ (after a certain $n$) are in the neighborhood of the limit point.
The requirement for all members (after certain $n$) is obviously stronger than the requirement for infinitely many points/members.
So every limit point is an accumulation point, but not every accumulation point is a limit point. Also note that: (1) if a sequence has a limit point, then that's the only accumulation point of the sequence; (2) if a sequence has more than one accumulation points, that this sequence has no limit point. Try to prove these two, it will clear your confusions.
Comment: This answer is much stronger than condition in general topological spaces [see here](https://chat.stackexchange.com/transcript/message/61669878#61669878)
Answer: Unfortunately, there doesn't seem to be one standard definition for theses terms.  One author may say that accumulation points are limit points, others do not.  Best thing to do is to check the definition given in book, paper, etc that you are reading.
Comment: It might depending on how these terms are defined in whatever source you're reading.
Comment: So it isn't a big deal to treat them somewhat interchangeably?


Is there a notation for a short rest of undetermined length; the rest equivalent of a grace note?

Question: Here's the phrase I'm working on, a nice chord progression from the finale of a symphony movement (Dopper 7 mov. 1) that I'm arranging for solo piano.

So the B♭ trill in the right hand exists for most of this phrase, but it's not the important part; the fortissimo chords are what the section is all about. The trill is "background noise", pardon my French. So it can be interrupted, as it is in ms 4 and 6, to get the big bold chord in.
I've currently notated this with an eighth rest and make the trill pick up after with a double-dotted half note. This works but I'm not sure if it's the best way; because I am notating two exact durations when really I don't care about the duration much. If a performer wants to let the chord breathe for a quarter note before resuming the trill, that's fine. If they are an acrobat and want to make the jump in the duration of a semihemidemisemiquaver, I say let them do it.
A grace note offers this freedom of duration; the left-hand grace note in ms 3 can be of any short-ish length (and can even be left out in this case) - and it also doesn't affect the length of the note/chord it leads up to. I'm wondering if there's something similar I can notate to interrupt the trill for just a small portion of time to get that chord in, without specifying the duration.
The two options I'm thinking of are: to not notate a rest for the trill at all (letting the performer figure out that it should be interrupted), or to add a tied grace note to every single note on that beat except for the trill.
Answer: The comma is generally used as a breath mark, but you could use it here.
Comment: And Gustav Mahler used this with relative frequency in his orchestral works, so there is precedent.
Comment: That's a novel usage to me, but it does make sense!
Comment: I do not think the comma is a very good idea, because it indicates a "breath" in the music, which is not what you want here. (See comments below)
Answer: You might very well leave it as such. A decent piano player will try to continue the trill as well as possible while playing these notes. If your want to specify that the trill does not need to be played as continuous as possible you might just annotate the part with something like il trillo con licenza (the trill with freedom) or something similar in the language of your choice such as perform the trill at your own discretion. Adding to much complexity to your notation might not be a good thing to do, as it confuses people, and if you want to encode that you want to leave interpretation entirely to the performer it might do so while conveying information you did not actually want to convey.
EDIT: Another way to do it is to code the less importance of the trill by reducing the head size like this:
Comment: @KeizerHarm Nes. Yo. Maybe. Tying the notes will make sure no one gets the idea to accent each bar. For percussion (where rolls spanning bars is quite common) and tremolo we'd usually not placer slurs, but for piano it makes sense. Check out the trills of Beethoven's Waldstein sonata, 3rd movement. And essentially the information you want to encode is a continuous flute or violin trill, so in fact a single attack, I suppose?
Comment: I think this is basically the best idea. Just write the notes as you want them, even if beginners will say "It's obviously impossible". I don't think it really helps to write something like "at your discretion", because it might suggest not trilling at all. (If you haven't already) I would write "con ped" at the beginning. It might also help to write a trill line all the way through the trilled Bb, which would make it instantly obvious that you have to interrupt it occasionally to play other notes. Similarly no grace note in bar 3. FWIW, I have big hands, but bar 1 is "impossible" ("this margi
Comment: Ooh, the small notehead option is really clever! Is tying all the B's together usual though? That feels like the whole line should be only one attack somehow.
Comment: I will use the small-notes version and add "con licenza" next to the trill sign. Thank you for your advice!
Comment: I don't like the way you have written bar 3. If you want a grace note, I would write a CC octave as in the Eb-D-C-Bb sequence, jumping up to the remaining three notes.
Comment: @BrianChandler Thank you for the feedback. This is the sort of thing I keep going back and forth on. Adding grace notes so I don't have to cut voices is an easy trap, so I considered that I could just leave the lower C out (or mark it as optional) and make the Cmin chord stand on its own, and went with the approach I went with. Making the CC octave be half tones on the other hand would better clarify it as a descending line... I don't know what I'll go with. Luckily I can edit these as much as I want, up to years later.


Como comparar uma posição da string com um caracter ? C

Question: A função processa_nomes não esta conseguindo comparar a posição da string 'a' com uma letra, estou querendo contar quantas letras 'A' aparecem na string e trocar as letras 'E' por um 3 .
<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int processa_nomes(char a[3][30])
{

    int i, j, cont=0;

    for(i=0; i<3; i++)
    {
        for(j=0; j<30; j++)
        {
            if(a[i][j]=='E')
            {
                a[i][j]= 3;
            }
        }

    }

    for(i=0; i<3; i++)
    {
        printf("Nome: %s \n", a[i]);
    }

    for(i=0; i<3; i++)
    {
        for(j=0; j<30; j++)
        {
            if(a[i][j]=='A')
            {
                cont++;
            }
        }

   }

    return cont;
}

int main()
{
    int i;
    char a[3][30];

    for(i=0; i<3; i++)
    {
        printf("Digite um nome: ");
        gets(a[i]);
    }

    printf("\nQuantidade de letras 'A' na string: %d\n", processa_nomes(a));

    return 0;
}
</code>
Comment: Note que a[i] não é um caractere mas sim o endereço para uma string de até 30 caracteres. Se quiser comparar strings utilize a função strcmp de .
Comment: Mas como vou fazer para verificar, por exemplo, quantas letras 'A' tem em cada string ?
Comment: Se quiser comparar cada uma das 3 strings então utilize um for para a quantidade de strings e outro for mais interno para a quantidade de caracteres de cada string e daí utilize um if quase da maneira como utilizou: if(a[i][j]=='E'). Agora não entendi o que deseja fazer quando for igual no caso da letra 'E' , no caso da letra 'A' tudo bem.
Comment: No caso da letra 'E', cada vez que ela aparecer eu desejo trocar ela pelo numeros 3
Comment: Então utilize a[i][j] = '3';. Caractere '3' e não o número 3, pois trata-se de um array de caracteres.
Comment: Agora sim deu certo, valeu !!
Answer: Como a resposta acabou sendo dada comentários, vou colocá-la aqui para futuras referências. Também diminuindo o número de loops:
<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int processa_nomes(char a[3][30])
{

    int i, j, cont=0;

    for(i=0; i<3; i++)
    {
        for(j=0; j<30; j++) {
            if(a[i][j]=='E') {
                a[i][j]= '3';
            } else if(a[i][j]=='A') {
                cont++;
            }
        }
        printf("Nome: %s \n", a[i]);
    }

    return cont;
}

int main()
{
    int i;
    char a[3][30];

    for(i=0; i<3; i++)
    {
        printf("Digite um nome: ");
        gets(a[i]);
    }

    printf("\nQuantidade de letras 'A' na string: %d\n", processa_nomes(a));

    return 0;
}
</code>


How to nest block elements inside an inline context in HTML5?

Question: I ran into a problem where I have to embed block level content directly inside a h1-h6 context. From the HTML5 specification I take that this has been ruled out to ensure compatibility with the default styles. Consequently, my code will not validate as HTML5. (However, it display perfectly in any browser I tested.)
I sketched my scenario in this jsFiddle.
Is there any way to nest block elements inside inline elements in a HTML5 conform way? I could imagine an element that switches from inline to block context but will, by default, not be displayed; I just don't know such an element.
Any help is appreciated.
PS: I know that JavaScript is capable of handling my example, but my solution has to be plain HTML+CSS.
Answer: Why exactly can't you use spans? Little demo: little link.
Comment: If I am not mistaken, spans, as inline elements, may not contain block elements (such as p, ul, ...) either.
Comment: @MRA Yes, that's another issue. You can try simulating the `ul` looks using `•`, and create line breaks using ``.
Comment: True, but this is something I'd rather like to avoid. I would have to find a workaround for each and every content tag that might end up in the in the pop-up box. Although, it is a kind of "last resort" option.
Answer: For content of that nature, you shouldn't be using <h[1-6]>. Use  instead.
Comment: @cimmanon - Because the drop-down is not part of the heading according to the semantics of the h# elements. The technique being is cute, but it is not compatible with HTML5 semantics.
Comment: My comment does not imply that the markup should not be adjusted, just that the h2 is still appropriate since he has a title.  There is no way to create what he wants that is semantically correct, valid HTML, and has the visual appearance he is after.  If it is not a true title, then by all means replace.
Comment: I may not like it, but this seems to be the way I have to go. Thanks for the help.
Comment: Why *replace* the h# tag?  He still has a title there.  Though I would argue that the footer tag might be more appropriate for the content in question.


How can my ear training be made better? (For Guitarist)

Question: I was looking for the lead (the music that starts the song) in the Hotel California Song. But I am having trouble locating the tab. Even after listening more than 50 times, I still cannot locate the guitar tab.Additionally, I have a very quick hand and can play any chord.
I am extremely discouraged.Furthermore, I do not want to copy the tab from YouTube or other website.
How can my ear training be made better?
Comment: https://music.stackexchange.com/questions/123/software-that-slows-down-music-to-help-in-transcribing
Comment: A teacher and/or loads of practice is what has served most of us. It's not an easy job, but knowing scales and chords is a very good start. That apart, there are many inaccurate tabs out there.
Comment: There are many, many questions on this site about improving ear training. Please read through some of those to see if they answer your question. If they don't, then please update your question to indicate what issue(s) are left unaddressed.
Comment: @Aaron Could you check and search the question for me?
Comment: That's your job when posting on this site — to do some basic research first. If you hover over the downvote button, you'll see that it says "This question does not show any research effort."
Comment: The wording in this question is really confusing. The word "tab" refers to a particular way of writing music down visually, but you seem to be describing trying to _hear_ the tab, which is impossible. I'm guessing that when you wrote "locating the tab," you meant "making out what the notes are," but I'm not completely sure.
Comment: Yes@TannerSwett I am referring to music notes, not tabs
Comment: I'm voting to close this question because it does not distinguish itself from the many other ear-training questions on this site.
Answer: In my experience, it's all about practicing and just hearing the same things over and over enough times. Playing by ear is definitely challenging at first. My advice is to break up the song into manageable chunks by pausing it. Try listening to the first five notes, and then find those on your instrument. If that's too hard, just do the first four notes, and so on. Then move on to the next chunk of notes, learn them, and add them to the first part. Soon you'll know all the notes and be able to practice it, and each song you learn by ear will get a little easier.