Installing wordpress and laravel in the same database because my hosting doesn't allow multiple databases

Question: I have existing Laravel website up and running at https://iqtestsite.com/ . I want to install a blog section for this website using wordpress. When i try one click installation, it shows an error that database already exist.
My Domain can only have one database, i currently have important data on the server. I can't lose any part of the data.
How should i proceed here.
Thanks for reading.
Comment: Your question looks off-topic for Stack Overflow _ Check out the top 2 FAQs in SO Help Section section on 'Asking' >>> https://stackoverflow.com/help/asking _ As the issue is specific to the setup on your webhost it's more likely they will be more able to help you _ Good Luck
Comment: Install the WordPress in your localhost and import the DB to your existing DB. then you can change your wp-config.php file manually cording to your DB details
Answer: This question is off-topic still I'll try to answer your question.
put the Wordpress Blog in the 'public' folder of your Laravel app.
i.e. .../laravel_app/public/wordpress_blog
or simply: laravel_app/public/blog
you can access the blog at https://www.your-site.com/blog
you can access the admin at https://www.your-site.com/blog/wp_admin
no need to worry about the routes in laravel, it will work just fine.
You can use the same database for both, just use a prefix for the WordPress tables e.g. 'wp_table_name'. you can set a prefix during WordPress installation. So you have a single database for both Laravel & Wordpress tables.
Answer: In WordPress table prefix write  wp2_
rest all you can put as same as before...
I guess it will work...
the restriction is always on the database, not tables... so add tables same as woocoomerce / wordfence and other olugin insert own tables in your database... so you can incert your tables in old database


Quadratic Gauss Expression for primitive $7$th roots of unity

Question: For  primitive $7$th root of unity $\omega$, calculate $|1+2\omega + 2\omega^2 + 2\omega^4|$.
Comment: That's a Gauss sum.
Comment: It would be helpful if you could explain how to find it.
Answer: Given that $w$ is a primitive 7th root of unity, we have $\overline w=w^6, \overline {w^2}=w^5, $ $\overline {w^4}=w^3$, $w^7=1$,
and $1+w+w^2+w^3+w^4+w^5+w^6=\dfrac{w^7-1}{w-1}=0$.
Therefore $|1+2w+2w^2+2w^4|^2=(1+2w+2w^2+2w^4)\overline{(1+2w+2w^2+2w^4)}$
$=(1+2w+2w^2+2w^4)(1+2w^6+2w^5+2w^3)=13+6w+6w^2+6w^3+6w^4+6w^5+6w^6$
$=7+6(1+w+w^2+w^3+w^4+w^5+w^6)=7.$


CF memory usage by cf app command

Question: I want to understand memory status reported by cf app command.
e.g. If for my app it returns
 state     since                    cpu     memory       disk           details

0   running   2017-02-11 08:06:39 AM   18.2%   2.2G of 4G   200.3M of 1G
What does this 2.2G means really? Because when I see my application in newrelic it shows like ~1GB being used. I believe actual allocation will also depend on some other parameter (xmx, memory calculatros?)  when application starts.
(It is spring boot application)
Answer: When you run cf app <app-name>, the output shows the memory and CPU usage that is reported by the Linux Kernel for your container.  Recent versions of CF obtain this using Guardian & runc, older versions using Warden.
Conceptually you can think of what it's reporting as the memory usage for all processes running inside the container.  This includes your application processes, but also a couple very small processes put there by the platform (one being the SSH daemon that facilitates cf ssh).  If you want to see more about what's running in your container, I would suggest executing cf ssh and then looking at ps aux or top.
In regards to your specific app, the difference that you're seeing is likely due to the fact that it's a Java app.  You need to make sure that you're looking at the full memory usage for the process and not just the heap usage.  Heap is only one part of the total memory usage for a Java app, which also includes PermGen (1.7) or Metaspace (1.8), threads, native code, direct memory and other memory used by the JVM itself.
Answer: It says that one instance of the app is running. The app was allotted / assigned 4GB of memory out of which (at the time when you ran cf app) the app had consumed 2.2 GB of total memory.
If New Relic is reporting close to 1 GB of memory, that could mean there are other things that is taking up the other 1.2 GB of memory.
I would start with looking at the buildpack that you are using. Are you using the standard java buildpack or it a custom buildpack that your company created? Does the buildpack add any other agents? Something like AppDynamics (not saying that is the culprit by any means) or something else. Find out that, and identify how much memory those add-ons are consuming.
I would suggest may be doing a heapdump of your running instance. You will have to ssh into the container for it. The head dump could be 2.2 GB and the disk assigned to your app is only 1GB, which will pose a problem. There are solutions but that depends on what version of PCF you are running.
Just a quick question, do you by any chance using nashorn in your app?
Hope this helps!
Comment: You are using standard buildpack. So, there are no addons then.
You can try ssh into the app instance container and check out the log files and see if you get any clues on what is running.

You will have to do `heapdump` to get a good look.

What version of PCF are you on?

CF memory usage by cf app command


How to configure permissions on application folder to write XML Documents

Question: I have a desktop aplication using VS2005.
The application writes an XML document into an application´s folder.
When I run with an administrator account the application runs OK, but when I run as a user without access rights I receive the access denied error message.
My application will be distributed to multiple users, and therefore could not make the release of access by Windows Explorer. Need access to be released when installing my application on the machine User.
How I can solve this problem?
I have to use the folder where the User to installed the application, which is usually C: \ Program Files \ ...
My application will create the following architecture:
C:\Program Files\CapProj\Data\ << where the XML files will be located >>
C:\Program Files\CapProj\Imagens\ << images folder >>

The .EXE file will be in C:\Program Files\CapProj\CapProj.EXE.
My application doesn't use any database system. This application only uses only XML files to store data, because this application will be distributed to many users in Brasil.
Answer: You should have your application write files that belong to a user in that user's My Documents folder, not into the application's folder.
You can get the path to the My Documents folder using the .NET Framework with the following C# code:
var myDocsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));

If the XML file is more like application settings, then use Environment.SpecialFolder.ApplicationData or a more appropriate special folder.
Answer: Consider using the user's AppData directory instead. You can use:
string appDataDir = Application.UserAppDataPath;


Durret problem 4.8.3 - Random walk and optional sampling theorem application

Question: Exercise 4.8.3 Durret states

Let $S_n= \xi_1 + \ldots \xi_n$, $(\xi_i)_i$ independent with $0$ mean and $Var(\xi_i)=\sigma ^2$. Then $S_n^2 - n \sigma^2$ is a martingale. Let consider the stopping time $T= \inf \{ n: |S_n|> a \}$.
Show $E[T]> \frac{a^2}{\sigma^2}$.

I need to know if my argument is okay, especially the application of the optional stopping theorem!

Of course the filtration is the canonical one $F_n = \sigma(\xi_i, i \leq n) $ and is easy to show that $S_n^2 - n \sigma^2$ is a $(F_n)_n$-adapted martingale.
Morever, $T$ is a stopping time since $\{T= n \}$ can be written as \begin{align}
( \cap_{i=1}^{N-1} \{ |S_i|<a \}) \cup \{ |S_n|>a \}
\end{align}
and by construction this belongs to $F_n$
To show the claim, I need to use the optional stopping theorem applied to the given martingale. The standard argument is that $T$ is not bounded, so I consider the stopped martingale $ S_{n ∧ T} - (n ∧ T) \sigma^2$.
For every $n$, $n∧T$ is bounded and $(n∧T) \rightarrow_n T$ Here I should show that $P(T< +\infty)=1$ a.s, but don't know how
Hence, by OST applied to stopping times $T ∧ n$ and $0$:
\begin{align}
E[S_T - T] = E[\lim_n S_{T ∧ n} - (T ∧ n) \sigma^2] = \lim_n E[S_{T ∧ n} - (T ∧ n) \sigma ^2]  = E[S_0]=0
\end{align}
where I used DCT.
Hence $E[T] \sigma^2= E[S_T^2]$, but when I stop at $T$ I have by definition: $|S_T|>a$ and hence follows $E[T] \sigma^2 = E[S_T^2]>E[a^2]=a^2$ and hence
\begin{align}
E[T]> \frac{a^2}{\sigma^2}
\end{align}
EDIT
To apply DCT, I note that $S_{ n \wedge T}^2 \leq (a+1)^2$ and hence, by OST, $E[T \wedge n]=E[S_{ n \wedge T}^2] \leq (a+1)^2$ and hence I can take the limit in $E[S_{ n \wedge T}^2 - T \wedge n]=0$ and obtain the thesis
Comment: Actually, I have noticed something: what is the dominating function that allows you to use DCT?
Comment: @TheoreticalEconomist I thought $S_{T ∧ N} - (T ∧ n) \sigma^2 < a^2$
Comment: I don't see why that's true. Bear in mind that what you actually need is that $\vert S_{T\wedge n} - (T\wedge n)\sigma^2 \vert \le X$ where $X$ is some integrable random variable. $X=a^2$ would do, if the inequality were true, but I just don't see it.
Comment: @TheoreticalEconomist you're right. Could you confirm the following? I think it should work:

$|S_{n \wedge T}| \leq |S_{n \wedge T-1} | + |S_{ n \wedge T -1} - S_{ n \wedge T} |  < a +1$ since the steps of the r.w. are of size 1, and so I have a uniform bound
Comment: The idea is good, but I think your last inequality should actually be $\le a + \vert \xi_{T\wedge n}\vert$, which is fine because this is integrable. Note in particular that the inequality is weak, not strict.
Comment: @TheoreticalEconomist Yes, and what about the term $-(T \wedge n) \sigma^2$? How can I bound this?
Comment: @TheoreticalEconomist

I just know it is bounded by $n$ for every $n$, but I really can't get a uniform bound...
Comment: Just found this answer, it has a similar argument : https://math.stackexchange.com/questions/2791145/application-of-the-optional-stopping-theorem?rq=1

In the answer he doesn't care about that term...
Comment: That's because saz is not trying to use the DCT. Maybe you can think about their approach and see if it works in your setting.
Comment: But even if he doesn't want to use DCT, this bound has somehow to be right...
Comment: saz's bound is correct, but not really relevant for what you're trying to do. I'm not sure what you mean by the bound has to somehow be right.
Comment: Oh nothing, I was mistaken sorry.
Comment: Actually, the text says to use the theorem

