Obter data de uma string

Question: Estou tentando criar uma expressão regular que retorne algumas datas contidas em strings. Os formatos são:

dd/MM/yyyy
dd-MM-yyyy
dd/MM
dd-MM

Ex:
public static void main(String[] args) {

    final String text1 = "Foo bar foo bar foo bar 29/01/2021 foo bar foo bar";

    final String text2 = "Foo bar foo bar 29-01-2021 foo bar foo bar";

    final String text3 = "Foo bar foo bar 29/01 foo bar foo bar";

    final String text4 = "Foo bar foo bar 29-01 foo bar foo bar";

    // result 29/01/2021
    final String date1 = getDate(text1);

    // result 29-01-2021
    final String date2 = getDate(text2);

    // result 29/01
    final String date3 = getDate(text3);

    // result 29-01
    final String date4 = getDate(text4);

}

private static String getDate(final String text) {
    return "Magic";

}

Answer: Conforme já explicado aqui, uma regex pode ajudar a encontrar algo que se pareça com uma data, mas ainda será importante validá-la - leia o link já indicado para mais detalhes, mas de maneira resumida, uma data possui regras complexas demais para serem validadas por uma regex (como a quantidade variável de dias em um mês, principalmente para fevereiro em anos bissextos).
Então você pode usar a regex para obter o trecho que contém uma possível data, e em seguida validá-lo com as ferramentas específicas (no caso, uma API de datas). Algo assim:
private static Pattern POSSIBLE_DATE_REGEX = Pattern.compile("\\b\\d{2}[-/]\\d{2}([-/]\\d{4})?\\b");
private static DateTimeFormatter DMY = DateTimeFormatter.ofPattern("[dd-MM[-uuuu]][dd/MM[/uuuu]]").withResolverStyle(ResolverStyle.STRICT);

static String getDate(String text) {
    Matcher matcher = POSSIBLE_DATE_REGEX.matcher(text);
    if (matcher.find()) { // se encontrou, valida a data
        String possivelData = matcher.group();
        try {
            DMY.parseBest(possivelData, LocalDate::from, MonthDay::from);
        } catch (DateTimeParseException e) {
            // data inválida (se quiser, imprima o erro: System.out.println("Erro: " + e.getMessage());
            return null;
        }
        return possivelData;
    }

    // se não encontrou, retorna null
    return null;
}

...
System.out.println(getDate(text1)); // 29/01/2021
System.out.println(getDate(text2)); // 29-01-2021
System.out.println(getDate(text3)); // 29/01
System.out.println(getDate(text4)); // 29-01

A ideia é pegar algo que se pareça com uma data: 2 dígitos (\d{2}), seguido de barra ou hífen ([-/]) e mais 2 dígitos (e opcionalmente, outra barra ou hífen e mais 4 dígitos - o ? após deste trecho torna-o opcional). Em volta da expressão eu coloco \b (explicado em detalhes aqui) para garantir que não haja outro dígito antes ou depois (assim evito casos como 123456/789, pois se não tivesse o \b a regex acabaria pegando o trecho "56/78").
Mas como essa regex também pode pegar coisas como "99/99/9999" (que é uma data inválida), e no link já indicado é explicado como seria difícil fazer uma regex mais precisa, eu prefiro usar a API de datas (no caso, o java.time, disponível a partir do Java 8) para verificar se a data é válida.
Para isso eu uso patterns opcionais (indicado pelos [ ]), então [dd-MM[-uuuu]][dd/MM[/uuuu]] diz que posso ter "dia-mês" (com "-ano" opcional) ou "dia/mês" (com "/ano" opcional).
Depois, no parseBest eu passo as possibilidades de objetos que podem ser criados (LocalDate e MonthDay, respectivamente classes que possuem dia, mês e ano, ou somente dia e mês). Se alguma delas conseguir ser construída, é porque a data é válida. Senão, é lançada uma exceção.
Para os casos em que não há uma data, ou ela é inválida, estou retornando null.

Java <= 7
Para Java <= 7, o java.time não está disponível, então você tem que usar SimpleDateFormat. A ideia é similar:
private static List<SimpleDateFormat> FORMATS = Arrays.asList(createFormat("dd-MM"), createFormat("dd-MM-yyyy"), createFormat("dd/MM"), createFormat("dd/MM/yyyy"));

private static SimpleDateFormat createFormat(String format) {
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    sdf.setLenient(false); // para validar corretamente as datas
    return sdf;
}

static String getDate(String text) {
    Matcher matcher = POSSIBLE_DATE_REGEX.matcher(text);
    if (matcher.find()) { // se encontrou, valida a data
        String possivelData = matcher.group();
        for (SimpleDateFormat sdf : FORMATS) {
            try {
                sdf.parse(possivelData);
                return possivelData;// se deu certo, não precisa testar os outros formatos
            } catch (ParseException e) {}
        }
        // se todos forem inválidos, é porque não encontrou
        return null;
    }

    // se não encontrou, retorna null
    return null;
}

Comment: Excelente resposta. Pequeno adendo, quando as *patterns* ou configurações de *parsing* se tornam complexas a classe [`DateTimeFormatterBuilder`](https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/time/format/DateTimeFormatterBuilder.html) pode ajudar a construir um `DateTimeFormatter`
Comment: Obrigado! Me ajudou muito!
Comment: @AnthonyAccioly Sim, eu também fiz uma versão com o builder, mas neste caso específico não vi muita vantagem: https://ideone.com/k69yHi - quando há somente campos opcionais, os colchetes já resolvem bem, eu costumo usar o builder [em outros casos](https://pt.stackoverflow.com/search?q=user%3Ame+DateTimeFormatterBuilder) :-)

Obter data de uma string


Sending a message to a remote terminal

Question: Is there a way to send a message to a remote terminal similar to using the wall command for other users on the local system?  In this scenario I want to specify a username@hostname and have a message appear in their terminal if they are logged in.
Answer: You can use the write command to send messages to a specific user instead of to everybody. You can send them over the network using whatever login credentials you already have, usually over ssh like this: ssh youruse@hostname write username to send username@hostname a message.
Comment: this opens up a connection to write message to the user, and I have to manually close the connection . How can I just open up a conncetion, send the message and close it. I want to write this inside a bash script
Comment: @Eular The same way you do for *any* STDIN stream in a shell. You can type a message and end it with CTRL-D, or pipe content to the command: `echo foo | ssh ...`.
Answer: you can use nc for example
in receiving host type  nc -l port_number and in sending host type nc ip port_number  like
nc -l 3106

in receiving host and
nc 192.168.32.98 3106

in sending host for me that worked
Comment: "Terminal", not "TCP port".
Comment: but you can see this message in your terminal

Sending a message to a remote terminal


Which hosting controller should I install in a dedicated server, that can handle PHP 5.3?

Question: Hey everyone, I'm new to server administration, so I'm just trying to find a good hosting controller that let me do/have these things in my new dedicated server:
- Create hosting accounts, each one with its own bandwidth/storage limits.
- PHP 5.3
- MySQL
Someone told me to install CentOS and Klox, but from what I read, klox does not support PHP 5.3. Any thoughts?
Answer: CentOS 5 (and I guess Red Hat Enterprise Linux 5 too) doesn't have great support for PHP 5.3, at least in it absence of it in the official yum repos.  Latest version available there is 5.1.6 which is pretty old...
If you are just starting out on this path, and require PHP 5.3 you might want to use another distro that does officially support PHP 5.3.  Ubuntu Server 10.10 has PHP 5.3 in its official apt packages.


Active Directory Sync: Change user's UPN

Question: How do I reconfigure Azure AD sync, used for making single-sign-on possible for Office365 from inside the domain, so that the domain name part of a user's UPN can change when synchronized?
E.g. assume the local domain is ad.contosolocal.com, and the external domain is contoso.com. Currently, only exact copying works, by matching its ID, e.g. by using MSonline;
$username="bob"
$UPN = (-join($username, "contoso.com"))
$guid=(get-ADUser $username).Objectguid
$immutableID=[system.convert]::ToBase64String($guid.tobytearray())
Set-MsolUser -UserPrincipalName $UPN -ImmutableId $immutableID

This does not work  very smoothly or reliably: it takes multiple sync attempts, manually fully synchronizing and running each possible option twice for both connectors, for a total of 16 synchronizations (2x2x import, export, sync, and delta), before Azure AD decides to set the UPN to the correct value, and not immediately but about 15 minutes later. It seems to want to set the UPN to bob instead of firstname.lastname@example.com for some to me as-of-yet inexplicable reason. Dealing with this for many users is frustrating for them as logins break while values are not set correctly.
Then I want:
+--------------------------+------------------+------------------+
|       Local value        |  Sent to Azure   |   Azure Value    |
+--------------------------+------------------+------------------+
| firstname.lastname@example.com  | email@example.com  | firstname.lastname@example.com  |
| email@example.com | email@example.com | firstname.lastname@example.com |
+--------------------------+------------------+------------------+

If this is naïvely done by making my own 'Synchronization rules' it breaks passwords (users are no longer able to log in, with 'password invalid' errors). Passwords only work when the user's UPN matches what it is online, even if password sync is turned off (seems like this is a bug). Of course, the e-mail domain matches that of the website, which means if local paths start doing the same this leads to DNS problems; no longer being able to access the company's website from the local domain.
The other way around, using  ad.contosolocal.com as the login online is also not really a viable option, users want to login using the 'real' domain name. (Aside from the number of support hours it would take to get all of them to change the login domain in all their programs on all their devices)
It is also possible for me to place the user's remote-UPN in a different local-AD-attribute (typically the mail attribute), in that case I could change the sync to match mail to UPN.
Unfortunately, re-running the Azure AD Connect wizard; it does not give me any options to change what I've got the UPN mapped to. It seems to simply not display the option after the first time you've ran it.
I want this to happen:

Passwords and usernames are synchronized from local AD to Azure AD.
The local domain part of UPNs is always a fixed value.
The remote domain part of the matched UPNs is always a fixed (different value)
Users need to be able to log in to Office365 from both outside the internal network, as well as inside.
Office-365 uses Single-Sign On; local outlook/word/etc. automatically logs into office-365 without having to provide credentials.

Q: How?
Comment: How often have you been performing this ridiculous procedure?
Answer: That sounds like "Prepare a non-routable domain for directory synchronization".
In essence, you need to add the domain.com into "Active Directory Domains and Trusts" MMC. Righ-click, go to properties and add UPN.
Overall have a look here:
https://docs.microsoft.com/en-us/microsoft-365/enterprise/prepare-for-directory-synchronization?view=o365-worldwide


Calculating $e^{i2\pi ab}$

