Compare mean heart rate after drug administration with multiple time points against baseline

Question: I want to compare mean heart rate change from baseline (T0) within the group. There are 10 continuous time points (T0,T1,....T10.) like t1 vs t0, t2 vs t0, t3 vs t0.. what test should i apply ? paired t test is appropriate? The studied drug was given at t2.
Comment: Do you have a control group who received a non-drug control? If so then you should think about comparing the drug with the non-drug control rather than just comparing times. (If you don't have a control group then your study may be incomplete in a way that statistics cannot help with.)
Comment: I have 2 drug groups,,  I want to compare baseline heart rate with other time point within the same group and need a p value!      Should I use paired t test or repeated anovo with bonferroni posthoc  to analyse?
Comment: What scientific inference do you wish to make? If you want to know whether both drugs had an effect then you need a control group to compare them with. If you only want to know if one of them had a larger absolute effect than the other than you can compare the two without a control group. The best way to evaluate drugs is by way of dose-response curves. Any single dose study has the possibility that the absence of effect is inadequate dose and any difference between the drugs is simply a difference in their potencies. Statistics cannot make up for bad design.
Comment: Unless your desired inference concerns the time at which the response occurred (or peaked) then do not compare all the time points. Instead, define a time point to be the response time (either the peak of the response variable or a reasonable set time point) and use that as the datum for each patient.
Comment: i compared both groups with unpaired tests..  i am planning to compare intra group variations from baseline... i have got the answer to for repeated measures anova with post hoc
Answer: I will assume that you do not have a control group (otherwise, you could proceed as similarly but add a group variable to the fit). This makes this kind of tricky, but here's an idea:
Denote with $h_{p,t}$ the heart rate of patient $p \in \mathcal{P}$ at time $t \in \{1, ..., 10\}$, and with $a_{t}$ an indicator variable that takes value one after treatment (i.e. for $t \ge 2$) and zero otherwise. Let the patient mean $m_p \sim \mathcal{N}(0, \sigma^2)$, follow a normal distribution with mean zero and unknown standard deviation $\sigma$. Finally let $\beta$ and $\mu$ be two fitted parameters.
Now fit the following mixed model:
$$
h_{p, t} = \mu + \beta a_t + m_p
$$
You can now test whether the drug had an effect by testing against the null hypothesis $\beta = 0$.
Intuitively, what this does is it assumes that the heart rate is distributed normally between patients with an unknown mean $\mu$ and standard deviation $\sigma$. Furthermore, after the drug has been administered, the heart rate is modulated by a constant $\beta$. However, it does not discriminate between any time-points after administration. I am not sure how one could a time dependency and also test for a drug effect without control group.
The above model can be implemented using the lme4 package in R, where $m_p$ is a random effect. If you absolutely need p-values, you can use lmerTest.


Configuring BGP using Azure portal

Question: Does Azure web portal support configuration of BGP on VPN gateways? All online documentation seems to contain steps using powershell. But powershell doesn't work with linux machine. Am I correct?
So, does only way to conifgure BGP on VPN gateways on azure is via powershell commands on windows machine?
Answer: You can't configure BGP via the Portal.
You have two other options for Linux / CLI you could run the required PowerShell commands in Azure Automation, you could write the script there and then call that from Linux.
Alternatively you could create a template which will also let you specify BGP, have a look at this one for details - https://github.com/Azure/azure-quickstart-templates/tree/master/101-site-to-site-vpn-create
Comment: Thanks for the response but I ended up creating a VM in azure with windows OS and installed azure powershell there. Though, I have another question, it seems like BgpPeeringAddress address is automatically assigned by azure (which is second last from CIDR block defined for GatewaySubnet). Can we change this to use link local address?

Configuring BGP using Azure portal


How can I use HAproxy with SSL and get X-Forwarded-For headers AND tell PHP that SSL is in use?

Question: I have the following setup:
(internet) ---> [  pfSense Box  ]    /-> [ Apache / PHP server ]
                [running HAproxy] --+--> [ Apache / PHP server ]
                                    +--> [ Apache / PHP server ]
                                     \-> [ Apache / PHP server ]

For HTTP requests this works great, requests are distributed to my Apache servers just fine. For SSL requests, I had HAproxy distributing the requests using TCP load balancing, and it worked however since HAproxy didn't act as a proxy, it didn't add the X-Forwarded-For HTTP header, and the Apache / PHP servers didn't know the client's real IP address.
So, I added stunnel in front of HAproxy, reading that stunnel could add the X-Forwarded-For HTTP header. However, the package which I could install into pfSense does not add this header... also, this apparently kills my ability to use KeepAlive requests, which I would really like to keep. But the biggest issue which killed that idea was that stunnel converted the HTTPS requests into plain HTTP requests, so PHP didn't know that SSL was enabled and tried to redirect to the SSL site.
How can I use HAproxy to load balance across a number of SSL servers, allowing those servers to both know the client's IP address and know that SSL is in use? And if possible, how can I do it on my pfSense server?
Or should I drop all this and just use nginx?
Comment: Re: stunnel and `X-Forwarded-For`, see [here](http://serverfault.com/questions/301221/haproxy-stunnel-keep-alive).
Comment: +1 for excellent ASCII diagramming.  :-)
Comment: @Shane: Thanks. That's exactly where I read that I lose KeepAlive :-)
Comment: @AlanHamlett, your [link](http://wakatime.com/blog/34-how-to-scale-ssl-with-haproxy-and-nginx) is 404.
Comment: @luckydonald thanks, here is an updated link. You can use Proxy Protocol by adding the send-proxy keyword to your haproxy config. I wrote a blog post with examples here: https://wakatime.com/blog/23-how-to-scale-ssl-with-haproxy-and-nginx
Answer: Just for the record, as this thread is often referred to concerning HAProxy + SSL, HAProxy does support native SSL on both sides since 1.5-dev12. So having X-Forwarded-For, HTTP keep-alive as well as a header telling the server that the connection was made over SSL is as simple as the following :
listen front
    bind :80
    bind :443 ssl crt /etc/haproxy/haproxy.pem
    mode http
    option http-server-close
    option forwardfor
    http-request set-header X-Forwarded-Proto https if { ssl_fc }
    server srv1 126.96.36.199:80 check ...
    ...

I'm sure that by the time you came up with something different, but at least new visitors will get the easy solution now :-)
Comment: I don't understand much about haproxy configuration for now, but with the latest version, I had to add an acl : `acl is-ssl dst_port 443` and rewrite a line : `reqadd X-Forwarded-Proto:\ https if is-ssl` Nginx seems to handle this header fairly well
Comment: @greg0ire that's because with latest haproxy there is no is_ssl but ssl_fc instead
Comment: this should be the accepted answer
Comment: Sorry Josh, I don't know enough about pfSense to know if you can update components on it or not, and since you were speaking about installing a package, I believed it was the case. Last time I tried it was around 5 years ago so I don't remember all the details.
Comment: This worked like a charm.  No nginx required.
Comment: Thanks, this is good general info... my question was about HAproxy *running on pfSense* so for now I need to use nginx in front of HAproxy still, as pfSense doesn't support this version of HAProxy (yet)
Answer: You dont need to drop it all, you could just use nginx in front of haproxy for SSL support, keeping all your load balancing config. You dont even need to use nginx for HTTP if you don't want to. Nginx can pass both X-Forwarded-For and a custom header indicating SSL is in use (and client cert information if you want). Nginx config snippet that sends required information:
proxy_set_header SCHEME $scheme;      # http/https
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header CLIENT_CERT $ssl_client_raw_cert;

Answer: For anyone else who finds this question, I followed Ochoto's advice and used nginx. Here's the specific steps I used to make this work on my pfSense router:

Using the pfsense web interface, I installed the pfsense PfJailctl package and the "jail_template" package under System > Packages so I could create a FreeBSD jail under which to compile and install nginx on the pfsense system.
I configured a jail for my nginx server under Services > Jails, giving the new jail the same hostname and IP address of the virtual IP alias which I had HAproxy running on. I bound the jail to the WAN interface. I used the default jail template and enabled unionfs rather than nullfs.
Once the jail had been started, I SSHed in to the pfsense box and ran jls to find the jail's number. I then ran jexec 1 sh to get a shell inside the jail. From there I set up BSD ports and installed nginx using:
portsnap extract
portsnap fetch update
cd /usr/ports/www/nginx
make install clean

I then configured nginx to listen on port 443, and pass all requests to HAproxy on port 80, including the real IP and the SSL status inside HTTP headers. My usr/local/etc/nginx/nginx.conf looks like:
worker_processes  1;

events {
    worker_connections  2048;
}

http {
    upstream haproxy {
        server 126.96.36.199:80;
    }

    server {
        listen       443;
        server_name  my.host.name default_server;
        ssl                  on;
        ssl_certificate      my.crt;
        ssl_certificate_key  my.key;
        ssl_session_timeout  5m;

        ssl_protocols  SSLv3 TLSv1;
        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers   on;

        location / {
            proxy_pass http://haproxy;

            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

            proxy_set_header X-Forwarded-Proto https;
        }
    }

}

I then modified my PHP application to detect the X-Forwarded-Proto HTTP Header:
function usingSSL()
{
    return (
       (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' )
        || (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])
               && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https' ));
}

So the final setup is:
(internet) ---> [ -> nginx -> haproxy -]--> (pool of apache servers)
                [    (pfSense server)  ]

Comment: You should disable SSLv2 unless you really need it. http://www.gnu.org/software/gnutls/manual/html_node/On-SSL-2-and-older-protocols.html I don't know why Nginx still supports it in its default config.
Comment: Also realise that with 1024 worker connections you will support at most 512 concurrent clients.
Comment: @Ochoto: Thanks for both of those tips! I'm new to HAproxy but even less familiar with nignx...
Answer: My configuration for a 1.5-dev-17 version of haproxy:
global
        log 127.0.0.1   local0
        log 127.0.0.1   local1 notice
        #log loghost    local0 info
        maxconn 4096
        #chroot /usr/share/haproxy
        user haproxy
        group haproxy
        daemon
        #debug
        #quiet

defaults
        log     global
        mode    http
        option  httplog
        option  dontlognull
        option  http-server-close
        retries 3
        option redispatch
        fullconn 1000
        maxconn 1000
        timeout queue 600s
        timeout connect 5s
        timeout client 600s
        timeout server 600s

frontend http-in
        bind *:80
        bind *:443 ssl crt /usr/local/etc/ssl/certs
        reqadd X-Forwarded-Proto:\ https if { ssl_fc }
        default_backend varnish-ha
        option forwardfor
backend varnish-ha
  server hafront1 10.1.69.1:6081  minconn 100 maxqueue 10000

It uses the ssl_fc ACL. Please note that the option  http-server-close part is very important.
Comment: Thanks! I'm running HAProxy v1.4 so I don't think I can do this, but it might help others.
Comment: Yes, and the 1.5 should be out soon.
Answer: HAProxy can't hit an SSL backend without using raw TCP mode, losing X-Forwarded-For, but, you could potentially re-encrypt the traffic with a listening stunnel for the backend transit.  Ugly, though.
I like Ochoto's approach better, with a caveat: nginx is a perfectly capable load balancer; if you're using it, I'd say use it for everything.  Proxy your incoming HTTPS to load balanced HTTPS backends - and that way, there's no need for custom headers for SSL information (unless you do need the client certificate).
Comment: I digress from nginx beeing a capable load balancer, unless you use the non standard module upstream_fair it does a simple round robin (or client ip hash) without taking into account if destination backend is already busy with requests and thus growing queue in that backend when there are other backends free and waiting for a job. HAProxy also nicely monitor backends and displays stats about them.
Comment: If only one of the following would become true
a) Nginx gets decent state tracking and fair load balancing
b) HAProxy gets decent SSL support

One can only hope
Comment: I just deployed a setup using nginx -> haproxy -> nginx -> backend for SSL, this is due to the lack of HTTPS support in haproxy as discussed here, but also because nginx does not support http health check scripts.
Comment: I'm not sure why I'm clinging on to HAproxy. I think it's because pfSense has a package for it, and SOIS uses it. Neither one is a great reason. :-)
Answer: I implemented a solution last year to integrate HAProxy with pfSense in a way that it harnesses all features of HAProxy and maintains a good isolation with pfSense. So that it is a viable option for production environments. SSL is terminated on HAProxy. I installed HAProxy inside a jail in pfSense using ezjail and Ports Collection. That way it is very easy to maintain both components independently. And you may install whatever version you want. I started with 1.5-dev13. And since then it is working perfectly for me. I have documented the whole thing here.
Installing HAProxy on pfSense
BTW Willy, thanks a lot for such an excellent product.


Existence of linear fractional transformation that map a circle to itself and exchanges two other points

Question: Q: Find a mobius transformation T with the following property or show that no such T exists.
There are distinct points $z_1, z_2, z_3, a, b$ in $\mathbb{C} \cup \{\infty\}$ with $T(z_1)=z_2$, $T(z_2)=z_3$, $T(z_3)=z_1$ and $T(a)=b$, $T(b)=a$?
By the theorem, there exists a unique mobius map that maps three distinct points to three distinct points. So there exists a map $T$ such that $T(z_1)=z_2$, $T(z_2)=z_3$, $T(z_3)=z_1$ and actually this $T$ maps a circle(or extended line) to itself.
Comment: The linear fractional transformation has three degrees of freedom, and once you specify the distinct images of three distinct complex arguments, you've completely specified a Moebius map.  From your facts, $T$ will have period $3$. If $a,b$ are distinct we cannot make  $T$ swap them.
Comment: Sorry for being cryptic, I just mean $T^3$ would have to be the identity map, given your facts.  Perhaps you mean you want to find a LFT such that five such distinct points exist, as opposed to starting with five points and finding a LFT?
Comment: Having mapped the first three points, there is no general reason why two other points $a,b$ should be swapped.
Comment: Yes, you are right. But I think what the question ask is that could there exists five distinct points that such a mobius exists. Or could there never be such a mobius map for any distinct five points.
Comment: What is the period of a linear fractional transformation? I can not find any reference online.
Comment: Yes, I think the question is to find a LFT such that five such distinct points exist. You are right, $T^3$ must be the identity map. Thank you very much!
Answer: Let $T$ be a linear fractional transformation such that for distinct $z_1,z_2,z_3$ in the "extended complex plane" $\mathbb{C} \cup \{\infty\}$ (also known as the Riemann sphere):
$$ T(z_1) = z_2\;, T(z_2) = z_3\;, T(z_3) = z_1 $$
Since $T^3(z_i) = z_i$ for $i=1,2,3$, it follows that $T^3$ is the identity since agreement of two linear fractional transformations on three distinct points implies they are the same.
Assume further that $a,b$ are such that $T(a) = b$ and $T(b)=a$.  Then:
$$ a = T^3(a) = T^2(b) = T(a) = b $$
so $a,b$ cannot be distinct.


Deletar arquivo Laravel

Question: Ao tentar deletar uma imagem de um diretorio especifico recebo a mensagem de que o arquivo não existe, porém consultando o caminho que o código esta executando eu vejo que o arquivo existe sim, e a string do caminho esta 100% correta.
Cheguei a considerar permissão mas o próprio código é quem cria a pasta, salva o arquivo dentro e lê, só que ele não apaga...
Storage::delete(public_path('uploads/'.$asset->contents->belongs_to.'/'.$asset->name));

File not found at path: var/www/xpto-digitaldev/public/uploads/2/217dade2ab7db91d12f1bca7b0cd4c82.png

Salvando o arquivo vindo do upload;
if ($request->hasFile('image')) {
   $extension = $image->getClientOriginalExtension();
   $newFileName = md5(rand(0,9999)).'.'.$extension;
   $image->move(public_path('uploads/'.$clientDirectory), $newFileName);
}

Comment: Não falta fechar os parentesis em `Storage::delete(public_path('uploads/'.$asset->contents->belongs_to.'/'.$asset->name);`? E se tentar `unlink(public_path('uploads/'.$asset->contents->belongs_to.'/'.$asset->name));`
Comment: @Miguel não, a função `public_path()` só espera 1 parametro, se eu tivesse esquecido de fechar o parênteses eu iria receber um erro de syntax.
Comment: Sim mas não parece que tenha fechado os do `delete(...`
Comment: Já arrumei @Miguel
Comment: Se fizer com unlink ? como lhe disse em cima
Comment: com unlink funcionou @Miguel, post sua resposta para que eu possa aprovar, vou estudar este caso tambem para ver porque o `delete` do Laravel que usa unlink não funcionou.
Comment: Talvez acrescente alguma coisa (indesejada neste caso) ao path do ficheiro a apagar. Eu custumo fazer sempre com unlink, ok vou postar a resposta. Obgado
Answer: Com Storage::delete(...), nunca tentei, uso sempre a função nativa de php unlink, experimente o seguinte:
unlink(public_path('uploads/'.$asset->contents->belongs_to.'/'.$asset->name));

Answer: Dá para usar o File.
File::delete('img/imagem.png');

Não se esqueça do:
use File;

File pode ser o mesmo que Storage.
Answer: Eu to usando o Storage assim e ta dando boa.
Storage::delete(["imagens/pasta/banners/arquivo.ext}"]);
colocar um array como parâmetro para os arquivos que quer excluir
Answer: Se estiver usando a estrutura do laravel pode usar da seguinte forma:
Storage::disk('public')->delete('exports/pasta_com_arquivo/'.nome_arquivo);
OBS: Lembre-se de importar o Storage
use Illuminate\Support\Facades\Storage;
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

Deletar arquivo Laravel


Changing clef position

Question: What's the purpose for changing the position of the clef on the staff, for example the alto clef could be on the first, third and fourth line while the notes on the staff remain unchanged?
Comment: Just to be accurate about the terminology, if a C clef is on the first or fourth lines, it's not an "alto" clef. It's a "soprano" or "tenor" clef. It's only an "alto" clef when it is on the third line. See https://en.wikipedia.org/wiki/Clef#/media/File:All_clefs.svg
Comment: https://www.earmaster.com/music-theory-online/ch01/chapter-1-1.html#clef
Answer: When you change the position of the clef you are changing where the notes are.
On a c clef the arrow points to middle C.  Even though ti is more rare, when you move a bass clef (F clef) the line or space between the two dots becomes F. Same thing for a Treble clef (g clef).
Take this image as an example.  In the alto clef the center line is middle C.  In the Tenor clef middle c is moved to the second line from the top.

Take the French violin clef below.  The bottom line is G, instead of the second line which is the typical treble clef (G clef) position.  With the Bass clef (F clef) the note F is shown by passing between the two dots.
Comment: Nice use of graphics.!

Changing clef position


Redirect to laravel controller action - action not defined

Question: I am trying to redirect the page from a controller to an action in another controller in Laravel 5.3. The error returned is:
InvalidArgumentException in UrlGenerator.php line 605:
Action App\Http\Controllers\StartChoosingController@index not defined.

My codes are as follows:
HomeController.php:

StartChoosingController.php:

As I looked over the internet to find an answer I could discover that my problem might be because of not having used the proper namespacing:
https://stackoverflow.com/questions/29822302/laravel-action-not-defined
Would you please tell me how and what to add to the namespace of use part of my code to fix the issue? Thank you very much in advance.
Comment: An advice that is related to how you debug your data : Laravel propose an advanced function that prettify the print_r which is `dd($var)`;
Answer: If you're using Route::resource() for controller routes, try to change index() method to showAll() and add parameter:
public function showAll($userTableData)

And use it:
redirect()->action('StartChoosingController@showAll', ['userTableData' => $user_table_data]);

Also, you'll need to define new route:
Route::get('show-all/{userTableData}', 'StartChoosingController@showAll')

If userTableData is not a string, but an object, you should pass data with post method and hidden inputs.
Comment: Thank you sir. You are awesome.
Comment: Thank you all, but this time there is no value passed to 'StartChoosingController'. After the redirection, the address bar shows `http://localhost/StartChoosingController?` and the error is the demonstrated page is `Missing argument 1 for App\Http\Controllers\StartChoosingController::index()`
Comment: Still the same problem. Is there any problem with my route:     `Route::get('/StartChoosingController', 'StartChoosingController@index');`
Comment: Yes, it should be `Route::get('StartChoosingController/{userTableData}', 'StartChoosingController@index');` It will work if your data is a string.
Answer: For my fellow Laravel 8 users, if you're experiencing the same issue try return redirect()->action([TargetController::class, 'controller_method']);
Answer: If you are using:
redirect()->action([App\Http\Controllers\StartChoosingController::class, 'index']);

please make sure that the above App\Http\Controllers\StartChoosingController::class is 'assigned' to an actual URL so that Laravel knows where actually do redirect.
Here is the full working example:
web.php
Route::get('some', function () {
    return redirect()->action([App\Http\Controllers\StartChoosingController::class, 'index']);
});

Route::get('some/index', [App\Http\Controllers\StartChoosingController::class, 'index']);

app/Http/Controllers/StartChoosingController.php
<?php

namespace App\Http\Controllers;

class StartChoosingController extends Controller
{
    public function index()
    {
        return 'hi';
    }
}


Cumulative distribution function of continuous random variables

Question: Marginal density functions: $f_{V}(v)=f_{W}(w)=\frac{1}{60}$
Joint density function: $f_{V,W}(v,w)=\frac{1}{3600}$, for $0\leq x\leq60$ and $0\leq y\leq60$
I need to find the cumulative density function of $T = W - V$
I'm thinking it's something along the lines of this:
$F_{t}(t)=\left\{\begin{matrix}
0 & w-v<0\\
\frac{t}{60} & 0 \leq w-v \leq 60\\
1 & w-v>60
\end{matrix}\right.$
Any help appreciated.
Thanks!
Comment: @DilipSarwate that answer is way above my head. What is a Jacobian?
Comment: Except for the random variables being $U(0,60)$ instead of $U(0.1)$,this question is a duplicate of [Problem with density of $X-Y$](https://math.stackexchange.com/q/203477/15941) which has several answers. Don't just read the answer by Aang which is overkill. Both Did and I gave much more straightforward answers to the question.
Answer: There are two ways of getting the density function…
1.) by convolution formuar
$V,W$ are independent RV (why?) so are $W$ and $-V$ and so the density of $T = W + (-V)$ is the convolution of the densities of $W$ and $-V$ which are known…
2.) $$f_T(t) = F'_T(t) = \int_{W-V \le t} f_{(V,W)}(v,w)\; dv dw$$ what can be calculated easily…
Comment: So are the results in my original post wrong? I used the convolution formula and got the same result and $\frac{1}{60}$ for the density function


selecting 4 letters from word BANANA (i am confused between 15 or 30)

Question: in how many ways 4 letters be selected to form words from the letters BANANA?
Comment: Assuming order doesn't matter, you can organize your thoughts by listing the outcomes in dictionary order: `AAAB`, `AAAN`, `AABN`, `AANN`, `ABNN`, there are only the five outcomes.  If order does matter, for each of these listed prior you can count the number of arrangements of them, giving $4+4+12+6+12=38$
Comment: Are you looking for `Permutations[Characters["banana"], {4}]`? There are 38 such permutations.
Comment: Did you try to use `DictionaryLookup`? Although it seems the dictionary does not know about naan, for example
Comment: This is unclear what sort of objects you are explicitly trying to count.  Do you treat $BANA$ as one of the objects you are counting?  Do you treat this the same or different than $NAAB$?  They both have the same collection of letters, just in a different order.
Comment: I adapted JMoravitz's suggestion here to give a worked example for the more general case of [6-letter combinations from MISSISSIPPI](https://math.stackexchange.com/a/4067365/206402), which for your 4-from-BANANA case would take repetition options of (`xxxy`,`xxyy`,`xxyz`), filled in $(2,1,2)$ ways and permuted in $(4,6,12)$ ways for the same answer.
Comment: @JMoravitz yeah you are right here
correct answer is 5
here order doesn't matter
thank you :)
Answer: Assuming order doesn't matter, you can organize your thoughts by listing the outcomes in dictionary order: AAAB, AAAN, AABN, AANN, ABNN, there are only the five outcomes. If order does matter, for each of these listed prior you can count the number of arrangements of them, giving 4+4+12+6+12=38
-@JMmoravitz


