Correct piano wrist movement

Question: I'm currently learning play piano by myself. Since I'm a beginner and I don't have any tutor, I'm very careful about learning proper technique.
Here it looks like Mr. Hoffman has no problem with wrist that goes low. His idea is about using the help of gravity as you can see here
Another idea is keeping the wrist always on same level and avoid the movement of wrist that goes low. Check here.
Since both ideas are told by those people  I don't want to separate them as this is wrong or this is right
What I want to learn is advantages and disadvantages of both techniques and what is the best for a beginner to continue with?
Comment: 'Movement' of wrists isn't exactly what this is about. 'Height' of wrists may be more apposite.
Answer: Probably a more important factor is your whole body level compared with the height of the keyboard itself. If you sit too low, it will inevitably cause your wrists to be low, as gravity works on your forearms.
I encourage sitting so that the elbows are about an inch higher than the top of the white keys. That way, my students can let gravity help with their playing. There's no point in fighting gravity when it can be used instead!
Having said all that, each person works out what's best for them, but hopefully my idea is a good start point. Low wrists (lower than the keys) is probably not a good position - certainly not all the playing time.
Answer: What's really bad technique is having a wrist that stays low below the level of the keys, while you are playing with your fingers. This is a very common beginner mistake that can result in painful wrists and eventually RSI. Don't do this.
That's why in the beginning many tutors try to keep the wrists level above the keys. It's a good starting point, but this is not a very hard rule. On the contrary don't try to make your wrists too stiff, as if your forearm and your hand are fused together in a single concrete block. This can create problems too.
In practice, it is clear from watching many professional pianist that the wrists don't have to stay level, but are used dynamically and can move a lot, above and below the level of the keys.
Answer: Your wrist is a fulcrum whose main purpose is to let the energy of your arm pass through the wrist, through the fingers and into the keys.  Much like if your alignment is off while walking.  If your knee or ankle is not properly aligned and you misstep, all your weight will stop in the joint that is not aligned thus, we sprain our knees or ankles.  Instead of our weight going into the ground, it goes into the joint that is misaligned.  Like electricity passing from point A to point B.  All is fine unless you get in its way and disrupt its path by touching the wire it is traveling on.
Wrists can take on various flexion shapes and those are okay as long as the shaping is a result of the arm and not originating in the wrist.  Does that make sense?  Like, if you hold your arm out, gravity will naturally flex your wrist.  YOU are not flexing it, gravity is. When playing, the various shapes of the arm and elbow will shape your wrist, you will not. I beleive this is the foundation of the Russian style of playing (I'm Polish).  There is a video called "Freeing the Caged Bird" where the author uses floor exercise to teach gravitational alignment of the fingers and wrist. They may be on Youtube.
Two shapes you never want to do are ulnar and radial deviation, that is twisting your wrist left or right to grab a key.  Remember, the arm places the finger, the finger and wrist don't contort to reach a key. The second is extending your wrist (dorsiflexion or bending it up).  This can happen if you sit too low.
To find your proper bench height, adjust your stool so that the bottom of your forearm is a little bit higher than the keys so that you can rest up.  If you sit too high you may slouch or slump resulting in hyperextension of your wrists.  If you sit too low you may raise your shoulders to make your wrists higher.  An improper bench height will literally give you a pain in the neck, or back, or wrists.  It will definitely affect even playing.
Go write on a chalk board, gently wash a window of wipe down a table, gently.  Notice that it is your shoulder, elbow and arm doing all the work.  Your wrist, hands and fingers just go where they are needed and your moving arm places them.  That is how you should approach piano playing.  The fingers don't drag the arm behind them.  If you play from any of your fulcrums, which include the fingers and each phalanx, that is where your gravitational energy will stop, where there is a break.
If you misstep while walking and all your gravitational energy goes into your ankle and not the floor, you sprain your ankle. At the piano, the damage is often cumulative and insidious. We often ignore tension thinking that we need more practice, strength, endurance or exercises.  In actuality, we need adjustments to our alignments.  Some teachers don't know this and they just tell you to practice more resulting in cumulative damage, poor technique or the illusion that you have no talent.
If you don't have tension, try this.  With your arm at a right angle in front of your chest, with all five fingers relaxed and together, thumb facing upward, rotate your forearm from your elbow as if you were playing a slow tremolo (like turning a screwdriver or turning a doorknob). The rotation or left/right movement comes from your pronator and supinator muscles surrounding your elbow.  The wrist nor fingers should move by themselves, it is the elbow which is moving them. If you already hardwired tension into your fingers and wrist (really your brain), you will have to eradicate it.  Rotation should be effortless and the P&S muscles are indefatigable.  Unlike your flexors which are designed for gripping, not speed. Also, if there is the slightest ulnar or radial deviation, your wrist will bear the brunt of the rotational force instead of it dissipating into the air.  That ain't good.
Of course, when you then move your arm to the keys and static load pronation on the keyboard, you will feel tension unless you've already acclimated to it or have brow beaten it into submission with silly exercises.  There are ways around static loading pronated tension but you should work on these with a teacher who hopefully knows anatomy and physics.
Piano playing isn't some mystical hocus pocus thing called talent.  It is mechanical and everything that moves must obey the laws of physics.  Pianists are not exempt. Ignore those laws of ergonomics and there will be a price to pay.  I should probably close with something diabolical such as "Bwahahahahaha..."
But seriously, find a teacher who knows the basic Newtonian laws.  Physics isn't just a class in HS that you don't use in the real world.  You use physics with every move you make.
Comment: I know that we have to avoid comments like "thanks" etc. but I would like to give you very special thanks for this detailed, logical explanation. "Freeing the Caged Bird" is a gem also.
Answer: There are exceptions to every rule, as I guess you're finding out. If you look at Horowitz, you'll find that his wrists often dip below the key level, especially when he's doing finger passages. (Check out some of his Mozart performances.) Gould's wrists would go even lower. But most top pianists keep their wrists above the keyboard level.
If you look at pianists performing, you'll see that a lot of where the wrists are in relation to the keys has to do with how high they sit. Gould was famous for bringing his own stool to sit on, presumably because standard piano benches wouldn't go low enough for him.
At the other extreme, Rubinstein sat very high at the piano, and his forearms were usually angled downward towards the keyboard. Other examples of pianists who sit high are Angela Hewitt and Daniel Barenboim.
The important thing, the most important thing in my opinion, is to avoid playing with too much tension in particular areas of your body. This is what causes injury most often. When I was a freshman in college as a piano major, I often got a great deal of tension in my forearms, mainly because I wasn't aware enough of all the different movements my fingers had to make to do certain things. I had to learn to get rid of that. Many years later, I realized that I was in the habit of clenching my jaw when I was doing something difficult. Obviously, this wasn't so good for my jaw, but it also had a way of interfering with movement in the upper body.
In the end, it's what works for you. I would start with the position that Mr. Kogut suggests, but would also experiment with different seat heights. I did a lot of that, and I never injured myself. Just be careful not to push yourself too hard in the wrong way. Push your mind, not your body, to find the music you want to make.

Correct piano wrist movement


Resources on Mathematics for the Educated non-Mathematician

Question: I was wondering what the best books are for giving an educated non-mathematician the gist of real mathematics. Not to say that I am by any means a real mathematician, but it is one of my goals to pursue graduate school and further studies in mathematics.
My father is educated in medicine and in physics, chemistry, and biology- primarily the latter two. He is the type of person with extremely meticulous study habits, and it seems as though he wants to understand my mathematical interests. My primary interests are topology/analysis, and I was wondering if someone could give me a good recommendation of literature I could give him so that he could understand the goals of modern mathematics.
I'm not looking for in-depth, or technical books on topology/analysis, I own those already- I just want a book that can put the field in perspective in a somewhat conversational, but not oversimplified manner$^\dagger$.
$\dagger$ Let me just emphasize that I am looking for books catered to people who are specialists in other fields, but didn't study mathematics rigorously outside of their own field.
Comment: Terence Tao's Analysis series is good for introductory reading.
Comment: For topology a book that I love is [_Topology without tears_](http://www.topologywithouttears.net/) of Morris. The Knuth's books generally are very fine too. I think a good book of topology, another of set theory, analysis and algebra are the core of maths.
Answer: I recommend The Princeton Companion to Mathematics and The Princeton Companion to Applied Mathematics.
Answer: You may also wish to look at Concepts of modern mathematics by Ian Stewart.
Answer: I would recommend Dr. Edward Frenkel's "Love and Math," as an introduction.
Comment: Yeah his book is almost as amazing as his teaching! I was very fortunate to have him as a professor.
Comment: Ha! I just bought this book earlier today, and would have posted it as an answer if you hadn't already done so.


How to configure EU cookie compliance module for only Google Analytics

Question: I have installed and configured the EU cookie compliance module, but it only displays the message when I log into admin section. I use Google Analytics and I must show the message for all the site.
I think that the issue is that Drupal doesn't set any cookie and that's why it doesn't display the message (the GA cookie is external to Drupal).
How can show the message when I use only the GA cookie?
Answer: In the permission page (admin/people/permissions), check "Display EU Cookie Compliance popup" for the anonymous user.


Information about requests made from client browser?

Question: Is there a way to detect which HTTP requests (from client Javascript) are sent with a successful status, when client visits my page? Or just check if specific part (lines of code) of third-party Javascript code is sending HTTP GET request with successful status?
It is possible with, for example, a Chrome extension, but can that be done in client side Javascript?
EDIT:
Please note, that I am new to web related stuff and have done a research on whether it is or in not possible, but that yielded no results. Therefore I am asking this here.
Answer: No, that can't be done with JavaScript.
JS doesn't have access to network traffic like that for a good reason:
Security
If that were possible, any site could get access to whatever you're sending to and receiving from your bank, for example.
Comment: Thanks! This helped a lot.
Comment: I'm glad it helped :-) Does it also answer your question?


Como saber quais as bibliotecas estão sendo usadas em um projeto python?

Question: Eu fiz uma instalação de uma aplicação feita em Python, ela funciona basicamente da seguinte forma, ela instala o Python, o programa e no final a instalação copia a pasta com as bibliotecas para a instalação do Python.
Tudo funciona perfeitamente, mas a instalação ficou muito grande por causa das bibliotecas, como tenho muitas bibliotecas que utilizo em outros projetos, e que não tem nada a ver com esta instalação, ficou muito grande, eu tentei escolher o que uso e o que não uso olhando os imports no projeto, mas vire e mexe durante os testes acontecem alguns erros por causa de uma biblioteca que esta faltando, e nem sempre o nome é sugestivo para procurar, no fim das contas tive que deixar todas as bibliotecas com medo de dar algum erro em produção.
Eu consigo de alguma forma saber quais bibliotecas estão sendo usadas em um determinado projeto?
Answer: De forma rápida e descuidada voce pode "corrigir", fazendo assim:
No ambiente de seu projeto faça:
$ pip freeze > requirements.txt

No ambiente de produção, faça:
$ pip install -r requirements.txt

Porque apesar de rápida e fácil, essa forma pode ser considerada "descuidada"? porque dessa maneira vc estara instalando em produção todos os pacotes instalados no ambiente de desenvolvimento, isso, na maioria das vezes, desnecessário.
Mas se vc quer fazer a coisa da forma correta, continue lendo.
Uma boa pratica é sempre iniciar cada projeto em um ambiente virtual único, para isso o ideal é usar um gerenciador de venvs, o que mais gosto é o anacoda/conda que, alem de ser um gerenciador de venv's é, também, um gerenciador de pacotes do python, uma espécie de "distribuição".
Se vc tivesse utilizado essa prática, então no início do desenvolvimento do projeto vc criaria uma env somente com a versão do python que vc utilizaria no projeto e, a medida que fosse precisando das libs iria alimentando um arquivos chamado requeriments.txt, então quando fosse para o ambiente de producção, bastaria fazer:
pip install -r requirements.txt

Pipreqs:
Se vc não fez nada disso e quer evitar a forma 'descuidada' de solucionar o problema, vamos tentar fazer uma espécie de "engenharia reversa" com pipreqs (embora ainda não seja a forma ideal, mas bem próxima disso). Com pipreqs vc constroi seu requirements.txt com base nos seus imports, mas de forma automática e não no olhometro, para isso bastaria fazer:
# Instalando o pipreqs
$ pip install pipreqs

# Construindo o requirements.txt
$ pipreqs /path/projeto
INFO: Successfully saved requirements file in /path/projeto/requirements.txt

Pireqs criára o requirements.txt no diretório do seu projeto, agora basta inclui-lo no seu instalador e executar o pip install -r reqirements na instalação.
Pq eu disse que não é o ideal dessa forma? pq no ambiente de desenvolvimento (mesmo considerando um virtual environment única) voce pode querer instalar alguns pacotes que não sejam necessários no ambiente de produção, então o ideal é sempre trabalhar como virtualenvs, o mais "enxuto possível" e ir adicionando manualmente as libs no requeriments.txt a medida que for desenvolvendo.
Pipreqs tem alguns parametros interessantes, veja:
$ pipreqs --help
pipreqs - Generate pip requirements.txt file based on imports

Usage:
    pipreqs [options] <path>

Options:
    --use-local           Use ONLY local package info instead of querying PyPI
    --pypi-server <url>   Use custom PyPi server
    --proxy <url>         Use Proxy, parameter will be passed to requests library. You can also just set the
                          environments parameter in your terminal:
                          $ export HTTP_PROXY="http://10.10.1.10:3128"
                          $ export HTTPS_PROXY="https://10.10.1.10:1080"
    --debug               Print debug information
    --ignore <dirs>...    Ignore extra directories, each separated by a comma
    --encoding <charset>  Use encoding parameter for file open
    --savepath <file>     Save the list of requirements in the given file
    --print               Output the list of requirements in the standard output
    --force               Overwrite existing requirements.txt

Obs.
Em ambos os casos (da forma correta ou da forma "descuidada") vc não vai mais precisar ficar "carregando" a pasta das bibliotecas na instalação.
Para saber mais sobre o anaconda, veja essa resposta aqui no STOpt.
Comment: Amigo deixa eu te perguntar, estou no windows, e estou tentando executar o pipreqs, tentei deste forma: python C:\Python27\Lib\site-packages\pipreqs\pipreqs.py e apresenta o seguinte erro: ImportError: cannot import name __version__
Comment: Vc não tem o pip instalado no windows? se não tiver, instale e utilize-o para instalar os pacotes. [Esse link](http://rafs.com.br/como-instalar-pip-no-windows/) pode te ajudar a instalar o pip no windows.
Comment: Eu já instalei o pipreqs utilizando o pip, mas ao tentar executar da este erro.
Comment: Cara... Faz um tempo que não tenho contato com o windows, mas teoricamente teria que ser igual ao linux, bastaria vc dar o comando `pipreqs c:\path\projeto`.  Veja se pipreqs é um binário (executável no windows),  com o comando whereis, se nao me engano no windows é `where`, tente assim `where pipreqs`, se for veja se o caminho dele está na variável path.
Comment: Em tempo: Considere utilizar o anaconda e acabe com seus problemas de pacotes e conflitos deles.
Answer: =help("modules")

Utilize a função nativa HELP.
No menu prompt do Python digite: help("modules") e o programa retornará a lista de todos os módulos instalados em ordem alfabética.
Observações:
1) Na primeira vez pode demorar um pouco;
2) A lista é muito completa e mostra módulos internos dos módulos principais e módulos pré-instalados.


How to access the Ansible getent module values & put into variable?

Question: I'm attempting to develop an Ansible playbook that uses the getent module to help manage various user accounts.  I would like to be able to access the various values like UID, GID, password, etc. (what I think is a Python dictionary -- but am not sure that is accurate).
How do I read/access if a password is lockecd (e.g. ! or !!)?
How do I read/access the UID or GID for say this account:
    ntp:x:38:38::/etc/ntp:/sbin/nologin
into a variable to be used for the next task?
Here is current playbook task so far.  Can this be done if a playbook?

- name: "getent variables"
  getent:
    database: passwd
    key: ntp #root  #uid
    split: ':'
    #fail_key:
    # register: getent_passwd
- debug:
    var: getent_passwd
Answer: Getent results will normally be added as facts to the hosts facts.
Keep in mind that the information about gid/uid/etc are in a separate database from information about passwords.
# ansible localhost -m getent -a 'database=passwd key=root'
localhost | SUCCESS => {
    "ansible_facts": {
        "getent_passwd": {
            "root": [
                "x",
                "0",
                "0",
                "root",
                "/root",
                "/bin/bash"
            ]
        }
    },
    "changed": false
}

# ansible localhost -m getent -a 'database=shadow key=root'
localhost | SUCCESS => {
    "ansible_facts": {
        "getent_shadow": {
            "root": [
                "*",
                "17939",
                "0",
                "99999",
                "7",
                "",
                "",
                ""
            ]
        }
    },
    "changed": false
}

How do I read/access the UID or GID for say this account: ntp:x:38:38::/etc/ntp:/sbin/nologin into a variable to be used for the next task?

It isn't that easy.
- name: "getent variables"
  getent:
    database: passwd
    key: ntp

- name: show the UID
  debug:
    var: getent_passwd['ntp'][1]

- name: show the GID
  debug:
    var: getent_passwd['ntp'][2]

- name: "getent variables"
  getent:
    database: passwd
    key: ntp

- name: show the password hash
  debug:
    var: getent_shadow['ntp'][0]

Answer: tl;dr - sample solutions to the problem with getent module (tricky) or user module (easier but more limited info)
You can get the most info by using the getent module, but it's tricky to pick out the items you want (use debug to show you the whole structure so you can work out how to specify the fields that you want).
To fetch some common fields with getent for example,
 - ansible.builtin.set_fact:
     username: ntp
 - ansible.builtin.getent:
     database: passwd
     key: "{{ username }}"
 - ansible.builtin.set_fact:
     uid: "{{ getent_passwd[username][1] }}"
     gid: "{{ getent_passwd[username][2] }}"
     home: "{{ getent_passwd[username][4] }}"
     shell: "{{ getent_passwd[username][5] }}"
 - ansible.builtin.debug:
     msg: "UID: {{ uid }}, GID: {{ gid }}, home: {{ home }}, shell: {{ shell }}"

To reiterate Zoredache's comment, the getent module will create host facts of the form getent_databasename where databasename will correspond with the database: specified to getent, thus getent_passwd above.
If it's only those particular fields you want, you could instead use the easier to understand user module with check_mode (without check_mode: true the user concerned will be created or modified so take care!). The corresponding lines would be,
- ansible.builtin.user:
    name: ntp
  check_mode: true
  register: res
- ansible.builtin.set_fact:
    uid: "{{ res.uid }}"
    gid: "{{ res.group }}"
    home: "{{ res.home }}"
    shell: "{{ res.shell }}"
- ansible.builtin.debug:
    msg: "UID: {{ uid }}, GID: {{ gid }}, home: {{ home }}, shell: {{ shell }}"


How to wait for user_data script to run when starting EC2 instances with ansible?

Question: I am using Ansible to start and configure EC2 instances that are currently based in an AMI (ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64-server-20161020 (ami-40d28157)) that doesn't have Python installed from start.
Since most ansible modules need python on the remote machine to work, rather than choosing to use a different AMI I tried to install python on the starting instances using an user_data script.
It kinda worked (Python is installed correctly), but the ansible ec2 task returns before the user_data script finishes running, and so the tasks on the following play (those that would actually configure the instance) fail with the error '/bin/sh: 1: /usr/bin/python: not found\r\n'
Since without python I can't even run most tasks on the remote host I can't simply check if /usr/bin/python or a marker file is there, or check the syslog output, for example.
I thought about adding a nc -l $SOME_PORT at the end of the user_data script and checking for it with the wait_for module, but it sounds like too much of a hack for me.
Is there a way to use the ec2 module to start an instance so that it waits until the user_data script finishes running?
For reference:
A playbook similar to what I'm using:
- name: Create the EC2 instance
  hosts: localhost
  gather_facts: false
  vars:
    name: myinstance
    ami: ami-40d28157
    #Other vars ommited for brevity
  tasks:
    - name: Launch Instance
      ec2:
        key_name: "{{ keypair }}"
        group: "{{ security_group }}"
        instance_type: "{{ instance_type }}"
        image: "{{ ami }}"
        user_data: "{{ lookup('file', 'user_data.sh') }}"
        wait: true
        region: "{{ region }}"
        vpc_subnet_id: "{{ subnet }}"
        assign_public_ip: no
        zone: "{{ zone }}"
        instance_tags: "{{ tag_map }}"
        exact_count: 1
        count_tag:
          Name: "{{ name }}"
      register: ec2

    - name: Add new Instance to host group
      add_host: name={{ item.private_ip }} groups={{ name }}
      with_items: "{{ ec2.instances }}"

    - name: Wait for SSH to come up
      wait_for: host={{ item.private_ip }} port=22 delay=60 timeout=320 state=started
      with_items: "{{ ec2.instances }}"

- name: Configure instance(s)
  hosts: myinstance
  tasks:
    - name: Example task
      command: touch a_file

The user_data.sh script:
#!/bin/bash
set -e -x
export DEBIAN_FRONTEND=noninteractive
sudo locale-gen pt_BR.UTF-8
sudo apt-get update && apt-get upgrade -y
sudo apt-get install -y python-minimal

Comment: Why not just create your own AMI with python already installed?
Comment: Since you already wait for port 22, I would block it in the `user_data.sh` script at the beginning and unblock at the end. There is no such option for `ec2` module.
Answer: It turns out you can use cloud-init command for that, namely:
cloud-init status --wait

So you should add the following snipped to your playbook:
- name: Wait for cloud-init / user-data to finish
  command: cloud-init status --wait
  changed_when: false

It looks a bit cleaner compared to the first answer.
Answer: Here is the answer to your question "How to wait for user data script to run when starting EC2 instances with ansible?":
- raw: test -f /var/lib/cloud/instance/boot-finished
  retries: 20
  register: cmd_res
  changed_when: false
  until: cmd_res | success

This will connect via ssh and succeed when boot-finished is present, which is created after cloud-init module on the host completes all modules (including user_data script).
But I'd suggest to create AMI with Python preinstalled, or use raw or script Ansible module to check/install Python (these modules don't require Python).
Comment: Just to note that with ansible >= 2.8 this solution gives a deprecation warning. [DEPRECATION WARNING]: Using tests as filters is deprecated. Instead of using `result|success` use `result is success`.


