nginx : no live upstreams while connecting to upstream

Question: 502 bad gateway error displayed when switching between site pages and some times on home page but not for the first request on the home page it is only when another page redirect to it. and it happens for some javascript files
load balancing configured on two upstreams php1 php2 both are apache server.
When I checked error log i fond:
no live upstreams while connecting to upstream

[error] 27212#0: *314 no live upstreams while connecting to   upstream, client: ip_address , server: example.com, request: "GET / HTTP/1.1", upstream: "http://example.com", host: "example.com", referrer: "http://example.com/mypages/"

and this is load balancing server configuration
  upstream example.com  {
    #  ip_hash;
      server php01 max_fails=3 fail_timeout=15s;
      server php02 max_fails=3 fail_timeout=15s;
    }

    server {
      listen IP:80;
      server_name example.com;
      access_log /var/log/nginx/example.com.access;
      error_log /var/log/nginx/example.com.error error;

     location / {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass  http://$server_name/$uri;
        proxy_cache_bypass $cookie_nocache $arg_nocache $arg_comment;
        proxy_cache_bypass $http_pragma $http_authorization;
        proxy_no_cache $cookie_nocache $arg_nocache $arg_comment;
        proxy_no_cache $http_pragma $http_authorization;
      }

    }

I searched for hours and nothing helpful found my streams are up and no problems with them.
Comment: Are your upstream servers (php01, php02) working? Could you telnet from ngnix machine to them ?
Comment: They are connected.
Comment: Have you checked that the upstream servers have enough processes running to handle the traffic? You should check upstream server logs if they deny requests for some reason.
Comment: I did and no problem with any upstream error log, and no access log for the bad gateway requests.
Comment: Did you find a solution to this problem?
Comment: You have to define upstrem directly, see here https://stackoverflow.com/a/36928712/2803344
Answer: This is not a problem with Nginx, it is a problem with your PHP backends not responding in time. You can add logging to Nginx to help confirm this.
As a second point of reference, you can you can top on the server and manually check if PHP is slamming the CPU for periods of time, another indicator of slow responses.
If very slow responses from PHP are OK with you, you can ask Nginx to wait longer before giving up:
 # Wait 5 minutes before giving up on the backend!
 proxy_read_timeout 5m;

By examining the logs with the timing information linked to above, you ought to be able to figure out which requests are slow for PHP to process.
To narrow down the problem, send these requests directly to the PHP backend.
Depending on what's happening, you might also be able enable caching of some requests in Nginx, avoiding some of slow requests.
Answer: Don't know if it is quite the same but what worked for me was to add max_fails = 0 to the end of the server name
upstream sm_url {
  server LOAD_BALANCER_DOMAIN_NAME: max_fails=0;
}
Comment: Having looked at this a bit more, the Python server this was hooked up to was giving back bad headers. I didn't bother fixing them as I didn't care enough about the service.
Answer: Rename the upstream to "up_example.com" and change
proxy_pass  http://$server_name/$uri;

be
proxy_pass  http://up_$server_name$uri;

Comment: While unconventional, I see no technical problem with the use of `$server_name`. If this was the problem, I think he would have problems /all/ the time, not just sometimes as reported.


Ordenar dicionário pelo valor Python

Question: Tenho um dicionário com o seguinte formato
dic={759147': 54, '186398060': 8, '199846203': 42, '191725321': 10, '158947719': 4}

gostaria de saber sé há como ordená-lo pelo valor e imprimir na tela. De modo que a saída seja.
'158947719': 4
'186398060': 8
'191725321': 10
'199846203': 42
'759147': 54

Answer: Pode usar a função sorted():
dic = {'759147': 54, '186398060': 8, '199846203': 42, '191725321': 10, '158947719': 4}
for item in sorted(dic, key = dic.get):
    print (dic[item])

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Só um detalhe, o termo mais correto seria classificar o dicionário.
Answer: Um dicionário em python não tem ordem, na maior parte dos casos não tem sentido manter a ordem dos itens do dicionário.
Porém existe o OrderedDict (também em python 2).
Alternativamente você pode ordenar uma lista com as chaves e acessar os valores na ordem dessa lista.

Ordenar dicionário pelo valor Python


show text value of html © entity in input type=text?

Question: I'm loading a value from a json file which contains a copyright character. It's stored in the json as a html entity - © which renders ©.
Handlebars is rendering a file editor for me in such a way that if the string is long it gets made into a textarea, and if it's short then it becomes a text input box instead. When rendered to a <textarea> the value is shown as its string version - something like © 2013 blah foo inc, whereas if the value is written to a <input type='text'> value, then the browser renders it as its entity equivalent, no the string itself. I can't figure out how to make the text value of the entity itself appear, not its interpreted shape.
Answer: As I understand that you want to convert html entity name (©) into it's character (©) in input type text/textarea.
var content = "© 2014 blah foo inc";
var copyright = $('
').html('©').text();
var encoded = content.replace(/©/g, copyright);
alert(encoded); // or $('#input_id').val(encoded);

Answer: The trick is to change © into &copy;. When displayed & turns into &.
The question doesn't specify the language, but in JavaScript you'd do
var content = "© 2013 blah foo inc";
var encoded = content.replace( /&/g, '&' );

Comment: Ok, so I'd have to modify Handlebars to do this or write an explicit value conversion helper to do so, but only in the case when being read from an `input type=text`, since the above wouldn't apply when the value is inside a textarea.. Hmm, not ideal, remotely. The value gets read back from the field using jQuery, might have to look at re-conversion after that point.


Maximum Value of Kernel Function in ABC

Question: Are there cases where a kernel function, must have 1 as the maximum value ??
The definition of a Kernel can be found in the following link,
https://en.wikipedia.org/wiki/Kernel_(statistics)#In_non-parametric_statistics
For example, in Approximate Bayesian Computing (ABC), we approximate the true likelihood of the data with the following integral
$$\int K_{h}(x_{true}-x)p(x|\theta)dx$$
where $x_{true}$ is our observed data, and $p(x|\theta)$ the model from which we sample.
In this case, can we assume that $K_{h}(x_{true}-x)$ is a weight function, so the sum across all $x$ has to be 1, so we  can assume that the maximum value of $K_{h}(x_{true}-x)$ is 1?
Because it is known that a scaled kernel, in general, is no constrained to have a maximum value of 1.
But in the case of the ABC approximation, should it have 1 as each maximum value?
Answer: The answer is no. You must have that $\int K_h(u)\mathrm{d}u = 1$, but that doesn't mean that $K_h(u) \leq 1$. The same applies to pdfs: a pdf $f$ can take values bigger than $1$, but it's integral $\int_a^b f(x)\mathrm{d}x = P(a \leq X \leq b)$ must be always less than $1$.
You can think of the uniform distribution centered at $0$ with support $(-\epsilon, \epsilon)$ for an example: the pdf (and kernel) is
$$ K_\epsilon(x) = \dfrac{1}{2\epsilon}\mathbb{I}(-\epsilon \leq x \leq \epsilon)$$
Just set $\epsilon$ to any small value ( e.g. $\varepsilon\approx 0.001$) and you get that $K_\epsilon$ takes only two values: either $0$ or $500 = 1/0.002$.
TLDR: A kernel or a pdf can take arbitrarily high $y$-values, but the higher the value, the smaller the support.
Comment: Thank you for your answer. In the case, where you consider the scaled kernel as weight then we have to divide it by each maximum value, and then it would be true that it has max value 1??
Comment: What are you using this kernel for ? If your goal is to estimate a density (KDE) then you don't need to normalize anything.
Comment: I'm using it for the Approximate Bayesian Computation. Where you approximate the likelihood with the integral $\int K_{h}(x_{true}-x)p(x|\theta)dx$
Comment: And maybe that scaled kernel is used as a weight, i.e weights which $x$ is closer to $x_{true}$.
Comment: I'm no ABC expert, maybe you should change your question to include ABC specific terminology and narrow the topic, this way users with ABC experience will answer your question(s) !
Comment: Yes, I'll do that, and check any luck. Thank you!
Answer: In the original ABC version (Tavaré et al., 1999), the (dichotomous) probability of acceptance of a simulation $x(\theta)$ from $p(\cdot|\theta)$ (and hence of the parameter value $\theta$) is
$$\mathbb I_{|x_\text{obs}-x(\theta)|<\epsilon}\in\{0,1\}$$
It is a natural generalisation (Fearnhead and Prangle, 2010) to consider a smoother function of the distance like
$$K(|x_\text{obs}-x(\theta)|/\epsilon)$$
provided of course that $K(|x_\text{obs}-x(\theta)|/\epsilon)\in(0,1)$. There is no constraint though that $K(\cdot/\epsilon)$ is a probability density and indeed it does not integrate to one (since the rescaled version of a true density $K$ would be $K(\cdot/\epsilon)/\epsilon$ instead). Nonetheless, the name kernel was adopted (or abused!) for $K(\cdot/\epsilon)$ by analogy with non-parametrics (Blum and François, 2010).
The associated ABC posterior then writes as
$$\pi(\theta)K(|x_\text{obs}-x(\theta)|/\epsilon)p(x|\theta)\Big/
\int_\Theta\int_{\mathfrak X} \pi(\theta)K(|x_\text{obs}-x(\theta)|/\epsilon)p(x|\theta)\text dx\text d\theta$$
by an accept reject argument,
which does not require $K(\cdot/\epsilon)$ to be a probability density.
Comment: So, If I understand well, I can consider the kernel (if it belongs in (0,1) ) as a smoothed version of the cut-off acceptance probability?
Comment: A smoothed version of the indicator function.

Maximum Value of Kernel Function in ABC


Probability mass function for the number of dice throws to obtain a second six

Question:
You throw a fair six-sided die until you get two sixes. Let $X$ be the number of throws you need to obtain the second six. Write down a formula for $P(X = k)$.

What is the thinking behind the answer?
Answer: Suppose that the $n$th throw is the second one to return a six. You will have one six in the $n-1$ previous throws, so:
$$P(X=n)=\binom{1}{1}\dfrac16 \times \binom {n-1}{1}\dfrac{1}{6} \times\left(\dfrac{5}{6}\right)^{n-1-1}\\=\binom{n-1}{1}\left(\frac16\right)^2\left(\frac56\right)^{n-2}$$
Answer: Say we have gotten one six in $k-1$ attempts. Based on the binomial distribution, the probability of this happening equals:
$${k-1 \choose 1} \bigg(\frac{1}{6}\bigg)^1 \bigg(\frac{5}{6}\bigg)^{k-2}$$
Then, the probability of hitting the second six on the $k^{th}$ turn equals $\frac{1}{6}$. Thus, we get:
$$P[X=k] = {k-1 \choose 1} \bigg(\frac{1}{6}\bigg)^2 \bigg(\frac{5}{6}\bigg)^{k-2} = (k-1)\frac{5^{k-2}}{6^{k}}$$


Player freezes in position when swapped in for another player

Question: I have character code:
extends CharacterBody3D
@onready var camera_mount = $camera_mount
@onready var animation_player = $visuals/mixamo_base/AnimationPlayer
@onready var visuals = $visuals
@onready var camera_3d = $camera_mount/Camera3D

@export var is_current:bool = true
@export var is_main = true
@export var SPEED = 5.0
@export var JUMP_VELOCITY = 4.5
@export var SENSIVITY = 0.05
var walk_speed = 3.0
var run_speed = 5.0
var is_running = false
var gravity = ProjectSettings.get_setting("physics/3d/default_gravity")

func _ready() -> void:
    if is_main:
        Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)

func _input(event):
    if is_main:
        if event is InputEventMouseMotion:
            rotate_y(deg_to_rad(-event.relative.x*SENSIVITY))
            visuals.rotate_y(deg_to_rad(event.relative.x*SENSIVITY))
            camera_mount.rotate_x(deg_to_rad(-event.relative.y*SENSIVITY))

func _physics_process(delta):
    if is_main:
        camera_3d.current = is_current

        if not is_on_floor():
            velocity.y -= gravity * delta
        if Input.is_action_pressed("run"):
            SPEED = run_speed
            is_running = true
        else:
            is_running = false
            SPEED = walk_speed

        if Input.is_action_just_pressed("ui_accept") and is_on_floor():
            velocity.y = JUMP_VELOCITY

        if Input.is_action_just_pressed("ui_cancel"):
            Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)

        var input_dir = Input.get_vector("move_left", "move_right", "move_forward", "move_back")

        var direction = (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
        if direction:
            if animation_player.current_animation != "walking" && is_running == false:
                animation_player.play("walking")

            if animation_player.current_animation != "running" && is_running:
                animation_player.play("running")

            visuals.look_at(position+direction)

            velocity.x = direction.x * SPEED
            velocity.z = direction.z * SPEED
        else:
            if animation_player.current_animation != "idle":
                animation_player.play("idle")

            velocity.x = move_toward(velocity.x, 0, SPEED)
            velocity.z = move_toward(velocity.z, 0, SPEED)

        camera_mount.rotation.x = clamp(camera_mount.rotation.x,
            deg_to_rad(-90),
            deg_to_rad(70)
        )

        move_and_slide()

And the script responsible for changing the character in the game using a button:
extends Node3D

@onready var player_1 = $"../Player1"
@onready var player_2 = $"../Player2"

func _physics_process(_delta):
    if Input.is_action_just_pressed("switch_player"):
        if player_1.is_main:
            player_1.is_main = false
            player_2.is_main = true
            player_2.is_current = true
            player_1.animation_player.play("idle")
        else:
            player_1.is_main = true
            player_2.is_main = false
            player_1.is_current = true
            player_2.animation_player.play("idle")

The problem is that if you change the player while the one you were playing for before is in the air, then he freezes in this position. How can I make it so that as soon as I change a player, the one I played for before falls to the ground, i.e. began to succumb to the laws of physics?
Answer: I've made something similar in concept so I might have an idea on what went wrong. You need to transfer property values from the old player to the new one. That way it'll seem like player_2 picks up exactly where player_1 left off.
Something like this:
extends Node3D

@onready var player_1 = $"../Player1"
@onready var player_2 = $"../Player2"

const TRANSFER_PROPERTIES = ["velocity", "is_running", "walk_speed"] # add whatever variable names you need

func transfer_values(from, to):

    to.set_physics_process(false) # avoid running the _physics_process while variables are being transfered
    from.set_physics_process(false)

    for prop in TRANSFER_PROPERTIES:
        to[prop] = from[prop]

    to.set_physics_process(true)
    from.set_physics_process(true)

func _physics_process(_delta):
    if Input.is_action_just_pressed("switch_player"):
        if player_1.is_main:
            transfer_values(player_1, player_2)
            player_1.is_main = false
            player_2.is_main = true
            player_2.is_current = true
            player_1.animation_player.play("idle")
        else:
            transfer_values(player_2, player_1)
            player_1.is_main = true
            player_2.is_main = false
            player_1.is_current = true
            player_2.animation_player.play("idle")

Some references that might help you out in the future if things get more complex:
get_script()
get_script_property_list()


$(\forall x \in A)(\forall y \in A)(x Ry \iff P_x ⊆ P_y)$ for a partial order $R$

Question: This is Velleman's exercise 4.4.10:
Suppose $R$ is a partial order on $A$. For each $x ∈ A$, let $P_x = \{a ∈ A | aRx\}$. Prove that $∀x ∈ A∀y ∈ A(x Ry ↔ P_x ⊆ P_y)$.
Here's my proof of it:
Proof. Suppose $x$ and $y$ to be arbitrary elements of $A$.
($\rightarrow$) Suppose $xRy$. Suppose $aRx$. Since $R$ is transitive then from $aRx$ and $xRy$ we get $aRy$. Therefore if $aRx$ then $aRy$ and therefore if $xRy$ then $(aRx \rightarrow aRy).$
($\leftarrow$) Suppose $(aRx \rightarrow aRy)$. By the definition of partial order we have $xRy$ and therefore if $(aRx \rightarrow aRy)$ then $xRy$.
From ($\rightarrow$) and ($\leftarrow$) we'll have $(x Ry ↔ P_x ⊆ P_y)$ and since $x$ and $y$ were arbitrary then $∀x ∈ A∀y ∈ A(x Ry ↔ P_x ⊆ P_y)$.
Is my proof correct? Particualrly the backward direction in which I didn't use "$(aRx \rightarrow aRy)$" directly.
Thanks a lot.
Answer: The $\leftarrow$ does indeed need a bit of work.
Use that $R$ is reflexive to get that $xRx$, and hence $x \in P_x$. Since $P_x \subseteq P_y$ that means that $x \in P_y$, and hence $xRy$
Comment: Dang you beat me by a few seconds :D
Comment: Funny how that happens :)
Comment: @JohnGriffin.  So what?  Is the stack a competitive game?
Answer: It seems correct, but you did skip a step in the backward direction with the words "by the definition of partial order". Here's a rewording:
Suppose $P_x\subseteq P_y$. Since $R$ is reflexive, we have $x\in P_x$. Thus the assumption gives $x\in P_y$, so that $xRy$.
This shows that you do infact use $(aRx\to aRy)$.
Comment: Great minds ...


