text:
Q: How to show query call back data results only start with Original code :
var data = {results: []}
    data.results = result;
    query.callback( data);

original internet code for loading data :(Any modification to get start with data)
$("#e5").select2({
    minimumInputLength: 1,
    query: function (query) {
        var data = {results: []}, i, j, s;
        for (i = 1; i < 5; i++) {
            s = "";
            for (j = 0; j < i; j++) {s = s + query.term;}
            data.results.push({id: query.term + i, text: s});
        }
        query.callback(data);
    }
});

Matcher function :
$("#e17").select2({
      matcher: function(term, text) { return text.toUpperCase().indexOf(term.toUpperCase())==0; }
});

Currently i am using this way :
      var $elem = $( ".auto{!randomJsIden}" );

        $elem.select2({
        minimumInputLength: 1,
        placeholder: "No value selected",
        allowClear : {!allowClear},
         query: function (query) {
             queryData{!randomJsIden}(query);
        },
             createSearchChoice:function(term, data) {
         if ({!syncManualEntry} == true) {
             return {id:term, text:term};
             }
            },
             matcher: function(term, text) { return text.toUpperCase().indexOf(term.toUpperCase())==0; },
            sortResults: function(results, container, query) {
             if (query.term) {
            return results.sort(function(a, b) {
                if (a.text.length > b.text.length) {
                    return 1;
                } else if (a.text.length < b.text.length) {
                    return -1;
                } else {
                    return 0;
                }
            });
            }
          return results;
             }
            });
------------------------------
------------------------------
 function queryData{!randomJsIden}(query){

           Visualforce.remoting.Manager.invokeAction(
                     '{!$RemoteAction.AutoCompleteV2_Con.getData}','{!sObjVal}','{!labelFieldVar}','{!valueFieldVar}',query.term,
                     function(result, event){

                         //if success
                         if(event.status){
                            var data = {results: []}
                            data.results =result;
                             query.callback( data);
                         }
                         else{
          alert('Invalid Field/Object API Name : '+event.message);
                         }
                     },
                      {escape: true}
                );
            }

Currently i am getting result all if i type letter a it is showing results containing a,I would like to like show result starting with a.
Updating question :
 <script>
        var v2{!randomJsIden}
function permute(input, permArr, usedChars) {
    var i, ch;
    for (i = 0; i < input.length; i++) {
        ch = input.splice(i, 1)[0];
        usedChars.push(ch);
        if (input.length === 0) {
            permArr.push(usedChars.slice());
        }
        permute(input, permArr, usedChars);
        input.splice(i, 0, ch);
        usedChars.pop();
    }
    return permArr;
}
        var prevVal{!randomJsIden};
        function autocompleteV2{!randomJsIden}(){
             var v2=this;
             jQuery(function($){ //on document.ready
                    v2.init($)
             });
        }

        autocompleteV2{!randomJsIden}.prototype={
            init : function($){

                       var $elem = $( ".auto{!randomJsIden}" ).select2({
                           minimumInputLength: 3,
                           placeholder: "No value selected",
                           allowClear : {!allowClear},
                           query: function (query) {
                               queryData{!randomJsIden}(query);

                           },
                           createSearchChoice:function(term, data) {
                                if({!syncManualEntry} == true){
                                    return {id:term, text:term};
                                }
                            },
                            matcher: function (term, text) {

        if (term.length === 0) return true;
        texts = text.split(" ");

        allCombinations = permute(texts, [], []);

        for (i in allCombinations) {
            if (allCombinations[i].join(" ").toUpperCase().indexOf(term.toUpperCase()) === 0) {
                return true;
            }
        }
        return false;
    },
    sortResults: function (results, container, query) {
        if (query.term) {
            // use the built in javascript sort function
            return results.sort(function (a, b) {
                if (a.text.length > b.text.length) {
                    return 1;
                } else if (a.text.length < b.text.length) {
                    return -1;
                } else {
                    return 0;
                }
            });
        }
        return results;
    }

                       });

                       $elem.on("select2-selecting", function(e) {

                           $('.hiddenField{!randomJsIden}').val(e.val);
                       });

                       $elem.on("select2-removed", function(e) {
                           $('.hiddenField{!randomJsIden}').val('');
                       });

                       if('{!cacheField}' !=''){
                           $elem.select2("data", {id: "{!targetFieldVar}", text: "{!cacheField}"})
                       }

                    },

            triggerSearch :function(val){

                                if(prevVal{!randomJsIden} != val){
                                    $=jQuery;
                                    prevVal{!randomJsIden} = val;
                                    var select = $('input.auto{!randomJsIden}');
                                    var search = $('.select2-input')
                                    select.select2('open');
                                    search.val(val);

                                    search.trigger("input");
                                }
                            }
        }

         /*
        *This method queries data according to the passed parameter
        *and populates the combobox accordingly
        ***/
        function queryData{!randomJsIden}(query){

           Visualforce.remoting.Manager.invokeAction(
                     '{!$RemoteAction.AutoCompleteV2_Con.getData}','{!sObjVal}','{!labelFieldVar}','{!valueFieldVar}',query.term,
                     function(result, event){

                         //if success
                         if(event.status){
                             var data = {results: []}
                             data.results = result;
                             query.callback( data);
                         }
                         else{
                              alert('Invalid Field/Object API Name : '+event.message);
                         }

                     },
                      {escape: true}
                );
            }

    </script>

    <apex:inputText style="{!Style}" id="hiddeninput" styleClass="auto{!randomJsIden}" value="{!cacheField}" />

    <apex:outputPanel id="hiddenPanel">
        <apex:inputText value="{!targetField}" id="hiddenField"
            styleClass="hiddenField{!randomJsIden}" style="display:none"/>
    </apex:outputPanel>
    <script>v2{!randomJsIden} = new autocompleteV2{!randomJsIden}({});</script>
</apex:component>

Still cant able to get result .I am using latest version from select2 3.5.4 please help me regarding this .
Help me regarding this .
Updating my question :
http://jsfiddle.net/Lnf8j/289/
i experimented with this fiddle :
$('#placeSelect').select2({
    width: '100%',
    allowClear: true,
    multiple: true,
    maximumSelectionSize: 1,
    placeholder: "Click here and start typing to search.",
    data: [
            { id: 1, text: "Ford"     },
            { id: 2, text: "Dodge"    },
            { id: 3, text: "Mercedes" },
            { id: 4, text: "Jaguar"   }
          ],
     matcher: function (term, text) {

           if (text.toUpperCase().indexOf(term.toUpperCase()) == 0) {
    return true;
  }

  return false;
}
});

i am getting good results
if i changed this to data by this
   query: function (query) {
    queryData{!randomJsIden}(query);
            },
         (OR)

 var data = {results: []}
data.results = result;
query.callback( data);

I am not getting good result
some thing to change here to get good result

A: Change your matcher function accordingly something like this:
  matcher: function(term, text) { return text.toUpperCase().startsWith(term.toUpperCase()); }

A: Change your matcher function (aka your "predicate") to test only the first character in text. There are a few ways to do this, but I think the best is to use regular expressions. A regular expression is a type of search term that you can use on strings. In this case, you might use a RegExp like term = /^a/i:

*

*/: Start the regular expression.

*^: This regular expression only matches at the beginning of the text.

*a: The regular expression succeeds if it sees a literal character a at the immediate beginning of the text (since we wrote ^).

*/: End the regular expression.

*i: The regular expression is case in-sensitive; it can match A or a.

This function will return true if a RegExp object term matches a string text:
function matcher(term, text) {
    if (text.match(term)) {
        return true;
    } else {
        return false;
    }
}

Of course, instead of return matcher(term, text)), you could just write return text.match(term) from then on. But beware that a positive result isn't just a true value (see the documentation of String.prototype.match).


