Show that $\dfrac{1}{2 \pi i} \int_{c- i \infty}^{c+ i \infty} F(s) G(w-s) ds = \int_0^{\infty} f(x) g(x) x^{w-1} dx.$

Question: Eq. 2.15.10 in Titchmarsh's book The Theory of the Riemann Zeta-Function comes with no proof:
Let f(x) and $F(s)$ be ralated by $$F(s) = \int_0^{\infty} f(x) x^{s-1} dx, \ \ \ f(x) = \dfrac{1}{2 \pi i} \int_{\sigma- i \infty}^{\sigma+ i \infty} F(s) x^{-s} ds.$$ Then we have, subject to appropriate conditions, $$\dfrac{1}{2 \pi i} \int_{c- i \infty}^{c+ i \infty} F(s) G(w-s) ds = \int_0^{\infty} f(x) g(x) x^{w-1} dx.$$ First thing to do is to compute the integral of $f(x)g(x)x^{w-1}$ and see what happens but I failed to reach a result, especially that I very much am hoping for a rigorous proof. Then searching on web and some books that I had lead me nowhere.
The two questions I have: How the equality is derived and what are the conditions are considered "appropriate"? (perhaps the author is thinking of determining the $c$ based on $\sigma_f$ and $\sigma_g$(?))

Note for Bounty: The post below from "Daigaku no Baku" answers the question partially - to get a complete answer I need to justify the interchange of integrals used in "Daigaku no Baku" 's answer and validity of the real interval for $\max (\alpha_1, 1- \beta_2 ) < c < \max ( \beta_1, 1- \alpha_2)$ mentioned in  en.wikipedia.org/wiki/Mellin_transform in the section concerning Parseval's theorem (which is my second question in OP).
Answer: $\newcommand{\cat}[1]{\mathcal{#1}}$
Substitute the definition of inverse Mellin transform of $f(x)$ into the integral on the right hand side. Change the order of integration and get $F(s)$ out of the integral that does not depend on $s$.
$$\int_{0}^{\infty}f(x)g(x)x^{w-1}dx=\frac{1}{2\pi i}\int_{0}^{\infty}\int_{\sigma-i\infty}^{\sigma+i\infty}F(s)x^{-s}g(x)x^{w-1} \ dx \ ds=\frac{1}{2\pi i}\int_{\sigma-i\infty}^{\sigma+i\infty}F(s)\int_{0}^{\infty}x^{w-s-1}g(x)dxds$$
$$\int_{0}^{\infty}x^{w-s-1}g(x)dx=\int_{0}^{\infty}x^{-s}x^{w-1}g(x)dx=G(w-s)$$
Here we used the property of Mellin transform $\cat{M}(x^\nu f(x))(s)=\cat{M}(f(x))(s+\nu)$
$$=\frac{1}{2\pi i}\int_{\sigma-i\infty}^{\sigma+i \infty}F(s)G(w-s)ds$$
The conditions for applicability can be found on the Wikipedia page, in the section concerning Parseval's theorem (which is how this result is called).
Comment: To justify exchanging the integrals, all you need to show is that the double integral converges absolutely. In absolute value, the only $s$-dependent term is $|F(s)|$, so you need to show that 1) $\int_{\mathbb{R}}{|F(\sigma+it)|dt}$ is finite, which should follow from the integrand being $O(1/t^2)$ as $t \rightarrow \infty$ (apparently a standard fact under standard assumptions), and 2) that $\int_{0}^{\infty}{|g(x)|x^{w-1-\sigma}dx}$ converges, which should also follow from growth estimates on $g$ at zero and infinity and judicious choice for $c,w,\sigma$.
Comment: Two questions: 1- How to do justify interchange of two integrals is allowed? 2- In wiki page, how the condition is imposed $\max (\alpha_1, 1- \beta_2 ) < c < \max ( \beta_1, 1- \alpha_2)$?
Comment: Sorry, I can't justify the the interchange without working out details, and rn I don't have time for that. Generally you can change the order of integration if the double integral has absolute convergence on the integration domain. Also, I don't understand your second question.
Comment: My second question is how to prove $\max (\alpha_1, 1- \beta_2 ) < c < \max ( \beta_1, 1- \alpha_2)$ that is the condition that comes in https://en.wikipedia.org/wiki/Mellin_transform in the section concerning Parseval's theorem which you suggest in your answer but I can't prove it
Comment: I would argue that there's nothing to prove here because your $c$ is not defined, it's just "something suitable" – which includes here this interval condition.
Comment: @Aphelli, condition for c is defined on the link provided in the answer but I cannot prove it.
Comment: As far as I can tell, you didn't require any specific condition or definition on $c$ beyond "appropriate assumptions". Why wouldn't this inequality be part of your appropriate assumptions? (Note that you meaningfully use $c$ in your own question, so it can't be defined in the answer).
Comment: @Aphelli, as time passed and I am reading it again I think I am understanding the Wiki page now ... Thanks :)


Checar se nome de usuário é único em tempo real

Question: Olá, galera!
Atualmente, para verificar se um nome de usuário é único, faço da forma mais básica. Envio o POST para uma página PHP que verifica no MySQL, só depois retorna o erro.
cadastro.php:
<form role="form" action="https://<?php print $_SERVER['HTTP_HOST']; ?>/cadastro/" enctype="multipart/form-data" method="post">

    Usuário
    <input name="usuario" type="text" class="form-control" minlength="4" placeholder="Digite um usuário único..." required>

  <button type="submit" class="btn">Criar</button>
</form>

