If $15$ distinct integers are chosen from the set $\{1, 2, \dots, 45 \}$, some two of them differ by $1, 3$ or $4$.

Question: $\blacksquare~$ Problem: If $15$ distinct integers are chosen from the set $\{1, 2, \dots, 45 \}$, some two of them differ by $1, 3$ or $4$.
$\blacksquare~$ My Approach:
Let the minimum element chosen be $n$. Then $n + 1 , n + 3 , n + 4 $ can't be taken.
We make a small claim.

$\bullet~$ Claim: In a set of $~7$ consecutive numbers at most $2$ numbers can be chosen.

$\bullet~$ $\textbf{Proof:}$ Let us name the elements of the set as $\{ 1,2,3,\dots,7 \}$.
Now let's consider the least element is chosen. If the least element is $1$, then $2,4,5$ can't be chosen.
So we are left with  $3, 6, 7$.
$\circ~$ If $~3~$ is chosen, then $6, 7$ can't be in the set. And if $~3~$ is not chosen, then only any one of the 2 elements $\{ 6, 7  \}$ be chosen. So, a maximum of $2$ elements can be chosen in this case.
$\circ \circ~$ If the least element is $2,$ then $3, 5, 6$ can't be there in the set. So, possible elements are 4, 7. So,  one of these two can be chosen. Then, a maximum of 2 elements can be chosen in this case.
$\circ \circ~$ If the least element is $3$, then $4,6,7$ gets cancelled. so only $5$ is left in the set i.e., $2$ elements at most.
$\circ \circ~$ If the least element is $4,$ then $5,7$ gets cancelled. So the only element left is $6$.
Similarly,
$\circ \circ~$ If $5$ is the least element then $6$ gets cancelled and only $7$ is left. i.e., two elements. If the least element is either $6$ or $7$, then there is only one element.
So a maximum of two elements in a set of $7$ consecutive elements can be chosen.
Hence, the proof of the claim is done!

So, for $42$ elements, a maximum of $2 \times 6 = 12$ can be taken. However, $3$ more elements are required from $3$ more consecutive elements, which is not possible since only 2 elements at most can be chosen from a set of 3 consecutive elements.
So, a $14$ element subset can be formed such that, no two of them differ by $1, 3, 4$. Hence the $15$th element is one of the cancelled elements, that is, there exists a pair with their difference being $1, 3$ or $4.$
Hence, done!

Please check the solution for glitches and give new ideas too :).
Comment: What is the question?  Well done.
Comment: @RossMillikan I don't understand what you mean.
Comment: I missed the last line.  I think it is a fine proof.
Comment: Oh! okay @RossMillikan
Comment: @RossMillikan The OP added the last line after your comment
Answer: It is a nice argument, and you have explained it very clearly, so well done.
If you are looking for improvements, and you want it to be a bit more formal, I would make two suggestions:

You are very thorough proving the claim, going through all the cases, which is great.  However you could shorten the proof of the claim by saying:

"If the least element is $x$, then we may subtract $x-1$ from all the numbers without changing their differences or the number of integers.  Thus without loss of generality we may assume the least element is $1$."
Then you do not need to consider the other cases.

The last part of the proof (after the claim is proved) is not as thorough as the proof of the claim.  You assume that for $k=0,\cdots,5$ the numbers $7k+1,7k+3$ are selected, without justifying that this is optimal.  It is obvious in a way, but for a formal proof you should justify this by saying something like:

"Pick the smallest $k$ where $7k+1, 7k+3$ are not picked.  Then replace the numbers in $\{7k+1,\cdots 7k+7\}$ that are picked with $7k+1, 7k+3$.  From the claim we know that we have not reduced the number of integers.  Also, we have not created any new differences of $1,3,4$."
Then finish the argument with your second to last paragraph.  I would reword the first sentence slightly: "So of the first $42$ elements, we may assume these $12$ are picked."
I would lose the last paragraph as it is not needed.
Answer: Nice proof!
In the optimal case, go up in $2$s wherever possible. You would start with $1$ and pick the smallest possible number, that is, $3$. We can't add $2$ again as that would be $1+4$, therefore we add the next smallest possible, $5$ to get our next number $8$. We can then add $2$ again, and the pattern continues:
$$1,3,8,10,15,17,22,24,29,31,36,38,43,45$$
Via this strategy we only pick $14$ numbers, so $15$ is impossible without violating the $1,3,4$ difference.
Comment: While this strategy is good in some cases, I think it's a bad general approach to proofs. I call it the "what's the worst that could happen?" model --- you work that out, show it's impossible, and say you're done. That relies on two things: (1) that the *second worst* doesn't turn out to be viable even though the worst is not, and (2) that you've correctly identified the worst case. My experience is that students (and even professionals) often manage to mess up with both failure modes.
Comment: You claim that you would pick the smallest possible number in order to generate an optimal sequence. But this is something that needs to be proven.
Answer: Here's a shorter version which however relies on the same ideas as your and Rhys Hughes' approach.
Let's assume we can choose $15$ integers whose mutual differences are never $0,1,3$ or $4$, and call them $x_1 <x_2 < \dots < x_{15}$ in ascending order.
Claim: For all $1 \le i \le 13$, we have $x_i +7 \le x_{i+2}$.
Proof of claim: Let's make a case distinction about what $x_{i+1}-x_i$ is. Since it cannot be $0,1,3$ or $4$, the only cases are:

First case, $x_{i+1} - x_{i} =2$. Then if we also had $x_{i+2} - x_{i+1} = 2$ we would have $x_{i+2}-x_i =4$ which was excluded. So $x_{i+2}-x_{i+1}$, since it cannot be $0,1,2,3,4$ must be $\ge 5$ which implies the claim.
Second case, $x_{i+1}-x_i \ge 5$. Then since $x_{i+2}-x_{i+1} \neq 0,1$ it must be $\ge 2$ and the claim follows.

The claim is proven.
Now it follows iteratively that $x_3 \ge x_1 +7$, $x_5 \ge x_3+7 \ge x_1+14$, ...,
$$x_{15} \ge x_1+49$$
which of course contradicts $1 \le x_1 \le x_{15} \le 45$. Actually this shows that you cannot even select $15$ such integers from the set $\{1, ..., 49\}$.


Does $\langle u,Tu \rangle=0$ imply that $T=0$?

Question: I have this simple question :

for an operator $T$ in a complex  Hilbert space we have:
   $\langle u,Tu \rangle =0$ for all $u$ in this Hilbert space. So does this imply that $T=0$? If yes, how to prove it?
Comment: Consider a rotation by $\pi/2$ in $\mathbb{R}^2$ with the standard inner product.
Answer: It is true when the Hilbert space is complex. You can see this via polarization. The others showed that it is false when the field is the reals.
Comment: Friedrich Philipp   how o show that in complexe ?
Comment: See Lemma 2 here: https://www.math.ksu.edu/~nagy/func-an-2007-2008/hs-1.pdf
Answer: You have $<u+v,T(u+v)>=<u,T(u)>+<u,T(v)>+<v,T(u)>+<v,T(v)>=<u,T(v)>+<v,T(u)>=0$.
Replace $v$ by $iv$, you have $<u,T(iv)>+<iv,T(u)>=-i<u,T(v)>+i<v,T(u)>$. This implies that $<u,T(v)>+<v,T(u)>=0$ and $<u,T(v)>-<v,T(u)>=0$. Thus $<v,T(u)>=0$ for every $v$. This implies $T(u)=0$.
Comment: it is a complexe hilbert space !!


Load sqlite3 extension in python3 sqlite

Question: How does one correctly load a sqlite extension into python sqlite import?
os: Windows 7 64bit
sqlite3 version: 3.14.1 64bit
python3 version: 3.5.2 64bit
Here is my process so far:
compile extension-functions.c to libsqlitefunctions.dll using this command:
gcc -shared -I "C:\Software\sqlite3\sqlite-master" -o libsqlitefunctions.dll extension-functions.c

Then I can happily use these functions in sqlite3 command line using this command:
SELECT load_extension('libsqlitefunctions.dll');

However when trying in the python script:
import sqlite3 as lite
con = lite.connect(db_file)
con.enable_load_extension(True)
con.load_extension("<<path to file>>\\libsqlitefunctions.dll")

This error appears:

Error The specified module could not be found. :

The extension-functions.c file does include the COMPILE_SQLITE_EXTENSIONS_AS_LOADABLE_MODULE section, and in fact it loads fine when using command line sqlite3
Additional notes:
The python sqlite package is installed and working correctly.
I've also tried updating the sqlite3.dll in the python path to the latest version
Comment: Check if you have `sqlite3` package installed . Else use `pip install sqlite3` in your windows command prompt to install it ,and try running the code again.
Comment: @Arihant yes it is installed. All other commands work, just an issue loading the extension.
Comment: What's the complete `<>`?
Comment: @Shawn - many different paths. I've tried every possiblity, including having the dll in the python3 PATH and the sqlite3 PATH and only putting the dll name in the call. But, by example, I would used something like this: "C:\\temp\\libsqlitefunctions.dll"
Answer: This isn't a nice answer, but it provides a method to use the extension in python.
Output sql commands to a file, then use subprocess to run the file directly into the command line, like so:
import subprocess
import uuid
import os

db_file = "trial02.db"
sqlite_functions_file = "libsqlitefunctions.dll"

sql_file = uuid.uuid4() + ".sql"
with open(sql_file, 'w') as fsql:
    fsql.write('/* auto script */\n\n')
    #load extension
    sql = "SELECT load_extension('" + sqlite_functions_file + "');"
    fsql.write(sql + '\n')
    #sql scripts
    sql = "insert into t(c) values (log(2));"
    fsql.write(sql + '\n')

args = [
    'sqlite3'
    , db_file
    , '< ', sql_file
]
print(' '.join(args))
out1 = subprocess.run(' '.join(args), shell=True)
os.remove(sql_file)

Answer: Place libsqlitefunctions.dll in a folder that is visible globally like c:\WINDOWS\ or some other folder from the PATH environment variable.
Then you will be able to load the extension using simple command:
con.load_extension("libsqlitefunctions.dll")

