Como trocar ponto por virgula em java e no tipo BigDecimal?

Question: Sou iniciante em java e estou com dúvida no tipo BigDecimal, pois ele aceita valores com pontos e não com virgulas. Estou desenvolvendo um software para videolocadora e quero salvar o valor da minha categoria de filme com virgula e não com ponto:
private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {

    BigDecimal valor = new BigDecimal(0);

    if (!cmpValor.getText().equals("")) {
        valor = new BigDecimal(cmpValor.getText());
    }
    if(cmpDescricao != null) {
        categoriaController.salvar(cmpDescricao.getText(), valor);
    }
}

Quando digito o valor da categoria com vírgula, minha aplicação gera erro:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException
    at java.math.BigDecimal.<init>(BigDecimal.java:494)
    at java.math.BigDecimal.<init>(BigDecimal.java:383)
    at java.math.BigDecimal.<init>(BigDecimal.java:806)
    at view.VideoCategoria.btnSalvarActionPerformed(VideoCategoria.java:206)
    at view.VideoCategoria.access$000(VideoCategoria.java:20)
    at view.VideoCategoria$1.actionPerformed(VideoCategoria.java:66)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6527)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
    at java.awt.Component.processEvent(Component.java:6292)
    at java.awt.Container.processEvent(Container.java:2234)
    at java.awt.Component.dispatchEventImpl(Component.java:4883)
    at java.awt.Container.dispatchEventImpl(Container.java:2292)
    at java.awt.Component.dispatchEvent(Component.java:4705)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
    at java.awt.Container.dispatchEventImpl(Container.java:2278)
    at java.awt.Window.dispatchEventImpl(Window.java:2739)
    at java.awt.Component.dispatchEvent(Component.java:4705)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:746)
    at java.awt.EventQueue.access$400(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:697)
    at java.awt.EventQueue$3.run(EventQueue.java:691)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:719)
    at java.awt.EventQueue$4.run(EventQueue.java:717)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:716)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Gostaria de saber se há um meio de ele aceitar números digitados com vírgula!
Answer: Você pode alterar a virgula por ponto através do código, assim, no front-end isso ficará transparante.
Exemplo
 valor = new BigDecimal(cmpValor.getText().replace(",",".");

Comment: @IgorContini, por favor, marque como resposta para que possa ajudar outras pessoas com a mesma dúvida.
Comment: Deu certo aqui! Valeu e obrigado!


Is it possible to change CIDR network flannel and Kubernetes

Question: Is it possible to change CIDR network flannel on running Kubernetes cluster?
If yes what will happen with  the launched pods?
Thanks
Answer: I've managed to change Flannel CIDR network pool in the following way:
Assuming that you have installed a fresh k8s cluster via kubeadm builder tool with adopting appropriate --pod-network-cidr flag in kubeadm init command:
Override podCIDR parameter on the particular k8s Node resource with a new IP source range, desirable way with piping output:
$ kubectl get no $hostname -o yaml >> file.yaml | sed -i "s~$old_ip~$new_ip~" file.yaml| kubectl delete no $hostname && kubectl create -f file.yaml

Replace "Network" field under net-conf.json header in the relevant Flannel ConfigMap with a new network IP range:
$ kubectl edit cm kube-flannel-cfg -n kube-system

net-conf.json: |
      {
        "Network": "10.244.0.0/16",
        "Backend": {
          "Type": "vxlan"
        }
      }

Wipe current CNI network interfaces remaining the old network pool:
$ sudo ip link del cni0; sudo ip link del flannel.1

Re-spawn Flannel and CoreDNS pods respectively:
$ kubectl delete pod --selector=app=flannel -n kube-system
$ kubectl delete pod --selector=k8s-app=kube-dns -n kube-system

Wait until CoreDNS pods obtain IP address from a new network pool. Keep in mind that your custom Pods will still retain the old IP addresses inside containers unless you re-create them manually as well.
Comment: Why is it so involved? I just went and used kubeadm reset and started building the cluster from scratch with another setting for --pod-network-cidr. It would make sense if kubeadm would provide simple cli support to change this setting.
Answer: For calico, create new IPpool and and disable old.... https://projectcalico.docs.tigera.io/networking/migrate-pools
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/509176)
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Is it possible to create a design of a web page using machine learning? Like generating CSS styles, assuming that we already had HTML

Question: There are many machine learning algorithms to generate music, like Magenta and GRUV. I want to know if it is possible to create algorithms like these but for generating styles for webpages.
Comment: Yes. That is, it is possible. Why would it not be? As higher level design programs are evolved, they are converging on AI assist.
Answer: Yes, that's totally possible. Andrej Karpathy wrote a blog post about Recurrent Neural Networks and shows several applications; one of them is generating Wikipedia articles including Markdown code, XML. The RNN could also generate LaTeX code which only needed slight corrections before being able to run, and also pieces of code in the style of Linux source code! You can read the blog here.


How to exclude Apache VirtualHost from global rewriting?

Question: I have setup Let's Encrypt SSL certificate on my VPS, which works fine, but now all VirtualHost are trying to load over https://.
I have found RewriteRule directive in le-redirect.conf:
<VirtualHost _default_:80>

ServerSignature Off

RewriteEngine On
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent]

ErrorLog /var/log/apache2/redirect.error.log
LogLevel warn

But I am not sure how to exclude specific VirtualHost named example.com from matching https rewrite rule.
Answer: Try adding this to httpd.conf or apache2.conf
<VirtualHost example.com>
   RewriteEngine Off
</VirtualHost>


Compare one array with another and replace missing values php

Question: I have two Arrays:
$a1=array("Maths","English","Science","ICT");
$a2=array("Maths","ICT");

I want to compare $a1 with $a2, then return
$a3=array("Maths",",,",",,","ICT");

