TCP Sockets Client/Server - server only respondsto first connection from client

Question: I have some simple client and server code, where the client sends some bytes to the server, and the server responds with some bytes.  The client prints the received bytes, and then closes the socket.
This works fine the first time  the client runs, but subsequent calls get no response.
package sockets.com;

// Client Side
import java.io.*;
import java.net.*;

public class ClientSideTCPSocket {
    public void run() {
        try {
            int serverPort = 4023;
            InetAddress host = InetAddress.getByName("localhost");

            System.out.println("Connecting to server on port " + serverPort);

            Socket socket = new Socket(host, serverPort);

            System.out.println("Just connected to " + socket.getRemoteSocketAddress());

            OutputStream out = socket.getOutputStream();
            InputStream in = socket.getInputStream();

            String s = "HELLO SERVER";
            byte[] bytes = s.getBytes("US-ASCII");

            for (byte b : bytes) {

                out.write(b);

            }

            int ch = 0;
            while ((ch = in.read()) >= 0) {

                System.out.println("Got byte " + ch);
            }

            out.flush();
            out.close();

            socket.close();

        } catch (UnknownHostException ex) {
            ex.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ClientSideTCPSocket client = new ClientSideTCPSocket();
        client.run();
    }
}

Server code
package sockets.com;

//Server Side
import java.net.*;
import java.io.*;

public class ServerSideTCPSocket {
    public void run() {
        try {
            int serverPort = 4023;
            ServerSocket serverSocket = new ServerSocket(serverPort);
            serverSocket.setSoTimeout(900000);
            while (true) {
                System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");

                Socket server = serverSocket.accept();
                System.out.println("Just connected to " + server.getRemoteSocketAddress());

                //
                int ch = 0;
                while ((ch = server.getInputStream().read()) >= 0) {

                    System.out.println("Got byte " + ch);
                }
                // Write to output stream

                OutputStream out = server.getOutputStream();

                String s = "HELLO CLIENT";
                byte[] bytes = s.getBytes("US-ASCII");

                for (byte b : bytes) {
                    System.out.println(b);

                    out.write(b);

                }

            }
        } catch (UnknownHostException ex) {

            ex.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ServerSideTCPSocket srv = new ServerSideTCPSocket();
        srv.run();
    }

}

Would be grateful for any comments regarding why this is  the case.  Thank you.
Answer: A few things:
This block of code will loop forever until after the client closes his connection:
            while ((ch = server.getInputStream().read()) >= 0) {

                System.out.println("Got byte " + ch);
            }

Then after the client closes his connection, the subsequent attempt to send "HELLO CLIENT" to the socket will generate an IO exception.  That will trigger your server loop to exit.
The easy fix is to adjust your protocol such that the "message" is completed on some sentinel char.  In my easy fix, I just adjusted it to break out when a ! was received.
Better to have each client session terminate on an ioexception instead of the entire server block.  My refactor of your code:
public class ServerSideTCPSocket {

    public void tryCloseSocketConnection(Socket socket) {
        try {
            socket.close();
        }
        catch(java.io.IOException ex) {
        }
    }

    public void processClientConnection (Socket clientConnection) throws java.io.IOException {

        int ch = 0;
        while ((ch = clientConnection.getInputStream().read()) >= 0) {

            System.out.println("Got byte " + ch);
            if (ch == '!') {
                break;
            }
        }
        // Write to output stream

        OutputStream out = clientConnection.getOutputStream();

        String s = "HELLO CLIENT!";
        byte[] bytes = s.getBytes("US-ASCII");

        for (byte b : bytes) {
            System.out.println(b);
            out.write(b);
        }
    }

