puppet 3.2.4: stack level too deep

Question: I am working on a refactoring project for a large repository of custom puppet modules.  This includes an upgrade from puppet 2.x to 3.2.4.  When I finally hit critical mass and started testing some of the changes, I quickly ran into the following error:
Info: Retrieving plugin
Info: Loading facts in /etc/puppet/modules/base/lib/facter/elversion.rb
Info: Loading facts in /etc/puppet/modules/base/lib/facter/site.rb
Info: Loading facts in /var/lib/puppet/lib/facter/elversion.rb
Info: Loading facts in /var/lib/puppet/lib/facter/site.rb
Error: Could not retrieve catalog from remote server: Error 400 on SERVER: stack level too deep at /etc/puppet/manifests/nodes.pp:9 on node puppet
Warning: Not using cache on failed catalog
Error: Could not retrieve catalog; skipping run

After looking through various puppet bug reports, I decided to try simplifying the problem.  I narrowed the issue down to two classes, defined as such:
class base::includes { }

and
class prod_secure::base::includes inherits base::includes { }

A node that includes nothing but prod_secure::base::includes produces the error output listed above.  The only possibly related warning that I see in puppet-lint is:
WARNING: class inherits across module namespaces on line 1

...but that's just a warning, and shouldn't crash puppet on an agent run, I wouldn't think.   Any ideas?  Is it possible that the namespacing scheme that I have set up unsupported by puppet?
UPDATE
I decided to take the testing a step further, and change the name of the inheriting class.  The new definition is:
class prod_secure::base2::includes2 inherits base::includes { }

The result is the same... stack level too deep.  It looks to me like this issue has nothing to do with namespacing.
UPDATE 2
During the previous round of debugging I missed one salient detail:
Wed Sep 11 11:25:09 -0400 2013 Puppet (info): Caching node for puppet
Wed Sep 11 11:25:09 -0400 2013 Puppet (debug): importing '/etc/puppet/manifests/nodes.pp' in environment production
Wed Sep 11 11:25:09 -0400 2013 Puppet (debug): importing '/etc/puppet/manifests/config_file.pp' in environment production
Wed Sep 11 11:25:10 -0400 2013 Puppet (debug): importing '/etc/puppet/modules/prod_secure/manifests/base2/includes2.pp' in environment production
Wed Sep 11 11:25:10 -0400 2013 Puppet (debug): Automatically imported prod_secure::base2::includes2 from prod_secure/base2/includes2 into production
Wed Sep 11 11:25:10 -0400 2013 Puppet (debug): importing '/etc/puppet/modules/prod_secure/manifests/base/includes.pp' in environment production
Wed Sep 11 11:25:10 -0400 2013 Puppet (debug): Automatically imported prod_secure::base::includes from prod_secure/base/includes into production
Wed Sep 11 11:25:10 -0400 2013 Puppet (err): stack level too deep at /etc/puppet/manifests/nodes.pp:9 on node puppet
Wrapped exception:
stack level too deep

I can't say I'm sure why, but it was still trying to load prod_secure::base::includes, and that was the offending entry.  After removing that file entirely, the test passed.  I'm back to the namespacing theory...
Comment: Do you have a module that tries to load `'modulename/*.pp'` manually, as a work for some autoloader problems way back in Puppet 0.25.x? I've seen this cause problems with modern versions of Puppet.
Comment: Just checked and...no.
Answer: You might want to try puppet 3.2.3.
3.2.2 had #21376 similiar  problem, but it was fixed in 3.2.3, it might be regression

puppet 3.2.4: stack level too deep


Android studio - Add linked file to package

Question: How to locate the linked by sourceset java file under the specific package.
for example we have the SomeManager.java file linked by sourceset in android studio it is located under the module node somedemosdk in project view. But we need that it will be located under the package node some.package because this package name defined in SomeManager.java does not recognized by android studio.
Please see the corresponding print screen:
Comment: Are you sure the name `package` is allowed in the name of package?
Comment: instead of package (which is Java reserved name) use `packages` ;-)
Comment: it is just for the example
in real i have different package name
Answer: some.package you need to rename you package to something like some.mypackage. because package is a reserved word in java.
Comment: it is just for the example in real i have different package name


Como fazer com que a variável id não se repita no loop?

Question: Estou tentando receber um array associativo como argumento deste métodos, na verdade recebe um array no primeiro argumento e um valor numérico no segundo.
Minha dúvida é como fazer com que a variável $id não se repita?
Pois está a dar esse erro:

Warning: PDOStatement::execute() [pdostatement.execute]:
  SQLSTATE[HY093]: Invalid parameter number: number of bound variables
  does not match number of tokens in C:\Program Files
  (x86)\EasyPHP-184.108.40.206\www\connect\standardModel.php on line 92

Fonte:
<?php
public function update($data = array(), $id)
{
    if (is_array($data) && count($data) > 0 && $id != false)
    {
        $sql = "update `{$this->table}` set ";

        foreach($data as $key => $value)
        {
            $sql .= $key . " = ?, ";
        }

        $sql = substr($sql, 0, - 2);
        $sql .= "where id = ?";

        $query = $this->db->prepare($sql);
        foreach($data as $value)
        {
            $query->bindValue($value . ",",$id);
        }

        if ($query->execute()) {
            return true;
        } else {
            return false;
        }
    }
}
?>

Comment: A últimas linhas (todo o `if`) podem ser simplificadas para `return $query->execute();`. Não complique o que é simples.
Comment: Pode fazer um bind dinâmico passando os valores no execute http://pt.stackoverflow.com/q/33524/91
Answer: Bem, não sei se isso vai te ajudar, mas já fiz isso uma vez da seguinte forma:

public static function update($tabela, $dados, $condicao = NULL){
    $sql = 'UPDATE '.$tabela.' SET ';
    foreach($dados as $key => $value):
        $campos[] = $key.'=?';
        $valores[] = $value;
    endforeach;
    $sql .= implode(', ', $campos);
    if(!is_null($condicao)) $sql .= ' WHERE '.$condicao;
    try{
        $query = self::$conexao->prepare($sql);
        $query->execute($valores);
    }catch(PDOException $e){
        self::erroLog(__FILE__, __FUNCTION__, $e->getMessage());
    }
}

Explicando:
$tabela eu passo a tabela onde será feito o update.
$dados é meu array que contem os dados.
$condicao é onde eu deixo como null por padrão para atualizar toda a tabela, no seu caso
para atualizar um id específico você pode passar ele como paramêtro.
Ex:
update('tabelaCarros', $arrayDados, 'id=2');
Código completo no GitHub
Answer: Essa mensagem aparece quando a consulta, quando que o número de colunas é diferente do de valores ou seja valores a mais e colunas de menos ou o contrário, no seu código a maneira que demanda menos alterações é atribuir um indíce id no em $data após a montagem da sql, uma variável de controle $i é necessária para informar o número de interrogação combinará com qual valor($value)
O código alterado ficará dessa forma:
$sql = substr($sql, 0, - 2);
$sql .= " where id = ?";
$query = $this->db->prepare($sql);

$data['id'] = $id;
$i = 1; //indice atual da interrogação.
foreach($data as $value)
{
   $query->bindValue($i, $value);
   $i++;
}

//simplificação sugerida pelo @Maniero
return $query->execute();

Comment: Infelizmente tá complicado, já tentei vários exemplos incluindo o que você postou. Já se passou um dia na tentativa , mas faz parte.
Comment: @valdineyfrança quando colocou o código essa linha estava certa? `$query->bindValue($value . ",",$id);` tem uma concatenação de uma virgula inválida


How were neural network trained before backpropagation was proposed?

Question: When learning neural networks one can often hear that Hinton proposed backpropagation in 1986.
After this big leap forward, we could train neural network efficiently.
But I have a question: How did we train a neural network without backpropagation before 1986?
Comment: [This](https://stats.stackexchange.com/questions/235862/is-it-possible-to-train-a-neural-network-without-backpropagation) may be of interest.
Comment: I'm not saying you should always check Wikipedia, but [you should check Wikipedia](https://en.wikipedia.org/wiki/Artificial_neural_network#History) before you ask questions so you can gather more info
Answer: I'm not very sure as to how much people used neural networks back then, due to limitations in computational resources.
There are, however, other methods with which one can train neural nets!

Conjugate gradient, first proposed in 1952
Newton's method (i did not find any reference as to when the formula we use today in NN's was published)
Quasi - Newton method (again, I found no reference to original publish date)
Levenberg-Marquardt algorithm, first published in 1944

For more information on each method, refer to the following link : https://www.neuraldesigner.com/blog/5_algorithms_to_train_a_neural_network
Comment: Note that backprop is not an optimizer, but an algorithm to compute gradients. All the approaches you mention require gradients.


Como manter SDK e JRE Java instalados e atualizados em um ambiente windows de desenvolvimento

Question: Como manter uma instalação java(SDK e JRE) segura, limpa e atualizada do Java em um computador usado para desenvolvimento de software?
Estou com problemas para manter meu ambiente de desenvolvimento, pois tenho as IDE's Eclipse e Android Studio instaladas, assim como algumas outras aplicações que usam o java, e hoje tive um problema enorme após uma atualização do Java, o path nas variáveis do Windows começaram a apontar para pastas que não eram as corretas, e ai Eclipse e o Android Studio param de funcionar, depois ajustei isso e o Tomcat se perdeu.
Answer: Não sei existe alguma outra maneira de as variável de ambiente de forma mais prática, fiz um script em powershell para automatizar esse processo.
Limitações:

Sua variável de ambiente precisa ter o nome de  JAVA_HOME caso seja outro nome é necessário substituir as ocorrencias de JAVA_HOME pelo nome da sua variável.
Algumas instalações do java não possuem o local de instação logo elas não serão exibidas.

clear
write-host "Aguarde..."
[object[]]$r =  (Get-WmiObject win32_product -Filter " name like 'JAVA %'")

$javaHome = "JAVA_HOME"

Write-Host "Valor atual do JAVA_HOME: $env:JAVA_HOME `n"

$opcao = 0
$itensValidos = @()
foreach($item in $r){
    if($item.InstallLocation -ne $null){
          Write-Host $opcao - $item.Name - $item.InstallLocation
          $itensValidos += $item
          $opcao++
    }
}

$selecionado = Read-Host "`nInforme qual instalação do java será definida em JAVA_HOME"

if($selecionado -lt 0 -or $selecionado -gt $itensValidos.Count -1){
   Write-Host "Opção invalida"
}

[Environment]::SetEnvironmentVariable($javaHome, $itensValidos[$selecionado].InstallLocation +"lib" , 'Machine')

Funcionamento
É feita a pesquisa de todos os softwares instalados que possuem JAVA nome, as linhas seguintes exibem o menu com as instalações válidas do java (aquelas que tem o caminho da insalação), depois é feita solicitação de será o nome caminho de JAVA_HOME e por último é feita a mudanção com o método SetEnvironmentVariable().
Fontes:
Windows PowerShell Tip of the Week
Classe Environment .net
Get-WmiObject
Comment: Só um adendo, tive que tirar o 'lib' do final dessa linha aqui [Environment]::SetEnvironmentVariable($javaHome, $itensValidos[$selecionado].InstallLocation **+"lib"** , 'Machine')
para funcionar corretamente, o android studio dizia que não encontrava uma versão válida da JVM, e passando o path para a pasta de instalação, exemplo: 'C:\Program Files\Java\jdk1.7.0_55\' funcionou
Comment: @alexandre werner, obrigado pela correção vou editar depois.


Which document describes which application icon sizes are needed to submit an app?