So replace the missing values  in $a2 with ",,"
This is my meager attempt :(
$a1=array("Maths","English","Science","ICT");
$a2=array("Maths","ICT");
$result = array_diff($a1, $a2);
foreach ($result as $v){
$a3 = str_replace($v, ",,", $a1);
}
print_r($a3);

Answer: Glad you figured it out, but I think this might work better:
<?php

$a1 = array("Maths", "English", "Science", "ICT");
$a2 = array("Maths", "ICT");

$a3 = $a1;

$keys = array_keys(array_diff($a1, $a2));
foreach ($keys as $key)
    $a3[$key] = ',,';

print_r($a3);

Output:
Array
(
    [0] => Maths
    [1] => ,,
    [2] => ,,
    [3] => ICT
)

Answer: Figured it out, thanks if you looked:
$a1=array("Maths","English","Science","ICT");
$a2=array("Maths","ICT");

$result = array_diff($a1, $a2);

foreach ($result as $v){

$v = str_replace($result, ",,", $a1);

}
print_r($v);

Comment: This won't work if you have a subject called `Biochemistry` and `chemistry`. [Example](https://eval.in/private/60d2b8380fa020).
Comment: I just encountered that exact problem with "English" and "English Lit" any ideas?
Comment: I encourage you to take a look at my answer. It will work even if the subject contains parts of other subjects.


Scaling a compact gives a compact in a locally compact vector space

Question: While wondering about why locally compact vector space are important, I was told that in a locally compact vector space if one scales a compact set by some number, than we still have a compact set, while this might fail in a vector space that is not locally compact. I was trying to see this with the space $\ell^2$ (space of real sequences with finite sum of squares) which is according to this post not locally compact. But then I realized that I don't even know what compact space look like in this vector space.
Answer: Since scaling is a continuous map of any Topological Vector Space to itself, the image of any compact subset of any TVS under scaling will also be compact.
Comment: I see. I don't remember what property it was then...
Comment: Still out of curiosity, what do the compact sets of $\ell^2$ look like? Is there a characterization like for finite $\mathbb{R}^n$?
Comment: Have a look here: https://math.stackexchange.com/questions/941897/examples-of-compact-sets-that-are-infinite-dimensional-and-not-bounded
Comment: thank you for the link. The motivation behind the original question was a proof in which I have a sequence of compact sets $K_n\subset X$ and it is written : "Since $X$ is locally compact, up to enlarging inductively each compact set, we may assume $K_n\subset \mathring{K}_{n+1}$ for any $n\in\mathbb{N}$".
Answer: Locally compact topological vector spaces are finite dimensional (see, e.g., Rudin's book) and thus not very interesting for functional analysis.


Fixar menu com bootstrap após descer scroll

Question: Estou usando bootstrap no meu código
Tem uma classe no nav do bootstrap que fixa o nav no topo

navbar-fixed-top

Porém quero que o nav só fique fixo quando o scroll passar por ele.
Como faço isso?
Um exemplo: Esse site
Answer: Penso que há um plugin capaz de fazer isso já no bootstrap, o affix, não precisa de nenhum javascript pelo que eu sei.
http://getbootstrap.com/2.3.2/javascript.html#affix
O menu lateral é um exemplo do uso do affix
Comment: Como faço para instalar o affix no meu html? Não consigo achar
Comment: Acho que não requer nenhuma instalação, basta copiar a tag e adapta-la para o que é preciso, aqui pode encontrar tudo sobre o affix https://www.w3schools.com/bootstrap/bootstrap_affix.asp
Comment: Não está funcionando. Coloquei `` e mesmo assim não fixa @K. Chanel
Comment: Experimente ver em Try it yourself no w3schools.com/bootstrap/bootstrap_affix.asp para experimentar e ver como funciona
Comment: a tag "offset-top" determina a quantidade de pixeis que é preciso fazer scroll até se afixar no topo e o que ativa o affix é a tag 'data-spy="affix"'
Answer: Encontrei um snippet no Bootsnipp
Navbar Affix


Controle de acesso a rotas - Laravel 5.1

Question: Tenho algumas views que somente clientes podem acessar, e algumas que somente administradores podem acessar. O que defini no caso é o id_cliente, que se for "1" é administrador e se for qualquer outro é cliente. Controlo isso com 2 Middleware localmente, mas quando publiquei em um servidor de hospedagem recebo um erro:

Esta página da web tem um loop de redirecionamento
ERR_TOO_MANY_REDIRECTS

Routes:
// Rotas para administradores
Route::group(['middleware' => 'auth', 'middleware' => 'SIST\Http\Middleware\AdminMiddleware'], function()
{
    Route::get('inicio', ['as' => 'inicio','uses' => 'Admin\InicioController@index']);
});

// Rotas para clientes
Route::group(['middleware' => 'auth', 'middleware' => 'SIST\Http\Middleware\ClientMiddleware'], function ()
{
    Route::get('sist', ['as' => 'sist','uses' => 'Client\SistController@index']);
});

Admin Middleware:
class AdminMiddleware
{
    public function handle($request, Closure $next)
    {
        if (Auth::user()->id_cliente !== 1)
        {
            return redirect('/sist');
        }else{
            return $next($request);
        }
    }
}

Client Middleware:
class ClientMiddleware
{
    public function handle($request, Closure $next)
    {
        $id_cliente = Auth::user()->id_cliente;

        if ($id_cliente === 1)
        {
            return redirect('/inicio');
        }else{
            $cliente = Cliente::find($id_cliente);
            return $next($request);
        }
    }
}

htaccess
<IfModule mod_rewrite.c>
        RewriteEngine on
        RewriteCond %{REQUEST_URI} !^public
        RewriteRule ^(.*)$ /public/$1 [L]
</IfModule>

Tenho muitas rotas dentro desses dois grupos e uso isso pra não deixar um cliente acessar rota de administrador digitando a URL. Não sei se é a melhor maneira, mas foi o que consegui fazer. Se tiver outra forma de fazer podem me falar por favor.
Comment: Veja através da ferramenta de desenvolvimento do seu navegador qual loop está ocorrendo. Quais os dois endereços que estão recebendo redirecionamento de um para o outro. O problema pode não ter nada a ver com seu middleware, mas sim com sua zona DNS.
Comment: ao fazer login com um usuário que deveria levar para o diretório "/inicio", ele fica redirecionando infinitamente para o "/sist". O mesmo acontece se eu tento logar com usuário que realmente deveria ser direcionado para o "/sist", porem o redirecionamento nunca para.
Comment: @MarcoAurélioDeleu, é como se ele não reconhecesse as condições, não sei... realmente não faço ideia. Editei a pergunta colocando o meu htaccess.
Answer: Você não pode usar apenas uma Route e apenas uma Middleware ?
Route::group(['middleware' => 'auth', 'middleware' => 'admin'], function(){
    Route::get('inicio', ['as' => 'inicio','uses' => 'Admin\InicioController@index']);
    Route::get('sist', ['as' => 'sist','uses' => 'Client\SistController@index']);
});

Registra essa Middleware no Kernel.php que fica na pasta app/Http, nesse array, última linha:
protected $routeMiddleware = [
    'auth'          => 'App\Http\Middleware\Authenticate',
    'auth.basic'    => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
    'guest'         => 'App\Http\Middleware\RedirectIfAuthenticated',
    'login'         => 'App\Http\Middleware\AdminMiddleware',
];

Daí no middleware do Route::group, coloca como fiz acima: middleware => 'admin' ao invés daquele nome todo.
Daí no AdminMiddleware.php faça os dois:
class AdminMiddleware
{
    public function handle($request, Closure $next)
    {
        if (Auth::user()->id_cliente !== 1){
            return redirect('/sist');
        }else{
            return redirect('/inicio');
        }
        return $next($request);
    }
}

Não tem a ver com o .htaccess.
Comment: até tentei agora dessa maneira mas o erro continua. Vou por uma imagem na pergunta. @Zoom
Answer: Acredite se quiser, mas depois de perder praticamente o dia inteiro nisso, resolvi o problema apenas trocando "===" por "==" e "!==" por "!=". Não sei o que pode ter ocasionado esse mal funcionamento na hospedagem, uma vez que localmente funcionava perfeitamente, mas foi isso!
Comment: Ow, e você saber que eu acabei errando meu script PHP. Eu ia fazer isso e acabei não fazendo na verificação dentro da middleware, pode até ver que está errada a verificação para qual link vai. Boa.
Answer: Sei que passou muito tempo, mas quis comentar para entenderem a diferença do "==" e "===", consequentemente "!=" e "!=="
Quando usamos a validação do tipo ===, se equivale a estritamente igual, o que isso quer dizer, além do valor da variável ter que ser igual o tipo também deve ser igual, exemplo:
Ex:
$id_cliente === 1

Neste caso, se sua variável for uma string, daria erro, pois está comparando um valor com uma variável que espera uma string.
Se for o caso, a comparação deveria ser assim:
$id_cliente === "1"


Como pegar variável com $_GET

Question: Olá, no meu htaccess está assim:
RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d

RewriteRule ^(.*)$ index.php?url=$1
RewriteRule ^download/([A-Za-z0-9]+)$ index.php?a=download&k=$1 [QSA,L]

E no download.php
<?php
$k = $_GET['k'];
echo $k;

Porem retorna esse erro quando eu acesso download/?k=aaaa ou download/?aaaa
Notice: Undefined index: k

index.php

    <?php
        require 'config/tratarUrl.php';
        include $pag;
    ?>

tratarUrl.php
<?php
$pUrl = strip_tags(trim(filter_input(INPUT_GET, 'url', FILTER_DEFAULT)));
$sUrl = (empty($pUrl) ? "index" : $pUrl);
$url = array_filter(explode('/', $sUrl));

if (count($url) > 1)
{
$cont = 1;
foreach ($url as $arg)
{
    define("PARAM" . $cont, $arg);
    $cont++;
}
}
else if (count($url) == 1)
{
if (file_exists(DIR_PAGES . $url[0] . '.php'))
{
    $pag = DIR_PAGES . $url[0] . '.php';
}
else
{
    if($url[0] != 'index')
    {
        $pag = DIR_PAGES . '404.php';
    }
    else
    {
        $pag = DIR_PAGES . 'home.php';
    }
}
} else {
$pag = DIR_PAGES . '404.php';
}

Comment: O que retorna com `var_dump($_SERVER["QUERY_STRING"]);`?
Comment: Retorna `string(13) "url=download/`, estranho ele não estar pegando o `aaaa` no final.
Comment: Creio que sua regra deva ser `RewriteRule ^download/([A-Za-z0-9]+)$ index.php?a=download&k=$1 [QSA,L]`
Comment: Continua retornando o mesmo erro `Undefined index: k` e mesma mensagem `string(13) "url=download/"`
Comment: Já modifiquei a pergunta.
Comment: Altere essa linha `# RewriteRule ^(.*)$ index.php?url=$1` com o `#` no inicio; essa regra está pegando tudo `(.*)`
Answer: Sua regra deve conter [QSA,L].

A flag QSA significa que vai aceitar uma seqüência para consulta.
A flag L significa que se a regra corresponder, não irá processar a cadeia seguinte

Mude a ordem da sua regra:
RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d

RewriteRule ^download/([A-Za-z0-9]+)$ index.php?a=download&k=$1 [QSA,L]
RewriteRule ^(.*)$ index.php?url=$1

Comment: Consegui resolver meu problema, porem surgiu outra duvida, para esse tópico não ficar sobrecarregado vou criar um novo.
Comment: Agora quando eu digito `site.com/download/?aaaa` retorna `Objeto não encontrado!`
Comment: Editei a perguntar para você entender melhor.
Comment: Mas sua regra para *download* é `site.com/download/arquivo`, e não `site.com/download/?aaaa`. Seguindo a lógica da regra, o parâmetro `a` é *download*, e o parâmetro `k` corresponde ao arquivo.
Comment: Quando eu entro em `site.com/download/aaaa` ele literalmente acessa o arquivo `/aaaa`, porem eu gostaria de quando acessar `site.com/download/aaaa` eu apenas pegasse a informação "aaaa" mas continuasse entrando no arquivo `download`.
Comment: Aparentemente por causa do seu loop. Veja se essa [resposta](http://pt.stackoverflow.com/a/27535/13412), ou a do Daniel ajudam no seu código.

Como pegar variável com $_GET


entity_metadata_wrapper langcode always prints default language

Question: I'm using entity_metadata_wrapper with entity translation to print fields in a template, but it always prints the default language when using a langcode in the options.
<code>$wrap = entity_metadata_wrapper('node', $node->nid, array('langcode' => 'zh-hans'));
print $wrap->field_main_subtitle->value(); // Returns English value
</code>
Printing out the $wrap array shows the following towards the end which might give some clue (langcode:protected => und):
<code>[propertyInfoAltered:protected] =>
    [langcode:protected] => und
    [propertyInfoDefaults:protected] => Array
        (
            [type] => text
            [getter callback] => entity_property_verbatim_get
            [clear] => Array
                (
                )

        )

    [type:protected] => node
    [data:protected] =>
    [info:protected] => Array
        (
            [langcode] => zh-hans
            [type] => node
            [property defaults] => Array
                (
                )

        )
</code>
Any ideas?
Answer: Try this
<code>print $wrap->language('zh-hans')->field_main_subtitle->value()
</code>
Comment: This works, but I thought one of the benefits of entity_metadata_wrapper was that you didn't need to hardcode the language when printing fields?


Different of Thread start()

Question: In researching previous project coding:
I found out that using Thread with 2 different way
First is
TimerThread tt=new TimerThread();
tt.start();

Second is
TimerThread tt=new TimerThread();
new Thread(tt).start();

is there any different between these 2 code when run?
Comment: What language is this? I assume Java but it would be helpful to tag it as such
Comment: I usually find ```Runnable``` and ```ScheduledExecutorService``` to be better choices than ```TimerTask``` and friends.
Answer: Geoffrey,
Yes. Kinda. The first option created a new TimerThread object and assigned it to the tt handle. It then accessed the start() method from that handle.
The second option created a new TimerThread object and assigned it to the tt handle. Then in the second line, created another new Thread object and assigned it to the tt handle, and then accessed the start() method through that "new" Thread object, thus orphaning the object created in the first line.
The only real difference is that option two does some unnecessary work in it's first line. I'm not 100% on this explanation, so I welcome anyone with a deeper understanding.
-Fletch
Answer: The first option was used when TimerThread was extended from Thread, and the second option was used when the TimerThread is an interface implemented from Runnable.
Hope it helps.

Different of Thread start()


selinux audit rule not logging anything

Question: I am trying to audit a directory tree for read, write, and permissions change. I created the rule using auditctl -w <path> -k media-watch, but ausearch -k media-watch only shows the creation (or deletion for debugging) of the rule, and not file creation or changes within the specified directory or below it in the tree. Selinux is disabled, if that's relevant.
Why? How can I make sure file access/changes are logged for auditing?
Answer: The man page says that -w is deprecated, so I wouldn't be using it. I'd be using the current format for such a rule instead. For example:
auditctl -a always,exit -F dir=/path/to/dir/ -k media-watch

Answer: I will argue with @Michael Hampton, about making all the rules in the format that he suggested. But I will agree with him on get guidance from the man page of the Linux Audit Kernel [1].
According to the manual, there are 3 types of rules control, file (Which is what @RedTedRedemption is trying to do) and system calls (Which is what @Michael is suggesting)
In your rule to track the modifications on the file of read, write, and change of permissions you need to add the modifier -p with these options:

w = write
a = change permissions or access
r = read

I think @RedTedRedemption is on the right path, setting up a rule to watch for modifications in a specific directory.
However, you need to establish this rule as permanent in the audit.rules file under /etc/audit/ directory. Otherwise, every time the audit daemon restarts, or the server restarts, the default rules will be applied again, and your settings will no longer be logging to the /var/log/audit/audit.log file.
To set up your rule to watch for the directory permanently, this is the line that you must type over the rules setting file under /etc/audit/audit.rules
 -w </your/file/path> -p war  -k <your-key>
In addition, you need to comment or delete these rules from there too:
# First rule – delete all
#-D

# Disable system call auditing.
# Remove the following line if you need the auditing.
#-a never,task

Because the above control rules are overriding and deleting all following rules on reload
And then, when you apply your changes to the audit.rules, run these commands:

service auditd reload or systemctl auditd reload
service auditd restart or systemctl auditd restart

Finally, to query for audit logs related to your rule you will need to run these commands:

sudo ausearch -i -k <your-key> -> To search for events related to your rule key
sudo aureport -k -> To print in screen an audit report organized by rule's keys
sudo aureport -f -> To print in screen an audit report organized by file's names

References:
https://linux.die.net/man/7/audit.rules [1]

selinux audit rule not logging anything


Split up messy column to several rows in excel file

Question: I have a csv file in which 2 of the cols has a lot of info that I want split up (see example below), and I want to split the column and make into rows, however I do not have a specific delimiter I can just use while reading in the file into pandas as the data is very messy. P.S, i used random letters/ numbers instead of the actual info in there, but it goes something like name, id, age, time, etc... (note not all the info is stored in strings in the actual data, some are just integers)
I know about .split(), but I don't think that would work with what I want. any help is appreciated.
   v1                                            |v2
   ---------------------------------------------------------------------------------------------
x |1                                             | 2
y |"n": "k", "f": "a", "m", C", "z": "2","4","1" |"n": "j", "f": "l", "n", q", "z": "5","9", "13"
v |8                                             |9

how would i make it like this:
   v1            | v2
-------------------------
x |1             |2
n |"k"           |"j"
f |"a", "m", "c" | "l", "n", "q"
z |"2","4","1"   | "5","9", "13"
v |8             | 9

Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: Why is this tagged R when you're asking about Pandas?
Comment: Can you provide the raw csv file ? Or at least the relevant part.
Comment: I tagged R because if there was a relevant solution in R, I'd do it in R instead of python/pandas
Comment: I cannot provide the raw csv file because it is confidential, but this gives a pretty good idea of what it looks like
Answer: Using R and assuming

the data shown reproducibly in the Note at the end and
we want to split the complex strings at the colons

separate the rows using separate_rows and then trim the whitespace off the ends of both columns.
library(dplyr)
library(tidyr)

d %>%
  separate_rows(v1, v2, sep = ":") %>%
  mutate(v1 = trimws(v1), v2 = trimws(v2))

giving:
# A tibble: 6 x 2
  v1                         v2
  <chr>                      <chr>
1 "1"                        "2"
2 "\"n\""                    "\"n\""
3 "\"k\", \"f\""             "\"j\", \"f\""
4 "\"a\", \"m\", C\", \"z\"" "\"l\", \"n\", q\", \"z\""
5 "\"2\",\"4\",\"1\""        "\"5\",\"9\", \"13\""
6 "8"                        "9"

Note
Lines <- 'v1                                           |v2
x |1                                             | 2
y |"n": "k", "f": "a", "m", C", "z": "2","4","1" |"n": "j", "f": "l", "n", q", "z": "5","9", "13"
v |8                                             |9'
d <- read.table(text = Lines, sep = "|", strip.white = TRUE, quote = "")


How to disable Transfer Encoding: chunked for ServiceStack

Question: Is there a way to configure ServiceStack to not add the transfer-encoding:chunked in the response of the HTTP header and disable this encoding type?
Answer: ServiceStack just works over raw ASP.NET IHttpHandlers so follows the standard behaviour of ASP.NET applies. This earlier question provides hints in how to change Transfer Encoding behaviour in ASP.NET.


Can a time series be stationary and still have seasonality?

Question: Would there be a case that a time series does have seasonality but, ADF test fails to point it out. I want to be sure of it being stationary so that I can use it in a regression and be sure that the results are not spurious.
Comment: Why not refer to Rob Hyndman's explanation on https://otexts.com/fpp2/stationarity.html#fn14? *"A stationary time series is one whose properties do not depend on the time at which the series is observed. Thus, time series with trends, or with seasonality, are not stationary — the trend and seasonality will affect the value of the time series at different times."* There's a footnote to this definition though.
Comment: You seem to equate a statistical test with a property of an underlying process.  Although the distinction may seem subtle, it's important. So, what exactly do you mean by "be stationary"?
Comment: A time series with a seasonal component is non-stationary.  If your target variable is stationary, it doesn't have a seasonal component, and therefore it seems unlikely to me that a seasonal time series is really an appropriate regressor.   The fact that you think it is causes me to wonder, along with @whuber, what exactly you mean by "be stationary".   See https://stats.stackexchange.com/questions/131092/does-a-seasonal-time-series-imply-a-stationary-or-a-non-stationary-time-series?rq=1, which your question may be a duplicate of.
Comment: Note that the first answer, despite being accepted, got a pretty negative score and a lot of disagreement.  However, mea culpa; this https://stats.stackexchange.com/questions/174741/can-a-time-series-be-stationary-if-the-formula-for-the-mean-level-depends-on-t one is a better quick reference.
Comment: @whisperer, if I read your last comment correctly, you seem to read the ADF test as an omnibus test against all sorts of possible violations of stationarity (e.g. the ones mentioned by Isabella). It definitely cannot do that. It is, broadly speaking, a test of the null of a stochastic trend against the alternative of mean reversion.
Comment: Thanks all, for your comments and references! As far as I understand, the answer seems to be yes it is possible to pass ADF test (declaring ADF stationary) and still have seasonality.
Comment: Can I use it to regress against y (definitely stationary) and be sure that the regression results are not spurious. Thanks for pointing it out. Will update the questions accordingly.
Comment: I checked that question and the two comments gave opposite views. The time series is stationary judging by the ADF test. From a design point of view, I agree that it is a less likely predictor. However during the non seasonal spikes it should be based on the relation between them.
Answer: For stationarity you have 3 criterions:

Constant mean
Constant variance
No seasonalities

The trick with DF/ADF is that it is testing for the first difference (aka the trend) only. It could iteratively cover larger differences (aka the seasonalities) as well but it is defined as it is. So, it says nothing about the seasonalities.
This video https://www.youtube.com/watch?v=1opjnegd_hA explains the equations where you will see the value of delta.
Comment: Because this is an unusual definition of stationarity, could you provide an authoritative reference?  In my experience, two kinds of stationarity are typically used: *strict stationarity* means all the finite-dimensional joint distributions of the process are invariant under time translation and *weak (second order) stationarity* means all first and second moments of those joint distributions are invariant under time translation.  Both imply the first two of your conditions; the first implies the third condition; but you omit mention of time-invariant *covariances,* which is crucial.


Would disabling these following functions in PHP.INI affect Drupal 7?

Question: If i disabled the following php functions:
disable_functions = escapeshellarg,escapeshellcmd,exec,ini_alter,parse_ini_file,passthru,pcntl_exec,popen,proc_close,proc_get_status,proc_nice,proc_open,proc_terminate,show_source,shell_exec,symlink,system
would this affect drupal 7 in anyway? I am disabling them to increase security on my server. This was mentioned on securing an Invision powerboard forum.
Comment: http://drupal.org/requirements/php - for Drupal core it doesn't. Not sure about modules that call system functions...
Comment: Drupal 7 core and much of contrib has a testing built in. Did you try this configuration and then running tests?
Answer: Yes, that may cause odd debug issues down the track.
Some of those are required by drush:
i.e:

escapeshellarg
escapeshellcmd

symlink is used in system.tar.inc
Modules such as devel and advanced_help use parse_ini_file
Other contrib may use others, e.g print_pdf uses proc_open


Drupal 7 to 8 migration The "taxonomy_term_reference_plain" plugin does not exist

Question: When running the d7_field_formatter_settings.yml (in core/modules/field/migrations/) migration I get the following error.
The "taxonomy_term_reference_plain" plugin does not exist

Has the taxonomy_term_reference_plain formatter been removed from Drupal 8?
If so what is the equivalent in drupal 8 and how can I map taxonomy_term_reference_plain into its drupal 8 equivalent during migration
Answer: Yes, taxonomy terms are now treated as general entities rather than special (for the most part), so some of the taxonomy-specific formatters were inevitably removed.
I believe the entity_reference_label formatter is the natural replacement for Drupal 8.


push javascript == undefined

Question: Estou tentando mandar um objeto para dentro de um arrey para assim obter uma sequencia de objetos porém quando eu uso a função push ela da erro falando que ta undefined vou deixar os códigos abaixo:
objectArrey: Object[]
//esse é a minha variável onde todos os objetos tem que estar

//nesse código é onde eu faço um forEach no meu arrey que chegou da api a adiciono extraio desse objeto as informações necessárias e na hora do push da o erro Cannot read property 'push' of undefined.
this.api.getAll().subscribe(
      data => {
        let arreyAst = data.near_earth_objects['2015-09-08'];
        let ast = {}
        arreyAst.forEach(element => {
          ast = {
              name: element.name,
            }

          this.objectArrey.push(ast)
        });
        console.log(this.objectArrey)
      },
      error => {
        console.log('Deu erro ' + error)
      })

Código completo do ts:
import { Component, OnInit } from '@angular/core';
import { ApiServiceService } from '../api-service.service';

@Component({
  selector: 'app-object',
  templateUrl: './object.component.html',
  styleUrls: ['./object.component.scss']
})
export class ObjectComponent implements OnInit {

  objectArrey: Object[]

  constructor(private api: ApiServiceService) { }

  ngOnInit(): void {
    this.getObj()
  }

  getObj(){
    this.api.getAll().subscribe(
      data => {
        let arreyAst = data.near_earth_objects['2015-09-08'];
        let ast = []
        arreyAst.forEach(element => {
          ast = [
            {
            name: element.name,
            }
          ]
          this.objectArrey.push(ast)
        });
        console.log(this.objectArrey)

      },
      error => {
        console.log('Deu erro ' + error)
      })
  }

}

Comment: Onde defines `this.objectArrey`? O que dá `typeof this.objectArrey, Array.isArray(this.objectArrey));` na primeira linha dessa função (antes do `forEach`)
Comment: eu não entendi muito bem, porém fiz isso e continuou dando erro.
Comment: Mostrou alguma coisa na consola?
Comment: a aplicação nem compila.
Comment: Cara consegui resolver, era um erro muito bobo que acaba passando despercebido, obrigado pela ajuda a solução é  objectArrey: Object[] = [] é so declarar um arrey vazio
Comment: ok, então tinhas um erro no TypeScript... esse erro deve ser visivel no compilador
Comment: não é não pow huahuau se não eu tinha lido o erro pow
Answer: Para resolver é só trocar a variável objectArrey para a seguinte forma:
objectArrey: Object[] = []

push javascript == undefined


Use IntentFiler in onPause()

Question: I want to start my Application (ex update my TextView) after press back button. But it didn't work. Please help me.
<code>public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
   intentFilter = new IntentFilter();
    intentFilter.addAction("SMS_RECEIVED_ACTION");
    registerReceiver(intentReceiver, intentFilter);
}

protected void onPause() {
     registerReceiver(intentReceiver, intentFilter);
     super.onPause();

}

private  BroadcastReceiver intentReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        sendSMS("123","message");

    }
};
</code>
Comment: Can you specify what you want to do exactly.. means you want to start new activity on back press and also want to update text view.
Comment: Are you trying to set the textview for an Activity that is paused and possible stopped/destroyed?  When it calls back to onResume it is being re-inited anyway.  Maybe try storing the value in another variable that won't be erased.
Comment: I want to send a message to a phonenumber when my app is onPause() using function sendSMS. can you help me.
Answer: I have updated your code try this and if any problem is there then ask me. I will try to help you ..
<code> @Override
    public void onBackPressed() {
        // FOR UPDATING YOUR TEXT VIEW.
        Intent broadcast_intent = new Intent("SMS_RECEIVED_ACTION");
        broadcast_intent.putExtra("number", textview_value_to_set);
        sendBroadcast(broadcast_intent);

        // // FOR STARTING YOUR NEW ACTIVITY.
        Intent intent = new Intent(getApplicationContext(), class_name.class);
        startActivity(intent);

        super.onBackPressed();
    }
