Nginx selects TLS version from another server

Question: nginx.conf:
events {
}

http {
    server {
        server_name {domain};
        listen 443 ssl;
        ssl_protocols TLSv1.2;
        ssl_certificate {path}.pem;
        ssl_certificate_key {path}.pem;
        return 200 'Success';
    }

    server {
        server_name _;
        listen 443 ssl default_server;
        ssl_protocols TLSv1.1;
        ssl_certificate {path}.pem;
        ssl_certificate_key {path}.pem;
        return 404 'Domain not found';
    }
}

Output of nginx -V:
nginx version: nginx/1.16.1
built with OpenSSL 1.1.1c  28 May 2019 (running with OpenSSL 1.1.1d  10 Sep 2019)
TLS SNI support enabled
configure arguments: {snipped}

Output of openssl version:
OpenSSL 1.1.1d  10 Sep 2019

With this setup, visiting {domain} displays "Success" over a TLS 1.1 connection. Why in the world is Nginx doing that, and how can I make it stop?
Answer: It's because the TLS is setup to include that protocol in the connector on port 443 as You configure that protocol on that ports connector. TLS is setup to allow v1.1 connections.
The choice of virtual host is only done based on server name.
To stop it You normally only enable tlsv1.2 and v1.3 for that port. The client then gets a proper SSL error that his protocols are not supported.
If You want to prevent the use of specific vhost if client does not offer 1.2 You can include a rewrite rule in the corresponding vhost that rewrites depending on value of variable $ssl_protocol. In that case You do not have a well behaving server because it completed handshake and afterwards returns error on application level. But it would do what You tried to do with Your above config.
I just found with OpenSSL 1.1.1 there is a functionality (SSL_CTX_set_client_hello_cb) that the (web)server could use to restrict TLS version depending on hostname.
However this is currenlty not implemented in nginx from what I can find.
Comment: If the protocol is per port, then why is it allowed as server-level config, and why does it always choose the second server's protocol? Swapping the two versions in the example results in a TLS 1.2 connection. And doesn't SNI let Nginx select a server before establishing a TLS connection?
Comment: The old SNI implementation doesn't really allow. The callbacks provided by OpenSSL (as example / default implementation) did not allow to adjust the SSL/TLS version anymore, thought SNI/ALPN allows it as the information is sent in client hello before the server needs to respond. This is my last sentence: in OpenSSL 1.1.1 there is a new function SSL_CTX_set_client_hello_cb which allows the application to install a callback that is called early enough to adjust this setting in the SSL context for that connection. this is not implemented in nginx till now.
Comment: For the other part it doesn't select the second servers protocol but configures the initial SSL context the listener using the default server for each defined ssl listening port (including certificate of default vhost, for example). After connection came in it sets all the ssl related options to the vhosts settings if ALPN/SNI is sent by client and a matching vhost is found. But at that stage with old callbacks OpenSSL wil ignore the protocol change. If one implements using the client_hello_cb instead of the older sni/alpn callbacks, this functionality will become available with current code.
Comment: Thank you. It's a shame Nginx doesn't document this.
Comment: It's just for consitency and Nginx tries to set it but OpenSSL does not honor. As a vhost can have a different listening port it must be definable in vhost. Of course there could be a check for this (so that it is only defined on the default vhost). And there is no need (but could be better documented). So as late as nginx implements client_hello_cb for new OpenSSL versions You can continue to use Your config and get the feature, but anyway Your default vhost which is generally documented as default (so for initial contact) must include all protocol versions You want to use within Your vhosts.
Comment: Yes nginx documentation is diffuclt. But it's very well documented, it's open-source ;-) And even OpenSSL itself does not document this issue good with the late running callbacks. So maybe nginx developer are just not aware, they try to set all settings from vhost. (But anyway I do not understand why to prefer nginx as long as the apache httpd is that fine it is until now ;-) )


Update webform submitted data through the DataBase?

Question: I see in the DataBase the table webform_submitted_data which contains the components's data of all webforms
But a token suddenly stop working as intended so the hidden fields of the webform, its data were incorrect for my use case. I fixed the issue but now want to update the affected submissions (luckly are only 10)
It is safe to update the respectives rows through a SQL statement? I do not need to trigger hooks, or other stuff, only need the correct data for the little code i write that uses it
Answer: Yes, that should be perfectly safe to do.
Take a backup first just in case, clear the cache after you've done it, and that should be fine.


How to open a port on a Google Cloud Compute Engine

Question: I have a Windows Server 2008 R2 instance, I want port 3000 to be accessible to the outside world. Here's what I have done so far.

I have configured that at the VPC network/Firewall Rules section. But still.
Comment: Are you trying to test a node app? Use `curl` and not `telnet`. Also make sure that your node.js app is running on `0.0.0.0:3000` and not `localhost:3000`.
Answer: Having the firewall rule open does not necessarily means a service will be listening on the other side.
Make sure you verify what ports are being listened on your Windows Server by following the tutorial in this post.
Then you should also verify the Windows firewall for blocking these ports.


$X=ABA^T$, X, A are matrix and need to solve matrix B by enforcing it as a diagonal matrix.

Question: $X=ABA^T$,
X is a square matrix and A is rectangular matrix and I need to solve matrix B by enforcing it as a diagonal matrix.
For non-singular matrix we can write B as $A^+XA^{+T}$, but B gets to be non-diagonal matrix. How can I get B as diagonal matrix. (Eigen decomposition of X gives different values of A).
Comment: Then we could just use the spectral theorem and take an orthogonal $A$ so that $X = ABA^T$ is an eigendecomposition
Comment: Is $X$ symmetric?
Comment: Yes X is symmetric ....
Answer: Here is an interesting property of the diagonalization operators
$$\eqalign{
 {\rm diag}(Z\,{\rm Diag}(y)\,W) = (W^T\circ Z)\,y \cr
}$$
where $\circ$ is the elementwise/Hadamard product, ${\rm Diag}(v)$ is a function which creates a diagonal matrix from its vector argument, and ${\rm diag}(M)$ creates a column vector from the diagonal of its matrix argument.
Applying this to your equation allows you to solve for $B={\rm Diag}(b)$ directly
$$\eqalign{
{\rm diag}(A\,{\rm Diag}(b)\,A^T) &= {\rm diag}(X) \cr
(A\circ A)\,b &= {\rm diag}(X) \cr
b &= (A\circ A)^+\,{\rm diag}(X) \cr
B &= {\rm Diag}\Big((A\circ A)^+\,{\rm diag}(X)\Big) \cr
}$$
where $M^+$ is the Moore-Penrose inverse of $M$.

Update

The diagonalization of $X$ throws away some information, so here is another relationship that uses vectorization, and therefore preserves all of that information.
$$\eqalign{
 {\rm vec}(Z\,{\rm Diag}(y)\,W) = (W^T\otimes u)\circ(v\otimes Z)\,y \cr
}$$ the vectors $(u,v)$ are vectors all of whose components equal unity; the dimensions are such that the products $Z^Tu$ and $Wv$ are defined; and $\otimes$ is the Kronecker product.
Reference for this operation can be found in: J Brewer, Kronecker products and matrix calculus in system theory, IEEE Transactions on circuits and systems, 1978. Link to pdf of paper from uta.edu
There the operation was defined in terms of the Khatri-Rao product, which results in $(W^T\otimes u)\circ(v\otimes Z)$.
Once again you can use this to solve for $B$
$$\eqalign{
{\rm vec}(A\,{\rm Diag}(b)\,A^T) &= {\rm vec}(X) \cr
(A\otimes u)\circ(u\otimes A)\,b &= {\rm vec}(X) \cr
b &= \big((A\otimes u)\circ(u\otimes A)\big)^+\,{\rm vec}(X) \cr
B &= {\rm Diag}\Big(\big((A\otimes u)\circ(u\otimes A)\big)^+\,{\rm vec}(X)\Big) \cr
}$$ note that $v=u$ for this problem and the dimensions of $u$ are such that $A^Tu$ is defined.
Comment: If $X=ABA^T$ is a strict equality (i.e. not just in a least-squares sense), then either of the methods proposed by @frank will work. Since the matrix dimensions in the 1st method are smaller, I'd use that one.
Comment: thanks a lot @frank.
Comment: @lynn ... if this is not a strict equality ... (least squares) then what will be the solution be?
Answer: If the problem is to find the diagonal matrix $B={\rm Diag}(b)$ which minimizes $$f(B)=\| ABA^T- X \|_F^2$$ then neither of @frank's results will work.
Instead solve for the vector $b$ which zeros the gradient of the function, i.e. $\frac{\partial f}{\partial b}=0$
$$\eqalign{
Y  &= ABA^T - X \cr
f  &= Y:Y \cr
\cr
df &= 2Y:dY \cr
   &= 2Y:A\,dB\,A^T \cr
   &= 2A^TYA:dB \cr
   &= 2A^TYA:{\rm Diag}(db) \cr
   &= 2\,{\rm diag}(A^TYA):db \cr
\cr
\frac{\partial f}{\partial b} &= 2\,{\rm diag}(A^TYA) = 0  \cr
\cr
{\rm diag}(A^TABA^TA) &= {\rm diag}(A^TXA) \cr
\big((A^TA)\circ(A^TA)\big)\,b &= {\rm diag}(A^TXA) \cr
\cr
 b &= \big((A^TA)\circ(A^TA)\big)^+\,{\rm diag}(A^TXA) \cr
 B &= {\rm Diag}\Big[\big((A^TA)\circ(A^TA)\big)^+\,{\rm diag}(A^TXA)\Big] \cr
}$$
where colon denotes the inner/Frobenius product, i.e. $\,A:B={\rm tr}(A^TB)$


Asymptotics of a recursive sequence

Question: I am asking for the asymptotics of a sequence $(a_n)_{n=0}^\infty$ defined by the following recursion relation
$$a_n = 1+\frac1{2^n}\sum_{k=0}^n {n\choose k}a_k,\, \forall n\in\mathbf N,\, a_0=0.$$
We can construct a generating function $f(x)=\sum_{n=0}^\infty \frac{a_n}{n!}x^n$.
$$f(x)=\sum_{n=0}^\infty \frac{a_n}{n!}x^n = \sum_{n=1}^\infty \frac{x^n}{n!}+\sum_{n=0}^\infty\sum_{k=0}^n\frac{a_k}{k!}\Big(\frac x2\Big)^k \frac1{(n-k)!}\Big(\frac x2\Big)^{n-k}=e^x-1+f\Big(\frac x2\Big)e^{\frac x2},$$
or
$$g(2x)=1-e^{-2x}+g(x)\Longleftrightarrow g(2^nx)-g(x)=n-\sum_{k=1}^ne^{-2^kx},\ g(x) := f(x)e^{-x}.$$
Is there an analytic expression for $g$? What is the aymptotics of $a_n$ as $n\to\infty$?