Question: It's crazy, but I can't find it. The HIG seems to talk only about system icons like "favorites", "search", etc.
Is there a special document that talks about this? Also, how must these icons be called and where must they be added?
Answer: Have you checked iTunes Connect Developer Guide? It describes submission related things.
Answer: I've only been able to kind of distill it from the HIG, but here's a blog post that's very helpful:
http://kgutteridge.co.uk/blog/2010/07/04/icon-sizes-filenames-for-ios-devices/

iTunesArtwork – Icon for iTunes AdHoc distribution (512×512)
firstname.lastname@example.com – Home screen icon for iPhone 4 (114×114)
Icon-72.png – Home screen icon for iPad (72×72)
firstname.lastname@example.com – Settings/Spotlight icon for iPhone 4 (58×58)
Icon.png – Home screen icon for iPhone 3 (57×57)
Icon-Small-50.png – Spotlight icon for iPad (50×50)
Icon-Small.png - Settings/Spotlight icon for iPhone 3 (29×29)

Might also check this out too for a bit more crucial info:
mrgan.tumblr.com/post/708404794/ios-app-icon-sizes
Answer: This is detailed in Apple's Technical Q&A QA1686: App Icons on iPad and iPhone.
Answer: Since this is one of the first questions that comes up when searching for the necessary icon sizes for iOS Apps, and in the meantime, things have changed again with the appearance the new iPad ("3"), I'd like to add the currently relevant information here:
Apple has conveniently collected all the details about custom icons and images in one place now. Here goes: iOS Human Interface Guidelines: Custom Icon and Image Creation Guidelines


Non-trigonometric/vector way of solving a property of a tangent line on an ellipse

Question:
Suppose that there is line $l$ that is tangent to an ellipse $A$ at
  point $\,P\,$.
The ellipse has the foci $F'$ and $F$.
One then creates two lines - each from each focus to the tangency
  point $\,P\,$ .
What I want to prove is that the acute degree formed at $P$ between
  $l$ and the line segment $F'P$ equals the acute degree formed between
  $l$ and the line segment $FP$ .
How would I be able to prove this?
(ellipse has a horizontal axis as a major axis.) (from Proving a property of an ellipse and a tangent line of the ellipse)