Question: I'm trying to calculate this expression $e^{i2\pi ab}$ where $a$ is an integer and $b$ is a real number.
One of the laws of exponents states that $a^{bc}=\left(a^b\right)^c$.
Applying that law gives us $e^{i2\pi ab}=\left(e^{i2\pi a}\right)^{b}$. Furthermore we know that $e^{i2\pi n}=1 $, $ \forall n \in \mathbb Z$.
Which means that $\left(e^{i2\pi a}\right)^{b}=1^b=1$. However this is wrong for $b\in \mathbb {R}$. In which of the steps have I made en error?
Comment: Welcome to Mathematics Stack Exchange.  Cf. [this question](https://math.stackexchange.com/questions/3219025/why-22-5-isnt-equal-to-2251-10)
Answer: That "law of exponents" you cite --- where'd it come from? Algebra 1, where you learned it worked for integer values of $b$ and $c$? Calculus, where you learned it worked for real values of $b$ and $c$ (and maybe learned that they had to be positive for it to actually make sense)?
Have you ever seen it stated or proved for complex numbers? Probably not, because it's not (generally) true when $a$ or $b$ is complex. Your question provides a nice example of the kind of failure that can occur in the complex case.
So that's where your argument goes wrong: you've overgeneralized something you learned earlier, without confirming that the generalization was valid.

Calculating $e^{i2\pi ab}$


Is there an alternative to hook_webform_submission_render_alter()?

Question: In Drupal 7, I was able to use hook_webform_submission_render_alter() to alter the rendering of webform submissions. For example, I was able to completely remove the display of specific fields depending on their answered values.
I am looking to do the same in Drupal 9, where that hook no longer exist. I tried different approaches with no luck so far.
What would be the alternative to hook_webform_submission_render_alter() in Webform?
Comment: A more precise replacement would be one of the Entity API implementations.
Comment: hook_webform_element_access may work for you. These are entities so do read https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/group/entity_crud/9
Comment: @cilefen

While not being a direct alternative to hook_webform_submission_render_alter, your suggestion to use hook_webform_element_access in order to hide webform field when viewing submissions works great in that case!

Thank you very much, you saved me some headaches! :-)
Answer: Based on your specific use case, you can use hook_webform_element_access to hide elements.


Solve for unknown matrix $S = M + \Lambda S \Lambda$

Question: Given a diagonal matrix $\Lambda$ (with at most one entry equal to zero) and an arbitrary matrix $M$, is it possible to determine $S$ from the matrix equation $S = M + \Lambda S \Lambda$?
I do not have any experience in solving equations like this, so any suggestions on how to start would be most welcome. Recommendations for (introductory) literature on the topic would also be much appreciated.
Answer: This is very simple because $\Lambda$ is diagonal.
Write out
$$
S = M + \Lambda S \Lambda
$$
in coordinates
$$
S_{ij} = M_{ij} + \sum_{kl} \Lambda_{ik} S_{kl} \Lambda_{lj}
$$
Because $\Lambda$ is diagonal than this simplifies to
$$
S_{ij} = M_{ij} + \Lambda_{ii} S_{ij} \Lambda_{jj}
$$
Form this you get
$$
S_{ij} = \frac{M_{ij}}{ 1- \Lambda_{ii}\Lambda_{jj}}
$$
And you can see the condition under which your equation has a solution
$$\Lambda_{ii}\Lambda_{jj} \neq 1 \qquad \text{or} \qquad M_{ij} = 0$$
Comment: Thanks! Hmm, $\Lambda_{11} = 1$, all other $\Lambda_{ii} < 1$. However, the value of $S_{11}$ (in fact the entire first column $S_{i1}$) seems to be irrelevant in my case, since $S$ is eventually post-multiplied by a column vector whose first entry is $0$ (I didn't mention this because it didn't seem relevant).
Comment: And what is $M_{11}$? If it is zero, than you are fine. The condition should be a little different, I edited the answer.
Comment: Yes, $M_{11}$ happens to be zero (in fact the entire first row of $M$ is zero, but the other bits of $M$ are arbitrary). This means that $S_{11} = \frac{0}{0}$, but I don't see why this would be defined as zero in this case?
Comment: Well the equation for $S_{ij}$ is $(1- \Lambda_{ii}\Lambda_{jj})S_{ij} = M_{ij}$. Only when $1- \Lambda_{ii}\Lambda_{jj}$ is nonzero, than you can divide by it and obtain $S_{ij} = \frac{M_{ij}}{ 1- \Lambda_{ii}\Lambda_{jj}}$. If both $M_{ij}$ and $1- \Lambda_{ii}\Lambda_{jj}$ is zero than $S_{ij}$ can be anything.


Balakrishnan identity

Question:
I don't know how to arrive to (4) in which $0<s<1$ and (5) identities [edit: 5th identity here ][2] in https://arxiv.org/abs/1808.05159v1. My attempt to (4) was using $\frac{1}{\Gamma(-s)}=\frac{\Gamma(1-s)}{-s}$ and rewriting the right hand side as a double integral
$$
\lambda^s = \int_{0}^\infty \int_{0}^\infty( x^{-s}e^{-x} + \frac{e^{-\lambda y}-1}{y^{1+s}}) dx dy
$$
but I don't think that gets me anywhere. Thank you for the help
Answer: Assume that $\lambda > 0$ and $0 < s <1$.
Integrating by parts, we have $$I = \int_{0}^{\infty} \left(e^{- \lambda t}-1 \right) \frac{\mathrm dt}{t^{1+s}} = \frac{\left(1-e^{ -\lambda t}  \right)}{st^{s}} \Bigg|_{0}^{\infty}  - \frac{\lambda}{s} \int_{0}^{\infty} \frac{e^{- \lambda t}}{t^{s}} \, \mathrm dt.  $$
Since $\lambda > 0$ and $s>0$, the boundary term vanishes at infinity.
And since $0 < s <1$, the boundary terms also vanishes as $t \to 0^{+}$.
So we have $$I =  - \frac{\lambda}{s} \int_{0}^{\infty} \frac{e^{- \lambda t}}{t^{s}} \, \mathrm dt.$$
Now make the substitution $u = \lambda t$.
$$I = - \frac{\lambda^{s}}{s} \int_{0}^{\infty} \frac{e^{-u}}{u^{s}} \, \mathrm du = - \frac{\lambda^{s}}{s} \, \Gamma(1-s) =  \lambda^{s} \,  \Gamma(-s)$$

Balakrishnan identity


Get submission values from a Webform

Question: I've got two fields in my form which are called geographicarea and specialty.
I'd like to use these values in an SQL query when the form is submitted.
How can I do it?
Answer: If I understand you correctly, you'd like to get a hold of the data before it gets inserted in the database so you can do something else with it?
If this is the case, hook_webform_submission_presave is your friend.
The $submission object will hold the submission data. This lets you change it before it's inserted in the database or, as in your case, just do something else with it.
Here's a list of all the webform hooks for D7 (with a link to D6 hooks as well if that's what you're using).

Get submission values from a Webform


Is there some way in firebase firestore to block the user from signing in with the same email or gmail account?

Question: I'm curious if it's possible in firestore to block the user's gmail or email account and prevent that user from signing in or registering again
Answer: If you go to authentication and disable that user, they will not be able to sign in or register
Answer: You can disable the user to prevent further access. You can't disable user using client SDK(react in your case), must use firebase admin API to do this. Something like this:
<code>admin.auth().updateUser(uid, {
    disabled: true
});
</code>
For more info:
https://stackoverflow.com/a/43141780/8087468
Comment: I actually plan to add something like a 'block' button in which the admin can block that user from using his or her gmail or email account. I'll need to install the firebase admin SDK then
Comment: You can use server or firebase functions between client and that function, the flow should be like this that you/Admin will click on the block button it would send the request to server or firebase function which would eventually run this piece of code.


Looking for piano studies to assist in playing melodies consisting of chords

Question: I've realized that a big skill im having trouble with is playing melodies that involve significant chord changes in either hand. As an example, I cannot get through Debussy Claire de Lune once it becomes primarily a chord driven melody (sorry, I don't have the music on front of me. it's the section after the introduction).
I can brute force my way through it, sure, but I've recently started really focusing my study on my weak points, and sticking with a piece I'm brute forcing isn't helping me in general.
What are some good pieces to gradually help me to get better at playing chords like the ones in that Debussy piece? To clarify, I'm looking to improve in my ability to read chords quickly, rather than memorize hand positions.
Comment: Note the the (broken) chords are accompaniment, not melody. The melody still consists of mostly single notes, mainly in the right hand.
Comment: You're not stating whether you find it technically difficult (e.g., does your (left, presumedly) hand cramp up or hurt; or whether you have a problem *reading* the actual broken chords. The letter is made more difficult in Claire de Lune because of it's key, D-flat major.
Comment: Usually my issue is that I can read music with at most 3 note chords and play smoothly. When the number of notes increases I have to stop at every chord, read it, and then continue. Even worse, since I can't read the chords fast enough I find that the only way to make it through such a passage is to memorize it. My goal is to be able to play more pieces from sight or at least while reading to reduce the time spent before I can play them smoothly, so this is not ideal.
Comment: "I find that the only way to make it through such a passage is to memorize it.": which in a sense, is what should happen. It's really hard to look up the notes every time you have to play them, especially since there are two staves to look at. One tip could be to learn to "feel" the broken chord arpeggios, by playing variations (just one hand first) of them first, in the relevant key(s).
Comment: I think there is a difference then between learning a piece for performance and learning it to just play. I enjoy reading music and playing through it without getting spectacular at it. I am working heavily on sight reading now, and that's what I'm going for with the studies im looking for. I don't expect to be able to sight read that piece, of course, but to be able to play it without significant hesitation is a goal.
Answer: The first thing to do is always practice scales. Claire de Lune is written in Db major, so always practice the key of D flat prior to practicing the Debussy's piece.
By practicing scales, you learn the language of music. In a short amount of time, you will no longer see just notes on the page, but rather also patterns and chord progressions.

Apropos your question regarding learning melodies involving chords:
If you haven't already, I'd recommend playing Bach's Prelude 1 in C Major. It is all broken chords. When you practice it, make sure you stop on each measure and label the chords. The point o
Block the chords (play the broken notes simultaneously), and then play them as written (i.e. broken and arpeggiated).
You will notice that Bach was using ii-V-I progressions way before they became a staple of Jazz music :)
For example:

the first chord in Bach's 1st Prelude is a C major triad
the second chord is a D minor 7
the third chord is a G7.
the fourth chord is a C major.

In the C Major scale: C is the 1st note, D is the 2nd note, and G is the 5th note.
So we have a I-ii-V-I progression at the very beginning of Bach's Prelude 1 in C Major.
I recommend learning the Bach Preludes. Bach was way ahead of his time. Most of the chord progressions that are widely used in jazz and rock music can be found in Bach's music.
Debussy is also fascinating. Miles Davis was heavily inspired by Debussy. I'd recommend learning Debussy's suite Pour le Piano if you want to dig deeper into an understanding of chords. Many of the chords used in that suite are straight up jazz chords. The last 6 measures of the 1st part (Prelude) are incredibly beautiful i.e.

A minor
Ab7+5
G7+5
C9
E minor 7
A minor

The 2nd part of the suite Sarabande is almost all exclusively chords. And the sonorities are fascinating.

The best way to learn chords is to learn scales inside and out. Chords are after all just scale tones played simultaneously.


Detect an arc from an image contour or edge

