How do I Include \news.php?

Question: I am trying to include a php document which name is news.php, but because I am doing this on a local server files navigate trough  \ and not /
My code looks as follows:
<?php include("\xnews\news.php");?>

But because of the \n which in php means newline (I believe) the output views the error:
Warning: include(\xnews\ews.php): failed to open stream: No such file or directory in C:\Users\Johanne-PC\Desktop\EasyPHP-12.0\www\my portable files\Homepage\news.php on line 44

Is there any way I can bypass this and include it successfully?
Comment: Escape your ` \ ` by using ` \\ `.
Answer: Use \:
<?php include("\\xnews\\news.php");

You can also use single quotes (which don't escape):
<?php include('\xnews\news.php');

Additionally, you can (edit: on all systems), use /:
<?php include('/xnews/news.php');

Comment: Using forward slashes has nothing to do with Apache. Support is built into Windows (actually since MS-DOS 2.0 where directories where bolted on). So you should preferrably use them for *all* paths; less compatibility woes once you use a normal server.
Answer: The problem is that \ is what's known as the escape character - it's used in special circumstances, such as \n being a newline. So to get an actual \ character, you have to escape it with a second \. As the other answers have said, you need to use:
<?php include("\\xnews\\news.php");?>

Answer: <?php include("\\xnews\\news.php");?>

How do I Include \news.php?


How to set multi validation to form control?

Question: I have a simple form with one input. I want to set multi validation in this input. I can set one validation for this like below but I want to set multi validation. please help me
this is my Html code:
   <form [formGroup]="contactForm" (ngSubmit)="onSubmit()">

          <input type="text" maxlength="11" inputmode="numeric" digitOnly formControlName="phoneNumber" />
          <input type="submit" value="دریافت لینک دانلود" [disabled]="!contactForm.valid">

   </form>

and this is the ts file:
contactForm: FormGroup;

  constructor() {
    this.contactForm = new FormGroup({
      phoneNumber: new FormControl("", [Validators.required])
    });
  }
 onSubmit() {
    console.log(this.contactForm.value);
  }

I want to set
Validators.minLength(11)

and
Validators.maxLength(11)

and ...
Comment: you can set it like this `[Validators.required, Validators.minLength(11),Validators.maxLength(11)]` in array.
Answer: Since FormControl validatorOrOpts is array you can set multiple Validation like this
constructor() {
    this.contactForm = new FormGroup({
      phoneNumber: new FormControl("", [Validators.required, Validators.minLength(11)])
    });
  }

or use Validators.compose

Compose multiple validators into a single function that returns the
  union of the individual error maps for the provided control

 constructor() {
    this.contactForm = new FormGroup({
      phoneNumber: new FormControl("", Validators.compose([Validators.required, Validators.minLength(11)]))
    });
  }

Answer: Complete Working Example You can find out in this StackBlitz Link,
Thought, Answer is already accepted and have working solution I have to give one of the robust solution for applying custom-validation multiple times.. At first it feels very long but at Long-Run of application scaling and re-usability You can re-use Your Own Custom-Validator-Function multiple time.
For Example, If you have pass-word field and you want to make that pass-word field to make validation like PassWord must have below validations...

Required
At least one SMALL letter is allowed
At least one UPPER letter is allowed
At least one NUMERIC letter is allowed
At least one SPECIAL-CHARACTER is allowed
At least Eight Letter is allowed

So Doing this type of Multiple validation in angular we are going to use one custom-Validation-Function-directive for better angular support. Create new file custom-validator.directive and then in this file put this code...
import{AbstractControl, ValidatorFn} from '@angular/forms';

export function customValidation(): ValidatorFn{
      return (control: AbstractControl) : {[key:string]: boolean} | null =>{
             const errorObject = {};

             const SMALL_LETTER_REGEXP = /^(?=.*[a-z])/;
             const UPPER_LETTER_REGEXP = /^(?=.*[A-Z])/;
             const NUMERIC_REGEXP = /^(?=.*[0-9])/;
             const SPECIAL_CHAR_REGEXP = /^(?=.*\W)/;
             const AT_LEAST_EIGHT_REGEXP = /^(?=.{8,})/

             if (SMALL_LETTER_REGEXP.test(control.value)){
             }else {
                 errorObject['atLeastOneSmallLetter'] = true;
              }
             if (UPPER_LETTER_REGEXP.test(control.value)){
             }else {
                errorObject['atLeastOneUpperLetter'] = true;
              }
            if(NUMERIC_REGEXP.test(control.value)){
            }else {
                errorObject['atLeastOneNumeric'] = true;
            }
            if(SPECIAL_CHAR_REGEXP.test(control.value)){
            }else {
                errorObject['atLeastOneSpecialChar'] = true;
            }
            if(AT_LEAST_EIGHT_REGEXP.test(control.value)){
            }else {
                errorObject['atLeastOneEightLength'] = true;
            }
         return errorObject;
      };
}

Now import this file in your component.ts where your formsGroup and FormsBuilder is there...
import {customValidation} from './custom-validator.directive';

export class AppComponent  {
    formGroup: FormGroup;
    constructor(private fb: FormBuilder){}
    ngOnInit(){
        this.formGroup = this.fb.group({
                             password: ['', [ Validators.required,  customValidation()]]
            })
    }
    get password(){
        return this.formGroup.get('password');
    }
}

In, Above code in this line password: ['', [ Validators.required,  customValidation()]], we are passing customValidation() function into the formGroup. this way we are applying all validations in this password form-control.
So each and every input key-field changes we are checking all password rules validation asynchronously. And tell user to enter only valid password matching character strings...
Your Template.HTML is
<form [formGroup]="formGroup">

         Enter Pass-Word
         <input id="password" class="form-control" placeholder="Password" type="password" formControlName="password" >

 Required

 At least one SMALL letter is allowed

 At least one UPPER letter is allowed

 At least one NUMERIC letter is allowed

 At least one SPECIAL-CHARACTER is allowed

 At least Eight Letter is allowed

</form>


How to get or extract the link path for terms in View

Question: I have created a Taxonomy Term view in Drupal 7,  and list out all my terms through "Taxonomy term: Name" field.
Now, I wonder how to extract the link path of each term so that I can reconstruct and adding the passing value through the url.
e.g.
<code>http://www.domain.com/fruit/apple?quantity=100
</code>
Answer: A quick solution will be:

Use "pathauto" to generate path for term pages (taxonomy/term/term_id => fruit/apple)
Use "global redirect" to force default path to custom paths
In your View build the URL like taxonomy/term/term_id?quantity=100 and should be translated at rendering time to fruit/apple?quantity=100

Thank you.
Comment: Thanks! It works!

Actually without using "global redirect", the "taxonomy/term/[tid]?quantity=100" applied in View's field link path will still rendered to "fruit/apple?quantity=100" automatically. I guess the Pathauto do the magic.

However, if I enable "global redirect", when typing the "taxonomy/term/1" in the url manually, it will automatically force default path to custom path "fruit/apple". Great thanks!
Comment: Glad to know it works for you.


How to create extra root user?

Question: I have tried making a root2 user which should have the same permissions as root by doing
useradd -g root root2
passwd root2
usermod -G root root2
usermod -aG wheel root2

but root2 can still not cat /etc/shadow as an example.
How can I create such user?
Comment: There can only be one root user. You can use `sudo` to give administrative privileges to other users.
Answer: Premise: using sudo (as suggested by the accepted answer) probably is the correct solution at your problem.
That said, if you really need something resembling a second root account, you can create an alias to the system root account.
To do that, follow these steps:

open /etc/passwd
locate the root account line (often the very first line). It will be something similar to root:x:0:0:root:/root:/bin/bash
copy/paste it changing the first root occurence in root2 (ie: changing it in root2:x:0:0:root:/root:/bin/bash)
save your changes and exit the text editor
issue passwd root2 and enter the new password

Note: if you whish, you can avoid direct editing the /etc/passwd file by replacing steps 1-3 with the following command: useradd -o -u 0 -g 0 -N -d /root/ -M root2 (see useradd --help for more information about the required options)
At this point, you can login using not only the original root account (with its original password), but also using the new root2 account (with its new password).
Anyway, remember that it is an alias of an existing user, rather than a completely new user. This means that any files created while logged as root2 have the very same numerical oid/gid of the original system root account (which has 0 as both uid and gid).
Answer: You can't. root is a special user with uid 0. Use sudo instead.
Comment: because a GID is not a UID.
Comment: Nothing that would give it real root permissions (aka is allowed to do everything). You can access files that are group-accessible for group `root`, but that's about it.
Comment: You can in fact have multiple root users. Just use a text editor to change root2 uid to 0. http://www.tldp.org/LDP/LGNET/48/tag/16.html
Comment: Interesting! With my above commands `root2` have a GID of 0, how come that doesn't give the user full root privileges?
Comment: So what does it give `root2` to have GID of 0?
Comment: @dmourati: Yes, I know this but this will be essentially the same user, because the user id is the same and you might end up with some hard-to-understand side effects. Using `sudo` is simple and effective.
Comment: @sven I agree with you above
Answer: This used to be somewhat common (before sudo alleviated the need).
The toor user (yes, that's "root" spelled backwards) is the most common alternate root user, sharing the special UID of zero with root.  See also this Super User question: Does the root account always have UID/GID 0?
This is the purpose of useradd --non-unique (useradd -o).  I believe you want something like:
useradd --non-unique --uid 0 root2

You should be able to give the account any that doesn't already exist on your system.
I do not recommend this.  You're far better off with one true root user, reserved for emergency console access.  Admins should all instead use sudo.  Especially remote admins (it is wise to prohibit root from connecting via ssh or other remote services, especially w.r.t. password logins).
Answer: Install sudo:
# apt install sudo

Create user and set password:
# useradd myuser
# passwd myuser
Enter new UNIX password: 123
Retype new UNIX password: 123

Add user to sudo config:
# visudo
...
myuser    ALL=(ALL:ALL) ALL

Login as myuser and get root permissions:
# su myuser
$ sudo apt install vim
[sudo] password for myuser: 123
...
The following NEW packages will be installed:
  libgpm2 libpython2.7 libpython2.7-minimal libpython2.7-stdlib vim
  vim-runtime

I think you need to read some information about permissions and user management in linux.

How to create extra root user?


Will the hbase kerberos token expired

Question: I have a spark streaming application, for every batch, I need to insert it to the hbase which is protected by kerberos. I found a solution, that is in the driver side I create a connection and obtain a token from that conn and then pass it to the executor. In the executor side, I decode it and get the token, in this way I can insert data to hbase successfully. This seems good, but my concern is that will the token expired? If so , how to solve it please?
My code snippet is
val ugi=UserGroupInformation.loginUserFromKeytabAndReturnUGI(principle,keytabfile);
ugi.doAs(new PrivilegedAction[Unit]() {
  def run(): Unit = {
    conn = ConnectionFactory.createConnection(conf)
    val token = TokenUtil.obtainToken(conn)
    tokenStr = token.encodeToUrlString()
  }
})

in the rdd.foreachpartition,
val token = new Token()
token.decodeFromUrlString(tokenStr)
UserGroupInformation.getCurrentUser.addToken(token)

Although I have searched a lot from Internet about this issue, but I did not found a good solution about this issue. The common answer to this question is
UserGroupInformation.getLoginUser().checkTGTAndReloginFromKeytab();

But as my test, inside this method,
public synchronized void checkTGTAndReloginFromKeytab() throws IOException {
if (!isSecurityEnabled()
    || user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS
    || !isKeytab)
  return;
KerberosTicket tgt = getTGT();
if (tgt != null && Time.now() < getRefreshTime(tgt)) {
  return;
}
reloginFromKeytab();

}
The isKeytab is always false, so it will never execute the following code,I do not understand why this return false. So anybody can help me solve this question? Any help is appreciated!
Comment: Congratulations! You have re-developed the Spark feature that automatically retrieves a "HBase token" and broadcasts it to the executors, whenever the Spark launcher detects a `hbase-site.xml` with Kerberos auth (since V1.3) You have also re-developed part of the standard HBase plugin for Spark, that was contributed by Cloudera and is available *(a)* in the CDH distro, *(b)* as an additional JAR for other distros using HBase 1.x, or *(c)* natively in HBase 2.x
Comment: But as I test, after several hours, the applications stoped at the insertToHabse method.And I got "javax.security.sasl.SaslException: DIGEST-MD5: digest response format violation. " exception, I suspect the token expired. I can renew the token, but I do not know when need I do it. I want to renew before the token expired, but when will the token expired
Comment: Did you simply SEARCH past StackOverflow questions? You might have found the answer by Chris Nauroth (Hortonworks) to https://stackoverflow.com/questions/34616676/should-i-call-ugi-checktgtandreloginfromkeytab-before-every-action-on-hadoop
Answer: It is caused by the java version. If you want to run a secured Hadoop cluster on JDK 1.7.0_85 or later, then you must run Apache Hadoop 2.7.0 or later.
To see this Jira issue HADOOP-10786

Will the hbase kerberos token expired


Drush isn't connecting to my database

Question: I have a Drupal install on a CentOS development server. Running drush from outside my web directory returns as you'd expect (a list of Drush commands).
Running drush from inside my web directory returns nothing at all. Running with debug returns this:
Using the Drush script found at /home/***/vendor/drush/drush/drush using pcntl_exec
[preflight] Config paths: /home/***/vendor/drush/drush/drush.yml
[preflight] Alias paths: /home/***/drush/sites,/home/coventry/drush/sites
[preflight] Commandfile search paths: /home/***/vendor/drush/drush/src

When using Drush from outside my web directory with --root, I get this:
drush uli --root=~/***.com
We could not find an applicable site for that command.

My settings.php file exists in that above directory/sites/default, and the database connection info works. The site is accessible in the browser.
Any ideas on this botched Drush install?
Comment: make sure Drush knows where mysql is. I ran into this the other day after updating XAMPP, and I need to add mysql back to my PATH (WIndows 10 machine). Drush can complete some commands without mysql, so it's not always immediately obvious this is missing.
Comment: Maybe `--root` doesn't like `~`. Maybe try an absolute path.
Answer: I had this error and for me I solved it by using a version of drush that is compatible with the version of Drupal that the site is using.
In my scenario I was getting that error when using drush 10 with a Drupal 7 site.
When I used Drush 8 with that same Drupal 7 site, I could then run usual drush commands, without getting that error.
Comment: Yes, the support matrix is listed on the Drush website.
Comment: +1 upvote Indeed! And my answer was in case this is what might help the OP as it did in my scenario. And others, who arrived here, like me when Google-ing this error!
Answer: In addition to above, make sure you are running the uli command from the docroot of your project, I had lando setup and I got same error because I was running the command outside the docroot.

Drush isn't connecting to my database


Advice for a classical guitarist and Jazz bassist

Question: I have played guitar and bass (classical and jazz) but my main instrument is the guitar.  I lost touch with the upright bass many years ago and want to pick it up again.  I also recently picked up the classical guitar and have been playing seriously for the past 4 years of so.
Here is the issue classical requires some right hand nail growth and proper maintenance for good tone and technique.  Upright jazz bass is mostly played pizzicato with the right hand.  Playing Bass (with some enthusiasm) will lead to broken right hand nails.
Is there anyone else out there who has gone down this path and had some success at both instruments?  Any advice on managing both is appreciated.
Comment: It is possible to play CG without nails. Check out Rob McKillop for instance. It's not for everyone but it's also not uncommon.  .
Answer: Jazz bass pizz. is normally played more by the side of the finger and so you might be able to avoid your long fingernails with some practice.  Long nails would be more of a problem for classical double bass pizz. than for jazz bass.
Comment: Yes, I do recall that about the technique.  But it still managed to break the index nail often.  May be a lost cause.  But thanks
Answer: One factor is proper maintenance of the right hand.  The nails become an issue for sure if they are allowed to grow too long.  Despite the use of nails on classical guitar they are not usually grown very long.  Most books show the nails flush with the ends of the finger or just 1mm beyond.  The string is actually plucked from the finger pad and nail together and long nails are not only not required but actually detrimental to proper technique.  I am not sure if a shorter nail would would allow compatibility with classical pizzicato but the combination of a short well groomed nail and jazz pizz might avoid this issue altogether.  I would guess that someone (e.g. me) serious about playing both would have to be vigilant about keeping the growth of the nails in check and adhering to proper technique on both instruments.


Determining if a linear transformation is one to one

Question: $T$ is the linear transformation from $\mathbb{R}^3 $ to $ \mathbb{R}^3$ : $T(a1, a2, a3) = (a1-a2, a2-a3, a3-a1)$
Question: Is $T$ one to one ?
Attempt:
After row reducing , I get that $a1-a3 = 0$ ,  $a2-a3 = 0$. $a3$ is free so no its not one to one.
Comment: I think that's correct. You can also note that $T(1,1,1) = 0$.
Answer: Yes it is not one to one indeed the matrix associated is
$$[T]=\begin{bmatrix}1&-1&0\\0&1&-1\\-1&0&1 \end{bmatrix}$$
with $rank(T)=2\implies \det(T)=0$ thus $[T]$ is not invertible.


Binding to property on root element in DataTemplate through a ContentControl

Question: In my user interface I sometimes want to put titles above usercontrols.
I want to declare these titles in XAML for future localizability, so I want to keep them out of the datacontexts.
Can databinding fetch them from a property set on the root node of the usercontrol?
I have boiled the problem down to the following code example:
using System.Windows;

namespace WpfApplication12
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            this.Person = new Author { Name = "Guge" };

            this.DataContext = this;
        }

        public object Person { get; set; }
    }

    public class Author
    {
        public string Name { get; set; }
    }
}

And:
<Window x:Class="WpfApplication12.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication12"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <DataTemplate DataType="{x:Type local:Author}">
        <Border AutomationProperties.Name="Author" BorderThickness="1" BorderBrush="Black">

        </Border>
    </DataTemplate>
</Window.Resources>
<StackPanel>

    <ContentControl x:Name="presentation" Content="{Binding Person}"/>
</StackPanel>

And the practical problem is: how can I use databinding in the content property of the "Position" Label to fetch the word "Author" from the AutomationProperties.Name property of the Border in the DataTemplate?
Answer: How about going the route over your data object:
public class Author
{
    public string Name { get; set; }
    public string TypeName { get; set; } // might be better in base class Person
}

And:
<Window.Resources>
    <DataTemplate DataType="{x:Type local:Author}">
        <Border AutomationProperties.Name="{Binding TypeName}"
                BorderThickness="1" BorderBrush="Black">

        </Border>
    </DataTemplate>
</Window.Resources>
<StackPanel>

    <ContentControl x:Name="presentation" Content="{Binding Person}"/>
</StackPanel>

Comment: Thanks. And I suppose setting TypeName to the contents of AutomationProperties.Name in code-behind?
Comment: There must be some place where Person.TypeName is set, yes. Generally speaking I do not like codebhind ( http://goo.gl/KyTW ). But if you use it, yes that's probably the place.
Comment: Of course you need to use the INotifyPropertyChanged pattern for the properties. Do you have that?
Answer: The solution so far is to add a string property for TypeName to the viewmodel and fill this with the contents of the AutomationProperties.Name in code-behind. And use the following binding:
<StackPanel>

    <ContentControl x:Name="presentation" Content="{Binding Person}"/>
</StackPanel>

However, I still think it should be possible to do this without using the ViewModel, I hope to be able to revisit this issue when my databinding skills have improved.


como faço para colocar um Scrollbar em uma janela no python como se fosse uma pagina web, quanto mais conteudo mais poderia descer pela Scrollbar

Question: Queria que ao entrar na janela do programa usando tkinter, fosse possivel usar um Scrollbar para procurar mais items da janela para que não fique com sua altura limitada, podendo arrastar a scrollbar para baixo (Vertical Apenas), para encontrar mais items na janela
Já criei o Scrollbar mas não sei a quem atribuir
jan = Tk()
jan.geometry('1360x760')

lbl = Label("TEXTOS COM NOME DE PRODUTOS")
lbl.place(x=500, y=200)

nao sei como atribuir o scrollbar a isso

sb1=Scrollbar(jan)
sb1.place(x=1330, y=110)

Comment: Dá uma olhada [nisso](http://effbot.org/tkinterbook/scrollbar.htm) @Marcos
Comment: Algo parecido com isto ? https://www.youtube.com/watch?v=7v1VNlV14aw
Answer: No tkinter, frames não podem ser rolados. A solução é criar um Canvas e colocar outro frame dentro dele.
Essa classe JanelaRolavel é um Frame que contém um Canvas com outro Frame dentro. Basta colocar seus objetos neste "subframe" (que está no atributo .conteudo) e eles vão ser roláveis:
import tkinter as t

class JanelaRolavel(t.Frame):
    def __init__(self, parent, *args, **kw):
        t.Frame.__init__(self, parent, *args, **kw)

        # cria um canvas e uma barra de rolagem para rolá-lo:
        rolagem = t.Scrollbar(self, orient=t.VERTICAL)
        rolagem.pack(fill=t.Y, side=t.RIGHT, expand=t.FALSE)
        self.canvas = t.Canvas(self, bd=0, highlightthickness=0,
                        yscrollcommand=rolagem.set)
        self.canvas.pack(side=t.LEFT, fill=t.BOTH, expand=t.TRUE)
        rolagem.config(command=self.canvas.yview)

        # reseta a visão:
        self.canvas.xview_moveto(0)
        self.canvas.yview_moveto(0)

        # cria um frame dentro do canvas
        # para que seja rolado junto com ele:
        self.conteudo =  t.Frame(self.canvas)
        self.id_conteudo = self.canvas.create_window(
            0, 0, window=self.conteudo, anchor=t.NW)

        # cria eventos para detectar mudanças no canvas
        # e sincronizar com a barra de rolagem:
        self.conteudo.bind('<Configure>', self._configurar_conteudo)
        self.canvas.bind('<Configure>', self._configurar_canvas)

    def _configurar_conteudo(self, evento):
            # atualiza a barra de rolagem para o tamanho do frame de conteudo:
            tamanho = (
                self.conteudo.winfo_reqwidth(),
                self.conteudo.winfo_reqheight()
            )
            self.canvas.config(scrollregion="0 0 %s %s" % tamanho)
            if self.conteudo.winfo_reqwidth() != self.canvas.winfo_width():
                # atualizar tambem a largura do canvas para caber o conteudo:
                self.canvas.config(width=self.conteudo.winfo_reqwidth())

    def _configurar_canvas(self, evento):
        if self.conteudo.winfo_reqwidth() != self.canvas.winfo_width():
            # atualizar tambem a largura do conteudo para preencher o canvas:
            self.canvas.itemconfigure(
                self.id_conteudo, width=self.canvas.winfo_width())

Segue agora um exemplo usando essa classe para fazer esta janela:

Código:
if __name__ == "__main__":
    class Exemplo(t.Tk):
        def __init__(self, *args, **kwargs):
            t.Tk.__init__(self, *args, **kwargs)

            self.frame = JanelaRolavel(self)
            self.frame.pack(fill=t.BOTH)
            for i in range(10): # cria botoes no frame interno
                t.Button(self.frame.conteudo,
                    text="Botão {}".format(i)).pack(fill=t.BOTH)

    app = Exemplo()
    app.mainloop()

Comment: Depende do que  quiser fazer, um `tkinter.ListBox` já pode prover toda a funcionalidade desejada, sem precisar do Canvas intermediário.  @Marcos: não deixe de olhar a documentação do ListBox também - http://effbot.org/tkinterbook/listbox.htm


Cannot capture special keys in C/C++ keylogger using GetAsyncKeyState

Question: I wrote a small key logger in C/C++ with the intent to capture all keys pressed. However, I am not able to capture some special keys such as ; : [ ] \ / ? " ' .
Let's consider I want to capture the ; or : key.
Currently, I have the following code snippet in an infinite loop:
if (GetAsyncKeyState(0xBA) == -32767)
    {
        //the statements inside the if clause are not executed when the key is pressed
        std::ofstream write("Record.txt", ios::app);
        if (GetAsyncKeyState(0x10))
            write << ":";
        else
            write << ";";

    }

where 0x10 is the code of the "SHIFT" virtual key (VK_SHIFT) and VK_OEM_1 (0xBA) is the virtual key for ;, as decribed in the Microsoft Docs: https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes.
As far as I acknowledge, the GetAsyncKeyState function returns -32767 after a key was just released.
The code above works for other virtual keys or simple keys, as described in the ASCII table (e.g. GetAsyncKeyState(48) works for the 0 key, GetAsyncKeyState(VK_RETURN) works for the ENTER key and so on.
I've already tried inputting the following arguments for the GetAsyncKeyState function:

The ASCII code for ';' , which is 59
The ';' character
VK_OEM_1 - the virtual key
0xBA - the virtual's key value in hex
186, as I've found here: https://www.amibroker.com/guide/afl/getasynckeystate.html.

None of the arguments makes the function return -32767 when the ';' key is pressed.
Do you have any idea of how am I supposed to use that function in order to capture that key and, consequently, all the other keys that are not captured by my approach ( [ ] \ / ? " ' .)?
P.S: I am using the standard English (US) keyboard layout.
Thanks in advance!
Comment: It returns 2 bits of info, bit #0 and bit #15.  Simplest way to test if a key is down is with GetAsyncKeyState(key) < 0, tells you that bit #15 is turned on, regardless of the bit #0 state.
Comment: Tried previously, without success.
Answer: I found the solution. Seems like Visual Studio is going crazy when you hide the console from the screen (it's like you change something in the code, but when you run again the application, the changes are not propagated).
However, I want to share with you some possible mistakes that may lead to the error that I've encountered:

If you use a char variable to store the ASCII code, for some keys it may exceed the maximum char size, thus I suggest using an unsigned char or an int.
If you plan to iterate through the list of all possible ASCII codes, try going up to the size of the Extended ASCII table. Do not limit to the standard one.

Here's the corresponding snippet of code regarding the issue that may help you:
int main()
{
    while (1){
    for (unsigned char i = 0; i < 255; i++){
            if (GetAsyncKeyState(i) == -32767) {
                if (i == VK_OEM_1) {
                    cout << ";";
                }
            }

        // ....
    }
}

}


Matlab web browser in compiled applications

Question: I've an application written in Matlab that uses the built-in Matlab browser; I do this because I need to be able to use the handle returned from web function to read properties of the browser window. This works fine when I just run it in Matlab. However, when I compile the application for distribution, it insists on using the system browser, which I can't read properties from. Does anyone know how to force the use of the Matlab browser in compiled applications?
Alternatively, is there anyway to get a handle for the browser window that is opened?
Answer: It turns out that the Matlab browser is not compiled; instead, the system browser is always used, and there doesn't seem to be a way to detect the close window event directly. However, I found that you can watch the CurrentLocation property to the same effect: If you wait for it to be filled, as soon as the window is closed it will be cleared, and you can detect a closed window that way. I've only tried this when the window is closed, not when the application quits, but it works (on Mac, at least).


How to represent e^(-t^2) in MATLAB?

Question: I am a beginner in MATLAB, and I need to represent e(-t2).
I know that, for example, to represent ex I use exp(x), and I have tried the following
1) tp=t^2; / tp=t*t;
   x=exp(-tp);
2) x=exp(-t^2);
3) x=exp(-(t*t));
4) x=exp(-t)*exp(-t);
What is the correct way to do it?
Comment: no. 4 (`x=exp(-t)*exp(-t);`) is mathematically wrong.
Comment: exp(-t)*exp(-t) is NOT equivalent to exp(-t^2), it is equivalent to exp(-2*t), a rather different number.
Answer: If t is a matrix, you need to use the element-wise multiplication or exponentiation. Note the dot.
x = exp( -t.^2 )

or
x = exp( -t.*t )

Answer: All the 3 first ways are identical. You have make sure that if t is a matrix you add . before using multiplication or the power.
for matrix:
t= [1 2 3;2 3 4;3 4 5];
tp=t.*t;
x=exp(-(t.^2));
y=exp(-(t.*t));
z=exp(-(tp));

gives the results:
x =

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

y =

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

z=

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

And using a scalar:
p=3;
pp=p^2;
x=exp(-(p^2));
y=exp(-(p*p));
z=exp(-pp);

gives the results:
x =

1.2341e-004

y =

1.2341e-004

z =

1.2341e-004

How to represent e^(-t^2) in MATLAB?


Laravel - Nested Relationships

Question: I'm learning Laravel and need to get a list of nested relationships. My foreign keys seem to be set up correctly.
products->servers->configs

Product Controller
$products = Product::with('servers')->get();

Product Model
 public function servers()
    {
        return $this->hasManyThrough(Config::class, Server::class);
    }

I'm only getting a list of servers that are the configs. Eg
products:{
  id:1,
  servers:[
    ram:16gb //this is the config not the server
 ]
}

How can I get the list of configs inside the servers inside the products? Eg
products:{
  id:1,
  server:{
    id:1,
    name:'big server',
    config:{
     ram:16gb
    }
  }
}

Answer: In Product Modal Use hasMany Method
public function servers()
    {
        return $this->hasMany(Server::class);
    }

In Server Modal Use hasMany(for many rows get) or hasOne(for single row get) method
 public function configs()
 {
       return $this->hasMany(Config::class);
 }

 public function config()
 {
        return $this->hasOne(Config::class);
 }

Now In ProuctController see how to get nested relationship data
 $products = Product::with('servers.configs')->get();

Comment: Thanks....I also went servers() in my product model return $this->hasMany(Server::class)->with('config');. It would be better get what you need from the controller rather than the model?
Comment: @ottz0 `return $this->hasMany(Server::class)->with('config');`: you shouldn't do that! Now every time you use the `servers` relation you'll automatically load the `config` models even if you don't want to thus having unecessary `DB` queries and unecessary processing on the `Eloquent` side to prepare those `config` models for you. It's better to load the relation only when needed.

Laravel - Nested Relationships


Update screen only works once and then stops working || UNITY

Question: So i have a 3x3 gameBoard. The character starts in the middle. When i press right nothing happens, when i press left nothing happens but when i press up it moves to the position in the code.
void Start()
{
    transform.position = new Vector2(0.28f, -0.27f);
    print(transform.position.x);
}

void Update()
{
    if (ChrP == new Vector2(0.28f, -0.27f))
    {
        if (Mathf.Abs(Input.GetAxisRaw("Right")) > 0.0f)
        {
            transform.position = new Vector2(1.95f, -0.27f);
        }
        if (Mathf.Abs(Input.GetAxisRaw("Left")) > 0.0f)
        {
            transform.position = new Vector2(-1.36f, -0.27f);
        }
        if (Mathf.Abs(Input.GetAxisRaw("Down")) > 0.0f)
        {
            transform.position = new Vector3(0.28f, -1.923f);
        }
        if (Mathf.Abs(Input.GetAxisRaw("Up")) > 0.0f)
        {
            transform.position = new Vector3(0.28f, 1.401f);
        }
        else
        {
        }
    }
}

So, for the new "Up" position i have the same type of code and i have checked everything but it just freezes instead of moving.
My expectation is that it is going to check every frame if i have pressed the button. Maybe i have missed something.
Also both after and before the if statement i have the same type of code but for other coordinates!
Comment: I suggest you learn how to debug code, surely this is something that is easily spotted? However, your `Update` method will only ever do anything if the `ChrP` value is at a very specific position.
Comment: @MichelAtwood DavidG is right why do you have that if statement in the beginning
Comment: the if statement in the beginning is too check where the object is located
Comment: But surely the object has moved...
Comment: why do you have an empty else statement?
Comment: If you found my answer worked, I ask that you upvote it or accept it as the answer please.
Answer: Check the transform.position function for your left and right code. You're creating a vector2 instead of a vector3 like you have in the up and down functions. According to the Unity Scripting API, transform.position takes a vector3 position, and not a vector2. The fix should be simple then:
if (Mathf.Abs(Input.GetAxisRaw("Right")) > 0.0f)
    {
        transform.position = new Vector3(1.95f, -0.27f);
    }
if (Mathf.Abs(Input.GetAxisRaw("Left")) > 0.0f)
    {
        transform.position = new Vector3(-1.36f, -0.27f);
    }


Remove Extra back slash "\" from string file path in c#

Question: How to convert
"String path = @"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\";
into
String path = @"C:\Abc\Omg\Why\Me\".
My approach is to first reverse the string and then remove all the "\" till we get first char, and the reverse it again.
How to do this in C#, is there any method for such operation?
Comment: I think you have `String path = @"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\";`
Answer: You can just construct path using the Path static class:
string path = Path.GetFullPath(@"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\");

After this operation, variable path will contain the minimal version:
C:\Abc\Omg\Why\Me\

Comment: Thanks @Zoran one should use only this for paths.
Comment: You may still have an issue if you need `Path.GetFullPath(@"C:\Windows\")` and `Path.GetFullPath(@"C:\Windows")` to have identical output. You could be passing paths to other systems that make different assumptions about path conventions. You may need a `.TrimEnd('\\')` or `.TrimEnd('\\') + '\\'` or equivalent to normalize the path depending on your use case.
Answer: You can use path.TrimEnd('\\'). Have a look at the documentation for String.TrimEnd.
If you want the trailing slash, you can add it back easily.
Comment: You should not treat file paths as simple strings. You should rely on .NET Framework's support for file paths because it knows it better. For example, who says that the segment delimiter is backslash? That is the system setting.
Comment: It's equally simple to use the `Path` class.
Comment: Thanks @DanielA.White since have accepted Zoran 's answer but yours will be used for further string manipulations.
Answer: var path = @"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\";
path = path.TrimEnd('\\') + '\\';

another solution is
var path = @"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\";
path = Path.GetFullPath(path);

Comment: It's not that simple when it gets to paths. For example, `Path` class is defining the path separator character. What will be when we compile this code into a UWP app and then every now and then receive a forward slashes instead of backslashes? Better stick to strong types and let the framework and OS do their part.
Comment: No need to manipulate strings. .NET Framework already has extensive support for file paths.
Comment: Agree. your solution is more elegant in this case. But what if Pranay wants remove another char in another string.


JQuery change selected value after clone dropdown

Question: I have this dropdown. I need clone for my other dropdown lists:
<select name="general">
<option value="0" style="font-size:11px">Nothing</option>
<option class="dropdown_root" value="1">Admin</option>
<option class="dropdown_root_first_lvl" value="2">General</option>
<option class="dropdown_root_next_lvl" value="3">Group</option>
<option class="dropdown_root_next_lvl" value="4">Sales</option>
</select>

<select name="group">
</select>

My problem is I want to clone the same content but I want the value selected from the list "group" is "Group" ... whose value is 3
I tried this:
var new_dd = $('select[name="general"] option').clone();
new_dd.val('3').attr('selected','selected').appendTo('select[name="group"]');

but I find this:
<select name="group">
<option value="3" style="font-size:11px" selected="selected">Nothing</option>
<option class="dropdown_root" value="3" selected="selected">Admin</option>
<option class="dropdown_root_first_lvl" value="3" selected="selected">General</option>
<option class="dropdown_root_next_lvl" value="3" selected="selected">Group</option>
<option class="dropdown_root_next_lvl" value="3" selected="selected">Sales</option>
</select>

I want to see is:
<select name="group">
<option value="0" style="font-size:11px">Nothing</option>
<option class="dropdown_root" value="1">Admin</option>
<option class="dropdown_root_first_lvl" value="2">General</option>
<option class="dropdown_root_next_lvl" value="3" selected="selected">Group</option>
<option class="dropdown_root_next_lvl" value="4">Sales</option>
</select>

How could obtain this?
Answer: var new_dd = $('select[name="general"] option').clone();
new_dd
    .filter(function() {
        return this.value == 3;  // filter for option with value=3
    }) // in this point I have only option with value=3
    .attr('selected', 'selected') // give selected to that option
    .end() // capture all options again
    .appendTo('select[name="group"]'); // append to target

DEMO
Comment: thanks, but I just clones the option value 3 ... I need the other options
Answer: try this:
$('select[name="general"] option').each(function(){
   $(this).clone().appendTo('select[name="general"]')
})

$('select[name="general"] option[value="3"]').prop("selected", true)

Answer: HERE is a DEMO. http://jsfiddle.net/Simplybj/Eyq5x/
var new_dd = $('select[name="general"] option').clone();
new_dd.appendTo('select[name="group"]');
$('select[name="group"]').val( $('select[name="general"] option').eq(2).val() ).attr('selected',true);


Entity Translation and Field Collection

Question: Entity Translation exposes a checkbox on fields, entitled:

Users may translate all occurrences of this field

When dealing with a Field Collection field, which of the following should I check the box for?

Only the field collection field
Only the child fields
Both the field collection field, and its child fields
Comment: You should only 'Enable translation' for the field collection field (i.e. not its child fields).
Answer: Field Collection doesn't support Entity Translation, so my advice is to find another way to achieve your aim.
There is a patch available which has been under development for a long time, use at your own risk.
The Drupal.org issue with it's accompanying patch can be found here:
https://www.drupal.org/node/1344672

Entity Translation and Field Collection


What is substitution simultaneously?

Question: I have been reading Kleene "Introduction to Metamathematics" and found out that, even though he has been using a notion of "substituting simultaneously", he has never defined it.
On page 78 he says "The substitution of term $t$ for a variable $x$  in a term or formula $A$ shall consist in replacing simultaneously each free occurrence of $x$ in $A$ by an occurrence of $t$."
On page 79 he says "Similarly, we define substitution performed simultaneously for a number of distinct variables."
So, what does "substitution performed simultaneously" actually means?
My thoughts:
if we are given formula $A(x)$ and we want to replace $t$ for a variable $x$ in it then, first of all, we find all places in $A(x)$ (which is a finite string of symbols) where $x$ is. Then, we go from left to right through the string $A(x)$ and write $t$ in each place where we identified the $x$ is.
One then might define substitution in $A(x_1, ... , x_n)$ for $t_1, ..., t_n$ recursively but then I guess one runs into problem that $t_2$ for example might be $x_3$. Then, the recursive mechanism is not the same as one would intuitively think as "simultaneous substitution", at least I think so.
So, probably, one could define simultaneous substitution in the case of many variables as, first of all, because $A(x_1, ..., x_n)$ is still a finite string, we find all occurences of $x_1, ... x_n$. Then, we go from the left to right in a given string and whenever we have occurence of some $x_i$ we replace it by $t_i$. Then, we continue until the string ends. Is this how it is supposed to be defined?
Answer: Yes, that is what 'simultaneously' means here.
As a concrete example, take the formula $A(x,y)$ to be $x=y$.
Substituting $x+y$ for $x$ and $x-y$ for $y$ simultaneously in $A$ yields
$$x+y = x-y$$
Substituting $x+y$ for $x$ and then substituting $x-y$ for $y$ in $A$ yields
$$x+(x-y)=x-y$$
These are evidently not the same formula!

What is substitution simultaneously?


Expressing a marginal probability using copulas

Question: Please correct me if I am wrong and kindly provide me with the correct notations. I have two questions:
We know that for the variables $(X,Y,Z)\in \mathbb{R}^3$, the marginal joint density $f(x,y)$ can be expressed as
\begin{equation}
f(x,y)=\int_{z}f(x,y,z)dz
\end{equation}
Furthermore, we know From Sklar's Theorem that
\begin{equation}
f(x,y,z)=f(x)f(y)f(z)c(F(x),F(y),F(z))
\end{equation}
Q1: So would it be correct to express $f(x,y)$ as follows
\begin{equation}
f(x,y)=\int_{z}f(x)f(y)f(z)c(F(x),F(y),F(z))dz
\end{equation}
and since $f(z)=dF(z)/dz$ (assuming $F(z)$ is differentiable)
\begin{equation}
f(x,y)=\int_{z}f(x)f(y)c(F(x),F(y),F(z))dF(z)
\end{equation}
Q2: If yes, how can one go on about calculating the above integral.
Thanks in advance.
Answer: The issue of notation seems crucial.  I propose, therefore, to disambiguate the ubiquitous and overloaded "$f$" by means of subscripts.  Thus, $f_{XYZ}$ will be the full density function and (therefore) the marginal density for $(X,Y)$ is
$$f_{XY}(x,y) = \int_{-\infty}^{\infty} f_{XYZ}(x,y,z)\,\mathrm{d}z.$$
If, for a sufficiently smooth version of $f_{XYZ}$ and real numbers $(x,y,z)$ you define a function $c$ on $[0,1]^3$ as
$$c\left(F_X(x),F_Y(y),F_Z(z)\right) = \left\{\begin{aligned}\frac{f_{XYZ}(x,y,z)}{f_X(x)f_Y(y)f_Z(z)} & & \text{if } f_X(x)f_Y(y)f_Z(z)\ne 0 \\ 0 && \text{otherwise,}\end{aligned}\right.$$
then indeed you may substitute this into the first expression for $f_{XY}$ to obtain
$$f_{XY}(x,y) = \int_{-\infty}^{\infty} f_X(x)f_Y(y)f_Z(z) c(F_X(x),F_Y(y),F_Z(z))\,\mathrm{d}z$$
and, because $\mathrm{d}F_Z(z) = f_Z(z)\,\mathrm{d}z$ by definition, substituting that into the foregoing does give
$$f_{XY}(x,y) = \int_{-\infty}^{\infty} f_X(x)f_Y(y)c(F_X(x),F_Y(y),F_Z(z))\,\mathrm{d}F_Z(z).$$
Concerning the calculation of such integrals, it comes down to what information you have and what form it's in; this is an unanswerable question in such generality.

Note that this $c$ is not the copula for $f_{XYZ}.$  The copula $C$ is given by
$$\begin{aligned}
C(F_X(x),F_Y(y),F_Z(z)) &= \Pr(X\le x,\,Y\le y,\,Z \le z) \\
&= F_{XYZ}(x,y,z) \\
&= \int^x\int^y\int^z f_{XYZ}(x,y,z)\,\mathrm{d}z\mathrm{d}y\mathrm{d}x.
\end{aligned}$$
Using a standard notation in literature on copulas,
$$DC(u,v,w) = \frac{\partial^3C(u,v,w)}{\partial u\partial v \partial w}$$
for $(u,v,w)\in[0,1]^3.$  Applying the Chain Rule (three times) we may relate that to the foregoing via
$$\begin{aligned}
f_{XYZ}(x,y,z) &= \frac{\partial^3C(F_X(x),F_Y(y),F_Z(z))}{\partial x\partial y \partial z} \\
&= DC(F_X(x),F_Y(y),F_Z(z))f_X(x)f_Y(y)f_X(z),
\end{aligned}$$
revealing $c$ as
$$c(u,v,w) = (DC)(u,v,w).$$
A simple example to contrast $c$ and $C$ is the case of independence of the variables $(X,Y,Z),$ for which $C(u,v,w)=uvw$ (the "independence copula") and $c(u,v,w)=DC(u,v,w)=1.$

Finally, to address the question in the title, a simple expression for the marginal probability in terms of the copula is
$$F_{XY}(x,y) = \Pr(X\le x,\,Y\le y) = \lim_{z\to\infty}\Pr(X\le x,Y\le y,Z\le z) = C(F(x),F(y),1).$$
Differentiate this with respect to $(x,y)$ to obtain the marginal density $f_{XY}.$
Comment: This is an incredibly complete and useful response. I thank you greatly for sparing your time.


Finding a transcendence basis of a field over a rational function field in positive characteristic

Question: Let $p$ be a prime number, and $k = \Bbb{F}_p(t)$ be a function field over $\Bbb{F}_p$. Let $R = k[x,y]/(x^p+y^p-t)$, and $K = \operatorname{QF}(R)$ be the quotient field of $R$. I need to find the transcendence degree of $K/k$, but my issue is unwinding all the definitions to get where I want.
I know $R$ is a UFD, which may or may not be useful. I attempted to write out an arbitrary element of $K$ but it was super messy, and probably not useful. It seems that $x$ and $y$ are transcendental elements over $k$ in $K$, but the algebraic relationship $x^p+y^p -t$ is throwing me off. It's a two-variable polynomial expression so that $x$ and $y$ should still be algebraically independent in $K$, I think.
So, my question is how do I seek out a transcendence basis for $K$ over $k$?
Answer: Hint: $k \subset k(x) \subset K$ and has transcendence degree $1$. On the other hand, $y\in K$ is a root of $p(Y) =Y^p + (x^p-t) \in k(x)[Y]$. The algebric relation is what makes then algebraically dependent.
Comment: Like in the linear case, in order to be basis as set has to be algebraically independent, so if $x,y$ belong to a transendence basis there are no polynomials relations (over k) $p(x,y)=0.
Comment: So for a transcendence basis of $K$ over $k$, given the ideal relationship, we only need $\{x\}$ or $\{y\}$, but not both?
Comment: Thanks, I think I have it. I needed it to use some facts about Kahler differentials, and the field theory was tripping me up.


New Python Programmer - trying to add a ValueError exception to a number guessing game

Question: I'm working through the Automate the Boring Stuff with Python Course on YouTube/udemy, and I'm on a lesson that covers a simple number guessing game. LINK
The code itself I more or less understand:
# This is a guess the number game.
import random

print('Hello. What is your name?')
name = input ()

print('Well, ' + name + ', I am thinking of a number between one and a ONE HUNDRED.')
secretNumber = random.randint(1, 100)

for guessesTaken in range(1, 7):
    print('Take a guess.')

    if guess < secretNumber:
        print('Your guess is too low.')
    elif guess > secretNumber:
        print('Your guess is too high.')

    else:
        break # This condition is for correct guesses!

if guess == secretNumber:
    print('Good job, ' + name + ', You took ' + str(guessesTaken) + ' guesses.')
else:
    print('Nope. The number I was thinking of was ' + str(secretNumber) + '. You Failed!')

You take a random integer between 1 and 100. The user tries to guess it. If they get it right, it tells you. If you're unable within a certain number of guesses, you lose.
I wanted to add a 'try' 'except' statement to deal with a non-integer input that the user might make. It took me a while to get around the syntax errors, but I managed to write:
for guessesTaken in range(1, 7):
    print('Take a guess.')
    try:
        guess = int(input())
    except ValueError:
        print ("That's not an integer!")
    if guess < secretNumber:
        print('Your guess is too low.')
    elif guess > secretNumber:
        print('Your guess is too high.')

    else:
        break # This condition is for correct guesses!

This produces the correct error message. However, it produces another 'NameError' because guess is now not properly defined.
How should I amend the flow statements to get me back to the point where the program allows me to input a different value?
Comment: You can use **`while True`** to wrap `try except` and use **`break`** at the end of the try block
Comment: You seem to have posted more code than what would be reasonable for your issue. Please read [ask] and how to make a [mre]; providing a MRE helps users answer your question and future users relate to your issue.
Answer: The problem is that when you catch the exception in your except statement, execution continues into the following if expression, at which point you get your NameError because guess isn't defined (because the assign statement raised a ValueError exception).
If the user enters an invalid input, you problem just want them to try again. That's what the continue statement is for:
for guessesTaken in range(1, 7):
    print('Take a guess.')
    try:
        guess = int(input())
    except ValueError:
        print ("That's not an integer!")
        continue

Answer: Your problem is that the loop is continuing after printing "That's not an integer". Use a continue statement to solve this problem.
for guessesTaken in range(1, 7):
print('Take a guess.')
try:
    guess = int(input())
except ValueError:
    print ("That's not an integer!")
    i -= 1
    continue // Returns to start of loop without executing the rest of it
if guess < secretNumber:
    print('Your guess is too low.')
elif guess > secretNumber:
    print('Your guess is too high.')

I've also added i -= 1 to reduce i by one. This is so that the user's number of guess left does not change in case they accidentally type a letter.


Breusch-Godfrey Test and the length of the lag, p

Question: I'll use Breusch-Godfrey (BG) test to test correlation of an AR(1) model. In order to perform a BG test, the simple regression model is first fitted by ordinary least squares to obtain a set of sample residuals. Then the residuals are used the  as the dependent variable and regressed over independent variables and its first p-lags. However a drawback of the BG test is that the value of p, the length of the lag, cannot be specified a priori. My question is; what is the best way to determine p?
Thank you.
Answer: In summary, the question already states that the alternative hypothesis of the Breusch-Godfrey test is not fully specified a priori. This is correct; however, below I discuss some ways to think about this test that might be helpful.
In theory, the specification of your model should give you some idea about the length of the lag that you can expect. Two examples:

If you have monthly data, then you should try p=12 to check whether the residuals for, say, all February data points are similar. Similarly, if you have quarterly data, then you should try p=4.
If you have overlapping data (e.g. t=1 contains S&P 500 returns from January 1950 to January 1960, t=2 contains returns from February 1951 to February 1952, etc.), there is an "information overlap" inherent in the specification of your model. See here and here for more information on this specific issue.

Empirically, you can of course always just try different lags and see how this affects the Breusch-Godfrey (BG) test statistic and the corresponding p-value. As you do so, bear in mind the following:

As you increase the number of lags, you are increasing the number of regressors in the BG regression (which regresses the residuals on the independent variables of your model and on the lagged residuals). This increase in the number of regressors will naturally lead to an increase in the test statistic since it is defined as n * R-squared (from the BG regression). This is somewhat balanced by the fact that the degrees of freedom of the Chi-Squared distribution (which this test statistic follows) increase with the number of lags and that thus the "significance hurdle" for the test also increases, but it is nevertheless something you should bear in mind.
The maximum number of lags that you can introduce is n-k, where k is the number of independent variables incl. the intercept. (If you were to have lags up to p=n-k, then the total number of regressors in the BG regression would be p+k=n. Obviously, you can't have a regression with more regressors, incl. the intercept, than data points.) Bear in mind that many computer programs (e.g. Stata and R) fill the beginning of the lagged error vectors with zeros in order to not lose the information in those data points. This is neat but it also means that as p approaches n-k, the additional lags don't contain that much information anymore since they consist mostly of zeros.


Density plot narrow peaks and mean far away from peaks

Question: I am trying to understand a density plot. It has narrow peaks and means are far away from the peaks. What would be the reason for such behavior? Should I be doing a different plot to understand this data other than a density plot?
Description of data: It's user performance and different colors represent different groups. You can think performance as step count and I have logged the performance.
<code>ggplot(dt, aes(x=log(step_count), fill=groups)) + geom_density(alpha=.3) +
  geom_vline(data=mean.steps, aes(xintercept=mean.val, color=groups), linetype="dashed", size=.5)
</code>
Comment: @RomanLuštrik Sorry, but that's misleading advice. For one, peak (meaning, position of peak, or mode) and mean should align for any unimodal symmetric distribution, and for two, that's possible otherwise. 0, 0, 1, 1, 1, 1, 3 has mean, median and mode all 1 but is not symmetric. Many asymmetric binomial distributions have mean equal to mode. Please see also my comment on the answer by mcastillon.
Comment: Is sounds like your question is more about the behavior of statistical methods/plots rather than a specific programming question. As such it probably belongs on [stats.se] instead.
Comment: Mean assumes the data comes from a normal distribution (which is why this statistic is appropriate only for such data). Peak and mean will align only when you distribution is (~perfectly) normal.
Comment: @NickCox I agree, but if one is interested in going backwards (from mean, this about distribution), it's less assumptions to assume a symmetric distribution because asymmetric distribution can be left-right skewed for starters. Hence, my advice to have a meaningful mean for symmetric distributions only. E.g. mean income per country means diddly squat (if you don't know the distribution) and assuming normality will give an erroneous perception at the very least.
Comment: We don't really disagree, I expect; nevertheless you are making stronger statements here than are needed or possible. For example, means can be pertinent for anything additive through their link to totals, regardless of skewness. Also, the mean has a definite **meaning**; if the issue is how much **use** it is, the answer is indeed sometimes little or none. More generally, if one were given the mean and nothing else, then there is indeed a question of what are the weakest extra assumptions that can be made, but that is a quite different problem from the problem in this thread.
Answer: One thing to note is that the means are far from the peaks for each of the groups except the blue one. All of your non-blue groups are skewed right (and thus not normally distributed) meaning the median performance of each group is less than the mean performance. What this means in the context of your data is that most users' performances are on the lower end while a few users have higher performances.
I'd say you have the right choice of visualization.
Comment: Skewness should be contrasted with symmetry, rather than normality. Advice received earlier to the effect that means only apply when data are normally distributed is  quite unsound. Statistical people routinely apply means not only to symmetrical distributions other than the normal but also to skewed distributions such as the Poisson, gamma or exponential. It's just that the mean is necessarily pulled towards high values when right skewness is present (and to low values when left skewness is present) and can sometimes be misleading if there are outliers. So, plot the data, as here.
Answer: I think your data are skewed right strongly but because you use log you can't see that, so mean being righter than peak is obviously unsurprising.
Comment: Seeing skewness when a log scale is used shows that the skewness is strong; skewness isn't thereby hidden unless the reader doesn't understand log scales. If by "normal" you mean "distributed following a normal (Gaussian) distribution", then the second part of your statement is contradictory or confused; if you mean something else, then your meaning isn't clear. Perhaps you just mean something like unsurprising.


How many group homomorphism are there from $A_3$ to $S_3$?

Question: How many group  homomorphism are there from $A_3$ to $S_3$?
Here is possible duplicate  answer. I was reading it but could not understand anything.
My attempt:  $A_3\cong\Bbb  Z_3$. Both  have same order and the subgroups of $S_3$ are $\{0\}$ and $S_3$. By using the first theorem of isomorphism I get:
For $\{0\}$, $\Bbb Z_3/\{0\} = \Bbb Z_3$. Now the number of order in $\Bbb Z_3$ is $\varphi(3) = 2$.
For $\{S_3\}$, $\Bbb Z_3/S_3  =\Bbb Z_2$, now the number of order in $\Bbb Z_2$ is $\varphi (2)=1$.
So the number of group homorphisms from $A_3$ to $S_3$ is  $\varphi(2) + \varphi(3) = 2+1 =3. $
Is my answer is correct or not?
Please verify and tell me the solution.
Answer: In general, a homomorphism from $Z_n$ to a group $G$, is given by $a\mapsto g^a$ where $g\in G$ and $g^n=e$. The number of these homomorphisms is
thus the number of solutions to $g^n=e$.
In $S_3$ there are three permutations whose cube is the identity.
Comment: +1 for ur answer,,,@ Lord Shark the unknown,,,can u tell me  how can i show in S3 there are three permutations whose cube is the identity?
Comment: @lomberlego You could write down all six elements of $S_3$.
Comment: @ Lord shark the unknown ..i have write {0},(12),(23),(13),(123) and (132)....now how can i show ?


Deploy a Java App with a database, what users need to install?

Question: If I have a Java app (not web app, 100% local), that I want to deploy. Do user have to install something extra other than the <code>.jar</code> file if I use a database?
Also good point if anyone can say each case of this 3 different databases : 1. Java DB (Derby), 2. H2, 3. MySQL.
Answer: None of them, or if you want to install a database to the client, Java DB is an option included with Java SE distro. You also need a client drivers to make a connection to db. Derby also has an embedded database drivers, which you can embed to the application.
Comment: thanks Roman for answering the question. Two differen questions:          1.So the database pretty much automatically comes with the app itself ? . Behind the scene – will it create any table or something OR it will save the data in excel or any other similar things like that?                                           2. What do you mean with the client java db
Comment: it's difficult to understand what you mean a database, it's itself an app  and doesn't come with app. And yes it creates tables or something. If your app can save data to execel format it's not a database, unless office is installed and used as a database.
Comment: ... because it's a server app, a vendor provides drivers for clients to use in their client apps, a database is not a part of Java EE and it's language agnostic. However  Derby has a pure Java implementation  and could be used in the embedded option, this way it's running to the same process as Java client.
Comment: ... however H2 is also pure Java and could be embedded, and may be has less size of the class library, but you should compare features your application needs, ....
Comment: by -database- i mean a normal database, not "just a place to store data like excel." .  -Itself/comes with the app- i mean the same as before, we don't have to install other than the jar file itself.
Comment: good, do you want install a server standalone or embedded?
Comment: alright, its more clear now,Nice question  :D, hmm.. i think desktop app(not web app) means i don't need any server, right? so it willl embedded i guess... Sorry if u getting confuse, not speak java and english that well :D
Comment: java client is a program written in java that connects to the database server
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/78720/discussion-between-hilmanrdn-and-roman-c).


How can I prevent the Nav Bar from leaving behind a black bar? (immersive mode)

Question: An app that uses immersive mode leaves a black bar at the bottom of the screen when the app is returned to after waiting a while (activity is destroyed).
What is happening: (I have enabled the developer option: "Don't keep activities" to reproduce this).

First time launch of the app. Immersive mode works as expected.
Swipe up to reveal the 'immersive sticky' nav bar, and use the 'Home' button to leave the app. The background of the nav bar briefly shows a black background before the app closes.
Use the 'Recents' button, and select the app to resume it.
The app opens to briefly reveal the nav bar over a black bar. The system ui collapses into immersive mode but the black bar remains.

This bug also only appears on Lollipop, not KitKat.
I have stripped back the app to simply launching a dummy activity with no functionality apart from setting System UI flags:
public class DummyActivity extends FragmentActivity {

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
        setSystemUiVisibility();
    }
}

public void setSystemUiVisibility() {
    if (getWindow() != null && getWindow().getDecorView() != null) {
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }
}

EDIT:
After creating a new fresh project with only this Activity I have seen this issue reproduced when using an app theme extending "android:Theme.Holo"..., and fixed the issue in this sample project when I extend the Material theme instead:
Change

to

Unfortunately this fix hasn't solved the issues in my main project, but it brings me closer to a solution and might help others with the same issue.
Comment: Have you tried to run Hierarchy Viewer to determine what is that bar?
Answer: I was having the same problem. Here are a few updates I made which made it go away. Hopefully one of these works for you!
activity_main.xml
android:fitsSystemWindows="false"

style-v21
<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowSharedElementsUseOverlay">false</item>

MainActivity.java
getWindow().getDecorView().setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
    );

Answer: For me it was a black bar at the top. Key thing was this in the activity style:
// Important to draw behind cutouts
<item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item>

Here is my code:
1- In Activity
private fun hideSystemUI() {
    sysUIHidden = true
    // Enables regular immersive mode.
    // For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE.
    // Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY
    window.decorView.systemUiVisibility = (
            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
            or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            // Hide the nav bar and status bar
            or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // Hide nav bar
            or View.SYSTEM_UI_FLAG_FULLSCREEN // Hide status bar
            )
}

private fun showSystemUI() {
    sysUIHidden = false
    window.decorView.systemUiVisibility = (
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            // Set the content to appear under the system bars so that the
            // content doesn't resize when the system bars hide and show.
            or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION // layout Behind nav bar
            or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // layout Behind status bar
            )
}

2- In root view of xml layout
android:fitsSystemWindows="false"

3- Style for the Full screen Activity:

Comment: This solved my issue. It is important to note you may need to change the minSdk in order to add the first line (<item name="android:windowLayout... ). On mine I had to move it from API level 21 to 27 and then it worked as it should. Thanks [fullmoon](https://stackoverflow.com/users/1143361/fullmoon).
Answer: Using

does solved the problem, but it only work for api:21.
In order to make it works for all system. You can create a directory called style-v21 in res directory, and put that style.xml there. Android system is smart enough to pick which one to use for new or old phone.


Filter a type to only its non-nullable attributes

Question: given this type
type HasOptionals = {
   name: string
   surname?: string
}

is it possible to generate a type that excludes any optional properties?
type example = OnlyRequired<HasOptionals> // { name: string }

Answer: You can use a mapped type with key remapping:
type OnlyRequired<T> = {
    [K in keyof T as undefined extends T[K] ? never : K]: T[K]
}

Now OnlyRequired<HasOptionals> is indeed { name: string; }.
Comment: this exactly answers my question, thank you. I'm having a bit of difficulty translating the solution when T is an array. Could you help define `OnlyRequired` when T is `[name: string,  surname?: string | undefined]`
Comment: @stackoverfloweth "having difficulty" is a long way short of a [mre]!
Comment: @stackoverfloweth that's a _tuple_ type, and should probably be a separate question. It's probably a dupe of https://stackoverflow.com/q/51672504/3001761.
Comment: https://stackoverflow.com/questions/70840917/filter-tuple-type-to-only-required-properties


What are the arguments for and against over-practicing?

Question: I am not a musician but instead draw a lot of inspiration from music and musicians for my pursuits (writing, mathematics, running). This week after seeing/hearing Itzhak Perlman play and conduct at the Philadelphia Orchestra, I viewed some of his pedagogical videos on YouTube. One one of the videos, he proclaimed, "There is absolutely such a thing as over-practicing." He continued by saying something to the effect of, "Five hours is about the maximum for daily practice time." He further insisted that, within each hour, ten minutes should be allocated for break time.
Are there prominent musicians who are known to disagree with Mr. Perlman's over-practicing philosophy?
Comment: I have never come close to reach dangerous levels that are close to the limit of over-practicing. I think I might be at times close to the limit of "under-practicing" though...
Answer: Off the top of my head, I would be very concerned with the potential for repetitive stress injuries, like carpal tunnel syndrome. Over time, mental fatigue will start to set in, and technique will suffer. As in any discipline, there is significant potential for burn-out, where motivation starts to decline.
The sole advantage is that the musician will be able to complete more work on the music in a shorter period of time. As in any other field, like writing, weight training, or medicine, the threshold for when practice turns more harmful than beneficial is highly personal. To declare a single time that applies to all musicians, or even a single musician in all situations, is nonsensical. It always depends on what needs to be done and how much time there is to do it.
Answer: I think the question of the maximum number of allowed practicing hours each day can be different for everyone. But I don't think it is possible to say that "over"-practicing may be a good thing. Any practice implies some stress on the body, or on the mind, and it is absolutely necessary to allow them some time "to heal", so they will be available the next day, and won't break at any time.
Then, I think it is possible to work on your instrument for 8 hours a day if you can have a few breaks included in your daily planning. But you need some time also to let new information, or new habits make their way on your mind too. And more than anything, what is important is that it is better to work a little each day, with specific goals and a great focus, than to work 2 days a week for 8 hours consecutively... It's even more important when you are a beginner.
And there is not such a thing than "good over-practicing" by its very definition. But you can have "good practices" at a professional level implying to spend a lot of hours each day practicing.
Answer: I heard a piece about Stéphane Grappelli on the radio the other day that mentioned how astounded he was at the amount of practise fellow musicians did, and that he'd sheepishly admit to never practising! I cannot see this as a good idea but it is another data point. It's backed up by Nigel Kennedy writing about him in the Guardian: "The strangest thing about Stéphane was that I never, ever saw him practise". Perhaps for him the sheer amount of performing he did stood in place of practise.
Answer: Is it even possible to practice more than five hours a day? After doing all that practice you should be pretty tired and needing of some rest. If by you do by some miracle have the power to continue the quality of the practice is not going to be high. It should then be better to go and do something else.
Also the amount of time is of secondary importance to the quality of the practice. Three hours of high quality practice is definitely better than five hours of doodling.

(2) For the musicians out there: how does Mr. Perlman's advice align
  with your experience?

This musician can tell you he is correct. Five hours with then minutes breaks in between the hours is absolutely the maximum you can do in a day. If you do that for two or three years your progress will be immense.
I also think that for the long term motivation of the student it should be better to not have a extreme practice schedule. It is also worth noting that these five hours a day philosophy is and should be directed at students at a Collegiate level of musicianship.
For young children it is often more important that there be a emphasis quality over quantity. For them a half hour a day under a parents supervision is better. When the hit there teenage years and they can start to motivate themselves then the practice becomes longer.
You should also take note that Julliard is solely motivated to produce performers. It is entirely possible to study for four years there and not know how to explain to a person how you get the flats in Ab minor.
In a music academy where you may want to learn to become a teacher there may be less practicing to focus on certain other parts of being a teacher like methodology, psychology and theory.
It all depends on who you teach, what level they are and what there ambitions are.
Comment: I practice about 3 to 4 hours per day on the clarinet and saxophone. I ALWAYS take breaks after playing a few pieces. Although I enjoy playing immensely, I am surprised at how tired I can get.  For one clarinet player I know well, his practicing has been at a heavy price.  He has as a result carpel tunnel.  To minimize the risk, you MUST take breaks.  These breaks are just as important as playing.
Comment: I know a few very good guitarists, with high technical skills, playing between 5 and 8 hours a day each day. I think this is necessary to be at their level and with their engagement. Anyway, it would be difficult to say that their training and playing is very focused for all this time. Maybe they are following a strict plan for 3-4 hours only. And obviously, they take several breaks.
Answer: I would be more specific and break down the types of practice activities you're talking about.

For all things, repetitive stress injuries are non-negotiable. Even with the best posture and technique and equipment, you do have to always supplement other activities and stretching and exercise into your daily routine or else you will have problems in the long term. Of course, genetics are weird and there are exceptions, but don't wait to find this out.
For practice that involves technique (the classic notion of practice, i.e. learning the mechanics of an instrument that involve physically playing), I would say there is definitely a limit on what you could hope to achieve in a single day. The complexity of training your entire nervous system to perfect a very finely tuned task is taxing on your body and brain and you will eventually reach a point of diminishing returns. While some people like to put exact numbers on this, and while research can probably hone in on a general number for the average person, everyone is different and you will just have to really be keen and introspective and find out for yourself what that number of hours is. It really is different for everyone.
For practice that involves mostly theoretical concepts or memorization, there are limits on this too. Concepts like The Pomodoro Technique put a specific number (30 minutes) on a type of "work-unit". But to me it can vary. Sometimes I reach a state of flow that can last for hours (unknowingly too) if I'm working on extending a concept that I already know, and other times 15/20 minutes is all I can do if what I'm working on memorizing is truly foreign and difficult to me. Again, introspection and experimentation is the key to the universe because you learn to pace yourself given what you're working on.
Then there's a type of practice that I think is truly limited by your waking hours in a day: just living in a concept. Sometimes when people I went to school with said they "practiced" for 8 hours, what they meant was that they would actually do things from items #2 and #3 for half-hour spurts and then spend large chunks of time day dreaming about what they just did, or watching youtube videos or listening to music or chatting with their peers. While it is not strict practice, it IS relevant however and productive if you have the time for it. In fact, I would say that this type of practice is also incredibly important for digesting material and plotting your next move. It allows your subconscious to take over and churn all the things you just put in your brain around and assimilate it. I can't tell you how many times I would work and work at something just to get up for only a couple minutes and have a new concept or a solution to my problem pop up in my head after only being away from the #2 or #3 type practice for mere minutes. The subconscious is more powerful then people realize and you need to learn how to effectively use it to set your brain up for success.

And add one more thing, sometimes, just simply playing is fun too. So lets say you finally reached that point of diminishing returns when working on something new (#2), you take a break by actually playing something "fun" (#4) with a friend. Is this over-practice? I say your only risk would possibly be repetitive strain injuries, but other then that, play away. Remember too, that as you get closer and closer to reaching a competent and "professional" status at any given task, your threshold for doing it increases as well. So it becomes more and more of a "natural" activity for you. So playing a song that you know well after practicing new and difficult material for hours on end might not be difficult or straining at all and you could play all day long.


Ubercart-based POS / Kiosk

Question: I have a Drupal 6/Ubercart 2 website with a desktop-specific theme. I intend to create a POS/Kiosk theme for the site, to be used when the site is accessed via a tablet (and possibly via smartphone). That theme would be bare-bones... a couple of Views showing products, probably the AJAX cart module, and very little informational pages. The POS concept would involve a kiosk with an ipad that public customers in a retail location would be able to use to place orders right then and there.
I suppose I just want to see if anyone out there has done a setup like this, or whether anyone has any ideas on things to avoid, issues that may be encountered, etc. Ideally, the end result of this port would be a recipe of sorts, that everyone else could use for similar situations.
So far, potential issues I have come up with are:

Must auto-log out users upon successful order completion. Is there a way to do this in Drupal/Ubercart via stock settings or an existing module?
Some type of auto- or manual-logout for when a customer walks away from the POS without completing the order (so that the "next person up" can start with an empty cart, or can at least easily clear the cart and start their own shopping experience). I suppose this can be accomplished with a large "Click here to start a new session" button that would basically be a "rebranded" log out button...
...I'm hoping other viewers of this question might be able to point out any other issues I may not have thoughts of yet.

Looking forward to any input anyone out there may have!
Comment: Number 3 is not possible, a website can't take control of a users browser for obvious reasons. If you can lock the iPad to a single site natively then fair enough, but I'd remove that part of the question as it can never have anything to do with Drupal. Also I can't actually find a question in there, do you just need to know how to log someone out after placing an order?
Comment: @Clive, I just refined the question to make it more question-like. RE: locking the ipad, I do want to lock that single ipad in the kiosk to a browser... not cause the website to take control of the browser. I will post elsewhere about whether that is something that can be accomplished.
Answer: I'm working on a similar problem.  I have an ubercart based shopping system that a customer wants to have available on a public computer in his store.  We need to change themes, branding etc and auto-logout users.  His users will also be ordering from home, so we have to identify that particular computer and change the behavior and look of the site when we know they are ordering from the in-store kiosk.
Kiosk module that may help
This module allows an administrator to put selected computers into "Kiosk Mode".
"Kiosk mode" simply means that a given computer will have an extra flag set for template files, which allows a themer to exclude certain page elements, such as off-site navigation.
I'm installing this on my test server and we'll see how well it goes.  I'm hoping to figure out how to get that variable (if $kiosk) into ubercart checkout conditions and trigger some actions based on it.  It seems like themeing is pretty easy with this module but as for changing behavior, I'm not super sure how it will work.
Please let me know if you find any magic bullets as we're both trying to do a similar thing and i'd be great to share a solution.
UPDATE: I've been working with kiosk mode module (drupal 7 version) for a bit and have been able to create custom rules by calling the kiosk_is_kiosk function defined in the module. Simply use custom php condition in rules with this code:
<code> return kiosk_is_kiosk();
</code>
And you can have different workflows for kiosk terminals than for regular on-line users.  So for example, once an order is finished the kiosk will log out the user, but not a person using the same site from the home.
-Zachary

Ubercart-based POS / Kiosk


Show all the upload fields

Question: Is there any way to show all the upload fields on a node?
Right now a user has to upload a single file and then get another field and so forth. Instead I would like to show the max number of permitted upload fields.
Answer: The add another option only appear if you choose unlimited in field settings.
If you choose an exact number say 5, it will display 5 image upload fields always.
Its the default property.

Show all the upload fields


Strange inequality in an NT problem

Question: If $a\neq b$ are positive integers and $a^2+ab+b^2 | ab(a+b)$ then show that $|a-b|>\sqrt[3]{ab}$.
WLOG $a>b$. $a^2+ab+b^2 | ab(a+b)-a(a^2+ab+b^2)=-a^3$, so we have $a^2+ab+b^2$ divides $a^3$ as well as $b^3$. From here I tried lots of things, but I don't think they are worth of mentioning. If you have any idea ,do not hesitate to suggest.
Comment: Since this is contest-math, please indicate a source, so that we know it's not an ongoing problem.
Comment: Equivalently we may show $(a-b)^3 \gt ab$.
Answer: Notice that $$a^2+ab+b^2\mid ab(a+b)\iff a^2+ab+b^2\mid a^3\iff a^2+ab+b^2\mid b^3$$ $$\iff a^2+ab+b^2\mid \gcd(a,b)^3$$
Thus, let $d:=\gcd(a,b)$, and let $x:=\frac{a}d, y:=\frac{b}d$. It follows that $$a^2+ab+b^2\mid \gcd(a,b)^3\iff x^2+xy+y^2\mid d\implies d>xy$$
You are left to show that $\lvert a-b\rvert>\sqrt[3]{ab}\iff \lvert dx-dy\rvert^3=\lvert a-b\rvert^3> ab = d^2\cdot xy\iff d\lvert x-y\rvert > xy$. But this is trivial, since $d>xy$ and $\lvert x-y\rvert\geqslant 1.$
Comment: @CalvinLin You are, of course, right.
Comment: In fact, since $ d > 3xy$, we have $ |a-b | > 3 \sqrt[3]{ab} $.  $\quad$ Makes me wonder what the contest setters were thinking about.
Comment: @CalvinLin You are absolutely right. I wonder if there is an alternative method that only shows the weaker estimate... I seems to me, however, that this should be the standard approach, but then, why $\sqrt[3]{ab}$ and not $3\sqrt[3]{ab}$?
Comment: This process is very standard. In fact, OP's observation of the algebraic manipulation leading to $a^3, b^3$ was nice, but not necessary. We have $ x^2 + xy + y^2 \mid d xy(x+y)$, and verify term wise that $ \gcd(x^2+xy+y^2, xy(x+y) ) = 1$ which leads to the conclusion of $x^2 + xy +y^2 \mid d \Rightarrow d > 3xy$.

Strange inequality in an NT problem


Why am I getting a parser error on my YAML config in MongoDB --Install

Question: I am trying to install the service for Mongodb. I am typing the following command in the cmd window, as administrator
c:/mongodb/bin/mongod.exe --config "C:\mongodb\mongod.cfg" --install,

but I am getting the following error:

Error parsing YAML config file: YAML-cpp: error at line 2, column 13 :
  illegal map value

Here is the config file contents:
systemLog:
    destination: file
    path: c:\data\log\mongod.log
storage:
    dbPath: c:\data\db

Answer: Well,
Note that YAML doesn't really satisfy with tabs, then, use space instead before destination and storage.
Don't forget to add a space after every ":" even in the lines systemLog and storage
Finally, use quotes to enclose your pathes and double backslashes in these pathes.
Try then with :
systemLog:
 destination: file
 path: "c:\\data\\log\\mongod.log"
storage:
 dbPath: "c:\\data\\db"


Why does the open string oscillate when I play its corresponding fretted note on another string?

Question: I noticed when I play for example a fretted A note on the E string, the below A string starts oscillating as well. I can observe this behaviour on all other strings. Why is this? Is this intended or do I have to get my acoustic guitar repaired?
Comment: @DavidBowling unfretted instruments have sympathetic vibrations too, if you hit it exactly right!
Answer: This phenomenon is called sympathetic resonance. There's nothing wrong with your instrument, in fact it's probably a sign that your instrument is in good working order!
What's happening is that the when you play the A on the E string, your instrument & the air around it is vibrating at that frequency (among others, but for the the purposes of this explanation the 110Hz fundamental frequency of the A is important). This is the frequency at which the A string vibrates when plucked. When the instrument & the air around it vibrate at that frequency the string vibrates in sympathy. You will also notice that your top E will vibrate along with your bottom E because of the same principal. And if you use a "just" tuning on your guitar the B string will vibrate along with the bottom E.  In fact, the strings that align with pitches in the harmonic series of the note played will vibrate along with it! (You can demonstrate this on a piano by holding down the sustain pedal, striking a note & then damping that note with your finger & listening for the sympathetically resonating strings.)
Comment: You can demonstrate this on guitar with a tiny strip of paper 1/4 of a postage stamp at most,  on an open string. Guitar on its back.
Comment: You've begged the question by calling it "sympathetic resonance" without explaining  what the mechanics are.
Answer: Adding to @David Bowling's comment, quote:

Sympathetic vibrations: when you play the fretted A, the instrument
  vibrates with frequencies that of course induce vibrations in the
  other strings.

Each string has natural resonances at the fundamental, first octave, fifth above that, fourth above that, and so on.  These correspond to vibrational nodes (spots with no string displacement) only at the nut and bridge for the fundamental, then with one node midway, then two nodes at 1/3 and 2/3, and so on.
Anyway, what happens is this:  every vibrating frequency in the body of the instrument transmits energy into each string.  However, only those harmonic frequencies a self-supporting; all other frequencies damp themselves out because the travelling energy wave, reflecting off the endpoints, is out of phase with itself and thus cancels out.


How do I check the version of a third-party module?

Question: There's a place in the search_krumo module where we want to supply a different JavaScript file path basing on the version of the Devel module being used.
Is there a Drupal function that will check the version for us, or do we need to get the module version with system_get_info(), and then do something with  $module['version'] (which is a string like 7.x-1.5) ourselves?
If the latter, how should we test if version is greater than 1.6? Should we convert the string to an integer, strip out the x and stuff, and compare integers?
Comment: use `version_compare` php function http://php.net/manual/en/function.version-compare.php
Answer: Supposing that the second version string is also in the 7.x-y.z format, where y and z are numbers, you could use code similar to the following one.
function compare_module_version($module, $version) {
  $info = system_get_info('module', $module);

  if (empty($info) || empty($info['version'])) {
    // The module doesn't exist, it's not enabled,
    // or there isn't any information about the module version.
    return FALSE;
  }

  return version_compare($info['version'], $version);
}

If $version uses the y.z format (where y and z are numbers), you can use the following code.
function compare_module_version($module, $version) {
  $info = system_get_info('module', $module);

  if (empty($info) || empty($info['version'])) {
    // The module doesn't exist, it's not enabled,
    // or there isn't any information about the module version.
    return FALSE;
  }

  return version_compare(substr($info['version'], 4), $version);
}

If then both the version strings are in the 7.x-y.z format, and you want to compare the version string without considering the Drupal compatibility part of the version, you could use the following code.
function compare_module_version($module, $version) {
  $info = system_get_info('module', $module);

  if (empty($info) || empty($info['version'])) {
    // The module doesn't exist, it's not enabled,
    // or there isn't any information about the module version.
    return FALSE;
  }

  return version_compare(substr($info['version'], 4), substr($version, 4));
}

version_compare() is thought to compare version number strings, and it is able to correctly handle a version like '7.x-1.0-alpha1', which is considered to be lower than '7.x-1.0-beta1'.
compare_module_version() returns FALSE if the module is not enabled (which also includes the case the module is not even installed), or when the information about the module version has not been found. Otherwise, it returns -1 if the module version is lower than the second function argument, 0 if they are equal, and 1 if the second function argument is lower.
I would not use drupal_parse_info_file() since that function re-parses the module .info file when the information contained in that file (or any .info file for enabled modules) has been already gathered from Drupal.
Answer:
You can use system_get_info('module',  'devel') function and split version to get number after 7.x-
Or goes with this aproach parsing info file here is a solution from stackoverflow get a module version


Does the standard error assume the mean is the centre of the distribution?

Question: In statistics we can calculate a mean of a sample and the standard error of the mean. Let's say the mean of a sample is 2 and the standard error 1.5. If we repeatedly sampled from this population, it would be expected that the average distance of the sample mean from the population mean is 1.5. Up until now I think I've subconsciously thought that 2 is assumed to be the centre of the distribution, or in other words the population mean. But am I right in saying that 2 is just as likely to be in the tails of the distribution as it is the centre of the distribution?
Answer: I understand your example such that The 2 is the population ("true") mean. An unbiased estimate of the mean would result in a sampling distribution which is centered about that population value.
However, in practice we don't know the population value. What we see is the mean in the sample, and that mean could have any possible value. It is more likely to be near the population mean, but there is no guarantee that that is the case in your particular sample. If you perform many statistical tests (as most of us will do in their lifetime) you will most of the time be near the population mean, but some of the times you will be way off.
Taken in isolation, you have no way of knowing when you are reasonably near and when not. However, usually we participate in a debate where multiple people/teams try different ways of answering the same or "sameish" question. In time it will become clear which study is the outlier and which study is not.

As an aside: You are right that a standard error is the standard deviation of the sampling distribution. However, a standard deviation is not the average deviation from the mean but the square root of the average squared deviations. Since squaring is a non-linear transformation: $\sqrt{\mathrm{E}(dev^2)} \neq \mathrm{E}(dev)$. In fact, in case of the mean we know that $\mathrm{E}(dev)= 0$, and the estimate of central tendency that minimizes $\mathrm{E}(|dev|)$ is the median.


I don't recognize the symbol on top of this note. What is it, and how does it affect the note?

Question: This is a picture of the note and the symbol. It's part of a blues trombone solo. I would like to know what the symbol is and how I should play it.
Comment: The symbol indicates how the tone has to move.
Answer: That is a bend or a dip.  You make a clear attack on the note and then do a very slight glissando around a quarter or half step down and then return to the original pitch.
Comment: Sorry -- I clicked on 'Answer; then made a cup of tea while I thought about it! I think we've described it identically so I'll upvote your answer.
Comment: I often need to notate such articulations in transcriptions. Would a similar, inverted mark be generally understood to mean a slight **raising** of the pitch before returning to center?
Comment: @JimL. In transcriptions you'd probably be fine. You'd generally be using those for academic purposes where the idea is to imitate the recording, not play it in the abstract without hearing it.  While I can't recall ever seeing that, if it was accompanied by the recording it woudl be obvious what you meant.  Its rare for me to play something like that but I have seen it before let me see if I can find the recording of that...
Answer: It's a bend: an articulation mark representing a brief flattening of the note.The note is attacked in tune but is immediately flattened - by up to a semitone - before coming up to pitch again.


Spark InvalidClassException

Question: I am try to send code to Spark master from intellij directly:
  def main(args: Array[String]) = {
    println("***hello spark-test***")
    val spark = SparkSession
      .builder()
      .master("spark://172.22.208.1:7077")
      .appName("Spark-Test Application")
      .getOrCreate()
    import spark.implicits._
    val rawData = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    val rdd = spark.sparkContext.parallelize(rawData)
    val df = rdd.toDF()
    val result = df.filter($"value" % 2 === 1).count()
    println(s"***Result odd numbers count: $result ***")
    spark.stop()
  }

result:
the application log hangs at connecting to master:
22/12/29 12:38:55 INFO StandaloneAppClient$ClientEndpoint: Connecting to master spark://172.22.208.1:7077...
22/12/29 12:38:55 INFO TransportClientFactory: Successfully created connection to /172.22.208.1:7077 after 38 ms (0 ms spent in bootstraps)
22/12/29 12:39:15 INFO StandaloneAppClient$ClientEndpoint: Connecting to master spark://172.22.208.1:7077...

driver log:
22/12/29 12:39:35 ERROR TransportRequestHandler: Error while invoking RpcHandler#receive() for one-way message.
java.io.InvalidClassException: scala.collection.immutable.ArraySeq; local class incompatible: stream classdesc serialVersionUID = -8615987390676041167, local class serialVersionUID = 2701977568115426262

spark version : spark-3.3.0-hadoop3-scala2.13
intellij's scala version: v2.13.5
However when I remove the line 'master("spark://172.22.208.1:7077")' and build a jar and send it via spark-submit it works fine.
Answer: Usually this error means that you are not running the same Spark version or the same Scala version.
You need to make sure that the code you are running on Intellij is running on the same Scala and Spark version than the one you are running on your cluster.
Since you mentionned you are running Scala 2.13 on IntelliJ, I guess that your local Spark version is not the same as the one you have on the cluster.

Spark InvalidClassException