</code>
Use this as your broadcast receiver. Dont forget to register reciever.
<code>    private  BroadcastReceiver intentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("SMS_RECEIVED_ACTION")) {
                TextView text = (TextView)findViewById(R.id.text);
                text.setText(intent.getExtras().getString("number"));
            }

        }
    };
</code>
Comment: Thanks everyone. I'm want when my device receive a sms, it will send another sms to a phonenumber. My app worked when it on the foreground, but I need it still running on background. Can you help me? Sorry if you didn'd understand me. My English is so bad.
Comment: I think you should bind a service with your activity whenever your receive sms update UI of your activity using broadcast or any other way. In this way when you will be in background it will work without any problem.

Use IntentFiler in onPause()


Show that $T$ is a topology on $X$.

Question: Let $f:X\rightarrow Y$ be a map and let $T'$ be a topology on $Y$.
Show that $$T=\{U\subseteq X \mid \exists V\in T' \text{ with }U=f^{-1}(V)\} $$ is a topology on $X$.
$T'$ is the coarsest topology on $X$ such that the map $f:(X, T) \rightarrow (Y, T') $ is continuous.
$$$$
We have to show:
1.The set $X$ and the empty set are elements of $T$ .

Any union of elements of $T$ belongs to $T$.

Any finite intersection of elements of $T$ belongs to $T$.

$$$$
Toshow these axioms, Ihave done the following:

It holds that $X\subseteq X$ and $f(X)\in T'$ where $T'$ is a topology, and so we get $X\in T$.
We also have that $\emptyset\subseteq X$ and $f(\emptyset)\in T'$ where $T'$ is a topology, and so we get $\emptyset\in T$.

We consider the union $O = \bigcup\limits_{\alpha \in I} U_{\alpha}$.

