Is the field generated by adding several p-th roots a Kummer extension

Question: Let $F$ be a field with $(char(F),p)=1$ or $char(F)=0$ containing the roots of unity of order $p$. Consider the following extension of $F$: $$F[a_1 ^{1/p},...,a_k ^{1/p}]$$ and assume $a_i\notin(F^*)^p$. One can prove that the polynomials $f_i(x)=x^p-a_i$ are either irreducible or they split. Indeed, every extension in the tower is galois both over $F$ and over the previous extension. My question is whether the final extension is a Kummer (abelian) extension over $F$?
It is abelian over the $(k-1)$ extension, and from the fundamental theorem of Galois extensions, for every $i=1,..,k-1$ $Gal(F[a_1 ^{1/p},...,a_{i+1} ^{1/p}]/F)$ is normal in $Gal(F[a_1 ^{1/p},...,a_{k} ^{1/p}]/F)$. However this a group $G$ can have a normal abelian subgroup $N$ and an abelian quotient $G/N$ without being abelian. I would like to understand why (and if) is $F[a_1 ^{1/p},...,a_k ^{1/p}]/F$ abelian.
Answer: Yes it's an Abelian extension. Each $\sigma$ in the Galois group maps
$a_i^{1/p}$ to $\omega_i a_i^{1/p}$ where $\omega_i$ s a $p$-th root of unity. The map $\sigma\mapsto(\omega_1,\ldots,\omega_k)$ is a group homomorphism embedding the Galois group in an elementary Abelian group.
Answer: Nothing wrong with Lord Shark's answer, just adding a different way of arriving at the conclusion.
Because the $a_i$s are all in $F$ you can adjoin their $p$th roots in any which order you want. This freedom forces the big extension to be Abelian. We can do it by induction $k$:

You know that $K_1:=F[a_1^{1/p}]$ is an Abelian extension of $F$.
The induction hypothesis tells us that $K_2:=F[a_2^{1/p},\ldots,a_k^{1/p}]$ is also an abelian extension of $F$.
So if $K:=F[a_1^{1/p},a_2^{1/p},\ldots,a_k^{1/p}]$, then we know that $Gal(K/K_1)$ and $Gal(K/K_2)$ are both normal subgroups of $Gal(K/F)$. Furthermore, basic Galois correspondence tells us that those two subgroups intersect trivially. Therefore the big Galois group is the direct product of those two subgroups. Consequently
$Gal(K/K_1)\simeq Gal(K_2/F)$ and $Gal(K/K_2)\simeq Gal(K_1/F)$ so the factor groups, hence also their direct product, are Abelian.


Why are these two functors isomorphic?

Question: Let $A$ be a local noetherian ring, $M$ an $A$-module finitely generated. Let $f$ be an $A$-regular and $M$-regular element (i.e. $f$ is not a zero divisors on $A$ nor on $M$). Then inside the category of $A/fA$-modules (I think we can suppose finitely generated), we have the following isomorphisms of functors:

Ext$^n_{A/fA}(M/fM,\_)\cong$ Ext$^n_A(M,\_)$ for every $n\geq0$
Ext$^n_{A/fA}(\_,M/fM)\cong$ Ext$^{n+1}_A(\_,M)$ for every $n\geq0$

I found this theorem into some notes but I don't know how to prove it. I'm even not sure to understand what it means, it seems to imply that the functor Ext$^n_A(M,\_)$ is defined on the category of $A/fA$-modules. Could you tell me how to prove it and could you help me to understand better the statement, please?
Comment: $A/f$-modules can be considered as $A$-modules by change of rings using the map $A \twoheadrightarrow A/f$.  That's why, with some abuse of notation, we can talk about $\operatorname{Ext}_A^n (M,N)$ for $N$ an $A/f$-module.  Which notes are you reading?
Comment: I guess, it is meant like, for all $A$-modules $M$ and $N$:
$$\mathrm{Ext}^n_{A/fA}(M/fM,\ N/fN) \cong \mathrm{Ext}^n_A(M, N)$$
I tried to prove it for $n=0$, i.e. for the case of $\ \mathrm{Hom}\ $ functor, but couldn't finish. Probably some property of local rings is needed to be considered.
Comment: @mt_ this one: http://archive.numdam.org/ARCHIVE/SAC/SAC_1966-1967__1_/SAC_1966-1967__1__A1_0/SAC_1966-1967__1__A1_0.pdf
Answer: Let $R,S$ be rings, let $\phi:R \to S$ be a ring map.  Then we have functors $\uparrow = \uparrow_R^S : \operatorname{mod}_R \to \operatorname{mod}_S$ ("induction") and $\downarrow = \downarrow^S_R : \operatorname{mod}_S \to \operatorname{mod}_
r$ ("restriction") defined as follows: $M \downarrow $ is the $R$-module with the same underlying set as $M$ and with $R$-action $r \cdot m := \phi(r)m$ and  $N \uparrow : S \otimes _R M$, where the right-action of $R$ on $S$ is $s\cdot r := s\phi(r)$.
Example: $\phi$ is a quotient map $A \to A/f$.  Then $N \uparrow = A/f \otimes _A N \cong N/fN$.
In general we have $\hom_S(M\uparrow, X ) \cong \hom_R( M, X\downarrow)$ - see Cartan and Eilenberg p.29.  This is "change of rings" and says that induction and restriction are mutually adjoint functors.  We always have a map $\phi^*: \operatorname{Ext}^n_S(M\uparrow, X) \to \operatorname{Ext}^n_R(M, X\downarrow)$ (use the Yoneda definition of Ext for example).  It is not an isomorphism in general, but if $\operatorname{Tor}^R_n(S, X) = 0$ for $n>0$ it is an isomorphism (CE page 118).
In your case, a projective resolution of $A/f$ over $A$ is given by
$$ 0 \to Af \to A \to A/f \to 0 $$
To compute the Tor groups, tensor with $M$:
$$ 0 \to Af \otimes _A M \to M \to M/f  \to 0$$
(making some identifications).  The only way this could fail to be exact is if $xf \otimes _A m \mapsto xfm$ were not injective, but $f$ is not a zero divisor on $M$.  Thus all higher Tor groups vanish.
Comment: To type the up/down arrow you need to say `\mathord\uparrow`; otherwise, being a relation, it gets the spacing wrong: compare `M\uparrow=N` $M\uparrow=N$ *vs.* `M\mathord\uparrow=N` $M\mathord\uparrow=N$ (inthe first case `\uparrow=` gets interpreted as a single relation, and spaced accordingly)
Comment: @Mariano thanks, I'd always hacked that with backslash exclamation mark but felt vaguely guilty about it.

Why are these two functors isomorphic?


Paired T test vs Wilcoxon signed-rank

Question: I am trying to determine whether a paired T test or Wilcoxon ranked sum test is more appropriate to test for significance of improvement in the following:
Patients were surveyed for pain scores before treatment on 0-10 scale
Patients were then given intervention
Patients were then surveyed for pain score after treatment on 0-10 scale.
The data are effectively paired since datapoints exist for the same patient pre and post treatment.
Wilcoxon-signed-rank yields a very small P value over 24 patients. Very, very small (p<0.0001).
IS wilcoxon-SR appropriate for this application or should I be using a paired T test or chi-square test?
Comment: @a.powell 1. why would that be necessary? (rather than just the differences being approximately normal, say)  2. How would normality be possible? They're integers between 0 and 10
Comment: Are the data (both pre- and post-treatment) distributed normally?
Comment: MG -- 1. what's your actual null (is it a null about means, or is it some more general null?) 2. Is the software you're using going to correctly handle the heavy ties you're likely to get in a signed rank test? (though 24 should be enough to use the normal approximation with adjustment for tied ranks reasonably successfully)
Answer: If your data is normally distributed -- you can analyze a number of ways, including a QQ Plot -- then it is fine to run a t-test. But, in order to make the least number of assumptions about the data it is best to use the non-parametric Wilcoxon Signed Rank test.
Due to the fact that you have very few samples (24) I would advise going the Wilcoxon Signed Rank path. I would thoroughly analyze this question because it appears to answer a lot on necessary questions.
Be sure to understand exactly how the type I error and the power behaves in your test.
Comment: It might be worth noting that the loss of power of the Wilcoxon test is only about 4% if the variable is normally distributed. This amounts to losing 1 observation out of 24.

Paired T test vs Wilcoxon signed-rank


Como obter valores de uma coluna de várias tabelas apresentadas em uma página web?

Question: Numa página da Web, há uma ou mais tabelas com informações das quais preciso obter em forma de lista.
Especificamente, preciso obter uma lista dos valores da 2ª coluna de uma tabela da página Web que eu informar. Como por exemplo, as páginas abaixo.

Link: https://www.iomat.mt.gov.br/do/navegadorhtml/mostrar.htm?id=630236&edi_id=3580