text:
Q: Is my proof of the irrationality of $\sqrt{3}$ legitimate? I read the proof of the irrationality of $\sqrt{3}$ in my textbook (Richard Hammack's Book of Proof), and I was wondering if my proof is legitimate as well.
Prop: $\sqrt{3}$ is irrational.
Suppose by way of contradiction that $\sqrt{3}$ is rational. Hence, $\sqrt{3} = \frac{m}{n}, m \in \mathbb{Z}, n \in \mathbb{N}$. Furthermore, suppose both $m,n$ are not even, so the fraction is reduced. Then, $3n^2=m^2$. Suppose $n$ is even, so $n = 2a, a \in \mathbb{Z}$. Therefore, $3 \cdot 4a^2=m^2 \longrightarrow m^2=12a^2 \longrightarrow m^2=2(6a^2)$ and $m^2$ is even, hence $m$ is even. This contradicts our assumption that both $m,n$ were not even, and hence $\sqrt{3}$ must be irrational. $\blacksquare$
Also, I'm wondering if I also need to show the case where $m$ is even?
Edit: Thank you for all the help. I realize that I was essentially trying to make the same argument as the classic proof of the irrationality of $\sqrt{2}$, but it doesn't quite work the same. I've done some research about the prime factorization theorem and I agree that $3n^2=m^2$ being a contradiction is definitely a more elegant proof that a case-by-case approach.

A: There are at least two flaws:

*

*you say $m,n$ are both not even, which in fact means neither $m$ nor $n$ are even.

*you say "so the fraction is reduced", but is $\frac{15}{25}$ reduced ?

Allowing only irreducible fractions, $$\sqrt3=\frac pq\iff p^2=3q^2.$$
So $p^2$ is a multiple of $3$, and so must $p$ be. Then $p^2$ is a multiple of $9$ and $q^2$ is a multiple of $3$. And so must $q$ be !

A: It's incomplete. You showed that $n$ cannot be even. But $n$ can still be odd and then your proof does not say that there is a contradiction (which there should be).

Here is a shorter proof:
Assume $3= m^2/n^2$ where $m,n \in \mathbb{Z}$, $n \neq 0$. Then
$$3n^2 = m^2$$
Comparing the unique prime factorizations of both sides we find that the prime $3$ occurs to odd power on the left side, but even power on the right side, contradicting the uniqueness of prime factorizations.
This same proof generalises to $\sqrt{p}$ is irrational for every prime $p$.

A: The $nth$ root of a number is rational precisely when $N$ is the $nth$ power of the rational number $\frac{a}{b}$.
$$\sqrt[n] N=\frac{a}{b} \iff N=\left (\frac{a}{b} \right )^n$$
Suppose that $\sqrt[n] N$ is not. There is a positive number $r$ subtracting $N$ so that their root is rational. We just need to define what $r$ is.
$$\sqrt[n] {N-r}= \frac{a}{b} \iff N=\left (\frac{a}{b} \right )^n+r, r>0$$
If $(\frac{a}{b})^n$ is the first term of a binomial expansion, then because we're adding something to it, $r$ is defined by its following terms, otherwise known for this summation starting at $1$.
$$r=\sum_{k=1}^n {n \choose k} \left (\frac{a}{b} \right )^{n-k} \left (\frac{c}{d} \right )^k$$
And when you replace and expand this in the expression, you end up with the following binomial, whose purpose is to show that N is a $nth$ power.
$$N=\left (\frac{a}{b}+\frac{c}{d} \right )^n$$
However, does it have a rational base, when it's expressed by the sum of two numbers? The only way to find out is to make it a linear combination.
$$N=\left (\frac{a}{b}+\frac{c}{d} \right )^n \iff \sqrt[n] N=\frac{a}{b}+\frac{c}{d}
\\ \frac{a}{b}=\lambda\sqrt[n] N\land\frac{c}{d}=\left (1-\lambda\right)\sqrt[n] N\implies1\sqrt[n] N=\lambda\sqrt[n] N+\left(1-\lambda\right)\sqrt[n] N$$
Therefore, using our assumption that $\sqrt[n] N$ is irrational, $\frac{a}{b}$ and $\frac{c}{d}$ must be too for some rational $\lambda$. Should the former be rational, the latter two are as well. The number $r$ that we defined is not necessarily irrational due to its products in the expansion.

Let's use the proposition in the opening question: $\sqrt 3$ is irrational.
$$\sqrt {3-r}=\frac{a}{b} \iff 3=\left (\frac{a}{b}\right )^2+r,r>0$$
We consider $r$ to be the binomial expansion using $n=2$.
$$r=2\left (\frac{a}{b}\right )\left (\frac{c}{d}\right )+\left (\frac{c}{d}\right )^2 \implies 3=\left (\frac{a}{b}+\frac{c}{d} \right )^2$$
Then find two numbers for the linear combination to hold.
$$\frac{a}{b}=\frac{\sqrt 3}{2}\land\frac{c}{d}=\frac{\sqrt 3}{2}\implies\sqrt 3=\frac{a}{b}+\frac{c}{d}$$
Therefore, since our assumption was that $\sqrt 3$ was irrational, those two numbers are as well. The number $r$ is rational:
$$r=2\left (\frac{\sqrt 3}{2}\right)\left (\frac{\sqrt 3}{2}\right )+\left (\frac{\sqrt 3}{2}\right )^2=\frac{9}{4}$$

Should this exercise be the square root of $4$, and because we can find two integers whose square is equal to it, the expression would unfold differently and you would find that the numbers in that linear combination are equal to $1$. It means that you can find a lower square by following that process even after the assumption that it has integer roots.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Address already in use: JVM_Bind but no process is listed using port with netstat I have a java process that make use of ServerSocket API (Java 8) and bind to the local port 12000.  Process runs under a Windows service Wrapper (exe4j).  I have a scheduled task that runs at 4am that stop the service and restart it after a couple of seconds.  That process is installed over 400 customers locations.
Everything was running smooth until about last friday.  A few processes failed to restart properly at 4am.  On 2 servers I was able to connect and verify, the restart failed with both a "Address already in use: JVM_Bind".  It's seems that the port 12000 was still in use by a the system.
I used every tools (processexplorer, tcpview, netstat -ano, name it) I know to try to find the process... with no success.  Only a machine reboot fixed the issue.  But problem came back a night or two later.
After some reading, I saw that I was doing a sockect.accept() with infinite timeout so I changed it for

socket.setSoTimeout(15000);
socket.accept();

instead.
I putted the new version in place but the problem is still there.
Machines got Windows updates. I did tests with the same Windows version fully updated but I can't reproduce.
I'm out of solution now.
Any ideas
Thanks

A: A windows update affected the release of address/port after process shutdown.
Refer to Address Bind exception in Tomcat for solution.

A: I am on the same problem here. I've got several Java instances running as servers but as soon as any of those Java applications is killed and restarted then they fail to do so complaining that the port is still in use. Never happened before and I used to restart them every now and then.
My Windows server machine also received some new updates a few days ago.
By the way, I am using a tool to monitor ports and applications and those ports are not being used by any program, so the application is actually killed.


text:
Q: How to move a mouse using the concept of object tracking in opencv? I was looking online and how people created this virtual mouse application using different principles such as color detector, object tracking, convexity defects etc etc. I wrote this program which actually tracks a single object from a webcam and its actually working really well. Now, the idea is to use this moving object which is being tracked and i want to control my mouse using this application. I dont want the source code and i want to do it myself. But i dont have any clue how to start it. I just hope if you guys can give me some clue or some ideas which can help me to connect my mouse to my program? I want to be able to do left click, right click, double click . Thanks

A: If you are able to track an object in the screen then you will get the object co-ordinates & set that as your target co-ordinate. I assume you already did that.
Now set the mouse cursor to that target co-ordinate refer this thread.


text:
Q: how to get selected cell value in gridview using asp..net I am using a Link button in a GridView. I need the value of the button I have clicked. Is there any way to achieve this ?

A: I suppose you want to get related row from GridView
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
    GridViewRow row = GridView1.Rows[e.NewSelectedIndex];

}

The required cell you can get from cells collection row.Cells


text:
Q: emitting a message to node.js after page close So I'm pretty new to it, so I apologize if I this is an entirely wrong approach of doing this, but I am currently programming a little chat application using node.js with express and socket.io. I managed to get a login message logged to the console but I am really struggling with the logout one. When a user opens up the page I take the roomname aswell as the username out of a cookie and send it to the server like shown here:
var socket = io();
var roomname = readCookie('Roomname');
var nickname = readCookie('Nickname');
var data = {'type': 'user', 'channel': roomname, 'user': nickname, 'data': "joined"};

socket.emit('chat', data);

After that I filter the message on the server side and send the answer to all clients like this:
case 'user':
  io.emit('chat/' + msg.channel, {type: 'user', user: msg.user, data: msg.data});
  break;

I always send the string "chat" followed by the roomname as a channel name so only the users that are in the right rooms can see the message. After that I sort out what kind of message was received by the client side:
case 'user':
  console.log(msg.user + " just " + msg.data + " the room!");
  break;

Now the only thing I need to do is somehow getting the room- and username to the server side once the user closes the page so I can send the message but with "left". (like this)
var data = {'type': 'user', 'channel': roomname, 'user': nickname, 'data': "left"};

socket.emit('chat', data);

My approach was finding an event that fires the code at the right time and I have been looking through stack overflow for a good hour now and I just couldn't find anything that did the job. I've tryed out all the variations of window.onbeforeunload I could find and none of them seemed to work. I could log some stuff to the console with some of them but I was never able to emit a message to the server side. I am aware that this may not be possible in the way I would like it to, but I really ran out of ideas what to try next. Can someone help me out?

A: You can add information about the client's username to the socket object, when the client connects for the first time. Then you will be able to use socket.username when client disconnects.
Client:
var socket = io();
var roomname = readCookie('Roomname');
var nickname = readCookie('Nickname');
socket.on('connect', () => {
    socket.emit("hello", {nick:nickname, room:roomname});
});

Server:
socket.on("hello", (data) => {
    socket.username = data.nick;
    socket.join(data.room);
    socket.room = data.room;
});
socket.on("disconnect", () => {
    var data = {'type':'user', 'channel':socket.room, 'user':socket.username, 'data':'left'};
    socket.broadcast.to(socket.room).emit('chat', data};
    socket.leave(socket.room);
});


text:
Q: The basis expansion of inertia tensor I want to express the inertia tensor in terms of the tensor products for cartesian coordinates in a Euclidean space, and for a general manifold
Consider the Euclidean space: $(\mathbb R^3, g)$ (where $g$ is the euclidean metric in cartesian coordinates) and the Angular momentum (in cartesian coordenates):
$$\textbf{L} = m\textbf{r}\times(\textbf{w}\times\textbf{r}) $$
where $\textbf{w}$ is the angular velocity vector.
So, we know that
$$\textbf{r}\times(\textbf{w}\times\textbf{r}) = \langle\textbf{r},\textbf{r}\rangle \textbf{w} -\langle\textbf{r},\textbf{w}\rangle\textbf{r}  $$
Then,using the summation convention in some parts,:

$$\textbf{L} = m[\langle\textbf{r},\textbf{r}\rangle \textbf{w} -\langle\textbf{r},\textbf{w}\rangle\textbf{r}]  \implies  L_i = m[ (\delta_{ij}r^ir^j)w^i- (r^i w^j) r^j] = m[r^ir_i (w_j\delta ^{ij})- (r^iw^j) r^j] = m[r^ir_i (w_j\delta ^{ij})- (r^ir^j) w^j] = m[r^ir_i (w_j\delta ^{ij})- (r^iw^j) r^j] = m{[r^ir_i\delta ^{ij}- (r^ir^j)]w_j} = \displaystyle \sum_{i} \sum_{j} m{[r^ir_i\delta ^{ij}- (r^ir^j)]w_j} = \sum_{j}I^{ij} w_j = \sum_{j}I_{ij} w_j $$

where:
 $w_j\delta ^{ij} = w^i\\ r^iw^j = \langle\textbf{r},\textbf{w}\rangle \\ r^ir_i = \delta_{ij}r^ir^j = \langle\textbf{r},\textbf{r}\rangle$
and $I^{ij} = I_{ij}$ because the coordinate system is cartesian i.e. $g = \delta_{ij}\mathbb d\mathbb r\otimes\mathbb d\mathbb r$.
So how can I write the tensor in terms of tensor products?
My guess:

$$I_{ij} = m \sum_{i} \sum_{j} [r^ir_i\delta ^{ij}- (r^ir^j)] = m \sum_{i} \sum_{j} [r^ir_j - (r^ir^j)]\iff \\ \textbf{I} = g - \mathbb r \otimes \mathbb r = \sum_{i} \sum_{j} \delta_{ij} \mathbb d\mathbb r^i\otimes\mathbb d\mathbb r^j - r^ir^j\mathbb e_{i} \otimes \mathbb e_{j} $$

A: Your index balance isn't good: for example, the expression $\delta_{ij}r^ir^j w^i$ is meaningless for Einstein's convention. When you wrote $L_i$ on the left-hand side, $i$ is not a dummy index anymore, so to write $\langle {\bf r},{\bf r}\rangle$ you must use some other indices, as in $\delta_{jk}r^jr^k$. Moreover, vectors have contravariant components, so we should go with $L^i$ instead of $L_i$ to avoid confusion. So: $${\bf L} = m(\langle {\bf r},{\bf r}\rangle {\bf w} - \langle {\bf r},{\bf w}\rangle{\bf r}) \implies L^i = m(\langle {\bf r},{\bf r}\rangle w^i - \langle{\bf r},{\bf w}\rangle r^i),$$and now we have $$L^i = m(\delta_{jk}r^jr^kw^i - \delta_{jk}r^jw^kr^i).$$Einstein's convention says we have a double sum $\sum_{j,k}$ there. I assume the definition of the inertia tensor (in coordinates) is $L^i = I^{ij}w_j$, where $w_j = \delta_{j\ell}w^\ell$. Note that we can actually keep the quantity $\langle{\bf r},{\bf r}\rangle$ as it is a number, to prevent indices from proliferating like a plague. Procceeding, we have $$L^i = m(\langle{\bf r},{\bf r}\rangle \delta^{ij}w_j - r^jr^iw_j) = m(\langle{\bf r},{\bf r}\rangle \delta^{ij}-r^ir^j)w_j \implies I^{ij} = m(\langle{\bf r},{\bf r}\rangle \delta^{ij}-r^ir^j).$$
In coordinate free notation, the last expression would be ${\bf I} = m(\langle{\bf r},{\bf r}\rangle {\rm Id} - {\bf r}\otimes {\bf r})$.