verifica.php:
<?php
  $SqlCheck = $ConDB -> prepare("SELECT COUNT(*) AS `ContUser` FROM
  `usuarios` WHERE `userName`=:USER;");
  $SqlCheck -> bindParam(":USER", $_POST['usuario']);
  $SqlCheck -> execute();
  $RowCheck = $SqlCheck -> fetch(PDO::FETCH_OBJ);
  $ContUser = $RowCheck -> ContUser;

  if ($ContUser == 0) {
    /* Realiza o cadastro */
  } else {
    echo 'Usuário já existe';
  }
?>

É possível fazer essa verificação enquanto digita no input, por exemplo, a partir do 4 caractere é mostrado na linha inferior se o usuário já existe? Em tempo real?
Talvez em jQuery ou ajax dê para fazer, mas não manjo nada dessas linguagens.
Comment: O ruim disso é que depois do 4º caractere vai estressar seu servidor com sucessivos requests.
Comment: Eu acho isso interessante, mas não sou muito aprofundado nisso porque nunca precisei ou não achei necessário aos meus projetos. Mas para evitar o muitos requests ao banco, o que seria péssimo, talvez uma ideia seria criando um arquivo de texto com todos os nomes de usuários já cadastrados e, em vez de consultar o banco, consultar esse arquivo. E ir atualizando esse arquivo de tempo em tempo.
Comment: Tem quantos nomes na tabela?
Comment: Hoje há somente um. O sistema ainda não está online.
Quero aprender fazer igual no cadastro do Gmail. Quando tira o foco do input, ele diz se já existe usuário, na div logo abaixo:
https://uploaddeimagens.com.br/imagens/crie_sua_conta_do_google_-_mozilla_firefox_2017-11-01_21-48-14-png
Comment: A partir do quarto caractere então eu não existiria hahaha
Comment: Dá pra fazer numa boa (e sem estressar o servidor) se você fizer um timer. Por exemplo, quando o campo muda, aguarda um tempinho e faz a checagem, assim não fica disparando requisições à toa enquanto digita. É como muitos sistemas em produção fazem hoje. Muitas vezes a resposta está nos próprios sites que você já visitou com o recurso. Ou faz só na perda de foco mesmo, aí é muito menos requisição.
Answer: Pagina senddata.html

<form method="POST" action="insertdata.php" onsubmit="return checkall();">
 <input type="text" name="username" id="UserName" onkeyup="checkname();">

 <input type="submit" name="submit_form" value="Submit">
</form>

Pagina checkdata.php
$mysqli = new mysqli("localhost", "USUARIO", "SENHA", "NOME_DB");

if(isset($_POST['user_name']))
{
 $name=$_POST['user_name'];

 $checkdata=$mysqli->query("SELECT COUNT(*) FROM user WHERE name = '$name'");

 $row = $checkdata->fetch_row();

 if ($row[0] > 0)
 {
  echo "Nome já existe";
 }
 else
 {
  echo "OK";
 }
 exit();
}

Pagina insertdata.php
if( isset( $_POST['submit_form'] ) )
{

    $name = $_POST['username'];

    $mysqli = new mysqli("localhost", "USUARIO", "SENHA", "NOME_DB");

    $mysqli->query("Insert into user (name) values ('".$name."')");
}

Comment: Muito obrigado, funcionou divinamente! Era exatamente o que estava procurando.
Obs.: em "url: 'checkdata.php'" precisei alterar para "url: 'https://meusite.com.br/verificarusuario/'", pois uso url amigável e não estava encontrando o arquivo.
Answer: Você poderia envolver em um método essa verificação, e fazer um evento no click de um butão chamando o Ajax para verificar se existe o usuário e retornar um resultado conforme o resultado vc faria algo;
Vamos supor que vc tenha um Butão e quando clicar no Butão o evento chama o Ajax para ir no seu arquivo php que tem a método realTime(). No Método vc return para o Ajax um json com o valor se verdadeiro Cadastro feito com sucesso, se não exibe ja existe o úsuario.
<?php
public function realTime(){
$SqlCheck = $ConDB -> prepare("SELECT COUNT(*) AS `ContUser` FROM
`usuarios` WHERE `userName`=:USER;");
$SqlCheck -> bindParam(":USER", $_POST['usuario']);
$SqlCheck -> execute();
$RowCheck = $SqlCheck -> fetch(PDO::FETCH_OBJ);
$ContUser = $RowCheck -> ContUser;

  if ($ContUser == 0) {
   return json_encode('Cadastro Realizado com sucesso!');
  } else {
    return json_encode('Usuário já existe');
  }
}
?>

<button id="verificaUser"></button>

$(document).ready(function(){
   $('#verificaUser').click(function(){
      $.ajax({
       url: 'caminho/da/funcaoQueVericaSeTemOUsuarioNoBanco.php',
       type: 'POST',
       dataType: 'JSON',
       success: function(e){
         alert(e);
       }
      });
   });
})


Supremum and Infimum of the $nth$ Tail

Question: Let $x_n = \frac{(-1)^n}{n}$. Find $\inf(T_n)$ and $\sup(T_n)$.
I believe that on this one I'm still having some trouble wrapping my head around the definition of the $nth$ tail, which I restate from my book here:
Let $x_n$ be any sequence of real numbers. Denote $T_n = \{ x_k$ | $k \geq n \}$, which we call the $nth$ tail of the sequence $x_n$.
My problem is that the $n$ in $T_n$ seems arbitrary. For example, it seems to me like,
$\sup(T_1) = \frac{1}{2}$,
$\sup(T_2) = \frac{1}{2}$,
$\sup(T_3) = \frac{1}{4}$,
$\sup(T_4) = \frac{1}{4}$,
$\sup(T_5) = \frac{1}{6}$,
$\sup(T_6) = \frac{1}{6}$,
and so on and so forth, because $T_n$ is just $x_n$, but beginning at an $n$ of our choice instead of 1. Thus, I'm not certain what it means to find the infimum and supremum of $T_n$ in general, as opposed to a particular $T_n$, where $n$ has become definite.
So, in short, what is it that I'm missing about the definition that's causing this confusion?
Answer: You can just write down your findings in terms of $n$:
$$
\sup T_{n}=\sup\left\{ x_{n}\colon k\geq n\right\} =\sup\left\{ \frac{\left(-1\right)^{k}}{k}\colon k\geq n\right\} =\begin{cases}
1/n, & \text{if }n\text{ is even}\\
1/(n+1), & \text{if }n\text{ is odd}
\end{cases}
$$
and similarly for the infimum.
Comment: Ah, that makes sense. So you're saying that I actually did understand the definition properly, and I just needed to come up with a more abstract way to express the answer?
Comment: Yeah, pretty much.

Supremum and Infimum of the $nth$ Tail


Streamread section of text file to string

Question: Using VB.NET. I am trying create a string of spatial coordinates for use as a parameter in querying a web service. The coordinates need to be extracted from a text file (a standard output from a GIS) which could be of any length.
The web service needs to see the string of coordinate pairs in a 'well known text' format separated by a comma. E.g. -2.780299 53.373266, -2.780606 53.372617, -2.782207 53.370392, -2.784552 53.362061
(superficially similar to a question asked here )
The text file is in this structure. To reiterate i need a string containing only the coordinates (pairs separated by a comma) after "161" and before "pen". 161 is not a consistent number though the word "Region" is.
<code>            Version   300
            Charset "WindowsLatin1"
            Delimiter ","
            CoordSys Earth Projection 1, 104
            Columns 1
              id Char(10)
            Data

            Region  1
              161
            -2.780299 53.373266
            -2.780312 53.373235
            -2.780535 53.372905
            -2.780606 53.372617
            -2.780844 53.372234
            -2.781227 53.371664
            -2.781239 53.371646
            -2.781409 53.371407
            -2.781779 53.3709
            -2.782101 53.370549
            -2.782204 53.370402
            -2.782207 53.370392
            -2.781142 53.37014
            -2.780263 53.369894
            -2.780314 53.369698
            -2.780378 53.36953
            -2.780453 53.369362
            -2.780532 53.369223
            -2.780611 53.369101
            -2.780826 53.368803
            -2.781468 53.367978
            -2.781768 53.367608
            -2.78184 53.367497
            -2.781863 53.367458
            -2.781806 53.367446
            -2.781751 53.367435
            -2.781712 53.367428
            -2.781733 53.367398
            -2.781753 53.367369
            -2.781847 53.36723
            -2.781949 53.367077
            -2.781866 53.367046
            -2.781492 53.366907
            -2.781182 53.36682
            -2.781269 53.366388
            -2.780878 53.366173
            -2.781063 53.365894
            -2.781693 53.365255
            -2.782277 53.364606
            -2.782594 53.364311
            -2.782652 53.364272
            -2.782676 53.364242
            -2.782687 53.364205
            -2.78268 53.364158
            -2.782643 53.364085
            -2.782643 53.364035
            -2.782943 53.363738
            -2.783346 53.363266
            -2.783736 53.362905
            -2.784254 53.362383
            -2.784552 53.362061
            -2.784617 53.361959
            -2.784113 53.361843
            -2.783923 53.361764
            -2.783968 53.361533
            -2.783978 53.361504
            -2.784358 53.361226
            -2.784823 53.360723
            -2.784833 53.360712
            -2.785201 53.360193
            -2.785831 53.359301
            -2.785832 53.359301
            -2.786182 53.358787
            -2.786484 53.358288
            -2.786318 53.35821
            -2.787152 53.356913
            -2.787255 53.356614
            -2.787199 53.356333
            -2.787559 53.356315
            -2.790294 53.356237
            -2.791854 53.35619
            -2.792974 53.356147
            -2.794152 53.356092
            -2.794698 53.35605
            -2.79521 53.356012
            -2.795333 53.356006
            -2.795732 53.355982
            -2.79586 53.355973
            -2.796257 53.355942
            -2.797842 53.355898
            -2.797931 53.355936
            -2.798299 53.355921
            -2.798399 53.355926
            -2.798727 53.355937
            -2.799055 53.355943
            -2.799382 53.355944
            -2.799711 53.355942
            -2.799919 53.355939
            -2.800248 53.355929
            -2.800575 53.355915
            -2.800901 53.355898
            -2.802135 53.355819
            -2.803302 53.355749
            -2.804436 53.355658
            -2.805646 53.355515
            -2.807964 53.355207
            -2.809126 53.355058
            -2.809593 53.354684
            -2.810372 53.354184
            -2.81147 53.353449
            -2.81147 53.353444
            -2.811472 53.353428
            -2.811474 53.353413
            -2.811477 53.353397
            -2.811481 53.353381
            -2.811487 53.353365
            -2.811492 53.35335
            -2.811506 53.353325
            -2.811538 53.35328
            -2.811578 53.353237
            -2.811617 53.353193
            -2.811622 53.353188
            -2.811663 53.353145
            -2.811704 53.353101
            -2.811749 53.353069
            -2.811852 53.352994
            -2.811875 53.352979
            -2.811983 53.352906
            -2.812094 53.352834
            -2.812209 53.352764
            -2.812324 53.352695
            -2.812443 53.352629
            -2.813163 53.352174
            -2.81362 53.351928
            -2.813782 53.352417
            -2.814005 53.353349
            -2.814147 53.354287
            -2.814206 53.355228
            -2.814183 53.356169
            -2.814077 53.357109
            -2.813889 53.358043
            -2.813619 53.358971
            -2.813268 53.359889
            -2.812837 53.360795
            -2.812327 53.361686
            -2.81174 53.36256
            -2.811077 53.363414
            -2.81034 53.364247
            -2.809531 53.365055
            -2.808652 53.365837
            -2.807706 53.366591
            -2.806694 53.367313
            -2.805621 53.368004
            -2.804489 53.36866
            -2.803301 53.369279
            -2.802059 53.369861
            -2.800769 53.370403
            -2.799433 53.370904
            -2.798055 53.371362
            -2.796638 53.371777
            -2.795187 53.372147
            -2.793705 53.372471
            -2.792197 53.372749
            -2.790666 53.372979
            -2.789118 53.37316
            -2.787556 53.373294
            -2.785984 53.373378
            -2.784407 53.373413
            -2.782829 53.373399
            -2.781254 53.373335
            -2.780299 53.373266
                Pen (2,2,16711680)
                Brush (5,16711680)
                Center -2.797227 53.362684
</code>
As always any help of direction would be appreciated. The existing code, which works over old SOAP based services, looks like the following. However, it uses a custom library that i will no longer be able to access and don't know how to replace. It also makes use of a spatial system (easting and northings) that are no longer recognised by the new services.
There is the potential i may be able to convert the spatial system within the program so if it is only possible to get this working without the need for the NBN library that would be a big step in the right direction.
<code>            Function GetPolyFromMIF(ByVal strMIF As String) As NBN.Polygon

                    Dim sr As StreamReader = New StreamReader(strMIF)
                    Dim sLine As String = sr.ReadLine
                    Dim iCoords As Integer
                    Dim iCoord As Integer
                    Dim sCoords() As String
                    Dim dblEasting As Double
                    Dim dblNorthing As Double
                    Dim coords() As NBN.Coordinate
                    Dim bPolyComplete As Boolean = False
                    Dim poly As NBN.Polygon = New NBN.Polygon

                    Do While Not sr.EndOfStream And Not bPolyComplete

                        If sLine.StartsWith("Region") Then

                            iCoords = Convert.ToInt16(sr.ReadLine)
                            ReDim coords(iCoords)
                            For iCoord = 1 To iCoords
                                sCoords = sr.ReadLine.Split(" ")
                                dblEasting = Convert.ToDouble(sCoords(0))
                                dblNorthing = Convert.ToDouble(sCoords(1))
                                coords(iCoord - 1) = New NBN.Coordinate
                                coords(iCoord - 1).x = dblEasting
                                coords(iCoord - 1).y = dblNorthing
                            Next
                            poly.srs = NBN.SpatialReferenceSystem.osgb_BNG
                            Dim boundary As NBN.PolygonBoundary = New NBN.PolygonBoundary
                            boundary.Ring = coords
                            poly.Boundary = boundary
                            bPolyComplete = True
                        Else
                            sLine = sr.ReadLine
                        End If
                    Loop

                    Return poly
                End Function
</code>
Answer: I would process the lines with a regex.  Load each line into your parser line by line but without detecting anything but matching to a regex pattern.  By taking this approach you can process any size of file and only retrieve those values from the file that you are interested in.
If you want me to post an explanation of what the Regex does, let me know and I can do that too.
If you want to figure out the regex yourself, type regex cheat sheet into google and pick any result that you might like to learn more about regex matching.
My code is based upon the following assumption.  Each of the coordinates are on a separate line as was implied by the file format that you posted.  I also assumed that you need to deliver the coordinates to your system in sets of four.  You mentioned the well known format was two coordinates followed by a comma and two more coordinates.  The code I wrote gives you a list of a class that I included and each instance of that class will have the four coordinates that make up a set in properties and a property that returns them in the format you wanted.  The list cannot have a coordinate set added to it that is not valid.  You might have a bug in my code in that it might miss the last coordinate, I never tested it that far.
<code>Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim lst As New List(Of CoordinateSet)
    Using sr As New System.IO.StreamReader("c:\temp\coords.txt")
        Dim line As String = sr.ReadLine
        Dim counter As Integer = 0
        Dim coord As New CoordinateSet
        While line IsNot Nothing
            If coord.CoordSet IsNot Nothing Then
                lst.Add(coord.Clone)
                coord = New CoordinateSet
            End If
            If IsMatch(line.Trim) Then
                If coord.One Is Nothing Then
                    coord.One = line.Trim
                ElseIf coord.Two Is Nothing Then
                    coord.Two = line.Trim
                ElseIf coord.Three Is Nothing Then
                    coord.Three = line.Trim
                ElseIf coord.Four Is Nothing Then
                    coord.Four = line.Trim
                End If
            End If
            line = sr.ReadLine
        End While
    End Using
    MessageBox.Show(String.Format("I found {0} coordinate pairs.", lst.Count))
End Sub

Private Function IsMatch(line As String) As Boolean
    Dim reg As New System.Text.RegularExpressions.Regex("^[-]?[0-9]+[\.]+[0-9]+[ ][-]?[0-9]+[\.]+[0-9]+")
    Return reg.IsMatch(line)
End Function

Public Class CoordinateSet
    Implements ICloneable
    Public Property One As String
    Public Property Two As String
    Public Property Three As String
    Public Property Four As String
    Public ReadOnly Property CoordSet As String
        Get
            If Not String.IsNullOrEmpty(One) AndAlso Not String.IsNullOrEmpty(Two) AndAlso Not String.IsNullOrEmpty(Three) AndAlso Not String.IsNullOrEmpty(Four) Then
                Return String.Format("{0} {1}, {2} {3}", One, Two, Three, Four)
            Else
                Return Nothing
            End If
        End Get
    End Property

    Public Function Clone() As Object Implements ICloneable.Clone
        Return MemberwiseClone()
    End Function
End Class
</code>
Comment: Thank you very much for your response. I haven't had the chance to try  your solution but just reading through your solution i think i may have confused things slightly. The text file format is in the structure shown (each coordinate point is on a separate line) but i do not need sets of for, instead i require a single string of all the points (which describe a polygon). With each coordinate/line separated by a comma. I may be able to work with the code you posted however so please bear with me!
Comment: The regex was particularly useful in identifying the lines to extract. Some modification of the code was required to fit my end use but the majority is as shown in this solution. Cheers Wizengamot!


Hide page title if the image field has a value

Question: I have a image field (field_image) on my content type. I want to show the image below the header with the node title inside. I am successfully doing that in page.html.twig.
{% if node.field_image %}

{{ node.label }}

{% endif %}

However, the page title is also showing up in the page title block inside of the Header region. I'm trying to find a way to hide the second page title, on the full node view, if the field_image field has a value.
How can I achieve this?
Comment: node.label has the title of that node!! What value you want to print there instead??
Comment: Yes, I am using {{ node.label }} to print in the #feature-image div. However, it's also showing up in the Page title block. I'd like to hide the block altogether if `field_image` has a value.
Answer: This method works for me. (Thanks to kim.kennof on Slack for the assistance.)
In my THEME.theme file:
function THEME_preprocess_page_title(&$variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    if ($node instanceof \Drupal\node\Entity\Node) {
      $variables['node'] = $node;
    }
  }
}

Then in page-title.html.twig:
{% if node.field_image is empty %}
  {% if title %}

{{ title }}

  {% endif %}
{% endif %}

Comment: `if ($node instanceof \Drupal\node\Entity\Node)` would be a lot more robust for the condition
Comment: No the inner condition. Better to check that something _is_ the single thing that it should be, rather than _isn't_ all the things it shouldn't be
Comment: @Clive Do you mean instead of `if ($node = \Drupal::routeMatch()->getParameter('node'))`?
Comment: Ahh, of course, makes sense. Code updated and works great. Thank you!
Answer: You an add a hook_block_access to a .module file in a custom module.
Include these use statements at the top of the file
use Drupal\node\NodeInterface;
use Drupal\Core\Access\AccessResult;

Then implement your hook like so.
/**
 * Hide page title block when the node being viewed has a hero image.
 *
 * Implements hook_block_access()
 */
function ifde_blog_block_access($block, $op, $account) {
  if ($block->id() == 'REPLACE_WITH_PAGE_TITLE_BLOCK_ID' && $op == 'view') {
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof NodeInterface && $node->hasField('field_image') && !empty($node->field_image->getValue())) {
      return AccessResult::isForbidden();
    }
  }
  return AccessResult::neutral();
}