Link: https://www.iomat.mt.gov.br/do/navegadorhtml/mostrar.htm?id=630237&edi_id=3580
Atualmente, eu copio a tabela para uma planilha e depois filtro a lista.
Mas se tivesse um script (Python, Ruby ou Perl) ou programa (Java ou C#) que apenas informasse o link e ele já retornasse a lista seria uma mão na roda.
A página com este tipo de matéria tem sempre um dos padrões acima.
Comment: Abra o console do Chrome (`Ferramentas > Console Javascript`) e escreva `$x("//tr[position() > 1]/td[2]/p/span/text()")`.
Comment: Acredito que para melhorar a pergunta você deveria deixar ela mais "genérica", para que possa ser útil para uma quantidade maior de desenvolvedores. Por exemplo no título: "Como obter valores de uma coluna de várias tabelas apresentadas em uma página web?" Daí dentro da pergunta, você até pode ser um pouco mais específico. Deste modo, você abre o leque da sua pergunta e continua com seu problema resolvido.
Comment: A sugestão do @BrunoGasparotto é ótima! Assim todo mundo ganha
Comment: Qual linguagem afinal? Para cada linguagem que você citou haverão diferentes ferramentas de *web crawling*.
Comment: @ricidleiv, eu achei que sua pergunta foi bem formulada. Você deixou claro que qualquer solução (com qualquer linguagem) é útil para você.
Comment: Obrigado @BrunoGasparotto, acatei sua sugestão do título e tentei reformular a introdução da pergunta.
Comment: Você tentou fazer esse script? Qual a problema aconteceu enquanto você tentava? Qual o código que deu problema? Qual é a pergunta exatamente?
Comment: Como eu especifiquei na pergunta, qualquer script ou programa. Quem já tiver alguma solução parecida baseada nesta dúvida.
Comment: Exatamente @rodrigorgs. Poderia postar como resposta. Obrigado pelo seu tempo.
Comment: Não posso postar como resposta enquanto a questão está *em suspenso*.
Comment: Como eu poderia reformular a pergunta para que fosse aprovada? Não vejo como ficar mais claro o que estou precisando. Eu postei na pergunta a solução que eu utilizo (mesmo que tosca, eu sei), mas queria algo mais robusto.
Answer: Abra o console do Chrome (Ferramentas > Console Javascript) e escreva o seguinte:
$x("//tr[position() > 1]/td[2]/p/span/text()")

Isso vai chamar a função Javascript $x (definida para o console do Chrome) e retornar o resultado da expressão XPath fornecida como parâmetro.
Explicação da expressão XPath

//tr[position() > 1]: seleciona todos os elementos tr da página exceto o primeiro
td[2]: seleciona apenas o segundo elemento td (i.e., a segunda coluna); você pode mudar o número da coluna ou usar td[position()=1 or position()=2] para selecionar as duas primeiras colunas, por exemplo.
p/span: seleciona o elemento span dentro do elemento p (isso vale para a página do seu exemplo; para outras páginas, você deve verificar os elementos dentro do td)
text() seleciona o conteúdo da tag.

Uso em linguagens de programação
A solução mais prática em qualquer linguagem de programação envolve a XPath com alguma biblioteca de XML. Exemplo em Ruby:
require 'nokogiri'
require 'open-uri'
require 'openssl'
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
doc = Nokogiri::HTML(open(ARGV[0]).read)
doc.xpath("//tr[position() > 1]/td[2]/p/span/text()").each { |x| puts x}

Exemplo de uso
ruby script.rb 'https://www.iomat.mt.gov.br/do/navegadorhtml/mostrar.htm?id=630237&edi_id=3580'

Comment: Achei ótima a solução Rodrigo, porém se você pudesse explicar detalhadamente oque o comando faz (por exemplo, qual dos parâmetros representa a coluna a ser buscada) seria ótimo, tornaria mais "adaptável", pois é uma solução boa pra muita gente, mas nem todos conhecem a sintaxe proposta.


Urbanairship: Delay in delivery of first push notification.

Question: I have heard that when using urbanairship, there is a delay of almost 24 hours in delivery of first push notification to a device. Is this correct? I have added an app and sent a push notification but though there is no error on erro console but I have not got the push on my device yet after 10 minutes of sending it. Can any one please guide me?
Best Regards
Answer: There isn't a 24 hour delay on push delivery using Urban Airship. There are many reasons a push may not be successful. I recommend you email Urban Airship Support at firstname.lastname@example.com so we can look into your particular situation. You can also check out our troubleshooting guide at https://docs.urbanairship.com/display/DOCS/Client%3A+iOS%3A+Push#ClientiOSPush-Troubleshooting
Thank you,
Urban Airship Support
Answer: To expand on what Ruth White mentioned, the delay you might perceive while using push notification for apple services is that development servers are not as fast as production servers. If you are using development servers, sometimes, for some circumstances, it can take several minutes before receiving a push notification. This is not controlled by Urban Airship, it's apple development servers.


É possível disparar dois tipos de ação no Redux ao mesmo tempo?

Question: Estou utilizando o Redux e Redux-saga em uma aplicação com React e com dúvida na hora de exibir o load para o usuário quando uma saga for disparada. Não sei se é uma boa prática, mas estava pensando na possibilidade de disparar 2 actions. 1 para exibição do load e outra para acionar a saga. É possível disparar dois tipos de ação ao mesmo tempo?
Answer: Falando de Redux, por mais que você tente, vc só vai conseguir disparar uma action de cada vez, isso porque no javascript, as instruções são executadas uma por vez e mesmo que vc use Redux-Saga, Redux-Thunk ou o que for, para tratar ações assíncronas, vai continuar sendo uma. Mas isso não quer dizer que elas serão resolvidas na ordem que são executadas.
No seu caso, é bem válida essa abordagem de uma action antes p/ atualizar o estado de loading, uma segunda action p/ fazer um fetch ou outra operação assíncrona e um terceiro p/ mudar o status de loading de novo.
Em se tratando de saga, não faço idéia por que nunca usei. Mas o princípio é o mesmo.
Comment: Obrigado @jan, depois de pesquisar descobri que dentro do saga consigo disparar uma action para o load e após o retorno do ajax posso disparar outra para ocultar o load.


Polynomial with constant ratio

Question:
What are all polynomials $P(x)$ with real coefficients such that for some $c>1$, for any integer $x$ there exists another integer $y$ with $P(y)=cP(x)$?

The monomials $P(x)=ax^n$ work because we can take $c=2^n$ and have $P(2x)=cP(x)$. If $P$ is not a monomial, then perhaps we can use an argument about the leading term dominating the remaining terms for large $x$, but that the remaining terms add some small value so that there is no $y$ such that $P(y)$ is exactly $cP(x)$.
Answer: Linear polynomials of the form $ax+ak$ work for any integer $k \gt 1$.  We choose $c=k,$  and $y=cx+c^2-c$, so $P(y)=P(cx+c^2-c)=acx+ac^2-ac+ac=cP(x)$  I have not shown that there are not others.

Polynomial with constant ratio


Create a background and banner that extend beyond container to fit browser screen. Similar to Obama's website

Question: I want my background image and banner to extend beyond the container to allow it to fit and center to different browser screen sizes.  I have created divs for each just need to know what settings each need to have.
The look I want is very similar to Obama's website.
http://www.barackobama.com/
Comment: Look at the CSS and HTML source code. It's not that complicated.
Comment: Could you please show your code or something relevant so we can see where you are facing problem. By the way the site you gave is very simple. make header Div fixed and the images in center, take it in a div and set margin:0 auto; the image will always in center.
Answer: you should use percent width and height. This way,

http://jsfiddle.net/yP4z7/


Can a fielder deliberately kick the ball over the boundary rope to keep a batsman on strike?

Question: In this potential situation the batting team has a recognized batsman and a tail ender at the crease, the recognized batsman is facing the last ball of the over and the fielding team therefore would prefer that either: he doesn't score any runs, scores 2 runs or scores a boundary so that at the start of the next over the tail ender will be on strike and not the batsman.
Supposing he hits the ball into the outfield but only takes a single run so that he retains the strike, would it be possible for the fielding team to deliberately kick the ball over the rope so that 4 runs are scored and the tail ender will then be on strike?
Clearly the situation would be pretty unsporting!
Answer: Law 19.7 in the MCC Laws of Cricket states that,

If the boundary results from an overthrow or from the wilful act of a fielder the runs scored shall be
(i) any runs for penalties awarded to either side AND
(ii) the allowance for the boundary AND
(iii) the runs completed by the batsmen, together with the run in progress if they had already crossed at the instant of the throw or act.
Law 18.12(b) (Batsman returning to wicket he has left) shall apply as from the instant of the throw or act.

In our case, this would mean that the single that the batsman took is awarded as well as the boundary, thereby adding 5 runs to the batting team. As the single is considered, the recognized batsman will face the first delivery of the new over.
Another source.
Answer: There was an incident of an England fielder (possibly Mark Butcher ??) dropping a simple catch, and in frustration kicking the ball, which rolled out for a boundary. I think the rule is that in the case of a fielder touching the ball (but not just a parry or dropped catch over the boundary) before it goes out for a boundary then the batting side score the runs plus the boundary, and the batting positions for the following ball are as if the runs are adhered to.
Comment: This doesn't add anything to the accepted answer.


Evaluation of Autocorr/Part Autocorr values

Question: I am practicing MA and AR modelling by using autocorrelation and partial autocorrelation values. My data is in the image below; I can see that only at lag 12 there is a value that might be considered but I have a dilemma: what model is this if any?

To be a MA of higher order the autocorr should be 0 After lag 12, but not before.
To be an AR I should see value oscillating and decaying up to lag 12.

Am I correct in my thinking or am I wrong?
I performed the Box-Jenkins test (lbqtest) with Matlab and only at lag 12 I have the rejection of the null hypothesis ( h =1 ) for an Alpha of 0.10.
Comment: What's the sample size? If it's greater than n=80 (so that n/4>20) then you may want to inspect higher lags, in particular lag 24 and possibly lag 36. Have you calculated a t value for the autocorrelation coefficient at lag 12? If so, what is it? Lastly, what do the blue lines in the ACF represent? Since you're trying to identify a tentative model, make sure that these are based on Bartlett's errors.
Answer: Though I am not an expert, the spike is fairly easy to interpret if you are evaluating monthly data.
One thing you may be interested in is trying to correct your data for seasonality as this may improve your regression results.
Answer: First of all, what kind of data are you analyzing?  That could give you an idea of whether you should expect a spike at h=12. You are mostly correct in your reasoning about the look of an ACF for different ARMA models.  However, if you had an MA(12) process like
$$
Y_t=\theta_{12}\epsilon_{t-12}+\epsilon_t
$$
then you could have an ACF plot that is approx. zero for h=1,...,11, nonzero for h=12, and then approx. zero afterwards.
In your case, this doesn't look like anything worth modelling. Remember that if you test a hypothesis of $H_0$: the autocorrelation at lag $h$ is significantly different from zero at significance level $\alpha=0.10$, on average you expect to make a type I error 10% of the time.  This is probably one of those times.
If you are curious, try fitting some MA(12) models and look at some model selction criterion (AIC, AICc, BIC, etc.) and see if any model gives a better fit than $Y_t=\epsilon_t$, $\epsilon_t \overset{iid}{\sim} N(0, \sigma^2)$. I am guessing no.


D7 Rules - User Profile Field in Send Email Action

Question: I'm using D7 with Rules 7.x-2.7. I am trying to create a Rule that will email and BCC all users of a particular role when a node of a certain content type is created. I've added the event: After saving new content of type..., and the action: Send mail to all users of a role. What I'm now trying to do is pull in the user profile data to populate the email body. Something like:
Hi [user-field-firstname],

A new announcement has been released. Please log in to your profile and browse to http://examplesite.com/user/[user-id]/announcements.

regards

I've been unsuccessful thus far. I've tried to add another action of Fetch entity by Id, but could find any decent selectors in the data selector. Any advice for me, please?
Comment: Have you tried the replacement patterns present in the Rules action page while creating the rules?
Check the image
http://drupal.cocomore.com/sites/default/files/blog_photos/drupal-rules-site_admin_email_notifications/drupal7-configure-message-new-user-4.png
Comment: I certainly have. But the only tokens I can see are those relating to `site` and `node`
Comment: Go ahead with Rules token but user object should be available by default. Can you post a screenshot?
Comment: **Solved** please see my answer below
Answer: I might try the Rules Token module (if you haven't already). It might contain what you need
Answer: SOLVED!!!
After breaking my head for a full day on this, I remembered something I read on a blog a while back about using views in Rules. So here goes and I hope this helps someone.

Download and enable the Drupal Views Rules (drush dl views_rules)
Configure and customize a new view with a Rules display as below:

with the row variables configured similar to:

Back in Rules, you will now see a new Add view loop method which can then be used as follows:

I really hope this helps someone else. Note that I'm not using the Rules Tokens or Profile2 modules - just the Views Rules module. :)


Spree commerce - Edit User object properties

Question: I'm new to spree and also still learning Rails
I don't completely understand how can I add new properties to the Spree::User object, so that I can set more data to the users that are registering to my site.
According to the not-so-clear documentation, I understand that I should create a User class and add preferences:
class User < ActiveRecord::Base
  preference :hot_salsa, :boolean
  preference :dark_chocolate, :boolean, :default => true
  preference :color, :string
  preference :favorite_number, :integer
  preference :language, :string, :default => "English"
end

But I'm not sure where should I save this file or how to name it at all.
Am I on the correct path?
Comment: IMHO This part is well documented. https://guides.spreecommerce.com/developer/logic.html#extending-classes
You create migraton, eval class and change or extend views as in link mention by @Saurabh
Answer: You can do it using a decorator. You can create the decorator as app/models/spree/user_decorator.rb and add your code in it.
Spree::User.class_eval do
  preference :hot_salsa, :boolean
  preference :dark_chocolate, :boolean, :default => true
  preference :color, :string
  preference :favorite_number, :integer
  preference :language, :string, :default => "English"
end

Find documentation for overidding or extending code here.
Answer: The fields you are adding should not be used as preferences as the value for preferences are serialised and then stored which will not be useful if you want to do some filtering/querying on these fields.
Rather these should be

separate attributes of user model (columns of spree_users table).
attributes of a separate new table may be spree_user_details (belongs_to :user) with has_one association from user model.


GSHEET How do I Extract Text from formula for creating automatic cell reference

Question: The context :
Each time i need a cell reference from my other sheet, I need others cell reference from the same line but from different column.
I would like to automate those adding reference values depending on the first reference i add manually.
I have a sheet named alpha and a sheet named beta
I have a cell A1 in alpha that refers to beta A1
I have this referred cell formula in alpha A1 to have the value from beta A1
=beta!A1
Objectif :
I would like to have in alpha B2 the cell automatically filled-in by the value from beta A7
the equivalence of this refered cell formula
=beta!A7
Because the number seven will never change, only the column can change it could be:
=beta!AC1
so I will need =beta!AC7 automatically populated.
The Goal :
The goal is to extract from the formula in alpha A1 all characters except number(s) by a formula (like SEARCH, LEN, from FORMULATEXT) to obtain
=beta!A
with this result, I will concatenate with a cell that has the value "7". to obtain the formula for the cell reference.

A
B
C

1
=beta!A1
=beta!A7
7

2
=beta!AC1
=beta!AC7

If anyone can give me this formula clue or a better way to reach my goal would be good
I tried the regex below but it removed the punctuation
=REGEXREPLACE(FORMULATEXT(A1),"[^[:alpha:]]", "")&C1 where C1 is the value "7"
But i have all the need without the exclamation mark "!"
=betaA7
instead of
=beta!A7
Thank you
Comment: Did you try `INDIRECT()` function? like `=INDIRECT("beta!A" & C1)`.
Answer: this is what you want
Use this to REGEXEXTRACT all the numbers and REGEXREPLACE then with "" nothing. and add &$C1 the value in C1.
=REGEXREPLACE(A1, REGEXEXTRACT(A1, "[0-9]+"), "")&$C1

A better way
See in Beta!A1 we have a value of Im beta A1
And in Beta!A7 we have a value of Im beta A7

And in alpha!A1 we hane the formula =beta!A1

To get the value of beta!A7 using the formula in alpha!A1 as an input we use this formula in beta!B1

=INDIRECT(REGEXREPLACE(SUBSTITUTE(FORMULATEXT(A1),"=",""), REGEXEXTRACT(SUBSTITUTE(FORMULATEXT(A1),"=",""), "[0-9]+"), "")&$C1)

Explanation
INDIRECT(=beta!A1)

Even more simpler approach
Use this formula directly
=OFFSET(beta!A1,C1-1,0)

Comment: This is what i did after you clarified ;) see the updated answer.
Comment: See Even more simple approach option 3 `=OFFSET(beta!A1,C1-1,0)`
Comment: Thank you, I should be more explicit because what I wrote is the formula, not the values inside the cells. So if i follow your formula and have a different data in cell. I have an error saying it's not a valid cell/range reference. What i have to manipulate is the formula in A1 not the result. The goal is to manipulate the formula of whatever the cell contains.
Comment: I tried replacing the cell by formulatext like '=INDIRECT(REGEXREPLACE(FORMULATEXT(A1), REGEXEXTRACT(FORMULATEXT(A1), "[0-9]+"), "")&$C1)' but gave me the same I think it's because it adds the equal at the first character
Comment: You tested option 1? did it work?
Comment: Just find a workaround but i'm sure there is something more straight forward: '=INDIRECT(REGEXREPLACE((REGEXREPLACE(FORMULATEXT(A1), REGEXEXTRACT(FORMULATEXT(A1), "[0-9]+"), "")&$C1),"(.{1})(.*)","$2"))'
Comment: 1 = we have the formula as a cell value '=(REGEXREPLACE(FORMULATEXT(A1), REGEXEXTRACT(FORMULATEXT(A1), "[0-9]+"), "")&$C1)'
2 = we remove the equal sign of this result above '=REGEXREPLACE(B1,"(.{1})(.*)","$2")'
3 = we combine both to have the formula without the equal '=REGEXREPLACE((REGEXREPLACE(FORMULATEXT(A1), REGEXEXTRACT(FORMULATEXT(A1), "[0-9]+"), "")&$C1),"(.{1})(.*)","$2")'
4 = we include indirect to transform it as a formula '=INDIRECT(REGEXREPLACE((REGEXREPLACE(FORMULATEXT(A1), REGEXEXTRACT(FORMULATEXT(A1), "[0-9]+"), "")&$C1),"(.{1})(.*)","$2"))'
Does anyone as more simple way?


determmine image of $f$

Question: Let $f(x)=\dfrac{1}{x+1}\sqrt{x^2-1}$
$D_f={(-\infty,-1)}\cup {[1, +\infty)}$
How can i show algebraically that $$f\left( (1,+\infty) \right)=(0,1)$$
Indeed,
let $y\in \mathbb{R} $
$$
\begin{align}
 y\in f\left( ]1,+\infty[ \right) &\iff f(x)=y\\
 &\iff \dfrac{1}{x+1}\sqrt{x^2-1}=y\\
 &\iff  \sqrt{x^2-1}=yx+y\\
&\iff \begin{cases}
 |x^{2}-1|=y^{2}(x+1)^{2}&  \\
yx+y>0& \\
x> 1 &\\
\end{cases} \\
 &\iff \begin{cases}
 x-1=y^{2}(x+1)&  \\
y(x+1)>0& \\
x> 1 &
\end{cases}\\
 &\iff \begin{cases}
 x-y^{2}x=y^{2}+1&  \\
y(x+1)>0& \\
x> 1 &
\end{cases}\\
 &\iff \begin{cases}
 x=\dfrac{y^{2}+1}{1-y^{2}}&  \\
y(x+1)>0& \\
x> 1 &
\end{cases}\\
&\iff \dfrac{y^{2}+1}{1-y^{2}}>1
\end{align}$$
i'm trying to show that $y\in (0,1)$
I'm stuck here
Comment: For a *general* function, it may be very difficult to determine the image. This one presents relatively few problems, though.
Comment: we can use $h(x)=(f(x))^{2}$ such that $h(x)=\dfrac{x-1}{x+1}$
Answer: for $x>1$
$$f(x)=\sqrt{1-\frac{2}{x+1}}$$
we see that $f$ is continuous and strictly increasing at $(1,+\infty)$.
but
$$\lim_{x\to 1^+}f(x)=0$$
and
$$\lim_{x\to+\infty}f(x)=1$$
thus
$$f((1,+\infty))=(0,1)$$

algebraically

let $x>1$
$$f(x)=y\implies 1-\frac{2}{1+x}=y^2$$
$$\implies x=\frac{2}{1-y^2}-1$$

$$x>1\implies 0 <\frac{2}{1+x}<1\implies 0<y<1$$
$$0<y<1\iff 0<1-y^2<1\implies \frac{1}{1-y^2}>1\implies x>1$$
Comment: this is Analytical Approach i'm looking  for algebric one
Comment: @Yacob Please look now.
Comment: how did you get that $f(x)=y\iff x=\frac{2}{1-y^2}-1$ please elaborate your steps
Comment: @Yacob And now, You see.
Comment: yes i see thank you
Comment: but w $x>1 \implies 01\implies 0<f(x)<1$ means $f((1,+\infty))\subset (0,1)$.
Comment: شكرا أخي عبد الله على شرحك القيم من أي بلد أنت أنا من المغرب
Comment: @Yacob De rien mon ami du monde. Oui Morocco.

determmine image of $f$


A problem about direct product

Question: Let $G = U \times V$ where $U, V$ are nonabelian simple groups. Then $G$ has precisely four different normal subgroups.
When I was showing the above statement, I did not use the fact that $U, V$ are nonabelian, so I want to see if someone can give me a proof that uses the information so that I can easily check if I was right.
Comment: You missed one: $\{(0,0), (1,1)\}$. // See also: http://groupprops.subwiki.org/wiki/Subgroup_structure_of_Klein_four-group
Comment: Did you try some examples with $U$ and $V$ abelian? E.g. $G = \mathbb{Z}_2 \times \mathbb{Z}_2$?
Comment: Yes. For that example, we have $1 \times 1, \mathbb{Z}/2\mathbb{Z} \times 1, 1 \times \mathbb{Z}/2\mathbb{Z}, \mathbb{Z}/2\mathbb{Z} \times \mathbb{Z}/2\mathbb{Z}$ and I believe these are all normal subgroups.
Comment: Oh, is it a diagonal subgroup? Thank you.
Answer: The proof I'm thinking of does indeed use that fact that $U$ and $V$ are nonabelian.
Let $G=U\times V$ be as you say. Let $N\leq G$ be a nontrivial normal subgroup. Suppose $x=(u,v)\in N$, with $u\neq 1$. (Or $v\neq 1$, at least one of the cases must be true.) Since $U$ is simple and nonabelian, there must exist some $g\in U$ such that $gu\neq ug$, for if not, $u\in Z(U)$, in which case $Z(U)$ is a nontrivial normal subgroup of $U$.
Let $y=(g,1)$, and consider the commutator $[y,x]=y^{-1}x^{-1}yx$. Since $N$ is normal, $[y,x]\in N$. Now define $G_1=\{(u,1):u\in U\}$. Observe that
$$
[y,x]=y^{-1}x^{-1}yx=(g^{-1}u^{-1}gu,1)\in G_1
$$
and $[y,x]\neq (1,1)$ since $gu\neq ug$. Thus $[y,x]\in G_1\cap N$. But then $G_1\cap N$ is a nontrivial, normal subgroup of $G_1\simeq U$, so necessarily $G_1\cap N=G_1$. Thus $G_1\leq N$.
If there exists some $(u,v)\in N$ with $v\neq 1$, then a similar argument would show $G_2\leq N$, where $G_2=\{(1,v):v\in V\}$. From this is follows that there are precisely four normal subgroups of $G$.
Comment: Thank you. I like this argument more than mine.
Comment: I don't see how you exclude other possibilities like $H \subseteq U \times U$ with $H = \{(x, x) : x \in U\}$ with this proof. Please let me know if I am missing anything.
Comment: @GilYoungCheong If $N$ is nontrivial and contains some $(u,v)$ with $u\neq 1$, the proof shows that $G_1\subseteq N$. One possibility then is that $N=G_1$, or $N$ properly contains $G_1$, and thus some $(u,v)\in N$ with $v\neq 1$. But then $G_2\subseteq N$. So for any $u\in U$ and any $v\in V$, $(u,1)$ and $(1,v)\in N$, but this implies $(u,1)\cdot(1,v)=(u,v)\in N$, so $N=G$. Thus the four normal subgroups are $\{\{(1,1)\}, G_1, G_2, G\}$.
Comment: @GilYoungCheong Thanks, happy to help.
Answer: Since the proof that I have in mind is different from above, I decided to answer the question on my own as well. The answer that I was looking for was more or less what Martin commented, which is enough to find what I assumed wrong though I take blames for not mentioning that the examples are "fine" for the answer.
Let $1 \times 1 < N \unlhd G = U \times V$.
Lemma 1. Let $N_{1} := \{(x, y) \in N : y = 1_{V}\}$  and $N_{2} := \{(x, y) \in N : x = 1_{U}\}$. Then $N_{1}, N_{2} \unlhd G$.

Proof. $N_{1} \neq \emptyset$ as it has $(1, 1)$. If $(x, 1), (x', 1) \in N_{U}$, then these elements are also in $N$, so $(x, 1)(x', 1)^{-1} = (xx'^{-1}, 1) \in N$ means the same product is in $N_{1}$, so $N_{1} \leqslant G$. Moreover, we have $(u^{-1}, v^{-1})(x, 1)(u, v) = (x^{u}, 1) \in N$ for any $(u, v) \in G$, so $N_{1} \unlhd G$. An almost identical proof gives $N_{2} \unlhd G$.

Let $\pi_{1}:U \times V \rightarrow U$ and $\pi_{2}:U \times V \rightarrow V$ denote projections.
Lemma 2. $\pi_{1}(N_{1}), \pi_{1}(N) \unlhd U, \pi_{2}(N_{2}), \pi_{2}(N) \unlhd V$.

Proof. Let $x \in \pi(N_{1})$, $(u, v) \in G$. Then $(x, 1) \in N_{1}$, so $(x, 1)^{(u,v)} = (x^{u}, 1) \in N$, so this is also in $N_{1}$, which shows $x^{u} \in \pi_{1}(N_{1})$, so $\pi_{1}(N_{1}) \unlhd U$. An almost identical proof shows $\pi_{2}(N_{2}) \unlhd V$.
Now let $x \in \pi_{1}(N)$. Then we have some $y_{0} \in V$ such that $(x, y_{0}) \in N$. Thus for any $(u, v) \in G$, we have $(x, y_{0})^{(u, v)} = (x^{u}, y_{0}^{v}) \in N$, so $x^{u} \in \pi_{1}(N)$. We conclude $\pi_{1}(N) \unlhd U$. Similarly, $\pi_{2}(N) \unlhd V$.

Lemma 3. If $\pi_{1}(N) = 1_{U}$, then $N = 1 \times 1$ or $1 \times V$. And if $\pi_{2}(N) = 1_{V}$, then $N = 1 \times 1$ or $U \times 1$.

Proof. Suppose that $\pi_{1}(N) = 1_{U}$. Then $N \unlhd 1 \times V$, so $N = 1 \times 1$ or $1 \times V$, considering $\pi_{2}(N) \unlhd V$, by Lemma 2 (if $\pi_{2}(N) > 1$, then $N \simeq \pi_{2}(N)$). Similarly for the rest of the statement.

Rest of the Argument. By Lemma 3 (and Lemma 2), we can assume $\pi_{1}(N) = U, \pi_{2}(N) = V$ (otherwise, $N \in \{1 \times 1, U \times 1, 1 \times V \}$). If $\pi_{1}(N_{1}) = 1_{U}$, then for any $(x, y), (x', y) \in N$, we have $(xx'^{-1}, 1) \in N$, so $(xx'^{-1}, 1) \in N_{1}$, so $xx'^{-1} = 1$ gives $x = x'$.
Suppose that $\pi_{1}(N_{1}) = 1_{U}$. Take any $u \in U$. Since $\pi_{1}(N) = U$, take $(u, v_{0}) \in N$. For any $a \in U$, we have $(u^{a}, v_{0}) = (u, v_{0})^{(a, 1)} \in N$. Since $(u, v_{0})$ and $(u_{a}, v_{0})$ have same element in the first component, the above argument gives $u = u^{a}$. Thus $u \in Z(U) \setminus \{1_{U}\}$, and this is nonsense since $U$ is nonabelian simple (and thus $Z(U) \lhd U$ properly gives $Z(U) = 1_{U}$.) This shows $\pi_{1}(N_{1}) = U$ and similarly we can show $\pi_{2}(N_{2}) = V$. This implies that $N = U \times V = G$.

A problem about direct product


Proving two sequences converge to the same limit $a_{n+1}\frac{a_n+b_n}{2} \ , \ b_{n+1}=\frac {2a_nb_n}{a_n+b_n} $

Question:
$\text{We have two sequences}$ $(a_n), (b_n)$ where $0<b_1<a_1$ and:
$$a_{n+1}=\frac{a_n+b_n}{2} \ , \ b_{n+1}=\frac {2a_nb_n}{a_n+b_n} $$
Prove both sequences converge to the same limit and try to find the
  limit.

What I did: Suppose $\displaystyle\lim_{n\to\infty}a_n=a, \displaystyle\lim_{n\to\infty}b_n=b$ So $\displaystyle\lim_{n\to\infty} \frac {a_n+b_n} 2= \frac{a+b} 2 =K$
Take $a_{n+2}= \frac {a_{n+1}+b_{n+1}}{2}=\frac {\frac{a_n+b_n}{2}+\frac {2a_nb_n}{a_n+b_n}}{2}=...=X$
We know that as $n$ tends to infinity $\lim x_n= \lim x_{n+1}$ so: $X=K$ and after some algebra I get $a=b$
As for the limit, it depends on only one of the sequences, since both tend to the same limit. The limit can be any constant or $\pm\infty$.
Is this approach correct ?
I excluded the algebra because I type this manually and to make the solution easier to read.
Comment: It seems that $a_{n+1}$ is a [geometric mean](http://en.wikipedia.org/wiki/Geometric_mean) of $a_n$ and $b_n$, and $b_{n+1}$ is a [harmonic mean](https://en.wikipedia.org/wiki/Harmonic_mean) of same two previous terms.
Comment: @JulienGodawatta Why we easily have $b_1<\cdots< b_n<\cdots<a_n<\cdots< a_1$ ?
Comment: @GinKin See mookid's answer.
Comment: @JiminP how did you get this ? there's no root nor $n$ in either...
Comment: @GinKin Oops. I meant arithmetic mean. Sorry.
Answer:
Just show via an induction that $b_n\le b_{n+1} \le a_{n+1} \le a_n$: this proves that both sequences are convergent.
Then take the limit in the definition and the previous inequality: you get
$$A = \frac 12 (A+B)
\\A\ge B$$so $A=B.$

details for 1.:
a) The inequality
$$
u<v\implies \frac {u+v}2<v
$$is trivial.
b)$$
u<v\implies \frac 1u > \frac 1v
\\ \implies \frac 1u > \frac 12 \left(\frac 1u +\frac 1v\right)
=\frac{u+v}{2uv}\implies u<  \frac{2uv}{u+v}
$$
c) As $0\le(\sqrt{u}-\sqrt{v})^2$,
$$
\sqrt{uv}\le \frac{u+v}2\\
4uv\le (u+v)^2\\
\frac{2uv}{u+v} \le  \frac {u+v}2
$$
Comment: this is just by induction.
Comment: How do you show that ?
Comment: the most simple way is via convexity.
Comment: Well this question is supposed to be answered without functions or convexity (it's early in the course).

In the comments above Julien said we have $b_1<\cdots< b_n<\cdots<a_n<\cdots< a_1$, how did he get this and how it can be used ?
Comment: explanations improved.
Comment: We know that $u<v \ $ only for the first term of both sequences. How can you imply it for all terms in both sequences ?
Comment: How did you get to this (in red) : $uv\le \frac{u+v}2\\
\color{red}{4uv\le (u+v)^2}\\
\frac{2uv}{u+v} \le  \frac {u+v}2$
Comment: thank you, it was a mistake (one radical missing). From $\sqrt{uv} \le (u+v)/2$, square and multiply by 4.
Answer: Firstly, in your initial solution K = a by definition, so the result a=b follows immediately.
For an estimate of the limit for large n observe that the next member of each sequence is between an and bn, and so the final result must also be between a1 and b1, and indeed between (a1 + b1)/2 and 2*(a1*b1)/(a1+b1), and so certainly not infinity.
Comment: Your assertion that the limit can be any constant is wrong. It is bounded by a1 and b1.
Comment: So you're saying my solution is wrong or not ?
Comment: You solution for equality assumes that the limits exist and this must be proved first. Once this is proved, however, by replacing K by a, (because by definition K = a) gives (a+b)/2 = a => a+b=2a => b=a


How to get data from an array in a json file through a Microsoft Azure Query

Question: How do I return the value of an element of an array in one of my inputs in which the index it's located at constantly changes?
I'm pretty sure the structure of my query is correct. I have two inputs and am using a join and am successfully getting some data from both tables successfully. However, I need to get the RemoteIpAddress from table B, but it is in an array in json format.
My Query
Here it is in text if you want to easily copy, paste, and/or edit it:
SELECT
A.context.data.eventTime as eventTime,
A.context.device.type as deviceType,
A.context.[user].anonId as userId,
A.context.device.roleInstance as machineName,
B.context.operation.name as eventName,
B.context.custom.dimensions[0],
--B.GetRecordPropertyValue(GetArrayElement(B.context.custom.dimensions,7), B.RemoteIpAddress) as remoteIpAddress,
--GetArrayElement(B.context.custom.dimensions,3),
--B.GetRecordPropertyValue(GetArrayElement(B.context.custom.dimensions,3), B.userName) as userName,
DATEDIFF(minute,A.context.data.eventTime,B.context.data.eventTime) as durationInMinutes

INTO DevUserlgnsOutput

FROM DevUserlgnsInput A TIMESTAMP BY A.context.data.eventTime

JOIN DevUserlgnsInput2 B TIMESTAMP BY B.context.data.eventTime
ON DATEDIFF(minute,A,B) BETWEEN 0 AND 5

The commented out lines do not work, so I've commented them out.
I've looked this up and saw recommendations to use GetRecordPropertyValue and GetArrayElement, so I did. I'm getting no errors, but it's returning null.
I also discovered that if I do B.context.custom.dimensions[0], the full array including the element I want to see is returned.
To further complicate things, I realized that the position of the element I want in the array is not always the same. In some sample data, it's 7, others it's 3.
Thanks in advance.
UPDATE after reading an answer:
My new query:
SELECT
Events.context.data.eventTime as eventTime,
Events.context.device.type as deviceType,
mDim.ArrayValue.MachineName as machineName,
mDim.ArrayValue.UserId as userID,
mDim.ArrayValue.RemoteIpAddress as remoteIpAddress,
mDim.ArrayValue.UserName as userName,
mDim.ArrayValue.EventName as eventName

INTO DevUserlgnsOutput

FROM DevUserlgnsInput2 Events

CROSS APPLY GetArrayElements(Events.context.custom.dimensions) AS mDim

Problem: I now have multiple rows for a single event, each one displaying 1 attribute I want to track (the rest of the columns in each row pertaining to the array are NULL). Any thoughts on how to fix that?
Comment: Did you try GetArrayElements (plural) to get all of them in a cross-apply?
https://msdn.microsoft.com/en-us/azure/stream-analytics/reference/getarrayelements-azure-stream-analytics
Comment: I tried and am using this method. I posted my updated query in my original question. However, multiple rows show up for a single event, each row only having 1 attribute of the array displaying (all other columns relating to the array display NULL). How do I fix this?
Answer: My solution:
    WITH Events AS

(

SELECT

  context.data.EventTime as eventTime,

  context.device.type as deviceType,

  GetRecordPropertyValue(GetArrayElement(context.custom.dimensions, 7), 'MachineName') AS machineName,

  GetRecordPropertyValue(GetArrayElement(context.custom.dimensions, 8), 'UserName') AS userName,

  GetRecordPropertyValue(GetArrayElement(context.custom.dimensions, 2), 'remoteIpAddress') AS remoteIpAddress,

  GetRecordPropertyValue(GetArrayElement(context.custom.dimensions, 0), 'EventName') AS eventName,

  CASE WHEN GetRecordPropertyValue(GetArrayElement(context.custom.dimensions, 12), 'UserId') is NULL THEN GetRecordPropertyValue(GetArrayElement(context.custom.dimensions, 11), 'UserId') ELSE GetRecordPropertyValue(GetArrayElement(context.custom.dimensions, 12), 'UserId') END as userId

FROM ProdUserlgnsInput

)

SELECT eventTime, deviceType, MachineName, UserId, UserName, remoteIpAddress, eventName  INTO ProdUserlgnsOutput FROM Events

However, I had to move the EventName property to the main array because the WITH statement I tried to use to get info from 2 separate arrays was not letting me put the results in a single output. Additionally, since the index of UserId was mostly 12, but sometimes 11. So, in order to display the actual UserId for all records, I used the "Case When" syntax.
I worked a lot to solve this problem, so if anyone wants more details, please feel free to ask.
Answer: Below Query fits your latest array structure, try it out:
SELECT
context.data.EventTime as eventTime,
context.device.type as deviceType,
GetRecordPropertyValue(GetArrayElement(context.custom.dimensions, 4), 'MachineName') AS machineName,
GetRecordPropertyValue(GetArrayElement(context.custom.dimensions, 5), 'UserId') AS userId,
GetRecordPropertyValue(GetArrayElement(context.custom.dimensions, 9), 'UserName') AS userName,
GetRecordPropertyValue(GetArrayElement(context.custom.dimensions, 11), 'remoteIpAddress') AS remoteIpAddress,
GetRecordPropertyValue(GetArrayElement(context.custom.dimensions, 13), 'EventName') AS eventName
INTO output1
FROM input1

Answer: You can use UDF
function arraygetvaluebyname(arg, name) {
    var z = arg;
    for(var i=0;i<z.length;i++){
        if(name === Object.keys(z[i])[0])
        {
            return z[i][name];
        }
    }
    return null;
}

Comment: Can you explain that further? What do you mean by "UDF", and what does that code do?
Comment: UDF : Azure Stream Analytics user-defined functions written in JavaScript
 https://learn.microsoft.com/en-us/azure/stream-analytics/stream-analytics-javascript-user-defined-functions


Como percorrer um elemento por um em um array JS

Question: Fala pessoal, boa tarde.
Eu estou a fazer uma funcao que tem a mesma utilidade do ANY.
Qual é a ideia, é saber se tem algum numero menor que o dado na funcao dentro do array, independente se ele esta na primeira ou na ultima posição do array.
Se exister retorna TRUE, se não, retorna FALSE
O codigo ta assim:

const numerosFora = [1];

function qualquer (num1, func){
 for(let i = 0; i < num1.length; i++){
   for(let i = 0; i < func.length; i++){
     if(num1[i] < func[i]){
        return true
      } else {
         return false
      }

      }
    }

}

console.log(qualquer([1,0],numerosFora))

Porem ele so retorna se o numero estiver na primeira posicao, no caso 0.
Comment: A pergunta nao esta clara e nao entendi direito o codigo tambem. Por que nao usa o any?
Comment: Começa o erro que você tem 2 loops aninhados usando a mesma variável "i", deveria ser duas variáveis diferentes, não?
Comment: @LucasCosta Fala Lucas, boa tarde.

A ideia é eu criar um proprio Any, entendeu?
Posso dizer que é o que ocorrer por tras da palavra `any`, entendeu?

É assim, eu quero saber como eu faco pra passar de um elemento para o outro no array.

EXEMPLO: Saber se existe o numero 3 no array:
Array = [1,2,3,4]

Quero saber como faco pra percorrer ate o 3 e retornar true, entendeu ?
E se retornar false, ele ir pro proximo, ate o ultimo, entendeu?

No meu, ele vai ate so o primeiro e retorna.
Answer: Se precisar fazer testes em um array para saber se algum de seus elementos satisfazem uma condição use o método Array.prototype.some().
O método some() aceita uma função callback e a evoca uma vez para cada elemento da array até o momento que essa função callback  retorne true.

/**
 * Procura em um array por um valor menor que o valor indicado.
 * @param {Array} arr - O array cujo os elementos serão testados contra val.
 * @param {number} val - O valor a ser testado contra os elementos de arr.
 * @returns {boolean} retorna true quando encontrar em arr um elemento menor que val caso o contrário retorna false.
 */
function menorQue(arr, val) {
  return arr.some((e) => {
    return e < val;
  });
}

let lista = [2, 3, 4, 5, 6];

console.log(menorQue(lista, 10));

console.log(menorQue(lista, 2));

Outra interpretação para o sua pergunta, devido a essa declaração const numerosFora = [1];, seria fazer a comparação entre dois arrays e retornando true caso seja encontrado no primeiro array um elemento menor que no segundo.

/**
 * Procura em arr1 por um elemento que seja menor que um dos valores de arr2.
 * @param {Array} arr1 - Array cujo os elementos serão testados.
 * @param {Array} arr2 - Array cujo os elementos serão testados.
 * @returns {boolean} retorna true quando encontrar em arr1 um elemento menor que qualque um dos elementos de arr2.
 */
function algumMenorQue(arr1, arr2) {
  return arr1.some((e) => {
    return arr2.some((e1) => {
      return e < e1;
    })
  });
}

let lista = [2, 3, 4, 5, 6];

console.log(algumMenorQue(lista, [7, 8, 9]));

console.log(algumMenorQue(lista, [0, 1]));
Answer: Os seus for possuem problema porque os dois usam a mesma variável i, logo, na comparação num1[i] < func[i], os i serão sempre do último for.
Outra coisa, quando você coloca um return, o laço termina, ou seja, os itens restantes da array que por ventura deveriam ser percorridos, não serão mais.
Como você quer apenas verificar se retorna true e parar o laço quando isso acontecer, deixe apenas o return true no laço (e altere a variável do segundo for):

const numerosFora = [1];

function qualquer (num1, func){
  for(let i = 0; i < num1.length; i++){
    for(let x = 0; x < func.length; x++){
      if(num1[i] < func[x]){
        return true;
      }else{
        console.log(false); // apenas como exemplo para mostrar no console
      }
    }
  }
}

console.log(qualquer([1,0],numerosFora))
Answer: Em JavaScript ES6 seria algo assim:
const qualquer = (a, b) => {
  return a.map(item1 => b.map(item2 => item1 < item2 ? true : false));
}

console.log(qualquer([1, 2, 3, 4], [1, 3, 5]));

   //Resultado
   //0: (3) [false, true, true]
   //1: (3) [false, true, true]
   //2: (3) [false, false, true]
   //3: (3) [false, false, true]


Is it possible to bind functions to window using "var" from inside a function?

Question: Preface: I'm a language researcher trying to accomodate a very specific use case of JavaScript. I am aware of "best practices" regarding scoping and usage of window, etc.
In scenario A below, the function bam is added to the global scope, available on the window object. In scenario B, the wrapperFn is executed in the global scope, but bam is not added to the global window object. In scenario C, it's clear that this refers to window.
Is there any way to add items to window from within functions using the "var .." declaration syntax (e.g not window.foo = func...)? What's the difference between eval'ing a global script compared to executing a function in the window context?
Scenario A:

Scenario B:

Scenario C:

Comment: If you'd describe this "very specific use case", perhaps somebody can provide an explicit suggestion.
Comment: @Pointy, I'm researching javascript instrumentation (e.g. https://github.com/adobe-research/fondue) and cannot modify original sources on pages. Instead, I need to wrap some of the globally executed javascript in functions and later invoke them as if they were ran globally.
Comment: @RayonDabre -- this is what i feared, are there any crazy hacks that might make this work?
Comment: I don't know, I didn't downvote and it's not a bad question.  That explanation in the comment is helpful. No, you can't force the runtime to make local variables be global without your own modifications internally (to the runtime). Local variables are local, and that's that. Things like browser debuggers *do* have special access to runtime internals, of course.
Comment: @y3sh, Why cant you use `window.` ?
Comment: @RayonDabre I _could_ but don't want to. I'm augmenting source code that others wrote and don't want to modify their code. The use-case is to wrap statements executed in the global scope for tracing and analytics. But I may only be able to wrap the function body, not the "var" part.
Answer: There is only one way to add anything to window using the declarative var keyword and that is with the frowned upon with keyword.
with (window) {
  var bam = console.log.bind(console)
}

This will allow you to run window.bam('test') (at least in Chrome).
To learn more about the with keyword, checkout the MDN page for it.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/with

JavaScript looks up an unqualified name by searching a scope chain associated with the execution context of the script or function containing that unqualified name. The 'with' statement adds the given object to the head of this scope chain during the evaluation of its statement body. If an unqualified name used in the body matches a property in the scope chain, then the name is bound to the property and the object containing the property. Otherwise a ReferenceError is thrown.

Extra
The reason your bam in B is undefined is because the scope in the "block" is the defined function wrapperFn. That doesn't mean that wrapperFn.bam is defined but rather bam is only available to any other code available in the wrapperFn block.
Comment: Am I correct to assume that this will not work if you place the _with_ block inside a function?
Comment: Correct, the execution scope changes so declarations are non-visible  to the outside scope(s)
Comment: Just ran some tests, the only way to use `with` is outside of a function–  execute the `with` in the same scope of the `expression`
Answer: You can explicitly create properties of the global context (window):
function g() {
  window.someFunction = function() {
    console.log("hi!");
  };
}

g();
someFunction(); // "hi!"

Variables declared with var inside functions are explicitly not global, but nothing prevents you making a copy of a value into a global property.
function g() {
  var someFunction = function() {
    console.log("hi!");
  };
  window.someFunction = someFunction;
}

Without such an explicit assignment, local variables are not global and cannot be made so.
Comment: No, you didn't use var. I'll clarify this.
Comment: This answer does not provide anything new that was not already stated in the question or comments on the question.
Comment: @y3sh the direct answer to your question is **no**.
Answer: You can remove var and it attach to window. However, it's not good practice to having a dirty window object. It's better to create namespaces.
  function x() {
         theVar = true ; // global, attached to window
  }

Comment: Yes, but OP doesn't tell it
Comment: Agreed; I was just making that note for future Stackoverflow visitors :)
Comment: does this happen regardless of function context?
Comment: @y3sh a reference to an undefined symbol on the left side of an assignment will cause a global variable to be created when the code is not running in "strict" mode. In "strict" mode, the code in this answer would produce an error.
Comment: @MarcosPérezGude, Op wants it **using "var"**


Variance of median from the mixture distribution

Question: Consider iid samples from a fixed distribution function $F(x)$ and consider its median. Now consider another median from iid samples where one half is drawn from $F_1(x)$ and the other is drawn from $F_2(x)$ with $F_1(x)+F_2(x)=2F(x)$ for all $x$. Which median has a larger variance?
Comment: Homework?  If so, please add the homework tag...  consider constructing an example, e.g., with a distribution on $\{-1,1\}$ to help develop some intuition.
Comment: Are you assuming that the sample size is always even?
Comment: Do you know how the variance of the median depends on the size of the sample?
Comment: Let us assume that they have the same number of even samples.
Comment: I don't think there is enough information about F1 and F2 to answer the question.  Let m be the median of F then F(m)=1/2.  Since F1(m)+F2(m)=2F(m), one of the Fis has a median less than m and the other has a median greater than m (assuming both     F1(m) and F2(m) are greater than 0).  But this doesn't even tell us which one has the larger median.  The sample median is an order statistic and the properties of order statistics that can be found in David's book on order statistics and many nonparametric statistics tests may help.
Comment: Also Kendall and Stuart Advanced Theory of Statistics Volume 1 may have a lot of information on this.  In fact I think there is a closed form solution for the variance of the median.  But even given the formula I think you will find there is something missing to compute and compare the variances. My first guess is that the one with the larger median has the larger variance.  I would check the formula though.  This may be a trick question and F1 and F2 have the same variance for the sample median.  That may mean that you do have sufficient information to solve the problem.
Comment: Yes I have seen Sen (1968) formula (2.9) that seems to suggest that variance is decreasing. Please advise. http://projecteuclid.org/DPubS?service=UI&version=1.0&verb=Display&handle=euclid.aoms/1177698155
Comment: I try to understand the relationship between this formula and http://stats.stackexchange.com/questions/16608/what-is-the-variance-of-the-weighted-mixture-of-two-gaussians
Answer: I did a Google search for variance of the sample median and found the 1978 paper by Maritz and Jarrett.  I remember this paper as it is referenced in my bootstrap book where I used it to show an example where the bootstrap distribution can be obtained without need for the Monte Carlo approximation.  I didn't go to the trouble of working out the solution to this problem based on the paper because this is a homework type problem and the site suggests providing hints to the solution rather than doing it for the author of the question.  The paper is in JASA 1978.
Comment: The paper [On the median of a finite mixture](http://dx.doi.org/10.1080/00949659708811826) by Al-hussinp and Osman (Journal of Statistical Computation and Simulation 58(2) 1997 121--144) might (or might not) be helpful. It contains an iterative scheme for finding the median of a mixture.


A question about hypothesis testing and maximum likelihood ratio test

Question: Assume there are 2000 students, $m$ boys and the rest are girl. Now we take a sample of 5 students which contains only 1 boy. We claim that there are more girls than boys in the population. So what we want to do is to check the maximum likelihood under $H_1$ $H_0$, but the problem is I don't know how to get the maximum likelihood. Some said that it attains max when $m=400$ under $H_0$ but I don't quite get how they get.
Comment: What are your hypotheses? $H_0:$ as many boys as girls and $H_1:$ more girls?
Comment: I don't understand why you want to use ML at all. Can't you just use $\frac{P(1 boy, 4 girls|m>1000)}{P(1 boy, 4 girls|m\le 1000)}$?
Answer: Maximum likelihood and likelihood ratios are not the same thing. Maximum likelihood is an estimation method, whereas likelihood ratios are used to construct tests.
For both of these, you need the likelihood function. In this case it is the probability function of a random variable with a hypergeometric distribution, since $X$, the number of boys sampled, is hypergeometric. Then
$P(X=k)=\frac{\binom{m}{k}\binom{2000-m}{5-k}}{\binom{2000}{5}}$
To obtain the maximum likelihood, maximize this with respect to $m$ for $k=1$. Your claim seems to be that the maximum is given by $m=200$, i.e. when the proportion of boys is 400/2000=1/5=the observered proportion.
To obtain the likelihood ratio test, compute $-2\ln\frac{P_{H_0}(X=1)}{P_{H_1}(X=1)}$. Your hypotheses should be statements about $m$.


Drupal site shows frontpage instead of added content

Question: I'm restoring a client's site after they lost all information. After some trouble, we could restore their database, which now shows all tables. The problem is that, after uploading all files and connecting to the database, the page displays Drupal's default frontpage and says 'no content has been created yet'. The database contains all tables, and I'm assuming the connection is right; otherwise I'd get an error message.
Why aren't I seeing all info stored there?
Comment: what about table prefixes? have you checked them?
Answer: You might have all of the tables, but you might not have all of the rows, perhaps. Two tables to look at: node and node_revision. See of there are rows there.
Comment: You're right!  I had not checked to see if the db was complete but it's not, those tables are empty.  I'll find out what the problem was, thank you :)


How to find points of the edge of one sphere inside another sphere.

Question: I am highly unqualified for this kind of discussion, but I need it for a CS project that I am working on at the moment.
I have one large sphere and inside it is a smaller sphere. When this smaller sphere collides with the edge of the larger sphere, I want to get a grid of points that form the edge of the larger sphere in a relatively simplistic calculation (aka I don't want to test a large chunk of points to see if they form the edge). Here is a 2D version of what I want to do that I made in MS Paint:
Comment: You just need to intersect two circles. This is easiest if you place the origin inside your large circle and rotate so that the small circle is on the $x$-axis. Then the points of intersection lie on a vertical line. This is worked out in [*Computational Geometry in C*](http://cs.smith.edu/~jorourke/books/ftp.html) p.332ff, whose code is available.
Comment: From the figure I more or less get what points you want to retrieve, but what I don't understand here is what universe are we in and what representation of your points you want/need. Since you mentioned a grid and computer science, I guess it would be discrete geometry, and you want a list of every red point of the (3D?) sphere... ? If it isn't discrete geometry, getting an exhaustive list of the points is impossible, in which case it'd be good to precise what you mean by "grid". Also, do you want an exact result or are approximations fine?
Comment: @duper51 But which 10 or 20? When you say "grid", how do you mean the points should be aligned? That isn't a trivial detail. Note that your result is going to be x steradians of the larger sphere, no matter what, and the intersection area you specify has limits from a single point up to one half of the sphere.
Comment: You might find this useful: http://www.ambrsoft.com/TrigoCalc/Sphere/TwoSpheres/Intersection.htm
Comment: @N.Bach I'm looking to create a grid of points that are inside the red area in the diagram. I don't want the list of (infinite) points, just a way to calculate say 10 or 20 inside the red area.
Answer: Following up on your answer to my comment, I assume you need your points to be "evenly" spaced out on the spherical cap, and the tricky part here is what precise meaning you put behind the word "evenly".
In essence, you want to define some sort of spherical grid on the large sphere, then clip it with the smaller sphere. The problem with defining such a grid is that the easy and quick way to do that would be to use longitude/latitude coordinates on the sphere, and evenly divide the angle parameters so as to obtain a grid. The main problem with that approach, is that around the north and south poles, the density of the grid is much higher than around the equator as you can see in this image from wikipedia:

(yes I was too lazy to make my own picture)
A better way to define a grid on a sphere would be to use a geodesic grid. Once again a wiki link, if you scroll down the page they list some pros/cons of geodesic grids compared to the above longitude-latitude grid.
Anyway, back to the "simple" case.
Let's call the larger sphere $s_0$, it is centered at $c_0$ and has radius $r_0$. Likewise for the smaller sphere we use the notations $s_1$, $c_1$ and $r_1$.
Using maths convention for spherical coordinates, $P$ belongs to $s_0$ if its coordinates can be written
\begin{align*}
x_P&=x_{c_0}+r_0\sin\varphi\cos\theta \\
y_P&=y_{c_0}+r_0\sin\varphi\sin\theta \\
z_P&=z_{c_0}+r_0\cos\varphi
\end{align*}
When using a rectangular grid, you should center your grid around the equator to reduce anisotropy. The intersection between the two spheres define a circle, its center lies on the line joining the centers of the sphere, so we want the line $(c_0c_1)$ to intersect the equator of the grid. Using standard coordinates conversion, you can compute the parameters $\theta_1$ and $\varphi_1$ that correspond to the direction of line $(c_0c_1)$.
You can then rotate the whole thing to make $(c_0c_1)$ parallel to plane
$xOy$. Then take the points
$$\left(r_0,\ i\Delta\theta,\ \frac\pi2+j\Delta\varphi\right)$$
where $i,j\in\mathbb Z$, and $\Delta\theta$ and $\Delta\varphi$ are step values computed according to how many points you want, and rotate the whole thing back to its original position.
Just a heads-up, let $r$ be the radius of the circle of intersection between the two spheres. Assuming your small sphere is indeed always "small",
or more precisely that you only need values
$\lvert i\Delta\theta \rvert\le\frac\pi2$
and $\lvert j\Delta\varphi \rvert\le\frac\pi2$,
you need
\begin{align*}
\lvert \sin\left(j\Delta\varphi\right) \rvert &\le \frac r{r_0} \\
\cos\left(i\Delta\theta\right) &\le \frac r{\lvert\sin\left(j\Delta\varphi\right)\rvert r_0}
\end{align*}
for the point to be inside the small sphere.
One last thing, you can compute $r$ from $r_0$, $r_1$ and the distance between $c_0$ and $c_1$ using Pythagoras, so depending exactly what you want you should be able to tune the step values properly.
Answer: Let $r$ be radius of big circle and $s$ be radius of smaller. Assume big circle's middle is at origin and small circle's origin is at $(a,0)$ with $a>0$. In other words small circle's center is on positive half of $x$ axis.
Then the formulas for the circles are $r^2=x^2+y^2$ and $s^2=(x-a)^2+y^2$. To find the value of $x$ for where the circles intersect, then solve for $x$ using these two equations. Since $y^2=r^2-x^2$, substitute that into second equation to get $$s^2=(x-a)^2+r^2-x^2 \Rightarrow x = \frac{a^2+r^2-s^2}{2a} \tag{1}$$.
Then any value of $x$ between that computed using (1) and $r$ is in the range of the red arc (from OP). So points can be computed by plugging values of $x$ in that range into equation for big circle.


Verificar a existência de uma string em um arquivo a partir de outro arquivo

Question: Tenho dois arquivos, um é esse:
gp2,POL-AES-SHA1,Prop-AES-SHA1
gp2,POL-AES-SHA1-PFS-2,Prop-AES-SHA
POL-3DES-SHA,Prop-3DES-SHA

Repare que podem ter 2 ou 3 itens por linha (separados por virgula).
No segundo arquivo tenho:
Prop-AES-SHA1,sha1,aes-256-cbc,8
Prop-AES-SHA,sha1,aes-128-cbc,24
POL-3DES-SHA,sha1,3des
IPSEC-AES-256-MD5,md5,aes-256-cbc
IPSEC-AES-256-CBC-SHA256,sha256,aes-256-cbc,8

Repare que  pode ter 3 ou 4 itens por linha, também separados por vírgula.
A ideia é que eu pegue o último item de cada linha do primeiro arquivo e procure por ela no segundo arquivo. Se eu encontrar, eu trago todos os itens da linha e crie uma linha misturando itens dos dois arquivos.
Ele só analisa 1 linha e o código para:
file1 = open('file1')
file2 = open('file2')

for i in file1:
    i = i.strip().split(',')
    last_i = i[-1]
    for i2 in file2:
        if last_i in i2:
            print(f'{i} + {i2}')

Answer: Pelo que entendi, você quer apresentar todos que derem 'match', mas esse seu segundo for só esta percorrendo o arquivo uma única vez. Neste caso, ou você armazenaria o conteúdo dele em algum canto, ou teria que percorrê-lo novamente a cada iteração do i.
Desta forma deve resolver seu problema.
file1 = open('file1.txt')

for i in file1:
    i = i.strip().split(',')
    last_i = i[-1]

    with open('file2.txt') as file2:
        for j in file2:
            if last_i in j:
                print(f'{i} + {j}')

Comment: Gostaria de agradecer imensamente a sua ajuda. Obrigado pelo tok sobre a abertura do segundo arquivo. Funcionou, agora eu consigo ajustar o resultado do print e continuar com o script! Muito obrigado mesmo!


Selecionar uma linha em que uma coluna tenha um elemento de um CSV

Question: Eu tenho uma tabela no banco de dados com a seguinte estrutura:
+---------+---------+------+-----+---------+----------------+
| Field   | Type    | Null | Key | Default | Extra          |
+---------+---------+------+-----+---------+----------------+
| id      | int(11) | NO   | PRI | NULL    | auto_increment |
| numeros | text    | YES  |     | NULL    |                |
+---------+---------+------+-----+---------+----------------+

Nela, eu tenho os seguintes valores:
+----+-------------------------------------+
| id | numeros                             |
+----+-------------------------------------+
|  1 | 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 |
|  2 | 1,3,5,9,11,13,15                    |
|  3 | 2,4,6,8,10,12                       |
|  4 | 1                                   |
|  5 | 15                                  |
+----+-------------------------------------+

numeros é uma coluna que contém valores separados por vírgula (CSV).
Como posso selecionar as linhas que contenham algum número desse conjunto?
Por exemplo, selecionar todas as linhas em que a coluna numeros contenha o valor 1.
Eu tentei fazer casos como:
mysql> SELECT * FROM `tabela` WHERE `numeros` LIKE '%1%';
+----+-------------------------------------+
| id | numeros                             |
+----+-------------------------------------+
|  1 | 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 |
|  2 | 1,3,5,9,11,13,15                    |
|  3 | 2,4,6,8,10,12                       |
|  4 | 1                                   |
|  5 | 15                                  |
+----+-------------------------------------+

Neste caso ele acaba selecionando todos que tenham o número 1, literalmente. Como é o caso das linhas 3 e 5.
mysql> SELECT * FROM `tabela` WHERE `numeros` LIKE '%1,%';
+----+-------------------------------------+
| id | numeros                             |
+----+-------------------------------------+
|  1 | 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 |
|  2 | 1,3,5,9,11,13,15                    |
+----+-------------------------------------+

Já neste, parece funcionar bem, mas a linha 4 não é selecionada.
Fora que, eu tenho tentado evitar o LIKE, já que esse número será digitado pelo usuário. E como sempre dizem, nunca confie na entrada do usuário, ainda mais para um caso como o do LIKE.
Comment: Como é mysql, as opções são mais restritas. Usando o like você precisaria testar todos os casos que são: Único elemento na lista, elemento começando a lista, elemento no meio de 2 elementos da lista, e elemento terminando a lista. Pensou em fazer dessa forma? Não sugiro como resposta pois não seria muito elegante, mas daria pra resolver.
Comment: 1 mude o modelo , normalize esta tabela 2 mude o modelo , normalize esta tabela 3 não sendo possível aplique um "unpivot" nesta coluna , mysql não tem pronto que eu saiba mas existem soluções de contorno --- voc~e deve repensar um modelo quando respostas que deveriam ser simples se tornam complicadas.
Comment: Os números sempre são salvos de forma ordenada?
Comment: Não, e o número 1 foi só um exemplo, teria que funcionar para qualquer outro número
Comment: Sim, mas a lista de números seria ordenada sempre?
Comment: Não, já que o servidor aceita qualquer tipo de CSV, que contenha números então funcionaria com `4,1,3,5`, por exemplo
Comment: Ahh, então é mais complicado :)
Comment: É, quebrei muito a cabeça com isso aí haha
Comment: Qual o/a modelo/normalização certo/a para fazer isso?
Comment: Colocando na 3FN você não teria mais uma coluna multivalorada. Essa coluna seria uma tabela nova com uma chave estrangeira para a tabela que a originou. Aí seria moleza ajustar a consulta usando as 2 tabelas.
Comment: A única alternativa seria criar outra tabela? Eu estou pensando na agilidade da consulta. Imagine que eu teria vários usuários. Esses números seriam como recursos que eles tem. Eu queria consultar todos os usuários que possuem um certo recurso. Não ficaria muito pesado quando eu juntar muitos usuários e muitos recursos? Não só pesado em tamanho de pedido, mas pesado em espaço em disco.
Comment: Tente LIKE '%,@num,%' sendo @num um parâmetro de entrada do usuário.
Comment: Victor, no seu caso, acabou não pegando nenhuma linha da tabela como especificado acima.
Comment: Tente entao like '%,'||@num||',%' testei aqui e parece que funcionou.
Comment: Esse daí não deu certo comigo não
Comment: Não alterar o modelo implica em um sql complexo para fazer uma coisa simples
Answer: Você pode utilizar a função FIND_IN_SET() para encontrar a substring no conjunto, por exemplo:
SELECT * FROM tabela WHERE FIND_IN_SET('3', numeros);

Vai retornar todos que contenham o elemento 3:
| id |                             numeros |
|----|-------------------------------------|
|  1 | 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 |
|  2 |                    1,3,5,9,11,13,15 |
|  6 |                               3,1,8 |

Comment: Nunca ia imaginar que existiria isso aí. Muito obrigado cara!


mysql: import multiple databases from sql dump with prefix

Question: I have a mysql dump in a .sql file. There are many databases in it with DROP DATABASE and USE commands before each database.
On the running server are databases with the same names. I don't want to overwrite them. How can I import all these databases with a prefix and without dropping any existing databases/tables? But existing databases with the prefix should be overwritten.
Answer: Let's initialize some variables for ease of use:
DB_PREFIX=yourprefix_
FILE_MYSQLDUMP=/path/to/mysqldump.sql

Now get a list of existing databases (excluding tables that start with the prefix you don't mind overwriting and the information_schema and mysql tables which probably shouldn't be in mysqldump.sql anyway):
echo "SHOW DATABASES;" \
| mysql \
| egrep -v "^(Database|information\_schema|mysql|${DB_PREFIX}(.*))$" \
> /var/tmp/existing_databases

Now loop through entries in existing_databases and replace the CREATE DATABASE statements in $FILE_MYSQLDUMP:
while read DB_NAME;
do
  ARG_SED="-i 's/CREATE DATABASE \`"${DB_NAME}"\`/CREATE DATABASE \`"${DB_PREFIX}${DB_NAME}"\`/g'";
  eval "sed ${ARG_SED} ${FILE_MYSQLDUMP}";
done < <(cat /var/tmp/existing_databases)

And once more to replace the USE statements:
while read DB_NAME;
do
  ARG_SED="-i 's/USE \`"${DB_NAME}"\`/USE \`"${DB_PREFIX}${DB_NAME}"\`/g'";
  eval "sed ${ARG_SED} ${FILE_MYSQLDUMP}";
done < <(cat /var/tmp/existing_databases)

Finally you can import your revised database dump with mysql < ${FILE_MYSQLDUMP} ... and, providing there aren't any tricky instances of USE or CREATE DATABASE in your database dump's records (yikes) you should have overwritten databases matching yourprefix_ and created prefixed versions of the other databases in the dump file.
Planning to do this regularly? Check out the Advanced Bash-Scripting Guide - it's covers almost everything you need.
Credit + upvotes to Escape a string for sed search pattern for the eval method for handling sed arguments.


Spectra, Picard categories and their k-invariants

Question: I am trying to understand the following statement, which is taken from Appendix B, Proposition B.12 of Hopkins and Singer's paper:

The correspondence $$ E\mapsto \pi_{\leq 1}E_0 $$  is an equivalence
between the 2-category of spectra E satisfying $\pi_iE=0, i\neq 0, 1$
and the 2-category of Picard categories.

In a previous definition (Definition B.5), they defined the k-invariant of a Picard category $C$ as an abelian group homomorphism
$$\pi_0C\otimes\mathbb{Z}/2\rightarrow \pi_1C,$$ which is induced by a "twist" on the tensor product. Also, they had made $\pi_{\leq 1}E_n$ into a Picard category in Example B.7 (see my previous question).
In the proof of the above proposition, it seems to me they were relating the following two concepts of k-invariants:

k-invariant for Postnikov tower of spectra
k-invariant for Picard category

More precisely, for a spectrum $E$ with only $\pi_0,\pi_1$ nontrivial, its k-invariant (from the Postnikov tower of $E$)
$$ H\pi_0E\rightarrow \Sigma^2H\pi_1E$$
determines its homotopy type. Then they claimed that

The set of homotopy classes of maps $ H\pi_0E\rightarrow \Sigma^2H\pi_1E$ is naturally isomorphic to $$\mathrm{hom}(A\otimes\mathbb{Z}/2, B).$$

without pointing out what $A$ and $B$ are referring to. After that, they concluded the proof by relating the two concepts of k-invariant:

One can associate to a Picard category with k-invariant $\epsilon$, the spectrum E with the same k-invariant.

I am quite confused by their proof. Especially the part involving $A$ and $B$, also how they transfer the k-invariant of Postnikov tower to the k-invariant of Picard category.
Thank you in advance for any comments, answers, and corrections!
Answer: $A$ and $B$ are just $\pi_0$ and $\pi_1$; they're citing a nontrivial but old theorem of stable homotopy theory in moving to maps out of $A\otimes \mathbb Z/2.$
I'd suggest reading an actual proof of this result, which I believe wasn't done until Johnson and Osorno here: https://arxiv.org/pdf/1201.2686.pdf
Comment: @timaeus Here are some remarks from a friend I convinced to look into this a bit more. As JHF says, the intended reference in the paper you cited is (27.1). This is at the very end of a formidable paper and used many results obtained along the way.

The proof is by computing $H^5(K(A, 3); B),$ which is in the stable range; this is done by the universal coefficient theorem and the computation of integral homology groups in Section 23, in particular (23.2) and Theorem 23.1. (1/4)
Comment: The relevant part of (23.2) --- that $H_4(K(3, \Pi); \mathbb Z) = 0$ --- is Theorem 20.5, which is straightforward when $\Pi$ is cyclic (compute for Moore spaces), but requires understanding "cross effects" to handle the necessary direct limit arguments. (2/4)
Comment: Theorem 23.1 --- the computation $H_5(K(\Pi, 3); \mathbb Z)$ --- requires understanding the explicit cell structure of these complexes, introduced by EM in these papers, and a previous computation of $H_4(K(\Pi, 2); \mathbb Z).$ This computation, Theorem 21.1, is in terms of a "Gamma" functor introduced earlier in the paper. They argue by a direct limit arguments it suffices to prove the claim for $\Pi$ cyclic, where they do it by extremely explicit computation using techniques described in Sections 14 and 15. (3/4)
Comment: It is probably going to be extremely difficult to read this in any way other than from the start. Another more recent reference that proves the same (more?) results is https://arxiv.org/abs/1312.5676 which seems to be self contained at a glance. (4/4)
Comment: Thank you Kevin for this most informative answer! I am still trying to figure out how this old theorem $[H\pi_0, \Sigma^2H\pi_1] \cong \mathrm{Hom}(\pi_0/2\pi_0, \pi_1)$ works. In the paper you mentioned, the authors cited "(2.7)" from a paper by Eilenberg and MacLane, which I found to be some commutative rule for face and degeneracy maps. I find it hard to see how this rule leads to the isomorphism. Could you please give me some further clues about it?
Comment: @timaeus Oh, no! I'm not immediately sure of a better reference for that bit.
Comment: @timaeus I think the reference "(2.7)" in Johnson-Osorno should instead be (27.1) in the section "Higher cohomology groups" in the Eilenberg-MacLane paper.
Comment: Thank you @Kevin (and also your friend) so much for these great remarks!


recording my screen view app in iOS

Question: i am building an application that records everything going on on my screen, i have many views and a camera view opening, i have tried:
ASScreenRecorder *recorder = [ASScreenRecorder sharedInstance];

if (recorder.isRecording) {
    [recorder stopRecordingWithCompletion:^{
        NSLog(@"Finished recording");
    }];
} else {
    [recorder startRecording];
    NSLog(@"Start recording");
}

from ASScreenRecorder, and also Glimpse library, but every time it seems to record everything but the camera view, it shows as blank, any suggestions?
Comment: Have you tried the iOS framework ReplayKit?
Comment: using ReplayKit freezes the camera view, i am using AVCapture,
Comment: actually this might work, but is there a way to crop the recording view of ReplayKit?
Answer: It's not possible to take a screenshot of AVPlayer. You can use AVAssetImageGenerator to get the required image from AVAsset and then Merge/Blend it with the screenshot you are getting from ASScreenRecorder.
Getting image from AVAsset (Sample code):
AVAsset *asset = [AVAsset assetWithURL:sourceURL];
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc]initWithAsset:asset];
CMTime time = CMTimeMake(1, 1);
CGImageRef imageRef = [imageGenerator copyCGImageAtTime:time actualTime:NULL error:NULL];
UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);

