How to changed the selected tab items in the Tabbar in iphone?

Question: I have created tab bar programmatically in the view controller. In my application, Initially displayed the tabbar and it has five tab bar items in the view.Using tab bar, Initially first tab item is selected. Now i want to change the selected items like, fourth item is initially selected.(See the image)
How do i achieve this?
Here my code is,
    tBar = [[UITabBarController alloc] init];

    first = [[first alloc] initWithNibName:@"first" bundle:nil];

    UINavigationController *navFirst = [[[UINavigationController alloc] initWithRootViewController:first] autorelease];

    second = [[second alloc] initWithNibName:@"second" bundle:nil];

    UINavigationController *navsecond = [[[UINavigationController alloc] initWithRootViewController:second] autorelease];

    third = [[third alloc] initWithNibName:@"third" bundle:nil];

   UINavigationController *navthird = [[[UINavigationController alloc] initWithRootViewController:third] autorelease];

   fourth = [[fourth alloc] initWithNibName:@"fourth" bundle:nil];

    UINavigationController *navfourth = [[[UINavigationController alloc] initWithRootViewController:fourth] autorelease];

   fifth = [[fifth alloc] initWithNibName:@"fifth" bundle:nil];

   UINavigationController *navfifth= [[[UINavigationController alloc] initWithRootViewController:fifth] autorelease];

   tBar.viewControllers = [NSArray arrayWithObjects:navFirst,navsecond, navthird, navfourth, navfifth,nil];

   [self.view addSubview:tBar.view];

   [self.navigationController pushViewController:tBar animated:NO];

See the below image. I want exactly like this,
image http://www.freeimagehosting.net/uploads/2798661c55.png
Please guide me.
Thanks.
Answer: Try this:
YourAppNameDelegate *appDelegate = (YourAppNameDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate tabBarController].selectedIndex = 3;

or
tBar.selectedIndex = 3;

Answer: If you want to change from a item to another programmatically you can also do this:
[self parentViewController].yourTabBar.selectedIndex = 3;

I hope this helps someone


FreeRTOS CPP Function Pointer

Question: I want to use a member function of a CPP Class for a FreeRTOS taskFunction.
Here is my initial solution
#ifndef TaskCPP_H
#define TaskCPP_H

#include "FreeRTOS.h"
#include "task.h"

template<typename T>
class TaskBase {

protected:
        xTaskHandle handle;
        void run() {};

public:

        static void taskfun(void* parm) {
            static_cast<T*>(parm)->run();
        #if INCLUDE_vTaskDelete
            vTaskDelete(static_cast<T*>(parm)->handle);
        #else
            while(1)
            vTaskDelay(10000);
        #endif
        }

        virtual ~TaskBase() {
#if INCLUDE_vTaskDelete
                vTaskDelete(handle);
#endif
                return;
        }

};

#endif /* __TaskCPP_H__ */

#ifndef HTTPSERVER_H_
#define HTTPSERVER_H_

#include "TaskBase.h"
#include <string.h>

#include "lwip/opt.h"
#include "lwip/debug.h"
#include "lwip/stats.h"
#include "lwip/tcp.h"
#include "lwip/api.h"
#include "lwip/ip_addr.h"

class HttpServer;

class HttpServer : public TaskBase<HttpServer> {

public:
        HttpServer();
        virtual ~HttpServer();

        void run();

        void listen(ip_addr *address, uint8_t port);
        void print();

protected:
        char taskName[50];
        ip_addr address;
        uint8_t port;

};

#endif /* HTTPSERVER_H_ */

#include "HttpServer.h"

HttpServer::HttpServer()
{

}

void HttpServer::listen(ip_addr *address, uint8_t port) {

        char buf[16];
        sprintf(taskName, "%s_%d\r\n", ipaddr_ntoa_r(address, buf, 16), port);

        DEBUGOUT("ADDRESS Listen: %x\r\n", &taskName);

        this->handle = sys_thread_new(this->taskName, &taskfun, NULL, DEFAULT_THREAD_STACKSIZE + 128, DEFAULT_THREAD_PRIO);

}

void HttpServer::run() {

        while(1) {

                print();

                Board_LED_Toggle(LEDS_LED2);
                vTaskDelay(configTICK_RATE_HZ / 14);

        }

}

void HttpServer::print() {

        DEBUGOUT("ADDRESS Listen: %x\r\n", &taskName);

}

HttpServer::~HttpServer() {
        // TODO Auto-generated destructor stub
}

Now my Problem ist that the context is not the same inside the run function. Printing the memory location of taskName is different inside listen(...) and run(...)
My nasty suspicion is that doing a static_cast of the run function looses the class context? Am I wrong?
Is there any other idea to provide a static function pointer to freeRTOS of a Class member function?
Here are the missing functions. The main and the sys_thread_new which is a wrapper only.
int main(void) {

        prvSetupHardware();

        HttpServer server;
        server.listen(IP_ADDR_ANY, 80);

        /* Start the scheduler */
        vTaskStartScheduler();

        /* Should never arrive here */
        return 1;

}

sys_thread_t sys_thread_new( const char *pcName, void( *pxThread )( void *pvParameters ), void *pvArg, int iStackSize, int iPriority )
{
xTaskHandle xCreatedTask;
portBASE_TYPE xResult;
sys_thread_t xReturn;

        xResult = xTaskCreate( pxThread, ( signed char * ) pcName, iStackSize, pvArg, iPriority, &xCreatedTask );

        if( xResult == pdPASS )
        {
                xReturn = xCreatedTask;
        }
        else
        {
                xReturn = NULL;
        }

        return xReturn;
}

Comment: AFAICS, `taskfun()` is expecting an `HttpServer` object to be passed as its argument, so why are you passing a NULL argument to `sys_thread_new()`?
Comment: What about the code where you presumably create the object and call `xTaskCreate()` with it somehow?
Comment: Could you extract a minimal example? In particular the template stuff and the multiple files are not necessary. Also, don't add multiple edit paragraphs and leave it to others to pick the relevant info from them. Instead, clean up your question as required by the site rules and make the relevant obvious.
Comment: Sry, but I was asked about the missing sections (where the object is created and the xTaskCreate) and I do not think that there are much lines out of scope.
Answer: I use something like this:
class MyClass{
public:
    static void run( void* pvParams ){
        ((MyClass*)pcParams)->runInner();
    }
    void runInner(){
        while ( true ){
            // TODO code here
        }
    }
};

then pass pointer to an object when creating task
MyClass* x = new MyClass;
xTaskCreate( MyClass::run, taskName, stackDepth, (void*) x, taskPrio, taskHandle );

edit:
Assuming you want to use templates:
template<typename T>
void run ( T* p ){
     ((T*)p)->run();
}

class MyClass{
public:
     void run(){
         while ( true ){
             // task code
         }
     }
}

then creating the task
MyClass* x = new MyClass;
xTaskCreate( run<MyClass>, taskName, stackDepth, x, taskPrio, taskHandle );

Edit:
You need to cast run to (void (*)(void*))
xTaskCreate( (void (*)(void*))run<MyClass>, taskName, stackDepth, x, taskPrio, taskHandle );

Comment: I will try your solution, but why xCreateTask should expect an HttpServer object? It's my decistion to specify something? And doing so whould result in an argument of `void run(void* httpServerObject)` isn't it?
Comment: I can't get what you're asking for,  could you please try to explain it again or provide an example?

FreeRTOS CPP Function Pointer


Compare Groovy array with enum values

Question: I have following Array in groovy:
test = [Andrew-PAR, Jackson-CDG, Jilly-MAD, Mike-CDG, Tim-AGP]

And also following enum
NAME_PLACE("Andrew-PAR, Jackson-CDG, Brian-NY")

Getting enum values like Andrew-PAR, Jackson-CDG, Brian-NY
What I need is
*Have to find out the values in enum which are not in the array 'test'
 ie, output will be 'Brian-NY'
I tried <enum returned values> - test to find the output - but it shows the whole value from enum like Andrew-PAR, Jackson-CDG, Brian-NY
Code for enum:
public enum StudentDetails {
    NAME_PLACE("Andrew-PAR, Jackson-CDG, Brian-NY"),
    NAME_COURSE("TEST1, TEST2"),

    private final String studentdetails

    StudentDetails (String studentdetails) {
        this.studentdetails = studentdetails
    }

    public String getstudent() {
        return studentdetails
    }

}

Code for getting enum values:
def student = StudentDetails.values().find {
            val.equalsIgnoreCase(it.name())
        } ?.getstudent()

Finding difference:
def diff = student - test

Answer: Try this:
public enum StudentDetails {
  NAME_PLACE("Andrew-PAR, Jackson-CDG, Brian-NY"),
  NAME_COURSE("TEST1, TEST2"),

  private final String studentdetails

  StudentDetails (String studentdetails) {
     this.studentdetails = studentdetails
  }

   public String getstudent() {
      return studentdetails
   }

  public String value(){
     return studentdetails

  }

}

def test = ["Andrew-PAR", "Jackson-CDG", "Jilly-MAD", "Mike-CDG", "Tim-AGP"]

println StudentDetails.NAME_PLACE.value().split(",")*.trim()-test

Comment: It didn't work for me. seems like enum is not returning any array

Compare Groovy array with enum values


Função preenchendo apenas uma linha

Question: Criei uma função para que a medida que o usuário digite um número de cliente, seja preenchido o nome fantasia do mesmo, porém como estes dados vem dentro de uma tabela e eu utilizo array para capturar (fazer insert e update) nesses dados, todas linhas se preenchem ao invés da única linha que eu digitei, alguém sabe como consertar isso ?

estrutura da tabela
<?php for($i = 0; $i <= 5; $i++){ //coloquei este valor para testar ?>

        <input type="hidden" maxlength="6" name="recnum[]" value="<?php $row['codigo_produto'] ?>">
        <input type="text" maxlength="" name="produto_cliente[]" style="border:none; width:100%; background-color: transparent;">
        <input type="text" maxlength="" class="cadcli_codigo" name="cadcli_codigo[]" style="border:none; width:100%; background-color: transparent;">
        <input type="text" maxlength="" name="nome_fantasia[]" style="border:none; width:100%; background-color: transparent;">
        <input type="text" maxlength="" name="emitente_nfe[]" class="emitente_nfe"  style="border:none; width:100%; background-color: transparent;">
        <input type="text" maxlength="" name="peso_bandeija[]" placeholder="0,0000" style="border:none; width:100%; background-color: transparent;">

<?php } ?>

index.php
$(document).ready(function(){
        $(".cadcli_codigo").on("change", function(){

                    var $nome_fantasia = $(this).closest("tr").find("input[name='nome_fantasia[]']");

                    $.getJSON('function_pro-1.php',{
                            cadcli_codigo: $( this ).val()
                    },function( json ){
                            $nome_fantasia.val ( json.nome_fantasia );
                    });
            });
    });

function_pro-1.php
function nome($cadcli_codigo, $conn){

    $result = "SELECT * FROM cadcli WHERE codigo = '$cadcli_codigo' ";

    $resultado = $conn->query($result);

    // DECLARA A VARIAVEL
    $valores = array();

    if($resultado){

        $row = mysqli_fetch_assoc($resultado);
        $valores['nome_fantasia'] = $row['nome_fantasia'];

    } else {
        return json_encode(array( 'error' => mysqli_error($conn) ));
    }

    return json_encode($valores);
}

if(isset($_GET['cadcli_codigo'])){
    echo nome($_GET['cadcli_codigo'], $conn);
}

Answer: Primeira coisa, teria tem que mudar o id="cadcli_codigo" para class="cadcli_codigo", pois no loop for está gerando vários elementos com o mesmo id, e isso, além de ser fora dos padrões (um id deve ser único em uma página1) está gerando conflito na captura do onchange.
Outra coisa é alterar o seletor da linha abaixo:
var $nome_fantasia = $("input[name='nome_fantasia[]']");

para a linha abaixo, de modo que o input a receber o valor seja o mesmo da linha do input que foi digitada a informação (no caso, o código do cliente):
var $nome_fantasia = $(this).closest("tr").find("input[name='nome_fantasia[]']");

Com essas alterações, seu código deve funcionar perfeitamente.

