one-point-compactification is a topological space

Question: Let $X$ be a local compact Hausdorff space endowed with a topology $\tau_X$ and consider $X_{\infty}=X\coprod\{\infty\}$ as a set. Let $$\tau_{X_\infty}:=\tau_X\cup \{U\subseteq X_\infty:\infty\in U\;\text{ and}\; X\setminus U\;\text{ is a compact subset of}\; X\}.$$
Claim: $\tau_{X_\infty}$ is a topology on $X_{\infty}$.
I want to prove: If $U_i\in \tau_{X_\infty}$ for $i\in I$, then $\bigcup_{i\in I} U_i\in\tau_{X_\infty} $
If $\infty\notin \bigcup_{i\in I} U_i$, it is $\bigcup_{i\in I} U_i\in \tau_X\subseteq \tau_{X_\infty}$. Now let $\infty\in \bigcup_{i\in I} U_i$ and write $\bigcup_{i\in I} U_i=( \bigcup_{i\in I,\infty\notin U_i} U_i)\cup ( \bigcup_{i\in I,\infty\in U_i} U_i)$. From the first case it is $\bigcup_{i\in I,\infty\in U_i} U_i\in \tau_{X_\infty}$, but I don't know how to continue.
Now let $U_1,U_2\in \tau_{X_\infty}$, I want to prove: $U_1\cap U_2\in \tau_{X_\infty}$. If $\infty\notin U_1$ for i=1 and i=2, it's clear. If $\infty\in U_1$, but $\infty\notin U_2$, $X\setminus U_2$ is compact in $X$ and $U_1\in \tau_{X_\infty}$. I don't know how to continue.
This is only where I'm stuck. I appreciate your help.
Answer: HINT: For the union, let $J=\{i\in I:\infty\in U_i\}$; then
$$X\setminus\bigcup_{j\in J}U_j=\bigcap_{j\in J}(X\setminus U_j)\;,$$
which is an intersection of compact subsets of $X$.
For the intersection, suppose that $\infty\in U_1\setminus U_2$. Then $\infty\notin U_1\cap U_2$, so you need to prove that $U_1\cap U_2\in\tau_X$. Let $V=U_1\setminus\{\infty\}=U_1\cap X$; clearly $U_1\cap U_2=V\cap U_2$, so you'll be done if you can show that $V\in\tau_X$. To do this, note that $X\setminus V=X_\infty\setminus U_1$, which is compact. Now use the fact that $X$ is Hausdorff.
Comment: @taglap: Whoa! The first step is fine, but in the second you've replaced the union by its complement. If you start with $$X\setminus\bigcup_{i\in I}U_i=X\setminus\left(\bigcup_{j\in J}U_j\cup\bigcup_{j\in I\setminus J}U_j\right)\;,$$ you can continue as you did. Alternatively, you could note that $\bigcup_{j\in J}U_j$ is the complement of $\bigcap_{j\in J}(X\setminus U_j)$, which, being an intersection of compact sets, is compact and hence (in a Hausdorff space) closed, so $\bigcup_{j\in J}U_j$ is open. So is $\bigcup_{j\in I\setminus J}U_j$, and hence so is their union.
Comment: @taglap: I did wonder whether it was an accidental error. Sounds like you're in business now.
Comment: thanks! If $X\in \tau_{X_\infty}$, then it is $X_\infty\setminus X=\{\infty\}$ closed in $X_\infty$. Now, why does follow that $V\in \tau_X$? Can I say that $V$ is a complement of a closed set $\{\infty\}$?
Comment: @taglap: No, $V$ isn't the complement of $\{\infty\}$ in general. But it's a member of $\tau_{X_\infty}$ that doesn't contain the point $\infty$, so it must be ... ?
Comment: ah, then $V$ must be a member of $\tau_X$. But why is $V\in \tau_{X_\infty}$?. I only know that $U_1$ is in $\tau_{X_\infty}$,
Comment: @taglap: Because it's the intersection of two members of $\tau_{X_\infty}$, $U_1$ and $X$.
Comment: but I still dont know, that the intersection of two members of $\tau_{X_\infty}$ lies in $\tau_{X_\infty}$, thats what I want to prove. Sorry, if I tax your patience.
Comment: @taglap: No, I should be apologizing: I completely forgot what we were doing! Hang on a minute and let me revise my answer slightly. Okay, have another look and see if you can finish it off now.
Comment: thank's, no problem, you help me a lot and I appreciate it! Compact subsets of Hausdorff spaces are closed. Therefore $V\setminus X$ is closed in $X$ and this means, $V$ is an open subset of $X$. Thank you very much! Now I will try the union
Comment: @taglap: You're welcome!
Comment: ok, for the union I obtain: $\bigcup_{i\in I} U_i=( \bigcup_{j\in J}U_j)\cup ( \bigcup_{j\notin J} U_j)=( \bigcap_{j\in J}X\setminus U_j)\cap ( \bigcap_{j\notin J}  X\setminus U_j)$ which is an intersection of a closed set $( \bigcap_{j\notin J}  X\setminus U_j)$ and a compact set $( \bigcap_{j\in J}  X\setminus U_j)$ and therefore compact, because $X$ is Hausdorff.
Comment: oh!! that wasn't on my purpose!! sorry^^, on my I wrote down that correctly, but thanks, you are right.
Comment: yes, you are right. thanks for all your great help!
Comment: @taglap: You're welcome!
Comment: Hi. I see that the condition that X is Hausdorff is important to show it is a topological space (I read in a book that it is a topology on $X_{\infty}$, but they don't say that (X, $\tau$) is Hausdorff. Can it be true then?)


Generalized Ramsey Numbers

Question: In "Graph Theory with Applications" by Bondy and Murty, the generalized Ramsey Numbers are defined as below.

Let $G_1,G_2,\dots,G_m$ be simple graphs. The generalised Ramsey Number $r(G_1,G_2,\dots,G_m)$ is the smallest integer $n$ such that every $m$-edge colouring $(E_1,E_2,\dots,E_m)$ of $K_n$ contains, for some $i$, a subgraph isomorphic to $G_i$ in colour $i$.

Say we have two simple graphs $G_1$ and $G_2$ such that $r(G_1,G_2)=5$. Then every possible $2$-edge coloring of $K_5$ has $G_1$ as a subgraph on color $1$ or $G_2$ as a subgraph in color $2$. Am I understanding this correctly?
If I am, then that would imply that for any $m$ simple graphs $G_1,G_2,\dots,G_m$, the following equality holds:
$$r(G_1,G_2,\dots,G_m)=\min\{r(G_i,G_i,\dots,G_i):i\in\{1,2,\dots,m\}\},$$
where there are $m$ of the $G_i$'s, correct?
Comment: Wouldn't this say that (blue=1, red=2) $r(K_3,K_2)=\min(r(K_3,K_3),r(K_2,K_2))=\min(6,2)=2$? That's not true, because an all blue $K_2$ has neither a blue triangle nor a red edge.
Answer: To your first question, yes, your understanding of the notation is correct.
To your second question, Steve Kass has pointed out in a comment that $$r(K_3,K_2)\gt\min(r(K_3,K_3),r(K_2,K_2)).$$
This example leaves open the possibility that the inequality $$r(G_1,G_2)\ge\min(r(G_1,G_1),r(G_2,G_2))$$ holds in general. This is also false. The question is discussed on pp. 43–44 of the book Examples and Counterexamples in Graph Theory by Michael Capobianco and John C. Molluzzo. It was conjectured by Frank Harary that

if $F_1,F_2$ have no isolates, then $r(F_1,F_2)\ge\min(r(F_1,F_1),r(F_2,F_2))$.

The counterexample to Harary's conjecture (attributed to Galvin) is that
$$r(P_5,K_{1,3})=5$$
while
$$r(P_5,P_5)=r(K_{1,3},K_{1,3})=6.$$
In order to refute Harary's conjecture, we need only show that $r(P_5,K_{1,3})\le5$ while $r(P_5,P_5)\gt5$ and $r(K_{1,3},K_{1,3})\gt5.$ (It's quite easy to see that $r(P_5,K_{1,3})\ge5$ and $r(K_{1,3},K_{1,3})\le6$ but we don't need this.)
To see that $r(P_5,P_5)\gt5,$ note that neither the graph $K_{1,4}$ nor its complement $\overline{K_{1,4}}=K_1+K_4$ contains a $P_5.$
To see that $r(K_{1,3},K_{1,3})\gt5,$ note that the self-complementary graph $C_5=\overline{C_5}$ contains no $K_{1,3}.$
To see that $r(P_5,K_{1,3})\le5,$ consider a graph $G$ of order $5$ whose complement $\overline G$ contains no $K_{1,3};$ we have to show that $G$ contains a $P_5.$ Since the graph $G$ has minimum degree $\delta(G)\ge2,$ it contains a cycle. We consider three cases.
If $G$ contains a $C_5,$ it clearly contains a $P_5.$
If $G$ contains a $C_4$ then, since the fifth vertex is joined to some vertex of the $C_4,$ we ckearly have a $P_5.$
Finally, suppose the longest cycle in $G$ is a $C_3.$ Let $u,v$ be the vertices off the $C_3.$ Then $u$ can't be joined to two vertices of the $C_3$ as that would make a $C_4;$ so $u$ is joined to $v$ and to one vertex of the $C_3,$ making a $P_5.$

Generalized Ramsey Numbers


Definition of Scale median

Question: Lehmann, in Theory of Point Estimation p.212 (and also on p.169), defines scale median as the solution to: $${E(X)I(X\le c)} = {E(X)I(X\ge c)}$$
given $X$ is a positive random variable, and ${E(X)}< \infty$.
However, the expression does not make sense as it ${E(X)I(X\le c)}$ and ${E(X)I(X\ge c)}$, are two random variables whose support intersect only at c. Hence a solution can not exist in general. Am I missing something here? Should it be defined as the solution to $${E(XI(X\le c))} = {E(XI(X\ge c))},$$
instead?
Comment: See this question answered here: http://math.stackexchange.com/questions/316644/scale-median-for-mre-estimators-with-absolute-difference-error-function-for-scal
Comment: @TrynnaDoStat : I did see that, but are the definitions of ${E(X)I(X\le c)}$ and ${E(X)I(X\ge c)}$ in the question not wrong? The OP there seems to use these quantities as numbers, while they are random variables.
Answer: It is interesting that in Google scholar, no results are found for "scale median". Any way, the exact text from Lehmann and Casella's book is (p. 212, 2nd edition)

3.7 Let $X$ be a positive random variable. (a) If $EX < ∞$, then the value of $c$ that minimizes $E|X/c − 1|$ is a solution to $EXI (X ≤ c) = EXI (X ≥
 c)$, which is known as a scale median.

Note carefully that there are no parentheses separating $X$ and $I (X ≤ c)$ or enclosing them. This is confusing notation alright, and uncharacteristic of the specific book where in other cases of the use of the $E$ operator, parentheses, brackets and curly brackets are used (some authors do write $EX$ instead of $E(X)$, but not here).
Taking clues from Did's answer and corrective comments in the math.SE linked thread, as well as here, it is indeed
$E\big[XI (X ≤ c)\big]$, since Did uses $E(X;X\leq c)$ which is equal to $E\big[XI (X ≤ c)\big]$, being the expected value restricted in the set $\{X\leq c\}$. The right-hand side integrals are also equal to $E\big[XI (X ≤ c)\big]$ and its counterpart, indicating just a typo from the part of the OP there.
Comment: Thanks a lot. I was a little confused, because in Lehmann and Casella's book on Page 169 (in the second edition),  they define the scale median as the expression I pasted, which is why I was a bit confused.\.
Comment: Well, that _does_ look like a mistake!

Definition of Scale median


How to add a CSS attribute to Image generated with image style

Question: Pretty much all in the title. I would like to add a CSS classes to images generated via a image style theme function, so that the output looks like :

Is there anyway to do so ?
Answer: If you are comfortable overriding theme functions in your theme's template.php you can just create a YOURTHEME_image_style() function:
http://api.drupal.org/api/drupal/modules--image--image.module/function/theme_image_style/7
Comment: Well i have to say theme function are still very blury for me right now. Would you by anychance have some link to resources that could clarify that ?
Comment: So the idea is to copy the code on the linked page into your theme's template.php file (if your theme doesn't have one, make it) then change the word "theme" in theme_image_style to the name of your theme, which might be zen_image_style or garland_image_style, etc.
Answer: Here's some code based on Ryan's answer.