text:
Q: The $\mathrm{Proj}$-construction and inverse limits I have a couple of questions about existence of certain inverse limits in the category of schemes (I am also happy about links to relevant literature... in the stacksproject I only found the affine case). Let $R$ be a noetherian ring.
Given an inverse system of (graded) morphisms of graded $R$-algebras $(S_{j+1} \rightarrow S_{j})_{j \in \mathbb{N}}$,  $S_j = \bigoplus_{i \in \mathbb{N}} S_j^{(i)}$ generated in degree $1$ and with $S_j^{(0)}=R$ for all $j$,

*

*Does the inverse limit $\lim\mathrm{Proj}(S_j)$ exist (as a scheme or some other object)?

*Do we have $\lim S_j=\mathrm{Proj}(\mathrm{colim}(S_j))$?

*If not in this generality, is at least true that $\lim \mathbb{P}^j_R=\mathrm{Proj}(R[x_0,x_1,\ldots])$?

*If $I \subseteq R[x_0,x_1,\ldots]$ is a homogeneous ideal, and $I_1 \subseteq I_2 \subseteq \cdots$ a chain of homogeneous ideals with $I_j \subset R[x_0,\ldots,x_j]$ and such that $\bigcup I_i = I$, and such that $I_{j+1} \subseteq I_j+(x_{j+1})$, write $V_{+}(I_j) \subseteq \mathbb{P}^j_R$ for the associated closed subset. Does the inverse limit $\lim V_{+}(I_j)$ exist? Is it $\mathrm{Proj}(R[x_0, \ldots]/I)$?


text:
Q: How does Xojo UI rendering for desktop work? I was wondering if anyone could provide information about how Xojo renders UI for the desktop?
Is Xojo using bindings to make OS specific UI controls available (much like wxWindows)? Or has Xojo custom implementations of all UI controls (much like QT Framework)?
Thanks.

A: Neither.  They are in fact actual OS native controls that are "bound" but not in the way wxWidgets does, as least in as much as I understand how wxWidgets works.
Xojo is basically a wrapper on top of an actual OS instance - which is why you can use the Handle to pass to OS functions.


text:
Q: Silverlight and icollectionview So I have a datagrid that I need to add custom sorting for and I also need to know the exact order of the sort.
I have read in order to do this I need to implement a custom icollectionview and bind it to the datagrid.
The problem I am having is that the documentation Microsoft gives on this interface is not that great.  Does anyone know how to do this or have any good tutorials on how to implement this interface for silverlight?

A: I'm looking for the same, and found this article from Colin Eberhardt. It shows how to implement sorting using an implementation of ICollectionView
If you figure out how to implement filtering, please let me know.

A: Silverlight 3 now supports and implementation of the ICollectionView, called PagedCollectionView.
This provides sorting and grouping, but not filtering.

A: The best example I've found is Microsoft's ICollectionView implementation that was created for use with the DataGrid.  Unfortunately, they tagged it internal so you can't just use it outright (and a copy & paste of the source requires a few modifications).  Bust out Reflector and open System.Windows.Controls.Data.dll - navigate to the System.Windows.Controls namespace and there you can find ListCollectionView.  Here's the definition to show that it implements ICollectionView:
internal class ListCollectionView : ICollectionView, INotifyCollectionChanged, INotifyPropertyChanged, IEnumerable
...
I really wish MS would provide this class - practically every LOB app needs it.

A: Here's how you perform a sort using ICollectionView.
ICollectionView view = CollectionViewSource.GetDefaultView(someCollection);
view.SortDescriptions.Add(new SortDescription("someProperty", ListSortDirection.Ascending));
view.SortDescriptions.Add(new SortDescription("someOtherProperty", ListSortDirection.Descending));

However it's not exactly what I would call "custom sorting"... It just lets you choose the sort criteria and direction. Could you be more specific on what you want to do ?

A: For other's who browse to this question, I've found these sites helpful as well:

*

*Silverlight 3 Custom Sorting with Paging Support - Manish Dalal's blog

*ICollectionView explained « C# Disciples
I hope that Silverlight 5 has a better alternative. :)


text:
Q: How can we understand if the value inside a String is an int or not in Python? I am writing a code where I am facing the problem and need a solution if it exists.
Suppose we have a following String type variable in Python which contains an integer value.
Eg:x='123'
I know that we can easily convert this by type conversion to int.
However, suppose we have the following list.
x=['123','Spain']

Is there any method in Python by which I can know which element of the list x is Integer contained inside a string and which is purely an Object?

A: I would recommend this method:
x = "123"
if x.isdigit():
    # int
elif x.replace(".","",1).isdigit():
    # float
else:
    # str

A: I assume you have similar question with this post.
But, from my perspective, for more general solution (language agnostic), you should learn more about Regular Expression, here also the same question


text:
Q: Limited permissions on linux I want to give a specific user on Linux some privileges to enable him to run commands like shutdown or apt-get. I don't want to use the SUID bit since there are other users that I don't want to let them use these commands.
How do I do something like this?

A: sudo would probably be the easiest way to do this.  You'll want to add something like the following to the sudoers file
username   ALL=(ALL) /sbin/shutdown, /usr/bin/apt-get

where username is replaced with the user's actual username.  You should be able to google for some examples - here is one such page.
Editing the sudoers file can be done safely by using the visudo program.


text:
Q: Serial Differencing Aggregation This is my 1st attempt at Elasticsearch. I am trying to sort the data based on timestamp and in the result I want the difference between 2 consecutive timestamps.
I am trying to achieve the same through Serial Differencing Aggregation where I expect a field output with the difference. I do not get any output field with the difference.
So the question is this approach correct or there is something else that needs to be done?
  "aggs": {
    "users": {
      "terms": {
        "field": "ts"
      },
      "aggs": {
        "my_date_histo": {
          "date_histogram": {
            "field": "ts",
            "interval": "second"
          },
          "aggs": {
            "the_sum": {
              "sum": {
                "field": "lemmings"
              }
            },
            "thirtieth_difference": {
              "serial_diff": {
                "buckets_path": "the_sum",
                "lag": 1
              }
            }
          }
        }
      }
    }
  }

Here I do not have a field named "lemmings" but ElasticSearch does not complain.


text:
Q: Discrete math, antisymmetric proof question I am so confused on this one question on my practice work. it's: Show that if R is an antisymmetric relation on S then any relation R' ⊆ R is also antisymmetric. I think how you solve it is if (x,y) are in R, they must be in R' since R' is a subset of R, thus (x,y) are in R'. To be antisymmetric x has to be related to y and y has to be related to x such that x = y. And since R is antisymmetric and x,y are in R and R' is a subset then x,y in R' follow the same condition of R making them antisymmetric. That's one way I think it's solved but not 100% sure.

A: Mistake: If $(x,y) \in R$, then they must be in $R'$ since $R'$ is a subset of $R$.
This reasoning is not correct. If you see a black cat, you certainly see cat. If you see a cat, it need not be black.
If $(x,y) \in R'$, then $(x,y) \in R$ since $R' \subset R$, since $R$ is antisymmetirc, $(y,x)\notin R$ and hence we conclude that $(y,x)\notin R'$. That is $R'$ is antisymmetric.


text:
Q: Running Pytorch on Cloud TPU VM on GCP gives INVALID_ARGUMENT: No matching devices found for '/job:localservice/replica:0/task:0/device:TPU_SYSTEM:0' I created a TPU VM on GCP.
I am following the documentation page on how to run a calculation on a Cloud TPU VM by using PyTorch
I have set the XRT TPU device configuration in the VM with
export XRT_TPU_CONFIG="localservice;0;localhost:51011"

I created a Python file with following contents:
import torch
import torch_xla.core.xla_model as xm

dev = xm.xla_device()
t1 = torch.randn(3,3,device=dev)
t2 = torch.randn(3,3,device=dev)
print(t1 + t2)

But when I run the file, python3 tpu-test.py, I get the following error:
$ python3 tpu_test.py
Traceback (most recent call last):
  File "tpu_test.py", line 6, in <module>
    dev = xm.xla_device()
  File "/usr/local/lib/python3.8/dist-packages/torch_xla/core/xla_model.py", line 244, in xla_device
    devices = get_xla_supported_devices(devkind=devkind)
  File "/usr/local/lib/python3.8/dist-packages/torch_xla/core/xla_model.py", line 138, in get_xla_supported_devices
    xla_devices = _DEVICES.value
  File "/usr/local/lib/python3.8/dist-packages/torch_xla/utils/utils.py", line 32, in value
    self._value = self._gen_fn()
  File "/usr/local/lib/python3.8/dist-packages/torch_xla/core/xla_model.py", line 20, in <lambda>
    _DEVICES = xu.LazyProperty(lambda: torch_xla._XLAC._xla_get_devices())
RuntimeError: tensorflow/compiler/xla/xla_client/xrt_computation_client.cc:1374 : Check failed: session.Run({tensorflow::Output(result, 0)}, &outputs) == ::tensorflow::Status::OK() (INVALID_ARGUMENT: No matching devices found for '/job:localservice/replica:0/task:0/device:TPU_SYSTEM:0' vs. OK)
*** Begin stack trace ***
    tensorflow::CurrentStackTrace[abi:cxx11]()
    xla::XrtComputationClient::InitializeAndFetchTopology(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, tensorflow::ConfigProto const&)
    xla::XrtComputationClient::InitializeDevices(std::unique_ptr<tensorflow::tpu::TopologyProto, std::default_delete<tensorflow::tpu::TopologyProto> >)
    xla::XrtComputationClient::XrtComputationClient(xla::XrtComputationClient::Options, std::unique_ptr<tensorflow::tpu::TopologyProto, std::default_delete<tensorflow::tpu::TopologyProto> >)
    xla::ComputationClient::Create()

    xla::ComputationClient::Get()

    PyCFunction_Call
    _PyObject_MakeTpCall
    _PyEval_EvalFrameDefault
    _PyFunction_Vectorcall
    _PyEval_EvalFrameDefault

    PyObject_GetAttr
    _PyEval_EvalFrameDefault
    _PyEval_EvalCodeWithName
    _PyFunction_Vectorcall
    _PyEval_EvalFrameDefault

    _PyEval_EvalFrameDefault
    _PyEval_EvalCodeWithName
    PyEval_EvalCode

    PyRun_SimpleFileExFlags
    Py_RunMain
    Py_BytesMain
    __libc_start_main
    _start
*** End stack trace ***

A: Try with the below flag
export TPU_NUM_DEVICES=[num of logical cores]
for eg: on v3-8,
export TPU_NUM_DEVICES=8


text:
Q: Creating game in JavaScript and P5 - few fundamental questions I am currently working on a game that needs to be done using HTML, JavaScript, CSS and P5.
Idea is to have the standard 2d game where the character needs to enter the exit door on the map. Main features are rotating the "map" or "canvas" by 90 degrees with Q and E buttons. Game similar to the already existing game called Rotate. When rotating the map character stays in the same position so its only background that rotating.
I have following questions regarding the best approach:

*

*Should I write the map manually, i.e. assign the location on the map of each boundary (floor, walls etc) and then when rotating the map by 90 degrees just mathematically adjust the boundaries to a different location? Is this the best approach or is there any more time efficient are smarter approach?

*Should I be using P5 at all or this all can be done in HTML with dom manipulation?

*I want to have the camera effect by showing only square of the map - so that character is always centered - when walking to the left map would be moving rather then the character. So that the map can be always rotated in the current point of the character - center of the map.
I appreciate any advice or recommendation in advance.
Thanks!

A: You can place all the objects with respect to the centre, using the formula: xpos = distance * sin(angle), ypos = distance * cos(angle); Here's an example you could refer to:
let a;
let dist = 50;

function setup() {
  createCanvas(400, 400);
  rectMode(CENTER);
  a = PI;
}

function draw() {
  background(220);
  translate(width / 2, height / 2);
  let x = dist * sin(a);
  let y = dist * cos(a);
  rect(x, y, 20, 20);
  line(0, 0, x, y);
}

function keyTyped() {
  if (key == 'q' || key == 'Q')
    a += PI / 2;
  if (key == 'e' || key == 'E')
    a -= PI / 2;
}


text:
Q: Should I aware a user having low accept rates, system generated names and giving identical answers?
I know it's a hated post, but is a GENUINE question. I was unsure, that's why I asked on Meta

*

*Whenever I see a user with username as user2347894 I ask them to use proper names.

*Whenever I see a user a new user or basically below 50 rep, or acceptance rate is below 70Most of the time only below 50, I ask them to make a habit to accept the answer,

*

*to increase the acceptance rate

*to give themselves some bonus point

*to help other know the working solution

*When I see identical answers, I ask them not to post such. Agreeing on the fact that it might be unknowingly
Today, I seem to have offended few users. Your Common Sense and Michael specially. So, should I stop doing this, or is there a better way to approach the new users, without offending them or sending the negative meaning?
May be they got me wrong, since I only comment on the post I am involved because, WHY would I comment on post I don't even see or answer, maybe they are thinking I am being greedy or selfish, or over competitive over the reputation.

A: As for 1 (one), meh.  I've seen users with more rep than you who have the anon name.  If you want to change it, you will.  Personally, I see low rep + anon name as a signpost as to what kind of user they are.
Please don't do 2 (two).
Frankly, any comments that aren't extremely polite about acceptance rate get deleted whenever they're seen.  And 70% (seventy percent) is way high to be bothering people.  Ramp that down to under 50% (fifty percent).
Think of it this way--you have two questions, it is completely reasonable to have a 50% (fifty percent) acceptance rate.
And for 3 (three), it depends.
We see flags all the time about "duplicate answers" and people getting all butthurt about it.  But when we check, the answers are pitifully trivial and were submitted only a few minutes apart.  Frankly, easy questions get lots of answers.  Once people take the time to answer, they'll still submit it when other answers are coming in.  You don't want to spend a couple minutes answering a question just to throw it away.
Discouraging people from providing correct answers is just wrong.  Discourage the OP from asking questions that are trivial to the point where multiple similar answers come within a short period of time.
No, wait, I take that back.  Don't do that.  Just flag as low quality and move on.
If the answers are not trivial, that's usually indicative of something else.  Don't bother waging a comment war with the person who answered, just flag for moderator attention.  We'll need that information to establish a pattern of malfeasance.  If you just leave a comment, we'll never know a user has been copying other people's work.

A:
Whenever I see a user with usernames as user2347894 I ask them to user proper names.

These are user names that are assigned automatically by the site to users who aren't logged in.  One of the key features of the site is that it's easy to participate.  You don't even have to log in to leave an answer.  Asking people to user a "proper" user name is counter to this notion.

Whenever I see a user a new user or basically below 50 rep, or acceptance rate is below 70, I ask them to make a habit to accept the answer...

Accepting answers is totally optional.  Keep in mind that you can see someone's 0% acceptance rate after they've asked only 5 questions, so it's possible that they don't have any answers worth accepting.  Telling them to accept an answer just encourages them to accept any answer whether it's the right one or not.  Before you tell anyone to accept answers to their previous questions, check to make sure they have a specific answer worth accepting and recommend that.

When I see an identical answers, I ask them not to post such.

Questions get identical answers all the time within the first few minutes of being posted.  This is normal.  The most complete and correct answers will rise to the top, so there's no reason to comment on the remaining answers.

A: Here's my opinion on those:

*

*Don't ask people to use "proper" names. They can use whatever username they like.

*I'm constantly annoyed by people saying "if this answer helped you, please accept it" on their own answer. I find it a little arrogant. There will always be people who comment telling users to improve their accept rate, and there's also the 15-minute waiting period for accepting an answer, which users won't always hit exactly. So please don't nag; Stack Overflow already has mechanisms built in that remind askers to accept answers.

*Keep doing this; duplicate answers are usually bad, especially if they're not duplicates of said user's own answers. Of course, if the answers aren't exact duplicates but the questions can be closed as duplicates, do that instead.

A: I honestly wouldn't worry too much about these issues -

*

*Who cares, really? Does it truly matter what username they have? Sure, if you're typing it in a comment or answer it may be inconvenient, but the English language is so contextual, you can go a long way without using somebody's name. Worst case, you can call them "the OP"

*Whenever I see a comment insisting that somebody accepts an answer or works on their accept rate, I immediately flag it as "too chatty", since it is. Time and again it has been stated on the network that accept rates are irrelevant and don't matter. Write a good answer and you'll get far more rep than an acceptance will give you if it's so important to you. The important thing is to get good questions and answers.

*If you truly do find an answer that is a duplicate on the same question, go ahead, have fun flagging or downvoting. If they are a little different, but say much the same thing, then it's a much greyer area - you'll need to decide for yourself if it's coincidence or not. On the whole though, there are far worse examples of bad behaviour by users than that.

A: *

*None of your business, if they don't want to use a different name it doesn't hurt anyone.

*If they have 0% accept rate and you suspect they don't even know that they can accept answers, you might post a very polite comment explaining the concept. Having an accept rate below 70% is perfectly acceptable, and if you comment on the accept rate for such users your comments are likely to get flagged and instantly deleted.

*If they are copying other peoples answers without improving anything that is certainly reason to comment on that. If people post nearly identical solutions at the same time, I wouldn't comment on it, that just happens sometimes.


text:
Q: Can't add custom font to application I am having trouble using a custom font in my application.
The following describes the steps I took
1 - Add .TTF font to application
2 - Modify the info.plist file.
3 - Add the key "Fonts provided by application" to a new row
4 - And add each .TTF file (of font) to each line.
So I have an array of fonts, each of which has a .ttf extension.
And then I try to add the font
UILabel *lblName = [[UILabel alloc] initWithFrame:CGRectMake(25, 65, 230, 33)];
lblName.backgroundColor = [UIColor clearColor];
[lblName  setFont: [UIFont fontWithName:@"acmesab" size:32]]; // acmesab is my custom "font" name.
lblName.textAlignment = NSTextAlignmentLeft;
lblName.text = @"Name:";
[simapleView addSubview:lblName];

A: You should look at your font-properties what the actual font-name is.
Sometimes you import the font with name FjallaOne-Regular. But if you look at the properties you see that the font is named like Fjalla One.
Therefore you need to use it like this.
[lblName  setFont: [UIFont fontWithName:@"Fjalla One" size:32]];

Instead of
[lblName  setFont: [UIFont fontWithName:@"FjallaOne-Regular" size:32]];

Also check if you set the correct target membership
You can see what I mean by the correct name over here
LINK

A: For the custom font first you have to install your .ttf file in your system.after that import it to your project. Rename .ttf file as shown in "FontBook"  and
add
 <key>UIAppFonts</key>
    <array>
    <string>Times New Roman.ttf</string>
</array>

in your info.plist file. and then use it as fontname in your project
CCLabelTTF *label1 = [CCLabelTTF labelWithString:@"Name" fontName:@"Times New Roman" fontSize:26];

A: Open your project -> Targeta -> Build Phase -> Copy Bundle Resources. Check your files are shows in list or not? If not then add them and run the application again.It should work.
Use following code to check whether font is added or not and add appropriate font name from listing.
NSArray *familyNames = [[NSArray alloc] initWithArray:[UIFont familyNames]];
NSArray *fontNames;
NSInteger indFamily, indFont;
for (indFamily=0; indFamily<[familyNames count]; ++indFamily)
{
    NSLog(@"Family name: %@", [familyNames objectAtIndex:indFamily]);
    fontNames = [[NSArray alloc] initWithArray:
                 [UIFont fontNamesForFamilyName:
                  [familyNames objectAtIndex:indFamily]]];
    for (indFont=0; indFont<[fontNames count]; ++indFont)
    {
        NSLog(@"    Font name: %@", [fontNames objectAtIndex:indFont]);
    }
    [fontNames release];
}
[familyNames release];

A: It can be tricky sometimes as certain fonts don't seem to be recognised. Have a look at my answer from a few months ago which might help you - https://stackoverflow.com/a/10170599/331854


text:
Q: While using RMI I got this Exception : unmarshaling return header Exception Good Evening,
I am using RMI for communicating between Web Application(RMI client) and One Standalone java application(RMI server).
It gives following stack trace
java.rmi.UnmarshalException: Error unmarshaling return header; nested exception is:
    java.net.SocketException: Connection reset
    at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:228)
    at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:378)
    at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
    at ac.in.coep.vtu.rt.rmi.client.StartComputeTaskPI.getHardwareMappings(StartComputeTaskPI.java:178)
    at ac.in.coep.vtu.rt.dcs.implementations.HardwareMappingsImpl.getHardwareMappingsAndTagnames(HardwareMappingsImpl.java:43)
    at ac.in.coep.vtu.rt.dcs.services.HardwareMappingsServices.getHardwareMappingsAndTagnames(HardwareMappingsServices.java:24)
    at ac.in.coep.vtu.rt.controller.HardwareMappingController.fetchDisplayDataForDCS(HardwareMappingController.java:57)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:212)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:900)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:311)
    at ac.in.coep.vtu.filters.NoBrowserCacheFilter.doFilter(NoBrowserCacheFilter.java:67)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:116)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:101)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:146)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:182)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at ac.in.coep.vtu.filters.CaptchaCaptureFilter.doFilterInternal(CaptchaCaptureFilter.java:53)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at ac.in.coep.vtu.filters.ExpiredSessionFilter.doFilter(ExpiredSessionFilter.java:73)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.session.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:125)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:173)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)
Caused by: java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:196)
    at java.net.SocketInputStream.read(SocketInputStream.java:122)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:235)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:254)
    at java.io.DataInputStream.readByte(DataInputStream.java:265)
    at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:214)
    ... 80 more