Designing a model to analyze hospital length of stay

Question: I'm trying to design a model to analyze hospital length of stay, and more specifically to ascertain the effect of sex on LOS in my data. My data contains demographic, comorbidity, and intra-operative variables (mostly continuous data like heart rate and medication dosage).
My outcomes of interest are all categorical, except for LOS. The data was collected prospectively but doesn't have a temporal aspect. LOS is just a continuous variable ranging from 0 to 120 days postop.
As such, I was wondering how I should go about calculating an effect size for sex on LOS. I considered a Cox PH model with death as competing risk, but wasn't sure how to set up the survival object as I only have the continuous/numeric "LOS" variable.
I'm of the mind that a linear regression (mixed model with hospital clusters) would be most appropriate, but in that case, what would be the best way to incorporate the death as competing risk? Would it be included as a covariate? Thank you!
Comment: Some other posts abot LOS:https://stats.stackexchange.com/questions/328275/how-to-model-remaining-hospital-length-of-stay, https://stats.stackexchange.com/questions/207999/which-is-more-appropriate-poisson-or-regular-linear-regression/208027#208027, https://stats.stackexchange.com/questions/580343/what-statistical-test-is-suitable-to-summarise-patient-time-in-hospital-with-hea, https://stats.stackexchange.com/questions/19703/how-best-to-analyze-length-of-stay-data-in-a-hospital-based-rct,
Answer: LOS is usually best modeled as a count variable using Poisson or negative binomial regression. Check the distribution of the variable using a histogram.
If you would like to include hospital clusters as a random effect, you can use mixed-effects Poisson/NB regression (using glmer and glmer.nb functions from lme4 package).
Comment: Thank you! My problem is that my LOS values are mostly non-integers (such as .38 of a day). The zero values can be fixed with a log1p but I think I'm left with a linear mixed model if the values aren't suitable for poisson or nb, right?
Comment: @smirza Yes you'd be looking at a log-linear model. Here are a few similar threads which could be informative: https://stats.stackexchange.com/questions/204696/what-regression-model-is-the-most-appropriate-to-use-with-count-data/204698#204698 https://stats.stackexchange.com/questions/38530/how-does-a-poisson-distribution-work-when-modeling-continuous-data-and-does-it-r                              https://stats.stackexchange.com/questions/204696/what-regression-model-is-the-most-appropriate-to-use-with-count-data/204698#204698


O "elif" não deixa executar o que é esperado

Question: Se fizer if cada um sozinho e executar com else, o cálculo aparece correto. Mas se usar os dois (if e elif) não reconhece as diferenças e não exibe os resultados esperados. Só haverá o desconto de R$7,00 se o preço estiver entre o número 23 e a idade digitada.
idade = int(input('Qual sua idade? '))
preço = float(input('Informe o valor: '))

#Desconto, deve estar entre o número 23 e a idade do cliente.

desconto = float(7)
if preço >= 23:
    print('Você terá um desconto de: R${:.2f}'.format(desconto))
elif preço <= idade:
    print('Você terá um desconto de: R${:.2f}'.format(desconto))
else:
    print('sem desconto')

Answer: Leia a descrição do critério que deve ser usado para dar o desconto. Tem um e ali, e é isso que deve fazer. Não existem duas condições diferentes, existe apenas uma composta de duas partes, ela tem limites da faixa a ser considerada.
Nunca use dois blocos de comandos para executar exatamente a mesma ação, basta um. Então não faz sentido fazer o elif aí, deve criar uma condição composta pelas duas partes do que está descrito que deve ser.
Use um and para concatenar as duas partes:
idade = int(input('Qual sua idade? '))
preço = float(input('Informe o valor: '))
desconto = 7.0
if preço >= 23 and preço <= idade:
    print('Você terá um desconto de: R${:.2f}'.format(desconto))
else:
    print('sem desconto')

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Em Python é possível fazer assim também:
if 23 <= preço <= idade:


how to solve homogenous differential equation $(x+y)^2 \space dx = xy \space dy$?

Question: i am stuck in this , first i find value of
$$dy/dx = (x+y)^2 / xy \tag{i}$$
let $y = vx$
differentiating both sides :
$$dy/dx = v + x \space dv/dx \tag{ii}$$
I tried to solve using equation $(i)$  and $(ii)$ but I am stuck.
$(x+y)^2 \space dx = xy \space dy$
Comment: After the transformation, your ODE becomes \begin{align} xv' + v &= (1+v)^{2}/v \\ \implies xvv' + v^{2} &= 1 + 2v + v^{2} \\ \implies xvv' &= 1 + 2v \\ \implies \frac{v dv}{1+2v} &= \frac{1}{x} dx \end{align} which can be integrated using integration by parts.
Answer: I'm skipping some initial steps as you've figured that out. As $y=vx\implies \frac{y}{x}=v$.
The original equation finally reduces to
$$v+x\frac{dv}{dx}=\frac{1}{v}+v+2\\ \implies x\frac{dv}{dx}=\frac{1+2v}{v}\\ \implies \frac{vdv}{1+2v}=\frac{dx}{x}$$
Can you take it up from here?
Comment: my mistake that i should have mention till what i finished,  i was stucked in the same line as  you have shown , but i have solved using 1/2 ∫(2v + 1 - 1)dv/1 + 2v
Answer: We are given that $\frac{dy}{dx}=\frac{(x+y)^2}{xy}$, substituting $y=vx$ in the rhs, we notice that $\frac{(x+y)^2}{xy}=\frac{1}{v}+v+2$, and from $y=vx$, by differentiating both sides with respect to $x$ we get, $\frac{dy}{dx}=v+x \frac{dv}{dx}$. Replacing the value of $\frac{dy}{dx}$ and $\frac{(x+y)^2}{xy}$, in the original equation we get,
$$v+x \frac{dv}{dx}=\frac{1}{v}+v+2$$
$$\implies x \frac{dv}{dx}=\frac{1}{v}+2$$
$$\implies x \frac{dv}{dx}=\frac{1+2v}{v}$$
$$\implies \frac{vdv}{1+2v}=\frac{dx}{x}$$
$$\implies \int\frac{vdv}{1+2v}=\int\frac{dx}{x}$$
The LHS integral is a simple U-substitution and the RHS is $\log_ex$


Yii2 password reset email, view not found