    public void run() {
        try {
            int serverPort = 4023;
            ServerSocket serverSocket = new ServerSocket(serverPort);
            serverSocket.setSoTimeout(900000);
            while (true) {
                System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");

                Socket clientConnection = serverSocket.accept();

                try {
                    System.out.println("Just connected to " + clientConnection.getRemoteSocketAddress());
                    processClientConnection(clientConnection);
                }
                catch (java.io.IOException ex) {
                    System.out.println("Socket connection error - terminating connection");
                }
                finally {
                    tryCloseSocketConnection(clientConnection);
                }
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ServerSideTCPSocket srv = new ServerSideTCPSocket();
        srv.run();
    }
}

Then adjust your client code's message to be:
        String s = "HELLO SERVER!";  // the exclamation point indicates "end of message".

Comment: Thanks.  In reality, the server will be receiving messages from a client written in C, which cannot be modified.  The client will be sending a fixed length of 256 bytes and then closing after receiving the response.
Comment: Then your terminating condition for the read loop is to break out of the loop after pulling out the 256th byte.  I'll leave that as exercise for you to complete.


Copy ~200.000 of s3 files to new prefixes

Question: I have ~200.000 s3 files that I need to partition, and have made an Athena query to produce a target s3 key for each of the original s3 keys. I can clearly create a script out of this, but how to make the process robust/reliable?
I need to partition csv files using info inside each csv so that each file is moved to a new prefix in the same bucket. The files are mapped 1-to-1, but the new prefix depends on the data inside the file
The copy command for each would be something like:
aws s3 cp s3://bucket/top_prefix/file.csv s3://bucket/top_prefix/var1=X/var2=Y/file.csv

And I can make a single big script to copy all through Athena and bit of SQL, but I am concerned about doing this reliably so that I can be sure that all are copied across, and not have the script fail, timeout etc. Should I "just run the script"? From my machine or better to put it in an ec2 1st? These kinds of questions
This is a one-off, as the application code producing the files in s3 will start outputting directly to partitions.
Comment: Thanks @JohnRotensteinI have updated my answer
Answer: If each file contains data for only one partition, then you can simply move the files as you have shown. This is quite efficient because the content of the files do not need to be processed.
If, however, lines within the files each belong to different partitions, then you can use Amazon Athena to 'select' lines from an input table and output the lines to a destination table that resides in a different path, with partitioning configured. However, Athena does not "move" the files -- it simply reads them and then stores the output. If you were to do this for new data each time, you would need to use an INSERT statement to copy the new data into an existing output table, then delete the input files from S3.
Since it is one-off, and each file belongs in only one partition, I would recommend you simply "run the script". It will go slightly faster from an EC2 instance, but the data is not uploaded/downloaded -- it all stays within S3.
I often create an Excel spreadsheet with a list of input locations and output locations. I create a formula to build the aws s3 cp <input> <output_path> commands, copy them to a text file and execute it as a batch. Works fine!
You mention that the destination depends on the data inside the object, so it would probably work well as a Python script that would loop through each object, 'peek' inside the object to see where it belongs, then issue a copy_object() command to send it to the right destination. (smart-open · PyPI is a great library for reading from an S3 object without having to download it first.)


socket joined the room but doesn't receive events in room

Question: Socket joins a room on connection, the room name can be found on rooms set defined on socket itself, but when an event is fired to that room, it doesn't receive that. Can someone figure out the issue with my code?
Joining
    this.socketIOServer.on('connect', async (socket: AuthenticatedSocket) => {
      if (socket?.request?.user?.id) {
        await socket.join(socket.request.user.id);
        console.log(socket.rooms); // Set(2) { 'j462VueHBUxufBucAAAB', '62c16b98be39c3605f03fd5a' }
      }
    });

Emitting

    console.log(
      'Sockets',
      AppointmentsSocketService.server.sockets.sockets.forEach(s => {
        console.log(s.rooms); // Set(2) { 'j462VueHBUxufBucAAAB', '62c16b98be39c3605f03fd5a' } Found in output
      }),
    );

    /* EMIT EVENT TO ROOM */
    AppointmentsSocketService.server
      .to(appointment.patient.id) // id is exactly as room name '62c16b98be39c3605f03fd5a'
      .emit('appointments/status', appointment);

    console.log(
      'Sockets',
      AppointmentsSocketService.server.sockets.sockets.forEach(s => {
        console.log(s.rooms); // Set(2) { 'j462VueHBUxufBucAAAB', '62c16b98be39c3605f03fd5a' } Found in output
      }),
    );

I'm testing through postman, & that never receives the response. I also try using Firecamp app as well as wrote dummy script to test - but never received event.
Answer: The event name on server-side code should be 'connection' instead of 'connect'. Like here  https://socket.io/get-started/chat
Your correct code would be:
Joining
    this.socketIOServer.on('connection', async (socket: AuthenticatedSocket) => {
      if (socket?.request?.user?.id) {
        await socket.join(socket.request.user.id);
        console.log(socket.rooms); // Set(2) { 'j462VueHBUxufBucAAAB', '62c16b98be39c3605f03fd5a' }
      }
    });

Comment: Your answer could be improved by providing an example of the solution and how it helps the OP.


Poisson distrubution proof question.

Question: I was reading over the proof for the Poisson distribution and came across this sentence:
 "But since $$\left[1-\frac{\lambda}{n}\right]^n\rightarrow e^{-\lambda}$$ as $$n\rightarrow\infty$$, ..."
Can someone explain how they have arrived at that result and why the above term doesn't simply become $$1^n=1$$? By the way $$\lambda=np$$ where p is the probability and n is the number of data points.
Comment: Recall "indeterminate forms" from the calculus. In general, if we know that $f(n)\to 0$ as $n\to\infty$, we cannot say anything about what happens to $(1+f(n))^n$ as $n\to\infty$.  But we do know that the limit of $(1+x/n)^n$ is $e^x$.
Answer: The fact $$
  \lim_{n\to\infty}\left(1 + \frac{x}{n}\right)^n = e^x
$$
is very well known (see here for example). It's sometimes even taken to be the definition of $e^x$.
Answer: fgp's answer that the limit can be taken as the definition of $e^x$ is totally right, but most often we define $$\lim_{n\to\infty} \left(1+\frac{1}{n}\right)^n = e$$
Now let us calculate $$\lim_{n\to\infty} \left(1+\frac{x}{n}\right)^n = e$$
We make the substitution $t=n/x$
$$\lim_{t\to\infty} \left(\left(1+\frac{1}{t}\right)^t\right)^x = e^x$$
Comment: This looks circular - how do you *define* exponentiation for non-rational exponents, without resorting to $e^x$? You might say that you imagine $x$ to be rational, in which case you can define $x^{\frac{p}{q}} := \sqrt[q]{x^p}$. This removes the circularity, but you'll now need to first show that $x^r$ is continuous in $x$ so that you may swap the limit and the exponentation.
Comment: @fgp yes I was referring to $x^y$ being continuous. Proving that is left as an exercise. In the case of *defining* this to be $e^x$ you also need to show things like $$\lim_{n\to\infty} \left(1+\frac{2}{n}\right)^n = \left[\lim_{n\to\infty} \left(1+\frac{2}{n}\right)^n\right]^2$$. But that follows from continuity as well.
Comment: Still, how do you get around the circularity? You need to *define* $x^y$ before you can prove it's continuity. So what your approach comes down to is to define exponentation for rational exponents, proving it continuous as a function $\mathbb{Q} \to \mathbb{R}$, then extending that to $\mathbb{R} \to \mathbb{R}$, the using *that* to define $e^x$. It seems way simpler to just *define* $e^x$ via the limit, proving it to be continuous and injective, defining $\log x$ as its inverse, and defining $x^y$ as $e^{y\log x}$.
Comment: @fgp seems simpler yes, at the end, since both methods work, it comes down to whatever "floats your boat"

Poisson distrubution proof question.


Preenchendo uma div usando each Jquery

Question: Tenho uma modal que renderiza uma partialView e quero passar dessa modal para tela view principal uma lista dinâmica de objetos listados que são selecionados pelo usuário
$(".corpoPedido", parent.document).text($(".lista.active").each(function () { /*html*/}))

quero inserir o resultado em uma div na view principal com a classe "corpoPedido" todas as tr que têm tanto a classe "lista" quanto " active"
mas estou errando na sintaxe.
Alguém pode me ajudar?
EDITADO:
na modal:
 @if (Model != null)
                {
                    foreach (var item in Model)
                    {

                                @Html.DisplayFor(modelItem => item.CODIGO)

                                @Html.DisplayFor(modelItem => item.img)

                                @Html.DisplayFor(modelItem => item.Descricao)

                                @Html.DisplayFor(modelItem => item.UN)

                                @Html.DisplayFor(modelItem => item.Grupo)

                                @Html.DisplayFor(modelItem => item.preco)

                                @Html.DisplayFor(modelItem => item.Quantidade)

                    }
                }

no js dessa mesma pagina:
$(".corpoPedido", parent.document).text($(".lista.active").each(function () {
                    '
 '+
                    '
' +
                        '
'+$(this).attr('data-codigo')+'
' +
                    '
' +
                    '
' +
                        '
'+$(this).attr('data-desc')+'
' +
                    '
' +
                    '
' +
                        '
'+$(this).attr('data-un')+'
' +
                    '
' +
                    '
' +
                        '
'+$(this).attr('data-grupo')+'
' +
                    '
' +
                    '
' +
                        '
'+$(this).attr('data-preco')+'
' +
                    '
' +
                    '
' +
                        '
' + $(this).attr('data-qnt') + '
' +
                    '
' +
                    '
' +
                        '

' +
                    '
' +
                    '
' +
                        '<input type="submit" value="X" class="btn btn-danger cancelItem" />' +
                    '
'
                }))

na main view

                    Código

                    Descrição

                    Und.

                    Grupo

                    Quantidade

                    Preço

                    Total

Comment: Poste seu código, pois está muito vago, explicando o que esta contecendo com este código que você postou,
     $(".corpoPedido", parent.document).text()

Pega todas tags que tem a classe corpoPedido

      $(".lista.active").each(function () { /*html*/})

Pega todas as tags q tem as classes lista e active
Comment: Desculpe pela falta de informação, pensei que poderia simplificar minha ideia de forma a ficar mais fácil a compreensão, editei o post e coloquei os códigos como pedido @MarcoViniciusSoaresDalalba
Answer: Fiz algumas alterações no teu código, para funcionar corretamente acredito que seja isto que estava procurando.

$(document).ready(function() {
  var html = "
";
  $(".lista.active").each(function() {
    html += '
 ' +
      '
' +
      '
' + $(this).attr('data-codigo') + '
' +
      '
' +
      '
' +
      '
' + $(this).attr('data-desc') + '
' +
      '
' +
      '
' +
      '
' + $(this).attr('data-un') + '
' +
      '
' +
      '
' +
      '
' + $(this).attr('data-grupo') + '
' +
      '
' +
      '
' +
      '
' + $(this).attr('data-preco') + '
' +
      '
' +
      '
' +
      '
' + $(this).attr('data-qnt') + '
' +
      '
' +
      '
' +
      '

' +
      '
' +
      '
' +
      '<input type="submit" value="X" class="btn btn-danger cancelItem" />' +
      '

'
  });

  $(".corpoPedido").html(html);

})

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    1
    2
    3
    4
    5
    6
    7

    12
    23
    34
    45
    56
    67
    78

      Código

      Descrição

      Und.

      Grupo

      Quantidade

      Preço

      Total

Preenchendo uma div usando each Jquery


Issue creating read-only user in PostgreSQL that results in user with greater permission with public schema

Question: I'm learning PostgreSQL and now I'm trying to create a read-only user.
CREATE USER user WITH PASSWORD 'password';
GRANT CONNECT ON DATABASE my-database TO user;
GRANT USAGE ON SCHEMA public to user;
GRANT SELECT ON ALL TABLES IN SCHEMA public to user;

However, I'm having issues using the public schema which has permissions to CREATE databases and others.
I don't want to affect other users or modify the public schema.
What would be the best way to GRANT FULL ONLY READ ACCESS?
Thanks from a newbie!
Comment: To create a database the user needs the `CREATEDB` privilege or be a superuser. Your `user` role has neither. Please verify your issue and add details to your question of what your problem is
Answer: You cannot solve this problem without modifying the public schema. You will have to
REVOKE CREATE ON SCHEMA public FROM PUBLIC;

Comment: Thanks, @Laurenz Albe
So what would be the best way to create a read-only user in your experience?
Comment: Grant `SELECT` permissions on all tables and views and `USAGE` on all schemas, and make sure that no write permissions are granted to `PUBLIC`.
Comment: Thanks again, @Laurenz Albe
Excuse my ignorance, but this is not going to affect other users or the functionality of my app, no?
Comment: It may, if the application tries to create objects in `public`. If it doesn't, it should be no problem. Test it!


iptables : ! not allowed with multiple source

Question: When I run this command :
sudo iptables -I FORWARD '!' -s x.x.x.x,y.y.y.y -d 172.18.0.3 -p tcp --dport 9114 -j DROP
I get the error :
iptables v1.6.1: ! not allowed with multiple source or destination IP addresses
Any ideas what is the correct command for this use case?
Answer: Negated logic should work here:
sudo iptables -I FORWARD -d 172.18.0.3 -p tcp --dport 9114 -j DROP
sudo iptables -I FORWARD -s x.x.x.x,y.y.y.y -d 172.18.0.3 -p tcp --dport 9114 -j ACCEPT

Commands have to be entered in this order so that the DROP rule appears last in the chain.
Comment: thank you
this worked for me


Note designs on the 10 hole major diatonic harmonica

Question: Here is the typical note design on 10 holes major diatonic harmonica in C major:

I have a few questions:

Why there is a G key in the 2nd draw and the 3rd blow? But it omits the F key? also omits the A key?

Is that because we need more the double-note chord GB (in the 2nd and 3rd draws) or because we need more the triple-note chord DGB (in the 1st, 2nd, and 3rd draws)? More than the F key and more than the A Key?

Then, why do we put A and B adjacent notes in the 6th draw and the 7th blow? Based on the above logic, we seem not to play the AB together which sounds "not a coherent chord"?

To favor the chord arguments, you can see:

CEG
DGB
GBD
BDF
DFA

But FAB (draw 5-7) or ABD (draw 6-8) seem to make less sense
Answer: Both of the odd aspects of the tuning you've noted are caused by the same thing: Harmonicas are originally designed to play chords! It was basically built by 19'th century Germans to play polkas.
And not necessarily just two or three notes at the time as you guessed, but possibly more! A harmonica in the key of C, as the one in your chart, was designed so that any way you could possibly blow into it produces a C major chord. When you draw, on the other hand, the entire lower half of the instrument produces a large G7 chord. This is the dominant to the C chord, and it's thus really useful when playing in the key of C. The notes DFA constitute the minor parallel of the subdominant, and you could even use the two notes FA to suggest an F major chord, the subdominant of C.
(In other terms you have the chords I, ii, (IV) and V7)
The chords are prioritised in order of importance, so that the one most important chord gets a lot of space.
The notes have been adjusted somewhat to allow for playing a melody in the upper half, but at least the bottom half is mainly intended as a chord instrument.
This doesn't mean you can't play melodies on it. In fact, people have spent over a century coming up with techniques to make the harmonica do things it wasn't intended to do. Today people are playing it fully chromatically, i.e. with all the notes you find on a piano, and some between as well! People DO play fantastic music on standard tuned harmonicas, it's just that there are quite a lot of hacks involved in their doing so.
Then, of course, no-one is forcing you to play the standard tuning if you don't like it. Though this is the most common there are many alternatives to choose from from many different brands, some tunings are even designed to play modern music ;)
Comment: many thanks! I appreciate your answer +1. I will wait for more answers/comments from others too.


Can't open EDMX-file in designer

Question: It opens as XML file only.
In MS VS 2010 Ultimate + SP1.
I need to open it in model-designer.
What can I do??
Answer: On the file in the solution explorer try
Right Click > Open With > ADO.NET Entity Data Model Designer
Comment: I have no option like this. Also, I even have no ADO.NET ENTITY MODEL via "add item" menu!
Comment: Seems you may need to (re) install the entity framework tools. This may help http://stackoverflow.com/questions/5696436/no-entity-data-model-edmx-template-with-visual-studio-2010-sp1-ado-net-entit
Comment: @Monochromie Do you have the "open with" option?
Answer: I've came across the same problem in Visual Studio 2015,i tried to open the file with
<code>Right Click > Open With > ADO.NET Entity Data Model Designer
</code>
and the option is not there.From there i realized my installation of Visual Studio 2015 must be without some components, so i went back to setup and installed Microsoft SQL Server Data Tools and Microsoft Web Developer Tools.Finally it worked ! The options are there when you open from solution and the file can be opened
Components that i added
Answer: Adds references to the System.Data, System.Data.Entity, System.Core, System.Security, and System.Runtime.Serialization assemblies to the project, if they do not already exist.

Can't open EDMX-file in designer


False statement returns an empty array

Question: So I am trying to write a code where if there a duplicate numbers it returns true and if there isn't duplicates it returns false.  I get the duplicates to show up but I want it to return the word false if there aren't duplicates.  Here is the code what am I missing.
var numbers= [14, 50, 27, 52,  41, 5, 9, 25, 10, 6];

var uniqueArray = numbers.map((number) => {
return {count:1, number: number}
})
.reduce((a, b) => {
a[b.number] = (a[b.number] || 0) + b.count
return a
}, {})

var duplicate = Object.keys(uniqueArray ).filter((a) => uniqueArray [a] > 1)

//console.log(duplicate)

function hasDuplicates(){
  if (duplicate = true) {
    return true
  }
}

Comment: `duplicate = true` assigns the value of `true` to the variable `duplicate`
Answer: function hasDuplicates(){ if (duplicate = true) { return true } }

The statement
duplicate = true

means "assign the variable duplicate the value true and return true.  That's not what you want.
Answer: I tried your code and I get an empty array if there's no duplicate
so I would rewrite hasDuplicates function to this
function hasDuplicates(){
  return duplicate.length === 0
}

Answer: Use Array.from(new Set(array)) to create unique array, then compare length of two array. If unique array has less element, it's the case of duplicate!
var numbers= [14, 50, 27, 52,  41, 5, 9, 25, 10, 6];
//console.log(numbers);
var uniqueArrays = Array.from(new Set(numbers));
if (uniqueArrays.length < numbers.length)
    console.log('Has duplicate!');
else
    console.log('No duplicate!');

Comment: Since it seems all we want is to check if there are duplicates, no need for Array.from, check directly against the `size` of this Set.
Comment: Using `Set` is also very expensive. I've included `Set` in the JS Perf if you care to see how they all perform.
Comment: Expensive = Worth!? Can you say somethings about JS Perf? Should use it in what cases?
Answer: You could simplify this by using  Array#some,  Array#every or Array#filter.
JS Perf
If you don't care about the actual duplicate values
Using Array#some

const numbers = [14, 50, 27, 52, 25, 41, 5, 9, 25, 10, 25, 6];

const hasDuplicates = numbers.some((number, index, a) => numbers.indexOf(number) !== index);

console.log(hasDuplicates);

Using Array#every

var numbers = [14, 50, 27, 52, 25, 41, 5, 9, 25, 10, 25, 6];

var hasDuplicates = !numbers.every((number, index) => numbers.indexOf(number) === index);

console.log(hasDuplicates);

Using Array#filter

const numbers = [14, 50, 27, 52, 25, 41, 5, 9, 25, 10, 25, 6];
const uniques = numbers.filter((number, index) => numbers.indexOf(number) === index);
const hasDuplicates = numbers.length !== uniques.length;

console.log(uniques, hasDuplicates);

If you do care

const numbers = [14, 50, 27, 52, 25, 41, 5, 9, 25, 10, 25, 6];

const duplicates = [];

const uniques = numbers.filter((number, index) => {
  return numbers.indexOf(number) === index || !duplicates.includes(number) && duplicates.push(number) && false;
});

function hasDuplicates(){
  return !!duplicates.length;
}

console.log(duplicates, uniques, hasDuplicates());

Comment: The first example would even win a few runs with `Array#some` instead of `#filter`.
Comment: Good point. I updated the answer to include using `.some` as the preferred choice but examples of `.filter` and `.every` with a JS Perf test.
Answer: function hasDuplicates() {
  return duplicate ? 'true' : 'false';
}

var numbers= [14, 50, 27, 52,  41, 5, 9, 25, 10, 6];
var unique = {};
numbers.forEach( n => { unique[n] = 1; } );
var duplicate = numbers.length != unique.length;

False statement returns an empty array


Test Convex Hull of Vectors

Question: My mathematical background is generally not so great so please pardon me if my question appears silly. I am trying to test the convex hull of 3 vectors for an intersection with coordinate axes as attached: https://i.stack.imgur.com/s8m0R.jpg
I have researched literature online but nothing is really specific as to this sort of problem. If you have any references or insightful approach as to how I can solve this, I would appreciate your help.
Thanks!
Comment: Your link asks for a password
Comment: Oops, please use this link: http://imgur.com/yXbBc4w I've changed it in the original post as well. Thanks for pointing it out.
Answer: I think I found the answer. It is a trivial one. Map the first two coordinates to the y-z plane and you find the line that connects eta1, eta2 since their x-components are zero. Then map the eta3 vertex to the xyz plane and interconnect the three points. It then becomes easy to see that K crosses the three planes. Cheers! –

Test Convex Hull of Vectors


Definition of Divergent Sequence

Question: I tried to check the definition of divergent sequences in many places. All of them define divergent sequence as a sequence which is not convergent.
I wonder if a Cauchy sequence (which is not convergent in a non-complete normed space) is still called a divergent sequence.
Comment: which is not convergent means divergent.
Comment: Even if your space is not complete, many Cauchy sequences do converge !!! For instance the constant ones, but also many others
Answer: If you are in a non-complete space and find a Cauchy sequence which does not converge, then by definition yes, this sequence is divergent. Cauchyness has nothing to do with it.

Definition of Divergent Sequence


C# EntryPointNotFoundException

Question: In my C# program, I'm making a call to the AT91Boot_Scan function in sam-ba.dll. In the documentation for this DLL, the signature for this function is void AT91Boot_Scan(char *pDevList)
Unfortunately, no matter what I try I keep getting EntryPointNotFoundException and ArgumentNullException errors:
Exception thrown at 0x75E3C54F in MyApp.exe: Microsoft C++ exception: EEMessageException at memory location 0x0038E304.
Exception thrown: 'System.EntryPointNotFoundException' in MyApp.exe
Unable to find an entry point named 'AT91Boot_Scan' in DLL 'sam-ba.dll'.
Exception thrown: 'System.ArgumentNullException' in System.Windows.Forms.dll

My code is as follows, what am I doing wrong?
[DllImport("sam-ba.dll")]
unsafe public static extern void AT91Boot_Scan(char* pDevList);

unsafe private string[] LoadDeviceList()
    {
        const int MAX_NUM_DEVICES = 10;
        const int BYTES_PER_DEVICE_NAME = 100;

        string[] deviceNames = new string[MAX_NUM_DEVICES];

        try
        {
            unsafe
            {
                // A pointer to an array of pointers of size MAX_NUM_DEVICES
                byte** deviceList = stackalloc byte*[MAX_NUM_DEVICES];

                for (int n = 0; n < MAX_NUM_DEVICES; n++)
                {
                    // A pointer to a buffer of size 100
                    byte* deviceNameBuffer = stackalloc byte[100];
                    deviceList[n] = deviceNameBuffer;
                }

                // Is casting byte** to char* even legal?
                AT91Boot_Scan((char*)deviceList);

                // Read back out the names by converting the bytes to strings
                for (int n = 0; n < MAX_NUM_DEVICES; n++)
                {
                    byte[] nameAsBytes = new byte[BYTES_PER_DEVICE_NAME];
                    Marshal.Copy((IntPtr)deviceList[n], nameAsBytes, 0, BYTES_PER_DEVICE_NAME);

                    string nameAsString = System.Text.Encoding.UTF8.GetString(nameAsBytes);
                    deviceNames[n] = nameAsString;
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        return deviceNames;
    }

Comment: I looked more closely at some of the doc for `sam-ba.dll` and it seems that this DLL is a COM / OLE object.  I was able to add a reference to the TLB file `SAMBA_DLL.tlb`, add a `using SAMBA_DLLLib;` and then instantiate an object from that with `SAMBA_DLLLib.ISAMBADLL mySamba = new SAMBA_DLLLib.SAMBADLL();`  Then when I work with that object variable `mySamba.` at design-time, Intellisense 'knows' what the methods and signatures look like, including the  `AT91Boot_Scan()` method you are interested in.  I think this is the way you want to go with this particular DLL and C#.
Comment: A C# console app typically requires an entry point called `Main()` see the following [MSDN article](https://msdn.microsoft.com/en-us/library/system.entrypointnotfoundexception(v=vs.110).aspx) which talks about `System.EntryPointNotFoundException` -- especially the first couple of points under **Remarks**.  Resolving this will fix at least one of the problems you are experiencing.
Comment: Your title and one of the tags you chose indicate `C#` but the code and messages look like `C++` -- which is it?
Comment: It's C# code calling a DLL (which I think is written in C++) Is there anything I can do to clear up confusion in my post?
Comment: Hmm I'm actually making a Windows Form App using Visual Studio, so the `Main()` method is there in `Program.cs`. I think my problem is that it's not finding the function `AT91Boot_Scan` in the DLL I'm using...Nonetheless the other points under Remarks raised some interesting points like decorated names...I'll try that out. Thanks!
Comment: You're right, adding the reference that way works. Thanks a ton!
Answer: Following David Tansey's solution in the comments, the way I should've gone about doing this was adding sam-ba.dll as a COM reference (Solution Explorer > References > Add References > Browse). Then just instantiating a ISAMBADLL class object and calling the methods through that class.

C# EntryPointNotFoundException


Writing to a Shapefile

Question: I'm having trouble writing/reading a Shapefile in python. I have an array of points that I would like to write to a polygon using pyshp.  The relevant parts of the code are:
dividedRects = [(7598325.0, 731579.0, 7698325.0, 631579.0), (7598325.0, 631579.0, 7698325.0, 611641.0), (7698325.0, 731579.0, 7728636.0, 631579.0), (7698325.0, 631579.0, 7728636.0, 611641.0)]

def createPolys(dividedRects):
    w = shapefile.Writer(shapefile.POLYGON)
    for i in range(0, len(dividedRects)):
        print i
        topLeft = [dividedRects[i][0],dividedRects[i][1]]
        topRight = [dividedRects[i][2], dividedRects[i][1]]
        bottomRight = [dividedRects[i][2], dividedRects[i][3]]
        bottomLeft = [dividedRects[i][0], dividedRects[i][3]]
        w.poly(parts=[[topLeft,topRight,bottomRight,bottomLeft]])
        w.field("ID", "C", "40")
        w.field("Events", "C", "40")
        w.record(str(i), str(0))
    w.save('cellFile')

createPolys(dividedRects)

This causes an error:
IndexError                                Traceback (most recent call last)
<ipython-input-36-503affbe838b> in <module>()
----> 1 createPolys(dividedRects)

<ipython-input-35-4c552ae29bc7> in createPolys(dividedRects)
     10         w.field("ID", "C", "40")
     11         w.field("Events", "C", "40")
---> 12         w.record(str(i), str(0))
     13     w.save('cellFile')
     14 #     topLeft = [dividedRects[1][0],dividedRects[1][1]]

C:\Users\Me\Anaconda2\lib\site-packages\shapefile.pyc in record(self, *recordList, **recordDict)
    967         if self.fields[0][0].startswith("Deletion"): fieldCount -= 1
    968         if recordList:
--> 969             [record.append(recordList[i]) for i in range(fieldCount)]
    970         elif recordDict:
    971             for field in self.fields:

IndexError: tuple index out of range

If I remove the field and records lines from createPolys:
def createPolys(dividedRects):
    w = shapefile.Writer(shapefile.POLYGON)
    for i in range(0, len(dividedRects)):
        print i
        topLeft = [dividedRects[i][0],dividedRects[i][1]]
        topRight = [dividedRects[i][2], dividedRects[i][1]]
        bottomRight = [dividedRects[i][2], dividedRects[i][3]]
        bottomLeft = [dividedRects[i][0], dividedRects[i][3]]
        w.poly(parts=[[topLeft,topRight,bottomRight,bottomLeft]])
#         w.field("ID", "C", "40")
#         w.field("Events", "C", "40")
#         w.record(str(i), str(0))
    w.save('cellFile')

Then I get an assertionerror when reading the records from the file:
createPolys(dividedRects)

sf2 = shapefile.Reader("cellFile")
print sf2.records()
shapes = sf2.shapes()
bbox = shapes[1].bbox
#['%.3f' % coord for coord in bbox]
print bbox
points = shapes[1].points
print points

AssertionError                            Traceback (most recent call last)
<ipython-input-37-597af0b882ba> in <module>()
      1 sf2 = shapefile.Reader("cellFile")
----> 2 print sf2.records()
      3 shapes = sf2.shapes()
      4 bbox = shapes[1].bbox
      5 #['%.3f' % coord for coord in bbox]

C:\Users\Me\Anaconda2\lib\site-packages\shapefile.pyc in records(self)
    528         """Returns all records in a dbf file."""
    529         if not self.numRecords:
--> 530             self.__dbfHeader()
    531         records = []
    532         f = self.__getFileObj(self.dbf)

C:\Users\Me\Anaconda2\lib\site-packages\shapefile.pyc in __dbfHeader(self)
    464             self.fields.append(fieldDesc)
    465         terminator = dbf.read(1)
--> 466         assert terminator == b("\r")
    467         self.fields.insert(0, ('DeletionFlag', 'C', 1, 0))
    468

AssertionError:

When I removed the loop and wrote one record it seemed to work ok.  What's going on?
Answer: I do not know about pyshp library, but I'll try to help anyways.
The two w.field() commands occur in the for loop.  This may cause the two columns "ID" and "Events" to be defined multiple times.  When you write only one record (polygon), it works fine (i.e. the w.record() command contains two values).  After the first iteration, there would be 4, 6, etc columns.  That would explain the behavior you describe.
Try moving the two w.field() lines before the for loop.
When you comment the w.record(), you obtain a shp (and shx) file with a number of records different from the corresponding dbffile.  That explains the assertion error when reading.
Unrelated to your problem, you could also simplify your code with enumerate (built-in function).
w = shapefile.Writer(shapefile.POLYGON)
w.field("ID", "C", "40")
w.field("Events", "C", "40")
for i,rect1 in enumerate(dividedRects):
    print i
    topLeft = [rect1[0],rect1[1]]
    topRight = [rect1[2], rect1[1]]
    bottomRight = [rect1[2], rect1[3]]
    bottomLeft = [rect1[0], rect1[3]]
    ....

(I cannot test since I do not have pyshp)  Good luck!
Comment: That did it, thanks!  I can't believe that I didn't see that, though I've been looking at if for hours...

Writing to a Shapefile


What is the benefit of a gaussian procces?

Question: I wonder about the advantage of a gp over "standard" regression tools like a loess. A gp fits to the data as best as possible, like every model tries to do this. More or less, let's keep it that simple.
Now, all I see is that a gp adds a confidence intervall around it's regression curve which becomes broader the lass data is available.
So where is the benefit of a gp?
A similar question has been answered, but it's over my head, at least at the moment.
Can someone please explain in simple words?
Answer: Some disadvantages of LOWESS vs GP are the following:

LOWESS will fail even for a moderate input dimension of data, while GP works in this case for right kernel selected
For LOWESS to work we need a dense training sample of points over the whole design space. For GP the requirements are less strict
We need additional tricks to control outliers

Some advantages of GP vs LOWESS are the following:

Both prediction and uncertainty estimate have analytical forms: at each point $x$ we have a posterior distribution given the data $\mathcal{N}(\mu(x), \sigma^2(x))$ with $\sigma^2(x)$ has analytical form and is natural uncertainty estimate
GP controls over the smoothness of the model by the selection of a proper kernel
Straightforward estimation of parameters: we write likelihood for the data and maximize it with respect to parameters of the kernel
GP can be treated as a special problem for the selection of a function from RKHS space
Theoretical justification: it is a solution of Kolmogorov-Wiener equations, so we minimize L2 error over all possible estimators under the assumption about the Gaussian joint data distribution
An interpolation without giving up the smoothness of the model, so the predictions $\hat{y}(x)$ equal to the true values $y(x)$.

IMO the most important points are limitation of LOWESS to moderate dimensions and absence of analytical and principled global prediction and uncertainty estimate. Also, I believe, that in practice GP just works better, than most of the kernel methods including LOWESS.


Use channel for matrix and box counting

Question: This code is from the most popular go matrix package https://github.com/skelterjohn/go.matrix/blob/go1/util.go
I googled this function and seems like it is for computing the fractal dimension. But in this package, this function is never used so I am having a hard time understanding this.
<code>func countBoxes(start, cap int) chan box {
        ints := make(chan box)
        go func() {
                for i := start; i < cap; i++ {
                        ints <- i
                }
                close(ints)
        }()
        return ints
}
</code>
Why do we need goroutine when we have only one anonymous function here?
And does anybody know what this function does in terms of matrix work?
Thanks in advance.
Answer: It returns a channel with cap - start queued integer events. (i.e. You can 'read'
start,start+1..,cap from the channel and then it closes ).
If you poke around in the code, it uses a similar kind of construct to create an iterator for the the indices of non-zero entries of sparse matrices. Look in sparse.go.
It's not used anywhere in the code that I can find, it may have been just to test
the idea.

Use channel for matrix and box counting


About prime ideals partial derivatives of polynomials

Question: Given a polynomial $f(x_1,... ,x_n)\in \mathbb{C}[x_1, ... ,x_n]$, we can formulate its (formal) partial derivative with respect to each of the $x_i$, say $f_{i}$. If $f\in \mathfrak{p}$ and $f_{i}\in \mathfrak{p}$ for each $i$, $\mathfrak{p}$ a prime ideal, do we have $f\in \mathfrak{p}^2$ in general?
Comment: I might be missing something, but if $f(x)=x^2$, then $f_1(x)=2x\in(x)$ (this is with $n=1$) but $f_1(x)\notin (x)^2$.
Comment: sorry for the serious typo.
Answer: Yes, this is true. (Edit: The comments below show that this argument only works for $\mathfrak p$ such that $\mathfrak p^2$ is primary. If this is not the case, the argument below gives that there exists $s\notin\mathfrak p$ such that $sf\in\mathfrak p^2.$ In particular, for $\operatorname{ord}_Z (f)$ we must localize at $Z.$)
In the case $\mathfrak p=\mathfrak m_a=(x_1-a_1,\ldots,x_n-a_n)$ is the maximal ideal of a point $a\in\Bbb A^n_{\Bbb C},$ the fact that $f\in\mathfrak m_a$ is equivalent to $f(a)=0.$ The fact that $\frac{\partial f}{\partial x_i}(a)=0$ for all $i=1,\ldots,n$ is equivalent to the linear term $f^{(1)}(x)=\sum_{i=1}^n\frac{\partial f}{\partial x_i}(a)(x_i-a_i)$ of the Taylor expansion $f(a)+f^{(1)}(x)+\cdots+f^{(m)}(x)$ of $f$ at $a$ being identically zero at $a.$ In other words $f(x)=f^{(2)}(x)+\cdots+f^{(m)}(x)$ at $a,$ which is equivalent to $f\in\mathfrak m_a^2.$
In the case of an arbitrary prime $\mathfrak p\in\Bbb C[x_1,\ldots,x_n],$ we know that $f\in\mathfrak p$ is equivalent to $f\in\mathfrak m_a$ for all maximal ideals $\mathfrak m_a\supseteq\mathfrak p.$ Geometrically, $f$ vanishes along the irreducible subvariety $V(\mathfrak p)$ if and only if $f$ vanishes at every (closed) point $a\in V(\mathfrak p).$ Suppose that $f\in\mathfrak p\subseteq\mathfrak m_a.$ By the previous, if $\frac{\partial f}{\partial x_i}\in\mathfrak p$ for every $i=1,\ldots,n,$ then $f\in\mathfrak m_a^2.$ Thus, $f\in\bigcap_{\mathfrak p\subseteq\mathfrak m_a}\mathfrak m_a^2.$
Let $Z=V(\mathfrak p)\subseteq\Bbb A^n_{\Bbb C},$ and let $I=(f)\subseteq\Bbb C[x_1,\ldots,x_n].$ The order of vanishing of $I$ along $Z,$ denoted $\operatorname{ord}_Z(I),$ is defined generally as
$$\max\{k~\vert~ I\subseteq I_Z^k\}=\max\{k~\vert~ (f)\subseteq \mathfrak p^k\}=\max\{k~\vert~ f\in\mathfrak p^k\},$$ and it is known that over algebraically closed fields this coincides with
$$\min_{a\in Z}\operatorname{ord}_a I=\min_{a\in Z}\left(\max\{k~\vert~ f\in\mathfrak m_a^k\}\right),$$ where $a\in Z$ denotes closed points. Since $f\in \mathfrak m_a^2,$ we have $\max\{k~\vert~ f\in\mathfrak m_a^k\}\ge 2$ for all $a\in Z,$ which in particular implies that $\operatorname{ord}_Z(I)\ge2,$ i.e., $f\in\mathfrak p^2.$
See Appendix A of this paper for more information about vanishing order of ideals.
(I initially wanted to show directly/algebraically that $f\in\bigcap_{\mathfrak p\subseteq\mathfrak m_a}\mathfrak m_a^2$ implies that $f\in\mathfrak p^2,$ but haven't quite gotten it to work yet. I'd be happy to see it done however, and will think a bit more on it.)
Comment: It is not hard to see that the condition $f, f_i\in\mathfrak p$ is equivalent to there exists $s\notin \mathfrak p$ such that $sf\in\mathfrak p^2$. So a positive anwer to the OP is equivalent to saying that $\mathfrak p^2$ is a primary ideal. I wonder whether this is true over any field. The exercise in Hauser's paper you pointed to implies that over an algebraically closed field, $\mathfrak p^d$ is primary for any $d\ge 1$.
Comment: Very nice, thanks @QiL for pointing this out!
Comment: Dear Andrew, but I am not sure this is true that $\mathfrak p^2$ is primary. In fact, for an integral subvariety $Z=V(\mathfrak p)$, ord$_Z(f)$ is the order of $f$ at the generic point of $Z$, so one can't conclude that $f\in \mathfrak p^2$ (at least from Hauser's paper).
Comment: And my comment on the exercise is also wrong.
Comment: Dear @QiL, I see. I think my mistake was in reading Hauser's definition -- I didn't notice that we must take powers of the ideals *in the local ring* of $Z$! Thus, what my argument actually shows is what you mention, there exists $s\notin\mathfrak p$ such that $sf\in\mathfrak p^2.$ It seems that Hauser's exercise gives the analogous result for higher order, i.e., that $f,f_i,f_{ij},\ldots,f_{i_1\ldots i_d}\in\mathfrak p$ is equivalent to $\exists s\notin\mathfrak p$ such that $sf\in\mathfrak p^d.$
Comment: Maybe the notation $O_{W,Z}$ is confusing. For the exercise, yes, in characteristic zero.


How to enable PHP in a field?

Question: I have created a content type in Drupal 8 and I added a field named "body". But I'm unable to use PHP code in this field.
How can I enable PHP in my "body" field?
Comment: Please don't ?!?
Comment: I would encourage you to find an alternate method, this is a very bad idea. If you expand your question as to what exactly you need to do, most likely there is a way to accomplish what you need to do without having to use PHP that way.
Answer: Using PHP in your body field is considered bad practice. Read: What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?
Even in the module page it clearly says:

Warning
Enabling this module can cause security and performance issues as it
  allows users to execute PHP code on your site. There are better
  alternatives out there that do not expose such vulnerabilities on your
  site.

The proper way to add your PHP:

Use a preprocess function in theme_name.theme located in your theme's folder.
Create a custom module that uses hooks or preprocess functions.

Furthermore, Twig has several filters and functions that you can make use of. Which in some cases, you don't even need to use PHP at all.
Answer: Install and configure PHP module.

The PHP Filter module adds a PHP filter to your site, for use with
text formats.

Note: The PHP filter core module has been removed from core starting with version 8.x. See also PHP filter overview.

How to enable PHP in a field?


Tem como inflar uma classe?

Question: Existem muitos métodos que você infla uma layout.xml mas eu precisa inflar uma classe dentro de uma tab, alguém sabe o que posso fazer? estou no sufoco aqui.
Para inflar layout.xml uso este código:
if(this.getTag() == "formulario3"){
   return inflater.inflate(R.layout.formulario3, container, false);
}

Porém criei um formulário dinâmico só por código Java e não estou conseguindo inflar.
Answer: daniel12345smith, supondo que a classe guarde objetos/propriedades do tipo View. Então, ao invés de "inflar" (que é uma opção exclusiva para trabalhar com os xml), você pode chamar métodos desta classe que inserem no Context desejado estes views relacionados à esta classe.
Exemplo
PrincipalActivity.java
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_principal);

    Contatos.carregaContatos(PrincipalActivity.this);
}

Contatos.java
public class Contatos
{

    public static void carregaContatos(Activity activity)
    {
        // declara TextView
        // note que "activity" agora pode procurar uma view da activity PrincipalActivity.java
        TextView textView = new TextView(); // ou "this.minhaTextView", whatever

        // codigo que insere uma View guardada e gerida por esta classe "Contatos"
        // note que "activity" agora pode procurar uma view da activity PrincipalActivity.java
        LinearLayout linearLayout = activity.findViewById(R.id.info);
        linearLayout.addView(textView);

    }

}

E assim sucessivamente. A ideia é manter a "logica" (domain logic e business logic) separada (infelizmente o Android segue um padrao View-Controller) e temos que nos virar como podemos.
Comment: vlw mas eu não tenho nada de xml no meu projeto, esse é o problema.
Comment: Opa, então, tudo bem! A ideia é esta mesma. Criar os Views como OBJETOS (por codigo) em suas classes e depois adicionar na Activity que você quiser, tudo por codigo. Note que `TextView textView = new TextView(); ` do meu exemplo acima não existe em XML nenhum...e ele foi adicionado ao container RelativeLayout por código, na linha abaixo. Mas pra isso, a ActivityPrincipal teve que chamar o método `Contatos.carregaContatos(PrincipalActivity.this);` e passar sua activity como parâmetro. Foi só pra exemplificar a que sua Ideia na pergunta pode seguir este fluxo. Aliás, eu faço tudo assim hehe.

Tem como inflar uma classe?


Why am I unable to remove nuget packages from a .NET project?

Question: I received the following task

Remove the nuget packages from MyProject (check other webapps):

AspNetSprites-Core
AspNetSprites-WebFormsControl

Since I am not too fluent in .NET-specific technicalities, I have been searching for a while to find these. I have been using Visual Studio 2015 to search for these and found them under packages in the project's file tree. After removing them and removing the following line from web.config:
<code>    <add assembly="Microsoft.Web.Samples.ImageSprite" namespace="Microsoft.Web.Samples" tagPrefix="asp" />
</code>
I expected to successfully remove these from the project, but after I built the project the files reappeared under packages. What could be the cause of this behavior?
Comment: https://docs.nuget.org/ndocs/tools/package-manager-ui#uninstalling-a-package...?
Answer: Since they are NuGet packages you should just be able to go to tools->NuGet Package Manager -> Manage NuGet packages for solution.
This will list all the installed packages for the project and you can uninstall them from here.
EDIT: Alternative solution from OP
That seems like a solution, but I already found out another one. I needed to remove the corresponding lines from packages.config
Comment: That seems like a solution, but I already found out another one. I needed to remove the corresponding lines from packages.config. If you edit your question with this alternative solution, I will surely accept it.


Writing Junit Test case for merging files in sftp server

Question: I am using apache commons VFS to connect to sftp server and write the content of files in /input directory into a single file in /output directory.The names of files in input directory is provided as a List. I am struggling to write Junit  test case for it.My intention is that once the code gets executed, I will compare the contents of file in /input against content of file in /output
public void exportFile(List<String> fileNamesList){
for (String file : fileNamesList){
            try(FileObject fileObject= //getsFileObject
                OutputStream fileOutputStream= fileObject.resolveFile("/output/"+"exportfile.txt").getContent().getOutputStream(true);
            )
                                            fileObject.resolveFile("/input/"+file).getContent().getInputStream().transferTo(fileOutputStream);

            }
            }

I want to write Junit test case for the above. The below is my setup for test case
            @BeforeAll
                  static void setUpSftpServer() throws IOException {
                System.out.println("inside setup ssh");
                sshd= SshServer.setUpDefaultServer();
                    sshd.setPort(1234);
                    sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());
                    sshd.setPublickeyAuthenticator(AcceptAllPublickeyAuthenticator.INSTANCE);
                    sshd.setSubsystemFactories(Arrays.asList(new SftpSubsystemFactory()));
                    sshd.start();
            }