Publish to twitter using javascript

Question: Is there any way to publish to twitter using javascript??
Answer: Because of the Same Origin Policy you need to post to your server and dispatch a request to twitter from there. Using this approach you can connect to twitter via JS.
Answer: Did you mean this way?
http://www.saschakimmel.com/2009/05/how-to-create-a-dynamic-tweet-this-button-with-javascript/
Answer: With the help of Php and jquery with the help of this tutorial I think you can make it possible
Tutorial
Demo
Answer: You can use the Tweet Box in Twitter Anywhere to tweet via Javascript. The user has to  sign in before tweeting.

Publish to twitter using javascript


C++ doesn't save the changes by other method

Question: I'm trying to implement a linked list class in C++ and I got problem. I have the += operator who adds new node.
the linked list class interface:
template <typename Type>

class LinkedList {
public:
    LinkedList<Type>* head;
//  linked list stracture
    Type data;
    LinkedList<Type>* next;
//  others ....
    size_t length;
public:
    LinkedList();
    ~LinkedList();
    void initializeHead(LinkedList<Type>* headPtr);
    size_t size() const;
    LinkedList& operator+=(const Type& add);
    void operator-=(const Type& remove);
    LinkedList<Type>& operator[] (const size_t index) const;
    bool operator== (const LinkedList<Type> &versus) const;
    friend ostream& operator<< (ostream& out,LinkedList& obj);
};