Comment: I unpacked [sqlite3 source](https://www.sqlite.org/download.html) to the same directory as [extension-functions.c](https://www.sqlite.org/contrib/download/extension-functions.c?get=25) and used this command: `gcc -fPIC -lm -shared extension-functions.c -o libsqlitefunctions.dll` to compile it, by the way. GCC came from [tdm-gcc](http://tdm-gcc.tdragon.net/download) package.


Chroot on Ubuntu 14.04.2 using Jailkit - /dev/pts No such file or directory

Question: For the past few days I've been trying to setup a chroot on my Ubuntu server but I've been running into an issue. I've tried several different methods of setting up a chroot on Ubuntu including just manually setting up folder permissions myself and then statically linking libraries for the binaries I wanted to allow but at the moment I'm currently using Jailkit to setup the chroot enviroment but with both setups I've had the same issue, after setting up the chroot and trying to log into ssh I'm immediately greeted with a forced closed terminal. When I run a debug sshd I see that it's because sshd cannot find /dev/pts for some reason even though it's in the chroot enviroment.
Here is my setup which was all populated by Jailkit except for /dev/pts which is mounted using
sudo mount -o  bind /dev/pts /data/jail/dev/pts

/data/jail/home/user
/data/jail/dev
/data/jail/dev/pts
/data/jail/dev/tty

This is what the debug sshd shows:
debug3: safely_chroot: checking '/'
debug3: safely_chroot: checking '/data/'
debug3: safely_chroot: checking '/data/jail/'
debug3: safely_chroot: checking '/data/jail/home/'
debug3: safely_chroot: checking '/data/jail/home/user'
Changed root directory to "/data/jail/home/user"
debug1: permanently_set_uid: 1002/1003
debug2: set_newkeys: mode 0
debug2: set_newkeys: mode 1
debug1: Entering interactive session for SSH2.
debug2: fd 6 setting O_NONBLOCK
debug2: fd 8 setting O_NONBLOCK
debug1: server_init_dispatch_20
debug3: Received SSH2_MSG_IGNORE
debug1: server_input_channel_open: ctype session rchan 256 win 16384 max 16384
debug1: input_session_request
debug1: channel 0: new [server-session]
debug2: session_new: allocate (allocated 0 max 10)
debug3: session_unused: session id 0 unused
debug1: session_new: session 0
debug1: session_open: channel 0
debug1: session_open: session 0: link with channel 0
debug1: server_input_channel_open: confirm session
debug1: server_input_channel_req: channel 0 request pty-req reply 1
debug1: session_by_channel: session 0 channel 0
debug1: session_input_channel_req: session 0 req pty-req
debug1: Allocating pty.
debug3: mm_request_send entering: type 28
debug3: mm_pty_allocate: waiting for MONITOR_ANS_PTY
debug3: mm_request_receive_expect entering: type 29
debug3: mm_request_receive entering
debug3: mm_request_receive entering
debug3: monitor_read: checking request 28
debug3: mm_answer_pty entering
debug2: session_new: allocate (allocated 0 max 10)
debug3: session_unused: session id 0 unused
debug1: session_new: session 0
debug1: SELinux support disabled
debug3: mm_request_send entering: type 29
debug3: mm_answer_pty: tty /dev/pts/8 ptyfd 5
debug1: session_pty_req: session 0 alloc /dev/pts/8
debug1: server_input_channel_req: channel 0 request shell reply 1
debug1: session_by_channel: session 0 channel 0
debug1: session_input_channel_req: session 0 req shell
Starting session: shell on pts/8 for user from *.*.*.* port 54006
debug2: fd 3 setting TCP_NODELAY
debug3: packet_set_tos: set IP_TOS 0x10
debug2: channel 0: rfd 11 isatty
debug2: fd 11 setting O_NONBLOCK
debug3: fd 9 is O_NONBLOCK
debug1: Setting controlling tty using TIOCSCTTY.
/dev/pts/8: No such file or directory
open /dev/tty failed - could not set controlling tty: No such file or directory
debug3: mm_request_receive entering
debug3: monitor_read: checking request 156
debug3: mm_answer_consolekit_register entering
debug1: session_by_tty: session 0 tty /dev/pts/8
debug1: Unable to open session: The name org.freedesktop.ConsoleKit was not provided by any .service files

Comment: Did you mount /data/jail/dev/pts with -o bind or with -t devpts (or some other way)?
Comment: Ah right I forgot to include that, I mounted it using sudo mount -o bind /dev/pts /data/jail/dev/pts
Answer: As far as I can tell, the ChrootDirectory is not properly set.
It should be set to:
ChrootDirectory /data/jail

Comment: The only thing I'm seeing now is this:

    `debug1: Unable to open session: The name org.freedesktop.ConsoleKit was not provided by any .service files`
Comment: Yes, thank you this solved the original problem of the missing /dev/pts but for some reason I'm still getting a forced closed terminal now with seemingly no error messages unless I'm missing something.


How to bind a Collection in an List of Objects in WPF

Question: I have a Collection of Objects and in each Object is a List of Properties (PropertyChanges). This Items should be listed under the "listViewPropertyDetails" Listview, but not even the converter "propertyChangeConverter" gets any object to convert. Any other Property in the Object is bindable like Username for example. But if i try to bind the Collection "PropertyChanges" nothing is shown an the converter don't get triggered. what have I forgotten? I am searching hours and don't find the right answer. Hope someone can help me.
public class ObjectHistory
{
    public string Username { get; set; }
    public DateTime DateOccurred { get; set; }
    public List<PropertyChange> PropertyChanges = new List<PropertyChange>();
}

public class PropertyChange
{
    public string PropertyName { get; set; }
    public string OldValue { get; set; }
    public string NewValue { get; set; }
}

<DataTemplate x:Key="HistoryObjectList">
    <Expander IsExpanded="True">
        <Expander.Header>
            <MultiBinding Converter="{StaticResource historyObjectHeaderConverter}">
                <Binding Path="DateOccurred"/>
                <Binding Path="Username"/>
            </MultiBinding>
        </Expander.Header>
        <Grid Name="grid1"
              Height="Auto">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>

            <ListView Name="listViewPropertyDetails"
                      Grid.Row="1"
                      Margin="15,25,0,0"
                      HorizontalAlignment="Stretch"
                      HorizontalContentAlignment="Stretch"
                      ItemsSource="{Binding PropertyChanges, Converter={StaticResource propertyChangeConverter}}"
                      >
                <ListView.View>
                <GridView>
                        <GridViewColumn Header="PropertyName"

                                             Width="120"
                                             DisplayMemberBinding="{Binding PropertyName}"/>
                        <GridViewColumn Header="OldValue"
                                             Width="265"
                                             DisplayMemberBinding="{Binding OldValue}"/>
                        <GridViewColumn Header="NewValue"
                                             Width="265"
                                             DisplayMemberBinding="{Binding NewValue}"/>
                    </GridView>
                </ListView.View>
            </ListView>
        </Grid>
    </Expander>
</DataTemplate>

Answer: PropertyChanges is not defined as a property but as a field and you cannot bind to fields. You should define it like this:
public List<PropertyChange> PropertyChanges { get; set; } = new List<PropertyChange>();


Fire OnClick after OnClientClick AJAX has finished

Question: I'm using ASP.Net and need to call a server side function after the JavaScript function has completely finished.
The problem is that it's executing the server code before the client code is finished and my hidden value is empty.  AJAX call is across domains so using async: false doesn't seem to work.
I've added the basic code below to explain a bit better.
HTML
<input id="hdnToken" type="hidden" name="hdntoken" value="" />
<asp:Button ID="btnSubmit" Text="Submit" OnClientClick="return getToken();" OnClick="btnSubmit_Click" runat="Server"></asp:Button>

JavaScript
function getToken() {
    $.ajax({
        async: false, // Ignored across domains
        method: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "jsonp",
        success: OnSuccess,
        error: OnError
    });

    function OnSuccess(response) {
        $('#hdnToken').val(response);
        return true;
    }

    function OnError(response) {
        console.log(response);
        return false;
    }
};

ASP.Net Server side code
protected void btnSubmit_Click(object sender, EventArgs e)
{
    var hidden = Request.Form["hdnToken"];
}

Answer: A simple trick would be to place a LinkButton on the page with no text but with an OnClick event.
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click"></asp:LinkButton>

Then you can simulate the PostBack from that link with the UniqueID

Now when the simulateClick() is run, it wil trigger the LinkButton1_Click method in code behind.
By placing a dummy LinkButton you don't need to disable enableEventValidation


Does every gutter point in SVM have positive multiplier?

Question: I understand that SVM is about solving the constrained optimization such that
$$\min_{\mathbf{w}} \dfrac{1}{2} \mathbf{w}^T\mathbf{w}$$
subject to
$$y_i(\mathbf{w}^T\mathbf{x_i}+b)\geq{1}, i=1, 2, ...,n$$

And this is handled using nonlinear optimization method Karush–Kuhn–Tucker approach where one step is based on the necessary complementary slackness condition such that
$${\alpha}_i\left(y_i(\mathbf{w}^T\mathbf{x_i}+b)-1\right)=0, i=1, 2, ...,n$$ has to be satified.

Because for non-gutter dots (i.e., the points not on the edge of the separating hyperplane), we have
$$y_i(\mathbf{w}^T\mathbf{x_i}+b)-1 > 0$$
the corresponding multiplier $\alpha_i$ then must be $0$. But my question is for gutter points, because
$$y_i(\mathbf{w}^T\mathbf{x_i}+b)-1 = 0$$
we know that the corresponding multiplier $\alpha_i$ should be non-negative, but are they necessarily positive? In other words, if I define support vector as any $\mathbf{x_i}$ on the gutter, then is this the same as if I define support vector as any $\mathbf{x_i}$ whose multiplier is positive?
Comment: I think I know what you mean, but I don't think "gutter point" is standard terminology? (When I google for "gutter point" and "svm" I only get this page.)
Answer: It's mathematically possible to have cases where the constraint $y_i(\mathbf{w}^T\mathbf{x_i}+b)\geq{1}$ is satisfied with equality and where Lagrange multiplier $a_i = 0$ if the constraint isn't active in the sense that without the constraint, you would still have the same solution $\mathbf{w}$. In practice, this is probably a knife-edge case.
Intuitively, multipliers are penalties for violating a constraint
The intuitive interpretation of Lagrangian multipliers is that they are the price of violating a constraint.
Imagine that we have the problem:
\begin{equation}
 \begin{array}{*2{>{\displaystyle}r}}
 \mbox{minimize (over $\mathbf{x}$)} & f(\mathbf{x}) \\
 \mbox{subject to} & g(\mathbf{x}) \leq 0
 \end{array}
\end{equation}
The Lagrangian is:
$$ \mathcal{L}\left(\mathbf{x}, \lambda \right) = f(\mathbf{x}) + \lambda g(\mathbf{x}) $$
$\lambda$ is a penalty for having a positive $g$. The intuitive idea is that there exists a price $\lambda^*$ for violating the constraint such that the optimizer is better off not violating the constraint.
(Side note: it's worth the time to understand KKT sufficient vs. necessary conditions, the primal vs. dual problem, weak duality, strong duality, and the saddle point property of the Lagrangian.)
Simple example:
\begin{equation}
 \begin{array}{*2{>{\displaystyle}r}}
 \mbox{minimize (over $x$)} & x^2 \\
 \mbox{subject to} & -x \leq 0
 \end{array}
\end{equation}
Lagrangian is:
$$ \mathcal{L} = x^2 - \lambda x $$
First order condition implies:
$$ 2x = \lambda $$
Solution is $x=0$, $\lambda = 0$. The solution to the unconstrained problem $\min x^2$ is $x = 0$. Basically, the point is on the boundary, but the constraint isn't doing any work.
If the unconstrained solution to the problem would have placed the point $x$ on the boundary of the constraint anyway, the penalty for violating the constraint may be zero. In practice, for many problems, this will be a knife-edge case.
Comment: X=0 gives the solution to minimize x^2 and it is in the constraint -x <=0. In such cases, do we need to formulate Lagrangian? I am wondering we need to form the Lagrangian only when the the optimal point for the convex cost function does not satisfy the constraint (which I am struggling to understand now).


JQuery spinner not to reset the value according to the step

Question: On jquery spinner, I want the size of the step to be 5, but I want to keep the initial value as 1 and then it should increment 5, so the next value should be 6, and then 11, and so on. But when defining step, its ignoring the initial value and taking it as 5 and then 10 and so on. my code is :
<code>$(".square-off-ticks-count").val(1).spinner({
        step:5,
        disabled: true,
        spin: function(e,ui){
            if ( ui.value >  96) {
                $( this ).spinner( "value", 1);
                return false;
            } else if ( ui.value < 1 ) {
                $( this ).spinner( "value", 96 );
                return false;
            }
        }
    });
</code>
I want the max value to be 96. Please help.
Answer: I think you can set the min / max in the initial configuration too, so you'd probably not need the spin function.
Try this:
<code>$(".square-off-ticks-count").spinner({
    step:5,
    min:1,
    max:96
});
</code>
Comment: That wasn't my question.


Literature on mathematically representing the "no knowledge" or "partial knowledge".

Question: I'm looking for relevant literature on various ways to encode "no knowledge" or "partial knowledge".
Let's say a variable $e$ is known to take a value from a set $E$ ("environment"), but do not know which particular value it takes. Let's assume further that you want to maximise some function $f(x,e)$ ("utility") that depends on both $x$ and $e$, where you have a control over $x\in X$ ("action") for some set $X$.
In this scenario, I'm looking for ways to model this unknown variable $e\in E$. One way I know of is to treat $e$ as a random variable over $E$, and endow it with a suitable prior distribution $\mathcal{D}$. Perhaps Jeffrey's prior could be used to represent "no information". Then, you can maximise the marginalised utility
$\underset{x\in X}{\max}\,\,\underset{e\sim\mathcal{D}}{\mathbb{E}}\,[f(x,e)]$
Second method used in Game Theory is to look at the worst-case scenario; we assume that there's an adversary choosing the worst environment possible against us, and we pick the best possible action in that case:
$\underset{x\in X}{\max}\,\,\underset{e\in E}{\min}\,\,[f(x,e)]$
The prior is good at representing partial knowledge: the distribution could be more peaky, or have less entropy, as knowledge is gained. But this method relies on having a good prior, which may be a philosophical challenge in itself. The worst-case bound is good at deriving guarantees independent of the particular instance of $e\in E$, but maybe the bound is too pessimistic, in particular if there is some partial knowledge on $e$.
I'm wondering in general if there's any literature on combining the notion of the worst-case bound from game theory and the bayesian "lack of information" interpretation of probability to represent uncertainty.
Answer: There is a robust control theory developed by economists Lars Peter Hansen and Thomas Sargent that takes into account the potential misspecification of the model of uncertainty. In your context, the uncertainty is about $e$, and the model of this uncertainty is either a suitable prior (your method one) or a pessimistic prior that puts probability 1 on $\underline{e}=\arg\min_{e\in E}f(x,e)$.
They have an article that introduces the theory:

Robust Control and Model Uncertainty

as well as a book, which is a more comprehensive treatment with various applications:

Robust Control and Model Uncertainty in Macroeconomics
Answer: I was following the pointers @Herr K. has provided and came across two fields of study that are highly related to my question - robust optimization (RO) and stochastic optimization (SO).
They study the optimization problems when the data are uncertain. The difference is that RO puts the constraint on the uncertainty over the data space, while SO constrains the set of probabilistic measures over the data space. More precisely, in my scenario
$
\underset{x\in X}{\max}\,\,\underset{e\in E}{\min}\,\,[f(x,e)]
$
is an instance of RO and
$
\underset{x\in X}{\max}\,\,\underset{e\sim\mathcal{D}}{\mathbb{E}}\,[f(x,e)]
$
is an instance of SO. In fact, SO advocates a more general formulation of the above:
$
\underset{x\in X}{\max}\,\,\underset{\mathcal{D}\in \mathbb{D}}{\min}\,\,\underset{e\sim\mathcal{D}}{\mathbb{E}}\,[f(x,e)]
$
where $\mathbb{D}$ is a set of measures over the environment space $E$. Note that this formulation covers RO as well: defining $\mathbb{D}$ as the set of all single-mass (or dirac delta) measures over $E$, we retrieve the RO. So this gives an option to interpolate between the first and second problem. This answers my question fully. For those who are eager to read more I found this book helpful
Ben-Tal et al. Robust Optimization. 2009.
but the field is huge and there are also many other good books on this topic.


Why does core use print rather than echo?

Question: I've read somewhere, and I don't remember where, that echo is a more efficient way of outputting data then print.
Why does Drupal core use print so much? Is there any special reason behind that?
Comment: On a sidenote: print will always return 1 as a value, echo won't return anything. I guess that might be useful in some cases.
Comment: What kind of case that might be?
Comment: I've wondered that too! Good question!
Answer: echo is only faster in academic environments. The difference is very marginal. A quick benchmark I just did: The time fetching one row from a table with more than 2000 nodes is 1 unit.
In order to get an improvement of 1 unit, I would need to replace about 3.700.000 (over 3 milion) print statements with echo. In other words, if you want performance improvements, this is hardly the place to start.
Seen that print can be used in a much wider range of cases then echo, the first has some advantages. It leaves you three options:

Always use print
Use echo where possible and fallback on print
Use echo always and refactor your code if echo cannot be used, to use it

Drupal has defaulted on the first.
To answer your actual question as to why this was chosen: It was not. It simply grew this way.
Comment: The most obvious is `if (! print some_method() ) {print some_other_method()}`. Since print returns a TRUE if it actually printed something. Echo returns nothing, which is why it is faster too. Another example you will see is `return print $somevalue` at the end of a method to return the status.
Comment: Could you provide an example of when echo cannot be used? It's just I can't imagine any at the moment.


Power series representation of a function

Question: I am trying to find a power series representation of
$$ \frac{1-x}{1+x} $$
My textbook does it by adding one and subtracting one on the numerator. I understand this method but was wondering if anyone could give me some input on doing it by the following method:
$$(1-x)\sum_{n=0}^\infty (-1)^{n}x^{n} $$
where the series is just the geometric series replaced by  $-x$.
After multiplying out I get stuck here:
$$\sum_{n=0}^\infty (-1)^{n}x^{n} - \sum_{n=0}^\infty (-1)^{n}x^{n+1} $$
I'm not sure how I could progress or if this method is actually doable, any input would be appreciated thanks!
Comment: @Reveillark Did you not read all the way through the problem?
Comment: Yes! I understand there are other ways to do it much like the one done in my textbook, I was just hoping to get some input on the method I stated above and whether it's valid or not.
Answer: Re-index:
$$\sum_{n=0}^\infty(-1)^nx^n-\sum_{n=0}^\infty(-1)^nx^{n+1}=\sum_{n=0}^\infty(-1)^nx^n+\sum_{n=0}^\infty(-1)^nx^n-1$$

$$=-1+2\sum_{n=0}^\infty(-1)^nx^n$$
Comment: This looks like just the answer I need! I'm just a bit confused on the second step and how you got the -x at the end?
Comment: Doesn't it look like this: $(1 - x + x^2 - x^3 + \ldots) - (x - x^2 + x^ 3 - \ldots) = 1 - 2x + 2x^2 - 2x^ 3 + \ldots$?
Comment: @melm Sorry, RobArthan caught a mistake.  Indeed, I think looking at his comment may do you better.  Now, I added one to the second original sum and then re-indexed everything to look better, and to preserve equality, I subtracted one as well.
Comment: You haven't done the reindexing right: the constant term should be $1$ not $2$.
Comment: @RobArthan I can't find what I did wrong.  Could you explain?
Comment: @melm I took the $n=0$ term out of the second original sum.
Comment: @SimplyBeautifulArt I see! Thank you very much I understand now
Comment: @SimplyBeautifulArt could I ask why you added 1 to the second original sum? Is that one of the terms of the original sum? I was just a bit confused as the original sum has x to the power of (n+1) so I'm not sure where the 1 came from. Thanks!
Comment: @melm Note:$$1+\sum_{n=0}^\infty(-1)^{n+1}x^{n+1}=(-1)^{-1+1}x^{-1+1}+\sum_{n=0}^\infty(-1)^{n+1}x^{n+1}=\sum_{n=-1}^\infty(-1)^{n+1}x^{n+1}=\sum_{n=0}^\infty\dots$$
Comment: @SimplyBeautifulArt We've only just learned this, I didn't know I could do that haha thank you!
Comment: @melm :D Well, hope you enjoy!
Answer: I would prefer do the following
$$
\begin{align}
\frac{1-x}{1+x}&=-1+\frac{2}{1+x}\\
&=-1+2\sum_{n=0}^{+\infty}(-1)^nx^n\\
&=\left[-1+\sum_{n=0}^{+\infty}(-1)^nx^n\right]+\sum_{n=0}^{+\infty}(-1)^nx^n\\
&=\left[-1+(1-x+x^2-x^3+\dots)\right]+\sum_{n=0}^{+\infty}(-1)^nx^n\\
&=(-x+x^2-x^3+\dots)+\sum_{n=0}^{+\infty}(-1)^nx^n\\
&=-x(1-x+x^2-x^3+\dots)+\sum_{n=0}^{+\infty}(-1)^nx^n\\
&=-x\sum_{n=0}^{+\infty}(-1)^nx^n+\sum_{n=0}^{+\infty}(-1)^nx^n\\
&=(-x+1)\sum_{n=0}^{+\infty}(-1)^nx^n.
&
\end{align}
$$


Aesthetics must be either length 1 or the same as the data (10): x, fill in r shiny

Question: In R below code is working but inside r shiny it is giving error.
code :
ggplot(df_score) +
        geom_bar(aes(x=emotion, y=..count.., fill=hashTag),position = "dodge")

data :
   score hashTag
1  Neutral   hash1
2  Neutral   hash1
3 Positive   hash1
4  Neutral   hash1
5  Neutral   hash1
6 Negative   hash2

error :
Aesthetics must be either length 1 or the same as the data (10): x, fill

Thanks...
Comment: Unless I am missing something here, your code should be `aes(x=score..` , since there is no variable called `emotion` in your sample dataframe. Also, since the `ggplot2` code is working fine and you are having problems with `shiny` part of the code, you should include that in your question.
Comment: Thanks..I have done a very bad mistake..
Answer: You've to add 'Print' in your code.
For example:
Graph<-ggplot(df_score) +
       geom_bar(aes(x=emotion, y=..count.., fill=hashTag),position = "dodge")

print(Graph)


Radius of convergence is always $1$ proof.

Question: Show that if $p(n)$ is any nontrivial polynomial, then the radius of convergence of the power series $$\sum_{n=0}^{\infty} p(n)x^n$$ is always $1$.
So we use the ratio test to get $\lim_{n\to\infty} \left|\frac{a_{n+1}}{a_n}\right| = |x| \lim_{n\to\infty}\left|\frac{p(n+1)}{p(n)}\right|$.
Any help would be great.
Answer: For any non-trivial polynomial $p$ the limit of $|\frac {p(x+1)} {p(x)}|$ as $ x \to\ \infty$ is $1$.
Let $p(x)= \sum\limits_{k=0}^{n} a_kx^{k}$. Then $\frac {p(x+1)} {p(x)}=\frac {\sum_{k=0}^{n} a_k(x+1)^{k}} {\sum_{k=0}^{n} a_kx^{k}}$. To see what happens when you let $x \to \infty$ simply divide the numerator and denominator by $x^{n}$ and then take the limit. You will see that the limit is $\frac {a_n} {a_n}=1$
Comment: How did you get $\frac{a_n}{a_n}=1$?
Comment: @squenshl When you divide all the terms by $x^{n}$ an take the limit term by term you see that all the terms except one has limit zero and you will be left with just $a_n$ in the numerator and also $a_n$ in the denominator. For example the second last term in the numerator would be $a_{n-1}/x$ when you divide by $x^{n}$ and the limit of this as $x \to \infty$ is $0$.


NullReferenceException in System.Threading.Tasks.RangeWorker.FindNewWork in Android Xamarin app

Question: In my Android native app created with Xamarin, I get the following crash report in HockeyApp:
Xamarin caused by: android.runtime.JavaProxyThrowable: System.NullReferenceException: Object reference not set to an instance of an object
  at System.Threading.Tasks.RangeWorker.FindNewWork (System.Int64& nFromInclusiveLocal, System.Int64& nToExclusiveLocal) [0x00000] in <8f1acca5a43d45c5b8d35add5a11806a>:0
  at System.Threading.Tasks.RangeWorker.FindNewWork32 (System.Int32& nFromInclusiveLocal32, System.Int32& nToExclusiveLocal32) [0x00000] in <8f1acca5a43d45c5b8d35add5a11806a>:0
  at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback () <0xec919968 + 0x00033> in <8f1acca5a43d45c5b8d35add5a11806a>:0

I cannot figure out what is causing this exception since the stack trace only contains .net code. I have looked at the framework's source code to see if I could make sense of it but to no avail.
I have also tried many different searches in my favorites search engines without finding any posts/articles about similar issues.
From the data associated with those crashes, it seems to be an issue happening exclusively on Samsung devices (S8, S8+ and Note8). I cannot be 100% sure that it doesn't affect other devices but I only have crash reports for those.
Any idea what could cause those crashes? Am I doing something wrong with threading, maybe with cancellation tokens? Are there conditions I am not handling correctly?
Any help to further troubleshoot this issue would be very welcomed.
Thank you
EDIT:
I understand that there is not much to go by but being that this is the only stacktrace I get in HockeyApp and I cannot repro, I have no idea what code causes this.
What I am looking for is more a clue about what could cause Mono threading code to have a null reference exception when I am not managing the threads myself. Or maybe this stacktrace is just a red herring and I need to be looking in other places?
Comment: May be it's a known bug: https://github.com/xamarin/xamarin-android/issues/1188
Comment: Please either provide a [mcve] or, without one, it is off-topic and it should be closed.
Answer: You should call .IsCompleted or .Wait() soon after callback. If you do it before the Context objects might go away and if your code is accessing those Context objects will be arbitrarily null (removed).
If you call Task.Wait() it would block the thread and then throw an AggregateException once the worker throws it. Try using try catch block to handle exception.
Issue JavaProxyThrowable not always happening due to calling service there might be your activity null some where. You should check null before using activity context.
Comment: Thank you for pointing this out. I suspect that I may have some other crashes that could be caused by this. I am definitely going to be looking into it
Answer: What caught my attention was the FindNewWork32 call -- link for the .NET implementation. Your app may be compiled for 32-bit architecture, and those Samsung devices you mentioned have a 64-bit processor.
This Microsoft paper shows how to target an app to one or more Android-supported CPU architectures. You may need to target multiple platforms:

To target multiple CPU architectures, you can select more than one ABI
  (at the expense of larger APK file size). You can use the Generate one
  package (.apk) per selected ABI option (described in Set Packaging
  Properties) to create a separate APK for each supported architecture.
You do not have to select arm64-v8a or x86_64 to target 64-bit
  devices; 64-bit support is not required to run your app on 64-bit
  hardware. For example, 64-bit ARM devices (such as the Nexus 9) can
  run apps configured for armeabi-v7a. The primary advantage of enabling
  64-bit support is to make it possible for your app to address more
  memory.
Comment: I believe you were correct as after adding arm64-v8a those exceptions seem to have gone away. It is still too early to be 100% sure as not all my users are on this updated version but things are looking good so far
Comment: Happy to help. Thanks Benoit.
Answer: I know this answer is not specific for your issue, but when you are dealing with an exception message, which is so brief, it's always a good idea to check system-wide logging. In case of Android, you might get more information using dmesg command (which is giving you the content of /var/log/messages file).
Good luck
Comment: Thank you for the suggestions but unfortunately I have been unable to repro those crashes on the emulator or on my devices so I would not be able to look at those logs


Interpreting chi-squared value returned by Excel 2010

Question: I'm trying to assess whether the number of doubles (dice) being rolled by my opponents on a backgammon website are fair; to the naked eye they most definitely aren't but I need some science to back up my claims.
Using the CHISQ.TEST function in Excel 2010, I'm getting a value returned of 0.038.  What does this actually mean?
For background info, the source data is
Total dice rolls = 3962
1-1 = 114
2-2 = 116
3-3 = 107
4-4 = 125
5-5 = 134
6-6 = 131
Many thanks for any pointers!
Comment: Your six dice rolls does not sum to 3962 (I get 727). Can you clarify?
Comment: those dicerolls are his non-doubles. only the doubles are specified.
Comment: As per Sirius, total dice rolls = 3962, the doubles only are specified
Answer: This seems like a good case for the binomial test
You'd expect $1/6$ of cases to be a double when you roll two dice.
I don't have excel in front of me, but judging from google searches it seems to have the  binom.dist function available for this.
You are observing 727 doubles out of the 3962 roll total.
The probability of this many should then be 1 minus this:
=BINOM.DIST( 727, 3962, 1/6, TRUE )

If excel is worth its salt, this should give: 0.9976782. Your p-value then is 1 - this (for a one-sided test), which is less than 0.05 and you shold reconsider ever playing with your friend again!
Comment: What's the significance of the 0.05 figure?
Comment: A p-value of 0.05 is deemed suffiient to reject your null hypothesis (which is that 1/6th of throws should be doubles in this case). It's an established norm, the history of which goes beyond the scope of this question.
Answer: I don't know about excel, and what that returned value of 0.038 is. At least, excel documentation ought to tell you if it is meant as the observed chi-squared value, or a p-value.
But using R I get:
N <- 3962
> doubles <- c(114, 116, 107, 125, 134, 131)
> str(chisq.test)
function (x, y = NULL, correct = TRUE, p = rep(1/length(x), length(x)),
    rescale.p = FALSE, simulate.p.value = FALSE, B = 2000)
> chisq.test(c(N-sum(doubles), doubles), p=c(5/6, rep(1/36, 6)))

    Chi-squared test for given probabilities

data:  c(N - sum(doubles), doubles)
X-squared = 13.118, df = 6, p-value = 0.0412

so some evidence of non-uniformity. It is usefull to look at the individual cell values (contributions to the chi-squared statistic):
 obs <- c(N-sum(doubles), doubles)
 names(obs) <- c("offdiag", "1-1", "2-2", "3-3", "4-4", "5-5", "6-6")
 p <- c(5/6, rep(1/36, 6))
 E <- N*p
 (obs-E)^2 / E
  offdiag       1-1       2-2       3-3       4-4       5-5       6-6
1.3461215 0.1413708 0.3210780 0.0848337 2.0293062 5.2095182 3.9858938

so the largest contributions to chi-squared comes from 5-5 and 6-6. The test in the answer by @Sirius only considers doubles as a group, not individually, in difference from this chi-squared test that considers the doubles individually.


Is it possible to automatically (implicitly) obtain a new Google Recaptcha token?

Question: Assume that we have a page with the recaptcha and a user has already successfully passed it. App sends a request to a server and everything goes ok. Next, the user wants to perform a similar request (which require a new recaptcha token on the server side) on this very page. Basically, I don't want to force the user to pass the same recaptcha again on the same page.
So I'd like to know if there is a way to implicitly obtain a new recaptcha token.
Answer: grecaptcha.reset(id_of_captcha_div)

This resets the reCAPTCHA widget. The id passed is purely optional. So the user has to re-click the captcha to solve it. This should also generate a new token for you to send to the server.
Comment: Thanks, but it's what I actually want to avoid. Once a user has successfully passed the recaptcha I don't want to show recaptcha widget to him anymore.
Comment: I see. I thought you wanted to show another widget. Well, I'm afraid, I can't think of a solution for this. Maybe someone else has a solution for this.


Integration of combination of Bessel Function and Exponential Function

Question: I have read "Watson:Treatise Theory of Bessel Function", "Table of Integration, Series and Product", "Handbook of Mathematical Functions, Formulas, Graphs and Mathematical Tables" and other online literature. But I unable to solve a integration of combination of Bessel and Exponential function. The function is
$$
\int_{-\frac{1}{2}}^{\frac{1}{2}}e^{-\iota \omega t} I_{0}\left [
b\sqrt{1-t^{2}} \right ]dt\
$$
I am using Walform Mathematica 9.1 for Mathematical analysis. Please Suggest me particular solution, Method or formulas to integrate this combined function. Also suggest any  other Software for this type of integration.
Comment: I am basically from engineering background.
Comment: As it stands, I don't see any particular reason to expect this to have a generic closed-form solution. Can you describe the motivation behind this integral?
Comment: I have to develop Fractional Fourier Transform of this Bessel Function. I read somewhere its explanation of integration in Book Review: George A. Campbell and Ronald M. Foster, Fourier Integrals for Practical Applications  by  J. K. Lamond. In history it was solve by Ben Lagon. But I have no access to these literature. Please help.
Comment: When you say 'solved', in what sense do you mean? I could well believe that there's a series expansion (in powers of $b$, say). It's harder for me to be confident that there's a closed-form solution, though it's not impossible.
Comment: Two observations: The imaginary part vanishes. By changing the integration limits to $\pm1$, and letting $\omega=b=1$, the value becomes $2$.
Comment: The function was part of kaiser window function proposed Sir J.F.Kaier. He told to interviewer(in an interview at IEEE website) that he picked this function and Fourier transform pair from Ben Lagon office board where he was solved recently. The result of this integration on page no. 698 (point-5) in the book  "Table of Integration, Series and Product" But I can't match them. try by series expansion, subsitution for whole square root term.
Comment: Do you mean 6.616.5 of Gradshteyn and Ryzhik? Note that that integration formula has the term $e^{- a t}$ with $a>0$, and has limits $[-1,1]$. The former can perhaps be resolved by analytic continuation, but the latter is much thornier since getting to different limits is typically as hard as doing the indefinite integral.
Comment: Yes sir it is 6.616.5
Comment: Please share this question.I have to solve it at any condition. It is so tough to solve and I have not much literature except stated above about Bessel integrals
Comment: @lucian I think user need all steps. that are involve to solve this integration.because user don't have strong mathematical background.
Comment: Please suggest me any relevant solved example @Semiclassical
Comment: @Harry Peter please give me some clue
Answer: This function is derived by Slepian and Pollak in 1961 and this is also know by Prolate-spheroidal wave function. For more detail read these articles
Prolate spheroidal wave functions, Fourier analysis, and uncertainty-I
Prolate spheroidal wave functions, Fourier analysis, and uncertainty-II
In 1964 J.F. kaiser introduce this function with simple approximate to family of  window function nearly ideal properties
Everybody thanks for suggestions


How to parse current page URL query parameters to create link using l() function

Question: I have a view in D7 with a few exposed filters.  This view generates a URL/page like this:  example.com/node?location=XXX&check-in=XXX&check-out=XXX&lang=XXX.
I am looking to build a link passing in a couple of the current page's query parameters from above.  I am using the l() function and currently have the following:
print l("link_name","http://www.example.com/path", array('attributes'=>array('target'=>'blank'), 'query'=>array('lang'=>'en', 'currency'=>'USD', 'standardCheckin'=>$view->get_exposed_input(), 'standardCheckout'=>$view->get_exposed_input())));

I am looking to pass in the check-in and check-out parameter values from the views-generated page in to my link function's standardCheckin and standardCheckout keys.  What I currently have obviously does not work.  I'm using the view::get_exposed_input function to pull in the values that are in the exposed filter, but it is pulling in ALL of the query parameters.  This function does not seem to have any query parameters to limit the query.  I also looked at using drupal_parse_url and drupal_get_query_parameters, but can not get those to work either (again, getting all parameters - can not limit to just the two I need).
I can pull the values from either the URL or from the exposed filter.  My PHP is a bit limited, but what is the best function to use (and a nudge syntactically on how to limit the query would be appreciated)?  Or is there a better Drupal method for achieving this?
Answer: Maybe something like this would be sufficient?
$url = drupal_parse_url('example.com/node?location=XXX&check-in=XXX&check-out=XXX&lang=XXX.');
$desired_params = array_intersect_key($url['query'], array_flip(array('check-in', 'check-out')));

array_intersect_key() will return the values in the first array whose keys also exist in the second array, while array_flip() inverts the values in the array with their keys, actually generating something like the following (in my example):
array(
  'check-in' => 0,
  'check-out' => 1,
)

You can probably use the same approach or a very similar one with view::get_exposed_input, which is probably the best way of getting the data you need.

I didn't get that you also needed to rename the parameters. Then I don't think there's any advantage in filtering the parameters, just pull out the ones you need by hand.
$params = drupal_parse_url('...');
l("link_name","http://www.example.com/path",
  array('attributes' => array('target' => 'blank'),
  'query'=>array(
    'lang' => 'en',
    'currency' => 'USD',
    'standardCheckin' => $params['query']['check-in'],
    'standardCheckout'=>$params['query']['check-out']
   )
  )
);

Comment: I'm not sure using array_intersect_key will work.  If I understand correctly, the keys have to match in both arrays.  In my example, I'm trying to match standardCheckin and standardCheckout in first URL with check-in and check-out in second URL.  They won't match, correct?  Then, want to pull the values from first URL and insert into second URL.
Comment: I didn't get that you also needed to rename the parameters. Then I don't think there's any advantage in filtering the parameters, just pull out the ones you need by hand.

    `$params = drupal_parse_url('...');

    l("link_name","http://www.example.com/path", array('attributes'=>array('target'=>'blank'), 'query'=>array('lang'=>'en', 'currency'=>'USD', 'standardCheckin'=>$params['query']['check-in'], 'standardCheckout'=>$params['query']['check-out'])));`
Comment: This works!  Using drupal_parse_url with l() function is giving the exact results I was looking for.  Thank you!  (Note: not sure how to make your comment the answer.)
Comment: Integrating the comment in the answer itself. :)


Is there any reason to use LIME now that shap is available?

Question: The context: explaining a binary classifier XGBoost model.
If we say that we are limited to the LIME and Shapley Additive Explanation aka "shap" package, is there any reason to use LIME? My impression is that LIME is a flawed, half-solution to the problem of explaining machine learning models, that may have been "better than nothing" a few years ago, but has now been superseded Lundberg's shap package/methodology. Which addresses the shortcomings of LIME. Can anyone think of reasons to use LIME?
Comment: Does this answer your question? [Comparison between SHAP (Shapley Additive Explanation) and LIME (Local Interpretable Model-Agnostic Explanations)](https://stats.stackexchange.com/questions/379744/comparison-between-shap-shapley-additive-explanation-and-lime-local-interpret)
Comment: Major flaw of any method that try to build an explanation by constructing an other model is so called infinite-regress. That, who is going to explain the explainer model. This is a bit philosophical.  But causal models would be preferable where explanations are needed in the first place or models that can answer counterfactual queries.
Comment: It does in that it lacks any definitive defense of LIME, and brings up the consistency property, which I consider to be quite devastating against LIME. I'm hoping someone can make a compelling case *for* using LIME, to challenge my current prior against it. So far all I have seen are undefended claims that it's good in concert with shap, nothing with a compelling example, of why LIME is useful.
Comment: What type of SHAP? Kernel, tree-, deeplift, ... The theoretic SHAP enjoys many nice properties but is unfeasible to calculate in practice.
Comment: TreeSHAP, will only be working on XGBoost binary classifiers
Answer: I wouldn't say that LIME is a flawed half-solution and that SHAP is a perfect full solution.
If anything, I would say both solutions are inherently flawed but perhaps are the best we have. If you are going to use a locally correct linear approximation of your machine learning model for the purpose of explaining predictions, then I would choose whichever software tool has the least bugs and most features that you like. Perhaps SHAP offers some theoretical properties which LIME doesn't, but it's not clear that these imply correctness of explanation. Perhaps they disallow some kinds of fishy explanations.
Most people are looking for a quick-fix for understanding their models, and LIME and SHAP do that. Sometimes regulators even require it. Does that mean you truly understand your models? I don't think so.
I don't see any reason to use LIME over SHAP unless the idea of locally approximating a function with a linear function and creating augmented examples for the purpose of training appeals to you.
Besides for that, I would recommend not using SHAP or LIME if your data is not always (especially if locally - I can think of some examples like if you're using categorical features with int encoding) linear.
I think a fair approach to model explanations is one which is very broad and approaches the question from many different angles. Are you looking to see whether there are hidden confounders? unfair biases? There are a lot of sources and usually it is recommended to use a broad range of solutions in order to understand your models and it is not as simple as choosing between lime and shap. Here is an example of IBM explaining their approach https://www.ibm.com/watson/explainable-ai


Capybara detecting CSS ID model ID with find('')

Question: I am currently working on an intranet for work which will include creating invoices.
While writing tests I am using Rspec and Capybara for testing and while running a request test I want to create an invoice and add a couple of items to make sure the vat is calculated correctly.
However I seem to be having an issue where Capybara finds the first #item_price and tries to match that instead of the newly created item.
Below is some of the code in my request test.
...
...
# Laptop for 369.96 inc vat
click_link "Add Item"
fill_in "Quantity", :with => 1
fill_in "Price", :with => 369.96
fill_in "Description", :with => "laptop for 369"
click_button "Create Item"
page.should have_content("Item was successfully created")

find('#item_quantity').should have_content(1)
find('#item_price').should have_content(369.96)
find('#item_description').should have_content("laptop for 369")
find('#item_total').should have_content(369.96)

find('#invoice_subtotal').should have_content(308.30)
find('#invoice_vat').should have_content(61.66)
find('#invoice_total').should have_content(369.96)

# Laptop for 337.53 inc vat
click_link "Add Item"
fill_in "Quantity", :with => 1
fill_in "Price", :with => 337.53
fill_in "Description", :with => "laptop for 337"
click_button "Create Item"
page.should have_content("Item was successfully created")

find('#item_quantity').should have_content(1)
### the offending code below
find('#item_price').should have_content(337.53)
###
find('#item_description').should have_content("laptop for 337")
...
...

I would like to be able to add #item_price_2 where 2 would be the item ID. When doing this and changing find('#item_price').should have_content(337.53) to find('#item_price_#{invoice.id}').should have_content(337.53) I get the exception:
Nokogiri::CSS::SyntaxError:
unexpected '#' after '[#<Nokogiri::CSS::Node:0x007f991889f270 @type=:CONDITIONAL_SELECTOR, @value=[#<Nokogiri::CSS::Node:0x007f991889f3d8 @type=:ELEMENT_NAME, @value=["*"]>, #<Nokogiri::CSS::Node:0x007f991889f9c8 @type=:ID, @value=["#item_price_"]>]>]'

Also changing it to double quotes "#item_price_{invoice.id}" gives me this exception:
undefined local variable or methodinvoice' for #

I'm guessing this is because I'm not using FactoryGirl so invoice isn't set as a method yet. I'm not using FactoryGirl in this occasion because I would like to test how the user would interact with the invoice and items forms.
What would be the best way to fix this problem? Is there a better way of doing what I am trying to do?
Many thanks in advance!
Answer: Your guess about invoice not being set yet is correct. After your form is submitted you could set it:
invoice = Invoice.last
Then your specs should pass.
Comment: Thanks for your answer, it was that simple! I can't seem to get it to work. Maybe I need to go to bed and have another look in the morning but here is my show view - https://gist.github.com/140a7edded546303b609
Comment: And here is part of my spec - https://gist.github.com/4fdee18e30da12e4c3f1 - I think that's all you need?
Comment: Line 6 of your spec should actually be after the steps to fill out the form and submit data (so, around line 22). As it stands now item1 and item2 are the same.
Comment: I ended up just using `page.should have_content...` because it couldn't find any of the CSS IDs even though they were there. I may have another look at another time


Intellij Github Integration gives me a different account

Question: I am new to IntelliJ IDE. I am trying to integrate Git/GitHub with the IDE. I am basically trying to commit and push my code to my personal GitHub. The problem is that an unknown GitHub account is already linked to my IDE and I don't know how to delete it.
When I go to VCS -> Import into version control -> Share project on GitHubit shows the unknown GitHub account.
Moreover, the account does exist in the version control either (CTRL + ALT + S).
Here, I deleted my account that I previously had and recreated it. This did not work.
Moreover, I also used the command line to verify git config user.name and user.email. This gave me the correct information relating to myself.
This issue arose when I downloaded a java project for a code test.
https://i.stack.imgur.com/faGlp.png
Comment: Try deleting the account here: File | Settings | Version Control | GitHub
Comment: Thats what i did
Comment: Where exactly doe the "unknown GitHub account" is shown? Could you please provide more details - e.g. screenshots - to clarify the issue
Answer: GitHub account and git config user.name are not in fact related. Setting in git config defines the author of commits but does not affect authentication to GitHub. The GitHub account in IDE Setting, on the contrary, affects the only authentication to GitHub, but does not define authors.
IntelliJ relies on git, so all the commit author things are on the git side. The account one enters in the IDE settings is only used for authentication to GitHub. This is the only account linked to the IDE. Deleting an entry in Settings would stop IDE from using this account anywhere.
On the other hand, git client might be using its own credential-helpers to help with authentication, and if some account is saved in the helper, it might produce unexpected behavior.


Return MongoDB result to an HTTP request

Question: I have a NodeJS route that looks like this:
app.get("/search/:query", (req, res, next) => {

    let obj = SearchText(req.params.query);

    res.status(200);
    res.json(obj);

});

which calls this function:
async function SearchText(query) {
    query = "Custom";
    let mongoPromise = new Promise((resolve, reject) => {
      MongoClient.connect(url,function(err, db) {
          if (err) throw err;
          var dbo = db.db("FunLibsTest");
          dbo.collection("texts").find({"name": { $regex: query }}).toArray(function(err, result) {
            if (err) reject(err);
            resolve(result);
            console.log(result);
            db.close();
        });
      });
    })

    let results = await mongoPromise;

    return results;
}

Expected result is whatever MongoDB finds, but it always returns "FAILED".
I do not believe MongoDB has a synchronous version of "find", but I want it to act synchronously so I can return the response to the HTTP request. How could I do this?
Comment: Why do you have async before the callback of `MongoClient.connect`?
Comment: Ok, I think your new problem is a scope problem, I am going to edit my answer to fit this comment, but you should change the callback to an arrow function.
Comment: I edited my answer to put db.close() before the resolve function, I think it wasn't resolving because the db was still open.
Comment: Actually, scratch what I was trying to do before, I edited my answer to give you a more linear solution.
Comment: @gegs921 I tried adding await to the dbo.collection function, but forgot to remove the async after testing. I tried to remove it, but it unfortunately didn't help.
Answer: EDIT:
This code jumps around to a lot of places when we could just make it very linear.
function SearchText(query) {
    return new Promise((resolve, reject) => {
      MongoClient.connect(url, (err, db) => {
          if (err) throw err;
          var dbo = db.db("FunLibsTest");
          dbo.collection("texts").find(query).toArray((err, result) => {
            if (err) reject(err);
            db.close();
            resolve(result);
        });
      });
    })
}

Then to use the function
app.get("/search/:query", (req, res, next) => {

    SearchText(req.params.query).then((results) => {
        res.status(200);
        res.json(results);
    });

});

Comment: I edited my answer to solve the problem of "Promise "
Comment: I think your problem might be the fact that you have the keyword `async` written before the callback in `Mongo.connect` in your edited answer.
Comment: Ok. Yw! Also, I'm flattered.
Comment: My query was indeed wrong, so I had to fix that, but it still returns instantly even when using await and async. Quickly after it has returned, the query finishes. It returns "Promise " now though, which I guess is progress.
Comment: Logging the returned value from the function still instantly gives "Promise {  }", while logging just after "resolve(result);" gives the correct value returned by MongoDB, but only after the function has returned. Nothing makes me rip my hair out more than asynchronous functions.
Comment: @AsgeirBjelland what part of the answer helped you? I want to edit the answer so that people that look at this question in the future dont get confused.
Comment: Not sure of the specifics, but making it linear and calling the function with a callback, basically everything after the edit basically, thank you legend.


Keras Tokenizer num_words doesn't seem to work

Question: >>> t = Tokenizer(num_words=3)
>>> l = ["Hello, World! This is so&#$ fantastic!", "There is no other world like this one"]
>>> t.fit_on_texts(l)
>>> t.word_index
{'fantastic': 6, 'like': 10, 'no': 8, 'this': 2, 'is': 3, 'there': 7, 'one': 11, 'other': 9, 'so': 5, 'world': 1, 'hello': 4}

I'd have expected t.word_index to have just the top 3 words. What am I doing wrong?
Comment: https://stackoverflow.com/a/63658573/10375049
Answer: There is nothing wrong in what you are doing. word_index is computed the same way no matter how many most frequent words you will use later (as you may see here). So when you will call any transformative method - Tokenizer will use only three most common words and at the same time, it will keep the counter of all words - even when it's obvious that it will not use it later.
Comment: So `num_words` has no bearing on `fit_on_texts()` either?
Answer: Just a add on Marcin's answer ("it will keep the counter of all words - even when it's obvious that it will not use it later.").
The reason it keeps counter on all words is that you can call fit_on_texts multiple times. Each time it will update the internal counters, and when transformations are called, it will use the top words based on the updated counters.
Hope it helps.
Answer: Limiting num_words to a small number (eg, 3) has no effect on fit_on_texts outputs such as word_index, word_counts, word_docs. It does have effect on texts_to_matrix. The resulting matrix will have num_words (3) columns.
>>> t = Tokenizer(num_words=3)
>>> l = ["Hello, World! This is so&#$ fantastic!", "There is no other world like this one"]
>>> t.fit_on_texts(l)
>>> print(t.word_index)
{'world': 1, 'this': 2, 'is': 3, 'hello': 4, 'so': 5, 'fantastic': 6, 'there': 7, 'no': 8, 'other': 9, 'like': 10, 'one': 11}

>>> t.texts_to_matrix(l, mode='count')
array([[0., 1., 1.],
       [0., 1., 1.]])

Answer: Just to add a little bit to farid khafizov's answer,
words at sequence of num_words and above are removed from the results of texts_to_sequences (4 in 1st, 5 in 2nd and 6 in 3rd sentence disappeared respectively)
import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer

print(tf.__version__) # 2.4.1, in my case
sentences = [
    'I love my dog',
    'I, love my cat',
    'You love my dog!'
]

tokenizer = Tokenizer(num_words=4)
tokenizer.fit_on_texts(sentences)
word_index = tokenizer.word_index
seq = tokenizer.texts_to_sequences(sentences)
print(word_index)  # {'love': 1, 'my': 2, 'i': 3, 'dog': 4, 'cat': 5, 'you': 6}
print(seq)         # [[3, 1, 2], [3, 1, 2], [1, 2]]


Find the probability of finding $r$ distinct numbers when picked from a set of $r$ distinct elements, $n$ times.

Question: You have a set containing $r$ distinct elements say $1,2,...,r$. You pick $n (n>r)$ samples from this set with replacement (equal probability of picking any number). What would be the probability of finding $r$ distinct elements when $n$ samples are drawn?
Note: Sequence of numbers matters.
I have worked out the following:
For $r=3$, I got the following formula for finding out the number of different configurations where we get $r$ distinct elements.
$N(n,r) = \sum_{i=1}^{n-r+1} \sum_{j=i+1}^{n-r+2} r^i * (r-1)^{j-i} * (r-2)^{n-j}$
Similarly, for $r=4$,
$N(n,r) = \sum_{i=1}^{n-r+1} \sum_{j=i+1}^{n-r+2} \sum_{k=j+1}^{n-r+3} r^i * (r-1)^{j-i} * (r-2)^{k-j} * (r-3)^{n-k}$
The probability of the event would be $\frac{N(n,r)}{r^n}$.
As $r$ increases, I don't think the formula for $N(n,r)$ is appreciable. There must be a better (elegant) way to solve this. Any leads are appreciated!
Thanks in advance!
PS: This might be asked before as well. I tried my best to see if there are similar questions, but couldn't find one. I would appreciate if anyone could point me to one if it exists!
Comment: Please clarify your question: you set up a probability space, but then you ask for the number of possible configurations, without regards to their differing probabilities. You also say "$r$ distinct numbers say $0,1,2,\dots,r$", which is also contradictory.
Comment: @GregMartin, thank you for your reply! I corrected the "r distinct numbers say $0,1,2,..$" part. Also, I modified the question. I hope it's clear now. Thanks again!
Comment: Why do you say the sequence of numbers matters?  You only care whether every number is selected at least once.  How is $1,2,3,1$ different from $1,1,2,3$?
Comment: @RossMillikan, for the case I'm looking at, $1,2,3,1$ is different from $1,1,2,3$. This is because I'm looking at the total number of possible configurations while calculating the probability. For Eg; when $r=2, n=3$, $N(3,2) = 6$. So, $P(E) = \frac{6}{8}$. Here, $N$ consists of $(1,2,1), (1,1,2), (2,1,1), (2,1,2), (2,2,1), (1,2,2)$ while total configurations consists of $(1,1,1), (2,2,2)$ in addition to $N$.
Answer: This is an inclusion-exclusion calculation.  The chance that a specific number is missing is $\left(\frac {r-1}r\right)^n$.  The chance that some number is missing would be $r$ times this, but we double count the cases where two numbers are missing, so need to add them back in once.  Then we removed the ones with three numbers missing three times and added them back in three times, so need to subtract them once and so on.  You get
$$1-r\left(\frac {r-1}r\right)^n+{r \choose 2}\left(\frac {r-2}r\right)^n-{r \choose 3}\left(\frac {r-3}r\right)^n+\ldots$$
Comment: thanks a lot for such an elegant solution! Never thought of it this way! I cannot upvote the answer as I do not have 15 reputations :(. But, will do when I get 15!
Answer: The Stirling number of the second kind, $\big\{ {n\atop r} \big\}$, is defined to be the number of ways to partition a set of $n$ elements into $r$ nonempty (unlabeled) subsets. It's not hard to see that your counting problem is asking about the same question for labeled subsets, the answer for which is simply $r! \big\{ {n\atop r} \big\}$. Therefore the probability in question is $\frac{r!}{r^n} \big\{ {n\atop r} \big\}$. This is consistent with the formula given in Ross Millikan's answer.
Comment: Thanks a lot for another approach/perspective on this problem! However, I think the probability is $\frac{r! \big\{ {n\atop r} \big\}}{r^n}$, if I'm not wrong.
Comment: Thanks for the correction—edited


Filling SVG element, working on data from JSON

Question: Hello I have JSON file with this structure (I have 249 countries, all with iso codes)
and as you can see I want to declare iso code as var iso, and visitors, as var visitors, and then if visistors have more than 1, and less than 50, fill SVG element where ID=iso with #94d31b, but it doesn't work... I don't know what to do now. and before I do "if" I want to fill Canada, but console says that ca does not exist, but I have this element in SVG, and when I delete this line, and put this line into if, then I have no error, so if doesn't work, because if he did, he should say that "ca" does not exist.
Answer: You're looping through your data incorrectly. You actually want to loop through the data.iso_countries array. Try:
$.getJSON("results.json", function(data) {
    data = data.iso_countries; // the array we really want
    for(var key in data) {

As for how to access individual parts of the SVG image, see this question.
Comment: It works, because now if works either, but this I have in console
TypeError: document.getElementById(...) is null
document.getElementById("iso").style.fill="#94d31b";
because I want to get ID by iso, because iso has actual isocode
document.getElementById(iso).style.fill="#94d31b"; if I put document.getElementById(ca).style.fill="#94d31b"; and then console says that ca does not exist, but in SVG Canada has id="ca" :|
Comment: Added a link to an existing question that should help you with that.
Comment: Thank you :) I updated my original post with new data from that link, because now, console says that svgMap is undefined...
TypeError: svgMap is undefined
svgMap.getElementById(iso).style.fill="#94d31b";
Comment: That should be a fairly straightforward fix. If your code has multiple problems, try to narrow them down and post them as separate questions.
Comment: it works! haha but now I don't know why, because if I use <embed to load this SVG, then it doesn't work, if I put whole SVG code just on site, then it works :D do you know why? I mean, do you know why even if I try to take SVG DOM structure, I cant?
Comment: I'm not sure how the DOM views `` versus ``, but I can't say I'm surprised, either. I think it interprets `` in the same way as `` and considers it a separate document. I may be way off, though.


"could not find the database engine startup handle sql 2008 r2" error

Question: I have hit a brick wall here... I am trying to install ssrs in one of my other VM. After installing sql server express and ssms(which installs successfully), I have tried to install ssrs(making another instance "MSSQLSERVER")... I always get this error...

could not find the database engine startup handle sql 2008 r2

Here is my log file
<code>Log Name:      System
Source:        Service Control Manager
Date:          10/8/2012 12:51:32 PM
Event ID:      7024
Task Category: None
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      REPORTING
Description:
The SQL Server (MSSQLSERVER) service terminated with service-specific error Only one      usage of each socket address (protocol/network address/port) is normally permitted..
Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
<System>
<Provider Name="Service Control Manager" Guid="{555908d1-a6d7-4695-8e1e-26931d2012f4}"    EventSourceName="Service Control Manager" />
<EventID Qualifiers="49152">7024</EventID>
<Version>0</Version>
<Level>2</Level>
<Task>0</Task>
<Opcode>0</Opcode>
<Keywords>0x8080000000000000</Keywords>
<TimeCreated SystemTime="2012-10-08T16:51:32.010000000Z" />
<EventRecordID>6103</EventRecordID>
<Correlation />
<Execution ProcessID="424" ThreadID="2800" />
<Channel>System</Channel>
<Computer>REPORTING</Computer>
<Security />
</System>
<EventData>
<Data Name="param1">SQL Server (MSSQLSERVER)</Data>
<Data Name="param2">%%10048</Data>
</EventData>
</Event>
</code>
I figured, I need to stop SQLEXPRESS first, so I stopped SQLEXPRESS and tried to reinstall ssrs, it works fine, but now I cannot start SQLEXPRESS... how can I install MSSQLSERVER instance for ssrs, without stopping SQLEXPRESS... please help
Answer: Figured this out... anyone with similar issues, please do not use another instance like I did... just install it as "sqlexpress" and You should not be getting errors... however I had to manually configure ssrs...


Usar valor modificado dentro de IF em outra variável

Question: Tenho uma condição de valor que é alterado dentro de IF e precisava usa-lo em outra opção chamada por menu, como posso executar?
from datetime import datetime

print("Bem-vindo usuário!")

menu = print('[1] Entrada/Saída\n[2] Estado atual de veículo\n[3] Vagas disponíveis')

iniciar = int(input("Digite opção para iniciar: "))

data = datetime.now().strftime('%H:%M dia:%d/%m/%Y')

vrestantes = 100

vagas = 100

if 1==iniciar:
    while (vrestantes > 0):
        carro = input("Digite placa: ")
        acao = int(input("[1]Entrada ou [0]Saida?: "))

        if acao ==0:
            print("Saída do carro {} às {}".format(carro,data))
            vrestantes = vrestantes + 1
            print("Total de vagas disponíveis: {}".format(vrestantes))
            if vrestantes > 100:
                print("Vagas não podem ser maiores que 100 por limitação de espaço")

        else:
            if acao ==1:
                print("Entrada do carro {} às {}".format(carro,data))
                vrestantes = vrestantes - 1
                print("Total de vagas disponíveis: {}".format(vrestantes))

caso eu queira acionar uma outra opção no menu (ex:3) para imprimir o valor que foi alterado, teria como?
no caso eu queria usar a função vrestantes e imprimir ela com um valor atualizado
Answer: No python usamos o elif para adicionar condições. Com três opções ficaria assim:
if acao == 0:
    ...
    ...
elif acao == 1:
    ...
    ...
elif acao == 2:
    ...
    ...


On git status I'm getting the subfolders of the main folder i want to add

Question: I want to add the main folder "my_project" to my bitbucket account, but on git status I'm getting the subfolders of the folder "my_project". So when I type in git add my_project im getting an error. How can I get to be displayed in the cmd the main folder "my_project" and not the subfolders of it? Can anyone help me?
I have tried with git reset and other stuff but it didn't help me.
Here I'm getting the subfolders of my_project and I don't have only my_project folder that contains the subfolders.

Here is the folder my_project on C disc
Comment: Why is your entire user directory a Git repository? (That's not C drive, that's `C:/Users/{your_user}/`) I assume you want that `.git` folder to be inside `my_project` instead?
Comment: AFAIK if you add the parent directory, then all subdirectories will also be added, unless you excluded them through a `.gitignore` file.
Answer: Delete the .git directory from your home directory.
rm -rf .git/

Then go to your project directory
cd my_project/

Now initialize git repository
git init
git status


Using a 3g usb dongle as Cisco router access point

Question: We have an office opening, and we aren't going to have comms into the building when management want the building to open.
Our only option (I think) Is to try and hook up a 3/4g dongle to something to act as the access point, and send all the traffic via that. The model of router we use wont support the usb dongle, so we need some sort of 'bridge'
My idea was to build a Linux box, plug the dongle into that and then via the Ethernet ports plug the router in.
We need the Cisco router in the equation as we create VPN connections over that back to head office. My question is will this work?
Comment: If you really have to go the 3g/4g route why not get an actual router that supports it like an 819 or RV215W?  Why make it more complex than it has to be?  And management is opening an office and doesn't want to spend the quite cheap funds to do it even semi-right?
Comment: We are moving the office from one building into another, so all the existing kit is being utilized, so we cant spend any money on it. Plus our main network guy has had issues in the past putting in new router models without testing them, so its not really an option. Its hopefully only going to be used for a month at the most
Comment: OK, then if your question is can you route LAN traffic through the Cisco router out the Linux box using a 4g card/dongle...sure, I don't see why not.  But everyone's situation is somewhat unique, so you'll have to decide if it will work for you and your team.
Comment: i think we might be on a bit of a fail with this anyway. The dongle seems to have been given an ip address in a private range, not a public one, so i dont think we'll be able to create a vpn tunnel to it anyway
Answer: www.cradlepoint.com
Snag one of those devices - seems to be the most widely deployed solution that I've seen for your use case.
http://www.cradlepoint.com/products/branch-office-retail-pos/cba750b-mobile-3g-4g-broadband-adapter
Answer: We never ended up using this, we just setup ICS on one pc, installed client vpn on the others and used that as the access point. Not ideal but it worked short term


Showing a set is Borel and a function is Borel measurable.

Question: I am stuck in the following question:
Suppose $f: B \rightarrow \mathbb{R}$ be a Borel measurable function. Let $g(x)=\begin{cases}
 f(x), & \text{if } x \in B,\\
 0,    & \text{if } x \in B^c
\end{cases}$.
I would like to first show that $B$ is a Borel set and that the function $g$ is Borel measurable. I know the required definitions, but I can't figure out how to put things together to solve this. Would someone please help?
Answer: Well the definition of a Borel measurable function is that the preimages of Borel sets are Borel. $\mathbb{R}$ is a very Borelly Borel set, so $f^{-1}(\mathbb{R}) = B$ is Borel as well. Simple as that!
Again to show that $g$ is Borel you need to show that $g^{-1}(A)$ is Borel for every Borel $A \subseteq \mathbb{R}$. But notice we may divide this into two cases: if $0 \in A$, then $g^{-1}(A) = B^{c} \cup f^{-1}(A)$. Both of these are Borel since, again $f$ is Borel measurable and $B^{c}$ is Borel as $B$ is (sigma algebras are closed under complements). And otherwise if $0 \not \in A$, then $g^{-1}(A) = f^{-1}(A)$ which is again Borel as $f$ is Borel measurable. Thus the $g$ preimages of borel sets are Borel, meaning $g$ is Borel.
Comment: (+1) for "$\mathbb{R}$ is a very Borelly Borel set" I might have used your expression in [this comment](https://math.stackexchange.com/questions/4007632/is-there-a-mathematical-way-to-measure-complexity#comment8290165_4007632) if I had seen it  a few weeks ago!
Answer: $B$ is a borel set because we may take $f^{-1}(\mathbb{R})=B$.
As for $g$, we see that $g^{-1}(0)$ is the complement of $B$ which must be a borel set since our borel sigma algebra is closed under complement. $g$ behaves as $f$ otherwise which implies it is borel measurable.


Wave Equation - Initial Value Problem

Question: Given
$$ u_{tt}−\Deltau = 0, \ \  for \ \ t≥ 0, \ x∈ \mathbb{R^3} $$
With initial conditions
$$ u(x, 0) = cos|x| $$
$$ u_t(x, 0) = 1 $$
Find $u(0, t)$ for all times $t>0$
$$$$
Perhaps here it is possible to somehow use D'Alambert's formula by reducing the system to radial coordinates using $r$ instead of $(x_1,x_2,x_3)$ ? Thank you for your help.
Answer: I figured it out. Use Kirchhoff Formula

Wave Equation - Initial Value Problem


Question on pointwise convergence of Sequence of functions

Question: In section 8.2 of  textbook "Introduction to real analysis by Bartle" example 8.2.1(c) is as follows:
$f_n : [0,1] →\mathbb{R}$ defined for $n≥2$ by
$$f_n(x) =
  \begin{cases}
     n^2x & \text{for $0≤x≤1/n$} \\[6pt]
    -n^2(x - 2/n) & \text{ for 1/n≤x≤2/n} \\[6pt]
  0 & \text{for 2/n≤x<1}
   \end{cases}$$
then $f_n$ is continuous on $[0,1]$ and hence Riemann integrable______ (upto this i have no problem)
My problem$f_n(x)→0$ for all $x\in\mathbb{R}$ but i unable to see this...
My attempt clearly for $x=0$, $f_n(0)=0$
For $0<x<1/n$, $|f_n(x)-f(x)|=|n^2x|=n^2x$
How, can say this is $<\epsilon$ for sufficiently large $n$?
Further, for other points $x$ how to establish its convergence and how to show integral of $f_n\text{  from $0$ to $1$}=1$  for $n≥2$
Please help and explain this example 8.2.1(c) in detail.
Comment: If $x$ is fixed, eventually $x > 2/n$ as $n$ increases
Answer: For a fixed $x \in (0,1]$, there exists  a positive integer $N > 2/x$.
Thus, for all $n \geqslant N$ we have $x > 2/n$ and $|f_n(x)-0| = f_n(x) = 0$.
Comment: @AkashPatalwanshi: You are trying to prove pointwise convergence to $0$. You consider a fixed value of $x$ in $(0,1]$. All that matters is for any $\epsilon > 0$ when $n > 2/x$ then $x > 2/n$  and $|f_n(x) - 0| < \epsilon$ -- trivially because $|f_n(x) - 0|  = 0$ for all $n > 2/x$. we don't care about $f_n(x)$ for small $n$ since we are looking at the limit as $n \to \infty$.
Comment: sir, so need to use the definition $n^2x$, $-n^2(x-2/n)$ since $x>2/n$ ?


Is a figured bass symbol supposed to show a raised 6th scale degree?

Question: I am harmonizing this figured bass

Please look at the E note where the blue arrow is pointing. I have raised this note because otherwise there would be an aug 2nd leap to the F#. Can someone please explain if raising this tone should appear in the figured bass symbols because in my exercise there is no figured bass symbol. Initially I wrote a Cm chord because the figured bass didnt say anything but the ^6 must be raised in this progression right?
Answer: It should be an E flat, not an E natural.  To avoid the augmented second, the E flat should be in a different voice from the F sharp.
(The melodic diminished fifth between the B flat and the E natural that you have in the soprano voice is also, in general, to be avoided.)
Comment: My voice leading book says the melodic dissonant leaps can be used to good effect so long as a change of direction smooths things out. Can you please explain why specifically you say that a d5 is to be avoided?
Comment: @armani it's one of those things that you have to be careful about more than that must be avoided at all costs, but melodic tritones are very rare and difficult to sing correctly.
Answer: Since there are no alterations for that chord in the figured bass, this pitch should definitely be an E♭, not an E♮.
You're right, though, that that creates an augmented second between E♭ and F♯. The solution is not to change the first pitch to E♮, but rather to move the soprano down from E♭ to D. Doing so will likely necessitate moving all three upper voices down; this will put a leap of a third in the alto (C down to A), but that's 100% acceptable.
If you're worried that the soprano is getting too low on that D, then good news: it can hop back up to a G on the succeeding i6 chord.
Comment: I would argue that changes are needed earlier in the exercise than on the first beat of the sixth measure.  But perhaps suggesting changes up front isn't the most effective way to answer, from a pedagogical standpoint.
Comment: Thanks for the fix.. So the figured bass would show a natural sign if I was supposed to raise the ^6? And the fact that it doesnt do so, means I am not allowed to voice the chord with the E in the soprano. Right?
Comment: @armani Correct. The E-flat can be in the soprano, but without the natural in the figured bass, there's no E-natural in this chord.
Comment: Now that I think about it, after the leap down to E, if I take the soprano down to D then wont it be wrong because the melody doesnt change direction after such a big leap?
Comment: @armani In a very strict style, perhaps that would be unideal, but I wouldn't exactly consider it wrong. It sounds stylistic to me when I look at it. But if you're worried, move the soprano from B-flat up to C, and then everything else should work out.
Answer: If no alteration was mentioned, than it shouldn't be raised.
In addition, that tritone leap between the Bb and the E♮ in the soprano is not really ideal and should be avoided (usually melodic tritones are avoided in the soprano parts), and it is better to start a melodic minor melodic line with the 5th degree instead of directly with the raised 6th. It is also better to avoid using the leading tone in the soprano (since in sometimes it might force you to solve it into a no 5th tonic). All are just suggestions.
I think the best solution for this issue would probably be taking the soprano to Eb and then to D, while the C (Alto) would go down to A and the G (Tenor) to F#. It would force you to get some of the voices a little low, but it is a proper solution for this situation, and it is very common to make a leap after a 4/2 chord.
You could fix it with replacing the Bb in the soprano before, but it would require you some more changes.


Validar login PHP

Question: Boas, Estou a tentar efetuar um login no pequeno projecto e estou com dificuldade em caso seja o $login esteja correcto vá para o compras.html caso esteja errado aparece login ou password errados.
$login = mysql_query("SELECT Nome, Password FROM tb_utilizador WHERE Nome ='$Nome' AND Password = '$Password'");

if ($login = TRUE ) {

    header('location: Compras.html');
} else {

    // falhou o login
    echo "
Utilizador ou password invalidos. Tente novamente
";
}

}
Answer: Tente dessa forma:
$login = mysql_query("SELECT Nome, Password FROM tb_utilizador WHERE Nome ='$Nome' AND Password = '$Password'");

$res = mysql_fetch_row($login);
   if($res)
   {
     header('location:compras.html');
   }

   else
   {
     header('location:error.php');
   }

O error.php irá ser a página onde você irá disponibilizar uma mensagem informando que o utilizador e/ou password se encontram incorretos. No caso de não ser essa a página você apenas altera o nome mostrado. Apenas coloquei error.php como exemplo para página de erro

Validar login PHP


How do I select how many pantients every doctor has?

Question: I have a table of Visits on the Hospital, included DoctorID, PacientID, Date....
I did like this but I recieved an error.
SELECT
d.DoctorID, COUNT(v.DoctorID)
FROM Visits v
left join Doctors d on  v.DoctorID=d.DoctorID

Answer: You care missing the group by:
SELECT d.DoctorID, COUNT(v.DoctorID)
FROM Doctors d LEFT JOIN
     Visits v
     ON v.DoctorID = d.DoctorID
GROUP BY d.DoctorID;

In addition, you presumably want the LEFT JOIN starting with Doctors so you keep all doctors.
Answer: Your query is missing a GROUP BY clause. Also I do not see the need for a JOIN. If you want the count of (distinct) patientsIDs per doctorID, you can get that information directly from the visit table, like so:
select doctorID, count(distinct patientID) from visits group by doctorID

Or, if you also want to see doctors that have no patients:
select d.doctorID, count(distinct v.patientID)
from doctors d
left join visits v on v.doctorID = d.doctorID
group by d.doctorID

Answer: Live demo on db<>fiddle
You are missing GroupBy clause.
So you can fix it in this way
SELECT d.Name, COUNT(v.DoctorID) AS PantientCount
FROM Doctors d
LEFT JOIN Visits v ON d.DoctorId = v.DoctorId
GROUP BY d.Name

You can also using Conditional aggregation query with a group by like below.
SELECT d.Name, SUM(CASE WHEN v.CustomerId IS NOT NULL THEN 1 ELSE 0 END) AS PantientCount
FROM Doctors d
LEFT JOIN Visits v ON d.DoctorId = v.DoctorId
GROUP BY d.Name

Output
Comment: Does this answer your question? Let me know if you need any help @Patrycja Bobek


Do I need both TransientFaultHandling and SaveChangesWithRetries for save data into Azure Storage?

Question: http://msdn.microsoft.com/en-us/library/hh680905(v=pandp.50).aspx
Transient Fault Handling gives the ability to handle connection errors etc.
SaveChangesWithRetries() says it can also retry when fault.
I like to know, Do I need to use TransientFaultHandling wrap on SaveChangesWithRetries;
or: since they are preventing the same thing, so SaveChangesWithRetries() is enough
Answer: That is very interesting.  I would not have thought that the 'Transient Fault Handing' (TFS) guide would have been used at all with the Windows Azure Storage client.  For blobs and queues (also with some table operations), there is already a default Retry policy on it.  So, if you were going to use the TFS policies in conjunction, I would definitely remove the Retry policy (using Retry.NoRetry) that is on the storage clients by default (which is a exponential backoff within 30 seec each, 4 retry policy).
All of this being said, I have found in practice that retry policies for Windows Azure storage have proved to be worse than useless (i.e. you are better off NOT using them at all).  Without specifying a very custom retry policy, they actually don't work well at all.  Note, I am talking about storage here and not SQL Azure.  Since you are using a REST based protocol, there is no stateful connection that can get 'reset' where a retry policy kinda makes sense.  Most of the errors you end up seeing (> 90% from experience) are ones that you would never want to retry anyway.  For instance, most failures are 403 forbidden, DNS resolution failures, 404 errors, etc.  Almost without exception, you would never want to retry those (e.g if you have bad credentials, why would you try 4 more times?).  What ends up happening in most cases, is that you are retrying an error that will never succeed and you waste ~2 minutes (4 retries at 30 secs each) to finally give up.  My advice is to simply disable the policy and just handle the exception.
Comment: I see that error very rarely.  I wonder why you are seeing that so much.  If necessary you can keep the default policy for some read operations and remove it for writes and such.
Comment: I got lots of error like `No connection could be made because the target machine actively refused it 184.108.40.206:443`. I use retry policy `new FixedInterval(3, TimeSpan.FromSeconds(1));`. Hope this work, will see
Comment: I also wondering why I hit the error so much, and why I always hit on same machine, check my new question please http://stackoverflow.com/questions/9859286/azure-table-storage-how-to-avoid-connection-error-i-tried-retry


Ripple effect in StackLayout or Grid after click

Question: How to achieve an effect of smooth change of background color in StackLayout or Grid after the click? If we create a button it has this effect out of the box - I showed that in an attached gif. The same is for ViewCell in ListView. It also has this ripple effect of changing background color after a click. But how to achieve that for StackLayout or Grid?
How to achive this
Answer: Solution 1:
Thought you said that ViewCell  has the ripple effect of changing background color after a click .You can put the Stacklayout or Grid in the listview which has only one ViewCell.

in xaml

<StackLayout>

    <ListView x:Name="listView">

        <ListView.ItemTemplate>

            <DataTemplate>

                <ViewCell>

                    <StackLayout>

                    </StackLayout>

                </ViewCell>

            </DataTemplate>

        </ListView.ItemTemplate>

    </ListView>

</StackLayout>

in code behind

public class Data
{
    public string Content { get; set; }
}

public partial class MainPage : ContentPage
{

    public ObservableCollection<Data> MySource { get; set; }

    public MainPage()
    {
        InitializeComponent();

        BindingContext = this;

        MySource = new ObservableCollection<Data>()
        {
          new Data() {Content="Click Me" },
        };

        listView.ItemsSource = MySource;

    }

}

Solution 2:
You can use the package TouchView from nuget
Add nuget package to your Xamarin.Forms .netStandard/PCL project and to your platform-specific projects (iOS and Android)

iOS: add TouchViewRenderer.Initialize() line to your AppDelegate
  (preserve from linker)

using TouchEffect.iOS;
namespace YourApp.iOS
{
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
    {
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();
            TouchViewRenderer.Initialize();
            LoadApplication(new App());
            return base.FinishedLaunching(app, options);
        }
    }
}

in xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:YourApp"
             xmlns:touch="clr-namespace:TouchEffect;assembly=TouchEffect"
             x:Class="App11.MainPage">

    <StackLayout>
        <touch:TouchView
            RegularBackgroundColor="LightGray"
            PressedBackgroundColor="Gray"
            PressedOpacity="1"

            PressedAnimationDuration="100"
            RegularAnimationDuration="100"
            Padding="10, 5"
            VerticalOptions="CenterAndExpand"
            HorizontalOptions="CenterAndExpand"
            Completed="Handle_TouchCompleted"
           >

        </touch:TouchView>
    </StackLayout>

</ContentPage>

in code behind

private void Handle_TouchCompleted(TouchEffect.TouchView sender, TouchEffect.EventArgs.TouchCompletedEventArgs args)
 {
    // do something you want
 }

Answer: BotonRefrescar.BackgroundColor = Color.FromHex("#32CEF9");
    Device.StartTimer(TimeSpan.FromMilliseconds(200), () =>
    {
        //do something
        BotonRefrescar.BackgroundColor = Color.FromHex("#32BBF9");
        return false;
    }
);

Comment: Why does your answer just has a bunch of code with 0 explanation?


Node image instead of pointer icon in openlayers map

Question: Does anyone know a way to change the pointer icons to node images?
Like the image below

I really like to have a little preview image from the node instead of hundreds of same looking pointers.
Any ideas?
Answer: output the image's URL in your view which supplies data to your map.
create a new openlayer style, and for the marker graphic, give it your field name enclosed in ${}.
eg. add field_image to your view, set it to output 'url to file'
then add a new style and tell it the marker graphic url is ${field_image} and select an image style (eg. thumbnail)
use this new marker style on your overlay and you'll see the image show up as a marker icon.


Extra handler breaks Datepicker field

Question: Problem
I have a form which a user can create data with and some of the fields are date fields which use jQuery datepicker.
The form is long and in order to help the user out, I have a series of help messages which appear when the relevant form input is focused.
When a form element is given focus, the form's ID is grabbed and attached as a class to the help div, which reveals the correct help message.
Example: jsfiddle - caveat in a moment
This works in the jsfiddle, however in Drupal it breaks. On click the calender opens but rather than selecting a link it hits the local hyperlink "#" below it and changes the url to http://mywebsite.com/form/#
The problem appears to be related to how the Drupal date jQuery module deals with Datepicker. I've narrowed it down to something to do with $(this).attr('id'), it doesn't like the that selector but I'm unsure as to why.
Full Script
  Drupal.behaviors.jobhelpAddClass = {
    attach: function (context, settings) {

      var jobHelp = $('#jobhelp').children();

      $('input, select').focus(function() {
        $(jobHelp).attr('id', $(this).attr('id'));
      });
    }
  };

I've tried with document ready instead of Drupal behaviours and it still breaks. I've also tried getting focus to call a function (with the same code), however neither works.
Answer: Looks like the problem is with the CSS rather than the id part. The typical id would be something like this: edit-field-date-und-0-value-datepicker-popup-0 and this id is dynamically generated and not grandee that it would stay same (i.e. you may get edit-field-date-und-0-value-datepicker-popup-1 if you have the same field twice in the same form).
You can use name instead of id. Here is the working fork of your jsfiddle with name: http://jsfiddle.net/vijaycs85/C4sh9/

Extra handler breaks Datepicker field