Copy and paste the code from theme_image_style to your theme's template.php.
replace theme in theme_image_style with your theme's name.
add the following lines to the function
  $variables['attributes'] = array(
      'class' => 'my-class',
  );

Instead of 'my-class' I wanted to use the actual style's name, so I used $variables['style_name'] instead. Image style names are always valid css class names, so there should be no problem with this approach. The function should look like this:
function MYTHEME_image_style($variables) {
  // Determine the dimensions of the styled image.
  $dimensions = array(
    'width' => $variables['width'],
    'height' => $variables['height'],
  );

  image_style_transform_dimensions($variables['style_name'], $dimensions);

  $variables['width'] = $dimensions['width'];
  $variables['height'] = $dimensions['height'];

  $variables['attributes'] = array(
    'class' => $variables['style_name'],
  );

  // Determine the url for the styled image.
  $variables['path'] = image_style_url($variables['style_name'], $variables['path']);
  return theme('image', $variables);
}

Answer: Use preprocess function
You want that class on the actual image, adding through JS/jQuery is messy and breaks if content is ajax loaded.
function THEMENAME_preprocess_field(&$variables) {

    if($variables['element']['#field_name'] == 'field_photo'){

        foreach($variables['items'] as $key => $item){

            $variables['items'][ $key ]['#item']['attributes']['class'][] = 'img-circle';

        }

    }

}

Why I don't use theme_image_style() for this
The issue with doing this through theme_image_style() is that it overrides the output function for just one field, what if you have multiple fields in different places... too many THEME_field__field_photo__team($variables) achieving the same as the above using theme_image_style() would look like this:
// Override the field 'field_photo' on the content type 'team'
function THEMENAME_field__field_photo__team($variables) {

    // Determine the dimensions of the styled image.
    $dimensions = array(
        'width' => $variables['width'],
        'height' => $variables['height'],
    );

    image_style_transform_dimensions($variables['style_name'], $dimensions);

    $variables['width'] = $dimensions['width'];
    $variables['height'] = $dimensions['height'];

    $variables['attributes'] = array(
        'class' => $variables['img-circle'],
    );

    // Determine the URL for the styled image.
    $variables['path'] = image_style_url($variables['style_name'], $variables['path']);
    return theme('image', $variables);

}