This set is in $T$ iff theimage under $f$ is in $T'$.
So we consider $f \left( O \right)$.
The union is well defined under images so we get \begin{equation*}f \left( O \right) = f \left( \bigcup\limits_{\alpha \in I} U_{\alpha} \right) = \bigcup\limits_{\alpha \in I} f \left( U_{\alpha} \right)\end{equation*}
Since each $U_{\alpha}$ is in $T$, the images $f\left( U_{\alpha} \right)$ are in $T'$.
Since $T'$ is a topology, is the union again in $T'$ and so we get that $O$ in $T$.

The respective argument of 2.for intersection.

Is everything correct?
Comment: First mistake.  Actually, it's because $Y\in T'$ that we get $X=f^{-1}(Y)\in T$.  We have no guarantee that $f(X)\in T'$.  But $Y\in T'$, because $T'$ is a topology (on $Y$).
Comment: Ahhh ok! I see!! For the empty set: We have that $\emptyset \in T'$ ,since $T'$ is a topology. and $\emptyset=f^{-1}(\emptyset)\in T$. Is the last step correct?@ChrisCuster
Comment: Yes!  I was just going to point that out.
Answer: $\emptyset = f^{-1}[\emptyset]$ and as $\emptyset \in T'$ we have by definition $\emptyset \in T$. Same for $X=f^{-1}[Y]$ and $Y \in T'$.
If $U,V \in T$ so $U = f^{-1}[U']$ for some $U' \in T'$ and $V = f^{-1}[V']$ for some $V' \in T'$, we have $U \cap V =  f^{-1}[U'] \cap f^{-1}[V']= f^{-1}[U' \cap V']$ and $U' \cap V' \in T'$, as $T'$ is closed under finite intersections, so $U \cap V \in T$ as well.
If for all $i \in I, U_i \in T$ so that we have $U'_i \in T'$ such that $f^{-1}[U'_i]=U_i$, then $\bigcup_i U'_i \in T'$ too and as $\bigcup_i U_i = \bigcup_i f^{-1}[U'_i] = f^{-1}[\bigcup_i U'_i]$ we get that $\bigcup_i U_i \in T$, as required.
So you have to write everything as preimages from $T'$, not check the image is in $T'$, because that is how $T$ is defined.
If $U$ is any topology on $X$ that makes $f: (X,U) \to (Y,T')$ continuous then for any $O \in T'$ we must have $f^{-1}[O] \in U$, but by definition, $f^{-1}[O]$ is the form of any set in $T$ so $T \subseteq U$. This shows that $T$ is the smallest (coarsest) topology that makes $f$ continuous.
Comment: @MaryStar No, because $f^{-1}$ commutes with intersections. Standard set theory fact.
Comment: How do we get that $U \cap V = f^{-1}[U' \cap V']$ ? Is this because the intersection is well defined under intersection?
Comment: Thank you very much!! :-)
Answer: So, we made two corrections, and you are well on your way!
Left is just to prove the intersection and union properties.  But they follow from the general facts:

$f^{-1}(A\cup B)=f^{-1}(A)\cup f^{-1}(B)$
$f^{-1}(A\cap B)=f^{-1}(A)\cap f^{-1}(B)$

Note there is another correction here:  you want preimages not forward images, because you're starting with the topology $T'$ on $Y$.
That $T$ is the coarsest topology that makes $f$ continuous is clear, because if you take out even one open set, the definition fails.
Comment: Basically.  I think you misspoke slightly when you said $U_{\alpha}$ is in $T$.  It's the _preimage_ of open sets that's going to be in $T$, as both @Henno and I have now pointed out.
Comment: The union is well defined under preimages so $$f^{-1} \left( \bigcup\limits_{\alpha \in I} U_{\alpha} \right) = \bigcup\limits_{\alpha \in I} f^{-1} \left( U_{\alpha} \right)$$
Since each $U_{\alpha}$ is in $T$, then the preimages $f^{-1} \left( U_{\alpha} \right)$ are in $T'$.

Since $T'$ is a topology it is closed under the union.

That means that $\bigcup\limits_{\alpha \in I} U_{\alpha}$ in $T$, right?
Comment: Thanks a lot!! :-)

Show that $T$ is a topology on $X$.


SQLite cannot execute from F# FSI

Question: None of the SQLite .NET packages work in FSI, even when referencing a module in a fs project. I've tried System.Data.SQLite, SQLitePCL.raw, and Microsoft.Data.Sqlite.
From System.Data.SQLite docs:

If the executable that starts the process consists entirely of managed code, it will run with the native processor architecture of the machine, which will be x64 on an x64 machine. Later on, this will cause assemblies containing any native code compiled for x86 (e.g. the "System.Data.SQLite.dll" mixed-mode assembly, the "SQLite.Interop.dll" native interop assembly, or the "sqlite3.dll" native library) to fail to load, typically resulting in a BadImageFormatException being thrown.

The error thrown typically looks like
System.DllNotFoundException: Unable to load DLL 'sqlite3': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
   at Microsoft.Data.Sqlite.Interop.NativeMethods.sqlite3_open_v2(IntPtr filename, Sqlite3Handle& ppDb, Int32 flags, IntPtr vfs)
   at Microsoft.Data.Sqlite.Interop.NativeMethods.sqlite3_open_v2(String filename, Sqlite3Handle& ppDb, Int32 flags, String vfs)
   at Microsoft.Data.Sqlite.SqliteConnection.Open()
   at <StartupCode$FSI_0009>.$FSI_0009.main@() in E:\BitSync\NonGitProjects\SQLiteSandbox\Microsoft.DataSandbox\Scripts\Script1.fsx:line 7

Demo gist
Has anyone found a solution to this? SQLite works just fine in compiled F# programs and in debug mode.
Comment: Don't know if you tried this or if it will help but can't hurt to mention it. See: [Loading Native DLLs in F# Interactive](http://christoph.ruegg.name/blog/loading-native-dlls-in-fsharp-interactive.html)
Comment: 32bit or 64bit FSI ?
Comment: @GuyCoder That's exactly what helped me get it working a few weeks back.
Comment: @Functional_S I tried both 32 & 64 bit FSI. Looks like the article Guy Coder posted has potential, trying that soon and will report back.
Answer: The artice Loading Native DLLs in F# Interactive has correct techniques for solving the problem of loading native DLLS.
In my case in my case I successfully tried
System.Environment.CurrentDirectory <- @"D:\Projects\SQLiteSandbox\SQLiteSandbox\bin\Debug\x86"

SQLite cannot execute from F# FSI


Is a finite covering of a $\partial\bar{\partial}$-manifold still $\partial\bar{\partial}$-manifold?

Question: A compact complex manifold is called a $\partial\bar{\partial}$-manifold if for every pair $p,q\in \mathbb{N}$, every smooth $d$-closed $(p,q)$-form $\eta$ on $X$, $\eta$ is $d$-exact iff $\partial$-exact iff $\bar{\partial}$-exact iff $\partial\bar{\partial}$-exact.
Classical Hodge theory shows all compact Kähler manifolds are $\partial\bar{\partial}$-manifolds, but not vice versa.
According to Theorem 5.22 of Real homotopy theory of Kähler manifolds (by Deligne et el.), given a bimeromorphic morphism $X\to Y$ of compact complex manifolds, if $X$ is a $\partial\bar{\partial}$-manifold, then we know $Y$ is also a $\partial\bar{\partial}$-manifold.
I wonder what happens in the other direction. Explicitly, if $M\to N$ is a finite covering of compact complex manifolds, and $N$ is a $\partial\bar{\partial}$-manifold, do we have that $M$ is a  $\partial\bar{\partial}$-manifold?
Answer: This question is natural and valuable.
EDIT: I don't know the case of finite covering.
But if we still consider a bimeromorphic morphism $f:X\rightarrow Y$. As far as I know, the converse of [DGMS] has been confirmed in the case $\text{dim}\leq 3$ (which is maybe the best possible result up to now) by
S. Rao--S. Yang--X. Yang, Dolbeault cohomologies of blowing up complex manifolds.
J. Math. Pures Appl. (9) 130 (2019), 68–92.
To prove this claim,  they established Dolbeault and De Rham blow up formulae, a characteristic of the $\partial\bar{\partial}$-lemma also provides the energy. For more details, one can refer to Remark 4.6 in their article.


Why is this set a circle: $E = \{z \in \mathbb{C} : |z + i| = 2|z|\}$.

Question: I am told

the set $E = \{z \in \mathbb{C} : |z + i| = 2|z|\}$ is a circle centered at $\dfrac{i}{3}$ of radius $\dfrac{2}{3}$.

We can write this equation like:
$$\sqrt{x^2 + (y + i)^2} = 2\sqrt{x^2 + y^2} \implies\\
x^2 + (y+i)^2 = 4x^2 + 4y^2 \implies \\
x^2 + y^2 + 2iy - 1 = 4x^2 + 4y^2 \implies\\
3x^2 + 3y^2 - 2iy = -1$$
Already, with that $y$ term, this can't be a circle, right?
Comment: You should not have an $i$ in the first expression.  It should be $y+1$.
Comment: `+(y+i)^2` You surely meant $\,+(y\color{red}{+1})^2\,$ there. `Why is this set a circle?` See for example [Proving the Apollonian circle formula](https://math.stackexchange.com/questions/2218133/proving-the-apollonian-circle-formula/).
Answer: Here a purely complex approach:
A circle in $\mathbb{C}$ with radius $r$ around $a$ is given by $\boxed{|z-a| = r}$. Squaring gives an equivalent equation:
$$ |z-a|^2 = (z-a)(\bar z - \bar a) = |z|^2 + |a|^2 - (a\bar z + \bar a z) = \boxed{|z|^2 +\color{blue}{|a|^2} - 2\Re{(\color{blue}{\bar a} z)} = r^2}$$
In your case you only need to check whether you can rearrange your given equation into the boxed form. From there you can read off immediately the radius and the center:
$$|z + i|^2 = |z - (-i)|^2 = 4|z|^2 \Leftrightarrow |z|^2 + 1 - 2\Re{(iz)}= 4 |z|^2 \Leftrightarrow |z|^2  + \frac{2}{3}\Re{(iz)} = \frac{1}{3}$$
Now, a quick complex square completion leads to the desired result:
$$\frac{1}{3} = |z|^2  + \frac{2}{3}\Re{(iz)} = |z|^2  - 2\Re{(\color{blue}{-\frac{1}{3}i}z)} +\color{blue}{\frac{1}{9}}  - \frac{1}{9} \Leftrightarrow \boxed{|z|^2 + \color{blue}{\frac{1}{9}} -2\Re{(\color{blue}{-\frac{1}{3}i}z)} = \frac{4}{9} }$$
This describes a circle around $\color{blue}{a = \frac{1}{3}i}$ with radius $r= \frac{2}{3}$.


Como implementar o método verifyDeveloperPayload?

Question: Alguém sabe como faço para implementar essa função, quando se trabalha com Google Billing?
Vi que um token deve ser gerado para verificação de licença e evitar fraudes.
Mas alguém sabe como implementar, por que implementar e os riscos que se corre, caso não seja implementado?
Answer: Acho que aqui está muito bem explicado :)
http://codigo-google.blogspot.com.br/2013/02/implementar-in-app-billing-em-android.html
Answer: O DeveloperPayload é apenas mais uma maneira de deixar o processo todo de compra mais seguro.
Caso não seja implementado, você está deixando de fazer mais uma verificação pra saber se a requisição é verdadeira. Estaria deixando um usuário (usando hack?) comprar vários items do seu app sem te pagar, por exemplo.

Como funciona?
Ao iniciar o processo de compra dentro do app, você cria um payload, que deve ser diferente para cada usuário, mas não diferente para cada aparelho (pois se um usuário fizer uma compra em um aparelho, ele tem que conseguir recuperar essa compra em outro aparelho). Usar uma string aleatória também não é legal, pelo mesmo motivo da mudança de aparelho.
O método verifyDeveloperPayload() é usado para verificar se o payload que veio da requisição é o mesmo que você usou para iniciar a requisição.
O recomendado é usar um servidor próprio para armazenar essas informações, assim independente da versão do app, ou do aparelho utilizado, é possível verificar se o payload está correto.
Se quiser ler mais sobre isso:
http://developer.android.com/google/play/billing/billing_best_practices.html#payload
Comment: Até aí tudo bem, mas no caso de eu não querer (ou não poder) ter um servidor próprio, existe alguma forma de eu fazer essa verificação? Eu vi aqui que talvez eu possa gerar a chave no momento da requisição e quando houver um retorno, caso de compra, eu verifico se foi o mesmo gerado na requisição. As vezes, assim possa funcionar...


Loop em R com indexação e matriz

Question: Estamos tentando utilizar o comando for para rodar uma função y (digamos y=5+3x+4z) variando os valores de z (digamos que z é uma combinação de 5 valores z=c(1,2,3,4,5)) e que x é uma distribuição normal de tamanho 1000. Após imprimir os valores, que usamos por meio de indexação, como poderíamos transformar esses resultados em uma matriz de 1000 linhas e 5 colunas (1000 observações para cada valor de z)?
Depois de usar o comando for:
z=c(1,2,3,4,5)
for(i in c(1,2,3,4,5)) print(y<-5+3x+4z[i]))