Question: I am trying to detect arcs inside an image. The information that I have for certain with me is the radius of the arc. I can try and maybe get the centre of the circle whose arc I want to identify.
Is there any algorithm in Open CV which can tell us that the detected contour ( or edge from canny edge is an arc or an approximation of an arc)
Any help on how this would be possible in OpenCV with Python or even a general approach would be very helpful
Thanks
Answer: If you think that there will not be any change in the shape (i mean arc won't become line or something like this) then you can have a look a Generalized Hough Transform (GHT) which can detect any shape you want.
Cons:

There is no directly function in openCV library for GHT but you can get several source code at internet.
It is sometimes slow but can become fast if you set the parameters properly.
It won't be able to detect if the shape changes. for exmaple, i tried to detect squares using GHT and i got good results but when square were not perfect squares (i.e. rectangle or something like that), it didn't detect.
Comment: Ok, I will try it out
I had seen it earlier, but have been worried about trying it out as I am working on a video in which I am trying to identify elliptical objects, the brightness and positon keeps on changing throughout
Comment: ok, if your source of images is a webcam then i think that GHT would not be a good option because scale/size/orientation won't be a problem but the shape would definitely be.
Comment: Its a HD video recording that I am working with
Ya, the shape and orientation keeps on changing throughout the video
Comment: as i mentioned, orientation change won't be a problem but changing shape will be a problem.
Answer: You can do it this way:

Convert the image to edges using canny filter.
Make the image binary using threshold function there is an option for regular threshold, otsu or adaptive.
Find contours with sufficient length (findContours function)
Iterate all the contours and try to fit ellipse (fitEllipse function)
Validate fitted ellipses by radius.
Check if detected ellipse is good fit - checking how much of the contour pixels are on the detected ellipse.
Select the best one.

You can try to increase the speed using RANSAC each time selecting 6 points from binarized image and trying to fit.
Comment: Thanks for the approach,
I have tried doing something like that it returns me way too many ellipses
I will explore RANSAC, don't have much idea about it
Answer: My math is rusty, but...
What about evaluating a contour by looping over its composite edge-nodes and finding those where the angle between the edges doesn't change too rapidly AND doesn't change sign?
A chain of angles (θ) where:
0 < θi < θmax
with number of edges (c) where:
c > dconst
would indicate an arc of:
radius ∝ 1/(θi + θi+1 + ...+ θn)/n)
or:
r ∝ 1/θave
and:
arclenth ∝ c
A way of finding these angles is discussed at Get angle from OpenCV Canny edge detector


Salvar dados de uma Row em um array

Question: Estou elaborando uma nova funcionalidade para um projeto Winforms em C#. Logo desenvolvi o seguinte método que retorna se no componente GridControl (gvDados) há uma linha selecionada ou não.
public bool RetornaSelecionado(bool Selecionado)
{
  int linhas = 0;

  foreach (int i in gvDados.GetSelectedRows())
  {
    DataRow row = gvDados.GetDataRow(i);
    linhas++;
     //TESTE MessageBox.Show(row[0].ToString());
  }
  if(linhas > 0)
  {
    MessageBox.Show("Selecionou");
    return Selecionado = true;
  }
  else
  {
    MessageBox.Show("Não selecionou");
    return Selecionado = false;
  }
}

O método funcionou do jeito que eu esperava. Quando seleciono um item no componente é exibido a mensagem Selecionou e quando não selecionado, a mensagem Não Selecionou é exibida. Após isto surgiu uma dúvida, como eu devo proceder para armazenar os dados de row em um outro array para que eu possa utilizar em outra validação do sistema?
Comment: é o nome do meu GridControl
Comment: eu fiz um ato mais amador kkkkk... Aquela linha comentada ali no código era pra saber qual item (ID, Nome, Setor) está sendo "pego" pelo `DataRow`, e é o ID...
Comment: o que é `gvDados`?
Comment: Debuga seu código e pega as informações em `DataRow`, ai basta atribuir no array que vc deseja!
Answer: Cria um array do tipo que você tá usando no datasource. Pra pegar o tipo é só dar um cast.
MeuObjeto oObjeto = (MeuObjeto)gvDados.GetRow(i);

Aí preenche o array com esses objetos.
Answer: Basta criar um lits<t> a onde T é a classe ou  o  tipo  que você deseja armazenar
Suponhamos que seja um int
Lits<int> meusDados =  new List<int>();

foreach (int i in gvDados.GetSelectedRows())
{
    DataRow row = gvDados.GetDataRow(i);
    linhas++;
    meusDados.Add(Int32.Parse(row[0].ToString()));
    //TESTE MessageBox.Show(row[0].ToString());
}

Comment: Marcos, eu comecei testar a sua resposta aqui e já topei em um outro detalhe... Como que eu faço para chamar essa lista em um evento, por exemplo?... Sinceramente eu preciso estudar Listas pq não manjo nada :/
Comment: Bom se o evento estiver dentro  da  mesma classe você pode colocar a lista  no  escopo global ou seja, crie essa variavel Lits meusDados fora da função.

Caso esteja em outra pode definir como  static
Comment: Como  assim  você quer chamar ela dentro de outra função ?

Salvar dados de uma Row em um array


How to make tools.run_flow function to work same as tools.run(deprecated method) in GmailApi authentication?

Question: I want to refresh tokens without providing authentication flow.can you guys help
Comment: what do you have so far? Show your code.
Answer: Based from this documentation, when users visit your app after a successful first-time authorization flow, your application can use a stored refresh token to authorize requests without prompting the user again.

If you have already authenticated the user, your application can retrieve the refresh token from its database and store the token in a server-side session. If the refresh token is revoked or is otherwise invalid, you'll need to catch this and take appropriate action.

Here is an example that shows how to instantiate a service object and then authorize it to make API requests.
<code>from apiclient.discovery import build
# ...

def build_service(credentials):
  """Build a Gmail service object.

  Args:
    credentials: OAuth 2.0 credentials.

  Returns:
    Gmail service object.
  """
  http = httplib2.Http()
  http = credentials.authorize(http)
  return build('gmail', 'v1', http=http)
</code>
Once OAuth 2.0 credentials have been retrieved, they can be used to authorize a Gmail service object and send requests to the API. Here is also an example in Google documentation.
Comment: Thanks @abielta I was using tools.run_flow even after authenticating once.I totally removed it and my code started running fine.


How to determine effect size confidence interval in a difference-of-differences A/B test

Question: This seems like it should be a really simple thing, so I apologize if this has been answered elsewhere, but I've browsed dozens of existing questions and none seem to fit exactly.
Suppose I have two cohort groups, control and target.  I apply a treatment to the target, and want to use DiD to compare conversion deltas between the two groups; pre and post treatment.
I believe the following r code correctly proves that in our instance, the effect is truly non-zero (i.e. we reject the NULL hypothesis).  However, because it's a binomial GLM, the confidence intervals are bounding the probability that it's non-zero, not the actual effect itself:
Converted <- c(2526,2500,2818,2268)
Offered <- c(3992,3956,4484,3996)
Cohort <- factor(c("Target","Target","Control","Control"))
Period <- factor(c(0,1,0,1))
ConvRate <- Converted / Offered

fit <- glm(ConvRate~Cohort*Period, family=binomial, weights=Offered)
summary(fit)

confint(fit)

(Summarized) Output:
Coefficients:
                     Estimate Std. Error z value Pr(>|z|)
(Intercept)           0.52560    0.03090  17.007  < 2e-16 ***
CohortTarget          0.01850    0.04509   0.410 0.681633
Period1              -0.25367    0.04444  -5.708 1.14e-08 ***
CohortTarget:Period1  0.25017    0.06434   3.888 0.000101 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance:  5.1064e+01  on 3  degrees of freedom
Residual deviance: -7.9270e-13  on 0  degrees of freedom
AIC: 42.851

Number of Fisher Scoring iterations: 2

Waiting for profiling to be done...
                          2.5 %     97.5 %
(Intercept)           0.4651823  0.5863361
CohortTarget         -0.0698583  0.1069002
Period1              -0.3407991 -0.1665982
CohortTarget:Period1  0.1240757  0.3762874

In order to get the actual effect size, I ran this through a LM, but it's refusing to provide me with confidence intervals;
lfit <- lm(ConvRate~Cohort*Period, weights=Offered)
summary(lfit)

confint(lfit)

Output:
Call:
lm(formula = ConvRate ~ Cohort * Period, weights = Offered)

Weighted Residuals:
ALL 4 residuals are 0: no residual degrees of freedom!

Coefficients:
                      Estimate Std. Error t value Pr(>|t|)
(Intercept)           0.628457         NA      NA       NA
CohortTarget          0.004309         NA      NA       NA
Period1              -0.060889         NA      NA       NA
CohortTarget:Period1  0.060075         NA      NA       NA

Residual standard error: NaN on 0 degrees of freedom
Multiple R-squared:      1, Adjusted R-squared:    NaN
F-statistic:   NaN on 3 and 0 DF,  p-value: NA

                     2.5 % 97.5 %
(Intercept)            NaN    NaN
CohortTarget           NaN    NaN
Period1                NaN    NaN
CohortTarget:Period1   NaN    NaN
Warning message:
In qt(a, object$df.residual) : NaNs produced

A similar issue results with family=gaussian when using GLM again:
Coefficients:
                      Estimate Std. Error t value Pr(>|t|)
(Intercept)           0.628457         NA      NA       NA
CohortTarget          0.004309         NA      NA       NA
Period1              -0.060889         NA      NA       NA
CohortTarget:Period1  0.060075         NA      NA       NA

(Dispersion parameter for gaussian family taken to be NaN)

    Null deviance: 1.2194e+01  on 3  degrees of freedom
Residual deviance: 2.0249e-28  on 0  degrees of freedom
AIC: -272.54

Number of Fisher Scoring iterations: 1

