If $f:X\to S^n$ is continuous and $v_0\in S^n$, can we find $F:X\to O(n+1)$ such that $F(x)v_0=f(x)$ for all $x$?

Question: The set $O(n+1)$ of orthogonal matrices acts transitively on $S^n\subseteq\Bbb R^{n+1}$, meaning that for every $x,y\in S^n$ there is a matrix $A\in O(n+1)$ such that $Ax=y$.
Now suppose that $X$ is a topological space and that we have a continuous map $f:X\to S^n$. If we fix $v_0\in S^n$, the transitivity of $O(n+1)$ means that to every $x\in X$ there exists $A_x\in O(n+1)$ such that $A_xv_0=f(x)$.

Question: Can we chose the matrices $A_x$ in such a way that the map
  $$F:X\to O(n+1),\quad x\mapsto A_x$$
  is continuous?

It would be sufficient to show that the evaluation map
$$\Phi:O(n+1)\to S^n,\quad \Phi(A)=Av_0$$
has a continuous right inverse
$$\Psi:S^n\to O(n+1).$$
In that case we can take $F=\Psi\circ f$.
Comment: I updated my answer a little bit. In particular, this is true for $n=3$, though I don't know an explicit section.
Answer: Your question is actually equivalent to the existence of a right inverse, by taking $X = S^n$.
Not necessarily. Pick $f: S^2 \to S^2$ to be the identity map, and suppose you had a lift $F: S^2 \to O(3)$. Because $\pi_2 O(3) = 0$, this lift is null-homotopic. Then projecting the null-homotopy down to $S^2$, we obtain a null-homotopy of the original map; that's nonsense, as the identity map $S^2 \to S^2$ induces an isomorphism on second homology.
For $n = 1$, this is true, because the action you've defined $SO(2) \to S^1$ is a diffeomorphism.
This is, however, occasionally true. One particular case is $n=3$; we may think of $SO(n+1) \to S^n$ as a principal $SO(n)$-bundle, and a section of this bundle is the same thing as a trivialization of the bundle. $G$-bundles over $S^n$ are classified by homotopy classes of maps from the equator $S^{n-1} \to G$; this construction is known as clutching functions. But in particular $\pi_2 SO(4) = 0$, so that this bundle actually is trivial for $n=3$.
Answer: The right inverse idea you and Mike mentioned is spot on.
Call a sphere $S^n$ special if for every continuous $f:X\rightarrow S^n$, there is a continuous $F:X\rightarrow O(n+1)$ as you've defined it.
Then we have the following theorem:

$S^n$ is special iff $n = 0,1,3,$ or $7$.

Proof:  As mentioned by Mike, $S^n$ is special iff there is a right inverse to the canonical map $O(n+1)\rightarrow S^n$.  But the projection map $O(n+1)\rightarrow S^n$ actually gives $O(n+1)$ the structure of a principal $O(n)$ bundle over $S^n$.  In the context of bundles, the name "right inverse" usually goes by the name "section".
Luckily, it's not too hard to show that a principal bundle has a section iff it's trivial.
Thus, we've shown $S^n$ is special iff the principal bundle $O(n)\rightarrow O(n+1)\rightarrow S^n$ is actually trivial.  But a manifold has a trivial frame bundle iff it is parallelizable.  According to Adams, this occurs iff $n=0,1,3$, or $7$.$\square$
As far as getting an explicit $\Psi$, for $S^0$, we have $O(1) = S^0$, so that's easy.  Further, $O(2)$ is two disjoint copies of $S^1$, so just map $S^1$ to the component of $O(2)$ containing the identity.  (That is, use $SO(2)\subseteq O(2)$ as Mike suggested).
But here is a method that works on all $4$ cases simultaneously.  Let $\mathbb{K}\in \{\mathbb{R}, \mathbb{C}, \mathbb{H}, \mathbb{Ca}\}$, (corresponding to $n=0,1,3,7$ respectively) where the last two are the quaternions and octonions.
Let $e_i\in \mathbb{K}$ denote the vector whose $i$th entry is $1$ with all other entries $0$.
Start by defining $\Psi:S^n\rightarrow O(n+1)$ with $\Psi(e_1)$ to be the matrix in $O(n+1)$ with columns given by $e_1,e_2,..,e_n$, which is just a complicated way of saying $\Psi(e_1) = I$.
Now, given $p\in S^n\subseteq \mathbb{K}$, define $\Psi(p)$ to be the matrix in $O(n+1)$ whose columns are $pe_i$. (In fact, the image is is $SO(n+1)$)
Comment: I managed to forget that this is precisely the frame bundle! Darn.


Como assim "Empty DataFrame"?

Question: Estou aprendendo e fazer uma lição da minha faculdade.
Meu professor pediu usar filtros de tabela de formato .csv usando o comando .query()
Então original é assim:
    Funcionario Escolaridade Genero  Idade  Meses  Salario
1     Fundam.2      M     37      0    16790
2     Superior      M     33     14    15460
3     Fundam.1      F     39     57     4690
4     Superior      F     56     36    18760
5     Fundam.1      F     48      1    10580
6     Fundam.2      F     50     84    18030
7     Fundam.2      F     60     21    15040
8     Fundam.2      F     66     40     6200
10    Fundam.2      F     27     68     4470
11    Fundam.2      F     45     94     2900
12    Fundam.1      M     57     99     6590
13    Fundam.2      M     23      7    15460
14    Fundam.2      F     23     30    11330
15    Superior      M     59     91     6580
16    Fundam.2      O     28     60    18260
17    Fundam.1      F     71     75     4700
18    Fundam.2      F     49     33     3840
19    Fundam.1      M     43     48     2320
20    Fundam.2      M     57     23     7250

Eu criei uma aplicação para filtrar com query.("Idade == 47" or "Meses > 44")
Então meu professor pediu a deve exibir colunas em ordem assim: "Idade", "Meses", "Funcionario", "Genero".
Eu programei assim:
import pandas as pd

dn = pd.read_csv("fake-file14.csv", sep = ",")

x = dn.query("Idade == 47" or "Meses > 44")

df = x[['Idade', 'Meses', 'Funcionario', 'Genero']]

print(df)

Isso apareceu:
Empty DataFrame
Columns: [Idade, Meses, Funcionario, Genero]
Index: []

Como assim? Por que aconteceu assim? Já tentei muitas vezes...
OBS: Meu professor quer aparecer assim:
Idade  Meses  Funcionario Genero
2      39     57            3      F
5      50     84            6      F
9      27     68           10      F
10     45     94           11      F
11     57     99           12      M
14     59     91           15      M
15     28     60           16      O
16     71     75           17      F
18     43     48           19      M

Answer: Me parece que o problema é a query:
x = dn.query("Idade == 47" or "Meses > 44")

Isso esta fazendo um or entre 2 strings e mandando o resultado para a query,
ou seja, se você colocar isso em um print esse vai ser o resultado
print( "Idade == 47" or "Meses > 44" )
> Idade == 47  # output

Como parece não ter nenhum registro com Idade == 47 o resultado é um DataFrame sem registros.
Como deveria ser:
x = dn.query("Idade == 47 or Meses > 44")

Veja funcionando no ideone, e no repl.it.

Uma outra forma de fazer essa busca:
x = dn[  (dn['Idade'] == 47)   |   (dn['Meses'] > 44)   ]
#               ↑              ↑          ↑
#         tabela verdade 1     |    tabela verdade 2
#                              |
#                   'OR' operador bitwise

Referencia: pandas.DataFrame.query

Como assim "Empty DataFrame"?


Is there any way to get user-wise list of flags?

Question: I want to do an analysis on our site on moderator aspect. I want to see the user lists who are flagging most (asc or desc order). Is that possible to view ?
Comment: have updated my answer with a working link
Comment: Are you talking flags or close votes?
Comment: @DavidManners flags.
Answer: you will probably find something for it on https://data.stackexchange.com/magento/queries
It may be a bit more complicated to build a query giving you exactly what you want.
Update
have build the Query for this
https://data.stackexchange.com/magento/query/351905/flags-per-user
Comment: I already checked and the only flag related data there is `PendingFlags`, so I guess that means "No".
Comment: Thanks for this. :)
Answer: Not sure maybe a mod could get a list but there are badges for flags so you could get a slight idea as to who flags and how often.


Does upgrading a server improve performance on low traffic site?

Question: I wish to use migrate to a Amazon's AWS EC2 instance for a basic Wordpress site running woocommerce.
However, I am torn between t2 and m3 instances: https://aws.amazon.com/ec2/instance-types/
My question is does a basic website with low traffic for a server that barely reaches 10% CPU at peak times, actually benefit from upgrading to a better server?
From my understanding, better machines are only beneficial if you have more traffic or your server or has high CPU usage. In which case, any upgrades to the server would be negligible.
Thanks for the help!
Answer: Probably not. What would work better is some optimisation:

Get your headers in order, especially around browser caching. Note that you don't need PRAGMA and should clear it, you just need Cache-Control. Static resources to > 7 days.
Set up the nginx page cache. If you're using Apache it has one too. If all your users are logged in this won't help, but if even a fraction are anonymous (eg Google) then it will help. If the site changes rapidly then microcaching is still valuable.
Get a CDN, CloudFlare has a free tier that's effective. It's critical to have your caching headers set up correctly before using a CDN otherwise you'll get no benefit

I have an article on server tuning for Wordpress/Nginx here, but much of it will apply to other situations. The two tutorials following that are for HTTP2 and Let's Encrypt, which will make things faster, and CloudFlare setup. SF prefers resources copied into the answer, but they're just too large to copy in.
By doing everything I described my page load time for Wordpress is usually around 1.5 seconds, and that's with the server on the other side of the world from the client.
Answer: The higher CPU and RAM resources definitely improve the processing speed of the server. If your site has more/complex SQL queries to run, which need more CPU and RAM usage, you can go with the high resources. Otherwise, additional resources will not be beneficial to you.


Modularização sem OSGI em projeto Web

Question: Tenho um projeto que será razoavelmente grande, então seria bem interessante modularizar, eu sei, existe o OSGi, mas eu achei muito complexo e tive dificuldade para adaptar a minha aplicação, a impressão que tive é que vai complicar mais do que facilitar a manutenção,é arrodeio demais simplesmente para usar uma classe que está em um jar separado através de uma interface, então estou pensando em fazer através de ClassLoader,  a estrutura que eu penso é a seguinte
Projeto Core
package core;

public interface IModulo {
<T> T getString();
}

Projeto Modulo exemplo
package modulo1;

import core.IModulo;

public class Teste implements IModulo{

public <T> T getString() {
    return (T) "Hello";
}
}