and here i have the += overload implement:
template <typename Type> LinkedList<Type>& LinkedList<Type>::operator +=(const Type& add) {
    // head ptr - :)
    LinkedList<Type>* p = head->next;
    // go to the end
    while(p) p = p->next;
    // now on end - create new..!!!
    try {
        p = new LinkedList<Type>;
    } catch (bad_alloc& e) {
        cout << "There\'s an allocation error....";
    } catch (...) {
        cout << "An unknown error.." << endl;
    }// fill and done
    p->data = add;
    p->next = NULL;
    // increment length .........
    ++head->length;
    // done ............
    return *p;
}

Additionally , I have "array" access overload method:
template <typename Type> LinkedList<Type>& LinkedList<Type>::operator [](const size_t index) const {
    if(index < 0 || index >= length) // invaild argument
        throw  exception();
    // continue
    LinkedList<Type>* p = head;
    for(size_t i = 0; i < index; ++i) p = p->next; // we are at what we want
    return *p;
}

All works correctly - I checked on the dibugger,
the problem is - += doesn't save the new node in "head->next", for some reason, after finish += method, head->next equal to null.
Do someone know why the new allocation don't link to head->next?
Thanks a lot!!
Comment: If you try to implement as stack it will be much simpler.
Comment: Linked lists are not any better than vectors. They are actually slower, and they do not support random access. At least implement such LL, that has constant time insertion, not O(n).
Answer: after  while(p) p = p->next; p is NULL
and next you do p = new LinkedList<Type>; but you don't link the p into the head.
Comment: Thanks, its better, it saves it new node - but It's seems like theres no NULL at the end of the list.. do you know why?
Comment: p->data = data; p->next = NULL; I think last node of the list should point to this new node to get the your expected results(NULL at end).
Answer: Instead of:
// go to the end
while(p) p = p->next;

You need:
head->next = p;

Answer: As the other answers say, you go beyond the list when you try to add. Try something like this:
template <typename Type> LinkedList<Type>& LinkedList<Type>::operator +=(const Type& add)
{
    LinkedList<Type> *last;

    // Find the last node in the list
    for (last = head; last != 0 && last->next != 0; last = last->next)
    {
    }

    // `last` now points to the last node in the list, or is zero
    // If zero (i.e. NULL) then list is empty

    if (last == 0)
    {
        head = new LinkedList<Type>;
        head->next = 0;
        head->data = add;
        head->length = 0;
    }
    else
    {
        last->next = new LinkedList<Type>;
        last->next->next = 0;
        last->next->data = add;
    }

    // We can safely use `head` as we are sure it won't be zero
    head->length++;

    // Return the added node
    return (last != 0 ? *last->next : *head);
}

Comment: Mm.. Ok, I try to fix by myself the `delete` problem. Thank you all very much!
Comment: @nimrod Be sure that the constructor zeroes the `head` member variable. Preferably the other variables as well, then you don't have to zero them out in the function I posted.
Answer: You can also use temporary variable to store last node and then the last node will point to new node.
This is sample code. You need to take care of some situations like adding first node etc.
LinkedList<Type>* temp = NULL;
while(p)
{
  temp = p;
  p = p->next;
}

try
{
  p = new LinkedList<Type>;
  temp->next = p;
}


Como posso publicar todos o branchs do git de uma só vez para meu repositório remoto no github?

Question: Tenho vários branchs que criei no meu git (aula1, aula2, aula3) que são variações do mesmo arquivo index.html, mas quando vou enviar para o github consigo enviar apenas o master
Existe alguma forma de enviar todos os branchs de uma só vez?
Answer: O ideal é entrar em cada branch para saber o que está sendo enviado, mas o jeito mais simples é:
git push --all

--all
  Faz push de todas as branchs (i.e. refs sobre refs/heads/); não pode ser usada com outro <refspec>


Javascript Randomly Positioned Div's without overlapping them