ServiceStack selfhosting disable caching for memory

Question: Using Selfhosting standard ServiceStack MVC Application every request get cached in the memory. Changing any js file have no conscience until i restart the server.
Is there any way around this problem for developing purposes?
Answer: Every request does not get cached in memory, when you're self-hosting it's running the binary dlls and static files that are copied into your /bin folder.
You can change Config.WebHostPhysicalPath to change ServiceStack to serve files from your solution folder instead, e.g:
SetConfig(new HostConfig {
#if DEBUG
    DebugMode = true,
    WebHostPhysicalPath = Path.GetFullPath(Path.Combine("~".MapServerPath(), "..", "..")),
#endif
});


Should I have to implement all 4 operator overload in order to deal with all const and non-const combinations?

Question: General context
I have a self-made struct and I want to compare two instance of it. In order to do that I obviously overload the operator== so I will be able to do so. Now, this operator may be called with 0 to 2 const instances and 0 to 2 non-const instances.
As I want my operator == to compare 2 const as it compare any possible combination of const and non-const, the best for me should be to write only one overload which can deal with all possible combination. But as far as I know, I didn't find any way to do so.
Question
Does that mean that if I need to consider all possible combination, I have to write all 4 possible overloads ? Is there anyway I can avoid to write 4 times the same function only with const keywords changing ?

Specific example
So here is the struct. It represents an object on a plan, and consists of its position and a value associated to it:
struct Foo
{
    int x;
    int y;
    double value;
};

Now let's say 2 Foo are equal if they have the same value and the same position. I have the following operator:
inline bool operator==(Foo object) // Compare two non-const Foo
{
    return (x == object.x) && (y == object.y) && (value == object.value);
}

But, eww, unlucky some Foo can be constants, meaning that my objects can't move on the plan and can't change their value. And now I need to check if two const Foo can be equals and if a non-const Foo can be equal to a const Foo.
Is there anyway I can do that but still avoid to write those following functions which are almost the same as the first one ?
inline bool operator==(const Foo &object) // Compare a non-const Foo with a const Foo
{
    return (x == object.x) && (y == object.y) && (value == object.value);
}

inline bool operator==(const Foo &object) const // Compare two const Foo
{
    return (x == object.x) && (y == object.y) && (value == object.value);
}

inline bool operator==(Foo object) const // Compare a const Foo with a non-const Foo
{
    return (x == object.x) && (y == object.y) && (value == object.value);
}

I don't have any requirements on c++ version. It can ever be c++17 or c++20.
Comment: I tried to make this as clear and concise as I could but don't hesitate to ask for any missing info
Comment: I don't see any reason to do so.
Answer: Operator==, like most binary operators, should normally be implemented as a single, non-member, free function:
 inline bool operator==(const Foo & a, const Foo & b ) {
       return a.x == b.x && a.y == b.y && a.value == b.value;
 }

Comment: C++ has always allowed (and encouraged) writting functions like this. As I said, you need to make it a non-member function.
Comment: Which c++ standard allow to do this ? Because I tried this too but it doesn't compile for me. I got a `too many parameters for binary operator 'operator=='` error
Answer: If you have a non-const Foo object, you can use it where const Foo& object are expected, and you can call const-method on it, so you should only have one overload:
bool operator==(Foo const& object) const {
    return (x == object.x) && (y == object.y) && (value == object.value);
}

You only needs to differentiate const and non-const overloads for specific cases where the behavior is different depending if the object is const or non-const, e.g., for operator[]:
// You want to return a reference on non-const object and a const-reference
// on const object, so you need both overloads.
X& operator[](std::size_t);
const X& operator[](std::size) const;

You usually want to have non-member functions for binary operators, with  friend if necessary. In your case, since all members are public, you can simply create a free function (outside the struct):
bool operator==(Foo const& lhs, Foo const& rhs) const {
    return lhs.x == rhs.x && lhs.y == rhs.y && lhs.value == rhs.vallue;
}

You can also drop that inline modifier which is kind of irrelevant nowadays, see, e.g., When should I write the keyword 'inline' for a function/method?.
You can also check What are the basic rules and idioms for operator overloading? for some idioms regarding operator overloading.
Comment: Alright, I see. I started by writing the passing-by-value function and got misleaded by the error I got, so I just added the `const reference` one and assumed that I needed all of those I described. Thanks for the precisions on the utility of multiple overloads also
Answer: There is no reason to do so!
As long as it is just comparison then it is preferred always to use const references:
  inline bool operator==(const Foo &object)const{
        return (x == object.x) && (y == object.y) && (value == object.value);
  }

The reason is you can pass the address or reference of const and non-const to a const member function but not the contrary.
There are some cases when overloading depending on constness matters.


Unexpected Python interpreter output

Question: I wrote an extremely basic python code which creates a file and appends 10 lines in it
>>> b = open("b.txt", 'w')
>>> for i in range(10):
...     b.write("line %d\n" %i)
...
7
7
7
7
7
7
7
7
7
7

Why are 7's outputted on the screen?
Comment: No of bytes it has written.
Comment: From `help(b.write)`: "Returns the number of characters written".
Comment: Try this at the command prompt: `for x in range(10): x**2`; then extrapolate :)
Answer: The '7's outputted to the console are the number of bytes written to the file, and are returned by the file.write function. See the docs here.
In addition, you should generally use the following format to handle files:
with open("b.txt", "w") as f:
    for i in range(10):
        f.write("line %d\n" %i)

This avoids having to manually close the file after you've finished with it.
Comment: This should be a comment, as it doesn't address anything the OP is asking about.
Comment: This would better serve as a comment than as an answer. While the point made is valid, it is totally irrelevant to the question asked.
Answer: This comes from the behavior of the interactive interpreter. You'll notice a similar effect if you write
>>> x = 5
>>> x
5

When you have a statement and don't set it equal to anything, the interactive interpreter will repr the output/return value and display it in the terminal. The return value for a file write command is the number of bytes written to the file.

Unexpected Python interpreter output


How many examples do I need to show that a change in a feature causes a change in prediction?

Question: not being a statistician I have a bit of a trouble to wrap my head around the following concept.
Say I have a dataset $D$ of $N$ data points and a binary classifier (that was fit to some other dataset) that has mean accuracy $a$.
I want to change $D$ to $D'$ by altering the data points in some way and want to observe the new accuracy $a'$ of the classifier, expecting $a' < a$.
How do I choose the dataset size $N$ to be able to reliably say that the change was responsible for the performance drop? How do I report the confidence of that statement? Do I have to do a power analysis?
To instantiate a concrete example:
Say I have a trained neural classifier that classifies tweets in two categories (toxic/non-toxic). I create $D$ as a set of tweets where the accuracy of the classifier is high, say $a = 0.9$. I change $D$ to $D'$ in some defined way, say by inserting a certain word at the beginning of the tweet and expect the classifier performance to be significantly lower on $D'$, $a' < a$. How big do I need to choose $N = |D|$, i.e. how many tweets do I need to create, how do I compute the significance and how do I report the confidence?
Thank you all very much!
Answer: great question. I know you're asking specifically about neural networks and about sample size. I will try to answer a bit indirectly by going over a few similar techniques that I'm familiar with.
In random forests there are a series of feature selection techniques that do exactly this type of analysis where they test the strength of a predictor by seeing how the accuracy changes after permuting the value. They don't really take sample size into account explicitly, but this might be another approach to pursue. They usually use some variant of the algorithm below, and then either create distributions for changes in errors or use user-defined cutoffs to identify important features. Some of these algorithms are hypothesis-based and some are not, so it gives you an idea of what sorts of tools are available.
The general algorithm goes as follows:
General Permutation Algorithm

Train a random forest, report scores & rank features
Shuffle or permute the values of the features in $D$
Train a new RF with the permuted features
Compare the feature importance before and after, and keep features exceeding a threshold

References to Permutation Techniques in RFs
Below are a few papers that deal with permuting features as a strategy to identify which have the strongest relationships to your target.

Altmann, A., Toloşi, L., Sander, O., & Lengauer, T. (2010). Permutation importance: a corrected feature importance measure. Bioinformatics, 26(10), 1340-1347.
Strobl, C., Boulesteix, A. L., Kneib, T., Augustin, T., & Zeileis, A. (2008). Conditional variable importance for random forests. BMC bioinformatics, 9(1), 307.
Janitza, S., Strobl, C. and Boulesteix, A.L., 2013. An AUC-based permutation variable importance measure for random forests. BMC bioinformatics, 14(1), p.119.

Hope this helps.


How to find a subspace that satisfies a direct sum

Question: The problem states:
Suppose
$$U=\{(x,x,y,y)\in F^4:x,y\in F\}$$
Find a subspace $W$ of $F^4$ such that $F^4$ equals the direct sum of $U$ and $ W$.
So I know that we are basically trying to find a $W$ such that when added with you there is only one way to write the sum such that it equals $F^4$.
My thoughts:
My best guess is that $W = \{(0,0,0,0)\}$ because that way your sum is unique. For example, if you get $U = (1, 1, 1, 1)$ the only possible way to obtain this value with the addition of these sets is by doing $(1+0, 1+0, 1+0, 1+0)$ which ends up being $(1, 1, 1, 1)$. If you were to make a change to any of the $x$'s or $y$'s from $U$, it is impossible to obtain the same result from a different way. Can anyone corroborate if I'm going in the right direction?
Comment: You want $U\oplus W = F^4 = \{(w, x, y, z)\in F^4: w, x, y, z\in F\}$
Answer: What we are basically trying to find is a space $W$ such that every $(x_1,x_2,x_3,x_4)\in F^4$ can be written as $w+(x,x,y,y)$ with $w\in W$ and $(x,x,y,y)\in U$.  This can be done for example if $W=\{(u,0,v,0):u,v\in F\}$.
Your suggestion that $W=\{(0,0,0,0)\}$ isn't going to work, because if you add $(0,0,0,0)$ to an element of $U$, that element still has the form $(x,x,y,y)$. You thus won't be able to get through that addition vectors in $F^4$ which don't have that form, say $(0,1,0,1)$.
Comment: Thank you, I understand what you are supposed to do now.
Answer: Put
\begin{align*}
u_1 &= \begin{bmatrix}1\\1\\0\\0\end{bmatrix} &
u_2 &= \begin{bmatrix}0\\0\\1\\1\end{bmatrix}
\end{align*}
and note that $\{u_1,u_2\}$ is a basis for $U$.