Tentamos definir uma matriz de y que não funciona pois ele imprimi a primeira coluna nas outras 4 restantes.
Comment: poste o código que você está usando, e o resultado esperado para podermos ajudar.
Comment: z=c(1,2,3,4,5)
y<-5+3x+4z
for(i in c(1,2,3,4,5)) print(matrix(5+3x+4z[i],100,5))
Comment: x=c(1,2,3,4,5)
z=c(1,2,3,4,5)
for(i in 1:5) print(matrix(5+3x+4z[i],100,5))
o resultado esperado tem que ser uma matriz de cinco colunas (cada coluna para os 5 z's) e 5 linhas (cada linha para os 5 x's).
Answer: Difícil entender qual o resultado esperado pelo OP, mas aqui vai uma tentativa.
Y = matrix(NA,nrow=0,ncol=5)
x=c(0,1,2,3,4)
z=c(1,2,3,4,5)
for (i in 1:5) {
  y = 1*x+2*z[i]
  Y = rbind(Y,y)
}
Y
  [,1] [,2] [,3] [,4] [,5]
y    2    3    4    5    6
y    4    5    6    7    8
y    6    7    8    9   10
y    8    9   10   11   12
y   10   11   12   13   14

Answer: Assumindo uma distribuição normal de média 0 e desvio padrão 1:
x <- rnorm(1000, mean = 0, sd = 1)
z <- c(1, 2, 3, 4, 5)
Y <- matrix(NA, 1000, 0)

for (i in z) {
  y <- 5 + 3*x + 4*i
  Y <- cbind(Y,y)
}

print(tail(Y))

                y         y        y        y        y
[995,]   4.450844  8.450844 12.45084 16.45084 20.45084
[996,]   9.072672 13.072672 17.07267 21.07267 25.07267
[997,]   8.609610 12.609610 16.60961 20.60961 24.60961
[998,]   6.977799 10.977799 14.97780 18.97780 22.97780
[999,]   5.896328  9.896328 13.89633 17.89633 21.89633
[1000,] 13.005769 17.005769 21.00577 25.00577 29.00577

Ao final, Y terá 1000 linhas e 5 colunas. Ou seja, 1000 observações para cada valor de z.
Answer: Você não precisa usar for neste caso.
Segue uma solução com sapply:
y <- function(x,z) 5+3*x+4*z
set.seed(1)
x <- rnorm(1000, mean = 0, sd = 1)
z <- c(1, 2, 3, 4, 5)
resultados<-sapply(z, y, x=x)

Os resultados serão 5 colunas (uma para cada z) com 1000 observações:
head(resultados) ### mostrando apenas os 6 primeiros
      [,1]     [,2]     [,3]     [,4]     [,5]
[1,]  7.120639 11.12064 15.12064 19.12064 23.12064
[2,]  9.550930 13.55093 17.55093 21.55093 25.55093
[3,]  6.493114 10.49311 14.49311 18.49311 22.49311
[4,] 13.785842 17.78584 21.78584 25.78584 29.78584
[5,]  9.988523 13.98852 17.98852 21.98852 25.98852
[6,]  6.538595 10.53859 14.53859 18.53859 22.53859

Loop em R com indexação e matriz


Analysis of cross correlation between point-processes