Question: I've been working on a random concept idea of having 6 clouds appear on a page with random comments pulled from a database. That part is easy, however I'm finding it extremely difficult to make sure the 6 clouds don't overlap each other. I've looked into Collision Detection a lot and found that there's no real suitable method of checking for a DIV within a range at X or Y before placing the new "randomly positioned" div on the page. I have my code below which I know is extremely messy right now. I currently have it checking the last DIV with reasonable success but if DIV 1 and DIV 3 for example, have similar X Y positions then It's a problem. Sorry If I'm making no sense.. here's my code and a jsFiddle
$(document).ready(function () {
var counter = 0;
//var colide = {};
var px = 0;
var py = 0;

var clouds = new Array("cloud1", "cloud2", "cloud3", "cloud4", "cloud5", "cloud6");
var cloudtext = new Array("This is text for cloud 1 :D", "This is text for cloud 2 :D", "This is text for cloud 3 :D", "This is text for cloud 4 :D", "This is text for cloud 5 :D", "This is text for cloud 6 :D");

function makeDiv() {
    if (counter < 6) {
        counter++;

        //var divsize = ((Math.random() * 100) + 50).toFixed();
        //var color = '#' + Math.round(0xffffff * Math.random()).toString(16);
        $newdiv = $('
' + cloudtext[counter - 1] + '
').css({

            'width': '354px',
                'height': '202px'

            //'width': divsize + 'px',
            //'height': divsize + 'px',
            //'background-color': color,
        });

        var posx = (Math.random() * ($(document).width() - 354)).toFixed();
        var posy = (Math.random() * ($(document).height() - 202)).toFixed();

        while (posy < 180) {
            posy = (Math.random() * ($(document).height() - 202)).toFixed();
        }

        if ((px > posx + 354) || (px < posx - 354)) {
            if ((py > posy + 202) || (py < posy - 202)) {

                //alert(px + ' - ' + posx + ' px(temp) - posx(newdiv) - good to go!');
                py = posy;
                px = posx;
                $newdiv.css({
                    'position': 'absolute',
                        'left': posx + 'px',
                        'top': posy + 'px',
                        'display': 'none',
                        'background-image': 'url(http://www.demixgaming.co.uk/cloud/images/Cloud.png)',
                        'text-align': 'center',
                        'line-height': '202px',
                        'color': '#000'
                }).appendTo('body').fadeIn(150).delay(300, function () {
                    makeDiv();
                });
            } else {
                counter--;
                px = posx;
                py = posy;
                makeDiv();
            }
        } else {
            counter--;
            px = posx;
            py = posy;
            makeDiv();
        };

    }
}
makeDiv();

});
JS Fiddle - Link to JSFiddle
Answer: The algorithm would look something like this; I might have made a mistake though

Get the document's height and width y = docH, x = docW
Subtract the
's height and width, y = y - divH, x = x - divH
Choose random co-ordinates curX, curY between 0..x, 0..y
newX = curX, newY = curY
For each previous

Call it's info prevX, prevY, prevW, prevH
If prevX < curX then newX = newX + prevW
If prevY < curY then newY = newY + prevH

Append
 at newX, newY
Save
 info curX, curY, divW, divH
If there is another
, go to step 2.
Comment: True, but you still only need to move the div if it overlaps in both X and Y - no need to move it if it's just aligned above/below or left/right of an existing div.
Comment: Substeps under 5 should be more like `'if (curX > prevX - divW && curX < prevX + divW && curY > prevY - divH && curY < prevY + divH) { pick new position and start checks over }'`
Comment: @ejegg The more items you're adding, the worse an idea it is to "pick new" with random, hence why I tried to make it translate.
Comment: Thanks a lot guys. I'm still pretty new with Javascript so It's taking me a while to get my head around it. I will re-work my code following the rules of that algorithm and see what I can come up with


How to get ipa file from build folder in iphone sdk 4.3

Question: I need to share distribution build to my client. When I used Xcode 4.0 it was very easy to find it. But now I am not able to see where the build folder places in the application folder. Now I am using Xcode 4.3. And it is little confusing for me. Can you guys please tell me the steps to find it out.
Thank you,
Chandra.
Comment: Have you upgraded to Xcode 4 from Xcode 3? Xcode 4 has a radically different system of how to do distribution and submission.
Answer: Connect your device
and
select XCode-->product-->archive then ipa file is generated in organizer then select your file and click on share and save,your ipa file is saved.
Answer: You should check your build settings in the xCode preferences.
Answer: In Xcode 3, you build the binary with Ad Hoc code signing settings and navigate to ~ProjectPath/build/AdHoc.ProjectName.
In Xcode 4, you have to "Archive" your binary. Then, open the organizer and select your app from the Archives menu. Once you've done that, choose the build of the app that ou want to share and click the "Share" button. Xcode 4 will prompt you to choose a codesigning certificate. This must match the one in your scheme. Once that is done, Xcode will ask you where to put it. Choose a location and then you will have answered your own question: The build is wherever you left it.


Avoiding Russell's paradox with ZF axioms

Question: I recently learned about the axioms of Zermelo–Fraenkel and I am trying to understand how those axioms avoid paradoxes such Russell's paradox. Recall that the "set" from Russell's paradox is:
$$R=\{x:x\notin x\}$$
Which led to the obvious contradiction $R\in R\iff R\notin R$.
I think that I understand it, my interpretation is:
Under $\mathsf{ZF}$ axiomatic system, the only way we can construct such a 'set' is from existing sets. So, using the axiom of separation we must have some set $B$ such that:
$$R=\{x\in B:x\notin x\}$$
Moreover, by the axiom of regularity it's not hard to prove that every set $A$ is not an element of itself, That is, $A\notin A$. Therefore, the formula $\varphi(x):=[x\notin x]$ is always true. Therefore:
$$R=\{x\in B:\overbrace{x\notin x}^{\text{always true}}\}=B$$
So no new set was created and no contradiction has been occurred.
Is my interpretation valid? Is that how $\mathsf{ZF}$ axioms 'avoid' such axioms?
Feedbacks will be appreciated!
Comment: Regularity alone isn't enough to avoid Russell's paradox: it just reduces that paradox to the argument that regularity shows the "universal set" is not a member of itself, whereas we would expect that everything is a member of the universal set, including the universal set itself.
Answer: Not quite; you must still consider why the original contradiction $R \in R \iff R \not \in R$ no longer applies.
That is because once you limit to $B$, you can no longer conclude $R \in R \iff R \not \in R$ anymore; you can only conclude that under the additional assumption that $R \in B$.  So the conclusion is simply that $R \not \in B$, and there is no contradiction.
Note that this holds even if you remove the axiom of regularity.
Comment: So just to clarify, If $R\in B$, we will get that $R\in R\iff R\notin R$. Thus we must conclude that $R\notin B$ and everything here is valid. Moreover, by the arguments I presented, it is true that $R=B$, right?
Comment: Yes, your arguments are correct, in the presence of the axiom of regularity.
Comment: Thanks for the answer!
Answer: Defining $R:=\{x\in B|x\notin x\}$, $R\in R\iff R\in B\land R\notin R$, which reduces by the tatutology $(p\iff q\land\neg p)\equiv(\neg p\land\neg q)$ to $R\notin R\land R\notin B$, rather than a contradiction. Regularity tells us further that $R=B$.
One more point: in theories such as ZF, we can do more than just prove certain sets exist. We can also prove a certain set doesn't exist by deriving a contradiction, including of course a hypothetical set whose elements are precisely those $x$ with $x\notin x$, by the usual argument. So we don't only fail to prove such a set does exist; we can also prove it doesn't. (A related concept is to say that the class of all sets $x$ with $x\notin x$ is not a set, but rather a proper class.)
Comment: Thank you! That's a great explanation


IMCE with Amazon S3

Question: I'm having an issue configuring IMCE to rely on the Amazon S3 bucket pointed to by the AmazonS3 module: https://www.drupal.org/project/amazons3. I have successfully configured image fields to use the S3 bucket location, but the IMCE file browsing window appears blank after being clicked on from within the ckeditor window and when file browsing is enabled for image fields.
Has anyone successfully hooked this up, and if so, could you either direct me to or write detailed, step-by-step instructions for accomplishing this?
Thanks in advance!
Answer: Use AmazonS3 7.x-1.x-dev version. It contains a fix for IMCE compatibility.
https://www.drupal.org/node/2204401
Comment: Seems straightforward. I'll test this tomorrow and see how it goes. Thanks for your assistance.
Comment: This solution worked.

IMCE with Amazon S3


Wiremock :How to read the stub from a file in wiremock?

Question: Currently I am setting up request and response in my stub through my java code like below.
wireMockRule.stubFor(WireMock.get(WireMock.urlEqualTo("/abc/xyz"))
                .willReturn(WireMock.aResponse()
                        .withBody("Hey")
                        .withStatus(HttpStatus.OK.value())
                        .withHeader("Content-Type",
                                "application/text")));

I wish to know if there is a possibility that I define all the stub configuration in the json file like below and just read it in my java code.
{
  "request": {
    "method": "GET",
    "url": "/abc/xyz"
  },
  "response": {
    "status": 200,
    "jsonBody": {"Hey"},
    "headers": {
      "Content-Type": "application/test"
    }
  }
}