How to solve $\cos(4x)=\cos\left(\frac\pi2+3x\right)$ for $0\le x\le \pi? $

Question: Question in the title please. I know that the two cosines are equal only when their arguments (i.e what's inside the brackets) are equal, therefore it is easy to arrive at the first trivial solution being $4x=\dfrac\pi2+3x $, which gives $x=\dfrac\pi2.$
Previously when solving simple trig equations of the form, for instance, $\cos x=\dfrac12$, my strategy is as follows:
1) because what comes after the '=' is a positive constant, we are only interested in x being in the $1$st and $4$th quadrants, as cosine is only positive there. Therefore discard x in the $2$nd and $3$rd quadrants.
2) Write down general solution in the form $x=2n\pi\pm a,$ where $n=0,1,2,\dots$
As what comes after '=' in my question is not a constant, I cannot seem to adapt the above strategy.
Any help would be greatly appreciated.
Comment: What does $\cos x =\cos y$ give you?
Answer: Well, you can actually use the following "immediate formulas"...
If $\cos x = \cos y$, then $x = \pm y + k.2\pi$
If $\sin x = \sin y$, then $x = y + k.2\pi$ or $x = (\pi - y) + k.2\pi$
If $\tan x = \tan y$, then $x = y + k.\pi$
where $k$ refers to an integer.
So for your equation, $\cos 4x = \cos (\frac{\pi}{2} + 3x)$ yields $4x = \pm (\frac{\pi}{2} + 3x) + k.2\pi$, so we get $x = \frac{\pi}{2} + k.2\pi$ or $x=-\frac{\pi}{14} + k.\frac{2\pi}{7}$. Since $0\le x \le\pi$, then the solutions for $x$ are $\frac{3\pi}{14}, \frac{\pi}{2}$, and $\frac{11\pi}{14}$. You can check that these solutions satisfy the given equation.
Answer: Guide:
If $2\pi\mathbb Z:=\{2\pi k\mid k\in\mathbb Z\}$ then:
$$\cos\alpha=\cos\beta\iff \alpha-\beta\in2\pi\mathbb Z\text{ or }\alpha+\beta\in2\pi\mathbb Z$$Work this out for $\alpha=4x$ and $\beta=\frac12\pi+3x$ and accept the solutions that satisfy $0\leq x\leq\pi$.
Answer: $$\cos x =\cos \alpha \implies x=2n\pi\pm \alpha, n=0,\pm1,\pm2,\pm3,...$$
So here $$\cos 2x = \cos (\pi/2+3x),~ x \le \pi.$$
$$\implies 2x=2n\pi \pm (\pi/2+3x) \implies 7x=2n\pi+ pi/2, x=-2m\pi+\pi/2$$ So $$x=\frac{2n\pi+\pi/2}{7}, n=1,2,3 \implies x=\frac{3\pi}{14}, \frac{\pi}{2}, \frac{11\pi}{14}.$$