Projeto principal, onde será "instalado" os módulos, esse projeto principal já tem o projeto Core como dependência, ou seja, a interface IModulo já está no classpath, se eu executar através de um simples classe main, funciona, mas pelo Tomcat não, veja o trecho de código
  import core.IModulo;
   public class Main {
public static void main(String[] args) {

    try {
        String jarDoModulo = "C:\\modulo1.jar";
        File file = new File(jarDoModulo);
        URL url;
        url = file.toURL();

        URL[] urls = new URL[] { url };
        ClassLoader cl = new URLClassLoader(urls);
        Class<IModulo> cls = (Class<IModulo>) cl.loadClass("modulo1.Teste");
        IModulo modulo1 = cls.newInstance();
        System.out.println(modulo1.getString());

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}

O erro que aparece é
Caused by: java.lang.ClassNotFoundException: core.IModulo
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
... 60 more

Comment: Olá Rodrigo, eu troquei a tag [tag:java-ee] pela [tag:tomcat] para tentar te ajudar a atrair mais respostas. Cada *container* possui suas especificidades de configuração de recursos e *ClassLoaders*. Além do que o Tomcat é um caso especial que não chega nem mesmo a ser um servidor de aplicação Java EE, é apenas um *container* Servlet / JSP.
Answer: Pelo que entendi seu requisito é basicamente separar implementações de determinadas interfaces do core. Estas implementações ficam em projetos jar à parte do seu projeto web principal.
O problema em que você esbarrou acontece pois o Tomcat possui sua própria hierarquia de class loaders.
Da forma que seu código foi escrito, dentro do Tomcat o IModulo será administrado por um WebappClassLoader e a classe Teste pelo seu URLClassLoader (que não possuí nenhuma instância de IModulo carregada, logo, dispara uma exceção).
Existem dois caminhos recomendados aqui:

Coloque o modulo1.jar na pasta WEB-INF/lib do seu projeto principal. Dessa forma as classes do seu módulo estarão disponíveis para a aplicação e você não precisará nem mexer com class loaders. A modularidade ainda é mantida no sentido de ser possível trocar a implementação do módulo sem alterar a aplicação core.
Usar ou escrever um ClassLoader personalizado (se você realmente quer deixar seu módulo em um local non-standard). Até o Tomcat 7 você poderia usar um VirtualWebappLoader para disponibilizar o jar do seu módulo; a partir do Tomcat 8 você pode usar o recurso de PreResources.
Comment: Entendi Anthony, realmente acaba sendo um código complexo e OSGi deve não ficar tão complexo assim, bem, primeiramente eu estou organizando a infra do meu projeto, onde eu já realmente separo fisicamente os módulos, olha, incrivelmente o código do projeto ficou limpinho e muito fácil de entender, extender, testabilidade etc... impressionante a modularização o quanto facilita, no caso ele está "modularizado" mas não com hotdeploy, acredito que com calma, tentando aplicar o OSGi em cima da minha estrutura que fiz agora, a coisa fique mais clara.
Comment: O problema da solução 1 é que eu teria que derrubar o tomcat e refazer o deploy para adicionar um modulo, com o classLoader penso eu, que eu posso "instalar" o jar em runtime e utilizá=lo em ter que parar o tomcat, estou certo?
Comment: Olá Rodrigo. Você não precisa derrubar o Tomcat, mas devido a própria natureza dos *class loaders*, precisará sim fazer um reload da aplicação. Configurar o Tomcat para ler novas versões de um .jar no `WEB-INF/lib` é questão de colocar um `reloadable="true"` no [context.xml](http://tomcat.apache.org/tomcat-8.0-doc/config/context.html). Nesse processo ele "reabrirá" a aplicação (como se você tivesse dado um `touch` no `web.xml`) descartando o antigo `ClassLoader` e abrindo um novo com todos os recursos do seu novo jar.
Comment: Você ainda pode fazer uma cópia de toda a pasta da sua aplicação, substituir apenas o jar e fazer um [deploy paralelo](http://tomcat.apache.org/tomcat-8.0-doc/config/context.html#Parallel_deployment) para evitar indisponibilidade para clientes consumindo versões antigas da aplicação.
Comment: Se mesmo um *reload* em ambiente versionado não atende seus requisitos eu diria para ir de OSGi mesmo. Substituição de classes a quente requer código não trivial (localizar todas as referências antigas de determinada classe, descartá-las, substituí-las por uma nova versão mantendo o estado das variáveis compatíveis, forçar GC do antigo `ClassLoader` para evitar *leaks*, etc).
Comment: Você vai acabar descobrindo que precisará demarcar interfaces de importação e exportação, de um *container* para gerir os *class loaders*, de comandos para publicar, startar e parar módulos, etc. No fim das contas acabará com um mini Equinox ou Felix escrito na unha :) (meu ponto é; se você realmente precisa fazer swap de *bundles* em produção à quente, OSGi acaba não sendo uma solução tão complexa assim, esse tipo de coisa realmente requer código complexo de infraestrutura).

Modularização sem OSGI em projeto Web


Processing - Stop image from disappearing when selecting another

Question: I am able to select an image file from my computer using the 't' key in the keyPressed() function and display it on the screen, but when I press the 't' key again to select another image, the previous image disappears.
I would like my program to not have the image disappear when selecting and displaying another.
I would also like to have background() inside draw() as the image will leave trails of images whenever I move it with the mouse.
My code
PImage img;
int imgX, imgY;
int mX, mY;
String path ="";

void setup() {
    size(1000, 800);
}

void draw() {
    background(204);
    if(mousePressed){ // is the mousebutton being held?
        imgX = mouseX-mX;
        imgY = mouseY-mY;
    }
    if (img != null) {
        image(img, imgX, imgY);
    }
    text("Press 't' to load an image", 40, 100);
}

void handleImage(File selection) {
    if (selection== null) {
        println ("nono");
    }
    else {
        path = selection.getAbsolutePath();
        img = loadImage(path);
    }
}

void mousePressed()
{
    // set variables for holding mouseposition offset
    // to the image
    mX = mouseX-imgX;
    mY = mouseY-imgY;
}

void keyPressed() {
    if(key == 't') {
        img = null;
        selectInput("select an image", "handleImage");
    }
}

Comment: The image is not disappearing. The image just changes, because you have just 1 image (`img`). The entire scene is redrawn in every frame so you can just see the "current" image.
Answer: The image is not disappearing. The image just changes, because you have just 1 image (img). The entire scene is redrawn in every frame so you can just see the "current" image.
Create a class MyImage, which can draw an image and change the position of an image:
class MyImage {
    PImage img;
    int x, y;

    MyImage(PImage img, int x, int y) {
        this.img = img;
        this.x = x;
        this.y = y;
    }

    void changePosition(int dx, int dy) {
        this.x += dx;
        this.y += dy;
    }

    void draw() {
        image(img, x, y);
    }
}

Use an ArrayList to manage multiple images:
ArrayList<MyImage> images = new ArrayList<MyImage>();

Add a new image when t is pressed:
String path = selection.getAbsolutePath();
PImage image = loadImage(path);
images.add(new MyImage(image, 0, 0));

Draw all the images  in a loop
for (int i = 0; i < images.size(); i++) {
    MyImage img = images.get(i);
    img.draw();
}

Use the mouseDragged() event call back to drag the last image in the list:
void mouseDragged() {
    if (images.size() > 0) {
        images.get(images.size()-1).changePosition(mouseX-pmouseX, mouseY-pmouseY);
    }
}

See the example:

class MyImage {
    PImage img;
    int x, y;

    MyImage(PImage img, int x, int y) {
        this.img = img;
        this.x = x;
        this.y = y;
    }

    void changePosition(int dx, int dy) {
        this.x += dx;
        this.y += dy;
    }

    void draw() {
        image(img, x, y);
    }
}

ArrayList<MyImage> images = new ArrayList<MyImage>();

void setup() {
    size(1000, 800);
}

void draw() {
    background(204);
    for (int i = 0; i < images.size(); i++) {
        MyImage img = images.get(i);
        img.draw();
    }
    text("Press 't' to load an image", 40, 100);
}

void handleImage(File selection) {
    if (selection == null) {
        println ("nono");
    }
    else {
        String path = selection.getAbsolutePath();
        PImage image = loadImage(path);
        images.add(new MyImage(image, 0, 0));
    }
}

void mouseDragged() {
    if (images.size() > 0) {
        images.get(images.size()-1).changePosition(mouseX-pmouseX, mouseY-pmouseY);
    }
}

void keyPressed() {
    if(key == 't') {
        selectInput("select an image", "handleImage");
    }
}

Comment: @GeorgeProfenza Thank you. I use [ScrrenToGif](https://www.screentogif.com/). It's marvelous easy, but it's just for windows os.
Comment: @Rabbid76 very nicely explained answer (+1)! (silly question: what do you use to screen record gifs ?)


Erro ao definir um background em uma label e colocar uma imagem acima do background desta mesma label

Question: //html
<code> <label class="home-header icon-menu">
                <img src="arquivos/menu.svg">
            </label>
</code>
//css
<code>.icon-menu {
    position: relative;
    top: 0.5cm;
    left: 0.39cm;
    cursor: pointer;
    background: red;
}
</code>
Comment: Cara mas isso não é um background, é uma imagem dentro de uma label. Explica melhor o que está tentando fazer, se possível edita sua resposta e coloca tb uma imagem do layout que pretende fazer
Comment: Certo tem a imagem dentro da label. Então, eu gostaria de colocar um fundo na imagem. Por exemplo : Tem a label depois o background e por fim a imagem sob o background.
Answer: Olha, A forma que você está utilizando a imagem está errada. Para um Background, você vai precisar definir no css que aquela imagem é um background(sem necessidade de chama-la no html), também será necessário definir o comportamento da imagem dentro do container, segue código de exemplo.
ps: Se as classes estiverem sendo usadas por outras tags que você não quer aplicar o background, convem criar uma classe adicional ou ID para o objeto em questão.
html:
<code> <label id="backimg" class="home-header icon-menu"/>
</code>
css:
<code>#backimg {
position: relative;
top: 0.5cm;
left: 0.39cm;
cursor: pointer;
width: 50px; <!-- especificar um tamanho para a tag é importante -->
height: 150px;
background: url('c:/caminho da imagem') no-repeat;
}
</code>
Answer: Obrigado a todos que procuraram me ajudar nas respostas, eu fiz a pergunta da forma errada, agora editei para ficar mais claro. Com explicação do @hugocsl, fui testando no meu código e percebi que estava faltando colocar o display: inline block. Muito obrigado a todos. Me desculpem!


Override page template and preserve administration navigation bar

Question: Short version; I am trying to override the default page.html.twig (in D8) for a controller from my module and the following examples I've found have not worked:

https://www.drupal.org/node/2499827
Override html.twig.html within custom module

My company is developing a custom module to embed a React app we originally built for another system inside the admin side of Drupal. As such, we would like to keep the admin navigation visible but the main body of the page should just be the react app.
So far, I have successfully embedded the app as the content of a page, but still have the page's header, footer, breadcrumbs, etc. I'm not sure if I'm declaring my module's theme incorrectly, or if my naming is wrong for my template, or something else.

Thanks in advance!
Module name: my_module

my_module.info.yaml
name: Overriding page module
description: "Module with a template that overrides the default page.html.twig"
package: mystuff

type: module
core: 8.x

my_module.module

function my_module_theme() {
    $theme['page__my_module'] = [
        'template' => 'page--my_module',
    ];

    return $theme;
}

my_module.routing.yml
my_module.content:
  path: '/hello'
  defaults:
    _controller: '\Drupal\my_module\Controller\HelloController::content'
    _title: 'Hello World'
  requirements:
    _permission: 'access content'

templates/page--my_module.html.twig
{#
  Taken from https://api.drupal.org/api/drupal/core%21themes%21seven%21templates%21page.html.twig/8.2.x
#}

      {{ page.header }}

    {{ page.pre_content }}
    {{ page.breadcrumb }}

      {{ page.highlighted }}
      {% if page.help %}

          {{ page.help }}

      {% endif %}

WHY DOESN'T THIS TEMPLATE GET USED!?

      {{ page.content }}

src/Controller/HelloController.php
<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;

class HelloController extends ControllerBase {
    public function content() {
        return array(
            '#type' => 'markup',
            '#theme' => 'my_module',
            '#markup' => $this->t('Hello World!')
        );
    }
}

UPDATED
Thanks to @kiamlaluno, I found I could use the theme suggestions hook to tell drupal what theme to apply. I changed my_module.module to:
<?php

function my_module_theme_suggestions_page(array $variables) {
  $path = explode('/', trim(\Drupal::service('path.current')->getPath(), '/'));
  if (isset($path[0]) && $path[0] == 'hello') {
    return 'page--my-module';
  }
}

function my_module_theme() {
    $theme['page--my-module'] = [
        'template' => 'page--my_module',
    ];

    return $theme;
}

and removed the #theme item from the controller's render array. It works now!
Comment: I almost want to say the template name should be page--my-module.html.twig. At the same time, have you enabled twig debugging to see if this suggestion makes it into the source output of the page?
Answer: What the code is missing is the code that sets those variables the template file is using. Since you are using page--mymodule as template name, the module needs to implement template_preprocess_page__mymodule().
Alternatively, you can suggest a template file using hook_theme_suggestions_page().
function my_module_theme_suggestions_page(array $variables) {
  $path = explode('/', trim(\Drupal::service('path.current')->getPath(), '/'));
  if (isset($path[0]) && $path[0] == 'hello') {
    return 'page--mymodule';
  }
}

Implementing hook_theme_suggestions_page() like I show, page--mymodule.html.twig will get the variables set in template_preprocess_page(), which are the same variables passed to page.html.twig.
Comment: Hats off to you wise one! That was exactly what I needed.


Laravel Homested file upload performance issue

Question: I am having a wierd problem with Laravel Homestead. After following all the steps(with success) in Laravel website to configure Homestead and setting up a small project I'm facing the following problem:

When uploading an image with intervention\image package it takes forever, and doesn't matter if it is a small or a big image

Already tried a different config using Vaprobash with Nginx too and the upload is super fast.
Is anyone out there facing the same problem or have some solution for me? (Going crazy here)
Answer: If the upload folder is a shared folder on your host, then you may want to enable nfs if you haven't already. You can do that by changing the lines in scripts/homestead.rb about shared folder to this (note the `type: "nfs"' has been added):
# Register All Of The Configured Shared Folders
settings["folders"].each do |folder|
  config.vm.synced_folder folder["map"], folder["to"], type: "nfs"
end

More info can be found here: https://docs.vagrantup.com/v2/synced-folders/nfs.html.
Comment: Just to make sure: you did reprovision you Vagrant box, right?


Android Beacon Library - detect specific UUID only

Question: The Android Beacon Library documentation describes using setBeaconLayout
to match any beacon broadcasting a given BLE pattern of bytes.
This is more flexible than iOS, where we are restricted to finding only beacons for which we pass the specific UUID in advance, However, since this iOS restriction exists, I was wondering if it makes sense to impose the same limitation on ourselves in Android.
Is it possible to pass a specific UUID to setBeaconLayout or some other API so that didEnterRegion, etc. will only be called for a beacon with this specific UUID?
Examples for any protocol (AltBeacon, iBeacon, etc.) would be welcome.
Answer: Yes, you an add a ProximityUUID filter using the Android Beacon Library.  Here's an example:
<code>Region region = new Region("myMonitoringRegion",
                            Identifier.parse("2F234454-CF6D-4A0F-ADF2-F4911BA9FFA6"),
                            null,
                            null);
beaconManager.startMonitoringBeaconsInRegion(region);
</code>
The above will match any beacon that has proximityUUID 2F234454-CF6D-4A0F-ADF2-F4911BA9FFA6 with any value for major and any value for minor.


Fredholm operators in Hilbert spaces

Question: Suppose $T_r$ and $T_l$ are the left and the right translations in $l_2$. $T_l$ maps $(x_1,x_2,x_3,...)$ to $(x_2,x_3,x_4,...)$, $T_r$ maps $(x_1,x_2,x_3,...)$ to $(0,x_1,x_2,...)$. It can be easily seen that $T_r$ and $T_l$ are fredholm operators and $\mathrm{Ind}(T_l)=1$ and $\mathrm{Ind}(T_r)=-1$. Moreover it is easy to verify that $\mathrm{Ind}(T_l^k)=k$ and $\mathrm{Ind}(T_r^k)=-1$. So, for all $k\in \mathbb{Z}$ there is a bounded fredholm operator $l_2\longrightarrow l_2$ whose index is $k$. Could you tell me how to prove that statement with an arbitrary hilbert space?
Comment: A separable infinite-dimensional Hilbert space always admits a countably infinite orthonormal basis, does it not?
Comment: Yes, if $H$ is separable, than it will be isomorphic to $l_2$. But there are also non separable Hilbert spaces.
Comment: I think you meant $\mathrm{Ind}(T_r^k)=-k$.
Answer: Given an arbitrary (infinite-dimensional) Hilbert space $\mathcal H$, you can find an orthonormal sequence $x_n$ in it (inductively, by choosing a unit vector $x_n$ from $\{x_1,\dots,x_{n-1}\}^\perp$). Let $M$ be the closed linear span of $\{x_n:n=1,2,\dots\}^\perp$, and $N=M^\perp$. On the space $M$ you have the natural analogues of $T_l$ and $T_r$. They can also act on $\mathcal H$ by keeping the $N$-component of a vector unchanged. The Fredholm indices stay the same.

Fredholm operators in Hilbert spaces


ESXi networking occasionally fails on VM start

Question: On my ESXi 3.5 servers, I occasionally see a problem where - on newly started VMs - I see no traffic at all on their virtual network interfaces.  I have to go into the VM settings and remove, then re-add the network interfaces before I see any traffic.
Has anyone seen this before?  Is it possible I need to configure my physical switches (Cisco) differently to support this?
I'm using portgroups to present VLAN traffic to VMs - I've seen this happen on both trunked and untrunked ports, if that matters.
Answer: I have seen this before.
When I edit the settings and click on the network adapter, the Connect at power on is checked but not the Connected. So far all I needed to do was to check the Connected box and the interface will come up.
I have not seen this on ESXi 4 yet, but will keep an eye out. Maybe it is related to the adapter type.
Comment: I'll check these settings next time I see the problem.  Good to hear it may be ok in ESXi4 though.
Answer: Here's a theory.
You have VMotion enabled and the machine migrated to a host where the network that it was linked to do not exist.
When you now remove and add a network adapter, it picks up "VM Network" which works.
Comment: We're not using VMotion here.


Lang $SL_2$ two formulas for Harish transform

Question: Let $G = SL_2$ and give it the standard Iwasawa decomposition $G = ANK$. Let: $$D(a) = \alpha(a)^{1/2} - \alpha(a)^{-1/2} := \rho(a) - \rho(a)^{-1}.$$ Now, Lang defines ($SL_2$, p.69) the Harish transform of a function $f \in C_c(G,K)$ to be $$Hf(a) := \rho(a)\int_Nf(an)dn = |D(a)|\int_{A\setminus G} f(x^{-1}ax)d\dot x$$
My trouble is in understanding why the two definitions agree for $\rho (a)≠1$. In the second integral, we're are integrating over $A\setminus G$, so we can write $x = nk$, whence $$f(x^{-1}ax) = f((nk)^{-1}ank) = f(n^{-1}an) $$ since $f \in C_c(G,K)$, i.e. it is invariant w.r.t. conjugation by elements in $K$. But now, I don't know who to get rid of the remaining $n^{-1}$ and get the factor before the integral.
Answer: This equality is not at all obvious. Just before that section, it was proven that
$$
\int_{A\backslash G} f(x^{-1}ax)\;dx\;=\; {\alpha(a)\over |D(\alpha)}
\int_K\int_N f(kank^{-1})\;dn\;dk
$$
for arbitrary $f\in C_c(G)$. For $f$ left and right $K$-invariant, the outer integral goes away, leaving just the integral over $N$.
The key point is the identity proven another page or two earlier, something like
$$
\int_N f(a^{-1}nan^{-1})\,dn\;=\; {1\over |\alpha(a)^{-1}-1|}\int_N f(n)\,dn
$$
which follows from multiplying out.


Help in choosing the right type of database

Question: As part of my learning, i am developing a google maps V3 application, to allow people to upload real estate and rental listings. I would like to know what database should i use? I am quite confused as i have researched mysql, coudb, cassandra, maria db and a whole lot more, the issue is that everyone has a + and - things to say with no consistent message, especially regarding RDMS VS No SQL, there is so much back and forth. Maybe anyone of these will be good enough, but i would like the guidance from some experienced developers here on which way to go. Thanks in advance...
Regards
Answer: Stick with the tried and tested - MySQL (or PostgreSQL) will almost certainly give you what you want, the world and its dog can help you out with SQL.
Once you've used one of those in anger, and realised its strengths and limitations, then you'll be much better placed to determine the merits (or otherwise) of an alternative.
For what it's worth, I've used MySQL since maybe 2000 in telecoms environments handling hundreds of thousands of calls a day for reporting, billing, logging, etc., and I see no good reason to change.
Comment: I hear you on this point, i learnt the hard way with javascript frameworks, spent a long time evaluating all and i was totally confused as everyone promoted the framework they liked, so i just decided to cut my teeth learning a few and after playing with jquery, dojo and sproutcore,i really understand the differences much better. I guess i should just cut my teeth on using a basic mysql and i will have a better feel for databases in general.
Comment: I just read about the CAP theorem, its starting to make a lot more sense now. Its funny how new technology can be over-hyped and be made to seem like a complete substitute rather than a complement.
Answer: Choice of DB comes down to your requirements. If you're a bank, you need an RDBMS. Consistency and data integrity are your primary concerns, and the no-sql "databases" cannot provide that. If you're a big social networking site and can live with the occasional bit of unsychronized data in exchange for some speed, then go with one of the nosql type systems.
And of course, nothing says you can't go with a hybrid system. Critical "must be correct/consistent" data in an RDBMS, and the other "can be glitchy" stuff in a nosql.
Comment: Therefore if my application does any credit card processing, i should choose an RDBMS?


Using Grafana and Prometheus to see stat of another server

Question: I have installed Grafana and Prometheus on Server-A. Also I've installed "Node Exporter Full" on it to see a dashboard like this:

As you can see, it's showing the resource usage of Server-A. Now I want to know, is it possible to get those reports and statistics of another server (like Server-B)? If yes, is it needed to install something on Server-B?
Answer: Yes you can do it. You must install node exporter on every server you want to get metrics then add it as a job in prometheus config file to scrape those metrics.


How can I transform a MIDI file of a vocal performance back into something that sounds like a voice?

Question: Given a MIDI file how can I transform it something that sounds like the vocal cadences on the wikipedia.org/wiki/Candence entry? I understand that the end result will be an audio file and not a MIDI file and I'd like it to sound like the audio files on the Wikipedia page.
What vocal synths/samplers would I need?
Comment: You should clarify your intentions. For instance, if you already have a MIDI file of that recording then all you need to do is change the program number to something like 53 or 54 to correspond to a vocal sound and export it as .mid file. But if your goal instead is to have people hear a _specific_ vocal sound like on that Wiki page (which are audio and not midi) then you'll need some sort of vocal synth or sampler to generate those sounds from the MIDI note data. But, it won't be a .mid file then. It will have to be audio in the end. So which do you want?
Answer: Ok, so essentially what you need to do is load that MIDI file into a DAW or something can play back MIDI using a VST synth/sampler or soundfont.
If your goal is for the end result to sound as much like the audio files on the Wikipedia page, then ideally you'd want to use the same sound generator (VST, soundfont, etc). If not then it's a matter of finding one as similar as possible to what they used.
Here's what I can tell you about what they used:

Wikipedia/Mediawiki has a <score> markup element which lets people embed Lilypond scores onto the page.
The Lilypond scores for those vocal cadences are using the "voice oohs" setting for Staff.midiInstrument. Basically, this is Lilypond's way of saying use General MIDI program number 54.
From that Lilypond code the score image and a MIDI file are automatically generated. The MIDI file is automatically converted to an .ogg audio file which is what you hear on the page.
It seems that this MIDI to .ogg conversion is done with FluidSynth.
FluidSynth uses soundfonts and you choose your own soundfont to use.

Here's what I'm still unsure about:

Whether FluidSynth includes any soundfonts by default.
What exact soundfont is used on the Wikipedia page given that you can load your own.

But the FluidSynth documentation does list a couple soundfont recommendations.
So, there are a couple ways that you could go about emulating that sound:

Install Mediawiki locally as well as the extensions for the <source> element. Then just do exactly what they did by writing out a Lilypond score on a page. But this is long way to go and does not technically answer your question because you'd need to write Lilypond notation instead of using a MIDI file.
Try to find the appropriate soundfont that FluidSynth is using, load that into a DAW or some other program (ex. MuseScore) that can both read/import MIDI and playback with a soundfont. Be sure to use program number 54 so you get the "voice oohs" instrument from that soundfont. Maybe experiment with different soundfonts until you find something that works. Then you'd export the end result as an audio file.


PHPUnit with custom/contrib and submodules structure

Question: I am starting to write our tests with PHPUnit on Drupal 8, and I am not sure about the best practices with the phpunit.xml.dist file.
We separates the custom and the contrib modules using two directories in the /modules directory - /modules/custom and modules/contrib.
The original phpunit.xml.dist file contains the following line <directory>../modules/*/tests/src/Unit</directory> so I had to add the
<directory>../modules/*/*/tests/src/Unit</directory> directory.
I have another issue with sub-modules, our current structure is /modules/custom/main_custom_module/modules/sub_module, so I had to add another directory to the file (<directory>../modules/*/*/modules/*/tests/src/Unit</directory>).
What is the best practice when it comes to overriding the phpunit.xml.dist file? should I remove the file from VC (e.g. git,svn..)?
Comment: `../modules/*/*/tests/src/Unit` please file a core patch for this.
Comment: That's a bug, see https://www.drupal.org/node/2499239.
Answer: The right thing to do is to not add it to the core phpunit.xml.dist file. You have your own code, so you want to test that. The idea that core also tests contrib / custom code is not the right thing to do, IMHO
Comment: As far as I understand your opinion is the opposite to D8 and PHPUnit's guidelines


Neo4j Java driver throws "connection reset by peer" exception

Question: We are using Spring Data Neo4j. All the queries work, however sometimes it throws an exception:
org.springframework.dao.TransientDataAccessResourceException: Connection to the database failed; Error code 'N/A'; nested exception is org.neo4j.driver.exceptions.ServiceUnavailableException: Connection to the database failed
Caused by: java.io.IOException: Connection reset by peer
    at sun.nio.ch.FileDispatcherImpl.read0(Native Method) ~[na:1.8.0_212]
    at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39) ~[na:1.8.0_212]
    at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223) ~[na:1.8.0_212]

and after some time it restores the connection.
How can this be fixed to restore the connection immediately?
Comment: Just an idea because there is not much context: do you consume the results after the query execution? It could be that you have open results that got closed before you post-process them.
So calling `consume()`, `list()` or similar to hydrate the results as fast as possible _could_ be a solution.
Answer: This exception comes from Neo4j Java Driver, which throws it when connection gets interrupted. In general, there may be several reasons for this to happen.
For instance, this might happen when driver acquires a connection from internal connection pool that has been idle for too long. Some cloud providers limit connection idle time for load balancers. Driver may fail as soon as it tries using such connection.
You can enable connection liveness check to assist with this. It makes sure that a short network exchange happens for every connection that has been idle over the configured timeout. If exchange fails, another connection is picked or established before it is provided for further driver usage. While this involves an extra network exchange, it is likely to prevent driver failures that might lead to higher-level retry management with potentially exponential delay. The timeout can be set to zero if you wish to test every connection.
Sample configuration:
var config = Config.builder()
                   .withConnectionLivenessCheckTimeout( 60000, TimeUnit.MILLISECONDS )
                   .build();

var driver = GraphDatabase.driver( URL, AuthTokens, config );


Auto-suggest products based on tags

Question: I am interested in autosuggesting products based on the tags an article contains which is read by a user.
How can I accomplish this with Drupal/Drupal Commerce?
thanks
Answer: I'm not entirely sure which one better fits your use case:
This blog post has an excellent way to accomplish product suggestions using the Radioactivity module.  http://www.wunderkraut.com/blog/drupal-commerce-product-suggestions-with-radioactivity/2013-08-22
There is also the Commerce Recommender module:  https://www.drupal.org/project/commerce_rec.
Again, I'm not sure if that is precisely what you're after.
A really straightforward way I could see is create a commerce product view that filters down to only products with the same taxonomy terms on the current article, create a block to hold that view, and display those products with/without their Add to Cart buttons.

Auto-suggest products based on tags


Control Webform's date field (datepicker) from JS

Question: I have to change number of months that's shown in datepicker of my date field in Webform, on desktop I need 2 months, but on mobile just 1.
I'm not able to control that using JS, so I created patch for Webform module to change that and show 2 months.
Is there some solution for this, how I can change stuff like this using JS even I initialized it through field settings in Webform module?
Answer: You can override it with js .. the trick is when it is when your js is attached.
so in your module you need ....
<?php
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id){
  if ($form_id === 'webform_submission_YOURFORMID') {
    $form['#attached']['library'][] = 'YOURMODULE/mymodule.fix-datepicker';
  }
}

then in your js please try some thing like..
(function ($, Drupal, drupalSettings) {
  'use strict';
  Drupal.behaviors.fixMyDatepicker = {
attach: function (context) {

  var dateElement = $('#edit-1'); // id of your date picker
  var dateData = dateElement.data();
  if (dateData.datepicker) {
    makeChangesToDatePicker();
  }
  else {
    var myInterv = setInterval(function() {
      if (dateData.datepicker) {
        makeChangesToDatePicker();
        clearInterval(myInterv);
      }
    }, 100);
  }

    function makeChangesToDatePicker() {
      //@TODO here check if mobile .
      var settings = dateData.datepicker.settings;
      settings.maxDate = '2019-03-11';
    }
   }
  };
 })(jQuery, Drupal, drupalSettings);

the above worked for me. remember datepicker is just: https://jqueryui.com/datepicker/
Answer: You can set default datePicker's options by defining Drupal.webform.datePicker.options via the CSS/JS tab.
@see https://cgit.drupalcode.org/webform/tree/js/webform.element.date.js


Why is Elasticlunr version 0.9.5 not working with Safari 10.3.3 (14F89) using the code below

Question: Using elasticlunr I set up an index as follows:
elasticlunr.clearStopWords();
elasticlunr.tokenizer.seperator = /[\s\-\/@]+/;

function indexStops(document) {
  var index = elasticlunr();
  index.pipeline.remove(elasticlunr.stemmer);

  index.setRef('stop_id');
  index.addField('stop_code');
  index.addField('stop_name');
  index.addField('stop_desc');
  index.saveDocument(false);

  var i = 0;
  for (var doc in document) {
    index.addDoc(document[doc]);
    i++;
  }
  return index;
}

I then use it as follows:
var results = index.search(searchText, {
  bool: "AND",
  expand: true
});

On any modern browser other than Safari it works. On Safari IOS 8.4.1 and 9.3.5 it works. On Safari 10.3.3 and modern versions of MAC OS X it does NOT work. It returns results for the occasional value of searchText but most do not return anything.  Two questions
Is there anything in this code snippet that is non standard and effecting the search on modern versions of Safari ?
Are there known problems with elasticlunr and certain browser versions ?
In general I do not have access to javascript debug facilities on apple platforms. However the one time I did the results when there was no match and there should have been could be seen in a debugger to be of the form:
results: [{ref: "0", score Nan}, {ref: "1", score Nan},{ref: "2", score Nan} .....etc... ]

Answer: For something that works on all browsers the solution is to write your own search. If your are not interested in stems or stopwords and have a json object with your data where the keys are the reference it is as simple as
var text;
for (var ref in dataAsJson) {
  // text is what you will use when searching for matches
  text = dataAsJson[ref].searchField1 + dataAsJson[ref].searchField2; //etc
  text = text.toLowerCase();
  dataAsJson[ref].search = text;
}

Then the method for searching (which does not kick in until the searchText contains at least 3 characters) is
function searchStops(dataAsJson, searchText) {
  var matchRefs = [];

  if (dataAsJson == undefined || searchText.length < 3) {
    return matchRefs;
  }

  // Create an array of searchTerms from searchText which are all lowercase.
  // Split on whitespace
  var terms = searchText.split(/[\s]+/);
  var searchTerms = [];
  for (var i=0; i<terms.length; i++) {
    if (terms[i].length > 0) {
      searchTerms.push(terms[i].toLowerCase());
    }
  }

  var match;
  var search;
  for (var ref in dataAsJson) {
    match = true;
    search = dataAsJson[ref].search;
    for (var i=0; i<searchTerms.length; i++) {
      if (search.indexOf(searchTerms[i]) == -1) {
        // Start by assuming a match, however if any of the terms are
        // not found we do not match
        match = false;
        break;
      }
    }
    if (match) {
      matchRefs.push(ref);
    }
  }

  return matchRefs;
}

I am using this with dataAsJson containing about 8000 lines with have 5-10 words each and have not noticed it as any slower than the equivalent elasticlunr implementation (both cases appears instantaneous to user)


Andengine chopped number in Text

Question: I use Text in Andengine and KozGoPr6N-Heavy. I use it in this way
Font font = FontFactory.createFromAsset(activity.getFontManager(), activity.getTextureManager(),256, 256, activity.getAssets(), "font/KozGoPr6N-Heavy.otf", 60, true, Color.WHITE);
font.load();
timerLabel = new Text(-90, 0, font, Integer.toString(0), 6, activity.getVertexBufferObjectManager());

But effect is not as I expect, it looks like chopped on left.

Any idea why?
Comment: check by increasing your texture.
Answer: Show us how you use your FontREgion. You probably use TextureOptions.DEFAULT while TextureOptions.BILINEAR will be better choice.
This is how I create font, you should do similiar:
public void loadMenuFonts(){
FontFactory.setAssetBasePath("font/");
final ITexture mainFontTexture = new BitmapTextureAtlas(activity.getTextureManager(), 256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);

mainFont = FontFactory.createStrokeFromAsset(activity.getFontManager(), mainFontTexture, activity.getAssets(), "mainFont.ttf", 30, true, Color.WHITE, 2, Color.rgb(22, 144, 189));

mainFont.load();
}

Notice that I use createStrokeFromAsset but you can simply use createFromAsset instead which is almost the same but the effect is font without stroke.

Andengine chopped number in Text


Using the contraction principle to prove that the sequence $a_n=f(a_{n-1})$ is convergent where $f(x)=1+1/x$

Question: Define function $f(x)$ from $\mathbb R^1$ to $\mathbb R^1$ by $f(x) = 1+1/x$.
Define $a_n$ inductively by $a_1=1$ and $a_n=f(a_{n-1})$ for $n \geq 2$.

Prove using the contraction principle that $(a_n)$ is convergent
Prove that if $\lim_{n\to \infty}$  of $a_n= L$ then $L = F(L)$; hint Q2C
Determine $\lim_{n\to \infty}$ of $a_n$

My thoughts
I honestly have no idea what  the contraction principle is,  I have googled it and have found no results.  And I also don't know what Q2C means.
Comment: What are your thoughts on the problem?  That is, please edit your question and include a brief summary of what you've tried so far, or any ideas you might have towards the solution.
Also, out of courtesy to those helping you, you should format the mathematical expressions in your question properly.  See [this page](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) for a tutorial on how to do so.
Comment: I googled contraction principle, and the first link that shows on top point to contraction principle on wikipedia, where it branches, and one of the two branches is Banach contraction principle, also known as [Banach fixed-point theorem](http://en.wikipedia.org/wiki/Banach_fixed-point_theorem) It is likely it has something to do with the problem you posted above, try to find out what, study it. (I couldn't believe you googled contraction principle and found nothing about it.)
Comment: [tag:proof-theory] is a technical branch of mathematical logic. Do not use this tag unless this is the intended sense.
Answer: The Banach contraction principle (which I state here only for the reals) says that if $f$ is a contraction mapping, that is if there is $q$ with $0\le q<0$ such that $|f(x)-f(y)|\le q |x-y|$ for all $x,y$ then $f$ has a unique fixed point $L$, that is $f(L)=L$, and moreover taking any $a_1$ the sequence $a_1,f(a_1),f(f(a_1)),...$ converges to $L$.
So, $a_1=1$ and $a_2=1+\frac11=2$. We will prove by induction that
$\frac32\le a_n \le 2$ whenever $n\ge 2$. Indeed this is true for $n=2$.
Assuming it is valid for some $n\ge2$, we have $\frac12\le \frac1{a_n} \le \frac23$,
so $1+\frac12=\frac32 \le 1+\frac1{a_n}=a_{n+1} \le 1+\frac23=\frac53<2$, which completes this proof by induction.
So consider the restriction of $f$ to the interval $[\frac32,2]$, we will show that it is a contraction mapping with $q=\frac49$. Indeed, take any $x,y\in[\frac32,2]$. Then $|f(x)-f(y)|=|1+\frac1x-(1+\frac1y)|= |\frac1x-\frac1y|=|\frac{y-x}{x y}|\le|y-x|\cdot(\frac23)^2=\frac49|x-y|$.
So, since $f$ is a contraction mapping on $[\frac32,2]$, the sequence
$a_2,f(a_2),f(f(a_2)),...$ converges to some limit $L\in[\frac32,2]$.
To find the value of $L$ use $Q2C$. If you don't know what $Q2C$ means
(I do not), then use common sense :) In the equality $a_n=f(a_{n-1})$ take limit as $n\to\infty$, we obtain $L=f(L)=1+\frac1L$ (note that this is exactly what your hint says), so we have the equation
$L^2=L+1$, or $L^2-L-1=0$, with roots $L_1=\frac{1-\sqrt{5}}2$ and $L_2=\frac{1+\sqrt{5}}2$. Note that $0>L_1\not\in[\frac32,2]$ hence we must have that
$L=L_2=\frac{1+\sqrt{5}}2$.


HTML select not working after AJAX call

Question: This is straight HTML/javascript. The page works fine when executed on its own, but through an AJAX call it does not work on IE11.
After clicking the 'show' button on the main page, it opens a list with options, read from an XML file; it accepts a double click to select an item and shows the selected number in an alert box.
(it also writes this value to a java properties file). On Chrome and FF it works as expected, but not in IE11.
On IE it refuses to select any item.
AJAX's return-page opens a div with absolute positioning, and dragging possibilities. After I drag the box with the list to another place, it suddenly does work in IE as well (but only after dragging more than just a few pixels).
I can only assume it's a type of bug in IE11, but is there a work around? Why would dragging the box make it work?
Here's the significant code:
in main.jsp:
<span id='showcurevent' onclick='showevent(<%=EVENTID%>, 0)'>Show

HTML select not working after AJAX call


Erro setar valor dos Parâmetros na Query

Question: Tenho um problema nessa SQL no Lazarus com Zeos e Firebird
toda vez que executo a procedure da o erro.
Eu já Adicionei os Parâmetros no componente TZQuery.

Mensagem de Erro:

[Notificação Exceções Depurador]
Projeto Autosad elevou classe exceção 'EZSQLException' com a mensagem:
SQL Error:  Dynamic SQL Error SQL error code =
-303 arithmetic exception,numeric overflow, or string truncation string right truncation
Error Code: -303.
 Incompatible column/host variable data type The SQL:
Select T1.DATA_AUDIENCIA, T1.HORA_AUDIENCIA, T2.NUMERO_PROCESSO, T1.NUMERO_E_VARA,
T1.ORGAO, T1.COMARCA, T1.ADVOGADO_DILIGENTE, T3.NOME_CLIENTE, T2.PARTE_CONTRARIA
from AUDIENCIAS T1, PROCESSOS T2, CLIENTES T3
where T1.NUMERO_PROCESSO = T2.NUMERO_PROCESSO and T2.COD_CLIENTE = T3.COD_CLIENTE and
T1.DATA_AUDIENCIA >= ? and T1.HORA_AUDIENCIA >= ?
order by T1.DATA_AUDIENCIA, T1.HORA_AUDIENCIA;

No arquivo:
'C:\Lazarus\components\Zeosdbo\src\dbc\ZDbcInterbase6Utils.pas' na linha 910

Código:
procedure TfrmEntradaSistema.AlimentaQryAudienciasInicial;
var vSql:String;
begin
  // Prepara e executa QUERY com as PROXIMAS AUDIENCIAS para a Tela Inicial
  vSql := 'Select '+
      '  T1.DATA_AUDIENCIA, '+
      '  T1.HORA_AUDIENCIA, '+
      '  T2.NUMERO_PROCESSO, '+
      '  T1.NUMERO_E_VARA, '+
      '  T1.ORGAO, '+
      '  T1.COMARCA, '+
      '  T1.ADVOGADO_DILIGENTE, '+
      '  T3.NOME_CLIENTE, '+
      '  T2.PARTE_CONTRARIA '+
      'from '+
      '  AUDIENCIAS T1, '+
      '  PROCESSOS T2, '+
      '  CLIENTES T3 '+
      'where '+
      '  T1.NUMERO_PROCESSO = T2.NUMERO_PROCESSO and '+
      '  T2.COD_CLIENTE     =  T3.COD_CLIENTE    and '+
      '  T1.DATA_AUDIENCIA >= :AudData and '+
      '  T1.HORA_AUDIENCIA >= :AudHora '+
      'order by T1.DATA_AUDIENCIA, T1.HORA_AUDIENCIA';
  DataModuleGeral2.qryAudienciasInicial.Close;
  DataModuleGeral2.qryAudienciasInicial.SQL.Clear;
  DataModuleGeral2.qryAudienciasInicial.SQL.Add(vSql);
  // Parâmetro
  DataModuleGeral2.qryAudienciasInicial.Params.ParamValues['AudData'] := QuotedStr(StringReplace(DateToStr(DataModuleGeral.tbParametrosDATA_SISTEMA.AsDateTime),'/','.',[rfReplaceAll]));
  DataModuleGeral2.qryAudienciasInicial.Params.ParamValues['AudHora'] := QuotedStr(TimeToStr(Time));
  DataModuleGeral2.qryAudienciasInicial.ExecSQL;
  DataModuleGeral2.qryAudienciasInicial.Active := True;
  DataModuleGeral2.qryAudienciasInicial.First;
end;

Como posso resolver isso?
Comment: Provavelmente esse erro deve estar relacionado a conversão de datas.
Comment: e como é que resolve?
Answer: // Parâmetro
DataModuleGeral2.qryAudienciasInicial.Params.ParamByName['AudData'].AsString :=

Não testei seu código. Mas isso foi a primeira coisa que me chamou a atenção.
Comment: Não entendi sua resposta?


Shapley values for groups of correlated features

Question: Is there a version of Shapley values that does not assume independence of features, and can be used to interpret importance of clusters of "similar" features (by adding individual feature importances for example)?
Comment: Look at [this answer](https://stats.stackexchange.com/a/610428/28500) to a related question. I'm not an expert on this, but it seems to be the type of thing you're looking fo.
Comment: Shapley values are used in a couple of different ways in the statistics and machine learning literature and it is not, in general, the case that Shapley value decomposition assumes that model features are independent (though some implementations do assume they are).  Can you expand on the use case to which you are applying Shapley values?  For instance, is this intended to decompose predicted scores by observation from a predictive algorithm? Or, alternatively, is it intended to determine important features in the model?
Comment: I feel like the important part of this is not so much the feature dependence but the fact that it wants the SHAP value for an entire chunk of variables (which might not be independent of each other) instead of just one variable.
Comment: @jluchman I was hoping to do the latter i.e. use this to get some idea of feature importance or weights for interpreting a blackbox model
Comment: @Dave Yeah I was hoping that since many methods of feature importance such as random forests or boosting assign lower importances to correlated variables that might each be of higher importance (due to, for example, randomly picking one or the other),  there might be a method that allows me to aggregate  feature importances in some way so that I may look at groups of correlated variables together.
Comment: @EdM Thank you! Will check that out!
Answer: See Relative variable importance/explained variation from a single model fit for a related discussion where a permutation-based importance measure breaks down with high collinearity but a new linear model projection technique does not.  The new relative explained variation measure applies to any regression model and may possibly apply to machine learning algorithms if a saturated linear model can approximate their outcomes.  This is along the lines of preconditioning AKA model approximation.
Answer: The method recommended here is based on 'classic' Shapley value decomposition that, as has been noted frequently in the literature, is not scalable as it involves 'removing columns/features' and thus refits $2^f$ different models (where $f$ is the number of features). This method does not assume independence of featrues however and, in fact, is very useful for ascribing importance in conditions where features are correlated (this is often noted in the literature on 'Dominance Analysis' - on which the {domir} package used below is based).  Shapley values, using the column dropping approach to Shapely values is also quite flexible as it is easy to drop multiple columns simultaneously.
As an example, consider this random forest model implemented in R with the mtcars data from the {datasets} package.
> set.seed(25)
> randomForest::randomForest(mpg ~ ., data = mtcars) |>
+   predict() |>
+   yardstick::rsq_vec(mtcars$mpg, estimate = _)
[1] 0.8489851

I set the seed to ensure the reproducibility of this result specifically, especially as the model is refit in runs below. It's standard importance metrics are also computed.
> set.seed(25)
> randomForest::randomForest(mpg ~ ., data = mtcars, importance = TRUE) |>
+   randomForest::importance()
       %IncMSE IncNodePurity
cyl  10.902547     165.83137
disp 12.746522     239.73487
hp   12.443743     193.31249
drat  5.389437      58.19412
wt   13.574631     242.07634
qsec  2.536330      28.38492
vs    4.417597      35.49211
am    3.717252      14.87757
gear  3.698947      19.99795
carb  6.280669      39.68566

These metrics suggest wt and disp are most important (in that order).
The alternative Shapley/dominance-based approach is computed below.
> domir::domir(
+   terms(mpg ~ ., data = mtcars) |> formula(),
+   \(fml) {
+     set.seed(25)
+     randomForest::randomForest(fml, data = mtcars) |>
+       predict() |>
+       yardstick::rsq_vec(mtcars$mpg, estimate = _)
+   },
+   .cdl = FALSE, .cpt = FALSE
+ )
Overall Value:      0.8489851

General Dominance Values:
     General Dominance Standardized Ranks
cyl         0.12199217   0.14369177     4
disp        0.17183115   0.20239595     1
hp          0.14207064   0.16734174     3
drat        0.02690479   0.03169053    10
wt          0.15773333   0.18579046     2
qsec        0.03852428   0.04537686     9
vs          0.05023545   0.05917118     6
am          0.04421375   0.05207835     7
gear        0.03942196   0.04643421     8
carb        0.05605759   0.06602895     5

This approach suggests also that disp and hp are important but in that order and, if interested, the user can ask for .cdl = TRUE to see the progression of feature collinearity affects how each feature explains variance in mpg. Note that this version of importance results in an exact decomposition of the $R^2$ into components attributable to each feature.  This is only possible when random elements in the model are held constant (i.e., the random forests have the same random seed).
Using the .set argument, a user can also group features which includes and drops them all jointly.
> domir::domir(
+   terms(mpg ~ ., data = mtcars) |> formula(),
+   \(fml) {
+     set.seed(25)
+     randomForest::randomForest(fml, data = mtcars) |>
+       predict() |>
+       yardstick::rsq_vec(mtcars$mpg, estimate = _)
+   },
+   .set =
+     list(`grp 1` = ~ cyl + disp + wt, `grp 2` = ~ carb + hp, `grp 3` = ~ gear + am),
+   .cdl = FALSE, .cpt = FALSE
+ )
Overall Value:      0.8489851

General Dominance Values:
      General Dominance Standardized Ranks
drat         0.05185996   0.06108465     6
qsec         0.05776773   0.06804328     5
vs           0.08047303   0.09478733     4
grp 1        0.33222563   0.39132092     1
grp 2        0.22981961   0.27069922     2
grp 3        0.09683914   0.11406459     3

Here, many of the most strongly correlated features are in grp 1 which results in the most important set of features. Note that grouping the features in this way affects how all the features' importance are computed as it affects the number of sub-models that are estimated and incorporated into the computations.
Again, this approach is much less scale-able than alternative implementations that sample the sub-model space or impose assumptions.  That said, the grouping of features can reduce the sub-model space substantially.  Moreover, features of little interest can be put into the .all argument and lumped into a component of the $R^2$ that does not contribute at all to the sub-model space.
Comment: gonna try this out- thanks!


Can Nginx translate TLS 1.0 to 1.3 for clients incompatible with TLS 1.3?

Question: I have old appliances that either do not support TLS or only support TLS 1.0.
Can Nginx translate between these incompatible devices using only HTTP or TLS 1.0 and endpoints that use TLS 1.3?
Comment: Not exactly translate, but yes your nginx can take browser/client side TLS 1.0 connections and forward requests to upstream in TLS 1.3. But retiring such old stuffs is still recommended.
Comment: I was meaning the other way.  things like old apc pdu's from the 90's cant talk tls3 and would need nginx to do something allow the browser to recieve tls3.
Comment: is this Stall equipment still in use for a production business environment? can you please confirm?
Answer: Short and Dirty Answer:
Yes, you can, but you should retire such old equipment. Nginx doesn't care what's beyond it, even if it is a valid or invalid SSL certificate in the Default Configuration.
Sample Configuration:
<code>server {
        server_name tld.domain.it;
        access_log /var/log/nginx/tld.domain.it.access.log;
        error_log /var/log/nginx/tld.domain.it.error.log;
        listen [::]:443 ssl ;
        listen 443 SSL ;
        #Useful for the old site
        proxy_no_cache 1;
        proxy_cache_bypass 1;

        #For reaaaly old broken stuff, force IE-Emulation Mode (may help)
        #add_header 'X-UA-Compatible' 'IE=EmulateIE7';

        #Force tls1
        #proxy_ssl_protocols TLSv1

        # I prefer to log also rewrite
        rewrite_log on;
        proxy_pass                              https://127.0.0.1:12345;
        proxy_set_header                        Host $http_host;

    }

    ssl_certificate /etc/letsencrypt/live/exmaple.it/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.it/privkey.pem;

}
</code>
References
https://docs.nginx.com/nginx/admin-guide/security-controls/securing-http-traffic-upstream/
https://docs.nginx.com/nginx/admin-guide/web-server/reverse-proxy/
https://nginx.org/en/docs/http/ngx_http_proxy_module.html
Comment: `Nginx doesn't care what's beyond it` as long as it is compiled with the outdated ciphers.   This will change in future releases of nginx.
Comment: I agree that it _may_ change, but in the current point of development it is set by default to ignore ssl errors ;)


Como parar uma execução no Python?

Question: Estou começando a programar em Python e gostaria de saber como faço para parar a execução do programa?
Na linguagem C por exemplo, existe o comando equivalente system("pause"). Se eu abrir o IDLE, mais especificamente o shell do Python o programa ao terminar a janela não fecha. Porém, se eu usar o executável do Python que é semelhante ao CMD o programa acaba se fechando ao terminar. O que faço para resolver esse problema?
Comment: `system("pause");` nao é um "comando do C" - ele usa uma chamada ao shell do sistema para rodar umoutro PROGRAMA inteiro - que é o Pause.  (O mesmo funciona em Python, como dado na resposta) - mas é equivalente a chamar um chaveiro pra arrombar a sua porta cada vez que quer entrar em casa, em vez de arrumar a fechadura.
Answer: Use a função "input"  - ela aguarda até que o usuário digite enter (ele pode digitar mais texto antes de apertar enter, mas se você não for fazer nada com esse texto, é indiferente):
input("Pressione <enter> para continuar")

O os.system("pause") executa um outro programa inteiro - e significa que o programa "Pause" tem que existir no seu sistema operacional, e ele é algo só do Windows: seu programa Python (ou C) que funcionaria em Linux, Mac, Android, passa a ser "windows only" só por causa dele.
Mas sobretudo, usar `system("pause"), mesmo em C, é equivalente em programação, a chamar um guincho pra levar seu carro a algum lugar, com você dentro, por que o carro está sem gasolina, em vez de abastecer.
Já a função "input" é interna do Python, sequer precisa importar qualquer módulo - e depende apenas da interação do próprio runtime do Python com a entrada padrão do programa. (Em C o correto seria usar a função fgets).
Comment: >>>>>>>>>>>>>> http://pt.stackoverflow.com/a/69853/3635
Comment: Isso. Mas algum demente começou a ensinar o tal `systen("pause")` para C em faculdades há algum tempo atrás, em vez de explicar qual era a natureza do terminal do stdin - as pessoas se formaram e hoje acham isso "normal". É uma das coisas mais surreais que já vi em computação.
Comment: Excelente explicação, poderia ter feito na pergunta que apontei ao invés de responder na dup e apontar nos campos de comentário.
Answer: Tenta esse, ele vai esperar você digitar uma tecla para continuar
import os
os.system("pause")

Comment: Funcionou, o código foi eficiente. Gostaria de agradecer pela ajuda e disponibilidade.

Como parar uma execução no Python?


Mapear dados como TIME do MySQL para JAVA acima de 24 horas Exemplo (37:26:30)

Question: Tenho um sistema que preciso trazer do banco MySQL informações de tempo acima de 24 horas para o Java.
Usamos hibernate e está da seguinte forma;
No banco o dado está como TIME (37:13:36) exemplo:
TEMPO_REPOUSO                     time          (NULL)             YES             (NULL)                   select,insert,update,references

No Mapeamento da tabela no Java está como TIME exemplo:
@Column(name="TEMPO_REPOUSO")
private Time tempoRepouso;

A consulta fizemos através de uma query usando springframework.
E o objeto que vai receber os dados do banco as variáveis correspondente aos dados declaramos também como TIME do java.sql.Time. Exemplo:
private Time tempoRepouso;

Estamos Mapeando em DTO no Java; Não consigo de forma nenhuma trafegar este dado, unica forma que veio informação foi declarando o objeto que vai receber os dados do banco como Date, mas é barrado quando no Banco possui informações de tempos maiores que 24horas.
Answer: Antes precisamos entender dois conceitos importantes: horários e durações. Considere as frases abaixo:

A reunião foi às duas horas da tarde
O filme tem duas horas de duração

No primeiro caso, "duas horas" é um horário: um momento específico do dia.
No segundo caso, "duas horas" é uma duração: uma quantidade de tempo, não necessariamente relacionada a um horário específico (não é dito que horas começa ou termina, nem sequer é dito se ele de fato foi assistido).
O que pode confundir é que ambos usam as mesmas palavras (horas, minutos, segundos) e até mesmo a forma de exibição pode ser a mesma (um relógio mostra "02:00" quando são 2 horas, um cronômetro mostra "02:00" quando já se passaram 2 horas). Mas eles são conceitos diferentes.

Dito isso, o tipo TIME do MySQL serve para ambos: ele tanto pode conter um horário, quanto uma duração (por isso seu range de valores varia entre '-838:59:59' e '838:59:59').
Já a classe java.sql.Time representa apenas um horário, e não serve para durações. Tanto que ela só aceita valores entre 0 e 23 para as horas, e valores acima disso são truncados:
System.out.println(Time.valueOf("25:59:59")); // 01:59:59

Sendo assim, não é possível mapear durações acima de 24 horas para um java.sql.Time.

No Java 8, existe uma classe específica para durações: java.time.Duration. A partir do JDBC 4.2 e Hibernate 5, há suporte para Duration, que é mapeado para BIGINT, então seria necessário mudar o tipo da coluna do banco, para conter apenas um número, correspondente ao total em nanossegundos (que é a precisão desta API).

Ou, você poderia criar um AttributeConverter para converter os valores para um Duration:
@Converter
public class DurationConverter implements AttributeConverter<Duration, Long> {
    @Override
    public Long convertToDatabaseColumn(Duration duration) {
        return duration == null ? null : duration.getSeconds();
    }

    @Override
    public Duration convertToEntityAttribute(Long dbData) {
        return dbData == null ? null : Duration.ofSeconds(dbData);
    }
}

...
@Column(name="TEMPO_REPOUSO")
@Convert(DurationConverter.class)
private Duration tempoRepouso;

Só que aí a query teria que retornar a quantidade de segundos correpondentes à duração, algo como SELECT TIME_TO_SEC(TEMPO_REPOUSO) etc. E da forma que está, suspeito que sirva apenas para consultas (atualizações e inserções neste campo precisariam de outra conversão, como SEC_TO_TIME para converter a quantidade de segundos para o TIME do MySQL).
Comment: Ola @hkotsubo depois de muito teste muita pesquisa, consegui resolver o problema levando sua resposta como base...

converti os dados no banco que eram Time para Long (para representar o período gravado em  segundos) e ai sim do lado do java utilizando o Long vindo do banco, transformei ele em Período usando a classe (org.apache.commons.lang.time.DurationFormatUtils) .

Muito obrigado ajudou demais!
Comment: Nossa muitíssimo obrigado Vou testar aqui o que você mencionou, sua resposta também agregou muito conhecimento pra mim, não consegui ser específico mas no meu caso é Duração mesmo o dado que preciso trabalhar aqui.
Comment: @DiegoSouza Blz, não esqueça que, **caso funcione** e resolva o seu problema, vc pode aceitar a resposta, [**veja aqui**](https://pt.meta.stackoverflow.com/q/1078/112052) como e porque fazê-lo. Não é obrigatório, mas é uma boa prática do site, para indicar a futuros visitantes que aquilo resolveu o problema. E quando tiver 15 pontos, [**vc também poderá votar**](/help/privileges/vote-up) em todas as respostas que achou úteis.


On the boy-girl paradox and the TED-ed frog riddle

Question: I'm aware this question has been asked many times - however, I feel I have a different take on the topic.
First, let's take a classic scenario. Here, a doctor has 2 babies. He checks both of their genders and tells the nurse "at least one of them is male". Here, the odds babies are both boys is clearly 1/3.
Next, let's spin this scenario. Here, the doctor still has 2 babies. He checks only one of their genders (you are unsure which one) and tells you "at least one of them is male". Here, the odds the babies are both boys is clearly 1/2. (unless I'm wrong here)
Finally, let me pose my question: does the frame of reference from which you are acquiring the information impact the statistics? In other words, if the medium from which you are acquiring the information is only aware of one of the two binary options (as in scenario 2), does that change the statistics?
More relevantly, in the TED-ed frog problem, is the scenario closer to my scenario 2? The medium by which you obtain the information can only know one of their sexes for certain, in my opinion.
On a side note, I also feel as if the riddle is confuddled if you group the three frogs into one triplet. For the sake of this post, though, we will not take this into consideration.
Comment: Not sure what exactly you mean by 'frame of reference' or 'medium' ... but take a look here: https://math.stackexchange.com/questions/2149812/the-two-daughter-problem/2150036#2150036 maybe this is along the lines of what you're thinking?
Comment: Not quite because Mr. Smith knows the gender of both of his children. Although we can take the scenario where he knows one of his children is a boy but doesn't know the other's gender. Is this still analogous to my second scenario listed in the original post?
Comment: Yes, that would be analogous. Or: I ran into one of Mr. Smith children and it was a boy. Then I learn Mr.Smith has a second child. So: I know that Mr.Smith has two children, at elast one of which is a boy ... in that case the probability of both being boys is $\frac{1}{2}$.  But there are other scenarios where I also 'know that one of Mr. Smith's children is a boy, and yet now the probability of both being boys is $\frac{1}{3}$. That's what I tried to describe in that post.
Comment: I see. Then, is the ted-ed frog problem analogous to situation 2, wherein we know there is a male, then learn that there is a second child/frog?
Comment: The way you phrase that is ambuiguous: "we know there is a male" .... *how* do you know there is a male? If you are looking at a specific frog and know for that specific frog it is a male, and then someone holds up a second frog for which you don;t kow the gender, then it's back to $\frac{1}{2}$ that both are males. But that is not the Ted-frog scnario: there you see two frogs, and know (given the call) that at least one is male. Now the probability both are male is $\frac{1}{3}$.
Answer: First, TED-ed's answer is wrong. It's equally likely that there is a female frog in either direction. The short explanation is that, if there was a male frog on the stump, it could have croaked first. Eliminating the cases where that could have happened reduces the chances that it was male.
I point that out, because it isolates the error made in this entire class of problems. It is incorrect to base the answer on the combinations that could produce the information. You need to also eliminate the cases that could, but wouldn't. A good example is the first doctor case you mentioned. You said the answer was clearly 1/3, but that is also wrong. It is 1/2.
Think about it: there is a 1/4 chance of BB, in which case the doctor will tell you there is a boy. There is a similar 1/4 chance of GG, in which case the doctor will tell you there is a girl. But in the 1/2 chance that there is one of each, why do you assume the doctor will always tell you there is a boy? You can only assume he picks either one with a 50% probability, in which case the answer is 1/2.
The information you have (the "frame of reference") does not impact "the statistics" of the cases that can exist in the absence of that information. But it can affect what you know can't exist with it. And how you obtained the information can affect it even more. The question you need to ask yourself is "Are there situations where this information is true, but I would have learned something else?" TED-ed's frog problem is a good example.
+++++
Here's the solution to TED-Ed's riddle. I'll use the event M2:F to mean two males in the clearing and a female on the stump, and M1F1:M to mean one of each in the clearing and a male on the stump. The event C means the first croak comes from the clearing.
Pr(M2:M)=1/8, Pr(M2:M & C)=(1/8)*(2/3)=1/12
Pr(M2:F)=1/8, Pr(M2:M & C)=1/8
Pr(M1F1:M)=1/4, Pr(M1F1:M & C)=(1/4)*(1/2)=1/8
Pr(M1F1:F)=1/4, Pr(M1F1:F & C)=1/4
Pr(C) = sum of all these = 1/12+1/8+1/8+1/4 = 7/12
Pr(M1F1|C) = [Pr(M1F1:M & C)+Pr(M1F1:F & C)]/Pr(C) = [1/8+1/4]/(7/12) = 9/14
Pr(F|C) = [Pr(M2:F & C)+Pr(M1F1 & C:F)]/(Pr(C) = [1/8+1/4]/(7/12) = 9/14
+++++
[Edit] I finally noticed the edit to the original post.

On a side note, I also feel as if the riddle is confuddled if you group the three frogs into one triplet. For the sake of this post, though, we will not take this into consideration.

Saying "I'm ignoring any situation where my answer might be wrong" does not make for a convincing argument that it is right. The riddle is not "confuddled" [sic] by considering all of the elements that are part of the problem as stated. It is addressed properly. There are three frogs in the problem.
Comment: It is indeed a well-known problem. It goes back to 1889, but the modern version was introduced by Martin Gardner in the April, 1959 issue of Scientific American. And he did say the answer was 1/3. But in October, he withdrew that answer because, as he stated it, the problem is ambiguous. The answer is 1/3 if, *and only if*, you ask the doctor "Is at least one a boy?" The answer is 1/2 if the doctor could have said "at least one is a girl" when there is one of each. Which he can do in your version.
Comment: The paragraph where you claim that I'm wrong in the doctor problem, either there is a misunderstanding or you're wrong. This is a very [link]well-known statistics problem(https://en.wikipedia.org/wiki/Boy_or_Girl_paradox#Bayesian_analysis). I don't know why you believe you can only assume he picks one with equal probability. I clearly state that he looks at both and states at least one of them is a boy, which I juxtapose in the next problem by saying he only looks at one of the babies (which I argued is 1/2)
Comment: There are 4 possibilities in the Doctor Problem: The doctor looks at ... (A) ... two boys and says "At least one male." (B) ... two girls and says "At least one female." (C) .... one of each and says "at least one male." (D) ... one of each and says "at least one female." The prior probabilities for cases A and B are 25%. If the prior probability for case C is P, then the prior probability for D is 50%-P. You assumed P=50%, which means that the answer for the identical problem that swaps boys for girls is 1. That's a paradox. If we aren't told how the doctor decides, we must assume P=25%


How to change the No Data message using iOS Charts?

Question: When using iOS Charts and there is no data, there is a default message that says "No chart data available". Can this default be edited and handle translations?
Answer: This is how you can customize the chart appearance before data is shown.
@IBOutlet private weak var chart: LineChartView!

chart.noDataText = "Loading"
chart.noDataTextColor = .green
chart.noDataFont = UIFont(name: "Helvetica", size: 10.0)!

Answer: FYI I am using a chart in a table view cell and found I needed to set the various noData parameters in awakeFromNib() for them to properly reflected.
override func awakeFromNib() {
    //show the activity indicator which automatically animates
    activityIndicator.isHidden = false

    projectionChartView.noDataText = "Loading..."
    projectionChartView.noDataFont = UIFont.systemFont(ofSize: 18.0, weight: .medium)
}

Answer: You can edit the default using .noDataText along the lines of the lines of the following:
lazy var lineChartView: LineChartView = {
    let chartView = LineChartView()
    chartView.noDataText = NSLocalizedString("chart_no_data", comment: "")

    ...

    return chartView
}()


Newbie Question - How do I add content to this page?

Question: I'm very new to drupal, and I've been put on this project.
So I wanted to create a custom page to display the privacy conditions, which is just a word file I have to copy (so just plain text).
I created the custom page, used the template they gave me and now I want to add the plain text, however I have no Idea where I can do that. Normally I should be able to do it on this page they told, but I can't figure out why I can't change the Main Content.

Sorry for this very silly question, but I can't find anything about this on the internet.
Comment: You shouldn't use a sledgehammer like panels to create a basic page with privacy conditions.  Get hold of somebody that knows something about Drupal and get them to help you re-enable the "Basic page" content type. Then use that for your static text.
Answer: Am not clear about your requirement, right now you are trying to display it using a panels. If your requirement is just to show a custom page with custom text.. then just add a basic page as a content and place the text in body field. Then call the page using the given path.
Comment: ye that's what I wanted to do, but I can't find the content type "basic page" in content types (it's a custom theme some guy made)
Comment: just check content -> add content -> basic page from admin menu on top. otherwise type this path "admin/content" and then proceed with add content.
Comment: Nope, it's on in the list. http://puu.sh/iSAp8/17e803bd78.png I think the guy from the theme disabled it.
Comment: May be the basic page content type is deleted. create a new content type and then create node using this new type with your content. Then dispaly it using panels.
Answer: You should be using "Add content" link to create a new "node". If you don't have such link (yet), then it must be that you have no permission (yet) to add content ...


Angle in a Triangle with Altitude and Median

Question: In triangle $ABC$, $m\measuredangle A=100^\circ$, $m\measuredangle B=50^\circ$, and $m\measuredangle C=30^\circ$. Points X and Y are on the sides of the triangle so that $\overline{AX}$ is an altitude and $\overline{BY}$ is a median. Compute $m\measuredangle YXC$.
I drew the diagram and it appears to me that $\overline{YX}$ and $\overline{AB}$ are parallel, which would give $m\measuredangle YXC=50^\circ$, but I'm not sure how to demonstrate this.
Answer: $YX$ is not parallel to $AB$. Focus on the triangle $AXC$ and compute all three of its angles. Is that a special triangle? Then what can you say about  the length of $AX$, the length of $AC$ and the length of $AY$ (recall $BY$ is a median). Now, can you compute all the angles of triangle $AXY$? Consequently, how much is $\angle \, YXC$? It is not $50^{\circ}$.
Comment: Ah, I see now. I appreciate your help very much. I often forget about side lengths when focusing on angles, and vice versa.


Float Action Button não fica fixo no rodapé com Collapsing ActionBar/Toolbar

Question: tenho um fragment com coordinator layout, recyclerview e um Float Action Button, e na view que chama esse fragment tem um tablayout que esconde e aparece conforme sobe ou desce o recycler view, ja tentei de várias formas deixar o fab fixo no rodapé, mas de toda forma ele sempre sobe quando desliza o recycler view

segue abaixo o código do fragment:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/frmLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="br.com.julioantonini.meuchat.ContatosFragment">

<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerContatos"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_marginBottom="70dp"
    android:layout_marginRight="10dp"
    android:layout_marginEnd="10dp"
    app:elevation="1dp"
    app:srcCompat="@drawable/ic_action_add"
    app:layout_anchor="@id/recyclerContatos"
    app:layout_anchorGravity="bottom|right|end"/>

e abaixo o código da activity:
<?xml version="1.0" encoding="utf-8"?>

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_height="wrap_content"
    android:layout_width="match_parent">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        app:layout_scrollFlags="scroll|enterAlways"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        app:tabIndicatorColor="@color/colorTab"/>

</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/viewPager"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_below="@id/appbar"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

Comment: Qual é o xml da sua activity? Atualiza na pergunta...
Comment: Adicionei o código da acitivity
Answer: Se não tiver problema em colocar seu FAB na activity, você pode fazer desta forma:
...
<android.support.v4.view.ViewPager
    android:id="@+id/viewPager"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_below="@id/appbar"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_marginBottom="70dp"
    android:layout_marginRight="10dp"
    android:layout_marginEnd="10dp"
    app:elevation="1dp"
    app:srcCompat="@drawable/ic_action_add"
    app:layout_anchor="@id/viewPager"
    app:layout_anchorGravity="bottom|right|end"/>

O que muda aqui é que o layout_anchor do seu FAB deixa de ser o RecyclerView e passa a ser o ViewPager. Além de, claro, retirar o FAB do layout do seu fragment e passar para a activity.
Comment: Será que é a única forma ? Pq são 3 tabs e ela só aparece na primeira, e após adicionar um usuário é preciso dar um reflesh na recycler view, aí terei q usar um broadcast pra fazer o reflesh né
Comment: Acredito que se você for abrir uma activity a partir de outra e, dependendo do resultado que ela retornar, você for atualizar alguma coisa, o recomendado é utilizar `startActivityForResult()` ao invés do `BroadcastReceiver`
Comment: Na questão de aparecer o botão só na primeira tab, você pode colocar um listener no seu ViewPager (`setOnPageChangeListener()`). E quando seu FAB estiver na primeira posição, use o método `show()`, caso contrário, o método `hide()`.
Comment: Quando ao ocultar, foi o que eu imaginei mesmo! Já o fab ele chama apenas um diálogo para inserir um novo usuário e em seguida atualiza o adapter do recycler view, o fab estando na activity, qual seria a melhor forma de avisar o fragment para atualizar o adapter do recycler view
Comment: Nesse caso você pode armazenar a instância do seu fragment como membro da sua activity, abrir o dialog normalmente, ainda na activity colocar um listener no dialog (é nativo ou você criou um customizado?) na ação em que o usuário é adicionado, e quando seu listener for chamado você verifica se a instância do seu fragment não é nula e chama um método do seu fragment que possa atualizar o recyclerview.
Se você não tiver entendido dessa forma, posso atualizar a resposta, mas você vai precisar atualizar a pergunta com o código do seu dialog e da sua activity
Comment: Obrigado Danilo, eu consegui fazer utilizando o broadcast já que o app utiliza o broadcast que ouve o firebase  e faz outras coisas, porem, você poderia, me passar o exemplo do código de como eu chamaria uma função do fragment através da view dessa forma de instância. estou engatinhando ainda no Android e todo conhecimento é bem vindo!
Comment: Você quer dizer chamar uma função do fragment através da activity?
Comment: Sim, dessa forma não precisaria enviar o broadcast nessa activity


error "invalid conversion from 'const char*' to 'char' [-fpermissive]" in c++

Question: I'm having a problem with my code. I'm trying to make a program that converts non integer numbers into binary. It returns an error in line 21 saying "invalid conversion from 'const char*' to 'char' [-fpermissive]".
What does this mean and how can I solve it?
#include <iostream>

#include <string>

using namespace std;

int main(){

    string number;

    cout<<"Insert number";
    cin>>number;
    int continue = 0, integer;
    bool first = false;
    while(continue >= 0){
        if(primo == false){
            integer = number[continue];
            first = true;
            continue++;
        }
        else{
            char dot = "."; //line 21
            char comma = ",";
            char check = number[continue];
            if((check == comma) or (check == dot)){
                continue = -1;
            }
            else{
                int encapsulation = number[continue]
                integer = (integer*10)+encapsulation;
                continue++;
            }

        }

    }
    cout<<integer;

    return 0;
}

Comment: `char dot = "."; ` you have used the wrong quotation marks for a char. It should be `char dot = '.';` for a char and "" for a string.
Comment: `continue` is a keyword in C++. You may not use it as an identifier. The variable `int continue;` is not allowed
Answer: A few mistakes:

continue is a keyword. I renamed it to cont

Double quotes "." is for strings. Chars constants are surrounded by single quotes as '.'.

#include <iostream>

#include <string>

using namespace std;

int main(){

    string number;

    cout<<"Insert number";
    cin>>number;
    int cont = 0;
    int integer;
    bool first = false;
    bool primo = false;
    while(cont >= 0){
        if(primo == false){
            integer = number[cont];
            first = true;
            cont++;
        }
        else{
            char dot = '.'; //line 21
            char comma = '.';
            char check = number[cont];
            if((check == comma) or (check == dot)){
                cont = -1;
            }
            else{
                int encapsulation = number[cont];
                integer = (integer*10)+encapsulation;
                cont++;
            }

        }

    }
    cout<<integer;

    return 0;
}

Godbolt: https://godbolt.org/z/Tvz3MKxx7
Comment: Thanks, the first error of continue is an error of translate, because i writed my program in my language and next i have translate all to english and the name of the variable is change to "continue. The second mistake is my error, thanks for helped me.


OSAS v4 Open Systems Accounting Software

Question: My company recently purchased another company and along with it, came an old SCO Openserver (v5) running OSAS v4. We use TinyTerm as recommended to access this but no one knows how to use it.  I've been tasked with finding a way to export this data into a more current database.
Does anyone have any ideas om how to do this?
Comment: Find a consultant who is familiar with the software and then hire that person to help you out.
Answer: This is more than "export data". You have an ERP system; you can't just simply dump it to CSV and expect to use it in another system. Even if all the fields mapped without a single problem, you don't have the business logic, scheduled jobs/exports, etc.
You should concentrate on finding a replacement product, and then working with the vendor or VAR to help migrate your old data.
Looking at OSAS's site, you could stay with the existing product line, if you like the software, and just upgrade the OS platform to a modern Unix, Linux, or Windows.


Convert time "PT10H30M" to "10:30 AM" time JAVA Android

Question: I'm trying to convert a time in format "PT10H30M" to format "10:30 AM" and save this on Date, time or timestamp variable in Java Android.
Any solution to do this?
Comment: Your input string represents a span-of-time unattached to the timeline. The correct object representation for that is a [`Duration`](https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html) in java.time (see Answer by Hugo below for [back-port to Android](https://github.com/JakeWharton/ThreeTenABP)). A time-of-day such as "10:30 AM" is *not* a span-of-time. Your input string is already in the correct textual representation for such a span-of-time, defined by the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) standard.
Comment: What type of `Object` do you want to end up with? `Calendar`? `Date`?
Comment: I prefer Date or Time, I don´t know if exits Timestamp in JAVA, but any type, just need convert "PT10H30M" to "10:30 AM"
Answer: Technically, PT10H30M is not a time, it's a representing duration: an amount of time (an amount of 10 hours and 30 minutes). That string is in standard ISO 8601 format.
Although the "name" (10 hours and 30 minutes) is similar to 10:30 AM (10 hours and 30 minutes AM), they're totally different concepts:

10:30 AM represents a time of the day
PT10H30M represents an amount of time - that can be, for example, added to a date/time:

01:00 AM plus the duration of PT10H30M results in 11:30 AM
11:00 PM plus the duration of PT10H30M results in 09:30 AM of the next day

Anyway, you could achieve what you want by adding the duration of PT10H30M to midnight (00:00).
In Android you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. You'll also need the ThreeTenABP (more on how to use it here).
You can use a LocalTime (which represents a time, with hour, minutes, seconds and nanoseconds), using a constant for midnight 00:00:00.0, and add a Duration to it:
import org.threeten.bp.LocalTime;
import org.threeten.bp.Duration;

LocalTime time = LocalTime.MIDNIGHT.plus(Duration.parse("PT10H30M"));

The result will be a time variable that holds the value corresponding to 10:30 AM.

If you want the corresponding String, you can use a org.threeten.bp.format.DateTimeFormatter:
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH);
System.out.println(time.format(fmt));

The result is a String with the value 10:30 AM. (Note that I also used a java.util.Locale to make sure it properly formats the String).
Comment: Exacty what I need, so many, many many thanks to you.

Just a add, for use the
import org.threeten.bp.LocalTime;
import org.threeten.bp.Duration;

Is necesary go to gradle and add dependency

dependencies {
    compile 'com.jakewharton.threetenabp:threetenabp:1.0.3'
}
Comment: @RaZoDiuM On Stack Overflow, you are welcome to make such fixes or additions to an Answer yourself.