Comment: Agreed, using a preprocessor is a good way to go here.  Since the field preprocessor can be called many times per page, what about using a node preprocessor instead?  For a field 'field_images', you can add the classes via `$variables['content']['field_images'][$key]['#item']['attributes']['class'][] = [your_css_class]`.
Comment: This helped me add a property to comply with Schema.org metadata. Thanks!
Comment: You are right perhaps calling this using a node preprocessor would be more efficient.
Answer: If the reason you want to add the class is to provide some extra css for the images, then you can circumvent this by going to an upper level in the dom tree.
Your images should be included in a field div that has a class like .field-type-image.
With this in mind, you can write a selector that picks the images, something like:
div.field-type-image img {border: 1px solid #ccc }
or a more specific one like:
div.field-type-image div.field-items div.field-item img {border: 1px solid #ccc }
Answer: I think you want to use this for captions. After much hunting around, use Jquery. This stuff is for Drupal 7.
create your js file. Call it caption.js. You can call it something else. Store it inside your theme somewhere.
Make sure the script gets called by editing your theme.info file and adding
scripts[] = pathtoyourfile/caption.js
caption.js should contain the following code
(function ($) {
Drupal.behaviors.caption = {
attach: function(context, settings) {
$('.views-field-field-useimage img').addClass('caption');
  }}})
(jQuery);

Substitute .views-field-field-useimage img for your own selector.
Hit the empty cache button and give it a go.
Answer: A suggestion for this answer.
Change the
$variables['attributes'] = array(
  'class' => $variables['style_name'],
);

to
$variables['attributes']['class'][] = $variables['style_name'];

so the image style name is appended to the class array and nothing is inadvertently squashed.
Full snippet:
function MYTHEME_image_style($variables) {
  // Determine the dimensions of the styled image.
  $dimensions = array(
    'width' => $variables['width'],
    'height' => $variables['height'],
  );

  image_style_transform_dimensions($variables['style_name'], $dimensions);

  $variables['width'] = $dimensions['width'];
  $variables['height'] = $dimensions['height'];

  $variables['attributes']['class'][] = $variables['style_name'];

  // Determine the url for the styled image.
  $variables['path'] = image_style_url($variables['style_name'], $variables['path']);
  return theme('image', $variables);
}


Write each of the following functions as a composition of functions chosen from $f$, $g$, and $h$.

Question:
Let $f(x)=|x|$, $g(x)=x-7$, and $h(x)=x^2$.

$A(x)=x^2-7$
$B(x)=x^2-14x+49$
$C(x)= |x-7|$
$D(x)=(x^2-7)^2$

For number one I tried using $(fog)(x)= f(g(x))$ but I got the answer as being the absolute value of $x-7$ which is wrong. Please help.
I understand how it works now. Thank you very much everyone!
Comment: Do you just need number 1, or any of the others?
Comment: I do not understand how to do one. I need all the answers but if you show me how to do one maybe I will be able to do the others.
Answer: $A(x)=(g\circ h)(x)$ as $g(x^{2})=x^{2}-7$.
Comment: Shouldn't it be $g(x^2)$, or am I missing something?
Comment: Ouch Ouch! I messed the order up, thanks!
Answer: $A(x)=g \circ h(x)$ since $g \circ h(x)=g (h(x))=g(x^2)=x^2-7$
$B(x)=h(g(x))$ since $h (g(x))=h((x-7))=(x-7)^2=x^2-14x+49$
Try to complete the other two,
Hint for the last one, you have to make two compositions.
Answer:
$A = g\circ h$ since $g(h(x)) = h(x)-7 = x^2-7$
$B = h\circ g$ since $h(g(x)) = (x-7)^2 = x^2-2\cdot 7x + 49$
$C = f\circ g$ since $f(g(x)) = \lvert g(x)\rvert = \lvert x-7\rvert$
$D = h\circ g\circ h$ since $h(g(h(x))) = \left(g(x^2)\right)^2 = (x^2-7)^2$


Setting Default value when Object mapping in Red-Gate Data Compare

Question: I am using Red-Gate Data Compare to synchronize two databases, lets call them DBSource and DBDestination.  DBDestination has a table, TableA which has a field which has a not null constraint.  TableA within DBSource has the same structure, apart from this new field.
When I synchronize using the Data Compare tool, it fails due to this particular not null field, since there's no object map I can set up for it.
I wanted to know if there is a way of setting a default on the tool, since I can't alter the schema of the destination table and the file is quite large to edit?
Answer: The best way to handle this is to alter the column in the database and put a default value on it. There isn't anything you can do in the SQL Data Compare settings to make it replace illegal NULL data with a default value.
Comment: Uservoice would be more effective. https://redgate.uservoice.com/forums/147879-sql-data-compare
Comment: This is what I ended up with. I think I might email the Red-Gate support to ask for this feature to be added.
Comment: Already there, https://redgate.uservoice.com/forums/147879-sql-data-compare/suggestions/2973662-allow-copying-data-to-destination-that-may-have-no


problemas com conversão de data com php

Question: Tenho a seguinte função que transforma timestamp em data legível em português
function dataEmPortugues ($timestamp, $hours = TRUE, $timeZone = "America/Sao_Paulo") {
  $timestamp=strtotime($timestamp);
    $dia_num = date("w", $timestamp);// Dia da semana.

    if($dia_num == 0){
      $dia_nome = "Domingo";
    }elseif($dia_num == 1){
      $dia_nome = "Segunda-feira";
    }elseif($dia_num == 2){
      $dia_nome = "Terça-feira";
    }elseif($dia_num == 3){
      $dia_nome = "Quarta-feira";
    }elseif($dia_num == 4){
      $dia_nome = "Quinta-feira";
    }elseif($dia_num == 5){
      $dia_nome = "Sexta-feira";
    }else{
      $dia_nome = "Sábado";
    }

    $dia_mes = date("d", $timestamp);// Dia do mês

    $mes_num = date("m", $timestamp);// Nome do mês

    if($mes_num == 01){
      $mes_nome = "Janeiro";
    }elseif($mes_num == 02){
      $mes_nome = "Fevereiro";
    }elseif($mes_num == 03){
      $mes_nome = "Março";
    }elseif($mes_num == 04){
      $mes_nome = "Abril";
    }elseif($mes_num == 05){
      $mes_nome = "Maio";
    }elseif($mes_num == 06){
      $mes_nome = "Junho";
    }elseif($mes_num == 07){
      $mes_nome = "Julho";
    }elseif($mes_num == 08){
      $mes_nome = "Agosto";
    }elseif($mes_num == 09){
      $mes_nome = "Setembro";
    }elseif($mes_num == 10){
      $mes_nome = "Outubro";
    }elseif($mes_num == 11){
      $mes_nome = "Novembro";
    }else{
      $mes_nome = "Dezembro";
    }
    $ano = date("Y", $timestamp);// Ano

    date_default_timezone_set($timeZone); // Set time-zone
    $hora = date ("H:i", $timestamp);

    if ($hours) {
      return $dia_nome.", ".$dia_mes." de ".$mes_nome." de ".$ano." às ".$hora;
    }
    else {
      return $dia_nome.", ".$dia_mes." de ".$mes_nome." de ".$ano;
    }
  }

tenho um time stamp
2016-11-30 15:12:09

e quando converto usando esta função ele retorna
Quarta-feira, 30 de Novembro de 2016 às 13:12

esta retornando com 2 horas de diferença. como arrumo isso ?
Comment: experimente com gmdate e veja o que acontece
Comment: mesmas 2 horas d diferença
Comment: na verdade é simples, precisa por o `date_default_timezone_set('America/Sao_Paulo');` logo que abre o `<?php`, pq seu timestamp está vindo de fora. Se tiver um include de conexao de DB, e/ou alguma config usada em geral, pode aproveitar e já deixar lá. Remova isso da função, pq nao vai adiantar nada mudar dentro.
Answer: Repensando no código:
No caso de usar a versão runtime, date_default_timezone_set, chame-a ANTES de usar as funções de data. No começo do código que chama a função, e não dentro dela.
No seu código aparentemente você está usando no meio da função, sendo que para ter consistência, teria que usar uma vez só logo depois de abrir o PHP.
Alternativas de configuração:
Quem define o fuso horário do PHP é essa função:
bool date_default_timezone_set ( string $timezone_identifier )

Ou esta diretiva da configuração:
date.timezone =

Manual:

http://php.net/manual/pt_BR/function.date-default-timezone-set.php
http://php.net/manual/pt_BR/datetime.configuration.php#ini.date.timezone

Nota: se em alguma situação precisar do horário sem o fuso, pode optar pela função gmdate(), que usa os mesmos parâmetros, mas toma a UTC como base.
Escolhendo a string correta:
Abaixo, os links do manual para facilitar para quem for customizar as chamadas para uma região específica.
Para Brasil, pode usar:
date_default_timezone_set('America/Sao_Paulo');

E para Portugal:
date_default_timezone_set('Europe/Lisbon');

Veja a lista completa aqui:

http://php.net/manual/pt_BR/timezones.php
Comment: sim ja estou usando essa função veja no meu script temo default timezone dentro dela
Comment: @JasarOrion experimente mudar para o local indicado na atualização
Comment: fiz como vc solicitou e ainda continua com 2 horas de diferença. Sera que meu apache esta errado ou meu php ou ate o Mysql?
Comment: Estranho. Vc tem acesso ao php.ini? precisa ver como está lá. E ver se as timezones estao ok no PHP, uma olhada no log do apache pode ajudar. Mesmo assim vou reler tudo e ver se consigo pensar em mais possibilidades.
Comment: @JasarOrion na verdade é simples, precisa por o `date_default_timezone_set('America/Sao_Paulo');` logo que abre o `<?php`, pq seu timestamp está vindo de fora. Se tiver um include de DB, e classe, pode aproveitar e já deixar lá. Remova isso da função, pq nao vai adiantar nada mudar dentro.
Comment: tendi , eu fiz um date no php e retorna ate os segundos exatos somenet quando pego o timestamp do db e tento converter que fica 2 horas defasado
Comment: Vai ver que no DB foi gravado defasado. O campo do DB é `date` ou é `timestamp`? Se estiver tudo defasado, com um update já arruma geral. Precisa ver se não faltou o date_default_timezone no arquivo que grava no DB.
Answer: Tomei a liberdade de dar uma "ajeitada" no padrão de código e remover redundâncias. Mas mantive a estrutura para não ser muito invasivo.
Um ponto interessante é que a partir do PHP7 o trecho com } elseif ($mes_num == 08) { poderia causar o erro tipo "parse" Invalid numeric literal.

Antes, octais literais que continham números inválidos, eram
  silenciosamente truncados (0128 se tornaria 012). Agora, um octal
  literal inválido causará um erro de parse.
  Consulte: http://php.net/manual/pt_BR/migration70.incompatible.php#migration70.incompatible.integers

Por isso removi todos os zeros a esquerda, mas de qualquer forma independente disso eu já teria removido.
Isso é apenas uma observação pois não era isso que causava o erro relatado na pergunta e desvia um pouco do foco principal.
Sobre o motivo do código original apresentar horário com 2 horas de diferença, não averiguei. Apenas refiz o script para um jeito mais fácil extraindo os valores com a função substr() pois julguei desnecessário fazer tantas chamadas a função date(), timezone, etc.
O importante é que a mudança faz com que função retorne o que deseja.
function dataEmPortugues($date, $hours = true)
{

    $dia_num = date('w', strtotime($date));// Dia da semana.

    if($dia_num == 0) {
        $dia_nome = 'Domingo';
    } elseif ($dia_num == 1) {
        $dia_nome = 'Segunda-feira';
    } elseif ($dia_num == 2) {
        $dia_nome = 'Terça-feira';
    } elseif ($dia_num == 3) {
        $dia_nome = 'Quarta-feira';
    } elseif ($dia_num == 4) {
        $dia_nome = 'Quinta-feira';
    } elseif ($dia_num == 5) {
        $dia_nome = 'Sexta-feira';
    } else {
        $dia_nome = 'Sábado';
    }

    // Faz um cast integer para remover zeros a esquerda
    $mes_num = (int)substr($date, 5, 2);// Nome do mês

    if($mes_num == 1) {
        $mes_nome = 'Janeiro';
    } elseif ($mes_num == 2) {
        $mes_nome = 'Fevereiro';
    } elseif ($mes_num == 3) {
        $mes_nome = 'Março';
    } elseif ($mes_num == 4) {
        $mes_nome = 'Abril';
    } elseif ($mes_num == 5) {
        $mes_nome = 'Maio';
    } elseif ($mes_num == 6) {
        $mes_nome = 'Junho';
    } elseif ($mes_num == 7) {
        $mes_nome = 'Julho';
    } elseif ($mes_num == 8) {
        $mes_nome = 'Agosto';
    } elseif ($mes_num == 9) {
        $mes_nome = 'Setembro';
    } elseif ($mes_num == 10) {
        $mes_nome = 'Outubro';
    } elseif ($mes_num == 11) {
        $mes_nome = 'Novembro';
    } else {
        $mes_nome = 'Dezembro';
    }

    return $dia_nome.', '.(int)substr($date, 8, 2).' de '.$mes_nome.' de '.substr($date, 0, 4).($hours? ' às '.substr($date, 11, 5): '');
}

echo dataEmPortugues('2016-11-30 15:12:09');

Tempo de execução: 0.0000169277191162109s (0.0169 milisegundos)

problemas com conversão de data com php


using badge with bootstrap 4 in asp.net core 3.1 asynchronous programing

Question: I have used badge in asp.net core 3.1 without Async method this is my code in service
 public int GetNotSeenContact()
    {
        return _context.Contacts.Where(s => s.Seen == false).Count();
    }

and this is call in scope layout :
 public int GetContactCont()
    {
        return _admin.GetNotSeenContact();
    }

and this is the place that I use this:
 int ConactBell = scope.GetContactCont();

and this is my html code that I called :
 @ConactBell

this is working very well but when I make it with Async method, it shows this exception instead of number for user:
System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Int32,DIG.Core.Classes.PanelLayoutScope+<GetContactCont>d__3]

Now these are my codes in async method in service:
 public async Task<int> GetNotSeenContact()
    {
        return await _context.Contacts.Where(s => s.Seen == false).CountAsync();
    }

this is in my scope class:
 public async Task<int> GetContactCont()
    {
        return await _admin.GetNotSeenContact();
    }

and this is the code where I use it inside html code:
@inject PanelLayoutScope scope
@{
Task<int> ConactBell = scope.GetContactCont();}

my html code :
@ConactBell

Please give me the best solution and tell me why does this happen when I use Async method. Thank you so much!
Comment: That's controller code. Don't put it in the view. That breaks how the MVC pattern works - the controller does the heavy lifting and produces a viewmodel/bag of data that's displayed by the view. A view doesn't support async code because it *doesn't need it* - the data should already be available
Comment: Even if you use the newer Razor Pages model, the *view* should never execute data access code. That's what the Controller (in MVC) or the PageModel (in Razor Pages) is for.
Answer: Because the method is asynchronous,you can try to use await.Change
@{
Task<int> ConactBell = scope.GetContactCont();}

to
@{
    var ConactBell =await scope.GetContactCont();}

result:
Comment: But as `Panagiotis Kanavos` said,we do not execute data access code in view.


Security issue with pg_hba.conf

Question: I have a PHP script on my server that needs access to a database user to work properly . The person who programmed that PHP script has told to add the following to pg_hba.conf :
host all all 127.0.0.1/32 trust

Can this cause any security related issues for me ? Based on my understanding, what that line does is that it allows scripts that are hosted locally to connect to pgsql without a password . Is this correct ?
Can the presence of that line cause any remote connections to my database to be established without the database password ?
Answer: Yes, that is a configuration that you should generally avoid outside of very limited special cases:

trust
Allow the connection unconditionally.
This method allows anyone that can connect to the PostgreSQL database server to login as any PostgreSQL user they wish, without the need for a password or any
other authentication.
[..]
trust authentication is only suitable for TCP/IP connections if you trust every user on every machine that is allowed to connect to the server by the pg_hba.conf lines that specify trust. It is seldom reasonable to use trust for any TCP/IP connections other than those from localhost (127.0.0.1).

Note that allowing connections without providing any password may already be the case, as many distributions default to authenticating connections via unix sockets as the connecting user. That would typically result in the www-data system user being able to use the www-data postgres user without a password. Check the rest of your authentication configuration to see if this is the case.
Recommendation: Provision password or certificate authentication, do not proceed with the trust option.
Note also that limiting something to loopback addresses only is generally not sufficiently secure guarantee against external access. There is a long history of loopback-bound services being accessed through other software acting as an unintended proxy.

Security issue with pg_hba.conf


Custom Scheduled Query in Google BigQuery using timezone

Question: I'm using scheduled query in Google BigQuery,
The requirement is to set it every 1st month at 04:00 (UTC+7) (Indonesia Time)
I've tried custom scheduled query but since the timezone is in UTC, so I can not achieve my requirement.
Sample :

1st day of month 04:00

How to solve this?
Can we set specific timezone in custom scheduled query in Google BigQuery?
Thanks
Comment: Please update the scheduled query and set the country first. With this you define the time zone as well.
Comment: Hi @Samuel
How to do that?
Answer: You can schedule your query based on your local time. For your requirements follow below steps:
Step 1: Write your query in the BigQuery console.

Step 2: Click the schedule button present at the top and select the option Create new schedule query

Step 3:  Below the heading schedule options select the Repeatsoption as monthly from the drop down button and select the start at set time option radio button.

Step 4: Now click on the calendar icon to select the country and timezone.

Step 5: select Indonesia time zone as per your requirement and set the date and time.

Step 6: Fill all the required fields and click the save button.
Comment: Hi @kiran-mathew , I've tried using your step, and set start time to 1 nov 4 AM WIT(Indo time), but when I check target date for next run is 1 January 2023 4 AM. (It skips 1 December, might be bcs If I set 1 nov, it translates to 31 oct, and since november only have 30 days, then is skipped) –
Comment: @HanChris The observation you made is correct. This is because when you schedule a query based on the local time zone, it gets converted into the UTC. As a workaround you can try to change the Repeat option from Monthly to Custom and specify `1 of month 04:00` or  you can also tweak the run time in a way so that even if it gets converted to UTC it will run on the 1st day of the month.
Comment: Hi @kiran-mathew, thank you for your response. Again, setting custom, can not specify the time zone. If I set 1 of month 04:00, will be converted to 1 of month 11:00 ICT (UTC+7). It's so silly that Google do not provide timezone for the custom value.


Why Is Total Sum of Squares Result from K-Means Analysis Different from Variance?

Question: I'm working on a project that requires some clustering analysis.  In performing the analysis, I noticed something that seemed odd to me.  I understand that in k-means the total sum of squares (total distance of all observations from the global center) equals the between sum of squares (distance between the centroids) plus the total within sum of squares (sum of the distances of each observation to its centroid).  But I also see that total sum of squares is not exactly equal to the total variance of the distribution, which I don't understand.  What I've noticed is that the two numbers (total sum of squares from k-means analysis vs. total variance) get closer to each other as the sample sizes get larger.  Here's a quick simulation in R that shows what I'm talking about:
require(dplyr)
compare_sd_km <- function(numObs){
    set.seed(3)
    x <- rnorm(numObs, 0, 1)
    y <- rnorm(numObs, 0, 1)

    km <- kmeans(data.frame(x,y), centers = 5)

    kmeansMeasure <- (km$betweenss + km$tot.withinss) / numObs
    varianceMeasure <- var(x) + var(y)
    return(c(kmeansMeasure, varianceMeasure))
}

numObsMultipliers <- c(1:5)
numObsMultipliers <- sapply(numObsMultipliers, function(x) 10^x)
comparisons <- lapply(numObsMultipliers, function(x)  compare_sd_km(x))
comparisons <- as.data.frame(do.call(rbind, comparisons))
comparisons$observations <- numObsMultipliers
colnames(comparisons) <- c('kmeansMeasure', 'varianceMeasure', 'observations')
comparisons <- mutate(comparisons, difference = kmeansMeasure - varianceMeasure)
comparisons <- comparisons[, c(3,1,2,4)]

#### RESULT ####
  observations kmeansMeasure varianceMeasure     difference
1           10      1.142764        1.269738 -0.12697379740
2          100      1.920365        1.939762 -0.01939762318
3         1000      1.988562        1.990553 -0.00199055288
4        10000      2.031035        2.031238 -0.00020312381
5       100000      2.007437        2.007457 -0.00002007457

Any ideas what's going on here?  Rounding issues?  Something having to do with how the algorithms are implemented?  Am I calculating something incorrectly? Or do total sum of squares and total variance actually mean something substantively different?  Thanks for any help anyone can provide.
Answer: I believe the issue here is the var function in R computes the unbiased estimator of the variance, i.e.
$s^2 = \displaystyle \frac{\sum_{i = 1}^n (x_i - \bar x)^2 }{ (n-1)}$
I think what you are getting from k-means will be equivalent to the MLE of $\sigma^2$, i.e.
$\hat \sigma^2 = \displaystyle \frac{\sum_{i = 1}^n (x_i - \bar x)^2 }{ n}$
Comment: Thanks, @Cliff AB! You're 100% correct. When I change the line of code that says `kmeansMeasure <- (kmbetweenss+kmbetweenss+kmtot.withinss) / numObs` to `kmeansMeasure <- (kmbetweenss+kmbetweenss+kmtot.withinss) / (numObs - 1)` the numbers match exactly. Very much appreciated.


Loading an swf with ActionScript code for iOS

Question: I read this was possible here:http://blogs.adobe.com/airodynamics/2012/11/09/packaging-and-loading-multiple-swfs-in-air-apps-on-ios/
However I can seam to get it right. My project is an ActionScript Mobile Project it uses the new AIR SDK 3.7. I create my SWF with Flash CS4. As publishing settings I use the Flash Player 10 with ActionScript 3.0. The ActionScript code is in the root. I set the swf version in the ActionScript Compiler to 10 -swf-version=10. I use the following code to load the swf:
<code>    public function TestSWF_Apple()
    {
        super();

        // support autoOrients
        stage.align = StageAlign.TOP_LEFT;
        stage.scaleMode = StageScaleMode.NO_SCALE;

        var _urlRequest:URLRequest = new URLRequest("preload.swf");
        var _loader:Loader = new Loader();
        var _lc:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain, null);
        _loader.load(_urlRequest, _lc);

        addChild(_loader);
    }