I read about mapping folder over many post. I am not sure what that is and how do I get it and how can it help in my use case?
Also, I read about body file name but that just helps with the response body while I wish to find a solution which helps with the whole stub from a file.
A working java example would be really helpful.
Comment: Have you read http://wiremock.org/docs/stubbing/? *"To create the stub described above ... the following document can [be] placed in a file with a `.json` extension under the `mappings` directory"*
Comment: Yes I have. It says that a json file can be placed under the mapping directory. I am not sure how do I get the mappings directory? Do I create it manually? I am using wiremock in my spring boot project
com.github.tomakehurst
wiremock
2.21.0
test
Comment: So did you try looking that up? http://wiremock.org/docs/configuration/#file-locations
Comment: Earlier I placed the above json in "src/main/resources/__files/abc.json" and was trying to fetch the stub in my code by using "withBodyFile()" method. So I was getting whole file contents as response body. Instead I wish to get the whole file as my complete stub. Now I have placed the file in the mappings directory ("src/main/resources/mappings/abc.json"). How do I get this a s stub in my java code?
Comment: @jonrsharpe It worked. Thanks. Stuck in on other problem, if you can help me. I am trying to define multiple stubs in one file with following format:  {
  "mappings": [
    {
      "request": {
        "url": "/multi/1",
        "method": "GET"
      },

      "response": {
        "status": 200
      }
    },

    {
      "request": {
        "url": "/multi/2",
        "method": "GET"
      },

      "response": {
        "status": 200
      }
    }
    }
  ]
}  I am getting Unrecognized field "mappings" (class com.github.tomakehurst.wiremock.stubbing.StubMapping)
Comment: AFAIK to use multiple mappings in a single mapping file you'll have to add it via the admin console instead of just housing it in the `mappings/` directory. If you have it in the `mappings/` directory, then WireMock thinks it is a mapping to use, and throws you that error because `mappings: ` is an invalid field for a singular mapping. Info on admin console: http://wiremock.org/docs/api/ . I'd probably suggest that you have each mapping in a separate mapping file.
Comment: @agoff Thanks for your reply. As suggested, I am working with separate files in mappings folder. Wish to ask one more question. Is there any way by which we can make wire mock thread safe. I mean multiple test cases in a suite can run in parallel and since I am instantiating wiremock as WireMockRule wireMockRule = new WireMockRule(8900); in each test case. So when they will run in parallel there will be clash for the port. How canI get over it?
Comment: If you don't need unique data per test, you can just have the one WireMock instance running. Instead of starting a new server for each test, just start the server before all tests and teardown after all are completed. If you need unique data and states, you'd have to spin up separate WireMock servers on separate ports.
Answer: Stubs file (src/test/resources):

Content file (stub.json):
Comment: This means that you start the wiremock server in java programmatically and still take advantage of configuring the stubs using json file. Correct? Initially I thought you can only use the stubs in the mappings folder if you use the standalone jar process.
Comment: Yes, with java your can run and stop wiremock programmatically. You can use config json file or programmatically.
Answer: Actually wiremock under the hood just reads the files and maps them to a POJO. This can be seen by looking through the library source code (JsonFileMappingsSource.loadMappingsInto).
So to achieve the same you can just do:
private static StubMappingCollection deserialize(String fileContent) {
    return com.github.tomakehurst.wiremock.common.Json.read(
        fileContent,
        StubMappingCollection.class);
}

Answer: You also can also set custom path to stubs in this way (version 3.3.1):
@Test
public void anyTest(WireMockRuntimeInfo runtimeInfo) {
    final WireMock wireMock = runtimeInfo.getWireMock();
    wireMock.loadMappingsFrom(rootDir);
}


Understanding the convolution as a weighted average to eliminate noise $ s(t) = \int x(a) w(t-a) da$

Question: I was reading Yoshua's Bengio [book][1] on convolutional neural networks and it has small section that described/explains the convolution in the context of estimating the location of a spaceship with a laser and removing noise from the measurements by taking a weighted average. However, I was not sure if I understood it fully.
Suppose we are tracking the location of a spaceship with a laser sensor and our sensor provides a single output $x(t)$ the position of the spaceship at time $t$ and it might have some noise.
To make this better we take an average of the locations we read, but make it a weighted average $w(a)$ (because we want to weight more recent measurements more, for example, since they might be more relevant). To fix this we build a new fuction $s(t)$ providing a smoothed estimate of the position of the spaceship:
$$ s(t) = \int x(a) w(t-a) da$$
I know that this operation is called the convolution (denoted $s(t) = (x * w)(t)$) but it didn't really make sense to me in this context of weighted average and wanted to confirm/check (also, for values in the future $w$ is zero).
The main issue I believe I have is with the indices not matching between $x(a)$ and $w(t-a)$ not matching, this is what is not intuitive. If we are making a weighted average and want a smooth estimate of $x(t)$ at time $t$, why wouldn't we compute:
$$ s(t) = \int^t_{-\infty} x(a) w(a) da $$
which intuitively just means to me, take a weighted average from the beginning of time to current time $t$. Though that is not what we do and we do some other funny integral (convolution) that makes little sense to me.
I did try to understand it better by considering individual infinitesimal summations of the integral but the indices still didn't make sense to me.
For example:
Consider the weight of the most recent measurement of the integral at $a = t$. At this time we have $w(t-a) = w(0)$ and $x(a) = x(t)$ and the term that constributes to our infinetesiam summation is about:
$$ x(a) w(t-a) = x(t) w(0)$$
but the $t$ and $0$ don't really match in indices and I was a little confused. Does someone understand this better and why the convolution is the appropriate thing to use? What is the meaning of $w(0)$? I am pretty sure they just define $w(a_-)$ (where $a_-$ are negative values) to be zero make sure the summation is zero for the future.
Is it that the index $w(0)$ is the weight for the most recent measurement no matter what the time is? That way it weights it the same for all values of $t$ we might be interested?
Answer: Maybe you got it already, but in case it helps here is what I think:
Note: All the plots shown are made with the great demo of this website.
The main advantage of using convolution as a way of averaging a function $x(t)$ with a weight function $w(t)$ is that you can "select" the time at which you want $w(t)$ to take action.
For example suppose that $w(t)$ and $x(t)$ are the next time-dependent functions:

In this case, if we make use of this averaging (or more correctly, the scaled weighted average of $x(t)$ due to the fact that we are not dividing the result by $\int w(t)\,dt$):
$$s(t)=\int_{-\infty}^tx(a)\,w(a)\,da$$
we could  only apply $w(t)$ in the region $t\in[0,1]$ because at any other time $w(t)=0$.
But if we make use of convolution:
$$s(t)=\int_{-\infty}^tx(a)\,w(t-a)\,da$$
we could get this scaled (up to a factor $\int w(t)\,dt$) weighted average at any time $t$ that we want. And I believe this is the reason why the author state that we can "weight more recent measurements". Following the example of the previous image, we will have this of the convolution:

Note: I recommend to visit the website I mentioned above and play with the demo. It will help a lot to visualize what I tried to explain.


Qual a melhor forma e mais segura de identificar um dispositivo no webservice?

Question: Estou desenvolvendo um APP (no momento somente Android - Java puro), ele consumira um webservice feito em PHP (utilizo o mini Framework Silex).
Como sabemos hoje temos que proteger tudo ao máximo, então tomei algumas medidas de segurança:

Utilizarei HTTPS em todas requisições entre dispositivos e o
webservice;
Cada dispositivo recebe pra si uma key única quando ele é aberto
pela primeira vez, a key permite acesso e identifica o dispositivo
no servidor.