Probability of not drawing an element of a certain element in an "binomial drawing" experiment

Question: I randomly draw 3 elements from a population of 100. What is the probability of a certain element in my whole population NOT being including in my drawing?
I know I can draw $C^3_{100} = 161.700$ different ways but the probability mentioned above I cannot compute?
Comment: This looks a lot like a "homework" question but I am actually exploring a Scenario optimization model in which I need to compute these kinds of probabilites
Comment: If you cannot draw the 'certain element', then the favourable draws are $\binom{99}{3}$.
Comment: This follows a simple case of a [hypergeometric distribution](https://en.wikipedia.org/wiki/Hypergeometric_distribution) where $K=1$ and $k=0$.
Answer: P(a certain element is not in draw/sample)=$\frac{{99\choose3}}{{100\choose3}}=\frac{99\times98\times97}{100\times99\times98}=97/100.$


Two equivalent definitions of convergent sequences?

Question: I know that:
Definiton 1. The sequence $(x_n)$ in the metric space $(X,d)$ is said to converge to the point $x_0\in X$ if $$\forall\epsilon>0, \exists n_0\in\mathbb{N} \text{ such that } \forall n\geq n_0, d(x_n,x_0)<\epsilon.$$
In other words, the sequence $(x_n)$ in the metric space $(X,d)$  converges to the point $x_0\in X$ if $d(x_n,x_0)\rightarrow 0$ with $n\rightarrow\infty.$
Definiton 2. The sequence $(x_n)$ in the metric space $(X,d)$ converges to the point $x_0\in X$ if in every neighborhood $U_{x_0}$ of $x_0$ there exists a natural number $n_0$ such that it is satisfied $\forall n\geq n_0\Rightarrow x_n\in U_{x_0}.$
The point $x_0$ is said to be the limit of the sequence $(x_n)$. Write $x_n\rightarrow x_0, (n\rightarrow\infty)$ or $\lim_{n\to\infty}x_n=x_0.$
Can these two definitions be proved to be equivalent?
Comment: What does "was the replies a natural number n0 such that to be completed" mean?
Comment: now corrected, I think now you clearer, thank you
Comment: Not really. First, I think your "suburb" is better translated as "neighborhood", and second: instead of all that you wrote, is enough to write "...every neighborhood $\;U_{x_0}\;$ of $\;x_0\;$ there exists $\;n_U\in\Bbb N\;$ s.t. $\;n>n_U\implies x_n\in U_{x_0}\;$ "
Comment: oh, ok sir, thanks
Answer: Where are you stuck? As some starting food for thought, notice that
1) For every open neighborhood $U_{x_0}$ of $x_0$, there exists an $\epsilon>0$ with $(x_0-\epsilon,x_0+\epsilon)\subset U_{x_0}$.
2) For every $\epsilon>0$, the set $(x_0-\epsilon,x_0+\epsilon)$ is an open neighborhood of $x_0$.
These two facts should suggest that both definitions have the same content.
Answer: Let $x_{n}$ converge to $x_{0}$ according to definition 1) and let
$N$ be a neighbourhood of $x_{0}$.
Since we are working in a metric
space this means exactly that some $\epsilon>0$ exists such that
$d\left(x_{0},y\right)<\epsilon\Rightarrow y\in N$.
Then $n_{0}\in\mathbb{N}$
exists such that $n\geq n_{0}$ implies that $d(x_{0},x_{n})<\epsilon$
and consequently $x_{n}\in N$.
Conversely let $x_{n}$ converge to
$x_{0}$ according to definition 2) .
Note that for every $\epsilon>0$
the set $N=\left\{ y\in X\mid d\left(x_{0},y\right)<\epsilon\right\} $
is a neighbourhood of $x_{0}$, hence some $n_{0}\in\mathbb{N}$ exists
such that $n\geq n_{0}$ implies that $x_{n}\in N$ or equivalently
$d(x_{0},x_{n})<\epsilon$.


How can I estimate the delay between two non-periodic time series?

Question: I'm wondering what the best way to estimate the delay and confidence between two non-periodic time series would be.
Specifically, I thought it would be interesting to look at the different economic indicators, say the price of oil and a stock price, and determine whether one predicts the other, with how much confidence and by how far in advance.
Most of the answers I've been able to find so far have described periodic time series and phase difference in radians. It is not clear to me how this type of analysis would convert to non-periodic data and difference in time instead of angle. It may be possible to glean some information from treating the data as periodic, so that's not completely out.
Any reading recommendations?
Thanks!
Answer: The most straightforward approach is probably cross-correlation. You may be interested in the answers to this post and the posts linked in the right-hand-side of that post (linked also in my comment to one of the answers).

Another approach is by means of a dynamic regression. You could fit an autoregressive distributed lag model. For a description of this model and some references see for example my answer to this post.
This will allow you to test for the significance of one variable to explain the other and also for the significance of lags of the explanatory variable. The order of the highest significant lag will be a measure of the delay between both variables.
For the kind of data that you mention (economic indicators), you will probably need to fit the model for the differences or growth rates of the variables (not for the original series) in order for them to be stationary and avoid possible spurious results due to stochastic trends in the variables.

A more involved approach would be as follows:

Extract a cyclical signal from each series, for example by means of the Hodrick and Prescott filter or model based approaches (ARIMA, structural time series models).
Identify the peaks and troughs in the estimated cyclical signals. These points can generally be easily identified from the graph and can be detected manually, but if you have many time series it is relatively easy to devise an algorithm to do that.
Inspect the dates of the peaks and troughs in each series and compare them.
Descriptive statistics of the difference between each peak or trough as well as an histogram of this differences can be helpful to determine whether a given series systematically reaches a peak some periods in advance or with delay compared to other series.

A nice way to look at the estimated cycles is the animated plot used by Statistics Netherlands to track the business cycle. This plot does not reveal exactly by how many periods an economic indicator is ahead or behind other indicators, but it's a nice way to summarize the results.
Comment: Thanks for your very thorough response! I will dig into each idea mentioned.
Answer: I suggest that you could simply use a prediction task not importantly how many lags one time-series is ahead of the other one; specially this makes sense while not necessarily always the difference of lags would continue the same during the history of two time-series; In the other hand, a prediction method can model it better. So, you have two features and a response variable as following:
x1 = history of price of oil till time t
x2 = history of stock price  till time t-1
y = price of stock price till time t(the one you think comes 'next after' the other)
Now using whatever prediction method (linear regression, SVR, SARIMA, ANN, ...) you train your model like this:
model.train =  (y(1:t) ~ x1(1:t) + x2(0:t-1) )
and you predict your response variable at each moment as:
model.predict ( x1(t+1) + x2(t) ) which returns you the y(t+1) which is the price of stock price in the next time-slot.
Good luck!


Obter o nome da Variável pela qual a função ou classe foi chamada

Question: Estava olhando como são criados os bancos de dados no SQLAlchemy e fiquei em duvida na parte aonde crio variáveis de classes e são convertidos para uma coluna no banco de dado com o nome da variável usada.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite+pysqlite:///base.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

class User(db.Model):
    __tablename__ = "users"
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)

    def __repr__(self):
        return f"<{self.username}>"

Como posso criar uma função que faz essa mesma coisa? que me retorne o nome da "Variável Original".
Ou que transforme o nome da "Variável Original" em uma Kwargs como acontecer na hora de salva algo no banco de dados.
db.session.add(User(username="Something"))
db.session.commit()

Answer: Não é possível para variáveis comuns quando chamam uma função (ok, até "é possível", mas é muito mais complicado, e não é a intenção de que algo assim seja feito).
Mas para nomes de atributos de classe - como é o caso aí, isso é possível sim - a questão é que ou a classe tem que ter uma metaclasse especial, ou o conteúdo do atributo de classe na decoração tem que ser um objeto que atenda ao protocolo de descritors (descriptor protocol) e tenha um método __set_name__.
Então, para ilustrar bem - isto é possível:
class MinhaClasse:
    meu_atributo = ClasseEspecial()

m = MinhaClasse()
print(m.nome)
out-> 'meu_atributo'

E isso não é possível (naquelas - "dá", mas não faça:):

def minha_funcao():
    minha_variavel = funcao_especial()
    print (minha_variavel.nome)

minha_funcao()
out-> 'minha_variavel'  # (Não tem como acontecer, a não ser com um hack muito grande)

Então, focando no que funciona e as pessoas são encorajadas a usar: se o seu atributo de classe for um objeto com um método __get__, ele é um descritor (um descriptor) - e o Python usa vários mecanismos legais com ele, inclusive podendo determinar o nome automaticamente:
No momento em que a classe é criada, o Python verifica todos os membros da classe que são descritores, e, se eles tiverem o método __set_name__, ele é chamado com dois parâmetros: a classe recém criada, e o próprio nome do membro, como uma string.
Ou seja, para o primeiro exemplo acima funcionar, pode-se usar algo assim:
class ClasseEspecial:
    def __get__(self, instance, owner):
        if instance is None: return self
        return instance.__dict__[self.name]
    def __set__(self, instance, value):
        instance.__dict__[self.name] = value
    def __set_name__(self, owner, name):
        self.name = name

class MinhaClasse:
    meu_atributo = ClasseEspecial()

E no modo interativo:

In [255]: MinhaClasse.meu_atributo.name
Out[255]: 'meu_atributo'