Waiting for profiling to be done...
Error in while ((step <- step + 1) < maxsteps && abs(z) < zmax) { :
  missing value where TRUE/FALSE needed
Calls: confint -> confint.glm -> profile -> profile.glm
In addition: Warning message:
In qf(1 - alpha, 1, n - p) : NaNs produced
Execution halted

I'm wondering how I can get the effect size confidence intervals?  The difference in differences is ~6% but I'm looking for statistically significant intervals.
Comment: That's not going to work b/c you're regression won't be able to calculate the variance. You need a dataset with a row for each observation. Your case is simpler but see how it's done here in this answer: https://stats.stackexchange.com/questions/560795/is-this-the-correct-way-to-estimate-a-difference-in-differences-model-in-r-mult
Comment: Perhaps I'm misunderstanding your code, but it seems you arranged the data you feed to your regression such that you only have four data points when in reality you have several thousand data points.
Comment: I accidentally posted this under a new account that can't comment, I'll comment from this one. Yes, I pre-aggregated the data as y is just a binary yes/no.
Comment: Thank you! I'll give it a try.
Answer: As I noted in the comments, the problem is that you're not providing the full dataset to the regression function.
For a toy example that involves only 20 observations
period <- c(rep(0, 10), rep(1, 10))
treatment <- c(rep(1, 5), rep(0, 5), rep(1, 5), rep(0, 5))
converted <- c(1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0)

dat <- data.frame(period, treatment, conversion)
head(dat)

summary(lm(converted ~ period + treatment +  period * treatment))

Now, you get a standard error for the interaction because it's possible to estimate the variance.
Comment: Thank you! I will try this.


Show AdMob Native Ads with MoPub (iOS)

Question: I am integrating MoPub SDK to mediate ADs from the Google AdMob network. I can get the AD to show after implementing my own customEvent and Adapter, but i can't get the AD to handle click events on its own. As in when I click on the AdMob native AD, it won't direct me anywhere. When using Facebook and Flurry's CustomEvent and Adapter, clicks are handled automatically. Anyone have any experience on this subject?
Thanks in Advance. Code below:
MPGoogleAdMobCustomEvent
@interface MPGoogleAdMobCustomEvent()
@property(nonatomic, strong)GADAdLoader *loader;
@end

@implementation MPGoogleAdMobCustomEvent

- (void)requestAdWithCustomEventInfo:(NSDictionary *)info
{
    MPLogInfo(@"MOPUB: requesting AdMob Native Ad");

    NSString *adUnitID = [info objectForKey:@"adUnitID"];

    if (!adUnitID) {

        [self.delegate nativeCustomEvent:self didFailToLoadAdWithError:MPNativeAdNSErrorForInvalidAdServerResponse(@"MOPUB: No AdUnitID from GoogleAdMob")];

        return;
    }

    self.loader = [[GADAdLoader alloc] initWithAdUnitID:adUnitID rootViewController:nil  adTypes:@[kGADAdLoaderAdTypeNativeContent] options:nil];
    self.loader.delegate = self;
    GADRequest *request = [GADRequest request];

#if (TARGET_OS_SIMULATOR)

    request.testDevices = @[ kGADSimulatorID ];

#endif

    CLLocation *location = [[CLLocationManager alloc] init].location;
    if (location) {
        [request setLocationWithLatitude:location.coordinate.latitude
                               longitude:location.coordinate.longitude
                                accuracy:location.horizontalAccuracy];
    }
    request.requestAgent = @"MoPub";
    [self.loader loadRequest:request];
}

- (void)adLoader:(GADAdLoader *)adLoader didReceiveNativeContentAd:(GADNativeContentAd *)nativeContentAd
{
    MPLogDebug(@"MOPUB: Did receive nativeAd");

    MPGoogleAdMobNativeAdAdapter *adapter = [[MPGoogleAdMobNativeAdAdapter alloc] initWithGADNativeContentAd:nativeContentAd];
    adapter.url = nativeContentAd.advertiser;
    MPNativeAd *interfaceAd = [[MPNativeAd alloc] initWithAdAdapter:adapter];

    NSMutableArray *imageArray = [NSMutableArray array];

    for (GADNativeAdImage *images in nativeContentAd.images) {

        [imageArray addObject:images.imageURL];

    }

    [super precacheImagesWithURLs:imageArray completionBlock:^(NSArray *errors) {

        if ([errors count]) {
            [self.delegate nativeCustomEvent:self didFailToLoadAdWithError:errors[0]];
        } else {
            [self.delegate nativeCustomEvent:self didLoadAd:interfaceAd];
        }

    }];
}

- (void)adLoader:(GADAdLoader *)adLoader didFailToReceiveAdWithError:(GADRequestError *)error
{
    MPLogDebug(@"MOPUB: AdMob ad failed to load with error (customEvent): %@", error.description);
    [self.delegate nativeCustomEvent:self didFailToLoadAdWithError:error];
}

@end

MPGoogleAdMobNativeAdAdapter
@interface MPGoogleAdMobNativeAdAdapter()<GADNativeAdDelegate>
@property(nonatomic, strong)NSDictionary *properties;
@end

@implementation MPGoogleAdMobNativeAdAdapter

- (instancetype)initWithGADNativeContentAd:(GADNativeContentAd *)contentAD
{
    self = [super init];
    if (self) {
        self.contentAd = contentAD;
        self.contentAd.delegate = self;
        self.properties = [self convertAssetsToProperties:contentAD];
    }
    return self;
}

- (NSDictionary *)convertAssetsToProperties:(GADNativeContentAd *)adNative
{
    self.contentAd = adNative;
    NSMutableDictionary * dictionary = [NSMutableDictionary dictionary];
    if (adNative.headline) {
        dictionary[kAdTitleKey] = adNative.headline;
    }
    if (adNative.body) {
        dictionary[kAdTextKey] = adNative.body;
    }
    if (adNative.images[0]) {
        dictionary[kAdMainImageKey] = ((GADNativeAdImage *)adNative.images[0]).imageURL.absoluteString;
    }
    if (adNative.callToAction) {
        dictionary[kAdCTATextKey] = adNative.callToAction;
    }
    return [dictionary copy];
}

#pragma mark MPNativeAdAdapter
- (NSTimeInterval)requiredSecondsForImpression
{
    return 0.0;
}

- (NSURL *)defaultActionURL
{
    return nil;
}

- (BOOL)enableThirdPartyClickTracking
{
    return YES;
}

- (void)willAttachToView:(UIView *)view
{
    self.contentAd.rootViewController = [self.delegate viewControllerForPresentingModalView];
}

- (void)didDetachFromView:(UIView *)view
{
    self.contentAd.rootViewController = nil;
}

#pragma mark GADNativeAdDelegate

- (void)nativeAdWillPresentScreen:(GADNativeAd *)nativeAd
{
    if ([self.delegate respondsToSelector:@selector(nativeAdWillPresentModalForAdapter:)]) {
        [self.delegate nativeAdWillPresentModalForAdapter:self];
    }
}

- (void)nativeAdDidDismissScreen:(GADNativeAd *)nativeAd
{
    if ([self.delegate respondsToSelector:@selector(nativeAdDidDismissModalForAdapter:)]) {
        [self.delegate nativeAdDidDismissModalForAdapter:self];
    }
}

- (void)nativeAdWillLeaveApplication:(GADNativeAd *)nativeAd
{
    if ([self.delegate respondsToSelector:@selector(nativeAdWillLeaveApplicationFromAdapter:)]) {
        [self.delegate nativeAdWillLeaveApplicationFromAdapter:self];
    }
}

@end

`

Answer: If you are having your custom UI for AdMob Ad's, then there will be a button which you will be using for callToAction part.
First of all you need to add a selector to detect action of click, to do add the selector for that button
[callToActionButton addTarget:self action:@selector(adCalled:) forControlEvents:UIControlEventTouchUpInside];

After that implement the adCalled method to get the click & call the method further, below is the code for your reference
Below is the example which I have used to get the ad object from my collection view & then I am redirecting it.
- (void)adCalled:(id)sender
{
    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:mainCollectionView];   // Get the button position
    NSIndexPath *indexPath = [collectionView indexPathForItemAtPoint:buttonPosition];    // Get the index path of button so that I can retrieve the correct ad object
    id selectedAd = [adArray objectAtIndex:indexPath.row];
    if ([selectedAd isKindOfClass:[GADNativeContentAd class]]) {
        NSString *url = [selectedAd valueForKey:@"googleClickTrackingURLString"];
        NSLog(@"URL is :%@", url);
        NSURL *googleUrl = [NSURL URLWithString:url];
        if ([[UIApplication sharedApplication] canOpenURL: googleUrl]) {
            [[UIApplication sharedApplication] openURL:googleUrl];
        }
    }
}

Using this I can open the link n web using the google tracking url.
Hope this helps.

Show AdMob Native Ads with MoPub (iOS)


Read "fractions" from .txt file and add them using C

Question: I'm trying to read "fractions" from a .txt file and store them in an array to later perform the sum and then simplify the result.
Fractions in the text file are represented as follows(separated by a blankspace):

3/2 -7/4 1/6 9/5.

I'm having trouble storing the data into the array.
#include <stdio.h>
#include <stdlib.h>
#define N 20 //just for testing

typedef struct{
    int numerator;
    int denominator;
}TFraction;

int main(){
    TFraction F[N];
    fillArray(F);
}
int fillArray(TFraction A[]){
    FILE *txt;
    char skip; //going to be rewritten with "/", can be ignored
    int i=0;

    fp=fopen("fractions.txt","r");

    while(!feof(fp)){
        fscanf(fp,"%d %c %d", A[i].numerator, skip, A[i].denominator);
        i++;
    }
    fclose(fp);
}

Once they array is filled, I should be able to perform the sum.
Any tips or ideas on my proposed solution, I'm open to suggestions on how to solve this.
Comment: You have not stated what trouble you are having and have not asked a question. Stack Overflow is for asking specific questions. Edit the question to provide a [mre]. If the problem is a compiler error message, show the exact text of the compiler error message. If the problem is the program does not execute as you desire, show an exact copy of input that reproduces the problem, an exact copy of the observed output, and a sample of the output desired instead.
Answer: As soon as you start parsing text from an external source (from the user, from a file, ... - anything that isn't a string literal in your own code) you can't assume the text is correct and should have adequate error handling that detects problems and describes what the problem is.
For an example, imagine what happens if the file contains "3.2 -7/4 1/69/5" - do you want to mistakenly assume that 3.2 is 3/2 and give the wrong answer? Do you you want to assume 1/69/5 is 1/69 followed by 5/??? without telling the user that there's a syntax error on the last fraction?
Once you've solved the parsing problem you'll have another problem...
The addition of fractions involves making sure that the denominators are equal. This is typically done using multiplication - e.g. 3/2 + -7/4 = (3*4)/(2*4) + (-7*2)/(4*2) = 12/8 + -14/8 = (12 + -14)/8 = (-2)/8.
For many additions; those multiplications cause the numerators and denominators to get very big, possibly too big to fit in an int. You can minimize the risk by doing a "fast simplify" (if numerator and divisor are both even then divide them both by 2) or a much more expensive "full simplify" (determine the Greatest Common Divisor and divide numerator and divisor by the GCD) after each addition.
Note that your question says "..and then simplify the result", so you might need code to do "full simplify" anyway.
Alternatively, maybe an estimate with precision loss problems is "close enough" and you can just convert fractions into floating point values before doing addition. This would change the whole nature of the problem.
Finally; if you only need to add the fractions then you don't need to store them and don't need an array to store them. You can have a loop that does "get next fraction; add it to the current total".


logistic regression simulation doesn't converge

Question: I want to do a logistic regression simulation using R
I use this code
set.seed(666)
age = rnorm(60)
blood_pressure = rnorm(60)
race = sample(c(rep(1,30),rep(0,30)))
inactivity = sample(c(rep(1,30),rep(0,30)))
weight = rnorm(60)

z=1+1*age+blood_pressure*2+3*weight+3*inactivity+0*race
pr=exp(z)/(1+exp(z))
y=rbinom(60,1,pr)

df = data.frame(y=y,age,blood_pressure,inactivity,weight,race)
glm(y~age+blood_pressure+inactivity+weight+race,data=df,family=binomial(link='logit'),control = list(maxit = 50))

I got very strange result from it.
Coefficients:
   (Intercept)             age  blood_pressure      inactivity          weight            race
        -39.75           46.64          106.65          143.52          229.75          100.87

And it says the model doesn't converge.
Does someone know what's wrong and how to fix it?
Comment: The posts bearing the tag [hauck-donner effect] will be very helpful in answering this question.
Comment: Another thing you might try is fitting a model without an intercept.  It's possible that `race` and `inactivity` together may be behaving too much like an intercept, but this is just a guess.
Answer: What else would you expect from setting the seed to 666?
But more seriously, the issue is that you have a very small sample size (60). As such, the chances that you can find a linear combination of your covariates such that observations with the linear combination below some threshold are all 0's, while observations with the linear combination above some threshold are all 1's is reasonably high. If you can find this, then at least one of your estimated coefficients will be infinity, causing all kinds of problems.
To illustrate, try increasing your sample size:
n <- 600
set.seed(555)
age = rnorm(n)
blood_pressure = rnorm(n)
race = sample(c(rep(1,n/2),rep(0,n/2)))
inactivity = sample(c(rep(1,n/2),rep(0,n/2)))
weight = rnorm(n)

z=1+1*age+blood_pressure*2+3*weight+3*inactivity+0*race
pr=exp(z)/(1+exp(z))
y=rbinom(n,1,pr)

df = data.frame(y=y,age,blood_pressure,inactivity,weight,race)
glm(y~age+blood_pressure+inactivity+weight+race,data=df,
    family=binomial(link='logit'),control = list(maxit = 50))

Answer: Look at the summary of your estimates and play with individual variables.  Currently the summary returns:
Coefficients:
                 Estimate Std. Error z value Pr(>|z|)
(Intercept)        -39.75  982476.12       0        1
age                 46.64  258055.84       0        1
blood_pressure     106.65  356355.42       0        1
inactivity         143.52  579221.32       0        1
weight             229.75  500237.07       0        1
race               100.87 1032211.12       0        1

This is clearly wrong.  When you remove race you get
               Estimate Std. Error z value Pr(>|z|)
(Intercept)       4.368      4.399   0.993    0.321
age               2.399      2.039   1.177    0.239
blood_pressure    9.120      6.596   1.383    0.167
inactivity        8.654      5.854   1.478    0.139
weight           15.164     10.705   1.417    0.157

Hence including race made the model misbehave.  You may have either multicollinearity issues, or the problem that all your observations are 0 on one side of a hyperplane, and 1 on the other side, as Cliff AB suggested.


How often have pitchers earned a win and a save on same day?

Question: On Sunday 25th April 2015, David Robertson managed a rare feat: he earned a win and a save on the same (calendar) day. While the first win technically was on Friday, according to the box score, for practical purposes he earned a win and a save on the same calendar day.
Has this ever happened before, and if so, how many times and by whom (if it's a reasonable number)?
Comment: When you say "same calendar day" , it seems odd (atleast to me) because Friday and Sunday are Definitely not the same on the calendar , unless that is standard baseball nomenclature. If it is not a standard baseball phrase, then something like "same day as per records" might be a better way to state it.
Comment: I think he was confused, because both games were played on Sunday April 26th, it was a doubleheader due to one game being postponed on Saturday.
Comment: Actually, the first game (the win) was the continuation of Friday's game which was suspended after eight in a tie. Robertson was announced for the ninth so he had to pitch to the first batter (and finished the inning). That occurred Sunday. It was 'officially' Friday as that's how they count resumed suspended games, but it occurred on Sunday.
Comment: Just to be clear - the meaning of 'calendar day' is meant to be that Robertson earned a win and a save on one day as measured from one sunrise to the next (or one midnight to the next). It wasn't considered one schedule day was the distinction I was trying to make.
Comment: It could happen in a "normal" double header, where the closer pitches the ninth, and gets a save in one game, then pitches 1 inning, and is the "pitcher of record" in the other game because his teammates "win" the game when they come bat after his inning.
Comment: It certainly could happen any number of ways - that, or even a game one night going into the next day getting the save after midnight and then the win the next.  I would like to know if it *has* happened, and how frequent it is.
Answer: Sunday, May 6, 1917, Bob Groom  got a save in the first game of a doubleheader for the St. Louis Browns over the Chicago White Sox. In the second game he got the win, pitching a no-hitter.
Comment: Well that certainly seems to qualify, though the save wasn't an official stat then, he definitely earned one by the modern definition.
Answer: May 28, 2019 Alex Colome, of the White Sox,  got a win in the first game of a double header and the save in the second:

Game 1, suspended from May 27 and completed on May 28.
Game 2, the regularly scheduled game for May 28.


Is PTR record needed if SPF record points to IP

Question: If sending email as email@example.com from mail server 220.127.116.11, and the SPF record of mydomain.com set as
<code>"v=spf1 ip4:126.96.36.199 -all"</code>
Will a PTR record do any good? Is PTR required for some e-mail servers to accept my e-mails, or is this SPF record sufficient for delivery purpose(without putting DKIM & ipv6 into consideration)?
Comment: Are you asking about an SPF PTR record, or a DNS PTR record?
Answer: Some mail servers will reject connections from IP's that don't have a PTR record. SPF doesn't change that behavior.
Comment: Thanks for answering. How will those mail servers behave if server 220.127.116.11 send e-mails as email@example.com that has SPF points to 22.214.171.124, but  not A/PTR records?
Answer: To extend longneck's perfectly good answer slightly, you cannot control what decisions the admins of other mail servers make about which emails to accept, and which to reject.
Some servers will refuse connections from servers that have no PTR record.  Others will use the lack of a PTR as one of a number of inputs to a weighted decision about whether to refuse a connection, or to consider content from such a server to be spam.  Any of these strategies can also be applied to servers which cannot be circularly-resolved - that is, when the hostname returned by looking up the server's IP's PTR record cannot in turn be resolved to get back to the IP address.
Most of these strategies are unaffected by the sender domain of a received email, which would in turn affect the choice of which SPF record to consult.  So no amount of messing around with SPF records can help you deliver to a server which has decided to take against your sending server on the basis of its lack of a satisfactory PTR record.


Using Varnish as load balancer

Question: Varnish already support load balancing HTTP 1.1 and Web Socket requests, e.g. https://www.varnish-cache.org/trac/wiki/LoadBalancing
Since we already using Varnish for caching purpose, are there any benefit if we add nginx or ha proxy in front of Varnish for load balancing, or should we just use Varnish for load balancing?
Seems this approach is quite rare, and why?
Comment: What problem are you trying to solve, and why do you want to make your setup more complex?
Answer: Disclaimer : I'm a varnish fanboy.
I'm not aware of people putting nginx in front of varnish : they sometimes do the opposite as nginx is supposed to be a lightweight webserver.
Unless I have a good reason not to do so, I would do the load balancing with varnish.
However using varnish for load balancing can be tricky :

You don't want varnish to be single point of failure so you think about 2 servers at least.
With active active setup you'll have to deal with cache consistency problem and set url purge in case of update.
With active passive setup, you'll have to deal with cache stampeding.
Comment: The fact that varnish does not do https, while nginx does, is the reason I put nginx in front of varnish sometimes.

Using Varnish as load balancer


MongoDB How to update fields in database manually?

Question: I have a collection in Mongo. I need to update some fields manually. The document is long, it has 20 fields.
I need to see what is inside and rewrite it or don't change itd. And I need to do this document by document.
What I need

take first document

show value of all fields

change manually the fields that needed update, keep the rest

record 1
id: 1
name: John
number: 6657383
city: Miami
position: driver
itd
record 2
id: 2
name: Kate
number: 66574444
city: NY
position: None
itd
I don't; want to make it like this:
update_one({name:John}, {set:...}}
update_one({name:Kate}, {set:...}}
Because in different  document i would like to change different fields, sometimes all fields should be changed. So I need to load what it is now in that document, see it and rewrite it and than update in mongo.
So I load first record:
id: 1
name: John -> change manually to "Robert"
number: 6657383
city: Miami -> "Change manually to NY
position: driver
itd
And the record is updated in mongo.
Answer: you can use mongodb compass UI
https://www.mongodb.com/products/compass


Passing unions via generics on conditional types assigns any instead of the union

Question: I need a generic type to assign to my actions. Actions can be either functions or functions that return a function, like this:
() => void
() => (input: I) => void

I have created an Action type with a conditional generic Input, like this:
type ConditionalInput = I extends null
    ? () => void
    : () => (input: I) => void;

It works great when you don't pass an Input:
const action1: ConditionalInput = () => { } // Fine;

And when you pass an Input that is not a union:
const action2: ConditionalInput<string> = () => str => { } // Fine;

but the input is any when you pass a union:
const action3: ConditionalInput<string | number> =
    () => strOrNum => { } // str is any!!;

This is a playground with the code: TS Playground
By the way, the union works fine if I don't use conditionals:
type NonConditionalInput = () => (input: I) => void;

const action4: NonConditionalInput<string | number> =
    () => strOrNum => { } // Fine;

Answer: You have hit upon the distributive behavior of conditional types. Basically the conditional type is applied to each member of the union and the result is the union of all applications. So in your case,  ConditionalInput<string | number> == ((input: string) => void) | ((input: number) => void);
To disable distribution, use a tuple :
type ConditionalInput = [I] extends [null]
    ? () => void
    : () => (input: I) => void;

const action3: ConditionalInput<string | number> =
    () => strOrNum => { } // ok now

Comment: Thanks!! I didn't know about that :)


Whats the reverse of android:dependency

Question: In Android if I wanted to only enable a CheckboxPreference when another certain CheckboxPreference is enabled, I would do something like this:
android:dependency="another_pref"

However, what if I want to do the reverse operation? Disable a preference when that certain is enabled. I cant seem to find any documentation on how to do that, yet Im pretty sure I once accomplished it somehow.
Thanks
Comment: Put the dependency on the other preference?
Comment: Dont think that would work, would it? Im not talking about toggling the checkBoxPreferences Im talking about disabling them (graying them out, making them unable to toggle)
Answer: One way is to invert the intuition of the master checkbox, and then when it is checked, enable the other.
However, this does not answer your question. To do this, you have to execute the following code in your Preference Fragment/Activity's onSharedPreferenceChangedListener:
CheckBoxPreference masterPreference = (CheckBoxPreference) findPreference(key1);
Preference dependentPreference = findPreference(key2);
dependentPreference.setEnabled(!masterPreference.isChecked());

Code logic: this code takes the checked state of the master preference. If it is unchecked, the dependent preference is enabled, and vice-versa.

Whats the reverse of android:dependency


Total Probability Theorem / Partition

Question: In the Total Probability Theorem we assume that the sample space is partitioned into subsets. If we consider $B$ to be the sample space and $A_1$, $A_2$ to be the partition then the theorem says:
$$\mathbb{P}(B)=\mathbb{P}(A_1) \mathbb{P}(B\mid A_1)+\mathbb{P}(A_2) \mathbb{P}(B\mid A_2)$$
My confusion is that if $A_1$ and $A_2$ are subsets of $B$, should not $\mathbb{P}(B\mid A_1)=1$?
Answer: That's correct: $\mathbb{P}(B\mid A_1)=\mathbb{P}(B\mid A_2)=1$, assuming that $A_1$ and $A_2$ have positive probability. Therefore the total probability theorem in this case reduces to
$$ \mathbb{P}(B)=\mathbb{P}(A_1)+\mathbb{P}(A_2) $$
which must hold if $A_1$ and $A_2$ form a partition of $B$.
The more interesting applications of the total probability theorem come when you have a partition $\{A_n\}$ of the sample space $\Omega$ and some other event $B$ you want to find the probability of.

Total Probability Theorem / Partition


Multiple radiobutton columns in gridview

Question: I have multiple radio buttons columns in my gridview, I want to select one column at a time
Comment: Can you be more specific with your question?
Answer: As i got, you want to check only one radio button in a row so just add an attribute
GroupName with same value to all radio buttons and it will work..
e.g
    <asp:TemplateField HeaderText="More Than 20% Estimate"  >
 <ItemTemplate >
 <asp:RadioButton ID="rdbGVRow8" GroupName ="Program"  onclick="javascript:CheckOtherIsCheckedByGVIDMore(this);" runat="server" />
  </ItemTemplate>
 </asp:TemplateField>

 <asp:TemplateField HeaderText="10% to 20% overestimate"  >
 <ItemTemplate >
 <asp:RadioButton ID="rdbGVRow7" GroupName ="Program" onclick="javascript:CheckOtherIsCheckedByGVIDMore(this);" runat="server" />
 </ItemTemplate>
 </asp:TemplateField>
    .
    .
    .
    .

where program is a value you can give your own value but remember same value to all radio buttons.
Answer: This rather lengthy tutorial is the best I've seen that solves this issue
Adding a GridView Column of Radio Buttons
http://www.asp.net/data-access/tutorials/adding-a-gridview-column-of-radio-buttons-cs
If you are using the same group name for your buttons and they still are not working:
"The reason the radio buttons are not grouped is because their rendered name attributes are different, despite having the same GroupName property setting." If you view the source it might look something like this:
<input id="ctl00_MainContent_Suppliers_ctl02_RowSelector"
    name="ctl00$MainContent$Suppliers$ctl02$SuppliersGroup"
    type="radio" value="RowSelector" />
<input id="ctl00_MainContent_Suppliers_ctl03_RowSelector"
    name="ctl00$MainContent$Suppliers$ctl03$SuppliersGroup"
    type="radio" value="RowSelector" />

The fix is to use literal controls to inject the name in.
protected void Suppliers_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // Grab a reference to the Literal control
        Literal output = (Literal)e.Row.FindControl("RadioButtonMarkup");
        // Output the markup except for the "checked" attribute
        output.Text = string.Format(
            @"<input type="radio" name="SuppliersGroup" " +
            @"id="RowSelector{0}" value="{0}" />", e.Row.RowIndex);
    }
}


Função com erro deepEqual

Question: Olá,
Estou no seguinte enunciado tentando completar:
"Ah, mas isso não acaba aqui" - disse Ana "Eu quero saber em quantos meses houve lucro, ou seja, o saldo foi maior que zero" .
Complete a função quantidadeDeMesesComLucro.
Exemplo:
function quantidadeDeMesesComLucro(umPeriodo) {
let quantidade= ???;
for (let mes=0; mes< umPeriodo.length; mes++) {
???
}
return quantidade;
}
E fiz o seguinte código:
function quantidadeDeMesesComLucro(umPeriodo){
let quantidade = 0;

for(let mes = 0; mes < umPeriodo.length; mes++){
    if(umPeriodo[mes] < 0)
        quantidade += 1;
}

return quantidade;

}
E aparece os seguintes erros informando que a solução não passou completamente:
x quantidadeDeMesesComLucro([1]) é 1
0 deepEqual 1
x quantidadeDeMesesComLucro([2, 20, 20]) é 3
0 deepEqual 3
x quantidadeDeMesesComLucro([10, -10, 2, 100]) é 3
0 deepEqual 3
Alguém pode me ajudar? Grata!
Comment: Não deveria ser `umPeriodo[mes] > 0` ao invés de `umPeriodo[mes] < 0`?
Comment: O erro permanece das 2 formas.
Answer: Não acho que essa questão precise de uma resposta, mas como a usuária diz que o código continua não funcionando mesmo com a correção na comparação, vou deixar o trecho de forma executável:

function quantidadeDeMesesComLucro(umPeriodo){
  let quantidade = 0;

  for (let mes = 0; mes < umPeriodo.length; mes++) {
    // compara se o valor do array umPeriodo na posição mês é maior do que 0
    if (umPeriodo[mes] > 0)
      quantidade += 1;
  }

  return quantidade;
}

console.log(quantidadeDeMesesComLucro([1]));
console.log(quantidadeDeMesesComLucro([2, 20, 20]));
console.log(quantidadeDeMesesComLucro([10, -10, 2, 100]));

Como você pode ver, ele printa 1, 3 e 3, respectivamente, da forma que deveria.
Comment: user140828, grata! Desta forma solucionou na plataforma!

Função com erro deepEqual


How can I send HTML mail when a new content is created with attachments using these modules?

Question: In my project, I need to send HTML mail when a new content is created with attachments using the Mimemail, Mail System, SMTP, and Rules modules.
Plain text mail is working fine with rules module but problem is with HTML mail.
Can you please tell me the procedure to configure Mail System and Mime mail with SMTP?
Answer: First you need to create a Rule to send a HTML email via Mimemail:

Once you've configured the rule correctly and have entered your HTML email content, you need to ensure the correct mail system class is being used by Drupal to send your emails:

If you don't select the MimeMail class within these settings, the default Drupal mail system will be uses and your HTML emails will be sent in plain text.


Is a basin of attraction necessarily an open set?

Question:
Definition:
The basin of attraction is the defined as the set of all initial conditions $x_{0}$ such that $x(t$) tends to an attracting fixed point  $x^{\ast}$ as time $t$ tends to $\infty$.

Is this basin of attraction necessarily an open set?
My text mentioned nothing about the basin of attraction being an open set-Of course this could imply that the audience is meant to think on a deeper level about the said properties of it being an open set. It is in a given example that I concluded that the author implicitly claimed that the basin of attraction is an open set.
I would like to know if it is indeed true that the basin of attraction is an open set and if it is how can it be shown on a heuristic level.
Thanks in advance.
Comment: The basin of attraction of a fixed point is usually defined for every fixed point, not only for *attracting* fixed points. Sure about this part of the definition in your question (which should not be called *Theorem*)?
Comment: @Did
It is a definition. Thanks for the heads up.
Comment: So, should we understand that there is no basin of attraction around non-attracting fixed points?
Comment: A basin of attraction can exists for non-attracting fixed point. As long as the point is a fixed point, a basin of attraction is possible about that point.@Did
Comment: Which is exactly the point I am making and the reason why the definition in your post should be clarified: are you considering all basins of attraction (and then they can be non open), or only basins of attraction around attracting fixed points (and then they are indeed open)?
Answer: As pointed out by Did, for non-attracting fixed points $x_0$ the set of points $x$ with $\lim_{t\to \infty} x(t)=x_0$ does not have to be open.
For an attractive fixed point, if the dynamical system is continuous then the attraction basin is indeed open (Note: For discontinuous dynamics this is clearly no true; for a counterexample, just pick any set $S$ containing a neighbourhood of $x_0$ and send it to $x_0$ and send the rest to some point $y_0$ not in $S$; the basin of attraction is now $S$).
To see this for continuous dynamics, argue as follows:
Start with $x_1$ in the attraction basin. We will find a neighborhood of it also in the attraction basin.
By definition of attractive fixed point, there exists  open $U$ around $x_0$ such that for any $x\in U$ $\lim_{t\to \infty} x(t)=x_0$. The fact that $x_1$ is attracted of $x_0$ means that $\lim_{t\to \infty} x_1(t)=x_0$. In particular, for some large $T$ we have $x_1(T)\in U$. Since the dynamics is continuous, the preimage of $U$ under $\phi_T$ (lets call it $V$) is open, and contains $x_1$.
I claim that all of $V$ is also in the basin of attraction -- which is obvious because any $x\in V$ ends up in $U$ after time $T$ and  then attracts to $x_0$; in formulas $\lim_{t\to \infty} x(t)=\lim_{(s=t-T)\to \infty} x(T)(s) =x_0$.
So there you have it: any $x_1$ in the basin has an open neighbourhood $V$ around it which is also entirely in the basin.
Answer: It is true. The heuristic argument is that if $x_0$ is in the basin of attraction, then you can find an $\epsilon$ that is very small (dependent on the gradient around $x_0$) such that $x_0+\epsilon$ is also in the basin of attraction because you can pick a small enough $\epsilon$ such that the first iteration for both wind up in "basically the same place" and then you can iterate this idea of being close enough across all $t$
Comment: When you speak of 'gradient', are you referring to the trajectories of a vector field?
Comment: @Mathematicing I mean, this is a differential equation right? So it has a potential function and a gradient?
Answer: I'm pretty sure it's an open set and can give a heuristic proof (note: this is excluding basins of attraction for unstable steady states since they are trivial (the point itself) which is closed). In 2D if you apply the Poincure-Bendixon theorem (basically, just that there's no chaos in 2D), then every flow goes to a fixed point or a periodic orbit. But between any of these, you must have an unstable steady state / periodic orbit, and so the boundary between basins of attraction are unstable states/orbits.
In higher dimensions, this is more difficult because of the possibility of chaos. However, it seems like it's always the case that between any region where there is an attractor (either a chaotic attractor, attracting orbit, or attracting steady state) there are unstable fixed points on the boundary. I wouldn't be able to prove it (and it could be wrong in some crazy example).


ArchLinux under Xen fails to see root fs after kernel upgrade to Linux-3.0

Question: I bought a VPS but the hosting company doesn't have a prebuilt image for Arch Linux x64, so I have to install from ISO using VNC in SolusVM.
The installation works fine, the box (Xen Guest) is bootable, but after an upgrade (pacman -Suy) kernel26 gets replaced with linux-3.0 and stops booting.
The message is:
Root device /dev/disk/by-uuid/{uuid} doesn't exist. Attempting to create it.
ERROR: unable to determine major/minor number of root device '/dev/disk/by-uuid/{uuid}

Only by-id and by-path folders exist in /dev/disk if checked from emergency shell, and the only device is QEMU CD-ROM.
How do I fix it so linux-3.0 boots under Xen?
Answer: Did you try editing your /etc/fstab file on the VM to point to the "/" partition directly (e.g. /dev/sda1 or whatever your disk is) instead of the uuid?
My only other thought is that this is some sort of udev and linux 3.0 issue.
If neither work. Could you post more details of your configuration, such as the Xen guest configuration file, the /etc/fstab, and the complete kernel boot messages.
Also with the added detail this is a fine question for the xen-users mailing list:
http://lists.xensource.com/mailman/listinfo/xen-users


Adding padding to submit buttons on Mac OS X

Question: I'm having trouble adding padding to a submit button. I've created an ultra simple example in a JSFiddle:
http://jsfiddle.net/yxr197pa/1/
Here's the code for it:
HTML:
<input type="submit" value="Submit" />

CSS:
input {
    padding: 20px;
}

I must just not be getting something really simple, and I'm kind of embarrassed I can't figure it out. It seems like no one else is having this problem, as I've searched quite extensively. I've even seen examples of people adding padding with no issues. Would really appreciate any help. Thank you!
Update
To clarify the problem for those who might be confused by what I'm asking: the code above doesn't alter the padding of the button in any way. It appears there's default padding applied to the button, but the padding I've specified simply doesn't show. Here's a picture depicting what I see when I enter the code above:
https://i.stack.imgur.com/tyASx.png
This issue has been fixed in an answer below, but the underlying cause is still a mystery to me. It appears to have something to do with my computer. I'm using a fully up to date Mac OS X. My PC, on the other hand, renders the example above completely normally. It doesn't matter what browser I use on my Mac either, it still doesn't render the padding that I'm specifying.
That's not the end of the story though, because after analyzing the source code on other websites, I found submit buttons that were rendering padding correctly on my Mac, with effectively identical code. See here:
http://htmlandcssbook.com/code-samples/chapter-14/styling-submit-buttons.html
So why is the padding being rendered sometimes and not others?
Comment: Chrome Ver. 40.0.2214.115 on OS X (10.10.2)
Comment: @JoshCrozier Yep, that worked. I also checked it on my PC and the example I left worked...anyone know what the deal is? It must be my computer
Comment: What browser are you using?
Comment: Strange that something as simple as padding wouldn't work in all browsers, but your example looks good to me on chromium http://i.imgur.com/hKE16R3.png
Comment: So what are you wanting? - you don't says what's actually wrong in the fiddle example.
Comment: @Tom Does this work for you? http://jsfiddle.net/378nmhow/
Answer: Based on the comments above, you said you're on a Mac (OS X)..
Therefore you need to set the the appearance property of the input element to none in order for the padding to work. I went ahead and added -webkit/-moz vendor prefixed properties too:

input {
  padding: 20px;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
}
<input type="submit" value="Submit" />

This just seems to be one of those strange cross-browser inconsistencies, because this doesn't appear to be an issue on Windows.
Comment: @Sachin Are you sure? Based on [Tom's comment](http://stackoverflow.com/questions/28801374/adding-padding-to-submit-buttons?noredirect=1#comment45876743_28801374), it worked. I'm going to fire up my Mac to see if there is some soft of browser option that is controlling this.
Comment: @JoshCrozier This worked for me, Josh. Wow, what a weird issue. Would you recommend using `button` instead of ``? This seems like such a fundamental element, and I figured that all browsers would've figured out how to implement it uniformly by now.
Answer: It looks to me like you cannot add padding to an input.
I think the closest you can get is increasing the height and the width of the input.


Android flash builder webview

Question: I'm currently developing a mobile application in flash builder for android.
In this application I'm using a web view, in this web view there is a link to a web-based application. The first thing you have to do is in this web-based application i login. This works fine. But i have one problem when i close the application and restart the application i always stay logged-in.
Is there any way to clear the data of a web view? Are options that clear the user data of the android application?
Here's my code
<code>    <fx:Script>
    <![CDATA[
        import flash.geom.Rectangle;
        import flash.media.StageWebView;
        import flash.net.*;
        import flash.net.URLRequest;

        import spark.components.Application;

        public var webView:StageWebView = new StageWebView();

        public function init():void
        {
            this.addEventListener(Event.ADDED_TO_STAGE , handleLoad );

        }
        public function handleLoad(e:Event):void
        {

            webView.stage = this.stage;
            webView.viewPort = new Rectangle( 0, 50, stage.stageWidth, stage.stageHeight );
            webView.loadURL("http://jd44jse.ncsbe.eu.jnj.com:54400/MfmWeb/flex/mfm/plocmenuHD/main.html");
        }

        protected function logoutHandler(event:MouseEvent):void
        {

            NativeApplication.nativeApplication.exit();

        }

    ]]>
</fx:Script>
</code>
Answer: OK you need to add a code within the logout button that forces the user logout.  Or nullify the user information values upon exit. I am not at my computer but I will work on your code and see what I can discover.

Android flash builder webview


Associating a user with a particular form submit/click

Question: In my web site i have created a custom content type Challenge which contains a list of tasks that the user has to do. I have created the custom content type from the CMS itself through admin/structure/content type. I have created a custom form, , and when the user clicks submit i have made a query which insures that the node id of that challenge and the user id is associated in a Challenge table (the code is below). It works fine. Now i need to create a view which shows the challenges accepted by the user, i.e., when the user logs in and clicks on a tab(i am using quicktab) then a view appears which shows the challenges undertaken by the user. Here my code for the query:
<code>function my_module_menu() {
  $items = array();
  $items['my_module/form'] = array(
    'title' => t('My form'),
    'page callback' => 'my_module_form',
    'access arguments' => array('access content'),
    'description' => t('My form'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function my_module_my_form($form_state) {

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Accept Challenge',
    '#submit' => array('my_module_action'),
    );

  return $form;
}

function my_module_action($form, &$form_state) {

 if ($node = menu_get_object()) {
  // Get the nid
   $nid = $node->nid;
    }
 global $user;
 if ( $user->uid ) {
 $query = db_insert('challenges')
    ->fields(array(
    'cid' =>$node->nid,
    'uid' => $user->uid
    ))
    ->execute();
}
</code>
Well, thats it then. Now how do i create a view to show a user their accepted challenge.
Thanks
Comment: Where to you want show challenge? In node viewing or views?
Comment: inside Node view
Answer:
For node you should load challenges data in your custom module, using next: hook_node_load and/or showing next: hook_node_view. See examples module for it: nodeapi_example.
For Views you should define connection with your custom table and node, there nice example for it.
For Views also you can use Data module.


Use the sine rule to prove trig identity

Question: Using the sine rule:
$$ \frac{a}{\sin(A)} = \frac{b}{\sin(B)} = \frac{c}{\sin(C)}$$
prove, for triangle ABC:
$$\sin\left(\frac{B-C}{2}\right) = \frac{b-c}{a} \cos\left(\frac A2\right)$$
Using the sine rule it's easy to translate the RHS into:
$$\sin\left(\frac{B-C}{2}\right) = \frac{\sin(B)-\sin(C)}{\sin(A)} \cos\left(\frac A2\right)$$
Yes, I can expand out the LHS, and use the difference of 2 sines in the RHS, but neither makes an obvious equality, especially with terms in a and A in the RHS.
A nudge in the right direction would really be appreciated. Thanks.
Answer: Just assume that $a/sin(A)=b/sin(B)=c/sin(C)=1/k$.
So $sin(A)=ka, sin(B)=kb,sin(C)=kc$.
Now substitute this and you will get the desired result.
Comment: Are you sure this leads anywhere different from what OP's tried?
Comment: Well he has given here his method and his last step. Now if we do what I have stated we will get the RHS.
Comment: I might have overlooked this, but how would you handle $\sin(B-C/2)$ and $\cos(A/2)$ using those substitutions?
Answer: Since $A+B+C=\pi$, the difference formula for $\sin$ gives \begin{align}\frac{\sin B-\sin C}{\sin A} \cos\frac A2&=\frac{2\cos\frac{B+C}2\sin\frac{B-C}2}{\sin(\pi-B-C)}\cos\frac{\pi-B-C}2\\&=\frac{2\sqrt{\frac{1+\cos(B+C)}2}\sin\frac{B-C}2}{\sin(B+C)}\sqrt{\frac{1+\cos(\pi-B-C)}2}\\&=\frac{2\sqrt{\frac{1+\cos(B+C)}2}\sin\frac{B-C}2}{\sin(B+C)}\sqrt{\frac{1-\cos(B+C)}2}\\&=\frac{\sin\frac{B-C}2}{\sin(B+C)}\sqrt{1-\cos^2(B+C)}\\&=\frac{\sin\frac{B-C}2}{\sin(B+C)}\sin(B+C)=\sin\frac{B-C}2\end{align} as required.


React lifecycle methods

Question: I have been doing react for a while and am familiar with some lifecycle methods but not so familiar with others
e.g. didMount is clearly for ajax requests or calling data from an api then loading it into the app
I think I have conquered shouldComponentUpdate, and have realised it is purely there for performance
but static getDerivedStateFromProps I cant really get my head around. is that for performance or does that add something else to the app?
and also componentDidUpdate, is this for performance again or where is a good example where I can use these?
clearly some methods are necessary to perform actions and actual requests. clearly some are there to improve performance etc. just would like to get some context around didUpdate and getDerived
thanks
Comment: Have you read https://reactjs.org/docs/react-component.html and https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html?
Comment: read the first, not the second. cheers.
Answer: Yo can understand the lifecycle hooks in react through this blog  : https://medium.com/@baphemot/understanding-reactjs-component-life-cycle-823a640b3e8d
Answer: Lifecycle methods made to allow you to run code at particular times in the process.
componentDidMount() is invoked immediately after a component is inserted into the tree, we commonly use it to make API requests.
Using React Hooks
useEffect(() => {
    makeApiRequest()
}, [])

componentDidUpdate() is invoked immediately after updating occurs (in the state or props). This method is not called for the initial render. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request
Using React Hooks
useEffect(() => {
    doYourStuff()
})

The difference between componentDidUpdate and the Hook above that the Hook will be called in the initial render also. There is no 100% alternative to the componentDidUpdate() method.

componentWillUnmount() is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions.
Using React Hooks
useEffect(() => {
    return () => {
        cleanUp()
    }
})

getDerivedStateFromProps() is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.
Read More -> React Lifecycle React Hooks

React lifecycle methods


Interpretation of Tensor product splines with multiple terms and their standard errors

Question: I am trying to understand the tensor product splines such as
library(mgcv)
vis.gam(gam(data=airquality, Ozone~s(Day, Month)), se = -1)
vis.gam(gam(data=airquality, Ozone~s(Day, Month, Temp)), se = -1)
vis.gam(gam(data=airquality, Ozone~s(Temp, Day, Month, Wind)), se = -1)

where visualised with generalised additive model such that

and lastly one standard errors such that

How to explain the tensor product splines? Why is the order important in forming the splines with s(...,...,...,...)?
Comment: @Maxtron it is visualising the partial effects conditional upon some value for the other covariates. The models are estimating different effects, but not because of order but due to the increasing complexity of the smooth fitted. If you include extra covariates in a regression model, the partial effects of the other terms will change and that's what is happening here. The last plot is showing the uncertainty in the surface with green being the lower and red the upper limit (IIRC this is 1SE but it may be 2SE). Temp is certainly a continuous variable.
Comment: If I am right, it is only plotting how ozone varies across the first two parameters, i.e., in the first plot, it is ozone ~ s(day, month), the second plot is also the same even when you have entered three regressors, and third plot is ozone  ~ s(temp,day). Perhaps, temp is a categorical data which is why you are seeing three plots. The key idea is to create a grid mesh of temp vs day or day vs month and use splines to fit a curve.
Answer: These are not tensor product splines. What you are fitting are 2d and 3d thin plate splines. These kinds of smooths are generally inappropriate for the models you fit here because they assume isotropy; that a unit change in one marginal covariate is the same as a unit change in the other marginal covariate and that therefore a single smoothness penalty is appropriate.
Tensor product splines are produced by the te() function (or t2() for a different parameterisation).
Apart from the first vis.gam() call, you are trying to visualise the partial effect of two covariates conditional upon the others (the other covariates are generally held at some typical value, such as their mean). In the same way that including or removing a term in a simple regression model changes the estimated effect (the partial effect) of a covariate in both models (unless the covariates are orthogonal), changing what terms are in the GAM causes changes in the estimated partial effects of those covariates.
This is compounded here because you are removing or including terms from a single high-dimensional smooth, and furthermore, you are not changing the order of the terms in the model independently of which terms are in the model.
Compare
library('mgcv')
data(airquality)

m1 <- gam(Ozone ~ s(Day, Month, Temp), data=airquality, method = 'REML')
m2 <- gam(Ozone ~ s(Month, Day, Temp), data=airquality, method = 'REML')

> printCoefmat(summary(m1)$s.table)
                     edf Ref.df      F   p-value
s(Day,Month,Temp) 13.495 16.379 9.9337 < 2.2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
> printCoefmat(summary(m2)$s.table)
                     edf Ref.df      F   p-value
s(Month,Day,Temp) 13.494 16.379 9.9338 < 2.2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

There are some slight differences but fitted values and summaries compare to the the first few decimal places. These difference are likely due to the way the 3d thin plate spline basis is being set up — it is a low-rank thin plate spline.
If we switch to tensor product smooths then the two models are the same regardless of order (note I have to set k lower here as it applies to each marginal so we have k^3 terms here prior to application of identifiability constraints).
m1 <- gam(Ozone ~ te(Day, Month, Temp, k=4), data=airquality, method = 'REML')
m2 <- gam(Ozone ~ te(Month, Day, Temp, k=4), data=airquality, method = 'REML')

> all.equal(fitted(m1), fitted(m2))
[1] TRUE

Comment: @hhh no; tensor product smooths do not assume isotropy. They involve multiple smoothness penalties: one per marginal smooth in the case of `te()` terms and one per marginal smooth plus one per "interaction" for `t2()` terms. The extra smoothness penalties in `t2()` terms is due to the special way the penalties on the basis functions are constructed.
Comment: Do tensor product splines assume isotrophy?


Saída de um método ou evento - C# / WPF

Question: Eu estou utilizando um return para poder sair do evento textEstado_Validate. O problema é que quando ele sai desse evento, ele entra no textEstado_KeyDown.
Como posso fazer para que ele não entre em mais nenhum método e nenhum evento?
private void textEstado_Validate(object sender, ValidationEventArgs e)
{
    Ação...

    return;
}

private void textEstado_KeyDown(object sender, KeyEventArgs e)
{
    Ação...
}

Existe um comando pra isso?
O textEstado é um TextEdit, componente do DevExpress
Comment: Qual o tipo do `textEstado`?
Comment: Um campo de texto, editei a descrição
Comment: é igual o TextBox;
Comment: Um TextBox "comum" não tem um evento de validação que receba um `ValidationEventArgs`. @Emerson, se a classe `ValidationEventArgs` tem uma propriedade `Handled`, você pode setá-la para `true` que o evento pára de ser propagado.
Comment: Eu tentei dessa forma, mesmo assim ele entrou no outro evento.
Answer: Você pode usar a propriedade Handled de ValidationEventArgs.
Isso fará com que o evento pare de ser propagado.
private void textEstado_Validate(object sender, ValidationEventArgs e)
{
    //Ação...

    e.Handled = true;
    return;
}

Veja na documentação de ValidationEventArgs do DevExpress
Comment: Já tentei dessa forma @jbueno, ele continua executando e entra no evento textEstado_KeyDown.
Ele entra nesse evento pq eu digito um caracter, correto?
Comment: O `KeyDown` é disparado sempre que alguma tecla é clicada quando o foco está no componente. Pensei que dessa forma funcionaria, vou criar um projeto de teste para verificar.
Comment: Eu agradeço qualquer ajuda...

Saída de um método ou evento - C# / WPF


Using a javascript countdown timer within an asp.net ajax application

Question: After spending hours trying to work out what's going on within my app, I have discovered there's a problem with my code that sets a javascript interval.
Here is my code that sets the interval...
Sys.Application.add_load(function PageLoad(sender, args) {

        var timer = $("#lbTimer");
        var intVal = "";
        var verifiedTime = Date.parse(timer.html());

        if ($("#imgLock").hasClass("hidden") && !isNaN(verifiedTime) && verifiedTime != null) {

            $("#imgLock").addClass("hidden");
            $("#imgUnlock").removeClass("hidden");

            intVal = setInterval(function () {
                $("#lbTimer").html(function () {
                    var t = parseInt((new Date() - verifiedTime) / 1000, 10);
                    t %= 3600;
                    var m = Math.floor(t / 60);
                    var s = Math.floor(t % 60);

                    if (m == 0 && s == 0) {

                        $("#lbLocked").removeClass("hidden");
                        $("#imgLock").removeClass("hidden");
                        $("#imgUnlock").addClass("hidden");
                        $("#lbTimer").html("");
                        window.clearInterval(intVal);
                        verifiedTime = "";
                    } else {
                        if (s == 0) {
                            $(this).html((m + ":0" + s).replace("-", ""));
                        } else {
                            $(this).html((m + 1 + ":" + s).replace("-", ""));
                        }

                        if (s > -10) {
                            if (m == -1) {
                                $(this).html($(this).html().replace(":", ":0"));
                            } else {
                                $(this).html($(this).html().replace("-", "0"));
                            }
                        } else {
                            $(this).html($(this).html().replace("-", ""));
                        }
                    }
                });
            }, 1000);

            $("#lbTimer").removeClass("hidden");

});

Now this works absolutely fine if there a fullpage reload.  Problem is that I'm developing an ajax enabled website and everything updates within an updatepanal.
The problem I'm encountering is that when the updatepanel panel updates a new javascript interval is being created so another counter is being added into #lbTimer resulting in a flicker between 2 or more countdown timers.
Obviously as the script is running on each pageload there's no way of clearing the interval that's already running on the page that I can see, which is resulting in multiple timers.
I did add in the following, whic solved the problem for a while, however I need the timer to update again on partial pageloads.
if (!args.get_isPartialLoad()) {
//Timer code here
}

Does anyone have any suggestions or recommendations how I can use a javascript countdown timer in my app allowing me to clear the interval to create a new one on partial page loads?
Hopefully I've given enough detail, but I can add more if required.
Thanks in advance for time and help!
Answer: Write the followig in partial load to clear off the timer set previously
var intervalID;
var resetTimer = function() {
if (intervalID) {
clearInterval(intervalID) };
intervalID = setInterval(function() {    your code here....};

Comment: Thanks for the quick response.

I'm not sure if I'm using that correctly, but intVal always returns as "undefined" when the page loads(partially)


An error occurs in the setting in BigQuery's DataTransferService

Question: Click on "ttransfer" in BQ's WebUI, enter customerID etc and press "add", the user's selection will appear.
If you press "next" on the next screen, you will return to BQ's webUI and the following error message will be displayed:

Error when creating new transfer

How can I fix this?
Answer: Most likely, there was an OAuth popup that was popup blocked. Please check.
Here are instructions if you are on Chrome:
https://support.google.com/chrome/answer/95472?co=GENIE.Platform%3DDesktop&hl=en


Finding the set of parameters for which the inequality holds for all $x,y$

Question: I encountered the following question about inequalities which I am curious how to solve.
The simplest case is to consider the inequality
$$|x|+|y|+|x+y|+ax+by\geq 0$$
where $x,y,a,b\in\mathbb{R}$.
The question is which values of parameters $a,b\in\mathbb{R}$ would guarantee that the inequality holds for all $x,y\in\mathbb{R}$.
I tried playing with such inequalities and was surprised that this question is harder than I anticipated.
I first found that necessarily $a\in [-2,2]$:
for $x=1$ and $y=0$ we get $2+a\geq 0$ so $a\geq -2$ and for $x=-1$ and $y=0$ we get $2-a\geq 0$ so $a\leq 2$.
Similarly, $b\in [-2,2]$ must hold.
Furthermore, I did find out that if $a=b\in [-2,2]$ then the inequality certainly holds for all $x,y\in\mathbb{R}$, because
$$|x|+|y|+|x+y|+ax+by=(|x|+ax/2)+(|y|+ay/2)+(|x+y|+a(x+y)/2)$$
and each element in the parentheses is non-negative because $a/2\in [-1,1]$ and so $$|z|+az/2=\begin{cases} (1+a/2)z & z\geq 0\\ (-1+a/2)z & z<0\end{cases}\geq 0$$
However, I am sure that there are also other parameters $a,b\in [-2,2]$ for which the inequality holds. For instance $a=2$ and $b=1$ turn out to be a valid solution for all $x,y\in\mathbb{R}$ if you consider the various different cases.
My question is how would I go about finding all such $a,b$?
More generally, is there some theory about such inequalities? Any good reference (paper/book) that is recommend to read in order to better grasp these inequalities?
I am also interested in more general inequalities, with more parameters and variables, for instance
$|x|+|y|+|z|+|x+y|+|x+z|+ax+by+cz\geq 0$
(with the task of finding $a,b,c$ so that it holds for all $x,y,z$).
I am interested to which extent there is a theory of how to solve these questions generally.
Answer: Suppose we have $\def\sgn{\operatorname{sgn}}$
$$|x|+|y|+|x+y|+ax+by \geqslant 0 \tag 1$$
for all $x$ and $y$.  Then this must apply in particular for $y=0$:
$$2|x|+ax = |x|(2+a\sgn x) \geqslant 0
\quad\implies\quad 2+a\sgn x \geqslant 0\tag 2$$
where $\sgn x$ denotes the sign of $x$.  This implies
$|a|\leqslant 2$ and also $|b|\leqslant2$ due to symmetry. When used with $x=-y$, one gets $|a-b|\leqslant 2$.
So more generally, let's try $y=wx$, so that $(1)$ becomes
$$\begin{align}
& |x|+|wx|+|x+wx|+ax+bwx \\
& \quad = |x|(1+|w|+|1+w| + (a+bw)\sgn x) \geqslant 0 \tag 3
\end{align}$$
Divide $(3)$ by $|x|$ to get
$$(a+bw)\sgn(-x) \leqslant 1+|w|+|1+w| \tag 4$$
resp.
$$|a+bw| \leqslant 1+|w|+|1+w| \qquad\text{for all }w\tag 5$$
Thus in the plane, the line $a+wb$ is wedged between $\pm(1+|w|+|1+w|)$.  The wedge is shown in the graphic in red+blue.  However, this wedging is too restrict because it does not take into account that both line and wedge depend on $w$, i.e. the wedge is a bit like a moving target. Lines that do not cross a wedge still represent valid solutions, though.

Now $(5)$ is simpler than $(1)$ in the sense that we have only one value, $w$, in the absulute values on the right side, so that when cases are considered, we are left with just 3 cases instead of the 8 cases of $(1)$. So let's try and split cases:
$$|a+wb|\leqslant\begin{cases}
2+2w, & w\geqslant 0 \\
2, & -1\leqslant w \leqslant 0 \\
-2w, & w \leqslant -1 \\
\end{cases}$$
The constraints from above are recovered for $w\in\{0,-1,\infty\}$.
Notice that due to symmetry, this must still hold true if $a$ and $b$ are exchanged.  Whilst this is somewhat simpler than $(1)$, it's not a satisfying solution and I am stuck here, but maybe some ideas are helpful.

Playing around with Desmos, it appears that the set you are looking for is the hexagon described by
$$\{a,b\in[-2,2] \ :\ |a-b|\leqslant 2\}$$
https://www.desmos.com/calculator/snisn01tvk
The parameter $w$ is named "g" in Desmos and can be changed with a slider.  The plane is the $a$-$b$-plane.  The set of solution is the intersection over all "g" resp. $w$.
Answer: Letting $x = 1, y = 0$, we have
$2 + a \ge 0$.
Letting $x = -1, y = 0$, we have
$2 - a \ge 0$.
Letting $x = 0, y = 1$, we have
$2 + b \ge 0$.
Letting $x = -1, y = 1$, we have
$2 - a + b \ge 0$.
Letting $x = 0, y = -1$, we have
$2 - b \ge 0$
Letting $x = 1, y = -1$, we have
$2 + a - b \ge 0$.
Thus, we have $a, b \in [-2, 2]$ and $|a - b| \le 2$.
$\phantom{2}$
On the other hand, suppose that
$a, b \in [-2, 2]$ and $|a - b| \le 2$.
Let us prove that
$$|x| + |y| + |x + y| + ax + by \ge 0,
\, \forall x, y \in \mathbb{R}.$$
We split into three cases:
Case 1: If $y = 0$, we have
$$\mathrm{LHS} = 2|x| + ax \ge 2|x| - |a|\cdot |x| = (2 - |a|)|x| \ge 0.$$
Case 2: If $y > 0$, since the inequality is homogeneous, WLOG, assume that $y = 1$.
It suffices to prove that
$$|x| + 1 + |x + 1| + ax + b \ge 0, \, \forall x\in \mathbb{R}.$$
(1) If $x \le -1$, we have
$$\mathrm{LHS} = - (2 - a)x + b \ge (2 - a) + b \ge 0.$$
(2) If $-1 < x \le 0$, we have
$$\mathrm{LHS} = 2 + ax + b.$$
If $a \le 0$, we have $2 + ax + b \ge 0$.
If $a > 0$, we have $2 + ax + b \ge 2 - a + b \ge 0$.
(3) If $x > 0$, we have
$$\mathrm{LHS} = (2 + a)x + 2 + b \ge 0.$$
Case 3: If $y < 0$, since the inequality is homogeneous, WLOG, assume that $y = -1$.
It suffices to prove that
$$|x| + 1 + |x - 1| + ax - b \ge 0, \, \forall x\in \mathbb{R}.$$
(1) If $x \le 0$, we have
$$\mathrm{LHS}
= - (2 - a)x + 2 - b \ge 0.$$
(2) If $0 < x \le 1$, we have
$$\mathrm{LHS} = 2 + ax - b.$$
If $a \ge 0$, we have $2 + ax - b \ge 0$.
If $a < 0$, we have $2 + ax - b \ge 2 + a - b \ge 0$.
(3) If $x > 1$, we have
$$\mathrm{LHS}
= (2 + a)x - b \ge 2 + a - b \ge 0.$$
We are done.