Question: I would like an advice on a analysis method I am using, to know if it it statistically sound.
I have measured two point processes $T^1 = t^1_1, t^1_2, \ldots, t^1_n$ and $T^2 = t^2_1, t^2_2, \ldots, t^2_m$ and I want to determine if the events in $T^1$ are somehow correlated to the events in $T^2$.
One of the methods that I have found in the literature is that of constructing a cross-correlation histogram: for each $t^1_n$ we find the delay to all the events of $T^2$ that fall in a given window of time (before and after $t^1_n$), and then we construct an histogram of all these delays.
If the two processes are not correlated I would expect a flat histogram, as the probability of having an event in $T^2$ after (or before) an event in $T^1$ is equal at all delays. On the other hand if there is a peak in the histogram, this suggests that the two point process are somehow influencing each other (or, at least, have some common input).
Now, this is nice and good, but how do I determine whether the histograms do have a peak (I have to say that for my particular set of data they're clearly flat, but still it would be nice to have a statistical way of confirming that)?
So, here what I've done: I've repeated the process of generating the histogram for several (1000) times keeping $T^1$ as it is and using a "shuffled" version of $T^2$.
To shuffle $T^2$ I calculate the intervals between all the events, shuffle them and sum them to reconstitute a new point process. In R I simply do this with:
<code>times2.swp <- cumsum(sample(diff(times2)))
</code>
So, I end up with 1000 new histogram, that show me the density of events in $T^{2*}$ compared to $T^1$.
For each bin of these histogram (they're all binned in the same way) I calculate the density of 95% of the histogram. In other words I'm saying, for instance: at time delay 5 ms, in 95% of the shuffled point processes there is a probability x of finding an event in $T^{2*}$ after an event in $T^1$.
I would then take this 95% value for all of the time delays and use it as some "confidence limit" (probably this is not the correct term) so that anything that goes over this limit in the original histogram can be considered a "true peak".
Question 1: is this method statistically correct? If not how would you tackle this problem?
Question 2: another thing that I want to see is whether there is a "longer" type of correlation of my data. For instance there may be similar changes in the rate of events in the two point processes (note that they may have quite different rates), but I'm not sure how to do that. I thought of creating an "envelope" of each point process using some sort of smoothing kernel and then performing a cross-correlation analysis of the two envelopes. Could you suggest any other possible type of analysis?
Answer: A standard method to analyze this problem in two or more dimensions is Ripley's (cross) K function, but there's no reason not to use it in one dimension, too.  (A Google search does a good job of digging up references.)  Essentially, it plots the CDF of all distances between points in the two realizations rather than a histogram approximation to the PDF of those distances.  (A variant, the L function, plots the difference between K and the null distribution for two uniform uncorrelated processes.)  This neatly sidesteps most of the issues you are confronting with the need to choose bins, to smooth, etc.  Confidence bands for K are typically created through simulation.  This is easy to do in R.  Many spatial stats packages for R can be used directly or readily adapted to this 1D case.  Roger Bivand's overview page on CRAN lists these packages: refer to the section on "Point Pattern Analysis."
Comment: Interesting... I'm a bit busy at the moment, but I'll definitely have a look at that!


The coefficient of $x^k$in the expansion of $\dfrac{1-2x-x^2}{e^x}$ is

Question:
The coefficient of $x^k$in the expansion of $\dfrac{1-2x-x^2}{e^x}$ is

This a question of university entrance examination, which my teachers didn't taught me and not in my syllabus.
I referred got this equation from Hall and Knight Algebra :

Coefficient of $x^r$ in the expansion of $\dfrac{1-ax-x^2}{e^x}$  is
  given by $$\dfrac{-1^r}{r!}\{1+ar-r(r-1)\}$$

However applying this answer gives me :
$$\dfrac{-1^k}{k!}(1+3k-k^2)$$
This doesn't match any of the choice given :
(A)$\:\dfrac{1-k-k^2}{k!}\qquad$
(B)$\:\dfrac{1-k}{k!}\qquad$
(C)$\:\dfrac{k^2+1}{k!}\qquad$
(D)$\:\dfrac{1}{k!}\qquad$
(E)$\:\dfrac{1+k}{k!}$
Comment: For one thing, you are missing some "$(-1)^r$"-s now and then.
Comment: Sorry, my mistake, edited now.
Answer: $$(1-2x-x^2)e^{-x}=
(1-2x-x^2)\sum_{k=0}^\infty(-1)^k\frac{x^k}{k!}.$$
I reckon the $x^k$ coefficent is
$$(-1)^k\frac1{k!}-(-1)^{k-1}2\frac1{(k-1)!}
-(-1)^{k-2}\frac{1}{(k-2)!}
=(-1)^k\frac{1+2k-k(k-1)}{k!}.$$
What does this simplify to?


If $f$ is holomorphic on some open set $G\subseteq \mathbb{C}$, then $f$ is infinitely often complex differentiable

Question: Let $G$ be an open subset of $\mathbb{C}$, and suppose that $f$ is holomorphic on $G$. Let $a\in G$ be arbitrary. The reason why $f$ is infinitely often complex differentiable is, in my opinion (if I'm wrong, please tell me), based on Cauchy's Integral Formula for Derivatives,

If $\overline{B(a,r)}\subseteq G$, then for every $z_0\in B(a,r)$ we have
$$f^{(n)}(z_0)=\frac{n!}{2\pi i}\int_{\partial B(a,r)}\frac{f(z)}{(z-z_0)^{n+1}}\,\mathrm{d}z,\quad n=0,1,2,\dots
$$

Clearly, one can find $\rho>0$ such that $B(a,r)\subseteq G$, because $G$ is open. But, is the existence of $\rho'>0$ satisfying that $\overline{B(a,\rho')}\subseteq G$ guaranteed?
Comment: $\overline{B(a,r/2)}\subset B(a, r) \subset G$.
Comment: @MartinR That's nice. So, the radius $r$ depends on the choice of $a$ (right?), and then create a small closed ball inside this open ball, say $\rho':=r/2$. The theorem in OP tells us that $f$ is infinitely often differentiable on $B(a,\rho')$. But, since $a$ was arbitrary, it is infinitely often differentiable on whole $G$ --- answering to the claim of the title. How does it sound?
Comment: That is correct.
Comment: @MartinR Beautiful. Thanks for your time!
Answer: For $a\in G$ there is an $R > 0$ such that $B(a, R) \subset G$. Setting $r =R/2$ one has $\overline{B(a,r)}\subset B(a, R) \subset G$. Now one can show with induction that for all integers $n \ge 0$:

$f$ is $n$-times differentiable in $B(a, r)$, and
for all $z_0 \in B(a, r)$, $$\tag{*}f^{(n)}(z_0)=\frac{n!}{2\pi i}\int_{\partial B(a,r)}\frac{f(z)}{(z-z_0)^{n+1}}\,dz \, .
$$

For $n=0$ this is Cauchy's integral formula. For the inductive step you have to show that you can differentiate under the integral sign on the right-hand side of $(*)$.
This shows that $f$ is infinitely often differentiable in a neighbourhood of every $a \in G$, which proves the claim.
So Cauchy's formula for the derivatives shows (for each $n$) both the existence of the $n$-th derivative, and the representation of $f^{(n)}$ as an integral.


Betting value, with our without bookmaker margin

Question: I am trying to find the value of a bet, with my percentage, that some team will win to see if i think there is value in some bet.
My question is, should i include the bookmakers margin, when i calculate the value of a bet, based on my percentage that some team will win?
I would think that i need to add the bookmakers margin to my percentage, to even out the margin they add to their odds -- is this wrong? Should i just go with my percentage and not add the bookmaker margin?
Comment: Right now the way you've worded this doesn't really have enough information for us to understand what you're asking.  Can you give an example of this?  Are you asking, given odds of +110 for a team, how you should evaluate the profit of a bet if you think they will win 55% of the time?
Comment: Lets say i have team 1 playing team 2. I think team 1 wins, with 60% probability. The odds is, lets say, 1.70.
This means, that the bookmaker belive that the team will win (1/58,8%) of the time.
If we add the rest of the bookmakers probabilities, we get: 5,6 and 3,65, which gives us: 1/5,6 = 17,9% and 1/3,65 = 27,4%.
When i add these up, i get 104,1% total, so the bookmaker has a 4,1% markup.

When i do my own percentages, should i then use my 60% (that i think the probability is), or should i use 60% + (4,1%/3) = 64,7%, adding the bookmakers markup, to my probability as well?
Comment: I think you need to explain what "do my own percentages" mean.  You think it should be 60% to win, and then you're comparing to 1.7x payout, so 1.02 average payout - great, what's the question?
Comment: My question is at its core:how to find the value of a bet, meaning, is there value in the long run. Do i:
1. odds / my estimation (60% chance of victory)
or
2. odds / my estimation (60% chance of victory) + bookmaker margin
Answer: Fundamentally, you don't care what the bookie's margin is. If for a bet of X, your expected payout is 1.70X and the chance of winning is 0.60, then your expected payout is (0.60 * 1.70)X = 1.02X and you're in the money. Assuming your estimate of 0.60 is correct of course...
The only disclaimer here is to ensure that your payout is actually 1.70X; if you're in a jurisdiction which taxes betting in some way, be very careful as to whether the quoted odds are net of tax.
Comment: That all depends on how things are presented. In the UK anyway, the bookie's margin isn't "added" to anything - their margin comes from the fact that $sum(p_outcome)$ over all outcomes where $p_outcome$ is the implicit probability of each outcome from the odds is more than one e.g. in a equally balanced contest, you'll see odds of something like 6/5 on for each side, giving $sum(p_outcome)$ = 6/11 + 6/11 = 12/11. Their margin is now that 1/11 "extra" which means the bookies make money even if they have equal bets on either side (continued...)
Comment: However, as an individual better, you don't care about that. All you need to know is that your expected payout on a successful bet of X is 1.83X. If you also think that the match is a toss-up, you'll think your expected return is 0.5 * 1.83X = 0.92X and a bad deal. Other countries/areas may or may not include the bookie's margin in the published odds, but once you have the expected payout for a bet, you're good.
Comment: Thanks for the answer.
Can you elaborate on why?
Comment: Why what? So long as your _expected payout_ is what you think it is, the maths is trivial. How odds are translated into expected payout is something that can vary between jurisdictions (e.g. whether the expected payout is gross or net of the bookie's odds) but once you've got your expected payout you're there.
Comment: What i mean is: To the bookies chances, they add a margin. Why shouldnt i add the same margin, to even out their added margin?
Comment: i get what your saying, and it was exactly what i was looking for. Thank you for taking the time to explain it to me.
Answer: Let's elaborate more on why the simple (0.60 * 1.70)X expression gives you a value bet. Taking the same example as in Kendall's answer:
Expected-Profit = Prob.Win * Win-profit - Prob.Loss * Bet-amount

We have:
Prob.Win = 0.6       (this is your analysis)
Prob.Loss = 0.4      (this is your analysis)
Win-profit = 0.7     (this is the bookie offer)
Bet amount = 1.0     (this is your bet)

Plugging in we get:
Expected-Profit = 0.6 * 0.7 - 0.4 * 1.0

Noticing that:
Expected-Payout = Expected-Profit + Bet-amount

we have:
Expected-Payout = (0.6 * 0.7 - 0.4 * 1.0) + (1.0)
                = (0.6 * 0.7 - 0.4) + (0.6 + 0.4)
                = (0.6 * 0.7) + (0.6)
                = 0.6 * 1.7

and with this simplification we do not actually need to look at the prob. of other outcomes (loss or draw (draw not show in this example)) and can always express:
Expected-Payout = Prob.win * Win-Payout

where Prob.win is your calculated value, so any Expected-Payout > 1.0 is in the money (in this case 0.6 * 1.7 = 1.02).
The same analysis can be done on other bets (loss or draw).


how to define a parameter must be a number in a function

Question: how do I write a defensive line of code stating a parameter must be a number or else console.log 'it must be a number
function getDiscount(taxBoolean,guests) {
    getPrices(taxBoolean)

    let condition1 = typeof(guests) == 0
    let condition2 = condition1 > 0 && condition1 < 30
    if (condition1 && condition2) {
        let discount = 0
        if (guests < 5) {
            discount = 5
        }
        else if (guests >= 5) {
            discount = 10
        }
 console.log(`Discount is : $${discount}`)
    }
     else{
        console.log(`the secound argument must be a number between 0 and 30`)
    }

}

Comment: [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/a/261593/3082296)
Answer: You can make use of the typeof operator like this:
if (typeof guests === 'number') {
    // number
} else {
    console.log('not a number');
}

Comment: Might be improved by using `Number.isInteger`, assuming we can't have half guests.


nunit-console not run tests with TestCase and TestCaseSource

Question: I'm using Xamarin Studio on OSX and i have implemented a test suite of PCL project (without references to View iOS and Android) with NUnit.Framework. All works fine inside Xamarin Studio via GUI (all tests are runned and it worked).
Now i'm trying to integrate test suite execution inside Jenkins. When i run via command line my test suite (this happens on Jenkins and also on my local environment)
 mono /Library/Frameworks/Mono.framework/Versions/3.12.0/lib/mono/4.5/nunit-console.exe Libs/Debug/MyTests.dll

i have this output
NUnit version 2.4.8
Copyright (C) 2002-2007 Charlie Poole.
Copyright (C) 2002-2004 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov.
Copyright (C) 2000-2002 Philip Craig.
All Rights Reserved.

Runtime Environment -
   OS Version: Unix 18.104.22.168
  CLR Version: 4.0.30319.17020 ( 3.12.0 ((detached/de2f33f Mon Feb  2 14:42:07 EST 2015) )

Tests run: 7, Failures: 0, Not run: 19, Time: 16.530 seconds

There are 19 tests not running with this kind of motivation:
<test-suite name="MyTestClass" success="True" time="0.000" asserts="0">
   <results>
      <test-case name="NamespaceExample.MyTestClass.MyTestMethod" description="My Test Description" executed="False">
         <reason>
            <message><![CDATA[Method MyTestMethod's signature is not correct: it must not have parameters.]]></message>
         </reason>
      </test-case>
   </results>
</test-suite>

this kind of tests have all a common feature, use of TestCase. Example
namespace NamespaceExample
{
    [TestFixture]
    public class MyTestClass
    {

        public IMyService service;

        [SetUp]
        public void TestCase()
        {
            // this method will be called before running every test
            service = new MyService ();
        }

        [Test (Description = "My Test Description")]
        [TestCase("it")]
        public void MyTestMethod(string code)
        {
            string terms = service.MethodToTest (code);
            Assert.IsNotNull (terms);
        }
    }
}

Seems that nunit-console not run test with TestCase parameters. I have also tried to use TestCaseSource with an IEnumerable source but results doesn't change.
If i don't pass this parameter inside method signature, but it sets inside method test is runned and works fine.
How could i solve?
I have read also this kind of issue Similar Question but it doesn't solve, because result it's same (tests not runned).
My environment is
=== Xamarin Studio ===

Version 5.7.1 (build 17)
Installation UUID: xxx
Runtime:
    Mono 3.12.0 ((detached/de2f33f)
    GTK+ 2.24.23 (Raleigh theme)

    Package version: 312000076

=== Apple Developer Tools ===

Xcode 6.0 (6299)
Build 6A313

=== Xamarin.iOS ===

Version: 188.8.131.52 (Indie Edition)
Hash: xxx
Branch:
Build date: 2015-01-24 09:42:21-0500

=== Xamarin.Android ===

Version: 184.108.40.206 (Indie Edition)
Android SDK: xxx/android-sdk-mac_x86
    Supported Android versions:
        1.6    (API level 4)
        2.1    (API level 7)
        2.2    (API level 8)
        2.3    (API level 10)
        3.1    (API level 12)
        4.0    (API level 14)
        4.0.3  (API level 15)
        4.1    (API level 16)
        4.2    (API level 17)
        4.3    (API level 18)
        4.4    (API level 19)
        4.4.87 (API level 20)
        5.0    (API level 21)
Java SDK: /usr
java version "1.7.0_71"
Java(TM) SE Runtime Environment (build 1.7.0_71-b14)
Java HotSpot(TM) 64-Bit Server VM (build 24.71-b01, mixed mode)

=== Xamarin.Mac ===

Not Installed

=== Build Information ===

Release ID: 507010017
Git revision: xxx
Build date: 2015-02-03 19:43:29-05
Xamarin addins: f7b7d34419c9ec24501bfa7c658e80a6305613e0

=== Operating System ===

Mac OS X 10.10.2
Darwin LS.local 14.1.0 Darwin Kernel Version 14.1.0
    Mon Dec 22 23:10:38 PST 2014

Answer: Try using a more recent NUnit version. You are using NUnit 2.4.8. Xamarin Studio's built in NUnit runner uses version 2.6.3 of NUnit.
It looks like NUnit 2.5 introduced support for the TestCase attribute. You can download NUnit from: http://nunit.org/index.php?p=download


Como ler arquivos de pasta e subpasta?

Question: Eu tenho uma função pra ler os arquivos da pasta, e não está funcionando.
preciso de uma função funcional que leia os arquivos das pastas e das subpastas.
Segue o código:
FolderBrowserDialog fbd = new FolderBrowserDialog();
            DialogResult result = fbd.ShowDialog();
            txtArquivo.Text = fbd.SelectedPath.ToString();

            //Marca o diretório a ser listado
            DirectoryInfo diretorio = new DirectoryInfo(txtArquivo.Text);
            //Executa função GetFile(Lista os arquivos desejados de acordo com o parametro)
            FileInfo[] Arquivos = diretorio.GetFiles("*.xml; *xlsx;");

            string[] files = System.IO.Directory.GetFiles(fbd.SelectedPath);

Comment: Você usou `diretorio.GetFiles("*.xml; *xlsx;");`. Esta forma de usar mais um padrão de busca não está documentado e nos teste que eu fiz, não foi possível pegar os dados das duas extensões, pelo contrário, usando os dois padrões separados com `;` faz retornar nada.
Comment: Dê uma olhada no [tour]. Você pode aceitar uma resposta se ela resolveu seu problema. Você pode votar em todos os posts do site também. Alguma lhe ajudou mais? Precisa que algo seja melhorado?
Answer: Se você estiver usando pelo menos o .NET 4.0 basicamente você precisa disto:
Directory.EnumerateFiles(fbd.SelectedPath, "*.*", SearchOption.AllDirectories))

Documentação
Ou pode usar desde a versão 2.0:
Directory.GetFiles(fbd.SelectedPath, "*.*", SearchOption.AllDirectories))

Documentação
Coloquei no GitHub para referência futura.
Ou seja, o que você precisava conhecer é a sobrecarga com o parâmetro de searchOptions.
Se quiser pegar uma extensão, específica é só mudar o padrão de busca de "*.*" para o extensão que deseja. Se quiser pegar mais de uma extensão terá que usar a solução que já lhe indiquei na minha outra resposta.
Existe um exemplo completo da Microsoft usando outra abordagem.

Como ler arquivos de pasta e subpasta?


How to embed HTML and CSS in a custom form element?

Question: This worked in Drupal 7 but isn't in Drupal 8.
$form['covid-19'] = array(
    '#markup' => '
Due to the COVID-19 situation, we will only be purchasing e-books and e-audiobooks at this time. You are welcome to enter your information for print books, DVDs, or CDs, and they will be purchased when the libraries re-open.  Inter-library Loans [loans from outside Yavapai County] are suspended for now.
',
);

I want the div with style info to stay intact so I can just comment it out when the crisis is over. Then I want to leave it there as a placeholder ready for the next crisis.
In this example, the strong tag makes it through but the div does not.
I also tried setting the div info as a #prefix and #suffix but that didn't work either.
Is there a way to do this?
Thank you!
Comment: See [Pass raw html to #markup](https://drupal.stackexchange.com/q/184963/89581) for numerous workarounds to the (intentional) filtering of markup on rendering.  Personally, I think it would probably be easier to just add a `.crisis` class to your site css...
Comment: Thanks for that link. Here's what worked for me: use Drupal\Core\Render\Markup;

[..]
return [
  '#markup' => Markup::create($html),
];
Answer: Markup strips away some tags and attributes. Here is a way to do it.
Add a class to your form
$form['#attributes']['class'][] = 'crisis';

Add css rule to your theme's css
.crisis {
    display: none;
}

if you do not have a library and a .css file to use, you need to create them. Define a library in your theme or module in your THEMEorMODULE.libraries.yml
crisis:
  version: 1.x
  css:
    theme:
      css/crisis.css: {}

create css/crisis.css file and put your css rule(s) in it
and attach the library to your form
$form['#attached']['library'][] = 'THEMEorMODULE/crisis'

and clear cache
NOTE: The above (pseudo)code is not tested.  For more information please have a look here
Comment: This is valuable information and I'm sure I'm going to use it soon. But for this situation I really wanted to keep everything in one place.


How do I prove that the sum: $1/\ln(n)^p$ diverges for $p>1$

Question: So I need to prove that the infinite sum $\frac{1}{(\ln(n)^p)}$ diverges for all values of $p$. I managed to prove it for $p\leq 1$ via comparison test with $1/n$. but for this I can't seem to find a way to prove it diverges for $p>1$.
Comment: $\sum_{n= 2^k}^{2^{k+1}} \ln^p( n) \approx \sum_{n= 2^k}^{2^{k+1}} \ln^p( 2^k) =2^k k^p \ln^p (2)$
Answer: In THIS ANSWER, I showed using only the limit definition of the exponential function and Bernoulli's Inequality that the logarithm function satisfies the inequalities
$$\frac{x-1}{x}\le \log(x)\le x-1 <x\tag 1$$
for $0<x$.

Using the property $\log(x^a)=a\log(x)$ in $(1)$, we obtain for $a>0$
$$\log(x)<\frac{x^a}{a}\tag2 $$
For $x>n>1$, we have from $(2)$
$$\frac{1}{\log^p(n)}>\frac{a}{n^{ap}}\tag 1$$
For any $p>1$, we can take $a=1/p$ so that $ap=1$.  Hence, the series $\sum_{n=1}\frac{1}{\log^p(n)}$ dominates the series, $\frac1p\sum_{n=2}^\infty\frac{1}{n}$, which diverges.  The comparison test guarantees that the series $\sum_{n=1}\frac{1}{\log^p(n)}$ diverges also.
Comment: One typo, but otherwise great!  [Note:  (2) $\Rightarrow$ $(\log(x))^p < (\frac{x^a}{a})^p =\frac{x^{ap}}{a^p}$  so putting $a=1/p$ gives $(\log(x))^p < \frac{x}{(\frac{1}{p})^p}$.  Rearranging/taking reciprocals gives $(\frac{1}{p})^p(\frac{1}{x})<(\frac{1}{\log(x)})^p$ $\Rightarrow \frac{1}{p^p}\frac{1}{n}<\frac{1}{\log^p(n)}$.]
Answer: Use that for $n$ large enough $\ln^p n < n$ and compare your series with $\sum 1/n$.
Comment: i will be required to explain why that statement  is true, so just to make sure im correct, i can prove that the limit of n/(ln(n)^p) goes to infinity and from that i can derive this statement?
Comment: @dvd280, apply L'Hôpital repeatedly or Cesaro-Stolz.
Answer: You can prove it using the following theorem

Theorem (the integral test): Let $f(x)$ be a continuous function of real numbers that is monotonic decreasing. Then for any $N\in\mathbb N$, $\sum_{n=N}^\infty f(n)$ converges if and only if $\int_N^\infty f(x)dx$ is finite.
Comment: I cant use it to prove stuff yet since we havent proven that theorem yet in class unfortunately.Thanks though!


Exists vs select count

Question: In SQL Server, performance wise, it is better to use IF EXISTS (select * ...) than IF (select count(1)...) > 0...
However, it looks like Oracle does not allow EXISTS inside the IF statement, what would be an alternative to do that because using IF select count(1) into... is very inefficient performance wise?
Example of code:
IF (select count(1) from _TABLE where FIELD IS NULL) > 0 THEN
UPDATE TABLE _TABLE
SET FIELD = VAR
WHERE FIELD IS NULL;
END IF;

Comment: Please show us the full PL/SQL code. It's unclear to me what you are trying to achieve.
Comment: That `if` is totally useless, because the `WHERE` clause does exactly the same thing. You are not optimizing anything here - it's actually the opposite: if there *are* rows where the column is NULL then you are running this test twice (because the `UPDATE` will *always* evaluate that condition)
Comment: Btw: if you think `count(1)` will be faster than `count(*)` you are mistaken as well.
Comment: I mean, it's just an example, sorry if I misled you here, the actualy query is very complex and I have to verify it returns rows before actually doing it. So, all in all,I have to run it twice and that slows it down a lot,.
Comment: I don't believe that you *have* to verify that it returns rows before running it. Are you aware that Oracle has a proper exception handling where you could deal with a "no rows found" situation?
Comment: yes, but what if my procedure has multiple select queries that could result in `no rows found`? How could I attach the exception block to this one query?
Comment: Put each query into a separate block with its own `exception` clause
Comment: Well I for one think it's nice that SQL Server has a performant way of doing work which is completely unnecessary.
Answer: the best way to write your code snippet is
UPDATE TABLE _TABLE
SET FIELD = VAR
WHERE FIELD IS NULL;

i.e. just do the update. it will either process rows or not. if you needed to check if it did process rows then add afterwards
if (sql%rowcount > 0)
then
...

generally in cases where you have logic like
declare
  v_cnt number;
begin
select count(*)
  into v_cnt
  from TABLE
 where ...;

if (v_cnt > 0) then..

its best to use ROWNUM = 1 because you DON'T CARE if there are 40 million rows..just have Oracle stop after finding 1 row.
declare
  v_cnt number;
begin
select count(*)
  into v_cnt
  from TABLE
 where rownum = 1
   and ...;

if (v_cnt > 0) then..

or
select count(*)
  into v_cnt
  from dual
 where exists (select null
                 from TABLE
                where ...);

whichever syntax you prefer.
Answer: As Per:
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:3069487275935
You could try:
  for x in ( select count(*) cnt
               from dual
              where exists ( select NULL from foo where bar ) )
  loop
        if ( x.cnt = 1 )
        then
          found do something
        else
          not found
        end if;
  end loop;

is one way (very fast, only runs the subquery as long as it "needs" to, where exists
stops the subquery after hitting the first row)
That loop always executes at least once and at most once since a count(*) on a table
without a group by clause ALWAYS returns at LEAST one row and at MOST one row (even of
the table itself is empty!)

Exists vs select count


How to check whether bluetooth has connected with other device programatically using Async Task?

Question: I need to check whether any device is connected and communicating to my device via bluetooth in doInBackground method in Async Task. If connected/communicating - display toast message as "Connected". if not display as "No device connected".
I've searched everywhere, but no answers satisfied my requirements.
Answer: I do not know your problem in detail, but my Solution would be the BroadhastReceiver for Bluetooth Adapter.
public class AnyActivity extends AppCompatActivity {

private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
private static boolean isConnected = false;
private static boolean isConnecting = false;
private static boolean isDisdconected = false;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_any);

        IntentFilter BT_ConState_filter  = new
        IntentFilter(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);

        this.registerReceiver(BR_BT_ConState, BT_ConState_filter);
}

BroadcastReceiver BR_BT_ConState =new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action_BR_BT_ConState =intent.getAction();
            int iBR_BT_ConState_state = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE, mBluetoothAdapter.ERROR);

            if (action_BR_BT_ConState.equals(mBluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED))
            {
                switch (iBR_BT_ConState_state) {
                    case BluetoothAdapter.STATE_CONNECTING:
                        Toast.makeText(this, "Connecting" ,Toast.LENGTH_SHORT).show();
                        isConnected = false;
                        isConnecting = true;
                        isDisdconected = false;
                        break;

                    case BluetoothAdapter.STATE_CONNECTED:
                        Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
                        isConnected = true;
                        isConnecting = false;
                        isDisdconected = false;
                        break;

                    case BluetoothAdapter.STATE_DISCONNECTED:
                        Toast.makeText(this, "Disconected", Toast.LENGTH_SHORT).show();
                        isConnected = false;
                        isConnecting = false;
                        isDisdconected = true;
                        break;
                }
            }
        }
    };

public static boolean isConnected(){
return isConnected;
}

public static boolean isDisConnected(){
return isDisConnected;
}

public static boolean isConnecting(){
return isDisConnected;
}

@Override
    protected void onDestroy(){
        super.onDestroy();
        context.unregisterReceiver(BR_BT_ConState);
    }
}

If you tell me what you want to do exactly, for example:
Run Some Code depending on state,
Execute some TextView Changes,
Or something like a callback Method,
or what else, I can try to help you even more.
What I did now is creating some static functions you should be able to call in your AsynkTask, just call AnyActivity.isConnected() and you get the current state of the BluetoothAdapter returned.
Comment: it is working as expected. But i need to do some changes as per my requirement.Thanks Dude.
Comment: No problem, you should have a look at @frestonic's solution, seems nice to me, too, but never tried.
Please Accept Answer if useful :)
Answer: are you talking abou ble gatt? it yes then create a callback
    private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        switch (newState) {
            case BluetoothProfile.STATE_DISCONNECTED:

                break;

            case BluetoothProfile.STATE_CONNECTING:

                break;

            case BluetoothProfile.STATE_CONNECTED:

                break;
        }
    }