If $\{u_1,u_2,v,w\}$ is a basis for $\Bbb F^4$, then $\Bbb F^4=U\oplus\DeclareMathOperator{Span}{Span}\Span\{v,w\}$

Can you prove this boxed statement?
Now, we can find suitable $v$ and $w$ algorithmically by computing the reduced row-echelon form of the matrix
$$
\left[\begin{array}{rr|rrrr}
1 & 0 & 1 & 0 & 0 & 0 \\
1 & 0 & 0 & 1 & 0 & 0 \\
0 & 1 & 0 & 0 & 1 & 0 \\
0 & 1 & 0 & 0 & 0 & 1
\end{array}\right]
$$
Row-reducing gives $\DeclareMathOperator{rref}{rref}$
$$
\rref
\left[\begin{array}{rrrrrr}
1 & 0 & 1 & 0 & 0 & 0 \\
1 & 0 & 0 & 1 & 0 & 0 \\
0 & 1 & 0 & 0 & 1 & 0 \\
0 & 1 & 0 & 0 & 0 & 1
\end{array}\right]
=
\left[\begin{array}{rrrrrr}
1 & 0 & 0 & 1 & 0 & 0 \\
0 & 1 & 0 & 0 & 0 & 1 \\
0 & 0 & 1 & -1 & 0 & 0 \\
0 & 0 & 0 & 0 & 1 & -1
\end{array}\right]
$$
The second two pivot columns in the reduced row-echelon form correspond to our desired $v$ and $w$ in the original matrix. That is, choosing
\begin{align*}
v &= \begin{bmatrix}1\\0\\0\\0\end{bmatrix} &
w &= \begin{bmatrix}0\\0\\1\\0\end{bmatrix}
\end{align*}
allows us to write $\Bbb F^4=U\oplus\Span\{v,w\}$.


If $a^n = 0$ for some $a \in R$, where R is a ring with unity, does that mean $R$ cannot be an integral domain?

Question: I think it cannot be an integral domain because $a\cdot a^{n-1} = 0$. But if $a=0$, this is true.
Answer: Clean it up a bit and it's true. Let $a\in R-\{0\}$, with $a^n=0$ for some $n\in\mathbb{N}$. Now let $m$ be the minimal element of $\mathbb{N}$ such that $a^m=0$. Then we have that $a^{m-1}\cdot a=0$, but neither are $0$.
Comment: So does $a \in R$ - {0} mean the ring must not have 0? Or $a \neq 0$?
Comment: Here it means $a\neq 0$. Rings have $0$ as a part of their definition; we need an additive identity.
Answer: If $R$ is an integral domain and $a^n=0$ then $a=0$. If $a^n=0$ and $a\ne 0$ then $R$ cannot be an integral domain because $a\cdot a^{n-1}=0$. If $a^n=0$ and $a=0$ then we cannot determine whether $R$ is an integral domain or not because we always have $0^n=0$.


Allow downloading files from private filesystem when paths to files are built without Drupal

Question: I have set up files under private filesystem (large tree of dirs and files).
Drupal does not know anything about those files, because they are not added by file upload field, but links are manually defined as strings (in special field in content type), and put in place with ftp.
Also, path to those files are not completely contained within string, but constructed in field--field_myfiled.tpl.php (some taxonomy magic adds parts of the path, so in actual string i have only filename).
Now, adding just system/files/ before link constructed in field--field_myfiled.tpl.php returns privilege errors, so I guess i need to tell Drupal somehow to allow downloading these files. I am not sure - could I use hook_file_download in this case, and how I could implement this or simmilar function or approach to give access to those files ?
EDIT: My latest findings are that it seems that hook_file_download is triggered whenever you try to access a valid link to a file in private filesystem. No need for anything except hook_file_download here!
Answer: Here are a few modules that should help you configure the way files are served.

Storage API module. It provides advanced file storage and serving options; such as to upload or serve from a separate server, via ftp, etc. It's my favorite option. I currently use it to host all files on a separate server.
CDN module. Designed for CDN related tasks, but can be used in your case to specify an alternative file location for specific file types.
Remote Steam Wrapper module. Not sure if this will work for private files. It makes it easier to serve external files.
Media Mover module. Provides advanced file serving possibilities, i.e. get files from a FTP server, provide file tokens for authentication, get files from CCK fields, etc. It's only available in development version.

Update
If you want to do it via custom code, use field_view_value() function to pull the URL from the field. Use file_create_url to create URL for streaming. You'll also need to use hook_file_download to allow the file to be downloaded; otherwise you will get a page not found.
Update
If I understood correctly, you have a field, where you enter the file name (i.e. myFile.pdf), and you rewrote its field theme (field--field_myfield.tpl.php) to generate the full location of the file. The problem here, is that you cannot include hooks/functions within a theme. Your solution would be to construct the file location in a custom module or template.php.
Example of rewriting the field value via template.php. Replace MYTHEME with your theme name.
function MYTHEME_preprocess_field(&$vars) {
  if($vars['element']['#field_name'] == 'field_myField') {
    $filePath = '/secret/location/' . $vars['items']['0']['#markup'];
    $vars['items']['0']['#markup'] = file_create_url($filePath);
    return;
  }
}

If you want to check for permissions, use hook_file_download.
Comment: Glad I could help:)
Comment: Thanks, information from your Update section is guidance what I need. I am not quite sure though, how I could in my custom code "register" links that will be put through  hook_file_download ?
Comment: problem is that drupal does not know for those files I am putting for download (those files does not have any db entry - they are just linked). Is there a way to construct "on the fly" data that will go through hook_file_download ?
Comment: See my update, above.
Comment: Thanks, it seems that this may lead me to the solution! I will need to test it. Meanwhile enjoy the bounty reward. ;)
Comment: I cannot get modified field to go through the hook_file_download. When using hook_file_download($uri) { drupal_set_message($uri); } it does not output anything (while when downloading from normal file field, it outputs $uri). I tried to "mimic" file_field by rewriting fields by MYTHEME_preprocess_field, but it actually never gets through. I need somehow to direct Drupal that my field needs to go through the function...
Answer: First i would make sure you can access these files directly via system/files/myfile.txt.
If it doesnt work, you'll have to check your .htaccess file and enable that directory for public viewing or just 755 permissions that folder.
if that does work, then I would create a View as either a block or page depending on the flexibility you need and add in the fields or terms associated with your tpl and create another text related field and rewrite the results of the previous field to construct your links using tokens.
Comment: He is trying to avoid having the files publicly downloadable as far as I can tell, which means he has to deny them with .htaccess. He is looking for a way to serve them through Drupal without Drupal being 'aware' of them.
Comment: Phizes is true - files are located out of the webroot. Also, I would like to avoid Views and make the solution as generic as possible (via custom module). Tnx for your effort!


What needs to be done to cleanly move a Bugzilla installation from one server to another?

Question: I have the most recent version of Bugzilla running on one server, and need to migrate it to another. What steps need to be taken to cleanly move Bugzilla to another host? Minimal downtime is acceptable.
Answer: Try the instructions here: https://wiki.mozilla.org/Bugzilla:Move_Installation


Why does my app occasionally crash when I change a frame?

Question: I have a custom UISegmentedControl and when I initialize it, it crashes sometimes. It is uncommon, about 1% of the time, (just uncommon enough to pass apple's "rigorous" app testing), and even though I have this exact same code in three other views, it only crashes on one particular one of them.
Code:
NSArray *providers = [[NSArray alloc] initWithObjects:@"All", @"Soon", @"Attn", @"Late",     @"Done", nil]; //categories for segmented control
FancySegmentedControl *fancy = [[FancySegmentedControl alloc] initWithItems:providers];
fancy.backgroundColor = [UIColor clearColor]; //change bg color
fancy.frame = CGRectMake(11, 86, 263, 29); //lldb crashes here
[fancy setBackgroundColor:[UIColor colorWithRed:42/255.0f
                                          green:82/255.0f
                                           blue:164/255.0f alpha:1] forState:UIControlStateNormal];

So, my symptoms are:
-Crash does not happen most of the time.
-Crash only happens on one of four view controllers even though the code is identical.
-Crash has only been noticed in the simulator (anything to do with that??) It is possible this is just because testing happens a lot more in simulator than on device, though.
-My project uses ARC.
The code for FancySegmentedControl is as follows:
@interface FancySegmentedControl : UISegmentedControl
{
    UIColor *bgNotSelected;
    UIColor *bgSelected;
    UIColor *barNotSelected;
    UIColor *barSelected;
}

-(void)setBackgroundColor:(UIColor *)color forState:(UIControlState)state;

-(void)setBarColor:(UIColor *)color forState:(UIControlState)state;

-(void)setTextAttributes:(NSDictionary *)attrs forState:(UIControlState) state;

@end

@implementation FancySegmentedControl

- (id)initWithItems:(NSArray *)items
{
    self = [super initWithItems:items];
    bgSelected = [UIColor blueColor];
    bgNotSelected = [UIColor whiteColor];
    barNotSelected = [UIColor lightGrayColor];
    barSelected = [UIColor orangeColor];
    self.selectedSegmentIndex = 0;
    if (self) {
        //change text stuff
        NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                    [UIFont boldSystemFontOfSize:17], UITextAttributeFont,
                                    [UIColor blackColor], UITextAttributeTextColor,
                                    nil];
        [self setTitleTextAttributes:attributes forState:UIControlStateNormal];
        NSDictionary *highlightedAttributes = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:UITextAttributeTextColor];
        [self setTitleTextAttributes:highlightedAttributes forState:UIControlStateHighlighted];

        //set all dividers to nothing
        UIView *yourView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 30)];
        UIGraphicsBeginImageContext(yourView.bounds.size);
        [yourView.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        [self setDividerImage:image
          forLeftSegmentState:UIControlStateNormal
            rightSegmentState:UIControlStateNormal
                   barMetrics:UIBarMetricsDefault];
        [self setDividerImage:image
          forLeftSegmentState:UIControlStateSelected
            rightSegmentState:UIControlStateNormal
                   barMetrics:UIBarMetricsDefault];
        [self setDividerImage:image
          forLeftSegmentState:UIControlStateNormal
            rightSegmentState:UIControlStateSelected
                   barMetrics:UIBarMetricsDefault];

        yourView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
        yourView.backgroundColor = bgNotSelected;
        UIView *barView = [[UIView alloc] initWithFrame:CGRectMake(0, yourView.frame.size.height - 3, 40, 3)];
        barView.backgroundColor = barNotSelected;
        [yourView addSubview:barView];
        UIGraphicsBeginImageContext(yourView.bounds.size);
        [yourView.layer renderInContext:UIGraphicsGetCurrentContext()];
        image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        UIImage *normalBackgroundImage = image;
        [self setBackgroundImage:normalBackgroundImage
                        forState:UIControlStateNormal
                      barMetrics:UIBarMetricsDefault];

        yourView.backgroundColor = bgSelected;
        barView = [[UIView alloc] initWithFrame:CGRectMake(0, yourView.frame.size.height - 3, 40, 3)];
        barView.backgroundColor = barSelected;
        [yourView addSubview:barView];
        UIGraphicsBeginImageContext(yourView.bounds.size);
        [yourView.layer renderInContext:UIGraphicsGetCurrentContext()];
        image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        UIImage *selectedBackgroundImage = image;
        [self setBackgroundImage:selectedBackgroundImage
                        forState:UIControlStateSelected
                      barMetrics:UIBarMetricsDefault];
    }
    return self;
}