</code>
Can someone tell me what am I missing. I still get the error: Uncompiled ActionScript.
Thanks,
Dave
Answer: If you're sure you're compiling with AIR 3.6 or higher and that preload.swf is included in your iOS app on export (check your Build Packaging settings): have you tried using an absolute path? If preload.swf ends up in the root folder of your app, try using
<code>var absoluteReference:File = File.applicationDirectory.resolvePath("preload.swf");
var _urlRequest:URLRequest = new URLRequest(absoluteReference.nativePath);
</code>


Mouse coordinates in Internet Explorer

Question: I have a map for my game, I have a script that on a click displays an alert of the mouse coordinates on the map.
The map scale is 1 map unit to 2.5 pixels and the map starts at -600, 600 and goes down to 600, 1700. Thus I can't simply throw out the pixels of the mouse.
I got it working (and was pretty happy about it) but alas IE (6) has issues. I have narrowed it down to IE not correctly getting the scroll parameters.
Here is the relevant code that is glitching but the full code is located at http://woarl.com/map/ieMap.html
tempX = event.clientX + document.body.scrollLeft;
tempY = event.clientY + document.body.scrollTop;

Thanks for any help
Comment: How to make it so that IE doesn't go wrong :P
Answer: Try:
tempX = event.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft);
tempY = event.clientY + (document.documentElement.scrollTop || document.body.scrollTop);

Checked your page, and the DOCTYPE is putting IE in standards mode, so the scrollXXX properties you want are actually in document.documentElement, not document.body.
Comment: Dude, you just fixed a bug I've spent the last couple of days tracking down! Thanks :-D
Answer: Mouse coordinate locations are horrible, due to the specs not noting whether they ought to be relative to the document or the viewpane, amongst other things.  There's a good description of the problem, as well as an example of script that should work across all browsers, at the bottom of http://www.quirksmode.org/js/events_properties.html.
In particular it looks like you need to add document.documentElement.scroll(Left|Top) as well as the event and document.body parameters.

Mouse coordinates in Internet Explorer


Application of Gauss' Divergence Theorem

Question: The problem is as follows:

My attempt towards solution:

What am I doing wrong here? What does the $(-1)$ signify on the right hand side?
Thank you.
Comment: You can use the divergence theorem when you have a closed surface.  You have been asked for the flux through the plane.  Not all 5 sides of the prism.
Comment: Should I just calculate the surface integral?
Comment: That is what you have been asked to do.  You can take what you have and subtract the surface integrals of the portions of the planes $x = 0, y = 0,z = 0, z = 4$ if you think that will be easier to calculate.
Comment: @DougM https://imgur.com/a/Bua19 ::: is this correct??
Answer: Using the divergence theorem.
If $S_1$ is your target.  $S_2,S_3,S_4, S_5$ are the sides cut by the planes $x = 0, y=0, z = 0, z = 4,$ respectively.
Gauss' divergence theorem says:
$\iint_{S_1} A\cdot dS_1 + \iint_{S_2} A\cdot dS_2 + \iint_{S_3} A\cdot dS_3 + \iint_{S_4} A\cdot dS_4 + \iint_{S_5} A\cdot dS_5 = \iiint \nabla\cdot A\ dV$
You can calculate:
$\int_0^4\int_0^6 y\ dy\ dz + \int_0^4\int_0^3 2x\ dx\ dy + \int_0^3\int_0^{1-2x} 4\ dy\ dx -36$
or
$\int_0^4\int_0^3 2(6-2x) + 2x\ dx \ dz$
And both should give you the same answer.


If for a complex function if $f^{(n)}(1/k)=0$ $\forall k \in \mathbb{N}$, then $f(z)$ is a polynomial

Question: $\mathbf{Question}:$ For a function $f: \mathbb{C} \to \mathbb{C}$ and $n \geq 1$, let $f^{(n)}$ denote the $n$th derivative of $f$ and $f^{(0)}=f$.
Let $f$ be an entire function such that for some $n\geq 1$, $f^{(n)}(\frac{1}{k})=0$, $\ \forall k\in \mathbb{N}$. Show that $f$ is a polynomial.
$\mathbf{Attempt}:$ $f$ being an entire function, we can express $f$ as $f(z)= \displaystyle\sum_{t=0}^\infty a_tz^t $.
We get $f^{(n)}(z)=\displaystyle\sum_{t=n}^\infty t(t-1)...(t-n+1)a_t z^{t-n}$
Firstly, we have $\displaystyle\lim_{k \to \infty}f^{(n)}\bigg(\frac{1}{k}\bigg)=n!a_n=0 \implies a_n=0$ ($k$ is natural)
Now, for $f^{(n)}(z)=\displaystyle\sum_{t=n+1}^\infty t(t-1)...(t-n+1)a_t z^{t-n}= z\displaystyle\sum_{t=n+1}^\infty t(t-1)...(t-n+1)a_tz^{t-n-1} \ $, and for $z=1/k$, $f^{(n)}(\frac{1}{k})=0 \implies \displaystyle\sum_{t=n+1}^\infty t(t-1)...(t-n+1)a_t\bigg(\frac{1}{k}\bigg)^{t-n-1}=0  $. Again, taking $k \to \infty $, we get $a_{n+1}=0$.
Let $a_{n+m}=0$. Then $f^{(n)}(z)=\displaystyle\sum_{t=n+m+1}^\infty t(t-1)...(t-n+1)a_t z^{t-n}=z^{m+1}\displaystyle\sum_{t=n+m+1}^\infty t(t-1)...(t-n+1)a_t z^{t-n-m-1}$
Now, $(\frac{1}{k})^{m+1}\displaystyle\sum_{t=n+m+1}^\infty t(t-1)...(t-n+1)a_t (1/k)^{t-n-m-1}=0 \implies \displaystyle\sum_{t=n+m+1}^\infty t(t-1)...(t-n+1)a_t (1/k)^{t-n-m-1}=0 $. Taking $\displaystyle\lim_{k \to ∞}\sum_{t=n+m+1}^\infty t(t-1)...(t-n+1)a_t (1/k)^{t-n-m-1}=0$, we are left with $a_{n+m+1}=0$.
Thus we conclude that $a_{n+p}=0$ for all $p \in \mathbb{N}$
Now, $f^{(n)}(z)=0$, which gives us $f(z)=c_0+c_1z+...c_{n-1}z^{n-1}$.
Is this method correct?
Kindly $\mathbf{Verify}$
PS: I am aware of the duplicates, I just want to get my method checked without me looking at the previously answered questions.
Comment: It suffices to treat the case $n=0$ as an entire function is polynomial iff its derivative is polynomial
Comment: @HagenvonEitzen I am not quite getting it, could you please explain a bit?
Answer: What's the point of all this over-complication?
$f$ is entire $\implies f^{(n)}$ is entire. Now $\{\frac{1}{k}\}_{k \ge 1} \subset \Bbb C$ has a limit point in $\Bbb C$ (which is connected), and $f^{(n)}$ being entire vanishes on $\{\frac{1}{k}:{k \ge 1}\} $ . Hence by Uniqueness principle, $f^{(n)} \equiv 0 \implies$ $f^{(n-1)}$ is a constant $\implies$ $f^{(n-2)}$ is a polynomial of degree at most 1 $\implies \dots \implies f$ is a polynomial of degree at most $(n-1)$
Comment: I did not know about the Uniqueness Principle.
Comment: @SubhasisBiswas Okay, but learn it. That result captures the very essence of doing Complex Analysis.
Answer: Write $g(z) = f^{(n)}(z)$ where $n$ has the property you described. The zeros of a nonconstant analytic function are isolated. Consider the sequence $a_k = \frac{1}{k}$, then since $g$ is analytic we find that
$$g(0) = \lim_{k\to \infty} g(a_k) = \lim_{k\to \infty
}0 = 0$$
Thus $0$ is not an isolated zero of $g$. We conclude that since $g$ is analytic, then it is constant and in particular $g= 0$. Now the power series representation in a domain about a point is unique. From here we can work backwards using antiderivatives to determine that $g(z) = c_o + c_1z + \ldots + c_{n-1}z^{n-1}$.
Edit: Sorry, just saw your request to verify. You should be more clear what is going on with your first statement. I think you are trying to show that $f^{(n)}(0) = 0$ and thus you find that the constant term is zero? For the second part, I think it would be clearer if you said "$f^{(n)}(0) = 0$ and we have shown that the constant term is zero.... we can write the expansion as $f^{(n)}(z) = z\sum_{k=n+1}^\infty \alpha_k z^{k-n-1}$. Well $f^{(n)}(\frac{1}{k}) = (\frac{1}{k})\sum_{k=n+1}^\infty \alpha_k z^{k-n-1} = 0$. Thus $\sum_{k=n+1}^\infty \alpha_k z^{k-n-1} = 0$ whenever $z\in\{0\}\cup\{\frac{1}{k}:k\in\mathbb{N}\}$". I think this is what you are doing and then say iterate?
Comment: Precisely so. But in addition, I am taking $\lim k \to \infty$ (while $k$ is taken over the natural numbers only), so that $\alpha_{n+1}$ is the only remaining term on the left hand side for $z=1/k$ and the right hand side is $0$
Comment: Would that be alright?
Comment: I think you will be alright as long as you are clear where the induction step is
Comment: I tried to prove that if a zero of an analytical function is non-isolated, then it must be constant. But it has remained unanswered (verification request). It would be of great help if you could check that out as well. My approach has been very similar to this one: https://math.stackexchange.com/q/3762284/389992
Comment: Thank you for bearing with me so far. Just for a final bit, I've made the inductive step much clearer now.
Comment: Kindly let me know if that is good enough.


Likelihood function of a streched exponential function