My RMI server code is
I am using codebase.
    Runtime.getRuntime().exec("rmiregistry");

    Runtime.getRuntime().exec("rmid -J-Djava.security.policy=rmid.policy");
    System.setProperty("java.rmi.server.codebase", clazzToAddToServerCodebase
            .getProtectionDomain().getCodeSource().getLocation().toString());

    System.setProperty("java.security.policy",                      PolicyFileLocator.getLocationOfPolicyFile());

    if(System.getSecurityManager() == null) {
         System.setSecurityManager(new SecurityManager());
    }

Compute is Remote class
    Compute engine = new ComputeEngine();
    Compute engineStub = (Compute) UnicastRemoteObject.exportObject(
                    engine, 0);

    Registry registry = LocateRegistry
                    .createRegistry(RTConstants.RMIPortNumber);
    registry.rebind(Compute.GET_VTU_RT_SERVICE, engineStub);
    System.out.println("SERVER STARTED ...");

Some times it runs properly.
Please help me to solve this issue.


text:
Q: insert large data in 2 collections at a time in mongodb I am trying to insert large data around 20,000 in both the collection. I have a list of the path in an array which gives me an XML data where I am filtering it and pushing it to the database. "results" is the array of path.
Here is the code
const https = require('https');
var xpath = require('xpath')
var dom = require('xmldom').DOMParser

    results.forEach(ress => {
        const options = {
          hostname: 'abcd.com',
          port: 443,
          path: '/local/content' + ress,
          method: 'GET',
          rejectUnauthorized: false,
          requestCert: true,
          agent: false
        };
        https.request(options, (res) => {
          res.setEncoding('utf-8');
          res.on('data', (d) => {  //here i am getting XML data
            var doc = new dom().parseFromString(d);
            var nodes = xpath.select("//content", doc);
              nodes.forEach((n, i) => {
                pathvalue.push({
                   ........
                })
                projectdep.push({
                 .........
                })
              });
              dbo.collection("comp").insertMany(pathvalue, (err, post) => {
              });
              dbo.collection("pro").insertMany(projectdep, (err, post) => {
              });
          });
        }).on('error', (e) => {
          console.error(e);
        }).end();
      });

please help me with insert large data which is loop inside a loop.

A: You may want to promisify the request method as
const https = require('https');

function httpRequest(params, postData) {
    return new Promise(function(resolve, reject) {
        var req = https.request(params, function(res) {
            // reject on bad status
            if (res.statusCode < 200 || res.statusCode >= 300) {
                return reject(new Error('statusCode=' + res.statusCode));
            }
            // cumulate data
            var body = [];
            res.on('data', function(chunk) {
                body.push(chunk);
            });
            // resolve on end
            res.on('end', function() {
                try {
                    body = JSON.parse(Buffer.concat(body).toString());
                } catch(e) {
                    reject(e);
                }
                resolve(body);
            });
        });
        // reject on request error
        req.on('error', function(err) {
            reject(err);
        });

        if (postData) {
            req.write(postData);
        }
        // IMPORTANT
        req.end();
    });
}

Then create a list of promises that you can resolve in an async/wait as
const xpath = require('xpath')
const DOMParser = require('xmldom').DOMParser;

const docsPromises = results.map(res => {
    const options = {
        hostname: 'abcd.com',
        port: 443,
        path: '/local/content' + res,
        method: 'GET',
        rejectUnauthorized: false,
        requestCert: true,
        agent: false
    };

    return httpRequest(options, null);
});

(async () => {
    try {
        const docs = await Promise.all(docsPromises);
        const pathvalue = []
        const projectdep = []

        docs.forEach(d => {
            const doc = new DOMParser().parseFromString(d);
            const nodes = xpath.select("//content", doc);
            nodes.forEach((node, i) => {
                pathvalue.push({ ...node })
                projectdep.push({ ...node })
            });
        })

        await dbo.collection("comp").insertMany(pathvalue);
        await dbo.collection("pro").insertMany(projectdep);
    } catch (err) {
        console.error(err)
    }
})();


text:
Q: Add tapGesture to tableView then can not perform tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) method As we know, we use the below code can endEditing the searchBar's firstResponder, but if there is a scrollView or tableView, the effect is different.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)

    self.view.endEditing(true)
}

I add the tapGesture to tableView, so I can endEditing the searchBar's firstResponder.
But after add the tapGesture to my tableView, the tableView's tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) function will not work any more.
How can I solve the issue?

Addition
My useful code is below:
let tap:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(tapTableView))
self.tableView.addGestureRecognizer(tap)

func tapTableView() {

    self.searchBar.endEditing(true)
}

A: add the tapGesture on the view not on tableView
let tap:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(tapTableView))
self.view.addGestureRecognizer(tap)

A: Instead on your table view add
    tableView.keyboardDismissMode = .onDrag

You can change .onDrag to .interactive too. Remove the Touches began.
Edit: From apple docs
case none
    The keyboard does not get dismissed with a drag.
case onDrag
    The keyboard is dismissed when a drag begins.
case interactive
    The keyboard follows the dragging touch offscreen, and can be pulled upward again to cancel the dismiss.


text:
Q: CNG Import ECC Pub/Priv Keyfrom file I've been trying to find how to import an ECC key from a file by ANY MEANS for ages. I have tried accessing an ECC cert from the Windows certificate store, from a .p12 file, and from a PKCS#8 OpenSSL key file with no success.
Just one of the many things I have tried is:
StreamReader fs = new StreamReader("key.pem");
String key = fs.ReadToEnd();
byte[] tempkey = System.Text.Encoding.ASCII.GetBytes(key);
CngKey cngKey = CngKey.Import(tempkey, CngKeyBlobFormat.Pkcs8PrivateBlob);

But no discriptive error messages are given, only that the last line either has invalid parameters or in the case of the code above An error occurred during encode or decode operation.
I am using the sample program from MSDN for ECDH and altered it to use the GCM mode of AES. All of this works fine until I try and use pre-generated ECC keys instead of the ones created by default at runtime for the Microsoft example. I have randomly tried all of the CngKeyBlobFormats but to be honest, I can't debug it very well because I don't know what those specific formats look like in raw data.
My key is in the following format however I am willing to use any format that will work (.p12, Microsoft Store, PKCS#8, etc.)
key.pem
-----BEGIN EC PARAMETERS-----
##############################
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
##############################
-----END EC PRIVATE KEY-----

Resources
MSDN API and Example: ECDiffieHellmanCng Class
MSDN API: CngKey Class
MSDN Blogs: AES GCM Mode
OpenSSL - Creating ECC keys

A: *

*Generate an ECC key in PEM format using OpenSSL:

& openssl ecparam -name "secp521r1" -genkey -param_enc explicit -out ".\private.key"

The contents of the file is:
-----BEGIN EC PARAMETERS-----
MIIBwwIBATBNBgcqhkjOPQEBAkIB////////////////////////////////////
//////////////////////////////////////////////////8wgZ8EQgH/////
////////////////////////////////////////////////////////////////
/////////////////ARCAFGVPrlhjhyaH5KaIaC2hUDuotpyW5mzFfO4tImRjvEJ
4VYZOVHsfpN7FlLAvTuxvwc1c9+IPSw08e9FH9RrUD8AAxUA0J6IACkcuFOWzGcX
OTKEqqDaZLoEgYUEAMaFjga3BATpzZ4+y2YjlbRCnGSBOQU/tSH4KK9ga009uqFL
Xnfv51ko/h3BJ6L/qN4zSLPBhWpCm/l+fjHC5b1mARg5KWp4mjvABFyKX7QsfRvZ
mPVESVebRGgXr70XJz5mLJfucple9CZAxVC5AT+tB2E1PHCGonLCQIi+lHaf0WZQ
AkIB///////////////////////////////////////////6UYaHg78vlmt/zAFI
9wml0Du1ybiJnEeuu2+3HpE4ZAkCAQE=
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
MIICngIBAQRCABEwHYVa214LUODzm4BXWkBFSTBDU/N/nNwTB/mAP1Khpn0vd0QH
b/8BrfMbUYzzWXtXsvRvxPzKB2Sc6s7JC8CfoIIBxzCCAcMCAQEwTQYHKoZIzj0B
AQJCAf//////////////////////////////////////////////////////////
////////////////////////////MIGfBEIB////////////////////////////
//////////////////////////////////////////////////////////wEQgBR
lT65YY4cmh+SmiGgtoVA7qLacluZsxXzuLSJkY7xCeFWGTlR7H6TexZSwL07sb8H
NXPfiD0sNPHvRR/Ua1A/AAMVANCeiAApHLhTlsxnFzkyhKqg2mS6BIGFBADGhY4G
twQE6c2ePstmI5W0QpxkgTkFP7Uh+CivYGtNPbqhS1537+dZKP4dwSei/6jeM0iz
wYVqQpv5fn4xwuW9ZgEYOSlqeJo7wARcil+0LH0b2Zj1RElXm0RoF6+9Fyc+ZiyX
7nKZXvQmQMVQuQE/rQdhNTxwhqJywkCIvpR2n9FmUAJCAf//////////////////
////////////////////////+lGGh4O/L5Zrf8wBSPcJpdA7tcm4iZxHrrtvtx6R
OGQJAgEBoYGJA4GGAAQAIzBvnlURokMqtUyYrOJ5Kd1Mz0/7xGXkbhOR4ReIt9mt
hsL2tK3PQWj/j28IEajPRbVtxxA7McxQfayY9vUKdF8A6+qkOBCji82nKwKyu2+9
7l5FowAW05SdWRgJnqHU5ENf2h3Hje5UH1AidcpDZgTDuCV263PRKCUqUwX+LRN3
t7Y=
-----END EC PRIVATE KEY-----

Uhhhh I posted a private key - This is a generated one not used :-)
The file contains the key in SEC.1 format, which Cng cannot import. So we convert it to PKCS#8:
& openssl pkcs8 -topk8 -inform pem -in ".\private.key" -outform PEM -nocrypt -out ".\private_plain.p8"

Here is the PKCS#8 content:
-----BEGIN PRIVATE KEY-----
MIICsAIBADCCAdAGByqGSM49AgEwggHDAgEBME0GByqGSM49AQECQgH/////////
////////////////////////////////////////////////////////////////
/////////////zCBnwRCAf//////////////////////////////////////////
///////////////////////////////////////////8BEIAUZU+uWGOHJofkpoh
oLaFQO6i2nJbmbMV87i0iZGO8QnhVhk5Uex+k3sWUsC9O7G/BzVz34g9LDTx70Uf
1GtQPwADFQDQnogAKRy4U5bMZxc5MoSqoNpkugSBhQQAxoWOBrcEBOnNnj7LZiOV
tEKcZIE5BT+1Ifgor2BrTT26oUted+/nWSj+HcEnov+o3jNIs8GFakKb+X5+McLl
vWYBGDkpaniaO8AEXIpftCx9G9mY9URJV5tEaBevvRcnPmYsl+5ymV70JkDFULkB
P60HYTU8cIaicsJAiL6Udp/RZlACQgH/////////////////////////////////
//////////pRhoeDvy+Wa3/MAUj3CaXQO7XJuImcR667b7cekThkCQIBAQSB1jCB
0wIBAQRCABEwHYVa214LUODzm4BXWkBFSTBDU/N/nNwTB/mAP1Khpn0vd0QHb/8B
rfMbUYzzWXtXsvRvxPzKB2Sc6s7JC8CfoYGJA4GGAAQAIzBvnlURokMqtUyYrOJ5
Kd1Mz0/7xGXkbhOR4ReIt9mthsL2tK3PQWj/j28IEajPRbVtxxA7McxQfayY9vUK
dF8A6+qkOBCji82nKwKyu2+97l5FowAW05SdWRgJnqHU5ENf2h3Hje5UH1AidcpD
ZgTDuCV263PRKCUqUwX+LRN3t7Y=
-----END PRIVATE KEY-----

