PL/SQL Trigger not displaying?

Question: So the simple code im trying to test is this:
set serveroutput on;

CREATE OR REPLACE TRIGGER dml_stud
   BEFORE INSERT OR UPDATE OR DELETE ON studenti
BEGIN
  dbms_output.put_line('DML change in table students !');

  CASE
     WHEN INSERTING THEN DBMS_OUTPUT.PUT_LINE('INSERT');
     WHEN DELETING THEN DBMS_OUTPUT.PUT_LINE('DELETE');
     WHEN UPDATING THEN DBMS_OUTPUT.PUT_LINE('UPDATE');
     -- WHEN UPDATING('NAME') THEN ....
  END CASE;
END;
/

delete from students where id=10000;

This is the output that I'm getting:
Trigger DML_STUD compiled

0 rows deleted.

Shouldn't the 'DELETE' text besomewhere before or after the "0 rows deleted" text ?
I'm using the latest version of Oracle SQL Developer, if that makes any difference.
Answer: I think you are checking for output in wrong place.
Go to View-> Dbms Output
Answer: There's no problem with your code, except for a typo for table name which should be students instead of studenti. You may use this :
CREATE OR REPLACE TRIGGER dml_stud
  BEFORE INSERT OR UPDATE OR DELETE ON students
BEGIN
  DBMS_OUTPUT.PUT_LINE('DML change in table students !');

  CASE
    WHEN INSERTING THEN
      DBMS_OUTPUT.PUT_LINE('INSERT');
    WHEN DELETING THEN
      DBMS_OUTPUT.PUT_LINE('DELETE');
    WHEN UPDATING THEN
      DBMS_OUTPUT.PUT_LINE('UPDATE');
  END CASE;
END;

Answer: If you switch from the GUI you currently use to good, old SQL*Plus, you'll notice that everything works as expected:
SQL> create table students as select * from emp;

Table created.

SQL> create or replace trigger dml_stud
  2     before insert or update or delete on students
  3  begin
  4    dbms_output.put_line('DML change in table students !');
  5
  6    case
  7       when inserting then dbms_output.put_line('INSERT');
  8       when deleting  then dbms_output.put_line('DELETE');
  9       when updating  then dbms_output.put_line('UPDATE');
 10    end case;
 11  end;
 12  /

Trigger created.

SQL> delete from students where ename = 'KING';
DML change in table students !
DELETE

1 row deleted.

SQL>

PL/SQL Trigger not displaying?


React-Native welcome screen mess with the background image

Question: From some reason I'm trying to set a big background and fit it to the mobile screen, I mean the width will be 100% and the height will be dynamic.
Also I have a bigger logo and I want to fit it into the screen so I gave it width & height but it's looks cut.. What i'm doing wrong? Just want a nice "Pre loader" screen with mean a background and logo in the middle..

import React, { Component } from 'react';
import { AppRegistry, StyleSheet, Text, View, Image } from 'react-native';

export default class Preload extends Component {
  render() {
    return (
        <View style={styles.mainBox}>
            <Image source={require('../app_images/preload/bg.jpg')} style={styles.bgImage} />
            <View><Image source={require('../app_images/preload/logo.png')} style={styles.logoImage} /></View>
        </View>
    );
  }
}

const styles = StyleSheet.create({
    mainBox:{
        flex: 1,
        alignItems:'center',
        justifyContent:'center',
        width: null,
        height: null
    },bgImage: {
        position:'absolute',
        top: 0,
        left: 0,
        alignSelf: 'stretch'
    },logoImage: {
        width: 100,
        height: 150
    }
});

AppRegistry.registerComponent('Preload', () => Preload);

Thanks!
Comment: did you try to change Image's `resizeMode` property? `cover`, `contain`
Answer: For the logo, you should use contain resizeMode.
logoImage: {
        width: 100,
        height: 150,
        resizeMode: 'contain'
}

For background mode, I think you can use cover and keep the view above it transparent


Classifying strings of characters using deep learning

Question: Have there been any efforts made to classify images with multiple characters in them using deep learning? I would be particularly interested in a model that generates new strings rather than attempts to segment them. Thanks!
Answer: This is the blog on number plate recognition I have read recently:

https://matthewearl.github.io/2016/05/06/cnn-anpr/


Using Hotelling's T-statistic to find an elliptic confidence set