Question: I'm using yii2's advanced template, with default functionalities of user auth system, here in frontend's site/request-password-reset page, when i'm entering email and click on send button, i'm getting the following error:

The view file does not exist:
  E:\xampp\htdocs\yii2_advanced\frontend/mail\passwordResetToken-html.php

looks like it's looking for the view in frontend instead of common, what do i need to do to fix it?
Comment: try this `getAlias('@common').'/mail/passwordResetToken-html.php'`
Comment: @G4M1TG, well, i tried `return \Yii::$app->mailer->compose(['html' => \Yii::getAlias('@common').'\passwordResetToken-html', 'text' => 'passwordResetToken-text'], ['user' => $user])` , but it appends frontend's url at the begining.
Answer: Use @app alias in your path
return \Yii::$app->mailer->compose([
        'html' => '@app/common/mail/passwordResetToken-html',
        'text' => '@app/common/mail/passwordResetToken-text'
    ], ['user' => $user]);

Comment: um, sorry, but it still including 'frontend' in the url, besides, i wonder why do i need to change the default scaffolding for this, i think it worked well without and modification in previous project.


How to add multiple suffixes for an integer field type?

Question: Is there a way to add multiple suffixes for an integer field type? For example, I want to input a value, and I want to be able to specify whether this is in inches or centimeters with a drop down box.
Is there a way to do this using only the field module?
Answer: There are 3 options:

Install the Measured Value Field module.
In your custom module implement hook_form_alter and add your dropdown there with markups.
Create actual dropdown and work with just markup.
Answer: Create an additional field (apart from the integer field you already have), and make it a select list with possible values "inches" or "centimeters". With that, you don't have to install any other module (only the field module will do).
Optionally, you may want to group them together using the Field collection module (but that requires an extra module of course).


MySQL - Why does count() change the behavior of outer join?