If $E[|X_T|] < \infty$ and $X_n 1 (T >n)$ is uniformly integrable, then $X_{T ∧n}$ is uniformly integrable and hence $E[X_0] ≤ E[X_T]$
Comment: @TheoreticalEconomist Just edited my post  with a way to bound $E[T \wedge n]$.
Comment: Why is $S_{T\wedge n}^2 \le (a+1)^2$? Note that $S_n$ is not a random walk, so it does not have increments of size $1$. $\xi_i$ could be, for example, normally distributed. What you actually have is $S_{T\wedge n}^2 \le \left(a + \left\vert \xi_{T\wedge n} \right\vert\right)^2$. Note also that, in order to apply the DCT, what you need to bound is $T\wedge n$ not $E[T\wedge n]$, so the argument in your edit is not correct.
Answer: I just want to summarise the discussion in the comments (as some of them have been deleted), give an argument that allows you to interchange taking limits and expectations, and make a remark about your application of the DCT.
First, you don't need to show that $P(T<\infty)=1$. You are able to apply the optional sampling theorem since $T\wedge n \le n$, which guarantees that $T\wedge n$ is a bounded stopping time.
We will now justify the step $$ E\left[\lim_{n\to \infty} S_{T\wedge n}^2 -(T\wedge n)\sigma^2\right] = \lim_{n\to \infty} E\left[ S_{T\wedge n}^2 -(T\wedge n)\sigma^2\right], \tag{*}\label{*} $$ in two separate steps using the dominated and monotone convergence theorems respectively.
As you argue in the comments, we observe first that $$\vert S_{T\wedge n} \vert \le \vert S_{(T\wedge n) -1} \vert + \vert S_{T\wedge n} - S_{(T\wedge n) -1}\vert \le a + \vert \xi_{T\wedge n} \vert.$$ Thus, $$ \vert S_{T\wedge n} \vert^2 = S_{T\wedge n}^2 \le \left(a + \left\vert \xi_{T\wedge n} \right\vert\right)^2, $$ where we know that the right-hand side is integrable. This means that $$ E\left[\lim_{n\to \infty} S_{T\wedge n}^2 \right] = \lim_{n\to \infty} E\left[ S_{T\wedge n}^2 \right]. $$
Now, observe that $T\wedge n$ is non-negative, and non-decreasing in $n$. Thus, we can use the monotone convergence theorem to conclude that $$ E\left[\lim_{n\to \infty}(T\wedge n)\sigma^2\right] = \lim_{n\to \infty} E\left[(T\wedge n)\sigma^2\right]. $$
Putting these two steps together gives us \eqref{*}.
Note that the argument you make in your edit is not correct, because it does not allow you to apply the DCT. The DCT requires that you find an integrable random variable $Z$ such that $T\wedge n \le Z$. What you've done is instead found an upper bound for $E[T\wedge n]$, which is not sufficient to apply the DCT.
The rest of your post looks fine.
Comment: Many thanks, you're right, I was thinking about a RW!


How to use default org-mode spreadsheet auto-sum behavior ?

Question: In this example:
|   | num |
|---+-----|
|   |   5 |
|   |   6 |
|   |   4 |
|---+-----|
| # |  15 |
| ^ | sum |
#+TBLFM: $sum=vsum(@2..@-1);

Every time you press "tab" in the sum area or C-c C-c in the table formula area below the table it recalculates the sum area. The problem is after it recalculates this area it adds this new sum to the current sum that's already in the area. (Try it in your emacs).
I've created this basic test to show issues I've encountered in creating complex spreadsheets in org. Until I find a solution I can't trust the sums emacs gives me because I may occasionally  press C-c C-c twice and it's inconvenient to have to go and zeo out all sum values in my form every time I recalculate.
If anyone knows a solution, please let me know.
Answer: Turns out it was a bug with the Org-mode version I was using:
release 5.23a is from Apr 23 10:17:27 2008
Kudos to Thumper_ in freenode #org-mode for pointing it out.
Be sure to update to the newest version of Org-mode, folks! :)
Answer: Maybe it's more clear to use vsum(@I..@II) to indicate the rows between the 2 hlines.
I cannot reproduce your accumulation problem; and just read your answer about the bug!!


Apache 2.4 + PHP-FPM + Dynamic ProxyPassMatch

Question: Expect result:
If I go to http://foo.local/index.php, file /var/www/html/foo/index.php will be executed.
It will be similar if I go to http://bar.local/index.php, /var/www/html/bar/index.php will be executed.
Here are my configurations:
<VirtualHost *:80>
    ServerAlias *.localhost
    VirtualDocumentRoot /var/www/html/%1/

    <IfModule proxy_module>
        #ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://localhost:9000/var/www/html/$1 (this  line works in normal virtualhost)
        ProxyRemoteMatch ^([^.]+).*/(.*\.php(/.*)?)$ fcgi://localhost:9000/var/www/html/$1/$2
    </IfModule>
</VirtualHost>

For now, this is working well for static files like .html.
But it will print .php files instead of executing them.
Please advise, thank you.
PS: If I use mod_php instead of php-fpm, it would be easier. But for learning purpose, I really want to go the hard way.
Answer: Here is my own solution (use RewriteRule with [P] flag instead of ProxyPass):
<VirtualHost *:80>
    ServerAlias *.localhost
    VirtualDocumentRoot /var/www/html/%1/

    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^([^.]+) [NC]
    RewriteRule ^/(.*\.php(/.*)?)$ fcgi://php:9000/var/www/html/%1/$1 [P]
    #<IfModule proxy_module>
        #ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://php:9000/var/www/html/$1
        #ProxyRemoteMatch ^([^.]+).*/(.*\.php(/.*)?)$ fcgi://php:9000/var/www/html/$1/$2
    #</IfModule>
</VirtualHost>


RESTful Web Services : How to simply post a paragraph entity

Question: I have simply activated the default paragraph ressource with core (8.8.3) module :

I would like to post a paragraph but even just with the "type" field, I got 403 error in response ! I have nearly the same request that works fine for node...
<code>        var newReleve = {

          type: [{
            target_id: 'releve_de_chantier'
          }],
          parent_id: [{
            value: this.nid,
          }],
          parent_type: [{
            value: 'projet',
          }],
          // field_type_de_releve_de_chantier: [
          //   {
          //     value: this.typeReleve
          //   }
          // ],

        };

        if(this.pid) {
          newReleve.id = [{
            value: this.pid
          }]
        }

        fetch('/entity/paragraph'+(this.pid ? '/'+this.pid : '')+'?_format=json', {
          method: this.pid ? 'PATCH' : 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-CSRF-Token': csrfToken
          },
          body: JSON.stringify(newReleve)})
          .then(response => {
            if(response.ok){
              return response.json();
            } else {
              console.log(response);
              throw('Error posting datas ! Details below \n ' + response.status + ' : ' + response.statusText);
            }
          })
          .then(para => {
            // console.log(para);
            this.pid = para.id[0].value;
            console.log(this.pid);

          })
          .catch( error => {
            alert('Enregistrement du relevé non effectué : erreur interne du programme ! Détail de l\'erreur : \n ' + (error.message ? error.message : error) );
            console.error(error);
          });
</code>
Any idea ?
thanks
Comment: GET and DELETE work fine
Comment: And I'm testing with admin account...
Comment: And when POSTing, I only get the return :
Comment: {
    "message": ""
}
Answer: Finally, seems it comes from Paragraph module, file ParagraphAccessControlHandler.php function checkCreateAccess :
<code>  protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {
// Allow paragraph entities to be created in the context of entity forms.
if (\Drupal::requestStack()->getCurrentRequest()->getRequestFormat() === 'html') {
  return AccessResult::allowed()->addCacheContexts(['request_format']);
}
return AccessResult::neutral()->addCacheContexts(['request_format']);
</code>
}
Code goes in the second return as request format is not html but json. If I force the return to be AccessResult::allowed(), the paragraph is created. Why this restriction to forms ? How to overwrite this without patching ?


Redhat or CentOS7 systemd may remove user IPC resources unexpectedly

Question: According to the comment below, linux systemd can remove my IPC resources without my allowance.
I already met this problem during important PoC(Proof of concept) test.
But, I have difficulty in reproducing this problem in my desktop.
Is there anybody who encountered this problem before and knows the easy way to reproduce it?
In my case, system removed my semaphore, and most processes were still up and some processes using removed semaphores encountered crash.
=================================================================
https://www.certdepot.net/rhel7-changes-between-versions/
RemoveIPC Directive
A new option called RemoveIPC was introduced in RHEL 7.2 through Systemd v219.
When set to yes, this option forces a cleanup of all allocated inter-process communication (IPC) resources linked to a user leaving his last session.
If a daemon is running as a user with a uid number >=1000, it may crash.
This option should always be set to no by default but, due to the logic of package upgrade, it is highly advisable to set RemoveIPC=no in the /etc/systemd/logind.conf file followed by # systemctl restart systemd-logind (source).
Answer: I finally found out the way to reproduce RemoveIPC problem.
<code>$ cat /etc/systemd/logind.conf |grep RemoveIPC
RemoveIPC=yes

$ systemctl restart systemd-logind
</code>

<code>1. remember there is no semaphore yet
---------------------------------------------------------------------------

╭─root@localhost  ~
╰─$ ipcs -s

------ Semaphore Arrays --------
key        semid      owner      perms      nsems

---------------------------------------------------------------------------
2. loginctl list-sessions
    (just one session exist in logind session list - root user)
---------------------------------------------------------------------------

╭─dplee@localhost  ~
╰─$ loginctl list-sessions
   SESSION   UID USER         SEAT
         1           0     root           seat0
   1 sessions listed.

---------------------------------------------------------------------------
3. RemoveIPC = yes, check if systemd-logind is up
    (set RemoveIPC = yes in /etc/systemd/logind.conf and execute "systemctl restart systemd-logind")
---------------------------------------------------------------------------

╭─root@localhost  ~
╰─$ cat /etc/systemd/logind.conf | grep RemoveIPC
RemoveIPC=yes

╭─root@localhost  ~
╰─$ ps -ef | grep systemd | grep login
root       923     1  0 12:26 ?        00:00:00 /usr/lib/systemd/systemd-logind

---------------------------------------------------------------------------
4. change user to dplee2 and start semaphore creation process.
---------------------------------------------------------------------------

╭─root@localhost  ~
╰─$ su - dplee2

╭─dplee2@localhost  ~
╰─$ cd work/test

╭─dplee2@localhost  ~/work/test
╰─$ cat t.c
#include <sys/types.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <stdio.h>
#include <unistd.h>

union semun
{
    int val;
    struct semid_ds *buf;
    unsigned short int *array;
};

static int  semid;
int main(int argc, char **argv)
{
    FILE* fp;

    union semun sem_union;

    struct sembuf mysem_open  = {0, -1, SEM_UNDO};
    struct sembuf mysem_close = {0, 1, SEM_UNDO};
    int sem_num;

    sem_num = 1;

    semid = semget(IPC_PRIVATE, sem_num, 0600|IPC_CREAT);
    if (semid == -1)
    {
        perror("semget error ");
        return -1;
    }

    sem_union.val = 1;
    if ( -1 == semctl( semid, 0, SETVAL, sem_union))
    {
            printf( "semctl()-SETVAL 실행 오류\n");
            return -1;
    }

    while(1)
    {
        sleep(1);
    }

    return 1;
}