Bind Inner Grid in Nested RadGrid from CodeBehind

Question: Hi I'm fooling around with the nesting feature on the radgrid.  How can I reference and bind a rad grid nested within a parent Radgrid in the OnItemDataBound Event.
I have tried
   var doc_grid = (RadGrid) item["doc_grid"].Controls[0];
   var doc_grid = (RadGrid)RadGrid1.FindControl("doc_grid");

Do I have to ref the NestView ...
Here is the general gist of the code ...
   <telerik:RadGrid ID="outerGrid" DataSourceID="SQL_Outer" runat="server" AutoGenerateColumns="True" OnItemDataBound="RowBound" DataKeyNames="MatNo"
        ShowGroupPanel="True">
        <MasterTableView DataSourceID="SQL_Outer" AllowMultiColumnSorting="True" DataKeyNames="MatNo" GroupLoadMode="Server">
            <Columns>
               <%--Stuff--%>
            </Columns>
            <NestedViewSettings DataSourceID="SqlDataSource2">
                <ParentTableRelation>
                    <telerik:GridRelationFields DetailKeyField="sysid" MasterKeyField="MatNo" />
                </ParentTableRelation>
            </NestedViewSettings>
            <NestedViewTemplate>

            <asp:Panel ID="NestedViewPanel" runat="server" CssClass="viewWrap">

                <telerik:RadGrid ID="doc_grid" runat="server">
                    <MasterTableView AutoGenerateColumns="False" DataKeyNames="sysid">
                      <%--Stuff--%>
                    </MasterTableView>
                </telerik:RadGrid>

            </asp:Panel>

            </NestedViewTemplate>
        </MasterTableView>
    </telerik:RadGrid>