recording my screen view app in iOS


ASP.NET Core 6.0 Web API error status: 400 title: "One or more validation errors occurred." for POST Request due to Foreign Keys

Question: I have been working on a project that uses .NET 6.0 and SQL and have been running into a status: 400 title: "One or more validation errors occurred." error whenever I try to make a POST request for my Treatments table as shown below (using Swagger).
400 - Undocumented
Error: response status is 400

Response body
Download
{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-471d5fa9b5bd60df0f6dddef0dcd44ad-4ed5f5f29428b83e-00",
  "errors": {
    "TblPet": [
      "The TblPet field is required."
    ],
    "Procedure": [
      "The Procedure field is required."
    ]
  }
}
Response headers
 content-type: application/problem+json; charset=utf-8
 date: Thu,14 Jul 2022 11:25:42 GMT
 server: Kestrel

The project follows this ERD:

The API was scaffolded using Visual Studio 2022 which created many public virtual items that are most likely a result from all the foreign keys that have been set. As a result, my GET requests would return the data for the specified table AND data from Foreign Key tables, so I have been using the [JsonIgnore] data annotation within the models to prevent this from happening which has been a solution so far.
The Treatments model class looks like this:
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;

namespace api.Models
{
    public partial class TblTreatment
    {
        public int Ownerid { get; set; }
        public string Petname { get; set; } = null!;
        public int Procedureid { get; set; }
        public DateTime Date { get; set; }
        public string? Notes { get; set; }
        public string? Payment { get; set; }
        [JsonIgnore]
        public virtual TblProcedure Procedure { get; set; } = null!;
        [JsonIgnore]
        public virtual TblPet TblPet { get; set; } = null!;
    }
}