Question: MySQL - Why does count() change the behavior of join
I have a simple case. Events and attendees. In my test below there are no attendees yet I still want a list of events so I use an outer join and that works. However if I want a list of events and the count of attendees it only returns the first row. Why
CREATE TABLE IF NOT EXISTS `event` (
 `event_id` int(11) NOT NULL AUTO_INCREMENT,
 `event_name` varchar(50) NOT NULL,
 PRIMARY KEY (`event_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

CREATE TABLE IF NOT EXISTS `attendees` (
  `event_id` int(11) NOT NULL,
  `attendee` varchar(50) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `event` (`event_id`, `event_name`)
VALUES
 (1, 'event one'),
 (2, 'event two'),
 (3, 'event three');

   SELECT e.*, a.attendee
     FROM `event` e
left outer join attendees a on e.event_id = a.event_id

returns:
event_id   event_name   attendee
---------------------------------
1          event one    NULL
2          event two    NULL
3          event three  NULL

However:
SELECT e.*, count(a.attendee)
  FROM `event` e
left outer join attendees a on e.event_id = a.event_id

only returns:
event_id     event_name    count(a.attendee)
---------------------------------------------
1            event one     0

Why?
Answer: When you add an aggregate function without specifying a GROUP BY you get one row corresponding to a single group consisting of all rows.
If you want a count per group you should add an explicit GROUP BY clause.
SELECT e.*, COUNT(a.attendee)
FROM `event` e
LEFT OUTER JOIN attendees a ON e.event_id = a.event_id
GROUP BY e.event_id

Comment: perfect  - that works!
SELECT e.*, count(a.attendee) FROM `event` e
left outer join attendees a on e.event_id = a.event_id
group by event_id
Comment: What would you change if I need both the count of attendees and the list of addendees?
Comment: @sdfor: I'd make two separate queries. Or query for the list of attendees and then count them in the client.
Comment: Thanks Mark, I think in my case your second choice makes sense. But it seems as you say, I can't combine getting both an aggregate and details in one SELECT.


Chords and Progressions Ear Training

Question: I'm getting pretty good at transcribing melodies, but chords are really difficult. This may be because the underlying harmony is mixed in with the bass as well as other instruments. It also may be because the chords don't "stand out" as well as the melody.
I know for some songs like blues, I can hear the typical 12 bar I IV V, but if you were to play me a just a single chord from that, I would have a hard time figuring it out what it was. Just pecking away until something sounds right.
And I miss passing chords also.
Mind you I listen to mainly blues and rock which can be heavily distorted to begin with.
What are some suggestions for getting better at this ?
Thanks
Answer: Recognising a single chord out of context is for those with absolute pitch  really. Recognising a chord from a three chord song with reference to another should be straightforward.
With I IV and V, if the song is on one chord, there's a 50:50 to guess with. Let's say it's on I. Choice - IV or V. both as far as each other away from I, often IV sounds like things have gone up, and V sounds like they've gone down - or up even further! On IV, choice I or V. I has gone home again, V moves only a small amount. On V, chances are it's I next (circle of fourths), or it drops a little to IV.
Use the bass, as often it's playing the root note of the chord - it's pretty well what bassists are expected to do in mainstream!
Get used to the sound of the three majors and three minors that are part of a key's family - as in C: C Dm Em F G Am. They will be the mainstay of chords for a lot of songs, as in it's a waste of time trying an F#m chord in the middle of a song in key C.  Don't worry about the 6ths, 7ths, 9ths etc yet - they all have basic triads as their foundations, so just learn to identify them as triads.
Have a go at playing the chords to simple songs without reference to written music. Most of the time, the main melody note in a bar will be part of the underlying harmony, so there's one note out of the three.
Answer: What might help:

Learn lots of songs, so you are exposed to popular chord progressions
Learn new chords, simply get a chord book and try to learn as many as you can

This way your ears get more attuned do "existing range of possibilities" which considering blues and popular music is not that wide.
Now to the method:

Find highest note first
Find lowest note
From there if you're not sure where to go, try to play to different possibilities of notes in between, try chords you already know and you might be able to identify a match

If you'll keep repeating this process and applying it to many different songs you'll for sure get better with practice.
Answer:
if you were to play me a just a single chord from that, I would have a hard time figuring it out

This may be about recognizing the chord root versus any chord tone. With groping about for any matching tone you have three tones (four with seventh chords) that you could match. But then you have to figure out which chord tone it is. I think you want to be able to identify the root.
You could do some training by playing chords then singing the various chord tones. You could start with going up the chord singing root, third, fifth. For an additional challenge you can try to pick out the third or fifth first instead of the root.
It might feel like vocal training, but it's really about trying to make your ear more sensitive to specific chord tones.
You want a more sensitive ear to go with the good tips provided in the other answers.
Comment: yeah just listen for the root because then you can add a perfect fifth on top of it, and then add either a major or minor third depending on what the chord quality sounds like.
Answer: Since you can transcribe melodies and you know about I, IV, V etc., I assume you can find what key a song is in. Excellent. And you say that you can peck away until something sounds right, which means that you hear chords at least a little bit. Excellent. You're almost there. The only thing left is practice.
The question you ask yourself when playing by ear is, "What would I have to play to sound like that?" And the palette of possible answers to try comes only from practicing. Practicing means, play songs by ear, without any visual reference material. Sing or whistle and play chords with your instrument.
Use the three chords of the major key: I, IV and V, and the three chords of its relative minor key: vi, ii and iii or usually III (major). These are enough for incredibly many pop songs. Whenever you feel that the chord might change, try the other five possibilities, almost always one of them is the right one. Repeat. You'll get better at it.
It might help to play all songs in C major / A minor, regardless of what key the original song is in.
Don't listen to only blues and rock. They often play tricks with tonality, flirting and mixing major/minor, jazzy stuff. It's better to play really syrupy pop songs which use strong chord roles to their maximum capacity. Old music. Things that your grandparents used to listen to. ;)

Chords and Progressions Ear Training


Find the Kernel and Range of a Linear Operator on $P_3$

Question: Let $L\colon P_3\to P_3$ be the linear operator defined as
$$L((p(x)) = p(0)x+p(1)\qquad \forall p \in P_3.$$
Looking for some help here. I'm close to the answer but I'm not quite getting the nuances of getting there.
Here's how I approached the problem:
$L(p(x)) = x(a + b(0) + c(0)) + (a + b(1) + c(1))= x(a) + (a+b+c)$
So, to find the Kernel set:
$a = 0$
$a + b + c = 0, or b + c = 0$

$a = 0$
$b = -c$
$c = \alpha$

So, $\alpha\,[0, -1, 1]$ is the Kernel, or $\operatorname{span}\{x^2, -x\}$. Answer says the span is $\operatorname{span}\{x^2- x\}$. How would I arrive here? Why are these answers different? Also, I'm not sure how the the $x$ multiplied by $p(0)$ comes into play. I assume it's important to the range. I guess the range is $P_2$ since there is only one vector in the kernel, but I'm not confident about these answers. Any help would be appreciated.
Comment: How do you expect help if you don't even bother telling is what are the domain and the codomain of $L$?
Comment: Sorry, updated with more info. It's a linear operator on P3.
Answer: If $P(x)=a+bx+cx^2$, then $L\bigl(P(x)\bigr)=ax+a+b+c$. So$$P(x)\in\ker L\iff a=a+b+c=0\iff a=0\wedge c=-b.$$Therefore, $\ker L$ are the polynomials of the form $P(x)=bx-bx^2$. That is, $\ker L=\langle x-x^2\rangle$.
The range is $\bigl\langle L(1),L(x),L(x^2)\bigr\rangle=\langle x+1,1,1\rangle=\langle x+1,1\rangle=\langle x,1\rangle$.
Answer: Let $p(x)=ax^3+bx^2+cx+d$ be arbitrary polynomial in $P_3$ then $p(0)=d$ and $p(1)= a+b+c+d$, then $$L(p) = dx+(a+b+c+d)$$
Say $L(p)=0$ then $d=0$ and $a+b+c+d=0$ so $c=-a-b$. So the kernel is $$\ker (L)=\{ax^3+bx^2-(a+b)x;\;a,b\in \mathbb{R}\}= span \{q(x),r(x)\}$$
Where $q(x)=x^3-x$ and $r(x)=x^2-x$


Yii CGridview hide rows

Question: I have three rows in my yii CGridview and having two type of user logins.I have to hide one of the three rows depending on the type of user.Please help.
Comment: The data for the grid view typically comes from a data provider. Modify the code that creates the data provider or its data source to behave differently based on the login type.
Answer: Use the Conditional statements like this:
public function newsearch()
{
    $id= Yii::app()->user->id;
    if($id = Your conditon){
        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        Your Criteria to display
    } else {
        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        Your Criteria to display
    }
    return new CActiveDataProvider($this, array(
        'criteria'=>$criteria,
    ));
}

And Call this dataprovider in your GridView data provider.
Answer: in your model add public static method
for example:
class Post extends CActiveRecord {

    public function tableName() {

        return 'posts';
    }

    public function rules() {

        return array();
    }

    public function attributeLabels() {

        return array();
    }

...
    public static function rulesUser() {
        if ( Yii::app()->user->id = 1 ) {
            return True;
        } else {
            return False;
    }
}

add in your gridview for row:
$this->widget('zii.widgets.grid.CGridView',
    array(
'id' => 'posts-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'emptyText' => '',
'columns' => array(
        'id',
        'title',
        'post',
        'date_create',
                    array(
                    'name' => 'status',
                    'visible' => Posts::rulesUser(),
                     )
        array(
        'class' => 'CButtonColumn',
        ),
    ),
    )
);

Comment: can you explain this a little bit more?
Comment: i must add that you have a typo.. is `if ( Yii::app()->user->id == 1 ) {`.. thanks again
Answer: or add in model
public $visible = True;

in you search add if or switch
public function search()
{
$criteria = new CDbCriteria;
     ...
    if (any if){
$this->visible = 1;
    }
return new CActiveDataProvider($this, array(
        'criteria' => $criteria,
    ));
}

in your gridview
...
array(
'name'     => 'value',
'visible'=>$model->visible,
)

...
Answer: I have solved the task by conditioning the  CDbCriteria as follows,
if(!Yii::app()->session["admin"])
{
   $criteria->condition='t.unique_id!="i-8874c6e3"';
}

Thanks all.

Yii CGridview hide rows


visual studio copy to clipboard IDE freezes

Question: this is really frustrating me. this problem occurs when I have a particularly large .cs file (one i'm working on at the moment has 6000 lines and many anonymous types).
I will copy a line or a part of text, and sometimes after copying several things to the clipboard, or sometimes even after the first copy, vs CPU usage shoots up to 50% and the IDE freezes for anything up to a minute, maybe longer. pasting happens immediately, no freezing.
if i end the devenv.exe task and restart it, usually the copying is good again for a couple of times until it starts freezing again.
i have a feeling the problem could be tied to intellisense trying to recalculate itself.. but why this happens when code is copied doesn't really make sense to me.
one thing i have found that if i copy text via the "select and drag & ctrl with the mouse" method, i avoid the problem. that is what led me to believe it may be something to do with the clipboard ring, or writing to the clipboard.
i have already tried:

SP1 installed
disabled antivirus
disabled intellisense by renaming feacp.dll (this doesn't seem to disable it at all)
disabled intellisense by unticking texteditor/c#/intellisense checkboxes (also doesn't seem to disable it at all)
disabled intellisense by unticking auto list members & parameter information (does seem to disable it)
ran a macro to remove all items from the clipboard ring - it removed them but the problem remained.

i must stress this only seems to happen as the code files get large, which is also usually due to having many anonymous types in the code.
i'm using Win7 x64 with 3gb RAM, however i had this problem on vista x64 too.
also, and i mean this in the nicest possible way, please don't take the refactoring approach. i do a lot of database work with large data sets so the anonymous types need to be there. it's my opinion that no matter how someone writes their code, this functionality of VS should work properly without freezing the IDE.
Comment: Which version of VS.Net are you using?
Answer: try this within visual studio
tools --> options --> text editor --> C#
disable Auto list members and Parameter information.
I have C# source which has more than 10,000 lines in a file and it doesnt cause any problems. Maybe its because my laptop has 4GB ram..
Comment: thanks andrew - i forgot to mention i'd tried that too, sorry!
Answer: I've come to the conclusion that it must be when one is editing massive .cs files.
I've since been working with ASP.NET MVC and haven't had this issue, and I've been using much more 'broken up' codes files.
My bad for programming design where i put 10K+ lines in a codebehind file. Yes I know, I've seen the error of my ways!
Comment: I humbly disagree with that assessment.  I came here searching for a solution because this is happening while editing a 50 line C# file, the only .cs file in this brand new console application.  (Jeez, I just saw this post is 10 years old..  still the first link for me on Google for the search, though.  Wish it were an actual solution.)  :/
Comment: What about CSS files? Mine are fairly small, the largest being 99 lines long. I am trying to update the themes for [the National Federation of the Blind's](http://www.nfbofsd.org) website, but whenever I paste a new gradient code from either [ColorZilla's Gradient Editor](http://www.colorzilla.com/gradient-editor/) or the completed Black and White theme of the website, Visual Studio 2015 freezes and stops working.
Answer: I've got this again in VS2022 no matter the file size from which I was trying to copy or how much text I was copying.
The only thing that worked was deleting the .vs folder and reopening the solution.
I've tried updating, repairing and even installing a different version of VS (enterprise, professional), disabling extensions and nothing seemed to work. Then I've realized that if I was recloning the repositories, it was working, which allowed me to narrow the issue down to the .vs folder.


Constant functions in set-theory

Question: I need some help with an exercise in set theory, which is about certain constant functions.
Let $S$ be a stationary subset of a regular uncountable cardinal $\lambda$. Given an ordinal $\alpha$, let $c_\alpha^\lambda$ denote the constant function with domain $\lambda$ and range $\{\alpha\}$.
Letting $\psi,\varphi$ range over all ordinal-valued functions with domain $\lambda$, define $$\varphi<_S\psi\mbox{ if and only if }\{\delta\in S\mid \varphi(\delta)≥\psi(\delta)\}\mbox{ is non-stationary}.$$ The relation $<_S$ is well-founded, so we can use it to define a rank $\|\cdot\|_S$ by recursion as
$$ \|\psi\|_S=\bigcup\{\|\varphi\|_S+1\mid \varphi<_S\psi\}. $$

How can we prove that, for all $\alpha\in{\rm Ord}$, $\|c_\alpha^\lambda\|_S \ge\alpha$ holds?
How can we determine the value of $\|c_\alpha^\lambda\|_S$ for all $\alpha<\lambda$?
Can we prove that $\|c_\lambda^\lambda\|_S >\lambda$?
Comment: You might want to provide a definition of $\|f\|_S$ as well.
Comment: What have you tried? Where are you stuck?
Comment: What precisely is difficult here?
Comment: $||Ψ||_S= \bigcup\ \{ ||φ||_S +1 | φ<_S Ψ\}$ is the definition of the S-rank, with S being stationary and $φ<_S ψ $ iff $ \{δ∈S|φ(δ)> ψ(δ)\} ∈ NS_λ$ (NS is the Non-stationary ideal on λ).   I just can't seem to figure out how I can determine the rank of the constant function, and thus don't know how to prove anything about it.
Comment: Do you see that $\|c_\alpha^\lambda\|_S$ is an ordinal for all $\alpha$, and can you prove that $\|c_\alpha^\lambda\|_S>\|c_\beta^\lambda\|_S$ whenever $\alpha>\beta$?
Comment: @Andrés E. Caicedo  I understand that $||c_α^λ||_S$ is an ordinal, but I do not know how to prove that $||c_α^λ||_S > ||c_β^λ||_S$ for α>β
Comment: Do you understand why $<_S$ is well-founded?
Comment: Yes, I proved it already via contradiction and using AC
Comment: Well, then use the definition to show that $\|c_\alpha^\lambda\|_S>\|c_\beta^\lambda\|_S$ whenever $\alpha>\beta$. It should be trivial.
Comment: Ok, I proved it...but I still don't know how I can use this to solve the problem
Comment: In your question, are you sure the last $\ge$ is not actually meant to be $>$? That is, shouldn't the last part of your question be asking to check whether $\|c_\lambda^\lambda\|_S>\lambda$?
Comment: Oh, yes indeed. Thank you, I made that small typo...
Comment: In your definition of $<_S$, are you sure you did not mean $\{\delta\in S\mid \varphi(\delta)\ge\psi(\delta)\}$ is non-stationary?, i.e., with $\ge$ instead of $>$?
Comment: Can you prove that if $\alpha<\beta$ then $c_\alpha^\lambda <_S c_\beta^\lambda$? Then the main claim would follow by a dead-simple induction on $\alpha$.
Answer: Note that $\alpha\mapsto\|c_\alpha^\lambda\|_S$ is strictly increasing (trivially): After all, $$\{\delta\in S\mid c_\beta^\lambda(\delta)\ge c_\alpha^\lambda(\delta)\}=\{\delta\in S\mid\beta\ge \alpha\}=\emptyset$$ if $\beta<\alpha$. This immediately gives that $\|c_\alpha^\lambda\|_S\ge\alpha$ for all $\alpha$.
Suppose now that $f<c_\alpha^\lambda$. This means that $\{\delta\in S\mid f(\delta)\ge \alpha\}$ is non-stationary, or, what is the same, $f(\delta)<\alpha$ for almost every $\delta\in S$. If, in addition, $\alpha<\lambda$, then in fact $f(\delta)<\delta$ for almost every $\delta\in S$. Use Fodor's lemma to conclude that $f$ coincides with some $c_\beta^\lambda$ for some $\beta<\alpha$ ("coincides" in the sense of $=_S$, where $f=_S g$ implies in particular that $\|f\|_S=\|g\|_S$). This should give you that $\|c_\alpha^\lambda\|_S=\alpha$ for all $\alpha<\lambda$.
Finally, check that the identity map is above all $c_\alpha^\lambda$, $\alpha<\lambda$, and below $c_\lambda^\lambda$.
Comment: Thank you very much!   Just one more question: Why is the identity map below $c_λ^λ$? I don't understand this point
Comment: Use the definitions, it is just as immediate as the other properties we discussed in the comments above.

Constant functions in set-theory


Grid search error in LIBSVM while optimizing C and g parameters

Question: I am using libsvm for a one-class classification problem. I am trying to select the ideal C and gamma parameters for different kernels(polynomial, linear and rbf) I am using the suggested matlab code that finds the the best parameters through a v-fold validation technique.
bestcv = 0;
for log2c = -1:3,
  for log2g = -4:1,
    cmd = ['-v 5 -c ', num2str(2^log2c), ' -g ', num2str(2^log2g)];
    cv = svmtrain(Target_train, train, cmd);
    if (cv >= bestcv),
      bestcv = cv; bestc = 2^log2c; bestg = 2^log2g;
    end
    fprintf('%g %g %g (bestc=%g, g=%g, rate=%g)\n', log2c, log2g, cv, bestc, bestg, bestcv);
  end
end

In v-fold cross-validation, we first divide the training set into v subsets of equal size. Sequentially one subset is tested using the classifier trained on the remaining v − 1 subsets. Thus, each instance of the whole training set is predicted once so the cross-validation accuracy is the percentage of data which are correctly classified.
In this code, the C and gamma take values in a range of (2^-1, 2^3) and (2^-4, 2^1)
I noticed that when the svmtrain function is called there is no specified parameter for -s which controls the the type of svm. The default parameter for -s in libsvm is 0 which is for C-SVC. I have a one-class clssification problem so I should be using -s 2 according to svmtrain options. However when I modify the 4th line of the above code into
cmd = ['-s 2 -v 5 -c ', num2str(2^log2c), ' -g ', num2str(2^log2g)];

I am getting this error:
Undefined function 'ge' for input arguments of type 'struct'.
Error in ergasia (line 37) if (cv >= bestcv),
For what I know, svm returns a model of type struct. My question is, is the code I am using suitable for parameter selection in a one class classification problem?
An other question: Is there a better way of defining the best C and gamma other than that? I found this method here: http://www.csie.ntu.edu.tw/~cjlin/papers/guide/guide.pdf
I could really use some help with that so thank you in advance.
Answer: The output of cross-validation with LIBSVM is a score. LIBSVM's internal cross-validation uses accuracy as score metric, which is known to be suboptimal for model selection. It would be better to use a measure like area under the ROC curve (which you can compute using perfcurve if you have the statistics toolbox). Your code seems okay at first glance, except that one-class SVM uses the nu parameter, not C.
You could use specialized libraries like Optunity to do the hyperparameter tuning for you. It offers more efficient routines than grid search to optimize hyperparameters (e.g. which require less parameter pairs to be tested) and has built-in cross-validation with score metrics of your choosing so you don't have to bother implementing it yourself. Optunity is available in MATLAB (example).
Disclaimer: I'm the main developer of Optunity.
Comment: Thank you for your answer. I am definetly going to check Optunity. However, this is a university assignment so I am not allowed to use any software other than LIBSVM, let alone I am required to write my own code for this specific task.
Comment: So the nu replaces c parameter in one-class svm?


Reducing modulo equations

Question: How do I reduce the following and remove the $11$ from LHS,
$$
11x \equiv 4 \ \ \text{mod }50
$$
Comment: Do you know when is a number invertible $\pmod{n}$? That is, for which $a$ one has some $b$ such that $ab = 1 \pmod{n}$?
Comment: Observe that $11 \times 9 \equiv -1$ (mod 50).
Answer: $11x = 50k +4$
Multiplying the equation by 9,
$99x = 450k + 36$
$-x = 50(9k - 2x) + 36$
$x = 50(2x - 9k -1) + 14$
$x \equiv 14 \pmod {50}$
Answer: Variant using the particularity of multiplication by $11$.
Generally $11\times \overline{ab}=\overline{asb}=100a+10s+b\, $ where $\, s=a+b$ (provided $s<10$).
Notice that when $s=5$ we have $\begin{cases}100a\equiv 0\pmod {50}\\10s\equiv 0\pmod{50}\\11\times \overline{ab}\equiv b\pmod{50}\end{cases}$
Since we want $b=4$ then $a=1$ is forced and $$11\times 14\equiv 4\pmod{50}$$
Note that it works too for finding the inverse of $11$ (this time $b=1$ and $a=4$), thus $11^{-1}\equiv 41\pmod{50}$.

Reducing modulo equations


How to divde two rows from different Dataframes in Python pandas which contain string and float.

Question: I have 2 dataframes I need to divide the value from 2 data frame which divide contain string and float the division should avoid the string and only do the division on float.

DF1

       Col1     Val11   Val12
    0  A        1       9
    1  B        3       1
    2  C        5       4
    3  D        1       3
    4  E        7       6

DF2

       Col2    Val21    Val22
    0  A       20       19
    1  B       35       11
    2  C       46       42
    3  D       31       53
    4  E       28       55

I wrote the below line of code
df2.iloc['Percent'] = df1.iloc[4]/df2.iloc[4]

But I get the below error message.

TypeError: unsupported operand type(s) for /: 'str' and 'str'

Final DF should look like this
       Col2    Val21    Val22
    0  A       20       19
    1  B       35       11
    2  C       46       42
    3  D       31       53
    4  E       28       55
               0.25     0.10

Thanks and Advance for the support
Answer: You need get all string columns to index by set_index and then divide:
df2 = df2.set_index('Col2')
df2.loc['Percent'] = df1.set_index('Col1').iloc[4].values / df2.iloc[4]
print (df2)

         Val21      Val22
Col2
A        20.00  19.000000
B        35.00  11.000000
C        46.00  42.000000
D        31.00  53.000000
E        28.00  55.000000
Percent   0.25   0.109091

If there is multiple string columns use subsets of columns for divide and also add subset to output:
df2.loc['Percent'] = df1[['Val11','Val12']].iloc[4].values /  df2[['Val21','Val22']].iloc[4]
print (df2)
        Col2  Val21      Val22
0          A  20.00  19.000000
1          B  35.00  11.000000
2          C  46.00  42.000000
3          D  31.00  53.000000
4          E  28.00  55.000000
Percent  NaN   0.25   0.109091

More generic solution:
str_cols1 = ['Col1']
str_cols2 = ['Col2']
df2.loc['Percent'] = df1.drop(str_cols1, axis=1).iloc[4].values /
                     df2.drop(str_cols2, axis=1).iloc[4]
print (df2)
        Col2  Val21      Val22
0          A  20.00  19.000000
1          B  35.00  11.000000
2          C  46.00  42.000000
3          D  31.00  53.000000
4          E  28.00  55.000000
Percent  NaN   0.25   0.109091

And better solution with select_dtypes:
df2.loc['Percent'] = df1.select_dtypes(['number']).iloc[4].values /
                     df2.select_dtypes(['number']).iloc[4]
print (df2)
        Col2  Val21      Val22
0          A  20.00  19.000000
1          B  35.00  11.000000
2          C  46.00  42.000000
3          D  31.00  53.000000
4          E  28.00  55.000000
Percent  NaN   0.25   0.109091

EDIT by comment:
Use to_numeric for replace non numeric values to NaN:
df1_numeric = df1.apply(lambda x: pd.to_numeric(x, errors='coerce'))
df2_numeric = df2.apply(lambda x: pd.to_numeric(x, errors='coerce'))

df2.loc['Percent'] = df1_numeric.iloc[4].values / df2_numeric.iloc[4]
print (df2)
        Col2  Val21     Val22
0          A  20.00        19
1          B  35.00         a
2          C  46.00        42
3          D  31.00        53
4          E  28.00        55
Percent  NaN   0.25  0.109091

Comment: Since this was an example I used only one string column. If I have multiple string columns will this solutions work ?
Comment: I add another solution, please check it.
Comment: Just in case the column names are too many it may not be feasible to write all can there be a generic solution ?
Comment: Say 3 string Columns and 14 numeric Columns
Comment: Please check last edit. Simply remove string columns and then divide.
Comment: Yes it also work thank you as some string cols are in between the values.
Comment: This string values between numeric values are in multiple columns?
Comment: 3 columns 2 at start and one is second last
Answer: Try this out:
df2.loc['Percent'] = df1.iloc[4, 1:] / df2.iloc[4, 1:]

Comment: Yes its also working. Thank you just one doubt what is the significance of 1: in the code.
Comment: Does it put the data in the correct columns though? I was not 100% sure of this answer ... The 1's are there to select columns from #1 to the end (i.e. skip the first one which is a string - that is what caused your problem)
Comment: oh..okay let me verify


Integrating external computer into a domain - some recommendations please

Question: Given:

A multi location company. Every office has local routers that connect to a central VPN capable router in a data center.

All fine so far. We now need to move a computer off site into a hosting center across the globe, to get it closer to some supplier computers we work for. it will run limited logic but latency is important, and our latency so far is too large.
This computer will be in a data center and does not require incoming connections except for administrative purposes, although it needs outgoing connections. I have no real chance to put one of my VPN routers there, sadly - otherwise I would have no problem. Usage of RRAS is not recommended (we had various probblems there over time). I could deal with it. The computer MUST integrate into the corporate structure via VPN and join the domain and be fully "tracked" (controlled for performance).
What is the best suggestion? So far it looks like my best bets would be to log in via RRAS and deal with whatever issues arise there plus use the local firewall the limit incoming connections to this computer to what is needed (which runs down to an emergency RDP connection allowance). Anyone a better idea?
Comment: What type of VPN is the router using?  Can't you just configure the computer to connect to that VPN directly?
Comment: I can handle pretty mjuuch every typ eof VPN (it is a Mikrotik router). I could set up direct connection to the company networks (i.e. the computer dials in), but somehow I dont have the best experience with windows RRAS...
Comment: RRAS is the VPN server, which I don't think would be involved here.  You'd need to setup the client on the remote server, but that does not make use of RRAS.
Comment: Time to give it a try.
Comment: Hmm perhaps you should check with the datacenter folks if they can create a VPN to that segment to your Microtik for you - I have found that our co-locators are more than happy to do that kind of thing...
Answer: Have a check to DirectAccess technology:
http://www.microsoft.com/en-us/server-cloud/windows-server/directaccess.aspx
Comment: Ok, fixed with server 2012 ;) Doing ;)
Comment: Requires to my knowledge iinternal use of IpV6 which we do not ahve at the moment. IT is also not able to be done for the moment due to router limiatations - which wil lbe handled in one of the next major releases, but that is a year away in the worst case.
Comment: no it runs also on ipv4 by encapsulating ipv6 into ipv4. Read here: http://technet.microsoft.com/en-us/library/dd734591(WS.10).aspx
Comment: Yes, but it does reqquire to use an internal IPV6 network. I can not movy my internal invfrastructure over at the moment. Need to wait another 1-2 releases of the router firmware for some missing features.
Answer: I'd set it up to use OpenVPN to connect back to your Mikrotik.  You can set it up as a boot service.
I do something similar with a hosted machine outside of our network.  Much better than mucking around with RRAS in my experience.
OpenVPN at startup
Comment: -1. Why should I set up OpenVPN when WIndows has compatible VPN technologies already on board? RRAS at least gets maintained by MS - no additional searchng and updating.


Do RNNs adjust memory during prediction/forward pass?

Question: Let's say i train a RNN to predict some curve given only 1 timestep as input. So the input is x(t) and the target is x(t+1). On the next timestep the input is x(t+1) and the target is x(t+2) and so on. During training it can memorize the inputs from previous timesteps and thus make more accurate predictions and afterwards the RNN can accurately predict the curve.
What i don't understand: If i have finished training and start predicting on a random point on the curve, how can the RNN predict anything? The memory it has is from the training data and maybe we stopped training when the curve was going up, but now we are predicting somewhere where it goes down. Is the RNN able to adjust its memory during prediction? So we could let it run for say 10 timesteps by using the available data and afterwards it can start using the predictions as input again?
If the question is unclear feel free to tell me and I will try to make it clearer.
ps: I asked the same question on reddit but haven't gotten an answer so far.
Answer: Usually, we start off each sequence with a special input. This will allow the RNN to initialize it's memory cells. Then, it can generate as many new samples as you want starting from the start state.
The memory cells do not carry over from training time to test time. The model learns the properties of the training data and encodes it into the parameters of the RNN, not the memory.
Answer: You feed the model a sequence of inputs at test time and let it finish it, rather than just one input. Take for example a model trained on text. If you just give it the letter "t", the next letter could really be almost anything. But if you give it the letters "this pie is goo" it will be likely to predict the next letter being "d". And the same goes with a curve.
Answer: Yes, you should refeed the predictions if you want to predict further into the future. However, with a one delay only model you'll never be able to detect/predict ups and downs. This is because a NN with only one input is simply a logistic regression (if you use sigmoid) and therefore is a linear model, so predictions will either go up, down or straight. You'll need at least two inputs if you want your NN to detect ups and downs, because then maybe up-down predicts down again, down down predicts up and so on. I'm simplifying here, but I hope you get the picture.


Beginning PHP (loading DIV)

Question: I'm just diving into PHP and have been doing some reading and playing around - with my code below, I'm trying to load the pages (as you can see) - I'm getting parse error. Syntax error, unexpecter T_VARIABLE in index.php on line 7
Line 7 on my index
<?php include(''$id'') ?>

I'm told is supposed to be for variables rather than ('$id')
When I use ('$id') or ('$nav_menu') as is in the current coding, it gives me failed to open stream: No such file or directory
I'm probably missing something blatantly obvious, but can someone point me in the right direction?
Thanks
<?php
if (is_numeric($_GET['id'])) //prevent hacking
{
switch ($_GET['id']) //get the id of menu needed for this page
{
case 0:
    $nav_menu = "content.php"; //if the variable is 0 or not set
    break;
case 1:
    $nav_menu = "bio.php"; //if the variable is 1, get category 1 links
    break;
case 2:
    $nav_menu = "contact.php"; //if the variable is 2, get category 2 links
    break;
default:
    $nav_menu = "content.php"; //redundant for defaulting if the id is greater than 2
}
}
?>

Comment: @frits van Campen Yeah! you're right (I tried it works =D)
Comment: Btw why do you ever want to use 2 pairs of single quotes around the $id variable?
Comment: @luca When you want to include the file '$id.php' ? :D It probably works on a Mac!
Comment: Awesome! :D +1 for actually trying
Answer: <?php include($id); ?>

no quotes.
Also, make sure you check the value of $id, you wouldn't want someone including "../../path/to/my/passwords.txt" or something equally unnerving ;)
The switch-case statement you have for $nav_menu is crude but effective and most certainly required.
Also, I'm pretty sure switch is safe so no need to check is_numeric on $_GET['id']
Edit: Jared mentioned relative vs absolute paths. I have no idea what he's saying but this is what I think about it:
Always always always always always always always always always always always always always always always always always always always always always always always always always use:
include (dirname(__FILE__) . "/thefile.ext");

this will always make your path without a doubt absolute.
Answer: There is no need to use quotes around a variable, but if you do, make sure you use " instead of ''. You could try:
<?php
include($id);
include($nav_menu);
?>

17 lines code could be shortened into two. You could use it instead:
<?php
$list = array("content.php", "bio.php", "contact.php");
$navmenu = (isset($_GET['id']) && isset($list[$_GET['id']]) ? $list[$_GET['id']] : 'content.php';
?>

Answer: You're doing four things wrong here.
First, you need semicolons at the end of each statement.
<?php include(''$id''); ?> // Note semicolon

You should have only one quote on either end of an inline string statement, with the other's escaped, ie:
<?php include('\'$id\''); ?> // Valid string

Now, if you want to expand that variable, you need to either use a double-quoted string or use a . concatenator. In this case, you don't need a quote around it:
<?php include("$id"); ?>
<?php include($id); ?>

Last, you should be giving the relative/absolute path to a file to include.
<?php

$path = "myinclude.php";
$path = "../includes/myinclude.php";
$path = "/web/my_site_com/includes/myinclude.php";

include($path);

?>

If you're using the switch to activate a particular file, you could do this with a double-quoted string:
<?php

$path = "../includes/$id";

include($path);

?>

Beginning PHP (loading DIV)


Users field manually delete from database cache problem

Question: i manually remove  a column of field_data_field_about in database belongs to some users. and this field is user field. And after in admin panel i edit this user which i delete this user column from database. But this user about value is shown there. Then i Clear All Caches then i come back to edit this user the about value is gone.
How can i disable cache for users fields?
Answer: I'm really not sure why you'd want to remove a column from a field table but just looking at your problem as is, a way by which you can disable caching of field values in the cache_field bin is by letting Drupal know that you don't want values for the field instances attached to a given entity type to be cached at all.
You can do this by implementing hook_entity_info_alter() from a custom module and setting the field cache key for the user entity as shown below:
function mymod_entity_info_alter(&$info) {
  $info['user']['field cache'] = FALSE;
}

You might find the documentation of hook_entity_info here useful. You might also want to lookup the definition of field_attach_load() from here.
Comment: users has mobile field and i send sms to this mobile number when users reset this or delete this number in admin i edit this user but the mobil number not gone when i clear cahche the mobile number is gone. İs this a problem or not?
Comment: should i disable cahce for this field or not disable it i don't know.
Comment: in my second comment i want to say users modify number on their profile after i'm admin in admin panel i test this user if number is gone.


Is there UI to manage ASP.NET Identity users/roles compatible with ASP.NET 5?

Question: I'm using:

VS2015u2
ASP.NET 5
MVC 6

I'm looking for some UI to manage users/roles.
Some things I've tried:

Identity Manager - https://github.com/IdentityManager/IdentityManager
I guess it's still not compatible with the latest asp changes.
Comment: Seems everybody make proprietary solutions for this :)
I'll try to have a look at IdentityManager (which is for Identity 2) - is it possible to port it to Identity 3/.Net Core...
Comment: Anyone find something for .NET Core 2.0?
Comment: Take a look at https://github.com/mguinness/IdentityManager and see if that suits your needs.
Comment: Any findings on this? :)
Comment: Are you looking for a tag or statement that allows you to hide elements depending on your role? Or just to add, edit and delete roles / permissions?
Comment: Just add/edit/delete users/roles.
Comment: Have you found something?
Comment: Nothing yet. Please update if you find something.
Comment: I am also looking for something for MVC, @johnny .NET Core 2.1 has the Identity UI which is in preview mode , but looks promising: https://blogs.msdn.microsoft.com/webdev/2018/03/02/aspnetcore-2-1-identity-ui/
Comment: For ASP.NET Core Identity, following repo may be helpful - https://github.com/mguinness/IdentityManagerUI
Answer: Recently, I tested the ASP.NET Web Application template with Individual Authentication and it worked fine with ASP.NET 5.
It is a Razor Pages Library, that you can scaffold if you need to edit the code as detailed here in the documentation: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-5.0&tabs=visual-studio
This is the relevant part:

The code in this case is Razor Pages instead of MVC, but you can have both in the same project as far as I understand, and migrating from Razor Pages to MVC should be fairly simple as stated in this GitHub discussion: https://github.com/aspnet/Identity/issues/1825#issuecomment-396342979
Answer: Please check out ASP.NET MVC 5 Security And Creating User Role
https://code.msdn.microsoft.com/ASPNET-MVC-5-Security-And-44cbdb97
Hopefully this is what you're looking for.
Answer: If you want get all of roles and users with UI to manage asp.net Identity.
Try to make new blank asp.net MVC project. Make sure do not click Individual User Account. Then go to Package Manager Console and hit following query on console.
<code>Install-Package Microsoft.AspNet.Identity.Samples -Version 2.2.0-alpha1
</code>
This package contains an asp.net MVC application which shows you how to use the features in asp.net Identity. Also compatible with asp.net. You should check default role and users once you connect database with ApplicationDbContext.


How should I write chord diagrams in text form, if they use two digit fret numbers?

Question: I'm used to notating chords in text form, such as E major being 022100 or A major being x02220, but what happens when you are using two-digit frets?
For example, in DADGBE tuning you can play A and Dm on the 9th and 10th frets:

Here, I have to use the fret numbers 10 to 12. How do I do this?
Comment: @Tim if I wanted 002220 I'd write A/E
Comment: So what's wrong with A major being 002220?! Why not put a hyphen between string/fret nos?
Answer: I guess this notation simply doesn't work. You could be creative and do slight modifications, for example: X-0-11-9-10-12,  X0(11)9(10)(12), X/0/11/9/10/12. I guess all these would be universally understandable in the context. I've never seen a standard notation in this case.
Comment: one more option would just be spaces: x 0 11 9 10 12.  above options are also good. just be consistent.
Comment: @b3ko the problem would be how to separate one chord from another maybe?
Comment: ah yeah, good point. i guess it depends on the overall structure. will this be part of a lead sheet, or just by itself, unclear.


How would I store a reference in a custom FieldType in Drupal 8?

Question: I am developing a module for Drupal 8 and want to make a field on one entity that references another along with some additional data. e.g. Library A has a copy of Book B (of Edition 2). There will be multiple values stored in the field for each source entity. In the above example Libraries will have multiple books.
I know how to implement a new FieldType and the widget and formatter for it, but I am wondering whether this is the best way for a reference. Would it be better to create a new entity to hold the relationship with the two endpoints and additional data (like I would create an xref table in MySQL)
If I do go with a FieldType, when it comes to implementing the storage of the new field, would I just store the id of the referenced entity and then have to wrap the access in a method to change id <-> entity?
Thanks in advance for your help!
Jamie
Answer: So you're actually asking two questions.

Should I use a field type or a relation?

Both works. Field type requires much less storage (everything is in the field table), but it's hardcoded to one specific use case. The alternative is basically https://www.drupal.org/project/relation or you could also use something like https://www.drupal.org/project/paragraphs, https://www.drupal.org/project/field_collection if you only have a source -> target reference (relation can to n-n references). For all, you'd create a relation/paragraph/collection type with your additional fields. More flexible, can be configured and doesn't require custom code, but each  reference is another entity that has to be stored and loaded.
You will have to decide what's better for your case, depends on performance vs. flexibility requirements, how many variations (you probably don't want to create 10 field types..) and so on.

If a field type, how do I create it.

That's actually fairly easy in Drupal 8. You just extend from the default entity reference field type (EntityReferenceItem), override methods like schema() and propertyDefinitions() to define what properties you have and how they are stored. Then you write a widget and formatter for it, extending from the widget/formatter that's closest to what you want (e.g. autocomplete or select for the reference selection).
The advantage is, all the actual reference things will just work through the parent classes, you just have to implement your additional properties.
Comment: Thank you! Your name seems to pop up all over the place while I've been learning Drupal... It's great to see someone willing to help us noobs get our heads around it!


Buttons not showing up in JPanel

Question: I'm having a ton of trouble figuring out why the buttons in this won't show? They were showing up earlier today when I test ran the program but now I've been stuck for 2 hours trying to get the buttons to show up again. It's also really weird because the panel is definitely showing up because the phrase "Welcome to the BookListApp" is showing up.
    public BookListUI() {
        textPrompt.setText("Welcome to the BookListApp, fellow bookworm. Start storing your books immediately!");
        textPrompt.setBounds(WIDTH / 2 - 300, 50,500,100);
        frame = new JFrame();
        panel = new JPanel();

        panel.setLayout(null);
        panel.setSize(WIDTH, HEIGHT);
        panel.add(textPrompt);
        addButtons();
        frame.setSize(WIDTH, HEIGHT);
        frame.add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("BookList Application");
        frame.setVisible(true);

    }

    public void addButtons() {
        panel.add(new JButton("Finished books"));
        panel.add(new JButton("Favorite books"));
        panel.add(new JButton("Search by genre"));
        panel.add(new JButton("Save all your books!"));
        panel.add(new JButton("Load your BookList Application"));
        panel.add(new JButton("Exit application"));
    }

    public static void main(String[] args) {
        new BookListUI();
    }

Comment: The problems start here: `panel.setLayout(null);`. Fix that using layouts before wasting any more of your time or asking us to waste ours.
Comment: .. `generalInfo` would be more accurate. 5) `addButtons()` - consider adding them (or the corresponding `Action` elements) to a `JToolBar` instead.
Comment: General tips: 1) [Edits] to add a [mre]. 2) Provide ASCII art or a simple drawing of how the GUI is expected to appear at both default size and when made larger. 3) `panel.setSize(WIDTH, HEIGHT); .. frame.setSize(WIDTH, HEIGHT);` The best than can be said of this is that the panel size will be ignored. One or both of the sizes is wrong, as a panel cannot be was big as the frame that displays it. It's better to `pack()` a frame to the right size for the content it displays. If the GUI uses layouts, that size will be suggested automatically.  4) `textPrompt` is poorly named. ..
Answer: Use one or more appropriate layout managers.  See Laying Out Components Within a Container
 for more details

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class BookListUI {

    JLabel textPrompt = new JLabel("Welcome to the BookListApp, fellow bookworm. Start storing your books immediately!", JLabel.CENTER);

    public BookListUI() {
        JFrame frame = new JFrame();

        JPanel contentPane = new JPanel(new BorderLayout());
        contentPane.setBorder(new EmptyBorder(32, 32, 32, 32));
        frame.setContentPane(contentPane);

        frame.add(textPrompt, BorderLayout.NORTH);
        JPanel menuPane = new JPanel(new GridLayout(-1, 1));
        menuPane.setBorder(new EmptyBorder(32, 32, 0, 32));
        addButtons(menuPane);
        frame.add(menuPane);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setTitle("BookList Application");
        frame.setVisible(true);

    }

    public void addButtons(Container container) {
        container.add(new JButton("Finished books"));
        container.add(new JButton("Favorite books"));
        container.add(new JButton("Search by genre"));
        container.add(new JButton("Save all your books!"));
        container.add(new JButton("Load your BookList Application"));
        container.add(new JButton("Exit application"));
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new BookListUI();
            }
        });
    }
}

Answer: If you use an absolute layout (panel.setLayout(null);) then you have to specify the bounds of the buttons to be visible:
button.setBounds(200, 200, 300, 30);

Comment: While not 'incorrect', this is a very poor way to layout a GUI and will result in many problems and lower the maintainability of the code. Until you understand how poor the advice is for cross-platform GUIs, please refrain from giving any more.
Comment: Yes, but he/she asked why the buttons were not visible, not asking for layout advice.
Comment: *"Yes, but.."* See [Is "Don't do it" a valid answer?](https://meta.stackexchange.com/q/8891/155831) Maybe if your answer had started, *"this is both one possibility, and also the worst way to do it"*. I might have up instead of down voted it.

Buttons not showing up in JPanel


Phonegap-nfc plugin causes build to fail on xcode

Question: I am using ionic 5 capacitor and i am trying to get phonegap-nfc plugin to work. It works fine on android but while building with xcode building fails.
Steps to reproduce with fresh project (selected Angular framework when it was asked):
ionic start myApp blank --capacitor
cd myApp
ionic build
ionic capacitor add ios
npx cap open ios

It opens in xcode and i can build and run project on simulator just fine. Then i install phonegap-nfc plugin:
npm install phonegap-nfc
npm install @ionic-native/nfc
ionic cap sync

When i try to build again i receive semantic issue with cordovaplugins. There are 5 errors in NfcPlugin.m file saying 'new' is unavailable with note saying 'init has been explicitly marked unavailable here. How to fix this issue?
Some version info of my system:
Xcode version: 12.5 (12E262)
macOS version: Big Sur 11.3
node version: 16.0.0 (also tried with 10.16.0)
npm version: 7.10.0
Screenshot of xcode errors
Answer: I will answer my own question as i happened to find solution. I dont what is broken in xcode 12.5, but uninstalling xcode 12.5 and installing xcode 11.7 i was able to build succesfully and scan NFC tags.
Comment: @KrishanPatel have look at https://github.com/chariotsolutions/phonegap-nfc/pull/451/commits/0c1b3c09d6f056e5f4a2124e6cbc7a50ee935436. You just have to replace new with alloc
Comment: please don't mark this as solved, I would like to know why this is broken as I am having the same issue!
Comment: I wont mark it as solved because it is more like workaround than actual solution. I got it working with xcode 12.2 too. I think for new ios apps xcode 12.x is needed for publishing app to store. I havent tried other version between 12.2 and 12.5.


como retorna array pata html via ajax/php

Question: eu tenho a função abaixo no arquivos functions.php
function get_ADRESS(){
    if(isset($_POST['getcep']) and $_SERVER['REQUEST_METHOD'] == "POST"){
        $cep = escape($_POST['cep']); //10
        $cep = preg_replace("/[^0-9]/", "", $cep);
        $url = "http://viacep.com.br/ws/$cep/xml/";
        $xml = @simplexml_load_file($url);
        echo $xml;
    }
}

}
$XML é uma matriz que me retorna cep, rua, uf, número. O que eu preciso eh rodar a funcao get_endereco na página register.php e depois informar esses valores no HTML abaixo, como consigo fazer isso ?

    <input type="text" class="form-control" placeholder="Endereço" id="cep_load" name="cep_load" value="{$cep}">

    <input type="text" class="form-control" placeholder="Endereço" id="address" name="address" value="{$rua}">

     <input class="form-control" id="city" name="city"  placeholder="Cidade" value="{$cidade}" >

Answer: Vamos ter 1 arquivo chamado getAdressAjax.php
<?php
require 'function.php';
get_ADRESS();
?>

*(vou supor que seu projeto usa JQuery) **(segue exemplo) Neste caso a requisição só é chamada quando o usuário tira o focus do campo 'cep_load'.
$('#cep_load').blur(function(){
    $.ajax({url: "getAdressAjax.php", success: function(result){
        $('#address').val(result.endereco);
        $('#city').val(result.cidade);
    });
});

Caso use Javascript puro apenas segue exemplos
Buscando "ajax example" no google você já acha muita coisa BOA.
Comment: Bartomeu, Muito obrigado msm! Abs


Is there at least one $n_0 \in \mathbb N$ for which this associated sequence produces an infinite number of primes?

Question: As there is much freedom in ways in which we can form number sequences and ask questions about them I defined the sequence of numbers associated to every natural number in this way:

Choose some natural number $n$. Add its digits in base $10$ and concatenate them with chosen number so to put them to the left to form a new number. Do the same with new number. And so on and so on...

To clarify let us add an example:
Choose, for example, $n=13$. Then $DS_{10}(13)=1+3=4$ and we get a new number $413$. Now we get $DS_{10}(413)=4+1+3=8$ and we obtain $8413$ and after that $168413$ and so on... It is obvious that we can do this with every natural number to obtain an infinite sequence $d(n)$ associated to every $n \in \mathbb N$.
The question is:

Is there at least one $n_0 \in \mathbb N$ such that $d(n_0)$ has an infinite number of prime numbers in itself?

Also, computational efforts are highly welcomed.
Comment: Regarding @M.Winter observation, if you start with a number which is not divisible by $2$ or $5$, then you will never end up in a number divisible by one of those.
Comment: Some observation: as soon as a number in your sequence is divisible by $2$, $3$ or $5$, all following number will be too. So no more primes can occur.
Comment: @DarielRudt Same seems to holds for $3$. The digit sum of a number $n$ is $\equiv n$ modulo $3$. So the sequence $d(n)$ will look like $1,2,1,2,1,2,...$ modulo $3$.
Answer: I'm afraid that, as these numbers grow super fast, it's going to be difficult to simulate the process for large input. However, I did some computational effort, and this is the result for all the primes below $25000$ (it took 2.5 minutes to compute this).
The longest chain was of six numbers:
<code>We try with 4021
We try with 74021
We try with 1474021
We try with 191474021
We try with 29191474021
We try with 40029191474021
4021 lasted 6
</code>
Despite I didn't use the best (most efficient) algorithm to do the primality test, the difference would not be worth the effort.
Comment: +1. Can you check, for example, every number below 25000 by calculating its first, say, 20 concatenations, and then see which one will hold the record for the number of primes in first 20 concatenations? See the comment of @M. Winter : "Some observation: as soon as a number in your sequence is divisible by 2, 3 or 5, all following number will be too. So no more primes can occur" so that you do not need to check all the numbers.


Pullback of a flat module is flat

Question: Let $f\colon (X,\mathcal{O}_X)\rightarrow (Y,\mathcal{O}_Y)$ be a map of ringed spaces.
In the Stacks Project, in the proof of Tag 09U8, they basically claim at some point, that for any flat $\mathcal{O}_Y$-module $\mathcal{F}$ its pullback $f^*\mathcal{F}$ is also flat.
Now they do link to a proof of this result, but in that linked statement they assume $f$ to be a flat morphism.
So if $f$ is flat, that the statement is clear, but does it also hold for an arbitrary $f$?
Answer: The trick is that you can change what $\mathcal{O}_X$ is to get a flat morphism. Let $X'=(X,f^{-1}\mathcal{O}_Y)$, which is flat over $Y$, as $(f^{-1}\mathcal{O}_Y)_x\cong\mathcal{O}_{Y,f(x)}$ and the induced map $\mathcal{O}_{Y,f(x)}\to\mathcal{O}_{Y,f(x)}$ is an isomorphism. Writing $$f^*\mathcal{F} \otimes_{\mathcal{O}_X} \mathcal{G} \cong f^{-1}\mathcal{F} \otimes_{f^{-1}\mathcal{O}_Y} \mathcal{O}_X \otimes_{\mathcal{O}_X} \mathcal{G} \cong f^{-1}\mathcal{F}\otimes_{f^{-1}\mathcal{O}_Y} \mathcal{G}$$ for $\mathcal{G}$ a sheaf of $\mathcal{O}_X$-modules, we see that pulling back to $X$ is equivalent to pulling back to $X'$ on the level of sheaves of abelian groups, and $X'\to Y$ is flat, so we can use the result.
This is essentially covered at the last statement (0GMU) in 02N2, but it could be added to the lemma you're reading to make it a little clearer, perhaps.
Comment: Ah i see, now i know how to finish the proof, thanks. However i think in the middle of the equation we should replace $\mathcal{O}_Y$ with $\mathcal{O}_X$.
Comment: Typo corrected, thanks for pointing it out.

Pullback of a flat module is flat


Convergence of $\int_0^\infty \frac{\log x}{1+x^p}\ dx$

Question: For which values of $p$ does the improper integral $$\int_0^\infty \frac{\log x}{1+x^p}\ dx$$
converge? I tried integration parts and various tricks, but it does not seems to work.
Thanks
Comment: Comparison. The integrand is continuous on $(0,+\infty)$, so the questions to be answered are: how does it behave at $0$ and how at $+\infty$?
Comment: As $x\to 0$, the denominator is almost $1$, hence you are integrating something comparable with $\log x$: $\int_0^1 \log x dx $ does not give problems. So as Daniel Fischer said, you should check for $x\to +\infty$. (use the fact that $\int_1^\infty x^p dx<+\infty$ iff $p<-1$).
Answer: We have
$$\int_0^\infty\dfrac{x^{\large a-1}}{1+x^b}\ dx=\frac{\pi}{b}\csc\left(\frac{a\pi}{b}\right)$$
for $0<a<b$. Differentiating with respect to $a$ then setting $a=1$ and $b=p$, we get
$$\int_0^\infty\dfrac{\ln x}{1+x^p}\ dx=-\frac{\pi^2}{p}\csc\left(\frac{\pi}{p}\right)\cot\left(\frac{\pi}{p}\right)$$
for $p>1$.


Wielandt's proof of Sylow's theorem.

Question: Let $|G|=p^{n}m$, and let $0\leq k\leq n$. Then the number of subgroups of $G$ of order $p^k$ is congruent to $1$ modulo $p$.
I know Wielandt's proof in the case $k=n$, which is standard, but I dont know how to use that proof to prove this above modification. Clearly the set $S$ on which we should make $G$ act by left multiplication has to be the set of all subsets of size $p^k$ and then we know that $\displaystyle \binom{p^{k}r} {p^{k}}$ is congruent to $r \bmod p$. But somehow using the Orbit-Stabilizer theorem I am unable to prove the above modification.
Could someone help me prove the above statement using a modification of Wielandt's proof?
Comment: You might want to check also this [entry][1]

  [1]: http://math.stackexchange.com/questions/203850/why-is-the-number-of-subgroups-of-a-finite-group-g-of-order-a-fixed-p-power-cong/203894#203894
Comment: I would say, this is Frobenius theorem (1895), rather than Sylow (1872). The reason is, this theorem appears in a paper of Frobenius, whose title is *generalization of Sylow theorems* and one of the generalization is the theorem you stated. It is not so easy to derive generalization from Sylow's original (third) theorem. see also my answer for similar question http://math.stackexchange.com/questions/1586060/the-number-of-p-subgroups-of-a-group/1593829#1593829
Answer: None of the versions of Wielandt's proofs of Sylow's Theorem that I have seen assume that $k=n$. I will cut and paste the proof from some lecture notes I have.
Theorem. Let $G$ be a finite group and let $p^\beta$ divide
$|G|$, where $p$ is prime. Let $k$ be the number of subgroups of $G$ of order
$p^\beta $.  Then $k \equiv 1 \pmod{p} $.
Proof.
Let $|G| = p^\alpha t$ with $p\nmid t$, so $\beta \le \alpha$.
Let $\Omega $ be the set of all subsets of $G$ of order $p^\beta $.
So
$|\Omega | =
\left( \begin{array}{c} p^\alpha t \\ p^\beta \end{array} \right)$.
Let $G$ act on $\Omega $ by right multiplication; i.e. if
$S \in \Omega$, then $S^g = Sg = \{sg \mid s \in S\}$.
Let $\Gamma$ be an orbit of $G^\Omega$.
If $T \in \Gamma$ and $x\in T$ then $1\in Tx^{-1} \in \Gamma$ so there is a set
$S\in \Gamma$ with $1\in S$.
Consider the stabilizer, ${\rm Stab} _G(S)$.
If $g\in {\rm Stab} _G(S)$ then $Sg=S$ so $1g = g \in S$.
Thus ${\rm Stab} _G(S) \subseteq S$.

Suppose that ${\rm Stab} _G(S) = S$, so $S$ is a subgroup of $G$.
Then, by the Orbit-Stabilizer Theorem,
$|\Gamma| = |G|/|{\rm Stab} _G(S)| = p^{\alpha }t/p^{\beta } =
p^{\alpha -\beta }t $ and
$\Gamma$ is the set of right cosets of $S$ in $G$. Thus only one element
of $\Gamma $ is a subgroup.
Conversely, if $T$ is a subgroup of $G$ of order $p^{\beta}$ then
$T^G$ (the orbit of $G^\Omega$ containing $T$) is the set of
right cosets of $T$ in $G$ so has length $p^{\alpha -\beta }t $

Suppose that ${\rm Stab} _G(S) \ne S$.
Then $|S| > |{\rm Stab} _G(S)|$, so  $|\Gamma | > p^{\alpha -\beta }t $.
Since $|\Gamma |$ divides $|G| = p^{\alpha }t $ we have
$p^{\alpha -\beta +1}$ divides $|\Gamma |$.
So by 1) no element of $\Gamma$ is a subgroup of $G$ in this case.

Hence, there are exactly $k$ orbits whose stabilizer has size $p^\beta $
and these orbits have have length $p^{\alpha -\beta }t $, whereas
those orbits whose stabilizer has size less than $p^\beta $ have length
divisible by  $p^{\alpha -\beta +1} $.
So
$|\Omega | = kp^{\alpha -\beta }t + l p^{\alpha -\beta +1}  $ for some $l$,
and hence $$|\Omega |/p^{\alpha -\beta } = kt + lp \equiv kt \pmod{p}.$$
Since $p \nmid t$, there is a unique $u \in \{1,\ldots,p-1\}$ with
$ut \equiv 1 \pmod{p}$, and multiplying by $u$ gives
$$k \equiv |\Omega |u/p^{\alpha -\beta } \!\!\!\pmod{p} \equiv
 \left( \begin{array}{c} p^\alpha t \\ p^\beta \end{array} \right)u
/p^{\alpha -\beta }\!\!\! \pmod{p}.$$
It is possible to prove directly that this last expression equals
1 mod $p$, but we can avoid that as follows.
Note that $k \pmod{p}$ is a function of $|G|$ and $p^\beta$ only,
and so it is the same for all groups of order $p^{\alpha} t$. So $k
\pmod{p}$ can be
determined from $G=C_{p^{\alpha} t}$, the cyclic group of order $p^{\alpha} t$.
Hence  $k \equiv 1  \pmod{p}$, since a cyclic group $G$ has a unique
subgroup of each order dividing $|G|$.
$\mathbf{Additional\ Remark\!:}$ This last trick of using the fact that the number of subgroups modulo $p$ depends only on $|G|$ is due to Graham Higman. In his original proof, Wielandt proved directly that the expression in the final displayed formula is congruent to $1$ modulo $p$.
Comment: Very nice solution, especially last argument using cyclic groups!
Comment: Yes of course $k$ depends on $G$. It is the value of $k$ modulo $p$ that depends only on $|G|$ and not on the structure of $G$.
Comment: Wait, if I understood correctly, your $k$ is the number of orbits that contains a subgroup (of order $p^\beta$), but should that not depend on the group structure? I mean, the way that the stabilizer behaves should depend on $G$?
Comment: For instant, this can be applied to $\beta=k$, in which case the groups are Sylow $p$-subgroups, but abelian groups always have a unique Sylow $p$-subgroups, whereas non-abelian groups not necessarily.
Comment: @DerekHolt That last trick with the cyclic group, is that yours or someone else's? I've always seen the n-choose-r evaluated modulo $p$.
Comment: @DavidA.Craven I am afraid I cannot claim credit for it - it is due to Graham Higman. I should have mentioned that in the proof, so I will edit it.

Wielandt's proof of Sylow's theorem.


Como permitir apenas números e ponto e vírgula no input text?

Question: Tenho um input em meu sistema onde o usuário deve inserir código (apenas números), porém ele pode colocar vários códigos, e pra separar utiliza ponto e vírgula (;).
Para que funcione eu criei o input como text e coloquei uma função, que é chamada através do event (input), que realiza a seguinte ação:
Input:
<input [disabled]="!selectHierarchy" id="numero" name="pesquisa" type="text" (input)="validaNumber()">

Função:
validaNumber(){
  let input = <HTMLInputElement>document.querySelector("#numero");
  input.value = input.value.replace(/[^0-9\;]/, '');
}

Deu certo, quando digito só aparece número e ponto e vírgula.
Porém se eu copiar um texto, e colar no input, aparece o texto normal. Como fazer essa validação funcionar também quando o usuário cola um texto?
Comment: Já tentou utilizar o evento `ngChange`? pois a validação só ocorrerá quando houver alterações no valor do input
Answer: Consegui resolver!
Eu adicionei o event binding (paste) que chama uma função quando alguém tenta colar algum texto:
<input [disabled]="!selectHierarchy" id="numero" name="pesquisa" type="text" (input)="validaNumber()" (paste)="teste($event)">

Na função eu criei um regex com tudo que não deve ser aceito no input, pego o valor e verifico se há alguma correspondência utilizando o regEx.test():
teste(event: ClipboardEvent){
let reg = /[a-zA-Z!@#$%^&*()_+\-=\[\]{}':"\\|,.<>\/?]/i;
let clipboardData = event.clipboardData;
let pastedText = clipboardData.getData('text');

 if (reg.test(pastedText)){
   event.preventDefault();
   event.cancelBubble = true;
   return false;
 }
}

Se tiver, cancela o evento e não deixa colar o texto.


Add meta tag description, page title and abstract programatically

Question: I have created a custom page using a tpl.php file and I want to add meta tag page title, abstract and description that page. Can anyone show me how to add these meta tags programatically to custom page?
<code>$description = array(
                 '#type' => 'html_tag',
                 '#tag' => 'meta',
                 '#attributes' => array(
                 'name' => 'description',
                 'content' => 'here all description goes',
               )
 );
drupal_add_html_head($description, 'description');
</code>
This is the code I am using to add description to my head.
Thanks in advance.
Answer: In your theme's template.php file, you could add something like
<code>/**
 * Implements hook_preprocess_html
 */
function THEME_NAME_preprocess_html(&$vars) {

  if (current_path() == 'my/custom/path') {
    $description = array(
      '#type' => 'html_tag',
      '#tag' => 'meta',
      '#attributes' => array(
        'name' => 'description',
        'content' => 'here all description goes',
      )
    );
    drupal_add_html_head($description, 'description');
  }

}
</code>
Clear cache to register new preprocess function.


Como colocar a data de hoje como valor padrão em um texbox como input tipo date?

Question: Tenho uma página para pesquisa de um relatório de vendas e uso um textbox que gera um input tipo "date", e sempre que a página carrega o valor do campo fica "dd/mm/yyyy".
Gostaria que sempre que a página fosse carregada o campo mostrasse a data atual sem eu precisar abrir o calendário para escolher a data. Como posso fazer isso?
Answer: Pelo que entendi, você está usando um DateTimePicker.
No evento Page_Load, creio que é só definir o campo com a data atual.
txtData.Value = DateTime.Today;

EDIT
Nos comentários, você está tendo como resultado em tela o seguinte:
<input name="calInicio" type="date" id="calInicio" class="form-control" placeholder="DD/MM/AAAA" style="height:32px;width:180px;">

O problema é que <input type="date" ...> precisa ter como valor inicial uma data no formato yyyy-mm-dd (veja a parte que fala sobre value). Ou seja, no Page_Load carregue seu TextBox da seguinte forma:
txtInicio.Text = DateTime.Today.ToString("yyyy-MM-dd");

Comment: Cara deu certo, muito obrigado !
Comment: Eu coloquei isso na programação, mas quando ele carrega a página não adianta, coloquei isso -> txtInicio.Text = DateTime.Today.ToShortDateString();

O atributo Value não tem em um textbox
Comment: Ah, entendi. Vou editar a resposta. Antes quero entender: você faz uma inspeção no HTML e o `` aparece pelo menos com um `value`? Ou não aparece nada?
Comment: Não aparece nada
Comment: O resultado no HTML por um acaso é ``?
Comment: Fica assim:
Comment: Agora tudo faz sentido. Fique de olho. Vou editar a resposta.


Low rank plus diagonal approximation of covariance of model parameters

Question: In this paper regarding Bayesian Deep Learning, in Section 3.4, the authors want to approximate the covariance of a distribution over the model parameters $\theta$. They first get an estimate of the diagonal covariance by approximating
\begin{equation}
\Sigma_{diag} = E[\theta^2] - E[\theta]^2
\end{equation}
where the expected values are estimated from $T$ samples. They also compute a low-rank approximation $\Sigma_{low-rank}$ of the full covariance matrix using only the last $K$ samples.
Then, they approximate the covariance matrix by
$\Sigma = \frac{1}{2} (\Sigma_{diag} - \Sigma_{low-rank})$
What is the reason for doing this? Why do we need a low rank approximation? And why is the sum of the diagonal and the low rank a good estimate of the covariance?
Answer: The reason they use a low rank plus diagonal approximation is to be parameter efficient. In the case of a deep neural network (the paper is about training Bayesian Neural Networks), the number of parameters in the networks (which becomes latent variables in the Bayesian model) is very large.
Considering all the covariances across all these model parameters would require a number of variational parameters roughly proportional to the square of the number of model parameters, which is probably too many for a computer to handle.
By using a diagonal plus low rank approximation, you need only a number of variational parameters roughly proportional to the number of model parameters directly.
The diagonal plus low rank approximation is more efficient than just a diagonal approximation, or a block diagonal approximation.


Create Waves Visualization Video Swift

Question: Here is what I am trying to do:

The screenshot is taken from a 6s iPhone.

I have been working on create video wavefrom and I would like to draw a waveform which looks look like the first screenshot. I am using VIWaveformView Github pods to draw waves. but I m confused how to draw same waves.
Code:
<code>@IBOutlet weak var vWmainWave: VIWaveformView!
override func viewDidLoad() {
    super.viewDidLoad()
    vWmainWave.waveformNodeViewProvider = BasicWaveFormNodeProvider(generator: { () -> NodePresentation in
        let view = VIWaveformNodeView()
        view.waveformLayer.strokeColor = UIColor(red:0.86, green:0.35, blue:0.62, alpha:1.00).cgColor
        return view
    }())
    vWmainWave.layoutIfNeeded()
    if let url = Bundle.main.url(forResource: "bulletTrain", withExtension: "mp4") {
        let asset = AVAsset.init(url: url)
        _ = vWmainWave.loadVoice(from: asset, completion: { (asset) in
        })
    }
}
</code>
Question: How to show the same waves as the original image(first screenshot)?
Can someone please explain to me how to draw same, I've tried to draw these waves but no results yet.
Any help would be greatly appreciated.
Thanks in advance.
Answer: you can check this part
<code>var waveformView: VIWaveformView!
override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor(red:0.10, green:0.14, blue:0.29, alpha:1.00)

        setupWaveformView()
        view.addSubview(waveformView)

        waveformView.translatesAutoresizingMaskIntoConstraints = false
        waveformView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 15).isActive = true
        waveformView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -15).isActive = true
        waveformView.topAnchor.constraint(equalTo: view.topAnchor, constant: 65).isActive = true
        waveformView.heightAnchor.constraint(equalToConstant: 80).isActive = true

        waveformView.layoutIfNeeded()
        if let url = Bundle.main.url(forResource: "Moon River", withExtension: "mp3") {
            let asset = AVAsset.init(url: url)
            _ = waveformView.loadVoice(from: asset, completion: { (asset) in
            })
        }
}
</code>
https://github.com/VideoFlint/VIWaveformView/blob/master/VIWaveformView/ViewController.swift
Comment: Thank you for your reply but this code for .mp3. I have already used this code but same issue this not available for video

Create Waves Visualization Video Swift