text:
Q: Why JavaScript ignores the HTML  label when trying to concatenate it with the result of the operator OR? Sorry for the question, I wasn't sure how to ask it. Basically I'm practicing JavaScript using logic operators. I have a really simple HTML code:

The file "logic_operators.js" has the next lines of code:
let value1 = true;
let value2 = false;

document.write(value1 && value2 + '
');
document.write(value1 || value2 + '
');
document.write(!value1 + '
');
document.write(!value2 + '
');

Basically, each document.write() sentence writes the result of each logic operant with a new line.
It works for each sentence except for the OR ( || ) one, it doesn't print the new line. I get the next result:
false
truefalse
true

I need to enclose the OR operation using parenthesis for the sentence to work:
document.write((value1 || value2) + '
');
Why is that? I'm new to JavaScript and can't really figure this out.

A: + has higher operator precedence than ||. Specifically, + has 14 and || has 6. So, the + operation is done first, when there aren't parentheses grouping the three operators.
document.write(value1 || value2 + '
');

is
document.write(value1 || (value2 + '
')

resulting in
document.write(true || (false + '
')

document.write(true)

The && also has lower precedence than +. && evaluates to the last operand if the first is truthy. So
document.write(value1 && value2 + '
');

document.write(true && false + '
');

document.write(true && (false + '
'));

document.write(false + '
');

So it happens to produce the newline like you want for these particular values of value1 and value2.
While you can avoid this problem by using parentheses, or by using writeln instead, it would be much, much better to avoid document.write completely.


text:
Q: How to get return / yield value of pytest dependency I am using pytest-dependency to create dependency on tests. I want the dependent test to get return value from another test.
Example:
@pytest.mark.dependency()
def test_owner_create_book(app):
  response = app.post(...)
  return response["data"]["id"]

@pytest.mark.dependency(depends=["test_owner_create_book"])
def test_owner_read_book(app):
  # I want to get the id from previous response here

How can I get the response from dependency?
Packages in use:
pytest = "^6.1.1"
pytest-dependency = "^0.5.1"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Save form with repeater fields with ajax I have a form in html where the user can add as many members as needed.
So I have a div with the members' details :

    Name:
    <input type="text" name="namemember">
//..........

And a button to add a new member:
<button id="b1" class="btn add-more" type="button">Add Member +</button>

This the jquery code to add a new member:

I know that if I had for example a fixed number of members I could read the data like this:
$_POST["namemember"];

But now how I can read the data passed when I have variable number of members? And how I can distinguish each member's details?

A: Use an array instead of singular name like
<input type="text" name="namemember[]">

And you can access it in PHP like:
$namemember = unserialize($_POST["namemember"]);
foreach( $namemember as $value ) {
 print $value;
}

as now $_POST['namemember'] is an array of fields

A: Do you store the information of the members in a BBDD?
If the answer is yes you can do a query to get all members and their details and have it in a variable.


text:
Q: Posting to Facebook wall using HttpMethod.POST unity3D well I am using unity and trying to post on my wall... I imported the Facebook sdk and i used the code in their docs which is
int score = 10000;

var scoreData =
    new Dictionary<string, string>() {{"score", score.ToString()}};

FB.API ("/me/scores", HttpMethod.POST, LogCallback, scoreData);

and i have allowed the publish settings (when i logged in ) still nothing happens ..
so here is my code exactly
    void Awake(){
    FB.Init (SetInit, OnHideUnity);

}

private void SetInit(){
    Debug.Log("IN");

}

private void OnHideUnity(bool isGameShown){

    if (!isGameShown) {
        Time.timeScale=0;

    }

    else {

        Time.timeScale = 1;
    }

}
    void FBlogin()
{if (!FB.IsLoggedIn) {

                    FB.Login ("email,publish_actions", AuthCallback);
            }
    else {  if (FB.IsLoggedIn) {
            //  Screen.orientation = ScreenOrientation.LandscapeRight;

            Dictionary<string,string> score1=new Dictionary<string, string>();
            score1.Add("Score","100");

            FB.API ("/me/scores",Facebook.HttpMethod.POST, AuthCallback, score1);
            Debug.Log("Okay");

        }

            }
}

void AuthCallback(FBResult result){
    if (FB.IsLoggedIn) {
    //  Screen.orientation = ScreenOrientation.LandscapeRight;

        int score = 10000;

        Dictionary<string,string> scoreData =
        new Dictionary<string, string>() {{"score", score.ToString()}};

        FB.API ("me/scores", HttpMethod.POST, LogCallback, scoreData);

        Dictionary<string,string> scoreData1 =
        new Dictionary<string, string>() {{"score", "0"}};

    }

    else {
        Debug.Log("FB LOGIN ERROR");

    }

}

A: well I found what was I doing wrong if you want to post to Facebook
    FB.API ("/me/feed", HttpMethod.POST, LogCallback,   new Dictionary<string, string>() {{"access_token", FB.AccessToken},{"message","Test"}});

and instead of "test" write your post .. this happens automatically without the fb dialog (you need to enable post on my behalf of course..)


text:
Q: Calculate the length of text Is it possible to calculate the length of a text written by TikZ?
I would like to fit a word inside circle. But sometimes the word is to long for the circle. So my idea was to calculate the length of the text and to adjust the font size if the text is too long.

A: May be a round fitbox (from tcolorbox) can help you. You just define box size and tcolorbox fits the text inside it. Only texts larger than provided space are reduced.
\documentclass{article}
\usepackage[most]{tcolorbox}
\usepackage{lmodern}

\newtcboxfit{\myfitbox}{%
    width = 3cm,
    square,
    circular arc,
    halign = center,
    valign = center,
    nobeforeafter
}

\begin{document}
\myfitbox{This is a long text inside a circular tcolorbox}
%
\myfitbox{This is an ever longer text inside a circular tcolorbox}
%
\myfitbox{This is a much more longer, longer and  longer text inside a circular tcolorbox}
%
\myfitbox{This is a much more longer, longer and  longer text inside a circular tcolorbox. This is a much more longer, longer and  longer text inside a circular tcolorbox}
\end{document}


text:
Q: How to have Jetty redirect http to https on the same port? This question is related to How to have Jetty redirect http to https and Jetty 9 - redirect http to https but not answered in either location.
Basically, we run our app at some port, say 8085. We have generally used HTTP to access this app. We've upgraded to requiring HTTPS now. We want a user accessing 8085 with HTTP to be redirected to 8085 with HTTPS. i.e. http://host:8085 -> https://host:8085
I understand that the normal process is to run HTTP and HTTPS on different ports, but we aren't going to be running HTTP at all.
Here is some of our configuration which is not working atm. After trying everything that I can, I can't get the server to respond to http://host:8085 at all.
Is this due to only one connector (HTTP or HTTPS) being able to listen to the port at one time?
Is there any other way to do this?
Thank you.

  <Configure class="org.eclipse.jetty.webapp.WebAppContext">
      <Get name="sessionHandler">
          <Get name="sessionManager">
              <Set name="usingCookies" type="boolean">true</Set>
          </Get>
      </Get>
    <Set name="securityHandler">
        <New class="org.eclipse.jetty.security.ConstraintSecurityHandler">
            <Call name="addConstraintMapping">
                <Arg>
                   <New class="org.eclipse.jetty.security.ConstraintMapping">
                       <Set name="pathSpec">/*</Set>
                       <Set name="constraint">
                          <New class="org.eclipse.jetty.util.security.Constraint">
                             <!-- 2 means CONFIDENTIAL. 1 means INTEGRITY -->
                             <Set name="dataConstraint">2</Set>
                          </New>
                       </Set>
                   </New>
                </Arg>
            </Call>
        </New>
    </Set>
  </Configure>

  <security-constraint>
    <web-resource-collection>
      <web-resource-name>Everything</web-resource-name>
      <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
      <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
  </security-constraint>

  <New id="httpConfig" class="org.eclipse.jetty.server.HttpConfiguration">
      <!-- This says Redirect to https://host:8085 if server returns "NOT SECURE" error -->
      <Set name="secureScheme">https</Set>
      <Set name="securePort"><Property name="jetty.secure.port" default="8085" /></Set>

      <Set name="outputBufferSize"><Property name="jetty.output.buffer.size" default="32768" /></Set>
      <Set name="requestHeaderSize"><Property name="jetty.request.header.size" default="8192" /></Set>
      <Set name="responseHeaderSize"><Property name="jetty.response.header.size" default="8192" /></Set>
      <Set name="sendServerVersion"><Property name="jetty.send.server.version" default="true" /></Set>
      <Set name="sendDateHeader"><Property name="jetty.send.date.header" default="false" /></Set>
      <Set name="headerCacheSize">512</Set>
      <!-- Uncomment to enable handling of X-Forwarded- style headers -->
      <Call name="addCustomizer">
        <Arg><New class="org.eclipse.jetty.server.ForwardedRequestCustomizer"/></Arg>
      </Call>
      <Call name="addCustomizer">
    <Arg><New class="org.eclipse.jetty.server.SecureRequestCustomizer" /></Arg>
      </Call>
    </New>

<Configure id="sslContextFactory" class="org.eclipse.jetty.util.ssl.SslContextFactory">
  <Set name="KeyStorePath"><Property name="jetty.base" default="/opt/app" />/<Property name="jetty.keystore" default="https/JettyKeyStore"/></Set>
  <Set name="KeyStorePassword"><Property name="jetty.keystore.password" default="OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4"/>*******</Set>
  <Set name="KeyManagerPassword"><Property name="jetty.keymanager.password" default="OBF:1u2u1wml1z7s1z7a1wnl1u2g"/></Set>
  <Set name="TrustStorePath"><Property name="jetty.base" default="/opt/app" />/<Property name="jetty.truststore" default="https/JettyKeyStore"/></Set>
  <Set name="TrustStorePassword"><Property name="jetty.truststore.password" default="OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4"/></Set>
  <Set name="EndpointIdentificationAlgorithm"></Set>
  <Set name="ExcludeCipherSuites">
    <Array type="String">
      <Item>SSL_RSA_WITH_DES_CBC_SHA</Item>
      <Item>SSL_DHE_RSA_WITH_DES_CBC_SHA</Item>
      <Item>SSL_DHE_DSS_WITH_DES_CBC_SHA</Item>
      <Item>SSL_RSA_EXPORT_WITH_RC4_40_MD5</Item>
      <Item>SSL_RSA_EXPORT_WITH_DES40_CBC_SHA</Item>
      <Item>SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA</Item>
      <Item>SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA</Item>
    </Array>
  </Set>

  <!-- =========================================================== -->
  <!-- Create a TLS specific HttpConfiguration based on the        -->
  <!-- common HttpConfiguration defined in jetty.xml               -->
  <!-- Add a SecureRequestCustomizer to extract certificate and    -->
  <!-- session information                                         -->
  <!-- =========================================================== -->
  <New id="sslHttpConfig" class="org.eclipse.jetty.server.HttpConfiguration">
    <Arg><Ref refid="httpConfig"/></Arg>
    <Call name="addCustomizer">
      <Arg><New class="org.eclipse.jetty.server.SecureRequestCustomizer"/></Arg>
    </Call>
  </New>

</Configure>

  <Call id="httpsConnector" name="addConnector">
    <Arg>
      <New class="org.eclipse.jetty.server.ServerConnector">
        <Arg name="server"><Ref refid="Server" /></Arg>
          <Arg name="factories">
            <Array type="org.eclipse.jetty.server.ConnectionFactory">
              <Item>
                <New class="org.eclipse.jetty.server.SslConnectionFactory">
                  <Arg name="next">http/1.1</Arg>
                  <Arg name="sslContextFactory"><Ref refid="sslContextFactory"/></Arg>
                </New>
              </Item>
              <Item>
                <New class="org.eclipse.jetty.server.HttpConnectionFactory">
                  <Arg name="config"><Ref refid="sslHttpConfig"/></Arg>
                </New>
              </Item>
            </Array>
          </Arg>
          <Set name="host"><Property name="jetty.host" />localhost</Set>
          <Set name="port"><Property name="https.port" default="8085" /></Set>
          <Set name="idleTimeout"><Property name="https.timeout" default="30000"/></Set>
          <Set name="name">standardConnection</Set>
        </New>
    </Arg>
  </Call>

  <Call name="addConnector">
    <Arg>
      <New class="org.eclipse.jetty.server.ServerConnector">
        <Arg name="server"><Ref refid="Server" /></Arg>
        <Arg name="factories">
          <Array type="org.eclipse.jetty.server.ConnectionFactory">
            <Item>
              <New class="org.eclipse.jetty.server.HttpConnectionFactory">
                <Arg name="config"><Ref refid="httpConfig" /></Arg>
              </New>
            </Item>
          </Array>
        </Arg>
        <Set name="host"><Property name="jetty.host" />localhost</Set>
        <Set name="port"><Property name="jetty.port" default="8085" /></Set>
        <Set name="idleTimeout"><Property name="http.timeout" default="30000"/></Set>
    <Set name="name">standardConnection</Set>
    <Set name="confidentialPort">8085</Set>
      </New>
    </Arg>
  </Call>


text:
Q: Add prefix to value in nested list of dicts I would like to add to this nested list of dictionaries prefix in the name of the members:
    pool:
      - name: "OPENSTACK_POC_POOL_KEYSTONE_SERVICE"
        port: 5000
        members:
          - name: "OPENSTACK_ECPOCMCTL01_OPENS_KEYSTONE_CONTAINER_097AD5B5"
            host: 10.5.1.2
          - name: "OPENSTACK_ECPOCMCTL02_OPENS_KEYSTONE_CONTAINER"
            host: 10.5.3.3
          - name: "OPENSTACK_ECPOCMCTL03_OPENS_KEYSTONE_CONTAINER"
            host: 10.3.1.7
        state: present

      - name: "OPENSTACK_POC_POOL_CINDER_API"
        port: 8776
        members:
          - name: "OPENSTACK_ECPOCMCTL01_OPENS"
            host: 10.5.2.9
          - name: "OPENSTACK_ECPOCMCTL02_OPENS"
            host: 10.3.2.168
          - name: "OPENSTACK_ECPOCMCTL03_OPENS"
            host: 10.3.1.6
        state: present

That will be like that:
pool:
  - name: "OPENSTACK_POC_POOL_KEYSTONE_SERVICE"
    port: 5000
    members:
      - name: "ANSIBLE-OPENSTACK_ECPOCMCTL01_OPENS_KEYSTONE_CONTAINER"
        host: 10.5.1.2
      - name: "ANSIBLE-OPENSTACK_ECPOCMCTL02_OPENS_KEYSTONE_CONTAINER"
        host: 10.5.3.3
      - name: "ANSIBLE-OPENSTACK_ECPOCMCTL03_OPENS_KEYSTONE_CONTAINER"
        host: 10.3.1.7
    state: present

  - name: "OPENSTACK_POC_POOL_CINDER_API"
    port: 8776
    members:
      - name: "ANSIBLE-OPENSTACK_ECPOCMCTL01_OPENS"
        host: 10.5.2.9
      - name: "ANSIBLE-OPENSTACK_ECPOCMCTL02_OPENS"
        host: 10.3.2.168
      - name: "ANSIBLE-OPENSTACK_ECPOCMCTL03_OPENS"
        host: 10.3.1.6
    state: present

I have more ways that I tried to reach it but I will show you my last version.
I tried this one, however since there are two name keys, it ignores one of them:
- set_fact:
   data2: "{{ data.members |combine({'name': 'ANSIBLE-' }) }}"
- name: with_nested
  set_fact:
    data2: [{'name': "{{item.0.name}}", 'members': [{'host': "{{item.1.host}}"}]}]
  with_subelements:
    - "{{ data }}"
    - "members"
  register: test

- debug:
    msg: "{{ item.members.0.name | regex_replace('^.*', 'a\\1') }}"
  loop: "{{ data | ansible.utils.remove_keys(target=['monitor']) }}"

The idea is to combine them and change the name with the prefix to a new dict, but I still couldn't figure it out.
I am using Ansible version 2.13.1, so a map update cannot be used here.

A: Update the names. Declare the variables
  pool_names: "{{ pool|json_query(pool_names_query) }}"
  pool_names_query: "[].{members: members[].{name: ['ANSIBLE', name].join('-',@),
                                             host: host}}"

give
  pool_names:
  - members:
    - host: 10.5.1.2
      name: ANSIBLE-OPENSTACK_ECPOCMCTL01_OPENS_KEYSTONE_CONTAINER_097AD5B5
    - host: 10.5.3.3
      name: ANSIBLE-OPENSTACK_ECPOCMCTL02_OPENS_KEYSTONE_CONTAINER
    - host: 10.3.1.7
      name: ANSIBLE-OPENSTACK_ECPOCMCTL03_OPENS_KEYSTONE_CONTAINER
  - members:
    - host: 10.5.2.9
      name: ANSIBLE-OPENSTACK_ECPOCMCTL01_OPENS
    - host: 10.3.2.168
      name: ANSIBLE-OPENSTACK_ECPOCMCTL02_OPENS
    - host: 10.3.1.6
      name: ANSIBLE-OPENSTACK_ECPOCMCTL03_OPENS

Combine the update
  pool_update: "{{ pool|zip(pool_names)|map('combine')|list }}"

gives the updated pool
  pool_update:
  - members:
    - host: 10.5.1.2
      name: ANSIBLE-OPENSTACK_ECPOCMCTL01_OPENS_KEYSTONE_CONTAINER_097AD5B5
    - host: 10.5.3.3
      name: ANSIBLE-OPENSTACK_ECPOCMCTL02_OPENS_KEYSTONE_CONTAINER
    - host: 10.3.1.7
      name: ANSIBLE-OPENSTACK_ECPOCMCTL03_OPENS_KEYSTONE_CONTAINER
    name: OPENSTACK_POC_POOL_KEYSTONE_SERVICE
    port: 5000
    state: present
  - members:
    - host: 10.5.2.9
      name: ANSIBLE-OPENSTACK_ECPOCMCTL01_OPENS
    - host: 10.3.2.168
      name: ANSIBLE-OPENSTACK_ECPOCMCTL02_OPENS
    - host: 10.3.1.6
      name: ANSIBLE-OPENSTACK_ECPOCMCTL03_OPENS
    name: OPENSTACK_POC_POOL_CINDER_API
    port: 8776
    state: present

Example of a complete playbook for testing
- hosts: localhost

  vars:

    pool:
      - name: "OPENSTACK_POC_POOL_KEYSTONE_SERVICE"
        port: 5000
        members:
          - name: "OPENSTACK_ECPOCMCTL01_OPENS_KEYSTONE_CONTAINER_097AD5B5"
            host: 10.5.1.2
          - name: "OPENSTACK_ECPOCMCTL02_OPENS_KEYSTONE_CONTAINER"
            host: 10.5.3.3
          - name: "OPENSTACK_ECPOCMCTL03_OPENS_KEYSTONE_CONTAINER"
            host: 10.3.1.7
        state: present
      - name: "OPENSTACK_POC_POOL_CINDER_API"
        port: 8776
        members:
          - name: "OPENSTACK_ECPOCMCTL01_OPENS"
            host: 10.5.2.9
          - name: "OPENSTACK_ECPOCMCTL02_OPENS"
            host: 10.3.2.168
          - name: "OPENSTACK_ECPOCMCTL03_OPENS"
            host: 10.3.1.6
        state: present

    pool_names: "{{ pool|json_query(pool_names_query) }}"
    pool_names_query: "[].{members: members[].{name: ['ANSIBLE', name].join('-',@),
                                               host: host}}"
    pool_update: "{{ pool|zip(pool_names)|map('combine')|list }}"

  tasks:

    - debug:
        var: pool_names
    - debug:
        var: pool_update


text:
Q: Convergence in $L^1$ of ratio of random variables with denominator positive but not bounded away from zero? Let $\{X_n\}_{n=1}^{\infty}, \{Y_n\}_{n=1}^{\infty}$ be such that $X_n$ converges to a constant $a$ in L1 (and hence in probability); $Y_n\geq c > 0$ for all $n$, and $Y_n$ converges in probability to a constant $b\geq 1$.  In this post it was proved that $E[\frac{X_n}{Y_n}]\rightarrow a/b$. Just to note, I am interested in continuous random variables, if that makes any difference.
I am wondering can the condition that $Y_n \ge c > 0$ for all $n$ be weakened to $Y_n > 0$ for all $n$? In particular because in practise $Y_n$ could be the sample variance which is a positive random variable but not generally bounded away from $0$.
Intuitively it seems like if the density of $Y_n$ decays fast enough at the origin for all $n$ we might still be able to say $E[\frac{X_n}{Y_n}] \to a/b$ even if there is no $c >0$ such that $Y_n \ge c$ for all $n$?

A: You cannot, in general, remove the intermediate $c$ such that $Y_n \geq c > 0$. Imagine taking, independent of $X_n$, $Y_n = 1$ with probability $1-1/n$ and $Y_n = 1/n^2$ with probability $1/n$. We have $Y_n \to 1$ in probability since $P(|Y_n - 1| \neq 0) = 1/n$.
However, $$E[X_n/Y_n] = E[X_n] E[1/Y_n] = E[X_n](n^2\cdot \frac1n + 1\cdot(1-\frac1n)) \to a \cdot \infty = \infty$$ if $a \neq 0$.
Recall Vitali's convergence theorem that tells us that $L^1$ convergence is equivalent to uniform integrability + convergence in probability. The $Y_n \geq c > 0$ condition guarantees both UI and convergence in probability, but $Y_n > 0$ does not.


text:
Q: Code conversion from 2.0 to 1.0 I am developing a bar code scanner on XCode 6.4.1
Here's Swift 2.0 Code:
do {
   videoInput = try AVCaptureDeviceInput(device: videoCaptureDevice)
} catch {
   return
}

Can you tell me the replacement of "do, try & catch" in swift 1.0

A: if let videoInput = AVCaptureDeviceInput(device: videoCaptureDevice) {
  //videoInput available
} else {
  return
}


text:
Q: Derivative of double centered Euclidean distance matrix I want to do this matrix calculus: Given, a distance matrix of squared Euclidean distances  $D(X)_{n \times n}$ of $n$ points $X \in \mathbb{R}^k$, and given $C_n$, a centering matrix as defined in https://en.wikipedia.org/wiki/Centering_matrix, I want to find derivative of $$-C_n D(X) C_n$$ wrt $X$.  Eqn 1049 or 1050 of chapter 5 'Euclidean Distance Matrix' of this wonderful book here: https://ccrma.stanford.edu/~dattorro/EDM.pdf which gives a simplification of $D(X)$ could be useful.
My guess is the gradient would be $-C_n(\cdot)$ where the placeholder $(\cdot)$ would be the r.h.s of eqn 1049. I could be wrong. Nevertheless, I was looking for simpler representations of this derivative so that its wieldy to use in computations and as part of a larger result or analysis.
$-0.5*C_n D(X) C_n$ occurs in technique of 'classical multidimensional scaling' and is related to Gramian matrix representation as can be seen in here as well Calculating Gramian matrix from Euclidean distance matrix

A: The Gram and Distance matrices of the data matrix $X$ are
$$\eqalign{
G &= X^TX,\qquad g={\rm diag}(G) \\
D &= g{\tt1}^T + {\tt1}g^T - 2G \\
}$$
The centering matrix is
$$\eqalign{
C &= I - \frac{{\tt11}^T}{n},\qquad C{\tt1}=0,\quad{\tt1}^TC=0^T \\
}$$
Write the function of interest and calculate its differential.
$$\eqalign{
F &= -CDC  \;=\;  2CGC \\
dF
 &= 2C\,dG\,C \\
 &= 2CX^TdX\,C + 2C\,dX^TXC \\
}$$
Then use vectorization to flatten the matrices and obtain the gradient as a matrix.
$$\eqalign{
df &= \Big((2C\otimes CX^T) + (2CX^T\otimes C)K\big)\,dx \\
\frac{\partial f}{\partial x}
 &= 2\left(C\otimes CX^T\right) + 2\left(CX^T\otimes C\right)K \\
}$$
where $K$ is the commutation matrix associated with the Kronecker product.
Without vectorization, the gradient is a matrix-by-matrix derivative (a fourth order tensor).
I can provide an expression for that, but I doubt you'd find it useful.
Let $Y=XC,\,$ then the tensor gradient expression is
$$\frac{\partial F_{ij}}{\partial X_{kl}}=2C_{il}Y_{kj}+2Y_{ki}C_{lj}$$

Update
Perhaps this a better way of writing the tensor.
$$\eqalign{
H &= C\star Y \qquad&\big({\rm Dyadic\,Product}\big) \\
H_{ijkl} &= C_{ij}Y_{kl}& \\
\frac{\partial F_{ij}}{\partial X_{kl}}
  &= 2\big(H_{ilkj} + H_{jlki}\big)\quad& \\
}$$


text:
Q: how to share a link on facebook without using third party library? i have doubt to implement share link on facebook and twitter.
actually  i implemented social share link using sharekit and addThis third party library it working fine but i want share link without using third party library.

A: In iOS 6, You can use UIActivityViewController to share your link to Social services.
Reference: http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIActivityViewController_Class/Reference/Reference.html#//apple_ref/occ/cl/UIActivityViewController
It is as easy as these few lines:
NSString *textToShare = @"I just shared this from my App";
UIImage *imageToShare = [UIImage imageNamed:@"Image.png"];
NSURL *urlToShare = [NSURL URLWithString:@"http://www.mylink.com"];
NSArray *activityItems = @[textToShare, imageToShare, urlToShare];
UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
[self presentViewController:activityVC animated:TRUE completion:nil];


text:
Q: Please explain this solution to me (with picture)
This is my teacher's work on how to prove a limit statement using delta-epsilon. I understand everything except the where I circled it red. How did he get rid of the term sqrt (x-5) + 2 in the denominator? Where in the world did the zero come from?

A: Making the denominator smaller makes the fraction value larger.
(Sharing a pizza with less folks allows for larger slices)


text:
Q: Android encode animated webp I tried many things so far, is here anyone who knows how I can encode a animated webp file?
I tried to rename a gif into a webp file (sometimes this helps) but that doesn't convert it. I need a real animated webp file.
Thanks in advance


text:
Q: Why is my custom sort not working with Material-UI Data Grid component? I have implemented Material-UI's Data Grid Component, taking data in from a JSON array brought back from my API, and have had to implement a RenderCell function to account for text overflow and renders a button to take Users to a separate page. I have also implemented their ValueGetter for extraction to Excel documents and further functionality that will convert values to an empty string should they be undefined or null and have thus implemented a custom sortComparator function as specified in their docs.
However, no matter what implementation I use for the sortComparator, if there are empty cells, they are placed near the top during the ascending sort, but correctly during the descending sort, but if all cells are filled, the sort works as intended.
I want my Data Grid to place all empty cells at the bottom during the sort, for both ascending and descending.
Custom Sort Attempt:
    const customSort = (a: GridCellValue, b: GridCellValue) =>
    {
        if(a === '') {
           return 0;
        }
        else {
            return b > a ? -1 : 1;
    }

A: According to MDN:

If a and b are two elements being compared, then:

*

*If compareFunction(a, b) returns a value > than 0, sort b before a.

*If compareFunction(a, b) returns a value ≤ 0, leave a and b in the same order.

So, note you shouldn't return 0 if you want the empty cell at the bottom.
You should also use two different customSort functions for ascending and descending order.
const customSortAsc = (a,b) => {
  if(a === '') return 1;
  if(b === '') return -1;
  if(a > b) return 1
  if(a < b) return -1;
  if(a === b) return 0;
}

const customSortDesc = (a,b) => {
  if(a === '') return 1;  // Not needed line, here for clarification
  if(b === '') return -1; // Not needed line, here for clarification
  if(a > b) return -1
  if(a < b) return 1;
  if(a === b) return 0;
}

 const initialArray = ['','ddd','aaa','','ccc','bbb',''];

 const sortedArrayAsc = [...initialArray].sort(customSortAsc);
 // sortedArrayAsc = ['aaa','bbb','ccc','ddd','','','']

 const sortedArrayDesc = [...initialArray].sort(customSortDesc);
 // sortedArrayDesc = ['ddd','ccc','bbb','aaa','','','']


text:
Q: Given corners of a quadrilateral, Plot shaded quadrilateral in 3d using matplotlib I have 4 corners of a rectangle (like this).
all_corners[0] = [[16.9491164719, 17.8960237441, 0.0],
    [17.89665059755603, 27.22995253575736, 0.0],
    [16.9491164719, 17.8960237441, 2.552],
    [17.89665059755603, 27.22995253575736, 2.552]]

I need to plot this rectangle in a 3d space and I also need to plot multiple rectangles in a similar way. Is there any way to get this done? Also I need this to work for arbitrary shapes like quadrilateral, polygon but it's secondary for now, first I need to plot a shaded rectangle with given corner coordinates.
I tried Poly3dCollection, i'm getting weird traingles, not rectangles and many methods I found isn't what I want or I'm getting errors.
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib.pyplot as plt
fig = plt.figure()
ax = Axes3D(fig)
ax.add_collection3d(Poly3DCollection(all_corners[0]))
ax.set_ylim3d(10,40)
ax.set_xlim3d(10,40)
ax.set_zlim3d(0,4)
plt.show()

A: You code is almost good. You only have two small mistakes:

*

*The vertices are connected in the order provided. You should pass them in the desired order. Otherwise, you will get a self-intersecting polygon.

*Poly3DCollection expects a list of array like objects where each item describes a polygon. This is useful if you want to add many polygons at once. Thus, you should not pass all_corners[0] but all_corners as the first parameter

from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib.pyplot as plt

all_corners = []

all_corners.append([[16.9491164719, 17.8960237441, 0.0],
    [17.89665059755603, 27.22995253575736, 0.0],
    [17.89665059755603, 27.22995253575736, 2.552],  # note the permutation of
    [16.9491164719, 17.8960237441, 2.552],          # these two points
    ])

# You can add many polygons at once
all_corners.append([[10, 10, 0.0], [15, 15, 0.0], [15, 15, 2],
    [10, 10, 2]])

fig = plt.figure()
ax = Axes3D(fig)
ax.add_collection3d(Poly3DCollection(all_corners)) # list of array-like
ax.set_ylim3d(10,40)
ax.set_xlim3d(10,40)
ax.set_zlim3d(0,4)
plt.show()


text:
Q: How can I reenable autocomplete support for just 1 site in my whole struts project? since I'm trying to solve this problem for some days, I thought about giving you guys a chance. The situation:
We're running a SAP Shop with Java Server Pages and Struts in background. We had to disable the HTML Header setable Cache with:
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Expires", "0");

Now what I want to do seemed to us as a simple task but turned out to be more scientific than we expected.
We want to turn auto-complete for IE back on just for the login page. What I and my colleague tried were simple approaches like resetting the header values to various "should be caching" values like 'public' with expirens tomorrow or sth. Neither did anything give us that auto-complete boxes in IE6 and up.
So does anyone know a method for JUST ONE PAGE in a Struts system to turn the caching & as we think the autocomplete back on?

A: I don't think autocomplete has anything to do with the caching response headers. autocomplete is on by default, and can be disabled on a specific form field using autocomplete="off". If you have such an attribute in your login form fields, then just remove it.
See How do you disable browser Autocomplete on web form field / input tag?

A: Okay by now I found the answer myself. It seems easier when you talk about it, does it?
So the problem was, that we used a javascript function to submit our login form site. But that's not how you should do it (say's microsoft). I heard a techcast some minutes ago about the internet explorer relying on suspicious buttons for implemented browser functionality.
Having heard that the answer was kind of clear in my head. I head to submit over a button. Since we (HAVE TO!) use Javascript to submit, cause the button is only a styled div, I had to call a button click to show IE that we do a 'official' postback.
That's the code:
function submitLoginForm()
{
    var hiddenSubmitBtn = document.getElementById("hiddenSubmitButton");
    if(hiddenSubmitBtn.click) {
        hiddenSubmitBtn.click();
    } else {
        document.loginform.submit();
    }
    return false;
}

It now works fine.


text:
Q: c# Excel позднее связывание Find Как на C# с Excel использовать метод Find через позднее связывание?
Делаю так. Всё работает только с одним параметром what. Как использовать остальные параметры? Выбивают исключения при любой попытке использовать остальные параметры поиска.
object[] args = new object[1];
args[0] = "привет";  //what
// args[1] = 0;       //after
// args[2] = "";      //LookIn
// args[3] = "";      //LookAt
// args[4] = "";      //SearchOrder
// args[5] = "";      //SearchDirection
// args[6] = "";      //MatchCase
// args[7] = null;    //MatchByte
// args[8] = null;    //SearchFormat

object res = rangeObject.GetType()
                        .InvokeMember("Find",
                           BindingFlags.InvokeMethod, null, rangeObject, args);

A: При работе с Interop библиотеками, если значение параметра отсутствует обычно передается значение Missing.Value, вот пример передаваемых значений в метод Range.Find():
        object[] args = new object[9];
        args[0] = "привет";
        args[1] = Missing.Value;
        args[2] = XlFindLookIn.xlValues;
        args[3] = Missing.Value;
        args[4] = Missing.Value;
        args[5] = XlSearchDirection.xlNext;
        args[6] = false;
        args[7] = false;
        args[8] = Missing.Value;


text:
Q: Network behavior of slow Windows shared storage I have got on my hands 3 Windows XP file servers (their sole purpose is their SMB share) running on a office with about 50 users. The workload is only office usage: they use it to store and share among them Access databases and XLS files, and they use the files over the network share.
It is almost instantaneous to copy a 700 Kb XLS file from one of the servers to a workstation, but it takes over a minute to load it from a remote share with Excel. This same file is loaded  in a few seconds if from a local disk.
I don't know what makes the access to the file so slow when using it via the network, I suspect it is some quirk of Windows remote file access (maybe authentication?), and I hope to be possible to change some simple flag on the servers to speed things up to a sane speed. I have taken screen shots of the network usage while loading the aforementioned XLS file, can you recognize this pattern and possibly give me some clue of what is the problem?
In the first image, there are two runs of Excel loading the remote file, both taking more than one minute to complete. The top and bottom graphs are from the same thing, but I only found later the task manager option to discriminate between upload (red) and download (yellow), so I took 2 different screenshots (concatenated bellow). Both runs took more than one minute, possibly more than 2 minutes.

In the second image there are the 3rd and 4th runs. This time they ran considerably faster than the first one, but still too slow for bearable use. Both took more than 1 minute, but in the 4th run it occurred to me to measure the time properly, and I found it to take 1 minute and 42 seconds. That was the fastest of them. This time I only took one screenshot, of the discriminated version.

What I noticed in all runs is the initial peak, about 8 seconds after I start the run, then the network usage drops to very low usage, then, a few seconds later, there is another peak, the biggest concentrated activity, then a long time of almost no activity, when finally Excel shows the file. There is still another peak that begins when the file is shown, and lasts for a few seconds. The offset between the start and end of the run, and the activity in the graph seems to be caused by a delay in the task manager to show the data. I don't know when the file is actually downloaded. I can't also explain why the green graph shows a small activity between peaks, and the red/yellow graph shows none. But the most intriguing of all is the minute long pause between the second and third peak, when I have no idea on what is happening, and certainly could be much faster.
Can someone experienced in Windows networks provide some expert guess on what is the problem with this setup (apart from decade old operating system)? Do you recognize these graph patterns? Can explain it? Have any hint on how to improve performance?

A: If the "slowness" only happens in Excel, I would probably look closer at the XML file and make sure the interpreter in Excel isn't having trouble parsing the XML.  Could be malformed or having some trouble reading it.  Try opening the file in other applications like Notepad etc and see if the slowness issue still exists.  FWIW, XP isn't a good platform for sharing files with that many (50) users as it is limited to 10 client connections.  You could be running into some contention issues with the other clients trying to read the XML file as well.  I don't think your issue is the size of the file, but rather what excel is doing with the file once it opens it.  But that is just my thought.  Try doing a CSV file dump and opening it up in Excel and see how long that takes.


text:
Q: Why is bash -c behaving strangely I have a file called wait_script.sh with the following contents
#!/bin/bash
until $(curl --output /dev/null --silent --head --fail http://localhost:4001);do
  printf '.'
  sleep 5
done

I can run it with:
./wait_script.sh

and it works as expected
I am able to run the same thing with:
until $(curl --output /dev/null --silent --head --fail http://localhost:4001);do;printf '.';sleep 5;done

But when I try to run it inside of bash -c, I get the following error:
bash -c "until $(curl --output /dev/null --silent --head --fail http://localhost:4001);do;printf '.';sleep 5;done"

bash: -c: line 0: syntax error near unexpected token `;'
bash: -c: line 0: `until ;do;printf '.';sleep 5;done'

Why is this error happening and how can I run the command inside of bash -c?

A: You have two errors:

*

*do is a terminator itself for an arbitrary command list that could contain a ;-delimited list of commands. It is not itself a command to be terminated by a ;. Omit the semicolon between do and printf.

*You don't want a command substitution here at all; until uses the exit status of curl to determine when to end the loop. Your original code only works because curl doesn't produce any output for the shell to treat as a command, so until "runs" the empty command, which always succeeds, terminating the loop immediately.

You should write
bash -c 'until curl ...; do printf "."; sleep 5; done'

ensuring that no single quotes are used inside the argument to -c.


text:
Q: Checking that a $_GET var doesn't exist in Laravel 5.3's HTTP Request Laravel has a method in its Request class that checks if a variable exists in the request.
$request->has('varnamegoeshere')

I need to do the inverse and check if a variable doesn't exist in the request. Naturally you would think the following would work, but it doesn't:
if(!$request->has('varnamegoeshere'))

How do I go about checking if a variable doesn't exist in the request?
UPDATE: Controller and class code below
Controller
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Project\Frontend\Repo\Vehicle\VehicleInterface;
use Illuminate\Support\Facades\View;

class SearchController extends BaseController
{
    protected $vehicle;

    public function __construct(
        VehicleInterface $vehicle
    )
    {
        $this->vehicle  = $vehicle;
    }

    public function index(Request $request)
    {
        /*
         * Search Refinement
         */

        // Set links that will refine user selection when clicked
        $search = array();

        if(!$request->has('make'))
        {
            // Fetch makes for user refinement
            $search['makes'] = $this->vehicle->setMakeLinks($request);
        }

        if(View::exists('index'))
        {
            return View::make('search')
                ->with('search', $search);
        }
    }
}

Eloquent class
<?php

namespace App\Project\Frontend\Repo\Vehicle;

use Illuminate\Database\Eloquent\Model;

class EloquentVehicle implements VehicleInterface
{
    /**
     * Protected variables
     *
     * @var Model
     */
    protected $vehicle;

    /**
     * EloquentVehicle constructor.
     *
     * @param Model $vehicle
     */
    public function __construct(
        Model $vehicle
    )
    {
        $this->vehicle = $vehicle;
    }

    /**
     * Create links based on unique makes retrieved from the database
     *
     * @param null $request
     * @return mixed
     */
    public function setMakeLinks($request = null)
    {
        $query = $this->vehicle->groupBy('make')
            ->orderBy('make', 'asc')
            ->get();

        // Create empty array
        $links = array();

        // Obtain query string
        $queryString = str_replace($request->url(), '', $request->fullUrl());

        foreach($query as $vehicle)
        {
            $append = '?make='.$vehicle->make;
            if ($queryString != '')
                $append = $queryString.'&make='.$vehicle->make;

            array_push($links, 'make.' for sale" itemprop="brand" href="'.url('usedcars/'.$append.'#searched').'">'.$vehicle->make.'');
        }

        return $links;
    }
}

View file
@extends('layouts.template')

@section('content')
    @if(isset($search['make']))

Find cars by Make

            @foreach($search['make'] as $link)
                {!! $link !!}
            @endforeach

    @endif
@endsection

A: Use exists instead of has:
if (!$request->exists('varnamegoeshere'))

Hope this helps!

A: I found my problem. The if statement in my view file had the singular "make" instead of the plural.
@if(isset($search['make']))

should be
@if(isset($search['makes']))


text:
Q: How to declare a string from multiple string variables C++ I want to know how I can declare a string from multiple string variables.
Example code:
std::string one = "one1";
std::string two = "two2";
std::string three = "three3";

std::string OneTwoThree = (one, " ", two, " ", three); // Here I want to save it as "one1 two2 three3"
std::cout << OneTwoThree;

Any help is really appreciated!

A: You can do it by adding all three strings as
std::string OneTwoThree = one+" "+two+" "+three;


text:
Q: On the iPhone, how do i parse a html page to get all the RSS links? in html an rss link looks somewhat like this
The feed title

i would like to get all links that match this description from a html page that has a list of rss feeds. anyone know of a good way to parse, with some sample code?

A: The libxml2 library can receive XPath queries with the following extensions. With these extensions you might issue the XPath query /a[@class = "rsslink"]/@href on your HTML document, in order to retrieve an NSArray with those attributes' values.


text:
Q: Как отправить файл в aiogram 3.0.0b4? Как отправить файл в aiogram версии 3.0.0b4?
Использую следующий код и не знаю, что делать дальше:
f = open('otchet.txt', 'w')
f.write(otchet)
f.close()

Файл создал, а как отправить понять не смог.

A: Для того чтобы это сделать, используйте специальную обёртку FSInputFile в aiogram для локальных файлов:
from aiogram.types.input_file import FSInputFile

document = FSInputFile('otchet.txt')
await bot.send_document(chatid, document)

Здесь chatid — ID чата, в который отправляется файл.


text: Q: Parallel port (LPT) file transfer software I am looking for (preferably freeware/opensource) Windows (XP/Vista) based application which allows files to be transferred across two computers through their parallel ports, something like Hyperterminal, except for parallel ports.


text:
Q: Spring - Returning JSON-formatted error messages from a filter I'm working on a Spring Boot REST application.
I've registered a custom AuthenticationEntryPoint that returns a '401 Unauthorized' error if a user doesn't provide credentials.
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
    }
}

This works great and returns the JSON-formatted DefaultErrorAttributes that look like this:
{
  "timestamp": 1465230610451,
  "status": 401,
  "error": "Unauthorized",
  "exception": "org.springframework.security.authentication.BadCredentialsException",
  "message": "Unauthorized",
  "path": "/webapp/login"
}

Now I've added a Filter to the application with the following doFilter() override:
@ Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException {
    try {
        // Here be some code that fails.
    } catch (Exception e) {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
    }

    chain.doFilter(request, response);
}

However instead of the JSON-formatted DefaultErrorAttributes shown above, this code returns the default Tomcat 'Error report' HTML page.
Why does this happen and what would be the best way to make both error messages consistent (JSON-formatted) in both cases?

A: Original link  http://teknosrc.com/java-break-filter-chain-return-custom-pojo-response-servlet/
public class TestFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,ServletException {

        if(ANY CONDITION){
            //ANY POJO CLASS
            // ErrorResponse is a public return object that you define yourself
            ErrorResponse errorResponse = new ErrorResponse();
            errorResponse.setCode(401);
            errorResponse.setMessage("Unauthorized Access");

            byte[] responseToSend = restResponseBytes(errorResponse);
            ((HttpServletResponse) response).setHeader("Content-Type", "application/json");
            ((HttpServletResponse) response).setStatus(401);
            response.getOutputStream().write(responseToSend);
            return;
        }

        //ANY OTHER BUSINESS LOGIC
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

    private byte[] restResponseBytes(ErrorResponse eErrorResponse) throws IOException {
        String serialized = new ObjectMapper().writeValueAsString(eErrorResponse);
        return serialized.getBytes();
    }
}


text:
Q: EF Core 3.1 - Add Tag to IIncludableQueryable without changing type TL;DR - I need a way in EF core 3.1.4 to add a tag to an IIncludableQueryable object, and still keeping it as an IIncludableQueryable instead of changing the type to IQueryable (the return type of TagWith function)
A while ago I created a piece of code to add table hints to EF Core's queries, using tags and interceptors. At the time, I only added the ability to add the hints on the "main" entity and on the first level of included entities (i.e. those from the "Include" method but not "ThenInclude" methods) using extension methods. Now I want to be able to add hints to the "ThenInclude"ed entities, and be able to chain them.
E.g. if my query is
context.Games.Include(g => g.Events)
             .ThenInclude(e => e.Team)
             .ThenInclude(t => t.Players)
             .Where(...)

right now I can only add hints to Games (the main entity) and Events (the first level of include) tables, but not for Teams or Players. I want to be able to add hints to all of them.
This is the relevant code:
public static class QueryHintsExtensions
{
    private const string Tag = "Use hint:";

    public static IQueryable<T> AddHint<T>(this IQueryable<T> source, DbContext context, QueryHintsTypes hint, string optionalParameter = "")
    {
        var tableName = GetTableName(typeof(T), context);
        return source.AddTag(hint, tableName, optionalParameter);
    }

    public static IIncludableQueryable<TEntity, TProperty> IncludeWithHint<TEntity, TProperty>(this IQueryable<TEntity> source, Expression<Func<TEntity, TProperty>> navigationPropertyPath, DbContext context, QueryHintsTypes hint, string optionalParameter = "") where TEntity : class
    {
        var tableName = GetTableName(typeof(TProperty), context);
        return source.AddTag(hint, tableName, optionalParameter).Include(navigationPropertyPath);
    }

    private static IQueryable<T> AddTag<T>(this IQueryable<T> source, QueryHintsTypes hint, string tableName, string optionalParameter = "")
    {
        return source.TagWith($"{Tag} {tableName},{hint},{optionalParameter}");
    }

    private static string GetTableName(Type ingestionModelType, DbContext context)
    {
        if (ingestionModelType.IsGenericType)
            ingestionModelType = ingestionModelType.GenericTypeArguments.Single();

        var model = context.Model;
        var entityType = model.FindEntityType(ingestionModelType);
        return entityType.GetTableName();
    }

    public static DbContextOptionsBuilder AddQueryHints(this DbContextOptionsBuilder builder) =>
        builder.AddInterceptors(new QueryHintInterceptor(Tag));
}

To get back to the example, in order to add forceseek to Games and Events tables, I would do this:
context.Games.AddHint(c, QueryHintsTypes.Forceseek)
             .IncludeWithHint(g => g.Events, c, QueryHintsTypes.Forceseek)
             .ThenInclude(e => e.Team)
             .ThenInclude(t => t.Players)
             .Where(...)

Now I also want to be able to do this:
context.Games.AddHint(c, QueryHintsTypes.Forceseek)
             .IncludeWithHint(g => g.Events, c, QueryHintsTypes.Forceseek)
             .ThenIncludeWithHint(e => e.Team, c, QueryHintsTypes.Forceseek)
             .ThenIncludeWithHint(t => t.Players, c, QueryHintsTypes.Forceseek)
             .Where(...)`

I can add the ability to do just one "ThenIncludeWithHint" by doing this:
public static IQueryable<TEntity> ThenIncludeWithHint<TEntity, TPrevious, TProperty>(this IIncludableQueryable<TEntity, TPrevious> source, Expression<Func<TPrevious, TProperty>> navigationPropertyPath, DbContext context, QueryHintsTypes hint, string optionalParameter = "") where TEntity : class
    {
        var tableName = GetTableName(typeof(TProperty), context);
        return source.ThenInclude(navigationPropertyPath).AddTag(hint, tableName, optionalParameter);
    }

But I would like to be able to chain "ThenIncludeWithHint", and for that I need to somehow be able to return an IIncludableQueryable from that method.
Is there any way to accomplish this?


text:
Q: JavaFx Autocompletion Listener radiobutton I have a textfield where I want to dinamically change the autocompletion list.
All that code is in initialize method of my controller.
This is the original assign when I first run the program: (nomi is the textfield, listaNomi is an ObservableList
listaNomi = OperatoreDAO.cercaNomiOp(attuale);
                TextFields.bindAutoCompletion(nomi,listaNomi);

That works, but now I want to change the list content when I select one of two different RadioButton (the OperatoreDAO.cercaNomiOp method takes a RadioButton as argument)
                contrattoGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {

                     @Override
                public void changed(ObservableValue<? extends Toggle> ov, Toggle t, Toggle t1) {
                    RadioButton selez = (RadioButton)t1.getToggleGroup().getSelectedToggle();

                    try {
                        listaNomi = OperatoreDAO.cercaNomiOp(selez);
                    } catch (ClassNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            });

I had to put ObservableList<String> listaNomi = FXCollections.observableArrayList();outside of initialize method cause says that the local variable must be final.
Now it doesn't says error but if I change radiobutton the list remains the same of the initialization.

A: Use AutoCompletionBinding<String>. This app demos how to use AutoCompletionBinding<String> and List<String> to change the binding based on the selected RadioButton.
import java.util.Arrays;
import java.util.List;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import org.controlsfx.control.textfield.AutoCompletionBinding;
import org.controlsfx.control.textfield.TextFields;

/**
 *
 * @author blj0011
 */
public class JavaFXApplication208 extends Application
{

    AutoCompletionBinding<String> abcBinding;
    AutoCompletionBinding<String> defBinding;

    @Override
    public void start(Stage primaryStage)
    {

        List<String> list1 = Arrays.asList("one", "two", "three");
        List<String> list2 = Arrays.asList("four", "five", "six");

        TextField textfield = new TextField();

        VBox root = new VBox();

        RadioButton radioButton1 = new RadioButton("Left");
        RadioButton radioButton2 = new RadioButton("Right");

        ToggleGroup radioGroup = new ToggleGroup();
        radioButton1.setToggleGroup(radioGroup);
        radioButton2.setToggleGroup(radioGroup);
        radioGroup.selectedToggleProperty().addListener((obs, oldValue, newValue) -> {
            RadioButton tempRadioButton = (RadioButton) newValue;
            if (tempRadioButton == radioButton1) {
                if (defBinding != null) {
                    defBinding.dispose();
                }
                abcBinding = TextFields.bindAutoCompletion(textfield, list1);
            }
            else if (tempRadioButton == radioButton2) {
                if (abcBinding != null) {
                    abcBinding.dispose();
                }
                defBinding = TextFields.bindAutoCompletion(textfield, list2);
            }
        });

        HBox hbox = new HBox(radioButton1, radioButton2);

        root.getChildren().addAll(hbox, textfield);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        launch(args);
    }

}


text:
Q: Reset zoom position when a new image is loaded in div The page I am creating currently has a div with an image inside. There are a set of links underneath this image div that, when a new link is clicked, the image in the div changes.
I also have a zooming effect on the image div, so that when the user clicks on the plus/minus symbols, or scrolls with their mouse, they zoom into the image.
The zooming script I am using is this one: http://lab.gianiaz.com/jquery/gzoom/
My issue is this: when a new link is clicked, and the image changed, the zoom remains "zoomed in". I am trying to make the zoom reset to completely zoomed out when a new image is  loaded in the div.
Anyone have any ideas?
P.S. I am using the latest Jquery, as well.
Here is a glimpse at my coding.

Image 1
Image 2
Image 3

A: I'm not an expert on Javascript, but I think you can try doing a 'reset' type deal and use the "onLoad" function in HTML to call a Javascript function that changes the zoom back to the original.

A: I would make it something like this:
HTML:

     Image 1
     Image 1
     Image 1

JQuery:
$(".imageSwap".on("click", function() {
     // reset function to set the zoom back to default
     ...

     var imageUrl = $(this).data('link');
     $("#SHOWCASEIMG".attr("src",imageUrl);
});

Since I don't know the zooming script, you need to create yourself a function that resets the zoom.

A: It seems you've solved with a little help ;-)
It's an old plugin, but it seems that someone uses it. With your question I've updated it and now it includes the setZoom method.
:-)

A: I was at last able to contact the original creator of the zoom script I was using, and he was kind enough to update the script to allow for the zoom to be reset. However, there was a issue that was quickly resolved between the two of us (but mostly him, truth be told, since I'm still a Javascript newbie). I told him I would update this post in case anyone came along with the same issue as me.
[http://lab.gianiaz.com/jquery/gzoom/][1]
The new JS file handles the zoom function just fine, but it is in the page itself that the changes need to be made.
This is what I had originally.

The new script looks like this:

The part that has changed is this:
$zoom = $("#zoom01").gzoom({

The issue that arose after the script was changed to allow for resetting the Zoom came when more than one $zoom was being called to accommodate for images of different sizes. That was done using this javascript language:
 $('#select1, #select2, #select3, #select4, #select5, #select6').click(function() {
                $('#subContainer1').show();
                $('#subContainer2').hide();
                $zoom.setZoom(0);
            });

            $('#select7, #select8').click(function() {
                $('#subContainer1').hide();
                $('#subContainer2').show();
                $zoom2.setZoom(0);
            });
        });

In order to resolve this, I changed the name for each $zoom being called:

Along with the script changing to the final version above, the HTML was also changed to accommodate for different image sizes.

Image 1
Image 2

The id values SHOWCASEIMG and SHOWCASEIMG2 change the image according to which zoom div is needed: zoom01 or zoom02. The id values 'select1' and 'select7' are used to designate what size the zoom box needs to be.
Many thanks to Giovanni for his invaluable help!


text:
Q: Call Sass's compile_file in Ruby I'd like to call compile_file from Sass in my Ruby file. When I do
compile_file("file.scss", options)

I receive the error: undefined method 'compile_file.' Am I missing a require or calling it wrong? Sass is installed and I can have it watch properly when I start it in terminal. I'd like to be able to call compile_file on my own when I'm not watching. Could someone give me example code on how to use Sass's compile_file in Ruby by passing in a filename and an object for options?

A: I don't know Sass, but in general you need to either use fully qualified name of the method Sass::compile_file or require the module into global space: require 'sass'

A: Try something like
require 'rubygems'
require 'sass'
puts 'methods available: ' + (Sass.methods.sort - Object.methods).inspect
Sass.compile_file

A: Install Sass before using require 'sass':
sudo gem install sass
Now create a file test.rb:
#!/usr/bin/ruby
require 'sass'
puts Sass::compile_file('./colors.scss')

(do chmod +x test.rb)
Now with colors.scss:
$color: blue !default;
p {
color: $color;
}

Running ./test.rb will output:
p {
  color: blue; }

According the docs you should use Sass::Engine:

Using Sass in Ruby code is very simple. After installing the Sass gem,
  you can use it by running require "sass" and using Sass::Engine.

#!/usr/bin/ruby
require 'sass'
sass_engine = Sass::Engine.for_file('./colors.scss', :syntax => :scss)
output = sass_engine.render
puts output


text:
Q: How to know the root of your website using $_SERVER? for example is I have a example site in xampp localhost htdocs:
C:/xampp/htdocs/example

and when I view the $_SERVER['PHP_SELF'] in a specific .php inside the sub-folder of the root, I will have to use the first string to get the root:
specific .php inside the subfolder:
C:/xampp/htdocs/example/subfolder/page.php

$_SERVER['PHP_SELF'] I will get in the .php:
/example/subfolder/page.php

but when I try this in a free hosting site, I get this:
/subfolder/page.php

the root I need in the localhost is:
/example/

while in a hosting site is:
/

is there a code to get the root of your website for both localhost and in a hosting site? or is there a hint/flag whatev. it is if I will need to use the first string /*first_string*/ to get the root in the $_SERVER? thanks!

A: $_SERVER['DOCUMENT_ROOT']

adding more characters to be able to save the answer....


text:
Q: Eigenvalues of a matrix close to a tridiagonal Toeplitz matrix
I am trying to find all the eigenvalues of $P$ defined below:

$$P=\begin{bmatrix}
0.5&0.5&0&0&\cdots 0&0 \\
0.25&0.5&0.25&0&\cdots 0&0\\
0&0.25&0.5&0.25&\cdots 0&0\\
\vdots \\
0&0&0&0&\cdots 0.5&0.5
\end{bmatrix}_{n\times n}$$
So $P$ has $0.5$ along the main diagonal. It has $0.25$ on diagonals above and below the main diagonal except for the first and last row. Hence $P$ is not exactly a Toeplitz matrix.
My attempt: A paper I'm looking at, gives eigenvalues of the following Toeplitz matrix
$$
Q=\begin{bmatrix}
b&a \\
c&b&a \\
&\ddots&\ddots&\ddots \\
&&c&b&a \\
&&&c&b
\end{bmatrix}
$$
as $\lambda_j = b+2\sqrt{ca}\cos\left(\frac{j\pi}{n+1} \right)$
So I'm wondering if I will be able to find eigenvalues of $P$ even though its not a Toeplitz matrix precisely?

A: $\def\a{\alpha}$
Let $u$ be an eigenvector of the matrix $P$ and assume the elements of the eigenvector have the form:
$$
u_k=e^{\alpha k}+ae^{-\alpha k},\tag1
$$
with some parameters $a$ and $\alpha$, which are to be found.
Obviously for all $k=2\dots(n-1)$
$$
(Pu)_k=\frac14\left(e^{\a k}+ae^{-\alpha k}\right)\left(e^\alpha+2+e^{-\alpha}\right)
=\frac14\left(e^\alpha+2+e^{-\alpha}\right)u_k.\tag2$$
Thus it remains only to find such $a$ and $\alpha$ that the equation $(2)$ is satisfied for $k=1$ and $k=n$ as well.
For $k=1$:
$$\begin{align}
&\frac12(e^{\a}+ae^{-\a}+e^{2\a}+ae^{-2\a})=\frac14\left(e^\a+2+e^{-\a}\right)\left(e^\alpha+a e^{-\alpha}\right)\\
&\iff
e^{2\a}+ae^{-2\a}=1+a \iff a=e^{2\a}.\tag{3}
\end{align}$$
For $k=n$:
$$\begin{align}
&\frac12(e^{\a(n-1)}+ae^{-\a(n-1)}+e^{\a n}+ae^{-\a n})
=\frac14\left(e^\a+2+e^{-\a}\right)\left(e^{\a n}+a e^{-\a n}\right)\\
&\iff e^{\a (n-1)}+ae^{-\a(n-1)}=e^{\a (n+1)}+ae^{-\a(n+1)}\\
&\iff e^{\a (n-1)}+ae^{-\a (n-1)}=e^{2\a}e^{\a(n-1)}+ae^{-2\a}e^{-\a(n-1)}\\
&\stackrel{(3)}\iff \left(e^{\a (n-1)}-e^{-\a (n-1)}\right)\left(1-e^{2\a}\right)=0\\
&\iff \a_m=\frac{\pi\,i}{n-1}m,\quad m=0\dots n-1
.\tag{4}
\end{align}$$
The corresponding eigenvalues are:
$$
\lambda_m=\frac14\left(e^{\a_m}+2+e^{-\a_m}\right)=\left(\frac{e^{\frac{\a_m}2}+e^{-\frac{\a_m}2}}2\right)^2=\cos^2\frac{\pi m}{2(n-1)},\quad m=0\dots n-1.\tag5
$$
Since all $n$ eigenvalues are distinct we are done.

A: (Not a solution)
I numerically found that the answer should be
$$
\lambda_j = \sin^{2}\left(\frac{j\pi}{2(n-1)}\right), \quad 0\leq j \leq n-1
$$
but I only have a vague idea to prove this. If we define $B_n = 2P_n - I_n$, then it is enough to show that the eigenvalues of $B_n$ are
$$
\cos\left(\frac{j\pi}{n-1}\right),\quad 0\leq j\leq n-1.
$$
It seems that the characteristic polynomial of $B_n$ is
$$
\phi_n(x) = \frac{1}{2^{n}}(x^2-1)U_{n-2}(x)
$$
where $U_n(x)$ is $n$-th Chebyshev polynomial of second kind. However, I'm not sure how to prove this, although it seems that using induction might give recurrence formula for $\phi_n$ which resembles that of $U_n$ a lot.


text:
Q: how to access Array with key in swift4 I am very new to swift, I used to code in objective C, but Now I am facing alot of problems while development in Swift. Right now I have json file imported in project
let file = Bundle.main.url(forResource: "test", withExtension: "json")

do {
    let data = try Data(contentsOf: file!)

    //let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary

    let json:NSArray = try (JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.mutableContainers) as? NSArray)!

    print(json[0])

} catch let error as NSError {
    print("Failed to load: \(error.localizedDescription)")
}

It gives output like
{
Correct = 1;
    EA = "50 Days  ";
    EB = "40 days";
    EC = "90 days";
    ED = "30  days";
}

And i Need to access only Content with key "EA".
previously with objective C, I used to access it like
[[json objectAtIndex:0] objectForKey:@"EA"]

Now when I am trying to access it like
json[0].objectForKey("EA") as? String

it says

Value of type 'Any' has no member 'objectForKey'

What should I do?

A: Swift 2
(json[0] as! NSDictionary).objectForKey("EA") as? String

Swift 3 & 4
(json[0] as! NSDictionary).object(forKey: "EA") as? String


text:
Q: How to read a large file as Pandas dataframe? I want to read a large file (4GB) as a Pandas dataframe. Since using Dask directly still consumes maximum CPU, I read the file as a pandas dataframe, then use dask_cudf, and then convert back to a pandas dataframe.
However, my code is still using maximum CPU on Kaggle. GPU accelerator is switched on.
import pandas as pd
from dask import dataframe as dd
from dask_cuda import LocalCUDACluster
from dask.distributed import Client
cluster = LocalCUDACluster()
client = Client(cluster)

df = pd.read_csv("../input/subtype-nt/meth_subtype_normal_tumor.csv", sep="\t", index_col=0)
ddf = dask_cudf.from_cudf(df, npartitions=2)
meth_sub_nt = ddf.infer_objects()

A: I have had similar problem. With some research, I came to know about Vaex.
You can read about its performance here and here.
Essentially this is what you can try to do:

*

*Read the csv file using Vaex and convert it to a hdf5 file (file format most optimised for Vaex)
vaex_df = vaex.from_csv('../input/subtype-nt/meth_subtype_normal_tumor.csv', convert=True, chunk_size=5_000)

*Open the hdf5 file using Vaex. Vaex will do the memory-mapping and thus will not load data into memory.
vaex_df = vaex.open('../input/subtype-nt/meth_subtype_normal_tumor.csv.hdf5')

Now you can perform operations on your Vaex dataframe just like you would be doing with Pandas. It will be blazingly fast and you will certainly notice huge performance gains (lower CPU and memory usage).
You can also try to read your csv file directly into Vaex dataframe without converting it to hdf5. I had read somewhere that Vaex works fastest with hdf5 files therefore I suggested the above approach.
vaex_df = vaex.from_csv('../input/subtype-nt/meth_subtype_normal_tumor.csv.hdf5', chunk_size=5_000)

A: Right now your code suggests that you first attempt to load data using pandas and then convert it to dask-cuDF dataframe. That's not optimal (or might not even be feasible). Instead, one can use dask_cudf.read_csv function (see docs):
from dask_cudf import read_csv

ddf = read_csv('example_output/foo_dask.csv')


text:
Q: how to set up icinga2 on Debian The biggest problem is that CLI wizard doesn't work on Debian package. So  icinga2 node wizard is impossible.
So i have to edit configs manually, but this is so weird, that after reading i know less then before.
Few questions:

*

*what is a difference between satelitte and client?

*What is a difference between zone and cluster?

*If set zones and endpoints, should I see hosts on webpanel? Or I have to set it independently?

I want to see all my hosts in one web panel, and I want to manage it from this one master computer.
I think, that I have to run icinga2 on all hosts.
What I did for now:
On master computer I changed zones.conf:
/*
 * Endpoint and Zone configuration for a cluster setup
 * This local example requires `NodeName` defined in
 * constants.conf.
 */

object Endpoint "chart-left" {
  host = "127.0.0.1"
}
object Endpoint "gonzales" {
  host = "W.X.Y.Z"
}

object Zone "master" {
  endpoints = [ "chart-left" ]
}

object Zone "checker" {
  endpoints = [ "gonzales" ]
  parent = "master"
}
/*
 * Defines a global zone containing templates,
 * etc. synced to all nodes, if they accept
 * configuration. All remote nodes need
 * this zone configured too.
 */

/*
object Zone "global-templates" {
  global = true
}
*/

And on client computer zones.conf differs with IP:
/*
 * Endpoint and Zone configuration for a cluster setup
 * This local example requires `NodeName` defined in
 * constants.conf.
 */

object Endpoint "chart-left" {
  host = "A.B.C.D"
}

object Zone "master" {
  endpoints = [ "chart-left" ]
}

object Endpoint "gonzales" {
  host = "127.0.0.1"
}
object Zone ZoneName {
  endpoints = [ "gonzales" ]
  parent = "master"
}
/*
 * Defines a global zone containing templates,
 * etc. synced to all nodes, if they accept
 * configuration. All remote nodes need
 * this zone configured too.
 */

/*
object Zone "global-templates" {
  global = true
}
*/

And in both logs appears some informations:
master:
[2016-04-13 00:47:17 +0200] information/ApiClient: Reconnecting to API endpoint 'gonzales' via host 'W.X.Y.Z' and port 5665

client:
[2016-04-13 00:54:10 +0200] information/ApiListener: New client connection for identity 'chart-left'

But looking at panel I still see only localhost (chart-left) - which is defined in hosts.conf.
The zones.d tree looks like:
zones.d/
  README
  checker/
  global-templates/
  master/

without any files in checker/ master/ nor global-templates/

A: This doesn't answer your question, but does solve the problem of the CLI not working properly. You can install the packages from debmon (this version is a bit newer) following the Icinga2 Getting Started Guide. (Make sure that you actually install the new version rather than the one in jessie.) Then you can just use the wizards.


text:
Q: working with groupby multiple columns in Python I have 3 columns in a dataframe, as:
User_ID, Product_Category_1 and Corresponding Purchase amount.
I am trying to group by based on User_ID and Product_Category_1 and selecting the average of Purchase amount.
So output dataframe will have: User_ID,Product_Category_1 and Avg_Purchase.
This is not working for me:
x=train_bk.groupby(["User_ID","Product_Category_1"],as_index=False)['Purchase'].transform('mean')

This gives me a series of the mean value of Purchase for each row. However I need to keep only the unique User_ID and Product_Category_1 combination
   x1 = train_bk.select(Average(train_bk.User_ID), train_bk.Product_Category_1,
          group_by=(train_bk.User_ID,train_bk.Product_Category_1))

I tried this from sql package. But it throws error: "name 'Average' is not defined". Also is there a good package in python that has SQL syntax similar to Teradata or MYSQL.

A: Ok, This seems to be working:
   x = train_bk.groupby(["User_ID","Product_Category_1"],as_index=False)['Purchase'].mean()


text:
Q: Processor Architecture for Assembly
Possible Duplicate:
assembly instruction set for my processor

I am currently trying to program my own simple operating system. I am learning C++ and herd you need to know assembly in your processors code. I was wondering how you would find this information. When I google Intel Core i5-2435M architecture, it says 64 bit, when I want to know if it's x86 or something else. I found post that told you how to do so on windows, but I'm on a mac. Since I'm just a kid (11) who hopes to do this over the next 4 years, I hope you can help me figure this out. Thanks!

A: x86, aka x86-32, aka IA-32 is a 32-bit instruction set. Your Intel Core i5 processor runs the 64-bit version of that, called x86-64, more specifically, Intel 64. Note that processor architecture has little or nothing to do with the operating system your computer is running (Windows vs Mac vs ...).
All that said, you don't really need to know assembly in order to write C++, at least as a beginner.
Good on you for starting early, and good luck!


text:
Q: An example of trans-series from Euler's equation There seems to be a generalization of the notion of the "asymptotic series" to a notion of "trans-series". One "simple" example of this seems to arise in trying to solve the Euler's equation by power-series, $$\frac {d\phi (z)} {dz } + A\phi(z) = \frac{A}{z} $$
A power series solution to this is, $$\phi_0(z) = \sum_{n=0}^{\infty} \frac{a_n } {z^{n+1}} $$ where $a_n = A^{-n}n!$. This series is an asymptotic series with zero-radius of convergence because the coefficients grow factorially in $n$.

*

*Now what I don't understand is as to how from all this it follows that one can construct a ``family of formal solutions to this ODE based on $\phi_0(z)$" as, $\phi(z) = \phi_0(z) + Ce^{-{Az}}$

The above is apparently an example of a "trans-series".

*

*I don't undertand as to how this has two small parameters $z$ and $e^{-\frac{A}{z} }$?

Here the strength of the non-perturbative effect $(A)$ and the divergence of the asymptotic series are related.

*

*But also in what sense is the $Ce^{-\frac{A}{z}}$ ``non-analytic at $z=\infty$"? That all the possible Taylor series coefficients go to $0$ on taking the $z=\infty$ limit? Is this a signature of being a trans-series?

A: The equation in question, $(2.17)$ in the book, is
$$
\phi'(z)+A\phi(z)=\frac Az\tag{1}
$$
Note that $(1)$ can be written in a way to generate an asymptotic series solution:
$$
\phi(z)=\frac1z-\frac{\phi'(z)}{A}\tag{2}
$$
Iterating this as a recursion, we get an asymptotic approximation to a solution, $(2.18)$ in the book:
$$
\phi_0(z)=\frac1z+\frac1{Az^2}+\frac2{A^2z^3}+\frac6{A^3z^4}+\cdots\tag{3}
$$
Given any two solutions to $(1)$, their difference must satisfy the homogeneous equation
$$
\phi_h'(z)+A\phi_h(z)=0\tag{4}
$$
The solution to $(4)$ is
$$
\phi_h(z)=Ce^{-Az}\tag{5}
$$
Thus, as mentioned in $(2.19)$ of the book, the general solution would be
$$
\phi_0(z)+Ce^{-Az}\tag{6}
$$
I think one point that the author is trying to make is that the asymptotic series for all of these solutions is given in $(3)$ since $\phi_h(z)$ decays much faster than any power of $\frac1z$. Unfortunately, there seem to be some confusing typos in point 2. following $(2.19)$ related to an earlier comment, $(2.4)$ in the book.


text:
Q: Node - middleware not applying a req property In my project, when a user logs in, I generate an auth token like so:
// For my User model
userSchema.methods.generateAuthToken = () => {
  const token = jwt.sign({ _id: this._id }, config.get('jwtPrivateKey'))
  return token
}

I then apply an auth middleware on a route that allows a user to create posts.
auth middleware:
module.exports = (req, res, next) => {
    const token = req.header('x-auth-token')
    if (!token) return res.status(401).send('No token provided')

    try {
        const decoded = jwt.verify(token, config.get('jwtPrivateKey'))
        req.user = decoded
        next()
    }
    catch (ex) {
        res.status(400).send('Invalid token')
    }
}

My route:
router.post('/', auth, upload.single('postImage'), async (req, res) => {
    console.log(req.user._id)
    const post = new Post({
        postImage: `http://localhost:3000/${req.file.path}`,
        caption: req.body.caption,
        user: req.user._id
    })

    await post.save()
    res.send(post)
})

As you can see, I log the req.user._id in the route, and when I call this endpoint, I get undefined logged to the console. Instead I expect the _id of the user who generated the auth token.
Below is my login route, where a user gets their auth token.
Login route:
router.post('/', validateLogin, async (req, res) => {
    const errors = validationResult(req)
    if (!errors.isEmpty()) return res.status(422).send(errors.array())

    let user = await User.findOne({ $or: [{ username: req.body.usernameEmail }, { email: req.body.usernameEmail }]})
    if (!user) return res.status(400).send('Invalid username/email or password')

    const validPassword = await bcrypt.compare(req.body.password, user.password)
    if (!validPassword) return res.status(400).send('Invalid username/email or password')

    const token = user.generateAuthToken()
    res.send(token)
})

Does anybody know the issue here? Thanks.


text:
Q: when arrays are implicitlly converted to pointers in c I have often heared that arrays are implicitly converted to pointers but
how and when it is needed . Do strings also implicitally converted to pointers?
A more common word i heared is array is decade into pointer so when and how it happens plzz show
programming example.

A: From the horse's mouth:

6.3.2.1 Lvalues, arrays, and function designators
...
3 Except when it is the operand of the sizeof operator, the _Alignof operator, or the
unary & operator, or is a string literal used to initialize an array, an expression that has
type ''array of type'' is converted to an expression with type ''pointer to type'' that points
to the initial element of the array object and is not an lvalue. If the array object has
register storage class, the behavior is undefined.

Given the following code:
char foo[]="This is a test";

printf( "Contents of foo = \"%s\"\n", foo );      // prints "This is a test"
printf( "Value of foo = %p\n", (void *) foo );    // prints address of first element
printf( "Value of &foo = %p\n", (void *) &foo );  // prints address of array
printf( "Size of foo = %zu\n", sizeof foo );      // prints number of bytes used
                                                  //   by foo

The type of the expression foo is "15-element array of char".  In the first two printf calls, the expression foo is not the operand of the sizeof or unary & operators, so it is converted to an expression of type "pointer to char" and its value is the address of the first element in the array; this pointer value is what gets passed to printf.
In the third printf call, the expression foo is the operand of the unary & operator, so the conversion rule doesn't apply; the type of the expression &foo is "pointer to 15-element array of char".  The last two lines will print the same value (the address of the array is the same as the address of the first element of the array), but the types are different.
In the last printf call, the expression foo is the operand of the sizeof operator, so the conversion rule doesn't apply; the result of the expression sizeof foo is the total number of bytes allocated to the array (15).
Note that the object designated by foo is an array, not a pointer; no storage is set aside for a pointer object apart from the array elements themselves.

A: when it is needed?
Often. It's convenient. For example strlen(s) looks less ugly than strlen(&s[0]), first is the implicit conversion, and both are equal
Do strings also implicitally converted to pointers?
yes.
Working with arrays and pointers is almost the same. there are differences:

*

*array variable can't be l-value

*sizeof(array) differs from sizeof(pointer)
function arguments, even when declared as arrays, are really just pointers. they can be l-value and sizeof() on them returns size of pointer

A: Its true that array expressions in C are generally converted to pointer expressions, and can be observed as such...  For example, given this simple demo code:
#include <ansi_c.h>
int main(void)
{
    int a[20]={2,3,5,8,6,4,3,2,1,7,8,9,0,4,6,7,8,9,0,2};
    char s[3][10] = {"one","two","three"};
    char *pS;

    pS = calloc (20, sizeof(char));//char array of 20 bytes, (string)

    strcpy(pS, "this is a string");

    printf("a[1] = %d\n", a[1]);
    printf("a (pointer) = %p\n\n", a);
    printf("s[0] = %s\ns[1] = %s\ns[2] = %s\n", s[0], s[1], s[2]);
    printf("s (pointer) = %p\n\n", s);
    printf("pS = %s\npS (pointer) = %p\n", pS, pS);

    free(pS);
    getchar();
    return 0;
}

Yields this output showing pointer (address of)  to first element of array a:


text:
Q: The rank of a matrix The original question is:
Show that the matrix $\Omega^{-1/2}X(X'\Omega^{-1}X)^{-1}X'\Omega^{-1/2}$, where $X$ is an $n\times p$ matrix and $\Omega^{-1}=\Omega^{-1/2}\Omega^{-1/2}$, is idempotent. What is its rank?
The first part is easy to show. But what's its rank?
Thanks in advance!

A: First note that, in order for $X^T \Omega^{-1} X$ to have the inverse, $X$ has to be of a full column rank, i.e., $X$ has rank $p \le n$.
Let us get some idea of the solution. We'll assume $\Omega$ to be symmetric (for the root to exist, this also means it's positive definite). Let $\Omega^{-1/2}X = U \Sigma V^T$ be an SVD of $\Omega^{-1/2}X$ Then
$$\Omega^{-1/2} X (X^T \Omega^{-1} X)^{-1} X^T \Omega^{-1/2} = U \Sigma V^T (V \Sigma^T \Sigma V^T)^{-1} V \Sigma^T U^T = U \Sigma (\Sigma^T \Sigma)^{-1} \Sigma^T U^T$$
also has rank $p$. This is most likely our solution., so let's get it, using a similar approach.
Let us assume that $\Omega$ is just nonsingular (not necessarily symmetric) such that $\Omega^{-1/2}$ exists. Let $X = U \Sigma V^T$ be an SVD of $X$.
We'll need some additional notation. Let $\tilde{\Sigma}$ denote the top left block of $\Sigma$ of order $p$, i.e.,
$$\Sigma = \begin{bmatrix} \tilde{\Sigma} \\ 0 \end{bmatrix}.$$
Furthermore, let
$$I_\Sigma = \begin{bmatrix} I_{p \times p} \\ 0_{(n-p) \times p} \end{bmatrix}.$$
Then $\Sigma = I_\Sigma \tilde{\Sigma}$ and $\Sigma^T = \tilde{\Sigma} I_\Sigma^T$. Note that $\tilde{\Sigma}$ is symmetric and nonsingular. Now,
\begin{align*}
M &:= \Omega^{-1/2} X (X^T \Omega^{-1} X)^{-1} X^T \Omega^{-1/2} \\
&= \Omega^{-1/2} U \Sigma V^T (V \Sigma^T U^T \Omega^{-1} U \Sigma V^T)^{-1} V \Sigma^T U^T \Omega^{-1/2} \\
&= \Omega^{-1/2} U \Sigma ( \Sigma^T U^T \Omega^{-1} U \Sigma )^{-1} \Sigma^T U^T \Omega^{-1/2} \\
&= \Omega^{-1/2} U I_\Sigma \tilde{\Sigma} ( \tilde{\Sigma} I_\Sigma^T U^T \Omega^{-1} U I_\Sigma \tilde{\Sigma} )^{-1} \tilde{\Sigma} I_\Sigma^T U^T \Omega^{-1/2} \\
&= \Omega^{-1/2} U I_\Sigma ( I_\Sigma^T U^T \Omega^{-1} U I_\Sigma )^{-1} I_\Sigma^T U^T \Omega^{-1/2}.
\end{align*}
So, $M$ has the same rank as $I_\Sigma ( I_\Sigma^T U^T \Omega^{-1} U I_\Sigma )^{-1} I_\Sigma^T$ which is a block matrix of a form
$$\begin{bmatrix}
(I_\Sigma^T U^T \Omega^{-1} U I_\Sigma)^{-1} & 0 \\
0 & 0
\end{bmatrix}.$$
Since $(I_\Sigma^T U^T \Omega^{-1} U I_\Sigma)^{-1}$ is nonsingular of order $p$, we conclude that the rank of $M$ is $p$.

A: Since $X'\Omega^{-1}X$ is an invertible $p\times p$ matrix, each factor in the product must have rank at least $p$. In particular, $n\ge p$. Since $X'$ is $p\times n$ and has rank $p$, its range is all of $K^p$, where $K$ is the underlying field (maybe $\mathbb{R}$).
It should be clear that the range of $X'\Omega^{-1/2}$ is $K^p$. Now following that with an invertible map $K^p\to K^p$, we conclude that the range of $(X'\Omega^{-1}X)^{-1}X'\Omega^{-1/2}$ is $K^p$ as well. So the range of $X(X'\Omega^{-1}X)^{-1}X'\Omega^{-1/2}$ is a $p$-dimensional subspace of $K^n$, since $X$ must be injective. Finally, $\Omega^{-1/2}$ is invertible, so it maps this $p$-dimensional space to another $p$-dimensional space, and it follows that the range of $\Omega^{-1/2}X(X'\Omega^{-1}X)^{-1}X'\Omega^{-1/2}$ is $p$-dimensional.


text:
Q: Creating a matrix for the following vector in R A vector contains the following numerical data after prime factorization of a certain number x:
c  <- c(2,2,2,3)

This is the prime factorization of 24
The first column of the matrix should contain the prime factors 2 and 3
The second column should contain the power of the prime factors.
e.g.
| 2  3 |

| 3  1 |

How would I go about creating this matrix.

A: With tabulate:
f <- as.integer(gmp::factorize(24))
cnts <- tabulate(f)[-1]
matrix(c(unique(f), cnts[cnts > 0L]), ncol = 2)
#>      [,1] [,2]
#> [1,]    2    3
#> [2,]    3    1

Or with table:
f <- table(as.integer(gmp::factorize(24)))
matrix(c(as.integer(names(f)), f), ncol = 2)
#>      [,1] [,2]
#> [1,]    2    3
#> [2,]    3    1

A: Here is a base R option by defining a function to factorize an integer, e.g.,
f <- function(n) {
  k <- 2
  v <- c()
  while (k <= n) {
    if (n %% k == 0) {
      v <- c(v, k)
      n <- n / k
    } else {
      k <- k + 1
    }
  }
  as.data.frame(table(v))
}

and you will see, for example
> f(24)
  v Freq
1 2    3
2 3    1

> f(46788)
    v Freq
1   2    2
2   3    1
3   7    1
4 557    1


text:
Q: Git strategy to backport bugfixes into older branches (cherry-pick vs. merge) We work as follows in our team:

*

*we have only a master branch in our GitHub repo, it's not stable - thinks get pushed there each day; for stable releases we use tags (for development, we use private forks on GitHub)

*we release a new minor version every 3 weeks, which contains bugfixes and new features (say 1.2.4, 1.2.5, 1.2.6...)

*we also have to maintain each minor old version for a limited amount of time (few months), so when someone uses 1.2.4 while the newest version is 1.2.7, and they find a bug, they can request us to fix the bug on the branch they use. Then we release a patch version, 1.2.4A.

*patches are rather exceptional. We usually do no more than 1-2 patches for the minor release. For most of the releases we don't do patches.

The question is, what's the best strategy to fix the bug on master and the old branch at the same time?
I can think of the two main strategies:

*

*Fix the bug on master, then checkout v1.2.4, then cherry-pick the appropriate commit (suppose the bugfix is one commit which always holds) and tag the resulting commit as v1.2.4A.

*Checkout v1.2.4, fix the bug and commit, tag the commit as v1.2.4A, and to incorporate it to master, do a merge.
I'm rather in favor of the first version (cherry-picking), but I would like to hear the other's comments about pros and cons.
Of course, things can get complicated when the commits in the middle introduce some major changes that can result in the fact that one can't create a commit which will work in both 1.2.4 and in master (for instance when some function name changed or more complicated things). But the more common situation is that the fix can be ported without problems.
Advantages of cherry-picking from master:

*

*I think the history is more "eatable" with cherry-picking. Consider this:
| <- bugfix done on master
|
|
| <- v1.2.7
...
|
|
|
|
|
|
|
|
|
|  - <- v.1.2.4A (cherry-picked from master)
| /
| <- v1.2.4

vs this:
| <- bugfix merged to master
|\
| \
|  |
|  |   <- v1.2.7
...
|  |
|  |
|  |
|  |
|  |
|  |
|  |
|  |
|  |
|  - <- v.1.2.4A (direct bugfix)
| /
| <- v1.2.4

Think of having dozens of commits in between. Consider having multiple patches applied like this in parallel. Half of the screen will be polluted.

*Let's say I fixed an issue on v1.2.4, but in a few days someone asks me for a patch on v1.2.3. Cherry-pick is the most sensible way to do it.
Are there any advantages of merging in our case that I overlooked? I can understand it preserves the connection between the two commits better than cherry-picking, but we keep a documentation of releases and all of this is also tracked there.

A: In open source projects that I've worked on, the consensus seems to be that fixes should land on master first, be tested there, and only then be back-ported to older releases. You can see this in how the Linux kernel does stable releases, for example: Developers submit patches for mainline but nominate them for inclusion in stable as well.
When cherry-picking in this situation, you probably want to use the -x flag:

When recording the commit, append a line that says "(cherry picked
  from commit ...)" to the original commit message in order to
  indicate which commit this change was cherry-picked from. This is
  done only for cherry picks without conflicts. ... [If]
  you are cherry-picking between two publicly visible branches (e.g.
  backporting a fix to a maintenance branch for an older release from
  a development branch), adding this information can be useful.

A: Your strategy 2, first fixing the bug on the prior release branch, e.g. v1.2.4 and then merging that change to your development trunk, is suggested by gitworkflows(7):

Rule: Topic branches
Make a side branch for every topic (feature, bugfix, …). Fork it off at the oldest integration branch that you will eventually want to merge it into. [emphasis added]
Many things can then be done very naturally:
To get the feature/bugfix into an integration branch, simply merge it. If the topic has evolved further in the meantime, merge again. (Note that you do not necessarily have to merge it to the oldest integration branch first. For example, you can first merge a bugfix to next, give it some testing time, and merge to maint when you know it is stable.)

One reason that this tends to work well is that in my experience, stuff gets added more frequently than it gets removed, so by making the change in the older branch, you avoid depending on any new functions etc. which may be available in the development trunk.
However you have to think about which branch you are targeting for the fix when you make the change, instead of just doing it on master and then deciding where to merge it.
Both strategies are viable and there are benefits to each.


text:
Q: Select date period in calendar year for several years by Pandas I would like to select date period in calendar for several years. So let's say from March 25th to August 25th every year. I was testing this approach: Filtering data for multiple years by date range given by months and days in pandas dataframe, however it is not working for me. Format of the date is datetime64[ns], so I am not quite sure what is wrong. I was testing different approaches and always end up working only with month selection without day limitations.
Here is my code snippet:
np.random.seed(0)
data = pd.DataFrame({'
    date': pd.date_range('1990-01-01', freq='d', periods=10000),
    'yield': np.random.randn(10000).cumsum(),
    'simulation': np.random.randn(10000).cumsum(),
    'Predicted': np.random.randn(10000).cumsum()})
out:
        date           yield    simulation  Predicted
0       1990-01-01     1.764     -0.202     0.330
1       1990-01-02     2.164     -1.035     0.330
2       1990-01-03     3.143     0.698      1.148
3       1990-01-04     5.384     0.889      1.576
4       1990-01-05     7.251     0.711     -0.928
...............................................
9995    2017-05-14  -186.162   111.432    -56.764
9996    2017-05-15  -186.119   111.323    -57.349
9997    2017-05-16  -185.602   111.266    -58.861
9998    2017-05-17  -185.635   110.207    -57.884
9999    2017-05-18  -184.337   109.880    -56.628

A: Try creating a Boolean index for each month's dates, then oring them together
import numpy as np
import pandas as pd

np.random.seed(0)
data = pd.DataFrame({
    'date': pd.date_range('1990-01-01', freq='d', periods=10000),
    'yield': np.random.randn(10000).cumsum(),
    'simulation': np.random.randn(10000).cumsum(),
    'Predicted': np.random.randn(10000).cumsum()
})

march_dates = (
        data['date'].dt.month.eq(3) &
        data['date'].dt.day.between(25, 31)
)
april_dates = (
        data['date'].dt.month.eq(4) &
        data['date'].dt.day.between(1, 25)
)
m = march_dates | april_dates

filtered_df = data[m]
print(filtered_df)

filtered_df:
           date       yield  simulation  Predicted
83   1990-03-25   -3.778287   11.467327   5.179931
84   1990-03-26   -2.290035    9.555657   7.388960
85   1990-03-27   -0.394146   10.490462   8.468163
86   1990-03-28    0.784634   11.336408   9.594991
87   1990-03-29    0.604709   11.454873   9.741437
...         ...         ...         ...        ...
9972 2017-04-21 -185.894256  103.212971 -62.513663
9973 2017-04-22 -186.199773  101.885143 -63.431743
9974 2017-04-23 -186.804921  101.908402 -63.195393
9975 2017-04-24 -186.580100  100.244993 -62.907841
9976 2017-04-25 -187.618573  100.814717 -62.071467

[896 rows x 4 columns]

A: You can use query function:
data.query("date >= '1990-03-25' and date <= '1991-08-25'")

Output:
          date     yield  simulation  Predicted
83  1990-03-25  3.871510    1.124867  -0.641264
84  1990-03-26  3.463583    1.308551  -1.727582
85  1990-03-27  2.730999    0.265739  -2.836030
86  1990-03-28  2.689405   -0.602710  -4.748007
87  1990-03-29  2.678018   -3.826888  -4.159625
..         ...       ...         ...        ...
597 1991-08-21 -1.645160    6.778537  -6.120725
598 1991-08-22 -2.304405    6.092513  -6.671160
599 1991-08-23 -3.955274    5.144826  -6.719812
600 1991-08-24 -3.554355    4.038627  -6.316459
601 1991-08-25 -4.692877    3.711540  -6.723403

A: Unfortunately you are not providing a reproducable example.

*

*You should make the date column the DataFrame index since this is the whole idea with DataFrames.

*Then you can easily apply the .month() and .day() methods to the index and filter them to your needs.

*If you're not familar with DataFrame indices, read the docs first,
e.g https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html


text:
Q: Why SMART is passing while it indicates failure for RAW read error rate? I have an external USB disk (WD Elements Caviar Green 2 To, WD20EADS-00W4B0) that started to fail (slow reads). My system logs didn't show anything unusual, this definitely indicates some supposedly serious problem.
To investigate, I've installed smartmontools, and checked SMART status. SMART passed but indicate the following issue:
...

SMART overall-health self-assessment test result: PASSED

...

1 Raw_Read_Error_Rate     0x002f   001   001   051    Pre-fail  Always   FAILING_NOW 64414

...

I've already started to clone my data (not before because this data is not highly critical), and will replace it in a few days. But I don't understand why SMART indicates passing, and not a WARNING instead since I believe the drive will soon die. Can you explain this to me ?
As a side question, would it be safe to reuse the drive after low-level formatting ?

A: Keep in mind, SMART is not a Pass/Fail kind of thing, but a set of stats that together can give you a general idea of a drives health. as such not all stats are created equal. Some are critical (high reallocated sector count) where as other are not so important.
Since this is the case, anyone who writes smart analysis software is making a decision as to which stats are important and which aren't, based on the stat itself and its value.
in this case, yes, I agree a Raw read error rate indicating a pre-fail condition is definitely cause for concern, and I would not trust that disk for much. I think the smartmontools folks should have flagged it as important, but they obviously choose not to.
No, this is a permant error (almost all SMART errors are permanent), so formatting should have no impact on the issue.  per this article, this error pertains to either the RW heads, or the disk platter surface, both of which would require replacement: http://www.ariolic.com/activesmart/smart-attributes/raw-read-error-rate.html