         @Test
            void exportFileTest() throws IOException, URISyntaxException {

                System.out.println("Inside exportFile test");
                FileObject fileObject=getFileObject();
                when(sftpConfiguration.connect()).thenReturn(fileObject);
                myobject.exportFile(Arrays.asList("a.txt"));
               String actualContent=fileObject.resolveFile("/input/a.txt").getContentContent().getString("UTF-8");
 String expectedContent=fileObject.resolveFile("/output/exportFile.txt").getContentContent().getString("UTF-8");
                assertTrue(actualContent.equals(expectedContent));

            }
    static FileObject getFileObject() throws URISyntaxException, FileSystemException {
            String userInfo = "uname" + ":" + "pwd";
            SftpFileSystemConfigBuilder sftpConfigBuilder = SftpFileSystemConfigBuilder.getInstance();
            FileSystemOptions options = new FileSystemOptions();
            IdentityProvider identityInfo = new IdentityInfo(new File("/fake/path/to/key"), "test".getBytes());
            sftpConfigBuilder.setIdentityProvider(options, identityInfo);
            URI uri=  new URI("sftp", userInfo, "127.0.0.1", Objects.requireNonNullElse(1234, -1), null, null, null);
           FileObject fileObject= VFS.getManager().resolveFile(uri.toString(),options);
           System.out.println("creating file object complete");
           fileObject.resolveFile("/input").createFolder(); //create a folder in the path
           fileObject.resolveFile("/output").createFolder();
           //code  to create a file called a.txt inside /input and write the string "abc" to the file
            return  fileObject;
        }

But I am getting an exception like below
org.apache.commons.vfs2.FileSystemException: Unknown message with code "Could not get the user id of the current user (error code: -1)".

This exception I am getting at the line
FileObject fileObject= VFS.getManager().resolveFile(uri.toString(),options);
How do I write the unittest for this case correctly?
Answer: This is caused by the SftpFileSystem failing to run the command id -u which doesn't exist on some SSH connections such as Windows OpenSSH. It runs this command when attempting to detect the exec channel. Resolve this by adding the following SFTP configuration:
sftpConfigBuilder.setDisableDetectExecChannel(options, true);

See here.


Runtime exception in syntax like defining two vals with identical names

Question: In some book I've got a code similar to this:
object ValVarsSamples extends App {