╭─dplee2@localhost  ~/work/test
╰─$ nohup ./a.out &
[1] 4602
nohup: ignoring input and appending output to `nohup.out'

---------------------------------------------------------------------------
5. check if semaphore created successfully and process is up.
---------------------------------------------------------------------------

╭─dplee2@localhost  ~/work/test
╰─$ ipcs -s

------ Semaphore Arrays --------
key        semid      owner      perms      nsems
0x00000000 229376     dplee2     600        1

╭─dplee2@localhost  ~/work/test
╰─$ ps -ef | grep dplee2 | grep a.out
dplee2    4602  4537  0 12:30 pts/0    00:00:00 ./a.out

---------------------------------------------------------------------------
5. still just one session is in session list : root user (not dplee2)
---------------------------------------------------------------------------

╭─dplee2@localhost  ~/work/test
╰─$ loginctl list-sessions
   SESSION    UID USER             SEAT
         1            0     root              seat0
   1 sessions listed.

---------------------------------------------------------------------------
6. create one more session (dplee2 user) through another window.
     (dplee2 session is SESSION id 3 as below)
---------------------------------------------------------------------------
$ ssh email@example.com

╭─dplee2@localhost  ~/work/test
╰─$ loginctl list-sessions
   SESSION    UID USER             SEAT
         1               0  root               seat0
         3       1005  dplee2
   2 sessions listed.

---------------------------------------------------------------------------
7. semaphore still exists and process is also still up.
---------------------------------------------------------------------------

╭─dplee2@localhost  ~/work/test
╰─$ ipcs -s

------ Semaphore Arrays --------
key        semid      owner      perms      nsems
0x00000000 229376     dplee2     600        1

╭─dplee2@localhost  ~/work/test
╰─$ ps -ef | grep dplee2 | grep a.out
dplee2    4602  4537  0 12:30 pts/0    00:00:00 ./a.out

---------------------------------------------------------------------------
8. close the second window (dplee2 user session) or log out.
    (or just execute "loginctl terminate-session 3" command)
   Then, dplee2 session is gone. (Only root user(the first logged in session) exists)
---------------------------------------------------------------------------

╭─root@localhost  ~/work/test
╰─$ loginctl list-sessions
   SESSION      UID USER             SEAT
         1                0   root               seat0
   1 sessions listed.

---------------------------------------------------------------------------
9. process is still up and the semaphore is gone. <-- removed by system
---------------------------------------------------------------------------

╭─root@localhost  ~/work/test
╰─$ ps -ef | grep dplee2 | grep a.out
dplee2    4602  4537  0 12:30 pts/0    00:00:00 ./a.out

╭─root@localhost  ~/work/test
╰─$ ipcs -s

------ Semaphore Arrays --------
key        semid      owner      perms      nsems
</code>


Como parar o "for" quando encontrar um elemento na lista?

Question: Tenho o seguinte código:
Console.Clear();
Console.Write("Nome da moto:");
string nomem = Console.ReadLine();
for (int i = 0; i < ListadeVeiculos.Count; i++)
{
      if (nomem == ListadeVeiculos[i].Nomemoto)
           Console.Write("Preço R$:" +ListadeVeiculos[i].Preco.ToString("0.00"));
      else Console.Write("Moto não cadastrada!");
}
Console.ReadKey();

Tem alguma forma de parar o for quando encontrar o elemento na Lista?
Nesse meu código se inserir 2 elementos na lista mostra a mensagem do if e do else.
Comment: Seria isso? https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/break
Answer: break encerra o laço. veja mais sobre ele em Deve-se usar break em for?. O código ficaria melhor assim:
Write("Nome da moto:");
var nomeMoto = ReadLine();
var cadastrada = false;
foreach (var veiculo in ListaDeVeiculos) {
    if (nomeMoto == veiculo.NomeMoto) {
        Write($"Preço {veiculo.Preco:C");
        cadastrada = true;
        break;
    }
}
if (!cadastrada) Write("Moto não cadastrada!");

Coloquei no GitHub para referência futura.
A impressão que dá é que o código tem outros problemas.
Comment: Obrigado! Consegui resolver o problema
Answer: Existe a instrução break que termina um loop.
var motos = new List<string>
{
    "MotoA",
    "MotoB",
    "MotoC",
    "MotoD"
};

foreach (var moto in motos)
{
    if (moto.Equals("MotoC"))
    {
        break;
    }
 }

Mais sobre a instrução break
https://docs.microsoft.com/pt-br/dotnet/csharp/language-reference/keywords/break


Arzela-Ascoli variant for $C^1$ functions

Question: Let $K$ be a compact subset of a smooth manifold, and for simplicity let $d(\cdot,\cdot)$ be any metric on $K$. Let $C^1(K)$ be the set of $C^1$ real-valued functions on $K$ equipped with the norm $$\|f\|_{C^1}:= \max \{\|f\|_\infty, \|df\|_\infty\},$$

Definition: Let $\mathcal{F}$ be a subset of $C^1(K)$. $\mathcal{F}$ is bounded if $$\exists M > 0: \forall f \in \mathcal{F}: \|f\|_{C^1} < M.$$ $\mathcal{F}$ is equicontinuous if for every $x \in K$ and $\epsilon > 0$ there exists $\delta > 0$ such that $$d(x,y) < \delta \implies \max\{|f(x)-f(y)|, \|df(x)-df(y)\|\} < \epsilon.$$
  $\mathcal{F}$ is closed if it is a closed subset of $C^1(K)$.

I believe the following variant of the Arzela-Ascoli theorem is true:

Theorem: A subset $\mathcal{F}$ of $C^1(K)$ is compact (in the topology induced by the $C^1$ norm) if and only if $\mathcal{F}$ is closed, bounded, and equicontinuous.

From reading the proof of the Arzela-Ascoli theorem, it seems to me that one could prove this variant with straightforward modifications. Can anyone please provide a reference containing this generalization (or point out that I am mistaken)?
Answer: You need to be a bit careful with definitions. What does $f \in C^1(K)$ mean? If you mean that $f$ extends to a $C^1$ function on $M$ with derivative $df$, this is false. Let $M = \mathbb R$ and let $K = \{0\} \cup \{1/n: n \in \mathbb N\}$, and let $f_n (1/k) = \sqrt k$ for $k \leq n$, $0$ otherwise, and let $df_n = 0$. A less pertinent, but still worth considering, point is that a smooth manifold does not come equipped with a natural norm on the cotangent space, so an appropriate definition of $\|df\|$ takes a little consideration (although you get a natural norm once you have chosen a metric).
Nonetheless, there is something to what you have written here. Mainly you need to add some Taylor remainder type term. Let's first consider $K \subset \mathbb R^n$ compact, $f_n: K \to \mathbb R$, and $G_n : K \to \mathbb R^n$ such that $f_n$ extends to a $C^1$ function on $\mathbb R^n$ with gradient $G_n$ on $K$. Does there exist $f, G$ such that $f_n \to f$, $G_n \to G$, and $f$ extends to a $C^1$ function such that $G = \nabla f$ on $K$? The answer is yes if the $f_n$ are uniformly bounded and uniformly equicontinuous, and the $G_n$ are, and
$$\sup\limits_n \sup\limits_{x,y \in K, x \neq y} {f_n(y) - f_n(x) + \langle G_n(x), y-x \rangle \over |x-y|^2} < \infty.$$
It follows from the usual Arzela-Ascoli theorem that $f_n$ and $G_n$ converge to some functions $f$ and $G$, and it is easy to check that the pair $(f,G)$ satisfy the above estimate. Any pair (called a $1$-jet) that satisfies this estimate extends to a $C^{1,1}$ function on $\mathbb R^n$ by Whitney's extension theorem. A good reference for further discussion and a proof is Stein's "Singular Integrals and Differentiability Properties of Functions" as well as this expository paper by Bierstone.
On a manifold, you can reduce to the $\mathbb R^n$ case by composing with coordinate functions. You can then extend the limit functions on each coordinate patch, and patch them together with a partition of unity.
Comment: Thanks for the answer. I'm having trouble understanding the first counterexample you gave. For example, why do you say "let $df = 0$"? Do you mean $df_n$?
Comment: Yes, you are right, it should read $df_n$.
Comment: I'm failing to see how the $f_n$ can extend to $C^1$ functions on $\mathbb{R}$ while simultaneously having $df_n\equiv 0$. Am I missing something here?
Comment: You're can only take $df_n = 0$ on $K$. Indeed the $C^{1,1}$ norm of an extension of $(f,G)$ is comparable to the Taylor remainder term in the second paragraph.
Comment: Ah, I understand now. Thank you.


Connect to ubuntu port from docker container

Question: I have a application running on port 8180 on my local machine
When I try to wget http://192.168.1.12:8180/auth from docker container,
I get following error
--2019-10-10 08:17:03--  http://192.168.1.12:8180/auth
Connecting to 192.168.1.12:8180... failed: Connection refused.

I tried following
❯ sudo ufw status                                                                                [14:17:44]
Status: active

To                         Action      From
--                         ------      ----
8180/tcp                   ALLOW       Anywhere
443/tcp                    ALLOW       Anywhere
80/tcp                     ALLOW       Anywhere
8180/tcp (v6)              ALLOW       Anywhere (v6)
443/tcp (v6)               ALLOW       Anywhere (v6)
80/tcp (v6)                ALLOW       Anywhere (v6)

Still getting the same error.
I have also tried --add-host="www.kkk.com:192.168.1.12"
and tried http://www.kkk.com:8180/auth
still got same issue
How to fix this??
❯ netstat -tnl |grep 8180                                                                                [16:39:04]
tcp        0      0 127.0.0.1:8180          0.0.0.0:*               LISTEN

Comment: `Connection refused` suggests that nothing is listening on that port on the target server.
Comment: i know what i means. there is a server running. still getting this error
Comment: Just that it's running doesn't mean that it's listening on that interface. Your post does not contain enough information to analyze the issue.
Comment: from the host machine when i go http://localhost:8180/auth i get response
Comment: Please run `netstat -tnl |grep 8180` and edit the output into your question.
Comment: updated the question
Answer: Your service is only listening on the loopback interface (127.0.0.1). To make it available on other interfaces bind it to 192.168.1.12 or 0.0.0.0 instead (to have it listen on all interfaces).


Clarification to: A finite group that has at most one subgroup of any size is cyclic

Question: I have been reading:  http://www.math.uconn.edu/~kconrad/blurbs/grouptheory/coset.pdf
Theorem 7.11 states: A finite group that has at most one subgroup of any size is cyclic.
I think this is a very crude formulation of theorem stated in this thread: If an Abelian group $G$ has order $n$ and at most one subgroup of order $d$ for all $d$ dividing $n$ then $G$ is cyclic
I believe the author of Theorem 7.11. forgot to explicitly state the order of each subgroup H has to the order of group G. Also, I don't really see, if the groups really have to be abelian or not, example (?)
As always: Any constructive hint, comment, answer or recommendation for further reading are appreciated. Thanks in advance.
Comment: Perhaps prove the contrapositive.
Comment: By missing out the conditions that the group is Abelian and that the order of the subgroup divides the order of the group, Theorem 7.11 is more general than the other statement because there is less you have to check before you can apply it. Of course it is easy that the order of a subgroup divides the order of the group, and of course once you know a group is cyclic, you know that it (and all its subgroups) are abelian. But in the 7.11 formulation these are consequences not assumptions.
Comment: Relevant: [Groups having at most one subgroup of any given finite index](http://math.stackexchange.com/questions/9934/groups-having-at-most-one-subgroup-of-any-given-finite-index)
Answer: You  are correct, it should explicitly state any size that divides the order of $G$. However the statement is still true in general. Here is the sketch of proof.
Since every subgroup of $G$ also has the same property, you may assume by induction that all subgroups of $G$ are cyclic. Also it is clear that all subgroups are normal in $G$. Since all Sylow $p$-subgroups of $G$ are normal we deduce that $G$ is nilpotent. Hence $G$ is a direct product of its Sylow subgroups which are all cyclic. So $G$ is cyclic.
Comment: The group $\mathbb Z / 6\mathbb Z$ has exactly one subgroup for each divisor of $6$, but isn't a $p$-group. I think the condition that each subgroup is normal implies nilpotency, but not that it must be a $p$-group.
Comment: @Stefan I meant without loss of generality we may assume that $G$ is a $p$-group. I edited my answer in a,I hope, more clear way.
Comment: Yes, I like your proof as it is way simpler than the counting arguments from the link.


How to "open" existing VMs in Hyper-V without importing them?

Question: I had a PC with two physical disks:

C: containing the host operating system
D: containing a folder D:\VMs where all my virtual machines were stored

Now, the C: disk died. I bought a new one, reinstalled Windows on it, enabled Hyper-V feature and now I just need to open the VMs from the D:\VMs folder. However, I don't seem to be able to find a menu item or anything that would allow me to do that - the only thing I see is the "import" command which unfortunately requires the VMs to be explicitly exported (my machines weren't).
I would think that when I have all the files constituting a VM (the VHD file, some XML files describing the settings etc.) it should be somehow possible to just "open" these existing VMs in Hyper-V, right? What command am I missing?
Edit: I know I can create a blank virtual machines and then just point them to use existing VHDs. However, I am not sure about all the different settings I've made to those VMs so I hope there's a way to simply open those existing VMs instead of recreating them.
Answer: You will want to create a new VM in the Hyper-V console, and when you get to the part about creating a new .vhd, or selecting one, simply browse to the existing .vhd files you have.

New > Virtual Machine
Name it, and select the directory the VM is in that you want to bring up
Select memory and network
"Use and existing virtual hard disk"  and select your .vhd

This method will bring them up exactly as they were when the server died, just reapply the same network, cpu and memory settings. Any machines that had snapshots will only be able to load them if you do an actual export/import, otherwise you are loading the base .vhd
Comment: So there is no way to "open" existing VMs without explicitly exporting / importing them? You just mentioned a couple of things that might cause trouble if I were to recreate all machines again (losing snapshots, VM settings etc.)
Comment: You can mount them as a volume, but that's about it. The only way, that i'm aware of to get them running w/o the ability to export from the old box, is the method I described.
Answer: this is possible, but it's not supported by microsoft.
basically, you have to create a new VM, copy the settings to the XML files, and rename the snapshots.
complete directions are here: http://eniackb.blogspot.com/2009/05/how-to-recover-hyper-v-virtual-machine.html
Answer: I had some success by importing an existing VM and just ensuring that the folders point to the original ones. A bit risky though as theoretically less robust import logic may try to overwrite the (disk) files with themselves, corrupting data. It worked for me - but I would make a copy first or ensure a backup is present and recoverable.


Seria interessante diretivas usando http.get?

Question: Este é um pedaço do html:

    {{projeto.name}}
    {{projeto.status}}

O mesmo utiliza um controller que faz a seguinte função
$http.get('system/project/listProjectsPerUser')
.then(function (response){
    if(response.data.success){
        $scope.projetos = response.data.projects;
        console.log($scope.projetos);
    }
    else{
        console.log('Erro');
    }
});

Minha dúvida é a seguinte, se seria interessante colocar esse html como diretiva e utilizar a própria diretiva para realizar a mesma função do controller, de preencher o array projetos e exibir o html.
Answer: Vai depender do seu contexto, mas de modo geral, não, pois toda vez que a diretiva for renderizada, ela irá executar a chamada $http. Muitas vezes a informação não muda constantemente de modo que precisamos toda hora refazer a chamada. Mas se for o caso de necessitar atualizar em u intervalo de tempo curto, ainda assim esse é o trabalho de um service, não de u  controller, directive ou component.
Primeiramente, o ideal seria usar component ao invés de directive para seguir os novos padrões de Angular (2, 3, 4...). Depois, você deve executar as chamadas $http e, posteriormente, armazenar as informações em um service. Depois, em seu component você apenas solicita os dados ao service e exibe.
Deste modo, o seu component pode tranquilamente ter o HTML internamente.


Use the definition of convergence of a sequence to show $\lim \frac {2n^2}{n^3+3}= 0$

Question:
Use the definition of convergence of a sequence to show $$\lim_{n\rightarrow \infty} \frac  {2n^2}{n^3+3}= 0$$

I understand that to do this we must show $ \frac  {2n^2}{n^3+3} \leq \varepsilon$, but I'm not sure how to do that.
Comment: If you have access to the Squeeze Theorem, the argument can be fairly short. Do you?
Comment: @alex.jordan preferably use only the definition if that's what the question asks for.
Comment: Actually to be pedantic you would need to specify $n$ in the limit. You probably mean $n \to \infty$, right?
Comment: @mathreadler It can be argued that when $a_n$ is understood to be a sequence (as opposed to a function of real $n$ or some other object), that $\lim a_n$ is unambiguously asking for the limit as $n\to\infty$. But it would come down to convention.
Comment: Yes you are right, I missed the word "sequence" and only saw the word limit ( at the time of reading ! ). Probably the natural numbers are the convention if the word "sequence" is used, I agree there ;)
Answer: Given $\epsilon>0$ choose $N$ large enough such that $\frac{2}{N} < \epsilon$ so that for $n>N$ we have $$\bigg|\frac{2n^2}{n^3+3}-0\bigg|=\frac{2n^2}{n^3+3}\leq\frac{2n^2}{n^3} =\frac{2}{n}< \frac{2}{N}<\epsilon$$


PHP Zip can't be found

Question: I'm running LEMP on a digitalocean droplet. We're running php v 7.2.19 on ubuntu 18.04.1.
I'm trying to install php-zip (apt-get install php7.2-zip) but am getting the error:

apt-get install php7.2-zip
  Reading package lists... Done
  Building dependency tree
  Reading state information... Done
  E: Unable to locate package php7.2-zip
  E: Couldn't find any package by glob 'php7.2-zip'
  E: Couldn't find any package by regex 'php7.2-zip'

I can't figure out why I can't install. Any suggestions?
Comment: What repos/ mirrors are you using? 17.04 is EOL since 2018-01
Comment: I'm not sure - sry I'm still learning a lot about this stuff. I booted with the DO one-click setup, which is "LEMP on18.04". Is there a way to check the repos/mirrors?
Comment: You are on 18.04, not 17.04. Try `sudo add-apt-repository universe && sudo apt update && sudo apt install php7.2-zip`. I assume your apt lists are wrong, check the files and entries in `/etc/apt/sources.list` and `/etc/apt/sources.list.d/`
Comment: that seems to have worked - thanks! I'm testing now but if y ou add an aswer I'll go ahead and accept it
Answer: The universe repository was missing. Solved by adding it via sudo add-apt-repository universe and then installing php7.2-zip.

PHP Zip can't be found


R Multiple Linear Regression; plotting results

Question: I'm trying to do some exploratory analysis on some weather. I'd like to do a multiple linear regression on my data and then plot the predicted value against the actual value. Here's where I've got so far:
data<-read.csv("Amsterdam.csv", header=TRUE)
data2<-data[SolarAltitude>0,]
data2.lm<-lm(DirectRadiation ~ DryBulbTemperature + RelHum
   +AtmosphericPressure, data=data2)
data.data.frame(data2,fitted.value=fitted(data2.lm),residual=resid(data2.lm))

If you could help, I would be very grateful,
Comment: With just one response variable, your method is multiple rather than multivariate. Indeed, using several predictors is hardly a big deal now, and many people would drop the multiple, not that "multiple" is in any sense wrong. I've edited accordingly.
Comment: Physically, your regression doesn't make sense. Direct radiation is an external input. The other variables are state variables saying something about the atmosphere at ground level. The physics here doesn't reduce to linear relations any way.
Comment: Direct radiation at the top of the atmosphere, yes, but it gets more complicated as to how much of it gets to the surface. I agree it's a long shot, but I'm trying to use this estimate data I don't have and I'm trying to make something that might be better than nothing.
Answer: The function fitted returns the fitted (predicted) values. To plot the fitted values against the actual values, you can use:
plot(data2$DirectRadiation, fitted(data2.lm))

This will produce a plot with the actual values on the horizontal axis and the fitted values on the vertical axis.
If the above code doesn't work due to missing data, you can try one of the following approaches:
 plot(fitted(data2.lm) + residuals(data2.lm), fitted(data2.lm))

 plot(data2.lm$model[[1]], fitted(data2.lm))

Comment: Sorry this doesn't work, > nrow(data2)
[1] 4407
> plot(data$DirectRadiation,fitted(data2.lm)
+ )
Error in xy.coords(x, y, xlabel, ylabel, log) :
  'x' and 'y' lengths differ
> nrow(fitted(data2.lm))
NULL
Comment: Do you have missing data?
Comment: @James See the update of my answer.


Ignoring all line feeds in a FreeMarker template

Question: I'm trying out FreeMarker, not for a web application but to generate text within a desktop application.  I'd like to get the text without any linefeeds, however it always appends a linefeed. For example, this would produce "blah blah\n"
<#if docType=1>
blah blah
<#if docType=2>
more blah
<#/if>

Any ideas? Bunching it all into one line works, but is horrible. Thanks.
Answer: See perhaps White-space handling, ftl and compress directives. But you can't suppress all linefeeds.
Another solution : filter the output, and replace \n by " ".
Comment: Thanks - actually I've found you can compress all line feeds.
    <@compress single_line=true>

Answer: I would also take a look at t,lt, and rt directives.
Using your example,
<#if docType=1>
blah blah <#t>
<#if docType=2>
more blah<#t>
<#/if>

Should produce blah blah more blah on a single line
Answer: <@compress single_line=true>...</@compress>

...this will output everything in between the compress tag as one line.


TCP-Streaming: Audio/Video Synchronization

Question: I have a question regarding TCP/Live-Streaming/Synchronization (programming language: Java):
Let's say I have a Client, that is capturing the Audio and Video from a camera. It is sending the audio and video data simultaneously (via Threads) via TCP-sockets to a server, that is receiving the audio and video stream simultaneously on two different threads.
[I know, UDP is normally used for live-streaming applications but there are reasons, why I'm using TCP..]
So, the question is: Will there be any chance to get out of sync ever via TCP? There are two streams on different sockets (one for audio, one for video), there may be a problem, that a packet has to be re-sent, but will the resend of the lost-packet be a problem (I mean, when resending a packet via TCP, will this cause a permanent delay or will the client just send the lost packet and the next packet faster for a few milliseconds)?
I'm sending the audio and video signal at the same time to the server. Will they always arrive at the same time on the server? If not, is there a way to produce/simulate the problem?
I've done some tests and the audio and video was always in sync. But I'm not sure, if it will always be like that (even after more than 5 hours of streaming).
Thank you.
Answer: If you use two different sockets, there's no guarantee. TCP guarantees data transmission in the correct order, but if you use two different streams for audio and video, it doesn't apply.
However, if the connection is fast enough there shouldn't be a problem. It sends it as fast as it can. If one stream gets "clogged up" though, it will delay and fall out of sync, but I doubt that would happen with your case for sending videos (as long as it's not too high an FPS or resolution).
I think it would be safer to use a single stream, but I think your way is fine to be honest. It all depends on: speed of the client, speed of the server, and speed of the network.


Why do SAC and TD3 use multiple critic networks as opposed to single network with multiple outputs?

Question: Q-function approximators based on neural networks tend to overestimate the Q-function. Accordingly, reinforcement learning algorithms such as Soft Actor-Critic (SAC) and Twin Delayed DDPG (TD3) use two separate critic networks which have single scalar output per sample and take minimum of their predictions to compensate for the inherent overestimation.
Why do they use separate networks with scalar output as opposed to a single network with vector output per sample, where, as a last step, minimum is taken across this vector? Isn't this equivalent, but more efficient?
Answer: Let's consider a critic $Q_\theta(s,a)$ implemented as a simple MLP with multiple hidden layers and some sort of nonlinear activation after each layer.
Instead of thinking of the critic as one block, we can decompose it into a feature extractor $\phi(s,a)$ comprising everything except the last layer, plus the final linear layer $w$, i.e. $Q_\theta(s,a) = w^T\phi(s,a)$.

Why do they use separate networks with scalar output as opposed to a single network with vector output per sample, where, as a last step, minimum is taken across this vector?
Isn't this equivalent, but more efficient?

When using double critics, we typically train them from scratch with two different random initializations, i.e. both critics will have separate feature extractors $\phi_1(s,a)$ and $\phi_2(s,a)$, as well as separate final layers $w_1$ and $w_2$.
What you're considering by having a vectorial output would mean having two output vectors [$w_1$,$w_2$] with the same, shared feature extractor $\phi(s,a)$, so it is definitely not equivalent.
The motivation for the double critics is to have two different "independent" estimators that "balance each other out" (in a very vague sense). Having two different outputs achieves this somewhat, but they are less "independent" than having two entirely different models.
I would encourage you to try it out in practice, it will definitely save compute and even if it performs a bit worse it would still be an interesting finding!
Comment: no, it's not independence that they are trying to achieve, but to counterbalance the overestimation due to the nature of Q learning
Comment: Yes, that's why I wrote `in a very vague sense` and added quotation marks. Of course, the two estimators are anything but independent, being trained on exactly the same data.


How does Spring Cloud Config understand the external properties?

Question: My question is how will a spring boot application which is pushed on cloud understand that it has to use so-and-so properties file that is stored in Git and referred in Spring Cloud config server?
I understand a cloud config server will have the Git repository url, etc.
and
a binding of spring-boot application with the spring cloud config service should happen,
but still I don't understand how an application understands that it has to use a properties file stored externally?
Answer: Name the properties file in the Git repo that is used by the Config server like:
/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties

Meaning if your client app is name mysoapapp, create a file: mysoapapp-dev.properties. Now run mysoapapp passing the active Spring profile: dev, using argument: -Dspring.profiles.active=dev
You should also confirm that the Config server is able to serve the files by sending a request like:
curl -v http://<the config server>/mysoapapp-dev.properties

and it should retrieve the properties.
I published a couple of blog posts about this topic that might help you:

Centralized and versioned configuration using Spring Cloud Config Server and Git
Refreshable Configuration using Spring Cloud Config Server, Spring Cloud Bus, RabbitMQ and Git
Comment: If I am not using spring profiles then ? I should name my properties file as mysoapapp.properties?
Comment: I don't remember, I can try once I get to my laptop, in the mean time, could you also try it?


Exchanging data between client and server without using sockets

Question: I need to develop an application in which I have a Java script running on the client that needs to call Java procedures on the server (for example getting data from a database, I cannot do it directly from the client because the only port that is open on my Web Service is port 80). Since the only port open on the server is port 80 and a Web Service is listening on that port I cannot create a Java socket (am I correct?). What other options do I have?
Thanks a lot in advance, any help will be greatly appreciated
Answer: You can not create another listener on the same server port - that is correct, but you can create a socket - that is the actual connection between the browser and server.
There may be a (large) number of sockets connections between client(s) and server but only one listener per public port.
Comment: That's what I guessed...Do you have any suggestion on how I could transfer data between server and client then?
Comment: Usually one would use AJAX https://www.google.co.uk/search?q=ajax to create asynchronous connections form client side JavaScript to server side (pages/scripts/servlets...)  You will have to read about it yourself and then ask for help with specific problems if you have any.


Failed to parse date ["2021-05-06 15:24:26 CEST"]: Invalid time zone indicator ' ', but timezone exists

Question: I am struggling a bit with the date format patterns in Kotlin.
I have a PHP backend, that formats dates in the format "Y-m-d H:i:s T", which as you might guess from the title, results in:  ["2021-05-06 15:24:26 CEST"]. As you can see there is also a timezone, in our case "CEST".
However, my Kotlin app tells me, that the " " is an invalid timezone format.
I am pretty confused of the different patterns used and it took me a while to get a grip, so it is possible, that there is an error inside of the pattern.
In Kotlin I have the following GSONBuilder:
val gson = GsonBuilder().setLenient().setDateFormat("yyyy-MM-dd HH:mm:ss z").create()

I also tried the pattern "yyyy-MM-dd H:m:s z" and "yyyy-MM-dd HH:mm:ss Z", but it didn´t work either. Is there an error in my pattern? I mean, the timezone is part of the result arriving. If yes, what would be the correct pattern?
Note: Debugger tells me an index out of bounds-exception, if that might help.
EDIT:
Shortened exception stack:
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: app, PID: 27254
    com.google.gson.JsonSyntaxException: 2021-05-11 10:07:04 CEST
        at com.google.gson.DefaultDateTypeAdapter.deserializeToDate(DefaultDateTypeAdapter.java:151)
        at com.google.gson.DefaultDateTypeAdapter.read(DefaultDateTypeAdapter.java:128)
        at
...
com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:41)
...
retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:40)
...
        at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:243)
        at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:153)
        at okhttp3.RealCall$AsyncCall.execute(RealCall.java:174)
        at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
        at
...
     Caused by: java.text.ParseException: Failed to parse date ["2021-05-11 10:07:04 CEST"]: Invalid time zone indicator ' '
        at com.google.gson.internal.bind.util.ISO8601Utils.parse(ISO8601Utils.java:274)
        at com.google.gson.DefaultDateTypeAdapter.deserializeToDate(DefaultDateTypeAdapter.java:149)
        at
... (Same as first stack trace)
     Caused by: java.lang.IndexOutOfBoundsException: Invalid time zone indicator ' '
        at com.google.gson.internal.bind.util.ISO8601Utils.parse(ISO8601Utils.java:245)
        at com.google.gson.DefaultDateTypeAdapter.deserializeToDate(DefaultDateTypeAdapter.java:149)
        at
... (same as first stack trace)

Edit 2:
Since CEST is indeed no valid Java ID, I changed the PHP format from "Y-m-d H:i:s T" to "Y-m-d H:i:s e", which now results in "2021-05-11 10:07:04 Europe/Berlin" and is indeed a valid timezone identifier according to cutikos comment.
However, the error is still the same.
Comment: I don't think `CEST` is a valid id https://garygregory.wordpress.com/2013/06/18/what-are-the-java-timezone-ids/
Comment: Well, it was produced by PHP, so it should be
Comment: Can you post your debugger error message?
Answer: The solution has been pretty simple:
The java format "yyyy-MM-dd HH:mm:ss Z" only accepts the numbers "00a0" format, so the correct PHP format would be:
"Y-m-d H:i:s O"
Hope this helps another person, struggling with dateformat conventions.


How to interpret the lasso selection plot

Question: I did lasso selection using lars::lars(), then I got this plot. I have no idea how to interpret it:

Could anyone provide a brief explanation? Why does it plot standardized coefficients against |beta|/max|beta|?
Comment: I am a bit fried to write a complete answer right now but for what's worth check the paper "Regression Shrinkage and Selection via the Lasso" by Tibshirani. You are practically looking at how many regression coefficients $\beta$ you are using (the # of solid vertical lines). More $\beta$'s enter your regression equation sequentially as your $|\beta|/max(|\beta|)$ increases.
Comment: Thanks for your comments. What I am wondering most is whether this figure tells me the best selected model. In another word, which variables and how may variables should be used in the selected model?
Comment: No, it does not help with that. $\alpha$/model selection is usually done via cross validation.
Answer: In regression, you're looking to find the $\beta$ that minimizes:
$ (Y - X_1\beta_1 - X_2\beta_2 - \text{...})^2 $
LASSO applies a penalty term to the minimization problem:
$ (Y - X_1\beta_1 - X_2\beta_2 - \text{...})^2 + \alpha\sum_i{|\beta_i|}$
So when $\alpha$ is zero, there is no penalization, and you have the OLS solution - this is max $|\beta|$ (or since I didn't write it as a vector, max $\sum{|\beta_i|}$).
As the penalization $\alpha$ increases, $\sum{|\beta_i|}$ is pulled towards zero, with the less important parameters being pulled to zero earlier. At some level of $\alpha$, all the $\beta_i$ have been pulled to zero.
This is the x-axis on the graph. Instead of presenting it as high $\alpha$ on the left decreasing to zero when moving right, it presents it as the ratio of the sum of the absolute current estimate over the sum of the absolute OLS estimates. The vertical bars indicate when a variable has been pulled to zero (and appear to be labeled with the number of variables remaining)
For the y-axis being standardized coefficients, generally when running LASSO, you standardize your X variables so that the penalization occurs equally over the variables. If they were measured on different scales, the penalization would be uneven (for example, consider multiplying all the values of one explanatory variable by 0.01 - then the coefficient of the OLS estimate would be 100x the size, and would be pulled harder when running LASSO).


Characterization of Jordan Bases with Jordan Chains

Question: A theorem in some notes I'm reading states:
Let $T \colon V \rightarrow V$ be linear and $E = (e_1,\dots,e_n)$ be a basis for V. Then E is a Jordan Basis for T and V if and only if there exists $k \geq 1$ and integers $i(0),\dots,i(k)$ such that $0 = i(0) < \dots < i(k) = n$ and
$(e_{i(t)+1},e_{i(t)+2}, \dots, e_{i(t+1)})$
Is a Jordan chain for all t with $0 \leq t < k$.
The conditions stated make no sense to me (it is probably a mistake in the notes), so what I'm looking for is an explanation of the last part of the theorem, or an exact statement of what it should be. Thanks
Comment: If it helps, in lectures he skipped this proposition saying that it was unnecessary. I don't really see how it follows from definitions $16, 22, 24$, so perhaps emailing him would clear it up?
Answer: The result (which is more of a definition) is that E is a Jordan basis if and only if it is a basis which is a union of disjoint Jordan chains.


How can I prove that the Wiener index of the hypercube graph is $k \cdot 4^{k-1}$?

Question: I'm trying to find the Wiener index of the Hypercube graph, $Q_k$. In case anyone does not know what that is, it's a graph where every vertex is labelled by a binary $k$-tuple, and where two vertices are connect only if the tuples differ in only one place. So for example, $Q_2$ would have vertices labelled $(0, 0), (0, 1), (1, 0)$ and $(1, 1)$. $(0, 0)$ would be connected to $(0, 1)$ and $(1, 0)$, and so on.
I wrote out a few examples and I think that the Wiener index of the graph can be represented by $k \cdot  4^{k-1}$. But how do I prove this? The only idea that occurs to me is to use induction, but I am not entirely sure how to go about doing this. Any help with this would be appreciated. If anyone has any other ideas for a proof, that would be fine too.
Comment: I think it's interesting that you went to to much trouble to explain the hypercube graph, which I think is a standard example, but didn't explain at all the Wiener index, which I had never heard of before.
Answer: Consider the vertex $\mathbf 0=(0,0,\dots,0)$ of the hypercube graph $Q_n$. For each $r\in[n]=\{1,2,\dots,n\}$ there are $\binom nr$ vertices at a distance of $r$ from $\mathbf 0$, so$$\sum_{v\in V(Q_n)}\operatorname{d}(\mathbf 0,v)=\sum_{r=1}^nr\binom nr.$$Since all vertices of $Q_n$ are similar, the Wiener index of $Q_n$ is equal to$$\frac12\sum_{u\in V(Q_n)}\sum_{v\in V(Q_n)}\operatorname{d}(u,v)=\frac12\cdot2^n\sum_{r=1}^n r\binom nr=2^{n-1}\sum_{r=1}^n r\binom nr.$$Differentiating the binomial identity$$\sum_{r=0}^n\binom nrx^r=(1+x)^n$$we get$$\sum_{r=1}^n r\binom nrx^{r-1}=n(1+x)^{n-1};$$on setting $x=1$ we have$$\sum_{r=1}^n r\binom nr=n2^{n-1},$$and so the Wiener index of $Q_n$ is equal to$$2^{n-1}\sum_{r=1}^n r\binom nr=2^{n-1}\cdot n2^{n-1}=n4^{n-1}.$$
Answer: For any two graphs $G$ and $H$ we have $$ W(G \square H ) = |V(G)|^2 W(H) + |V(H)|^2W(G),$$ where $W(G)$ is the Wiener index of $G.$
Now the hypercube graph $Q_k = Q_{k-1} \square K_2$ and the result now immediately follows by induction.


How to declare a datetime type of variable in ssms

Question: this is the code i tried and i got some errors in it I need to create a variable named createddate and use it in the another table.
Comment: make sure that is part of the question then and still how is it not doing that? Please give us an example input where the problem occurs. Make sure to [edit] the question with these details. Comments are not the place for new additions to the question
Comment: Okay so what exactly should be the output and what error are you getting? How is it not working? What is the current result as opposed to the expected result? What input are you using for testing? Please provide us a bit more details to help us debug the problem without needing us to create tests, compile and run the code ourselves. If we have all the details it is much easier for us to help you. So please help us, help you.
Comment: Actually  what I want in my program  first is to when user enters list size less than 0 or greater than 21 then it should display invalid input and exit the program, and next when user enters input if he enters negative numbers it should display invalid input and exit the program. along with that if user enters only 4 inputs where 5 inputs are required then also it should give invalid input and exit the program.
Comment: ok I edited that there is no place the question became bigger by elaborating it.
Answer:
along with that if user enters only 4 inputs where 5 inputs are required then also it should give invalid input and exit the program.

Please provide a working example in which you can only enter 4 inputs to your program after defining the amount as 5. Do so without changing the way the inputs are aquired, and please also provide a step by step explantion how you are able to do that.
Answer: I have written a code for you, please let me know is this u wanted ??
MIN_LENGTH = 0
MAX_LENGTH = 21

a = int(input('Total number of plots: '))

if a<MIN_LENGTH or a>MAX_LENGTH:
  print('Invalid Input')
  exit()

lst=[]
for i in range(a):
  ch = input(f'do you want to enter value for plot {i+1} (y/n)')
  if ch=='y':
     value = int(input(f'Enter value for plot {i+1}: '))
     if value<0:
        print('Invalid Input')
        exit()
     lst.append(value)
  else:
     print('Invalid Input')
     exit()
n =1
for i in lst:
  print(f'plot:{n}= {i}')
  n+=1

Answer: Your while n1 !=n2: loop ensures, that user will have to enter the correct number of inputs. Otherwise he will not come out of loop. Is that not what you require?
Comment: No n2 has nothing to do with this. I just used it casually to check how many values i am taking. I have removed that part of the code.
Comment: Still, your loop guarantees that you will take n1 valid values. So user is still inputting correct number.
Comment: yes it has to exit if the n1 values are not given as input.
Comment: But that is happening already with your loop. So there is no way a user can provide invalid input.
Answer: add below code after n2+=1

if n2>4:
    break
Comment: ok for n inputs then what about only 2 inputs given into list.
Comment: It means you want to decide at runtime how many inputs you want to enter into the list right??
Comment: yes it depends on the user if the user enters correct number of inputs it will be ok. if not then program has to terminate without any error.


How do I translate this sql-injection-susceptible function to a prepared function in MySQLi?

Question: I have two functions which are sql-injection-susceptible, I have managed to translate the first one into a prepared function but I'm failing to see how I would translate the second one. This is the original first one:
    function modify($sql, &$id)
    {
        $link = database_link();

        $result = mysqli_query($link, $sql);

        $insertId = mysqli_insert_id($link);

        return mysqli_affected_rows($link);
    }

Which I translated to:
    function preparedModify($sql, $types, &$insertId, ...$value)
    {
        $statement = mysqli_prepare(database_link(), $sql);

        $statement->bind_param($types, ...$value);

        $statement->execute();

        $insertId = $statement->insert_id;

        return $statement->affected_rows;
    }

Which worked and I'm happy with. This is my second function that needs to be translated:
    function select($sql, &$rows)
    {

        $link = database_link();

        $result = mysqli_query($link, $sql);

        $rows = array();

        while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
            $rows[] = $row;
        }

        return mysqli_num_rows($result);
    }

Which is totally unclear to me how I would translate it as a beginner. Could you help me while at the same time breaking down your answer(s) to point out what the strategy behind your translation is? Because my strategy for the first function was just googling for alternative functions and that way I managed to do the first one but I reached nowhere with the second one using the same approach.
Comment: What is your particular problem? Why can't at last start the same way as in the other function - with ...$value stuff?
Comment: @YourCommonSense That part I figured out indeed, just the way I would do the part with the array `$rows` that I haven't managed and still unclear to me.
Comment: Note that this would still be susceptible to SQL injection if the SQL itself can be tampered with.  Moving it to a prepared statement protects injection from the variables but you still need to ensure that the SQL is trusted.
Comment: @Egret can u give a small example demonstrating what you mean, please?
Comment: The sql itself is passed in as a variable so we can't tell from the code snippet what it's source is.  If it was passed in from an untrusted source (a client) or if it was created with concatenation with strings from an untrusted source that would still leave you vulnerable to SQL inj - even if you use prepared statements.
Answer: There is a quirk, I have to admit, with running prepared SELECT queries, as you cannot just fetch a familiar array right from the statement so you will need an additional function call, get_result(). But at least you could have started the same way as with the other function as it is the correct way to run a function with prepared statements.
A couple other things to note

I suppose that database_link() creates a new database connection every time it is called. It should never be this way, a connection must be created only once. Therefore create it first and then pass the $link variable into all your function calls.
returning a function's result through a parameter is ugly and unreadable and for these reasons is frowned upon. And you don't have to return the row count - it just makes no sense as you can always use count($rows) to get the count.
it is highly inconvenient to put separate variables into the function call, I learned it the hard way. Instead, put them in the form of array. This way you will be able to either have separate variables or a single variable that already contains all the data required.

Given all that we can create a procedure that is easy to use and read, based on my Mysqli helper function:
function select($link, $sql, $values = [], $types = '')
{
    if (!$values) {
        $result = $link->query($sql);
    } else {
        $types = $types ?: str_repeat("s", count($values));
        $stmt = $mysqli->prepare($sql);
        $stmt->bind_param($types, ...$values);
        $stmt->execute();
        $result = $stmt->get_result();
    }
    return $result->fetch_all(MYSQLI_ASSOC);
}

$link = database_link();
$rows = select($link, "SELECT * FROM employees WHERE salary > ?", [$gross]);
if ($rows) {
    // you don't actually need even a count() call
}

Answer: If you have mysqlnd installed (to allow use of mysqli_stmt::get_result), the changes can be fairly simple. The first part is the same as preparedModify, then we just use a call to get_result and the rest of the function remains the same:
function preparedSelect($sql, $types, &$rows, ...$value)
{
    $statement = mysqli_prepare(database_link(), $sql);

    $statement->bind_param($types, ...$value);

    $statement->execute();

    $result = $statement->get_result();

    $rows = array();

    while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
        $rows[] = $row;
    }

    return $statement->num_rows;
}

As has been commented, you don't need the loop to generate $rows, you can simply use mysqli_result::fetch_all:
$rows = $result->fetch_all(MYSQLI_ASSOC);

Again this requires the native mysqlnd driver to be installed.
Comment: @Doesitmatter `affected_rows` is for `INSERT`, `UPDATE` and `DELETE` queries. `num_rows` is for `SELECT` queries.
Comment: You don't need the while loop. You can just fetchAll records and return.
Comment: @Doesitmatter a `SELECT` query shouldn't have a `VALUES` clause... that's why the `prepare` failed.
Comment: @Doesitmatter also a REGEXP expression placeholder shouldn't be in quotes.
Comment: May I ask why did you choose to use `num_rows` instead of `affected_rows`?


Can I lose the ability to sing whistle notes?

Question: I am a male 14 years old and I can whistle quite well, but if my voice will change will I lose the ability to reach them? And high notes in particular??
Comment: Related question: https://music.stackexchange.com/questions/71822/how-can-i-recover-lost-whistle-register-male
Comment: As comments below mention, do you mean true whistling, where sound is generated in the oral cavity with tongue and lip positions, or do you mean  singing in  falsetto?
Answer: There's no reason why you should not be able to whistle well after your voice breaks. The voice is produced in your throat. You don't whistle from your throat, it's only the air that comes from there. The whistle is produced from your lips, which won't have much effect on the depth of your voice.
Comment: I believe the OP is asking about the "[whistle register](https://en.wikipedia.org/wiki/Whistle_register)".
Comment: @Aaron - you could be right - it's lost something in translation...
Comment: @Aaron My thanks to you for introducing me to that bit of vocab!  I never knew there was anything above "falsetto."


how to get the web form results

Question: I need to get the results of the web form as a block to display with the webform.
It seems views has no way.
Answer: I have been able to get Webform information into Views in the past, but I ended up delving into the database to do so since the integration of Webform and Views is limited to submission ids and edit links, not the specific data that was entered by the user.
I found this tutorial online that might be useful for you. http://archive.org/details/DisplayWebformSubmissionDataInViews

how to get the web form results


Sending an email in Python: Unexpected EOF while parsing

Question: I am new to Python programming and have a project to try to send a simple email to myself for testing purposes and keep encountering some errors. At first I tried using the first template from email: Examples on the Python website to send a simple message. I created a plain text file with some words in it to read from.
This is my code:
# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.mime.text import MIMEText

# Open a plain text file for reading.  For this example, assume that
# the text file contains only ASCII characters.
fp = open('test.txt', 'r')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()

# me == the sender's email address
# you == the recipient's email address
me = "email@example.com"
you = "email@example.com"
msg['Subject'] = 'The contents of %s' % 'test.txt'
msg['From'] = me
msg['To'] = you

# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('my Outlook account server')
s.sendmail(me, [you], msg.as_string())
s.quit()

And I get this error:
Traceback (most recent call last) -  on line 18:
msg['Subject'] = 'The contents of %s' % 'test.txt'

So I tried a different format of code that I got from pythonRocks_1:
import smtplib

SERVER = 'mail.company.com'
FROM = 'firstname.lastname@example.com'
TO = ['email@example.com']
SUBJECT = "Test Subject SMTP"
TEXT = "If this is in the body of the email, test is a success!"

message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

try:
    s = smtplib.SMTP(SERVER)
    s.sendmail(FROM, TO, message) # this line is not correctly putting info in proper fields for Outlook 2010
    s.quit()
    print "Successfully sent email."

except:

    import sys, traceback

    tb = sys.exc_info()[2]
    print "An error occurred on line " + str(tb.tb_lineno)
    print "Error: unable to send email"

With this error:
An error occurred on line 19
Error: unable to send email

My line 19 reads:
 s = smtplib.SMTP(SERVER)

Do you think my SMTP server is incorrect? I went into my Account Settings under my Outlook 2010 email and found the SMTP server from there. I'm not exactly sure what else it could be.
Comment: are you using `msg['Subject'] = 'The contents of %s' % 'test.txt'`?
Answer: One of the first things that jumped out to me is that you do not have a password, unless you have a very strange mail server(or are running one locally end even then... you're going to need to set that up somewhere. You are also not giving a port for the email server which, in my experience, is required.
Here is a modified version of your code that works for gmail. You'll have to, of course, make some changes to reflect your environment. This version stores your password in plain text in the source, that is a pretty bad idea and you will want to change that. A previous, similar question(here: Determine which port my exchange service is using for e-mail sending -> cakePhP CakeEmail) has some information about the settings/ports/etc for an exchange server.
import smtplib

TO = '<user>@gmail.com'
FROM = '<target>@gmail.com'
PWD = '<password>'
SERVER = "smtp.gmail.com" # gmail settings, this will come from your mail server
PORT = 587 #gmail settings, this will come from your server
SUBJECT = "Test Email"
TEXT = "This is  a test"
message = """To: {TO}\r\nFrom: {FROM}\r\nSubject:{SUBJECT}\r\n{TEXT}""".format(TO=TO, FROM=FROM, SUBJECT=SUBJECT, TEXT=TEXT)

try:
    # connect to the server and log in
    smtpserver = smtplib.SMTP(SERVER, PORT)
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo
    smtpserver.login(FROM, PWD)

    # print our message just to ensure we have everything
    print message

    # send the message
    smtpserver.sendmail(FROM, TO, message)

    # close the server
    smtpserver.close()

    # let ues know it is done
    print 'done!'

except:
    import sys, traceback

    tb = sys.exc_info()[2]
    print "An error occurred on line " + str(tb.tb_lineno)
    print "Error: unable to send email"

Comment: Thank you so much for the help. I still can't get it to compile correctly but I think it's because I have an incorrect port number.
Comment: Something that helped me immensely when working with this sort of stuff was to try it with a google or other free, online email address first. Exchange and similar corporate email servers can be tricky and, at times, require some heft finagling. Set everything up the way you want with a test or dummy account on some free, easy to use service and, once everything is working, figure out how to refactor everything for the corporate server. I recall that my first email app had to work with a server that required SSL which was a pain(you should check this on your server as well.)


Problems with cross-validation for time-ordered data

Question: Let's assume a simple scenario: You want to forecast the house prices of various properties. The dataset is cross-sectional in nature, as you only observe each property once. However, you also have a timestamp of the observation (month/year).
In a sense, this means that the data is intrinsically time-ordered. In general, I know that with time series data, the use of e.g., k-fold cross-validation can be problematic. However, I don't have real time series data (multiple obs. for one house), but time-ordered data across houses. It is also clear that for time series data, there are other approaches such as rolling estimation.
In particular, I would like to understand theoretically from a statistical/econometric perspective why this might be problematic rather than just intuitively. Does anyone have a theoretical guide to this topic or know of relevant literature to delve deeper into this topic?
EDIT: Based on @Björn's answer, it seems useful to provide more information about the goal here. The goal is actually to predict future prices based on the trained model.
Comment: If there is ordering, major issue, naively applying standard cross-validation may create a situation of predicting past using future data points. We did a survey on cross-validation in time series and proposed approach to do full-cross validation. [here](https://arxiv.org/abs/1910.09394).  Though rolling estimation is standard practice.
Answer: Your validation splits should match your target task. If taking a database, in a randomized fashion finding out sales prices and then filling the numbers for the rest is the task (without an intent to predict future sales), then simple cross-validation is just fine. If the goal is to predict future prices, then a past-vs-future split is better (whether that's a single such split or multiple ones). Why? Here's some examples of what could go wrong (and it's usually very hard to intervene to prevent these):

Multiple sales of the same house might be in the data. If I have a past and a future sale, then guessing the the current sales price was inbetween is a pretty good bet. Sufficiently complex models will manage to memorize data to give this kind of answer and you will not even notice until you specifically look for it (I've seen exactly this type of thing with a xgboost once). On the other hand, in practice you would not have this information and real predictions would be less reliable.
Multiple similar new units might go onto the market at the same time. It's probably a good guess that identical properties in the same local go for about the same price (plus-minus a bit of negotiating skill by people).
If things like inflation, state of the economy etc. change over time, then these might have various effects on property prices. If you have sales data at the exact same time of a future sale, then that might tell you a lot about these effects that you would not know in practice (even if you put current economic forecasts and inflation numbers into your model, which would presumably somewhat help).
A model trained with future data does not need to extrapolate into the future, it only needs to interpolate. So, a validation set-up like that does not test the ability of a model to extrapolate into the future. Of course, if we plan to regularly re-train a model (let's say once a month), it will not ever need to extrapolate very far into the future, so this might be less of a concern. Nevertheless, extrapolating a little bit into the future is still harder than interpolating with knowledge of the future.
All this, so far, assumed that individual sales don't affect each other, but that might also be the case.

E.g. if people know the sales prices of recent sales in the area, they might target a price close to that (with adjustments depending on the property), but if that is so, then data from the future tells you something about similar past sales (but you would not have that knowledge when predicting the future).
Or, sales prices in one area might move in the same way due to being affected by some local event (new highway being buildt, new school opened etc.) and the model would learn this via other future sales from the area rather than from the things that could predict this in practice (e.g. knowledge of local events that move house prices).
Answer: I can't speak to the theoretical aspects, but why not preprocess your data to avoid the problem? If you can get some house price inflation data you can inflate the prices of the older (earlier timestamped) properties to values you can reasonably expect them to fetch today and then train your predictive algorithm using apple to apple comparisons across the data.
Comment: This seems natural in this setting with house prices, however, this is only an assumed simple scenario. In many cases, this will not be possible in reality.
Answer: I don't think that having a time-stamp on the data is necessary problematic for housing price forecasting.
The procedure is to decompose the house into its attributes (size, location, etc.), add dummy variables for time and then do regression on these variables, this is called a "hedonic model" in the econometric literature, for a detailed discussion check for instance chapter 4.3 of "The practice of econometrics: Classic and contemporary" Berdnt, 1996.
When you use this method, you estimate the coefficients accompanying the dummy time variables, so the model does not use specific house values from the past to compute future values.
Answer: One critical issue is the cage of covariance includes time varying effects, which can impose and unrecognised pattern on the data if not handled appropriately. There will be a general trends across house prices depending on the general economic situation evolving over time. more complex patterns such as evolving fashions and functional requirements will impose addition layers of complexity.
It is related to the Moiré effect. Here's a figure I've created recently that shows how hidden patterns in the data can affect CV, using an extreme example for demonstration purposes. Moiré patterns can be extremely complex and hard to detect if you don't look for them intentionally. If the periodicity of the sampling is a multiplicative factor of the periodicity of the underlying trend then you may under-sample underlying effects in the modelling set that mostly get held out for the test set (or vice versa).

Visualisation of experimental factor distribution in the simulated structured dataset. The color is created by red channel for time interval, green channel to indicate dose exposure, blue channel to indicate experimental group membership. Selection to hold out group indicated 1/3 reduction in intensity. a-c) Week of study as x-axis, dose group (sub-divided by experimental group) as Y-axis. a) is the basic experimental design matrix. b) black pixels indicate samples selected by sequential block selection for K-fold c) black pixels indicate samples selected using Monte-Carlo d) the average properties of the train and test sets with each selection method.


Add new option for ui-select2 in angular js

Question: I am using ui-select2 in angularjs which uses select2 plugin of jquery.  I have some pre-defined list and then when i start searching for anything and if that is not found in list i want to add a new value.  I am doing something like this :
var selectOptions = {
    formatNoMatches: function(term) {
                return "Add new country";
            }
 };

 $scope.addCountry = function(countryName) {
    console.log (' test');
 };

But the click doesnt work and the console in addCountry is never printed.  Any idea how to add new option for ui-select2 in angular js ?
Comment: I'm pretty sure the ng-click is not working because this code is not compiled by angularjs since you output it at runtime... Can you provide us a plunker or a fiddle? It would help us to find a solution from what you already have.
Comment: i tried $compile ("Add new country") ($scope), but this returns [object object] instead of html;
Answer: I've done this, not via click but by allowing the user to just enter what they like in the select2 and hit enter:
<input type="text" ui-select2="selectOpts" ng-model="selected"/>

In coffeescript but I hope you get the idea:
  $scope.selectOpts =
    maximumSelectionSize: 1
    data: $scope.someListOfData
    tags: true
    multiple: false
    createSearchChoice: (term) ->
      {id: term, text: term}

I hope that puts you on the right track, the basic thing is to set "tags: true"

Puts Select2 into 'tagging'mode where the user can add new choices and
  pre-existing tags are provided via this options attribute which is
  either

and createSearchChoice (search in http://ivaynberg.github.io/select2/ for this):

Creates a new selectable choice from user's search term. Allows creation of choices not available via the query function. Useful when the user can create choices on the fly, eg for the 'tagging' usecase


My website serves properly on IP address but not on domain name

Question: I am using nginx, ubuntu 14, gunicorn, django 1.11, python 2.7.
I have put my domain in Allowed_HOSTS in the settings for django.
This is what I have under sites-available:
server {
        listen 8000;
        listen 80;
        server_name IP domain.com;

        location /static/ {
                root /home/username/website/src;
        }

        location / {
                include proxy_params;
                proxy_pass http://unix:/home/username/website/website.sock;
        }
}

When I put in the IP address into a computer connected to the network, the site comes up just fine, but when I type in the domain I set up, it shows me this: .
Comment: You need to edit `/etc/hosts` to redirect the site to the specific IP address.
Comment: @WillemVanOnsem Like this? `IP       domain.com`
Comment: @WillemVanOnsem Do you have any good sources or tutorials about this? Because I can't find anything to help me learn how to connect a domain name to my IP.
Comment: I think this might be a start: https://unix.stackexchange.com/q/36009
Comment: @WillemVanOnsem The /etc/hosts didn't seem to do anything. I'm probably missing something else as well.
Answer: I have written up the process to get a wordpress site on the internet with a LAMP backend, for future reference that some might find useful.
Install LAMP stack:

sudo apt install lamp-server^ -y

Install wordpress:

cd var/www/html/
sudo wget https://wordpress.org/latest.tar.gz
sudo chown www-data:www-data wordpress/

Login to mysql root user:

sudo mysql -u root -p
select a password
create database wordpress;
GRANT ALL PRIVILEGES ON wordpress.* TO 'server'@'localhost' IDENTIFIED BY 'my_password_here';
FLUSH PRIVILEGES;
EXIT;
Navigate to localhost/wordpress in your browser and enter the information for database name, server name, password, leave localhost and wp_ as is.

Now that you have wordpress running on your localhost environment, let's make it public.
Create a directory for site.

sudo mkdir -p /var/www/html/mywebsite.com
sudo chmod -R 755 /var/www/html/mywebsite.com
sudo cp /etc/apache2/sites-available/000-default.conf/ /etc/apache2/sites-available/mywebsite.com.conf

Open /etc/apache2/sites-available/mywebsite.com.conf file to configure/modify your server settings (add options if they don't exist):

ServerAdmin email@example.com
ServerName www.mywebsite.com
ServerAlias mywebsite.com
DocumentRoot /var/www/html/mywebsite.com
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

Reload apache:

sudo a2ensite mywebsite.com.conf
sudo systemctl restart apache2
sudo service apache2 reload

Add link between public IP (get from whatsmyip) and domain name (www.mywebsite.com)  in /etc/hosts:

123.456.789.123 www.mywebsite.com

You can now go to www.mywebsite.com/wordpress to see your default wordpress page.
www.mywebsite.com/wordpress/wp-admin will take you to the login page which you can use to login to your server.
References:

https://www.youtube.com/watch?v=lpMCBjTsZ60&t=56s
https://code-maven.com/set-up-cgi-with-apache


Como criar somatório com "sum" com multiplas colunas queryover

Question: Galera preciso criar uma consulta com queryOver(Nhibernate) C#, para somar mais de uma coluna. Exemplo em sql puro:
SELECT SUM(coluna1 + coluna2 + coluna3 + coluna4)
FROM tabela

Primeiramente eu fiz dessa forma:
Tabela tabela = null;
Session.QueryOver<Tabela>(() => tabela)
           .Select(Projections.Sum<Tabela>(t => t.coluna1))
           .Select(Projections.Sum<Tabela>(t => t.coluna2))
           .Select(Projections.Sum<Tabela>(t => t.coluna3))
           .Select(Projections.Sum<Tabela>(t => t.coluna4))

Mas dessa forma somo cada coluna e gera 4 colunas, gostaria de somar todas e gerar uma coluna só.
Answer:
Solução baseado nesta resposta do SO.

Você pode utilizar Projections.SqlFunction, para aplicar um projection customizado no Projections.Sum, utilizando o NHibernate.Dialect.Function.VarArgsSQLFunction para informar o template do bind SQL.
Algo similar ao seguinte exemplo:
Tabela itemAlias = null;

var query = Session.QueryOver<Tabela>(() => itemAlias)
    .Select(Projections.Sum(
        Projections.SqlFunction(
            new NHibernate.Dialect.Function.VarArgsSQLFunction("(", " + ", ")"),
            NHibernateUtil.Double,
            Projections.Property(() => itemAlias.coluna1),
            Projections.Property(() => itemAlias.coluna2),
            Projections.Property(() => itemAlias.coluna3),
            Projections.Property(() => itemAlias.coluna4)
        )
    )
);

var result = query.SingleOrDefault<double>();

O SQL gerado por essa query será algo simular a isso (dependendo do banco de dados):
select sum((THIS_.COLUNA1 + THIS_.COLUNA2 + THIS_.COLUNA3 + THIS_.COLUNA4)) as Y0_
from TABELA THIS_

Comment: isso mesmo que precisava, funcionou certinho, obrigado pela ajuda!
Answer: Não consigo pensar numa forma "NHibernate" de fazer isso. A solução seria executar uma query pura
var query = "select C.prop1 + C.prop2 from Classe as C";

var sum = session.CreateQuery(query).UniqueResult<double>();

Edit:
Talvez você possa tentar desta forma
Session.QueryOver
(() => tabela)
   .Select(Projections.Sum
(t => t.Prop1 + t.Prop2 + t.Prop3 + t.Prop4));

Comment: Obrigado pela resposta, mas dessa forma já sabia, precisava msm com queryOver. @jbueno.
Comment: Você usa NHibernate com Linq?
Comment: Uso tambem. Editei a pergunta e coloquei como estava fazendo anteriormente com queryOver, só que daquela forma gera 4 colunas.
Comment: Dá uma olhada na edição @MarcosVinicius
Comment: Fiz dessa forma, parece que não da pra colocar mais de uma coluna. Apresenta exceção:
Message=a variável 't' de tipo Tabela' é referenciada no escopo '', mas ela não está definida.


KeyEvent doesn't detect any keys C#

Question: I'm currently stumped. I can't seem to get the KeyEvent to work. Simple code like this just won't respond to the key I'm pressing. I've tried KeyDown and KeyPress. No errors while compiling... what is causing this?? It will just let me enter the E key without prompting the MEssage box.
<code> private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
    {
        if (e.KeyCode == Keys.E)
        {
            MessageBox.Show("E");
        }
    }
</code>
Comment: You need to debug this yourself. Is the code being executed? If yes, what is the value of `e.KeyCode`? If not, why is the event handler not being attached?
Comment: Maybe you should do MessageBox.Show(e.KeyCode.toString()); and see the output ,because i think you're missing the KeyCode or You're Keyboard is not a standard one.
Answer: I think you should be using the PreviewKeyDown Event, for example, instead of the standard key events, as sometimes these events are blocked an not bubbled up through the control.
Comment: @gmajor, if this was the answer, instead of saying "thanks", accept the answer with the check left to the question.
Answer: You should change the Form KeyPreview property  to true where textbox1 is located.

KeyEvent doesn't detect any keys C#


How To Remove Underline of Angular Material Date Picker

Question: I want to remove underline of Date Picker.

By using inspect I did it but its not working by css. How can I do it by css
<code>::ng-deep{
    &.mdc-line-ripple::after{
        border-bottom-style:none !important ;
    }
}
</code>
Answer: You are using regular CSS. Try to use:
<code>::ng-deep .mdc-line-ripple::after {
  border-bottom-width: 0 !important;
}
</code>
See more:

Nesting CSS classes


What are the properties around Pi products

Question: There are some well-known evaluations around summations like $\sum 1$ or $\sum i^2$ but what are these properties for products, specifically something like $\prod_{i=0}^{n-1} (n-i)$.
I basically have an algorithm with a terrible running time of $n \cdot (n-1) \cdot (n-2) \cdots (1)$ and I'd like to be able to express this in bigOh notation but I'm not sure what class it evaluates to. It is sort of $\mathcal{O}(n^n)$ but not really since each subsequent multiplication is $n-1$.
Comment: $n\cdot (n-1)\dots 2\cdot 1$ is called $n!$ (Factorial) Whas this the question?
Comment: haahaa! I was thinking too hard. You are right - so obvious.
Comment: Typesetting tip: \prod_{i=0}^{n-1} versus \prod_{i=0}^{n-1} in a "displayed" as opposed to "inline" setting look like this: $\displaystyle\prod_{i=0}^{n-1}$ versus $\displaystyle\Pi_{i=0}^{n-1}$.  In an "inline" setting, they look like this: $\prod_{i=0}^{n-1}$ versus $\Pi_{i=0}^{n-1}$.  These differences are why \prod is used instead of \Pi, and similarly \sum instead of \Sigma. ${}\qquad{}$
Answer: The well-known Stirling's formula says that $$n! \sim \sqrt{2\pi n} \left( \frac{n}{e} \right)^n$$ as $n\to\infty$.
Answer: The product you have is $\prod_{i=0}^{n-1} (n-i) = \prod_{i=1}^{n} i = n!$ ($n$ factorial).  These are well-known and you can compute them once (or even look them up).
Comment: Yep - I was thinking too hard and missed the obvious!


Fazer um parâmetro alterar o valor da variável com apontador

Question: É possível trabalhar com ponteiros no JS, caso sim, como faço isso?
No exemplo abaixo o objetivo é fazer a variável str ficar com o valor: "funcionou :D"
var str = "teste";

function ponteiro(texto){
   texto = "funcionou :D"
}

ponteiro(str);

Comment: so tem que dizer que `str = "funcionou :D"`
Answer: Imagino que esteja falando de ponteiro ou referência, ou seja, você quer poder alterar a variável dentro da função e o valor se refletir na variável original usada como argumento da função. Isto não é possível diretamente em JS e em geral não faz sentido algo assim porque você pode retornar esse valor na função e aí mudar o valor na função chamadora:

function apontador(texto) {
   return "funcionou :D";
}
var str = "teste";
str = apontador(str);
console.log(str);

Se você tem que retornar mais de um coisa e por isso está querendo fazer algo do tipo então o ideal seria retornar mais de um dado encapsulando em um objeto:

function apontador(texto) {
   return ["funcionou :D", "Outro texto " + texto];
}
var str = "teste";
var objeto = apontador(str);
console.log(objeto[0]);

Você poderia usar um nome no array em vez de usar o índice numérico se achar que é importante.
Se ainda quiser muito insistir nisso tem como encapsular a variável em um objeto que seja por referência e aí obter o resultado que deseja:

function apontador(objeto) {
   objeto[0] = "funcionou :D";
}
var str = "teste";
var objeto = [str];
apontador(objeto);
console.log(objeto[0]);

Coloquei no GitHub para referência futura.
Novamente, desnecessário.
Tecnicamente uma string é uma referência, mas tem semântica de valor então ela não faz o que espera de forma automática, precisa de uma estrutura auxiliar por JavaScript não ter uma sintaxe que dê a semântica de referência de forma natural.
Comment: Obrigado Maniero pela resposta! Estou procurando entender melhor o funcionamento dos ponteiros para poder aplicar em outra função que estou criando, nesta outra faz mais sentido usar ponteiros sim :D
Comment: JS não tem ponteiros aparentes então você não tem como aprender usar ponteiro em JS.