Obs.: A key é armazenada tanto no servidor quanto no dispositivo do usuário e em qualquer requisição essa key é enviada para o servidor e o servidor verifica se é igual a que ele possuí.
Pretendo ainda implementar mais questões de segurança, como criptografar os dados antes de saírem dos dispositivos ou do webservice, e obviamente quando chegar no destino final vão ser descriptografados, claro cada dispositivo terá sua própria senha e o servidor possuíra todas as senhas. Isso eu ainda não sei como irei fazer então se alguém quiser dar algum concelho será bem-vindo. Outra coisa que farei é a ofuscação do código do APP.
Porém no momento o que me incomoda é as trocas de informações entre o servidor e os dispositivos, essa forma que estou trabalhando pra mim está muito superficial então gostaria de incrementar a segurança nas requisições. Porém não faço ideia de como realizar isso e venho pedir dicas da comunidade para eu poder melhorar minhas aplicações.
Comment: Recomendações são muito subjetivas. Se você já tem o web service tente pesquisar sobre "formas de autenticação de autorização em web services"
Comment: Com a atualização da pergunta ficou mais claro o que você está procurando. A sua preocupação sobre segurança do conteúdo, se já está usando HTTPS não vejo motivo para criptografar os dados. Na questão de autorização, se estiver usando token, da uma olhada no [JWT] (https://jwt.io/introduction/)
Comment: @MateusFMello HTTPS é uma camada se segurança em cima do HTTP. O browser troca informação criptografada com o servidor web. É claro que não é 100% seguro porque ele é baseado em certificados, ou seja, se tiverem acesso a sua chave pode ser quebrado, mas dai até mesmo uma criptografia própria que você fizer vai ter uma chave correndo o mesmo risco. Certificados também podem ter custos.
Comment: Faltam muitas informações na questão, inclua mais detalhes como qual tecnologia usou para o WebService. Vou colocar uma resposta mais informativa apenas para lhe dar um norte, mais é preciso elaborar melhor sua questão.
Comment: @Pagotti sim concordo porém estou numa seca de ideias sobre esse assunto que vim pedir qualquer ideia pra comunidade.
Comment: @Pagotti o HTTPS protege todas as informações da requisição? Pois se não proteger um atacante pode ter acesso aos dados necessário como o token, vou ver sobre esse JWT, obrigado
Answer: O que você está procurando é um método de autenticação ou autorização para o seu WebService, mais isto varia de acordo com a tecnologia empreendida no desenvolvimento do seu WebService. Se você estiver utilizando WebServices SOAP ou WCF com .NET é uma abordagem, se estiver utilizando APIs REST a abordagem é outra. Entende como isso pode ser complexo?
Vou lhe passar algumas informações que poderão lhe dar um norte sobre o que pode ser feito, baseado em tecnologias .NET que são as que domíno. Visto também que você não explicou qual a tecnologia utilizou para desenvolver seu backend.
Basicamente autenticação com serviços Web envolvem o envio de algumas informações no cabeçalho da requisição e processamento destes dados no servidor, validando o usuário (dispositivo) ou não, o que deve gerar um erro HTTP 401 - Unauthorized.
Existem bibliotecas e frameworks que ajudam a fazer isso em cada tecnologia, por exemplo em ASP.NET MVC tem o ASP .NET Identity, o OAuth 2.0 que pode ser utilizado com Web API e também integra sua aplicação com redes sociais como Twitter e Facebook.
Dentro de cada abordagem, também existem inúmeras maneiras de se implementar autenticação.
Agora, se você quiser desenvolver tudo na mão, o que não é o ideal, você pode incluir um parâmetro nos métodos do WebService que pode servir de token de validação, e em cada você pode criar um método para validação deste token.
Não me orgulho disso, mais já fiz isso algumas vezes, abaixo o exemplo de um método que criei em um WCF:
<code>public class WcfClientValidations : IWcfClientValidations
{
    DataContext context = new DataContext();

    public string GetData(string clientToken, int code)
    {
        TokenValidation(clientToken);

        return context.Data.Where(o => o.code = code).ToList();
    }

    private void TokenValidation(string clientToken)
    {
        if (string.IsNullOrEmpty(clientToken))
        {
            throw new Exception("Token inexistente !");
        }

        try
        {
            var clientCode = (int) Base64Decode(clientToken);
            var clientDb = context.Clients.Where(o => o.code = clientCode);

            if (clientDb == null)
              throw new Exception("Cliente inexistente ou token inválido !");
        }
        catch (Exception e)
        {
            throw new Exception("Problemas ao validar o cliente !");
        }
    }

    private static string Base64Decode(string base64EncodedData)
    {
        var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
        return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
    }
}
</code>
Como você pode ver no método GetData eu recebo um clientToken que é convertido e válidado retornando uma exceção caso o cliente não exista.
Espero ter ajudado, apesar de não ter muitas informações na pergunta.
Comment: Então estou fazendo algo parecido, estou utilizando php no webservice, dai eu fiz o seguinte, na primeira vez em que o usuário acessa o APP ele se conecta no webservice e solicita um token, o token é uma sha512 gerada a partir de algumas informações sobre o dispositivo que foram enviadas na requisição, essa hash é salva no dispositivo e no webservice e a cada nova requisição essa hash é verificada, dai é dada ou não a permissão pro dispositivo.


Change a c++ class attribute from a QML text input

Question: Alright, so the title says exactly what I'm trying to do. I'll show you the code and the issue I have.
What I want to do

I'm trying to open a file from a click on a button with a custom file name entered in a textInput. This textInput is handled through my AntennaFile class. The file opening happens in the openButtonClicked function.
The issue I have

My m_fileName attribute doesn't have a value in the openButtonClicked function even though it has one in the setFileName one (I checked in debug with breakpoints and with qDebug()).
So how does one make the attribute not "lose" it's value? I'm surely missing something very simple and important for all of this to work and it's driving me crazy.
So here is all the needed code (I think?) so you can see exactly what I have done.
antennafile.cpp
#include "antennafile.h"

AntennaFile::AntennaFile(QObject *parent) : QObject(parent)
{
}

QString AntennaFile::getFileName()
{
    return m_fileName;
}

void AntennaFile::setFileName(const QString &fileName)
{
    if (fileName != m_fileName)
    {
        m_fileName = fileName;
        emit fileNameChanged();
        qDebug() << m_fileName; // Here, m_fileName has the value of what I typed in the textInput
    }
}

void AntennaFile::processFile(QString fileName, QVector<QString> &vecOfStrs)
{
    // Code removed for smaller post
}

void AntennaFile::openButtonClicked()
{
    QVector<QString> vecOfStrs;
    QString nameOfFile = "../QMLStageProject/AntennaTypes/";
    nameOfFile.append(m_fileName);
    qDebug() << nameOfFile; // Here, m_fileName is empty, hence, nothing is changed to nameOfFile

    processFile(nameOfFile, vecOfStrs);
}

antennafile.h
#ifndef AntennaFile_H
#define AntennaFile_H

#include "framework.h"
#include "antennadata.h"

class AntennaFile : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString fileName READ getFileName WRITE setFileName NOTIFY fileNameChanged)

public:
    explicit AntennaFile(QObject *parent = 0);
    QString getFileName();
    void setFileName(const QString &fileName);

private:
    void processFile(QString fileName, QVector<QString> & vecOfStrs);

public slots:
    void  openButtonClicked();

signals:
    void fileNameChanged();

private:
    QString m_fileName;
};

#endif // AntennaFile_H

main.cpp
#include "framework.h"
#include "antennafile.h"
#include "antennatablemodel.h"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;

    const QUrl url(QStringLiteral("qrc:/main.qml"));

    AntennaFile antennaFile;
    engine.rootContext()->setContextProperty("_AntennaFile", &antennaFile);

    // Registers
    qmlRegisterType<AntennaFile>("AntennaFile", 1, 0, "AntennaFile");
    qmlRegisterType<AntennaTableModel>("AntennaTableModel", 1, 0, "AntennaTableModel"); // An other class

    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);

    engine.load(url);

    return app.exec();
}

main.qml - not all the code again, just what is needed
import QtQuick 2.12
import QtQuick 2.6
import QtQuick.Window 2.12
import QtQuick.Controls 1.4
import QtQuick.Controls 2.0
import QtQuick.Controls 2.14
import QtCharts 2.3

import AntennaFile 1.0;
import AntennaTableModel 1.0;

Window
{
    id: window
    visible: true
    width: 950
    height: 680
    title: qsTr("QML Stage Project")

    AntennaFile {
        id: antennafile
    }

    TextInput {
        id: antennaTextInput
        x: 92
        y: 14
        width: 351
        height: 20
        text: antennafile.fileName
        font.pixelSize: 17
        onTextChanged: antennafile.fileName = text
    }

    Button {
        id: openButton
        x: 363
        y: 0
        width: 170
        height: 31
        text: qsTr("Open")
        font.pixelSize: 15
        onClicked: _AntennaFile.openButtonClicked();
    }
}

Comment: Also a possible bug is: you have two instances of AntennaFile! The first one is in your main as context property "_AntennaFile". The second one is declared directly in your main.qml
Comment: it not clear in your code when/how "openButtonClicked" is called in QML. Can you add that to your example?
Comment: Just edited it! I forgot about it sorry ^^'
So how would I make the two of these instances "linked" / only one instance?
Answer: you have two instances of AntennaFile! The first one as context property. The second one in your main.qml. Your are not using the same one for the text edit and button!
Changing your code like this, should work:
import QtQuick 2.12
import QtQuick 2.6
import QtQuick.Window 2.12
import QtQuick.Controls 1.4
import QtQuick.Controls 2.0
import QtQuick.Controls 2.14
import QtCharts 2.3

import AntennaFile 1.0;
import AntennaTableModel 1.0;

Window
{
    id: window
    visible: true
    width: 950
    height: 680
    title: qsTr("QML Stage Project")

    AntennaFile {
        id: antennafile
    }

    TextInput {
        id: antennaTextInput
        x: 92
        y: 14
        width: 351
        height: 20
        text: antennafile.fileName
        font.pixelSize: 17
        onTextChanged: antennafile.fileName = text
    }

    Button {
        id: openButton
        x: 363
        y: 0
        width: 170
        height: 31
        text: qsTr("Open")
        font.pixelSize: 15
        onClicked: antennafile.openButtonClicked();
    }
}

You can actually delete these lines from your main:
AntennaFile antennaFile;
engine.rootContext()->setContextProperty("_AntennaFile", &antennaFile);

Comment: setContextProperty is used when you want to keep ownership of the object in c++. That way the object is instantiated only once and can be used in multiple qml files as well as in c++. This is especially useful for a sigleton.

You can test it in your code by removing the AntennaFile { } item from qml and using only the "_AntennaFile" property that you declared in c++.
Comment: You are life savior! Thanks for your help!
I can't believe it was so simple but at the same tipe I was so far from it. I don't really get the use of the setContextProperty if  you can just do it this way, but I'll do some research on the subject. Thanks again!
Comment: Thanks for this answer aswell, really useful informations. Very happy that I got all my questions answered. Take it easy!


Mysqldump max_allowed_packet issue

Question: I need to migrate a database that was managed by someone who left the company.
The source server is MariaDB 1:10.5.5, the destination MariaDB 1:10.5.19.
The existing backup scripts use the following command:
mysqldump --max_allowed_packet=5120M -u root -p my_db > my_dump.sql
Both servers have the following settings
In /etc/mysql/conf.d/mysqldump.cnf:
[mysqldump]
quick
quote-names
max_allowed_packet      = 16M

In /etc/mysql/mariadb.conf.d/50-server.cnf:
max_allowed_packet=524288000  (-> = 500MB)
I don't know why but there must be a reason it was set like this.
I don't understand why using "--max_allowed_packet=5120M" on the command line.
It doesn't fit with the server settings and the MySQL documentation says that the mysqldump max_allowed_packet value must not exceed the server value and that the protocol has a max value of 1G.
If I run "mysqldump --max_allowed_packet=5120M -u root -p my_db > my_dump.sql" manually,
I get this warning:
"Warning: option 'max_allowed_packet': unsigned value 5368709120 adjusted to 2147483648"
How can I dump this database safely? I need to be sure I don't loose any data and that it will import in the new server.
Do I have to use "max_allowed_packet"? Maybe with the same value as the server (524288000) ?
Thanks!
Comment: Consider upgrading in-place.  (No dump + restore)  But it would be good to take a backup.
Answer: As long as its less then the limit at both ends, and you don't have any very large blobs in your database that would exceed the packet size, you want lose data by using a smaller packet size or a different packet size at each end of the exchange.
Comment: Thank you. How to be sure there's no large blob in the DB? Would I get a warning or error during mysqldump if there was any?
Comment: yes, you'll get a warning.

Mysqldump max_allowed_packet issue


Do i need to create an add on for my jira instance if i want to create a mobile client for it?