If there is an analytic expression, we can use the Cauchy residue theorem to analyze the asymptotics of $a_n$.
Answer: Let $h(x)=f(x)e^{-x}$. We have
$$h(x) = 1-e^{-x}+h\left(\frac{x}{2}\right)=\sum_{n\geq 0}\left(1-e^{-x/2^n}\right)=\sum_{n\geq 0}\sum_{m\geq 1}\frac{(-1)^{m+1} x^m}{m! 2^{mn}} $$
hence
$$ h(x) = \sum_{m\geq 1}\frac{(-1)^{m+1}x^m}{m!\left(1-\frac{1}{2^m}\right)}$$
and
$$ f(x)=\sum_{n\geq 0}\frac{x^n}{n!}\sum_{m\geq 1}\frac{(-1)^{m+1} x^m}{m!\left(1-\frac{1}{2^m}\right)}=\sum_{s\geq 1}\frac{x^s}{s!}\sum_{m=1}^{s}\binom{s}{m}\frac{(-1)^{m+1}}{1-\frac{1}{2^m}}$$
where
$$ \sum_{m=1}^{s}\binom{s}{m}\frac{(-1)^{m+1}}{2^{km}}=1-\left(1-\frac{1}{2^k}\right)^s $$
ensures
$$ f(x)=\sum_{s\geq 1}\frac{x^s}{s!}\underbrace{\sum_{k\geq 0}\left[1-\left(1-\frac{1}{2^k}\right)^s\right]}_{a_s}.$$
If we approximate $\left[1-\left(1-\frac{1}{2^k}\right)^s\right]$ with $\frac{s}{2^k}$ we have $a_s\approx s$. On the other hand the approximation  $\left[1-\left(1-\frac{1}{2^k}\right)^s\right]\approx \frac{s}{2^k}$ is accurate only for small values of $s$; $1-e^{-s/2^k}$ is much better. Using the explicit representation for $a_s$, numerical experiments suggest that
$$ a_s \approx A \log\left(B+Cs\right)\qquad \text{for }s\to +\infty$$
with $A\approx C\approx \sqrt{2}\approx\frac{1}{\log 2}$ and $a_s$ is clearly related to the Weibull distribution, appearing, for instance, in the Fisher–Tippett–Gnedenko theorem. Indeed, by defining
$$b_s=\sum_{k\geq 0}\left(1-e^{-s/2^k}\right) $$
we have
$$ b_{2s}-b_s = 1-e^{-s} \approx 1\text{ for large values of }s$$
and the only regular solutions of $b_{2s}-b_s=1$ are $b_s=D+\log_2(s)$.
Comment: Oh, darn, I should have run my last expression in the opposite direction just as you do in your first line... Anyway, you are right. Both the finite and infinite sums are good. Are you able to answer the main question, the second question, regarding the asymptotics of $a_n$ for large $n$?
Comment: The term between square brackets is approximately s/2^k, so such sequence has an approximately linear growth.
Comment: I am not so sure about that. What about the terms of $\big(\frac{s}{2^k}\big)^j$ for larger $j$'s? Bear in mind we are looking at large $s$.
Comment: @Hans: answer updated. $a_s$ behaves like $s$ for (very) small values of $s$ and is bounded by a multiple of $\log(s)$ for (moderately) large values of $s$.
Comment: Nice idea. 1) It is best not to mention the case for small $s$ which is obvious from the original recursion. 2) Could you please make the asymptotic argument, which I think is right, rigorous?
Comment: @Hans: to make it rigorous it is enough to introduce $c_s=b_s-\log_2(s)$ and to study the asymptotic behaviour of the function $$\sum_{k\geq 0}e^{-2^k s}$$ which over $s\geq 1$ clearly is $O(1)$.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/72398/discussion-between-hans-and-jack-daurizio).
Comment: Would you mind coming into the chatroom to continue the discussion? Even before looking at $c_s$, $b_s$ itself is an asymptotic approximation. We need to treat both approximations, in the final recursion.
Comment: +1 for the two analytic summation expressions and the good heuristic idea for the asymptotics. Thank you, Jack! However, it is still not a proof for the asymptotics. Are you still interested in providing a proof? If so, I will await your completion of the proof. If not, I will consider posing another question seeking proof. It would be appreciated if you could please let me know your intention. Thank you again.
Comment: Jack: Would you be interested in taking a look at this question https://math.stackexchange.com/q/3386637/64809 regarding asymptotics?
Answer: W. Szpankowski in 'Average Case Analysis of Algorithms on Sequences' treats this exact problem in Example 10.6.  The techniques used are Mellin transforms and analytic depoissonization (no probabalistic arguments).  His result is, up to the first 2 oscillatory terms,
$$a_n \sim \frac{\log(n) + \gamma}{\log2}+\frac{1}{2} + P_0 + \frac{1}{2n}P_2$$
$$ P_0 = \frac{1}{\log2}\sum_{k=1}^{\infty}\, \Gamma(\frac{2\pi\,i\,k}{\log{2}})\exp{(-2\pi i k \frac{\log{n}}{\log{2}})} +\Gamma(\frac{-2\pi\,i\,k}{\log{2}})\exp{(2\pi i k \frac{\log{n}}{\log{2}})}.$$
$$ P_2 = \frac{1}{\log2}\sum_{k=-\infty}^{\infty}\, \Gamma(2+\frac{2\pi\,i\,k}{\log{2}})\exp{(-2\pi i k \frac{\log{n}}{\log{2}})}  $$
About 4 digits agreement are obtained for $n$ as small as 15. The problem is stated in Jack D'Aurizrio's alternate expression for $a_n,$
$$ a_n = \sum_{k=0}^{\infty} \big(1-(1-2^{-k})^n\big) .$$
Comment: Excellent. +1 Thank you.
Comment: Would you be interested in taking a look at this question https://math.stackexchange.com/q/3386637/64809 also regarding asymptotics?

Asymptotics of a recursive sequence


Can a commutative ring $R$ with identity be isomorphic to the product ring $R\times R$?

Question: This is a simple question, but I have no idea with this. Can a commutative ring $R$ with identity be isomorphic to the product ring $R\times R$?
It is clear that this is not true when $R$ is an integral domain, because $R$ has no zero divisors while $(0,1)(1,0)=0$ in $R\times R$. But does this still false in the general case?
Comment: Please search for your questions first. This one was at the top of the list of related questions on the right hand side column.
Answer: Just take a non-zero ring $S$, and consider the infinite Cartesian product
$$R=S\times S\times S\times\cdots.$$
Now, are there any Noetherian examples?
Comment: Thanks. You mean that there are no counterexamples when $R$ is Noetherian?
Comment: I think there are no Noetherian counterexamples; in any case it's a good follow-up question!
Answer: There are counterexamples, the easiest being from to the observation that $R^{\Bbb N}\times R^{\Bbb N}\cong R^{\Bbb N}$


What does Contextual Filters (in Views) serve for?

Question: I was playing with filtering content using views but seems I can't make them work the way I want : to display the articles of an edition based on the latest issue no. (or latest issue date) on the frontpage. I figure out this can be done using contextual filter but don't know how.
My content types are:
editions: edition_no, edition_date, edition_title
article: title, body, edition_no.
Many thanks for help.
Answer: Contextual filters in Views 3 replaces the 'Arguments' of Views 2.
It's best used with paths as outlined in this video: http://nodeone.se/blogg/learn-views-with-nodeone-part-19-contextual-filters-with-paths.
By the sounds of it, the filtering of your view could do the same job.


How to render the table from SQL Server into front page