Not read the PKCS#8 and import the key:
$bytes = [Convert]::FromBase64String(
  [String]::Join(
    [String]::Empty,
    ([IO.File]::ReadAllLines(".\private_plain.p8") `
      | Where-Object { $_.StartsWith("-") -ne $true })));

$key = [System.Security.Cryptography.CngKey]::Import(
  $bytes,
  [System.Security.Cryptography.CngKeyBlobFormat]::Pkcs8PrivateBlob);

Write-Host $key.Algorithm

A: Although this may not be the only issue, you cannot simply ASCII encode a PEM file and then act as it is a PKCS#8 encoded blob. PKCS#8 is specified in ASN.1, which is normally BER/DER encoded. PEM base 64 encodes this binary encoding and then puts a header and footer around the base 64 to indicate the type of data that was encoded.
Note that the encoded parameters may have to be skipped. Hopefully these parameters are present in the encoding of the private key.


text:
Q: Extracting URLs from JSON file with python The JSON file is like this:
[
        {
            "src": "https://",
            "viewcount": "0"
        },
        {
            "src": "https://",
            "viewcount": "0"
        }

]

I wish to extract all the values under src (all of which are urls) with python.
How can I do so?
Thank you.

A: Try loading JSON first.
Sample output:

import json

myjsonstr =  '[{"src": "https://google.com","viewcount": "0"},{"src": "https://yahoo.com","viewcount": "0"}]'

myjsonobj = json.loads(myjsonstr)

for eachitem in myjsonobj:
    print(eachitem["src"])

A: You're looking for the json module. loads will try to parse a string (watch out, there's an extra/missing bracket in what you posted).
After that, it's a regular dict.
import json

source = """[
        {
            "src": "https://",
            "viewcount": "0"
        },
        {
            "src": "https://",
            "viewcount": "0"
        }
    ]
"""

urls = [x['src'] for x in json.loads(j)]

['https://', 'https://']


text:
Q: Wide to long omitting the early NAs I have this simple data frame,
colx <- c(2002-01, 2002-02, 2002-03, 2002-04)
cola <- c(10, 20, NA, 40)
colb <- c(NA, NA, NA, 400)
colc <- c(1000, 2000, 3000, 4000)

df <- data.frame(colx, cola, colb, colc)
df
> df
  colx cola colb colc
1 2001   10   NA 1000
2 2000   20   NA 2000
3 1999   NA   NA 3000
4 1998   40  400 4000

I want to convert it to long shape,
library(reshape2)
df_long <- melt(df, id.vars = c("colx"))
df_long

> df_long
   colx variable value
1  2001     cola    10
2  2000     cola    20
3  1999     cola    NA
4  1998     cola    40
5  2001     colb    NA
6  2000     colb    NA
7  1999     colb    NA
8  1998     colb   400
9  2001     colc  1000
10 2000     colc  2000
11 1999     colc  3000
12 1998     colc  4000

However, I want to avoid NAs if they exist at the beginning of the variable. E.g. in 'colb' the first 3 cases are NA. I want to avoid those NAs. However, if the NAs appear later in the variable, e.g. case 3 in cola, I don't want to remove it. The expected output should look as follows,
> df_long
  colx variable value
1 2001     cola    10
2 2000     cola    20
3 1999     cola    NA
4 1998     cola    40
5 1998     colb   400
6 2001     colc  1000
7 2000     colc  2000
8 1999     colc  3000
9 1998     colc  4000

Any suggestions on the way to achive this?

A: I don't think @Maël's solution works if you have NAs both in the beginning and in the middle of time series.
You can use cumany function in dplyr package.
df %>%
  pivot_longer(-colx) %>%
  group_by(name) %>%
  filter(cumany(!is.na(value)))


text:
Q: Kinesis Stream to S3 Backup using Firehose I am using AWS Kinesis Stream that is containing customer transactions. I want to backup the transactions into S3 before start processing them. How can I use bare Kinesis Firehose to backup the transactions from Kinesis Stream without running any Lambda or other computing component for it?

A: You can reverse the order of your Kinesis building blocks:

*

*Instead of writing into Kinesis Stream, write into Kinesis Firehose that is directed to S3.

*Run Kinesis Analytics (KA) application to read the events from your Kinesis Firehose (KF), and write them to a Kinesis Stream (KS). You can use the functionality of KA to do some of the filtering, aggregation and joins that you would otherwise run in your code (Lambda or KCL).


text:
Q: How do you make a primary key with Valentina Studio? Creating a table with fields in Valentina Studio with a primary key 'id'.  How do you set a primary key with Valentina? I know how to in the terminal.

A: It looks like you can by:

*

*Right click the table -> select 'Design'

*Click on the 'Constraints' tab in the dialog that opened

*Select the 'Primary Key' tab

*enjoy.


text:
Q: Calculating vector lengths within my loop The code is meant to draw a line with each click of the mouse made within the figure. Here is my code;
b=1
while b>0;
    axis([-10, 10, -10, 10])
    b=b+1
    [x(b),y(b)]=ginput(1)
    plot(x,y,x,y)
end

However I cant get my head around how I can add the vectors seeing as some are + and some are -, I need to turn the negatives into positives. I need to add code that will give me an overall combined length after all the mouse clicks. Maybe I am just thinking about it completely wrong.
I have tried;
length=(sqrt(x.^2)+(y.^2))

I was hoping this would give me the correct vector length accept unless I click an exact straight line.

A: Your problem is twofold: there's a typo, I think instead of
length=(sqrt(x.^2)+(y.^2))

you mean
length=sqrt((x.^2)+(y.^2))

The second problem is, that this does not actually calculate the length of your path, instead, you probably want something like
clear all
b=1;
radius = 3;
while b>0;
    axis([-10, 10, -10, 10])
    b=b+1;
    [x(b),y(b)]=ginput(1);
    plot(x,y,x,y);
    length(b)=sqrt((x(b)-x(b-1))^2+(y(b)-y(b-1))^2);
    if sqrt(x(b)^2 + y(b)^2) < radius; break; end
end
sum(length)

which calculates the length for each new piece you add and sums them all up.
As soon as you click within "radius" distance of 0 the while loop breaks.
Also, generally it's good practice to preallocate variables, no big deal here, cause your arrays are small, just saying.
Note: Dan's solution gives you a vectorized way of calculating the total length in one step, so in case you don't need the individual path lengths this is the more concise way to go.

A: So assuming that x and y are vectors of sequential points, if you want to get the total distance then you need to take the sum of the distance between each point i.e.
Σi(sqrt((xi-xi-1)2+(yi-yi-1)2))
in Matlab we can calculate all the x (and y) differences in one step using the diff function so in the end we get
length = sum(sqrt(diff(x).^2 + diff(y).^2))


text:
Q: Enabling lightContent status bar style in a VIPER project In previous versions of Swift, to change the status bar style I would use 'preferredStatusBarStyle' and return .lightContent.
This method is now unavailable, I have tried every solution on SO such as:
    self.navigationController?.navigationBar.barStyle = UIBarStyle.black
    self.navigationController?.isNavigationBarHidden = true

However, these techniques do not work. Can someone please shed some light on this. Currently in my plist, I have 'statusBarStyle' set to 'UIStatusBarStyleLightContent'.
You're welcome to download my project here: https://github.com/benskill/Flash-Flags

A: In iOS 10, preferredStatusBarStyle is a property, not a method. So instead of overriding it with a func declaration, you override the getter with a var declaration.
override var preferredStatusBarStyle: UIStatusBarStyle {
   return .lightContent
}


text: Q: How to do reverse engineering in ASP.NET Core with IdentityDbContext<> I have an existing database with Identity DB context model in it. When I reverse engineer it, it creates a context deriving from DbContext - but I want it to derive from IdentityDbContext.


text:
Q: Not sure if my String code is case sensitive I keep getting the incorrect answer to how many lines contain the text. I believe my code is ignoring punctuation (e.g. it won't detect the) and upper-case variations like (The).
For Example, if a file contains 5268 lines, and 1137 of those lines contain the word "the", my code returns output saying it only contains 1032 of those lines contain the word "the".
Thank you. Code is Below
while((sentence=buffer.readLine()) != null) //Reading Content from the file till the end of file
{
    if (sentence.contains(search_word))
    {
        word_line_count++;
    }
    line_count++; //increment line count for every while loop iteration
}

System.out.println(file_name + " has " + line_count + " lines"); //printing the line count
System.out.println("Enter some text");
System.out.println( word_line_count + " line(s) contain " + "\"" + search_word + "\""); //printing the number of lines contains the given word
file_object.close(); //closing file object

A: Punctuation is counted, but mixed case is not. Easiest fix would be to change
if (sentence.contains(search_word))

to
if (sentence.toLowerCase().contains(search_word.toLowerCase()))

it would be even better to convert search_word to lowercase once before the loop.


text:
Q: Matrix multiplication resulting in different values in MATLAB and NUMPY(?) Here's the matrix
>> x = [2 7 5 9 2; 8 3 1 6 10; 4 7 3 10 1; 6 7 10 1 8;2 8 2 5 9]

Matlab gives me
>> mtimes(x',x)
ans =

   124   124    94   122   154
   124   220   145   198   179
    94   145   139   101   121
   122   198   101   243   141
   154   179   121   141   250

However, the same operation(on same data) in python(numpy) produces different result. I'm unable to understand why?
import numpy as np
a = [[2, 7, 5, 9, 2],[8,3,1,6,10],[4,7,3,10,1],[6,7,10,1,8],[2,8,2,5,9]]
x = np.array(a)
print 'A : ',type(x),'\n',x,'\n\n'
# print np.transpose(A)
X = np.multiply(np.transpose(x),x)
print "A'*A",type(X),'\n',X

produces
A :  <type 'numpy.ndarray'>
[[ 2  7  5  9  2]
 [ 8  3  1  6 10]
 [ 4  7  3 10  1]
 [ 6  7 10  1  8]
 [ 2  8  2  5  9]]

A'*A <type 'numpy.ndarray'>
[[  4  56  20  54   4]
 [ 56   9   7  42  80]
 [ 20   7   9 100   2]
 [ 54  42 100   1  40]
 [  4  80   2  40  81]]

A: Numpy documentation states that the operator you apply performs element-wise multiplication.
However, mtimes in MATLAB does matrix multiplication.
To verify, MATLAB syntax for element-wise multiplication produces the same result you see in numpy:
disp(x.'.*x)

     4    56    20    54     4
    56     9     7    42    80
    20     7     9   100     2
    54    42   100     1    40
     4    80     2    40    81


text:
Q: mIRC - Pausing hash table Code;
on *:text:!ticket *:#:{
 var %hash $+(ticket.,#)
  if $istok(%owner,$nick,32) && $2 == on && !$hget(%hash) {
    hmake %hash
    msg # Ticket now is open. Use !ticket <point> to join.
  }
  elseif $2 isnum && $2 > 0 && $hget(%hash) {
    var %topic $+(#,.,$nick), %point $readini(points.ini,%topic,points)
    if %point >= $2 {
      var %p $calc(%point - $2)
      writeini points.ini %topic points %p
      var %i $hget(%hash,0).item, %t $calc(%i + $2)
      while %i < %t { inc %i | hadd %hash %i $nick }
      msg # $nick $+ , You bought $2 ticket, you now have %p points
   }
    else { msg # $nick Sorry, you only have %point points }
  }
  elseif ($nick isop #) && $2 == roll && $hget(%hash) {
    var %i $rand(1,$hget(%hash,0).data)
    msg # The winner is $hget(%hash,%i).data $+ .
    //I want to pause the raffle here so no more people can buy tickets but it sill keeps the entrys
  }
   elseif ($nick isop #) && $2 == over && $hget(%hash) {
        hfree %hash
  }
    elseif ($nick isop #) && $2 == go && $hget(%hash) {
            //I want people to be allowed to by more tickets and have the old tickets still count
  }
}

It's all good. I just need to be able to pause the raffle but not get rid of the entries and then be able to resume the raffle. Comments in code to explain

A: this is the part you want
on *:text:!ticket *:#:{
var %hash $+(ticket.,#)
if $istok(%owner,$nick,32) && $2 == on && !$hget(%hash) {
hmake %hash
msg # Ticket now is open. Use !ticket <point> to join.
}
elseif $2 isnum && $2 > 0 && $hget(%hash) {
var %topic $+(#,.,$nick), %point $readini(points.ini,%topic,points)
if %point >= $2 && !%pause {
// here script will check if %pause is not set, so script will run normal, if yes, it wont work
  var %p $calc(%point - $2)
  writeini points.ini %topic points %p
  var %i $hget(%hash,0).item, %t $calc(%i + $2)
  while %i < %t { inc %i | hadd %hash %i $nick }
  msg # $nick $+ , You bought $2 ticket, you now have %p points
 }
else { msg # $nick Sorry, you only have %point points }
}
elseif ($nick isop #) && $2 == roll && $hget(%hash) {
var %i $rand(1,$hget(%hash,0).data)
msg # The winner is $hget(%hash,%i).data $+ .
inc -u10 %pause
//10 is time in seconds you can choose whatever time you want, so in this way, no one  can buy tickets for 10 seconds
}
elseif ($nick isop #) && $2 == over && $hget(%hash) {
hfree %hash
}
elseif ($nick isop #) && $2 == go && $hget(%hash) {
unset %pause
// if someone typed "roll" and then you want to buy more tickes, typing "go" will just unset %pause
// you can set %pause for more time, or just an unlimmited time
}
}

i didnt test it yet


text:
Q: When is a k-space locally compact? We're looking at the possible cardinal sequences of LCS (locally compact, Hausdorff, scattered) spaces, which has led us to think about taking a quotient of a locally compact, scattered space.
A k-space (compactly generated Hausdorff space) is a quotient space of a disjoint union of compact Hausdorff spaces. Every locally compact Hausdorff space is a k-space, but not every k-space is locally compact. However, every k-space is a quotient of a locally compact Hausdorff space.

*

*Is there a general condition for a k-space to be locally compact?

*What if we assume the space is a quotient of an LCS space?

*Is there a condition that also guarantees a k-space is an LCS space?
Looking through Engelking and Google I couldn't find anything.

A: $\DeclareMathOperator\colim{colim}\DeclareMathOperator\CS{CS}\DeclareMathOperator\CSN{CSN}$The examples considered in algebraic topology are usually like $\mathbb{R}^\infty=\colim_n\mathbb{R}^n$ or $O(\infty)=\colim_n O(n)$ (the infinite orthogonal group) or infinite-dimensional CW complexes.  These can usually be written as the colimit of locally compact Hausdorff spaces $X_n$ and
closed inclusions $X_n\to X_{n+1}$, where $X_n$ typically has
empty interior in $X_{n+1}$.  In this context, a standard lemma
says that every compact subset $K\subseteq X$ is contained in
some $X_n$ and so has empty interior in $X_{n+1}$ (and therefore
also has empty interior in $X$).  Thus, examples of this type
will never be locally compact.
One could consider the class $\mathcal{C}$ of k-spaces in which every compact set has empty interior, which is a kind of opposite to local compactness.   I think that this class of spaces contains most of the popular examples and has good closure properties.
On the other hand, very many spaces can be written as a quotient of an LCS space.  Indeed, let $\CS(X)$ be the set of continuous maps $\mathbb{N}\cup\{\infty\}\to X$ (i.e. pairs consisting of a convergent sequence and its limit).  We can give $\CS(X)$ the discrete topology and the space $\CSN(X)=\CS(X)\times(\mathbb{N}\cup\{\infty\})$ the product topology.  This makes $\CSN(X)$ into an LCS space, with an evident surjective evaluation map $\epsilon\colon \CSN(X)\to X$.  The space $X$ is said to be sequential if $\epsilon$ is a quotient map.  (The definition is usually phrased differently, but easily seen to be equivalent.)  One can check that if $X$ is a k-space and every compact subspace is metrisable then $X$ is sequential.  This covers most examples typically considered in algebraic topology.
My guess is that the space $\beta(\mathbb{N})$ (the Stone–Čech compactification of the naturals) is not a quotient of an LCS space, but I have not checked that.

A: For first-countable regular spaces (which form an important subclass of LCS-spaces) there exists a simple characterization: a first-countable regular space $X$ is not locally countably compact if and only if $X$ contains a closed subspace, homeomorphic to the subspace $$\mathbb L=\{(0,0)\}\cup\{(\tfrac1n,\tfrac1{nm}):n,m\in\mathbb N\}$$ of the Euclidean plane.
This characterization implies that a first-countable paracompact space $X$ is locally compact if and only if $X$ contains no closed subspaces, homeomorphic to $\mathbb L$.


text:
Q: Define custom projection with small offset in QGIS I have a series of raster maps of geophysics for an archaeological site in Turkey. These are ostensibly in UTM zone 35, WGS84 projection, but the surveyors set their grid with a total station using a slightly different coordinate for our local datum than the one we use, 1.726 m to the W and 0.735 m to the S. So when I bring them into QGIS 3.18 with the data for the site as a whole, they end up shifted a couple meters to the SW. What is the easiest way to bring them all into alignment with the rest of the system?
I naively tried creating a custom projection with a small offset (like post Shift a CRS by an observed offset) by adding 1.726 to the false easting and 0.735 to the false northing of the project CRS 32635, so:
PROJCRS["GeoIm 2018",
    BASEGEOGCRS["WGS 84",
        DATUM["World Geodetic System 1984",
            ELLIPSOID["WGS 84",6378137,298.257223563,
                LENGTHUNIT["metre",1]]],
        PRIMEM["Greenwich",0,
            ANGLEUNIT["degree",0.0174532925199433]],
        ID["EPSG",4326]],
    CONVERSION["unnamed",
        METHOD["Transverse Mercator",
            ID["EPSG",9807]],
        PARAMETER["Latitude of natural origin",0,
            ANGLEUNIT["degree",0.0174532925199433],
            ID["EPSG",8801]],
        PARAMETER["Longitude of natural origin",27,
            ANGLEUNIT["degree",0.0174532925199433],
            ID["EPSG",8802]],
        PARAMETER["Scale factor at natural origin",0.9996,
            SCALEUNIT["unity",1],
            ID["EPSG",8805]],
        PARAMETER["False easting",50001.726,
            LENGTHUNIT["metre",1],
            ID["EPSG",8806]],
        PARAMETER["False northing",0.735,
            LENGTHUNIT["metre",1],
            ID["EPSG",8807]]],
    CS[Cartesian,2],
        AXIS["easting",east,
            ORDER[1],
            LENGTHUNIT["metre",1,
                ID["EPSG",9001]]],
        AXIS["northing",north,
            ORDER[2],
            LENGTHUNIT["metre",1,
    ID["EPSG",9001]]]]

This however shifts a test raster by about 450000 m to the east. I'm obviously flailing here; can someone point me in the right direction? Since I will be getting more data from these folks in the future, it seems better to somehow recognize their system than manually move every raster by a given amount.

A: Your false easting is only 50,001 m instead of the required 500,001.


text:
Q: Why does calling eval without a block terminate this Perl program? The following program stops at the 2nd call to eval. Is that expected? I read perldoc -f eval and am surprised that the output of print "2: ..." is not displayed.
eval {die("The curly braces seem to rescue me! Life moves on")};
print "1: $@\n";
eval die("Program actually terminates here! Subsequent prints are not shown");
print "2: $@\n";

A: perldoc -f eval

eval EXPR
eval BLOCK
eval    In the first form, often referred to as a "string eval", the
        return value of EXPR is parsed and executed as if it were a little
        Perl program.

… so die is called and then the string it returns is evaluated.
… except it doesn't return a string. It makes the program die so eval is never called.


text:
Q: jQuery reel Directional mode with sequence not working am new to jquery Reel plugin, Directional mode with sequence not working, please correct my code
<img src="fish/DSCN0691.JPG" width="210" height="186"
  class="reel"
  id="image"
  data-images="fish/DSCN####.JPG|691..702"
  data-directional="true"
  data-frame="3"
  data-opening="1"
  data-delay="3"
  data-speed="1">

for each direction it should take 6frames... but its working as normal reel. please correct my code. thanks.


text:
Q: Python - How can I download csv dataset from ourworldindata.org in Google Colab? As written in the question, I would like to download a csv dataset from the website ourworldindata.org for further data manipulation using Google Colab. In principle, I could download it to my machine and upload it to Colab or save it to my Google Drive after having linked it to the Colab worksheet.
However, I was wondering if there is a more straightforward way to get the data.

A: You can download datasets using !wget 'link to the file', but in ourworldindata.org, you don't get a specific link to download the .csv file is what I observed in most of the cases.
But for a few datasets, you can find the link to download the .csv file and you can use
cd 'working_folder'

!wget https://covid.ourworldindata.org/data/owid-covid-data.csv

to download the file directly to your working folder


text:
Q: Qt. signal linked to slot of latest object I am creating multiple object of type QWidget_WindowContact at runtime. When I click the Increment or decrement buttons the value in the last generated object gets updated and not the value in the same object.
I am struggling to properly link the signals and slots, so that when multiple objects of the same type are generated at runtime the signal emitted by the button coressponds to the signal in the right object.
QWidget_WindowContact.h:
#ifndef QWIDGET_WINDOWCONTACT_H
#define QWIDGET_WINDOWCONTACT_H

#include "qwidget.h"

class QWidget_WindowContact : public QWidget
{

Q_OBJECT

public:
    explicit QWidget_WindowContact(QWidget* parent = nullptr);

    private slots:
        void on_btnInc_clicked();
        void on_btnDec_clicked();
        void on_btnDel_clicked();

private:
    QPoint offset;

protected:

};

#endif // QWIDGETTEMP_H

QWidget_WindowContact.h:
#include <QtWidgets>

#include "QWidget_WindowContact.h"

QSpinBox* counter;

QWidget_WindowContact::QWidget_WindowContact(QWidget* parent) : QWidget(parent)
{
    this->setObjectName("");
    setMinimumSize(100, 100);

    this->setStyleSheet("border: 1px solid gray");

    QVBoxLayout* layout = new QVBoxLayout(this);

    QLabel* name = new QLabel("WINDOWCONTACT", this);

    QPushButton* btnInc = new QPushButton("Increment", this);
    btnInc->setObjectName("btnInc");
    QPushButton* btnDec = new QPushButton("Decrement", this);
    btnDec->setObjectName("btnDec");
    QPushButton* btnDel = new QPushButton("Delete Widget", this);
    btnDel->setObjectName("btnDel");

    counter = new QSpinBox(this);
    counter->setObjectName("counter");

    connect(this->findChild<QPushButton*>("btnInc"), SIGNAL(clicked()), this, SLOT(on_btnInc_clicked()));
    connect(this->findChild<QPushButton*>("btnDec"), SIGNAL(clicked()), this, SLOT(on_btnDec_clicked()));
    connect(this->findChild<QPushButton*>("btnDel"), SIGNAL(clicked()), this, SLOT(on_btnDel_clicked()));

    layout->addWidget(name);
    layout->addWidget(counter);
    layout->addWidget(btnInc);
    layout->addWidget(btnDec);
    layout->addWidget(btnDel);

}

void QWidget_WindowContact::on_btnInc_clicked()
{
    counter->setValue(counter->value() + 1);
}

void QWidget_WindowContact::on_btnDec_clicked()
{
    counter->setValue(counter->value() - 1);
}

void QWidget_WindowContact::on_btnDel_clicked()
{
    close();
}

A: You have
QSpinBox* counter;

as a global variable, which changes its value every time new QWidget_WindowContact is created. This piece of code:
void QWidget_WindowContact::on_btnInc_clicked()
{
    counter->setValue(counter->value() + 1);
}

is using this global variable, which is always the pointer to the most recently created QSpinBox. Remove the global variable and either keep this QSpinBox* ptr as a private member of your class, or use findChild QT feature:
void QWidget_WindowContact::on_btnInc_clicked()
{
    QSpinBox* counter = this->findChild<QSpinBox*>("counter");
    counter->setValue(counter->value() + 1);
}

As a side note, findChild is not actually needed in your CTor, because you still have the pointers to corresponding objects in scope.

A: Generally speaking, setting the widget names is not necessary unless you need it for debugging tools or introspection. Naming can be easily added at construction time using a template class, as well as insertion into the layout. That cuts down on verbosity. Note that WQ is a library class that you'd write once, and use widely, so there's not much concern with how "convoluted" it is - although of course it should use an actual tag-dispatch header library to
#include <QtWidgets>

static inline constexpr auto name_ = [] {};
static inline constexpr auto layout_ = [] {};
static inline constexpr auto text_ = [] {};

template<class Base>
class WQ : public Base
{
public:
    WQ() = default;

    template<class... Args>
    WQ(decltype(layout_), QLayout *layout, Args &&...args) : WQ(std::forward<Args>(args)...)
    {
        layout->addWidget(this);
    }

    template<class... Args>
    WQ(decltype(name_), QStringView name, Args &&...args) : WQ(std::forward<Args>(args)...)
    {
        this->setObjectName(name.toString());
    }

    template<class... Args>
    WQ(decltype(text_), QStringView text, Args &&...args) : WQ(std::forward<Args>(args)...)
    {
        this->setText(text.toString());
    }
};

The widget can be very compact, and built up declaratively - don't feel inspired by the code that comes as Qt examples, it's unnecessarily verbose. We can set up most "short" widget properties in the body of the class:
class QWidget_WindowContact : public QWidget
{
    Q_OBJECT
    using Self = QWidget_WindowContact;

public:
    explicit QWidget_WindowContact(QWidget *parent = nullptr);

private:
    void inc_clicked();
    void dec_clicked();

    QPoint offset;
    QVBoxLayout layout{this};
    WQ<QLabel> name{::layout_, &layout, ::text_, tr("WINDOWCONTACT")};
    WQ<QPushButton> btnInc{::layout_, &layout, ::text_, tr("Increment")};
    WQ<QPushButton> btnDec{::layout_, &layout, ::text_, tr("Decrement")};
    WQ<QPushButton> btnDel{::layout_, &layout, ::text_, tr("Delete Widget")};
    WQ<QSpinBox> counter{::layout_, &layout, ::name_, L"counter"};
};

Then, the constructor is simple as well:
QWidget_WindowContact::QWidget_WindowContact(QWidget *parent) : QWidget(parent)
{
    setMinimumSize(100, 100);
    setStyleSheet("border: 1px solid gray");

    connect(&btnInc, &QPushButton::clicked, this, &Self::inc_clicked);
    connect(&btnDec, &QPushButton::clicked, this, &Self::dec_clicked);
    connect(&btnDel, &QPushButton::clicked, this, &Self::close);
}

The slots remain as they were, and there's no need to actually make them slots unless you need that for introspection. Don't wrap methods in slots that "do nothing" but just forward the call - it's unnecessary. Also note the use of modern (Qt 5) style of signal-slot connections. Also note that the current Qt version is Qt 6.1 - so the modern signal-slot syntax is hardly "modern".
void QWidget_WindowContact::inc_clicked()
{
    counter.setValue(counter.value() + 1);
}

void QWidget_WindowContact::dec_clicked()
{
    counter.setValue(counter.value() - 1);
}

The example sets up a 3x3 grid of the widgets within an outer window:
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QWidget w;
    QGridLayout layout{&w};
    constexpr int rows = 3, cols = 3;
    QWidget_WindowContact wc[rows * cols];
    for (int i = 0; i < rows; ++i)
        for (int j = 0; j < cols; ++j)
            layout.addWidget(&wc[i * cols + j], i, j);
    w.show();
    return a.exec();
}

#include "main.moc"

This concludes the compileable example. It looks like this:


text:
Q: Is there any method to choose the value of each pixel according to land cover I have 2 images; one is land cover image (imgA) and monthly mean temperature image (imgB). I'd like to choose value of each pixel from imgB corresponding to imgA.
WhaT I expected is each pixel of certain land cover type should have different values in different area. I tried it using zonal statistic in ArcGIS and ERDAS. But zonal statistic give me only one value of each land cover (not in each pixel value). I'd like to keep all original pixel values of imgB according to each land cover. How can I do this using ArcGIS or ERDAS?

A: Using Raster Calculator in ArcGIS should accomplish this task.  Create a new field in your land cover raster and assign indicator numbers to each type (ie, Industrial = 100, Forest = 200, etc).  Then add the two raster layers.  Your output will have a 3-digit field where the first digit will indicate land cover and the second and third digits will represent the mean temp.


text:
Q: Prestashop 1.6 - php into admin override tpl Just wanted to include a custom php file into an override template I've made but when I use:
{php} include('custom_code.php'); {/php}

or:
{include_php file='../../../../../../panel/update.php'}

The page crashes. Prestashop is so hard to modify.

A: The approach you are following to include the PHP file is absolutely wrong, you should include the file in the Class file responsible for rendering the TPL file.
Once you do that you can write the business logic in the class file and then pass the required data to TPL file using the following code:
$this->context->smarty->assign('any_var', $any_value);

By using this you can get the data in your Smarty file and use the same accordingly.

A: I have solved the issue creating a plugin for smarty in the directory /tools/smarty/plugins with the file name function.update_customer.php . then i pute the code in my template .tpl with this shortcode hook {update_customer} .
Hope that helps in the future...


text:
Q: Что делает setlocale()? C/C++ Мне нужно перевести строку из cp1251 в Unicode. Для этого я использую MutliByteToWideChar(1251, ...).
Странность заключается в том, что если не сделать:
setlocate(LC_ALL, "rus");

То символы с кодами [128-255] переводятся неверно. Да, я знаю, что setlocale() задает используемую локаль... Но я не понимаю, какая тут связь с функцией конвертации, которой явно указали, что входная строка находится в cp1251.

A: setlocale задает текущую локаль для функций стандартной библиотеки С. Она никак не влияет на функцию MutliByteToWideChar. В этом легко убедиться на практике, данный код отлично работает без необходимости использовать setlocale:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

int __cdecl main(int argc, char **argv)
{
    char str[]="Привет";
    wchar_t* wstr = new wchar_t[1024];
    MultiByteToWideChar( 1251 , 0 , str , sizeof(str), wstr , 1024 );

    HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
    WriteConsoleW(consoleHandle, wstr, wcslen(wstr), NULL, NULL);

    getchar();
    return 0;
}

Ищите проблему в другом месте.


text:
Q: Only display hours if time is greater than 60 minutes I'm using a time-tracking sheet that calculates the time spent on a job by doing a simple subtraction between a start time and an end time in two cells.
The hh:mm format would suffice in this case, or as a small modification I'm using [h] "h" mm "m", but the issue with both is that I do not want the hours to display when there are none (when hours = 0).
If for example 35 minutes are logged I would like the output to be 35 m and not 0 h 35 m. The [mm] format might be an option then, but I would still like my time above 60 minutes to be displayed as 1 h 30 m, and not 90 m.

A: Please try:
[<0.04166666][mm] "m";[h] "h" mm "m"

A: Not at all elegant, but how about this:
=IF(HOUR(time)<1,MINUTE(time)&"m",HOUR(time)&"h "&MINUTE(time)&"m")
Returns a cell value 02:24:00 as "2h 24m"
and a cell value 00:14:24 as "14m"


text:
Q: Convert Image to binary I want to find the connected components of an image. I'm totally a beginner. Can somebody give me a link to some tutorials for this purpose. Also what is a binary image?. What does the term mean convert image to binary image? I'm working in C#.

A: A binary image is an image that has only two valid pixel values. Usually 1 and 0 or the lowest and highest value withn a bit depth. Like 0 and 255 for 8bit images.
To create binary images from gray scale images you define a function that gives you either one of your two values for each pixel value in your source image.
The most common and simple way is to apply a global threshold.
Often you have to know or specify which of both values is background and which is foreground to get meaningful information out of algorithms that take binary input.

A: A binary image is an image encoded only with 0 and 1. It allows a better compression, because it uses only 1 bit per pixel. But as the access to a bit is a little bit longer than the access to a byte (8 bits), and as we now have plenty or RAM, people usually work with 8 bits images, and then with binary pixels values of 0 and 255.
For the Connected Component Labeling (and counting), the fastest algorithm is the "Union Find". On this link you will find Java (fist post) and C implementations (second post).