Question: The problem: We have samples of sizes ${n_1} = 25,{n_2} = 15,{n_3} = 30$ drawn independently from $N\left( {{\mu _i},{\sigma ^2}} \right),i = 1,2,3$ (normal distributions with same variance). We have ${\overline x _1} = 10.5,{\overline x _2} = 14,{\overline x _1} = 12,s_1^2 = 2.5,s_2^2 = 3,s_3^2 = 2.7$ (unbiased variance estimators).
Find 95% elliptic confidence set for $\left( {{z_1},{z_2}} \right) = \left( {{\mu _1} + {\mu _2} - 2{\mu _3},{\mu _1} - {\mu _2}} \right)$ by using Hotelling's distribution.
My attempt: We have $$\left( {{X_{1i}},{X_{2j}},{X_{3k}}} \right)\sim N\left( {\left( {\begin{array}{*{20}{c}}
  {{\mu _1}} \\
  {{\mu _2}} \\
  {{\mu _3}}
\end{array}} \right),\left[ {\begin{array}{*{20}{c}}
  {{\sigma ^2}}&0&0 \\
  0&{{\sigma ^2}}&0 \\
  0&0&{{\sigma ^2}}
\end{array}} \right]} \right) \Rightarrow \left( {{{\overline X }_1},{{\overline X }_2},{{\overline X }_3}} \right)\sim N\left( {\underbrace {\left( {\begin{array}{*{20}{c}}
  {{\mu _1}} \\
  {{\mu _2}} \\
  {{\mu _3}}
\end{array}} \right)}_\mu ,\underbrace {\left[ {\begin{array}{*{20}{c}}
  {{\sigma ^2}/{n_1}}&0&0 \\
  0&{{\sigma ^2}/{n_2}}&0 \\
  0&0&{{\sigma ^2}/{n_3}}
\end{array}} \right]}_\Sigma } \right)$$
So $$\left( {{Z_1},{Z_2}} \right) = \left( {{{\overline X }_1} + {{\overline X }_2} - 2{{\overline X }_3},{{\overline X }_1} - {{\overline X }_2}} \right) = \underbrace {\left( {\begin{array}{*{20}{c}}
  1&1&{ - 2} \\
  1&{ - 1}&0
\end{array}} \right)}_B\left( {\begin{array}{*{20}{c}}
  {{{\overline X }_1}} \\
  {{{\overline X }_2}} \\
  {{{\overline X }_3}}
\end{array}} \right)\sim N\left( {B\mu ,B\Sigma B'} \right)$$
and
$$\left( {{Z_1},{Z_2}} \right)\sim N\left( {\left( {\begin{array}{*{20}{c}}
  {{\mu _1} + {\mu _2} - 2{\mu _3}} \\
  {{\mu _1} - {\mu _2}}
\end{array}} \right),\left( {\begin{array}{*{20}{c}}
  {{\sigma ^2}\left( {\frac{1}{{{n_1}}} + \frac{1}{{{n_2}}} + \frac{4}{{{n_3}}}} \right)}&{{\sigma ^2}\left( {\frac{1}{{{n_1}}} - \frac{1}{{{n_2}}}} \right)} \\
  {{\sigma ^2}\left( {\frac{1}{{{n_1}}} - \frac{1}{{{n_2}}}} \right)}&{{\sigma ^2}\left( {\frac{1}{{{n_1}}} + \frac{1}{{{n_2}}}} \right)}
\end{array}} \right)} \right)$$
The only estimator for ${{\sigma ^2}}$ that comes to mind is the pooled variance ${\widehat \sigma ^2} = s_p^2 = \frac{{\sum\limits_{i = 1}^3 {\left( {{n_i} - 1} \right)s_i^2} }}{{\sum\limits_{i = 1}^3 {\left( {{n_i} - 1} \right)} }}$, but I don't see how to get from there to Hotelling's distribution. I'm assuming that $S = s_p^2\left( {\begin{array}{*{20}{c}}
  {\frac{1}{{{n_1}}} + \frac{1}{{{n_2}}} + \frac{4}{{{n_3}}}}&{\frac{1}{{{n_1}}} - \frac{1}{{{n_2}}}} \\
  {\frac{1}{{{n_1}}} - \frac{1}{{{n_2}}}}&{\frac{1}{{{n_1}}} + \frac{1}{{{n_2}}}}
\end{array}} \right)$ does not follow a Wishart distribution.
How would I find the required elliptic confidence set for the linear combination of expectations with unknown (and common) variance from those independent normally distributed samples?
EDIT: We also know that $\sum\limits_{i = 1}^3 {\left( {{n_i} - 1} \right)\frac{{S_i^2}}{{{\sigma ^2}}}} \sim {\chi ^2}\left( {\sum\limits_{i = 1}^3 {\left( {{n_i} - 1} \right)} } \right)$, which further makes me suspect that Hotelling's distribution will not play a role in the solution. Still, I don't see which test statistic to employ (I'm guessing ${\left( {\left( {{z_1},{z_2}} \right) - B\mu } \right)^\prime }{S^{ - 1}}\left( {\left( {{z_1},{z_2}} \right) - B\mu } \right)$) and which distribution would it follow.
EDIT2: Also see here
Comment: Your question might be better received at https://stats.stackexchange.com/.
Comment: Thank you for suggesting it
Answer: We can approach this problem from the perspective of the classical linear model:
$$
\begin{align}
X &\sim \mathcal{N}(\mathcal{X}\beta,\sigma^2I_n),\\
X &= (X_{11},\ldots,X_{1n_1},X_{21},\ldots,X_{2n_2},X_{31},\ldots,X_{3n_3})^\mathsf{T},\\
\mathcal{X}&=\begin{pmatrix}
\mathbf{1}_{n_1} & \mathbf{0}_{n_1} & \mathbf{0}_{n_1}\\
\mathbf{0}_{n_2} & \mathbf{1}_{n_2} & \mathbf{0}_{n_2}\\
\mathbf{0}_{n_3} & \mathbf{0}_{n_3} & \mathbf{1}_{n_3}
\end{pmatrix},\\
\beta &= \begin{pmatrix}
\mu_1\\
\mu_2\\
\mu_3
\end{pmatrix},\\
n &= n_1+n_2+n_3.
\end{align}
$$
We then know that
$$
\begin{align}
&(\mathcal{X}^\mathsf{T}\mathcal{X})^{-1}\mathcal{X}^\mathsf{T}X \mathrel{=:} \hat{\beta} \sim \mathcal{N}(\beta,\sigma^2(\mathcal{X}^\mathsf{T}\mathcal{X})^{-1}),\\
&\frac{(B \hat{\beta} - b)^\mathsf{T}(B( \mathcal{X}^\mathsf{T}\mathcal{X})^{-1}B^\mathsf{T})^{-1} (B \hat{\beta} - b)/m}{\widehat{\sigma}^2}\mathrel{=:}F\overset{H_0}{\sim} F_{m,n-3},\\
&\widehat{\sigma}^2=\frac{1}{n-3}(X-\mathcal{X}\hat{\beta})^\mathsf{T}(X-\mathcal{X}\hat{\beta})
\end{align}
$$
under a null hypothesis of the form
$$
H_0:B\beta=b\in \mathbb{R}^{m}, B\in \mathbb{R}^{m\times3},\text{rank}(B)=m.
$$
Therefore, a $((1-\alpha)\cdot100)\%$ confidence region for $B\beta$ is given by
$$
\left\{\tilde{b}\in\mathbb{R}^m:(B \hat{\beta} - \tilde{b})^\mathsf{T}(B( \mathcal{X}^\mathsf{T}\mathcal{X})^{-1}B^\mathsf{T})^{-1} (B \hat{\beta} - \tilde{b})\leq m \widehat{\sigma}^2F_{m,n-3}^{1-\alpha}\right\},
$$
where $F_{m,n-3}^{1-\alpha}$ is the $(1-\alpha)$-quantile of the $F$-distribution with $m$ and $n-3$ degrees of freedom.
In your case, we have $\alpha=0.05,m=2,n=70,B\beta=(\mu_1 + \mu_2 - 2\mu_3, \mu_1 - \mu_2)^\mathsf{T}$, and you've calculated
$$
B( \mathcal{X}^\mathsf{T}\mathcal{X})^{-1}B^\mathsf{T}=
\begin{pmatrix}
  \frac{1}{n_1} + \frac{1}{n_2} + \frac{4}{n_3} & \frac{1}{n_1} - \frac{1}{n_2}\\
  \frac{1}{n_1} - \frac{1}{n_2} & \frac{1}{n_1} + \frac{1}{n_2}
\end{pmatrix},\\
B\hat{\beta}= \begin{pmatrix}
\overline{X}_1 + \overline{X}_2 - 2\overline{X}_3\\
\overline{X}_1 - \overline{X}_2
\end{pmatrix},
$$
and $\widehat{\sigma}^2=s^2_p$ already.
We could equivalently construct the confidence region based on Hotelling's T-squared distribution since
$$
F \sim F_{m,n-3} \iff \frac{m(m+n-4)}{n-3}F \sim T^2_{m,m+n-4}.
$$


Embed RichFilemanager

Question: I want to embed RichFilemaneger (https://github.com/servocoder/RichFilemanager) in a Drupal-8 site. RichFilemanager has its own index.html and a php-conncetor for implementation in other sites.
But it's not clear to me which approach to follow.
Should i keep RichFilemanager in it's own directory in the Drupal-root and connect to it via the php-connector? In that case it seems to me that Drupal can't take care of the security...
or should i copy the content of the index.html to a twig template? But that would make it hard to keep up with updates of RichFilemanager.
Can anyone point me in the right direction?
Are there similar tools implemented which i could use as an example?
Answer: You should include it with composer to your Drupal project. That is step one. You don't need to consider package management - composer will do this for you.
How you wire it up from there is basically up to you and your use case. I assume first you start with a basic controller and go from there in a custom module.

Embed RichFilemanager


Transclude content of nested directive into the outer directive

Question: i want to create a new AngularJS directive (outer-directive) that wraps some content (e.g. html or other directives) and creates dynamically a small navigation on the left side.
I don't get this sample running. The content-section directive is just for grouping content directives in the left side menu and does not need any markup. The content directive should show it's transcluded content in the outer-directive placeholder only if active.
Anyone has an idea or hint on how to solve this problem with AngularjS 1.5?
Example in pseudo code:

<outer-directive>
  <content-section heading="Section 1">
    <content heading="Content 1 in Section 1">

    </content>
    <content heading="Content 2 in Section 1">

    </content>
  </content-section>
  <content-section heading="Section 2">
    <content heading="Content 1 in Section 2">

    </content>
  </content-section>
</outer-directive>

Directive template:

{{contentSection.heading}}

            {{content.heading}}

    <ng-transclude></ng-transclude>

Directives pseudo code:

angular.module('myApp')
    .directive('outerDirective',
    [
        function() {
            return {
                restrict: 'E',
                transclude: true,
                replace: true,
                templateUrl: 'outer-template.html',
                controller: [
                    '$scope',
                    function($scope) {
                        $scope.contentSections = [];

                        this.addContentSection = function(contentSectionScope) {
                            var that = this;
                            $scope.contentSections.push(contentSectionScope);

                            contentSectionScope.$on('$destroy',
                                function(event) {
                                    that.removeContentSection(contentSectionScope);
                                });
                        };

                        this.removeContentSection = function(contentSectionScope) {
                            var index = $scope.contentSections.indexOf(contentSectionScope);
                            if (index !== -1) {
                                $scope.contentSections.splice(index, 1);
                            }
                        };

                      // ...
                    }
                ]
            }
        }
    ])
    .directive('contentSection',
    [
        function() {
            return {
                restrict: 'E',
                require: '^outerDirective',
                transclude: true,
                replace: true,
                //template: '',
                scope: {
                    heading: '@'
                },
                controller: [
                    '$scope',
                    function($scope,) {
                        $scope.contents = [];

                        this.addContent = function (contentScope) {
                            var that = this;
                            $scope.contents.push(contentScope);

                            contentScope.$on('$destroy',
                                function (event) {
                                    that.removeContent(contentScope);
                                });
                        };

                        this.removeContent = function (contentScope) {
                            var index = $scope.contents.indexOf(contentScope);
                            if (index !== -1) {
                                $scope.contents.splice(index, 1);
                            }
                        };
                    }
                ],
                link: function (scope, element, attrs, outerCtrl) {
                    outerCtrl.addContentSection(scope);
                }
            }
        }
    ])
.directive('content',
    [
        function () {
            return {
                restrict: 'E',
                require: '^contentSection',
                transclude: true,
                template: '

',
                scope: {
                    heading: '@'
                },
                controller: [
                    '$scope',
                    function ($scope) {

                    }
                ],
                link: function (scope, element, attrs, contentSectionCtrl) {
                    contentSectionCtrl.addContent(scope);
                }
            }
        }
    ]);;
Answer: Angular UI's "Tabs" directive solves this problem.
In your case you would do something like this:
angular.module('myApp', ['ui.bootstrap']);

Your HTML would be:

<uib-tabset template-url="custom-tabset-template.html">
  <uib-tab heading="Section 1">

    Section 1 Content
  </uib-tab>
  <uib-tab heading="Section 2">

    Section 2 Content
  </uib-tab>
  <uib-tab heading="Section 3">

    Section 3 Content
  </uib-tab>
</uib-tabset>

And the custom-tabset-template.html would be:

and here is a working plunker.
Enjoy.


window.open is not opening a new window when used with parameters

Question: On clicking of the HyperLink , i am calling the below function
window.open("<%=forHyperLink%>",'name','height=600,width=800');

The issue is that , with the above line , only one time Hyper Link click is working
(That is if another hyper link is clicked , no window is being opened up)
But if i remove the parameters for window.open and simply use
window.open("<%=forHyperLink%>");

Then on click of every Hyperlink a new window is being opened.
Please adivce .
Comment: Please show HOW you call this code. If you have `onclick="window.open("` then the quotes are wrong. If you reuse the "name" which is not a good name for a window, it may go behind. try '_blank' instead
Answer: Change the name of each window per link so the window opened on initial click won't be re-used.
I'm guessing that clicking on other links opens the links on the initial/currently opened pop-up and causes confusion that it doesn't open new windows.
// first window to open
window.open("first.html",'name','height=600,width=800');

// opens in the same window where first.html is opened because
// it targets the same window called `name`
window.open("second.html",'name','height=600,width=800');

// this works because by default it will open a new one everytime it is executed
window.open("new.html");

// opens a window with unique name
window.open("<%=forHyperLink%>",'name_' + Math.random(),'height=600,width=800');

Comment: Than you for your suggestions , i want to open the sam epage by clicking on the hyper links , how can i chnage the name of the HTML Page ??
Comment: you could add some random numbers to change the window name and make it unique for each e.g. `window.open("<%=forHyperLink%>",'name_' + Math.random(),'height=600,width=800');
` let me update my answer for that.
Answer: You can use window.open("<%=forHyperLink%>",'name_'+(new Date()).getTime(),'height=600,width=800');
'name_'+(new Date()).getTime() will be changed at each window opened
oNewWindow = window.open( [sURL] [, sName] [, sFeatures] [, bReplace])
Please find the detail of window.open from the following link
http://msdn.microsoft.com/en-us/library/ms536651(v=vs.85).aspx


postfix conditional recipient rewriting

Question: I'm struggling to integrate Postfix with RT. I'm new to all this so I might be doing some dumb mistakes.
AFAIU, Postfix and RT integrate with a mapping between the RT queue and the recipient address in the /etc/alias file.
We have done this for two queues:
support:    "|/opt/rt4/bin/rt-mailgate --queue general --action correspond --url http://localhost"
support-urgent "|/opt/rt4/bin/rt-mailgate --queue urgent --action correspond --url http://localhost"

So whenever an email is sent to firstname.lastname@example.com, it gets in queue general and whenever it is sent to firstname.lastname@example.com, it gets in the other queue.
However, we'd like to simplify the life of our customers by only communicating one single email address to them: email@example.com.
We'd then maintain a list of customers for whom we have a contract that gives them priority.
Basically, we'd need to do some conditional recipient rewriting based on a lookup on the sender address. If firstname.lastname@example.com is in our priority list, the recipient address should be changed to firstname.lastname@example.com for rt to pick it up in the right queue. If email@example.com is not on the list, then no rewriting would be necessary.
Is this simple to do or would I require a second Postfix instance on another port?
Thanks for any help or clues.
Seb.
Answer: RT has a full automation system called Scrips that allows you to add actions on every transaction on an RT ticket. Using this system, you could create a new scrip to "Change Queue Based on Sender". You can then write some action code to look at the requestors email address, consult some configuration that maps the "from" domain to your queues, then update the queue on the incoming ticket.
The RT community wiki has an example scrip that sets a queue automatically. In your case, you should be able to look at the Requestor object on the ticket since the ticket has already been created. The condition would be On Create.
Answer: If you are familiar with Unix tools but not with Perl, you can also do this mail processing in procmail.
You need to add into your /etc/procmail/main.cf:
mailbox_command = procmail -a "$EXTENSION"

Example /etc/procmailrc:
:0
* ^From: .*<+email@example.com>+
* ^Subject:.*optional.*
| /opt/rt4/bin/rt-mailgate --action correspond --queue urgent --url http://localhost

You can use regular expressions to match the list of VIP users, or keep an whitelist in an external file
However, if you are going to deal with a lot of RT configuration, investing time on learning about Scrips may be a better option as Jim suggested.

postfix conditional recipient rewriting


Help in a proof for a lemma

Question: The lemma below has a small proof in the page 5. But I don't understand the details. I would like that someone help me. the details can be found here.
Lemma 1.3
Assume (H1) holds. Let $u \in W^{1,p}$ be a solutin to (E2) in $Q$. Denote by $A = \max(2^{N},2^{p+1}B\}$ with $B$ as in (H1). Then for $0<\delta<1$ fixed, there exist ad $\varepsilon= \varepsilon(\delta)>0$ such that if hjypothesis (H2) holds for such $\varepsilon$, and $Q_k \subset \overline{Q_k} \subset \dfrac{1}{4}Q$ satisfies
\begin{equation}
|Q_k \cap \{x :M(\nabla u|^{p}) < A \lambda| > \delta |Q_k|,
\end{equation}
the predecessor $\overline{Q}_k$ satisfies $\overline{Q}_k \subset \{x:M(|\nabla u|^{p}) > A \lambda\}.$ Remark: $A$ does not depend on $S$

What is the $S$ above? They have not told about $S$
The statement the predecessor of $\overline{Q}_k$ suggests that $Q_k$ is a Caldrón-Zygmund covering of a set $A \subset Q$ such that $|A| < \delta |Q|$.  Maybe of $\{x:M(|\nabla u|^{p} > A \lambda\}$. Is this  true?
What is $\overline{Q}$ in the solution of the corresponding problem (AP) $u_h$. Is it a typo? Was $\overline{Q} = \overline{Q}_k$  such that there exists $x \in \overline{Q}_k$ such that
\begin{equation}
\dfrac{1}{|Q|} \int_{Q} | \nabla u(y)|^{p}dy \le \lambda \quad \mbox{for all cubes} \quad Q \ni x.
\end{equation}
like above in the proof?
Consider the maximal operator
\begin{equation}
M^{*}(|\nabla u|^{p}) = \sup_{x \in Q, Q \subset 2 \overline{Q}_k} \dfrac{1}{|Q|} \int_{Q} | \nabla u(y)|^{p}dy ;
\end{equation}
then for $x \in Q_k, M(|\nabla u(x)|^{p}\le \max\{M^{*}(|\nabla u(x)|^{p}),2^N \lambda\}$. Why is the reason for this inequality?

In the page 5 we have

Since $A=\max\{2^N,2^{p+1}B\}$ a direct computation suggests that
\begin{equation}
|\{x \in Q_k : M^{*}| \nabla u|^{p})\}|>\dfrac{A \lambda}{2^{p+1}}.
\end{equation}
To explain this fact, I see the following. We have that $\|\nabla u\|^{p}_{L^{\infty}(\overline{Q}_k})\le \dfrac{\lambda B}{2}$. Then if $Q \subset \overline{Q}_k$ we have
$\dfrac{1}{|Q|}\int_{Q} | \nabla u_h(y)|^{p}\dfrac{\lambda B}{2}$, and since $\dfrac{\lambda A}{2^{p+1}} \ge B \lambda$ this suggests that $M^{*}(| \nabla u|^{p}(x) \le \dfrac{A \lambda}{2^{p+1}}$. But if $Q \subset 2 \overline{Q}_k$ but $Q \not\subset \overline{Q}_k$ I don't what should I do. Where can I use that fact that $A\ge 2^N$?
Finally at the end we have
\begin{equation}
| \{x \in Q_k : M^{*}(| \nabla u|^{p}) \ge A \lambda\}| < \delta |Q_k|
\end{equation}
and we reach a contradiction. Can we prove
\begin{equation}
| \{x \in Q_k : M(| \nabla u|^{p}) \ge A \lambda\}| \le | \{x \in Q_k : M^{*}(| \nabla u|^{p}) \ge A \lambda\}|
\end{equation}
to obtain the contradiction?

Sorry if my English is bad.
Answer: I answer questions 1-4 below. It's possible that after reading this you will be able to sort out the page 6 part. If not, leave a comment and I'll be happy to continue.

I think $S$ should be $Q$. The probably worked with "square $S$" in an earlier version of the paper, and then changed to "cube $Q$".
Please don't introduce extra confusion by using $A$ in two ways in the same sentence. :) The assumption $Q_k\subset \overline{Q}_k\subset \frac{1}{4} Q$ says that: we have some cube $\overline{Q}_k$ contained in $\frac{1}{4} Q$, and $Q_k$ is one of its dyadic children. The lemma is about the values of the maximal function in two cubes: a parent and a child. The subscript $k$ is really unnecessary, they use it just to implicitly tell the reader that these are dyadic cubes. (I disapprove of this notation.)
Yes, they sometimes drop the (unnecessary) subscript $k$. Read $\overline{Q}$ as $\overline{Q}_k$. Note that $\tilde Q=4\overline{Q}_k$ is contained in $Q$ by assumption of the lemma.
Recall that the proof is by contradiction; it begins by assuming that the maximal function is $\le\lambda$ somewhere in $\overline{Q}_k$. Divide the cubes containing $x$ into three groups:

"large" cubes: those that contains $\overline{Q}_k$. On them the
the average of $|\nabla u|^p$ is  $\le\lambda$ by the above assumption.
"small" cubes: those that are contained in $2\overline{Q}_k$. On them the average is at most $M^*(|\nabla u|^p)$.
other cubes. If $x\in Q_k$ is contained in some cube $Q'$ which is not "small", then $2Q'$ is "large": draw a picture of this. Since the average over $2Q'$ is  $\le\lambda$, it follows that  the average over $Q'$ is  $\le 2^N\lambda$. (The authors write $Q$ in the definition of $M^*$, forgetting that $Q$ already has a meaning: it was introduced in the statement of lemma. I'm writing $Q'$ instead.)

(Page 6 questions)

We want to prove that $M^*(|\nabla u_h|^p)\le \frac{A \lambda}{2^{p+1}}$ on $Q_k$. Since $M^*$ takes averages only over the cubes contained in $2\overline{Q}_k$, it suffices to show that $\|\nabla u_h\|^p\le \frac{A \lambda}{2^{p+1}}$ on $2\overline{Q}_k$. Applying (1.1) with $2\overline{Q}_k$ in place of $Q$, we get an upper bound in terms of the average over $4\overline{Q}_k$. Recall that $4\overline{Q}_k$ is also denoted by $\tilde Q$, and the average over it was bounded by $\lambda$ on the previous page. This yields $\|\nabla u_h\|^p\le \frac{B \lambda}{2}\le \frac{A \lambda}{2^{p+1}}$ on $2\overline{Q}_k$, as required. We do not need $A\ge 2^N$ here; it will be used to answer your next question.
From the last line on page 5 we get the following: if $\mu$  is a number such that $\mu>2^N\lambda$, then $\{x \in Q_k : M(| \nabla u|^{p}) \ge \mu \} \subset \{x \in Q_k : M^{*}(| \nabla u|^{p}) \ge \mu\}$. (In fact, the sets are the same but we don't need this.) Now we want to apply this with $\mu = A\lambda$. Apparently, the authors missed the fact that they need strict inequality $A\lambda>2^N\lambda$ for the logic to work. So, you should  fix this by replacing the definition of $A$ with, for example, $A=\max(A^N+1, 2^{p+1}B)$.
Comment: I still can not get the last part. Finally at the end we have $\cdots$.
Comment: When I did I draw for anwer 4. I saw a possible counterexemplo. Using the notation $Q_r(x_0)=\{x \in \mathbb{R}^{2}:|x-x_0|_{\infty}<\dfrac{r}{2}\}$ take $Q=Q_8((0,0)),Q_k=Q_1(1/2,1/2),\overline{Q}_k=Q_2(1,1)$ and $Q´=Q_1(-1/4,-1/4)$. Then $2\overline{Q}_k=Q_4(1,1)$ and $2Q´=Q_2(-1/4,-1/4)$.Then $Q´$ isn't a small cube, for example, $(1/8,-5/8) \in Q`\backslash 2\overline{Q}_k$ and $2Q´$ isn't a large cube, for example, $\{(0,0),(1,1),(1/2,1/2)\} \in \overline{Q}_k \backslash 2Q´$.Am  I wrong?
Comment: By the way I left a bounty of 200 in http://math.stackexchange.com/questions/179156/understanding-a-theorem-concerning-sobolev-spaces about a theorem $A$ of this article.

Help in a proof for a lemma


Equivalent Gradients in Kernelized SVM

Question: Let $\varphi: \mathcal{X} \to \mathcal{H}$ a mapping with corresponding kernel $K:\mathcal{X}\times\mathcal{X}\to \mathbb{R}$ (that is, $K\left(x,x'\right) = \left<\varphi\left(x\right), \varphi\left(x'\right)\right>$), and consider the soft-SVM problem over the dataset $\left\lbrace x_i, y_i\right\rbrace_{i=1}^m$
$$
\min_{w\in \mathcal{H}} \left(\frac{\lambda}{2} \left\Vert w \right\Vert^2 + \frac{1}{m} \sum_{i=1}^{m} \max\left\lbrace 0, 1-y_i \left<w, \varphi\left(x_i\right)\right> \right\rbrace \right)
$$
The representer theorem states that the solution admits the following form
$$
w^* =\sum _{j=1}^{m} \alpha_j^{*}\varphi\left(x_i\right)
$$
Let G be the Gramm matrix $G_{ij} = \left<\varphi\left(x_i\right), \varphi\left(x_j\right)\right> $. Then, we can equivalently write the problem as
$$
\min_{\alpha \in \mathbb{R}^m } \left(\alpha^T G \alpha + \frac{1}{m} \sum_{i=1}^{m} \max\left\lbrace 0, 1- y_i\sum_{j=1}^m\alpha_j G_{ji} \right\rbrace \right)
$$
And we are guaranteed to have the same solution.
The problem is convex (both in $\alpha$ and $w$), so we can solve it using stochastic gradient descent. However, optimizing on $w$ and optimizing on $\alpha$ seem to result in two very different rules for $\alpha$. Let $x_i,y_i$ be a single random sample.

The gradient of the loss function of first equation (on a single, random, sample) w.r.t to $w$ is $- y_i \varphi\left(x_i\right) 1_\left\lbrace y_i\left<w,\varphi\left(x_i\right)\right><1\right\rbrace$. This means that each iteration we update only one coordinate of $\alpha$. (This is the version that appears in the books)
The gradient of the loss function is the second equation w.r.t alpha is, instead, $-y_i G e_i 1_\left\lbrace y_i\left<w,\varphi\left(x_i\right)\right><1\right\rbrace$ (where $e_i$ is the standard basis element). This means, that every step we update all the coordinates of $\alpha$.

The two gradients are related, but by multiplication by $G^{-1}$. Thus seems to me that it can't be that they are equivalent.
Is the second method valid, or is it a mistake to use these updates?

Answer: The second method is valid. It will converge because like you said, the problem is  convex in terms of $\alpha$. However the two methods will not follow the same trajectory.
The two methods are related via preconditioning. Section 4 of the Pegasos paper has some commentary on this. I give an explicit description of this preconditioning below.
Since $G$ is positive semi-definite, let $\sqrt{G}$ be its principal square root.
Let $\beta = \sqrt{G}\alpha$ and define
$$
\begin{align}
\mathcal{L}_\alpha(\alpha)
&= \frac{\lambda}{2} \alpha^T G \alpha
+ \frac{1}{m} \sum_{i=1}^{m} \max\left\lbrace
    0, 1 - y_i \alpha^T G e_i
\right\rbrace \\
= \mathcal{L}_\beta(\beta)
&= \frac{\lambda}{2} \beta^T \beta
+ \frac{1}{m} \sum_{i=1}^{m} \max\left\lbrace
    0, 1 - y_i \beta^T \sqrt{G} e_i
\right\rbrace.
\end{align}
$$
This means
$$
\begin{align}
\nabla \mathcal{L}_\beta(\beta)
&= \lambda \beta
+ \frac{1}{m} \sum_{i=1}^{m}
    - y_i \sqrt{G} e_i
    \cdot 1_\left\lbrace y_i\left<w,\varphi\left(x_i\right)\right><1\right\rbrace
\\
&=
\sqrt{G} \left( \lambda \alpha
+ \frac{1}{m} \sum_{i=1}^{m}
    - y_i e_i
    \cdot 1_\left\lbrace y_i\left<w,\varphi\left(x_i\right)\right><1\right\rbrace
\right).
\end{align}
$$
Now moving a displacement $\sqrt{G} d$ in $\beta$-space is equivalent to moving a displacement $d$ in $\alpha$-space. Thus moving in $\beta$-space a displacement of $\eta \cdot \nabla \mathcal{L}_\beta(\beta)$ is equivalent to moving in $\alpha$-space a displacement of
$$
\eta \cdot \left(
\lambda \alpha
+ \frac{1}{m} \sum_{i=1}^{m}
    - y_i e_i
    \cdot 1_\left\lbrace y_i\left<w,\varphi\left(x_i\right)\right><1\right\rbrace
\right).
$$
This last update is equivalent to the update of $\alpha$ when optimizing on $w$.

Equivalent Gradients in Kernelized SVM


If statement for multiples of an variable

Question: I know how to construct if statements that can take multiple conditions.
if ((condition1) || (condition2) || (conditionN))
    statements;

And I want to simply the expression I have at the moment.
if ((gameScore == 480) || (gameScore == 960) || (gameScore == 1440))

Basically I want to have a if statement or something similar the will execute code when gameScore is equal to any multiple of 480.
Comment: you want the `%` operator - [See here](http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx). `if(gameScore % 480 == 0)`
Answer: You can use the modulus (%) operator which is similar to division (/) but returns the remainder of the operation instead of the quotient. The remainder will be 0 after dividing by 480 if the number is a multiple of 480.
if ((gameScore % 480) == 0)

Answer: Well if you only need to check multiples of 480, use a modulus-based check.
if (gameScore % 480 == 0) {}

To answer your first question, a switch statement is another option for combining if-statements for certain circumstances.  So in this example, you could do something like
switch (number)
{
    // A switch section can have more than one case label.
    case 480:
    case 960:
    case 1440:
        //do stuff for these three cases
    default:
        //else
        break;
}

See http://msdn.microsoft.com/en-us/library/06tc147t.aspx for more on switch statements in C#.


Proving this sequent using only natural deduction

Question: $ p \rightarrow q,s \rightarrow t \quad \vdash \quad (p \land s) \rightarrow (q \land t) $
We are not allowed to use truth tables, De-morgan's laws, or any other method except natural deduction. Laws allowed: Implication, And, Or, MT, PBC, Copy Rule, Negation, Double Negation, Contradictions.
Both introduction and elimination wherever applicable.
Here is a sample style we are supposed to use while writing the proof :
2:   $ p \lor \neg p $                      $\quad L.E.M. $
3:   $ p $                                  $ \quad assumption $
4:   $ q $                                  $\quad \rightarrow e \quad 1,3 $
5:   $ \neg p \lor q $                      $\quad \lor i_2 \quad 4 $
6:   $ \neg p $                              $\quad assumption $
Comment: Assume $p \land s$ and use $\land$-elim, followed by $\to$-elim twice, followed by $\land$-intro and conclude with $\to$-intro.
Answer: If you can use the deduction theorem you can assume $p\land s$ and from that follows $p$ and subsequently $q$. Also follows $s$ and subsequently $t$. And since you've proven both $q$ and $t$, $q\land t$ follows. Then you discharge the assumption resulting in the statement to be proved.
$$\begin{align}
\tag{1}p\rightarrow q, s\rightarrow t, p\land s
&\vdash p\land s&\text{ assumption}
\\\tag{2}p\rightarrow q, s\rightarrow t, p\land s
&\vdash p&\text{ CE(1)}
\\\tag{3}p\rightarrow q, s\rightarrow t, p\land s
&\vdash p\rightarrow q&\text{ assumption}
\\\tag{4}p\rightarrow q, s\rightarrow t, p\land s
&\vdash q&\text{ MP(2,3)}
\\\tag{5}p\rightarrow q, s\rightarrow t, p\land s
&\vdash s&\text{ CE(1)}
\\\tag{6}p\rightarrow q, s\rightarrow t, p\land s
&\vdash s\rightarrow t&\text{ assumption}
\\\tag{7}
p\rightarrow q, s\rightarrow t, p\land s
&\vdash t&\text{ MP(5,6)}
\\\tag{8}
p\rightarrow q, s\rightarrow t, p\land s
&\vdash s\land t&\text{ CI(5,7)}
\\\tag{9}p\rightarrow q, s\rightarrow t
&\vdash (p\land s) \rightarrow (s\land t)&\text{ DT(8)}
\\
\end{align}$$
Where CE is conjuction elimination, MP is modus ponens, CI is conjuction introduction and DT is the deduction theorem. Assumption is of course using one of the assumptions to the left of the $\vdash$.
Comment: I wonder why this answer was downvoted...
Answer: 01. (p→q)∧(s→t)  premise
  02. p∧s          assumption
  03. (p→q)∧(s→t)  restate 01
  04. p            ∧elim 02
  05. p→q          ∧elim 03
  06. q            MP 04 05
  07. s            ∧elim 02
  08. s→t          ∧elim 03
  09. t            MP 07 08
  10. q∧t          ∧intro 06 09
11. (p∧s)→(q∧t)  →intro 02 10

Therefore, ((p→q)∧(s→t))⊢((p∧s)→(q∧t)).


How to loop through an array an put create an array of objects using react and javascript?

Question: i want to loop through an array elements and create an array of objects with its values.
below is the array example which comes from querying from an api.
const array = [
    "first",
    "second",
]

now i want to create an array of objects like below
const arr_obj = [
    {
         label: "first",
         value: "first",
     }
     {
         label: "second",
         value: "second",
      }
  ]

i have tried like below
const arr_obj = React.useMemo(() => {
    const output = arr.forEach(item => { //error
        return {
            label: item,
             value: item,
         }
     }, [arr]});

but this gives error arr could be possibly undefined or null and also i think this is not the way to create an array of objects with label, value pairs from the array elements.
could someone help me with this. thanks.
Answer: Use Array.map:

const array = [
  "first",
  "second",
]

const res = array.map(e => ({
  label: e,
  value: e
}))
console.log(res)
Comment: thanks how can i check if array is null or undefined before mapping? i get error object could be possibly null | undefined.
Comment: @stackuser You can wrap the `map` in an if statement: `if (array != null){ /* map */ }`
Answer: Why not try this one?

const array = [
  "first",
  "second",
]
let arr_obj = []
for (let i in array) {
  arr_obj.push({
    label: array[i],
    value: array[i],
  })
}
console.log(arr_obj)


Is there a significant GC performance gain by re using float arrays in Java?

Question: I am developing an Android game in Java, and the garbage collector regularly kicks in and causes a lag spike.
After looking at my object allocation, a big portion of what gets recycled is a float[]. I create a new float[] every frame for multiple objects.
Does it make sense to re use a float[] or is the performance impact of it insignificant (especially compared to objects).
public float[] rectangleToVerts(float x, float y, float width, float height)
    float[] verts = new float[8];

    verts[0] = x - width / 2;
    verts[1] = y + height / 2;
    verts[2] = x + width / 2;
    verts[3] = y + height / 2;
    verts[4] = x + width / 2;
    verts[5] = y - height / 2;
    verts[6] = x - width / 2;
    verts[7] = y - height / 2;

    return verts;
}

public void tick(){
    shape.setVertices(rectangleToVerts(x, y, 5, 5);
}

VERSUS
public float[] rectangleToVerts(float x, float y, float width, float
    height, float[] verts)

    verts[0] = x - width / 2;
    verts[1] = y + height / 2;
    verts[2] = x + width / 2;
    verts[3] = y + height / 2;
    verts[4] = x + width / 2;
    verts[5] = y - height / 2;
    verts[6] = x - width / 2;
    verts[7] = y - height / 2;

    return verts;
}

private float[8] verts;

public void tick(){
    shape.setVertices(rectangleToVerts(x, y, 5, 5, verts);
}

Comment: It's not so much "at once", but how many have been created/destroyed between GC runs or spikes.   If you're only creating 15-20, then I'd be surprised if that has a big impact on the GC;  on the other hand, 15-20 per frame @ 25 fps with spikes 5 seconds, that's a couple of thousand.  Still, try the different alternatives and see.  For 15-20 at once, though, certainly not worth worrying about the weak references I mentioned.
Comment: An array is an object, so offhand there wouldn't be any difference compared to using  some different object.  For your alternatives, though, I wouldn't have a problem with a shape having `verts` stored rather than assigning/recalculating/garbage each time.  If you have LOTS AND LOTS of shapes, there could be an increase in memory overhead, so worth being aware of weak memory references in that case if it proves appropriate.
Comment: @racraman There are on average around 15 shape objects (never exceeding 20) in the level at once. Do you think this optimization would help to prevent GC from causing momentary lag spikes or will there be no difference in performance?
Comment: Reusing objects, including arrays, is likely to reduce GC churn, especially on Android.
Comment: @LouisWasserman totally agree - both for `verts`, and also (or especially) the shapes themselves if possible.
Comment: As others have implied, the only way is to try it and see. And if you're shooting for a mass market, it's best to try on as many different devices as you can. Outguessing GC is tough. Hanging onto buffers can reduce pressure on ephemeral collection, but creating long-lived objects can also create other problems.
Answer: It's difficult to say exactly how much more efficient your code will be in the second example, but it is certainly more efficient. Each array is itself an object, and the fewer new references you create, the less often the Garbage Collector will run. Since you said that a large portion of what gets recycled is float[] types, this seems like a likely candidate. If you're working in Android Studio 3.0 or higher, you can use the Memory Profiler to see how memory is allocated by your program and determine if this is in fact the source of your slowdown.
As a side note, you're also calculating the values of each vertex twice. (For instance, verts[0] and verts[6] are both being set to x - width / 2.) A quick and easy optimization might look like this:
public float[] rectangleToVerts(float x, float y, float width, float height, float[] verts)
{
    verts[0] = x - width / 2;
    verts[6] = verts[0];

    verts[1] = y + height / 2;
    verts[3] = verts[1];

    verts[2] = x + width / 2;
    verts[4] = verts[2];

    verts[5] = y - height / 2;
    verts[7] = verts[5];

    return verts;
}

Hope this helps!


React JSX parser error

Question: I'm trying to learn React but this is making me get stuck:

I keep getting this error:
Uncaught Error: Parse Error: Line 5: Unexpected token <
    at http://localhost:420/

^

I've tried wrapping it in another div or a span but nothing worked what am I doing wrong?
Answer: You should return the JSX, but you are returning an object, which cannot contain JSX.
var Avatar = React.createClass({
  render: function(){
    return ( // note a parenthesis, not a brace

    ); // same
  }
});

Answer: In React all tags must be closed, according to this,
in JSX, <MyComponent /> alone is valid while <MyComponent> isn't.
In your case you miss close tag for img. Try to use:

React JSX parser error


Mysql Update query is taking a lot of time

Question: I am having one mysql table which is having one column(numviews) on this table which is updated frequently(same update query run in a loop) . It is taking a lot of time more than 2secs and i am not able to find out how to improve this because it is affecting/slowing my application too which is having dependency on this table.   Here is mysql table.
Note : Its an innodb table and there is no other slow queries. This table is under mariadb galera cluster. I am having 300 max connections also. In any point of time the global connection doesn't go beyond 170/180.
CREATE TABLE `data_table` (
  `site` VARCHAR(100) NOT NULL DEFAULT '',
  `active` TINYINT(3) UNSIGNED NOT NULL DEFAULT '0',
  `numclicks` INT(10) UNSIGNED NOT NULL DEFAULT '0',
  `numviews` INT(20) UNSIGNED NOT NULL DEFAULT '0',
  `country` VARCHAR(200) DEFAULT NULL,
  `viewcount` INT(10) UNSIGNED NOT NULL DEFAULT '0',
  `name` VARCHAR(150) NOT NULL DEFAULT '',
  `comments` TEXT NOT NULL,
  `boost` FLOAT DEFAULT '0',
  `daily_limit` INT(11) DEFAULT '0',
  PRIMARY KEY (`site`)
) ENGINE=INNODB DEFAULT CHARSET=latin1

and here is the mysql update query which run on a loop(Its around 50 times the below query runs on this table).
UPDATE data_table  set numviews = numviews + 1 where site='xyz';

Query OK, 1 row affected (2.57 sec)
Rows matched: 1  Changed: 1  Warnings: 0

SELECT site,active,numclicks,numviews,country,viewcount FROM data_table WHERE site='xyz'\G
*************************** 1. ROW ***************************
                    site: xyz
                  active: 1
               numclicks: 130406
                numviews: 48962
                 country: |xx yy |
               viewcount: 134022

EDIT: I can see some deadlock also.
------- TRX HAS BEEN WAITING 2 SEC FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 3020 page no 10 n bits 120 index `PRIMARY` of table `data_table`trx table locks 1 total table locks 47  trx id 71211631903 lock_mode X locks rec but not gap waiting lock hold time 2 wait time before grant 0
------------------
---TRANSACTION 71211631885, ACTIVE 2 sec starting index read
mysql tables in use 1, locked 1
LOCK WAIT 2 lock struct(s), heap size 360, 1 row lock(s)
MySQL thread id 1083597, OS thread handle 0x7f782a335700, query id 184464304 machine1 XX.XX.XX.XX user updating
UPDATE data_table set numviews = numviews + 1 where site='xyz'
Trx #rec lock waits 12 #table lock waits 0
Trx total rec lock wait time 12 SEC
Trx total table lock wait time 0 SEC
------- TRX HAS BEEN WAITING 2 SEC FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 3020 page no 10 n bits 120 index `PRIMARY` of table `data_table` trx table locks 1 total table locks 47  trx id 71211631885 lock_mode X locks rec but not gap waiting lock hold time 2 wait time before grant 0
------------------
---TRANSACTION 71211631883, ACTIVE 2 sec
mysql tables in use 1, locked 1
2 lock struct(s), heap size 360, 1 row lock(s), undo log entries 1
MySQL thread id 1082885, OS thread handle 0x7f713e848700, query id 184464302 xxx XX.XX.XX.XX user query end
UPDATE data_table set numviews = numviews + 1 where site='xyz'
Trx #rec lock waits 225 #table lock waits 0
Trx total rec lock wait time 366 SEC
Trx total table lock wait time 0 SEC

Can anyone help me how to improve this update query ?
Comment: no.of rows you have in table?
Comment: @Rahul Less than 1000
Comment: @Strawberry Yes it is a loop i mean i am just incrementing the numviews by 1 , it is a process. I am having 300 max connections also. In any point of time the global connection doesn't go beyond 170/180.
Comment: I suspect they are the same @Strawberry
Comment: sorry my bad, updated the question
Comment: @Strawberry where clause is required because the site is unique.
Comment: @Strawberry Here is the scenario : Loop checks some condition if it satisfies then it updates the numviews. The loop is basically on  2M records.
Comment: how many nodes are in the cluster ? Does you update verytime over the same node ?
Comment: @BerndBuffen 2 nodes + 1(Garbd) . Its a cluster and it updates on the other nodes. So we update only one node always.
Comment: So each time it's called, the 'loop'  actually only runs once.
Comment: So I'm still confused about that '50 times' bit
Comment: i see 2 bad things. first use a int or bigint  with autoincrement as primary key and put a unique key on site. the primary key is use for nearly anything in galera also for update the other nodes. also you can use a new field siteMd5 varchar(32) where you store the md5 of site. then its much quicker to find the correct row. and the second split it in 2 tables. one with the new id and numviews and in the other id and the nearly static fields. so you reduce the read request in the system.
Comment: @Strawberry Because this loop create the 50 threads around and runs this update query.
Comment: Sorry, I don't understand that statement
Answer: You don't actually need that, what you are trying to do is update the column OR increment the num_views column. What I mean is, say you are looping for 1000 times and performing the UPDATE; Instead perform a single update with the value 1000 saying set numviews = 1000 + 1 (OR) in other words if you have the total number of views value before hand then can perform a single UPDATE operation. If so then below code would do the same
UPDATE data_table set numviews = total_views + 1 where site='xyz';

Comment: Your query is a different update, than the update the questioner proposed. Meaning it does not do the same. The original update results in different numbers per row. Your update will set the whole column `numviews` to one value, which is likely not the desired result.
Comment: Dont you think its same as UPDATE data_table  set numviews = numviews + 1 where site='xyz';
Comment: run the loop then update the number one time, good call Rahul!
Comment: @Sthita, NO, cause say you are looping for 1000 times and performing the UPDATE. Instead perform a single update with the value 1000 saying `set numviews = 1000 + 1`
Comment: this makes no sense. More coffee required.
Comment: @GhostGambler, I don't think so, see OP's post ... update results in single row. which means the same row getting updated multiple times resulting in final value. that's why I made that guess.
Comment: But what has a column `numviews`, whose semantic is (from the name) to count the number of viewers of a specific row, to do with the total number of rows of the table?
Comment: @GhostGambler, Ahh ... total no.of rows is just an example. See my comment to OP. What I mean is perform a single update with the actual value than having multiple updates.
Comment: But how to combine `update test set value=5 where test="banana"` and `update test set value=3 where test="apple"` into one query?
Comment: @GhostGambler, you don't. you replace the where condition variable and set value in application code and call the same update statement.
Answer: Rapidly changing counters (clicks, views) should be in a separate table.  That way, queries (reads and writes) that don't need those columns won't interfere with them.
Remove that UPDATE from any transaction -- do it as its own transaction.
How far apart are your Galera nodes?  If they are cross-country at, say, 100ms, then you can do only 10 such updates per second.  If that is your case read my high speed ingestion blog; then we can discuss how to use MyISAM on Galera to allow a much higher throughput of your UPDATEs.
Answer: Make sure the site column has an index, or if you can determine site by ID instead of name would improve it much more. Create and set ID as primary key. Also, if there is only one site, you might improve it a bit with LIMIT 1. Else I'm not sure. Maybe you can improve it with PDO to prepare the same request with different values if you run it in a loop.
Comment: Yes as you can see site is a primary key. So it is by default has an index.
Comment: you are right, I saw it now in the end of the create table, thanks :)


Atualizar conteúdo de arquivo JSON

Question: Estou tentando manipular um arquivo JSON usando Python porém sempre que eu rodo o programa ele apaga o arquivo JSON fazendo com que eu perca a ultima alteração, tem como fazer ele só adicionar ao arquivo?
Arquivo:
{
  "PERGUNTA 1": "RESPOSTA",
  "PERGUNTA 2": "RESPOSTA",
  "PERGUNTA 3": "RESPOSTA",
  "PERGUNTA 4": "RESPOSTA",
}

Função que salva no arquivo:
guardar = {pergunta.upper():resposta}
with open('dados.json', 'w', encoding='utf-8') as gravar_file:
     json.dump(guardar, gravar_file,ensure_ascii=False,sort_keys=True, indent=4, separators=(',',':'))

Sempre que rodo esse trecho de código eu perco as outras perguntas que eu tinha no meu arquivo.
Mudei o argumento de w para a:
try:
    guardar = {pergunta.upper():resposta}
    with open('dados.json', 'a', encoding='utf-8') as gravar_file:
        json.dumps(guardar, gravar_file, ensure_ascii=False, indent=4, separators=(',',':'))
        print('Pergunta guardada!')
except:
      print('Não consegui aprender...')
      aprender()

Porém, agora após executar a função acima o meu JSON fica da seguinte forma:
{
  "PERGUNTA 1": "RESPOSTA",
  "PERGUNTA 2": "RESPOSTA",
  "PERGUNTA 3": "RESPOSTA",
  "PERGUNTA 4": "RESPOSTA",
}{
  "PERGUNTA 5": "RESPOSTA"
}

E ele ainda dá erro pois o Python não colocou a , para separar os objetos.
Answer: O problema é que somente escrever os dados no final do arquivo não é o suficiente para fazer o que você precisa.
Ao escrever no final do arquivo com a opção 'a', você está escrevendo apenas o conteúdo da nova pergunta, ignorando a semântica do conteúdo do arquivo (na verdade a nova pergunta deveria ser adicionada ao objeto JSON já existente, em vez de ser escrito logo depois).
Ou seja, o arquivo já tem um objeto JSON contendo várias perguntas. Em vez de adicionar uma pergunta neste objeto, o que você fez foi escrever outro objeto logo depois. Por isso o arquivo ficou desse jeito:
{
  "PERGUNTA 1": "RESPOSTA",
  "PERGUNTA 2": "RESPOSTA",
  "PERGUNTA 3": "RESPOSTA",
  "PERGUNTA 4": "RESPOSTA",
}{
  "PERGUNTA 5": "RESPOSTA"
}

E se você tentar lê-lo novamente, dará erro, porque isso não é um JSON válido (já que agora são 2 objetos diferentes, em vez de apenas um: o primeiro objeto tem as perguntas de 1 a 4, e o segundo objeto tem a pergunta 5).
Mas pelo que entendi, o que você queria era um único objeto contendo todas as 5 perguntas:
{
  "PERGUNTA 1": "RESPOSTA",
  "PERGUNTA 2": "RESPOSTA",
  "PERGUNTA 3": "RESPOSTA",
  "PERGUNTA 4": "RESPOSTA",
  "PERGUNTA 5": "RESPOSTA"
}

Uma opção para resolver seria abrir o arquivo e carregar todo o seu conteúdo com json.load, obtendo assim o respectivo objeto. Depois você atualiza este objeto com a nova pergunta e sobrescreve o arquivo.
Mas em vez de escrever diretamente no mesmo arquivo, creio que seja melhor primeiro escrever o conteúdo em um arquivo temporário, e só no final, se tudo der certo, você renomeia o arquivo temporário. Assim, se ocorrer um erro durante a escrita, o arquivo original é preservado (pois o erro só afetará o arquivo temporário). Ficaria assim:
import json
import shutil
import tempfile

with open('dados.json', 'r', encoding='utf-8') as arq, \
     tempfile.NamedTemporaryFile('w', delete=False) as out:
    # ler todo o arquivo e obter o objeto JSON
    dados = json.load(arq)
    # atualizar os dados com a nova pergunta
    dados["PERGUNTA 5"] = "RESPOSTA"
    # escreve o objeto atualizado no arquivo temporário
    json.dump(dados, out, ensure_ascii=False, indent=4, separators=(',',':'))

# se tudo deu certo, renomeia o arquivo temporário
shutil.move(out.name, 'dados.json')

Para criar o arquivo temporário, usei o módulo tempfile. Com isso, após o código rodar, o conteúdo do arquivo será:
{
    "PERGUNTA 1":"RESPOSTA",
    "PERGUNTA 2":"RESPOSTA",
    "PERGUNTA 3":"RESPOSTA",
    "PERGUNTA 4":"RESPOSTA",
    "PERGUNTA 5":"RESPOSTA"
}

Este método funciona também para outros casos, como por exemplo apagar uma das perguntas, ou atualizar o texto delas (pois aí o arquivo pode ficar menor que o original, então somente escrever no final não seria a ação mais adequada).

Um detalhe, o seu arquivo original não pode ter a vírgula depois da pergunta 4, senão ela será um JSON inválido:
{
  "PERGUNTA 1": "RESPOSTA",
  "PERGUNTA 2": "RESPOSTA",
  "PERGUNTA 3": "RESPOSTA",
  "PERGUNTA 4": "RESPOSTA", <-- esta vírgula está errada, e deve ser removida
}

Por fim, se a ideia é que o arquivo sirva para persistir os dados, mas não necessariamente precise ser lido por uma pessoa, considere usar os módulos pickle ou shelve - este último em especial parece ser mais adequado à sua necessidade. Uma ideia seria primeiro converter o seu JSON original para o formato do shelve:
import json
import shelve

# primeira vez, carregar o arquivo JSON e criar o arquivo no formato do shelve
with open('dados.json', 'r', encoding='utf-8') as arq, \
     shelve.open('dados_shelve.json') as novos_dados:
    dados = json.load(arq)
    novos_dados.update(dados)

Depois, basta atualizar o novo arquivo usando o próprio shelve:
# da segunda vez em diante, basta ler o arquivo com shelve
with shelve.open('dados_shelve.json') as dados:
    # a linha abaixo já atualiza o arquivo
    dados["PERGUNTA 5"] = "RESPOSTA"

A diferença é que o shelve cria arquivos binários, e não um texto bonitinho como o arquivo JSON. Mas se a ideia é somente persistir os dados e ir atualizando-os, sem que uma pessoa precise lê-lo, esta é uma boa alternativa.
Comment: @HenriqueFH `out.name` é o nome do arquivo temporário. Sem isso o `move` não saberia qual arquivo renomear
Comment: olá estava olhando seu código pois estava com a mesma dificuldade do autor da pergunta, e me ficou uma dúvida. shutil.move(out.name, 'dados.json'). Nesta parte do código, porque usastes "out.name"?
Answer: Posso te ajudar com a logica:

Carregue o conteúdo do arquivo

Transforme o conteúdo em JSON

Altere o objeto json em memoria

Salve o objeto JSON ('sobreescrevendo o arquivo')

dessa forma você não precisara se preocupar em fazer seu código escrever a sintaxe correta pois ao transformar o JSON em string a sintaxy vai estar correta
Carregue o conteúdo do arquivo
    arquivo = open("dados.json", "r")

transforme o conteúdo do arquivo em um objeto JSON
import json
conteudo = json.load(arquivo)

Manipule o Objeto Json
... o que vc quiser fazer....
Salve o objeto JSON ('sobreescrevendo o arquivo')
arquivo.close() # Fecha o arquivo que estava aberto como somente leitura
arquivo = open("dados.json", "w") # Sobrescreve o arquivo
json.dump(conteudo, arquivo) # Salva o Json no arquivo
arquivo.close() # Fecha o arquivo

Comment: Se está lendo de um arquivo, vc pode fazer diretamente `json.load(arquivo)`. Não tem porque ler todas as linhas, juntá-las em uma string, e só depois fazer o `load` (é uma volta desnecessária). Outro detalhe é que se for converter uma string, deve usar `json.loads(string)` (load**s** em vez de load, senão dará erro). Para escrever, mesma coisa: não precisa criar uma string e depois escrevê-la no arquivo, pode fazer só `json.dump(objetoJson, arquivo)`.
Comment: Então edite a resposta e faça isso :-)
Comment: Mas o problema principal é que vc abriu o arquivo com a opção `'w'`, que abre o arquivo para escrita, além de apagar todo o conteúdo do mesmo (ou seja, não vai conseguir ler). Aliás, esse é um dos problemas citados na pergunta: "*Sempre que rodo esse trecho de código eu perco as outras perguntas que eu tinha no meu arquivo*"
Comment: Seu primeiro comentário concordo plenamente, porem no segundo comentário é possivel abrir como somente ´r´ pega o json fecha e na hroa de salvar abrir com ´w´
Comment: Editado. ( era uma afirmação/pergunta)
Answer: Sim é possível, basta mudar o modo de abertura para escrita do arquivo.
Utilizando o seu código:
with open('dados.json', 'a', encoding='utf-8') as gravar_file:
#resto do código

Repare que nesta solução a diferença é o modo de leitura dos arquivos. Estamos abrindo o arquivo para escrever, utilizando a estratégia de escrever no final do arquivo.
O modo de leitura é o segundo parâmetro da função open, quando utilizamos o modo w, estamos abrindo o arquivo para escrita, porém limpando o conteúdo anterior.
Quando abrimos utilizando o modo a estamos abrindo o arquivo para escrita, porém escrevendo sempre ao final do arquivo.
+---+--------------------------------------+
| w | limpa o conteúdo e escreve valores   |
+---+--------------------------------------+
| a | abre o arquivo para escrita no final |
+---+--------------------------------------+

Para aprender mais sobre quais os métodos de abertura de arquivo, recomendo visualizar a documentação.
Comment: Bom dia! Isso foi uma solução porem tive outro problema kkk
a minha variável que contem o dict que vai ser guardado no json está da seguinte forma
guardar = {pergunta.upper():resposta} e quando eu salvo ela no json, ele cria outra chave fazendo assim dar erro no json.
Eu queria adicionar ela na chave ja existente pois o meu json é simples ele so tem uma chave e eu so queria adicionar outros valores nele. qual seria a solução pra isso?
Comment: Cara, eu não sei se entendi o problema, mas em python se vc tem uma variável dentro de chaves isso é um dict. Se vc quer salvar um json, deveria fazer o import da classe `json` e para salvar json vc usaria a função json.dumps(objetoagravar). Passando um objeto a gravar.
Comment: vou editar a perguntar e colocar a função
Comment: Editei a pergunta

Atualizar conteúdo de arquivo JSON


How do I copy style from one button to another?

Question: My goal:
I am trying to replace the button on a screen using Javascript.
I need the buttons to look the same, so I am trying to copy the style from the old button to the new button.
The problem:
The button styling is not being reflected on the newButton (either because I am not getting it properly from oldButton, or because I am not applying it to newButton properly)
Here is my code:
oldButtonStyle = window.getComputedStyle(oldButton).cssText;

newButton = document.createElement("INPUT");
newButton.style.cssText = oldButtonStyle;

oldButton.parentNode.replaceChild(
  newButton,
  oldButton
);

Any ideas? Thanks!
Comment: _"Any ideas?"_ - Maybe, but first... Why? Why do replace a "button" with a text input? What do you try to accomplish with that?
Comment: just add the same class to the new button...
Answer: First get the element style with style.cssText
Then use setAttribute() to set the style.
Here in the snippet below you can set the style on the button with id btn2 when you click on it.

const style = document.getElementById("btn1").style.cssText;

function setStyle() {
  document.getElementById("btn2").setAttribute('style', style);
}
<button style="color: red;background-color: yellow" id="btn1">button 1</button>
<button id="btn2" onclick="setStyle()">button 2</button>
Answer: Not sure what you are trying to achieve exactly, but based on "I need the buttons to look the same, so I am trying to copy the style from the old button to the new button.",
Here is a simple solution

// Write Javascript code!
const appDiv = document.getElementById("app");

const oldButton = document.getElementById('button');
const oldButtonStyle = window.getComputedStyle(
  document.getElementById('button1'),
  "" // optional for pulling styles from pseudo selectors :before, :after
).cssText;

const newButton = document.createElement("INPUT");
newButton.style.cssText = oldButtonStyle;

oldButton.parentNode.replaceChild(newButton, oldButton);
h1,
h2 {
  font-family: Lato;
}

#button {
  height: 64px;
  border: red;
  width: 100px;
  background: red;
}

#button1 {
  height: 64px;
  border: red;
  width: 100px;
  background: yellow;
}

  <button id="button">Old</button>
  <button id="button1">Another Button</button>

Comment: What does the `, "")` do? Why did you add `#button1` and what does this change?
Comment: `, "")` is an optional argument, used for pulling styles from pseudo selectors `:before`, `:after`. `#button1` is just to show that the styles indeed do get copied. (Note: Background color property in CSS)
Answer: Just use that old button color specification by using DOM in app.js file

        <button onclick="myFunction()" id="btn" type="button" style="background-color:
         green;cursor: pointer;">Click Me!</button>

// create app.js file and clone the color by using id and create a new button tag and link whatever you provide specification to them and in lastjust append it

const colorElement = document.getElementById('btn').style.backgroundColor;

function myFunction() {
    var x = document.createElement("BUTTON");
    var t = document.createTextNode("Click me");
    x.style.backgroundColor = colorElement
    x.appendChild(t);
    document.body.appendChild(x);
}


Nagios plugin to monitor FreeSWITCH

Question: I am trying to configure Nagios to monitor FreeSWITCH as mentioned at https://github.com/kjhosein/nagios-freeswitch-plugin .
I have downloaded the script from git and followed listed steps.
On remote (NRPE) server I have added below line in nrpe.cfg file
command[check_freeswitch_health]=/usr/lib64/nagios/plugins/check_freeswitch_health.pl $ARG1$

On Nagios server,added in commands.cfg file
define command {
    command_name    check_freeswitch_health
    command_line    $USER1$/check_nrpe -H $HOSTADDRESS$ -c check_freeswitch_health $ARG1$
  }

and in services.cfg file
define service {
    host_name       freeswitch01
    service_description     FreeSWITCH - Calls Count
    check_command   check_freeswitch_health!-a '-q show-calls-count'!!!!!!!
  }

But on Nagios web interface I am getting
CHECK_NRPE: Received 0 bytes from daemon. Check the remote server logs for error messages.

On remote server, logs(/var/log/syslog) showing below error
Request contained command arguments!
Client request was invalid, bailing out...

What I am missing here ? Can anyone please assist me with correct configurations ?
Thanks,
Rutu
Answer:
Make sure you can run that perl script locally, as the nagios/nrpe user.
Make sure that perl script doesn't depend on ENV (e.g., $PATH). Verify by running through env -i /usr/lib64/nagios/plugins/check_freeswitch_health.pl ...
Use your generic check_nrpe command definition, instead of writing a check_{whatever} for every different NRPE command you want to run.
To pass args with -a, you must enable command arguments in nrpe.cfg by setting dont_blame_nrpe=1

For example, if your check_nrpe command looks like this:
define command {
    command_name    check_nrpe
    command_line    $USER1$/check_nrpe -H $HOSTADDRESS$ -c $ARG1$ -a $ARG2$
}

Then your service definition would be:
define service {
    host_name       freeswitch01
    service_description     FreeSWITCH - Calls Count
    check_command   check_nrpe!check_freeswitch_health!-q show-calls-count
}

(Why do you have !!!!!!! at the end of your command?)
Or, if the only option you ever pass to that perl script is -q, you can put it in the command definition in the NRPE config:
command[check_freeswitch_health]=/usr/lib64/nagios/plugins/check_freeswitch_health.pl -q $ARG1$

Then your check_command would be just check_nrpe!check_freeswitch_health!show-calls-count
Comment: Hi Keith,
Thank you for detailed explanation to my query.

1.Make sure you can run that perl script locally, as the nagios/nrpe user.
>>How can I check that perl script is run as nagios/nrpe user?

2.Make sure that perl script doesn't depend on ENV (e.g., $PATH).
>>When I run env -i /usr/lib/nagios/plugins/check_freeswitch_health.pl -q show-calls-count on nrpe server,it gives:
REESWITCH_HEALTH OK - Result of check is: 0 total.  | show-calls-count=0;;
Comment: 3.Use your generic check_nrpe command definition, instead of writing a check_{whatever} for every different NRPE command you want to run.
>> I have tried as you have suggested but still getting same issue.

I have script check_freeswitch_health.pl at /usr/lib/nagios/plugins/
Is there any specific steps to install nagios-freeswitch-plugin ?
Comment: Added a step 4 for you ;-) Not sure how I missed this the first time, sorry.

Nagios plugin to monitor FreeSWITCH


Placing $n$ points so that their distances lie in $[1,a]$

Question: What is the maximum number of points we can place in the plane so that the distance between any two such points is in the interval $[1,a]$?
I had initially conjectured that the maximum could be found by trying with regular $n$-gons of side $1$ until the largest diagonal exceeded $a$.
However I have recently found this to be false. Placing $7$ points with distances in $[1,2]$ is possible by taking a hexagon of side length $1$ and placing one point on each vertex and one in the center of the hexagon. On the other hand a heptagon of side length $1$ has its largest diagonals of length approximately $2.246$.
What is the maximum number of points we can place given $a$? Is there a neat construction which achieves this all the time?

Also note that if we can solve this problem then we can solve the problem of placing $n$ Points on the plane so as to maximize the number of pairs of points $(a,b)$ at distance between $1$ and $a$. This is because if we know the maximum possible clique we can build the Turan Graph by placing a lot of points in the same place.
Answer: This belongs to a wide class of packing problems that are quite hard to solve.
Anyway, some heuristics are quite easy. If we take $n$ points inside a unit circle, with respect to a uniform probability distribution, we expect that the most distant points are two units apart and the infimum of the distances is around $\frac{2}{\sqrt{n}}$.
So, assuming that $a$ is big, we expect to be able place around $a^2$ points in such a way that their distances lie in $[1,a]$, but not much more.
Comment: Thanks! Do you have any references?
Comment: @Gamamal: not at hand, but I bet that by googling something like "probabilistic arguments for circle packing" you can find interesting material.


JqGrid MVC post data is not working

Question: I am trying to pass some values from jQGrid to controller of  my MVC application. The grid was displaying properly but no data was showing.
My code is below
Ajax
<code>function LoadGrid(varLocationID) {
                var jqDataUrl = null;
                jqDataUrl = "ManageRoutes/ManageRoutes" //+ x;
                var Location = varLocationID.getAttribute('value');
                var  grid = $("#grid").grid({
                   url: "/ManageRoutes/GetRoutes/",
                   postData: { "szLocationID": function () { return Location; } },
                    cache: false,
                    datatype: "json",
                    mtype: "POST",

                    // Specify the column names
                    colNames: ["RouteID", "CompanyID", "LocationID", "SalesManCode", "SalesManName"],
                    // Configure the columns
                    colModel: [
                        { name: "RouteID", index: "RouteID", width: 70, align: "left" },
                        { name: "CompanyID", index: "CompanyID", width: 200, align: "left" },
                        { name: "LocationID", index: "LocationID", width: 200, align: "left" },
                        { name: "SalesManCode", index: "SalesManCode", width: 150, align: "left" },
                        { name: "SalesManName", index: "SalesManName", width: 170, align: "left" }

                    ],
                    pager: { enable: true, limit: 5, sizes: [2, 5, 10, 20] }
                });
</code>
and code in controller
<code>[HttpPost]
    public JsonResult GetRoutes(string szLocationID)
    {
        List<RouteNames> qry = new List<RouteNames>();
        using (TESTEntities1 dc = new TESTEntities1())
        {
            qry = (from s in dc.t_hhc_dnl_Route_ID.AsEnumerable()
                   select new RouteNames
                   {
                       CompanyID = s.CompanyID,
                       LocationID = s.LocationID ,
                       RouteID = s.RouteID,
                       SalesManCode=s.SalesManCode ,
                       SalesManName = s.SalesManName

                   }).Where(m => m.LocationID.Contains(szLocationID)).Take(100).ToList();
        }

        var jsonData = new
        {
            data = from emp in qry select emp
        };

        return Json(jsonData, JsonRequestBehavior.AllowGet);

    }
</code>
Any help would be appreciated.
Answer: Changed as below code and got worked ..
<code>"ajax": {
           "url": "/ManageRoutes/GetRoutes",
           "type": "POST",
           "data": function (d) {
            d.szLocationID = Location;
         }
</code>

JqGrid MVC post data is not working


SaltStack: How do I configure the minion to use a different publisher port?

Question: Now I am having a salt-master behind an NAT, the master's 4505 and 4506 ports have been mapped to the 44505 and 44506 ports on the router.
There's a master_port option but I think that only changes the port 4506 to 44506. How do I configure the minion to use 44505 instead of 4505 when connecting to this master?
Answer: Important update 10/14/2015:
It was my fault - my network was not good so some working methods may have been thought not working... I will keep my old answer, but it didn't seem correct - it failed after I rebooted both my minion and master.
What seems to work now is:
I put publish_port: 44505 in the file /etc/salt/master on the master, so salt opens port 44505 on the master now. Then I changed the port mapping configuration on the router, to map the router's port 44505 to master's port 44505 (instead of 4505).
I don't know what the mechanism is, but it seems that the master can tell the minion which publish port to use, therefore the public port number on the router should be consistent with the local port number on the master.
Now my /etc/salt/minion configuration is just:
master: xxx.xxx.xx.xxx
master_port: 44506

The original answer which is WRONG:
I think I made it work by simply using the same publish_port option in the minion configuration file. I don't think it is mentioned on the documentation. It is NOT in the default /etc/salt/minion configuration file either.
Now my /etc/salt/minion configuration is like:
master: xxx.xxx.xx.xxx
publish_port: 44505
master_port: 44506

Simply adding publish_port: 44505 to the /etc/salt/master configuration file on master does not make its minions connect to that publish port automatically. You will need to explicitly specify it in your minion configuration.


ASPNET WMI class not available

Question: I need to extract the ASPNET\Requests Queued performance counter from some IIS servers via WMI.
The WMI class for this sort of thing appears to be contained in Win32_PerfFormattedData_ASPNET_ASPNET. I've queried all available classes in root\cimv2 on my Win 2003/IIS6 servers, and it's not listed.
It is, however, available on an unrelated Win2008/IIS7 box (which is interesting but doesn't really help me much). I can view these counters in PerfMon without any issues.
What gives? Why is this WMI class not available on my Windows 2003 servers?
Answer: Check the following registry keys and ensure "Disable Performance Counters" is either not present, or set to 0:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ASP.NET\Performance\Disable Performance Counters
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ASP.NET_2.0.50727\Performance\Disable Performance Counters
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ASP.NET_64\Performance\Disable Performance Counters
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ASP.NET_64_2.0.50727\Performance\Disable Performance Counters
If you have a 32-bit OS, only the first two keys will be present. If you have a 64-bit OS, all 4 keys will be present.
Comment: Great suggestion but I have tried both zero'ing those keys and deleting them altogether with no result. Also I
Comment: Does the performance counter show up in perfmon?
Comment: Yes, all ASP.NET and ASP.NETv2 counters are available in perfmon.
Comment: I would recommend the wmi diagnosis utility for win2003: http://www.microsoft.com/downloads/details.aspx?FamilyID=d7ba3cd6-18d1-4d05-b11e-4c64192ae97d
Answer: I found an excellent msdn blog article which helped me: http://blogs.msdn.com/b/tom/archive/2008/04/11/asp-net-performance-counters-missing.aspx

ASPNET WMI class not available


Why am I getting gibberish output, along with valid output, when reading a String^ ?

Question: I'm trying to write a few integers to a file (as a string.) Every time I try to run this bit of code I get the integers into the text file like planned, but before the integers, I get some gibberish. I did some experimenting, and found out that if I put nothing into System::String ^ b, it would give the same gibberish output into the file or a message box, but I couldn't figure out why it would do this if I was concatenating those integers to it (as strings). What could be going wrong here?
using namespace msclr::interop;
using namespace System;
using namespace System::IO;
using namespace System::Text;

...

System::IO::StreamWriter ^ x;
char buffer[21], buffer2[3];
int a;
for(a = 0; a < 10; a++){
    itoa(weight[a], buffer, 10);
    strcat(buffer, buffer2);
}
System::String ^ b = marshal_as<String^>(buffer);
x->WriteLine(b);

Answer: What format is the file in? You may be reading a UTF-8 file with a byte-order mark that is silently applied by a text editing program.
http://en.wikipedia.org/wiki/Byte_order_mark
Comment: Sorry, meant that I was reading the String from memory, and putting it into a file, or a message box.
Answer: Typo in question or bug in code: pass buffer2 to itoa instead of buffer.
Also, initialize buffer to "";


Any numpy/torch style to set value given an index ndarray and a flag ndarray?

Question: I'm working on PyTorch and currently I met a problem for which I've no idea how to solve it in a torch/numpy style. For example, suppose I have three PyTorch tensors
import torch
import numpy as np

indices = torch.from_numpy(np.array([[2, 1, 3, 0], [1, 0, 3, 2]]))
flags = torch.from_numpy(np.array([[False, False, False, True], [False, False, True, True]]))
tensor = torch.from_numpy(np.array([[2.8, 0.5, 1.2, 0.9], [3.1, 2.8, 1.3, 2.5]]))

Here flags is a boolean flag tensor to show which elements in indices should be extracted. Given the extracted indices, I want to set the corresponding elements in tensor to an indicated const (say 1e-30). Based on the example shown above, I want
>>> sub_indices = indices.op1(flags)
>>> sub_indices
tensor([[0], [3, 2]])
>>> tensor.op2(sub_indices, 1e-30)
>>> tensor
tensor([[1e-30, 0.5, 1.2, 0.9], [3.1, 2.8, 1e-30, 1e-30]])

Could anyone help to give a solution? I'm using list comprehension but I think this way is a little bit ugly. I tried indices[flags] but it only returns a 1d-array [0, 3, 2] so applying this would change all rows on the same columns 0, 2, 3
Some additional remarks:

The number of "True" values for each row in flags cannot be determined
Each row of indices is assured to be a permutation of sequence 0 ... N - 1

Below is a numpy version of the example code, for the convenience of copy-pasting. I doubt whether this could be done in a pure numpy way
import numpy as np

indices = np.array([[2, 1, 3, 0], [1, 0, 3, 2]])
flags = np.array([[False, False, False, True], [False, False, True, True]])
tensor = np.array([[2.8, 0.5, 1.2, 0.9], [3.1, 2.8, 1.3, 2.5]])

Answer: You may sort flags according to the indices to create a mask, then use the mask as a mux. Here is an example code:
indices = np.array([[2, 1, 3, 0], [1, 0, 3, 2]])
flags = np.array([[False, False, False, True], [False, False, True, True]])
tensor = np.array([[2.8, 0.5, 1.2, 0.9], [3.1, 2.8, 1.3, 2.5]])

indices_sorted = indices.argsort(axis=1)
mask = np.take_along_axis(flags, indices_sorted, axis=1)
result = tensor * (1 - mask) + 1e-30 * mask

I'm not quite familiar with pytorch, but I guess it is not a good idea to gather a ragged tensor. Though, even in the worst case, you can convert to/from numpy arrays.
Answer: The pytorch version of @soloice's solution. In pytorch, torch.gather is used instead of torch.take.
indices = torch.tensor([[2, 1, 3, 0], [1, 0, 3, 2]])
flags = torch.tensor([[False, False, False, True], [False, False, True, True]])
tensor = torch.tensor([[2.8, 0.5, 1.2, 0.9], [3.1, 2.8, 1.3, 2.5]])

indices_sorted = indices.argsort(axis=1)
mask = torch.gather(flags, 1, indices_sorted).float()
result = tensor * (1 - mask) + 1e-30 * mask


Selected Row context menu appreared

Question: I want to implement the context menu for the selected row. One time, one row can be selected and if user right click on it, context menu should be popped up. if user clicks other rows which are not selected, the context menu should not be popped up.
My code is given; Please give me an idea?
jQuery:
jQuery(document).bind("contextmenu", function(e) {
     jQuery('#myMenu').hide();
     return false;
     });

     jQuery('.even').bind("contextmenu", function(e) {
         jQuery('#myMenu').css({
             top: e.pageY+'px',
                 left: e.pageX+'px'
                 }).show();
         return false;

     });

     jQuery('.odd').bind("contextmenu", function(e) {
         jQuery('#myMenu').css({
             top: e.pageY+'px',
                 left: e.pageX+'px'
                 }).show();
         return false;

         });

Context Menu:

<%include:SignforReview%>

<%include:SignforApproval%>

<%include:RetractReviewSignature%>

<%include:RetractReviewSignature%>

HTML -

<tr id="line_<%=getData(ttEnl.line-num)%>"
                        <%if:rowStyle(2)%>
                            class="even"
                            onmouseover="highlightLink(this,'even');"
                            onmouseout="restore(this,'even');"
                            onclick="setSelected(this,'even');subjectSessionCheck('<%=getData(ttEnl.line-num)%>','<%=getData(ttEnl.rEnlRowid)%>','<%=getData(ttEnl.obj_enl)%>'); "
                        <%else:rowStyle%>
                            class="odd"
                            onmouseover="highlightLink(this,'odd');"
                            onmouseout="restore(this,'odd');"
                            onclick="setSelected(this,'odd');subjectSessionCheck('<%=getData(ttEnl.line-num)%>','<%=getData(ttEnl.rEnlRowid)%>','<%=getData(ttEnl.obj_enl)%>'); "
                        <%end:rowStyle%>
.....
.....
.....

Answer: Your code is pretty much there.  You are just missing a few things:

on your css class, you have to set the position: 'absolute'
when you render the selected row, you have add a class called rowselected to it. You can either do this by setting class="even rowselected" or by doing it with
$(selector).addClass('rowselected')
you have to change your selector class to only select $('.even.rowselected, .odd.rowselected')

http://jsfiddle.net/rkw79/58dRL/

Selected Row context menu appreared


Is there a convenient way to map a file uri to os.path?

Question: A subsystem which I have no control over insists on providing filesystem paths in the form of a uri. Is there a python module/function which can convert this path into the appropriate form expected by the filesystem in a platform independent manner?
Comment: Are you going to be doing more than just reading from it?
Comment: No, I want to pass that uri or equivalent form into the python modules for path manipulation
Answer: The solution from @Jakob Bowyer doesn't convert URL encoded characters to regular UTF-8 characters. For that you need to use urllib.parse.unquote.
>>> from urllib.parse import unquote, urlparse
>>> unquote(urlparse('file:///home/user/some%20file.txt').path)
'/home/user/some file.txt'

Comment: @Boris because the path returned for windows file URIs starts with a slash `unquote(urlparse('file:///C:/Program Files/Steam/').path)` -> `'/C:/Program Files/Steam/'`
Comment: Consider using [`urllib.parse.unquote_plus`](https://docs.python.org/library/urllib.parse.html#urllib.parse.unquote_plus) which is "like `unquote()`, but also replace plus signs with spaces".
Comment: @IwanAucamp can you explain why?
Comment: Perfect for my linux environment
Answer: Use urllib.parse.urlparse to get the path from the URI:
import os
from urllib.parse import urlparse
p = urlparse('file://C:/test/doc.txt')
final_path = os.path.abspath(os.path.join(p.netloc, p.path))

Comment: The valid file URI for `C:\test\doc.txt` is `file:///C:/test/doc.txt` not `file://C:/test/doc.txt` - see [IETF RFC 8089: The "file" URI Scheme / 2. Syntax](https://tools.ietf.org/html/rfc8089#section-2) and run this in recent python 3 `import pathlib; print(pathlib.PureWindowsPath("C:\\test\\doc.txt").as_uri())` so this answer is not accurate.
Comment: @JakobBowyer - the .path in the second line should be removed otherwise you are just returning a string to variable p instead of the tuple that you need to process in the third line.
Answer: Of all the answers so far, I found none that catch edge cases, doesn't require branching, are both 2/3 compatible, and cross-platform.
In short, this does the job, using only builtins:
try:
    from urllib.parse import urlparse, unquote
    from urllib.request import url2pathname
except ImportError:
    # backwards compatability
    from urlparse import urlparse
    from urllib import unquote, url2pathname

def uri_to_path(uri):
    parsed = urlparse(uri)
    host = "{0}{0}{mnt}{0}".format(os.path.sep, mnt=parsed.netloc)
    return os.path.normpath(
        os.path.join(host, url2pathname(unquote(parsed.path)))
    )

The tricky bit (I found) was when working in Windows with paths specifying a host.  This is a non-issue outside of Windows: network locations in *NIX can only be reached via paths after being mounted to the root of the filesystem.
From Wikipedia:
A file URI takes the form of file://host/path , where host is the fully qualified domain name of the system on which the path is accessible [...]. If host is omitted, it is taken to be "localhost".
With that in mind, I make it a rule to ALWAYS prefix the path with the netloc provided by urlparse, before passing it to os.path.abspath, which is necessary as it removes any resulting redundant slashes (os.path.normpath, which also claims to fix the slashes, can get a little over-zealous in Windows, hence the use of abspath).
The other crucial component in the conversion is using unquote to escape/decode the URL percent-encoding, which your filesystem won't otherwise understand.  Again, this might be a bigger issue on Windows, which allows things like $ and spaces in paths, which will have been encoded in the file URI.
For a demo:
import os
from pathlib import Path   # This demo requires pip install for Python < 3.4
import sys
try:
    from urllib.parse import urlparse, unquote
    from urllib.request import url2pathname
except ImportError:  # backwards compatability:
    from urlparse import urlparse
    from urllib import unquote, url2pathname

DIVIDER = "-" * 30

if sys.platform == "win32":  # WINDOWS
    filepaths = [
        r"C:\Python27\Scripts\pip.exe",
        r"C:\yikes\paths with spaces.txt",
        r"\\localhost\c$\WINDOWS\clock.avi",
        r"\\networkstorage\homes\rdekleer",
    ]
else:  # *NIX
    filepaths = [
        os.path.expanduser("~/.profile"),
        "/usr/share/python3/py3versions.py",
    ]

for path in filepaths:
    uri = Path(path).as_uri()
    parsed = urlparse(uri)
    host = "{0}{0}{mnt}{0}".format(os.path.sep, mnt=parsed.netloc)
    normpath = os.path.normpath(
        os.path.join(host, url2pathname(unquote(parsed.path)))
    )
    absolutized = os.path.abspath(
        os.path.join(host, url2pathname(unquote(parsed.path)))
    )
    result = ("{DIVIDER}"
              "\norig path:       \t{path}"
              "\nconverted to URI:\t{uri}"
              "\nrebuilt normpath:\t{normpath}"
              "\nrebuilt abspath:\t{absolutized}").format(**locals())
    print(result)
    assert path == absolutized

Results (WINDOWS):
------------------------------
orig path:              C:\Python27\Scripts\pip.exe
converted to URI:       file:///C:/Python27/Scripts/pip.exe
rebuilt normpath:       C:\Python27\Scripts\pip.exe
rebuilt abspath:        C:\Python27\Scripts\pip.exe
------------------------------
orig path:              C:\yikes\paths with spaces.txt
converted to URI:       file:///C:/yikes/paths%20with%20spaces.txt
rebuilt normpath:       C:\yikes\paths with spaces.txt
rebuilt abspath:        C:\yikes\paths with spaces.txt
------------------------------
orig path:              \\localhost\c$\WINDOWS\clock.avi
converted to URI:       file://localhost/c%24/WINDOWS/clock.avi
rebuilt normpath:       \localhost\c$\WINDOWS\clock.avi
rebuilt abspath:        \\localhost\c$\WINDOWS\clock.avi
------------------------------
orig path:              \\networkstorage\homes\rdekleer
converted to URI:       file://networkstorage/homes/rdekleer
rebuilt normpath:       \networkstorage\homes\rdekleer
rebuilt abspath:        \\networkstorage\homes\rdekleer

Results (*NIX):
------------------------------
orig path:              /home/rdekleer/.profile
converted to URI:       file:///home/rdekleer/.profile
rebuilt normpath:       /home/rdekleer/.profile
rebuilt abspath:        /home/rdekleer/.profile
------------------------------
orig path:              /usr/share/python3/py3versions.py
converted to URI:       file:///usr/share/python3/py3versions.py
rebuilt normpath:       /usr/share/python3/py3versions.py
rebuilt abspath:        /usr/share/python3/py3versions.py

Comment: according to the [documentation](https://docs.python.org/3/library/urllib.request.html#urllib.request.url2pathname) `url2pathname` uses `unquote` so `url2pathname(parsed.path)` should be sufficient
Comment: Your solution breaks when the encoded pathname includes urlencode-like characters. E.g. the filename `foo%20bar.baz` will be correctly encoded by your solution to `foo%2520bar.baz`, but incorrectly decoded to `foo bar.baz`. This happens because of the unmatched `unquote` inside `url2pathname`, as pointed out by @dshanahan
Answer: To convert a file uri to a path with python (specific to 3, I can make for python 2 if someone really wants it):

Parse the uri with urllib.parse.urlparse

Unquote the path component of the parsed uri with urllib.parse.unquote

then ...

a. If path is a windows path and starts with /: strip the first character of unquoted path component (path component of file:///C:/some/file.txt is /C:/some/file.txt which is not interpreted to be equivalent to C:\some\file.txt by pathlib.PureWindowsPath)
b. Otherwise just use the unquoted path component as is.
Here is a function that does this:
import urllib
import pathlib

def file_uri_to_path(file_uri, path_class=pathlib.PurePath):
    """
    This function returns a pathlib.PurePath object for the supplied file URI.

    :param str file_uri: The file URI ...
    :param class path_class: The type of path in the file_uri. By default it uses
        the system specific path pathlib.PurePath, to force a specific type of path
        pass pathlib.PureWindowsPath or pathlib.PurePosixPath
    :returns: the pathlib.PurePath object
    :rtype: pathlib.PurePath
    """
    windows_path = isinstance(path_class(),pathlib.PureWindowsPath)
    file_uri_parsed = urllib.parse.urlparse(file_uri)
    file_uri_path_unquoted = urllib.parse.unquote(file_uri_parsed.path)
    if windows_path and file_uri_path_unquoted.startswith("/"):
        result = path_class(file_uri_path_unquoted[1:])
    else:
        result = path_class(file_uri_path_unquoted)
    if result.is_absolute() == False:
        raise ValueError("Invalid file uri {} : resulting path {} not absolute".format(
            file_uri, result))
    return result

Usage examples (ran on linux):
>>> file_uri_to_path("file:///etc/hosts")
PurePosixPath('/etc/hosts')

>>> file_uri_to_path("file:///etc/hosts", pathlib.PurePosixPath)
PurePosixPath('/etc/hosts')

>>> file_uri_to_path("file:///C:/Program Files/Steam/", pathlib.PureWindowsPath)
PureWindowsPath('C:/Program Files/Steam')

>>> file_uri_to_path("file:/proc/cpuinfo", pathlib.PurePosixPath)
PurePosixPath('/proc/cpuinfo')

>>> file_uri_to_path("file:c:/system32/etc/hosts", pathlib.PureWindowsPath)
PureWindowsPath('c:/system32/etc/hosts')

This function works for windows and posix file URIs and it will handle file URIs without an authority section. It will however NOT do validation of the URI's authority so this will not be honoured:
IETF RFC 8089: The "file" URI Scheme / 2. Syntax

The "host" is the fully qualified domain name of the system on which
the file is accessible.  This allows a client on another system to
know that it cannot access the file system, or perhaps that it needs
to use some other local mechanism to access the file.

Validation (pytest) for the function:
import os
import pytest

def validate(file_uri, expected_windows_path, expected_posix_path):
    if expected_windows_path is not None:
        expected_windows_path_object = pathlib.PureWindowsPath(expected_windows_path)
    if expected_posix_path is not None:
        expected_posix_path_object = pathlib.PurePosixPath(expected_posix_path)

    if expected_windows_path is not None:
        if os.name == "nt":
            assert file_uri_to_path(file_uri) == expected_windows_path_object
        assert file_uri_to_path(file_uri, pathlib.PureWindowsPath) == expected_windows_path_object

    if expected_posix_path is not None:
        if os.name != "nt":
            assert file_uri_to_path(file_uri) == expected_posix_path_object
        assert file_uri_to_path(file_uri, pathlib.PurePosixPath) == expected_posix_path_object

def test_some_paths():
    validate(pathlib.PureWindowsPath(r"C:\Windows\System32\Drivers\etc\hosts").as_uri(),
        expected_windows_path=r"C:\Windows\System32\Drivers\etc\hosts",
        expected_posix_path=r"/C:/Windows/System32/Drivers/etc/hosts")

    validate(pathlib.PurePosixPath(r"/C:/Windows/System32/Drivers/etc/hosts").as_uri(),
        expected_windows_path=r"C:\Windows\System32\Drivers\etc\hosts",
        expected_posix_path=r"/C:/Windows/System32/Drivers/etc/hosts")

    validate(pathlib.PureWindowsPath(r"C:\some dir\some file").as_uri(),
        expected_windows_path=r"C:\some dir\some file",
        expected_posix_path=r"/C:/some dir/some file")

    validate(pathlib.PurePosixPath(r"/C:/some dir/some file").as_uri(),
        expected_windows_path=r"C:\some dir\some file",
        expected_posix_path=r"/C:/some dir/some file")

def test_invalid_url():
    with pytest.raises(ValueError) as excinfo:
        validate(r"file://C:/test/doc.txt",
            expected_windows_path=r"test\doc.txt",
            expected_posix_path=r"/test/doc.txt")
        assert "is not absolute" in str(excinfo.value)

def test_escaped():
    validate(r"file:///home/user/some%20file.txt",
        expected_windows_path=None,
        expected_posix_path=r"/home/user/some file.txt")
    validate(r"file:///C:/some%20dir/some%20file.txt",
        expected_windows_path="C:\some dir\some file.txt",
        expected_posix_path=r"/C:/some dir/some file.txt")

def test_no_authority():
    validate(r"file:c:/path/to/file",
        expected_windows_path=r"c:\path\to\file",
        expected_posix_path=None)
    validate(r"file:/path/to/file",
        expected_windows_path=None,
        expected_posix_path=r"/path/to/file")

This contribution is licensed (in addition to any other licenses which may apply) under the Zero-Clause BSD License (0BSD) license
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

To the extent possible under law, Iwan Aucamp has waived all copyright and related or neighboring rights to this stackexchange contribution. This work is published from: Norway.
Answer: The solution from @colton7909 is mostly correct and helped me get to this answer, but has some import errors with Python 3. That and I think this is a better way to deal with the 'file://' part of the URL than simply chopping off the first 7 characters. So I feel this is the most idiomatic way to do this using the standard library:
import urllib.parse
url_data = urllib.parse.urlparse('file:///home/user/some%20file.txt')
path = urllib.parse.unquote(url_data.path)

This example should produce the string '/home/user/some file.txt'
Answer: Starting from python 3.13, you can use the pathlib.Path.from_uri() method, a new constructor to create a pathlib.Path object from a 'file' URI (file://).
For example:
>>> p = Path.from_uri('file:////server/share')
WindowsPath('//server/share')
>>> p = Path.from_uri('file://///server/share')
WindowsPath('//server/share')
>>> p = Path.from_uri('file:c:/windows')
WindowsPath('c:/windows')
>>> p = Path.from_uri('file:/c|/windows')
WindowsPath('c:/windows')


CSS Hover not showing

Question: Okay, so I have an image for a background that has 1px of a blur filter in the CSS.
That works.
Then, I added a CSS :hover selector to a new CSS rule that changes the blur filter to 0.
When I hover over it on the browser, however, it doesn't change the blur at all! (I went into Google Chrome Inspect Element and used the handy feature of forcing the :hover selector, and then it worked. So I know it's not the CSS that's buggy.)
How can I get this to work? It's a blur filter on a div in a header. Any ideas?

            Home
            -
            Types of Cake

Cakes

body header {
    width:100%;
    text-align:center;
    box-shadow:0 4px 4px 4px rgba(0,0,0,0.2);
    z-index:4;
    position:relative;
    background-color:linear-gradient(CornFlowerBlue,RoyalBlue);
}
body header div#bgimage {
    background-attachment:fixed;
    background-position:center;
    background-size:cover;
    background-image:url(hydrangea-cakes-2.jpg);
    filter:blur(1px);
    position:absolute;
    width:100%;
    height:100%;
}

The important parts of the HTML are the header and the div id="bgimage"
Comment: Another element might be capturing the hover event.  We can't tell, though, without seeing some of the code.  Can you post an example of the issue or at least provide the markup and styles?
Comment: let me edit the post real quick
Answer: You haven't already added the :hover pseudo-class.
#bgimage:hover {
  /* the styles you want to display on hover */
}

Answer: You did not add the :hover part of the CSS but it works for me if I just add this to the CSS:
#bgimage:hover {
  filter: none;
}

CSS Hover not showing


Meaning of Eigenvalues and Eigenvectors

Question: Let's say we have some transformation matrix:
$$\begin{pmatrix} 2 & 2\\ 2 & 5 \end{pmatrix}$$
The eigen vectors are:
$$\lambda_1 = 6 \quad \lambda_2 = 1$$
With eigenvectors:
$$\begin{pmatrix} 0.5 \\ 1 \end{pmatrix} \quad \begin{pmatrix} -2 \\ 1 \end{pmatrix}$$
And we know that, if we multiply this matrix by a (1,1) vector, we get:
$$\begin{pmatrix} 2 & 2\\ 2 & 5 \end{pmatrix} \begin{pmatrix} 1 \\ 1 \end{pmatrix} = \begin{pmatrix} 4 \\ 7 \end{pmatrix}$$
I have the question of "what do the eigenvalues and eigenvectors tell us about the transformation matrix". I know that the eigenvalue means scale and eigenvector means direction, but how do I get the (4,7) if I JUST know the eigenvalues and eigenvectors?
Answer: The two given eigenvectors span $\Bbb R^2$. So we can write $\left(\begin{smallmatrix}1\\1\end{smallmatrix}\right)$ as a linear combination of the two:
$$
\begin{pmatrix}1\\1\end{pmatrix} = 1.2\begin{pmatrix}0.5\\1\end{pmatrix} - 0.2\begin{pmatrix}-2\\1\end{pmatrix}
$$
Now we can apply your matrix to both sides here. Using linearity on the right-hand side, the result must be
$$
\lambda_1\cdot1.2\begin{pmatrix}0.5\\1\end{pmatrix} - \lambda_2\cdot0.2\begin{pmatrix}-2\\1\end{pmatrix}
$$
Just insert and calculate, and you get the answer.
Comment: Oh! Thank you so much!
Answer: If you only know the eigenvalues and the eigenvectors, then you can write ${1\choose 1}$ as a linear combination of these eigenvectors, and then you can use the fact that the given matrix acts as a linear operator on these vectors, and so you can apply the appropriate scalar to these vectors.
You need to solve $a\begin{pmatrix} 0.5 \\ 1 \end{pmatrix} + b\begin{pmatrix} -2 \\ 1 \end{pmatrix}=\begin{pmatrix} 1 \\ 1 \end{pmatrix}$, which is equivalent to
$$\begin{pmatrix} 0.5 & -2\\ 1 & 1 \end{pmatrix}\begin{pmatrix} a \\ b \end{pmatrix}=\begin{pmatrix} 1 \\ 1 \end{pmatrix}.$$
So you can apply the inverse of this matrix to both sides and figure out what $a$ and $b$ are.
Comment: Thank you so much! This answers it well!

Meaning of Eigenvalues and Eigenvectors