-(void)setBackgroundColor:(UIColor *)color forState:(UIControlState)state
{
    UIColor *barColor;
    if (state == UIControlStateSelected)
    {
        bgSelected = color;
        barColor = barSelected;
    }
    else
    {
        bgNotSelected = color;
        barColor = barNotSelected;
    }
    UIView *yourView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
    yourView.backgroundColor = color;
    UIView *barView = [[UIView alloc] initWithFrame:CGRectMake(0, yourView.frame.size.height - 3, 40, 3)];
    barView.backgroundColor = barColor;
    [yourView addSubview:barView];
    UIGraphicsBeginImageContext(yourView.bounds.size);
    [yourView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    [self setBackgroundImage:image
                    forState:state
                  barMetrics:UIBarMetricsDefault];
}

-(void)setBarColor:(UIColor *)color forState:(UIControlState)state
{
    UIColor *bgColor;
    if (state == UIControlStateSelected)
    {
        barSelected = color;
        bgColor = bgSelected;
    }
    else
    {
        barNotSelected = color;
        bgColor = bgNotSelected;
    }
    UIView *yourView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
    yourView.backgroundColor = bgColor;
    UIView *barView = [[UIView alloc] initWithFrame:CGRectMake(0, yourView.frame.size.height - 3, 40, 3)];
    barView.backgroundColor = color;
    [yourView addSubview:barView];
    UIGraphicsBeginImageContext(yourView.bounds.size);
    [yourView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    [self setBackgroundImage:image
                    forState:state
                  barMetrics:UIBarMetricsDefault];
}

-(void)setTextAttributes:(NSDictionary *)attrs forState:(UIControlState) state
{
    if (state == UIControlStateSelected)
    {
        //in case user mistakes the states
        state = UIControlStateHighlighted;
    }
    [self setTitleTextAttributes:attrs forState:state];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end

The full error message:
* thread #1: tid = 0x1f03, 0x0134609b libobjc.A.dylib`objc_msgSend + 15, stop reason =     EXC_BAD_ACCESS (code=2, address=0xb0000008)
frame #0: 0x0134609b libobjc.A.dylib`objc_msgSend + 15
frame #1: 0x0059bcd5 UIKit`-[UISegmentedControl _setBackgroundImage:forState:barMetrics:] + 148
frame #2: 0x0059bd69 UIKit`-[UISegmentedControl setBackgroundImage:forState:barMetrics:] + 73
frame #3: 0x0004f9f5 Services`-[FancySegmentedControl setBarColor:forState:](self=0x0ea5d740, _cmd=0x000518fd, color=0x08db4630, state=0x00000004) + 1141 at FancySegmentedControl.m:135
frame #4: 0x0000538c Services`-[ServicesViewController fixSearchBar](self=0x07f791a0, _cmd=0x0005170b) + 1132 at ServicesViewController.m:174
frame #5: 0x00003f38 Services`-[ServicesViewController viewDidLoad](self=0x07f791a0, _cmd=0x017fe1dd) + 616 at ServicesViewController.m:49
frame #6: 0x0056964e UIKit`-[UIViewController view] + 184
frame #7: 0x00569941 UIKit`-[UIViewController contentScrollView] + 36
frame #8: 0x0057b47d UIKit`-[UINavigationController _computeAndApplyScrollContentInsetDeltaForViewController:] + 36
frame #9: 0x0057b66f UIKit`-[UINavigationController _layoutViewController:] + 43
frame #10: 0x0057b93b UIKit`-[UINavigationController _startTransition:fromViewController:toViewController:] + 303
frame #11: 0x0057c3df UIKit`-[UINavigationController _startDeferredTransitionIfNeeded] + 288
frame #12: 0x0057c561 UIKit`-[UINavigationController __viewWillLayoutSubviews] + 33
frame #13: 0x006984ca UIKit`-[UILayoutContainerView layoutSubviews] + 222
frame #14: 0x004e2301 UIKit`-[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 145
frame #15: 0x019b8e72 CoreFoundation`-[NSObject performSelector:withObject:] + 66
frame #16: 0x003c292d QuartzCore`-[CALayer layoutSublayers] + 266
frame #17: 0x003cc827 QuartzCore`CA::Layer::layout_if_needed(CA::Transaction*) + 231
frame #18: 0x00352fa7 QuartzCore`CA::Context::commit_transaction(CA::Transaction*) + 377
frame #19: 0x00354ea6 QuartzCore`CA::Transaction::commit() + 374
frame #20: 0x00354580 QuartzCore`CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 80
frame #21: 0x0198b9ce CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 30
frame #22: 0x01922670 CoreFoundation`__CFRunLoopDoObservers + 384
frame #23: 0x018ee4f6 CoreFoundation`__CFRunLoopRun + 1174
frame #24: 0x018eddb4 CoreFoundation`CFRunLoopRunSpecific + 212
frame #25: 0x018edccb CoreFoundation`CFRunLoopRunInMode + 123
frame #26: 0x01b49879 GraphicsServices`GSEventRunModal + 207
frame #27: 0x01b4993e GraphicsServices`GSEventRun + 114
frame #28: 0x004a3a9b UIKit`UIApplicationMain + 1175
frame #29: 0x000036d0 Services`main(argc=1, argv=0xbffff214) + 80 at main.m:16
frame #30: 0x000025e5 Services`start + 53

Comment: Why is `FancySegmentedControl` working with pointers to `UIControlState` variables?
Comment: Looks like you have your own custom class for the segmented control. Can you include its code?
Comment: I do not think the code has anything to do with it, since it does not die on any other vc.
Comment: If you must know, the code is hosted on gitHub: https://github.com/mkeehan/MySegmentedControl
Comment: What is the crash message?
Comment: So it can change the background based off of the control state of the segment? It seems pretty standard for subclassing the uisegmented control. What else could I use?
Comment: Well for that you wouldn't want to pass a pointer around then. Pass the state itself. Not sure if that's your problem but if you ran zombies and didn't catch sending to a deallocated instance that does point to some other invalid address.
Comment: So wait, how would I pass the state itself? You should just post an answer, yours is better than anything else anybody has answered.
Answer: UIControlState is an enum. You are passing a pointer to a value that is supposed to be a UIControlState, but actually pointer's value is used directly, not even dereferenced.
Remove the pointer from the UIControlState parameter in the signature and you will be OK.
-(void)setBarColor:(UIColor *)color forState:(UIControlState)state

This will then meet the UISegmentedControl's method signature:
-(void)setBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics

Comment: Yes, cleanup is a good idea. It can miraculously solve issues all the time.
Comment: I saw in the stack trace that it was calling initWithObjects rather than initWithItems, so I made a dummy function called initWithObjects that called initWithItems and everything miraculously worked. No idea why that happened though, the code clearly said [fancy initWithItems:providers]; Just glad it works.
Comment: I edited the code in the way that I thought was correct, the error is still happening. Did I edit correctly?
Comment: Is it the same error? Or it happens somewhere else? This change should solve at least the original issue.
Comment: I cleaned the build (which I've found to be a very good fixer after I repair memory bugs), let me see if it still happens. I'll just accept your answer if it doesn't show up in the next hour or so. Thank you!
Comment: Hey, now it is crashing on the initWithItems function. Can you give me a hint about why that happens? Same code as before.
Comment: Without crash log it's a little hard. I had crash issues with the array initialization the way you do. Since then I have always used the modern obj-c syntax and those kind of problems disappeared. If you submit the log it will be a little easier.
Comment: I didn't have a chance to reply yesterday. Can you tell what was the issue? I'm really curious about it.
Answer: Have you tried running this with zombies turned on?
EXC_BAD_ACCESS mostly occurs because you are trying to do something with memory that has already been freed and the stuff that's there is junk now.
It looks like in your code:
frame #1: 0x0059bcd5 UIKit`-[UISegmentedControl _setBackgroundImage:forState:barMetrics:] + 148

Is the last thing that we see before you have this error.
Put a breakpoint in here and check that the params are real, etc.  Or
The reason you only see this crash sometimes probably has to do with memory usage. Other stuff going in in your code, the simulator, the device, etc is causing memory to cleaned up and re-used. For whatever reason, deallocators are not getting called most of the time, and so the pointer you have to that block of memory remains valid even though according to the semantics from your program it doesn't necessarily have to be. In other more stressed situations, it's probably that memory is being reclaimed, deallocators are run, and now the system knows that that memory has been returned to the system's allocation heap and so it throws an exception when you try to fiddle with it.
Comment: I ran it with NSZombies and it happened exactly the same way with no change. Besides, I'm using ARC to manage memory.


How to test for significant differences in means across  four within subject conditions where dependent variable is a proportion?

Question: I have a dataset with four within-subject conditions. Participants gave binary answers to 8 questions in each condition, and these were averaged to form a proportion for each condition. I would like to compare the mean proportions of people choosing a particular answer between conditions. For example 80% chose a particular answer in the first condition, 60% in the second 40% in the third 20% in the fourth.
Here's a graph of the results:
Mean probability of guessing RED drops as no. GREEN increases. I want to see whether the drop is significant.

How can I somehow summarize whether this drop is significant?
Comment: @Daniel Okay. I've tried to update your question to make this clearer; feel free to make it even clearer; at first I thought you were comparing individual items; It's a very different question if you are comparing mean proportions.
Comment: It sounds like you have one sample of people who answered a question 4 times in different circumstances. Why then you mentioned "unequal sample size"? What did you mean?
Comment: @Yes I was trying to mention something one step further so I edited it out. Yes basically its one sample with 4 within subject conidtions. I would like to see if participants chose a particular answer significantly less in each 4 conditions.
Comment: So in each condition, each participant completed 8 binary questions and then you use those 8 questions to form a proportion for each participant, and then you are comparing mean proportions across conditions of the design?
Comment: @Jeromy Anglim yes
Answer: Here's a simple rule: when you can compute a proportion within an individual, don't. Dixon (2008) and Jaeger (2008) both demonstrate that this can lead to erroneous inferences. The proper approach to analysis of repeated binary data is to use an inferential approach that treats the data as binary. Here is code (for R) to grab the latest version of the ez package and compute likelihood ratios for your design's effects (and, by the way, treating your numeric variables as continuous but possibly non-linear via gam, thereby enhancing power):
#install CRAN ez
install.packages('ez')
library(ez)

#get ready to retrieve Dev version of ez
install.packages('RCurl')

#retrieve ezDev
source('https://raw.github.com/mike-lawrence/ez/master/R/ezDev.R')

#load Dev version of ez's functions into memory
ezDev()

#now run the model
my_mix = ezMixed(
    data = my_data
    , dv = .(choice_is_red)
    , random = .(participant)
    , fixed = .(num_green,num_red,message)
)
print(my_mix$summary)
#In the summary, the bits column represents the computed evidence
#associated with each effect, on the log-base-2 (aka "bits") scale.
#The absolute value represents the strength of evidence while the sign
#represents whether the effect (+) or its null (-) is supported.

#visualize the 3-way with CIs that eliminate between-participants variance
preds = ezPredict(
    fit = my_mix$models$'num_green:num_red:message'$unrestricted
)
p = ezPlot2(
    predictions = preds
    , x = .(num_green)
    , split = .(num_red)
    , row = .(message)
    , x_lab = 'No. green'
    , split_lab = 'No. red'
    , y_lab = 'Likelihood of choosing red (log-odds)'
)
print(p$plot)

This code assumes that your data is stored in the object my_data, which has the following structure (order of columns is unimportant, just that they're all there and that it is the raw question-by-question info for each participant):
participant question num_red num_green message choice_is_red
sub1        1        3       2         red     0
sub1        2        4       4         red     1
sub1        3        1       3         blue    0
...
sub2        1        2       1         blue    0
sub2        2        1       2         red     1
...

Comment: thanks! So to get this clear: dv = number of participants choosing RED for the particular question (but how do I do this for all 8 question?), random = subject id, fixed= number of green (1,2,3,4) number of red (5,7,9), message received (RED or BLUE). The data looks the following: participants answer 8 questions, 2 questions each for the 4 conditions. So no.GREEN = 1 for question 1 and 2, no.GREEN=2 for question 3,4, etc. Here I want to see whether people choose RED significantly less as no.GREEN increases. THen a second question would be whether there's a difference between no.RED 5,7,9
Comment: See the updated answer that describes the expected data format.
Comment: I've updated the datafile: http://dl.dropbox.com/u/22681355/datafile2.xls
Basically what differs is that num_red can only be 5, 7 and 9 and participants gave responses as RED / BLUE but in the graph I've made it mean choice from 0(blue) to 1 (red). How does this modify the code above?
Comment: also the command: #retrieve ezDev
source('https://raw.github.com/mike-lawrence/ez/master/R/ezDev.R')
 doesn't seem to work: Error in file(file, "r", encoding = encoding) :
  cannot open the connection
In addition: Warning message:
In file(file, "r", encoding = encoding)
Comment: You have to run the source() command while connected to the internet.
Comment: I was connected to the internet since I managed to install the package :)
Answer: [Note: The following reply pertains to older drafting of the question, "How to test for significant differences in proportions across four within subject conditions?" Later the question was cleared up in that the proportions are actually averaged across various variables.]
You might use McNemar's test which is a repeated-measures comparison of proportions. Classic form of the test is for binary response and is therefore suits you. The test is pairwise comparison: only two conditions at a time. The 2x2 frequency table (Yes, No one condition vs Yes, No another condition) is formed and the Ho that the table is symmetric about the diagonal is tested.
When variables are dichotomous (like yours) McNemar test is equivalent to Sign test so you could apply that either.
Check also Cochran Q test as an extension of McNemar's test from pairwise to omnibus comparison


Browser ends PHP infinite loops and then prints the data

Question: I am trying to capture live feeds from a card reader and printing it using PHP.
<?php
    $i=0;
    for(;;)
    {
        $subdata=file_get_contents("/home/openflow/subscribedata.txt");
        $subdata2=file_get_contents("/home/openflow/subscribedatatemp.txt");

        if($subdata!=$subdata2)
        {
            copy("/home/openflow/subscribedatatemp.txt","/home/openflow/subscribedata.txt");
            $sub=file_get_contents("/home/openflow/subscribedata.txt");
            $i++;
            echo "\n". $i."--".$sub;
        }
    }
?>

I am using the for loop as an infinite loop. Whenever there is new data, my card reader script writes it into the subscribedatatemp.txt file and the above script checks for a difference between subscribedatatemp.txt (the latest entry) and subscribedata.txt (the previous entry). If there's a difference, it should copy the latest onto the previous and echo the latest data.
The problem is when I am executing the PHP code above, it doesn't show anything for a while and after sometime the browser stops loading and displays all the data that it got in the loading time.
This indicates that the loop execution is getting stopped and all the data is being printed after the end of the while loop, right? How can I correct this?
Comment: ``. Also you should try to avoid running "tight" loops that don't give other processes the chance to get some CPU time. Introduce a `sleep(50)` or `sleep(100)` before the end of the for-loop.
Comment: Your script is probably timing out, try adding `set_time_limit(0)` to the top
Comment: where should i add that? I am new to php and am not sure where to add the line. can you please tell me where to add it?
Answer: At the top of your code, add this line:
set_time_limit(0);

So your whole code looks like this:
<?php
set_time_limit(0);
$i=0;
for(;;)
{
$subdata=file_get_contents("/home/openflow/subscribedata.txt");
$subdata2=file_get_contents("/home/openflow/subscribedatatemp.txt");

if($subdata!=$subdata2)
{
copy("/home/openflow/subscribedatatemp.txt","/home/openflow/subscribedata.txt");
$sub=file_get_contents("/home/openflow/subscribedata.txt");
$i++;
echo "\n". $i."--".$sub;
}
}
?>

Read more on set_time_limit() here.
Also, check if max_execution_time in your php.ini file is not set.
Comment: Make sure you've disabled output buffering (ini setting `output_buffering`) -- see more http://php.net/manual/en/book.outcontrol.php
Comment: i tried the same thing and the data wouldn't be echoed until the execution ends.. it shouldn't be that way right?

Whenever there's a chenge, there should be an echo.. @imulsion
Answer: Use set_time_limit() to prevent your script from timing out by passing in a 0 at the beginning of the script to make it an infinite wait.
You also want to add a sleep() to your loop so it doesn't consume all of your CPU cycles.
Finally you will need to add a flush() at the end of each loop to empty the buffer and send it to the client.
<?php
// set an infinite timeout
set_time_limit(0);
// create an infinite loop
while (true) {
    // do your logic here
    $subdata=file_get_contents("/home/openflow/subscribedata.txt");
    $subdata2=file_get_contents("/home/openflow/subscribedatatemp.txt");
    // .... etc.

    // flush buffer to the client
    flush();

    // go to sleep to give the CPU a break
    sleep(100);
}
?>

Answer: If I'm understanding you correctly, you're trying to display output after each loop (instead of waiting for the whole script to end), so to echo(flush) each loop, you'll need to add flush() at the end of the loop.
Also we'll add set_time_limit(0) before the loop, so our script takes it time to execute.
<?php
set_time_limit(0);
ob_end_flush();

$i=0;
for(;;)
{
$subdata=file_get_contents("/home/openflow/subscribedata.txt");
$subdata2=file_get_contents("/home/openflow/subscribedatatemp.txt");

if($subdata!=$subdata2)
{
copy("/home/openflow/subscribedatatemp.txt","/home/openflow/subscribedata.txt");
$sub=file_get_contents("/home/openflow/subscribedata.txt");
$i++;
echo "\n". $i."--".$sub;
/*flush()*/
}

}
ob_start();
?>

Comment: nope.. that's not even showing any kind of data.. adding flush isn't getting me any data.. and if i remove time limit and run the script too... the output i got previously isn't displayed.. am just getting a blank screen
Comment: i am getting the same blank screen again after a while :|
Answer: use flush and sleep functions at the end of your loop...
but it would be better to use ajax call for this..


How to determine the complement when the predicate is not a simple inclusion

Question: I'm given sets defined using set-builder notation and I'm not entirely sure how to take the complement of the set. I ask a general question in Part I, then a related question in a more complicated case that is relevant to the proof I'm trying to construct in Part II.
Part I
I know for set defined in set-builder notation where the predicate is simply an inclusion of the set elements in another set, like
\begin{equation}
X = \{ x \in U : x \in B \cup C \}
\end{equation}
then the complement is
\begin{align}
X^c &= \{ x \in U : x \in B \cup C \}^c \\
    &= \{ x \in U : x \notin B \cup C \} & \text{(this is the definition I've seen)} \\
    &= \{ x \in U : \neg(x \in B \cup C) \}.
\end{align}
But can I use the negation of the predicate in general to derive the set-builder form of the complement?
For example, let
\begin{equation} A = \{ x \in U : f(x) \in B \hspace{2pt} \wedge \hspace{2pt} g(x) \in C \},
\end{equation}
then would the complement simply be
\begin{align}
A^c &= \{ x \in U : \neg(f(x) \in B \hspace{2pt} \wedge \hspace{2pt} g(x) \in C) \} \\
&= \{ x \in U : f(x) \in B^c \hspace{2pt} \vee \hspace{2pt} g(x) \in C^c \}?
\end{align}
Part II
In a more complicated case, if I'm given the following definitions for the inverse of the mapping $f : U \rightarrow V$
\begin{equation}
f^{-1}(X) = \{ f^{-1}(F_v) : F_v \in X \}, \hspace{10pt} X \subseteq 2^{V}
\end{equation}
where
\begin{equation}
f^{-1}(F_v) = \{ x \in U : f(x) \in F_v \}, \hspace{10pt} F_v \in 2^V.
\end{equation}
Then given some specific $A \in f^{-1}(X)$ where $X \subseteq 2^V$, what would the set builder form of $A^c$ look like?
I was thinking that I could say, from the definition of $f^{-1}(X)$, that $A$ could be expressed in set-builder notation as follows.
Because $A \in f^{-1}(X)$ there must be some $F_v \in X$ such that
\begin{align}
A &= f^{-1}(F_v) \\
  &= \{ x \in U : f(x) \in F_v \}.
\end{align}
Using the same $F_v$, if my assumption about how to take the complement of a set in set-builder notation is correct, then I could then write $A^c$ as
\begin{align}
A^c &= (f^{-1}(F_v))^c \\
    &= \{ x \in U : f(x) \in F_v \}^c \\
    &= \{ x \in U : \neg(f(x) \in F_v) \} \\
    &= \{ x \in U : f(x) \in F_v^c \} \\
    &= f^{-1}(F_v^c).
\end{align}
Is this correct?
Answer: For the first part, you are correct. If I define some subset $A$ of a fixed "universal" set $U$ by
$$A:=\{x\in U:\phi(x)\}$$
where $\phi$ is some set theory formula, then
$$A^{\mathsf{c}}:=U\setminus A=\{x\in U:\neg\phi(x)\}.$$
For the second part, it seems your question boils down to whether the complement of pre-image equals the pre-image of the complement, which it does!
Proposition
Let $ X $ and $ Y $ be sets.
Let $ f:X\to Y $.
For each $ B\in\mathscr{P}\left(Y\right) $, $ f^{-1}\left(Y\setminus B\right)=X\setminus f^{-1}\left(B\right) $.
Proof.
Let $ B\in\mathscr{P}\left(Y\right)$ be arbitrary.
\begin{align*}
f^{-1}\left(Y\setminus B\right)&=\left\{z\in X:f\left(z\right)\in\left(Y\setminus B\right)\right\}\\
&=\left\{z\in X:f\left(z\right)\in \left\{y\in Y:y\notin B\right\}\right\}\\
&=\left\{z\in X:f\left(z\right)\notin B\right\}\\
&=\left\{z\in X:z\notin f^{-1}\left(B\right)\right\}\\
&=X\setminus f^{-1}\left(B\right).
\end{align*}
Comment: Very interesting thank you Alberto. Just a quick question In your proof going from line 3 to line 4. This is based on the observation that if $f(z) \notin B$ then, from the definition of $f^{-1}(B)$ we know that $z \notin f^{-1}(B)$ right?
Comment: That's right. Line (3) is a subset of Line (4) because of what you mentioned. But also mentally justify Line (4) is a subset of Line (3) in order to justify the equality.


A technical detail in Fary Milnor Theorem

Question: I'm learning the Fary-Milnor theorem. At the end of the proof, I have a technical problem which is :
 that a closed curve $l$ in $R^{3}$ whose z-coordinate has absolute maximum $M$ and absolute minimum $m$ and the cross section of $(x,y,z_{0})\cap l$ ,$z_{0}\in (m,M)$ contains exactly two points, prove that this curve $l$ is unknotted.

We have to construct a homotopy between this curve and a circle and at every moment of homotopy the corresponding curve is also homotopic with a circle. I want to find a neat way.
Comment: Details for *what*? Do you see how to prove that you get just two points on the curve for $z$ values between $m$ and $M$? Do you see why you fill in something homeomorphic to a disk if so? And can you draw a tiny circle in that disk?
Comment: The usual definition of unknotted is that you can fill in a (topological) disk. That's what your picture shows (although you still have to prove it). Once you have a disk filled in, you can easily isotope your curve to a small circle in the disk.
Comment: @TedShifrin  Can you provide some details? Thank you in advance.
Answer: As it was explained by Ted Shifrin, the knot is trivial since one can fill in a disk; this disc wept by horizontal chords.
If you want a more formal proof, then you need to choose a definition of knot and trival knot.
One possibility is to define it as a 3D-polygon.
With this definition, a formal proof is given here; see Proposition 1.1.


Bayes graph model parameter dependencies problem with prior density

Question: Suppose I have a graph model

with underlying density (denote $f(\theta_1|\theta_0):=f(\theta_1)$)
$$f(\theta|x)\propto \prod_{i=1}^k f(x_i|\theta_{1:i})f(\theta_i|\theta_{1:i-1}). $$
Suppose markov property such that $x_i$ does not depend on $\theta_{1:i-1}$ if I know $\theta_i$ and $\theta_i$ does not depend on $\theta_{1:i-2}$ if I know $\theta_{i-1}$. Then model can be described by
$$f(\theta|x)\propto \prod_{i=1}^k f(x_i|\theta_{i})f(\theta_i|\theta_{i-1}) .$$
I know densities $f(x_i|\theta_i)$ and $f(\theta_i|\theta_{i-1})$, but I would like to enlist into this model that I know also $f(\theta_i)\;\forall i\in\{1,\dotsc, k\}$. I have prior information about each $\theta$ that I would like to add into model, but still can't find a way how to construct such a model. Does anybody know how to deal with that?
Comment: But you can already calculate $f(\theta_i)$
Answer: Either $f(\theta_i)$ (which should be denoted $f_i$ to avoid confusing notations) is the marginal of
$$\prod_{i=1}^k f(\theta_i|\theta_{i-1})\tag{1}$$
and in this case there is no clear interest in considering it.
Or $f_i(\theta_i)$ is not the marginal of (1) and in this case the model is incoherent from a probabilistic perspective.
Comment: The problem is that I have prior information about each $\theta_i$ but I also want to model that parameters $\theta_i$ and $\theta_{i+1}$ are quite similar. I want to say that for example $\theta_{i+1}|\theta_i\sim\mathcal{N}(\theta_{i},\sigma)$, but also$\theta_i\sim\text{some distribution independent of }\theta_{i-1}$. How to enlist this infromation into a model?
Comment: In this case you could build a copula that preserves the $f_i$'s as marginal and leaves open the correlation between the $\theta_i$'s.


Criar Novo Reporitório - Git / Bitbucket. Git (Could not read from remote repository)

Question: Estou fazendo o tutorial de Ruby on Rails e estou travando em um problema. Já fiz um repositório hello_app (cap um), e agora estou tentando fazer o toy_app (cap dois). Este é o passo a passo do tutorial:
1) Eu criei novo diretório (toy_app) e digitei:
"$ bundle install --without production" pra instalar os gems.

2) Então, precisamos inserir o toy_app no sistema de versionamento:
$ git init

$ git add -A

$ git commit -m "Initialize repository"

Feito com sucesso também!
3) Criar repositório no bitbucket. Aqui está meu problema. No capitulo um eu já criei um repositório. Agora, vim no Bitbucket, criei o novo repositório "toy_app" (não preciso adicionar a "SSH Key", ne?). O Bitbucket orienta que seja digitado:
$ cd toy_app

$ git remote add origin firstname.lastname@example.com:MoisesHotmail/toy_app.git

$ git push -u origin --all

$ git push -u origin --tags

Mas quando digitei o segundo comando, apareceu a seguinte mensagem:

conq: repository does not exist. fatal: Could not read from remote
  repository. Please make sure you have the correct access rights and
  the repository exists.

O que eu faço? Não consigo seguir a diante. Podem me ajudar?
Answer: Acho que devia ser algum bug, desses que acontecem sem razão. Dei "$ git init" e resolveu. Fiz os comandos de novo e funcionou.
Obrigado pessoal!
Answer: Você pode especificar o username que o SSH deve enviar para o repositório remoto como parte da sua url. Coloque o username, seguido por um @, antes do hostname do repositório:
git remote set-url website abc@***.com:path/to/repo


Por quê obtenho resultados diferentes para os mesmos valores enviados à uma função em PHP?

Question: Preciso transformar HORA em DECIMAL e depois fazer a operação contrária.
Criei as funções conforme mostro abaixo, mas o resultado não foi eficiente por que, dependendo da origem do valor, o resultado é diferente, mesmo sendo o mesmo Type.
Segue o Código:
<?php
// Nutro as variáveis com o mesmo valor e o mesmo tipo de Type
// Mas uma de forma direta e outra via uma function.
$A = 1.01694444444; // Esta dá o retorno errado da function Func_1
$B = Func_2('01:01:01'); // Esta dá o retorno correto da function Func_1

echo $A . '
' . $B;

echo "

";

// Mas o resultado dos cálculos da function abaixo é diferente
echo Func_1($A) . '
' . Func_1($B);

function Func_2($time){
   $hms = explode(":", $time);
   return ($hms[0] + ($hms[1]/60) + ($hms[2]/3600));
}

function Func_1($dec){
   $seconds = ($dec * 3600);
   $hours = floor($dec);
   $seconds -= $hours * 3600;
   $minutes = floor($seconds / 60);
   $seconds -= $minutes * 60;
   return lz($hours).":".lz($minutes).":".lz($seconds);
}

function lz($num){
   return (strlen($num) < 2) ? "0{$num}" : $num;
}
?>

Já procurei em todo lugar, mas não sei como resolver isso.
Segue um LINK do exemplo acima: https://puffgestor.com.br/problema.php
Comment: @JetroBernardo só mudei a linha 20 https://ideone.com/d2dkA1 - teste com valores diversos.
Comment: Deu um `var_dump` em cada passo para ver? Tentou forçar o tipo da variável? Pelo visto é só arredondamento/precisão.
Comment: Basicamente o problema é estar trabalhando com ponto flutuante. Vai precisar de um `round( $seconds )` pra compensar. Se precisa de exatidão, não deveria estar trabalhando com float
Comment: Já tentei de tudo. Não faço idéia do que está acontecendo.
Se eu chamar a função assim:
$A = 1.01694444444; Func_1(''.$A..'); Colocando aspas simples, funciona. Mas da mesma forma, não funciona se o valor vier da base de dados.
Comment: Estava fazendo isso @Bacco: `$seconds = round($seconds);`
Comment: @rbz exato, é como "resolver". Mas enquanto o Jetro estiver usando essa escala, é só um paliativo. Melhor seria trabalhar com valor em segundos em inteiros, em vez de horas.
Comment: @Bacco, já tentei. Não posso arredondar por que mudaria os segundos na reconversão para HHMMSS.
Comment: @Bacco, mas se fizer no final como na minha resposta, ainda iria atrapalhar? Acho que não enxerguei o problema da escala...
Comment: @Bacco FUNCIONOU !!! Obrigado, amigo. Eu havia tentado arredondar na linha 25, no retorno da function lz do seconds, mas não funfou. Muito obrigado, Fera.
Comment: Veja aqui um teste mais extenso para avaliar: https://ideone.com/RM1fTK
Comment: Na linha 25 não adianta fazer o round porque você ainda está usando o `$second` por conta do `-=`, assim você está subtraindo o flutuante do outro arredondado.
Comment: @rbz exatamente. Obrigado, amigo. Pela ajuda.
Answer: Conforme eu já havia postado nos comentários, é um problema de arredondamento causado pelo uso do float.
Sugiro alteração desta maneira:
function Func_1($dec){
   $seconds = round($dec * 3600); // <---- acrescentado o round
   $hours = floor($dec);
   $seconds -= $hours * 3600;
   $minutes = floor($seconds / 60);
   $seconds -= $minutes * 60;
   return lz($hours).":".lz($minutes).":".lz($seconds);
}

Veja funcionando no IDEONE.
Usando o operador de resto de divisão (%) e a função de formatação sprintf dá para simplificar um pouco, e eliminar a função lz completamente:
function Func_1($dec){
   $s       = round($dec*3600);
   $hours   = floor($dec);
   $minutes = floor(($s%3600)/60);
   $seconds = $s%60;
   return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
}

function Func_2($time){
   $hms = explode(":", $time);
   return $hms[0] + $hms[1]/60 + $hms[2]/3600;
}

Veja funcionando no IDEONE.
Aqui tem um pouco de teoria que pode ajudar no entendimento:

Qual a forma correta de usar os tipos float, double e decimal?
Answer: No método function Func_2() você apenas trata inteiros.
No método Func_1() você está fazendo cálculos com um valor flutuante (float, double, real).

Uma opção de solução é arredondas as decimais dos segundos:
$seconds = round($seconds);

function Func_1($dec){
   $seconds = ($dec * 3600);
   $hours = floor($dec);
   $seconds -= $hours * 3600;
   $minutes = floor($seconds / 60);
   $seconds -= $minutes * 60;
   $seconds = round($seconds);
   return lz($hours).":".lz($minutes).":".lz($seconds);
}

Adicionado no valor de $seconds já com todos os cálculos para evitar erro anterior.

Caso não dê certo, mostre a falha para tratarmos!


How do I make arrays interact with each other?

Question: I'm having trouble with a school assignment:

Write a program to create two arrays namely asciiArray and
  decimalArray of 52  elements each. In the asciiArray, store letters of
  the English alphabet; both lower and  upper case letters. In the
  decimalArray, store the corresponding decimal values of  each of the
  letters in the specific position in the asciiArray. For example,  If
  asciiArray[0] holds 'A' then decimalArray[0] will hold the value 65.
  Pass these arrays to a method displayDecValue. Inside the method,
  prompt the user  to enter any of the letters of the English alphabet
  and display the corresponding  decimal value.

I have some of the coding down, but I do not know how to make the arrays interact with each other and return the value. Sorry if this is simple; I have never done Java before.  We also can't use anything advanced to write the code (it's beginner's Java).
import java.util.Scanner;

public class ParallelArrays {
    public static void main (String [] args) {
        char[] asciiArray = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
                              'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
                              'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
                              'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
                              'W', 'X', 'Y', 'Z' };
        int[] decimalArray = {97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,
                              114,115,116,117,118,119,120,121,122,65,66,67,68,69,70,71,72,73,74,
                              75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90};
        displayDecValue(asciiArray, decimalArray);
    }

    public static void displayDecValue(char [ ] ascii, int [ ] dec) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter a letter (a-z or A-Z): ");

        ascii = input.next().charAt(0);

        dec[0] = (int)ascii[0];

        System.out.printf("Decimal value of %c is: " + dec[0], ascii);
    }
}

Comment: You won't be making the arrays interact with each other, you'll instead write some code that interacts with both of the arrays in a consistent and expected way.
Comment: What you've got to do is search the ascii array for a match, then print the corresponding dec array value.  This implies a loop.  And note that you should not be assigning anything TO either ascii or dec inside your displayDecValue method.
Comment: (Can't believe that anyone actually upvoted this question.)
Comment: I know this is an assignment and you have to follow it, but realistically, you would never do this. With characters like this, you can probably get away with some sort of casting. For more complex data types, you would use a `Map` of some kind.
Comment: Arrays are purely passive -- they don't "do" anything.
Comment: First figure out how to search "ascii" for a match to the input character (which SHOULD NOT be assigned to "ascii", but to a temporary `char` variable).  (And if you don't know what a "temporary" or "local" variable is, pay better attention in class next time!)
Comment: assigned char value to hold user input, figuring out loop now
Answer: Following are things which you should wonder
1) You are storing the input from the user into array variable ascii. What would happen here?
2) You are reassigning predefined dec array at index position 0, with ascii[0]. What does this mean?
3) How would you search for the char in the ascii array(Hint : loop) and match it with dec array?
4) Is the print statement following C or Java syntax?
Then you will be able to fix the code easily.
Answer: You no need to manually feed decimal array values. you can do something like below.
if we convert or typecast char to int we will get decimal value of that character.
eg
      int output= (int)'a';// here output is 97 that equivalent to decimal value of character 'a'.
    int[] decimalArray = new int[asciiArray.length];
    for (int i = 0; i < asciiArray.length; i++) {
        decimalArray[i] = (int)asciiArray[i];
    }