Question: I would very much appreciate help regarding the following problem: I want to fit a stretched exponential function to different datasets by maximum likelihood:
$$y = e^{(b_0 x^{(b_1 - 1)} + b_2)}$$
$b_0$, $b_1$ and $b_2$ denote the parameters of the function, while "$x$" and "$y$" are variables. Unfortunately, my statistical skills are not sufficient in this area: Can anyone tell me the likelihood function of this stretched exponential function?
Comment: Likelihood makes no sense and cannot be determined until you specify a *probability model* for any discrepancies between observed values of $y$ and those predicted from the associated values of $x$.  What probability model would be appropriate in your application or might be suggested by the data?
Comment: When you are minimizing squared error, you are in effect assuming the errors are additive, independent, and have Normal distributions with a common variance.
Comment: You appear to contradict yourself.  Either you want to minimize the sum of squares of residuals or you do not.  If you do not, then we're back to the beginning: exactly how do you want to cope with discrepancies between the observed and fitted values of $y$?  "ML" isn't an answer--it's a technology to do the fitting after you have quantitatively answered that fundamental question.
Comment: Thank you very much whuber for your quick reply. I am not sure regarding your remarks. Basically, I want to replicate the results of a recently published paper ([link](http://dx.doi.org/10.3390/e18100364)). The authors estimate the entropy rate for natural language data. Since the true entropy rate is defined as a limit for an infinite amount of text and because the probabilistic model of natural language is unknown, the authors estimate the entropy for many different amounts of data and then use the ansatz function mentioned in my question to extrapolate.
Comment: So "x" is the amount of text (measured in characters) that is used to estimate the entropy rate "y".

In their paper the authors fit a nonlinear regression where the square error between the predicted and the observed values is minimised. Now, I want to use Stata's maximum likelihood capabilities ([link](https://www.stata.com/features/overview/maximum-likelihood-estimation/))  to fit this function. To this end, I want to specify an appropriate likelihood function that Stata maximize. I hope this helps to clarify my question. Many thanks again. Alex
Comment: Thanks again,
I already tried to fit my data using non linear regressions. For several reasons (especially convergence), I would like to try using a maximum likelihood estimation approach.
Comment: I understand, but I am still not sure how to answer that question quantitatively. To fit via ML with Stata, I need to produce observation-by-observation values of the log likelihood. Or put differently, I need to write a program that evaluates the log likelihood, Stata then fits the model and obtains estimates
Comment: It is assumed that the overall log likelihood ln ln(L) is equal to the sum of all individual log likelihood values that are generated via the use- written program (or evaluator). For this program, I need to know the observation-by-observation log likelihood function.
Answer: In comments you suggest the model for an observation $Y$ associated with a regressor value $x$ is the one with homoscedastic Normal errors
$$Y \sim \mathcal{N}\left(\exp\left(b_0 x^{b_1-1} + b_2\right), \sigma^2\right)$$
and that different $Y$ are independent.  Writing $b=(b_0, b_1, b_2)$ and
$$\mu(x; b) = \exp\left(b_0 x^{b_1-1} + b_2\right),\tag{1}$$
we may therefore express the probability density function (PDF) of each observation $y_i$, $i=1,\ldots, n$ as
$$f_Y(y_i; x_i) = \frac{1}{\sqrt{2\pi\sigma^2}} \exp\left(-\frac{(y_i-\mu(x_i;b))^2}{2\sigma^2}\right)$$
I'm pretty sure Stata wants you to supply the log likelihood function because in all but small problems the likelihood would underflow the IEEE double-precision floats it uses. The independence assumption implies the likelihood is the product of values of the PDF, whence its logarithm is the sum of their logarithms,
$$\eqalign{
\Lambda(y_1,\ldots,y_n; x_1,\ldots,x_n) &= \sum_{i=1}^n \log\left(\frac{1}{\sqrt{2\pi\sigma^2}}\right) - \frac{(y_i-\mu(x_i, b))^2}{2\sigma^2}\\
&=-\frac{n}{2}\log(2\pi\sigma^2) - \frac{1}{2\sigma^2}\sum_{i=1}^n (y_i-\mu(x_i, b))^2
.\tag{2}}$$
$(1)$ and $(2)$ together provide an explicit formula for $\Lambda$ as a function of $b$ and $\sigma$ (depending, of course, on the data).
Note that conditional on any value of $\sigma$, maximizing $\Lambda$ amounts to finding $b$ to minimize the sum of squares of discrepancies between the $y_i$ and $\mu(x_i;b)$ (the right-hand term).
Except for huge datasets, maximizing $\Lambda$ accurately can be a delicate computation.  You can help your software out by finding some approximate initial solutions.  Consider exploring a set of reasonable values of $b_1$ and regressing (using ordinary least squares) $\log(y)$ against $x^{b_1-1}$ to estimate the slope $b_0$ and intercept $b_2$.  Pick the solution $\hat b = (\hat b_0, \hat b_1, \hat b_2)$ with the best fit and start Stata's search at $\hat b$.  If you can, supply some bounds for these parameters so it can constrain that search.
Comment: Dear whuber, I will try to implement your solution tomorrow. Thank you, very much appreciated!


What is the VC dimension of a decision tree?

Question: What is the VC dimension of a decision tree with k splits in two dimensions? Let us say the model is CART and the only allowed splits are parallel to the axes.
So for one split we can order 3 points in a triangle and then for any labeling of the points we could get perfect prediction (i.e.: shattered points)
But what about 2 splits, or any general k?
Answer: I'm not sure this is a question with a simple answer, nor do I believe it is a question that even needs to be asked about decision trees.
Consult Aslan et al., Calculating the VC-Dimension of Trees (2009). They address this problem by doing an exhaustive search, in small trees, and then providing an approximate, recursive formula for estimating the VC dimension on larger trees. They then use this formula as part of a pruning algorithm. Had there been a closed-form answer to your question, I am sure they would have supplied it. They felt the need to iterate their way through even fairly small trees.
My two cents worth. I'm not sure that it's meaningful to talk about the VC dimension for decision tres. Consider a $d$ dimensional response, where each item is a binary outcome. This is the situation considered by Aslan et al. There are $2^d$ possible outcomes in this sample space and $2^d$ possible response patterns. If I build a complete tree, with $d$ levels and $2^d$ leaves, then I can shatter any pattern of $2^d$ responses. But nobody fits complete trees. Typically, you overfit and then prune back using cross-validation. What you get at the end is a smaller and simpler tree, but your hypothesis set is still large. Aslan et al. try to estimate the VC dimension of families of isomorphic trees. Each family is a hypothesis set with its own VC dimension.

The previous picture illustrates a tree for a space with $d=3$ that shatters 4 points: $(1,0,0,1),(1,1,1,0),(0,1,0,1), (1,1,0,1)$. The fourth entry is the "response". Aslan et al. would regard a tree with the same shape, but using $x1$ and $x2$, say, to be isomorphic and part of the same hypothesis set. So, although there are only 3 leaves on each of these trees, the set of such trees can shatter 4 points and the VC dimension is 4 in this case. However, the same tree could occur in a space with 4 variables, in which case the VC dimension would be 5. So it's complicated.
Aslan's brute force solution seems to work fairly well, but what they get isn't really the VC dimension of the algorithms people use, since these rely on pruning and cross-validation. It's hard to say what the hypothesis space actually is, since in principle, we start with a shattering number of possible trees, but then prune back to something more reasonable. Even if someone begins with an a priori choice not to go beyond two layers, say, there may still be a need to prune the tree. And we don't really need the VC dimension, since cross-validation goes after the out of sample error directly.
To be fair to Aslan et al., they don't use the VC dimension to characterize their hypothesis space. They calculate the VC dimension of branches and use that quantity to determine if the branch should be cut. At each stage, they use the VC dimension of the specific configuration of the branch under consideration. They don't look at the VC dimension of the problem as a whole.
If your variables are continuous and the response depends on reaching a threshold, then a decision tree is basically creating a bunch of perceptrons, so the VC dimension would presumably be greater than that (since you have to estimate the cutoff point to make the split). If the response depends monotonically on a continuous response, CART will chop it up into a bunch of steps, trying to recreate a regression model. I would not use trees in that case -- possibly gam or regression.
Answer: I know this post is kind of old and already has an accepted answered, but as it is the first to link appear on Google when asking about the VC dimension of decision trees, I will allow myself to give some new information as a follow up.
In a recent paper, Decision trees as partitioning machines to characterize their generalization properties by
Jean-Samuel Leboeuf, Frédéric LeBlanc and Mario Marchand, the authors consider the VC dimension of decision trees on examples of $\ell$ features (which is a generalization of your question which concerns only 2 dimensions). There, they show that the VC dimension of the class of a single split (AKA decision stumps) is given by the largest integer $d$ which satisfies
$2\ell \ge \binom{d}{\left\lfloor\frac{d}{2}\right\rfloor}$. The proof is quite complex and proceeds by reformulating the problem as a matching problem on graphs.
Furthermore, while an exact expression is still out of reach, they are able to give an upper bound on the growth function of general decision trees in a recursive fashion, from which they show that the VC dimension is of order $\mathcal{O}(L_T \log (\ell L_T))$, with $L_T$ the number of leaves of the tree. They also develop a new pruning algorithm based on their results, which seems to perform better in practice than CART's cost complexity pruning algorithm without the need for cross-validation, showing that the VC dimension of decision trees can be useful.
Disclaimer: I am one of the author of the paper.
Comment: Congrats on such an impressive work!
Comment: Thank you, I did work hard on this!
Comment: Great answer. I am currently interested in learning theory for decision trees and this is a good starting point. Are there other results in this direction that you know of? Perhaps going beyond VC dimensions
Comment: Hi Claudio! I'm not sure what you mean by "going beyond VC dimension", but the litterature is limited as you can see in the "Related Work" section of the paper. Since the publication of our paper, we have considered categorical features in addition to real-valued ones in a new [preprint](https://arxiv.org/pdf/2210.10781.pdf). If by "beyond" you mean other complexity measures, there have been some work on multiclass dimensions such as the Natarajan dimension or Graph dimension (for example https://arxiv.org/pdf/2209.07015.pdf).
Comment: You can also check the work of Golea et al. (https://papers.nips.cc/paper/1997/file/4f87658ef0de194413056248a00ce009-Paper.pdf) on data-dependent analysis of decision trees and there have been some intersting work on "sample compression" approaches.


Differentaition problem

Question: How to differentiate $$f(x)= x+ (4/x-1)$$,$$
f'(x) = 1.(x-1)^{-1}.(-1)(1).1 $$
Is that right or there's a better solution if right?
Any help will be appreciated.
Comment: Use Math jax please. It will be more readable.
Comment: are you trying to find the derivative of the following - $$f(x)= x+ \frac{4}{x-1}$$
Answer: What you wrote was $x+ \frac{4}{x}- 1$.  Its derivative would be $1-\frac{4}{x^2}$.
If you meant $x+ \frac{4}{x- 1}$ then the derivative is $1-\frac{4}{(x- 1)^2}$.  Neither is what you wrote,
Answer: write it in the form
$$f(x)=x+4(x-1)^{-1}$$ and use the sum and the power rule so $$f'(x)=1-4(-1)(x-1)^{-2}$$

Differentaition problem


Showing that $\prod_{n=1}^{\infty}\left(1+\frac{1}{F_{2^n+1}L_{2^n+1}}\right)=\frac{3}{\phi^2}$

Question: Infinite product
$F_{n}:=[1,1,2,3,5,8,\cdots]$ and
$L_{n}:=[1,3,4,7,\cdots]$
for $n=1,2,3,\cdots$ respectively.
$\frac{1+\sqrt5}{2}=\phi$
Show that,
$$\prod_{n=1}^{\infty}\left(1+\frac{1}{F_{2^n+1}L_{2^n+1}}\right)=\frac{3}{\phi^2}$$

We took the idea from this site
Expand the product
(1)
$$\left(1+\frac{1}{F_{3}L_{3}}\right)\cdot\left(1+\frac{1}{F_{5}L_{5}}\right)\cdot\left(1+\frac{1}{F_{9}L_{9}}\right)\cdots=\frac{3}{\phi^2}$$
$F_{n}=\frac{\phi^n-(-\phi)^{-n}}{\sqrt5}$
$L_{n}=\phi^n+(-\phi)^{-n}$
$F_{n}L_{n}=\frac{\phi^{2n}-(-\phi)^{-2n}}{\sqrt5}=F_{2n}$
Rewrite (1)
$$\left(1+\frac{1}{F_{6}}\right)\cdot\left(1+\frac{1}{F_{10}}\right)\cdot\left(1+\frac{1}{F_{18}}\right)\cdots=\frac{3}{\phi^2}$$
Still doesn't help much to get from LHS to RHS.
We have $F_{2n}=F^2_{n+1}-F^2_{n-1}$
I have substituted in, but the formula seem too messy and more complicated.
Can anybody please give a hand?
Comment: $F_{4k+2}+1=F_{2k+2}L_{2k}$
Answer: Use $$F_{4k+2}+1=F_{2k+2}L_{2k}\tag{1}$$ with $k=2^{n-1}$. Also note $$\prod_{k=1}^{n}L_{2^{k}}=\prod_{k=1}^{n}\phi^{2^k}+(-\phi)^{-2^{k}}=\frac{\phi^{2^{k+1}}-(-\phi)^{-2^{k+1}}}{\phi^2-(-\phi)^{-2}}=\frac{F_{2^{k+1}}}{F_{2}}\tag{2} $$ From $\text{(1)}$, note that  $$\left(1+\frac{1}{F_{6}}\right)\cdot\left(1+\frac{1}{F_{10}}\right)\cdot\left(1+\frac{1}{F_{18}}\right)\cdots \left(1+\frac{1}{F_{2^{k+1}+2}}\right)=\frac{F_{4}L_{2}L_{4} \dots L_{2^k}}{F_{2^{k+1}+2}} $$ Using $\text{(2)}$, we have $$\frac{F_{4}L_{2}L_{4} \dots L_{2^k}}{F_{2^{k+1}+2}}=\frac{3F_{2^{k+1}}}{F_{2^{k+1}+2}}$$
But $$\lim_{k \to \infty}\frac{3F_{2^{k+1}}}{F_{2^{k+1}+2}}=\frac{3}{\phi^2}$$
Comment: Yes thank you @MXYMXY, different approach.
Answer: Hint. One may use the following result,

$$
\prod_{n=1}^{\infty}\left(1+\frac{F_b}{F_{2^na+b}}\right)=\frac{1-(-1)^b\phi^{-2a-2b}}{1-\phi^{-2a}} \tag1
$$

which is proved by J. Sondow here (see proposition 1 on page 3), where $\phi=\dfrac{1+\sqrt5}{2}$ and where $F_{n}:=[1,1,2,3,5,8,\cdots]$  are the Fibonacci numbers.
Applying $(1)$ with $a=2$, $b=2$ using $F_{2^n+1}L_{2^n+1}=F_{2^{n+1}+2}$ gives the announced infinite product.
Comment: @mahdi This is a pretty particular case from Sondow's general result. You should send it to him ;).
Comment: Thank you @Olivier OLoa you makes it look so simple. I will send it to him see what he will say.


Prove that $\{a \in (0,1) \mid |f(a)-L(a)|>1\}$ is finite

Question: Let $f:[0,1] \to \mathbb{R}$ be a function continuous at the points $0$ and $1$ and such that the limits $L(a)=\lim _{x \to a} f(x) \in \mathbb{R}$ exist for every $a \in (0,1)$. Prove that the set $\{a \in (0,1) \mid |f(a)-L(a)|>1\}$ must be finite.
I have no clue where to start with this problem.
Comment: Note proper notation for sets in MathJax or LaTeX: $$ \mathscr S = \{a,b,c,d\} $$ $$ \mathscr T = \left\{ \frac 1 2, \frac 3 2 \right\} $$ Also note the use of \mid, as in my edit to the question.
Answer: Note that the set $$A = \{a\mid a\in(0, 1), |f(a) - L(a)| > 1\}$$ is bounded. If it is infinite then by Bolzano Weierstrass theorem there is an accumulation point $c$ of $A$ in $[0, 1]$.
Note that the function $L$ is continuous on $[0, 1]$ (try to prove yourself). Consider the sequence of point $x_{n} \in A$ such that $x_{n} \to c$. Then we have $$|f(x_{n}) - L(x_{n})| > 1$$ for all $n$. Letting $n \to \infty$ we see that $|L(c) - L(c)| \geq 1$ which is a contradiction.
Note that the continuity of $f$ at end points is not needed. What is needed is that $f$ has one sided limits at the endpoints $0$ and $1$.
Answer: Hint: Show that this subset of $ [0, 1] $ is closed (thus compact) and discrete in the subspace topology.


Resizing a specific TinyMCE editor added by JS

Question: I am adding/replacing two textareas with TinyMCE via two different javascript clicks/calls. They have different IDs and are being added correctly by the 'execCommand' call:
tinymce.execCommand('mceAddControl',true,'comment1');

However, I am having trouble resizing the objects when there are more than one on screen. If there is just one I am able to successfully call 'resizeTo' using the 'activeEditor' to resize the object, like this:
tinymce.execCommand('mceAddControl',true,'comment1');
var ed = tinymce.activeEditor;
ed.theme.resizeTo(400, 200);

But when there is more than one editor, I cannot use 'activeEditor' and I don't know how to select a specific editor to resize. I have tried the following, but it didn't work:
var edd = tinymce.get('comment2');
edd.theme.resizeTo(350,306);

Any help/suggestions? Thanks!
Answer: In order to have to working tinymce editors with textareas as source elements you have given each of those testareas a unique id. This id will help you to get the correct editor instance.
Use
var editor = tinymce.get('your_textarea_id');

to get the correct editor. That's all.
Comment: I believe my problem was that I was trying to resize it to a size (width in particular) that was lower than the min allowed width (because of the toolbars perhaps?). So I wasn't seeing it resize and believed it wasn't working. Thanks for the reply!


linear 4×4 system of nonhomogeneous differential equations with repeated eigenvalues.

Question: I'm trying to find the general solution of this system of linear Nonhomogeneous differential equation:
$$X'=\begin{bmatrix}
-2 &1  &1 &-1\\
-1 & -1 & 1 &0\\
0 &0  &-1 &0\\
0 &-1  &0 &0
\end{bmatrix}X +
\begin{bmatrix}
e^t \\
2t \\
e^{-2t} \\
0
\end{bmatrix}
$$
as an aproach, I found the eigenvalue $-1$ with multiplicity of 4.
And I found two eigenvectors:
$$V^{(1)}=\begin{bmatrix}
1 \\
0 \\
1 \\
0
\end{bmatrix}$$ and $$V^{(2)}=\begin{bmatrix}
0 \\
1 \\
0 \\
1
\end{bmatrix}$$
so i got two answers for the Corresponding homogeneous equation:
$$X^{(1)}=\begin{bmatrix}
1 \\
0 \\
1 \\
0
\end{bmatrix}e^{-t}$$
and $$X^{(2)}=\begin{bmatrix}
0 \\
1 \\
0 \\
1
\end{bmatrix}e^{-t}$$
since we have 2 eigenvectors and one eigenvalue with multiplicity of 4, I tried to find the other two answers by assuming them as $X=vte^{-t} + ηe^{-t}$ and I got:
$X^{(3)}=\begin{bmatrix}
0 \\
1 \\
0 \\
1
\end{bmatrix}te^{-t} + \begin{bmatrix}
0 \\
0 \\
1 \\
1
\end{bmatrix}e^{-t}$
$X^{(4)}=\begin{bmatrix}
0 \\
1 \\
0 \\
1
\end{bmatrix}te^{-t} + \begin{bmatrix}
-1 \\
-1 \\
0 \\
0
\end{bmatrix}e^{-t}$
I wanna know if the Answers I found are correct.
if Yes, we have:
$$X=\begin{bmatrix}
e^{-t} &0  &0 &-e^{-t}\\
0 & e^{-t} & te^{-t} &te^{-t}-e^{-t}\\
e^{-t} &0  &e^{-t} &0\\
0 &e^{-t}  &te^{-t}+e^{-t} &te^{-t}
\end{bmatrix}$$
using the Variation of Parameters method, we have to inverse X to find the answer but A is singular $(detA=0)$ :(
where am I going wrong? can someone help me?
Answer: You assumed that the Jordan blocks for $-1$ were of sizes $\{2,2\}$ – they're in fact of sizes $\{3,1\}$:
$$A=\begin{bmatrix}0&-1&1&1\\1&-1&0&0\\0&0&0&1\\1&0&0&0\end{bmatrix}\begin{bmatrix}-1&1&0&0\\0&-1&1&0\\0&0&-1&0\\0&0&0&-1\end{bmatrix}\begin{bmatrix}0&-1&1&1\\1&-1&0&0\\0&0&0&1\\1&0&0&0\end{bmatrix}^{-1}$$
So one homogeneous solution is a vector times $t^2e^{-t}$:
$$X=\begin{bmatrix}1-t&t&t&-t\\-t+t^2/2&1-t^2/2&t-t^2/2&t^2/2\\0&0&1&0\\t^2/2&-t-t^2/2&-t^2/2&1+t+t^2/2\end{bmatrix}e^{-t}$$
Comment: I don't understand something. in Jordan blocks all the arrays above Main diagonal must be 1, but here the array 3×4 isn't 1, why? and in the matrix of eigenvectors where does the third column come from?


ip rule and route doesn't get respected

Question: I'm trying to route packets based on their source address, and have added the following:
# ip rule add from 10.10.10.0/16 dev eth0 table foobar
# ip route add default via 18.104.22.168 dev eth0 table foobar

Testing the routing however gives me wrong via address:
# ip route get 18.104.22.168 from 10.10.10.1
188.8.131.52 from 10.10.10.1 via 220.127.116.11 dev eth0

Why doesn't this get respected?
This is my regular routes
# ip route list
default via 22.214.171.124 dev eth0

and
# ip route show table foobar
default via 18.104.22.168 dev eth0

and
# ip rule list
0:  from all lookup local
32765:  from 10.10.10.0/16 iif eth0 lookup foobar
32766:  from all lookup main
32767:  from all lookup default

Comment: Isn't 10.10.10.0/16 a host address in the 10.10.0.0 subnet ?
Answer: Your issue isn't issue. In rule you use not only source address, but also input interface match. So, there are two ways to solve your "problem":

Don't use the dev eth0 in the rule
Add iif eth0 in the ip route get... command. The iif option allows you use non-local addresses in the ip route get command, so you can use something like:
ip route get 184.108.40.206 from 10.10.20.253 iif eth0
Comment: I was wondering if that was it. Since they're both routed to eth0, it might just be returning the default because that's the top rule for that interface. I'd add a new interface on eth1, and see if that changed it.
Comment: In the `ip route get` by default used the loopback interface if `iif` isn't specified. If you want the bloody details, you can look at source code ( https://elixir.bootlin.com/linux/latest/source/net/ipv4/route.c#L2868 )

ip rule and route doesn't get respected


How are the various guarantees provided to SVMs by Statistical Learning Theory affected by the Kernel Function

Question: I never studied the field in depth, but I am very aware that state of the art performance in most ML tasks is now achieved by various flavors of neural networks.  At the same time, Vladimir Vapnik, the co-founder Statistical Learning Theory (SLT), and the co-inventor of SVMs is continuing to play around with various marginal improvements to SVMs, such a privileged information (https://www.youtube.com/watch?v=5mvfpSdWsOo) or using location information (https://www.youtube.com/watch?v=LEYglsxKclo). In this interview he seems explicitly hostile to deep learning, claiming that the problems it might be solving are actually easy (https://www.youtube.com/watch?v=STFcvzoxVw4#t=23m39s). To my untrained eye, the biggest benefit of NNs is that they produce their own kernels from the ground up, which in the SVM framework have to be designed by hand. In some sense, SVMs push the task of intelligence once step back, to the problem of kernel design.
Which brings me to my question: How are the guarantees of SLT dependent on the kernels? Obviously the right kernel can transform a problem from one requiring slack variables to one lacking them, but if theory itself cannot provide rigorous and mechanical method of producing kernels, then it seems SLT is severely incomplete as a theory of inference. Am I misunderstanding something?
Answer: Some thoughts on your interesting question:
Good features are problem dependent. So seems difficult (if possible) to incorporate feature engineering into any rigorous mathematical framework.
To me, pushing the problem of finding good features to finding good kernels is a way to separate the problem in two parts.
First, the mathematics (learning from good/noisy features), and second, the practical nature of your data (finding features from your observations - sometimes using an arbitrary off-the-shelf mapping, but sometimes using your knowledge and understanding of how the data was generated).
It is indeed very nice that neural networks can find their own feature mappings. However this is an empirical observation, it is not the case that we mathematically understand how or why these features should be good.
You may call SLT "severely incomplete as a theory of inference", but our understanding of why neural networks should work is even more incomplete.
Finally, as you stated, the state of the art results are achieved by using various different architectures for neural networks.
While some neural networks achieve stellar performance, others perform poorly on the same datasets.
So, to me, the situation for SVM ad neural networks is similar: your performance will be strongly influenced by the choice of kernel or the network.
However if you go for SVM, then at least we can mathematically understand something - the "learning" step ;-)
Answer: A lot of the theoretical underpinnings of the SVM are based on the linear maximum margin classifier.  However, the advantage of a kernel is that the SVM can be viewed as a linear maximum margin classifier that is constructed in a feature space that is implicitly defined by the kernel.  As imposing a fixed kernel is equivalent to a fixed transformation of the data, which is equivalent to just solving some other fixed classification problem.  This means that any theory that holds for a linear classifier also holds for a fixed kernel.
However, in most practical cases, we don't use a fixed kernel.  In general, the kernel has some hyper-parameters that we also learn from the data, e.g. via cross-validation.  As soon as we tune the kernel parameters, we have immediately invalidated a lot of the theory on which it is based.  Theoretical results become much harder to obtain as soon as you include
learning the kernel.
Having said which (IMHO) the main reason that the SVM works so well is that it really encourages us to think about regularisation and doing something (SRM) about over-fitting.  That doesn't really rely too heavily on the theoretical justification.


ListView e AniIndicator

Question: Se alguém puder dar um help, Estou com o seguinte problema : Tenho dois componentes em uma form, um ListView e um AniIndicator, estou carregando os dados do ListView em blocos vindos do banco de dados conforme a demanda. gostaria que o AniIndicator fica-se rodando enquanto carrega os registros, mas o AniIndicator para de rodar quando carrego novos registros no ListView, já tentei fazer com Thread mas não consegui. Se alguém tiver uma luz.
Comment: já possui algo programado? Mostra para nós como esta carregando os dados.
Answer: Fiz o código abaixo de teste e deu tudo certo, tente utilizar a procedure Application.ProcessMessages durante o loop do carregamento dos dados no TListView
Segue:
procedure TesteAniIndicator;
var
  I: Integer;
begin
  AniIndicator1.Visible := True;
  AniIndicator1.Enabled := True;
  try
    for I := 0 to 1000 do
    begin
      Sleep(10);
      Application.ProcessMessages;
    end;
  finally
    AniIndicator1.Enabled := False;
    AniIndicator1.Visible := False;
  end;
end;

ListView e AniIndicator


PowerBuilder 12.NET automated builds using Nant

Question: Can someone please shed some light on different possibilities of build automation for, PB 12.NET applications. Since PB is .NET, can tools like NAnt or CruiseControl (with MSBuild) can be used to build and deploy the applications.
Basically, Can it be ORCAScript /  ECrane PowerGEN independent.
Comment: Have you tried using anything to automate your builds?
Comment: @Bernad Yes I do, that was long time back. Used combination of ANT & ORCAScript to create build and deploy.
Answer: I'm usually wary of "never say never", but I'm pretty sure your answer is no.
To call the PowerBuilder compiler, you need to call PB's ORCA API. The IDE does that. ORCAScript provides you a command line interface to that. PowerGen provides a GUI front end (and lots of additional functionality) to that.
However, I'd expect you could use ORCAScript or PowerGen from these tools. For example, here's a blog post describing leveraging ORACScript in CruiseControl with NAnt. PowerGen has a very robust set of command line options, and will give you more power and opportunities from the command line (e.g. PBL optimization, more efficient bootstrapping).
Good luck,
Terry.
Comment: thanks for the inputs, Now I clearly understand that we need to have ORCA API's to build PB applications, be it be, PB 12 classic or '.NET' edition. Since PB 12 '.NET' edition stores PB Objects quite differently, I think this will make bootstrapping less complicated.
Comment: What about using the command line arguments to the PB executable? Do those still exist in PB 12?  In 10.5 we use those to build projects such as: `pb105.exe /w myworkspace.pbw /t mytarget.pbt /deploy /ou logfile.txt`


Python game encountering random lag spikes

Question: For the first time ever, I tried my hand at creating a pretty simple game, pong. I did this using turtle and figured it out by using a mixture of searching online, previous knowledge, and some stack overflow questions, and for the most part, it's working perfectly. However, when running the game, I seem to encounter the occasional lag spike where the game will slow down by nearly 50%, and then all of a sudden go to 150%. I have a decent laptop, but even so, for a game this size, this shouldn't be happening, any idea why? The audio also seems to be delayed slightly too.
If you want to try it with the font + audio files: https://github.com/JamesJ42/PythonPong
# My attempt at pong (atari game)

import turtle
import winsound

wn = turtle.Screen()
wn.title("Pong")
wn.bgcolor("black")
wn.setup(width = 800, height = 600)
wn.tracer(0)

# Score
player_1_score = 0
player_2_score = 0

# Paddle A
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.color("white")
paddle_a.shapesize(stretch_wid = 5, stretch_len = 1)
paddle_a.penup()
paddle_a.goto(-350, 0)

# Paddle B
paddle_b = turtle.Turtle()
paddle_b.speed(0)
paddle_b.shape("square")
paddle_b.color("white")
paddle_b.shapesize(stretch_wid = 5, stretch_len = 1)
paddle_b.penup()
paddle_b.goto(350, 0)

# Ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape("square")
ball.color("white")
ball.penup()
ball.goto(0, 0)
ball.dx = 0.1
ball.dy = 0.1

# Pen
pen = turtle.Turtle()
pen.speed(0)
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
pen.write("PLAYER 1: 0  PLAYER 2: 0", align = "center", font = ("EightBit Atari", 24, "normal"))

# Finish game
finish = turtle.Turtle()
finish.speed(0)
finish.color("white")
finish.penup()
finish.hideturtle()
finish.goto(0, 240)
finish.write("FINISH GAME: SHIFT + Q", align = "center", font = ("EightBit Atari", 10, "normal"))

# Functions
def paddle_a_up():
    y = paddle_a.ycor()
    y += 20
    paddle_a.sety(y)

def paddle_a_down():
    y = paddle_a.ycor()
    y -= 20
    paddle_a.sety(y)

def paddle_b_up():
    y = paddle_b.ycor()
    y += 20
    paddle_b.sety(y)

def paddle_b_down():
    y = paddle_b.ycor()
    y -= 20
    paddle_b.sety(y)

def exit_game():
    turtle.bye()

# Keyboard binding
wn.listen()
wn.onkeypress(paddle_a_up, "w")
wn.onkeypress(paddle_a_down, "s")
wn.onkeypress(paddle_b_up, "Up")
wn.onkeypress(paddle_b_down, "Down")
wn.onkeypress(exit_game, "Q")

# Main game loop
while True:
    wn.update()

    # Move the ball
    ball.setx(ball.xcor() + ball.dx)
    ball.sety(ball.ycor() + ball.dy)

    # Border checking
    if ball.ycor() > 290:
        ball.sety(290)
        ball.dy *= -1
        winsound.PlaySound("wall.wav", winsound.SND_ASYNC)

    if ball.ycor() < -290:
        ball.sety(- 290)
        ball.dy *= -1
        winsound.PlaySound("wall.wav", winsound.SND_ASYNC)

    if ball.xcor() > 390:
        ball.goto(0, 0)
        ball.dx *= -1
        player_1_score += 1
        pen.clear()
        pen.write(f"PLAYER 1: {player_1_score}  PLAYER 2: {player_2_score}", align = "center", font = ("EightBit Atari", 24, "normal"))
        winsound.PlaySound("score.wav", winsound.SND_ASYNC)

    if ball.xcor() < -390:
        ball.goto(0, 0)
        ball.dx *= -1
        player_2_score += 1
        pen.clear()
        pen.write(f"PLAYER 1: {player_1_score}  PLAYER 2: {player_2_score}", align = "center", font = ("EightBit Atari", 24, "normal"))
        winsound.PlaySound("score.wav", winsound.SND_ASYNC)

    # Paddle and ball collisions
    if (ball.xcor() > 340 and ball.xcor() < 350) and (ball.ycor() < paddle_b.ycor() + 40 and ball.ycor() > paddle_b.ycor() - 40):
        ball.setx(340)
        ball.dx *= -1
        winsound.PlaySound("paddle.wav", winsound.SND_ASYNC)

    if (ball.xcor() < -340 and ball.xcor() > -350) and (ball.ycor() < paddle_a.ycor() + 40 and ball.ycor() > paddle_a.ycor() - 40):
        ball.setx(-340)
        ball.dx *= -1
        winsound.PlaySound("paddle.wav", winsound.SND_ASYNC)

Answer: I found some Pygame documentation on my computer. It had some advice from David Clark, where he suggested you add .convert_alpha() at the end of all Pygame image loads. This increased my framerate from 9 to 32
or even try using Pyglet
Comment: How is Pygame related to Python turtle?
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: I wasn't able to reproduce the lag spike problem on my slow laptop, but I'm guessing it's due to the while True: busy loop and the tiny step size here:
ball.dx = 0.1
ball.dy = 0.1

What seems to be happening is the render loop is running (or trying to run) as fast as possible, moving the ball a very small amount on each step. On a fast machine, this achieves the correct feel for the game speed, but on slower machines (like mine), the game runs at a snail's pace (it takes 10 seconds or so to get the ball across the screen once).
Although it's not likely to be perfectly consistent for all machines, if you use ontimer and a faster movement speed for the ball, you can take control of the framerate and ensure the process isn't just maxing out all of its CPU time trying to render as many frames as possible. Hopefully, this will reduce lag spikes that might be caused by periodic scheduling anomalies and interruptions.
# ...
ball.dx = 7  # bigger step per frame
ball.dy = 7
# ...

# Main game loop
def tick():
    # not the greatest practice; TODO convert to a function
    global player_1_score
    global player_2_score

    # Move the ball

    # ...

    wn.update()
    wn.ontimer(tick, frame_delay_ms)

frame_delay_ms = 1000 // 30
tick()
turtle.mainloop()

If this runs abnormally fast or slow on your machine, I'd be curious to hear. It can be improved to render frames at a fixed rate by checking the delta time between frames, but I'll assume it's good enough until I hear otherwise.


How To Install Git Daemon on Ubuntu 10.04 Linux with SparkleShare (and use it like Drop Box)

Question: I tried following this doc...
https://help.ubuntu.com/community/Git
...but unfortunately the "initialKeyFileName" step is not explained.
Answer: It says on the top:

You already have a public ssh key on your local machine you can use that to initialize the repository. Don't have one? Look here.

The linked article is great, should be no problem to follow it.
Comment: Wow. I missed that. Need to slow down a bit.
Answer: Sparkle Share – Git server   installation in Ubuntu 10.04
I am starting with an empty Ubuntu server 10.04 with just openssh installed. I assuming that you can access you server from http://mydomain.com
Install Git
aptitude build-dep git-core
apt-get install git-core
git --version   #(not necessary just to insure that is installed)

Add user git
adduser --disabled-password git
git init --bare /home/git/MyProject  #(your projects folder, named as you like)

Make a key file in order to login without a password
mkdir /home/git/.ssh
touch /home/git/.ssh/authorized_keys

Edit file /home/git/.ssh/authorized_keys and paste your key. You can find it your projects file as .txt file at The client side.
pico /home/git/.ssh/authorized_keys

Change owner and permissions on files
chmod 700 /home/git/.ssh
chmod 600 /home/git/.ssh/authorized_keys
chown -R git:git /home/git

Add your server in client
mydomain.com      ,        /home/git/MyProject

Answer: I've create a document here about install git on Debian box, i think that you may follow the same step on a Ubuntu


value of the local variable

Question: I was messing around with some PHP codes and found this which baffles me
DisplayButton($width, $name, $url, $judge);

public function DisplayButton($width, $name, $url, $active = true)
{
if ($active)
{
  echo "

        $name	";
}
else
{
  echo "

        $name	";
}
}

how could you define a parameter like $active=true in this case, because as I believe that the value of the passed boolean variable $judge(either true or false) is going to be forced to change to true because of the $active= true, so how could it possibly reach to the else statement? I probably misunderstood the argument $active=true, but how? Thank you very much
Answer: Pass false, not true to reach that else block
$active = true at function declaration means that parameter is optional, so you can omit it while call the function. But if you pass it, then default value doesn't affect in any way.

value of the local variable


Como compartilhar dados de uma aplicação web?

Question: Eu tenho o seguinte problema, tenho uma aplicação feita em (HTML, CSS JS, JQuey) outra aplicação está em ReactJS, nessa primeira aplicação ela está hospedada e em um dominio diferente por exemplo https://exemplo-a.com.br/ e a outra está em https://exemplo-b.amazonaws.com, localmente foi feito um teste passando os dados pelo cookies e funcionou, porém pesquisando vimos que não é possivel compartilhar dados entre dominios diferente em cookies, tem alguma outra maneira de resolver esse problema de compartilhamento ?
Answer: Acredito que o ideal seja utilizar/criar um banco de dados em um servidor, para manipular essas informações e com uma API você armazena as informações que você captar em um domínio e faz a request dessas informações no outro domínio. Acredito que essa seja a melhor alterantiva, ainda mais se os dados que precisarem ser manipulados forem sensíveis.


Operations based on conditional values from differents columns

Question: My dataset is such, Unitatsconsum_2021:
structure(list(NUMERO = structure(c(15, 16, 16, 17, 17, 18, 18,
19, 19, 19, 20, 20, 20, 21, 21, 21), format.stata = "%12.0g"),
    edat = c(41, 84, 53, 66, 65, 73, 72, 62, 60, 34, 54, 52,
    24, 48, 12, 17), membres = c(1L, 2L, 2L, 2L, 2L, 2L,
    2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L)), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -16L), groups = structure(list(
    NUMERO = structure(c(15, 16, 17, 18, 19, 20, 21), format.stata = "%12.0g"),
    .rows = structure(list(1L, 2:3, 4:5, 6:7, 8:10, 11:13, 14:16), ptype = integer(0), class = c("vctrs_list_of",
    "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -7L), .drop = TRUE))

And I want to create a new variable, say unitats_consum, which should be equal to:
1 + 0.5*((membres if edat>13)-1) + 0.3*(membres if edat>=13)
And the result should be shared by NUMERO, so each identical NUMERO should have the same unitats consum.
So far, I have tried this:
Despesa_unitatsconsum_2021 <- Despesa_membres_llar_2021 %>%
group_by(NUMERO) %>%
  mutate(unitats_consum = (1 + 0.5*((membres if edat > 13)-1) + 0.3*((membres if edat <= 13))))

I can't find which operator works as if and how this operatio can be grouped by NUMERO. Any help will be very appreciated.
Comment: You may need `ifelse` or `case_when` i.e. `Despesa_membres_llar_2021 %>% mutate(unitats_consum = ifelse(edat > 13, 1 + 0.5 *(membres -1), 0.3 *(membres)))`
Answer: To create the new variable 'unitats_consum', you can use the 'ifelse' statement within mutate function. But the condition must be indicated correctly:
Despesa_unitatsconsum_2021 <- Despesa_unitatsconsum_2021 %>%
  mutate(unitats_consum = 1 + 0.5 * ifelse(edat > 13,
  membres - 1, 0) + 0.3 * ifelse(edat <= 13, membres, 0))

Despesa_unitatsconsum_2021

   edat membres unitats_consum
40   73       1            1.0
41   73       1            1.0
42   73       1            1.0
43   73       1            1.0
44   73       1            1.0
45   73       1            1.0
46   44       2            1.5
47   44       2            1.5
48   44       2            1.5
49   44       2            1.5
50   44       2            1.5


adb logcat returns "Logcat read failure"

Question: After noticing that Logcat messages were not showing up in Android Studio, I tried every solution out there, and nothing worked. I eventually tried the command adb devices and sure enough my device was there, but as soon as I tried adb logcat it returned "logcat read failure".
Developer settings are turned on, and so it debugging. I'm on a rooted phone running 7.0 Nougat, with an open bootloader.
Could it be that I'm rooted and it somehow messed up some permissions? I've never encountered this issue before, even on a rooted phone.
Logcat works when using an emulator.
Comment: Have you tried plugging it out and in again? Serious question. Is the cable working properly with other devices ?
Answer: Did you try to use alogcat ROOT app.  Is it work on the device? App link
Comment: Installed it, gave it root access, and still nothing shows up. Blank screen.
Answer: I was facing the same issue as yours. Then I asked the developer of the ROM if he is facing the same issue. The developer said that it is working fine for him. So I flashed the ROM again and noticed that logcat was properly working. So it was clear that the problem was due to some apps or changes that I did on the ROM.
After debugging , I found that it was ARISE Sound System that was the root cause of this problem for me.
So if your are using ARISE Sound System dirty flash the ROM to remove it and check if this solves the problem for you. For now I am only using Viper4Android.
Comment: Oh man, I was so pumped to read your reply as I did have ARISE installed, but unfortunately it did not solve my problem.. I dirty flashed, and now I do not have ARISE, and I'm still receiving the "logcat read failure"..
Comment: I did another dirty flash to remove the root, and I only used it for ARISE, and it works now!! So the root was the cause of the problem!
Comment: Hi, I had the same problem and I did the same than you removed ARISE, but now I don't have notifications sounds :(
Comment: So, what if they don't using ARISE Sound system? Does it mean that answer is not correct?
Answer: So, post here right answer because I spent a such many time to solve this.
Ok, when in Android Studio I start debug an app on real Smart TV device I saw in logcat nothing. When I ran "logcat" on device directly I got "logcat read failure"
A year before I removed "logd" from "system/bin" and this was a problem.. but I forgot about it. Even if I've copied it back it doesn't work. Because SELinuxe Security Context
Solution: give the logd it's context back with a chcon util.
More details you can find here: https://forum.xda-developers.com/t/guide-how-to-restore-logd-to-your-device-fix-adb-logcat-read-failure-or-empty-logs.3512946/#post-69930494


Does $e^{xy}=(e^x)^y$ hold when $x$ and $y$ are real?

Question: The question is as above.
Does $e^{xy}=(e^x)^y$ hold when $x$ and $y$ are real?
I remember that the answer is yes but am a little bit not confident. I know that the equality fails when $x$ an $y$ are extended to complex numbers(there is an issue of branch cut). Am I right?
Comment: Hint for real numbers: take the natural log of both sides.
Comment: What is your definition of $e^x$ for real numbers $x$? The solution will depend heavily on how you define it (although the answer will likely be the same in either case).
Answer: Definition: for $a>0$ and any complex $b$, let $a^b$ be:
$$a^b=\exp(b\log a)$$
Therefore, for $a>0$, real $x$ and complex $y$,
$$(a^x)^y=\exp(x \log a)^y=\exp(y \log[\exp(x \log a)])=\exp(xy\log a)=a^{xy}$$
This can't apply to all complex $x$ because you need $\exp(x\log a)$ to be a positive real number to apply the definition above. And the definition does not work for complex or negative $a$ because of a branch problem with the logarithm.
Note that to write $(a^x)^y=(a^y)^x$, you need both $x$ and $y$ to be real.

Note also: $e^x$ is often an abuse of notation for $\exp(x)$, which is a function (defined on $\Bbb C$ and entire). The notation $e^x$ is "correct" because you can check easily with the definition above that $e^x=\exp(x)$. However, if you don't define the power function $a^b$ beforehand, the notation $e^x$ is meaningless.
It's a kind of circular reasoning: you would need to define $e^x$ first, in order to define $a^b$. Actually, you define $\exp(x)$ first, then $a^b$, then you can check $e^x=\exp(x)$. And that's true for every complex $x$.
But there are other ways to define $a^b$ that don't depend on the exponential. IIRC, there is something starting from Dedekind cuts: I saw this in a book once, if someone has the reference, I would really like to know!


Role of misspecification by biased data in the generalization error

Question: I am confused with the role that model misspecification plays in the generalization error, in particular when the misspecification is due to a biased (non representative) training dataset. To clarify what I mean, imagine a non-representative sample where there seems to be a linear pattern when in fact the pattern is more complex in the population. If we base our modeling decisions on that sample we might decide for a linear model and, as a result, misspecify the model. So, some doubts I have:

My understanding is that the bias and variance in the error decomposition are properties of the predictor and not the data. However, the training data causes bias error, which seems to indicate that the data does play a role in the decomposition. Is it that the decomposition assumes that the data is always representative of the population? In other words, it does not take into account biases in the data such as sampling bias or omitted variables.

The other question I have is that it is not clear that biased data only causes bias error (misspecification) but also variance. My reasoning is that if we had chosen another training sample (one without the biases), our predictor would have made better predictions, indicating that there is variance error, too.

I think my misunderstanding is on the assumptions of the learning paradigm: for instance, that biases in the data are out of the picture when talking about variance and bias of the model, but I would like to confirm it and shed some light on these questions.
Answer: Bias in a model can be due to many factors. From what I understand, you maybe talking about sampling bias. It Happens when the training data doesn't accurately represent the environment the program is expected to run into.
It is not possible to train a model on the entire universe of data, rather data is assumed to be sampled from the population. There is science behind sampling the training data that is both large enough and representative enough to mitigate sample bias and must come from the same population density. In your case, the data seems to be from different population densities which contradicts the assumption of machine learning theory i.e training data should be sampled from the same population. and hence will never generalise.
The machine learning theory is based on the assumption that there exists a true function g(x) (which we don't need to know) and our goal is to come up with a hypothesis f(x) which approximates g(x) on the sampled dataset. Bias and variance in error decomposition both are dependent on your choice of hypothesis f(x) and the true function g(x) of the population.

Bias occurs when your hypothesis is far from the true function. Even if you have representative data and not using the right hypothesis, you will have high bias. For ex: if you are using linear hypothesis to model a non-linear function.

Variance occurs when you have large pool of hypothesis(high model complexity) which makes it difficult to navigate to the true function resulting in higher variance. For ex: using a polynomial regression to model a linear relationship.

For a deeper understanding check out: https://www.youtube.com/watch?v=L_0efNkdGMc
This is one of the best resource for machine learning theory.


Bold text from exposed filters

Question: I'm using an exposed filter in views to find nodes that contain that word in the body field.
I would like to show that word in the body in bold.
Answer: You can achieve this using search_excerpt function.
for eg:
in your views tpl file add the following code
<code> <?php foreach ($rows as $id => $row):

      $keys = $_GET['body_value'];
      $row = search_excerpt($keys, $row);
 ?>
</code>
it will highlight the searched word, see the screenshot below

Bold text from exposed filters