Por que isso funciona assim? Por que o corpo das classes é executado no momento em que um módulo é importado (em geral) - quando o bloco definido pelo comando class chega ao fim, o Python faz uma série de chamadas internas, que recebem como dados todas as variáveis definidas no corpo da classe (os atributos),  aí o mecanismo que descrevi acima entra em ação e o método __set_name__ é chamado.
Já em uma função, o corpo delas só é executado quando elas são chamadas - as variáveis "não existem" até a função estar em execução,  e apesar dos mecanismos de introspecção do Python permitirem que o programa possa "ver" esses nomes de variável diretamente, isso não é recoemndado: o ideal é que nomes de variáveis sejam parte da estrutura do programa - se você precisa manipualr um nome de variável como dado (por exemplo, uma string), o melhor é usar um dicionário.  E também isso seria muito pouco útil - uma variável em uma função só é visível para o código dentro daquela própria função - ao contrário de um atributo de classe que pode ser consultado de qualquer lugar diretamente.
Só para deixar a resposta completa, vou descrever como uma função que é chamada poderia saber em qual variável vai ser armazenada - mas não vou dar um exemplo em código:
Existe um tipo de objeto que se chama "Frame" que mantém o estado de uma função em execução: ele tem como atributos o código que está sendo executado e as variáveis locais, e o frme da função "pai" - a função que chamou a função atual.
COm isso, uma função ao ser chamada pode:

obter o próprio frame de execução
do próprio frame, obter o frame da função onde ela foi chamada
nesse frame, obter o número da linha e ponto onde está a chamada a função (essa informação também está no frame)
obter o objeto de código (__code__): uma sequência de bytes representando o bytecode aquela função
olhar dentro do bytecode qual foi a instrução onde a função foi chamada
achar a partir dali as instruções que colocam o valor de retorno em uma variável local
obter, no objeto de código, o nome da variável a partir da sua posição

E, ao contrário do que acontece com atributos de classe, isso tudo vai funcionar por que a implementação de referência cPython faz dessa forma, e permite esses acessos - mas outras implementações de Python, como Pypy, Brython, etc.... não precisam (e não implementam) isso da mesma forma, então não dá para isso funcionar em qualquer variante da linguagem.


pager_query() - How to fetch only 100 records with a pagination 10 items per page?

Question: $result = pager_query($query, 10, 0, NULL, $args);

Currently with above code , I am getting all results with 10 items per page. But I need to display only first 100 records , with 10 items per page. Is this possible with pager_query()  or any alternate solution using plain PHP and MySQL?
Answer: You can pass a $count_query argument to pager_query(), which you can use to control the overall count:
e.g.
$sql = 'SELECT * FROM my_table';
$count_sql = 'SELECT COUNT(id) FROM my_table LIMIT 100';

$result = pager_query($sql, 10, 0, $count_sql);

Comment: Tried that , no effect, is there anything to be added additionally?
Comment: I've never actually tried that, it just made sense logically. I don't think there's any other approach to getting the standard `pager_query()` to do what you want, if the above doesn't work you'll have to go for a custom implementation
Comment: Try changing to `LIMIT 0, 100`.
Answer: Replace '$args' with '100' in pager_query() and check.
Answer: If you need to supply any argument to your query just add them after all the **pager_query arguments like so:**
Example Query:
$query = "SELECT heading, summary, publish_date FROM {news} WHERE category_id = %d ORDER BY publish_date DESC";

$result = pager_query($query, 100, 0, NULL, $cat_id);

So, for the pager_query example above let me explain the arguments:

1st arg ($query) = The query to be executed.
2nd arg (10) = $limit The number of query results to display per page.
3rd arg (0) = $element The integer number of the pager we are working with.
4th arg (NULL) = $count_query Just put NULL which is the default for this variable.
5th arg ($cat_id) = The argument that needs to be passed to the query itself.
Answer: $query = new EntityFieldQuery();
$results = $query->entityCondition('entity_type', 'node')
          ->entityCondition('bundle', 'your_content_type')
          ->fieldCondition('field_village_schedule_state', 'value', 'your_value','=')
         $_GET['village'],'=')
           ->range(0,100)
           ->execute();

  if (isset($results['node'])) {
       $nodes = node_load_multiple(array_keys($results['node']));
       foreach ($nodes as $row)
        {
          // Your Code Here for dispaly.
        }
     }


Focus keybinging on the "Type to search in keybindings" on the keybings shortcuts file in VS Code?

Question: Is there a keybing to focus on the "Type to search in keybindings" on the keybings shortcuts file in VS Code? If not, is there a way to set it? I just don't want to use the mouse when I want to search for another keybinding...
Answer: Control-f (or Command-F on Mac) brings me there


Find the Tangent line that intersects the graph at another point

Question: I am having trouble figuring out methodology to find another point of intersection for my tangent line $y=-38x+6$ and curve $2x^3+10x^2-28x$.
The question asks to determine tangent line at $x=-3$ for above function, and I know that they already intersect at $(-3, 120)$ having solved for $f(a)$. and using the secant method to find the slope of the above tangent line at $x=-3$.
Find another point of intersection:
$-38x+6 = 2x^3+10x^2-28x$
$0=2x^3+10x^2+10x-6$ [solve for roots]
I know that $(x+3)$ is a root by method of substitution for figuring $zero$ of the $cubic$, and when I perform the long div I end up with a remainder. It makes me think my methodology is incorrect. How should I solve this one? Thanks
Comment: Try the long division again -- you made an error in it at some point.  In fact, if you instead divide by $(x+3)^2$ it'll give the answer quicker.
Comment: @BrianMoehring thanks - I indeed made an error
Answer: Note that $$2x^3+10x^2+10x-6=2 (x+3) \left(x^2+2 x-1\right)$$
Comment: Thanks! I factored out the $2$ in the quadratic and employed quadratic formula to success.


Why doesnt keyframes animation work in safari

Question: So I´m working on a gallery for my page, and wanted some animation. What I want is for the images to go from border-radius 50% to 0%. This works just fine in chrome, but I cant get It to work on safari. Here is the CSS:
<code>.bild {
  text-align: center;
  overflow: hidden;
  position: relative;
  height: 95%;
  width: 95%;
  -webkit-animation-name: out;
  -webkit-animation-duration: .9s;
  border-radius: 50%;
}

.bild:hover{
  -webkit-animation-name: in;
  -webkit-animation-duration: .9s;
  border-radius: 0;
}

@-webkit-keyframes in {
  0% {border-radius: 50%;}
  100% {border-radius: 0%;}
}