1 Existem vários "Josés" no mundo, mas cada José tem uma
  impressão digital diferente do outro. É como no HTML: pode haver vários divs, inputs etc., mas nenhum deles deve ter o mesmo id numa mesma página. No caso da class é diferente: pode haver vários "Josés" carecas no mundo. Como no HTML, pode haver vários elementos com a mesma class.
Comment: @VictorT. Obg! Sucesso!
Comment: alterei o código porém não funciona da mesma forma
Comment: @VictorT. Oq não funciona?
Comment: eu vacilei, vou editar o código acima, perceba que está com # invés de . para referenciar cadcli_codigo, desculpa, obrigado pela ajuda vou colocar como a melhor resposta cara e obrigado por compartilhar sua sabedoria também rs

Função preenchendo apenas uma linha


Finding the set of values so all roots of the equation are real numbers

Question: Find the set he set of all values of $\alpha, α ∈ (-π/2 ,π/2)$ such that all solutions of $x^4-2x^2+ \tan(α)=0$ are real numbers.
This question was first asked here by a friend of mine, but he's new to the site and is not really aware of all the rules (I am helping him with that), so I am asking this here with more details. We are both high school students and this problem was adapted from an entrance exam we are studying for.
This is his work:
$0 \le (x^2-1)^2$
$(x^2-1)^2 + \tan(\alpha) = 1\implies \tan(\alpha) \le 1\implies \alpha \in \left[-\dfrac{\pi}{4}, \dfrac{\pi}{4}\right]$
This is my work:
$y^2 - 2y + \tan(\alpha) = 0$
$y = \dfrac{2 \pm \sqrt{4 - 4\tan(\alpha)}}{2}$
$4 - 4\tan(\alpha) \geq 0$
$\tan(\alpha) \geq 1 \implies \alpha \in \left[-\dfrac{\pi}{4}, \dfrac{\pi}{4}\right]$
Basically, we both got the same answers in different ways, but the problem says the answer is actually $\alpha \in \left[0, \dfrac{\pi}{4}\right]$, and it gives no explanation. We cannot find any mistakes in our work. Could anyone explain what's going on?
Comment: If you plug in $\alpha=-\pi/4$ you will see that the polynomial will have complex roots. The main issue is that $y=x^2$, so $y$ has to be non-negative.
Comment: Yes. You are on the right track.
Comment: @JackyChong Thank you a lot! So our mistake was really simple. I'm goint to answer the question myself.
Comment: @JackyChong Wait, I think I just realized: if $\tan(\alpha) < 0$, then $4 \tan(\alpha) > 4$, so $y$ could be a negative value and then $x$ is going to be a complex number. Is this right? I think this is what we were missing! Thank you for your comment.
Answer: You could have avoided the problem computing the discriminant of the quartic equation (have a look here).
$$\Delta=256 \,(\tan (\alpha )-1)^2 \,\tan (\alpha )$$
Quoting Wikipedia :
"If $\Delta < 0$ then the equation has two distinct real roots and two complex conjugate non-real roots".
Then, the result since the sign of $\Delta$ is the sign of  $\tan (\alpha )$.
Comment: @Ingrid. Most of the time, we do not use it but, in this case, the coefficients are so simple ! Cheers :-)
Comment: This is also really nice, we do not study the quartic equation in school so we did not know about the discriminant. Thank you.
Answer: As stated in the comments, when $\tan(\alpha) < 0$, then $\sqrt{4 - 4 \tan(\alpha)} > 2$, so $y^2 - 2y + \tan(\alpha) = 0$ will have a positive and a negative solution, thus when we plug the negative solution back into $y = x^2$, $x$ will be a complex number. Hence $\tan(\alpha) \geq 0$ and so the set is $\left[0, \dfrac{\pi}{4}\right]$.


How to prevent cart from being emptied

Question: In my Drupal 7 site I have inserted an extra page in the checkout process (using a custom module), after the review page, where the customer can choose between 2 custom payment methods. My problem is that if the customer decides to leave the checkout process after reaching the custom payment page, all line items are cleared from the cart.
If he/she only goes one step back to the review page the cart is still intact. Also if he/she leaves the checkout process from the review page, the cart is not emptied, even after going back from the custom payment page. So it does not seem as though the cart is emptied when clicking Continue on the review page, after all.
Now, I need to change this behaviour so that the cart is not cleared if the visitor leaves the checkout process when on my custom payment page.
What do I need to do?
Answer: Turns out I needed to update the order state on the new checkout page. Since the user is supposed to choose a payment method on this custom page it suffised to create a simple Rule that fires on that event.
In case anyone else have the same problem (as described in the question), here it is:
<code>{ "rules_keep_order_state" : {
    "LABEL" : "Keep order state",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "commerce_order", "commerce_payment" ],
    "ON" : { "commerce_payment_methods" : [] },
    "DO" : [
      { "commerce_order_update_state" : { "commerce_order" : [ "commerce_order" ], "order_state" : "checkout" } }
    ]
  }
}
</code>

How to prevent cart from being emptied


How to alter the result of my view using filters?

Question: I have a view with 2 exposed filter.. I only want to change the result of my view when filters are used, ie if they have any value and press the button to run the filters.
I try to used the hook_views_pre_render, but doesn't work...
<code>function node_db_views_pre_render(&$view) {
   if($view->name=="demo" && $view->current_display == 'page_1' &&  $view->exposed_input['date_filter'] != NULL) {
       $get_date = $view->exposed_input['date_filter'];
       $min = $get_date['min']['value'];
       $max = $get_date['max']['value'];

         $query_power = "SELECT h.id, h.name, count(c.room_id) as busy
                         FROM table_1 c JOIN table_2 h ON c.id = h.id
                         WHERE '%s' < c.in_date OR '%s' > c.in_date
                         AND '%s' < c.out_date OR '%s' > c.out_date";

         $result = db_query($query_power, $min, $min, $max, $max);

       $items = get_rows($result); // this is a function gets the data from the sentence and makes a array.

       $view->result = $items;
   }
}
</code>
Exist other hook that can help me?..Thanks :D
Answer: you should use hook_views_query_alter, because hook_views_pre_render is called after the query is done, so you cannot influence your database request anymore.
The views documentation has been added to the Drupal api docs recently, so for more info look at:
http://api.drupal.org/api/views/docs%21views.api.php/group/views_hooks/7
or
http://views.doc.logrus.com/
Comment: So, first i use hook_views_query_alter where i get the value of my filters, then execute the query ... then use hook_views_pre_render for show the result.. ¿this is the way? Or i only use the first hook and autommatically my view show the result that i require?
Comment: You should only use one hook (hook_views_query_alter), where you can check for filters values (eg. $view->exposed_input['YOUR_FILTER_IDENTIFIER']), and then you can add conditions to your query object
Comment: @30equals.. do you have any example of this hook?. because, when i override the query... i have a fatal-error .-.


target blank direto na URL

Question: No meu site eu tenho um botão flutuante que tem uma imagem e me possibilita colocar um URL, porém, não tem a opção de fazer abrir em uma aba nova. Tem apenas o espaço para a URL.
Eu gostaria de saber se tem como fazer a função target=_blank direto na URL, tipo www.meusite.com.br/contato=_blank
Desta forma, mesmo sem ter a opção manual de abrir em uma nova aba, eu conseguiria colocar o target=_blank direto na URL e fazer abrir em uma aba nova ao ser clicado nesse link.
Existe isso?
Comment: Tente inserir: `javascript: window.open('pagina.html', '_blank')`
Comment: Pode ser com JavaScript? Existe uma infinidade de formas de fazer usando Js...
Answer: A reposta curta é não. Isso não é possível porque uma URL é requisitada através da barra de navegação o navegador faz um GET e a sua página é recarregada completamente. O que significa que para o browser já é uma "nova página".
O que você quer fazer é abrir uma nova página á partir da sua página atual. Isso pode ser feito utilizando a tag 'a' do html:
example

ou dinamicamente com javascript
window.open('http://example.com', '_blank');

Answer: Direto na url não vai ter como. A única forma possível seria você inserir um código javascript na sua página. Por exemplo, se você adicionar o código abaixo, toda vez que clicar em qualquer elemento de sua página document que seja um anchor a, ele irá abrir o link em uma nova aba.
$(document).on('click', 'a', function(e){
    e.preventDefault();
    var url = $(this).attr('href');
    window.open(url, '_blank');
});

target blank direto na URL


Tomcat ajp13 connector returns 404 for all requests