Question: I use node express app with the mssql package (https://www.npmjs.com/package/mssql) to read data from my Azure SQL Server database. In general, I could read the table in the database, however, I don't know how to visualize the table into front page which I use handlebars template for node.
Here is my code:
routes/index.js
const express = require('express');
const router = express.Router();
const config = require('../dbconfig');
const sql = require('mssql');

// Get homepage
router.get('/', function(req, res) {

  // Read data rows from the database (dbo.lendbook table)
  new sql.ConnectionPool(config).connect().then(pool => {
    return pool.query `select * from dbo.lendbook`
  }).then(result => {
    res.render('index');
      // Output the data which was read in the terminal:
    //  console.dir(result);
  }).catch(err => {
    console.log(err);
  });

views/index.handlebars

Dashboard

Welcome to your dashboard

{{#each rows}}

{{item}}

{{/each}}

This is the table from the database I could read by the function above

Answer: Try this:
routes/index.js
new sql.ConnectionPool(config).connect().then(pool => {
    return pool.query `select * from dbo.lendbook`
}).then(result => {

    res.render('index', {
        rows: result.recordset
    });

}).catch(err => {
    console.log(err);
});

views/index.handlebars

Dashboard

Welcome to your dashboard

    {{#each rows}}

            {{this.id}}
            {{this.rate}}
            {{this.amount}}

    {{/each}}


Print specific field of a specific node

Question: I have the content type of "Front Page Section" where there are the fields "body" and "field_home_section_photo".
On the home page (page--front.tpl.php) I would like to be able to print the body and image fields separately for particular nodes with their formatting in place:

Print Node 42 Body

Print Node 42 Image

Print Node 43 Body

Print Node 43 Image

Print Node 44 Body

Print Node 45 Image
Answer: You can do this by hook_preprocess_node(&$vars) function. By this function you can check the Node ID then if it is some custom IDs, fetch the appropriate data and assign them in $vars array.
In the aggregate we have
function THEME_preprocess_node(&$vars){
    if(drupal_is_front_page() == true){
         if($vars['node']->nid == 44){
             $newNode = node_load(45);
             $wrapper = entity_metadata_wrapper('node',$newNode);
             $image = $wrapper->field_home_section_photo->value();
 //here use kpr($vars) to get the correct syntax of  field_home_section_photo in $vars
// suppose it is $var['fields']['field_home_section_photo']->value
              $var['fields']['field_home_section_photo']->value = $image;
           }
      }
}

don't forget to install entity module.
Comment: Does the above code go into the template.php file? If so what code do I use in the page--front.tpl.php?
Comment: Yes it goes. This function (hook) is triggered before loading any node. Because you are displaying set of nodes on front page so this function is triggered in that time as well. You dont need to do anything in front page, just adjust this function with your website fields
Comment: I corrected the code
Answer: If you're not familiar with the module layer of drupal I would suggest using the views module to build a view page of all the nodes of type "Front Page Section" and use this as the front page.
https://www.drupal.org/project/views
Comment: The Views module doesn't work here. For node id = 44 he wants to print body with id=45 and image with id=44.
Comment: Exactly @Suranga. So for e.g. 'load node=42;Print node body; Print node image;end;Load node 44;print node body;print node image;end'
Comment: @IamOnStage Why wouldn't a view of 'fields' (body and Image) of all nodes of  the type "Front Page Section" work? Because your question seems to imply that it would.
Comment: I wanted to hard code into the front page the display of certain nodes which would allow more specific HTML wrapper of the image and body content (as views adds in loads of extra rubbish) it is just just drop the fields into some clean Bootstrap columns. Also from a permission point of view.

Print specific field of a specific node


window.open from iframe erases page's contents

Question: I have a website with an iframe. In the iframe, I have a button that should, when clicked, open a new browser window to the specified URL. The good news is - it does, the bad news is that on the launching page, all content gets erased (I checked the source code of it and only the closing body and html tags remain). The environment is IE9. I don't want to have to screenshot a button then make it a link and img, I shouldn't have to do that in 2012!!!
Please help!!
The code I'm using is:
<code><button onclick="window.open('admin.php')">ADMIN</button>
</code>
Comment: You can keep your button in the form, if you want. Just set `type="button"` for your button.
Comment: The page has PHP in it which is stripped before it gets to the browser, and that's just to display some error message after searching the database. There's no other javascript in the page. I'm a hand coder and have triple checked that there are no missing speech marks or arrows.
Comment: Ok cool, I figured it out. I had the button within a form, removed it from the form and it works like juice.
Answer: I had the button within a form, removed it from the form and it works like juice.


Big Data: Which HD Parameters are Important?

Question: I work with a lot of datasets that are in the tens of GBs, usually split into several files. Performing any type of dataside-wide operation (grep, sed, search, read/write to/from databases and Hadoop) on these files is of course very slow and time consuming. Until now, I have been using whatever HD I can get for a good deal - typically Seagates at 5400rpm or 7200rpm.
It is time for me to upgrade the HD. What parameters should I be looking at for the type of work I described? Spindle speed? Interface? Seek time and throughput? I have read various things that some of them do not matter so I am confused.
I can provide more info if this is not enough.
Answer: Use more than one disk if you can - stripe them at the OS level or get Hadoop to distribute the data over multiple drives - having more than one spindle seeking will massively improve performance, and be cheaper than SSD.
Answer: Spindle speed is certainly important, as is seek time. But the most important thing for dealing with massive database files is the ability for random read/writes (that is, taking a lot of data from all different areas of the disk, as opposed to Sequential Read/Write, where all the data is in order on the disk)
This is where SAS absolutely excels. With a normal IDE or SATA disk, if you have four pieces of data that are non-sequential, and the requests are received in a certain order, then the drive has to do an entire revolution to pick up each individual piece of data.
With SAS, the controller will order the request in the order that they can best be serviced, and will order then so that multiple pieces of data can be picked up in a single revolution if possible. So just because the requests come in as A B C D, the SAS drive might serve them in A D C B, because that's the order that they are on the physical disk. A normal SATA/IDE drive can only serve them A B C D even though this is not an optimal order.
Comment: Do you mean command queueing? Newer SATA drives do that as well, not just SAS...
Comment: No, I mean re-ordering the commands into their optimal order, so that multiple chunks of random data can be retrieved within a single revolution.
Comment: Unfortunately the only reference I can find to this on the intertron at the moment is a forum: http://www.tomshardware.com/forum/248547-32-raid-sata#t1760727 - hardly admissible in court, but I know I've read about this elsewhere.
Comment: It is bullshit. SAS can queue a LOT (2 billion outstanding per protocol and disc, though most discs can not handle that). But SATA standard for 10 years has "NCG" (Native COmmand Queueing" which does the same for a 32 command limit. SAS IS better -but please try sticking to facts.
Answer: Seek time is not that important for entire-data scanning/analysis operations (assuming you use flat files or modern scalable database like Hypertable, instead of traditional B-Tree* based database which would require significant random seeks to scan large tables. If you rely on random I/O of hard drives to deal with large data set, you'd certainly be doing it wrong.
The most important factors for this type of work is raw sustained (uncached) sequential read/write throughput and the ability to handle multiple scans at the same time without degrading to random I/O patterns. There is a good benchmark from one these benchmark sites for 1+TB SATA drives. It showed that Seagate and Western digital drives are pretty good at handling multiple scans while Samsung drives degrades dramatically when there are more than one scan going on.
Answer: Solid state drives woul really help you here, if you can afford them.


Friedman's test is very significant, but its post hoc comparisons are not significant

Question: This post does not include an answer for my question.
I have perform a Friedman test on a results obtained by several methods on multiple datasets, as described in this paper: "Statistical Comparisons of Classifiers over Multiple Data Sets"
The Friedman's statistic is (16.667) which exceeds the Chi-Square critical value (14.067) so the null hypothesis H0 (no difference between the methods) must be rejected. However, when I used a post-hoc test (Shaffer test) to identify the differences, All the adjusted P-values obtained by Shaffer test are bigger than  level of significance 0.05. This means that there are no statically significant differences between the results obtained by these methods.
Is this result correct or not? Why the H0 is rejected at the first stage, then not rejected at the post-hoc test?
If this result is correct, what does it mean?
Original Data:
    Data sets,Method1, Method2, Method3, Method4, Method5, Method6, Method7, Method8
    F1,1.3708E-01,1.0227E-01,1.2801E-01,1.0512E-01,1.4476E-01,1.1309E-01,1.4002E-01,1.2801E-01
    F2,2.2731E-01,2.2758E-01,2.1174E-01,2.2516E-01,2.1865E-01,2.1740E-01,2.2620E-01,2.1174E-01
    F3,8.6773E-02,8.5749E-02,8.1918E-02,8.5238E-02,8.7778E-02,8.3436E-02,8.9080E-02,8.1918E-02
    F4,1.7313E-01,1.7626E-01,1.6378E-01,1.8294E-01,2.0685E-01,8.0293E-02,2.0000E-01,1.6378E-01

Average Ranks:
Method1  3.25
Method2  4.25
Method3  6.5
Method4  4.75
Method5  2.25
Method6  6.5
Method7  2
Method8  6.5

Adjusted P-values:
0.262494
0.262494
0.262494
0.296897
0.296897
0.296897
1.272641
1.272641
1.272641
1.797619
2.382635
3.102894
3.102894
3.102894
3.102894
3.22677
3.747857
3.747857
3.747857
3.747857
3.763891
3.94592
3.94592
3.94592
3.94592
3.94592
3.94592
3.94592

Addition information
According to that paper, "If the null-hypothesis is rejected, we can proceed with a post-hoc test." A a post-hoc test is used to identify which pairs of algorithms are significantly different than each other. Thus, in a multiple comparison, all possible pairwise comparisons need to be computed (N × N comparison). The number of possible comparisons in an all pairwise comparisons is N(N-1)/2. So we have 8(8 - 1)/2=28 hypotheses and an adjusted P-Value for each hypothes.
Comment: For all that you deny the relevance of the linked question, a number of points made there are relevant here.
Answer: Friedman's test and the ad hoc test use somewhat different distributions and criteria. In any case, Bonferroni ad hoc tests can be too conservative (not likely enough to reject), especially if you are making several ad hoc comparisons.
You do not give the P-values, the number of levels, level means/medians for the Friedman test, or ad hoc adjusted P-values. So it is not possible to give more than a guess at he particulars, trying to answer your question.
Here is my guess: It looks as if the main Friedman test may have been significant at something like the 2% significance level with maybe 8 levels of the main factor, and the most nearly significant ad hoc test may have been significant at something like the 7% level (adjusted). If so, the results may be annoying, but not wrong--or even entirely unexpected.
qchisq(.95, 7)
[1] 14.06714
1 - pchisq(16.67, 7)
[1] 0.01965259

If the overall Friedman test is significant, then it is reasonable to guess that
the two levels with the greatest difference in location must be significantly different, but you may not be able to test for sure how locations of the (8 or so) levels are ranked.
In doing a 'power and sample size' analysis, in advance of taking data, one should try to determine how many 'blocks' are needed for ad hoc tests with a desired effect size to be detectable. This is not always easy to do.
Addendum. I see that you have appended a couple of dozen "adjusted" P-values to your question. Perhaps you will get more satisfactory results if you make only the very few most important ad hoc comparisons. You seem to be paying a very heavy Bonferroni adjustment penalty for making so many.
Comment: If you found this answer helpful, then please consider
[upvoting](https://stats.stackexchange.com/help/why-vote)
and/or
[accepting](https://stats.stackexchange.com/help/accepted-answer)
it.
Comment: could you please check the question, I have included the average ranks and the adjusted P-values.
Comment: Saw them. See my corresponding Addendum. Maybe confine comparisons to the most important among Methods 3, 6. 7. and  8.
Comment: could you please check the Addition information. If this result is correct, what we can conclude from the statistical analysis? Are these methods have the same performance or different, and how to determine which method is better?
Comment: I have included the original data (at the top of the question).
Comment: Thanks for data. I verified the P-value of the Friedman test, but am not familiar with your specific method of _ad hoc_ testing and did not verify the 28 P-values you give in your question. Perhaps see [this page](https://www.sheffield.ac.uk/polopoly_fs/1.714578!/file/stcp-marquier-FriedmanR.pdf) to compare your results with another method of _ad hoc_ testing. Only 4 obs/meth, so difficult. // Method medians round to `0.155 0.139  0.146 0.144 0.176 0.098 0.170 0.146` where Method 6 stands out as smallest. Could not verify your 'Average Ranks.' // Sorry, but will have to leave it at that.
Comment: I have used the KEEL tool [link](https://sci2s.ugr.es/keel/download.php) to calculate the Average Ranks and perform the Shaffer post-hoc test. Thank for your help.


Prove $a^n \rightarrow 0$ as $n \rightarrow \infty$ for $\left|a\right| < 1$ without use of log properties

Question: $a^n \rightarrow 0$ as $n \rightarrow \infty$ for $\left|a\right|  < 1 $

Hint $u_{2n}$ = $u_{n}^2$
I have totally no idea how to prove this, this looks obvious but i found out proof is really hard...
I am doing a real analysis course and there's a lot of proving and I stuck there.
Any advices? Practice makes perfect?
Comment: Does $a_n=a^n$ for all $n \in \mathbb{N}$?
Comment: It's unclear what is $a_n$.
Comment: should be $a^n$ sorry
Answer: Replacing $a$ by $|a|$, one can assume without loss of generality that $a$ is a nonnegative real number. If $a=0$, the result is direct. If $0\lt a\lt1$, the sequence defined by $u_n=a^n$ is decreasing and positive hence it converges to some finite nonnegative limit $\ell$. Since $u_{n+1}=au_n$, $\ell=a\ell$. Since $a\ne1$, the only possible limit is $\ell=0$, QED.
The hint that $u_{2n}=u_n^2$ can probably be used as follows, once one knows that the limit $\ell$ exists and is finite: $\ell=\ell^2$ hence $\ell=0$ or $1$ and, since $u_n\leqslant u_1=a\lt1$ for every $n\geqslant1$, $\ell\ne1$ hence $\ell=0$.
Answer: Proof sketch:  Maybe try showing that $|\frac{1}{a^n}| \to \infty$.
Fix $p = |\frac{1}{a}| > 1$, and let $p = ( 1 + b )$.  Show by induction that $p^n \ge 1 + nb$, and conclude the statement above using the Archimedean property of the reals.
Answer: Since $0\le|a|\lt1$, we have $0\le|a|^{n+1}\le|a|^n$. Since $|a|^n$ is a non-increasing sequence, bounded below, $A=\lim\limits_{n\to\infty}|a|^n$ exists. Then,
$$
\begin{align}
|a|A
&=|a|\lim_{n\to\infty}|a|^n\\
&=\lim_{n\to\infty}|a|^n\\
&=A
\end{align}
$$
Thus, $(|a|-1)A=0\implies A=0$. Therefore,
$$
\left|\lim_{n\to\infty}a^n\right|=\lim_{n\to\infty}|a|^n=A=0
$$
Answer: Let $u_n = a^n$ with $|a|< 1$
Let $v_n=|u_n|$
$v_{n+1} = a v_n < v_n$ so $(v_n)$ is decreasing
$0 \le v_n$ so $(v_n)$ is minored
Since $(v_n)$ is minored and decreasing, it converges.

Now let $v_\infty=\lim\limits_{n\to \infty}v_n$
You have $v_{n+1} = a v_n$
By making $n\to \infty$ on both sides (which you can do because $x\mapsto ax$ is continuous) you get:
$v_\infty = a v_\infty$
$0 = (a-1) v_\infty$
But $|a|<1$ so $a-1\not= 0$ so $v_\infty=0$

That is $|u_n|\underset{n\to\infty}{\longrightarrow}0$
So we can conclude that $u_n\underset{n\to\infty}{\longrightarrow}0$


I want my Dialogflow bot to say a message which includes the result from a MongoDB query

Question: I am querying a collection in MongoDB from Dialoglow Fulfillment. I then want my bot to respond with a message which includes this query. The code in the function of the Dialogflow Fulfillment is:
function readRecord(agent){
var name;
MongoClient.connect(uri, function(err, client) {
   const collection = client.db("test").collection("data");
    collection.find({fname: 'Example'}).toArray(function(err, result){
        if (err) throw err;
        console.log(result);
        name = result.lname;
        agent.add("Found last name: ", name);
    });
    client.close();
});

}
When I run this I get no response from my from the bot. When I console.log(result) the information is there but I can't seem to get the bot to say it.
Answer: The issue is that the intent handler expects you to return a Promise if you are doing any asynchronous functions - like accessing a database. The easiest way to do this is to change from using callbacks with MongoDB to using versions of the functions that return Promises, and then to return the promise.
I haven't tested, but something like this might work
return MongoClient.connect( uri )
  .then( client => {
    const collection = client.db("test").collection("data");
    return collection.find({fname: 'Example'}).toArray();
  })
  .then( result => {
    let name = result[0].lname;
    agent.add("Found last name: "+name);
  });

Comment: Thanks that worked for me. The one change I made let name = result[0].lname instead of let name = result.lname
Comment: Thanks. I had based the code on your original, and I've now updated it.


Problema ao usar 'Google Fonts'

Question: Gostaria usar uma fonte da Google sem precisar de Conexão (internet). Vi que o @font-face tem esse poder. Basta apenas baixar a fonte em um dos formatos (preferi o .EOT por também ser aceito pelo IE Browser) e declarar da seguinte forma:
@font-face {
  font-family: 'VT323';
  font-style: normal;
  font-weight: 400;
  src: url('../fonts/VT323-Regular.eot');
  src: url('../fonts/VT323-Regular.eot?#iefix') format('embedded-opentype'),
       url('../fonts/VT323-Regular.ttf') format('truetype');
}

Onde url é onde está localizado o arquivo da fonte.
E para fazer uso dela deve-se apenas chamar o font-family, obviamente, com o nome declarado no @font-face:
.home-text {
    font-family: 'VT323', cursive;
    text-align: center;
    font-size: 1.4em;
}

Contudo, ainda não consigo gozar da fonte VT323. Os códigos acima são originais do meu projeto. Segue abaixo a estrutura dos diretórios dos arquivos (informação adicional):
Comment: @josepostiga a [w3schools não é uma boa referência](http://www.w3fools.com/)
Comment: Tenta usar todos os formatos, isso ajuda até na compatibilidade
Comment: Tentou adicionar o `font-weight: 400` também no `.home-text`?
Comment: Tentei agora e não mudou o cenário.
Comment: Funciona se você pôr a fonte no mesmo diretório que o arquivo CSS (e mudar a declaração ```font-face``` pra refletir isso)? Qual seria a situação aonde você usaria isso? Seria possível instalar a fonte no sistema? Se for, será que não é mais prático dessa forma? Qual navegador você está usando?
Comment: tente usar 'fonts/VT323-regula...' ao invés de '../fonts/VT323-regula...'
Comment: @Leandro, Já usei esse site pra converter de '.ttf' para '.eot', não faz sentido converter novamente.

George, não mudou o cenário. Existe um classe nesse mesmo arquivo '.css' que usa um arquivo externo no mesmo nível que essa fonte. O 'source' do mesmo estava da forma que eu 'repliquei' no código da dúvida.
Comment: Tenta converter a font para o formato web fonts, uso esse site para converter http://www.fontsquirrel.com/tools/webfont-generator
Comment: Já tentou mudar os nomes das fontes para letra pequena e actualizar, obviamente, na url? Segundo a W3Schools, fontes com letras maiúsculas podem ter comportamentos estranhos, especialmente em IE. Reparei que, na última declaração da propriedade src tem **'** em vez de **'**. Pode não ser nada, mas mantém a consistência. **EDIT** Reparei agora que no código tem a fonte com o nome VT323-Regular.eot mas na imagem com os directórios tem o nome VT323-regular.eot. Altere para reflectir a realidade, se não for um erro ortográfico aquando a criação da imagem.
Comment: Coloquei os arquivos na pasta do CSS e fiz as devidas alterações inclusive renomeá-las para minúsculo. Nenhuma alteração no cenário.*** Acho que esse é um daqueles erros tão óbvios que não é fácil de enxergar... rsr
Comment: O Google Fonts detecta o user agent na hora de carregar as fontes: baixou o código usando mais de um navegador? Ainda, se o código for realmente o original, por que tem 'aspas curvas' nele?
Comment: @PhellipeLins recentemente resolvi um problema parecido. A solução está nas Respostas abaixo. De qualquer forma copiei e colei seu CSS num arquivo e fiz um hexdump -x e o caracter ' (plic) usado na sua solução na seção `@font-face` parece não estar correto.
Answer: o SkyFonts permite você sincronizar fontes do GoogleFonts com seu Desktop.
No MAC OS X o SkyFonts baixa os fontes para a pasta ~/Library/Application Support/skyfonts-google e você pode copiar para a pasta /css/fonts do seu site.
Obviamente você não precisa usar SkyFonts, basta fazer o Download. Eu uso por comodidade na gestão de Fonts nos meus Computadores.
Agora ao problema do VT323. O procedimento abaixo eu testei no Chrome e Safari.
Crie um arquivo css em /css/vt323.css com o seguinte conteúdo:
@font-face {
  font-family: 'VT323';
  font-style: normal;
  font-weight: 400;
  src: local('VT323'), local('VT323-Regular'), url(VT323-Regular.ttf) format('ttf');
}

No seu HTML coloque as seguintes linhas de código no :
<link href="/css/vt323.css" rel="stylesheet">

Abaixo uma ilustração de como pesquisar e sincronizar o fonte VT323 com seu Desktop usando o SkyFonts.
Comment: Mas isso seria tudo feito localmente?
Comment: Na minha proposta de solução eliminamos a dependência do usuário com uma conexão com a Internet para baixar os fontes de um site tal como o  http://fonts.googleapis.com. Recentemente tive de fazer isso para evitar que a página congelasse numa Intranet devido a queda do link com a Internet.
Answer: Já tentou o IcoMoon?
Tem ótimos recursos para editar e baixar arquivos de fontes.
Eu uso primariamente para criar ícones como fontes mas acredito que possa ser usado como fontes para escrever textos (bem, na pior das hipoteses você terá que "desenhar" as letras que você vai precisar).
Tem bons exemplos e talvez você possa usar como referência.
Comment: Não pretendo driblar o problema, quero resolve-lo!

Problema ao usar 'Google Fonts'


how do i check the RAM on my Ubuntu sever?

Question: I'm using an old laptop that originally had 512MB of RAM and installed Ubuntu Server 12.04
I upgraded the old 512MB memory card to 1GB memory card, and now i just want to check how much RAM my "laptop Ubuntu Server" actually recognized...
If someone knows the Ubuntu Server command to checking RAM that is being recognized, please let me know...
Thanx in advance.
Comment: I'm not sure why both of the below answers were down voted. Both of the are ways to accomplish what you asked. Regardless, I've +1'ed both of them.
Comment: Welcome to Server Fault! Your question is off topic for Serverfault because it doesn't appear to relate to servers/networking or desktop infrastructure in a professional environment. It may be on topic for [Superuser](http://superuser.com) but please [search](http://superuser.com/search) their site for similar questions that may already have the answer you're looking for.
Comment: @EEAA Someone might be downvoting answers to questions that they feel should be flagged+ignored (perception of rep farming I guess), but that's kinda malicious and not really how it's supposed to work. Threw in a +1 of my own.
Comment: @EEAA, throw in 2 for me too. The answers are fine.
Answer: Would
cat /proc/meminfo | grep MemTotal

work for you?
Answer: In addition to the previous command you can also use: free


Widget without using SwiftUI

Question: Is it possible to create a widget in iOS 14+ without using SwiftUI? When adding the target it doesn't give you the option between storyboard and SwiftUI like it does when creating a new project. Is it possible to build out a Widget using Storyboard or XIB?
Comment: You can only use SwiftUI for building widgets. This post lists the types of views that you can use when building a widget https://stackoverflow.com/questions/63135404/why-do-some-views-appear-as-a-red-no-entry-sign-in-widgets
Answer: No, it's not possible to create a widget without using SwiftUI. Here's what Apple's documentation says:

To implement a widget, you add a widget extension to your app. You configure the widget with a timeline provider, and use SwiftUI views to display the widget's content. The timeline provider tells WidgetKit when to update your widget's content.
Comment: I hate my life.
Comment: Can we add widget using SwiftUI in Swift project ?
Answer: If you just want to create a widget without an app, you could use Scriptable, where you write your code in JavaScript and can use native components for your UI.
Comment: any affiliation? [/help/promotion](/help/promotion)
Comment: Is this a valid technical solution, or a generic approach? WidgetKit has some specific requirements.

Widget without using SwiftUI


How to start a service without the need to change password

Question: We have developed a backup software for a SQL Server(2019) that runs on a Windows Server 2019 for a customer.
The app (.net Windows Forms) has an interface to configure the backups (e.g. select day's for backup, backup times every day, and so on) and further configuration's (data to SMTP-Server, mail distribution list, and so on). Further the client contains functions to restore database.
The backups are started over a timer.
The App works fine, but has to run 24/7/365.
Problem description:
The app run's on a customer server and the customer don't allow accounts where the password never expire.
Further the server is (at least) rebooted every two weeks automatically.
So... we have to access the server and start our client new at least every two weeks, what is not nice.
Therefore, we think about to "split" the backup App in two parts:

Windows Client (with deactivated backup and E-Mail functions)
Windows service (read the config files at startup, do the backups, send E-Mails)

=> Target: The Service to the backup is started automatically after a server reboot (no need to start in manually).
Needs:
The Service need to have access to the local disk (read (.ini) configuration file, store the backups), to the SQL-Server (installed on the same server) and to the SMTP-Server (located on another customer server) to be able to send E-Mails.
As mentioned above, the target is to use a "system account" without password (that has to be changed periodically).
We are developers, not system engineers... therefore the "starter questions":
As far as we know, there are System accounts for "Local System", "Local Service" and "Network Service" (maybe there are more...).
Question:
Has one of the above mentioned accounts all needed rights (or is there another)?
Thanks!
Answer: Yes, you absolutely need to have the interactive "configuration" and "service" parts separate.  The Service part needs to run all the time, the configuration part only as and when needed.
The idea of having an application running "on the console" of a Windows Server these days is troublesome, at best, and gets harder with each version of Windows.  Having produced Windows Services that are still in Production 20 years on, I'm a little surprised you didn't come across this "challenge" during development and testing.
But anyway ...

The app run's on a customer server and the customer don't allow accounts where the password never expire.

Given that Windows supports numerous, "system" accounts whose password never expire, this is a strange "Requirement" to have inflicted on your application.
Question: Is this "Requirement" actually relevant?
To use the "configuration" app, you would need to log into the machine, so you'd use whatever credentials you were given for this purpose - those, interactive, User-specific, credentials should expire periodically.
The "service" part should just run and do stuff.
If these system accounts had expiring passwords, the Windows ecosystem would be utterly unusable.

The Service need to have access to the local disk (read (.ini) configuration file, store the backups) ...

Yes, absolutely.
Any of the "Service" accounts should have this level of access.

... and to the SMTP-Server ... to be able to send E-Mails.

Access to anything "off" the box requires a Network-aware account.
Network Service is probably your best bet.

... to the SQL-Server (installed on the same server) ...

Danger, Will Robinson!
Are you seriously saying that your "backup" utility is taking and storing SQL Server backups on the same machine as the SQL Server instance itself?
This undermines your whole solution.
If you lost the machine on which SQL Server was running, then you'd also lose the backups of your database as well and, since the only reason that backups exist is to guarantee that you can get the database back no matter what goes horribly, horribly wrong, then your "backup solution" is completely compromised.
You absolutely must get the backups off of that server and onto a.n.other machine, well away from the databases that they are protecting.
Comment: Thanks for your reply. So.. I think, I should go with the Network Service. Regarding the backups on the same machine: You're principally right, but the server is a VIRTUAL server that is backed up every hour from the IT of the customer. So... we already would have a backup (of the whole server), but the IT of the customer mandatory wanted a logical backup in advance. So the backup of the backups is guaranteed.
Comment: Database != File.
A backup of the server is only good as of the Point in Time it was taken.  SQL Server backups allow /far finer/ granularity of Recovery.
And just because something is a VM Guest DOES NOT make it safe from the *VM Controller* deciding, one day, to randomly "scribble" all over its disks - the same disks that hold the disk images of the running, VM Guest machines, utterly trashing them in the process!  Been there.  Seen it.  Not pretty.  I would suggest that your Recovery Strategy needs a bit of "fine tuning".
Comment: I have successfully developed the windows service now and start it under the network  service. Anything works, but I had to grant the network service in addition some rights in the file system. I have accepted your answer now. Thanks again.


How can i enable automatic path creating for all nodes?

Question: In Drupal 7.12 i use pathauto, cleanurls, transliteration, i18n.
When i edit one node i saw that, "Generate automatic URL alias" in unchecked.
Then i checked other nodes and saw that for all type of nodes it became unchecked.
I'm pretty sure that it was checked until last week.
The last modifications i made:
I updated Pathauto module, installed Transliteration, installed Debug Cron module.
So, how can i re-enable this checkbox in node settings page automatically ?
(Of course i can i that manually, by editing every node, and checking the check-box)
Thank you very much for your help.
Answer: If you have Pathauto installed, it will generate path aliases for your nodes. It unchecks the box when there's already a path alias, letting you know that it won't change the alias if you change the content. You can change this behavior with the 'Update action' setting here: /admin/config/search/path/settings
Comment: Thank you for help. In my settings this was checked "Create a new alias. Leave the existing alias functioning." Should i check another one?
Comment: Depends on whether you want to generate a new URL every time the node is edited.
Answer: Read the documentation page on How does Pathauto determine if the 'Automatic URL alias' checkbox should be checked or not?.
If the checkbox is unchecked on existing nodes it means that the current alias for the node does not match the alias that Pathauto "would" generate for the node. Maybe if you changed the patterns for your nodes, it would mean they're "out of sync" with the real patterns and then Pathauto un-checks the checkbox by default.
Comment: This is a great insight and a useful documentation link. We regularly see nodes losing the checkbox, even despite the fact that pathauto_persist is on. Remaining problems we see: 1) how should the user notice that some nodes (often among tens of thousands) became unchecked, 2) how to check them back on without hacking about in the database.
Answer: if you want to force it, even if it's unchecked,just create a module as follow :
<?php
function pathauto_checkbox_node_presave($node){
  global $user;
  if($node->type=='you_content_type'){
    $node->path['pathauto']=1;
  }
}
?>

if you want for every type just remove the "if" condition
Comment: I think this code needs to save again the node.Is this possible to force that without saving the node?thanks
Comment: It's been a while now, but I think if you do a bulk update, it should be okay.
Answer: Also you can do it using:
$node->path['pathauto'] = TRUE;

Answer: Some of my contents url were manually generated , some other not.
I wanted to homogenize all content by content types and did not want to do it one by one
I have defined patterns in
admin/config/search/path/patterns

then
  delete all alias and did a bulk update

this action reset all content to automatically generated alias
Answer: You can do this using View's arbitrary script also for the node which is already created and the automatic path creating for all nodes in false (i.e "Generate automatic URL alias" is not checked.)

Here I have created a view to updating the path from "node/[node-id]" to "automatically generated URL".
Follow the below steps.

Create the view as shown in the above image
Go to the view page.
Select the option from the dropdown and the node from the list for which you want to check the checkbox "Generate automatic URL alias" as shown in the below image.

Click on execute. Now on next step enter the code. Then

$node = node_load($entity->nid);
$node->path['pathauto'] = TRUE;
node_save($entity);

Click on confirm. Once completed, go to that node.
edit the node and check the checkbox "Generate automatic URL alias" is checked now. and path is also created automatically


Velocity-time graph

Question: A car travelling at a constant velocity of $20m/s$ passes a stationary sport car. Ten seconds afterwards the sport car accelerates uniformly at $3m/s²$ to reach a speed of $30m/s$ with which it continues. Find when and where the sport car overtakes the first car.
How to indicate the bolded on a velocity time graph is the problem I'm having and hence finding a solution to the problem.
Answer: Hint. First of all recall the main equations of  one-dimensional kinematics.
Let $v_c(t)$ and $v_s(t)$ be the velocity at time $t$ of the car and the sport car respectively. At time $t=0$, the travelling car passes the stationary sport car at the origin. Then for $t\geq 0$,
$$v_c(t)=20\quad\text{and}\quad v_s(t)=\begin{cases}
0&\text{for $t\leq 10$,}\\
3(t-10)&\text{for $10<t\leq t_1$,}\\
30&\text{for $t_1<t$.}
\end{cases}$$
where $t_1$ is a time to be found.
Can you take it from here?
Comment: @Orestes Dante Any progress? Are you still interested in solving your problem?

Velocity-time graph


Collection inheritance java vs groovy

Question: Assuming this class hierarchy:
class A {}
class B extends class A {}

The following code is not valid in Java:
List list = new ArrayList();

Because ArrayList is not a subtype of List.
However, in groovy the code above does not seem to raise an error. Why is that?
Answer: Groovy ignores your generics unless you annotate things with @CompileStatic

Collection inheritance java vs groovy


Fingering Advice for Bach Invention 13

Question: I was hoping to get some feedback about my choice of fingering shown in the picture below.
Answer: Your fingering isn't bad. I compared it to an ancient Willis Edition I have that my dad got me way back when... (It cost $1.75 oh so many years ago!) and you are pretty close to that in most places, however, I'd like to point out some things you might find helpful.
Keep in mind that this fingering works for me, and it may not work for you. Also keep in mind that the purpose of fingering, in many cases, is to align your hand for a new position. The in between notes should fit the hand simply without difficulty, while other fingers are then being used to pivot the hands and direct them in a particular direction so the performer can get his or her hand ready for the next place on the keyboard.
This is something that really needs attention, especially, in Bach and Scarlatti, as well other Baroque and Classical period music, and it definitely works well in Chopin too. Remember Chopin studied a lot of Bach and Mozart!
Anyway, back to your fingering, which I've seemed to have moved bit off topic from...
1st measure:
RH: Use a 1 on the G-sharp as this gets your hand shaped to hit the E above with the 5 finger.
LH: Is okay. Coming down with a 2 on the A is fine since it's an end of the phrase and you are moving your hand slightly to hit the E below with your 5th finger.
2nd measure: OK
3rd measure:
You need to open your hand up a bit. Playing cramped doesn't give you room to move as this measure splits and runs upwards very quickly so...
Try this instead (copied from my Willis Edition)
RH: 5 4 instead of a 4 2, use a 2 4 instead of a 1 4 (opens up the hand), the rest is okay
LH: Try this instead... 1 2 3 1 3 1 4 (a combination of yours and mine here).
4th measure: OK
5th measure:
Try this for the LH:
5 3 2 1 5 3 2 1 3 1
6th measure in C-maj.:
LH: 5 then 5 to start the move upwards. Remember this is a phrase end and a short breath will give you a chance to change positions quickly.
The rest is okay.
You've got the idea here, let us know how you make out on this and of course as more questions.
Comment: Thank you. I was actually using 5 4 on 3rd measure RH, but changed it to 4 2 to make it consistent with measures 4,5, and 6. I was making a lot of mistakes and then I re-did the fingering with the aim of maximizing consistency -- hoping that would reduce mistakes.
Comment: Consistency is one of the best things with fingering. I find that this is then one less thing to remember making the music learning and playing process easier. :-)

Fingering Advice for Bach Invention 13


jQuery: $(this).data() is null

Question: I don't know why $(this).data() returns null in button click event handler but when debugging in firebug,  $("#" + $(this).attr("id")).data() returns the data that i expect.
for (var i = 0; i < options.AvailableOperations.length; i++) {
        var operation = options.AvailableOperations[i];
        var button = $(this).find("#btn" + operation);
        button.data("operation", operation);
        button.data("entityId", options.entityId);
        button.parent().removeClass('disabledRevButton');

        var data = { operation: operation, entityId: options.entityId };
        button.click(function () {

            $.postJson({
                url: GlobalVars.perfomDFOperation,
                data: $(this).data(),
                success: function (data) {
                    if (data != null) {
                        if (data.IsSuccess && data.RefreshPage) {
                            location.reload(true);
                        }
                        else if (!data.isSuccess) {
                            alert("error: " + data.Message)
                        }
                    }
                }
            });
        });
    }

Answer: The this may not be referring to the button itself anymore since it's inside the $.postJson() scope already.
You may want to try using a closure.
button.click(function(){

    var myBtn = $(this);
    $.postJson({
        data: myBtn.data(),
        // blah
    });

});

I'm not sure, but worth a try.
Comment: "$.postJson() scope" - nope, object gets created, before passing it to postJson
Answer: Isn't the variable 'button' the seletion you're looking to fetch data() from? Use buton.data() because $(this) can easily reference something else along the process.
I'd recommend you to use console.log() for debugging purposes, for example, before you attempt to post the JSON, do a console.log($(this)) and see what it references.

jQuery: $(this).data() is null


How to go to a previous commit without deleting recent commits

Question: Assume that I have made following commits: c1, c2, c3 and that I am presently on commit c3. Now I want to go back to commit c1 without removing c2 and c3 commits. Once I am on c1, I want to create another branch from there. How do I do it ?
Answer: Just create the branch directly:
git branch newbranch commitid
And commitid can be a lot of things. HEAD~2 will do what you want for your specific example.
And by the way, you wouldn't even lose c2 and c3 if you just checked out c1: they are available in the reflog (see git reflog).
Comment: Thanks for replying. So if I have to goto c2, I use commitid as HEAD~1 ? Ans yes, I also have to checkout on newbranch.
Comment: You can even checkout directly if you want, just replace `branch` with `checkout -b` in the command above. And yes, that would be `HEAD~1`. In git parlance, in fact, it is not a commitid but a refspec, which can be so many things it's not even funny.
Comment: What if I just want to goto C1 but this time I donot want to branch from c1 ?
Comment: Then just `git checkout` it. Git will warn you that you are currently not on a branch, but it can be done. And if you want to create a branch from this point, use `git branch newbranch HEAD`.


Using both OOP and Function programming paradims

Question: I read about OOP and Function programming. And I found both have pros and cons.
Such as:

OOP: have side effect, and sometimes it is very usefull
Function: easy to code and think. But don't have side effect and loop.

And I wonder if I can using both OOP and Function paradigm in one project. Is it be recommended in practice?
Comment: pretty much every JS project is based on a mix of those two paradigms
Comment: @PatrykCieszkowski yes, I usually use both
Comment: Highly recommend learning Functional Reactive Programming, will replace any need you have for OOP and side effects.
Answer: There's nothing preventing both paradigms from being used together. Arguments on each side sometimes can be misleading as people tend to focus on languages and their features as opposed to the paradigms themselves. OOP doesn't need to have state/side effects, and functional programming doesn't always make things easier or faster. The good engineer will use the right tools for the right task, which means getting a good understanding of both.
Comment: yes, that is right, depending on task and project


Is there a functional interpretation for VIIb in La Follia?

Question: La Follia chord peogression is usually written as:
i - V7 - i - VII - III - VII - i - V7 (first eight bars)
i -V7 - VII - III - VII - i,V7 - i (second eight bars)
I can understand how this progression works for the most part but I don't really understand the motion VII - i from the point of view of classical functional harmony. Is there any explanation for its use from this point of view? (I'm not looking for an analysis from the point of view of popular music or jazz, I'm aware of some ways to rationalize the progression from those standpoints).
Answer: In a relative major key, VII - i would become V - vi which can be viewed as a deceive cadence.
Because of this, you can think of certain sections of this progression dipping into the relative major where VII - III can be looked at as V/III - III and the deceptive resolution as a non functioning secondary dominant V/III - i which is expecting to have the V - I resolution.
Answer: I have seen the basic "La Folia" described as a "double tonic" progression. The patterns i-V-i alternate with III-VII-III or i-V-i in the minor key followed by V-I-V in the relative major. Contemporary theorists mostly thought of this progression as a bass line with some stuff above it. The bass line is 1-V-1-7-3-7 with the melody 1-7-1-2-3-2-7 in the soprano.
Sometimes the Romanesca, Passamezzo Antico, and Passamezzo Moderno were treated the same way but with a different melody. At the time of La Folia's early incarnations, functional harmony had not been codified.


Prove/disprove: $\forall f\ \in \mathbb N ^{\mathbb R}. \forall x\in \mathbb R. \exists y\in \mathbb R ((f(x)=f(y))\wedge (x\neq y))$

Question:
Prove/disprove: $\forall f\ \in \mathbb N ^{\mathbb R}. \forall x\in \mathbb R. \exists y\in \mathbb R ((f(x)=f(y))\wedge (x\neq y))$

This statement looks very similar to the definition of injective function but it has $\exists y$ instead for all, so I think it's false, take $f(x)=\lfloor x\rfloor$ then the statement is false $\forall x\ge 1$.
I also tried to make it harder and prove:

$\forall f\ \in \mathbb N ^{\mathbb R}. \forall x,y \in \mathbb R ((f(x)=f(y))\wedge (x\neq y))$

Which I think is true, since the reals are compact and the cardinalities are different, is the way to do this is to suppose there exists a function such that $f(x)=f(y)\to x=y$? but I don't see how to reach the contradiction..
Comment: How is your example of the floor function a counterexample? We certainly have that $$\;\forall\;x\in\Bbb R\;\exists\,y\in\Bbb R\;\;s.t.\;\;f(x)=f(y)\;\wedge\;x\neq y\;$$
Comment: The first statement says that every function (from the reals to the naturals) is not-injective. The second one says that every function (from the real numbers to the natural numbers) is constant.
Comment: @GitGud I disagree with the first claim you made. See my answer and compare to the initial assertion about the function. That initial assertion is saying more than just not injective.
Comment: @user2566092 You're right, I should have said that the first statement implies that every function is not-injective.
Answer: Hint: What happens if you map all real numbers to a given integer, except for one real number that you map to a different integer?
Comment: Then we have $f(x)=f(y)\wedge x\neq y$ for all the reals that map to the first integer.
Comment: Right but it fails for the remaining one real number $x$ that maps to a different integer!!!
Comment: I submit to you that it disproves all the claims. Check the first claim carefully with my example, considering the unique point $x$ that maps to a different integer. Then does there exist a $y$ such that...?
Answer: Look at the negation of the proposition.
$$
\exists f\ \in \mathbb N ^{\mathbb R}. \exists x\in \mathbb R. \forall y\in \mathbb R ((f(x)\neq f(y))\vee (x= y))
$$
It is true. Just build a function with such property. For exemple,
$$
f(x)=
\left\{
\begin{array}{cc}
0 & \mbox{ if } x=0,\\
\left\lfloor x \right\rfloor^2+1 & \mbox{ if  } x\neq 0
\end{array}
\right.
$$
So if the negation is true the statement is false.
Answer: Suppose the statement isn't true. Then, as you noted, there exists a function $\;f:\Bbb R\to\Bbb N\;$ which is injective.
But then this carries that $\;2^{\aleph_0}=|\Bbb R|\le|\Bbb N|=\aleph_0\;$ , and this is very not true.
Comment: Is there a way to do this without the cardinalities?
Comment: I suppose there is, but why not?


Why getProperties method is not present in the Ember namespace?

Question: I have been reading about the methods in the Ember namespace and I was not able to find the method getProperties which I know exists. On searching I found the method in Ember Instrumentation namespace. But, I was able to find the setProperties method in Ember Namespace.
Is there a reason why getProperties method is defined in the Ember Instrumentation namespace rather than Ember namespace?
Answer: It's a bug in one of the pages, it's accidentally including getProperties with instrumentation, it's really part of Ember Metal.
https://github.com/emberjs/website/tree/master/source/api
Comment: Thanks. Found it in ember-metal as you said - [https://github.com/emberjs/ember.js/blob/master/packages/ember-metal/lib/get_properties.js](https://github.com/emberjs/ember.js/blob/master/packages/ember-metal/lib/get_properties.js)


What is the meaning of set-theoretic notation {}=0 and {{}}=1?

Question: I'm told by very intelligent set-theorists that 0={} and 1={{}}. First and foremost I'm not saying that this is false, I'm just a pretty dumb and stupid fellow who can't handle this concept in his head. So my question is pretty straight-forward, why 0={}, 1={{}}, 2={{{}}} and so on...
For example if we put it in a true statement about the natural numbers it doesn't make sense: 4×2=8 does it mean that {{{{{}}}}}×{{{}}}={{{{{{{{{}}}}}}}}}? The only concept of set "multiplication" is the Cartesian product but unfortunately I don't know it... Also if we have 6/2=3 does it mean that {{{{{{{}}}}}}}/{{{}}}={{{{}}}}? So there's some sort of set "division"?
Also why does one think that a "number" is a set?
Or is it that I'm the one who misunderstands things here maybe we "assign" a natural number to a set, that is for example: 1→{{}}, but then what does "assign" mean and how do you define the natural numbers in the first place?
Please clarify these concepts to me and I'll be deeply grateful to you :) Thanks!
Comment: I was taught this mechanism as a way to "build" the integers as sets, and set-theory processes can build the rationals and reals as well.  But I was taught that each integer is the power set of the last, so $0=\{\},1=\{\{\}\},2=\{\{\},\{\{\}\}\},\dots$
Comment: To the person who voted to close: How the hell is this question "not related to mathematics..."?
Comment: @abiessu: The standard set theoretic definition of the natural numbers doesn't take $n+1$ to be the power set of $n$, but rather $n+1 = n \cup \{n\}$. That way, we have $n = \{m \mid m < n\}$ and $|n| = n$, instead of $|n| = 2^n$.
Comment: That is, $3 = \{\{\},\{\{\}\}, \{\{\},\{\{\}\}\}\}= \{0,1,2\}$, not $\{\{\},\{\{\}\},\{\{\{\}\}\}, \{\{\},\{\{\}\}\}\} = \{0,1,\{\{\{\}\}\},2\}$.
Comment: @AlexKruckman: that must be the correct way.  It's been over ten years, so I must just be conflating the one definition with the other
Comment: There are other approaches to defining the natural numbers that avoid such counter-intuitive constructions. You could simply start with Peano's axioms where a number is not thought of as a set with elements, just an ordinary object. If assuming PA is too much of a leap of faith for you, you can derive PA if you admit the existence of even one infinite set (Dedekind).
Answer: There are two points here:

There are two ways to extend the idea that $0=\varnothing$ and $1=\{\varnothing\}$. Either by taking $n+1=\{n\}$, or by taking $n+1=n\cup\{n\}$ (where $n+1$ really just means "the successor of $n$", I know that we haven't defined addition yet.)
The former was used by Zermelo, originally, and the latter by von Neumann, and it is the modern standard for representing the natural numbers with sets. Note that in this representation, the Cartesian product almost defines the product. While $2\times 4$ is not exactly $8$, we can tell that it is $8$ by saying that $m\cdot n=k$ if and only if there is a bijection between the sets $m\times n$ and $k$.

In either case, not every multiplication has to be the Cartesian product. There are other definitions that we can use. Moreover, not every notion of product has to coincide with any other "naturally occurring" notion of product.
More specifically, given a set which represents the natural numbers, the product is simply a function, taking two variables as input, returning a natural number (or an object representing one). This function can be pretty much anything, as long as it satisfies certain basic properties. As noted above, in the von Neumann interpretation of natural numbers as sets we have a fairly easy way for defining the multiplication.

Finally, let me add that we don't "think that a number is a set". We can use set theory to interpret many, if not all, mathematical theories. This has foundational benefits. Since it means that as long as you believe that set theory is consistent, everything that you can build within it is consistent. In particular the natural numbers, the real numbers, and so on. Set theory is a natural choice, since we already use sets so much anyway. So in set theory we really reduce the number of types of objects that we worry about (from a foundational point of view. This is like how no matter what type of variable you use in C++, the computer ends up interpreting this as a binary string of electric current, and not as physically different objects).
Comment: @Cameron: No, I didn't mean that as $10^5$. It's just that you padded your comment with `{}`'s, and as established, those are $0$'s. :-P (Not that funny, I admit. But in my defense, I never said it's funny!)
Comment: @Cameron: Is that +1 $00000$? :-)
Comment: Lol! Perhaps a little steep.
Comment: I looked at this question, and immediately thought "I bet Asaf is going to give a pretty awesome answer to this one..."  It's interesting to see people's specialties.
Comment: Whoa excellent answer, just what I was looking for! Thanks Asaf you're awesome dude!!
Comment: You're welcome!
Comment: @anorton: Heh, thanks, I guess. With me it's pretty easy to guess. Just a quick look on my top tags, and on the top users of those tags will reveal where I hang my hat... I suppose... :-)
Answer: The definitions in question seem to be for the von Neumann ordinals. By definition, each ordinal is the set of its predecessors, so (for example):
$$0=\{\}\\1=\{0\}=\{\{\}\}\\2=\{0,1\}=\{\{\},\{\{\}\}\},$$ and so on. (Note that the definition of $2$ is not the same as the one you inferred.)
Wikipedia's article on ordinal arithmetic is pretty straightforward and understandable. Take a look and see what you think. If you have specific questions, feel free to let me know.
Comment: @user174364: No, and there's a good reason for it. Mathematically we think about the natural numbers, usually anyway, as the unique model of a particular set of axioms; and the collection of the finite ordinals, along with the ordinal arithmetic (and equivalently, the set of finite cardinals with cardinal arithmetic, which is the same thing -- for finite cardinals) is exactly such model. So we can really think about the finite ordinals as natural numbers. Would you say that $0_\Bbb N$ and $0_\Bbb Z$, $0_\Bbb R$, etc. are all different? If no, then $0_{\rm Ord}$ is the same too.
Comment: Ah so those are different concepts? If so then this clears out many of my misunderstandings, perhaps we should consider a different notation for the "ordinary" 0 and the "ordinal" 0?
Answer: I can't fully agree with @BadZen.  Yes, in practice most "working" mathematicians rarely worry about fundamental issues like these and the "natural" numbers seem "obvious" to us.  (Insert famous Kronecker quote here.)  But the history of analysis has shown that a clear definition of the real numbers was needed before rigorous proofs for various basic results could be given.  (Was this rigor really necessary?  Well, even a genius like Euler made some embarrassing mistakes which nowadays every undergraduate could spot.  Not because he was dumb, but because some of the things he dealt with simply lacked a clear definition.)
So, historically it wasn't that the "sticky statements" came out of the blue and then just for fun a lot of clever guys stopped working on "serious" math in order to deal with foundations for half a century, it was the other way around: It turned out that the "naive" way of dealing with sets which was for example used to introduce notions like Dedekind cuts led to inconsistencies and threatened to kill the whole project.  That's why people came up with ZF and so on.  (And then came Gödel.  But that's another story.)
Not only did Kronecker more than hundred years ago claim that $\pi$ doesn't exist, even today there are serious mathematicians who don't "believe" in irrational numbers and/or infinite sets, so these issues are far from settled.
And, while I'm at it, is it really so "obvious" what a natural number is?  You "know" what symbols like "4", "IV", "four", or maybe "vier" denote, but have you ever seen such a thing?  You have an abstract concept of "fourness" (4 apples, 4 cars, 4 planets), but does that imply that "4" exists and what would existence actually mean in this case?  Is the existence of "4" more obvious than the existence of "$\pi$"?
There's, BTW, a very nice new book about questions like these (and their history) from John Stillwell called The Real Numbers - highly recommended (like all of Stillwell's books).
Comment: Good answer! +1
Comment: I am currently reading Stillwell's The Real Numbers, and I wholeheartedly agree with your praise.
Comment: The curiosity of the foundations in the 19th century is that first the complex numbers were robustly defined in terms of the real numbers (e.g. as pairs of real numbers with certain properties), then the real numbers were defined in terms of rational numbers (e.g. Dedekind cuts), then the rationals in terms of integers (e.g. congruence classes of pairs of integers), then the integers in terms of natural numbers (similarly) and only finally were foundations given for natural numbers (e.g. Peano axioms or sets).
Answer: So, historically, because of various sticky statements that we can write down that make no sense (Russell's paradox, Cantor paradox, etc), we have felt a need to formally justify our use of all symbols in mathematical statements, to give them well-defined, formal meanings, as if they were elements of computer programs.
Numbers and sets provide unique challenges if we try to do this, because they are /integral to the very basic concepts of proof itself/.
The way that you resolve these challenges is a formal set theory, wherein you get statements like {}=0.   Think of it like "0" is defined as {} for our purposes - we are starting with a world where the symbol '0' has no meaning, and proceeding onwards to do... the entire rest of mathematics, with nothing a formal set of rules and some axioms (statements assumed 'true').
The construction of the natural numbers you give is by no means the only one possible!   So the statement "0 = {}" is not a universal, given, derivable, etc... thing.  It is just one way of reconciling the concepts of numbers and sets with regard to a formal system of logic where we can avoid some of the "nonsense statements" that have caused logicians and mathematicians grief in the past.  There are others!  Studying the extends to which these models are equivalent / apply to each other in the presence of various sets of axioms is a discipline of logic with a rich body of literature.
You really needn't worry about it on some "fundamental" or intuitionistic level, unless you are interested in that sort of logic.
[edit - I don't have enough "reputation" to comment on Frunobulax's post below (bombs won't stop him; we're going to have to use NUCLEAR FORCE! :) ), but breifly, yes I mostly agree with what he is saying - the development of the formalism was/is not a "tangential" activity - there is no good reason to believe people  and people  are talking about the same, consistent, mathematics without it, instead of some kind of pre-Babel situation!
The real numbers are somewhat different than the natural numbers however, as these are not so intimately related to the ideas of proof (ie. the metalogic for all of the mathematics including the domain of reals can be expressed without reals for most every non-exotic/non-contrived model, etc)   This touches on the "non-belief" in real numbers...  although I don't think anyone doesn't believe in /countably infinite/ sets, as again there are certain proofs that require rather... complex... proof systems without them.
This is admittedly a sort of a nitpick, however...]
Comment: Your edit seems... confused. Especially the second paragraph.
Comment: @BadZen: Not bombs, [rockets](http://globalia.net/donlope/fz/lyrics/Roxy_and_Elsewhere.html#Cheepnis)... :)
Answer: You learned when you were young that 0 is zero. But that's silly: 0 is a circle drawn on a computer screen, not a number!!
What you really learned is that 0 is a way to represent the number zero in a visual medium.
It is useful to have ways to represent numbers in a set-theoretic medium. The notation scheme typically used is to represent a natural number as the set of all smaller numbers; e.g. we represent five as $\{ 0, 1, 2, 3, 4 \}$. '3' here, of course, means our representation of three, which is $\{0,1,2\}$. The first few numbers in this representation if we really need to fully spell them out is

0 = {}
1 = {{}}
2 = {{}, {{}}}
3 = {{}, {{}}, {{}, {{}}}}
4 = {{}, {{}}, {{}, {{}}}, {{}, {{}}, {{}, {{}}}}}
Comment: I learned that $0$ is a circle drawn on a piece of paper with a pencil; later on it was relaxed to allow printed and inked versions of the circle; and sometimes it had a small line crossing through it to distinguish it from O and other circles. But maybe I'm just getting old... :(


Application of Hidden Markov Model to CRM

Question: What are some of the applications of a HMM in the marketing field - specifically CRM and targeted marketing?
For example, is it mainly for predicting an outcome given a sequence? Such as if web site visitor visits {Page 2, Page 54, page 23} what is the probability they will $<next>$ visit page 22? Or visit page 22 in that session?
Is HMM a stand alone technique or normally coupled with other things?
Comment: CRM? (Yes, I know what it is. But, it helps to define such things within the question.)
Answer: It sounds like you're looking for an n-order Markov model and not a hidden Markov model. Typically, an HMM would be useful if you wanted to identify hidden states at each selection in a series of selections. An n-order Markov model would give you the conditional probability of choosing the n+1'st state given the previous n states, which would be useful in the example you just described.
Comment: DaRob: Do you have any tutorials to point towards for this model?
Answer: A google search for 'hidden markov model marketing' turned up this paper: A Hidden Markov Model of Customer Relationship Dynamics. Google scholar and the references in the above paper may turn up a few more applications of HMM in marketing.


Check registery key value on multiple clients

Question: Is there any way or a tool to check a specific registry key value, for multiple clients
on a network almost 2000 pc ?
Thanks
Comment: do you have powershell available to you?
Comment: yes its available
Answer: This sounds like a job for reg combined with psexec.
Comment: can you tell me how ?


Nested Quantifiers - Excluding Self

Question: I'm trying to understand the following examples of expressing an English sentence using nested quantifiers.
Example One
"Everybody loves somebody else."
$\forall x \exists y ((x \ne y) \land L(x, y))$
Relevant table.
I was told that this means that everybody loves at least one other person, but that it does not exclude the self: $L(x,x)$.
Example Two
"Everybody loves somebody other than self."
$\forall x \exists y (L(x, y) \land \neg L(x, x))$
Relevant table.
Apparently this does exclude the self.
I don't see the difference between these examples. As far as I understand, $(x \ne y)$ is functionally equivalent to $\neg L(x, x)$. Because $(x \ne y)$ is always false at the diagonals, it seems like the first example should also exclude the self.
Any help would be greatly appreciated. :)
Comment: I do not see however, how either of the natural language sentences conveys that self-love does not exist
Answer: The clause "$(x \neq y) \wedge L(x,y)$" explicitly asserts the truth of $x$ loving $y$ for some $y$ that is different from $x$, but is completely silent on the truth of $L(x,x)$.  (The inequality condition ensures that the clause cannot speak to the truth or falsity of $L(x,x)$.)
The clause "$L(x,y) \wedge \neg L(x,x)$" asserts both $L(x,x)$ is false and $L(x,y)$ is true.  This forces $y \neq x$ and also explicitly assigns a truth value to $L(x,x)$.
Comment: So because $(x \ne y)$ always evaluates to false in the case when $L(x, x)$, $(x \ne y)$ always dominates the value of $L(x, x)$? I'm having trouble seeing why it is important to make the distinction that $(x \ne y) \land L(x, y)$ is "completely silent on the truth of" $L(x,x)$, because I can't think of an instance where these examples would have different truth values given the same inputs. Is it a mistake to assume that they're logically equivalent?
Comment: If all you tell me is the value of $L(x,y)$ for $x \neq y$, you never tell me the value of $L(x,x)$.  Since you don't tell me if it is true or false, I can't infer anything about it.

Nested Quantifiers - Excluding Self


How to upload multiple files from directory to S3?

Question: I have a directory on an Ubuntu, with 340K images, 45GB of total size! Is there an efficient way to transfer them all to an S3 of DigitalOcean?
I thought of using s3cmd put or s3cmd sync but I'm guessing that would perform the put operation on every single file individually.
Any thoughts would be much appreciated!
Answer: You can use the https://github.com/mishudark/s3-parallel-put, which achieves higher throughput by multithreading but still individual files will be uploaded using single PUT operations since its happening in parallel entire operation will be done sooner. The throughput depends on factors like no of CPU, network bandwidth etc.
Comment: Generally if your process is more CPU bound, then have ideal thing would be N process/Threads in N core machine, and in our case it since it is more IO bound(n/w is IO) you can have 2 or 3 threads per core, But Don't have ratio like 10 or more Threads to 1 Core, lot of time will be wasted in context switching. Ideal thing for IO bound is start with 2*N(N -no of core) threads and slowly increase the number and until you hit a optimal number after which your performance starts degrading, assume you have 2 or 4 core machine and ran 100 process then it is might not be optimal, reduce the count.
Comment: Thanks for the response! I tried to transfer 2700 files (400MB) as a test, with 100 processes and finished in 30s! Sometimes though, it slowed-down and logged  `(BotoServerError: 503 Slow Down)`. Do you know how to figure out the best number of processes?


Set session variable in laravel

Question: I would like to set a variable in the session using laravel this way
Session::set('variableName')=$value;

but the problem is that I don't know where to put this code, 'cause I would like to set it for one time (when the guest visite the home page or any other page)?
The main idea is to use a global variable to use it in all application controllers, I heared about something related to configuration variables but I'm not sure if it will be a good Idea to use config variables or only the session?
Thanks
Comment: that is illegal PHP. the left-hand-side of an assignment operation cannot be an expression. `set()` is a function/method call - it can only RETURN a value, you cannot assign a value to it.
Comment: This is very well documented here: http://laravel.com/docs/5.0/session
Answer: The correct syntax for this is:
Session::set('variableName', $value);

For Laravel 5.4 and later, the correct method to use is put:
Session::put('variableName', $value);

To get the variable, you would use:
Session::get('variableName');

If you need to set it once, I'd figure out when exactly you want it set and use Events to do it.
For example, if you want to set it when someone logs in, you'd use:
Event::listen('auth.login', function() {
    Session::set('variableName', $value);
});

Comment: @user3158900, why there is a need of service provider?
Comment: Please Tell Me Where We Can Use this Event?
Comment: in routes or controller?
Comment: You'd probably want to create a service provider for it and put it in there.
Answer: I think your question ultimately can be boiled down to this:

Where can I set a long-lived value that is accessible globally in my application?

The obvious answer is that it depends.  What it depends on are a couple of factors:

Will the value ever be different, or is it going to be the same for everybody?
How long exactly is long-lived? (Forever? A Day? One browsing 'session'?)

Config
If the value is the same for everyone and will seldom change, the best place to probably put it is in a configuration file somewhere underneath app/config, e.g. app/config/companyname.php:
<?php
return [
    'somevalue' => 10,
];

You could access this value from anywhere in your application via Config::get('companyname.somevalue')
Session
If the value you are intending to store is going to be different for each user, the most logical place to put it is in Session.  This is what you allude to in your question, but you are using incorrect syntax.  The correct syntax to store a variable in Session is:
Session::put('somekey', 'somevalue');

The correct syntax to retrieve it back out later is:
Session::get('somekey');

As far as when to perform these operations, that's a little up to you.  I would probably choose a route filter if on Laravel 4.x or Middleware if using Laravel 5.  Below is an example of using a route filter that leverages another class to actually come up with the value:
// File: ValueMaker.php (saved in some folder that can be autoloaded)
class ValueMaker
{
    public function makeValue()
    {
        return 42;
    }
}

// File: app/filters.php is probably the best place
Route::filter('set_value', function() {
    $valueMaker = app()->make('ValueMaker');
    Session::put('somevalue', $valueMaker->makeValue());
});

// File: app/routes.php
Route::group(['before' => 'set_value'], function() {
   // Value has already been 'made' by this point.
   return View::make('view')
       ->with('value', Session::get('somevalue'))
   ;
});

Comment: upvote because of hhtg :-) and the good and comprehensive answer.
Answer: In Laravel 5.6, you will need to set it as:
session(['variableName' => $value]);

To retrieve it, is as simple as:
$variableName = session('variableName');

Comment: Can I retrieve it from any controller ?
Comment: yes, A session is a way to store information (in variables) to be used across multiple pages
Answer: For example, To store data in the session, you will typically use the putmethod or the session helper:
// Via a request instance...
$request->session()->put('key', 'value');

or
// Via the global helper...
session(['key' => 'value']);

for retrieving an item from the session, you can use get :
$value = $request->session()->get('key', 'default value');

or global session helper :
$value = session('key', 'default value');

To determine if an item is present in the session, you may use the has method:
if ($request->session()->has('users')) {
//
}

Answer: To add to the above answers, ensure you define your function like this:
public function functionName(Request $request)  {
       //
}

Note the "(Request $request)", now set a session like this:
$request->session()->put('key', 'value');

And retrieve the session in this way:
$data = $request->session()->get('key');

To erase the session try this:
$request->session()->forget('key');

or
$request->session()->flush();

Answer: in Laravel 5.4
use this method:
Session::put('variableName', $value);

Answer: In Laravel 6.x
// Retrieve a piece of data from the session...
$value = session('key');

// Specifying a default value...
$value = session('key', 'default');

// Store a piece of data in the session...
session(['key' => 'value']);

https://laravel.com/docs/6.x/session
Answer: You can try
 Session::put('variable_Name', "Your Data Save Successfully !");
 Session::get('variable_Name');

Comment: This is used to store value in session \Session::put('variable_Name', "Your Data Save Successfully !"); and this is used Session::get('variable_Name');
to get the value which i store in session
Answer: to set session you can try this:
$request->session()->put('key','value');

also to get session data you can try this:
$request->session()->get('key');

If you want to get all session data:
$request->session()->all();

Answer: If you want persistence sessions,
Method 1: use session()->save() or Session::save()
session(['key' => 'value']);
//or
session()->put('key', 'value');

//then
session()->save();

echo session('key');

Method 2: Move bellow line from protected $middlewareGroups of app\Http\Kernel.php to protected $middleware array as first line
\Illuminate\Session\Middleware\StartSession::class,

Make sure the storage directory has write permission
chmod -R a+rw storage/

Don't use dd() to verify session, use print_r()

Set session variable in laravel


Show that $f(x)=g(x)$ for all $x \in \mathbb R$

Question: Let $f,g:\mathbb R \rightarrow \mathbb R$ be both continuous. Supose that $f(x)=g(x)$ for all $ x \in D$, where $D\subseteq\mathbb R$ is dense. Show that $f(x)=g(x)$, for all $x \in \mathbb R$. Id like a hint to solve this question.
Comment: Consider $h^{-1}(\{0\})$ where $h(x) = f(x)-g(x)$.
Comment: Letting $\mathcal D$ be the set of dense subsets of $\Bbb R$, is the hypothesys $$(\forall D\in \mathcal D)(\forall x\in D)(f(x)=g(x))$$ or is it $$(\exists D\in \mathcal D)(\forall x\in D)(f(x)=g(x))?$$
Comment: Seems to me that it is the latter.
Comment: A more general version of this question can be found [here](http://math.stackexchange.com/q/408706/28900).
Answer: Hint: For any $x_n \to x$ you have $f(x) = \lim_n f(x_n)$ and $\lim_n g(x_n) = g(x)$.
For each $x$, is it possible to select a sequence $x_n$ such that $x_n \to x$ and $\lim_n f(x_n) = \lim_n g(x_n)$?
Answer: One more hint:
Define $h(x) = f(x)-g(x)$. For any given $y$ and $\delta$, there exists $x \in D$, such that $|x-y| < \delta$. Now, for prove that for any given $\epsilon$, since $h$ is continuous, $h(y) - h(x) = h(y) <\epsilon$.
Answer: Let $X$ be a topological space, and $Y$ a Hausdorff space. Then the set $\mathrm{diffker}(f,g)$ of points $x\in X$ such that $f(x)=g(x)$ is closed in $X$. For its complement is open: if $x\notin\mathrm{diffker}(f,g)$ then $f(x)\neq g(x)$ and $f(x)$ and $g(x)$ have distinct open neighborhoods in $Y$, taking the intersection of their preimages gives a neighborhood of $x$ in $X$ contained in $\mathrm{diffker}(f,g)$. If $\mathrm{diffker}(f,g)$ is dense in $X$, then $\mathrm{diffker}(f,g)=\overline{\mathrm{diffker}(f,g)}=X$. Now put $X=Y=\mathbf{R}$.
Answer: HINT: $(f-g)^{-1}(\{0\})$ is closed and $D \subset (f-g)^{-1}(\{0\})$.


$\text{Ker P $ ,$ Im P}$ and Direct Sum

Question:
Let $V$ be a vector space. Let $P:V\rightarrow V$ be a linear map such that $P^2=P$.
Show that

$$V=\text{Ker P + Im P}.$$ and $$\text{Ker P}\cap\text{Im P}=\left\{0\right\}.$$
HINT. an element $v\in V$ is $v=v-P(v)+P(v)$.
Proof. Since $P(v-P(v))=P(v)-P^2(v)=0$, we see that $V=\text{Ker P + Im P}.$ How did we see this, I couldn't understand As for intersection, note that if $w$ lies in the set  $\text{Ker P}\cap\text{Im P}$, then there exist a vector $v$ such that $P(v)=w$ I couldn't understand this $P(v)=w$ **, so that $P(v)=P(w)$. But since $P(w)=0$, we conclude that $w=P(v)=0$ **Why?. Hence
$$V=\text{Ker P + Im P}.$$ and $$\text{Ker P}\cap\text{Im P}=\left\{0\right\}.$$
that is it is direct sum.
I have a question that I wrote phrases in bold
Comment: Possible duplicate of [Show that $V=ker(P)+im(P)$ and $ker(P)\cap im(P)=\{0_v\}$](https://math.stackexchange.com/questions/995612/show-that-v-kerpimp-and-kerp-cap-imp-0-v)
Comment: $V \neq kerP + ImP$, are you sure you didn't mean $V = kerP \oplus ImP$ ?
Comment: @VictoriaM The question is from Lang's Linear Algebra page 71, question 10. And yes, I sure.
Comment: Ah, I just checked the book. The notation $+$ was meant to be $\oplus$. See https://i.imgur.com/Psz82Qy.png
Comment: @VictoriaM Since $\ker P$ and $\operatorname{im}P$ are subspaces of $V$, the two notations are not mutually exclusive, all the more if the condition $\ker P\cap\operatorname{im}P=\{0\}$ holds.
Comment: @VictoriaM The question is essentially to prove $V = \operatorname{Ker} P \oplus \operatorname{Im} P$ in two parts: show $V$ is the sum of these subspaces, then show the sum is direct.
Comment: Edited question, can you see now?
Comment: @VictoriaM Edited question, can you see now?
Comment: @TheoBendit edited question, can you see now?
Answer:
Since $P(v−P(v))=P(v)−P^2(v)=0$, we see that $V=\operatorname{Ker} P + \operatorname{Im} P$. How did we see this, I couldn't understand

What they're showing here is that $v - P(v) \in \operatorname{Ker} P$. Just consider the definition of $\operatorname{Ker} P$; it's the set of vectors that $P$ sends to $0$. Since they're applying $P$ to $v - P(v)$ and getting $0$, this means $v - P(v) \in \operatorname{Ker} P$.
Couple this with the simple observation that $P(v) \in \operatorname{Im} P$ (it is, after all, the result of applying $P$ to an element of $V$), and this implies that
$$v = \underbrace{P(v)}_{\in \; \operatorname{Im} P} + \underbrace{v - P(v)}_{\in \; \operatorname{Ker} P} \in \operatorname{Im} P + \operatorname{Ker} P.$$

As for intersection, note that if $w$ lies in the set $\operatorname{Ker} P \cap \operatorname{Im} P$, then there exist a vector $v$ such that $P(v)=w$ I couldn't understand this

If $w \in \operatorname{Ker} P \cap \operatorname{Im} P$, then $w \in \operatorname{Im} P$ (it's also true that $w \in \operatorname{Ker} P$, but we don't need this fact just yet). The image of $P$ is the set of all vectors of the form $P(v)$, where $v \in V$. This is literally the definition. To say $w \in \operatorname{Im} P$ is exactly the same thing as saying there is some $v \in V$ such that $w = P(v)$.

so that $P(v)=P(w)$. But since $P(w)=0$, we conclude that $w=P(v)=0$ Why?

We know that $w = P(v)$, by construction of $v$. Applying $P$ to both sides, using the fact that $P^2 = P$, we get
$$P(w) = P^2(v) = P(v).$$
We know that $P(w) = 0$ because $w \in \operatorname{Ker} P$ (remember, $w$ is in both $\operatorname{Ker} P$ and $\operatorname{Im} P$ by assumption!) and the definition of the kernel is the set of vectors that $P$ sends to $0$. So, $P$ sends $w$ to $0$. By the above equality, this means $P(v) = 0$. But, our construction of $v$ was a vector in $V$ such that $w = P(v)$, so joining these equalities up,
$$w = P(v) = 0.$$
That is, the only vector in $V$ that lies both in $\operatorname{Ker} P$ and $\operatorname{Im} P$ is the zero vector!
Comment: Than you very much!

$\text{Ker P $ ,$ Im P}$ and Direct Sum


Não estou conseguindo fazer o programa retornar a maior e a menor média

Question:
O problema é esse:
Escreva um programa que lê um arquivo chamado notas.txt que contém em cada linha o nome de
um aluno e quatro notas entre 0 e 100. O programa deve então exibir na tela a maior e a menor média
dentre todos os alunos.
Meu código é esse:
<code>arquivo = open('notas.txt')
for linha in arquivo:
    notas = linha[4:]
    soma = 0
    for nota in notas.split():
        soma=soma+int(nota)
    media = soma / 4
    print(media)

arquivo.close()
</code>
Comment: Olá @nicole-askar da uma olhada neste exemplo [aqui](https://ideone.com/QoFTdA) ele pode ser melhorado, mais já vai te dar um norte.
Comment: Nicole Askar, teste esse [exemplo](https://replit.com/@Augusto-Vasques/Media#main.py)
Comment: https://replit.com/@hkotsubo/Media#main.py
Answer: A resposta para este problema é a seguinte:
<code>    # -*- coding: utf-8 -*-
    arquivo = open('notas.txt', 'r')
    notas = []
    medias = []

    for linha in arquivo:
        campos = linha.split(' ')
        nome = campos[0]
        notas = []
        for nota in campos[1:]:
            notas.append(int(nota))
            media = sum(notas)/len(notas)
        medias.append(media)
        maior_media = max(medias)
        menor_media = min(medias)
    print(f'{maior_media:.2f}')
    print(f'{menor_media:.2f}')
    arquivo.close()
</code>
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).