With [JsonIgnore], the response body for the POST request looks like this, which is the response body that I would like. Maybe removing the payment section would be a good idea as each procedure already has a preset price and will not be changed during the POST request so by providing the procedureid, the API should automatically associate the price with the procedure. But again, I'm not too sure:
{
  "ownerid": 1,
  "petname": "Buster",
  "procedureid": 1,
  "date": "2022-07-14T11:25:31.335Z",
  "notes": "Broken Nose",
  "payment": "24"
}

However, without it, it looks like this, which requests data input for Treatments, Procedure table and Pets table as they have foreign keys attached to them:
{
  "ownerid": 0,
  "petname": "string",
  "procedureid": 0,
  "date": "2022-07-14T11:41:34.382Z",
  "notes": "string",
  "payment": "string",
  "procedure": {
    "procedureid": 0,
    "description": "string",
    "price": 0
  },
  "tblPet": {
    "ownerid": 0,
    "petname": "string",
    "type": "string"
  }

The POST request for the Treatments controller is as follows:
[HttpPost]
public async Task<ActionResult<List<TblTreatment>>> AddTreatment(TblTreatment treatment)
{
    _context.TblTreatments.Add(treatment);
    await _context.SaveChangesAsync();

    return Ok(await _context.TblTreatments.ToListAsync());
}

This format for POST requests have been working for my other controllers but not for the Treatments controller and I am not sure why. I suspect that the issue may be caused by the all foreign keys associated with the Treatments table, as the error is requesting data inputs for the foreign key tables (which I do not want to input). I am at a complete loss as to what needs to be changed.
Any advice on this would be greatly appreciated.
Comment: I would recommend not to use entities as models and introduce some [DTOs](https://en.wikipedia.org/wiki/Data_transfer_object) which will represent only needed data in concrete scenario and map them from/to entities (to reduce amount of code you can use some library for example automapper for this). This way you can prevent such scenarios and also other problems like overposting and so on.
Comment: Sorry, thank you for your advice Guru Stron
Comment: That's a good point. I didn't even know that was an option.
I will definitely take on board your advice for future projects.
Thanks again, Guru Stron.
Comment: I'm not Serge, but you are welcome)
Answer: since you are using net6 ALL NOT REQUIRED properties should be nullable explicitly. So you should try this
        public string? Petname { get; set; }
        public int? Procedureid { get; set; }
        [JsonIgnore]
        public virtual TblProcedure? Procedure { get; set; }
        [JsonIgnore]
        public virtual TblPet? TblPet { get; set; }

or another way is that you can remove a nullable option from a project file
<PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>

    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

or add this line into config (startup or program)
services.AddControllers(
options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true

Comment: options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes might be the single longest boolean property within the framework.  And it is exactly what I needed. Upgrading from NET5 NET6 and enabling nullable in my project files caused this issue, but it went unnoticed until I started regression testing against old API endpoints.  So at that point I had a hell of time tracing it back to this.  Thanks for the answer!
Comment: +1 for comprehensive answer with 3 possible approaches. My use case involves consuming models from a .net standard nuget package, so explicitly nullable properties isn't an option. Removing the nullable option is overkill, it's a feature I want in the rest of the project and the startup approach also didn't work, possibly because of the models' source. Any other ideas? I've had to specify query parameters individually and make them nullable for now.
Answer: as a note for others finding this post,
we had the problem in our Azure APIs (same error), Suddenly - after a release with no changes that should introduce this error.
(pipelines for different environment have the same setup, code is the same... )
My colleague told me they had a similar error a year ago, API worked in production and acceptance but not in dev/test
I was about to set the controller option "SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true"
but found the newtonsoft option "NullValueHandling.Ignore;" in our startup and disabled the option.
.AddNewtonsoftJson(options =>
                {
                   options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                });

The API worked again (the strange thing was that we had working API in dev environment but not in production and it wasn't possible to replicate on local machine.
Then uncommented the code (reverting it) and API still works after deploy... Confusing
then I installed the same build again, the one not wokring, to see if we just needed a reinstall or restart - but the error was back.
I haven't validated yet but my theory is that the reason could be that we get different build-agents from azure, we are currently using "windows 2022" but not specifying the dotnet version with build step "Use .NET Core" and SDK version, f ex sdk 6.0.300


Prove there is an orthogonal basis for $V$ of eigenvectors for both $T$ and adjoint $T^*$

Question: Let $V$ be a finite-dimensional vector space. Let $T:V\to V$ be a linear map such that $T^*T=TT^*$, where $T^*$ is the adjoint of $T$.
I've shown that if $v$ is an eigenvector of $T^*$, then $\langle v\rangle ^{\perp}$ is $T$-invariant and that $\ker (T-\lambda I)$ is $T^*$-invariant.
Using these facts, how do I show that there exists an orthogonal basis for $V$ consisting of vectors which are eigenvectors for both $T$ and $T^*$?
Answer: For any normal operator $S$ (that is, $S^*S=SS^*$) you have
$$
\|Sv\|^2
=\langle S^*Sv,v\rangle= \langle SS^*v,v\rangle=\|S^*v\|^2.
$$
This gives you that, for any $\lambda\in\mathbb C$,
$$
\ker(T-\lambda)=\ker(T^*-\overline\lambda).
$$
From this it follows that $T$ and $T^*$ have the same eigenvectors. Now you can start with a unit eigenvectors $v_1$ for $T$. You have already shown that $\{v_1\}^\perp$ is invariant for $T$; so there is a unit eigenvector $v_2$ for $T$, orthogonal to $v_1$. Now work on $\{v_1,v_2\}^\perp$, and repeat.


Add target="_blank" to menu item of type MENU_LOCAL_ACTION

Question: How can I add a target="_blank" property to a menu item of type MENU_LOCAL_ACTION ? I cannot do 'options' on MENU_LOCAL_TASK, MENU_DEFAULT_LOCAL_TASK, and MENU_LOCAL_ACTION items.
I tried with jQuery
(function($) {
    $(document).ready(function() {
        $('.page-admin-commerce-reports-incomplete-payments .action_links li a[href]').attr({
            target: "_blank",
            title: "Opens in a new window"
        })
    });
}(jQuery));

But it didn't work.
Thanks!
Answer: There seems to be a module for this: Menu target.
In case you need to do it programmatically, you can have a look at the source code for inspiration. As far as I see, the module adds a special class to the menu items you select, and then some JS captures the click and opens a new window:
  $('a.target-blank', context).once('target-blank', function () {
    $(this).click(function() {
      window.open(this.href);
      return false;
    });
  });

Answer: So I misspelled the class name!
.action-links not .action_links
My fault, the jQuery code worked fine.
Answer: You could try Menu Attributes module. It works with Drupal 8 as far as I know


Fill in Times between Dates, can it be done without a recursive cte

Question: The below code gives me the correct result but in sql could it be done without a recursive cte?
Maybe a cross apply.
declare @t table
(locationID int,
 StartTime datetime,
 EndTime datetime
)

 insert @t
 values (1,'1900-01-01 08:00','1900-01-01 19:30')
 ;
 insert @t
 values (2,'1900-01-01 10:00','1900-01-01 15:00')
 ;
 insert @t
 values (3,'1900-01-01 09:30','1900-01-01 21:00')
 ;
with cte_t
as
(
  select locationID, StartTime, EndTime, StartTime as [Time]
  from @t
 union all
  select locationID, StartTime, EndTime, dateadd(mi,30,[Time]) as [Time]
  from cte_t
  where [Time] < [EndTime]
)

select * from cte_t order by locationID

Comment: With a physical table [like this](https://stackoverflow.com/a/32474751/5089204) you will have a very handsome list of values you can use in various scenarios. A pure numbers table is fine, but you can add a lot of addtional information to this...
Comment: https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=c1ffdd41faaaa631a11877bce65f982f
Comment: Yes, with a Tally Table. They're much faster than an rCTE.
Comment: Recursive CTE returning 59 row where as CROSS APPLY only 9. Which one is expected?
Comment: OK thanks Larnu so you mean like this example first create the times in a cte and join.
Comment: https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=254c23fa99ddb9543fd233e0e5362073
Comment: sorry mkRabbani I don't understand where is the 9 rows from the cross apply coming from?
Answer: with sample_data_table
as
(
    select locationID,cast(StartTime as datetime) as StartTime,cast(EndTime as datetime) EndTime
    from (values (1,'1900-01-01 08:00','1900-01-01 19:30')
                ,(2,'1900-01-01 10:00','1900-01-01 15:00')
                ,(3,'1900-01-01 09:30','1900-01-01 21:00')
    ) t(locationID,StartTime,EndTime)
)

, cte_times AS
(
 SELECT  TOP ((DATEDIFF(HOUR , cast('19000101' as datetime), cast('19000102' as datetime))*2))
 ROW_NUMBER() OVER (ORDER BY number) AS rownum,
 DATEADD(minute, (ROW_NUMBER() OVER (ORDER BY number) -1)*30, cast('19000101' as datetime)) AS dt
 FROM [master].dbo.spt_values
 WHERE [type] = N'P'
)

 select a.*, b.*
 from sample_data_table as a
 inner join cte_times as b on a.StartTime <= b.dt and a.EndTime >= b.dt
 order by a.locationID,b.dt

Comment: Just search the internet - [numbers table](https://stackoverflow.com/questions/1393951/what-is-the-best-way-to-create-and-populate-a-numbers-table)
Comment: Tally Table...like I have my example above? so there are only two possible ways rCTE and Tally ( and I guess loop).


Executar método no form1 para alteração no form2

Question: Estou desenvolvendo um gerenciador de estoque, e os dados estão sendo armazenados em um banco de dados. O problema que estou enfrentando é o seguinte: quando eu adiciono um novo produto por exemplo, criei um botão "Atualizar lista" (deixei em vermelho na imagem), que quando o usuário clica nele, ele atualiza o ListView e mostra o novo produto inserido.

Acontece o seguinte, quando a pessoa clica em "Novo produto" (para adicionar um novo produto), abre uma nova form para fazer o cadastro.
O que eu estou tentando fazer, é atualizar a ListView dos produtos (que está no form1), quando o usuário cadastra um produto pelo form2.
Eu já tentei instanciar a classe da form1 e chamar o método, não da erro nenhum, porem a ListView dos produtos não atualiza. Como posso resolver?

Método para atualizar a ListView que eu estou usando:
<code>// Método para atualizar a ListView Produtos
public void RefreshList()
{
    // Limpar o campo da List View
    listView_Cliente.Items.Clear();

    // Lógica para atualizar a list view
    con.Open();
    cmdListView = new SqlCommand("select * from produtos", con);
    da = new SqlDataAdapter(cmdListView);
    ds = new DataSet();
    da.Fill(ds, "estoque");

    con.Close();
    dt = ds.Tables["estoque"];

    int i;
    for (i = 0; i <= dt.Rows.Count - 1; i++)
    {
        listView_Cliente.Items.Add(dt.Rows[i].ItemArray[0].ToString());
        // temos 4 colunas (sendo uma a ID), então aqui só criamos 3, a ID vai automática
        listView_Cliente.Items[i].SubItems.Add(dt.Rows[i].ItemArray[1].ToString());
        listView_Cliente.Items[i].SubItems.Add(dt.Rows[i].ItemArray[2].ToString());
        listView_Cliente.Items[i].SubItems.Add(dt.Rows[i].ItemArray[3].ToString());
        listView_Cliente.Items[i].SubItems.Add(dt.Rows[i].ItemArray[4].ToString());

    }
}
</code>
Basicamente então instanciei a classe do form1 (que está o método para atualizar o ListView) para o form2, lá eu chamei o método para atualizar o ListView, o Visual Studio não apresentou erros, porem, o List View não atualiza. Tentei fazer de outras maneiras em algumas postagens gringas que eu vi, porem, também sem sucesso. Agradeço qualquer ajuda!
Comment: Já tentou chamar o método de atualizar lista no final do método cadastrar?
Comment: Tentei, também não da erro, mas não atualiza. Será que tenho que fazer alguma mudança no código para que ele identifique que a ListView que quero atualizar está em outro form?
Estou fazendo dessa maneira:
1. Instancio a classe que possuí o método e a List View:
TelaLogado atualizarEstoque = new TelaLogado();
2. Chamo o método no objeto instanciado (dentro do método de cadastrar):
atualizarEstoque.RefreshList()
Comment: Você não precisa executar o `Bind()` do componente após atualizar seus itens?
Answer: Como um primeiro passo, ao inves de fazer new Form1(), na hora que voce faz new Form2(), passa por parametro a listView_Cliente, assim voce vai estar passando por referencia (quando se passa um objeto por parâmetro, no C# é padrão passar por referência) esse componente do Form1, assim quando voce alterar algo nele, vai refletir na instancia original do Form1.
Uma coisa interessante de entender nesse caso é que cada instancia tem 'vida própria', entao se criar uma nova instancia de Form1, não vai afetar a instancia anterior de Form1. Entender isso já é um grande passo para entender o 'runtime', da utilidade de se ter ou não novas instancias, e a importância de passar parametros por referência.
Despois que conseguir acertar, existe formas mais "elegantes" de tratar isso,  como usar delegates, é bom ver para depois entender até como algumas coisas funcionam no windows forms.
Answer: Obrigado a todas as respostas. O que ocorreu é que meu caso em específico eu abria a form2 e mantinha a form1 aberta. Quem fechava no final era a form2 somente. Enfim, eu consegui atualizar a ListView passando por parâmetro e abrindo a form1 novamente (meio gambi), porem, a form1 ficava aberta em duplicidade, e não conseguia fechar a duplicidade.
Como fiquei um tempão preso nesse problema, precisei ser objetivo na solução (vi na NET que outro meio de resolver isso é através de BIND, caso eu alguém precise).
Eu resolvi da seguinte forma, na hora de abrir a form2, ao invés de usar somente "form2.Show()", usei "form2.ShowDialog()", e na sequência chamei o método que atualiza minha ListView. QUando usa o ShowDialog(), assim que fecho a form2, ele chama esse método e atualiza a Lista. Não é exatamente o que eu estava pensando, mas já melhorou muito o funcionamento do programa, e cumpriu o objetivo principal que era retirar o botão para o usuário ficar atualizando a lista. Assim que sobrar um tempo maior vou estudar sobre o BIND
Como ficou o código:
<code>AddProduct telaProduto = new AddProduct();
            telaProduto.ShowDialog();
            RefreshList();
</code>