CodeBehind:
protected void RowBound(object sender, GridItemEventArgs e)
{
    if (e.Item is GridDataItem)
    {
        var item = (GridDataItem)e.Item;
        var mat_no = item.GetDataKeyValue("MatNo");

        //!!!!I Can't figure out how to Reference the Inner RadGrid!!!!
        //var doc_grid = (RadGrid) item["doc_grid"].Controls[0];
        var doc_grid = (RadGrid)RadGrid1.FindControl("doc_grid");

        using (var con = new SqlConnection())
        {
            con.ConnectionString = ConfigurationManager.ConnectionStrings["TimeMatters11ConnectionString"].ConnectionString;
            var cmd = new SqlCommand("SELECT sysid, ccode, [desc], [View] = 'View Doc' " +
                                     "FROM lntmu11.document " +
                                     "WHERE mat_no = @matno", con);
            cmd.Parameters.AddWithValue("@matno", mat_no);
            con.Open();
            var reader = cmd.ExecuteReader();
            doc_grid.DataSource = reader;
            doc_grid.DataBind();
            con.Close();
        }
    }

Thanks in Advance ...
Answer: You need to cast as GridNestedViewItem instead of GridDataItem.
protected void RowBound(object sender, GridItemEventArgs e)
{
   if (e.Item is GridNestedViewItem)
   {
      GridNestedViewItem item = e.Item as GridNestedViewItem;
   }
}


minimizing MSE of estimator $\theta(a,b) = \frac{1}{n} \sum^n_{i=1} Y_ia_i + b$

Question: We have $Y_i = \theta + \epsilon$, $E\epsilon = 0$ and $Var(\epsilon) = 0.5$.
We have a proposed estimator for $\epsilon$ :
$\hat{\theta}(a,b) = \frac{1}{n} \sum^n_{i=1} Y_ia_i + b$. And $a = (a_i)^n_{i=1}$ must satisfy the constraint $\frac{1}{n}\sum^n_{i=1} a_i = 1$
We want to find $a = (a_i)^n_{i=1}$ and $b$ minimize the MSE of our estimator. Here is some of my work:
MSE = $E[(\hat{\theta} - \theta)^2]$
My guess is we want to take the derivative with respect to $b$ and $a$ and find the optimal values that way. As in, minimize what is inside of the expectation.
I have
$$ (\hat{\theta} - \theta)^2 = (\frac{1}{n} \sum Y_ia_i + b - \theta )^2\\
= (\frac{1}{n}\sum Y_i a_i + \frac{1}{n}\sum b - \theta)^2 \\
 = (\frac{1}{n}Y_i a_i + b - \theta)^2$$
We take the derivative with respect to b.
$$2(\frac{1}{n}\sum Y_i a_i + b - \theta) $$
Setting that to zero we have $$b^* = \frac{n\theta}{2*\sum Y_ia_i}$$
Before I move on to follow the same steps with $a$ I am wondering whether this is the correct approach since I am having a hard time interpreting having an optimal value for variables in our estimator having $\theta$ in them.
Comment: Among other issues, you're forgetting the "mean" ("M") bit in "MSE."
Comment: Ah, I see that's why you take the expectation first in your answer.
Answer: You have mistakes in your simplification and you need to take the expectation $E[(\hat\theta-\theta)^2]$ before differentiating.
\begin{align*}
(\hat\theta-\theta)^2&=\Big(\frac{1}{n}\sum_ia_iY_i+b-\theta\Big)^2\\
&=\Big(\frac{1}{n}\sum_ia_i(Y_i-\theta)+b\Big)^2\\
&=\frac{1}{n^2}\Big[\sum_ia_i(Y_i-\theta)\Big]^2+b^2+\frac{2}{n}\Big[\sum_ia_i(Y_i-\theta)\Big]b.
\end{align*}
Note
\begin{align*}
E\Big[\sum_ia_i(Y_i-\theta)\Big]&=\sum_ia_iE(Y_i-\theta)=0,\\
E\Big[\Big(\sum_ia_i(Y_i-\theta)\Big)^2\Big]&=\operatorname{Var}\Big[\sum_ia_i(Y_i-\theta)\Big]=\sum_ia_i^2\operatorname{Var}(Y_i-\theta)=\frac{1}{2}\sum_ia_i^2.
\end{align*}
Then:
$$
E[(\hat\theta-\theta)^2]=\frac{1}{2n^2}\sum_ia_i^2+b^2.
$$
It remains to use Cauchy-Schwarz
$$
n\sum_ia_i^2=\sum_i1^2\sum_ia_i^2\geq\Big(\sum_i1\cdot a_i\Big)^2=n^2\implies\sum_ia_i^2\geq n
$$
and the observation $b^2\geq 0$ to find the optimal $a_i=1$ $\forall i$ and $b=0$.
Comment: I am having trouble understanding how we go from the Cauchy-Schwartz  part. Do we now use our simplification to find the optimal $a$ and $b$?
Comment: never mind , Thank you!


how to differentiate 2 grid's while exporting to pdf

Question: i have 2 grid's which i need to export to pdf...
now i can export.. but
i can differentiate 2 grid's...meaning the 2 grids are adding in a single table..
i need space betweeen 2 grids so that i can differentiate...
how can i keep empty space between 2 grids....here is my code
gridview1: gvrpaList
gridview1: rptisslst
   protected void btnExportPDF_Click(object sender, EventArgs e)

  {

  Response.ContentType = "application/pdf";

Response.AddHeader("content-disposition",

"attachment;filename=GridViewExport.pdf");

Response.Cache.SetCacheability(HttpCacheability.NoCache);

StringWriter sw = new StringWriter();

HtmlTextWriter hw = new HtmlTextWriter(sw);

gvrpaList.AllowPaging = false;

//gvrpaList.DataBind();

gvrpaList.RenderControl(hw);

gvrpaList.HeaderRow.Style.Add("width", "15%");

gvrpaList.HeaderRow.Style.Add("font-size", "15px");

gvrpaList.Style.Add("text-decoration", "none");

gvrpaList.Style.Add("font-family", "Arial, Helvetica, sans-serif;");

gvrpaList.Style.Add("font-size", "8px");

rptisslst.AllowPaging = false;

rptisslst.RenderControl(hw);

rptisslst.HeaderRow.Style.Add("width", "15%");

rptisslst.HeaderRow.Style.Add("font-size", "15px");

rptisslst.Style.Add("text-decoration", "none");

rptisslst.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
rptisslst.Style.Add("font-size", "8px");

StringReader sr = new StringReader(sw.ToString());

Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);

HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

 byte[] byteArr = Encoding.ASCII.GetBytes(sw.ToString());
 MemoryStream stream = new MemoryStream(byteArr);

 StreamReader stre = new StreamReader(stream);

  pdfDoc.Open();

  htmlparser.Parse(stre);

  pdfDoc.Close();

  Response.Write(pdfDoc);

  Response.End();
   }
   public override void VerifyRenderingInServerForm(Control control)
  {
  // verifies the control is rendered here
   }

Answer: You could try to add a line break:
gvrpaList.RenderControl(hw);
hw.Write("
");
rptisslst.RenderControl(hw);


What is Vincent Persichetti saying about finding primary chords in the modes?

Question: I'm really confused about what Vincent Persichetti wrote in his book Twentieth Century Harmony, where he says speaking of primary chords in modes, "The Primary chords are the tonic, plus two dominant equivalents. These double dominants are those major or minor triads that include the characteristic scale step which produces the principal flavor of the mode."
Persichetti then goes on to show how in the mode D Lydian, (Characteristic flavor: Raised 4th step) the Primary chords are I, II and VII.
In another example, he shows the Primary chords in D Mixolydian, (Characteristic flavor: Lowered 7th step) the Primary chords are I, V and VII.
I'm confused by the wording you see in the quote, and can't seem to wrap my mind around the procedure for picking out the Primary chords in Modes.
Thank you all.
Answer: According to Persichetti, the primary chords of a mode are the tonic, and two other major or minor triads that include the mode's characteristic scale step. The focus here is on the modes that are different from the standard major and (natural) minor scale, and locrian is also excluded because of its diminished tonic triad. As you probably know, the characteristic scale steps of the remaining four modes (dorian, phrygian, lydian, mixolydian) are the notes that distinguish the mode from the common major or minor scales. For dorian it is the natural sixth, for phrygian the minor second, for lydian the raised fourth, and for mixolydian the minor seventh.
Now there are always three triads in the scale including the characteristic scale step, because that note can appear as the root, the third, or the fifth of a chord. However, one of those triads is always a diminished triad, so there remain only two major or minor triads including the characteristic scale step. For dorian, the (major or minor) triads including the natural sixth are ii and IV. For phrygian you get II and vii, for lydian II and vii, and for mixolydian v and VII.


Generating a population of individuals with known Gaussian and uniform random properties

Question: Suppose that I have a number of variables.  Each is known to be Gaussian or uniformly random with known parameters and occur with a known probability.  I also have a table of correlations (or covariances if that's easier) for each one.  It would be great if these parameters could come from any kind of distribution, but if not, uniform and Gaussian are fine for my interests.
So, a typical problem case would be A is Gaussian with mean a1 and variance a2; B is uniform with maximum b1 and minimum b2.  C is Gaussian with mean c1 and variance c2.   Then I have a table of correlations A with B, A with C and B with C.
How would I write an algorithm to generate a sample of random vectors (A,B,C) which satisfy the above properties.  Again, it would be really great if the variables could come from any kind of distribution, but I would settle for at least Gaussian only, uniform only or a mixture of Gaussian and uniform variables.
It would be nice to have an approach that would scale up easily.
I would like to implement this myself, rather than use some predefined package. So, I'm interested in algorithmic details.
Comment: Do you mean that $(A,B,C)$ occurs then you pick $A$ with probability $p_1$, $B$ with probability $p_2$, and $C$ with probability $p_3$?
Comment: I removed the comments about probability. I realize now that it made no sense.
Comment: Sorry, in my opinion, it makes less sense now...
Comment: @Xi'an. Imagine a population of people with height, weight, eye color. Now, lets say height is Gaussian, weight is Gaussian and eye color is Binomial.  There are measured correlations between all these variables. I am wondering if there is a procedure for generating a person from this population randomly.
Comment: If the corresponding multivariate distribution is fully defined, then the answer is **yes**. If instead you only know the marginals and the correlation between the components, the answer is **no**, because there is not a single distribution with those characteristics.
Comment: What would it take to have it be fully-defined? I am thinking about doing something like this for a simulation.  So, I would be willing to settle for producing individuals from ANY population that satisfies these constraints.
Comment: Apart from the Gaussian multivariate distribution, it is rare to find distributions where you can specify the correlations as some of the parameters of the distribution... Copulas can help towards this goal but the parameters will have to be derived numerically.
Answer: If I understand correctly the setup, a pseudo-algorithm to generate from this distribution would be

generate $(A,B,C,...)$ from their joint distribution
take as your random variable a component of this vector selected with probability $p_1,p_2,\ldots$

For instance, if the joint of $(A,B,C)$ is normal $\cal{N}(\mu,\Sigma)$,

generate $(A,B,C)\sim\cal{N}(\mu,\Sigma)$
take $X=\begin{cases}A &\text{with probability }p_1\\B &\text{with
    probability }p_2\\C &\text{with probability }p_3\end{cases}$

with a corresponding R code for n simulations (assuming mu, Sigma and prob properly defined):
<code>ABC=mvrnorm(n,mu=mu,Sigma=Sigma)
X=ABC[cbind(1:n,sample(1:3,n,prob=prob,rep=TRUE))]
</code>