Is there any way to do this without using trigonometry? I do understand the answers there, but I also need purely geometric ones without calculus, vector and trigonometry...
Answer: Ok. I will prove that the external bisector of $\widehat{FPF'}$ is tangent to $A$ in $P$. Take $X$ on $FP$ such that $PX=PF'$ and $P$ lies between $F$ and $X$. In this way, $XF'$ is parallel to the internal angle bisector of $\widehat{FPF'}$. Call $r$ the external bisector of $\widehat{FPF'}$. Suppose that there is a point $Q\neq P$ on $r$ belonging to $A$:
$$ FX = FP+PF' = FQ + QF' = FQ + QX $$
must hold, but this is clearly impossible, since there is a unique point $P$ on $r$ such that $FP+PX=FX$. Since we got a contradiction, we have that the only point belonging to both $r$ and $A$ is $P$, so $r$ is tangent to $A$.


Systems of equations over reals

Question:
Solve over reals
  $$2x^2+xy+x-3y+3=0$$
$$3xy+y^2-2x+6y-6=0$$

Adding or subtracting these equations doesn't help, and completing the square also doesn't work. I'm considering substituting $x+y$ and $xy$, but it also doesn't show much promise. Thanks!
Comment: Multiplying the first equation by two, then adding the result to the second equation, gives:

$$4x^2+5xy+y^2=0$$

which is equivalent to

$$(2x+y)^2=-xy$$

Since the left hand side is non-negative (it's a square), the right hand side must be non-negative as well $$-xy \geq 0 $$

We can exclude $x=0$ or $y=0$ quite easily, by plugging them in. Therefore, $$-xy > 0$$ is a strict inequality, which means that $x$ and $y$ must be opposite signs.
Comment: On another note, both the first equation and the second equations are equations of [conic sections](https://en.wikipedia.org/wiki/Conic_section). In particular, they are the equations of [hyperbolas](https://en.wikipedia.org/wiki/Hyperbola).
Answer: $$2x^2+xy+x-3y+3=0\tag{1}$$
$$3xy+y^2-2x+6y-6=0\tag{2}$$
Take 2$\times$(1)+(2) to get,
$$4x^2+5xy+y^2=0 \implies (4x+y)(x+y)=0$$
which yields $y=-x$ and $y=-4x$. Plug them into (1)
$$x^2+4x+3=0\implies x=-1,\>x=-3$$
$$2x^2-13x-3=0\implies x=\frac{13\pm\sqrt{193}}{4}$$
Then, evaluated the corresponding $y$'s to obtain the follow solutions,
$$(-1,1),\>\>\>(-3,3),\>\>\>
\left(\frac{13+\sqrt{193}}{4},-13-\sqrt{193}\right),
\left(\frac{13-\sqrt{193}}{4},-13+\sqrt{193}\right)$$
Comment: Nice, +1 I missed the factorization of $4x^2+5xy+y^2=0$
Comment: @ZubinMukerjee - Just saw your comments. Similar path.
Comment: Yes, always worth a try to get rid of the additive constants.
Answer: Another way to do it.
From the first equation, extract $y$
$$y=-\frac{2 x^2+x+3}{x-3}$$
Plug $y$ in the second equation to get
$$\frac{-2 x^4+5 x^3+49 x^2+51 x+9}{(x-3)^2}=0$$ By inspection $x=-1$ and $x=-3$ are roots of the numerator. So, we are left with
$$\frac{(x+1) (x+3) \left(2 x^2-13 x-3\right)}{(x-3)^2}=0$$ So, the four roots for $x$ and the corresponding $y$'s.

Systems of equations over reals


Windows: Print to printer from R - quick and dirty is OK

Question: On a Windows PC, how can I quickly print a data.frame to a printer?  It doesn't have to be pretty; just trying to get it printed out for documentation purposes.
I'm aware of this SO question How to print (to paper) a nicely-formatted data frame and answers but I'm really looking for something that just prints out the text
Comment: Copy/paste it into notepad and print that.
Answer: Here's a bit of code that I use all the time:
print_to_printer <-function(df, addquotes = FALSE){
write.csv(df, "c:\\PRINT_ME.txt", quote = addquotes)
shell("NOTEPAD /P c:\\PRINT_ME.txt")
cat(quote(df), " has been printed to printer")}

then you can use it with
print_to_printer(my_df)

if your data.frame is called my_df.  Your can change the printed quotes on or off, as needed.
I have to give credit to Alin Constantin for helping me to derive the solution in R:   http://alinconstantin.blogspot.com/2012/08/notepadexe-command-line-arguments.html


Como listar várias colunas usando o Inner Join e o left join?

Question: Como posso fazer para pegar dados de duas tabelas?
Exemplo.

os campos
`assunto,nomeremetente,cpfremetente,observacao` da tabela **protocolos**

e o datacriacao da tabela protocolo_documentos
é do protocolo_documentos é dataformat(datacriacao,'%d/%m/%Y') as datacriacao ficando assim a query de inicial .
$Query ="SELECT
                        dataformat(datacriacao,'%d/%m/%Y') as datacriacao,
                         assunto,nomeremetente,cpfremetente,observacao
                           FROM protocolos
                               ORDER BY formatted_date DESC";

Comment: [Qual é a diferença entre INNER JOIN e OUTER JOIN?](http://pt.stackoverflow.com/q/6441/91)
Comment: @rray Você tá muito rápido hoje :p
Comment: @rray quer pegar somente a datacriacao da tabela  protocolo_documentos e o restante da tabela protocolos.
Comment: @allanaraujo, qual relação entre as tabelas?
Comment: Quero pegar todos os dados  assunto,nomeremetente,cpfremetente,observacao  e trazer conforma o datacriacao  de protocolo_documentos
Answer: Você precisar especificar a relação entre as duas tabelas na clausula ON, conforme o exemplo abaixo
SELECT dataformat(pd.datacriacao,'%d/%m/%Y') as datacriacao, p.*
FROM protocolos p
join protocolo_Documentos pd
on pd.protocolo = p.protocolo -- aqui tem que ser a relação entre as duas tabelas
ORDER BY formatted_date DESC

Quanto ao uso do JOIN ou LEFT JOIN, veja como usar aqui.


What is the relationship betwen covariance, covariance matrix and cross-correlation?

Question: I am not good at math and apologize if I made stupid mistakes in this question.
Assume I have two random variables X = [1, 2, 7, 3, 0, 10 ...] and Y = [12, 1, 5, 7, 9, ...].
According to the definition, cov(X,Y)=E[(X-E[Y])(Y-E[Y])] = E[XY]-E[X][Y], so it looks like a scalar to me, which measures how X is related to Y. If I am writing a python script to calculate it, it will be like:
import numpy as np
X = [1, 2, 7, 3, 0, 10]
Y = [12, 1, 5, 7, 9, 4]
X=np.asarray(X)
Y=np.asarray(Y)
cov = (X*Y).mean()-X.mean()*Y.mean()
print(cov)
# output is -5.944444444444446

But if I use numpy.cov(X,Y), it returns a 2 x 2 matrix:
import numpy as np
X = [1, 2, 7, 3, 0, 10]
Y = [12, 1, 5, 7, 9, 4]
c = np.cov(X,Y, rowvar = True)
print(c)
# output is [[14.96666667 -7.13333333]
            [-7.13333333 15.06666667]]

How should I interpret the above 2x2 matrix?
I guess, if I treat X and Y as two time sequenes, I can calculate cross correlation like this:
print(np.correlate(X,Y))
# output is 110

So my questions are:
(1) How cross-corrlation is related to just covariance, if X and Y can be seen as time sequences?
(2) According to the above case, what is the relation between my calculated scalar value and the 2x2 matrix obtained from numpy.cov(x,y)?
Answer: np.cov function returns you a covariance matrix, where off-diagonal entries are covariances and diagonal entries are variances. The covariance estimate of np.cov is unbiased (check bias argument), which means the normalisation is done with $N-1$, here $5$, since there are $6$ observations. It'd be $-7.13\times 6/5\approx -5.94$ if it was normalised by $N=6$. That is precisely what you do while you're taking means in your implementation. Also, np.correlate with default arguments apparently calculates the dot product of the vectors.


Does $P(X\leq a) = P(X^2\leq a^2)$ if $X$ is a positive random variable and $a>0$?

Question: The answer looks positive to me, since $$P(\omega:X(\omega) \leq a) = P(\omega:X(\omega)^2\leq a^2)$$
Am I right?
Comment: yes you are right.
Answer: If $X(\omega) > 0$ for all $\omega$, and $a>0$, then
$$
    X(\omega)^2 \leq a^2 \iff X(\omega) \leq a
$$
So as sets,
$$
    \{\omega : X(\omega)^2 \leq a^2\} = \{\omega :  X(\omega) \leq a\}
$$


NHibernate query using Expression> not working

Question: I have a repository interface which defines the following method:
IEnumerable<T> GetMany(Expression<Func<T, bool>> where);

I have implemented two, almost identical repositories which implement this interface. My first repository uses the Entity Framework. It implements the above method as:
private readonly IObjectSet<T> _objectSet;

public IEnumerable<T> GetMany(Expression<Func<T, bool>> whereExpression)
    {
        return _objectSet.Where(whereExpression);
    }

When I run my program I can see that the above method successfully translates 'whereExpression' into SQL and the query only returns entities which match my whereExpression.
My second repository uses NHibernate and implements the method as follows:
private readonly ISession _context;

public IEnumerable<T> GetMany(Expression<Func<T, bool>> whereExpression)
    {
        return _context.Query<T>().Where(whereExpression);
    }

The above doesn't work though. My query returns nothing. It doesn't look to me like any SQL is being generated at all when I use NHibernate. Can anyone explain how I can get this to work using NHibernate? Ultimately I want to be able to pass a where clause to th repository and have NHibernate translate that into SQL.
As an aside point, I read that I need to use Expression> as opposed to just Func when implementing this. I can successfully get this to work using Func, but it seems to load every record from the database and apply the whereExpression afterwards. This means I load far more entities than I actually want. Is my understanding of this correct?
***EDIT TO ORIGINAL POST
This is very strange, but I've just gotten this to work by changing my whereExpression. I had been requested that the query return all entities whose ID was an even number:
var results = productRepository.GetMany(a => a.Id % 2 == 0);

I changed this to:
var results = productRepository.GetMany(a => a.Price > 0m);
And it worked immediately. So this looks like it caused by trying to query on the ID of the entity. I am using the HiLo ID generator for NHibernate. Any idea why I can't query on the ID value?
**ANOTHER EDIT
This also doesn't work:
var results = productRepository.GetMany(a => a.UnitsInStock % 2 == 0);

yet this does:
var results = productRepository.GetMany(a => a.UnitsInStock > 400 == 0);

Units in stock is just an integer column. It looks to me like the modulo operator doesn't work with NHibernate and Linq.
Comment: Have you tried QueryOver() instead of Query()?  The differences are mentioned here: [Tradeoffs using NHibernate 3.0 QueryOver or LINQ provider](http://stackoverflow.com/questions/3874012/tradeoffs-using-nhibernate-3-0-queryover-or-linq-provider).
Comment: I haven't actually. Will look into it thanks.
Answer: You must call ToFuture() or ToList() for actual fetch data from database.
private readonly ISession _context;

public IEnumerable<T> GetMany(Expression<Func<T, bool>> whereExpression)
{
    return _context.Query<T>().Where(whereExpression).ToFuture();
}

or
private readonly ISession _context;

public IEnumerable<T> GetMany(Expression<Func<T, bool>> whereExpression)
{
    return _context.Query<T>().Where(whereExpression).ToList();
}

UPDATED
According to updated information: this is limitations of linq for NHibernate provider implementation.
Comment: This doesn't work either unfortunately. I still see no SQL generated and I get an exception: Operation is not valid due to the current state of the object


Type 'Observable' is not assignable to type 'Observable'

Question: Eu estava fazendo um curso de Angular 10 + Spring boot e me deparei com o seguintes erros:

Type 'Observable' is not assignable to type 'Observable'.
Type 'ArrayBuffer' is missing the following properties from type 'Entidade': id, description, done, createdDate, doneDate.
Argument of type 'String' is not assignable to parameter of type 'string'.
'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible.

Esse erro ocorre na classe corpo.service.ts.
Classes abaixo:
corpo.service.ts
import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';
import { Entidade } from './entidade'

import { HttpClient } from '@angular/common/http'

@Injectable({
  providedIn: 'root'
})
export class CorpoService {

    apiURL: String = 'http://localhost:8080/api/entidades';

  constructor(
   private http: HttpClient
  ) { }

  salvar (Entidade: Entidade) : Observable<Entidade>{
  return  this.http.post<Entidade>(this.apiURL, entidade)
}
}

entidade.ts
export class Entidade {
    id: number;
    description: string;
    done: boolean;
    createdDate: string;
    doneDate: string;
}

app.component.ts
import { Entidade } from './entidade';
import { Component } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms'
import { CorpoService } from './corpo.service'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  form: FormGroup = new FormGroup({
    description : new FormControl('')
  })

  constructor (
    private service: CorpoService
  ){}

  submit(){
    console.log(this.form.value)
    const entidade: Entidade = { ...this.form.value}
    this.service
    .salvar(entidade)
    .subscribe(savedEntidade => console.log(entidade) )
  }
}

Alguém poderia me ajudar?
Comment: O que seria **entidade** neste trecho: `return  this.http.post(this.apiURL, entidade)`?
Comment: No caso seria ele estaria salvando os atributos da classe entidade.ts
Answer: Pessoal já descobri o erro, no caso o erro estava no apiURL: String = 'http://localhost:8080/api/entidades';
eu alterei a String para string e deu certo.


javascript length duration

Question: i have following function in php, how can i convert this in javascript?
 function length_duration ($seconds)
 {
  $hours = $mins = $sec = NULL;

  //for seconds
  if($seconds > 0)
   $sec = ($seconds % 60 < 10) ? "0".($seconds%60) : ($seconds%60);

  //for mins
  if($seconds > 60)
   $mins  = (($seconds/60%60)<10) ? "0".($seconds/60%60).":" : "".($seconds/60%60).":";

  //for hours
  if($seconds/60 > 60)
   $hours = (($seconds/60/60) < 10) ? "0".($seconds/60/60).":" : "".($seconds/60/60).":";

  return $hours.$mins.$sec;
 }

Answer: mostly remove the $, replace . with +, declare variables with var and use ~~ to deal with the funny way javascript handles decimals
demo: http://jsfiddle.net/kR4Pz/1/
function length_duration (seconds)
 {
  var hours = '', mins = '', sec = '';

  //for seconds
  if(seconds > 0)
   sec = (seconds % 60 < 10) ? "0"+(seconds%60) : ""+(seconds%60);

  //for mins
  if(seconds >= 60)
   mins  = ~~(((seconds/60)%60)<10) ? "0"+~~((seconds/60)%60)+":" : ""+~~((seconds/60)%60)+":";

  //for hours
  if(seconds/60 >= 60)
   hours = ~~(((seconds/60)/60) < 10) ? "0"+~~((seconds/60)/60)+":" : ""+~~((seconds/60)/60)+":";

  return hours+mins+sec;
 }

Comment: Double bitwise complement to force a number to integer?  How amusing.
Answer: There are a few differences in rounding and number-to-string conversion between the two languages.  Also, there are a couple of bugs in the original, where for example a time of exactly one minute would format incorrectly.
function length_duration (seconds)
{
  var hours = "", mins = "", sec = "";

  //for seconds
  if(seconds > 0)
   sec = (seconds % 60 < 10) ? "0"+String(seconds%60) : ""+String(seconds%60);

  seconds -= (seconds % 60);

  //for mins
  if(seconds >= 60)
   mins  = ((seconds/60%60)<10) ? "0"+String(seconds/60%60)+":" : ""+String(seconds/60%60)+":";

  seconds -= (seconds % (60*60));

  //for hours
  if(seconds/60 >= 60)
   hours = ((seconds/60/60) < 10) ? "0"+String(seconds/60/60)+":" : ""+String(seconds/60/60)+":";

  return hours+mins+sec;
}

javascript length duration


How to convert ebcdic format to ASCII using Scala?

Question: How do I convert EBCDIC format to ASCII using Scala programming?
Comment: What have you tried? What specifically are you stuck on?
Comment: i can convert EBCDIC format to ASCII in Unix by this 'dd if=input_file of=output_file conv=ascii' but i want do same conversion in scala.
Answer: Something along the lines of
<code>import java.nio.file._

val ebcdicBytes = Files.readAllBytes(Paths.get("/whereEver/myEbcdicFile"))
val asciiBytes = new String(ebcdicBytes, "Cp1047").getBytes("ASCII")
</code>
might work.
Comment: i can convert EBCDIC format to ASCII in Unix by this 'dd if=input_file of=output_file conv=ascii' but i want do same conversion in scala.
Comment: Ok. The above code converts ebcdic to ascii using Scala (at least it should: I didn't bother testing it on any ebcdic-encoded files). Does it answer your question? If not: is anything unclear? I mean, it's like 2 lines, everything is built-in already...
Comment: Good. It looks like you should have enough material for an [MCVE](https://stackoverflow.com/help/mcve) by now. It would be nice if you could somehow provide an example of the file for which the problem occurs.
Comment: i need to do same as this in scala https://stackoverflow.com/questions/20349491/converting-ebcdic-to-ascii-in-java


Extending isometries between compact subspaces of Cantor space

Question: Let $\omega$ be the set of natural numbers. $2^\omega$ is the Cantor space.
Suppose $K$, $L \subset 2^\omega$ are compact, and there is an isometry $f: K \to L$.  Then how could one extend $f$ to an isometry from $2^\omega$ to $2^\omega$?  Here we are considering $2^\omega$ with the minimum difference metric, which gives the standard product topology; i.e.
$ d(x,y) = 2^{-\min \{ n : x(n) \neq y(n) \}}. $
Comment: @tomasz All isometries that I know arise as compositions of partial reflections. By which I mean the following construction: pick a finite binary sequence $a_1,\dots, a_n$. If $x\in \{0,1\}^{\omega}$ begins with this sequence, then flip all of its digits after $n$th. Otherwise leave it as it was. This can be visualized by reflecting a part of infinite binary tree around the axis of symmetry of that part.
Comment: Can someone give an example of an exotic isometry of the Cantor space (that is, one which isn't just a translation)? If there were none, it should be very easy to extend the isometry, if at all possible.
Comment: @tomasz Oh, I did not realize that by translation you meant group translations. I'm not used to thinking of this space as a group.
Comment: @LeonidKovalev: yeah, you're right, I didn't think of that. But you need not flip all the bits after $n$th, you may flip only some arbitrary ones. (In the previous comment I did not notice that you flip bits only for SOME sequences, that's why I deleted it). Still, that doesn't strike me as very exotic. I wonder if that's all of them. :)
Comment: @tomasz OK, let's summarize: for any collection of functions $f_n : \{0,1\}^n\to \{0,1\}$ we get an isometry $F$ such that the $n$th digit of $F(x)$  is $f_n$ applied to the beginning of $x$. Any map not of this kind must change some digit based on a later digit... I doubt this could be isometric.
Comment: @tomasz Indeed these are all isometries. If $x$ and $x'$ agree in the first $n$ digits, then their images under any isometry also agree in the first $n$ digits. Hence, the isometry must be of the kind described in the previous comment.
Comment: Oops, forgot that $ f_n$ must be linear in the last variable, that is $f_n=x_n+g_n (x_1,\dots x_{n-1})$.
Answer: When $u$ is a finite binary word, $u\cdot 2^\omega$ means the interval of $2^\omega$ formed by infinite words with prefix $u$ ($\cdot$ denotes word concatenation).
Let $A_{fin}$ be the set of finite prefixes of $A\subseteq 2^\omega$.
We say that $F: A_{fin}\to B_{fin}$ is an isometry if:

$|F(x)|=|x|$;
$x\preceq y$ implies $F(x)\preceq F(y)$ where $\preceq$ is the prefix relation;
$F$ is injective, or equivalently $F(x0)\ne F(x1)$ when both are in the domain of $F$.

Side-note: When $A_{fin}=B_{fin}$ (or more generally, when the multiset of word lengths of $A_{fin}$ and $B_{fin}$ coincide), the last condition can also be replaced by "$F$ is bijective". The first condition then becomes redundant.

Lemma: The relation
  $$\forall u\in A_{fin}, \quad f(u\cdot 2^\omega)\subseteq F(u)\cdot 2^\omega$$
  is a bijection between isometries $f: A\to B$ and isometries $F: A_{fin}\to B_{fin}$.

Proof:

When $uv\in A$, $F(u)$ must be the first $|u|=n$ symbols of $f(uv)$. This constructs $F$ in a well-defined way because $d(f(uv),f(uw))=d(uv,uw)\le 2^{-n}$. When $x\ne y$, if $|x|\ne|y|$ then of course $F(x)\ne F(y)$; otherwise $d(f(x),f(y))=d(x,y)>2^{-|x|}$ therefore $F(x)\ne F(y)$.
Conversely, $f(x)=\lim_{u\preceq x} F(u)$ is well-defined by monotony of $F$, and if $d(x,y)=2^{-n}$ we can let $u0,u1$ be the prefixes of length $n+1$ of $x,y$: $2^{-n}=d(u0,u1)=d(F(u0),F(u1))=d(f(x),f(y))$.

Side-note: this also gives the following statement, which was not a priori obvious:

Corollary: An isometry $f: A\to A$ on $2^\omega$ is a bijection.

Corollary: Isometries $A_{fin}\to B_{fin}$ as defined above are precisely the isometries $A_{fin}\to B_{fin}$ under the minimum difference metric and under word length, where the metric is extended to finite words by $d(x,u)=\max d(x,u0^\omega),d(x,u1^\omega)$. This justifies the use of the word "isometry".

Theorem: Let $A,B$ be arbitrary subsets of $2^\omega$. An isometry $f: A\to B$ can be extended to an isometry $g: 2^\omega\to 2^\omega$. As could also be shown by topological arguments, the extension is unique if and only if $A_{fin}=(2^\omega)_{fin}$, that is iff $A$ is dense in $2^\omega$.

Proof: We just have to extend an isometry $F:A_{fin}\to B_{fin}$. When $u$ is non-empty, let $\sigma_F(u)$ be the last symbol of $F(u)$. We have that $\sigma:\{0,1\}^+\to\{0,1\}$ is the last symbol of an isometry $(2^\omega)_{fin}\to (2^\omega)_{fin}$ if and only if $\sigma(x1)=\neg \sigma(x0)$. So we can define $$\sigma(x0)=\begin{cases}
\sigma_F(x0) & x0\in A_{fin}\\
\neg\sigma_F(x1) & x1\in A_{fin}\\
0 & \text{else}
\end{cases}$$
so that the relations $\sigma(x1)=\neg \sigma(x0)$ and $G(ua)=G(u)\sigma(ua)$ uniquely define an isometry $G: (2^\omega)_{fin}\to (2^\omega)_{fin}$. $G$ extends $F$, so the isometry $g: 2^\omega\to 2^\omega$ extends $f$.
Comment: Thanks for the very thorough explanation! (You did not define $2^*$, but I understand it is $(2^\omega)_{fin}$).


Foco em Elementos HTML com javascript

Question: Tenho o seguinte código. Este código contem 5 divs onde ao clicar sobre cada uma ,a que foi clicada recebe um valor de background.Quero que após clicar em uma delas,no próximo clique, a que foi clicada perca o beckground sem alterar as demais.
EX.:Cliquei na div 1 ,ficou vermelha.Cliquei na div 2 ,ficou vermelha,Cliquei na div 1 perdeu a cor vermelha ,mas a 2 tem de continuar vermelha.

 $(function () {

 $('.Classe').click(function () {

 $(this).css('background','red');

 });

 });

valor 1

valor 2

valor 3

valor 4

valor 5

Answer: Vc pode criar um classe que chama .ativa por exemplo e usar o método toggleClass para colocar e retirar o background vermelho quando clicar.
Veja o exemplo para entender melhor. Repare que no primeiro clique eu adiciona a classe .ativa que tem o background vermelho, e no segundo clique eu faço o toggleClass para remover essa classe assim retirando o vermelho do fundo.

$(".Classe").click(function(event){
   $(this).toggleClass("ativa");
});
div.ativa {
  background-color: #f00;
}

valor 1

valor 2

valor 3

valor 4

valor 5

Foco em Elementos HTML com javascript


What is it called to play a music with flowing tempo in piano?

Question:
What is it called to play a music with flowing tempo in piano ?

What I mean by "flowing tempo" is that when you, for example, start the music by playing it strong and little fast, but then you play soft and rather slow etc. like moving on a wave.
Comment: Rubato - where the player stretches and squashes the timing?
Answer: Rubato.   This specifically means compensating for each slow-down with a speed-up.  If there was a click track, you'd come out on the right beat at the end!
'Rubato' doesn't instruct you to play the slow bits soft, the fast bits loud though.
If you want the more common effect of slowing down at the 'expressive' bits but never really making up the time, just use one of the many words that mean 'Freely', 'with expression' etc.
Comment: I think of Chopin every time the word "Rubato" is mentioned
Comment: Chopin was fond of writing decorative passages where keeping strict tempo would be rushed, if not impossible to play!  But this isn't really 'rubato'.
Answer: It's what it sounds like... flowing. It is a feel thing. When you play enough music you start to get an innate sense of these things that are extremely nuanced. They cannot be described because they are a complex of interactive elements.
Tempo is not just a metronome. Tempo is a feeling of both time, rhythm, melody, harmony, dynamics, etc(and every one of those elements are elements of every other one).
For example, suppose a piece of music goes from point A to point B in whatever way it does. Now, suppose all you do is change one element such as the dynamics. For the music to flow, the tempo might have to be subtly changed.
Why? Because that is the way it is. It can be because of simple performance reasons such as when you play at ff it changes the physical way you play which alters the timing. If you try to play it the same way as pp it will sound/feel wrong(or not quite as good or right).
It is such a complex thing that when you try to overthink it you end up making it worse. Simply play, you will understand everything in due time. If it doesn't feel right, it isn't... and it's simple as that.
Now, you might say that what if we just change the expressive indication from flowing to calando or from allegro to adagio? Well, the composer tries to chose the closest tempo indicator that he can that works with all the other elements. Have you ever noticed that with some pieces that if you alter the tempo even a little that it destroys the feel while with others it doesn't seem to matter? Well, that is precisely because of all the other elements that are in play.
Again, we can try to parse everything build a tomb of what is going on, but your brain can figure this stuff out instantly if you just allow it to do it's job. It's called experience and it's something that you learn over a long period of time.
Don't get bogged down in the details. Most of the great musicians don't "know" shit as far as "theory" is concerned. They just played and learned to play well then people think it's great and special and try to figure out what makes it special and codify rules which only confuses people like you.
Also, each person is different and will have subtle differences in how they perform something due to their physical differences(hand size, finger length, muscle strength, etc) along with their experiences, etc.
Flowing means to flow, like water flows... it can flow smoothly or like rapids. It's just a word, it means nothing because water actually doesn't flow but it lets you know something is going on. Physics would tell you it's gravity at work, Zen Buddhists will tell you it's all in your head, it doesn't matter. It is what it is. If you really want to get somewhere, get nowhere! (which you probably don't get because you are too busy trying to get somewhere... so I will interpret, it means stop overthinking it and just do!)


How to find the entity specific named id?

Question: How do I map entity type to the entity specific named id, like this:
node => nid
taxonomy_term => tid
comment => cid

so that I can turn code like
 $entity->nid

into something like
$entity->{$label}

and correctly handle non-node entities.
Answer: This should do it (definitely works for all core entities, I don't have any custom entities to play with on my sandbox site I'm afraid):
$type = 'taxonomy_term';

// Get the entity type info
$info = entity_get_info($type);

// Grab the id key
$key = $info['entity keys']['id'];

// $key contains 'tid'

I'm pretty positive this will work across any entity type though, according to hook_entity_info() the id property of entity keys is required:

Every entity object passed to the Field API must have this property and its value must be numeric.


Python - No module named pygst

Question: I'm using virtualenv on Ubuntu 14.04 with Python 2.7.13, and I'm trying to get import pygst to work (I'm a complete Python noob).
I downloaded:
https://gstreamer.freedesktop.org/src/gst-python/gst-python-1.12.1.tar.xz
Compiled and installed with:
./configure --prefix=$VIRTUAL_ENV && make install
However I still cannot import pygst:
>>> import pygst
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named pygst

There's also no pip package that matches pygst. I must be missing something really simple, but I can't figure it out.
This does not help either, because it only affects the system Python installation, not virtualenv:
sudo apt-get install python-gst0.10 gstreamer0.10-plugins-good gstreamer0.10-plugins-ugly

How do I install pygst with virtualenv?
Comment: Did you try using `sudo apt-get install ` ?
Comment: http://www.techinfected.net/2017/01/how-to-install-python-gst-in-ubuntu.html
Comment: @code_byter Yes. This is not the system python installation. It's a virtualenv. Installing the `python-gst0.10` modules do not help.
Comment: `pip install`inside your virtualenv folder.
Comment: Another way mentioned here is to use the python interpreter of your choice: http://python-guide-pt-br.readthedocs.io/en/latest/dev/virtualenvs/ - where you can specify your local python
Comment: There is no pip package for pygst.
Comment: Try to acrivate your virual environment with the `.\bin\activate` script, and then run `pip install` with your's package
Comment: @YuvalPruss I did that, but there does not exist a pip package for pygst. At least I cannot find one. `pip install pygst` -> `Could not find a version that satisfies the requirement pygst`.
Comment: try to `apt-get install python-pip` in the activate mode.
Answer: You need to install the pygst module
sudo apt-get install python-gst0.10 gstreamer0.10-plugins-good gstreamer0.10-plugins-ugly

Then if you want access it in you virtualenv you can make a symlink to your site-packages, just replace 'venv' with the foldername of your virtualenv.
cd venv/lib/python2.7/site-packages
ln -s /usr/lib/python2.7/dist-packages/glib
ln -s /usr/lib/python2.7/dist-packages/gobject
ln -s /usr/lib/python2.7/dist-packages/gst-0.10
ln -s /usr/lib/python2.7/dist-packages/gstoption.so
ln -s /usr/lib/python2.7/dist-packages/gtk-2.0
ln -s /usr/lib/python2.7/dist-packages/pygst.pth
ln -s /usr/lib/python2.7/dist-packages/pygst.py
ln -s /usr/lib/python2.7/dist-packages/pygtk.pth
ln -s /usr/lib/python2.7/dist-packages/pygtk.py

Comment: Ok. I was able to get this to work by accepting that I had to downgrade to pygst 0.10. Two additional changes were needed: 1) Compile Python with `--enable-unicode=ucs4`, 2) `ln -s /usr/lib/python2.7/dist-packages/gi` in the `site-packages` folder. Thanks for your help.

Python - No module named pygst


LSI SCSI Card Slow With LTO4

Question: In a Ubuntu system I have an LSI card with a 53C1030 controller and I'm getting write speeds to LTO4 tape at only 4MiBps. The drive should be capable of 120MBps.
I have found a copy of lsiutil and attempted to enable write caching but I don't have the proper options under the RAID menu.
Is there some other form of configuration I need to do? Or is there a compatibility or hardware problem?
Here is some information on the card:
$ lspci | grep SCSI
04:08.0 SCSI storage controller: LSI Logic / Symbios Logic 53c1030 PCI-X Fusion-MPT Dual Ultra320 SCSI (rev c1)

Here is the result of identify in lsiutil
Current active firmware version is 01032700 (1.03.39)
Firmware image's version is MPTFW-01.03.39.00-IT
 LSI Logic
x86 BIOS image's version is MPTBIOS-5.05.21.00 (2005.10.03)

Comment: For starters, this is some seriously old equipment. Has it ever worked in this workload, or is this you putting it into service?
Comment: This is a "new" installation of used equipment for personal use. These parts have never been used together before.
Answer:
Caching does not work on tape/sequential devices.
Make sure that each SCSI channel is properly set up:

exactly two active, LVD or LVD/SE terminators
at least one device providing termination power
no mixing of single-ended and differential devices
no branches
decent LVD cables - LVD cables use twisted pairs, no straight ribbon

Check the HBA's BIOS setup for device config, set the LTO to U320, synchronous, parity.
Comment: I've got the new SCSI card installed an now I'm getting 60MiBps. So I'd say problem solved.
Comment: The LTO4 drive is the only device connected to the card. I believe it has a build in terminator. In BIOS I only get options for "multi initiator configuration". There are no pre-drive settings.
Comment: "I believe it has a built-in terminator" is likely wrong. LVD devices usually don't.
Comment: https://docs.oracle.com/cd/E21418_01/en/CRCM2177/CRCM2177.pdf page 17 shows the jumper on the back for the terminator. I have a non-ribbon LVD cable. I'm not sure it it is internally twisted pair.
Comment: That manual is for Certance LTO-1 and LTO-2 drives. These drives can optionally provide *termination power* which is *not termination* - check bottom of page 18.
Comment: Alright, my LTO4 drive also has that jumper but I cannot find an proper install manual for it so I just used the LTO1/2 version. But if it still isn't a built in terminator then it wont work. My cable only has two LVD connectors on it, so I assume I will need a pass-through terminator.
Comment: What's the model? Are the jumpers labeled? Usually, `TE` stands for *termination enable* while `TP` refers to *termination power*. You need at least one device providing termination power (usually the HBA) and one active terminator on each end of the bus.
Comment: It's an HP EH921B. The jumpers are labeled. It is labeled as `TP`. It's in the middle of a 26hr write operation right now, tomorrow I'll try pulling the `TP` jumper to see if that makes a difference. Since there are only two LVD connectors on my cable adding a terminator(which I don't currently have) will be difficult.
Comment: Disabling TP won't make a difference (unless it's the only TP, then it'll get worse). You need a terminator. You can get LVD cables with integrated terminators very cheap used.
Comment: In the [quickspecs](https://h20195.www2.hpe.com/v2/getpdf.aspx/c04123270.pdf?ver=14) page 13 you can read *No terminator is required for SCSI internal models (assumes use of terminated cable).* This implies there's no termination on the drive.
Comment: Ok, that's good to know. I've ordered a pass through terminator which I should receive in about a week. Thank you for the help. I'll report back with the outcome when I get the terminator installed.
Comment: The [pass through terminator](https://i.imgur.com/tADdfkv.png) came in early and after installing it I'm still only getting ~4MiBps transfer rates.
Comment: Termination was definitely off and is hopfully fixed now - the other terminator is from the HBA? Reread the checklist above, there may be multiple problems. The speed you're getting indicates that synchronous transfer fails altogether.
Comment: I got to the point where I had determined that there were no BIOS settings for the card because it had HP vendor firmware&BIOS on it. After hours of searching I tried flashing the closest firmware&BIOS I could find that were not vendor modified. It ended up bricking the card, which I somewhat expected. So I've got a replacement Adaptec SCSI card on the way now.
Answer: I ran into this issue with an IBM LTO-4 drive on the same SCSI controller as the original question (LSI 53c1030). Interestingly the controller had no issues with a Tandberg (HP) LTO-4 drive. Both drives were external. Full speed on the HP drive, 1-4MB/s on the IBM. No issues with cabling or termination, although the IBM required an active terminator whereas the HP had one built in. No obvious configuration issues either.
Without knowing exactly what setting was causing the issue, I was able to resolve it by resetting the SCSI controller to defaults using lsiutil (option 61: restore default settings). You can find a mirror here: https://github.com/mute55/LSIUtil - I used version 1.62.

LSI SCSI Card Slow With LTO4


Como arrastar um elemento livremente na página com javascript puro?

Question: Gostaria de saber como mover um elemento na página livremente com javascript sem frameworks, seria apenas arrastar e largar em qualquer canto da página
Comment: Dá uma olhada aqui:http://pt.stackoverflow.com/q/75422/129
Comment: Queres mesmo fazer isso com JavaScript? o HTML já suporta drag & drop
Comment: Sim amigo, preciso que seja com o javascript puro, sem frameworks
Comment: @TalesBreno olhe todos exemplos, logo o PRIMEIRO é com javascript puro, clique em "Exibir trecho de código" ;)
Comment: Qual é a funcionalidade que pretendes na tua aplicação? Talvez não precises de JavaScript de todo...
Comment: @Guilherme Nascimento Obrigado pela tentativa, mas ele não move o elemento livremente na tela, ele só permite soltar um elemento em local premeditado
Comment: @TalesBreno Você poderia [edit] a sua pergunta e adicionar essa informação (arrastar o elemento livremente)? Da forma que a pergunta está, ela é a mesma da que o GuilhermeNascimento postou.
Comment: Eu realmente preciso arrastar o elemento com javascript sem ser o fantasma que o HTML5 proporciona. A pergunta foi editada
Comment: Adicionei um exemplo em http://pt.stackoverflow.com/a/64342/3635
Answer: segue uma resposta baseada em uma resposta do Sergio (porém sem o uso de Bibliotecas e Frameworks (a.k.a jQuery).

var Draggable = function (elemento) {
  var that = this;
  this.elemento = elemento;
  this.posX = 0;
  this.posY = 0;
  this.top = 0;
  this.left = 0;
  this.refMouseUp = function (event) {
    that.onMouseUp(event);
  }

  this.refMouseMove = function (event) {
    that.onMouseMove(event);
  }

  this.elemento.addEventListener("mousedown", function (event) {
    that.onMouseDown(event);
  });
}

Draggable.prototype.onMouseDown = function (event) {
  this.posX = event.x;
  this.posY = event.y;

  this.elemento.classList.add("dragging");
  window.addEventListener("mousemove", this.refMouseMove);
  window.addEventListener("mouseup", this.refMouseUp);
}

Draggable.prototype.onMouseMove = function (event) {
  var diffX = event.x - this.posX;
  var diffY = event.y - this.posY;
  this.elemento.style.top = (this.top + diffY) + "px";
  this.elemento.style.left = (this.left + diffX) + "px";
}

Draggable.prototype.onMouseUp = function (event) {
  this.top = parseInt(this.elemento.style.top.replace(/\D/g, '')) || 0;
  this.left = parseInt(this.elemento.style.left.replace(/\D/g, '')) || 0;
  this.elemento.classList.remove("dragging");
  window.removeEventListener("mousemove", this.refMouseMove);
  window.removeEventListener("mouseup", this.refMouseUp);
}

var draggables = document.querySelectorAll(".draggable");
[].forEach.call(draggables, function (draggable, indice) {
  new Draggable(draggable);
});
html, body {
  position: relative;
  width: 100%;
  height: 100%;
  margin: 0px;
  padding: 0px;
}

.bloco {
  float: left;
  margin: 5px;
  border-radius: 5px;
  background-color: white;
  box-shadow: 0px 0px 5px black;
  width: 128px;
  height: 128px;
  background-image: url('http://image.flaticon.com/icons/svg/96/96958.svg');
  background-size: calc(100% - 10px);
  background-position: center;
  background-repeat: no-repeat;
}

.draggable {
  position: relative;
  top: 0px;
  left: 0px;
  transition: transform 0.3s linear z-index 0.3 linear;
  z-index: 0;
}

.dragging {
  transform: scale(1.1);
  z-index: 999;
}

Comment: Toby pode colocar um fiddle? Aqui a snipped do SO não está funcionar muito bem, no meu não dá
Comment: Só para constar, jQuery é uma biblioteca, não um _framework_.
Comment: Há uns bugs no drag... ele não quer arrastar às vezes. Isso está acontecendo porque você não declarou os eventos `onmousemove` e `onmouseup` no objeto global `window`.
Comment: @TheProHands apesar do bug citado não está ocorrendo aqui e eu acho que não é necessario adicionar o "mousemove" ao window, acabei por realizar as modificações.
Answer: Para arrastar um elemento eu uso os eventos onmousedown, onmousemove e onmouseup (eu declaro os dois últimos em window), se necessário podem ser usados mais eventos.
Para arrastar o elemento de qualquer ponto é necessário subtrair as posições do ponteiro do mouse pelas posições do elemento ao começar à segurá-lo, e assim que o elemento ser arrastado ele obterá a posição do ponteiro do mouse subtraída pelo valor obtido do primeiro cálculo feito quando o elemento foi segurado, por exemplo, no evento onmousedown.
Edit: mudei a propriedade "client" + ("X" || "Y") para "page" + "("X" || "Y"), pois ela retorna as coordenadas reais da página e eu não tinha percebido isso.

var dragMe = document.getElementById("drag_me"),
  /* o x inicial do drag*/
  dragOfX = 0,
  /* o y inicial do drag */
  dragOfY = 0;

/* ao segurar o elemento */
function dragStart(e) {
    /* define o x inicial do drag */
    dragOfX = e.pageX - dragMe.offsetLeft;
    /* define o y inicial do drag */
    dragOfY = e.pageY - dragMe.offsetTop;

    /* adiciona os eventos */
    addEventListener("mousemove", dragMove);
    addEventListener("mouseup", dragEnd);
}

/* ao ser arrastado */
function dragMove(e) {
    /* atualiza a posição do elemento */
    dragMe.style.left = (e.pageX - dragOfX) + 'px';
    dragMe.style.top = (e.pageY - dragOfY) + 'px';
}

/* ao terminar o drag */
function dragEnd() {
    /* remove os eventos */
    removeEventListener("mousemove", dragMove);
    removeEventListener("mouseup", dragEnd);
}

/* adiciona o evento que começa o drag */
dragMe.addEventListener("mousedown", dragStart);
#drag_me {
    -webkit-user-select: none;
       -moz-user-select: none;
        -ms-user-select: none;
            user-select: none;
    position: absolute;
}

Drag me

Comment: era o position: absolute mesmo. Obrigado!
Comment: Como concilio as funções ao elemento no HTML, criei a div com o id: drag_me, mas não tive resultado...
Comment: @TalesBreno Você está executando o código quando a página é totalmente carregada ou quando todos os elementos já são declarados? Pois bem, eu fiz um teste e funcionou.
Comment: Sim, verificando no navegador, percebe-se que o código esta alterando via propriedade style o posicionamento do elemento, mas o elemento não esta se movendo como deveria
Comment: me mostre seu código html para ver se me esqueci de fazer alguma marcação
Comment: @TalesBreno Eu adicionei o estilo `position: absolute` ao elemento... Vou transformar isso num fiddle. #Editado
Comment: @TalesBreno ^--^ Veja o edit, mudei o `clientX` para `pageX`. Agora funciona com o scroll... eu não tinha percebido isso.


Get all a href links using SimpleHTMLDom library & change these on the 'fly'

Question: I'd like to get to all the a href links within the html string and convert all of the links as follows:
Google

Would change to look like this...
Google

Can anyone suggest how I do this?
<?php

require_once('simple_html_dom.php');
// load the class
$html = new simple_html_dom();

// load the entire string containing everything user entered here

$string = "<base href='http://www.site.biz/clients/g/'>GoogleYahoo";
$return = $html->load($string);

$links = $html->find('a');

foreach ($links as $link)
{
    var_dump($link);
}

?>
Comment: For reference, i'd highly recommend dumping simple_html_dom altogether.  It actually manages to make PHP segfault here, and eats up 5x as much memory and runs at 1/5 the speed of PHP's built in DOM stuff.  (That's not exaggeration, either.  I timed it running through some test suites i have.  Real world time, not benchmarks.  :P )
Answer: Have you tried something like
$links = $html->find('a');

foreach ($links as $link)
{
    if(isset($link->href))
    {
        $link->href = 'www.mysite.com/link.php?URL=' . $link->href;
    }
}

$newHTML = $html->save();

// $newHTML now contains the modified HTML


smtp-server privacy at work

Question: The sys-admin at work has given me the address to the office smtp-server. At work I have to provide username/password to access it. No problems so far.
In addition, at home I must connect to the office-network via VPN in order to send mails. What reasons are there for a sys-admin to make a smtp-server private like this? I am thinking about the VPN-connection, specifically
Comment: This question is off-topic. You are not a system admin and you don't face a technical problem you need to solve (or even could). Please read our [FAQ].
Comment: I was merely interested because it is the first time I am required to use VPN in order to access an SMTP.. doesn't seem reasonable that my post is thumbed down because I didn't provide a specific number of reasons (if that is why...). But 1-2 is fine
Comment: Sorry, my comment sounded unintentionally snotty so I torched it.  I didn't downvote so I can't answer to that.
Answer: Short answer: SMTP is on its own unencrypted. But to me, that's just the lazy way out going the VPN route. SMTP authentication is perfectly understandable to prevent people from using it to relay spam (open relay) since it's not really feasible to whitelist home IP addresses that can vary.

smtp-server privacy at work


O Primefaces não enxerga os métodos de minha classe

Question: Eis meu problema:
No xhtml abaixo (listaDeOSs.xhtml) quando coloco deste modo, ele não reconhece o método que fiz em meu Bean (o método do bean retorna uma lista). O JSF juntamente com o primefaces é mostrado na tela perfeitamente, só que não retornando os dados (No records found).
<?xml version="1.0" encoding="UTF-8"?>

<h:head>
</h:head>
<h:body>
    <h:form>

                <h:outputText value="#{sza.ZA_CLIENTE}" />

                <h:outputText value="#{sza.ZA_CODFUN}" />

    </h:form>
</h:body>

Abaixo a tela apresentada que não mostra os dados:

Em contrapartida, quando utilizo o jsf com html, o código reconhece o método do meu bean e consequentemente funciona (me retornando os dados). Só que fica feio, diferente do primefaces que é bonito.

Abaixo o meu bean:
package br.com.moriahitg.bean;

import java.util.ArrayList;

import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import br.com.moriahitg.dao.SZA990DAO;
/*import br.com.moriahitg.modelo.SA1990;*/
import br.com.moriahitg.modelo.SZA990;

@ManagedBean (name="MBean")
@SessionScoped
public class MBean implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
List<SZA990> list = new ArrayList<SZA990>();

public SZA990 sza;

@SuppressWarnings("unchecked")
public List<SZA990> retornaOSsPorCliente () {
SZA990DAO szadao = new SZA990DAO();
list =  szadao.getOSPorCliente("000002");
return list;
}
/*
public Iterator retornaOSsPorCliente (SA1990 sa1) {
SZA990DAO szadao = new SZA990DAO();
list = szadao.getOSPorCliente(sa1.getA1_COD());
Iterator it = list.iterator();
return it;
}
*/
public List<SZA990> getList() {
return list;
}

public void setList(List<SZA990> list) {
this.list = list;
}

public SZA990 getSza() {
return sza;
}
public void setSza(SZA990 sza) {
this.sza = sza;
}
}

Meu faces-cofig abaixo:
<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
    version="2.2">
    <managed-bean>
        <managed-bean-name>MBean</managed-bean-name>
        <managed-bean-class>br.com.moriahitg.bean.MBean</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>
</faces-config>

Meu web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
        <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>t.xhtml</welcome-file>
    </welcome-file-list>
</web-app>

Comment: Olá Neemias. Qual versão do JSF e PrimeFaces você esta utilizando?
Comment: Olá Murilo, a versão é 4.0 de acordo com o pom.xml
Comment: Resolvido pessoal! A solução foi colocar ajax="false" no commandbutton e reiniciar tudo para limpar o session. Uma advertência para os iniciantes como eu: Caso esteja usando session, mude para request. Digo isso porque as vezes você roda o código correto, mas a informação anterior (a errada) fica armazenada e é ela que aparece em sua tela. Por isso da a impressão de que o que você está rodando ainda está errado.
Answer: Tenta remover o <managed-bean>...</managed-bean> do faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
    version="2.2">

</faces-config>

A anotação @ManagedBean faz o papel de apontar a classe como sendo um bean gerenciavel. Procure tambem remover a propriedade (name="MBean") do @ManagedBean. Por default, na tela o JSF vai apresentar o seu BEAN com o nome da classe minusculo #{mBean.metodo()}.
O primefaces não reconheceu os metodos porque você não adicionou os metodos no faces-config juntamente com o seu Bean. Esse é o motivo de somente usar a anotação @managedBean e não mapear seu Ben no faces-config. Pois com a anotação o ja se resolve essas problemas de mapeamento.
Também, em seu botão
, recomendo que coloque um ID para sua DataTable e mande dar um update nesse id update="myDataTable" no botão.
Comment: Obrigado Murilo! Vou seguir suas recomendações!
Comment: Por nada Neemias. Qualquer coisa é só chamar :-)
Comment: Quer dizer que se eu colocar apenas a anotação @managedBean, ele vai adicionar também os métodos?
Comment: Sim, isso mesmo. Os métodos publicos "public" a tela jsf/xhtml vai conseguir ver, mas métodos privados não será visto pela tela jsf/xhtml.


how to impove image processing in android

Question: this link  contains some tutorials for image processing and is useful for me, but my problem is it is too slow to process.Actually i would try to processing effect on image when sliding bar. Means when user scroll the slider based on that image processing is done. when image size is 70x70(30kb) it is ok for me(performance was good) but when its size is increasing it will take too much time to process.i have try to reduce the size of bitmap upto 40% using bitmap.compress , but still its size is too large to process.

Also, will image processing time is depends on colors on image ?
how to decrease the size of the image/bitmap so image processing not take too much time.
is there any other way to processing bitmap fast or using above tutorial how i improve the performance?
Comment: Do a low resolution preview. Doing a preview at full res is not a good idea even on desktop computers. Image processing times should not be dependent on colors in the image in most known algorithms. I don't know what kind of data structure holds your pixel data. In general, I can say that in a past life, I've used (for example) every alternate or fourth line to do my previews, but for doing this, your data structure must be suitable enough.
Answer: I don't know if this will answer your questions, but hopefully it'll help you.
A few ideas:

Do preview processing on a down-sized version of the original image. This will make your processing considerably faster than having to do it on the original full resolution image.
Only do processing when the user releases the slider. If the application has to continuously process the image while the user is changing the value of the slider, it'll take a long time to process the image. Instead, only apply the image effects when the user has released the slider and selected a value. It'll speed up things considerably. I'm assuming you're using a SeekBar - if so, you'd need to apply your image effects in the onStopTrackingTouch() method of the OnSeekBarChangeListener.
Use RGB_565 for your preview processing. It uses less memory and should make things a bit faster.
Optimize your code. Carefully go through your code, and check if there's anything that could be done in a faster way. One of the usual problems in your case would be creating an excessive amount of Bitmaps.

Hope it helps!
Comment: thanks for replying. Yes down-sized image is faster than original image. you are right do the processing on release the slider fast, but requirement is processing on sliding. will RGB_565 reduce the quality of the image ?
Comment: Well, it's slightly lower quality, but if you only use it for the thumbnail preview, it should be just fine :)


TypeScript Get IconName from string

Question: I'm working on Angular project, with typeScript.
I've added FontAwesome module.
Now I want to display FontAwesome Icon from string.
`
<fa-icon class="panel-heading__icon" [icon]="['fas', iconName]"></fa-icon>

`
When i put directly a good value of IconName, like that:
`
public iconName: IconName = 'coffee';

`
It works.
But, I need to pass a variable string and convert it to IconName.
`
this.iconName = this._model?.icon

`
I get : "Type 'string' is not assignable to type 'IconName'.ts(2322)"
How fix it ?
Comment: you can try using `this.iconName = this._model?.icon as IconName`
Answer: Basically the typescript type checker is complaining because you are trying to use a string instead of an IconName. The IconName type from font-awesome is a type that allows different string literals but not any arbitrary string value.
You have two options to fix this problem:
Option 1:
Use the proper type for the icon attribute on the model type.
So for example if the type of the _model attribute is an interface this can look like this:
interface Model {
     ...
     icon: IconName
}

Option 2: If you can't change the model type you can tell the typescript compiler that you are sure that this icon property has the IconName type by using a type assertion:
this.iconName = this._model?.icon as IconName.

Be aware that there is no runtime check that the icon attribute really hold a valid IconName.
Comment: Option 1 : move the problem to an other place.
I received by request the icon, so I need to tranform string to IconName.
Option 2: OK
I had already test that, my real problem was that I don't use the same version of fontawesome icon, I received name of font awesome icon version 6.2.0 instead of 5.15.0.

TypeScript Get IconName from string


Is it good practice to remove the password from a ssl cert?

Question: I have read at several blogs now that one should remove passwords from SSL certificates in order to avoid password prompts during Apache restarts.
Is this true and does this pose any security risks?
Comment: If you are really concerned, there is hardware available, where your private key can be stored on a USB device, and will never be retrievable.  This won't really work in a hosted environment though.
Comment: I note in passing, just to avoid confusion, that the certificate is never encrypted, nor would there be any point in doing so; for the SSL handshake to complete, the certificate has to be offered in plaintext to anyone who asks for it.  A certificate is just a third-party-signed public key.  It's the **private key**, the asymmetric counterpart of the public key (which is able to decrypt traffic encrypted to the public key), that can be stored encrypted and about which you are asking.
Answer: Yeah, it will stop the prompts being sent to the terminal when starting a web server.
And yes it does pose a security risk because where before the certificate was encrypted it is now in plain text. This means it might be possible to steal a completely working certificate from the machine.
Whether this poses a significant security risk to you depends on what the repercussions would be if it happened to you and what the you gain from doing it this way.
If it's more important to you that services should restart gracefully even if unattended than the security of the SSL system overall then it's a straight forward answer.
Personally, I find keeping decrypted copies of SSL certificates overall has more pros than cons for my typical workload, here's why;

An attacker would still have a copy of the certificate even if it was encrypted so it would be your duty to revoke it anyway.
These days it's far easier for an attacker to obtain a valid certificate for your site via social engineering than to steal a working copy of one.
Certificates naturally expire making their attack surface limited.
Host based security systems such as traditionally permissions and SELinux offer a robust means of protecting certificates on the platform.
A certificate isn't a be-all and end-all of a secure system. There are many other aspects to consider such as the data you store, the media you store it on and the value and/or personal nature of the data.

Things that might make me encrypt:

If you used the certificate to perform mutual authentication.
It's a wildcard certificate or a certificate which hosts multiple domains (the losses double, or triple or whatever many hosts can be used for it)
The certificate is multi-purpose in some other fashion.
The certificates purpose is to ensure the integrity high value data (medical records, financial transactions and the like).
The other end expects a high degree of trust and/or is reliant on the integrity of your system to make operational decisions.

Ultimately, don't rely on others to make security decisions for you. You need to weight the risks and determine what is best for you and your institution using as much information as possible.
Answer: It provides some more security, but the reality is that if someone has gotten far enough into your system to get access to your private SSL key than you probably have bigger issues.
From a practical perspective, do you really want to be there every time apache needs to be restarted to put in a password?
One thing you could do is keep the key unpassword protected on your server (and protect it via normal system security) and keep the backup of the key you store elsewhere with a  password. So if someone is able to scrap the key from somewhere other than your server (much more likely, think someones laptop getting stolen with it on their desktop) it is still protected.
Answer: Cient keys used for login should be password protected.
If you want SSL based services to restart without manual intervention, you have two options:

Don't have a password on the key, and protect it so that only services that need it can access it.
Store the password in plain text or a plain text equivalent on the server so that services which need it can provide the password.  (You may end up with multiple copies of the password in poorly secured configuration files.)

Backup copies of the key should be password protected and secured as if they weren't password protected.


How can I login to my local drupal site 8.3.1 which was under maintence mode

Question: I just logout to see what will the home page look like. Now, I can't login into my local site.
Comment: You can go to /user if logging in is allowed, or use drush with drush uli to auto login as user 1 to view the site.
Answer: You can also try to login by enter below url.
<code>http://example.com/?q=admin
or
http://example.com/user
</code>
Answer: Just go to /user/login, it works even in maintenance mode, and then sign in as an admin.


SQL server pivot on table with join

Question: I have this simple sql statement:
SELECT FCDT.description AS DetailType, FCD.data
FROM Contact_Detail FCD
LEFT JOIN Contact_Detail_Types FCDT
ON FCD.contact_detail_types_id=FCDT.contact_detail_types_id
WHERE contacts_id='4AA36958--0804CA'

which makes this result:
DetailType   data
-------------------------------
Phone        123-456-7890
Email        firstname.lastname@example.com

I need to convert this rows to columns, to have this result:
Phone         Email
--------------------------------
123-456-7890  email@example.com

How I can accomplish this? I have some hours playing with the pivot function, but no results so far.
Answer: Select * From
(SELECT FCDT.description AS DetailType, FCD.data As Data
FROM Contact_Detail FCD
LEFT JOIN Contact_Detail_Types FCDT
ON FCD.contact_detail_types_id=FCDT.contact_detail_types_id
WHERE contacts_id='4AA36958--0804CA')P
pivot
(Max(Data) for DetailType in ([Phone], [Email])) As Pvt

Comment: Then we have to go with dynamic sql statement. This link may help you. [Link](http://stackoverflow.com/questions/15745042/efficiently-convert-rows-to-columns-in-sql-server)
Comment: Thanks Sravan! works, but what happen if the initial query returns more rows (like fax, Cell Phone, etc)? The DetailType its dinamyc!
Comment: It doesn't matter as long as 'DetailType in ([Phone], [Email])' remains the same. If you want all of them as columns, add it in here.
Comment: Then there is no way to have variable columns in the pivot part of the sql sentence? If a user add a new record to DetailType, then forces me to modify this query and add one more element to the pivot list

SQL server pivot on table with join


Sistema de abas em CSS para de funcionar ao mudar quantidade

Question: Estou tentando usar um sistema de abas em CSS puro. Pareceu muito bom, porém quando adiciono novas abas ou removo alguma ele para de funcionar, alguém sabe me falar o porque?
Só com 3 abas funciona bem:

.tabs input[type='radio'] {
    display:none
}
.tabs label {
    width:100px;
    text-align:center;
    padding: 20px;
    color:#666666;
    display:inline-block;
    cursor:pointer;
}
.tab-content {
    display:none;
    background-color:#F3F3F3;
    border-top:6px #FE7B43 solid;
    text-align:center;
    padding:50px 0;
    position:relative;
}
#tabs-1 :checked + * + * + label { background-color:#FE7B43; color:#FFF; }
#tabs-1 :checked + * + * + * + * + * + .tab-content { display: block }

                <input id="tab-1-1" name="tabs-group-1" type="radio" checked />
                <input id="tab-1-2" name="tabs-group-1" type="radio" />
                <input id="tab-1-3" name="tabs-group-1" type="radio" />

                ABA 1
                ABA 2
                ABA 3

                    asdasdasdasdasd

dfasdfsadfasdfasdasdasdasdasd

dfasdfsadfasdfasdasdasdasdasd

dfasdfsadfasdf

                    CONTEUDO ABA 2

                    CONTEUDO ABA 3

Answer: A arquitetura desse CSS não é das melhores na hora da manutenção, pois ela depende da quantidade de elementos intermediários pra cada aba. Se gerar dinamicamente, com uma linguagem server-side tudo bem, mas para atualizar manualmente, precisa estar bem "inteirado" do funcionamento.
Antes de mais nada, veja funcionando com 4 abas:

.tabs input[type='radio'] {
    display:none
}
.tabs label {
    width:100px;
    text-align:center;
    padding: 20px;
    color:#666666;
    display:inline-block;
    cursor:pointer;
}
.tab-content {
    display:none;
    background-color:#F3F3F3;
    border-top:6px #FE7B43 solid;
    text-align:center;
    padding:50px 0;
    position:relative;
}
#tabs-1 :checked + * + * + * + label { background-color:#FE7B43; color:#FFF; }
#tabs-1 :checked + * + * + * + * + * + * + * + .tab-content { display: block }

                <input id="tab-1-1" name="tabs-group-1" type="radio" checked />
                <input id="tab-1-2" name="tabs-group-1" type="radio" />
                <input id="tab-1-3" name="tabs-group-1" type="radio" />
                <input id="tab-1-4" name="tabs-group-1" type="radio" />

                ABA 1
                ABA 2
                ABA 3
                ABA 4

                    asdasdasdasdasd

dfasdfsadfasdfasdasdasdasdasd

dfasdfsadfasdfasdasdasdasdasd

dfasdfsadfasdf

                    CONTEUDO ABA 2

                    CONTEUDO ABA 3

                    CONTEUDO ABA 4

Pra funcionar, foram ajustadas estas linhas
#tabs-1 :checked + * + * + * + label { background-color:#FE7B43; color:#FFF; }
#tabs-1 :checked + * + * + * + * + * + * + * + .tab-content { display: block }

Um + * a mais na primeira linha, pra cada aba, e dois na segunda linha.
Uma solução mais escalável seria colocar os checkboxes antes de cada aba, e usar o seletor + absoluto
Refatorando para funcionar independente do número de abas
A técnica é a mesma, mas reordenei os campos e o CSS de forma a cada radiobutton estar sempre à mesma distância da sua respectiva aba e seu conteúdo. Para aumentar ou diminuir a quantidade de abas, basta replicar os blocos de radio + label + div.
O único cuidado é fazer com que todas as abas caibam na mesma linha.

.tabs input[type='radio'] {
    display:none;
    position:absolute;
    left:-100px;
}
.tabs label {
    width:60px;
    text-align:center;
    padding: 20px;
    color:#666666;
    display:inline-block;
    cursor:pointer;
}
.tab-content {
    display:none;
    position:absolute;
    left:0;
    width:100%;
    background-color:#F3F3F3;
    border-top:6px #FE7B43 solid;
    text-align:center;
    padding:50px 0;
}
#tabs-1 {position:relative}
#tabs-1 :checked + label { background-color:#FE7B43; color:#FFF; }
#tabs-1 :checked + label + .tab-content { display: block }

  <input id="tab-1-1" name="tabs-group-1" type="radio" checked />
  ABA 1

    CONTEUDO ABA 1

  <input id="tab-1-2" name="tabs-group-1" type="radio" />
  ABA 2

    CONTEUDO ABA 2

  <input id="tab-1-3" name="tabs-group-1" type="radio" />
  ABA 3

    CONTEUDO ABA 3

  <input id="tab-1-4" name="tabs-group-1" type="radio" />
  ABA 4

    CONTEUDO ABA 4

  <input id="tab-1-5" name="tabs-group-1" type="radio" />
  ABA 5

    CONTEUDO ABA 5

Answer: Cada vez que você adicionar mais abas, vai precisar aumentar o numero de * + no CSS na parte:
#tabs-1 :checked + * + * + * + label {
  background-color: #FE7B43;
  color: #FFF;
}

#tabs-1 :checked + * + * +  * + * + * + * + * + .tab-content {
  display: block
}

.tabs input[type='radio'] {
  display: none
}
.tabs label {
  width: 100px;
  text-align: center;
  padding: 20px;
  color: #666666;
  display: inline-block;
  cursor: pointer;
}
.tab-content {
  display: none;
  background-color: #F3F3F3;
  border-top: 6px #FE7B43 solid;
  text-align: center;
  padding: 50px 0;
  position: relative;
}
#tabs-1 :checked + * + * + * + label {
  background-color: #FE7B43;
  color: #FFF;
}
#tabs-1 :checked + * + * +  * + * + * + * + * + .tab-content {
  display: block
}

  <input id="tab-1-1" name="tabs-group-1" type="radio" checked />
  <input id="tab-1-2" name="tabs-group-1" type="radio" />
  <input id="tab-1-3" name="tabs-group-1" type="radio" />
  <input id="tab-1-4" name="tabs-group-1" type="radio" />
  ABA 1
  ABA 2
  ABA 3
  ABA 4

    CONTEUDO ABA 1

    CONTEUDO ABA 2

    CONTEUDO ABA 3

    CONTEUDO ABA 4

Comment: tem como fazer isso de forma automática?usando jQuery?
Comment: +1 diagnosticamos praticamente ao mesmo tempo e a mesma coisa.
Comment: Yp @Bacco, só que a sua esta mais completa rs, eu pelo menos não saberia explicar o porque... vou excluir a minha resposta hausahs
Comment: @MarceloBonifazio não exclua não, tá valendo. A minha eu complementei mais no sentido de mostrar a alternativa. Deixe a sua, pois os votos são merecidos (e vc na verdade postou até um pouco antes da minha).


How to fix some text symbols in JSON android

Question: Below picture describes my problem -

How to fix some text symbols in JSON android
My Code
<code>@Override
public void onBindViewHolder(@NonNull ToursViewHolder holder, int position) {

    tourData = tourDataList.get(position);

    holder.tourDate.setText(tourData.getTourDate());
    holder.tourTitle.setText(tourData.getTitle().getTitleRendered());

    Glide.with(context)
            .clear(holder.tourImg);
    Glide.with(context)
            .load(tourData.getTourEmbedded().getWpFeaturedmedia().get(0).getMediaDetails().getSizes().getFull().getSourceUrl())
            .into(holder.tourImg);

}
</code>
Comment: Try to set in HTML format :  holder.tourTitle.setText(Html.fromHtml(tourData.getTitle().getTitleRendered()));
Answer: Try using:
<code>String title = Html.fromHtml(tourData.getTitle().getTitleRendered(), Html.FROM_HTML_MODE_COMPACT);
holder.tourTitle.setText(title);
</code>


Re-training custom NER loses info about previous labels

Question: I have a custom NER model that is working fine to find locations:
"I like London and Berlin"
LOC London
LOC Berlin

I am trying to add another custom NER training to it, following this guide. However, when I add a new label, the previous model loses its information about the label types. Namely:
"Do you like horses? I like London and Berlin"
ANIMAL horses
ANIMAL London
ANIMAL Berlin

(I have simply added the second sentence to the test_text variable in the link above, that's why no additional code is provided)
Can anybody shed some light on this? I am using spaCy 2.2.4
Answer: The reason for the poor results is due to a concept called catastrophic forgetting. You can get more information here.
tl;dr
As you are training your model with new entities, it is forgetting what it previously learnt.
In order to make sure that the old learnings are not forgotten, you need to feed the model examples of the other types of entities too during retraining. By doing this, you will ensure that the model does not self tune and skew itself to predict everything as the new entity being trained.
You can read about possible solutions that can be implemented here
Comment: Thank you, I found out about catastrophic forgetting after asking the question. However, I may be wrong but I think this is a different phenomenon, since the NER detects the concepts correctly but labels them incorrectly.


Difference in means statistical test for non-normal, heteroscedastic data?

Question: Suppose I have a data set with three or more groups.  After some exploratory data analysis, I find that

The groups do not come from a normal distribution
the variances within the groups are not equal, and violate the rule of thumb that the largest variance is no more than 4 times the smallest variance.

If I'm interested in a statistical test for the difference in means across these groups, what tests can I use?
From what I understand, ANOVA requires normality (although it tends to be robust against deviations from normality) and homoscedasticity. The Kruskal-Wallis test and the Fisher-Pitman permutation test can deal with the non-normality, but I believe both require homoscedasticity.  Using Welch's ANOVA will help with the unequal variances, but it requires normality.
I'm interested in how this community would suggest moving forward with a difference in means analysis.
Comment: You could try bootstrapping?  See https://stats.stackexchange.com/questions/56971/alternative-to-one-way-anova-unequal-variance  Could you show us a plot of the data (or share a link)?
Comment: Clarification:  ¿Do you want to say a difference exists and attach a p-value to this claim? or ¿do you want to actually locate differences between specific groups? (Curious as to what the long-run research question is here)
Comment: If the variances are different you have already shown the groups are different so perhaps you need to specify why you also need to test the means?
Comment: @kjetilbhalvorsen:  I didn't have particular data in mind. I was hoping for some general approaches that others have used in this situation or one similar.
Comment: @GreggH:  I had in mind a p-value type test to refute a claim of equal means, but I'm open to other statistical approaches that communicate a similar idea.
Comment: also...one other point of clarification...the question title says "non-normal" but the scenario you describe (bullet 1) says the data is "normal"
Comment: A simple thing to do: dummify the category id, regress the variable of interest on these dummies, use robust variance-covariance matrix (e.g. White's) for Wald's test, there you go. No normality, no homoskedasticity, no undergrad shit like that that is used purely for psychological comfort.
A better thing to do: do an ordinary LS, get the residuals, estimate the residual variance in each group, apply weighted LS with weights reciprocal to these variances. Voilà, you have the **best** linear unbiased estimator (BLUE). You do not even need non-parametric estimation... All relies on asymptotics.
Answer: This is an interesting thread so I thought I would add my own thoughts to it. If I understand things correctly, you have a situation where you are interested in testing differences between k population means (where k > 2) when the populations are normal but have different spreads.
As a first resort, you could try applying a variance-stabilizing transformation to the data you collected on the outcome variable (e.g., log transformation if these data are strictly positive).  If the transformation works, you can then apply the standard ANOVA to the transformed outcome data (presuming the other assumptions underlying ANOVA still hold). In general, the more complicated the transformation, the more complicated the ensuing interpretation. Also, in some situations, you may be hard-pressed to find an adequate transformation.
A better approach, in my view, would be to use generalized least squares (gls) regression to analyze the untransformed outcome data. In R, the gls approach is implemented via the gls() function in the nlme package:
<code>install.packages("nlme")
require(nlme)

model <- gls(outcome ~ group,
         data = yourdata,
         weights = varIdent(form = ~1|group))

summary(model)

anova(model)
</code>
The gls approach will help you relate the outcome variable (expressed on its original scale) to the group variable, while allowing for the possibility that the error variability is different across levels of the group variable.  The approach will estimate the error variability in each group for you, under the assumption of normality of the errors within each group. More importantly, the gls approach will provide you with a flexible framework for testing a priori contrasts or performing various types of post-hoc multiple comparisons. Checking model diagnostics is also straightforward.
The bootstrapping approach is also a possibility, though I think it's not as easy to implement as the gls approach, especially when you consider the need to test a priori contrasts or perform post-hoc multiple comparisons.
This question has been asked before and addressed here, for example: Explicitly modelling unequal variances in a linear model to get better conf/pred intervals?.
Comment: Thanks Isabella.  Does this approach still require a normal distributions among the groups?
Comment: Isabella, I couldn't find any aspect of @Andreï's comment that is uncivil, especially taking into account that the 500 character limit practically forces people to dispense with the usual niceties and get right to the point.  I agree that his request to "correct" the answer may be asking a lot and you're right that it's too much to expect every answer to be "optimal," but one thing this site has going for it is that encourages us to *improve* answers.  When everyone cooperates toward that end, it works well.
Comment: @IsabellaGhement I am very sorry if it seemed too harsh, I am just allergic to distributional assumptions where they are not needed. In no way I wanted to offend you. You wrote: `Yes, the gls approach requires normal distributions for the values of the outcome variable in each group`. But this is just wrong! It does not. Addressing the White's matrix biasedness—one may use Davidson—McKinnon's or Cribari-Neto's finite-sample correction. Asymptotically they are all the same, though. The OP asked for differences in means, but in a more general setting, Mann—Whitney's test with Bonferroni correcti
Comment: Yes, the gls approach requires normal distributions for the values of the outcome variable in each group, but the level of spread of these distributions can depend on the group variable. If the normality assumption is violated, then you would have to resort to gls + bootstrap, I guess. (In your question, you mentioned that you do have normality of the data in each group, hence my recommendation to use gls.)
Comment: @stats_curious In no way (G)LS assumes normality of error terms! The inference will be asymptotically valid with White's variance-covariance matrix estimate, since the (G)LS estimators are asymptotically normal, even if the model error comes from an unknown distribution. In case of heteroskedasticity of the most general form, Robinson's (1987) estimator, `E[XX'/σ²(X)]^(-1) E[XY/σ²(X)]`, will asymptotically beat **any** GLS estimator; in the discrete regression case, like here, the estimator of `σ²(X)` is just `E[ε²|X]` measured for each discrete X. Please correct your answer.
Comment: The White estimator may not perform well in finite samples (so it may need a finite sample correction). It is also biased, so it may require a bias correction. No solution is perfect!
Comment: Thank you, @whuber. I am new to the site and get rattled more easily, I guess. I deleted two of my comments after reading your response, but I still think no solution is perfect and the one proposed by the commenter has its own drawbacks. I won't edit my answer in view of this.
Comment: on for multiple comparisons is the way to go. I guess, instead of criticising your answer, I should have prepared a rigorous separate answer...
Comment: Sorry, did not see that there are 3 or more groups. In this case, Dunn's test after Kruskal—Wallis' ANOVA on ranks is the right way for post hoc comparison.
Comment: I think I understand where you are coming from, Andrei. I had in mind the gls() function in R, which uses either maximum likelihood, or restricted maximum likelihood for estimation and most likely relies on normality for subsequent inferences/predictions based on the model.  I believe gls() uses the gaussian family by default (if not, how could one derive the likelihood?).
Comment: Thank you for elaborating on your comments, Andrei (not sure how to get the accent on the i to spell your name correctly).  I think your point, in general, is (?) that normality is not needed for obtaining gls estimates. However, I had presumed that the asker was interested in performing tests of hypothses and constructing confidence intervals, in which case normality of the errors in each group would come in handy.


get text with jsoup

Question: I have this HTML

Lifts open today include Agassiz to the top, Sunset, Hart Prairie, Little and Big Spruce from

                    9 a.m. - 4 p.m.

Trails Open

100% of trails open with 30 groomed runs.

I want the text "Lifts open today....."

This is my code. Nothing is show. There is no error in the logcat
Document doc = Jsoup.connect(url).get();
            Elements div = doc.select("div.right");
            for (Element liftope : div){
                Elements p =liftope.select("#items > li > p");
                liftoper = p.text();
            }

What is wrong???
Answer: If you want only that text "Lifts open today include: Agassiz to the top, Sunset, Hart Prairie, Aspen and Little Spruce Conveyor!" this (i try) work:
Element div = doc.getElementById("contentinterior");
Elements uls = div.getElementsByTag("ul");
Element ul = uls.get(2);
String result = ul.text();

Comment: @AgustinScalisi can you post all html?
Comment: Is based on this page     http://www.arizonasnowbowl.com/resort/snow_report.php        I want to display the text on this CSS path #items > li > p > strong > span > strong
Comment: @AgustinScalisi check my update answer, i try and work
Comment: @AgustinScalisi if you are happy and the answer is useful, you can accept! bye!
Comment: @AgustinScalisi for accept you must click on "V" below the down arrow on left. cheers!

get text with jsoup


Proper way of averaging histograms

Question: How does one go about averaging multiple histograms of a quantity $x,$ if the individual histograms do not have the same range, that is, $R_i=\text{max}(x_i)-\text{min}(x_i)$ will be different for two different $i$ values (where $i$ here is indexing over the realizations of the experiment/histogram). Only common point between them is that the bin size is fixed, $b=1.$
How can I perform the averaging whilst making sure that no discrepancy arises for values of $x$ that do not occur in all histograms (as $R_i$'s can be different)? I am interested solely in the methodology here.
Comment: (1) Why not combine your datasets into one and draw the histogram of that? (2) Where they overlap, do your histograms use the same breakpoints or not? (3) Is the amount of data exactly the same in each experiment?
Comment: Please explain what the mathematical process of "averaging histograms" is intended to represent.  Only then would we have a definite basis to recommend an appropriate methodology.
Comment: @whuber Actually thought of doing your suggestion (1) at first, don't know why I didn't go through with it, I'll go do it now. I guess that counts as an averaging of some sort. (2) yes, (3) no there are different number of datapoints gathered from each experiment.
Comment: @whuber I repeat an experiment $5$ times, with the same exact conditions  each time. Each of them gives me a different histogram for the system temperature. From the $5$ together, I intend to compute a single, average, histogram.
Comment: That's good--(1) is your best option.  Before you go any further, though, you would appreciate the related information at http://stats.stackexchange.com/questions/51718 .
Comment: @whuber Many thanks for your assistance, I will also look into the linked post.
Answer: So I've had a look around and this is the best answer I have found:
http://se.mathworks.com/matlabcentral/answers/59865-how-to-combine-different-histograms
From what I understand you have to adjust the range your bins cover in every histogram so that there is a universal range for them all; $R$ instead of $R_i$. I think you can do this by creating empty bins in each histogram. Then you can just add them together and take the average normally (by dividing by the number of histograms).
Hope that helps.
Comment: Thanks for your answer. Well this would be probably (honestly I'm not sure) problematic, as introducing 0's into the dataset would highly underestimate the uncommon values between histograms, right? for example if we have $x=10$ in only the histogram $i=2,$ with frequency ($f(x)=100$) where in total we have only 5 histograms, then in the averaged histogram $10$ comes with a frequency $20.$ But is that ok?
Comment: Notice that (later) the OP indicated the various histograms represent *different* amounts of data.  Since a standard histogram plots frequency *density* (not frequency itself--that would just be a bar chart), simply adding the values as recommended in your reference would be incorrect.
Comment: @whuber right, but if I understand correctly as long as we don't normalize the histogram (by sum of all frequencies), it is just a bar chart of frequencies (as the one you point to), right?
Comment: Then maybe, and this is a MAYBE, you could try this approach which I think would be similar to taking the weighted average of every bin: You take every bin and combine them and divide by the number of histograms that bins has been in. For example if you have $f(x_1 = 10)=100$ and $f(x_2 = 10) = 20$, you take the average of them and have $f(x_m = 10) = \frac{100 + 20}{2}=60$. Similarly if you have $f(x_i = 5) = 80$ for all $i = 1,2,3,4,5$ then you have $f(x_m = 5) = \frac{80+80+80+80+80}{5}=80$. Does this sound logical to you?
Comment: But looking at this answer now, it would be bad if $f(x=10) = 100$ only occured in one of the bins, then you would have a bias in the sense that $x=10$ will have a bigger bin even though more $x=5$ have occured. I think the way whuber is describing above could be best, to just combine your dataset and make a new histogram.
Comment: Sure, I'll go with whuber's suggestion then, I appreciate your effort. Thanks again.
Comment: No worries at all, glad to have been able to 'kinda' help haha.
Comment: Ah yes of course! Thank you for pointing that out whuber!
Comment: Actually yeah, and the bin widths are 1 so there might be different amounts of data in each histogram, but frequency density x width is the same for all histograms and width would always be 1.

Proper way of averaging histograms