@-webkit-keyframes out {
  0% {border-radius: 0%;}
  100% {border-radius: 50%;}
}
</code>
Comment: Welcome to Stack Overflow! Questions seeking code help must include the **shortest code** necessary to reproduce it **in the question itself** preferably in a [**Stack Snippet**](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/).  See [**How to create a Minimal, Reproducible Example**](http://stackoverflow.com/help/reprex)
Answer: You should try with CSS mixins. Different browsers require different prefixes for some styles:
<code>-webkit-animation-duration: $duration;
-moz-animation-duration:    $duration;
-ms-animation-duration:     $duration;
-o-animation-duration:      $duration;
animation-duration:         $duration;

-webkit-animation-name: $animation-name;
-moz-animation-name:    $animation-name;
-ms-animation-name:     $animation-name;
-o-animation-name:      $animation-name;
animation-name:         $animation-name;

@-webkit-keyframes in {
    0% {border-radius: 50%;}
  100% {border-radius: 0%;}
}

@-moz-keyframes in {
    0% {border-radius: 50%;}
  100% {border-radius: 0%;}
}

@-ms-keyframes in {
    0% {border-radius: 50%;}
  100% {border-radius: 0%;}
}

@-o-keyframes in {
    0% {border-radius: 50%;}
  100% {border-radius: 0%;}
}

@keyframes in {
    0% {border-radius: 50%;}
  100% {border-radius: 0%;}
}
</code>
Note that you need also keyframes for 'out' animation-name in your case.
If this doesn't help, please provide HTML code or create a Codepen so we can see the whole code isolated.
Comment: prefixes are not more needed for animation since too long


I cannot start any program from PythonStdioGames and get an error, how can I prevent this?

Question: I am relatively new to Python and programming in general and currently learning Python with the book "Automate the boring stuff with Python" by Al Sweigart. As recommended in the book, I wanted to do some programming exercises myself by looking into the module gamesbyexample (https://github.com/asweigart/pythonstdiogames/).
However, whenever I start one of the games I get the following error message in the Terminal:
<code>AdminisatorsMBP:~ simon$ /Library/Frameworks/Python.framework/Versions/3.8/bin/python3 /Users/simon/Library/Python/3.8/lib/python/site-packages/gamesbyexample/__crashdetector__.py 0.1.5 /Users/simon/Library/Python/3.8/lib/python/site-packages/gamesbyexample/alphabetizequiz.py
  File "/Users/simon/Library/Python/3.8/lib/python/site-packages/gamesbyexample/__crashdetector__.py", line 16
    except KeyboardInterrupt, EOFError:
                            ^
SyntaxError: invalid syntax
</code>
I tried using multiple versions of python, 3.7.7 and 3.8.2, but with both versions, the same message comes up.
How could I get this running properly?
Comment: Did you download the scripts directly from Github, or did they come from elsewhere? In the file `_crashreporter.py` there is a recent change (April 2 2020) that reads "Missed this syntax error in the crash detector somehow." Perhaps you have an older version?
Answer: This is a syntax error, which means that you're probably missing something in the code that the compiler was expecting to be there.
If you could please also post the code, we could see what the problem is.


Bulk insertion in django rest framework

Question: When I am trying to create multiple instances in a single request it shows error if one instance is not correct in the batch. But how can I write my create method to insert correct instances in the batch. That means only correct instances will insert in the db and also show the errors message for the wrong instances.
[
    {
        "name": "oil",
        "unit_price": 200
    },
    {
        "name": "meat",
        "unit_type": "raw",
        "unit_price": 1000
    }
        "name": "salt",
        "unit_type": "raw",
        "unit_price": -100
    }

]

I want to insert first two instances will be insert in the db and for last one it will throws an error like this.
    "errors":
 [

        {
            "unit_price": [
                "Enter positive number."
            ]
        }
 ]

Here is my serializer
class ProductSerializer(serializers.ModelSerializer):

    def validate_unit_price(self, value):
         if (value) > 0:
             return value
         raise serializers.ValidationError("Enter positive number.")

    class Meta:
        model  = Product
        fields = [ 'name', 'unit_type', 'unit_price']

Also my views function is
@api_view(['POST'])
def store(request):

    serializer          =   ProductSerializer(data = request.data,many=True)

    if serializer.is_valid():
        serializer.save()
    return Response({'response_code': '500', 'response': status.HTTP_500_INTERNAL_SERVER_ERROR, 'message': 'Something went wrong', 'data': request.data, 'errors': serializer.errors})

Comment: Are you aware of library [djangorestframework-bulk](https://pypi.org/project/djangorestframework-bulk/)?
Comment: @RossRogers Last release April 2015?
Comment: I'm still using it and it works great.  Old code doesn't mean bad.
Answer: Since you're using one ProductSerializer instance, you won't be able to save if is_valid returns False. If you want to create all valid datasets and return the ones that errored, you might want to consider creating a serializer instance per entry, and keeping track of the data returned. You can build out a list of response values for the user that way, so partial failure is allowed.
My suggestion will not make this a "bulk" operation, but it technically isn't with many=True. many=True just wraps your serializer with a ListSerializer, which just calls create using the wrapped serializer per attribute. So you're performing a save() per instance of data as is.
Comment: How can i use that in my code? I can't  understand the implementation.
Comment: Many init gets called when `many=True`: https://github.com/encode/django-rest-framework/blob/d985c7cbb999b2bc18a109249c583e91f4c27aec/rest_framework/serializers.py#L124-L154

This calls the list serializer class (defaults to `ListSerializer`) with the current serializer as the child. This `ListSerializer` on `save()` will call `create()`, which calls `create()` on the child per arg instance: https://github.com/encode/django-rest-framework/blob/d985c7cbb999b2bc18a109249c583e91f4c27aec/rest_framework/serializers.py#L678-L713
Comment: As for not allowing save if `is_valid()` is false, that's true on both single serializer instances and list serializers: https://github.com/encode/django-rest-framework/blob/d985c7cbb999b2bc18a109249c583e91f4c27aec/rest_framework/serializers.py#L168-L175

Bulk insertion in django rest framework


What are the most important rugby union club leagues?

Question: What are the most important rugby union club leagues in the world? By "most important" I mean the leagues where the players are professional and where the teams are able to win international cups and/or tournaments.
Answer: Given the relatively limited geographical distribution of rugby union, it's not entirely surprising that the top leagues are in the top Test playing nations:

Super Rugby in Australia, New Zealand and South Africa; in 2016, expanded to include Argentina and Japan.
Top 14 in France.
Premiership Rugby in England.
Pro14 in Ireland, Italy, Scotland, and Wales; in 2017, expanded to include two South African clubs removed from Super Rugby.

Other than those leagues, the other major club competition is the European Rugby Champions Cup, which matches the top teams from England, France, Ireland, Italy, Scotland and Wales (the Six Nations countries) from the previous year.


Express Validatior - How Do I Break The Validation Chain?

Question: I have a date field that I want to ensure is in a valid format and if so is the user over 18. The format is YYYY-MM-DD.
Here is one of my validators - the one that is failing:
body('birthday', 'Date format should be: YYYY-MM-DD')
  .isRFC3339()
  .custom(date => {
    const over18 = moment().diff(date, 'years') >= 18;
    if(!over18) {
      return Promise.reject('You must be 18 or over!');
    }
  }),

Currently what happens is if the date is not a RFC3339 date the validation chain continues. This is problematic because moment produces an error if I pass an ill formatted date.
How do I break the chain after the call to .isRFC3339() so that if the date is invalid the custom validator will not run? I couldn't find anything in the docs
Comment: I don't know enough about express and express-validator, but if you want to prevent momentjs' _Deprecation Warning_, you can use [`moment(String, String)`](http://momentjs.com/docs/#/parsing/string-format/) as showed [here](https://stackoverflow.com/q/43101278/4131048) (in your case something like: `moment().diff(moment(date, moment.ISO_8601), 'years')`). You can also use momentjs [strict parsing mode](http://momentjs.com/guides/#/parsing/strict-mode/) and check valid dates using [`isValid()`](http://momentjs.com/docs/#/parsing/is-valid/).
Comment: But the problem is if a user enters `thisisnotadate` instead of a date momentjs wouldn't be able to parse that and would fail anyway.
Comment: A better idea would probably be to check if the data is valid within the custom validator and return a promise rejection if invalid.
Comment: I think I missed what is the desired output for `thisisnotadate`, I was thinking at something like: `const mDate = moment(date, moment.ISO_8601, true); const over18 = moment().diff(mDate, 'years') >= 18; if(!mDate.isValid() || !over18) return Promise.reject;` (using only custom validator without `isRFC3339()`), but I'm not sure that is what you are looking for.
Comment: Yup that's perfect.
Answer: You can use momentjs strict mode together with String + Format parsing using moment.ISO_8601 (or moment.HTML5_FMT.DATE) special formats.
Your code could be like the following:
body('birthday', 'Date format should be: YYYY-MM-DD')
  // .isRFC3339() // no more needed
  .custom(date => {
    const mDate = moment(date, moment.ISO_8601, true);
    const over18 = moment().diff(mDate, 'years') >= 18;
    if(!mDate.isValid()) {
      return Promise.reject('Date is not YYYY-MM-DD');
    if(!over18) {
      return Promise.reject('You must be 18 or over!');
    }
  }),

Comment: For some reason I had to add `return true` at the end in order for it to validate. Otherwise it was returning the `Date format should be: ...` error. No idea why as the docs don't mention it.
Comment: Maintainer here. [It _is_ in the docs](https://express-validator.github.io/docs/validation-chain-api.html#customvalidator), but I see that it  could be more prominent. PRs welcome!
Comment: I don't know enough about express-validator, I'm glad that you managed to make it work adding the `return true`.


positive/negative fields of function that includes integrals

Question: Edit: please follow the comments on the suggested answer, I still do need help.
Given (), a continuous and positive function for every x.
We define a new function () in the following way:

I have found the Derivative for g(x) and want to know when it's positive/negative/equal to zero
Here's my findings till now I found g'x: (sorry for adding a picture, I don't know how to write them here)

also I found that when x=0 g'(x) is equal to 1.
But how can I continue from here, I am a little bit confused with x and t since they have the same job...
proof that g'(0)=1:
Answer: $$ \forall x\neq0,g'(x)=f(x)\left(\int_0^x f(t)dt\right)^{-2}\left(x\int_0^x f(t)dt-\int_0^x tf(t)dt\right) $$
Since $f\geqslant 0$, $\forall t\in[0,x],tf(t)\leqslant xf(t)$ so that $g'(x)\geqslant 0$ for $x>0$. If $x<0$, we still have $tf(t)\leqslant xf(t)$ for $t\in[0,x]$ but $g'(x)\leqslant 0$ because $x<0$.
Comment: Please Note; f>0 (it can't be equal to 0)
Comment: $f>0$ does not mean that $f\geqslant 0$ and $f\neq 0$, it means that $\forall x, f(x)>0$, which is not the same thing.
Comment: according to your answer x=0 is where g'(x)=0 but that's not right
Comment: $x=t$ ? But $t$ is not defined, it is a free variable, it makes no sense... I proved that $g'(x)\geqslant 0$ for $x>0$ and $g'(x)\leqslant 0$ for $x<0$. And $g'(x)=0\iff f(x)=0$ or $x\int_0^x f(t)dt=\int_0^x tf(t)dt$. Moreover, if $x\int_0^x f(t)dt=\int_0^x tf(t)dt$, $\int_0^x(xf(t)-tf(t))dt=0$. If there exists $x\neq 0$ such that $\int_0^x(xf(t)-tf(t))dt=0$, since $t\mapsto xf(t)-tf(t)$ is positive and continuous, then $xf(t)-tf(t)=0$ for all $t\in[0,x]$. If we suppose that $f(t)>0$ for all $t\in\mathbb{R}$, then $t=x$ for all $t\in[0,x]$ which is not. Thus $g'(x)=0\iff x=0$ because $f(x)>0$.
Comment: ok you said g'(x) = 0 if x=0 but since we know that x is different than 0 (in the first case of g'(x)) this says that g'(x) is never equal to 0! but we know that g(x) is going up when x>=0 and going down when x<=0 that says (given f is continues) x=0 should be the point where g'(x)=0. it's a contradiction
Comment: How did you find $g'(0)=1$ ?
Comment: see the last image in my edited post


Fair selection of most popular items among separate voting sets

Question: This is a practical problem that arose in real life, which I believe creates interesting mathematical questions.
There is a festival of small plays lasting 8 weeks. Each week 10 short plays are staged (as one show) and the audience votes for their favorite play among those 10. The next week we have a set of 10 new plays, the audience (different to last's week's audience) votes again and so on. Thus, from each week we have a most popular play. So 8 most popular plays. We want to select the 2 "most popular" out of these 8 plays to advance to the Final. The quotes around "most popular" are there to show that it is inherently unfair to compare popular plays from different weeks, since each week has a different set of plays. But let's say we cannot do anything about this and still we need to find a "fair" way to announce the 2 most popular out of the popular winners from each week. One obvious thing we do is to use percentages of votes instead of absolute vote numbers, since the audience numbers (hence votes) vary from week to week. The two plays with the highest percentages among the 8 winners are named "most popular" and advance to the Final.
There is a complication though that makes the whole problem mathematically interesting. Not all weeks have exactly 10 plays. Some might have 8 or 9, some might have 11. It is unfair to compare percentages of popular votes from sets that have different cardinality. If you do not see the unfairness immediately, consider an extreme case: week A has just two plays and week B has 10 plays. The winner of week A gets 60%, the winner of week B 20%. Is really A's winner that much more popular? Of course not. We need a way to adjust the percentages to a normative week of 10 plays.
The organisers of the festival have recognised this and apply the following formula, where $p$ is the percentage of received votes of the most popular play of one week, $\hat{p}$ the adjusted percentage, and $n$ the actual number of plays in that week.
$$\hat{p} = p \cdot \frac{n}{10}$$
This formula might seem intuitive at some level, but on closer inspection one can find that it is really arbitrary. Let's take n to be 9, and assume one play got 20%. The adjusted percentage is 18%. This can be interpreted in 2 equivalent ways: either

The total number of votes remains the same and 1/10 of each play's votes were taken to be given to an imaginary extra play, or
The votes of each play remain constant and the extra imaginary play gets an extra 1/9 of the total votes cast, so we have 10/9 total votes cast (compared to the actual votes cast). In other words the extra imaginary play got the average number of votes among the 9 plays.

Makes some sense, but let's look closer.

For interpretation 1: why should we take the same % votes from each play? This way we are taking more votes from the popular plays and less from the unpopular. Why not take the same amount of votes from each play (not same %)? Or even take more votes from unpopular plays than from popular. Afterall isn't probable for a popular play to retain its votes?
For interpretation 2:  Why should the imaginary play added, add to the total votes, the average votes per play? Why not the median? Why not some other estimation that gives the most probable number of votes given the distribution of votes we have seen so far?

Do different ways matter, and is there a more fair way? (maybe in the sense of maximum likelihood). I give a partial answer below in the answers section
I would also appreciate your help in finding a better title for the problem.
Comment: Another way for comparison: use the ratio of actual percentage divided by the average percentage a play can get. For example, both these cases get a "grade" of 2: 1) a play among 5 plays getting 40%, 2) a play among 10 plays getting 20%. This is exactly equivalent to the "official" formula: your grade is the adjusted percentage multiplied by the number of normative plays (10 in the official formula). What is unfair in this way? Grade upper limit depends on number of plays in a week. Eg 2plays(95%, 5%) 10plays(20%, 15%, 15%, 10%,...). Play in 2nd case seems more popular using the grade. Is it?
Answer: Say you had eight batches of exactly ten plays.  For the first five weeks, they had evenly split ballots - roughly 10% for each play, with one play winning by one vote.
Then in week 6, the winner has 12%, while the other 9 have around 9.77% apiece.  In week 7, the same thing happens, except at 12.01%.  In week 8, the winner has 13%, 2nd place has just under 12%, and the remaining films have just over 9.375% apiece.
Who should the top two winners be, intuitively?  I ask because that would give you clues on how exactly you want your rule to work.
If I label each of those four winners A through D, then different cases could be made for:
1) A and B should win since they both had the highest margins of weekly winners.
2) B and C should win since they had the highest percentages.
3) C and D should win since they had the highest margin ahead of the films they scored better than.
At any rate, I think you could basically argue that it is a poorly formed question (so far) just because it depends on a nebulous definition of fairness.  If you specify more requirements of what a fair outcome would be in an ideal structure (ten plays every week) then it might be easier for you to come up with a consistent approach.
I'm assuming the festival's organizers would pick #2) B and C, even though it strikes me as unfair because a winner could be penalized just from it being a good night at the theater.
If that's the case, then you need to do another round of soul-searching.  Imagine eight rounds where you have clear results of a 12% winner, and nine 9.77% 2nd-place winners.  Take one of those 9.77% plays and move it to another night.  What does that mean for the 11-play night?  Does it mean that the people that the people that didn't vote for the first-place-winner would just split their votes ten ways instead of nine ways, thereby creating more margin between 1st and 2nd place?  Or does it mean that the same margin is retained, with scores of 11.12% for the winner vs 8.89% for the other ten finishes?  Or perhaps you want to retain the percentage-above-average that the winner would get, in which case the winner would have 10.91%  while the others would have 8.91%  At any rate, I think it's something where you have specify the ideal behavior first before you can come up with the math on how to approximate that behavior afterwards.
Comment: Thanks @tunesmit for pointing out even more unfairness issues with the general voting scheme, but this is a given as a I state in my initial question. The pinnacle of unfairness is that the plays are not compared to each other (only in limited batches of 10). I was interested in a specific twist of the voting scheme after we accept it. When we accept the scheme the answer to your example is 2). For my question (on the twist) I was pointing the problems with averages and asking what would a metric of fairness could be, offering some suggestions and insights.
Answer: I tested the effect of adjustment using the actual vote distributions from various weeks. So in a sense I took an experimental approach. Here's what I did:
I have actual voting data of several weeks with 10 plays each. Let's just look at one week here. I assumed that one play was not there. I calculated the adjusted percentage for the remaining plays using the "official" formula and compared it with the actual percentage. I did this for every possible excluded play. Adjusted percentages were above or below the actual percentage depending on which play was excluded, but the averages of these adjusted percentages (over all possible excluded plays) followed some clear trends.
More formally. Let $p_i$ be the vote percentage for play $i$, in a week of $m$ plays. Let $p_i^k$ be the vote percentage of play $i$, when we exclude play $k$ from the set ($i\neq k$). That is, $p_i^k$ is the observed percentage from a set of $m-1$ plays ($m$ plays, minus play $k$). Let $\hat{p_i^k}$ be the adjusted percentage based on the official formula ( $\hat{p_i^k} = p_i^k \cdot \frac{m-1}{m}$). The average adjusted percentage $\hat{p_i}$ for play i is given as:
$$\hat{p_i} = \frac{1}{m-1} \sum_{k=0}^{m-1}\hat{p_i^k} = \frac{1}{m} \sum_{k=0}^{m-1}p_i^k$$
Is $p_i \approx \hat{p_i}$ ?  It turns out, not really. The popular plays are getting disadvantaged and the unpopular ones advantaged by the adjustment. For practical purposes the difference is not very big (observed at most 0.2%), since the distribution of votes is not very uneven, but if a play gets say 70% of the votes then the adjusted percentage is about 5% less.
I also tried a different adjustment method to replace the "official" formula: I add an extra play, which brings extra votes. The extra votes are distributed uniformly from the votes of  the $m-1$ plays in the set. With this new method, the adjusted percentage is closer to the actual observed one, but still popular plays get slightly penalised. For example the 70% runaway winner got 2.5% less in the adjusted percentage.
So different ways do matter, and they matter most when the distribution of votes is most uneven. Is there a fair way? I guess the question can be transformed to this: If we add another sample in our set (in our case: votes for an imaginary play), what is a fair sample? Maybe the answer depends on which property of the set's distribution you want to keep. Maybe not. Anything fair comes to mind when talking about votes/preferences?
Answer: The way I see it, you have N plays total, and if they would be evaluated all together, each would get p_i of the votes. Now, you have them randomly put together in groups, and assume the group we are looking at has n members (let's call the collection of plays in that group A). All we can observe are the probabilities within the group, let's call them q_i. So for play i, we have:
  q_i = p_i / Sum_over_A(p_k)
I'm not sure how to define fairness exactly, but it seems like finding the best estimate of p_i given q_i would be the thing to do. I don't know how to actually do this though.
A simple thing would be to approximate Sum_over_A(p_k) as (1/N)*n. This gives p_i = q_i*n/N, which is equivalent to the "official" formula. As long as the n don't differ to much between groups, it could be a reasonable approximation.
Or alternatively, Sum_over_A(p_k) = p_i + Sum_over_A{i}(p_k) = p_i + (1-p_i)*(n-1)/(N-1). This would result in something like p_i = q_i * (n-1)/(N-1-q_i*N+q_i*n). I realize none of this is too mathematical or exact.


Why is $H^1(X, \mathcal{O}) \neq 0$ for $X = (B(0, 1)\times B(0, 2)) \cup (B(0, 2)\times B(0, 1))$?

Question: In this MathOverflow answer, David Speyer says that
\begin{align*}
X &= \{ (z,w) \in \mathbb{C}^2 : (|z|, |w|) \in [0,1) \times [0,2) \cup [0,2) \times [0,1) \}\\
&= (B(0, 1)\times B(0, 2)) \cup (B(0, 2)\times B(0, 1))
\end{align*}
is an example of a contractible manifold such that $H^1(X, \mathcal{O}) \neq 0$. I can see that $X$ is contractible, but I don't know how to show that $H^1(X, \mathcal{O}) \neq 0$. Can we explicitly write down a $\bar{\partial}$-closed $(0, 1)$-form on $X$ which is not exact or do we need to use some sheaf cohomology?
Comment: I think you can just write down, with the presented to you cover, a non-trivial Cech cocycle.
Answer: $\def\CC{\mathbb{C}}\def\cO{\mathcal{O}}$Let $U = \{ (z,w) : |z| < 1,\ |w| < 2 \}$ and $V = \{ (z,w) : |z|<2, |w|<1 \}$. So $X = U \cup V$. Note that
$$\cO(U) = \left\{ \sum a_{ij} z^i w^j : |a_{ij}| = O((1+\delta)^i (1/2+\epsilon)^j)  \ \forall \delta, \epsilon>0 \right\}$$
$$\cO(V) = \left\{ \sum b_{ij} z^i w^j : |b_{ij}| = O((1/2+\delta)^i (1+\epsilon)^j)  \ \forall \delta, \epsilon>0 \right\}$$
$$\cO(U \cap V) = \left\{ \sum c_{ij} z^i w^j : |c_{ij}| = O((1+\delta)^i (1+\epsilon)^j)  \ \forall \delta, \epsilon>0 \right\}.$$
Since $U$, $V$ and $U \cap V$ are polydiscs, they are Stein and we can compute $H^1(X, \cO)$ with respect to the Cech cover by $U$ and $V$. This tells us that $H^1(X, \cO)$ is the cokernel of $\cO(U) \oplus \cO(V) \longrightarrow \cO(U \cap V)$. If $\sum a_{ij} z^i w^j$ and $\sum b_{ij} z^i w^j$ are holomorphic on $U$ and $V$ respectively, then $|a_{ij} + b_{ij}| = O((1/2+\delta)^{\min(i,j)})$. So, for example, $\sum z^i w^i$ is holomorphic on $U \cap V$ but cannot be expressed as the sum of such a $\sum a_{ij} z^i w^j$ and $\sum b_{ij} z^i w^j$.
Turning this into an explicit $\bar{\partial}$-closed non-$\bar{\partial}$-exact $(0,1)$-form is doable but not illuminating. Let $f+g=1$ be a partition of unity with $f$ supported on $U$ and $g$ on $V$, and let $c \in \cO(U \cap V)$ represent a nontrivial Cech-cocycle. Then $\bar{\partial}(f c) + \bar{\partial}(gc) = \bar{\partial}(c) = 0$ on $U \cap V$. Define a $1$-form on $X$ to be $\bar{\partial}(f c)$ on $U$ and $-\bar{\partial}(f c)$ on $V$; this is the $\bar{\partial}$-closed non-$\bar{\partial}$-exact given by the isomorphism between sheaf and Dolbeault cohomologies.
The usual way to think about $X$ is in terms of holomorphically convex hulls: Let $h(z,w) = \sum d_{ij} z^i w^j \in \cO(X)$ and let $(z_0, w_0) \in \CC^2$ with $|z_0 w_0| < 2$. Taking a weighted geometric mean of the bounds $|d_{ij}| = O((1+\delta)^i (1/2+\epsilon)^j)$ and $|d_{ij}| = O((1/2+\delta)^i (1+\epsilon)^j)$, we obtain $|d_{ij}| = O((|z_0|+\delta)^{-i} (|w_0|+\epsilon)^{-j})$, so $h$ extends to $(z_0, w_0)$. If we choose $(z_0, w_0)$ not to lie in $X$ (for example, $(1.2, 1.2)$), then we have given a point in the holomorphically convex hull of $X$ but not in $X$. (And, in fact, the holomorphically convex hull of $X$ is $\{ (z,w) : |z|<2, |w|<2, |zw|<2 \}$.)
A non-holomorphically convex set can never have vanishing $H^1(\cO)$. Consider the Koszul sequence $0 \to \cO \to \cO^2 \to \cO \to \CC_{(z_0, w_0)} \to 0$ where the last term is the skyscraper sheaf at $(z_0, w_0)$. Restricting to $X$, we obtain an exact sequence of sheaves $0 \to \cO \to \cO^2 \to \cO \to 0$. But the corresponding map of global sections $\cO(X)^2 \to \cO(X)$ is not surjective, because any function in the image of this map can be evaluated at $(z_0, w_0)$ and must vanish there. So there must be an $H^1(X, \cO)$ term to recieve the cokernel of $\cO(X)^2 \to \cO(X)$.


BoxLayout can't be shared error?

Question: Hi there I am working on a Java app and below is an excerpt from a custom class called Gui which extends JFrame:
public Gui(){
    super("EVC Scan & Price");
    setSize(400,500);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setResizable(false);
    // GridLayout layout = new GridLayout(5,1);
    BoxLayout layout = new BoxLayout(this, BoxLayout.Y_AXIS);
    setLayout(layout);

    //add header row
    headerRow.setAlignmentX(Component.CENTER_ALIGNMENT);
    BorderLayout layoutHeading = new BorderLayout();
    headerRow.setLayout(layoutHeading);
    if (headerImg != null){
    ImageIcon icon = new ImageIcon(headerImg);
    picLabel.setIcon(icon);}
    headerRow.add(picLabel, BorderLayout.NORTH);
    title.setAlignmentX(JLabel.CENTER_ALIGNMENT);
    headerRow.add(title, BorderLayout.SOUTH);
    add(headerRow);

    //add first row
    firstRow.setAlignmentX(Component.LEFT_ALIGNMENT);
    BoxLayout layoutRow1 = new BoxLayout(firstRow,BoxLayout.Y_AXIS);
    firstRow.setLayout(layoutRow1);
    firstRow.add(catLabel);
    scroll.setSize(390,100);
    firstRow.add(scroll);
    add(firstRow);

    setVisible(true);
}

I have read many tutorials and the api and really can not see anything wrong with this, however the line reading: add(headerRow); seems to be the trigger for a "BoxLayout can't be shared" error.
If I change the layout for the JFrame to a flowlayout the nested boxlayout applied to the firstRow section works fine?
Can anyone help please?
Answer: Change this:
BoxLayout layout = new BoxLayout(this, BoxLayout.Y_AXIS);

to this:
BoxLayout layout = new BoxLayout(getContentPane(), BoxLayout.Y_AXIS);

The error-producing code passes the JFrame into the BoxLayout's constructor as the BoxLayout using container when in fact it's not. In truth, you're adding the layout to the JFrame's contentPane and not the JFrame.
As an aside, you may be painting yourself in a corner by having your class extend JFrame, forcing you to create and display JFrames, when often more flexibility is called for. In fact, I would venture that most of the Swing GUI code that I've created and that I've seen does not extend JFrame, and in fact it is rare that you'll ever want to do this. More commonly your GUI classes will be geared towards creating JPanels, which can then be placed into JFrames or JDialogs, or JTabbedPanes, or swapped via CardLayouts, wherever needed. This will greatly increase the flexibility of your GUI coding.

BoxLayout can't be shared error?


Filezilla connection error

Question: I have Red Hat Enterprise Linux (RHEL) 5 LAN server with Squid 2.6 stable proxy settings.
Under this have some Windows XP desktops.
Now I installed FileZilla FTP client in Windows XP, to service my client's websites.
But I can't connect FTP servers through FileZilla.
I set generic proxy too. (HTTP/1.1 USING CONNECT method.)
I get an error message,

Status: Connecting to (ftp hostname) through proxy
Status: Connecting to hostname:port...
Status: Connection with proxy established, performing handshake...
Response: Proxy reply: HTTP/1.0 403 Forbidden

How can I solve this problem?
Answer: Frequently, corporate web proxies will allow a CONNECT to port 443 only. Filezilla will be attempting to connect to port 21 (FTP command port) through your proxy but your proxy is telling you that is forbidden.
So how to get around this? Set up a virtual machine running Linux somewhere on the public internet. Configure port 443 as a SSH server port. Use putty to make a connection via your web proxy to port 443 on your virtual server, and set up SOCKS proxying through that connection (tunnel). Finally, configure Filezilla to use your local SOCKS proxy (which is really redirecting connections to your virtual Linux host through the SSH tunnel established over your web proxy).

Filezilla connection error


merge two lists based on a condition

Question:     "ansible_facts": {
        "list1": [
            "10",
            "2",
            "4",
            "5",
            "6",
            "7",
            "7",
            "8",
            "9"
        ],

        "list2": [
            [
                "10",
                "xxxxx"
            ],
            [
                "2",
                "yyyyy"
            ],
            [
                "4",
                "zzzzz"
            ],
            [
                "5",
                "mmmmm"
            ],
            [
                "6",
                "fffff"
            ],
            [
                "7",
                "gggggg"
            ],
            [
                "8",
                "hhhhh"
            ],
            [
                "9",
                "kkkkkk"
            ]

Here I have two lists, I want to merge list2, just the words(xxxx,yyyy,...) with list1, but with condition that whenever the number on list2 match list1 then merge it to it's according number on list 1. But as you can see there can be some repeating number making it not perfectly aligned. When I sort the list like above still the the condition won't work when numbers repeat.
``
the condition that i've tried
    when: list1[item|int] == list2[item|int]
    with_sequence: start=0 end={{countvar.stdout|int - 1}}

Expected merged list
```
    "list3": [
        [
            "10",
            "xxxxx"
        ],
        [
            "2",
            "yyyyy"
        ],
        [
            "4",
            "zzzzz"
        ],
        [
            "5",
            "mmmmm"
        ],
        [
            "6",
            "fffff"
        ],
        [
            "7",
            "gggggg"
        ],
        [
            "7",
            "gggggg"
        ],
        [
            "8",
            "hhhhh"
        ],
        [
            "9",
            "kkkkkk"
        ]

Comment: add the expected (merged) list to the question
Comment: I've added it to post
Answer:
Given the lists
  l1: ['10', '2', '4', '5', '6', '7', '7', '8', '9']
  l2:
    - ['10', xxxxx]
    - ['2', yyyyy]
    - ['4', zzzzz]
    - ['5', mmmmm]
    - ['6', fffff]
    - ['7', gggggg]
    - ['8', hhhhh]
    - ['9', kkkkkk]

Convert the second list to a dictionary

  d2: "{{ dict(l2) }}"

gives
  d2:
    '10': xxxxx
    '2': yyyyy
    '4': zzzzz
    '5': mmmmm
    '6': fffff
    '7': gggggg
    '8': hhhhh
    '9': kkkkkk

Extract the values

  v1: "{{ l1|map('extract', d2)|list }}"

gives
  v1: [xxxxx, yyyyy, zzzzz, mmmmm, fffff, gggggg, gggggg, hhhhh, kkkkkk]

zip the lists

  l3: "{{ l1|zip(v1) }}"

gives what you're looking for
  l3:
    - ['10', xxxxx]
    - ['2', yyyyy]
    - ['4', zzzzz]
    - ['5', mmmmm]
    - ['6', fffff]
    - ['7', gggggg]
    - ['7', gggggg]
    - ['8', hhhhh]
    - ['9', kkkkkk]

You can put it in one line which gives the same result
  l3: "{{ l1|zip(l1|map('extract', dict(l2))|list) }}"

Example of a complete playbook for testing

- hosts: localhost

  vars:

    l1: ['10', '2', '4', '5', '6', '7', '7', '8', '9']
    l2:
      - ['10', xxxxx]
      - ['2', yyyyy]
      - ['4', zzzzz]
      - ['5', mmmmm]
      - ['6', fffff]
      - ['7', gggggg]
      - ['8', hhhhh]
      - ['9', kkkkkk]

    d2: "{{ dict(l2) }}"
    v1: "{{ l1|map('extract', d2)|list }}"
    l3: "{{ l1|zip(v1) }}"
    l4: "{{ l1|zip(l1|map('extract', dict(l2))|list) }}"

  tasks:

    - debug:
        var: d2
    - debug:
        var: v1|to_yaml
    - debug:
        var: l3|to_yaml
    - debug:
        var: l4|to_yaml

The filter to_yaml can use anchor

 l3|to_yaml: |-
    - ['10', xxxxx]
    - ['2', yyyyy]
    - ['4', zzzzz]
    - ['5', mmmmm]
    - ['6', fffff]
    - &id001 ['7', gggggg]
    - *id001
    - ['8', hhhhh]
    - ['9', kkkkkk]

Use community.general.yaml callback.

shell> ansible-config dump | grep DEFAULT_STDOUT_CALLBACK
DEFAULT_STDOUT_CALLBACK(/scratch/test-061/ansible.cfg) = yaml

merge two lists based on a condition


Prove an inequality in real analysis

Question: Let $(X,F,u)$  be a measure space and suppose $\{ f_{n} \}$is a sequence of measurable functions with the property that for all $ n>1 $,
$$
u  \{ x\in X:|f_{n}(x)|\geq  \lambda \} \leq C\exp(-\lambda^{2}/n)
$$
for all $\lambda >0$. (Here C is a constant independent of $n$.) Let $n_{k}=2^{k}$. Prove that
$$
\limsup_{k \to \infty} \frac{|f_{n_k}|}{\sqrt{n_{k}\log (\log(n_{k}))}}\leq 1\text{ a.e.}
$$
Comment: no, there is no other information about the space.
Comment: This isn't true in general, e.g., $f_n = 0$
Comment: what do you mean by $f_{n}$independent?
Comment: sorry, you caught me in the middle of editing that, I think the inequality goes the wrong way, because you want the $f_i$ to be fairly *big* ,
Comment: I am sorrry about that, thanks a lot, you are right, I have already correct it.
Comment: I suspect that there's still some mistake in your post. See my answer below, and also the fact that there really is relatively little point in passing to the subsequence $n_k = 2^k$ with the way the question is worded.
Answer: I am in a rush so I'll give a hint to the new version. I'll flesh it out if you don't figure it out yourself by tomorrow.
Hint: Let $B_\epsilon$ be the set $\{ \limsup \frac{|f_{n_k}|}{\sqrt{n_k \log \log n_k}} > 1 + \epsilon$. We can write $B_0$ as a countable union of sets of the form $B_\epsilon$ for $\epsilon > 0$. Next, we can show that each $B_\epsilon$ for $\epsilon > 0$ has measure 0, using the decay property you assumed.

Edit: the below addresses a previous version of the question
As stated it is false.
Let $X = (0,1)$, $F$ be the Borel $\sigma$-algebra, and $u$ the usual Lebesgue measure.
Let $f_n(x) \equiv n$. Then we have that
$$ u\{ |f_n| \geq \lambda\} = \begin{cases} 1 & n \geq \lambda \\ 0 & n < \lambda \end{cases} $$
Observe that if $n \geq \lambda$, $e^{-\lambda/n} \geq e^{-n/n} = e^{-1}$. So the required condition is satisfied for any $C > e$.
Now, we have
$$ \frac{|f_{n_k}|}{\sqrt{n_k \log \log n_k}} = \sqrt{ \frac{n_k}{\log\log n_k}} \nearrow \infty $$
so we have that precisely everywhere
$$ \limsup \frac{|f_{n_k}|}{\sqrt{n_k \log \log n_k}} > 1$$
Comment: Thanks for your effort, however I have a typo and the change the direction of the inequality
Comment: I am sorry again, there should be $\lambda ^{2}$there, and I really have no idea with the $n_{k}=2^{k}$
Answer: Let $\varepsilon>0$ and
$$A_k := \left[ \frac{|f_{n_k}|}{\sqrt{n_k \cdot \log \log n_k}} \geq 1+ \varepsilon \right] $$
We want to show that $$\sum_{k \geq 0} u(A_k)< \infty \tag{1} $$ From this we conclude by the Borel-cantelli theorem that
$$\limsup_{k \to \infty} \frac{|f_{n_k}|}{\sqrt{n_k \cdot \log \log n_k}} \leq 1+ \varepsilon$$
(this part of Borel-cantelli holds also for measure spaces, not only probability spaces.)
So remaining is to show (1). Using the decay property we obtain
$$u(A_k) = u \left(\left[ |f_{n_k}| \geq (1+\varepsilon) \cdot \sqrt{n_k \cdot \log \log n_k} \right] \right) \leq C \cdot \exp \left( -(1+\varepsilon)^2 \cdot \frac{n_k \cdot \log \log n_k}{n_k} \right) \\ = C \cdot \exp \left(\log \left(\log n_k \right)^{-(1+\varepsilon)^2} \right) = C \cdot \frac{1}{(k \cdot \log 2)^{(1+\varepsilon)^2}}$$
hence
$$\sum_{k \geq 0} u(A_k) \leq  \frac{C}{(\log 2)^{(1+\varepsilon)^2}} \cdot \sum_{k \geq 0}\frac{1}{k^{(1+\varepsilon)^2}} < \infty$$
notation $[f_{n_k} \in B] := \{x \in X; f_{n_k}(x) \in B\}$ denotes the pre-image of $B$.

Prove an inequality in real analysis


Unable to select image using flutter image picker on iOS simulator

Question: I am learning how to select images from gallery. I have implemented flutter image picker for the same. But when I try to select the image in simulator, I am not able to do so.
Please help
Flutter Doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, 1.26.0-17.3.pre, on macOS 11.1 20C69 darwin-arm, locale en-IN)
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
[✓] Xcode - develop for iOS and macOS
[✓] Android Studio (version 4.1)
[✓] Connected device (1 available)

• No issues found!

My code
import 'dart:io';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

void main() {
  runApp(MaterialApp(
    home: Play(),
    // theme: ThemeData.dark(),
  ));
}

class Play extends StatefulWidget {
  @override
  _PlayState createState() => _PlayState();
}

class _PlayState extends State<Play> {
  File _file;

  ImagePicker _picker = ImagePicker();

  PickedFile _pickedFile;

  Future _getImageFromGallery() async {
    print("Getting Image from Gallery.");
    _pickedFile = await _picker.getImage(source: ImageSource.gallery);
    print(_pickedFile.path);
    setState(() {
      _file = File(_pickedFile.path);
    });
  }

  Future _getImageFromCamera() async {
    print("Getting Image from Camera.");
    _pickedFile = await _picker.getImage(source: ImageSource.camera);
    setState(() {
      _file = File(_pickedFile.path);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Play"),
      ),
      body: Column(
        children: [
          Center(
            child: ElevatedButton(
                onLongPress: _getImageFromCamera,
                onPressed: _getImageFromGallery,
                child: Text("Get Image")),
          ),
          _file != null
              ? Image.file(
                  _file,
                  height: 200,
                )
              : Icon(
                  Icons.image,
                  size: 100,
                ),
        ],
      ),
    );
  }
}

I am using M1 Mac air. I have switched to beta channel to get rid of some verbose error.
Everything is working fine. Just, when I click on an image nothing happens. It doesn't get selected.
Comment: Have any issue you faces when try upload image?
Comment: And have you add Camera permissions on your `ios/info.plist` ?
Comment: yes I have added `NSPhotoLibraryUsageDescription
Need to access gallery in order to get image.
NSCameraUsageDescription
Need to access camera in order to get image.
NSPhotoLibraryAddUsageDescription
Add photo liabrary description`
Comment: same code works perfectly on windows
Comment: I have the same issue. did you find any solution
Comment: Same here. Mac Mini M1.
Same code works fine on Android.
Comment: Same here, on M1 MacBook pro. It's been a roadblock since i don't have any physical IOS device to test the App. Let me know if anyone has a workaround.
Comment: Same Issue .Open Gallery but unable to select image using flutter image_picker: 0.7.3 on iOS simulator. I have MacBook pro.
Comment: Same issue. I believe it has to do something with the latest version of XCode or M1 chip.
Comment: The same issue, must be something to do with the M1 chip. Can't run a fluent Android simulator nor iOS Simulator works perfectly.
Comment: Chiming in here:  Same exact issue.  M1 Mac Mini.
Comment: Same issue with the M1 machine, is it related to M1
Comment: Same here, any news ?
Comment: you could not use camera  in simulator but only in real device in usb link or wifi.
Answer: I've tried your code and it works on my simulator:

There are discussions online including this GitHub post, that this could be an Apple bug and no known workaround.
In fact, there are people in Apple Developer Forums reports this kind of issue.
Answer: I was facing the same issue on iOS 17. I fixed it by adding the following line into info.plist
<key>NSPhotoLibraryUsageDescription</key>
<string>We need access to your photo library to pick an image for your profile.</string>

If you are accessing the camera you also need to add these
 <key>NSPhotoLibraryUsageDescription</key>
    <string>Need to upload image</string>
    <key>NSCameraUsageDescription</key>
    <string>Need to upload image</string>
    <key>NSMicrophoneUsageDescription</key>
    <string>Need to upload image</string>


ASPXCOMBOBOX Edit Mode inserts NULL VALUES to database

Question: i am creating an asp application, everything seemed to go well until recently when i decided to use ASPXComboBox in gridview, here is how i put it
ComboBox Gets values from customers table ie
customer_ID  -- this is set as value field
Customer_name -- this is set as text field
there is no problem with displaying values.
my problem is when i am on Edit Mode even though previous values of the column are displayed on the combobox if i dont change or re-select the on the combobox it then inserts NULL values to the database while updating.
i desperately need help i have searched all over. please reply
Answer: If you are using GridViewDataComboBoxColumn you can get value like this.
GridViewDataComboBoxColumn column = gridView.Columns["ColumnName"] as GridViewDataComboBoxColumn;
string text = column.PropertiesComboBox.Items.FindByValue(e.NewValues["ColumnName"]).Text;

Reference : http://www.devexpress.com/Support/Center/Question/Details/Q450251
here is the demo preoject:
http://www.devexpress.com/Support/Center/Attachment/GetAttachment?fileOid=9eb0e913-6fb0-45fe-90d5-76cabdce740e&fileName=Q381107.zip
http://www.devexpress.com/Support/Center/Question/Details/Q381107


Não é possível visualizar detalhes de eventos criado no schedule do primefaces

Question: Isso esta me intrigando tem um tempo, uso no projeto o schedule do primefaces para adicionar eventos, ate ai tudo bem, todos os computadores adicionam e mandam para o database online, existe também um método que lista todos os detalhes de cada evento quando se clica nele, só que alguns computadores da certo ver eventos cadastrados por um mas em outro PC não é possível, não faço ideia alguma de porque isso está acontecendo e nem de como resolver.
Eu criei esse no meu PC e eu consigo ver.

Esse foi criado em outro PC e ainda consigo ver ( do meu pc).

Esse foi criado em outro PC e não consigo ver ( porem em ainda outro PC sem ser o que eu consigo ver os eventos, consegue mostrar os desse.)

Então talvez tenha ficado confuso, me parece que os eventos estão aparecendo em pares ( não sei se realmente são pares) mas sei que os 4 que testei 2 conseguem ver os detalhes dos eventos deles e os outros não.
Detalhe todos os eventos aparecem no scheuld para todos os PC mas os detalhes não.
Answer: Isto esta relacionado aos eventos Ajax
Ou seja, quando você define (ou não, mas deveria limitar o escopo de atualização da pagina) a propriedade process="@this" processa só a tag current, se usar a propriedade update="@form", ai ele atualiza a arvore de componentes parent form(definição a nível didático ajuste para seu contexto).
Porque funciona a primeira vez? ou segunda até uma hora não funcionais mais. Você atualiza a árvore de componentes do JSF ultima vez antes de dar erro, mas não notificou o próximo que determinada parte da pagina mudou.
Nesse, vai e vem, o scop da view (árvore de componente esta desatualizado, com relação ao estado que ele sabe, ai acontece isso)
Solução sugerida, quando se tem um componente complexo, use um p:outpuPanel, e processe e atualize ele, sempre visível, diminui a complexidade dessa atualização do DOM.
Isso parece complexo, mas é Ajax e seus conceitos, Atualizando o DOM e não notificando todos. tipo tinha uma rua, agora tem um buraco na rua, mas não tem placa avisando (então problema) para não ter problema avise todos ou a quem interessa.


Java Apache Commons CLI does not find setArgs()

Question: I am trying to get multiple arguments passed to a java program. The Apache Commons CLI interface has been set up correctly and works. However, when I try to use
setArgs(Option.UNLIMITED_VALUES), it gives me an error
The method setArgs(int) is undefined for the type Options.
My code looks like this:
import java.io.Console;
import java.util.Arrays;
import java.io.IOException;
import org.apache.commons.cli.*;

public class main {

public static void main(String[] args) {

    @SuppressWarnings("deprecation")
    CommandLineParser parser = new BasicParser();

    Options options = new Options();
    options.setArgs(Option.UNLIMITED_VALUES);
    options.addOption("p", true, "Program under test");
    options.addOption("o", true, "Oracle");
    options.addOption("n", true, "Number of test cases");

    try {
        CommandLine commandline = parser.parse(options, args);

        System.out.println(commandline.getOptionValue("p"));

    } catch (ParseException e) {
        System.out.println("Command line failed.");
        e.printStackTrace();
    }

}

}

Answer: setArgs is a method related to Option not Options
Comment: However, this creates another issue. Now the same line gives me "Cannot make a static reference to the non-static method setArgs(int) from the type Option". Any clue?
Comment: You're probably calling `Option.setArgs` statically. Create an instance of `Option` before attempting to use `setArgs` on the instance of that class
Comment: You're a lifesaver! Thanks!


MySql Trigger Error: Can't update table in stored function/trigger because it is already used by statement which invoked this stored function/trigger

Question: I have written the code for trigger the function to update my table after inset event complete.
This is my code,
CREATE TRIGGER `first_trigger` AFTER INSERT ON `table1`
FOR EACH
ROW UPDATE table1
SET test= "verified"

Error Message I got it,
Error: Can't update table 'table1' in stored function/trigger because it is
already used by statement which invoked this stored function/trigger.
How to solve this error?
Comment: Why not set test in the insert?
Answer: You must alter the value which would be saved into the table. Of course you must do this before the saving, i.e. in BEFORE INSERT trigger.
To refer to the value for the row which is currently inserted you must refer to it using the alias NEW which acts as pseudo-table which contains one row which is inserted now.
CREATE TRIGGER `first_trigger`
BEFORE INSERT ON `table1`
FOR EACH ROW
SET NEW.test= 'verified';


Firebase getDisplayName() retorna vazio

Question: Eu tenho o seguinte código que deve retornar os dados do usuário logado pelo Firebase, ele retorna o usuário sem problema algum, o ID e o Email, mas o valor do nome retorna vazio ou nulo. Como se estivesse cadastrado o usuário sem nome, mas no cadastro consta o nome do usuário normalmente. Alguém sabe pq? Eu já pesquisei e parece que tem algum bug com o getDisplayName do Firebase. Já obtiveram uma solução?
public static FirebaseUser getUsuarioAtual() {
        FirebaseAuth usuario = ConfiguracaoFirebase.getFirebaseAutenticacao();
        return usuario.getCurrentUser();
    }

    public static Usuario getDadosUsuarioLogado() {
        FirebaseUser firebaseUser = getUsuarioAtual();

        Usuario usuario = new Usuario();
        usuario.setId(firebaseUser.getUid());
        usuario.setEmail(firebaseUser.getEmail());
        usuario.setNome(firebaseUser.getDisplayName());

        return usuario;
    }

Answer: Após uma pesquisa eu descobri que esse era um bug em algumas versões do Firebase, veja aqui.  Ele foi introduzido na versão 9.8.0, então se você usar a versão 9.6.1 ele não ocorre. Eu não sei dizer se o bug já foi corrigido, mas tente usar a última versão disponível, que é a 16.0.4.
Nessa página que citei acima alguns usuários relataram problemas também com o método FirebaseUser.getPhotoUrl(), além do método FirebaseUser.getDisplayName().
Encontrei algumas soluções alternativas em respostas do SOen, veja se alguma resolve o seu problema.
Usando FirebaseUser.getProviderData() (link):
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
    String displayName = user.getDisplayName();
    Uri profileUri = user.getPhotoUrl();

    for (UserInfo userInfo : user.getProviderData()) {
        if (displayName == null && userInfo.getDisplayName() != null) {
            displayName = userInfo.getDisplayName();
        }
        if (profileUri == null && userInfo.getPhotoUrl() != null) {
            profileUri = userInfo.getPhotoUrl();
        }
    }

    accountNameTextView.setText(displayName);
    if (profileUri != null) {
        Glide.with(this)
                .load(profileUri)
                .fitCenter()
                .into(userProfilePicture);
    }
}

Deslogando e logando novamente (link):
// Comando para deslogar o usuário atual.
FirebaseAuth.getInstance().signOut();
// Depois disso logar novamente:
// https://firebase.google.com/docs/auth/android/password-auth

E outra pergunta sobre o mesmo assunto aqui.
Comment: C.Oli, alguma solução funcionou para você? Deixe comentado aqui se sim ou se não, por favor, para ajudar outros que encontrem esse mesmo problema.
Comment: Eu consegui resolver excluindo os perfis já criados e criando novamente, ele passou a retornar normalmente o valor do nome. Com o método de deslogar e logar novamente tbm funciona.
Comment: Usando `FirebaseUser.getProviderData()` não funcionou pra mim

Firebase getDisplayName() retorna vazio


Hyper-V Shutdown fails - error 32768

Question: I'm in the process of attempting to automate Hyper-V for our dev\test lab.  I downloaded the PSHyperV pack, most of the scripts work however when I attempt to shutdown the machine it fails with the error code 32768.
I also tried the script off Ben's blog.
However this also failed.
<code>__GENUS          : 2
__CLASS          : __PARAMETERS
__SUPERCLASS     :
__DYNASTY        : __PARAMETERS
__RELPATH        :
__PROPERTY_COUNT : 1
__DERIVATION     : {}
__SERVER         :
__NAMESPACE      :
__PATH           :
ReturnValue      : 32768
</code>
Does anyone have any ideas?
Answer: Here is an explanation: http://social.technet.microsoft.com/Forums/en-US/winserverhyperv/thread/ddcf44cb-7cf2-413d-abe4-b0ed33f5d3fa

Hyper-V Shutdown fails - error 32768