  val pattern = "([ 0-9] +) ([ A-Za-z] +)". r   // RegEx

  val pattern( count, fruit) = "100 Bananas"
}

This is supposed to be a trick, it should like defining same names for two vals, but it is not.
So, this fails with an exception.
The question: what this might be about? (what's that supposed to be?) and why it does not work?
--
As I understand first: val pattern - refers to RegEx constructor function.. And in second val we are trying to pass the params using such a syntax? just putting a string
Answer: This is an extractor:
val pattern( count, fruit) = "100 Bananas"

This code is equivalent
val res = pattern.unapplySeq("100 Bananas")
count = res.get(0)
fruit = res.get(1)

Comment: What I'm not comfortable with is: "val" it looks very much as if I define a new value. When unapply happens in match-case, then it's ok
Answer: The problem is your regex doesn't match, you should change it to:
val pattern = "([ 0-9]+) ([ A-Za-z]+)". r

The space before + in [ A-Za-z] + means you are matching a single character in the class [ A-Za-z] and then at least one space character. You have the same issue with [ 0-9] +.
Scala regexes define an extractor, which returns a sequence of matching groups in the regular expression. Your regex defines two groups so if the match succeeds the sequence will contain two elements.
Comment: ah.. even to this: "([0-9]+) ([A-Za-z]+)". Deleted spaces.. Ok.
Could you explain the syntax of such a val-repeating.?


Google Services draining battery of Nexus 6

Question: This happened three times in the last month:
My Nexus 6 battery drained in several hours. When I reboot and go to battery usage, I always found Google Services uses up to 90% of the battery. However there is no application on my Nexus 6 called "Google Services". What does it mean?
Answer: It means the apps made by Google. In my case, I had problems with Gmail and Google Fit that were draining my phone.
Disabling Google Fit (which is useless in my case) and removing non-google accounts from gmail (hotmail, yahoo, customs) and putting them in their native app solved the problem for me.
Hope this helps ! Good luck ;)


How to get the "ctrl c" or mouse copy event in a Powerpoint 2013 Addin (developed in C#)?

Question: Code below is not trapping character type in MS Powerpoint, It does just outside of Powerpoint and how can I catch the "control copy" or "right mouse click copy" inside this code?
Code below is not trapping character type in MS Powerpoint, It does just outside of Powerpoint and how can I catch the "control copy" or "right mouse click copy" inside this code?
Code below is not trapping character type in MS Powerpoint, It does just outside of Powerpoint and how can I catch the "control copy" or "right mouse click copy" inside this code?
<code>    public partial class ThisAddIn
    {

        private const int WH_KEYBOARD_LL = 13;
        private const int WM_KEYDOWN = 0x0100;

        private static IntPtr hookId = IntPtr.Zero;
        private delegate IntPtr HookProcedure(int nCode, IntPtr wParam, IntPtr lParam);
        private static HookProcedure procedure = HookCallback;

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook, HookProcedure lpfn, IntPtr hMod, uint dwThreadId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            hookId = SetHook(procedure);
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
            UnhookWindowsHookEx(hookId);
        }

        private static IntPtr SetHook(HookProcedure procedure)
        {
            using (Process process = Process.GetCurrentProcess())
            using (ProcessModule module = process.MainModule)
                return SetWindowsHookEx(WH_KEYBOARD_LL, procedure, GetModuleHandle(module.ModuleName), 0);
        }

        private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
            {

                int pointerCode = Marshal.ReadInt32(lParam);
                string pressedKey = ((Keys)pointerCode).ToString();

                //Do some sort of processing on key press
                var thread = new Thread(() => { if (pressedKey.ToLower() == "LControlKey") { MessageBox.Show(pressedKey); } });
                thread.Start();
            }
            return CallNextHookEx(hookId, nCode, wParam, lParam);
        }

        protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
        {
            return new Ribbon();
        }

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }

        #endregion
    }
</code>
Answer: Use a custom ribbon.
<code><customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui" onLoad="Ribbon_Load">
  <commands>
    <command idMso="Cut" onAction="CopyIntercept" />
    <command idMso="Copy" onAction="CopyIntercept" />
  </commands>
</customUI>

public void CopyIntercept(IRibbonControl control, ref bool CancelDefault)
{
}
</code>
You might be able to do this with a Ribbon Designer, but the sample above is for an XML ribbon.


Is the ideal $(x,3)$ of $\mathbb{Z}[x]$ prime or maximal?

Question: I can't solve this question. I know that (x,3) is maximal ideal if $\mathbb{Z}[x]/ (x,3)$  is a field and (x,3) is a prime ideal if $\mathbb{Z}[x]/(x,3)$ is a domain. I know that there are isomorphism theorems about it but I`m totally confused. Could some one help me please?
Thanks!
Comment: If $I$ is maximal in $R$, $(I,X)$ is maximal in $R[X]$.
Answer: Apply the isomorphism theorems for rings to justify the following
$$\left(\Bbb Z[x]\right)/\left(\langle x\,,\,3\rangle\right)\cong\left(\Bbb Z[x]/\langle x\rangle\right)/\left(\langle x,3\rangle/\langle x\rangle\right)\cong\Bbb Z/\langle 3\rangle=:\Bbb F_3$$
So...
Added as punishment for myself for being uncareful:
$$\left(\Bbb Z[x]\right)/\left(\langle x\,,\,3\rangle\right)\cong\left(\Bbb Z[x]/\langle 3\rangle\right)/\left(\langle x,3\rangle/\langle 3\rangle\right)\cong\Bbb F_3[x]/\langle x\rangle\cong\Bbb F_3$$
Comment: Well how do you apply them? I know I have to make a function and take a subset of another ideal. But its quite vague to me still.
Comment: Of course, @rschwieb. Thanks (otherwise how come...?). In fact, I may add another, similar, way.
Comment: @DonAntonio Looks great :)
Answer: The method of @DonAntonio is best, but here's a rough and ready argument:
To factor out by the ideal $(x,3)$ is to treat computations in the original ring $\mathbb Z[x]$ as if both $x$ and $3$ are zero. So polynomials immediately lose all their nonconstant terms, and even these behave as integers modulo $3$.
Alternatively, just construct a ring homomorphism from $\mathbb Z[x]$ onto $\mathbb Z/(3)$. What you want is $f(x)\mapsto \bigl(f(0)\pmod3\bigr)$. Now check that the kernel is $(x,3)$.