Question: I'm sure the answer is simple, but I'm tearing my hair out.
I'm rebuilding an apache httpd + tomcat site on a new Ubuntu 16 system with Apache 2.4 and Tomcat 8.5.23.
I have tomcat running and the ajp13 connector appears to be running, but requests to http://abilities.tld/ give 404.
The 404 shows up in the mod_jk.log as originating from tomcat, so it's not a simple httpd 404.
Abbreviated vhost config
<code><VirtualHost 18.104.22.168:80>
    DocumentRoot "/home/user/subdir/html"
    ServerName abilities.tld
    ServerAlias www.abilities.tld
    <Directory "/home/user/subdir/html">
            allow from all
            Options ExecCGI Includes FollowSymLinks
            AllowOverride All
            Require all granted
    </Directory>

    SuexecUserGroup user user

    JkMount /* ajp13
    #Directives to enable Apache to continue serving applications dependent on it.
    SetEnvIf Request_URI "/webmail*" no-jk
    SetEnvIf Request_URI "/mail*" no-jk
    SetEnvIf Request_URI "/awstats*" no-jk
    SetEnvIf Request_URI "/myadmin*" no-jk
    SetEnvIf Request_URI "/pgadmin*" no-jk
    SetEnvIf Request_URI "/cgi-bin*" no-jk

    #DirectoryIndex /abilities
</code>
`
Apache vhost log
188.8.131.52 - - [16/Nov/2017:14:08:18 +1100] "GET / HTTP/1.1" 404 164
Visiting http://184.108.40.206:8080/host-manager/html works fine and shows the virtual hosts
The catalina log shows the startup deployment of WARs as expected.
In server.xml
<code>     <Host appBase="/home/user/subdir/html" name="abilities.tld" unpackWARs="true" autoDeploy="true">
            <Alias>www.abilities.tld</Alias>
            <Context path="" docBase="abilities" debug="0" reloadable="true"/>
            <Logger className="org.apache.catalina.logger.FileLogger" prefix="abilities.tld" suffix=".txt" timestamp="true"/>
      </Host>
</code>
and in /var/log/apache2/mod_jk.log
<code>[Thu Nov 16 14:46:53.105 2017] [26722:140421309081472] [debug] map_uri_to_worker_ext::jk_uri_worker_map.c (1179): Attempting to map URI '/' from 1 maps
[Thu Nov 16 14:46:53.105 2017] [26722:140421309081472] [debug] find_match::jk_uri_worker_map.c (978): Attempting to map context URI '/*=ajp13' source 'JkMount'
[Thu Nov 16 14:46:53.105 2017] [26722:140421309081472] [debug] find_match::jk_uri_worker_map.c (991): Found a wildchar match '/*=ajp13'
[Thu Nov 16 14:46:53.105 2017] [26722:140421309081472] [debug] jk_handler::mod_jk.c (2823): Into handler jakarta-servlet worker=ajp13 r->proxyreq=0
[Thu Nov 16 14:46:53.105 2017] [26722:140421309081472] [debug] wc_get_worker_for_name::jk_worker.c (120): found a worker ajp13
[Thu Nov 16 14:46:53.105 2017] [26722:140421309081472] [debug] wc_get_name_for_type::jk_worker.c (304): Found worker type 'ajp13'
[Thu Nov 16 14:46:53.105 2017] [26722:140421309081472] [debug] init_ws_service::mod_jk.c (1196): Service protocol=HTTP/1.1 method=GET ssl=false host=(null) addr=184.108.40.206 name=abilities.tld port=80 auth=(null) user=(null) laddr=22.214.171.124 raddr=220.127.116.11 uaddr=188.8.131.52 uri=/
[Thu Nov 16 14:46:53.105 2017] [26722:140421309081472] [debug] ajp_get_endpoint::jk_ajp_common.c (3351): (ajp13) acquired connection pool slot=0 after 0 retries
[Thu Nov 16 14:46:53.106 2017] [26722:140421309081472] [debug] ajp_marshal_into_msgb::jk_ajp_common.c (684): (ajp13) ajp marshaling done
[Thu Nov 16 14:46:53.106 2017] [26722:140421309081472] [debug] ajp_service::jk_ajp_common.c (2586): processing ajp13 with 2 retries
[Thu Nov 16 14:46:53.106 2017] [26722:140421309081472] [debug] jk_shutdown_socket::jk_connect.c (932): About to shutdown socket 37         [127.0.0.1:50968 -> 127.0.0.1:8009]
[Thu Nov 16 14:46:53.106 2017] [26722:140421309081472] [debug] jk_is_input_event::jk_connect.c (1406): error event during poll on socket 37 [errno=107] (event=24)
[Thu Nov 16 14:46:53.106 2017] [26722:140421309081472] [debug] jk_shutdown_socket::jk_connect.c (1016): Shutdown socket 37 [127.0.0.1:50968 -> 127.0.0.1:8009] and read 0 lingering bytes in 0 sec.
[Thu Nov 16 14:46:53.106 2017] [26722:140421309081472] [debug] ajp_send_request::jk_ajp_common.c (1639): (ajp13) failed sending request, socket 37 is not connected any more (errno=0)
[Thu Nov 16 14:46:53.106 2017] [26722:140421309081472] [debug] ajp_abort_endpoint::jk_ajp_common.c (821): (ajp13) aborting endpoint with socket 37
[Thu Nov 16 14:46:53.106 2017] [26722:140421309081472] [debug] ajp_send_request::jk_ajp_common.c (1717): (ajp13) no usable connection found, will create a new one, detected by connect check (1), cping (0), send (0).
[Thu Nov 16 14:46:53.106 2017] [26722:140421309081472] [debug] jk_open_socket::jk_connect.c (675): socket TCP_NODELAY set to On
[Thu Nov 16 14:46:53.106 2017] [26722:140421309081472] [debug] jk_open_socket::jk_connect.c (799): trying to connect socket 37 to 127.0.0.1:8009
[Thu Nov 16 14:46:53.107 2017] [26722:140421309081472] [debug] jk_open_socket::jk_connect.c (825): socket 37 [127.0.0.1:58717 -> 127.0.0.1:8009] connected
[Thu Nov 16 14:46:53.107 2017] [26722:140421309081472] [debug] ajp_connection_tcp_send_message::jk_ajp_common.c (1267): sending to ajp13 pos=4 len=704 max=8192
......
[Thu Nov 16 14:46:53.172 2017] [26722:140421309081472] [debug] ajp_unmarshal_response::jk_ajp_common.c (739): (ajp13) status = 404
</code>
Where else can I look to figure out why tomcat is giving 404?
Thanks
Answer: So the answer was that the tomcat vhost was failing to load and the web request was being served by the localhost (default) vhost. Hence the 404.


Filepath in jsp

Question: Following are 2 (MSDS,Shell-CCL) folders in my application
MSDS-->WebContent-->cclFooter.jsp
Shell-CCL-->WebContent-->jsps-->cclTNCDetails.jsp
Now i am currently in cclFooter.jsp
I am trying to access cclTNCDetails.jsp in Shell-CCL folder
I have tried the following but none of them worked. Please explain how to do
<a herf="javascript:openLinkFooter('<%= contextpath1%>/../Shell-CCL/jsps/cclTNCDetails.jsp');">Exa

where the context path takes me to root/MSDS folder.
Exa

But none of them helped. Pls tell me how to navigate to the given file
Comment: Are these both folders under ROOT folder? I mean under same context or different context.
Comment: Put a `../` in front of `<%= context...` maybe...
Comment: @ParkashKumar I am new to this. I will try to explain what it is. So when i am in cclTNCDetails.jsp, the context of the application is www.cclportal-tst.shell.com/Shell-CCL. When i am working in cclFooter.jsp, the context will be  www.cclportal-tst.shell.com/MSDS. So i thinks MSDS and Shell-CCL are like siblings. Pls correct me if i am wrong
Answer: Try this:
Exa

I am not sure, what about the WebContent here.

Filepath in jsp


Abrir automaticamente o meu programa c#

Question: Boas,
Criei um programa para converter uns formatos de ficheiros.
Agora no windows, pus por default, que sempre que eu clicar 2x no ficheiro *.csr abrir o meu programa.
Como faço programaticamente, sempre que o utilizador abrir um ficheiro *.csr, abrir o meu programa, e colocar automaticamente no OpenFileDialog o caminho desse ficheiro?
Obrigado.
Neste momento tenho um botão para abrir ficheiro: CSR ou CNF.
Depois o código que tenho é este:
<code> private void button2_Click(object sender, EventArgs e)
    {
        string arquivoCNF = VariaveisGlobais.cnf;
        string arquivoCSR = VariaveisGlobais.csr;

        ExecutarComandoSSL(arquivoCNF, arquivoCSR);

        textBox3.Text = ("");
        button2.Enabled = false;
        button3.Enabled = false;
        button4.Enabled = false;
        return;
    }

 //Variáveis
    public static class VariaveisGlobais
    {
        public static string CNF { get; set; }
        public static string CSR { get; set; }
        public static string cnf { get; set; }
        public static string csr { get; set; }
    }
</code>
O que estou pedindo é:
Se o utilizador NÃO ABRE o programa, mas abre directamente um CSR ou CNF, ele corre esse código.
Comment: No seu programa ou no VisualStudio? Voce criou um programa que le os ficheiros?
Comment: Não entendi @GuilhermeNascimento...
Comment: Voce esta criando um software que lê os arquivos ou você quer configurar o visualstudio? Voce disse "Criei um programa" isto da a entender que voce criou um programa que lê arquivos .csr, entao o seu problema nao e com o visualstudio e sim com o seu programa. Talvez a resposta do resposta do OnoSendai lhe ajude. Mas o que me parece e que voce quer deixar pre selecionado no OpenDialog, no entanto isto nao esta claro ainda.
Comment: @GuilhermeNascimento é isso mesmo amigo. Eu quero que ai abrir o .csr o programa corra o código que eu tenho.
Quando se abre o meu programa tem um botão para abrir o ficheiro CSR e fazer a leitura.
O que eu quero é que a pessoa quando abre um ficheiro CSR (sem o programa) ele abra o programa sozinho e corra o código.
Comment: Então poste o que fez ate agora, por favor leia esta orientação: http://pt.stackoverflow.com/help/mcve
Comment: @GuilhermeNascimento editado!
Comment: Não tem como correr o código diretamente, o que vai correr é o código compilado em um aplicativo. Você quer criar um aplicativo que no windows o tal aplicativo fique definido como padrão pra tal extensão?
Answer: No Visual Studio:
<code>Project Properties > Publish > Options > File Associations
</code>
Você verá a seguinte interface:

Informe a extensão desejada e o programa associado.
Utilizando a publicação ClickOnce o instalador criará o vínculo entre a extensão e o programa automaticamente.

Abrir automaticamente o meu programa c#


Como manter uma sincronização em tempo real?

Question: Estou elaborando um app e já tenho o tratamento do banco de dados finalizado.
Mas surgiu uma dúvida de como posso criar um sistema de sincronização em tempo real do banco local do app com o banco do servidor remoto.
Se alguém souber explicar ou tiver um tutorial relacionado fico grato.
Comment: [Aqui](http://developer.couchbase.com/mobile/develop/guides/couchbase-lite/native-api/replication/index.html) fala algo sobre esse processo.
Comment: Obrigado @"Mechanic, pelo que vi é um serviço de backend que oferece a ferramenta de sincronização em tempo real, mas o codido de exemplo deles e a explicação é boa. Obrigado.
Comment: Vamos imaginar que vc tem um tablet com um BDD e um servidor com um BDD. Se vc quer sincronizar os 2, por exemplo cada 2 horas, tudo bem, isso parece lógico. Mas se vc quer sincronizar 'em tempo real', porque ter um BDD "local"??? Precisa somente enviar or dados da tablet pelo servidor e salvar os dados na BDD do servidor. Como no web: um servidor com a BDD e varias clientes que não tem BDD mas que enviam os dados no servidor. Não?
Comment: Sim eu entendi a logica que vc propôs. Mas como oq falo é de uma estrutura onde o banco comunica e envia ao app cliente que existem novos dados e o envia de forma automatizada.
Answer: Depois de algumas pesquisas na internet, e graças ao amigo @QMechanic73, verifiquei que esta é uma ferramenta bastante usada em banco de dados NOSQL.
 Que são sistemas de armazenamentos que não usam SQL(ou sistemas de relacionamento por tabelas).
O link apresentado por @Mechanic73 leva ao site do CoachDB onde possui um tutorial explicando sobre o serviço de sincronização e com um exemplo de uso.
Link CoachDB.
Obrigado.


Generative adverserial network for class imbalance

Question: Beaulieu-Jones et al. (2017) just published a new paper on generating clinical data with Generative Adverserial Nets.  Many clinical outcomes have very low prevalence.  My question: could GANs, like SMOTE, be used to augment the less prevalent class?
Answer: I think that the answer might be no.  There is a fixed amount of information in a dataset and a theoretically optimal classifier would use all of that information.  The GAN trained on the dataset does not actually create new information, it just samples from the distribution that best represents the original dataset.  So, new examples generated by the GAN would not increase the net information in the dataset and therefore would not be useful for class imbalance.
It might be useful for regularization (eg, dataset augmentation), but I don't think that this would be necessary with an optimally trained classifier.


ValueAccessor is empty in the custom binding (knockoutjs & googlemap)

Question: I have a view model which get  places via ajax request. These places are coming, but when I try to use it in the custom binding google map, valueAccessor is empty.
Can you explain to me what  wrong I'm doing?

var  MapViewModel  = function(){

 var self = this;
    var yelp = new YelpDataProvider();
    var categories = [{"id": 1,"name" : "Bars"}, {"id": 2,"name" : "Gyms"}];
    var addresses = [];
 self.places = ko.observableArray();
 self.selectCategory  = ko.observable();

    self.selectCategory.subscribe(function(category) {
     var _filtered = addresses;

     if(typeof category != "undefined")
      _filtered = _.where(_filtered, {'categoryId': category});

        yelp.getDataForPlaces(_filtered).then(function(place){
   self.places(place);
  });
    });

 yelp.getDataForPlaces(addresses).then(function(place){
  self.places(place);
 })

}

ko.bindingHandlers.googlemap = {
    init: function (element, valueAccessor) {
     debugger;
        var value = ko.utils.unwrapObservable(valueAccessor());
        console.log(value);
        console.log(valueAccessor());
        var centerPoint = new google.maps.LatLng(value[0].location.coordinate.latitude,
             value[0].location.coordinate.longitude);

    var myWrapper = $("#wrapper");
    $("#menu-toggle").click(function(e) {
      e.preventDefault();
      $("#wrapper").toggleClass("toggled");
      myWrapper.one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(e) {
         // code to execute after transition ends
         google.maps.event.trigger(map, 'resize');
      });
    });

    // create the map
    var myOptions = {
      zoom: 5,
      center: centerPoint,
      mapTypeControl: true,
      mapTypeControlOptions: {
        style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
      },
      navigationControl: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP
   }

    var map = new google.maps.Map(element, mapOptions)

    var infowindow = new google.maps.InfoWindow({
    size: new google.maps.Size(150, 50)
  });

  google.maps.event.addListener(map, 'click', function() {
   infowindow.close();
  });

  _.each(value,function(place){
   var _point = new google.maps.LatLng(place[0].location.coordinate.latitude,
                 place[0].location.coordinate.longitude);
    var marker = createMarker(point, place.businesses[0].id,
     businesses[0].snippet_text)
  });

  google.maps.event.addListener(map, 'click', function() {
       infowindow.close();
      });

  google.maps.event.addDomListener(window, 'load', initialize);

    }
};

ko.applyBindings(MapViewModel);

Comment: You are not creating your view model correctly, the `new` keyword is missing. It should look like `ko.applyBindings(new MapViewModel());`
Comment: Anyway, problem isn't solving.
Answer: I am not sure why aren't you able to access "places", but below is another way you can try accessing it inside of your binding handler -

Update the binding in your html to pass in the viewModel -

Include "allBindingAccessors" as a parameter to your handler -
ko.bindingHandlers.googlemap = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        var viewModel = allBindingsAccessor().viewModel;
        var value = viewModel.places();
        // Do more stuff
    }
}

Hope this works :P


Neg Binomial and the Jeffreys' Prior

Question: I'm trying to obtain the Jeffreys' prior for a negative binomial distribution. I can't see where I go wrong, so if someone could help point that out that would be appreciated.
Okay, so the situation is this: I am to compare the prior distributions obtained using a binomial and a negative binomial, where (in both cases) there are $n$ trials and $m$ successes. I get the right answer for the binomial case, but not for the negative binomial.
Let's call the Jeffreys' prior $\pi_J(\theta)$. Then,
$$
\pi_J(\theta)\propto [I(\theta)]^{1/2}.
$$
Under the regularity conditions (fulfilled as we are dealing with the exponential family),
$$
I(\theta)=-E\left(\frac{\partial^2 \log L(\theta|x)}{\partial \theta^2}\right)
$$
where for the negative binomial $n$ is $x$ in the above expression (the total number of successes $m$ is fixed, $n$ is not). The distribution --I think-- is
$$
p(m|\theta)\propto\theta^m(1-\theta)^{n-m}
$$
since $\theta$ is defined as the probability of success and $m$ is the number of successes. This is also the likelihood, since $m$ is a scalar and not a vector. Hence,
$$
L(\theta|n)\propto\theta^m(1-\theta)^{n-m}\\
\log L(\theta|n)=m\log\theta +(n-m)\log (1-\theta)\\
\frac{\partial\log L(\theta|n)}{\partial \theta}=\frac{m}{\theta}-\frac{n-m}{1-\theta}\\
\frac{\partial^2\log L(\theta|n)}{\partial \theta^2}=-\frac{m}{\theta^2}-\frac{n-m}{(1-\theta)^2}
$$
so the Fisher information is
$$
I(\theta)=-E\left(\frac{\partial^2\log L(\theta|n)}{\partial \theta^2}\right)=\frac{m}{\theta^2}+\frac{E(n)-m}{(1-\theta)^2}=\frac{m}{\theta^2}+\frac{\frac{m\theta}{1-\theta}-m}{(1-\theta)^2}\\
=\frac{m(1-\theta)^2+\frac{m\theta^3}{(1-\theta)}-m\theta^2}{\theta^2(1-\theta)^2}=\frac{m(1-2\theta)+\frac{m\theta^3}{(1-\theta)}}{\theta^2(1-\theta)^2}\\
=\frac{m(1-2\theta)(1-\theta)+m\theta^3}{\theta^2(1-\theta)^3}=\frac{m(1-3\theta+2\theta^2+\theta^3)}{\theta^2(1-\theta)^3}\\
\propto\frac{1-3\theta+2\theta^2+\theta^3}{\theta^2(1-\theta)^3}
$$
This, however, does not give me the correct answer. The correct answer is
$$
\pi_J(\theta)\propto \frac{1}{\theta(1-\theta)^{1/2}}
$$
which means that the Information I get should be
$$
I(\theta)=\frac{1}{\theta^2(1-\theta)}
$$
since the prior should be proportional to the square root of the information.
Can anyone find any mistakes? I wouldn't be surprised if I screwed something up with the set up of the distribution (successes vs failures with their respective probabilities, etc).
I used the expected value from Wikipedia and I know the correct answer from here (page 3).
Answer: The problem arises because the negative binomial distribution can be parametrized differently. As a consequence, the expectation differs for different parametrizations. The way you have specified the negative binomial distribution, the expectation of $n$ is $E(n) = m/\theta$ (e.g. see here on page 3). With that, the Fisher information simplifies to $$I(\theta) = m\left(\frac{1}{\theta^2(1-\theta)}\right)$$
Thus the Jeffreys' prior is
$$
\pi_{J}(\theta) = |I(\theta)|^{1/2}\propto \theta^{-1}(1-\theta)^{-1/2}
$$
as you already noted.
Comment: Terrific! That's very helpful and also an excellent reference as it goes through the very problem I was struggling with. Thank you!
Comment: Archived version of the (now dead) link in the answer: http://web.archive.org/web/20180219125451/https://www.ida.liu.se/~732A46/2012/OtherMaterial/SolutionsExam1.pdf
Comment: I've found a solution that uses another formulation, see [here](http://www2.isye.gatech.edu/~brani/isyebayes/bank/Quiz71.pdf). Glad I could help. You're welcome.

Neg Binomial and the Jeffreys' Prior


RHEL 6 Upstart User Jobs

Question: Does RHEL6 support upstart user jobs?
I modified /etc/dbus-1/system.d/Upstart.conf and added a policy section for my username.  I then created ~/init.d/userjob.conf.
When I do inictrl list it doesn't show up.
Does RHEL6 support this? If so how do I debug it?
Answer: User jobs are supported from version 1.3 of Upstart.
See:
http://upstart.ubuntu.com/cookbook/#user-job
RHEL6 (or CentOS 6) use version: 0.6.5.

RHEL 6 Upstart User Jobs


How to check the output gradient by each layer in pytorch in my code?

Question: I am working on the pytorch to learn.
And  There is a question how to check the output gradient by each layer in my code.
My code is below
#import the nescessary libs
import numpy as np
import torch
import time

# Loading the Fashion-MNIST dataset
from torchvision import datasets, transforms

# Get GPU Device

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

# Define a transform to normalize the data
transform = transforms.Compose([transforms.ToTensor(),
                                    transforms.Normalize((0.5,), (0.5,))
                                                                   ])
# Download and load the training data
trainset = datasets.FashionMNIST('MNIST_data/', download = True, train = True, transform = transform)
testset = datasets.FashionMNIST('MNIST_data/', download = True, train = False, transform = transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size = 32, shuffle = True, num_workers=4)
testloader = torch.utils.data.DataLoader(testset, batch_size = 32, shuffle = True, num_workers=4)

# Examine a sample
dataiter = iter(trainloader)
images, labels = dataiter.next()

# Define the network architecture
from torch import nn, optim
import torch.nn.functional as F

model = nn.Sequential(nn.Linear(784, 128),
                      nn.ReLU(),
                      nn.Linear(128, 10),
                      nn.LogSoftmax(dim = 1)
                     )
model.to(device)

# Define the loss
criterion = nn.CrossEntropyLoss()

# Define the optimizer
optimizer = optim.Adam(model.parameters(), lr = 0.001)

# Define the epochs
epochs = 5

train_losses, test_losses = [], []

# start = time.time()
for e in range(epochs):
    running_loss = 0

    for images, labels in trainloader:
    # Flatten Fashion-MNIST images into a 784 long vector
        images = images.to(device)
        labels = labels.to(device)
        images = images.view(images.shape[0], -1)

    # Training pass
        optimizer.zero_grad()

        output = model.forward(images)
        loss = criterion(output, labels)

        loss.backward()

#         print(loss.grad)

        optimizer.step()

        running_loss += loss.item()

    else:
        print(model[0].grad)

If I print model[0].grad after back-propagation, Is it going to be the output gradient by each layer for every epoches?
Or, If I want to know the output gradient by each layer, where and what am I should print?
Thank you!!
Thank you for reading
Answer: Well, this is a good question if you need to know the inner computation within your model. Let me explain to you!
So firstly when you print the model variable you'll get this output:
Sequential(
  (0): Linear(in_features=784, out_features=128, bias=True)
  (1): ReLU()
  (2): Linear(in_features=128, out_features=10, bias=True)
  (3): LogSoftmax(dim=1)
)

And if you choose model[0], that means you have selected the first layer of the model. that is Linear(in_features=784, out_features=128, bias=True). If you will look at the documentation of torch.nn.Linear here, you will find that there are two variables to this class that you can access. One is Linear.weight and the other is Linear.bias which will give you the weights and biases of that corresponding layer respectively.
Remember you cannot use model.weight to look at the weights of the model as your linear layers are kept inside a container called nn.Sequential which doesn't has a weight attribute.
So coming back to looking at weights and biases, you can access them per layer. So model[0].weight and model[0].bias are the weights and biases of the first layer. And similarly to access the gradients of the first layer model[0].weight.grad and model[0].bias.grad will be the gradients.
Comment: This is a perfect answer that I want to know!! Awesome, thanks a lot, and what if I would love to know the "output" gradient for each layer?
Comment: If you mean gradient of each perceptron of each layer then `model[0].weight.grad` will show you exactly that (for 1st layer). And be sure to mark this answer as accepted if you like it.
Comment: What you mention is parameter gradient I think(taking `y = wx + b` parameter gradient is `w` and `b` here)? Does the output gradient refer to the gradient of `x`?
Comment: If you have `y=ln(x)` (or any other function per se) then the output gradient of y also changes with the value of x.. don't you think?
Comment: Does these greadients represent the value of last forward calculating? Can we get the gradients of each epoch?


Dificuldade em chamada XMLHttpRequest com JavaScript puro

Question: Estou com dificuldade a uns dias, sou iniciante e mesmo lendo a documentação as vezes aplicar não é tão simples quanto parece, entendo que me falta exp para compreender.
meu problema: estou usando a api google maps JavaScript e uma API que eu fiz para carregar no mapa os pontos (marcadores). Porém, as vezes carrega o mapa e não carrega os pontos, consigo ver isso pois usei o console.log(marcadores.length) para verificar e ele vem zerado, aí eu atualizo a página e tudo carrega corretamente, mas também pode carregar vazio novamente.
Alguém poderia por favor me dar uma luz?
Eu gostaria de chamar a função initMap() somente após carregar o array com os dados que vieram da API do meu DB, como proceder?
Segue abaixo código que utilizo para carregar os dados da api:
var marcadores = [];
function carregaPosicoes(){
    var request = new XMLHttpRequest();
    request.open("GET", "http://localhost:5000/Truck/Veiculos", true);

    request.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        const data = JSON.parse(this.response);
        data.forEach(veiculo => {
            marcadores.push(veiculo);
            });
        };
    };
    initMap();
    request.send();

};

Comment: :D foi quase instantaneo @CmteCardeal, pra não perder a piada, eu fui mais "Pontual" ;)
Comment: @RicardoPontual hahahahah [hahaha](https://www.youtube.com/watch?v=il9CTqbvOcc). Pontuando que a pergunta tem mais haver com `XMLHttpRequest` do que async/await
Comment: pode mover `initMap();` para dentro da function `onreadystatechange`. Aqui o conceito é quando executa a linha `request.open` o fluxo do código já segue para a linha a seguir que é  `request.onreadystatechange`, porém essa linha espera o retorna da API, uma *promise* como chamamos, então como ainda não há nada, segue para próxima linha que é o `initMap()` e ai ainda não tem dados, pq a chamada ainda não retornou, por isso precisa mover essa linha para dentro da function
Comment: Pelo o que eu entendi, voce poderia chamar a funcao `init` dentro do `if`, após o `forEach`. Testou dessa forma?
Comment: @RicardoPontual 4 segundos mais rápido do que eu XD
Comment: A sua pergunta não tem relação com _async/await_. Tem mais haver com o objeto `XMLHttpRequest`, então eu editei o titulo da pergunta.
Comment: @CmteCardeal, obrigado pela edição, é que quando eu pesquisava sobre "esperar carregar objeto e executar função" sempre caia em async/await. Vou testar as sugestões aqui e volto para comentar o que funcionou. muito obrigado a todos até o momento.
Comment: adicionei uma responsta para demontrar o que o @Piovezan respondeu
Answer: Entenda que essa function() abaixo é uma "callback" (você não manda chamar diretamente, só passa a referência da função para alguém que irá mandar chamá-la quando for o momento apropriado para isso) e está sendo declarada agora mas só irá ser chamada pelo objeto XMLHttpRequest quando ocorrer o evento ready state change, ou seja, num momento posterior a quando foi declarada (quando o sua requisição (request) para a API do servidor, que leva um tempo para ocorrer e o código não pode ficar esperando, tiver chegado ao fim, por exemplo), enquanto que a initMap() já está sendo chamada logo após essa declaração e antes da requisição ocorrer.
request.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        const data = JSON.parse(this.response);
        data.forEach(veiculo => {
            marcadores.push(veiculo);
            });
        };
    };
    initMap();

Tentando fazer um tradução, o nome "onreadystatechange" significa "quando ocorrer a mudança no estado 'pronto', ou para o estado 'pronto' (me chame)" e indica qual função vai ser chamada quando ocorrer esse evento. "on<nome-do-evento>" é uma nomenclatura comum para essa situação de código que reage a eventos.
Portanto jogando a initMap() para ser chamada dentro dela deve resolver, pois passará a chamar quando o evento ocorrer e logo após isso ter populado o mapa:
request.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        const data = JSON.parse(this.response);
        data.forEach(veiculo => {
            marcadores.push(veiculo);
            });
        };
       initMap();
    };

Para saber mais:

O que é um evento?
O que é callback?
Answer: Para complementar a resposta do @Piovezan, vou montar um exemplo simples demonstrando o fluxo do programa quando se tem um callback ou promise.
Esse pedaço de programa escreve no console os pontos por onde passa, 1 em 1. Repare que, ao executar a orden não é a mesma, porque foi criada uma function para gerar uma espera de 1s, e simula uma chamada assíncrona, por exemplo uma API:

/////////////// 1
console.log("ponto 1");
var dados = {};

/////////////// 2
console.log("ponto 2");
sleep(1000).then(() => {
    /////////////// 3
    console.log("ponto 3");
    dados.algumaCoisa = "oi";

    /////////////// 4
    console.log("ponto 4");
    console.log("dados.algumaCoisa=" + dados.algumaCoisa);
});

/////////////// 5
console.log("ponto 5");
console.log("dados.algumaCoisa=" + dados.algumaCoisa);

function sleep (time) {
  return new Promise((resolve) => setTimeout(resolve, time));
}

/////////////// 6
console.log("ponto 6");

O resultado desse código é:
ponto 1
ponto 2
ponto 5  <- aqui seguiu o fluxo, pulou os dois pontos que estão na função de callback
dados.algumaCoisa=undefined  <- algumaCoisa ainda não foi definido
ponto 6
ponto 3 <- após 1s, entra no callback
ponto 4
dados.algumaCoisa=oi <- agora algumaCoisa tem valor :)

Comment: Pelo pouco que entendo de JS, Promises são um conceito bem análogo a Futures do Java. Ambos retornam uma referência para algo que ainda não chegou a ocorrer, ter essa referência agora não é muito útil mas por outro lado é bastante útil poder usá-la para definir qual vai ser a callback que vai ser chamada após essa ocorrência (em geral para lidar com o resultado retornado pela ocorrência, como dados trazidos de uma requisição remota). É uma forma de programar reatividade a eventos. Mas acho que você deu uma pequena volta no exemplo, a callback poderia ter sido passada direto para setTimeout().
Comment: Mas sei que fez isso para ilustras as Promises, o resultado só fica mais complicado de entender (mas fica mais fácil quando você acompanha o código na ordem que os comentários indicam). :) A utilidade é demonstrada quando você observa que o código que reage ao evento está frequentemente vinculado ao momento em que esse evento é chamado, então apesar de ocorrerem em momentos distintos devem ficar juntos a fim de compartilharem o mesmo escopo.


Class loading Exception in java reflection

Question: I have selected a jar file using file selector, then loaded all the classes in the jar file using java reflection. Some classes has dependency on another jar file.
But when I try to get method of class then following exception is thrown because this class has a import statement import com.thoughtworks.xstream.XStream; and XStream class is defined in another jar file.
Exception in thread "main" java.lang.NoClassDefFoundError: com/thoughtworks/xstream/io/HierarchicalStreamDriver
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2365)
    at java.lang.Class.privateGetPublicMethods(Class.java:2488)
    at java.lang.Class.getMethods(Class.java:1406)
    at com.axway.xtp.testgenerator.templatewizard.MethodSelectionWizardUI.updateListofMethods(MethodSelectionWizardUI.java:744)
    at com.axway.xtp.testgenerator.templatewizard.MethodSelectionWizardUI$7.widgetSelected(MethodSelectionWizardUI.java:474)
    at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:90)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:66)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:928)

I wanted to know that is there any way to prevent the dependency class or jar file to be loaded using java reflection. Following are the piece of code I am using to load classes.
URLClassLoader ucl = new URLClassLoader(new URL[] { new URL("file:" + codeRepository) });
JarFile jarFile = new JarFile(new File(codeRepository));
Enumeration enm = jarFile.entries();
while (enm.hasMoreElements()) {
  JarEntry entry = ((JarEntry) enm.nextElement());

  if (entry.getName().endsWith(".class")) {
    String fullClassNameWithPath = entry.getName();
    String fullyClassifiedClassName = fullClassNameWithPath
        .replace('/', '.');

    try {
      Class c = ucl.loadClass(fullyClassifiedClassName.substring(
          0, fullyClassifiedClassName.indexOf(".class")));
      String className = c.getPackage().getName() + "."
          + c.getSimpleName();
      listClasses.add(className);
    } catch (Exception e) {
      continue;
    } catch (Throwable t) {
      continue;
    }
  }
}

Comment: Not sure this is possible.  You'll have to load the dependency libraries as well.
Answer: Well, if your application depends on that class, you most definitely need to have the jar containing it (or provide an alternative path containing the package+class) on the classpath.
Answer: As part of the classloading process, any classes which the class you want to load depends upon will also be loaded.
I don't think there's anything you can do about that.


when using async/await with mongoose i get an error

Question: I want to get an ObjectId from my mongo database, but with async / await, i get an error:
ERROR [ExceptionsHandler] Query was already executed: Role.findOne({ name: { '$in': [ 'admin' ] } })
MongooseError: Query was already executed: Role.findOne({ name: { '$in': [ 'admin' ] } })
I want to call mongoose asynchronously because my userRoles array is empty when i want to use it after this code block;
here's the code
role.guard.ts
<code>  [...]
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const userRoles: string[] = [];
    let accessRoleId = '';

    let isAuthorized = false;
    const accessRole = this.reflector.get<string[]>('roles', context.getHandler());
    if (!accessRole) {
      return true;
    }
    const request = context.switchToHttp().getRequest();
    const user = request.user;

    for (let i = 0; i < user.roles.length; i++) {
      const role: string = user.roles[i]
      userRoles.push(role);
    }

    const findId = await this.RoleModel.findOne({ 'name': accessRole }
    , (err, role) => {
    if (err){
        console.log(err);
    }
    else {
        console.log('role ->', role._id.valueOf()); // role -> 621268634b936e81528bc220
        accessRoleId = role._id.valueOf();
    }
  });

  [...]

}
</code>
Any idea? Thanks!
Answer: You either use callbacks or promises.
Callbacks:
<code> const findId = this.RoleModel.findOne({ 'name': accessRole }
    , (err, role) => {
    if (err){
        console.log(err);
    }
    else {
        console.log('role ->', role._id.valueOf()); // role -> 621268634b936e81528bc220
        accessRoleId = role._id.valueOf();
    }
</code>
Promises:
<code> try {
     const role = await this.RoleModel.findOne({ 'name': accessRole });
     console.log('role ->', role._id.valueOf()); // role -> 621268634b936e81528bc220
     accessRoleId = role._id.valueOf();
 } catch(err) {
     console.log(err);
 }
</code>


Find a function f(n) such that T(n) is $\Theta(n \cdot log(n)) $

Question: Find a function f(n) such that $ T(n)=16 \cdot T(\frac{n}{4}) + f(n) = \Theta(n \cdot log(n)) $
Also, another section of the question is where $T(n) = \Theta(n^{2})$
I've tried using the master method in reverse, but have failed to accomplish anything.
Any ideas?
EDIT!
My apologies! I have just discovered that some of the questions were meant to be unsolvable, the matter is understood then. Thank you all for your guidelines!
Comment: Unless there is some typo in what you wrote (or I made a mistake in checking it),  "the Master Theorem in reverse" does not look like it could help here. Note that you have $a=16$ and $b=4$, so that $\log_b a = 2$. Looking through cases [$1$ and $2$ of the theorem](https://en.wikipedia.org/wiki/Master_theorem#Case_2), they will not give you what you want:
- Case 1 would give you $\Theta(n^c)$ for some $c< 2$
- Case 2 would give you $\Theta(n^2 \log^k n)$ for some $k \geq 0$
- Case 2 would give you $\Theta(f(n))$ but for $f(n) = \Omega(n^{2+\epsilon})$, so eventually $T(n) = \omega(n\log n)$.
Comment: Are you certain it shouldn't read $n^2\log n $?
Comment: Very certain about it sir.
And the reason being another question that asks about $n^{2}log(n)$
Answer: This will not be possible. Notice that under the (very natural) assumption that $f\geq 0$, then  you get
$$
T(n) \geq 16 T\!\left(\frac{n}{4}\right)
$$
so that $T(n) \geq T^\prime(n)$ where $T^\prime$ is defined by the same initial conditions as $T$ and satisfies
$$
T^\prime(n)  = 16 T^\prime\!\left(\frac{n}{4}\right)
$$
Not, solving this last recurrence (e.g., via the Master theorem, although in this case it is overkill) results in $T^\prime(n) = \Theta(n^2)$. Therefore, we get $T(n) = \Omega(n^2)$, ruling out the possibility that $T(n) = \Theta(n\log n)$.

Note that getting $T(n) = \Theta(n^2\log n)$, however, is possible, so it may have been a typo.


Cone with height $9$ cm and radius $3$ cm is filled at a rate of $1.2~\text{cm}^3$. Find the rate of change when $h=3$.

Question: A cone with radius $3$ cm and height $9$ cm is filled with water at a rate of $1.2~\text{cm}^3$. Find the rate of change of the height of the water when the height of the water is $3$ cm.
I differentiated both sides to get $$\frac{dV}{dt}= \frac{1}{3} \pi \cdot 2(3)~\frac{dh}{dt}$$ Solving for $dh/dt$ I got $5.23599$. My textbook says to use similar triangles but I didn't, I am wondering if there is another way to solve of the rate of change of the height of the water at $h=3$?
Comment: The reason you are supposed to use similar triangles is to express the volume as a function of the height of the cone before you differentiate, assuming that you wish to find the rate at which the height of  the water is changing, which you have not explicitly stated.
Comment: I assume you meant to write the rate in cubic centimeterrs per second, or per millsecond, or ... some time unit.
Comment: This [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) explains how to use MathJax.
Comment: Yes, the rate a which the height of the water is changing is what the question asks for. But when i use similar triangles I get r=1 because r/3=3/9 but in my textbook it has h/2 so you can eliminate r from the volume equation.
Comment: It should be $r/h = 3/9 \implies r = h/3$.
Answer: $$ V =\dfrac{\pi}{3}r^2 h $$
Note that there are two terms when you differentiate a product.
$$ \dfrac{dV}{dt} =\dfrac{\pi}{3} (2r\dfrac{dr}{dt} h + r^2 \dfrac{dh}{dt})\tag1$$
If $\alpha $ is semi-vertical angle (constant) of cone then by similar triangles of differential growths $(dr,dh)$ and quotient rule differentiation
$$\dfrac{dr/dt}{dh/dt} =\dfrac{r}{h}= \tan \alpha \tag2$$
I assume you have been asked to use similar triangles in order to appreciate that there is proportion between $(r,h)$ and their differentials $ (dr,dh)$ as shown.
Plug into (1) for $\dfrac{dr}{dt}$ from (2) as other quantities are known, in order to find out $\dfrac{dh}{dt}$.
To find $dV/dt$ $ (r=1,h=3) $ .. should be finally plugged into (1)
alternatively from the above we can write $r$ items into $h$ items to directly obtain $ ( t= \tan \alpha) $
$$ \dfrac{dV}{dt}=\frac{\pi}{3}(2ht\dfrac{dh}{dt} th+h^2t^2\dfrac{dh}{dt}) =\pi h^2 t^2\dfrac{d h}{dt} =\pi r_{max}^2 \dfrac{dh}{dt}= \pi \dfrac{dh}{dt};\,\, dh/dt= \frac{1.2}{\pi} \tag3 $$
EDIT1:
Using the disc method of finding differential volumes for integration we have at start as commented by Ross Millikan:
$$ dV = A dh =\pi r^2 dh,\, (dh/dt) = (dV/dt)/(\pi r^2) = \frac{1.2}{\pi} $$
obtained directly regardless of profile of the rotated solid. If grey shaded vessel has same top area (comparing with a conical vessel with its apex pointing down inverted) then also the same level/drain rates relation holds good. It is independent of second order volume quantities, differential triangle similarity is conceptually all built-in, what was calculated needlessly roundabout.
Answer: The volume of a right-circular cone is given by the formula
$$V = \frac{1}{3}\pi r^2h$$
The volume is a function of two variables.  If we differentiate with respect to time, we obtain
$$\frac{dV}{dt} = \frac{2}{3}\pi rh~\frac{dr}{dt} + \frac{1}{3} \pi r^2~\frac{dh}{dt}$$
We wish to solve for $dh/dt$ given $dV/dt$ and $h$.  However, we do not know $r$ or $dr/dt$.
However, we can relate $r$ and $h$ by using similar triangles to eliminate $r$ from the equation and write the volume as a function of $h$.  Consider the diagram below.

By similar triangles,
$$\frac{r}{h} = \frac{3}{9} = \frac{1}{3} \implies r = \frac{h}{3}$$
Hence, we can express $V$ as a function of $h$.
\begin{align*}
V(h) & = \frac{1}{3}\pi\left(\frac{h}{3}\right)^2h\\
     & = \frac{1}{27}\pi h^3
\end{align*}
Differentiating implicitly with respect to time yields
$$\frac{dV}{dt} = \frac{1}{9}\pi h^2~\frac{dh}{dt}$$
Since we are given $dV/dt$ and $h$, you can now solve for $dh/dt$.
If we had instead used the equation
$$\frac{dV}{dt} = \frac{2}{3}\pi rh~\frac{dr}{dt} + \frac{1}{3}\pi r^2~\frac{dh}{dt}$$
we would need to find $r$ and $dr/dt$.  To do so, we use similar triangles to obtain the relationship
$$r = \frac{h}{3}$$
which allows us to calculate $r$.  Differentiating with respect to time gives
$$\frac{dr}{dt} = \frac{1}{3}~\frac{dh}{dt}$$
We use similar triangles since we need to know the relationship between $r$ and $h$ in order to substitute for the variables in the equation relating $dV/dt$ and $dh/dt$.
Comment: How exactly did you produce your diagram? What software or tools specifically? I am interested for personal use.
Comment: @Decaf-Math  I used the [LaTeX](https://www.latex-project.org/) drawing program tikz.
Answer: Much simpler is to note that when $h=3$ cm the radius is $1$ cm.  The area of the water is then $\pi$ cm$^2$ so the rate of rise is $\frac {1.2}\pi$ cm/sec
Comment: Yes, the result only depends on the area at the moment.  If you add a volume $dV$ of water you raise the level $dV/A$.  The slope on the sides makes a second order correction.
Comment: Simpler answer yes, The main task was also to employ similar triangles.
Comment: Which I did to get the radius from the shape of the cone.
Comment: I am not sure understood this. You should get same result for a cylinder, a cone or a paraboloid bowl  of $(r,z) $ dimensions at   [ base, middle , top edge] = $  [(0,0), (1,1), (2,4)] ? $
Comment: Phew yeah ! That's how one integrates volumes of revolution by assembling differential discs, right? Thank you!
Comment: That is correct.


Operação com grande matriz

Question: Pessoal gostaria de saber como posso fazer a distância euclidiana ao quadrado entre os vetores octadimensionais de b e os que não estão em a numa super matriz como esta do exemplo.
Pensei assim e não funcionou. Alguém tem uma ideia?
Li a base toda:
a = matrix(rnorm(4177*8), ncol = 8)

só pra exemplificar peguei os 1000 primeiros:
b = a[1:1000, ]

A função tira os que são iguais e deixa os diferentes:
d = a[!apply(a, 1, function(arow) any(apply(b, 1, function(brow) all(brow==arow)))),]

distancia = t(d - b)%*%(d - b)

Mas tenho o seguinte erro:

Error in d - b : non-conformable arrays
Comment: O erro que você deveria receber não é esse. Sua mensagem de erro possui `C`, e sua matriz tem nome `c`. Além disso, não é uma boa ideia utilizar nomes de funções nativas, especialmente uma como `c()`. Você deveria receber outro erro, em virtude das matrizes `c` e `b` serem de tamanhos diferentes.
Comment: Agora que você editou, o erro já te diz o problema: Você quer subtrair matrizes de tamanhos diferentes, há algo de errado na sua matemática, e não no seu código.
Comment: Estou verificando. Muito grato!
Answer: A questão é como definir uma matriz a apropriada.
Se usar:
N=2000
a = matrix(rnorm(N*2*8), ncol = 8)
#b = a[1:N, ]
#para fazer a questão mais desafiadora pode definir b com linhas aleatórias de a
b = a[sample(2*N,N), ]

O seu problema teria solução.

Operação com grande matriz


Swift: How to pass my selected textField as a parameter through selector parameter of my UIBarButtonItem

Question: I have two text Fields and both of them invoke a date picker when they are clicked upon by the user. I have a date picker that has a done button and I want to show the time that I select from my date picker on my selected textField. So how can I pass the selected text Field as an argument in the selector parameter of my UIBarButtonItem.
Below is the whole code. Please Help. Thank you!
@IBOutlet weak var startingTimeTxt: UITextField!

@IBOutlet weak var endingTimeTxt: UITextField!

let datePickerTime = UIDatePicker()

override func viewDidLoad() {
    super.viewDidLoad()

    startingTimeTxt.delegate = self
    endingTimeTxt.delegate = self

    datePickerTime.datePickerMode = .time
}

func createDatePicker(textField: UITextField) {
    //toolbar
    let toolbar = UIToolbar()
    toolbar.sizeToFit() //will fit to full screen

    //bar done button
    let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(donePressed(textField: )))
    //remember in selector u dont want to call the method , just name it
    toolbar.setItems([doneBtn], animated: true)

    //assign toolbar
    textField.inputAccessoryView = toolbar

    //assign date picker to textfield
    textField.inputView = datePickerTime

}

 @objc func donePressed(textField: UITextField) {
    textField.text = "\(datePickerTime)"
    self.view.endEditing(true)

  }
}

//MARK: - TextField Delegate
extension NewActivityTableViewController: UITextFieldDelegate {

func textFieldDidBeginEditing(_ textField: UITextField) {

    if textField == startingTimeTxt {
        createDatePicker(textField: textField)
    }
    else if textField == endingTimeTxt {
        createDatePicker(textField: textField)
    }
 }

}

Comment: Not at all. The parameter of a target/action method must be the affected UI element (the bar button), nothing else.
Answer: You need to make it  button: UIBarButtonItem as it's what you added the selector for and inside the method access the date of the picker and use a date formatter to extract the required text and assign it to the textfield's text
let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(donePressed(_:)))

With
@objc func donePressed(_ button: UIBarButtonItem) {
  print(datePickerTime.date)
}

Also check Swift: using UIDatePicker as UITextField inputView not updating


Using Boost.Pool in VS2010 - Linker error

Question: The Boost.Pool documentation says that (emphasis mine):

The Boost Pool library is a header-only library. That means there is
  no .lib, .dll, or .so to build; just add the Boost directory to your
  compiler's include file path, and you should be good to go!

But when I try to compile code like this in VS2010 SP1:
#include <string>
#include <vector>

#include <boost\pool\pool_alloc.hpp>

int main()
{
    typedef std::basic_string<wchar_t, std::char_traits<wchar_t>,
        boost::pool_allocator<wchar_t>> PoolString;

    std::vector<PoolString> vec;
    for (int i = 0; i < 100; i++)
    {
        PoolString s(L"Some test string. ABCDEF.");
        vec.push_back(s);
    }

    // Release pool memory
    boost::singleton_pool<boost::pool_allocator_tag, sizeof(wchar_t)>::release_memory();

    return 0;
}

I got a linker error:

error LNK1104: cannot open file
  'libboost_thread-vc100-mt-gd-1_49.lib'

Is Boost.Pool documentation incorrect?
What am I missing here?
How can I use Boost.Pool?
Comment: The `boost::singleton_pool` is using a `mutex` type, which is located in the `boost::thread` library. Therefore you need to link libboost_thread.
Comment: if you look in boost\pool\detail\mutex.hpp it appears that pool lib defines its own mutex and does not refer the boost::thread lib
Comment: @MariusBucur: I'll check again, to verify my answer.
Comment: @nabulke Indeed boost::pool 1.49 uses the boost::thread, I was looking at version 1.47 which defines its own mutex (http://www.boost.org/doc/libs/1_47_0/boost/pool/detail/mutex.hpp). If linking with thread lib is not desired there is the option to use and older pool lib version.
Answer: The boost::singleton_pool is using a default mutex implementation that is located in boost::thread, which is not header only.
See the singleton_pool header quoted below for information on how to remove the dependency:

Mutex This class is the type of mutex to use to protect
  simultaneous access to the underlying Pool.   Can be any Boost.Thread
  Mutex type or boost::details::pool::null_mutex.  It is
  exposed so that users may declare some singleton pools normally (i.e.,
  with synchronization), but   some singleton pools without
  synchronization (by specifying
  boost::details::pool::null_mutex) for efficiency reasons.
  The member typedef mutex exposes the value of this template
  parameter.  The default for this  parameter is
  boost::details::pool::default_mutex which is a synonym for either
  boost::details::pool::null_mutex  (when threading support is
  turned off in the compiler (so BOOST_HAS_THREADS is not set), or
  threading support  has ben explicitly disabled with
  BOOST_DISABLE_THREADS (Boost-wide disabling of threads) or
  BOOST_POOL_NO_MT (this library only))  or for boost::mutex
  (when threading support is enabled in the compiler).
Answer: In boost/config/user.hpp:261 there is
//
// Turn threading support off if BOOST_DISABLE_THREADS is defined:
//
#if defined(BOOST_DISABLE_THREADS) && defined(BOOST_HAS_THREADS)
#  undef BOOST_HAS_THREADS
#endif

I think if you
    #define BOOST_DISABLE_THREADS
before including  it will solve it.
After you will have to manage this option into your build system for your users maybe.
Answer: From what I see the boost::pool dependency on thread lib was added in boost 1_48 (see 1.47 and 1.48
I think this is unfortunate, a better decision it would have been to use the header only lightweight mutex
You can change the pool\detail\mutex.hpp but probably it is simpler to link with the thread lib, especially if you are using other libs.


Mathematical Induction & Proof of "Twelve Days of Christmas" Formula

Question: Conjecture and prove a formula for $$\sum\limits_{i=1}^n\sum\limits_{j=1}^i j.$$ Note when $n=12$ the sum equals the total number of gifts given in the "twelve days of xmas" song.
Comment: I posted Posted Pascal's triangle, slightly more rows than needed. It's for the children.
Comment: diagonals in Pascal's triangle.
Answer: Hint:
$$\sum_{j=1}^ij=\frac{i(i+1)}{2}$$
$$\sum_{i=1}^ni^2=\frac{n(n+1)(2n+1)}{6}$$
Answer: When you're asked to make a conjecture, the first thing to do is collect some data:
$$\begin{array}{c|c|c}
n&\sum_{k=1}^nk&\sum_{k=1}^n\sum_{i=1}^ki\\ \hline
1&1&1\\
2&3&4\\
3&6&10\\
4&10&20\\
5&15&35\\
6&21&56
\end{array}$$
Where you go from here depends on what you already know. If you're familiar with Pascal's triangle and binomial coefficients, shown below in rectangular form, you might recognize the three columns of the table above as the non-zero parts of the $1,2$, and $3$ columns of Pascal's triangle.
$$\begin{array}{c|ccccc|ccccc}
n\backslash k&0&1&2&3&4&0&1&2&3&4\\ \hline
0&1&0&0&0&0&\binom00&\binom01&\binom02&\binom03&\binom04\\
1&1&1&0&0&0&\binom10&\binom11&\binom12&\binom13&\binom14\\
2&1&2&1&0&0&\binom20&\binom21&\binom22&\binom23&\binom24\\
3&1&3&3&1&0&\binom30&\binom31&\binom32&\binom33&\binom34\\
4&1&4&6&4&1&\binom40&\binom41&\binom42&\binom43&\binom44\\
5&1&5&10&10&5&\binom50&\binom51&\binom52&\binom53&\binom54\\
6&1&6&15&20&15&\binom60&\binom61&\binom62&\binom63&\binom64\\
7&1&7&21&35&35&\binom70&\binom71&\binom72&\binom73&\binom74\\
8&1&8&28&56&70&\binom80&\binom81&\binom82&\binom83&\binom84
\end{array}$$
In that case you could conjecture that
$$\sum_{k=1}^n\sum_{i=1}^ki=\binom{n+2}3$$
and then try to prove it by induction on $n$. If you're not yet acquainted with binomial coefficients and Pascal's triangle but do know formulas for the sum of consecutive integers and squares, you might realize that
$$\sum_{i=1}^ki=\frac{k(k+1)}2=\frac12\left(k^2+k\right)$$
and work from there.
Answer: =-=-=-=-=-=-=-=-=-=-=-=-=

=-=-=-=-=-=-=-=-=-=-=-=-=
I like the part in the binomial coefficients in row 14 where we get 1001, 2002, 3003 in a row. It is clear from a diagram of the Gaussian normal distribution that this happens for real numbers, but here we have actual integers. Plus it illustrates the part about certain elements being divisible by primes, including some in later rows, in this case primes 7,11,13, the 7 shows up because 14 = 2 * 7.
Anyway, as I said, look carefully at the diagonals.
Answer: The lyrics for the song The Twelve Days of Christmas may be stated in mathematical form as follows:
$$\sum_{n=1}^{12}\left(g(n)+\sum_{i=1}^n f(n+1-i)\right)$$
where
$g(n)=$ On the $n$-th day of Christmas my true love sent to me
$f(1)   \;\ =$   A partridge in a pear tree
$f(2)   \;\ =$   Two turtle doves and
$f(3)   \;\ =$   Three french hens
$f(4)   \;\ =$   Four calling birds
$f(5)   \;\ =$   Five golden rings
$f(6)   \;\ =$   Six geese a-laying
$f(7)   \;\ =$  Seven swans a-swimming
$f(8)   \;\ =$   Eight maids a-milking
$f(9)   \;\ =$   Nine ladies dancing
$f(10)=$  Ten lords a-leaping
$f(11)=$  Eleven pipers piping
$f(12)=$  Twelve drummers drumming
The total number of gifts may be computed as follows:
$$\begin{align}
\color{red}{\sum_{n=1}^{12}}\color{orange}{\sum_{i=1}^n}\color{green}{ (n+1-i)}
&=\color{red}{\sum_{n=1}^{12}}\color{orange}{\sum_{i=1}^n}\color{green}{ \sum_{j=i}^n 1}\\
&=\color{red}{\sum_{i=1}^n}\color{green}{ \sum_{j=1}^n}\color{orange}{\sum_{i=1}^j 1}\\
&=\color{red}{\sum_{n=1}^{12}}\color{green}{\sum_{j=1}^n}\color{orange}{ \binom j1}\\
&=\color{red}{\sum_{n=1}^{12}}\color{green}{\binom {n+1}2}\\
&=\color{red}{\binom {12+2}3}\\
&=\color{red}{\binom {14}3}\\
&=\color{red}{364\quad\blacksquare}
\end{align}$$


K-means Mahalanobis vs Euclidean distance

Question: I currently am trying to cluster "types" of changes on bitemporal multispectral satellite images.
I applied a thing called a mad transform to both images, 5000 x 5000 pixels x 5 bands.
Each band is a "variable" as it is radiance information from a different spectrum of light.
This transform is basically equivalent to PC applied to the substraction of both images.
Naturally I can get up to 5 mad components. Now I would like to find this types of change on these components. If I use K-means on the components I would use an euclidean distance but I just wanted to know what could be the gain in using a mahalanobis distance if there is any.
Comment: Please expand your question to include some context, otherwise it is impossible to tell what problem you are considering, and, thus makes it impossible to provide advice. Please see the FAQ for advice on how to ask questions on this site.
Answer: I haven't understood the type of transformation you used, so my answer will be a general one. The short answer is: How much you will gain using Mahalanobis distance really depends on the shape of natural groupings (i.e. clusters) in your data.
The choice of using Mahalanobis vs Euclidean distance in k-means is really a choice between using the full-covariance of your clusters or ignoring them. When you use Euclidean distance, you assume that the clusters have identity covariances. In 2D, this means that your clusters have circular shapes. Obviously, if the covariances of the natural groupings in your data are not identity matrices, e.g. in 2D, clusters have elliptical shaped covariances, then using Mahalanobis over Euclidean will be much better modeling.
You can try both and see whether or not using the Mahalanobis distance gives you a significant gain. It also depends on what you will do after clustering. Clustering itself is usually not the ultimate purpose. You will probably use the clusters in some subsequent processing. So, the choice of  Euclidean vs Mahalanobis may be determined by the performance of your subsequent processing.
Comment: If the two distributions have identity covariance matrices that just means the Mahalanobis distance reduces to Euclidean distance.  So it doesn't make sense to talk about choosing one over the other.


How to allow users unsubscribe without logging in by changing the value of a custom field?

Question: I have a Drupal 7 site with a checkbox (Boolean field) that users check on registration to receive promotional emails.
However, Gmail started blocking some of my emails because they want every email to have a link that users can click to unsubscribe without logging in.
The first idea that came to mind is to link to a webform and then process the unsubscriptions manually, which doesn't sound like any fun.
Answer: This can be solved using the form API.

Define a path using hook_menu().
Define an unsubscribe form for the menu path.
Write a validation handler to check the email address.
Write a submit handler for the form.


Does ARIMA(0,1,11)4 exist?

Question: I have, without luck, searched to find what an ARIMA model that is differenced once, and has two moving average terms (one at lag 1 and one at lag 4) is called.
The equation for what I am asking for is the following: $(1-B)Y_t= (1-0.5B-0.2B^4)a_t$.
What I have come up with of possibilities are:
ARIMA(0,1,2)4
ARIMA(0,1,1,1)4
ARIMA(0,1,1 1)4
Answer: This a ARIMA(0,1,4) model with zero restriction on some of the parameters. Usually nobody fits such types of restricted models, since it is hard to justify the restrictions.
If you really want to give this model a name, you need to invent a new notation. This means stating unambiguously the model and corresponding notation. For example ARIMA(p,d,q) means that the model is written like this
$$(1-\phi_1B-...-\phi_pB^p)(1-B)^dY_t = (1+ \theta_1B+...+\theta_qB^q)Z_t$$
where $Z_t$ is the white noise, and lag polynomials do not have common roots. So you need to write down something similar. Then you need to make this notation known, since the point of the notation is that people understand it in unambiguous way.
Answer: No. The reason is because the pdq notation is too simple to define that model. More general solutions like SAS and AUTOBOX , SPSS  and others allow these kinds of models to be formed and estimated. It may be time to put away simple approaches and start to do more comprehensive/correct modelling.
Comment: Thank you for the answer IrishStat. I have identified that model as the most fitting model with SAS PROC ARIMA in SAS BASE 9.4. But i will just write the equation instead, then.
Thank once again!
Comment: The SAS Proc does not test for the existence of Pulses, Level Shifts , Seasonal Pulses or Local Time Trends AND the constancy of both parameters and error variance over time . These considerations and more warrant you downloading a 30 day free trial of AUTOBOX (which I have helped develop) .
Comment: What i have done is the following:
PROC ARIMA DATA=SASUSER.sales;
*where intervention=0;
IDENTIFY VAR=sales(1) crosscorr=(intervention(1)) nlag=10;
estimate noint q=(1,4) input=(intervention) method=ml;
forecast out=results lead=0;
RUN;

This is, from what i understand a BoxTiao intervention analysis where the test is that the intervention is abrupt and permanent (w).  E.g. Woodfield does the same : http://www.sascommunity.org/sugi/SUGI87/Sugi-12-57%20Woodfield.pdf .
Am i way off?
Comment: I am sorry for the ugly formatting, i am not quite sure how to change that.
Comment: You are doing Intervention Modelling which requires that you pre-specify  the nature of the intervention  and the form of the response.In your case you are specifying a permanent and instantaneous response. Intervention Detection actually Identifies the kind of intervention and the nature of the response.
Comment: Arh, okay. Yes i have tried specifying the intervention in other ways as well, in order to ensure that this is actually the correct pattern. I take it that what i have done is in fact doable and that it is possible from that SAS-statement to conclude that if the intervention variable is significant then a step function is an acceptable way to model the intervention, and its' estimate can be interpreted as the effect of the intervention.
That would also make sense, since what i am modelling is the effect of increasing opening hours in a store. Thank you very much for your help!
Comment: Often one needs to identify the ARIMA structure after the Intervention has been accounted for rather than before as you probably have done.
Comment: Do you have any references for that, because i would really like to include that in my thesis since the theory that i know of says that the process is: apply ARIMA to the longest timespan (pre/post intervention) and then afterwards apply whole data set to see the effect?
Comment: http://www.autobox.com/cms/index.php/blog/entry/build-or-make-your-own-arima-forecasting-model is an updated flowchart on TF modelling. You are  1) assuming the nature of the intervention  2) assuming that the post intervention ARIMA model is the same as the pre-intervention ARIMA model 3) that the model's errors have constant variance and that there are no other necessary Intervention such as Pulses, seasonal pulses , local time trends. I would nearly guarantee that the residuals are full of structure violating the test that you are reporting.Post your data and I will confirm this.
Comment: What you are saying is worth a lot since i have no other sounding board for this! thank you! 1) The assumption of the nature of the intervention is definitely something that puts the results at risk. 2) modelling the postintervention is unfortunately not possible with only 11 observations (yes, this makes the conclusion even less valid) 3) I have tested the model for ARCH-effects in the residuals hoping this is enough to state variance homogeneity. And lastly i have to assume my way out of other interfering interventions. Unfortunately data is confidential, so it cannot be reposted.
Comment: code your data thus you are not violating any confidentiality agreement.
Comment: ARIMA(p,d,q) is a mathematical definition of a stochastic process. It does not matter which software package implements it (or its variation for that matter). So the comment about the "Hard Time Series" and toys is out of place here.
Comment: The pdq notation is not general enough which is why simple expressions are often ( nearly always !) insufficient.... For example if the model is y(t)=.5*y(t-1)+.5*y(t-3) this is neither a (3,0,0) or a (2,0,0) and certainly there is no room in the pdq notation to deal with empirically identified deterministic series , parameter changes and the error variance deterministic changes.
Comment: "Usually nobody fits such types of restricted models, since it is hard to justify the restrictions."  It is not hard at all when the estimated coefficient for one of the lags is 0.0 or thereabout . The restriiction could be theory based but it could be and perhaps should be based upon empirical findings but that is a lot of effort when you don't have the required functionality to parsimoniously apply the tools of analysis.
Comment: "Then you need to make this notation known, since the point of the notation is that people understand it in unambiguous way." Simply specifiy the number of polynomials and their class(ar or ma) AND the number of coefficients(lags) in each polynomial AND their specific integer lags. This is not too difficult for some but apparently too difficult for others wishing simplicity at the price of efficiency/correctness. Programmers shouldn't rule because of complexity/generality of expression.
Comment: Note that I said that it is hard to justify the restriction, not that it is hard to estimate such type of model. My point concerning the notation was precisely that: state the definition so that others understand it. Modifying the existing notation without specifying what it means is not fruitful.

Does ARIMA(0,1,11)4 exist?


Windows 2008 r2 2 node cluster - one node unavailable

Question: I have 2 node Windows 2008 r2 cluster, i failed over service onto node2, restarted node1, and after restart node1 is unavailable. The networks interfaces will not come up and both interface are unavailable.
Server setup:
On 2 vmware esxi 5 on fiber san, disk are pRDMs. 2 windows 2008 r2 sp1 full patched up to Jan 2012. The cluster has been working for 3 months with multi reboots. I have the exact same cluster setup working just fine.
event log errors:
event id: 1573
Node1 failed to form a cluster. This was because the witness was not accessible. Please ensure that the witness resource is online and available.

eventid: 1069
Cluster resource 'Quorum' in clustered service or application 'Cluster Group' failed.

eventid: 7024
The Network Location Awareness service terminated with service-specific error %%-1073741288.

services unable to start
base filtering engine - Error 5: Access is denied

dhcp client (running static ip address) - Error 5: Access is denied
IKE and AuthIP IPsec keying - Error 1068: the dependency service or group failed to start

network list services  - Error 1068: the dependency service or group failed to start

network location awareness - event id 7024 - The Network Location Awareness service terminated with service-specific error %%-1073741288.

Comment: These are virtualised servers? What's the network adapter status from within the console of the VM?
Comment: yes, both nic are active and showing packets.
Answer:
The networks interfaces will not come up and both interface are unavailable.

Found your problem. You need to fix that.
Comment: How to fix the network interface that are unavailable? I am able to RDP into the server and I see packets going back and forward on both interfaces.
Comment: Where can you see packets going back and forth on the interfaces? Where do you see that they are "not up" and "unavailable"?
Comment: Under Network Connections > status of the adapter. In failover cluster manager > cluster > networks.
Comment: You haven't changed any of the network configuration have you? If you right click the network in Failover and show the critical events do you have anything other than event id 1130?
Comment: The DBA add redgate sqlbackup 6.5 non cluster version to the two nodes in the cluster. I removed the software and still get private interface is unreachable. I can ping the private IP address and get a reply. I can move the application between the two nodes now without failing.
Answer: The solution is simple, because the problem is with permissions of the services at the registry level, at the SO, not at Vmware.
To solve it, just Run a Command Prompt (as Administrator) on the SO and execute the following commands:
net localgroup administrators localservice /add
net localgroup administrators networkservice /add

Reboot and thats it: both services should be up and running!


$\gcd(P(a),Q(a),R(a),S(a),T(a))=1$ for any particular value of $a$?

Question: Let's define five binomials as :
$P(a)=2a+1$
$Q(a)=3a+4$
$R(a)=4a+9$
$S(a)=5a+16$
$T(a)=6a+25$
How to prove that :

$\gcd(P(a),Q(a),R(a),S(a),T(a))=1$
for any particular value of $a$ , $(a\in \mathbb{Z^{+}})$ ?

I have checked statement by little Maple program for a many values of $a$:
Comment: We don't need all the conditions. If $p$ divides first two numbers, it divides $a+3$. If $p$ divides the next two numbers, it divides $a+5$. If it divides all three, it divides $a+5$ and $a+3$, so it divides $2$. But $p$ is not even by first condition.
Comment: Maple is a wonderful program, and Canadian too. But typing in the program seems like more work than the proof.
Comment: @Andre,right,but requires activation of less number of brain cells
Answer: You only need the first three.
Any factor of each also divides a linear combination of them.
But $P(a)-a(P(a)+R(a)-2Q(a))= 2a+1-a(2a+1+4a+9-6a-8)=1$ so the highest common factor is 1.
Comment: @Henry,result is $4a+1$ not $1$,you have a small typo,change sign in front of $a$
Answer: We don't even need $T(a)$.  Here's a proof that $gcd(P(a),Q(a),R(a),S(a))=1$.
Fix $a\in \mathbb{N}$ and suppose $d$ is a common divisor of each of $P(a)$, $Q(a)$, $R(a)$, and $S(a)$.  Since $d\vert 2a+1$, we know that $d$ is odd.
Since $Q(a)=3a+4=(a+3) + (2a+1)$, it follows that $d \vert a+3$.
Since $R(a)=4a+9=(3a+4)+(a+5)$, it follows that $d \vert a+5$.
Further, $d$ divides $(a+3) + (a+5)=2a+8=(2a+1)+7$,  hence $d \vert 7\,\Rightarrow\,d\in \{1,7\}$.  Suppose $d=7$.
Then $7 \vert S(a)$, hence 7 divides $(4a+9)+(a+7)$.  Thus, $7 \vert a+7$ and it follows that $7 \vert a$.  However, then we would have $7=d \equiv 2a+1 \equiv 1 \mod(7)$, a contradiction.
Therefore the only common divisor of $P(a)$, $Q(a)$, $R(a)$, and $S(a)$ is 1 and hence $gcd(P(a),Q(a),R(a),S(a))=1$.
Comment: ....or you can get a shorter version of this via Andre's comment above.  Well done!


Emberjs display data after promise gets fulfilled?

Question: I am a bit conceptually confused about how this works.
The user enters data on the form, presses next. The controller 's nextStep action fires and I ask the model to get data from the server. When the data arrives, I transition to the results route. At that point, I have the route store the previous model on a variable on the controller. Then I want to iterate through the data on the template.
The problem is that nothing shows up.
This is what I have (in the appropriate files):
//Step 1 Controller (partial - nextStep action)
var businessmatch = this.store.find('businessmatch', {businessname: businessname, phonenumber: phonenumber, zipcode: zipcode})
    .then(function (result) {
         // The model has data at this point
         controller.transitionToRoute('step2');
    });

// step2 Router
import Ember from 'ember';

export default Ember.Route.extend({
    setupController: function(controller, model) {
        controller.set('businessmatches', this.store.find('businessmatch'));
    }
});

// Step2 template (partial)
        {{#each businessmatches}}
            {{businessname}}
        {{/each}}

// Model
import DS from 'ember-data';

var Businessmatch = DS.Model.extend({
    businessname: DS.attr('string'),
    phonenumber: DS.attr('string'),
    address: DS.attr('string'),
    pageurl: DS.attr('string'),
    thubmurl: DS.attr('string')
});

export default Businessmatch;

// Sample response from server
{
   "businessmatches":[
      {
         "businessname":"El Farolito",
         "pageurl":"/biz/el-farolito-san-francisco-2",
         "thumburl":"/bphoto/ohpxQWg-hB9Sb27HkVg-yQ/90s.jpg",
         "address":"780 El Camino RealMillbrae, CA 94030",
         "phonenumber":"(650) 583-0487",
         "id":1
      },
      {
         "businessname":"El Farolito",
         "pageurl":"/biz/el-farolito-san-francisco-4",
         "thumburl":"/photo/AW76YTovuu9YsO69_BcLKQ/30s.jpg",
         "address":"2779 Mission StSan Francisco, CA 94110",
         "phonenumber":"(415) 824-7877",
         "id":2
      },
      {
         "businessname":"El Farolito",
         "pageurl":"/biz/el-farolito-san-francisco",
         "thumburl":"/bphoto/LgTOTIicRY6XArigmPhBpw/90s.jpg",
         "address":"2950 24th StSan Francisco, CA 94110",
         "phonenumber":"(415) 641-0758",
         "id":3
      }
   ]
}

Answer: Found it, if I change
controller.set('businessmatches', this.store.find('businessmatch'));
to
controller.set('businessmatches', this.store.all('businessmatch'));
it works as expected.
Would be interested to know why though, if anyone can explain.
Comment: `this.store.all('businessmatch')` is a a sync operation. It returns only cached copies already present in the store. If you want it to actually query the api, you'd need to use it like a promise: `this.store.find('businessmatch').then(function (results) { // set controller property here })`
Comment: @tstirrat The thing is, if I do the `transitionToRoute` without waiting for the promise to get fulfilled (and use `.all()`), the page will load empty and the values will get filled later. I expected the same would happen with `find()`, but it doesn't.
Answer: @tstirrat is correct, the store.all() method immediately returns an array of cached records, while the store.find() method returns a promise of fetched records.
Is there a specific reason you aren't using the model hooks in your route? They are promise aware, and will wait for your store.find() to resolve then pass the model on to your setupController. You can then reference the previous models with modelFor('step1') or just use store.all() again.
Comment: Yes, routes have `beforeModel`, `model`, and `afterModel` as described in the [Ember guide](http://emberjs.com/guides/routing/asynchronous-routing/). `setupController` happens immediately after `afterModel`, and does not wait for promises to resolve before moving on.
Comment: Thank you very much for your answer! By model hook, you mean `model: function() {return this.store.find('businessmatch')}`? I assumed that `setupController` and this were equivalent with the only difference being that in the latter I could specify the property 's name while one the former it would be `model`. So much for making assumptions :| For the record, I tested `all()` more than once in the case where the transition was set outside the promise 's`then` section and the template updated when the data was received. `RecordArray` has an `update` method so perhaps some magic happens there?


Proving recurrence relation by mathematical induction

Question: Consider the following recurrence relation:

$T(1) = 1$
$T(n) = 2T(\frac{n}{2}) + n$

I suspect that $T(n) = n + n\log_2 n$. Using mathematical induction, the base case holds since $T(1) = 1$. The inductive step seems a little complicated: how to prove $T(k+1)$ holds assuming $T(k)$ is true for $k\geq1$?
Any help is appreciated.
Comment: This recurrence relation doesn't seem to tell you what, say, $T(3)$ is.
Comment: Perhaps induct on powers of $2$? I assume that's closer to what you're looking for since you have $\log_2(n)$ instead of a floor function there (since for $n \ne 2^a$ you'll definitely not get integers).
Answer: Another way to write your suspected formula is $T\left(2^k\right) = 2^k(k+1)$.
When $k=0$, we have $T(1) = 1$ so that's okay.
Now, assuming the formula holds for $k$, we would have by the recurrence relationship that
\begin{align}
T\left(2^{k+1}\right)
&= 2T\left(2^k\right) + 2^{k+1}
\\&= 2\left(2^k(k+1)\right)+2^{k+1}
\\&= 2^{k+1}(k+1)+2^{k+1}
\\&= 2^{k+1}(k+2)
\end{align}
which agrees with the suspected formula.
So by induction, the suspected formula is correct.
Notice, however, that it is only defined for powers of $2$.
This is because the recurrence relation itself is not defined for other integers.
Comment: Things are clearer now, but could you explain the first line of the inductive step, please? How do you know that $T(2^{k+1})=2T(2^k)+2^{k+1}$?
Comment: This is the given recurrence relationship $T(n) = 2T(n/2) + n$.
Comment: Right, so you can use the inductive hypothesis. Thanks!
Comment: You're welcome! Glad to have helped.


Differentiate without using chain rule in 5 steps

Question: I'm facing problem with this challenge problem. Evaluate
$\frac{d}{dx}\frac{\left(x\sin x+\cos x\right)}{\left(x\sin x-\cos x\right)^2}$ without using chain rule and using the basic differentiation rules in 5 steps.
Comment: What problems have you faced while trying this? What basic differentiation rules do you know?
Comment: It appears to be a lot hairy and difficult to simply using product and quotient rules.
Comment: It's really not so bad if you just do it slowly and properly. The point is that you have to show where you get stuck, not ask others to do it for you.
Comment: That is what I'm not able to make out, I've expanded all the terms but at the end I reach a point where no further simplification is possible and I don't get the desired answer.
Comment: Write it down here, then perhaps somebody can help.
Comment: What would be the solution with chain rule?
Comment: can we use the quotient rule?
Comment: @Dr.SonnhardGraubner See OP's second comment; I would think so.
Comment: I don't see why this can't be done in ONE step without the chain rule. You have $y = \frac{A(x)}{B(x)\cdot B(x)},$ so $y' = \frac{A'BB\; - \; A(BB' + B'B)}{(BB)^2},$ where expressions for $A,$ $B,$ $A',$ and $B'$ in terms of $x,$ $\sin x,$ and $\cos x$ are written down as you write this out. Here I'm only using the $A$'s and $B$'s as abbreviations in explaining what one does. If this violates anything, then I think you need to explain exactly what constitutes "a step".
Answer: the quotient rule is given by
$$\frac{u'v-uv'}{v^2}$$
given $$u=x\sin(x)+\cos(x)$$
$$v=?(x\sin(x)-\cos(x))^2$$ then we get
$$u'=\sin(x)+x\cos(x)-\sin(x)=x\cos(x)$$
$$v'=2(x\sin(x)-\cos(x))(\sin(x)+x\cos(x)+\sin(x))$$
can you proceed?