Question: I am planning to create a mobile application and plan to talk to with my JIRA instance using rest api and after digging through rest api for JIRA 6.1.3 , i have a doubt whether do we need to create a plugin for JIRA instance if i want to create a mobile client for it ?
Answer: Basically if you want to talk to JIRA via REST you don't need JIRA plugin unless you need to add some REST points for your needs, or store some data in JIRA which plugins can do.
You can also consider creating JIRA addon to serve some nicelooking pages for your mobile that is creating mobile web application instead.


python optparse, how to include additional info in usage output?

Question: Using python's optparse module I would like to add extra example lines below the regular usage output. My current help_print() output looks like this:
usage: check_dell.py [options]

options:
-h, --help     show this help message and exit
-s, --storage  checks virtual and physical disks
-c, --chassis  checks specified chassis components

I would like it to include usage examples for the less *nix literate users at my work. Something like this:
usage: check_dell.py [options]

options:
-h, --help     show this help message and exit
-s, --storage  checks virtual and physical disks
-c, --chassis  checks specified chassis components

Examples:

check_dell -c all
check_dell -c fans memory voltage
check_dell -s

How would I accomplish this? What optparse options allow for such? Current code:
import optparse

def main():
    parser = optparse.OptionParser()
    parser.add_option('-s', '--storage', action='store_true', default=False, help='checks virtual and physical disks')
    parser.add_option('-c', '--chassis', action='store_true', default=False, help='checks specified chassis components')

(opts, args) = parser.parse_args()

Comment: Migrate to argparse :-)
Answer: parser = optparse.OptionParser(epilog="otherstuff")

The default format_epilog strips the newlines (uses textwrap), so you would need to override format_epilog in your parser like this.
def main():

    class MyParser(optparse.OptionParser):
        def format_epilog(self, formatter):
            return self.epilog

    parser =MyParser(epilog=
"""Examples:

check_dell -c all
check_dell -c fans memory voltage
check_dell -s
""")
...

Here's a bit more detail.
If you look in optparse.py in the class OptionParser there is a method called format_epilog which is called by format_help
here is the snippet from optparse.py
def format_epilog(self, formatter):
    return formatter.format_epilog(self.epilog)

def format_help(self, formatter=None):
    if formatter is None:
        formatter = self.formatter
    result = []
    if self.usage:
        result.append(self.get_usage() + "\n")
    if self.description:
        result.append(self.format_description(formatter) + "\n")
    result.append(self.format_option_help(formatter))
    result.append(self.format_epilog(formatter))
    return "".join(result)

The default behaviour of formatter.format_epilog is to use textwrap.fill which amongst other things, strips the newlines from the epilog. Since we want the newlines to be preserved, we subclass OptionParser and change the behaviour of format_epilog
Comment: epilog appears to have been added after 2.4 :(
Comment: Thank you very much, that's awesome, since it's not documented on the optparse page.
Comment: This will be my first non-bash script so please excuse my n00bness. What if I wanted three or four lines of epilog?
Comment: +1 - you learn something new everyday. I knew about `description` and have used it for similar purposes. This is much nicer. Interestingly enough, it is mentioned in the _in interpreter help_ so it is in the docstring... `import optparse; help(optparse.OptionParser)` shows it...
Comment: I added it and it works great! Thanks gnibbler. I read the Chapter on OOP in "Core Python" just yesterday, and I haven't the slightest what is going on here. I am going to stare blankly at it for the next few hours till I get it. Wish me luck.
Answer: Elaborating on the winning answer (which helped me solve the same problem in my own code), one quick-and-dirty option is to directly override the class's method with an identity method:
optparse.OptionParser.format_epilog = lambda self, formatter: self.epilog
optparser = optparse.OptionParser(epilog=helptext)

to get helptext printed as a verbatim epilog.
I think this overrides the epilog formatting for all uses of the OptionParser class in your program, however, so all such epilogs must be passed in verbatim where you use OptionParser elsewhere in your program.
Answer: Use the usage parameter:
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)

You can add more through (just an example):
group = OptionGroup(parser, "Dangerous Options",
                    "Caution: use these options at your own risk.  "
                    "It is believed that some of them bite.")
group.add_option("-g", action="store_true", help="Group option.")
parser.add_option_group(group)

Example output:

usage:  [options] arg1 arg2
options:   -h, --help           show this help message and exit
  -v, --verbose        make lots of noise [default]
  -q, --quiet          be vewwy quiet (I'm hunting wabbits)
  -fFILE, --file=FILE  write output to FILE
  -mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate', [default], 'expert'
Dangerous Options:   Caution: use of
  these options is at your own risk.  It
  is believed that   some of them bite.
  -g                 Group option.

Have a look here.
Comment: Thanks for the quick help! What if I wanted the examples to appear below the regular usage summary?
Answer: Another idea on how to do this would be disabling the default behavior for -h and printing your own help screen, which can include the default one:
from optparse import OptionParser

parser = OptionParser(add_help_option=False,
                      epilog="This can't be easily\n multilined")
parser.add_option('-h', '--help', dest='help', action='store_true',
                  help='show this help message and exit')

(options, args) = parser.parse_args()

if options.help:
    parser.print_help()
    print 'now we have an epilog'
    print 'with as many lines as you wish'
    sys.exit()

That is basically what the parser does with the default behavior of add_help_option=True, excluding of course the prints.
But, in all honesty, I'd also prefer a way to simply add any given number of description lines in the beginning and in the end.
Answer: There is a description parameter you can pass to the OptionParser constructor.  This allows you to include arbitrary text that appears after usage, but before the list of options.
See 184.108.40.206. Creating the parser.
Answer: I subclassed IndentedHelpFormatter, and it was pretty simple:
class PlainHelpFormatter(optparse.IndentedHelpFormatter):
    def format_description(self, description):
        if description:
            return description + "\n"
        else:
            return ""
    def format_epilog(self, epilog):
        if epilog:
            return epilog + "\n"
        else:
            return ""


Remove file from Apache using servlet

Question: I'm uploading files using servlet my little code is like this:
ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());

try {
    fileItemsList = servletFileUpload.parseRequest(request);
} catch (FileUploadException ex) {
    Logger.getLogger(iThink.class.getName()).log(Level.SEVERE, null, ex);
}

String optionalFileName = "";
FileItem fileItem = null;

Iterator it = fileItemsList.iterator();
...

The file is uploaded to apache directory (\webapps\mysite\uploads\abd.zip). Uploading is working fine but I want to delete it.
Comment: Have you tried doing it yourself? I good place to start is [java file delete](http://www.google.com/search?ie=UTF-8&q=java+file+delete)
Answer: Since you already got a list of FileItem objects you can simply iterate over that list and call FileItem#delete on the items. Alternatively use File#delete from Java's standard library.
Comment: i made little mistake in directory so its working fine now thank you for your reply..

Remove file from Apache using servlet


Jazz piano: improving voicings

Question: I run into these two problems related to chords:

My accompany with my left hand conflicts/try to occupy the same tones as my right hand, melody.
My voicings are boring and dull. Very standardised and little variety. But, the simplicity means I can get through a standard, roughly.

I wonder, how do I solve this?
Theoretically it's easy — the chord tones are known and it's just about picking different voicings. However, that's a daunting task, and maybe it's about breaking it down. Should I get Levine's classic The Jazz Piano Book? Maybe I'm looking for a path that is constructive, pedagogical and doesn't involve reinventing the wheel.
I would like flexibility, choice from a large library of voicings. And in the future, creative improvisation stemming from it.
Some pianists on Youtube have hand positions that are very broad, like 6 or 7 tones distance in each hand. Maybe this is a hint to how to make it more interesting.
Comment: Can you give an example of a voicing you think is boring and dull?
Comment: From an artistic perspective I wouldn't say there's a voicing that is boring and dull, they become so by misuse. A voicing is a component and has its proper use. I've misused them because I don't know others and therefore become bored by them. So, a voicing might be boring for me, but fascinating for you ;-)
Answer: Hard to give advice if you are not telling us what voicings you are currently playing.
Practice first your shell voicings: 1 3 7 and 1 7 3. (Low to high). As you stitch chords together try to limit big jumps in the top note. Use your ears and break the rules if it sounds OK to you.
So first 4 chords of "all the things you are" (Fm7, Bbm7, Eb7, AbM7, ...) becomes: F Eb Ab,  Bb Db Ab,  Eb Db G,  Ab C G, ...
Or F Ab Eb,  Bb Ab Db,  Eb G Db,  Ab G C, ...
Then try rootless: 3 7 9 or 7 3 6. Again, favor the voice leadings with limited jumps.
A bit more rich rootless left hand voicings are 3 5 7 9 or 7 9 3 6. So a Gm7 C7 FM7 becomes: Bb D F A,  Bb D E A,  A C E G.
Another trick is to play only root with the left hand and  with the right hand 3 + 7 + melody or 7+3+melody. If the melody is a 3 or 7, then you play just 3 and 7. Just make sure that the melody note is always on top.
Comment: 1 7 3? I must have small hands.
Comment: @ToddWilcox - probably not. An octave or a 9th seems pretty standard, and I need to roll a tenth. Might spawn a question as to why piano keys are that size - given that all that time ago, theoretically, people were slightly *smaller* than now. Maybe an octave was the max. stretch?
Comment: I agree, 1 7 3 is a stretch for me as well. @Kris, what I typically play is 713 in LH because it's compact, easy to locate and rarely conflict with melody. Another I play is 1 7 in LH and 3 + melody in RH. That one is closer to where I want to go: spread out and chord tones in RH. Augmented seems to lend itself poorly to putting the top tone at the bottom. Thanks for your suggestions, I'll look at it.
Answer: I'm learning to do Chord substitutions and inversions on the guitar, but it's harder than I thought. I start with the notes in a chord, then try rearranging them to find chords that work. Like replacing a CM7 with a C6add9, or F#m7 with A6/C#.

Jazz piano: improving voicings


Performace em consulta nativa