Tubulum Construction: How does including elbows affect the pitch?

Question: I am considering building a tubulum out of 2" PVC pipes. (Like Blue Man Group) There are some specs on the internet for making the notes, but no one really says when inserting an elbow into the length, how much doing it will change the pitch of the note. Can I add a fixed amount to the overall pipe length for each elbow? I would like to know ahead of time before I do a lot of cutting and wasting time and materials. I would think it would be better to have at least one bend in each pipe because you want to strike the pipe in a vertical position, but you want the end to be in a somewhat horizontal position facing the listeners.
I am especially interested in the guidance of someone who has first hand experience in building a tubulum.
Comment: The header is potentially misleading. I think you're asking more about the difference in *pitch* that elbows make, whereas using *tone* refers more to *timbre*. Interesting project - tell us when it's up and running. I call it a **tuber**...
Comment: Thank you. I'm sure you are right. Everyone here is more musical than I.
Answer: As a rule of thumb, you can measure the length of the elbow along a line through its middle and add it to the whole.  I would still (as I did with my tubulum) make the total length of each pipe a few inches longer than the specs and tune to pitch when it's done anyway.


The Impact of Multiplying the Dependent and Independent Variables by a Constant

Question: I have a regression model in which the intercept is 0 and the slope is 3. Now I multiply the dependent variable by 10 and independent by 2. I wish to find out what happens to the intercept and slope. I ran a calculation and found out that the slope is now 15, but I am not sure how to prove it. If I could understand why the intercept is without change, I could prove it easily.
$10y=a+b\cdot 2x$
$30x=a+2xb$
Comment: I am aware of the formulas and of the fact that both averages will be multiplied by the same constant, but how do I tackle the sum of xy, for instance ?
Comment: Drawing yourself a picture may help. You could also use the formulas for slope and intercept, see https://stats.stackexchange.com/questions/199575/slope-and-intercept-of-linear-regression
Comment: $\sum_i (c_1 x_i) (c_2 y_i) = ?$
Answer: For a classic linear regression model, $y=bx+a+\epsilon$, we have the following formulas:
$$b=\frac{n\sum xy-\sum x\sum y}{n\sum x^2-(\sum x)^2}, \ \ \ a=\frac{\sum y \sum x^2-\sum x\sum xy}{n\sum x^2-(\sum x)^2}$$
Now, if we change the IV and DV as : $x\rightarrow cx, y\rightarrow dy$
$$b_{new}=\frac{ncd\sum xy-cd\sum x\sum y}{nc^2\sum x^2-c^2(\sum x)^2}=b\frac{d}{c}, \ \ a_{new}=\frac{c^2d\sum y \sum x^2-c^2d\sum x\sum xy}{nc^2\sum x^2-c^2(\sum x)^2}=ad$$
Intercept normally changes, but since it was $0$, new coefficients don't have any effects.
Comment: This follows more directly from just focusing on the units and dimensions of the systematic part of the model. So the first part of the argument is to note that the intercept has the same units as $y$ and that the slope has units of $y$ / units of $x$.  The second part of the argument is then easy to fill in. Tacitly you are assuming that errors have mean zero so variability around the line is immaterial.
Comment: @NickCox ; I was just going to add it as an alternate solution (which doesn't narrow down the concept to OLS), but why don't you add it as another answer?
Comment: Feel free to build the idea into yours.


Think independent random variables defined on a duplicated product space

Question: Let $(\Omega, \mathcal{F}, \mathbb{P})$ be a probability space on which defines two random variables
$$
X \colon \Omega \to \mathbb{R}\\
Y \colon \Omega \to \mathbb{R}
$$
Now suppose that $X$ and $Y$ are independent meaning that $\mathbb{P}(\omega \in \Omega \colon X \in A, Y \in B) = \mathbb{P}(\omega \in \Omega \colon X \in A)\, \mathbb{P}(\omega \in \Omega \colon Y \in B)$ for every $A,B \in \mathcal{B}$.
Now let us duplicate the space $(\Omega, \mathcal{F}, \mathbb{P})$ yielding $(\Omega', \mathcal{F}', \mathbb{P}')$ such that $\Omega = \Omega'$, $\mathcal{F}=\mathcal{F}'$, and $\mathbb{P} = \mathbb{P}'$. We consider the  product space $(\Omega \times \Omega', \mathcal{F}\otimes \mathcal{F}', \mathbb{P}\,\mathbb{P}')$.
We then extend those random variables to that product space by
$$
\overline{X}(\omega,\omega')\colon \Omega \times \Omega' \to \mathbb{R} = X(\omega), \\
\overline{Y}(\omega,\omega')\colon \Omega \times \Omega' \to \mathbb{R} = Y(\omega')
$$
We can verify that $\overline{X}$ and $\overline{X}$ are random variables on that product space, and they are independent.
Am I on a correct path to think about the independence of $X$ and $Y$ in this product measure sense? In short, suppose we have two indepdendent random variables on a probaiblity space, can I think them as the sliced random variables on their product measure space?
Comment: If you start with two independent random variables on some probability space $(\Omega, \mathscr{F}, \mathbf{P})$ then _they are already independent and there is nothing left to do._ I believe you want the opposite, _how to construct two independent copies of a given distribution._ Check my answer below.
Comment: @WillM. Thank you for your answer, but my question seems a bit poorly written. I know what independence mean in terms of distribution. What I want to know is: Given two independent random variables on some probability space, is it "legal" to form a *product probability space not state space*?
Comment: My answer and comment are very relevant then. You are completely lost: you are confusing a random variable with its distribution. A random variable is __by definition__ a measurable function. As such, if you are given two independent random variables, that means that you are given two functions already, nothing to define. If, in contrast, you want to create two independent random variables with a given distribution, then my answer is the construction.
Comment: Are you confused by phrases such as "take an independent copy of $X$"? Because those phrases mean my construction in the answer. Also, notice that when such a phrase occurs, is probably something relating to _distributional properties of the random variable_ and not the actual random variables as functions.
Comment: Also, random variables do not have state space, they are real-valued always! So, it seems you are confusing many different probability concepts.
Answer: I think you are confused a bit.
If you want to create two independent copies of a given radom variable with distribution $F,$ do this: start with a distribution, say $F$ on $\mathbf{R}.$ This distribution function induces a measure $\mu_F$ on the Borel set of $\mathbf{R}.$ If you want a pair of random variables with distribution $F$ each of them and that are independendent, then you will consider the probability space $(\mathbf{R}^2, \mathscr{B}_{\mathbf{R}^2}, \mu_F \otimes \mu_F)$ and to define the random variables you will then set $X(\omega) = x$ and $Y(\omega) = y$ where $\omega = (x, y).$ By definition, $X$ and $Y$ are independent and they both have distribution $F.$ Mutatis mutandis you can do the same with two probability spaces $(\mathrm{X}, \mathscr{X}, \mu)$ and $(\mathrm{Y}, \mathscr{Y}, \nu)$ and consider the product space $\mathrm{Z} = \mathrm{X} \times \mathrm{Y},$ $\mathscr{Z} = \mathscr{X} \otimes \mathscr{Y}$ and $\rho = \mu \otimes \nu$ and the random object is $T(x, y) = (x, y)$ which is a $\mathrm{Z}$-valued random object with independent coordinates and whose marginal laws are $\mu$ and $\nu,$ respectively.
If you start with two random variables $X$ and $Y$ defined on respective probability spaces $(\Omega_X, \mathscr{F}_X, \mathbf{P}_X)$ and $(\Omega_Y, \mathscr{F}_Y, \mathbf{P}_Y)$: then you can construct the product space
$$
(\Omega, \mathscr{F}, \mathbf{P}) = (\Omega_X \times \Omega_Y, \mathscr{F}_X \otimes \mathscr{F}_Y, \mathbf{P}_X \otimes \mathbf{P}_Y)
$$
and on it then define a random vector $Z(\omega) = Z(\omega_x, \omega_y) = (X(\omega_x), Y(\omega_y)) \in \mathbf{R}^2.$ Consider the projections $\mathbf{R}^2 \to \mathbf{R}$ given by $\pi_1(x,y) = x$ and $\pi_2(x,y) = y.$ In this construction, it follows that $\pi_1(Z)$ and $\pi_2(Z)$ are independent random variables defined on $\Omega$ with respective probabilities $\mathbf{P}_X$ and $\mathbf{P}_Y.$ These are your $\bar{X}$ and $\bar{Y}.$
Do every pair of independent random variables come from a product space? No. Consider uniform distribution on $[0, 1].$ Given a random number of this distribution, it can be expanded uniquely as $\sum\limits_{k = 1}^\infty b_k 2^{-k}$ where $b_k$ is either $0$ or $1$ and the expansion is unique by considering finite representations (that is, there is no infinite sequence of contiguous 1s starting some index until infinity). The random bits $(b_k)$ are independent Bernoulli with parameter $\dfrac{1}{2}$ and they do not come from a product space. However, in general is good idea to think of independent random vectors as defined on product spaces.
Comment: You second part is very close to my question ^. Given a pair of independent rvs, can we always form a product probability space (not the space that rvs map to)? Your examples shows that this is not true. But, how about those extended rvs $\overline{X}$ and $\overline{Y}$ as shown in the questions?
Comment: You have not understand yet. If you start with $X$ and $Y$ two indepedent random variables, there is nothing to do, they are already defined (by whatever means).


Wifi-connect works in bash but not in crontab

Question: I use wifi-connect to configure my Raspberry Pi in unknown WLAN Networks.
wifi-connect works when I execute it via command line once the system booted, but when I put it into sudo crontab -e, it won't work. The cron logs show no errors. The autostart of my own scripts works.
My crontab:
@reboot /usr/local/sbin/wifi-connect
Does someone have a hint for me why this does not work?
Answer: Usually this kind of issues (when things works in a terminal but not in crontab), since there is nothing tricky in the crontab entry (you are just calling a executable with no arguments) are due to timing issue. Likely the crontab entry get executed before the network stack is ready. To do a quick test add a delay to that execution prepending sleep 60; to your command, this will delay the execution of 1 minute, which should be enough. Anyway this is not a reliable solution, you will have to user a script o a service which actually check for the network stack.
Comment: take a look here: https://www.freedesktop.org/wiki/Software/systemd/NetworkTarget/
Comment: Hm yeah I already tried it with a 10 second delay but I will try with 60 seconds as well. Could you give me a hint for what exactly I have to check if I want to write a script? Whether the network drivers are loaded?
Comment: Thank you so much! I tried it with a 20 second delay and it works. I also had to add a "sudo" before the command despite it beeing in "sudo crontab -e". Weird. Well, I will look into writing a script to check for the network stack. Thanks again!


Retrieve nested data from firebase using Swift

Question: How can I access the website url as it is nested. I also don't know how to access the img under the Medium section either. I can access the other information no problem by the code in the provided image:
What my firebase looks like
What my code looks like
    ref = Database.database().reference()

    ref.child("artists").queryOrderedByKey().observe(.value) { snapshot in
        var temp = [Artist]()
        for child in snapshot.children {

            if let child = child as? DataSnapshot {
                // decode json into Artist Struct
                let model = try! FirestoreDecoder().decode(Artist.self, from: child.value as! [String : Any])
                temp.append(model)

               // print(model)

            }
        }

Comment: The code in the question doesn't actually access anything in Firebase - it's a Swift struture. Please include your existing Firebase code so we can understand where the issue is. Check out [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
Comment: Sorry about that. I will update my post to include the code that decodes the jSon file
Answer: Let ref = Database().database.refrence()

ref.child("TopNode").child("secondInerNode").observe(.value, with: {//stuff})

You write the path to the spot where you have the data and then observe.
TopNode
   secondInerNode
      name: value;

Check the docs for more info.
Comment: Thanks for the quick response. I have just updated my post to show that that was my current code. After reading the documentation, I am still unsure on how to pull out the nested data: the 2 img and the website. Thank you for your help
Comment: child.childSnapshot("name of what u want") justy do .somthing and it search through option for what u want


How to get the content owned by the currently logged-in user?

Question: A user is the owner of only one node, and I want to redirect the user, at login time, to his only owned node.
How can I get the node content if I know only the logged-in user?
Answer: This is how I have do it:
function MYHOOK_user_login(&$edit, $account) {
    global $user;
    $nid = db_query('SELECT nid FROM {node} WHERE uid = :uid', array(':uid' => $user->uid))->fetchField();
    drupal_goto('node/' . $nid);
}

Answer: Take a look at hook_user_login -> http://api.drupal.org/api/drupal/modules--user--user.api.php/function/hook_user_login/7. This is where you can add your own custom code to do things like look up the node ID (nid) by user ID (uid) and then issue a drupal_goto (http://api.drupal.org/api/drupal/includes--common.inc/function/drupal_goto/7)
There's also the option of doing the customization with hook_form_alter to the login form which might be considered more of a D6 solution. You'll have to provide more details if these suggestions are not addressing your question.
Comment: this is the issues how to look up the node ID (nid) by user ID (uid) ?
Answer: $nid = db_query('SELECT nid FROM {node} WHERE uid = :uid AND type = :type', array(':uid' => $user->uid, ':type' => $node_type))->fetchField():

This will get you the nid.
Comment: As I there is just on node content per user I don't think is necessarily to set also the type. I have tested the query's to see which one is faster and the result was the same `Query took 0.0002 sec`.
Comment: Are you sure that users will only ever have a single node they created? I'd suggest to add the type condition, just to be sure.
Comment: In my case it is sure that they will have only one node created, because they have no right to create nodes, only to view and edit it.
Answer: Note: please disregard this answer (see the comments for why).

$nid = db_select('node', 'n')
  ->fields('n', array('nid'))
  ->condition('n.uid', $user->uid)
  ->range(0, 1)
  ->fetchField()

I'd be tempted to do it this way since it's more the 'Drupal' way, although the other suggestions are certainly valid. Note that I've put a limit on the SQL statement for safety.
Comment: db_select() is 30% slower then db_query() should only be used if there is a reason for it. Reasons include that you need paging/tablesort, have dynamic queries or need stuff like node_access.
Comment: See http://drupal.org/node/1067802. It's not surprising, SelectQuery is an OOP abstraction layer with lots of string mangling and many, many method calls on top of db_query()
Comment: That's interesting. Didn't know that. Do you have a link to some benchmarks for this 30% slowdown? I'd like to know more about this!
Comment: Thanks for this. I will start my own question to take this a bit further.


How should I interpret the Android Developers ViewModel lifecycle diagram?

Question: The following diagram appears in the Android Jetpack ViewModel Overview:

Why does the upper onDestroy graphic in the middle column have a pointy end and not terminate the ViewModel Scope while the other onDestroy graphic has a square end and terminate the ViewModel Scope?
Answer: I was able to get in touch with the creator of the diagram, Jose Alcérreca, who told me "the second onDestroy doesn't have an arrow is because it's the end of the activity's lifecycle (triggered by finish() not a recreation)."
I was also pointed to the source code for ComponentActivity, which shows the observer for ON_DESTROY:
    getLifecycle().addObserver(new LifecycleEventObserver() {
        @Override
        public void onStateChanged(@NonNull LifecycleOwner source,
                @NonNull Lifecycle.Event event) {
            if (event == Lifecycle.Event.ON_DESTROY) {
                // Clear out the available context
                mContextAwareHelper.clearAvailableContext();
                // And clear the ViewModelStore
                if (!isChangingConfigurations()) {   // ***
                    getViewModelStore().clear();     // ***
                }
            }
        }
    });

As the starred lines show, the clear() method is called for the ViewModelStore only if the call to onDestroy() is not due to a configuration change.


e.preventdefault and asp.net login form not working

Question: I am trying to submit the asp.net login form only if the https.get function does not produce an error. If it returns an error, I do not want the login form submitted. When I call e.preventDefault() the login page just refreshes without logging the user in.
Why is this?
var loginForm = $('form');
var https = require("https");
var url = 'https://examplesite.com/';

loginForm.on('submit', function (e) {
        var loginSubmit = this;
        e.preventDefault();
            https.get(url, function (res) {
                res.resume();
                loginSubmit.submit();
            }).on('error', function () {
                // display error, do not login
            });
});

Comment: It's part of node.js. I am 'pinging' the server before submitting the login request. But asp.net will not submit the form with the code above.
Comment: I don't get it...is this code running on client side or server side ?
Answer: I assume the loginForm is the actual form, the $('form') in jQuery. Which is the same as loginSubmit in your function.
See, when the submit() event is raised, you call the function inside, which calls loginSubmit.submit() again. Is it a problem?
You can try bind the function to the submit button's click event.
Need more information about res.resume(). And can you please give us where your loginForm variable comes from?

UPDATE:
I would bind to the click event of the submit button.
$(document).on('click','btn#submit', function(e){
    e.preventDefault();
    // make the get call
    $.get(url)
         .done(function(){
             // success callback => submit the form.
             $('form').submit();
         })
         .fail(function(){
             // fail callback => display error.
         });
});

I don't know much about your https call. And I am also not very clear about that your  res.resume(). But you should have some clue now.
Comment: Yes, loginForm is $('form') in jQuery. I am basically trying to run the login form through that https function so that if it returns true then it submits the login, or false, will not.
Comment: Is there any special reason you did not use jQuery to run that https function? Like `$.get(url).done(//success).fail(//fail)`. But I am concerned about calling `loginSubmit.submit()` inside the your submit callback function.
Comment: Good question, I should probably use that instead. How would I halt the login submission until I get a true or false from the get request?
Comment: detach the event from loginform onSubmit using `.off()`. Attach it again when you get a response
Comment: That is why I suggest bind to the button click event. Let me update the answer.
Comment: Would you be able to elaborate on your example .. I'm having a tough time following.


Does exchangeability imply conditional independence?

Question: Let $A,B,C$ be a sequence of exchangeable random variables, i.e. $P(A=a,B=b,C=c) = P(B=b,A=a,C=c)=P(C=c,B=b,A=a)$
and so on for any permutation of $\{A=a,B=b,C=c\}$.
Is $P(A=a,B=b|C=c) = P(A=a|C=c)P(B=b|C=c)$?

I'm working through a proof that assumes this, but I can't seem to prove this simple result (and even suspect it isn't true).
I know we want to show the following equality
$\frac{P(A=a,B=b,C=c)}{P(C=c)} = \frac{P(A=a,C=c)}{P(C=c)} \times \frac{P(B=b,C=c)}{P(C=c)}$. But I'm not sure how.
Comment: I am not sure what exchangeable is supposed to mean.  Are A, B, C, really random variables?  Or are they events?  If they're rv's, it's not really clear what P(A,B,C) means (though it can be made clear).  If they're events, all events are exchangable.
Comment: Your definition is still off; it should be $P(A=a,B=b,C=c)=P(A=b,B=c,C=a)=\dots$.
Answer: It is not true that $A$ and $B$ are conditionally independent given $C$. For example, shuffle a deck of three cards, two of which are black and one of which is red, and let $A$ (resp. $B,C$) equal $1$ when the first (resp. second, third) card is red, and $0$ otherwise. Then $A,B,C$ are exchangeable, but neither two are independent given the third.


Regex angular ngModel

Question: Olá, estou com um problema com regex e angular.
Tenho um input que utiliza ngModel, e estou precisando utilizar um regex nele que impeça o usuário digitar inicialmente um número, ou seja, obrigatoriamente o primeiro digito do input não pode ser um número.
O problema, é que não consigo encontrar um regex que faça isso e não consigo aplicar nenhum regex com ngModel.
Alguém poderia me ajudar por favor. Meu input se encontra assim no momento:
 <input
     placeholder="Input name"
     class="inputs"
     value="{{input.inputField}}"
     pattern="^[a-z]"
     [(ngModel)]="input[i].inputField" />

Agradeço desde já...
Comment: Você pode criar uma função e chamar ela no atributo onKeyDown do seu input, e nela fazer essa validação de primeiro caractere como letra e o restante como números.
Comment: Não é só trocar o `pattern` por `ng-pattern`? https://docs.angularjs.org/api/ng/directive/ngPattern#usage
Comment: usa diretiva, mais fácil
Comment: http://kazale.com/angular-2-mascara-entrada-dados-input-mask-diretivas/
Answer: Não precisa de expressão regular para fazer esta validação, você pode pegar o primeiro valor do input com o método substr() e verificar se é um número com o método isNaN():
TS
if(e.target.value.substr(0,1) == isNaN(e.key)) {
  this.valores = undefined;
  this.message = true;
  return;
}

HTML
<input placeholder="Input name" [(ngModel)]="valores" (keydown)="eventos($event)"
 [readOnly]="message" (click)="volta()"/>

Pode ver um exemplo funcionando aqui.

Regex angular ngModel


Showing that $2z^4-3z^3+3z^2-z+1=0$ has no Real Roots

Question:
I am trying to show that $$p(z)=2z^4-3z^3+3z^2-z+1=0$$ has no real roots.

From a previous related post, I incorrectly proposed the following:
Suppose $p(z)$ has a root on the real axes, then $p(x)=2x^4-3x^3+3x^2-x+1=0$ for some $x\in\mathbb{R}$. Now by the rational root theorem, the only possible roots that $p(x)$ can have is when $x=1$. But $p(1)\neq 0$ and hence $p(z)$ cannot have a root on the real axes by contradiction.
Alternatively, if we can show that $p(x)\geq 0$ or $p(x)\leq 0$, this would be sufficient to show that no real roots exist. But this is not obvious. I have also shown that $p(z)$ has no imaginary roots.
I am unsure of how to show that $p(z)$ does not have a real root.
Comment: a real root isn't always a rational root.
Comment: Yep, I agree. A real root could be $\sqrt{1912}$. If you are referring to my "incorrectly proposed" solution, then yes you are right.
Comment: FYI: Note that $p(-z)=2z^4+3z^3+3z^2+z+1$, which has no coefficient sign changes. By the [Descartes Rule of Signs](https://en.wikipedia.org/wiki/Descartes%27_rule_of_signs), there are no negative (real) roots. Unfortunately, the Rule isn't helpful here for the positive case: since $p(z)$ exhibits four coefficient sign changes, Descartes only tells us that there are $4$, $2$, or $0$ positive (real) roots.
Answer: For a real $z$ we have:
$$
2z^4-3z^3+3z^2-z+1
=
\underbrace{z^2(2z^2-3z+2)}_{\ge 0}+
\underbrace{z^2-z+1}_{>0}
>0\ .
$$
Comment: @JulianAngussmith That looks like a reasonable way to reach that conclusion.
Comment: Quick question: Is $z^2(2z^2-3z+2)\geq 0$ as $z^2\geq 0$ and $2z^2-3z+2>0$?
Comment: @JulianAngussmith Yes, i tried to split the polynomial, so that we have as a sufficient condition for positivity the fact that two polynomials of second degree are positive. (And one of them is involved so that we can write the strict inequality, the other one with a factor which is $\ge 0$.)
Answer: I see the two threes in there, and I immediately think binomial theorem. To make those threes appear in the right degrees and with the right sign, you would need
$$
z(z-1)^3 = z^4 - 3z^3 + 3z^2 - z
$$
Thus we have
$$
p(z) = z(z-1)^3 + z^4 + 1
$$
Clearly $z^4 + 1$ is always greater than or equal to $1$. It remains to show that $z(z-1)^3>-1$. Since the only place $z(z-1)^3$ is negative is for $x\in (0,1)$, and on that interval, it's the product of one term between $0$ and $1$, and one term between $-1$ and $0$, we have our result.
Answer: Note that$$P\left(x+\frac38\right)=2 x^4+\frac{21 x^2}{16}+\frac{13x}{32}+\frac{1901}{2048}.$$Since the discriminant of $\frac{21 x^2}{16}+\frac{13x}{32}+\frac{1901}{2048}$ is negative, $\frac{21 x^2}{16}+\frac{13x}{32}+\frac{1901}{2048}>0$ for each real number $x$. Therefore$$(\forall x\in\mathbb{R}):P\left(x+\frac38\right)>0$$and this is equivalent to $(\forall x\in\mathbb{R}):P(x)>0$.
Comment: How did you guess $\frac{3}{8}$would work?
Comment: @HennoBrandsma It's just a matter of making the degree-3 term of $p(z + a)$ disappear. It's not very difficult to insert and solve, but it could've been pointed out explicitly.
Comment: @HennoBrandsma Probably because the coefficient of $x^3$ is $-3$, and $2\cdot \binom{4}{1}\cdot\frac{3}{8}=3$ (here, $2$ is the leading coefficient).
Comment: @HennoBrandsma If you have a polynomial $p(x)=a_nx^n+a_{n-1}x^{n-1}+\cdots a_ax+a_0$, then the coefficient of $x^{n-1}$ in $p\left(x-\frac{a_{n-1}}{na_n}\right)$ is always $0$.
Answer: Hint:  Note that $$2z^4-3z^3+3z^2-z+1=2\,\left(z^2-\frac{3}4z\right)^2+\frac{15}{8}\,\left(z-\frac{4}{15}\right)^2+\frac{13}{15}\,.$$


Using php command to pass custom php.ini values into drush phar

Question: I'm struggling with adding php values into drush.phar. Last time I installed drush I used composer and for that method I could add the php.ini values into the drush.ini, but with the new way to install the drush.phar, the drush.ini doesn't seem to be supported. I've been trying to use the new method of adding php values into the drush.phar, but either it doesn't work or I am doing it wrong. Here's an example of what I tried:
php -d memory_limit=256M /usr/local/bin/drush --php-options=memory_limit=256M
When I try something like that it just gives me the drush help so I'm assuming I've got something wrong.
Here's the example from the drush docs:
php -d foo=bar drush.phar --php-options=foo=bar

I'm not familiar with using the php command, but I guess I can just go back to using composer if I am not able add a few php values to the drush.phar this way. I also need to add open_basedir with an empty value since I need my php.ini to use open_basedir. I'm not sure how this php command is suppose to handle empty values.
Hoping someone has been able to do this.
Answer: You did it exactly right -- just add the additional Drush command, options and arguments after the part you already typed in.  For example:
php -d memory_limit=256M /usr/local/bin/drush --php-options=memory_limit=256M --root=/path --uri=example.com status
That's kind of a lot of typing, so you might want to make an alias:
alias drush='php -d memory_limit=256M /usr/local/bin/drush --php-options=memory_limit=256M'
Then:
drush --root=/path --uri=example.com status
Comment: Thanks. I think I am getting somewhere now. Interesting.

Does this mean that the command isn't permanent and has to be repeated every time? If that's true, would I need to add mulitple php options to the alias? Like for open_basedir, error_reporting, display_errors, etc...?
Comment: To make your alias files persistent, add them to a .bashrc file. (See: https://www.google.com/search?q=bashrc) If you have a lot of options to set, using -d would make your commandline very long. It would be better to use `php -c /path/to/php.ini` if you are setting more than one value.
Comment: Looks like it is working so far.

Added: `alias drush='php -c /etc/drush/php.ini'` to .bashrc.
Then:
`$ source .bashrc`
Comment: Then: `[public_html]$ drush --root=/path --uri=example.com status`

After that the other basic drush commands started working.

Thanks again for the tips!
Comment: Don't forget to include `--php-options='-c /etc/drush/php.ini'` in your alias.
Comment: OK. Drush had already started functioning without any warnings, but I changed the alias to this:
`alias drush="php -c /etc/drush/php.ini --php-options='-c /etc/drush/php.ini'"`
Comment: `alias drush="php -c /etc/drush/php.ini /usr/local/bin/drush --php-options='-c /etc/drush/php.ini'"`


getxattr operation not supported samba audit

Question: I have a strange issue with my samba ldap server, its a centos server with same 3.0, it was working fine from quite some time but suddenly I noticed that my log file is full of messages saying getxattr operation not supported samba audit..and it goes upto some TBs. If i comment vfs_object then it works fine but it doesn't log audit msgs which I dont want to be skipped.
couldn't find a way around.
Answer: Maybe your samba shares reside on a filesystem without xattr support (or mounted with the noxattr mount option)?
Comment: Yes, this filesystem is ext3 and it doesn't support xattr, but it was running from the beginning, and if doesnt support xattr, what is the way around to get rid of this msg?
Comment: Ext3 supports xattr, you should simply mount it with the **user_xattr** mount option.
Comment: I remounted the filesystem with user_xattr but showing me the below logs:   Apr 16 16:40:50 user smbd_audit: USER|IP|getxattr|fail (Operation not supported)|.//s.jpeg|user.SAMBA_PAI
Comment: Have you restarted samba? Have you installed xattr user-space utilities and library? If issuing `getfattr -d `, what you see?
Comment: yes i had restarted samba several times, log messages file flooded with this type of entries, for same IP its showing this error for all files placed in the shared folder, then again it goes for next IP and hit error for all files. Getfattr returns nothing. Can I share you the screenshot in any means to have a better idea about the same? What is this user.SAMBA_PAI means?
Comment: One more thing I noticed, let say I have opened the shared drive, then this error is shown for all the files and folders placed in that directory, again when I open any subdirectory, error logged for all the files and folders in subdirectory. And this is happening for the all the users in organization.
Answer: Though its not a good solution but you can skip this failure error from smb.conf file by just changing the log failure to exclude this getxattr option.