the complete example is below.
import java.util.Scanner;

public class ParallelArrays {
    public static void main(String[] args) {
        char[] asciiArray = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
                'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
                'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
                'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                'U', 'V', 'W', 'X', 'Y', 'Z' };

        int[] decimalArray = new int[asciiArray.length];
        for (int i = 0; i < asciiArray.length; i++) {
            decimalArray[i] = (int)asciiArray[i];
        }
        displayDecValue(asciiArray, decimalArray);
    }

    public static void displayDecValue(char[] ascii, int[] dec) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter a letter (a-z or A-Z): ");

        char inputChar = input.next().charAt(0);

        for (int i = 0; i < ascii.length; i++) {

            if (inputChar == ascii[i]) {
                System.out.printf("Decimal value of '" + ascii[i] + "' is: "
                        + dec[0]);
                break;
            }

        }

    }

}


Is product of any isometries in $\mathbb{R}^n$ an isometry?

Question: I am reading the book Putnam and Beyond by R.Gelca and T.Andreescu, and there is the following problem (#118):

Let $V_1,V_2,...,V_m$ and $W_1,W_2,...,W_m$ be isometries of $\mathbb{R}^n$ ($m,n$ positive integers). Assume that for all $x$ with $||x|| \leq 1$, $||V_i x - W_i x|| \leq 1,\ i = 1,2,...,m$. Prove that:
  $$
\Big|\Big| \big(\prod_{i=1}^m V_i\big)\ x - \big(\prod_{i=1}^m W_i\big)\ x \Big|\Big| \leq m
$$
  for all $x$ with $||x|| \leq 1$.

Why the following solution is wrong (I presume that it's wrong because authors used a more sophisticated one and mine is too obvious):
We know, that isometries form a group, so $V = V_2 \cdot ... \cdot V_m$, $W = W_2 \cdot ... \cdot W_m$ are isometries too. That's why for all $x$ such that $||x|| \leq 1$ we have $||Vx|| = ||x|| \leq 1$ and $||Wx|| = ||x|| \leq 1$. But this means that vectors $Vx$ and $Wx$ satisfy the property from the task and we have $||V_1(Vx) - W_1(Wx)|| \leq 1$, which is the desired result (and even stronger).
P.S. If my argument is valid, then what condition should be added to the task so it is not valid anymore?
Comment: If $m\ge 3$, let all $V_i$ be the identity, let all $W_i$ be the same rotation by a $\pi/m$. Then $\|V_ix-W_ix\|\le 1$ for all $\|x\|1$, but the porudtc of all $W_i$ is negative identity and so $\|\prod V_i x-\prod W_ix\|=\|2x\|$ can be up to $2$.
Comment: Could it be that the isometries are not necessarily linear, i.e., $V_i(0)$ need not be $0$? -- Alos, if if they are linear isometries, you only get $\|\|\le 2$ (but that would be good enough for $m\ge 2$)
Comment: I suppose they could be non-linear, but how does it change anything? Why would we get $||...|| \leq 2$? Condition in the task says that $||V_i x - W_i x|| \leq 1$ for any $x$ s.t. $||x|| \leq 1$
Answer: You can only conclude
$$\lVert V_1(Vx) - W_1(Wx) \rVert = \lVert V_1(Vx)  - V_1(Wx) +  V_1(Wx) - W_1(Wx) \rVert \le   \lVert V_1(Vx)  - V_1(Wx) \rVert + \lVert V_1(Wx) - W_1(Wx) \rVert = \lVert Vx  - Wx \rVert + \lVert V_1(Wx) - W_1(Wx) \rVert \le\lVert Vx  - Wx \rVert + 1.$$
This reduces a product of $m$ isometries to one of $m-1$.
Comment: If all $V_i =$ identity and all $W_i = T =$ translation by some $v$ with $\lVert v \rVert = 1$, then we see that $=m$ is possible.
Comment: I just realized that the above argument only works when $\lVert Wx \rVert \le 1$ for  $\lVert x \rVert \le 1$. This holds if the isometries are linear, but in that case gimusi has observed that $\lVert Vx - Wx \rVert \le 2$ for any two isometries $V,W$ and any $x$ with  $\lVert x \rVert \le 1$. Hagen von Eitzen has shown that $=2$ can occur for $m \ge 3$. So the relevant case seems to be that isometries are arbitrary members of the Euclidean group $E(n)$.
Comment: The argument presented in the question breaks down when considering $\lVert V_1(Vx) - W_1(Wx) \rVert$. In general we have $Vx \ne Wx$, and even if they are equal one has in general $\lVert Vx \rVert > 1$ (unless the isometries are linear).
Answer: I agree with your observations but then we should conclude that
$$\|Vx-Wx\|\le \|Vx\|+\|Wx\|\le 2$$


What's the advantage of having requirements point directly to git repository rather than PyPi?

Question: Recently I asked a Python library maintainer if he could upload a new tagged version of his library to PyPI (https://pypi.org/).
He stated that PyPI is not so important nowadays [1].
Is is true? Do people (i.e., you) indeed tend not to use PyPI? If so, what do you use instead and why?
The requirements.txt apparently allows you to specify the git repository directly, skipping PyPI by using git+https://github.com/<repo> directly. Though I can't think of any particular advantage over using PyPI.
Are there any graphs to support the statement? Should the statement be true I would expect the amount of downloads from PyPI (per interval) would be decreasing in time. PyPI publishes this kind of data to Google BigQuery. Checked now and the number of downloads are as follows:
202009    1565855136 -- the query was run on 11th of September 2020
202008    5155068175
202007    5409386519
202006    5211181171
202005    5108756961
202004    4812648839
202003    4670947975
202002    4067963794
202001    4155726766
201912    3867376444
201911    3845881964
201910    3922992929
201909    3492788322
201908    3374679723
201907    3338326277
201906    2998812162
201905    3028973146
201904    2436032402
201903    2732697164

Obtained using this query:
SELECT
  SUBSTR(_TABLE_SUFFIX, 1, 6) AS `month`,
  COUNT(1) AS num_downloads
FROM `the-psf.pypi.downloads*`
WHERE
  _TABLE_SUFFIX BETWEEN FORMAT_DATE(
      '%Y%m01', DATE_SUB(CURRENT_DATE(), INTERVAL 18 MONTH))
  AND FORMAT_DATE('%Y%m%d', CURRENT_DATE())
GROUP BY `month`
ORDER BY `month` DESC

I am aware that this question might not have a correct answer and thus might not be following all the standards of questions asked at StackOverflow. However I can't think of better place to ask on this.
[1] https://github.com/lavr/python-emails/issues/139
Comment: I don't think that is true at all, maybe he just hasn't automated the push to pypi step..?  I don't see any reason why you wouldn't push any non-breaking changes immediately.
Comment: *In my opinion*, the maintainer's statement is not correct. Publishing well-defined versions on some version repository that just works (aka PyPI) is much simpler to communicate than hardcoding some specific source code repository.
Answer:
PyPI is not so important nowadays Is is true?

Not at all. The advantages of publishing on PyPI:

One can publish wheels at PyPI so pip install package downloads a platform-specific wheel.

PyPI is hosted at a CDN (content delivery network) so downloading from PyPI is fast.

3a. pip caches downloaded packages so it doesn't re-download packages for every virtual environment. It caches by their original URLs and the URLs for PyPI are stable.
3b. pip very badly caches cloned repositories. Usually it re-clones a-new the entire repository.
Comment: depending on the git repository, you will also download the whole git history which might not be needed for the production setup of the certain package.


How to calculate expected value of a game that doesn't need to be played to completion e.g. Blackjack and stopping when aces are gone.

Question: Consider a simple example where I have a prize behind one of two doors.
The prize is $1.90.
I will let you choose a door for $1.00.
If you choose the winning door first, you can walk away.
If you choose the losing door first, you can pay me another dollar to open the other door.
So you'll either win on the first door and walk away with \$0.90 profit, or you'll lose on the first door, pay another dollar to open the second, and walk away with a -$0.10 loss.
1/2 * \$0.90 + 1/2 * -\$0.10 = $0.40 expected value.
How can this be extrapolated to a larger number of doors and a wider variety of prizes?
For example, 10 doors with 1 prize of \$7 and 2 prizes of \$1 and the rest \$0.
Edit with image for clarification:
3 Doors with values [3, 1, 0]
In this particular case I could just stop on "3" because it's obvious that's I can't win more. But how could I somehow programmatically or mathematically determine when the best place to stop is and what the expected value of the game is when I stop there?
Answer: First, you need to specify the conditions (whether deterministic or probabilistic) that a person will stop on. IE, they'll stop as soon as they profit, or they'll stop with probability (Profit/\$1).
Then, this just becomes a probability tree. In your given example, you had two branches: 50% chance they took the door with the prize and 50% they didn't. If you expand to your 10 door version, you start with 3 branches: .1 probability of \$7, .2 probability of \$1 and .7 probability of \$0.
After each branch, depending on your stop conditions, you'll either terminate at that point, or have further branches, which will be different based on which branch you're on.
Let's say that your stop condition is that you have to have profited (deterministic) to make things simpler. Then your \$7 branch and your \$1 branch are both immediate stops, and only the \$0 branch expands. The next step branches as follows:
(1/9) chance of \$7, (2/9) chance of \$1, (6/9) chance of \$0.
You can repeat until your tree is complete with every end node being a point at which your player would stop.
Then, each end node has a probability equal to the product of every branch probability along the way.
For example, the end node of \$0 followed by \$7 would have a probability of 7/10 * 1/9 = 7/90.
Once you have a probability for each end node, you multiply by that node's value to calculate your expected value in the usual way.
Comment: Thanks. I'm trying to work through this again given what you said and I think I should have asked the question another way.

What you said makes sense and I can work it out for some stopping condition, such as having made a profit.

I'm stuck on figuring out how to do it if my stopping condition is: Stop if the value of stopping is greater than the value of continuing.

I'm going to edit my question so I can get better formatting for a visualization.
Comment: Work out the probability tree for not stopping (IE, fully open all doors). Then evaluate your stopping condition backwards from the leaves, eliminating leaves where you'd have stopped at the previous point. As you do this, it will revise your expected value for each branch, all the way back to the start. I recommend using code to do this if you're doing it for anything larger than n=3.
Comment: Makes sense. Got some working code. But my n = 12. What is that... 12! + 11! + 10!... possible nodes that I need to do calculations for? It was just too slow. Haven't been able to figure out a way to make it work.
Comment: As a shortcut, you can stop each branch when there are no doors with prizes left, since it will only get worse from there. That cuts down your cases significantly. Also, if you run this in C# with good code or MATLAB with decent code, it should compute in under a day.