Question: Bom dia, estou em um projeto em que devo montar gráficos com base em consultas realizadas em um banco Postgres.
Esse banco tem uma estrutura para BI e as tabelas possuem na média 40 milhões de linhas.
As consultas que devo realizar no banco, estão sendo feita através de querys nativas pelo JPA, essas consultas chegam a demorar até 5 minutos para retornar os dados, mas quando executado no PgAdmin ou no DBeaver (ide generico para bancos com base no ide do eclipse), o tempo de retorno é de 20ms.
A aplicação é em EJB, utilizando JPA e Hibernate, utilizamos o JBoss EAP 6.3 como middleware, a conexão com o banco esta sendo gerenciado pelo proprio JBoss, poderia ser alguma configuração dele ou o problema é outro mesmo?
Consulta
select date_part('day', dt.dta) dia,
    sum(distinct(fp.valorvendido)) venda,
    sum(distinct(fp.valortotalcustodia)) custo,
    sum(distinct(fp.valorlucrototal)) lucro,
    round(((sum(fp.valorlucrototal) / sum(fp.valortotalcustodia)) * 100),2) margem,
    sum(distinct(dp.qtdvendido)) qtd_vendido
from ft_produto fp
    inner join dmn_tempo dt
        on dt.dta = ft.dta
where fp.nrodivisao in (1, 2, 3)
    and fp.nroempresa = 9
    and fp.nrosegmento in (1, 2, 3, 4, 7, 8, 9, 10)
    and dt.anomes = 201604
    and fp.seqproduto = 20615
group by dt.dta order by dia

Plano de executção gerado pelo PgAdmin
"Sort  (cost=444.86..444.86 rows=1 width=34)"
"  Sort Key: (date_part('day'::text, dt.dta))"
"  ->  GroupAggregate  (cost=444.27..444.85 rows=1 width=34)"
"        ->  Merge Join  (cost=444.27..444.81 rows=1 width=34)"
"              Merge Cond: (fp.dta = dt.dta)"
"              ->  Sort  (cost=434.74..434.99 rows=100 width=34)"
"                    Sort Key: fp.dta"
"                    ->  Bitmap Heap Scan on ft_produto dp  (cost=27.15..431.41 rows=100 width=34)"
"                          Recheck Cond: ((nroempresa = 9) AND (nrodivisao = ANY ('{1,2,3}'::bigint[])) AND (seqproduto = 20615))"
"                          Filter: (nrosegmento = ANY ('{1,2,3,4,7,8,9,10}'::integer[]))"
"                          ->  Bitmap Index Scan on ind_dmn_produto15  (cost=0.00..27.13 rows=101 width=0)"
"                                Index Cond: ((nroempresa = 9) AND (nrodivisao = ANY ('{1,2,3}'::bigint[])) AND (seqproduto = 20615))"
"              ->  Sort  (cost=9.51..9.59 rows=30 width=8)"
"                    Sort Key: dt.dta"
"                    ->  Index Scan using ind_dmn_tempo01 on dmn_tempo dt  (cost=0.00..8.78 rows=30 width=8)"
"                          Index Cond: (anomes = 201604)"

Comment: Dá uma olhada na consulta gerada pelo Hibernate e como esta mesma consulta chega ao banco de dados. Provavelmente os parâmetros passados podem não estar coincidindo com o tipo correto no banco e, assim, não utilizando o índice das colunas nas tabelas. No SQL Server, por exemplo, já fiz uma consulta por campo texto que esperava que o parâmetro passado chegasse como VARCHAR mas o driver jTDS colocava um `N` na frente, convertendo para NVARCHAR.
Comment: @Dherik Então já fiz isso, a mesma consulta que executo na aplicação a que lega 5 minutos, quando executada nas ides leva 20~30ms, isso que estou achando estranho
Comment: Você viu como os parâmetros estão chegando no banco de dados nesta consulta? Você precisa ter **certeza** se a consulta que chega ao banco de dados e que ele executa é exatamente a mesma que você usa ao executar no PdAgmin. Seria interessante mostrar como você captura o SQL executado pelo banco de dados e como captura o SQL gerado pelo Hibernate, talvez o problema esteja em como você está investigando o problema.
Comment: @Dherik Sim, confirmei os parametros no debug da aplicação, e os testes que executei nas ides são exatamente as mesmas.
Comment: @João o resultado da consulta é uma Lista de Object ? Você pode ativar as estatísticas do Hibernate e ver quanto tempo precisamente ele gasta com a execução do select. Para ativar dá uma olhada nessa resposta: http://stackoverflow.com/questions/12656452/spring-hibernate-show-query-execution-time
Comment: Você consegue identificar a consulta demorada ocorrendo no banco de dados? O ideal era tentar ver o plano de execução desta consulta. Inclusive, pegando carona no comentário do adelmo, a demora pode estar no lado do Hibernate, depois do resultado (embora acho isto bem raro de ocorrer, nunca vi demora assim para ser sincero).
Comment: @adelmo00 Já utilizo as estatísticas e o tempo de retorno sempre esta entre 3 à 5 minutos
Comment: @Dherik adicionei o plano de execução e a consulta caso isso ajude no problema, mas sim analisei todas as estastíticas, e respondendo a sua pergunta sim, eu busto uma Lista de Array Object
Comment: Mas e o plano da consulta enviada pelo Hibernate? O ideal era começar identificando se esta consulta enviada pelo Hibernate realmente demora de 3-5 minutos dentro do banco de dados.
Comment: @Dherik então o tempo dito acima é o tempo dito nas estatisticas do hibernate, tenterei por uma imagem.
Comment: @Dherik fiz os testes baseado no seu primeiro comentario que foi editado e não tinha visto, funcionou, era realmente um paramentro que na hora que o hibernate dava parse ele estava colocando em um tipo diferente.
Comment: hehehe, muito bom! Vou colocar como resposta então.
Answer: Dê uma olhada na consulta gerada pelo Hibernate e como esta mesma consulta chega ao banco de dados.
Provavelmente os parâmetros passados podem não estar coincidindo com o tipo correto das colunas envolvidas da tabela no banco e, assim, não utilizando o índice das colunas nas tabelas e gerando este tempo maior no retorno dos resultados.
No SQL Server, por exemplo, já fiz uma consulta por campo texto que esperava que o parâmetro passado chegasse como VARCHAR:
SELECT * from Pessoa WHERE nome = 'Paulo'

Mas o driver jTDS colocava um N na frente, convertendo para NVARCHAR.
SELECT * from Pessoa WHERE nome = N'Paulo'

Não utilizando o índice do banco de dados e prejudicando o desempenho da consulta.

Performace em consulta nativa


Send email with profile2 fields with account email token in rules

Question: I am trying to send an email to users contains information they put into their profile2 fields when they registered on the website.
My problem is that their is no email field token available in rules and I was wondering if their is a way to expose the account email token so that I send emails to the user.
The rule I have setup is as follows and I have exported the rule which can be found below.
Event: After saving a new profile
Actions: Send HTML e-mail
<code>{ "rules_email_banking_details" : {
    "LABEL" : "Email Banking Details",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "mimemail", "profile2" ],
    "ON" : { "profile2_insert" : [] },
    "DO" : [
      { "mimemail" : {
          "key" : "[site:name]",
          "to" : "[profile2:field_account_email]",
          "subject" : "Banking Details for accounts that you must make a  payment to.",
          "body" : "[profile2:field_name_of_your_bank]",
          "language" : [ "" ]
        }
      }
    ]
  }
}
</code>
If anybody has some advice that could help it would be much appreciated.
Answer: Your token will be - [profile2:user:mail]. It is available in your rule with the setup that you described. You might not see it in replacement patterns for the "to" field when you are using "direct input" mode, but if you switch to "data selection" mode - you'll be able to find that token much easier.


How to figure which function(s) are triggered upon file download to check permissions

Question: I am experimenting with private file system, done custom way :) .
There is file system/files/test.txt (That is, private://test.txt).
When I try to access the file, I get access denied from Drupal, as expected (site redirects to Access denied page, and dblog shows that accesss have been denied).
But now I want to know what module/function have blocked access to the file. I am blindly trying to check hook_file_download or hook_file_download_access, but as far as I can see it does not go through that functions.
All that in attempt to solve this.
Answer: If the Drupal log shows you that the access has been denied, then you have a simple way to debug this: if you have a debugger, simply set a breakpoint in drupal_set_message. Skip calls to that function (there shouldn't be too many) until you get the one with the access denied message - and then look at the backtrace. This should show you which function denied the access.
If you don't have a debugger, you can simply (temporarily) add some extra code in that function to test for the relevant error message, and then output a backtrace using debug_backtrace. You can output the data on the screen, to a log file using drupal_debug (if you have the devel module enabled), add it to the generated error message, etc.
Comment: Understood - the error is generated by Core. So what I'm suggesting is to add some code at the point where the error is generated (ie. drupal_set_message), and to output a backtrace at that point. The backtrace will show you which function is generating the error - and therefore which function is denying the access. Once you know that, you might be able to work out how to customize access by looking at that function's code. This does require you to change Core, but that's only temporarily to debug what is happening.
Comment: nice tips, but problem is that I do not know what functions are being called when access was denied. I use devel and using drupal_set_message to see if some function has been triggered, but here simply I dont know  where to look :(
Comment: What do you mean by "dblog shows that accesss have been denied" ? Do you get an error in the Drupal Reports ? If so that calls drupal_set_message. What do you get when you output a backtrace from that function when that specific error is logged ?
Comment: yes, dblog says that access has been denied (and that was what I expected). But I cannot figure which module blocks access, so I can customize access with an hook.
Comment: Alice, error message was generated by Drupal core, it is not message that I output to watchdog.
Comment: Ah! I got your point! It was not drupal_set_message though, but watchdog (), also from core. I set up temporarely   var_dump(debug_backtrace()); there and got array of functions called! Tnx!
Answer: This sounds as though its not Drupal blocking the access to this file but the filesystem. When Drupal runs it runs with the permissions of the webserver its running on. If the webserver can't access these files neither can PHP and subsequently Drupal.
A way to see if this is the problem is to set the file permissions on this test file to 777 and see what happens then.