No response from HttpServlet with AsyncContext

Question: I'm trying to implement async servlet on Tomcat, that will send update to client every time an HttpSessionAttributeListener.attributeReplaced() is triggered. Client side is configured to receive Server Sent Events.
Although the listener receives the updates, the browser does not receive any response. Browser's developer pane shows, that the request is pending and it ends with error 500 after the timeout set by the AsyncContext.setTimeout(). I run out of ideas, why this is happening.
JS
var source = new EventSource('/acount/sse');

source.onmessage = function (event) {
    console.log(event.data);
    document.querySelector('#messageArea p').innerHTML += event.data;
};

And this is my servlet code:
Servlet
public class SSE extends HttpServlet implements HttpSessionAttributeListener {

    public static final String ATTR_ENTRY_PROCESSOR_PROGRESS = "entryProcessorProgress";

    private AsyncContext aCtx;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);

        resp.setContentType("text/event-stream");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setHeader("Connection", "keep-alive");
        resp.setCharacterEncoding("UTF-8");

        aCtx = req.startAsync(req, resp);
        aCtx.setTimeout(80000);

    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        write(httpSessionBindingEvent);
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
        write(httpSessionBindingEvent);
    }

    private void write(HttpSessionBindingEvent httpSessionBindingEvent) {
        if (httpSessionBindingEvent.getName().equals(ATTR_ENTRY_PROCESSOR_PROGRESS)) {
            try {
                String message = "data: " + httpSessionBindingEvent.getValue() + "\n\n";
                aCtx.getResponse().getWriter().write(message);
                aCtx.getResponse().getWriter().flush();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

}

Answer: The problem:
I tried your code and there was a java.lang.NullPointerException  in:
 aCtx.getResponse().getWriter().write(message);

Because the aCtx is null.
You have mixed the Servlet and Listener, but when the Listeners methods are called, the AsyncContext initialization is not. Therefore nothings go to the browser.
I splitted your code in Servlet an Listener and smuggled the AsychContext object through a session attribute. So it was accessible in the listener.
And it works.
The Complete Code:
The HTML:
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Server Event Listener</title>

The Servlet:
package testingThings.ServerSentEvent;

import java.io.IOException;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(asyncSupported = true, value = {"/ServerSentEvent"})
public class ServerSentEvent extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // add @WebServlet(asyncSupported = true) instead
        // http://stackoverflow.com/questions/7855712/how-to-avoid-request-set-async-supported-true-to-enable-async-servlet-3-0-proces
        // req.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);

        resp.setContentType("text/event-stream");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setHeader("Connection", "keep-alive");
        resp.setCharacterEncoding("UTF-8");

        AsyncContext aCtx = req.startAsync(req, resp);
        aCtx.setTimeout(80000);

        // add a asyncContext a session Attribute
        req.getSession().setAttribute("asyncContext", aCtx);

        //start logging in listener
        req.getSession().setAttribute("entryProcessorProgress", "trigger output");
    }
}

The HttpSessionAttributeListener:
package testingThings.ServerSentEvent;

import java.io.IOException;

import javax.servlet.AsyncContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

@WebListener
public class SessionAttributeListener implements HttpSessionAttributeListener {

    public static final String ATTR_ENTRY_PROCESSOR_PROGRESS = "entryProcessorProgress";

    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        write(httpSessionBindingEvent);
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
        write(httpSessionBindingEvent);
    }

    private void write(HttpSessionBindingEvent httpSessionBindingEvent) {
        if (httpSessionBindingEvent.getName().equals(ATTR_ENTRY_PROCESSOR_PROGRESS)) {
            try {
                // get the AsyncContext from the session
                AsyncContext aCtx = (AsyncContext) httpSessionBindingEvent.getSession().getAttribute("asyncContext");
                String message = "data: " + httpSessionBindingEvent.getValue() + "
\n\n";
                aCtx.getResponse().getWriter().write(message);
                aCtx.getResponse().getWriter().flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


iPhone 6 Plus Resolution Image for custom keyboard in iOS8

Question: I am confusing about the resolution of image that will use for iPhone 6 Plus.
My App is Keyboard Extension for Custom Keyboard.
I use Background Image for Keyboard.
For iPhone 5 , 5s , background image pixel size is
320px x 216px

640px x 432px for @2x

But for iPhone 6 Plus , i use @3x Resolution.So
960px x 648px

It's because i multiply 320 x 3 = 960
However when i test in iPhone 6 Plus Simulator , Keyboard Background Image is a little blurring and not perfectly.

I am sure that my pics is not blurring.
Is my Calculation for @3x right? or something wrong?
Comment: "Keyboard Background Image is a little blurring" can you show the picture?
Comment: Did you put any check to show image for iPhone 6 plus?
Comment: @Jonast92 Added Image And Hemant No.
Comment: I think it's best if you take a screenshot of the default keyboard from the iPhone 6 Plus simulator at 100% scale (command-1 in the Simulator or Window > Scale > 100%), and use that to check the size.
Answer: I finally found solution for my own question.It's because of Apple's Scale Mode Feature that allow app can run in iPhone 6 and iPhone 6+ with normal resolution.
My solution is When i add iCon and Launch screen image for iPhone 6 and iPhone 6+ , the full HD Retina Display can display.
iCon Size are :
1. 87 x 87
2. 120 x 120
3. 180 x 180

For iPhone 6+ Landscape Launch screen image size is : 2208 × 1242
For iPhone 6+ Portrait Launch screen image size is : 1242 × 2208
For iPhone 6 Portrait Launch screen image size is : 750 × 1334
After added above iCons and Launch screen images , my app working with full resolution.


Allow multiple taxonomy term values on term listing page

Question: Is it possible to return results of multiple taxonomy terms on the taxonomy/term/%tid page?
For example, taxonomy/term/203+221 or taxonomy/term/203/221 should display all nodes with either one of those two terms.
Answer: I've found the path taxonomy/term/203+221 (which will yield the nodes tagged with either 203 OR 221) is possible by making a slight change to the Contextual Filter of the taxonomy/term/%tid view (which you should have enabled in Structure > Views > Taxonomy Term.
Expand the Advanced section of the view configuration, click on the first Contextual filter "Content: Has taxonomy term ID (with depth)".

You will see a checkbox that allows multiple values, which is checked by default.

However, to get this working I had to scroll further down to the "Specify validation criteria" section and change the "Filter value type" to "Terms separated by a , or +".

Now you should be able to use multiple term IDs in your URL, combined with a "+", to see all nodes tagged with any of the IDs in the list. You can test out various URL arguments using the Views Auto preview:


Error while compiling the Xcode project (IPhone)

Question: I added ffmpeg iphone port into my library and I can able to use a few of its functions like avcodec_init(),.. without any errors.
But when I include this function call "avcodec_register_all" Xcode is giving error after compilation
The error message is :
*---------------
ld: ldr 12-bit displacement out of range (4276 max +/-4096) in _CFRelease$stub in _CFRelease$stub from /Users/foxit/Documents/CameraTest/build/CameraTest.build/Debug-iphoneos/CameraTest.build/Objects-normal/armv6/CameraTest
Command /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc-4.2 failed with exit code 1
*-------------
Does anyone know whats wrong with this ?
Regards,
Raghu
Answer: This problem exists in iPhone OS 3.1 or later while building in Xcode. Try re-arringing the link order of the libraries in your target's link library phase. I have discussed this issue in: http://www.galloway.me.uk/2009/12/ldr-12-bit-displacement-out-of-range/
There is an inherent problem in iPhone SDK 3.1 and later. Will have to wait until Apple fixes it or we will have to do some trail and error changes.
In our case, just re-ordering libavfilter and libavcodec to the last would simply work.
Comment: Follow output-example.c file in the source of FFMpeg source. Implement the required methods from it. Override fill_yuv_image() method so that you convert your RGB data to YUV by using sws_scale() method and fill that raw data into AVFrame which is passed as an argument to fill_yuv_image().
Comment: Hi Raj,
 Do you know a way to convert raw surface buffer to AvFrame() ?
I am trying to write a video recording application.I am able to hold the raw data of the image (screen) but not able to find the conversion from that raw data into AVframe to encode it.
Thanks
Answer: I was able to get rid of the error by unselecting the "Compile For Thumb" compiler option.
So here are my settings:
Base SDK:  iPhone Device 4.0
iPhone OS Deployment Target: 3.1.3

I did add -no_order_inits to the linker options but that did not work for me.
If you select a deployment target of 3.0 then you also will not get the error.
BTW, I am also using the FFMPEG and libMMS libraries.
Answer: Same as
this problem?
Suggestion there is:

Please select deployment target "iPhone OS 3.0" or earlier. It is known Xcode linker issue with deployment targets "iPhone OS 3.1" and later.
Comment: No that is not the problem, the same thing working in another Xocde project which I cant use it for some reasons
Comment: I was also seeing this problem and reordering my frameworks didn't work.  After changing my build target from 3.1 to 3.0 the problem disappears.
Answer: For me on 4.2 and using ffmpeg, solution was to specify "Optimized (armv7)" in field "Architectures" instead "Standard (armv6 armv7)"
if this can help you...
Answer: Since I am using a CMake generated XCode project I don't have all the flexibility I would like in re-ordering my link lines.  I stared at the ld(1) man page for a while and found this:
-no_order_inits

"When the -order_file option is not
  used, the linker lays out functions in
  object file order and it moves all
  initializer routines to the start of
  the __text section and terminator
  routines to the end. Use this option
  to disable the automatic
  re-arrangement of initializers and
  terminators."

Adding this to the link line made the error go away.
Answer: I've had this problem in MonoTouch, and posted a solution for it here: http://microsoft2apple.com/2010/09/30/solved-ldr-12-bit-displacement-out-of-range/


Crud com php ajax

Question: tenho uma tabela que quero personaliza e deixa-lá um crud completo, com delete, insert, update e delete múltiplos registros, 1- queria ver se poderia deixa essa tabela compatível com jquery 2.2.0 ou um jquery mais avançado pois ele so aceita o 1.8.1, eu consegui inserir o php com while na td, mas o pesquisa não busca em todas as paginas da tabela, só pesquisa na pagina onde os registro esta a amostra, ou seja, eu tenho que da next para pesquisa na outra pagina!

        <link rel="stylesheet" href="custom.css" media="screen" />

    <form method="post" action="../melhorando-exibicao-tabelas-jquery/exemplo.html" id="frm-filtro">

    Pesquisar
    <input type="text" id="pesquisar" name="pesquisar" size="30" />

</form>

      <input type="checkbox" value="1" id="marcar-todos" name="marcar-todos" />
      ID
      Nome

  <?php
    require_once 'dbconfig.php';
    $conn = Conexao::getInstance();
    $stmt = $conn->prepare("SELECT * FROM tb_cidades ORDER BY id DESC");
    $stmt->execute();
    while($row=$stmt->fetch(PDO::FETCH_ASSOC))
    {
        ?>

      <input type="checkbox" value="1" name="marcar[]" />
                <?= $row['id']; ?>
      <?= $row['nome']; ?>

    <?php
    }
    ?>

    <form>

                Exibir <select class="pagesize">
                        <option selected="selected"  value="10">10</option>
                        <option value="20">20</option>
                        <option value="30">30</option>
                        <option  value="40">40</option>
                </select> registros

        <input type="text" class="pagedisplay"/>

    </form>

jquery.tablesorter.pager.js
(function($) {
    $.extend({
        tablesorterPager: new function() {

            function updatePageDisplay(c) {
                var s = $(c.cssPageDisplay,c.container).val((c.page+1) + c.seperator + c.totalPages);
            }

            function setPageSize(table,size) {
                var c = table.config;
                c.size = size;
                c.totalPages = Math.ceil(c.totalRows / c.size);
                c.pagerPositionSet = false;
                moveToPage(table);
                fixPosition(table);
            }

            function fixPosition(table) {
                var c = table.config;
                if(!c.pagerPositionSet && c.positionFixed) {
                    var c = table.config, o = $(table);
                    if(o.offset) {
                        c.container.css({
                            top: o.offset().top + o.height() + 'px',
                            position: 'absolute'
                        });
                    }
                    c.pagerPositionSet = true;
                }
            }

            function moveToFirstPage(table) {
                var c = table.config;
                c.page = 0;
                moveToPage(table);
            }

            function moveToLastPage(table) {
                var c = table.config;
                c.page = (c.totalPages-1);
                moveToPage(table);
            }

            function moveToNextPage(table) {
                var c = table.config;
                c.page++;
                if(c.page >= (c.totalPages-1)) {
                    c.page = (c.totalPages-1);
                }
                moveToPage(table);
            }

            function moveToPrevPage(table) {
                var c = table.config;
                c.page--;
                if(c.page <= 0) {
                    c.page = 0;
                }
                moveToPage(table);
            }

            function moveToPage(table) {
                var c = table.config;
                if(c.page < 0 || c.page > (c.totalPages-1)) {
                    c.page = 0;
                }

                renderTable(table,c.rowsCopy);
            }

            function renderTable(table,rows) {

                var c = table.config;
                var l = rows.length;
                var s = (c.page * c.size);
                var e = (s + c.size);
                if(e > rows.length ) {
                    e = rows.length;
                }

                var tableBody = $(table.tBodies[0]);

                // clear the table body

                $.tablesorter.clearTableBody(table);

                for(var i = s; i < e; i++) {

                    //tableBody.append(rows[i]);

                    var o = rows[i];
                    var l = o.length;
                    for(var j=0; j < l; j++) {

                        tableBody[0].appendChild(o[j]);

                    }
                }

                fixPosition(table,tableBody);

                $(table).trigger("applyWidgets");

                if( c.page >= c.totalPages ) {
                    moveToLastPage(table);
                }

                updatePageDisplay(c);
            }

            this.appender = function(table,rows) {

                var c = table.config;

                c.rowsCopy = rows;
                c.totalRows = rows.length;
                c.totalPages = Math.ceil(c.totalRows / c.size);

                renderTable(table,rows);
            };

            this.defaults = {
                size: 10,
                offset: 0,
                page: 0,
                totalRows: 0,
                totalPages: 0,
                container: null,
                cssNext: '.next',
                cssPrev: '.prev',
                cssFirst: '.first',
                cssLast: '.last',
                cssPageDisplay: '.pagedisplay',
                cssPageSize: '.pagesize',
                seperator: "/",
                positionFixed: true,
                appender: this.appender
            };

            this.construct = function(settings) {

                return this.each(function() {

                    config = $.extend(this.config, $.tablesorterPager.defaults, settings);

                    var table = this, pager = config.container;

                    $(this).trigger("appendCache");

                    config.size = parseInt($(".pagesize",pager).val());

                    $(config.cssFirst,pager).click(function() {
                        moveToFirstPage(table);
                        return false;
                    });
                    $(config.cssNext,pager).click(function() {
                        moveToNextPage(table);
                        return false;
                    });
                    $(config.cssPrev,pager).click(function() {
                        moveToPrevPage(table);
                        return false;
                    });
                    $(config.cssLast,pager).click(function() {
                        moveToLastPage(table);
                        return false;
                    });
                    $(config.cssPageSize,pager).change(function() {
                        setPageSize(table,parseInt($(this).val()));
                        return false;
                    });
                });
            };

        }
    });
    // extend plugin scope
    $.fn.extend({
        tablesorterPager: $.tablesorterPager.construct
    });

})(jQuery);

alguém tem uma ideia como fazer?
Comment: Rapaz acho que entendi sua questão, existem alguns plugins que fazem a tabela funcionar para pesquisa e listar as consultas. Confere esse link https://datatables.net/examples/basic_init/zero_configuration.html vc faz a consulta normal em php e a tabela vai listar organizando o frontend.
Answer:
só pesquisa na pagina onde os registro esta a amostra, ou seja, eu
  tenho que da next para pesquisa na outra pagina!

Isso é assim mesmo cara, pois a pesquisa está apenas no FrontEnd. Você tem que fazer essa pesquisa no backend.
Para isso, vc deve usar um plugin que aceite filtro com ajax, veja:
https://mottie.github.io/tablesorter/docs/example-pager-ajax.html

Crud com php ajax


replace css on certain pages by another css

Question: I use drupal 6. How do I remove global.css from certain path like cart* and replace it with another css? I can add for example stylesheets[all][] = custom.css inside my theme info file but how to load it only on path cart*  and how to disable global.css on the same path? Thank you
Answer: You would need to use your theme to watch for it. You'll need to hook into preprocess_page and look for the global.css file in the css array and unset it. Below is an example of how to remove the modules/system/system.css you'll need to see where in the array global.css is and do the same thing. You'll want to wrap that inside of an if for your paths. In this example I use arg() to get the first path value (ie cart) and turn it on for that case. You can do what ever you want.
function phptemplate_preprocess_page(&$vars)
{
    if(arg(0) == 'cart') {
        $css = $vars['css'];
        unset($css['all']['module']['modules/system/system.css']);
        $vars['styles'] = drupal_get_css($css);
    }
}


Acessar dados de um objeto js

Question: Tenho o seguinte objeto JS exibido pelo console.log

Só consigo acessar a propriedade status do objeto em si, mas preciso acessar a propriedade status que está dentro do objeto value e possui o valor 400, mas todos os tipos de assessores de propriedade que tento dão undefined quando tento ir além do primeiro status (de valor 0) apresentado. Alguém pode me ajudar? Gostaria de saber também qual o nome que se dá para essas propriedades "internas" do objeto?
Comment: Como você tentou? Pelo log, deve ser objeto.value.status. Talvez o problema não seja a forma de acesso, e sim o momento em que você tenta acessar esses dados (pode ser quecestja tentando acessar antes dos dados estarem disponíveis, caso venham por Ajax)
Comment: Para acessar é o que o bfavarreto falou, já com relação ao nome sua pergunta é a resposta, tanto que o método para retornar as nome das propriedades interna é `Object.getOwnPropertyNames()` sao propriedades não?
Comment: Realmente se trata de uma requisição ajax feita por uma função Restangular.all, talvez seja a questão de os dados não estarem disponíveis a tempo. Estou tentando com `object.value.status` mas recebo undefined ou Tried to load AngularJS more than once
Comment: Coloque na pergunta o trecho de código que faz a requisição, e o trecho que tenta tratar a resposta.
Answer: Como o bfavaretto disse veja o momento que está acessando os dados, pois pode ainda não estar disponível, mas a sintaxe é esta como no exemplo. Você tem um objeto dados, que para acessar qualquer uma das suas propriedades basta colocar o . antes da propriedade. No seu caso aí pela imagem não tem nenhum array senão você teria que acessar o índice da propriedade para pegar seu valor:

var dados = {
  pure: true,
  status: 2,
  value: {
    data: "",
    status: 400,
    headers: "bla-bla-bla"
  }
}

console.log(dados.status +" - "+ dados.value.status );
Comment: Repara na saída do console que a pergunta mostra. Parece que o valor de `status` era `0` no momento do log, e `2` no momento em que ele expandiu o objeto. Tá com muita cara de o problema ser outro: tentar acessar dado de operação assíncrona antes de ele estar disponível.
Comment: Pessoal, optamos por alterar o backend que o verdadeiro causador do problema que está ocorrendo ao lançar uma exceção indevida, a tentativa no JS era mais uma tentativa de resolver na gambiarra do que de resolver de fato o problema.
Comment: Sim, verdade.  Provavelmente o problema era este mesmo.

Acessar dados de um objeto js


Read Drush config file

Question: I am creting a module with Drush integration. My challenge now is how to read the Drush config file in ~/.drush/myconfig.drushrc.php.
I tried drush_load_config_file but it is not working.
drush_load_config_file($context, _drush_config_file($context, 'deployment'));
Comment: Why? What are you trying to do? drushrc of user's choice will already be executed before your module's function will start. This should require absolutely no action on your part.
Comment: My goal there is to read the variable value set by user. Example are `$options['repository']` and `$options['docroot']`. Those are user defined values so I need to know what are the values for the module to do its function. Thanks
Answer: Sounds as if you are looking in the wrong place to integrate your module with Drush.
You need to create a drush folder within your custom module and create a YOURMODULE.drush.inc file inside with appropriate Drush hooks.
Here's an example code:
/**
 * Implements hook_drush_command().
 */
function boilerplate_drush_command() {
  $items['boilerplate-hello'] = array(
    'callback' => 'boilerplate_hello_command',
    'description' => dt('Sample Drush command for boilerplate module.'),
    'bootstrap' => DRUSH_BOOTSTRAP_DRUSH,
    'arguments' => array(
      'name' => dt('Optional. A name which will be greeted upon running the command.'),
    ),
    'aliases' => array('boilerplate-hi'),
  );

  return $items;
}

/**
 * Implements hook_drush_help().
 */
function boilerplate_drush_help($section) {
  switch ($section) {
    case 'drush:boilerplate-hello':
      return dt('Sample Drush command for boilerplate module. It will just greet you, optionally with a name you provided.');
  }
}

/**
 * Command to download the Chosen plugin.
 */
function boilerplate_hello_command() {
  $args = func_get_args();
  $name = (!empty($args[0])) ? $args[0] : FALSE;

  if ($name) {
    drush_log(dt('Hello @name!', array('@name' => $name)), 'success');
  }
  else {
    drush_log(dt('Hello there!'), 'success');
  }
}

This will allow you to run the command using drush boilerplate-hello or drush boilerplate-hi (alias). If you pass an argument, for example drush boilerplate-hello ninjascorner it will take it as an argument, which is the functionality you need.
This is taken from my Drupal module boilerplate. The Drush integration from there is working, so you can install the module and play around with it to see how it works.
Comment: You're welcome; however I still didn't quite get what you are trying to do. What is the reason you can't put the repo URL in the `module.drush.inc` file? Or are you speaking about Drush make file by any chance?
Comment: Thanks for a very detailed answer Topsitemakers. However, I wanted to read deployment.drushrc.php for example where users can put the configurations like repo URL, target directory to put the code from repository. Thanks
Comment: The reason I can put the repo url in module.drush.inc is because I dont want other people to edit the module. I am planning to contribute this module to the community and it is not a good idea to put the config in the module. BTW this is a deployment module.
Comment: If you don't want others to edit the config, just hardcode it in constants within the module. That's a perfectly valid way to do it. If you want to contribute this, you can explain exactly what you are trying to achieve/what is the purpose so others can suggest you the best solution.

Read Drush config file


Passar conteúdo do banco de dados de uma página para outra

Question: Parece ser algo simples de se pesquisar, mas não estou conseguindo. Eu gostaria de quando clicado em um item da lista, abrir uma nova página com as informações detalhadas desse item, vai ser as mesmas informações usadas na página inicial. Mas não sei como posso fazer isso. Criei uma página apenas, mas preciso receber o conteudo de cada item clicado nela.

Fiz um botão e quando clico vai pra pagina, so preciso receber os dados lá. Não postei o código pq nao sei exatamente qual parte do codigo postar aqui, mas se alguem puder me ajudar e precisar, só me falar. Eu quero receber as mesmas informações na segunda página, porém do item selecionado.  Obrigado!
html page1  <ion-item no-lines *ngFor="let produto of produtos" no-padding>

 {{produto.nom_produto}}

ts page 1
this.navCtrl.push(ConteudoprodutoPage, {valor: "{produto.nom_produto}"} )

ts page 2
  export class ConteudoprodutoPage {

  valor ="";

 constructor(public navCtrl: NavController, public navParams: NavParams) {
 this.valor = this.navParams.get("valor");
  }

html page 2  <ion-card-header>
            {{produto.nom_produto}}
        </ion-card-header>

Comment: Como você já faz para receber os conteúdos na página da lista?
Comment: Possível duplicata de [Como passar dados de um item selecionado numa ng-repeat para outra view](https://pt.stackoverflow.com/questions/209938/como-passar-dados-de-um-item-selecionado-numa-ng-repeat-para-outra-view)
Answer: Você pode passar como parâmetro na navegação entre páginas. Esse seria o código para chamar a página seguinte:
this.navCtrl.push("PaginaDetalhesPage", {itemSelecionado: item});

Na página aberta com os detalhes, você recebe o valor da navegação:
this.item = navParams.get('itemSelecionado');

Comment: Mas o que seria o " {itemSelecionado: item}"  ?
Comment: Seria o item selecionado do ngFor na primeira página, com a lista com todos os itens.
Comment: Não vi o clique no seu html, mas acredito que você esteja passando o produto como parâmetro. Você pode passar o produto total para a página seguinte, e não só o nome. Na ts page 1: `this.navCtrl.push(ConteudoprodutoPage, {valor: produto} )`. Na ts page 2, você recebe esse parâmetro que passou como o próprio produto e não como uma variável nova. `this.produto = this.navParams.get("valor");` O `this.produto` é o que você usa no html da page 2.
Comment: Estou conseguindo receber os dados na outra página, mas tem como eu filtrar para receber apenas  do item clicado?  Ter tem, mas não sei se entendeu o que eu quis dizer. Sempre que clicar em um produto, mostrar apenas as informações dele.
Comment: Sim, no html, inclua a função de clique na linha em que você informa o ngFor: ``. Nessa função `produtoSelecionado(produto)`, chame a página seguinte, informando como parâmetro de navegação o produto que você recebeu, como eu informei anteriormente: `this.navCtrl.push(ConteudoprodutoPage, {valor: produto} )`.
Comment: e no html da page 2? se eu uso  //   //  ele pega todos os itens, mas se eu não usar da erro
Comment: No html da página 2 você só tem o `produto`, que veio da navegação em `this.produto = this.navParams.get("valor");`. Na página 2 você não precisa ter o `produtos`. No html da página 2 você não precisa usar um ngFor, mas sim, só os dados do produto.
Comment: recebo o erro quando uso           {{produto.nom_produto}}      na page 2.
Runtime Error
Uncaught (in promise): TypeError: Cannot read property 'nom_produto' of undefined TypeError.
Comment: Você alterou no contructor para `this.produto`, onde está `this.valor`?
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/81952/discussion-between-felipe-xst-and-renata).
Comment: no contructor da page2 está: this.produtos = this.navParams.get("valor");
e no click da page 1:
querocomprar() {
this.navCtrl.push(ConteudoprodutoPage, {
valor: this.produtos
})
}
Comment: estava fazendo algumas coisas erradas.  Mas consegui já, obrigado :D


$z=x=y$ in $\Bbb R^3$

Question: It is a simply question. But I want to make sure. The surface $$z=x=y$$ represents  a line in $\Bbb R^3$ that passes  through the origin. Is that correct?
Comment: Yes, the set $\{(x,y,z)\in\Bbb R^3~:~x=y=z\}$ is a line passing through the origin and the point $(1,1,1)$ and can be rewritten as $\{(t,t,t)~:~t\in \Bbb R\}$ or as $\text{span}\{(1,1,1)\}$ and is a one-dimensional subspace of $\Bbb R^3$
Comment: No.  The set $\{(x,y,z)\in\Bbb R^3~:~x=y\}$ is a plane and is $\{(t,t,s)~:~t,s\in\Bbb R\}$ is $\text{span}\{(1,1,0),(0,0,1)\}$ is a two-dimensional subspace.  It is the plane which includes the origin as well as the points $(1,1,0)$ and $(0,0,1)$
Comment: @JMoravitz, I am kind of confused little bit , Is it the same if we just say $x=y$ in $\Bbb R^3$
Comment: @JMoravitz, Yes, you are right . Thank you so much.
Comment: Why are you calling it a *surface* if it's a line, though?
Answer: Consider the your surface $S=\lbrace(x,y,z)\in \mathbb{R}^3 \mid x=y=z \rbrace$ subspace of $\mathbb{R}^3$ a basis for $S$ is $\beta=\lbrace (1,1,1)\rbrace$ therefore your $S$ is a line that pass throught of $(1,1,1)$. As @JMoravitz say.

$z=x=y$ in $\Bbb R^3$


Inno Setup - Transparent Splash Screen

Question: I have a problem and I need your help..I want to find a differente way to put a transparent splash screen or the correction of my code. The code here works... but there is a problem, some people get an error at the end of the installation.
This is how look the error at the end of the installation

I check another lines in my code and I found that the problem was the code of the splash screen, if I delete it the installer works perfect, I see that what I need is a procedure DeinitializeSetup(); but I don't know how tu put it in the splash screen section, I get this kind of error if I delete the procedure DeinitializeSetup(); in another codes, like skin, logo, etc.. the files that goes to temp folder of windows... then what I need is the procedure DeinitializeSetup(); in the splash screen code to solve this... :( here is the dll file for anyone to test IsUtilsHb.dll
then...please if anybody know a different way to put a transparent splash screen... ill be grateful.. or better.. to fix this code section :)
[setup]
AppName=Slash PNG
AppVerName=1.0
DefaultDirName={pf}\program

[Languages]
Name: "spanish"; MessagesFile: "compiler:Languages\Spanish.isl"

[Files]
Source: IsUtilsHb.dll; DestDir: {app}; Flags: dontcopy
Source: SplashScreen.png; DestDir: {app}; Flags: dontcopy

[Code]
function SplashScreen(hWnd: Integer; pathPng: String; nSleep: Integer): Integer;
external 'SplashScreen@files:IsUtilsHb.dll stdcall';

procedure InitializeWizard();
var
  SplashFileName: string;
begin
  SplashFileName := ExpandConstant('{tmp}\SplashScreen.png');
  ExtractTemporaryFile('SplashScreen.png');
  SplashScreen(StrToInt(ExpandConstant('{hwnd}')), SplashFileName, 5000);
end;

Comment: If you'd like transparent animated PNG slideshow, you can take a look at [`Inno Image Animator`](http://code.google.com/p/inno-image-animator/wiki/Introduction). But if you want, I can quite easily modify it to just one image (as a new FOS project) with specifications you tell ;-)
Answer: After looking all around the internet, I got this solution:
This is the DLL am using:
isgsg.dll
[setup]
AppName=Slash PNG
AppVerName=1.0
DefaultDirName={pf}\program

[Languages]
Name: "spanish"; MessagesFile: "compiler:Languages\Spanish.isl"

Source: "Splash.png"; DestDir: {tmp}; Flags: ignoreversion dontcopy nocompression
Source: isgsg.dll; DestDir: {tmp}; Flags: ignoreversion dontcopy nocompression

[Code]
procedure ShowSplashScreen(p1:HWND;p2:string;p3,p4,p5,p6,p7:integer;p8:boolean;p9:Cardinal;p10:integer); external 'ShowSplashScreen@files:isgsg.dll stdcall delayload';

procedure InitializeWizard();
begin
  ExtractTemporaryFile('Splash.png');
  ShowSplashScreen(WizardForm.Handle,ExpandConstant('{tmp}\Splash.png'),1000,3000,1000,0,255,True,$FFFFFF,10);
end;

Answer: Just added:
ShowSplashScreen(WizardForm.Handle,ExpandConstant('{tmp}\Splash.png'),1000,3000,1000,0,255,True,$FFFFFF,10);

Interpretation:
ShowSplashScreen(WizardForm.Handle,ExpandConstant('{tmp}\Splash.png'),1000(appear time),3000(show time),1000(disappear time),0(like a intermittent reload time),255(transparency 0..255),True,$FFFFFF (transparency color if not png transp),10);

like a intermittent reload time = use 9999999 and you see like a thunder image

Inno Setup - Transparent Splash Screen


How to change a stored actions noun or the overall current action in Inform7?

Question: EDIT: Massive cleanup, to make the current status clearer!
I want to modify an action in either of two aspects:
Either change the noun in an action previously retrieved by current action not in the same turn
or
Change the action name of the current (or stored) action (so change waiting to unlocking it with).
I tried:

directly accessing the noun of a stored action: now the noun of storedAction is
accessing the action name of the current action as well as the one stored by the poor attempt of now the action name part of current action is
Answer: I came up with a really hacky feeling solution to my problem. I switched an extra truthstate, repeated the stored action (using try) and then modified noun and second noun according to my needs.
I am not happy with what I had to come up with to get this to work, but this seemed to be the only way possible.
If there will be posted any other solutions to this that are cleaner I will mark them as correct.


Substituição de variaveis no corpo da mensagem

Question: Estou criando um sistema de perfil de mensagens, quando o sistema executa uma determinada ação ele pega determinado perfil e dispara a mensagem como e-mail, no entanto gostaria que no corpo da mensagem, quando escrito {{variavel}} gostaria que ele pegasse o valor da $variavel correspondente (de forma automática), no entanto não sei como se chama esse método e ainda não encontrei solução alguma, será que alguém teria condições de dar uma ajudinha?
Explicação:
Tenho a seguinte mensagem:

{{nome}} Lorem Ipsum is simply dummy text of the printing and typesetting industry {{email}}

Para substituir esses valores eu teria que fazer da seguinte forma:
str_replace("{{nome}}", $nome, $mensagem);
str_replace("{{email}}", $email, $mensagem);

Só que eu queria fazer isso de forma que fosse automática.
Comment: Por exemplo: no corpo da mensagem vai conter isso `{{nome}} {{email}}` quero que isso seja trocado pela variavél que vai estar internamente no PHP `$nome $email` com seus respectivos valores.
Answer: Depois de ver a discussão, cheguei as seguintes soluções.
Poderia utilizar a função preg_replace_callback.
function preg_parse($template, $vars) {
    $re = '/\{\{([^}]+)\}\}/';

    return preg_replace_callback($re, function($match) use($vars) {
        $key = trim($match[1]); //Remove os espaços da direita e esquerda do nome da variável
        return isset($vars[$key]) ? $vars[$key] : $match[0];
    }, $template);
}

Ou automatizar a definição das variáveis na solução do @Sergio (pelo que entendi na discussão era o que estava faltando para você) .
function replace_parse($template, $vars) {
    $keys   = array_map(function($key) { return '{{'.$key.'}}'; }, array_keys($vars));
    $values = array_values($vars);

    return str_replace($keys, $values, $template);
}

Tendo como exemplo o seguinte código.
$vars     = array('nome' => 'foo', 'email' => 'email@example.com');
$template = '{{nome}} Lorem Ipsum is simply dummy text of the printing and typesetting industry {{email}}';

echo preg_parse($template, $vars).PHP_EOL;
echo replace_parse($template, $vars).PHP_EOL;

A saída é.
foo Lorem Ipsum is simply dummy text of the printing and typesetting industry firstname.lastname@example.com
foo Lorem Ipsum is simply dummy text of the printing and typesetting industry firstname.lastname@example.com

Porem na função preg_parse remove os espaços entre as tags {{ e }}, algo que a replace_parse não faz.
Comment: Quanto tempo em, igualmente.
Comment: *+1* pelo `preg_replace_callback`. *Off*: Ainda frequenta o Fórum-Invaders? Luis/hacker_wap!
Comment: Eventualmente acesso, uma vez por mês +/- eu dou uma espiada lá, você seria?
Comment: Eu era o *CoderSc*. Que bom vê-lo por aqui. =)
Comment: O primeiro exemplo parece bem interessante, vou dar uma testada nele. Obrigado.
Answer: Uma outra alternativa que pode ser utilizada é a função strtr, ela tem como objetivo, traduzir/substituir determinados caracteres de uma string. Veja um exemplo:
$texto = 'Bem-vindo ao Stack Overflow em Inglês';
$traducao = array('Inglês' => 'Português');

echo strtr($texto, $traducao); // Bem-vindo ao Stack Overflow em Português

Ver demonstração
Supondo que as variáveis nome e email já estejam definidas com o valor que você quer, faça o seguinte:
$mensagem = '{{nome}} Lorem Ipsum is simply text of the printing and typesetting industry {{email}}';
$nome  = 'Maria';
$email = 'firstname.lastname@example.com';

$traducao = array("{{nome}}"  => $nome,
                  "{{email}}" => $email,
                 );

echo strtr($mensagem, $traducao);

Ver demonstração
Answer: Para substituir dentro de uma string podes usar o str_replace();.
A sintaxe é:

$stringFinal = str_replace("a substituir", "substituto", "string original");

Assim no teu caso poderia ser algo como
$email = str_replace({{variavel}}, $variavel, $corpoDoEmail);

Também podes usar arrays no str_replace. Desta maneira podes substituir muitos pedaços de cada vez:
$pedacos =     array('{{nome}}', '{{mail}}');
$substitutos = array($nome, $email);
$output  =     str_replace($pedacos , $substitutos , $corpoDoEmail);

Comment: Vamos [continuar esta discussão no bate-papo](http://chat.stackexchange.com/rooms/23846/discussion-between-sergio-and-italo-izaac).
Comment: isso dá certo, porém se eu tiver 100 variáveis terei de fazer isso para cada uma das 100. Queria que fosse de forma automática. Já tentei com o `preg_replace()` mas não obtive nenhum resultado.
Comment: @ItaloIzaac podes explicar melhor na pergunta e juntar um exemplo? 100 variáveis diferentes no texto ou fazer a substituição para 100 textos diferentes?
Comment: @ItaloIzaac editei a resposta.
Comment: Eu dei uma pequena explicação no original, dê uma olhada. Obrigado desde já por tentar ajudar!
Comment: @ItaloIzaac o que queres dizer "de forma automática"? fazendo isso com arrays no `str_replace` é tb automático...
Comment: Mas eu teria que colocar cada uma das variaveis dentro do array ... de forma automática, sem eu precisar ter de adicionar mais uma variavel sempre que eu alterar uma dela.


A question regarding lebesgue stieljes measure in 2 dimensions

Question: I am trying a problem that  is based on lebesgue stieljes measure in 2 dimensions. I could not solve it part although I tried manipulating Right hand side several times. Actually I am confused where to use $ x_i $ $ \le $ $ y_i $  , if i= 1,2 .
Question is - If X : $ R^2 $---> R and F: $ R^2 $  --->R .
Then prove monotonicity ie
if x= ( $x_1$ ,$ x_2$) and y= ( $y_1$,$y_2$ ) and  $ x_i $ $ \le $ $ y_i  $  for i = 1,2
Then prove that $ \delta $ F(x, y) = F($ y_1$, $ y_2 $)
+ F($ x_1$, $ x_2$) - F( $ x_1$, $ y_2 $) - F( $ y_1$, $x_2$) is always $\ge  $ 0 .
Can some one please help .
Answer: If $\mu$ is a finite measure on the Borel sigma algebra of  $\mathbb R^{2}$ abd $F(x,y)=\mu((-\infty,x]\times (-\infty,y])$ then $F(y_1,y_2)+F(x_1,x_2)-F(x_1,y_2)-F(y_1,x_2)$ is nothing but $\mu ((x_1,y_1]\times (x_2,y_2])$. To see this write $(x_1,y_1]$ as the difference of $(-\infty,y_1]$ and $(-\infty,x_1]$ and $(x_2,y_2]$ as the difference of $(-\infty,y_2]$ and $(-\infty,x_2]$
Comment: @ Kavi Rama Murthy Thank you


Vegas NHL team and trades

Question: If I remember correctly, the new Las Vegas NHL team will be picking third in each round of the 2017 Entry Draft and will be subject to the draft lottery as well. I have a question:

Are the existing franchises allowed to make deals with Vegas such that they pick/do not pick a particular player from them in the Expansion Draft in exchange for draft picks?
Answer: The answer to your question is yes.
Current NHL teams are allowed to negotiate with the Vegas team, although it is completely up to Vegas to accept the offers. It is common in expansion drafts (in most sports) to have existing teams convince the new team to not select a player by giving them a certain package in return.
The trade would officially be as follows. The existing team sends a player/pick package in exchange for "future considerations", which in this case, refer to the expansion team not selecting (or selecting) a certain player.
For a comparable, look in the 1998 NHL expansion draft, with the Nashville Predators:

Los Angeles traded Kimmo Timonen and Jan Vopat to Nashville after the Predators agreed not to select Garry Galley.

This is one of a many deals that have been made over the years regarding the expansion draft process.

Vegas NHL team and trades


How many Non-Borel sets are there?

Question: I'm currently doing a course on measure theoretic probability. In the course I learned that the cardinality of Borel $ \sigma $-algebra $ \mathscr{B} $ is the same as that of continuum $ \mathbb{R} $. But what is the cardinality of the set of Non-Borel Sets, let's call it $ \mathcal{S} $.
My inital guess is along these lines. That since $ \mathcal{S} = \mathscr{B^{c}} $. We can write that,
$$ \mathbb{2^R} = \mathcal{S} ~ \cup \mathscr{B} $$ Assume that $ \mathcal{S} $ has the same cardinality as $ \mathbb{R} $. Now we know that $ \mathscr{B} $ also has the same cardinality as that of $ \mathbb{R} $. But their union $ \mathbb{2^R} $ has a stricly greater cardinality than $ \mathbb{R} $. Again assuming that union of uncountable sets of same cardinality has the same cardinality (I'm aware that this is true for countable sets, but not sure about uncountables), this results in a contradiction.
Hence the set $ \mathcal{S} $ must have a strictly bigger cardinality than $ \mathbb{R} $. Are the approach and the conclusion correct?
Comment: Your argument needs some tweaking. Here's the simplest way to do it, in my opinion. Let $f:\mathbb R\to\mathbb R\setminus{(0,1]}$ be defined as $$f(x)=\begin{cases}x&x\leq0\\x+1&x>0\end{cases}$$I'll leave it to you to show that this map is an injection. Let $X$ be some non-measurable set in $[0.25,0.75]$. Let $g:\mathcal P(\mathbb R)\to\mathcal P(\mathbb R)$ be defined by $g(S)=f(S)\cup X$. I'll leave it to you to show that the image of $g$ consists of only immeasurable sets, and that $g$ is an injection. By CSB the cardinality of $\mathcal S=\left\vert\mathcal P(\mathbb R)\right\vert$.
Comment: You argument is correct. If $A$ and $B$ are infinite sets of the same cardinality, the $A\cup B$ has also the same cardinality. It true no matter $A$ and $B$ is countable or uncountable.
Answer: The sum of two infinite cardinals is the larger of the two cardinals.
Comment: And it follows that $S$ has the same cardinality as $2^{\mathbb R}$ (which can be stronger than just saying it's strictly bigger than $\mathbb R$).
Comment: As an $\epsilon$-generalization, this is still true under the assumption that at least one of the cardinals is infinite.

How many Non-Borel sets are there?


box moved when using flexible box model

Question: I am trying to build a nested layout with the flexible box model in firefox.
I managed to boil it down to a simple example:
HTML:

CSS:
#outer {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
}

#inner {
    border: 1px solid green;
    display:block;
    width: 100%;
    height: 100%;
    position: absolute;

}

#content {
    display: -moz-box;
    width: 100%;
    height: 100%;
    border: 1px solid red;
}

#scroller {

    \-moz-box-flex: 1;
    display:block;
}

Also I made this small jsFiddle: http://jsfiddle.net/dankurka/27GDt/1/
The problem is that the content div gets rendered about 12 px to low (as you can see from the borders in the jsFiddle). How can I fix this?
Answer: Add vertical-align: top:
#content {
    display: -moz-box;
    width: 100%;
    height: 100%;
    border: 1px solid red;
    vertical-align: top;
}

Comment: thank you very much, already invested a lot of time to figure this one out :)

box moved when using flexible box model


Gamma/Poisson Posterior Distrib Given Prior:

Question: I need to find the model over a period of length t. This is what I've done:
Based on the Bayes' theorem, the relationship between the prior, the posterior, and the likelihood function is
$p(\theta|x) = \frac{p(x|\theta)p(\theta)}{\int p(x|\theta^{`})p(\theta^{`})}$.
Before computing the posterior $p(\lambda|x)$ with prior $g(\lambda;r,\alpha) = \frac{\alpha^{r} \lambda^{r-1} e^{-\lambda\alpha}}{\Gamma(r)}$ and Poisson pmf $p(x|\lambda(t))= \frac{e^{{-\lambda}t}(\lambda*t)^x }{x!}$
After canceling some terms in the numerator and denominator, $p(\lambda(t)|x)= \frac{ (\alpha+t)^{r+x} \lambda^{r+x-1} e^{-\lambda(\alpha+t)}}{\Gamma(r+x)} = Gamma(\lambda; r + x, \alpha+t)$.
Now we know that $E[X(t)] = \frac{r+x}{\alpha+t}$.
However I am trying to calculate:
$E[X(t^∗+t)−X(t)|X(t)]$ and not sure how to approach this problem.
Comment: How long is the period from $t$ to $t^*+t$?  See if you can figure out how that applies if you were to rewrite your first sentence.  Also, you should put the "self-study" tag on for homework or self-study problems.
Comment: The period from $t$ to $t^*+t$ is $t*$. Do I just re-derive posterior?
Comment: You don't have to rederive it... $t$ is just a variable indicating the length of the period.  If the length of the period is $t^*$, just use $t^*$ instead if $t$.
Comment: @jbowman I posted what I think may be the solution below - would love your thoughts on it.
Answer: I am thinking of doing this:
$g(\lambda;r,\alpha) = A= \frac{\alpha^{r} \lambda^{r-1} e^{-\lambda\alpha}}{\Gamma(r)}$ and Poisson pmf $p(x|\lambda(t))= B = \frac{e^{{-\lambda}t}(\lambda t^*)^x }{x!}$
and using $p(\lambda(t)|x)= C= \frac{ (\alpha+t)^{r+x} \lambda^{r+x-1} e^{-\lambda(\alpha+t)}}{\Gamma(r+x)} = Gamma(\lambda; r + x, \alpha+t)$.
and now recalculating/solving for
$p(\theta|x) = \frac{p(x|\theta)p(\theta)}{\int p(x|\theta^{`})p(\theta^{`})}$.
So using the simplified notation,
I would obtain: $\frac{AB}C$ which would be another Gamma at which point the $E[X=t^*]$ is $r/\alpha$
Comment: You are overthinking it. You have an expression for E[x(t)] and you want to find E[x(t*)] .  Just substitute t* everywhere you see t.  t is a parameter, it's not fixed.  If it takes on the value 2, substitute 2 everywhere.  If it takes on the value t*, just substitute t* everywhere.
Comment: But doesn't seeing the first $t$ give info about the true value of $\lambda$ so we have to use the posterior distribution of $\lambda$
Comment: Please ignore my confusing initial comment here.  To clear up a little confusion in your original post, you have $E[X(t)] = \frac{r+x}{\alpha+t}$.  This isn't quite right, it's $E[\lambda|X,t]$.  So, after you've seen the first $(x,t)$, you have the $x$ and $t$ necessary to plug into $\frac{r+x}{\alpha+t}$ to get the posterior mean of $\lambda$.  Now, for $X(t^*+t)-X(t)$, that's the same (distributionally) as $X(t^*)$, so will have mean $\lambda t^*$.   You can plug the expression for $E[\lambda|x,t]$ right in to find $E[X(t+t^*)-X(t)]$.
Comment: @jbowman what do you mean by plug in?
Comment: put into, substitute into.


Need an explanation on a shift syntax in code - C++

Question: I need some further explanation on a code I don't quite understand.
This is a program that takes a num = 25 and starts moving it left with a << syntax.
#include <iostream>
using namespace std;

int main(){

    cout << "Shift to the left" << endl;

    short numb = 25;

    cout << "Starting value: ";

    for (int i = sizeof(short)*8 - 1; i >= 0; i--)
        cout << (((1 << i) & numb) == 0 ? "0" : "1");
    cout << " " << numb << endl;

    for (int i = 0; i < sizeof(short)*8; i++){
        numb <<= 1;
        cout << "Shift" << (i+1 < 10 ? "0" : "")
                         << i+1 << "        : ";

        for (int i = sizeof(short)*8 - 1; i >= 0; i--)
            cout << (((1 << i) & numb) == 0 ? "0" : "1");
        cout << " " << numb << endl;
    }
    return 0;

}

After the line where the first for loop is executed (the count line), what value does the & syntax takes into consideration? ((1 << i) & numb)
I don't understand how the program can take ((1 << i) & numb), compares the two and return a value.
Also why do we declare i to be sizeof(short)*8 - 1? Why don't we just type in 16-1? Is there a specific reason to do this or is it just to make the code look more complex?
And an explanation on why we even declare i to be 15-1 would be highly appreciative.
Hope I haven't given you too much, I'm a beginner and I need some guidance with some problems to which answers I can't still yet come up with by myself.
Thanks!
Comment: `sizeof(short) * 8` is the number of bits in a `short`. `8` should really be `CHAR_BIT`. `sizeof(short) * 8 - 1` is the number of bits one has to left-shift `1` to get a value where the highest bit of a `short` is set. `((1 << i) & numb)` yields `0` when the bit at position `i + 1` is not set.
Comment: `sizeof(short)` is not guaranteed to be `2`.
Comment: `& syntax` here is *bitwise and* operator
Answer: The bitwise shift operators are the right-shift operator (>>), which moves the bits of shift_expression to the right, and the left-shift operator (<<), which moves the bits of shift_expression to the left. There are also two complex operators that can be used to assign the value directly to the value on left. These are the <<= operator and the >>= operator.
The left-shift operator causes the bits in shift-expression to be shifted to the left by the number of positions specified by additive-expression. The bit positions that have been vacated by the shift operation are zero-filled. A left shift is a logical shift (the bits that are shifted off the end are discarded, including the sign bit).
The right-shift operator causes the bit pattern in shift-expression to be shifted to the right by the number of positions specified by additive-expression. For unsigned numbers, the bit positions that have been vacated by the shift operation are zero-filled. For signed numbers, the sign bit is used to fill the vacated bit positions. In other words, if the number is positive, 0 is used, and if the number is negative, 1 is used.
Demo Code:
using namespace std;
int main() {
   int a = 1, b = 3;

   // a right now is 00000001
   // Left shifting it by 3 will make it 00001000, ie, 8
   a = a << 3;
   cout << a << endl; // Gives output 8

   // Right shifting a by 2 will make it 00000010, ie, 2
   a = a >> 2;
   cout << a << endl;  // Gives output 2
   return 0;
}

The result of a right-shift of a signed negative number is implementation-dependent. If you left-shift a signed number so that the sign bit is affected, the result is undefined.


Como o FireMonkey(Delphi) compila para Android?

Question: Efetuei algumas pesquisas mas não obtive bons resultados, a pasta do projeto fica aparentemente igual a um projeto comum do Delphi ou C++!

VCL - Delphi
FMX - Firemonkey

Observem:

Com exceção da pasta Android, onde contem algumas sub-pastas, é possível encontrar o APK já compilado, arquivos .XLM, e diversos arquivos com a extensão .SO (essa não faço ideia do que seja).
Programar para Android ou IPhone nessa IDE é a mesma coisa que programar para Delphi!
Então pergunto, como essa IDE compila para Android?
Seria pura Abstração de Classes Java?
EDIT

A possibilidade de desenvolver para Android, foi implementada na
  versão XE5!
  Para desenvolver Android com o RADStudio precisamos das seguintes ferramentas:
Java Development Kit (JDK)
Android Software Development Kit (SDK)
Android Native Development Kit (NDK)
Comment: Usando um compilador para cada plataforma? Acho que não está claro exatamente o que você perguntou...
Comment: Ele usa o NDK, mas como eu não sei, mas tenha certeza que existe um passo intermediário em C ou Java, porque a Embarcadero prometeu código nativo pra todas as plataformas.
Comment: @DarkHyudrA Sim sim, já podemos desenvolver verdadeiramente nativo! Vou dar uma explorada por ae sobre a NDK e ver o que acontece!
Comment: @DarkHyudrA não tem passo intermediário... É um compilador diferente. Só isso.
Comment: @EMBarbosa Fonte? Tu tá dizendo que eles tem um NDK alterado? Porque o NDK é bem claro dizendo com que linguagens ele consegue funcionar. E se a Embarcadero tivesse feito um código milagroso que passa direto de delphi pra dpk, por que o NDK é algo necessário na compilação? Eu não sou nenhum mestre do Deplhi, mas eu não consigo ver como possa acontecer a geração do dpk sem um passo intermediário. É a mesma coisa com Haxe, haxe é compilado pra C que aí o código C é que é compilado pela NDK pra gerar o dpk.
Comment: @DarkHyudrA Fonte? Onde é que o NDK diz com que linguagens ele consegue funcionar e que não pode ser uma linguagem compilada diferente de C ou Java?
Answer: Até onde deu para entender, basicamente é isto, ele abstrai as classes e compila o Apk (não tão simples assim).

Traduzido de uma nota:
Desenvolvedores Delphi são amplamente protegidos contra a complexidade da NDK, já que o código usando o alto nível de abstração fornecida pela biblioteca de tempo de execução (RTL) e do quadro FireMonkey. Se isso é tudo que você precisa que eu deveria pensar que tudo ficará bem. Se você tem uma biblioteca Java você precisa chamar a partir da aplicação Delphi Android, você precisa usar JNI (Java Native Interface), que não é muito divertido.

Outro ponto a salientar é que o FireMonkey emula controles visuais, como botões, listas etc. Os usuários podem não perceber, mas os componentes comportam exatamente como os controles nativos, mas isso é complicado de fazer perfeitamente.
A promessa da Embarcadero é que desenvolveríamos de forma nativa em relação ao código, mas não em relação aos controles que utiliza.
Aqui podemos encontrar a documentação da NDK
VCL é incompatível com FireMonkey
FireMonkey (FMX) e a biblioteca de componentes do Visual (VCL) não são compatíveis e não devem ser utilizados em conjunto no mesmo módulo. Isto quer dizer que um módulo deve ser exclusivamente um ou outro, quer FireMonkey ou VCL. A incompatibilidade é causado por diferenças quadro entre FireMonkey (FMX) e VCL.
No entanto, você pode:
Use uma biblioteca FireMonkey com uma aplicação de VCL, ou usar uma biblioteca VCL com uma aplicação FireMonkey, conforme descrito em bibliotecas compartilhadas para Mac OS X.
        Leia as orientações gerais para a conversão de uma aplicação VCL para FireMonkey em Convertendo de VCL para FireMonkey.
        Leia um procedimento geral para a migração de uma aplicação de VCL para FireMonkey na migração de aplicativos VCL para múltiplos dispositivos.
        Obter um programa VCL-to-FireMonkey conversor em http://www.midaconverter.com/.
Três grandes bibliotecas são fornecidos pela RAD Studio:
FireMonkey (FMX) é uma biblioteca de componentes visuais com gráficos sofisticados, animação e capacidades de estilo. Você pode criar aplicações FireMonkey para qualquer plataforma de destino suportados.
Biblioteca de Componentes Visuais (VCL) é uma hierarquia de objetos de componentes visuais que são suportados apenas no Windows (em aplicações Win32 e Win64).
Run-Time Library (RTL) é uma biblioteca processual compartilhada por Delphi e C ++ para qualquer plataforma de destino suportados. A RTL é composta por membros dos sistema, System.SysUtils, System.IOUtils e System.Classes unidades.
Você pode usar livremente a RTL em um aplicativo FireMonkey, mas você não pode usar diretamente o VCL em um módulo de aplicação FireMonkey.
Fonte


Amazon SES error on VERIFIED domain and EMAIL, correct region (Laravel)

Question: Trying to send email through Amazon SES. Both the domains and email are verified, account is out of the sandbox (have been using it without problems a while ago), and the reqion is set correctly. trying it from Laravel 5.4
right now is
SesException in WrappedHttpHandler.php line 192:
    Error executing "SendRawEmail" on "https://email.eu-west-1.amazonaws.com"; AWS HTTP error: Client error: `POST https://email.eu-west-1.amazonaws.com` resulted in a `400 Bad Request` response:
<ErrorResponse xmlns="http://ses.amazonaws.com/doc/2010-12-01/">
<Error>
<Type>Sender</Type>
MessageReje (truncated...)
MessageRejected (client): Email address is not verified. The following
identities failed the check in region EU-WEST-1: email@example.com -
<ErrorResponse xmlns="http://ses.amazonaws.com/doc/2010-12-01/">
<Error>
<Type>Sender</Type>
MessageRejected
<Message>Email address is not verified. The following identities failed the
 check in region EU-WEST-1: firstname.lastname@example.com</Message>
</Error>
<RequestId>82e11e14-c1fc-11e7-9836-57d1bfe12a45</RequestId>
</ErrorResponse>

does anyone have any clue?
Comment: SES regions are (mostly) independent.  The address must be verified in the region you're connecting to.  Check this?  You're invoking eu-west-1.  Is that where you're verified?
Comment: yessss, it is verified, i checkid it for 1000 times. keepm in mind that this worked for quite a bit, and i didnt modified a thing. just noticed that suddenly no mails are passed.
Answer: I know that this is fairly old, but this fixed my issue.

It is complaining your To: email address is not verified. Looks like you are in SES Sandbox mode. Until you change your SES account to production account, you have to verify your Sender email address too.
  When you tested both From and To are your email address (which is already verified).
  From: Verifying Email Addresses in Amazon SES
  Until your account is out of the Amazon SES sandbox, you must also verify the email address of every recipient except for the recipients provided by the Amazon SES mailbox simulator. For more information about the mailbox simulator, see Testing Amazon SES Email Sending. For more information about moving out of the sandbox, see Moving Out of the Amazon SES Sandbox.
  Moving Out of the Amazon SES Sandbox

Reference: SES Email not verified for "to" field in Laravel
Hope you have a great day!
Comment: i hope this answer will help me sending emails. as it was working few days back. but now I see this error.
Answer: One thing pops to mind is that you have several aws accounts configured you are not using the correct account.
My suggestion is to rotate your existing AWS key and update your Laravel configuration file and see if you get the same error.
Or try entering the wrong AWS AccessKey.
As far as I can tell, the error is a standard error and my only conclusion is that the keys you are using are not bound to that account.
Comment: got to try it and inform you, just for curiosity... :)
Comment: tried using wrong key (on purpose), the error message is different (the process fails at the auth level, before sending)
Comment: How about creating a new keypair? Or a new user and a new keypair for the new user?


Zenoss MySQL database backups are huge after multiversion upgrade

Question: The Context:
We ran Zenoss 2.2 for way too long, and decided it was time to upgrade to the current version, 3.2. I followed the upgrade steps here, and checked to make sure everything was working after each incremental version upgrade. I made sure to restart when unsure, and verified that all of the database migrations (and the preupgrade ZenPack) applied properly. Everything worked, with the exception of a couple of outdated ZenPacks that we weren't using much anyway. We run CentOS 5, so I used the old rpm'd versions available on sourceforge for the intermediate upgrades, and then made the last "hop" to 3.2 using yum. For some reason yum didn't install the core zenpacks for 3.2, so I did that manually, and then everything was fine: zenoss worked great, no issues. Well...except one.
The Problem:
We schedule backups using cron/mysqldump of Zenoss' events database. Those backups go off daily, and usually take up around 7-800MB of space. After the Zenoss upgrade, those backups are taking up more than 200GB (with a 'G'!) of space, though I haven't seen one finish yet. To run the backup, we are using
mysqldump -A | gzip > dump-12-28-2011.sql.gz

We have MySQL 5, so --extended-insert is a default parameter for mysqldump. Zenoss is the only thing using the database (and the "events" database is the only one present besides the mysql one), and I've turned Zenoss off for the duration of the dump. My ibdata1 (we only have 1) file is around 13GB now. I don't know how big it was before the upgrade. I have tried this solution to delete old events detail entries. The query ran forever, but afterwards the dumps balloon in size the same way they did before. Why is this happening? I have backups from before the upgrade, should I revert?
TL;DR:
Why are my Zenoss "events" database dumps 1000X larger after a multiversion upgrade?
Answer: After a couple of days of digging, I figured out the problem: InnoDB corruption.
Out events database really WAS quite large (we were retaining a year's worth of old events, and had a ton of windows computers reporting tetchy little things, so we had a lot of data), but that wasn't the issue. I started running $ZENHOME\Products\ZenUtils\ZenDeleteEvents.py -n 60 to trim our events history back to 60 days, and MySQL crashed after it got about halfway done. I looked in the MySQL logs, and there were a ton of InnoDB corruption errors. This was the eventual solution:

Stop Zenoss
Stop MySQL
Put MySQL in InnoDB recovery mode 2
Start MySQL
Dump the events database via mysqldump -uzenoss -pzenoss events >
dump.sql For some reason, after the pruning via ZenDeleteEvents.py,
the dump worked, and didn't grow unmanagably large.
Stop MySQL
Take the ibdata/innodb log files/events schema definitions out of
/var/lib/mysql, and put them somewhere for safekeeping (in case the
subsequent steps didn't work)
Take MySQL out of recovery mode
Start MySQL
As the zenoss user, run zeneventbuild localhost zenoss zenoss
 events (these parameters might be different for others: the syntax
 is zeneventbuild <dbhost> <dbuser> <dbpassword> <dbname>
As root, run mysql, then grant super on *.* to
 'zenoss'@'localhost' identified by 'zenoss';
Restart MySQL
Restore the events database dump, via mysql -uzenoss -pzenoss
 events < dump.sql
Restart MySQL again (probably unnecessary, but I'm paranoid)
Start Zenoss

After that, everything worked fine, though I didn't have a lot of historical events (which I wasn't using anyway). This thread in the zenoss forums was instrumental in helping me figure out what was going on.


REST API to download large sized files in JAVA 8 without running into timeout

Question: I have client and server side apps which are designed to have a session no longer than 30 seconds.
I am writing a rest api to download reports which sometimes contains really large amount of data but it's running into timeouts. Is there any better way to do this so it doesn't exceed time limit of 30 seconds?
Here is the controller at server side:
@GetMapping("/download")
public void downloadReport() {
    List<Person> people = getPeople(); // data retrieval logic

    response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
    response.addHeader(HttpHeaders.CONTENT_TYPE,

    MediaType.APPLICATION_OCTET_STREAM_VALUE);

    for (String person : people) {
        StreamUtils.copy(new ByteArrayInputStream(person.concat("\n").getBytes(StandardCharsets.UTF_8)),
   response.getOutputStream());
    }
    response.flushBuffer();
}

Here is the code on client side:
@GetMapping("/download")
public void downloadReport(@RequestParam MultiValueMap<String, String> downloadRequest, HttpServletResponse response) throws Exception {
    ResponseEntity<byte[]> result = restClient.downloadReport(URI, downloadRequest);
    if (result.getStatusCode().equals(HttpStatus.OK)) {
        String fileName = result.getHeaders().getContentDisposition().getFilename();
        response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
        response.addHeader("Content-Type", "application/octet-stream");
        StreamUtils.copy(result.getBody(), response.getOutputStream());
        response.flushBuffer();
    } else {
        throw new Exception("Could not download report.");
    }
}

Any advice is much appreciated.
Comment: Are you sure the problem is in your code? Is the download speed slower than you'd expect? Or is the file just too large to be downloaded in under 30 seconds? Because if that's the case, you'll either have to break the file up into smaller parts or disable/enlarge the timeout for download endpoints.
Comment: did you try flushing after each person?
Comment: The best way to handle "Downloading context" is to use "Websockets".
Comment: @JonathanJOhx why? http is perfectly capable of handling very long downloads without issue. it's just a matter of letting the client know that you still have stuff to send
Comment: @AMagic, you have an api that calls an api, gets the response, and sends it to its own client? isn't that what a proxy does?
Comment: @njzk2 Using Websockets for Long Downloads:
Real-time Updates > Websockets are ideal when you need real-time updates during the download process. With Websockets, the server can send data to the client as soon as it's available, allowing for a more interactive and real-time experience.
Bidirectional Communication > Websockets allow bidirectional communication, meaning the client can also send data or control messages to the server, which is useful for more interactive applications.
Comment: @Jorn Breaking the files is a good idea but isn't an option. My guess is that it's taking longer in `StreamUtils.copy` on both client and server side. There could be some way to make it faster?
Comment: You haven't shown where `StreamUtils` is coming from (Apache?), but I doubt there's a bottleneck there. Copying one stream to another is very much a solved problem, and if you're using a big library, I wouldn't assume it's the bottleneck. However, using the `ByteArrayInputStream` is a lot of unneccessary overhead. You'd be better off writing to the output stream directly.
Comment: You could also open a normal `java.net.ServerSocket`, get its local port, then forward the client to that port, or in any other way confer the message of the new port to the client. Maybe even use a `java.net.Socket` in the client. This way you could use the o-so-much-better raw Sockets instead of HTTP, maybe even use `ZipOutputStream`, and have no more timeouts to worry about. The big and ugly downside is how to handle firewalls and proxies and other routing interference...
Comment: But it looks like the real problem in your code lies with you handling all that String data, wrapping all that up in a huge array (check your systems swap file activity!), and only once it's all there, then write it to the `OutputStream`. Maybe try writing every line that `person` has onto the stream directly. Maybe also `flush()` afterwards, if there's a lot of time between the last write and getting the next person ready... And another problem  is that the server does not send how much data it actually sends, so maybe the client is waiting for more. Try closing the connection after sending.
Answer: Well, there's one optimization you can easily do. Writing to a ByteArrayInputStream first, then copying that to the OutputStream is not needed.
@GetMapping("/download")
public void downloadReport() {
    List<Person> people = getPeople(); // data retrieval logic

    response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
    response.addHeader(HttpHeaders.CONTENT_TYPE,

    MediaType.APPLICATION_OCTET_STREAM_VALUE);

    try (PrintWriter writer = new PrintWriter(response.getOutputStream(), false, StandardCharsets.UTF_8)) {
        for (String person : people) {
            writer.write(person);
            writer.write("\n");
        }
        response.flushBuffer();
    }
}


Simple functions are dense in L1

Question: This is question 5.D in Bartle's Elements of Integration.
If $f \in L(X,\mathcal X,\mu)$ and $\epsilon > 0$, then there exists a $\mathcal X$ − measurable simple function $\phi$ such that: $\int|f-\phi|d\mu<\epsilon$.
The answer seems trivial when $f$ is either (a.e.) positive or (a.e.) negative. However, when it is both positive and negative, I cannot define simple function that works for both cases.
Comment: Hint:  $f= \max(f,0)-\max (-f,0)$. .
Comment: I tried that. Approximate the $f^+$ and $f^-$ through non-negative simple functions $\phi^+$ and $\phi^-$, but this forces me to define $\phi =\phi^+-\phi^- $ which is not simple because it is not positive.
Comment: https://en.wikipedia.org/wiki/Simple_function
Comment: So, $\phi$ is a simple function since it takes only a finite number of values. Thank you. Note myself: read definitions carefully in the future.
Answer: Begin by noticing that $f=f^+-f^-$ where$$
f^+(x)=\max\{f(x),0\}\text{ and }f^-(x)=\max\{-f(x),0\}
$$and, similarly, $\varphi=\varphi^+-\varphi^-$ for a simple function $\varphi$. Since the functions $f^+,f^-,\varphi^+$ and $\varphi^-$ are all nonnegative, the following results are trivial$$
\int |f^+-\varphi^+|\,d\mu<\frac{\varepsilon}{2}\text{ and }\int |f^--\varphi^-|\,d\mu<\frac{\varepsilon}{2}
$$for any $\varepsilon>0$. Then, we have$$
\int |f-\varphi|\,d\mu\leq \int |(f^+-f^-)-(\varphi^+-\varphi^-)|\,d\mu\leq \int |f^+-\varphi^+|\,d\mu+\int |f^--\varphi^-|\,d\mu<\varepsilon.
$$
Comment: Why $\int |f^+ - \phi^+| d\mu < \frac{\varepsilon}{2}$? I know that given $\varepsilon > 0$, exist a simple function $\phi^+$ such that $|f^+ - \phi^+| < \frac{\varepsilon}{2}$, then $\int |f^+ - \phi^+| d\mu < \frac{\varepsilon}{2} \int d\mu \Longrightarrow \int |f^+ - \phi^+| d\mu < \frac{\varepsilon}{2} \mu(X)$. I think it's not possible choose $\varepsilon = \frac{\alpha}{\mu(X)}$ for an arbitrary $\alpha > 0$ unless $\mu(X) < + \infty$, so why $\int |f^+ - \phi^+| d\mu < \frac{\varepsilon}{2}$?

Simple functions are dense in L1


Deletar item do listview no Xamarin

Question: Como faço para deletar um item do meu listview ? Eu deleto o item, porém quando clico no item seguinte é selecionado o mesmo item que eu havia deletado.
Meu código:
<code>adapter.Remove("LISTA 1");
adapter.Remove("LISTA 2");
adapter.Remove("LISTA 3");
adapter.Remove("LISTA 4");
</code>
Comment: do you using ObservableCollection in your itemsource? Só pra constar, esse é StackOverFlow em português, caso você seja brasileiro, aqui pode postar a pergunta em Pt msm.
Comment: Eu não estou usando !
Comment: Por favor Renato, traduza sua pergunta ou ela será fechada pela comunidade.
Answer: Bom, creio que possa tentar algum dos pontos que vou listar abaixo:

Verifique se seu adapter possui uma sobrecarga para utilizar uma ObservableCollection no lugar do List, já que o observablecollection vai notificar quando algo for alterado.
Você pode fazer o set do seu adapter novamente após remover o item da sua lista, dessa forma carrega um lista já sem o item que foi removido
Você pode verificar o funcionamento do NotifyDataSetChanged do seu Adapter, seria o mesmo funcionamento do ObservableCollection que listei primeiro.
Comment: Obrigado pela dica BrianSouza, fazendo set do adapter novamente funcionou muito bem, queria aproveitar a oportunidade te pergunta sabe como que faz para mudar um item da listview de cor ?
Comment: Opa, valeu. Marca como resposta pois sua dúvida pode ser a mesma de outros. Não esqueça de editar seu post para deixar no moldes do Stack. Sobre a sua dúvida, abra outro post para podermos separar os tópicos.

Deletar item do listview no Xamarin


Prove there exists a unique $n$-th degree polynomial that passes through $n+1$ points in the plane

Question: I know given two points in the plane $(x_1,y_1)$ and $(x_2,y_2)$ there exists a unique 1st degree (linear) polynomial that passes through those points. We all learned in Algebra how to find the slope between those points and then calculate the y-intercept.
To take it down a notch, given the point $(a,b)$, the unique 0th degree polynomial that passes through it is $y=b$.
My conjecture is that given three points $(x_1,y_1)$, $(x_2,y_2)$, and $(x_3,y_3)$, there exists a 2nd degree (quadratic) polynomial that passes through these points, and furthermore, that polynomial is unique. I wonder, how would one determine the equation of this quadratic?
If my conjecture is correct, a corollary would be the generalization that given any $\left(n+1\right)$ points in the plane, there exists one unique $n$th degree polynomial that passes through those points.
Please prove, or disprove with a counter-example.
Further Readings:

658789 is a related question but I'm not sure if it's exactly what I'm looking for.
This very cool interactive web app lets you drag points around and shows the polynomial that goes through them
Comment: You seem to be looking for interpolating polynomials. See this: http://en.wikipedia.org/wiki/Polynomial_interpolation#Uniqueness_of_the_interpolating_polynomial
Comment: There is a unique polynomial of degree $\le n$ through $n+1$ points $(x_i,y_i)$, where the $x_i$ are distinct. The polynomial need not have degree *exactly* $n$.
Comment: Any arbitrary 3 points, then.
Comment: There is no quadratic (degree two) polynomial which passes through the points $(0,1)$, $(1,1)$, and $(2,1)$. There is however a constant function which does.
Comment: @AndréNicolas Not true. Given the points $(0,0)$, $(1,1)$, and $(2,3)$, there does not exist a 1st degree polynomial (a line) that goes through all 3 points. Did you mean "$\ge$"?
Comment: I asked that the $x_i$ be distinct.
Answer: Assume you have given $n+1$ points $(x_1,y_1),\cdots, (x_{n+1},y_{n+1}).$ (Of course, $x_i\ne x_j$ if $i\ne j.$) A polynomial of degree equal to or smaller than $n$ is of the form $p_n(x)=a_nx^n+\cdots+a_1x+a_0.$ To study the existence and uniqueness of such a polynomial consider the system of linear equations:
$$
\left\{\begin{array}{ccc}
a_nx_1^n+a_{n-1}x_1^{n-1}\cdots+a_1x_1+a_0 & =& y_1\\ \vdots & &\\
a_nx_{n+1}^n+a_{n-1}x_{n+1}^{n-1}\cdots+a_1x_{n+1}+a_0 & =& y_{n+1}
\end{array}\right.
$$
We write the system as
$$
\begin{pmatrix}x_1^n & x_1^{n-1} &\cdots & x_1 & 1 \\ \vdots & \vdots & \ddots & \vdots \\ x_{n+1}^n &  x_{n+1}^{n-1}& \cdots & x_{n+1} & 1\end{pmatrix} \begin{pmatrix} a_n \\ \vdots \\ a_0 \end{pmatrix}=\begin{pmatrix} y_1 \\ \vdots \\ y_{n+1} \end{pmatrix}
$$
Since the matrix of coefficients of the system is non singular (it is a Vandermonde matrix (see Vandermonde)) the system has a unique solution, that is, there exists one polynomial of degree $n$ through the $n+1$ given points, and it is unique.
Comment: I think it would be waaaaay simpler to just say there are n unknowns with n equations. People are much more likely to be familiar with this resulting in a unique answer than they are to know what a Vandermonde matrix is (even though saying n unknowns with n equations is a slight simplification since the equations must be linearly independent).
Comment: I think you forgot the equation for $(x_{n+1}, y_{n+1})$. Otherwise your Vandermonde matrix wouldn't even be quadratic ($n$ rows, $n+1$ columns) and you couldn't argue with the determinant
Comment: @Quotenbanane You are right. Thank you for pointing out my mistake.
Comment: @JosephGarvin The first half of the answer already clearly shows n unknowns with n equations. So, if you want to stop there, you can stop there. He's just noting that the difficulty of proving that those n equations have a solution, is equal to the difficulty in proving that a Vandermonde has non-zero determinant, because both are proving the exact same thing. (Such a proof isn't that hard though)
Comment: The polynomial $p_n(x)$ as stated " of degree n" is not correct. It's of a degree $\leq n.$ This might seem trivial but it's extremely important to not remember the interpolation problem (and solution) as: throught $n+1$ points there is unique polynomial of degree $n$-- this is not true. What's true is that through $n+1$ points there is unique polynomial of degree $\leq n.$
For example every polynomial $p$ of degree $\leq n$ conincides with it's Lagrange interpolating polynomial $L_n(p,x)$ of $n+1$ nodes. And the Lagrange polynomial of any function of $n+1$ nodes is of degree most $n.$
Answer: For an easy proof of uniqueness of such a polynomial (johannesvalks gives existence) assume we have $f,g$ of degree $n$ with $f(x_i)=g(x_i)=y_i$ for $1\leq i \leq n+1$.
Then $f-g$ has degree no bigger than $n$, so if $f-g\ne 0$ then $f-g$ has at most $n$ roots, but $f-g$ has at least $n+1$ roots so $f=g$.
Answer: You can define
$$ P_k(x) = \prod_{\jmath \ne k}^n \frac{ x - x_\jmath }{ x_k - x_\jmath } $$
It is clear that
$$ P_k(x_\ell) = \delta_{k\ell} $$
Then you can define
$$ f(x) = \sum_{k=1}^n y_k P_k(x) $$
and you will find
$$ f(x_\ell) = \sum_{k=1}^n y_k \delta_{k\ell} = y_l$$
The function $f(x)$ is a polynomial of degree $n-1$
So in general, such a polynomial is given by
$$ f(x) = \sum_{k=1}^n y_k \prod_{\ell \ne k}^n \frac{ x - x_\ell }{ x_k - x_\ell} $$

Two points gives
$$ f(x) = y_1 \frac{x-x_2}{x_1-x_2} + y_2 \frac{x-x_1}{x_2-x_1} $$
Three points gives
$$ f(x) = y_1 \frac{x-x_2}{x_1-x_2} \frac{x-x_3}{x_1-x_3} + y_2 \frac{x-x_1}{x_2-x_1} \frac{x-x_3}{x_2-x_3} + y_3 \frac{x-x_1}{x_3-x_1} \frac{x-x_2}{x_3-x_2} $$
Four points gives
$$ f(x) = y_1 \frac{x-x_2}{x_1-x_2} \frac{x-x_3}{x_1-x_3} \frac{x-x_4}{x_1-x_4}
+ y_2 \frac{x-x_1}{x_2-x_1} \frac{x-x_3}{x_2-x_3} \frac{x-x_4}{x_2-x_4}\\
+ y_3 \frac{x-x_1}{x_3-x_1} \frac{x-x_2}{x_3-x_2} \frac{x-x_4}{x_3-x_4}
+ y_4 \frac{x-x_1}{x_4-x_1} \frac{x-x_2}{x_4-x_2} \frac{x-x_3}{x_4-x_3}$$
and so on...
Comment: Just to make sure I am following, does the "two points" then mean we're approximating a 2 degree polynomial? thank you!
Answer: johannesvalks' answer proves existence but not uniqueness.  The Lagrange interpolation polynomials used will have degree $\le n$, as each is the sum of polynomials. Given two polynomials $P,Q$ with $\deg(P),\deg(Q)\le n$ both passing through $n+1$ distinct points $(x_i,y_i)$ with $1\le i\le n+1$, divide to get $P=(x-x_i)P_i+y_i$ and $Q=(x-x_i)Q_i+y_i$, for some $P_i,Q_i$, so that $$P-Q=(x-x_i)(P_i-Q_i).$$  Then $P-Q$ has $n+1$ distinct roots, while $P$ and $Q$ have at most $n$, so $P-Q$ must be the zero polynomial.


Haskell Could not find module 'Random' when running GHCI, what should I do

Question: This is a guess number code.
when I run it, I got an error : could not find the module 'Random'. what should I do ?
module Main where

import IO
import Random

main = do
       hSetBuffering stdin LineBuffering
       num <- randomRIO (1::Int, 100)
       putStrLn "I'm thinking of a number between 1 and 100"
       doGuessing num = do
           putStrLn "Enter your guess:"
           guess <- getLine
           let guessNum = read guess
           if guessNum < num
              then do putStrLn "Too Low!"
                   doGuessing num
           else if guessNum > num
              then do putStrLn "Too High"
                   doGuessing num
           else do putStrLn "You Win!"

Answer: You should be using
import System.IO
import System.Random

instead.
Answer: Install random package. The easiest way to do this is to use cabal
cabal install random

Comment: @MathematicalOrchid No, it is no longer included in GHC version 7.2.1 http://www.haskell.org/ghc/docs/7.2.1/html/users_guide/release-7-2-1.html#id569450
Comment: How to do that? just adding this code or? could you explain it in detail? thanks so much
Comment: cabal is a system for managing haskell packages. If you are using linux, just install it from your distro's package manager (e.g. `sudo apt-get install cabal` in Ubuntu). I'm not familiar with Haskell development on Windows at all, so I can't help you in this case


How to create customer information form in home page and form data store in database in opencart

Question: I have tried to creating form but data are not save in database table.
I have written the following code.
view/common/home.tpl:
<form action="" method="post" enctype="multipart/form-data" class="form-horizontal form" id="contact">
<legend><?php echo $text_form; ?></legend>

            <?php echo $entry_first_name; ?>

              <input type="text" name="first_name" value="<?php echo $first_name; ?>" id="input_first_name" class="form-control" />
              <?php if ($error_first_name) { ?>

<?php echo $error_first_name; ?>

              <?php } ?>

            <input class="btn btn-primary" type="submit" name="submit" value="<?php echo $button_submit; ?>" />

</form>

controller/common/home.php
class ControllerCommonHome extends Controller
{
    public function index() {

        if (isset($this->request->get['route'])) {
            $this->document->addLink(HTTP_SERVER, 'canonical');
        }

        $this->load->language('common/home');

        $this->document->setTitle($this->language->get('heading_title'));

        $data['breadcrumbs'] = array();

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_home'),
            'href' => $this->url->link('common/home')
        );

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_account'),
            'href' => $this->url->link('common/home', '', 'SSL')
        );

        $url = '';

        if (isset($this->request->get['page'])) {
            $url .= '&page=' . $this->request->get['page'];
        }

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link('common/home', $url, 'SSL')
        );

        $data['heading_title'] = $this->language->get('heading_title');

        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];
        } else {
            $page = 1;
        }

        $data['returns'] = array();

        $data['id'] = $this->language->get('id');
        $data['first_name'] = $this->language->get('first_name');

        $data['button_continue'] = $this->language->get('button_continue');

        $this->load->model('common/home');

        $data['column_left'] = $this->load->controller('common/column_left');
        $data['column_right'] = $this->load->controller('common/column_right');
        $data['content_top'] = $this->load->controller('common/content_top');
        $data['content_bottom'] = $this->load->controller('common/content_bottom');
        $data['footer'] = $this->load->controller('common/footer');
        $data['header'] = $this->load->controller('common/header');

        if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/common/home.tpl')) {
            $this->response->setOutput($this->load->view($this->config->get('config_template') . '/template/common/home.tpl', $data));
        } else {
            $this->response->setOutput($this->load->view('default/template/common/home.tpl', $data));
        }
    }

    public function add() {
        $this->load->language('common/home');

        $this->load->model('common/home');

        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
            $return_id = $this->model_common_home->addCustomerbook($this->request->post);

            // Add to activity log
            $this->load->model('common/home');

            $this->response->redirect($this->url->link('common/home/success', '', 'SSL'));
        }

        $this->document->setTitle($this->language->get('heading_title'));
        $this->document->addScript('catalog/view/javascript/jquery/datetimepicker/moment.js');
        $this->document->addScript('catalog/view/javascript/jquery/datetimepicker/bootstrap-datetimepicker.min.js');
        $this->document->addStyle('catalog/view/javascript/jquery/datetimepicker/bootstrap-datetimepicker.min.css');

        $data['breadcrumbs'] = array();

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_home'),
            'href' => $this->url->link('common/home')
        );

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_account'),
            'href' => $this->url->link('common/home', '', 'SSL')
        );

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link('common/home/add', '', 'SSL')
        );

        $data['heading_title'] = $this->language->get('heading_title');

        $data['text_first'] = $this->language->get('text_first');

        $data['entry_first_name'] = $this->language->get('entry_first_name');

        $data['button_submit'] = $this->language->get('button_submit');
        $data['button_back'] = $this->language->get('button_back');

        if (isset($this->error['warning'])) {
            $data['error_warning'] = $this->error['warning'];
        } else {
            $data['error_warning'] = '';
        }

        if (isset($this->error['order_id'])) {
            $data['error_order_id'] = $this->error['order_id'];
        } else {
            $data['error_order_id'] = '';
        }

        if (isset($this->error['first_name'])) {
            $data['error_first_name'] = $this->error['first_name'];
        } else {
            $data['error_first_name'] = '';
        }

        $data['action'] = $this->url->link('common/home/add', '', 'SSL');

        if (isset($this->request->post['firstname'])) {
            $data['firstname'] = $this->request->post['firstname'];
        } elseif (!empty($order_info)) {
            $data['firstname'] = $order_info['firstname'];
        } else {
            $data['firstname'] = $this->customer->getFirstName();
        }

        // Captcha
        if ($this->config->get($this->config->get('config_captcha') . '_status') && in_array('return', (array)$this->config->get('config_captcha_page'))) {
            $data['captcha'] = $this->load->controller('captcha/' . $this->config->get('config_captcha'), $this->error);
        } else {
            $data['captcha'] = '';
        }

        $data['back'] = $this->url->link('common/home', '', 'SSL');

        $data['column_left'] = $this->load->controller('common/column_left');
        $data['column_right'] = $this->load->controller('common/column_right');
        $data['content_top'] = $this->load->controller('common/content_top');
        $data['content_bottom'] = $this->load->controller('common/content_bottom');
        $data['footer'] = $this->load->controller('common/footer');
        $data['header'] = $this->load->controller('common/header');

        if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/account/return_form.tpl')) {
            $this->response->setOutput($this->load->view($this->config->get('config_template') . '/template/account/return_form.tpl', $data));
        } else {
            $this->response->setOutput($this->load->view('default/template/account/return_form.tpl', $data));
        }
    }

    protected function validate() {
      .......
    }

    public function success() {
        $this->load->language('common/home');

        $this->document->setTitle($this->language->get('heading_title'));

        $data['breadcrumbs'] = array();

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_home'),
            'href' => $this->url->link('common/home')
        );

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link('account/return', '', 'SSL')
        );

        $data['heading_title'] = $this->language->get('heading_title');

        $data['text_message'] = $this->language->get('text_message');

        $data['button_continue'] = $this->language->get('button_continue');

        $data['continue'] = $this->url->link('common/home');

        $data['column_left'] = $this->load->controller('common/column_left');
        $data['column_right'] = $this->load->controller('common/column_right');
        $data['content_top'] = $this->load->controller('common/content_top');
        $data['content_bottom'] = $this->load->controller('common/content_bottom');
        $data['footer'] = $this->load->controller('common/footer');
        $data['header'] = $this->load->controller('common/header');

        if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/common/success.tpl')) {
            $this->response->setOutput($this->load->view($this->config->get('config_template') . '/template/common/success.tpl', $data));
        } else {
            $this->response->setOutput($this->load->view('default/template/common/success.tpl', $data));
        }
    }

}

model/common/home.php
class ModelCommonHome extends Model {
    public function addCustomerbook($data) {

        $this->event->trigger('pre.home.add', $data);

        $this->db->query("INSERT INTO `" . DB_PREFIX . "contact_book` SET contact_id = '" . (int)$data['id'] . "', first_name = '" . $this->db->escape($data['first_name']) . "' ");

        $id = $this->db->getLastId();

        $this->event->trigger('post.home.add', $id);

        return $id;

    }

I'm not too good at MVC so please help me out to solve this problem.
Comment: Please be more specific. No one will read a bunch of code without knowing what actually is the problem...
Comment: okay can u help me out as how to submit a form in opencart and persist its data in database .
Answer: Sujit, You need to check opencart contact us form functionality for post date to controller. Contact us form does not store data to database but you will make following changes on controller file
$this->load->model('catalog/contact');
$this->model_catalog_contact->addContact($this->request->post;

model/Catalog/contact.php

Create addContact($data) function on it and then make insert query as you know that.


Localize my Constructor

Question: class Student
{
private:
    string name;
    int year;
    string semester;
    int AmtClass;
    static string Year[4];

public:
    Student();
    Student(int AmtClass);
    Student(Student &);

    void setName(string name);
    void setYear(int year);
    void setSemester(string semester);
    void setAmtClass(int AmtClass);

    string getName();
    int getYear();
    string getSemester();
    int getAmtClass();

    ~Student()
        {
            if(AmtClass > 0)
                delete [] course;
        }
};

string Student::Year[4] = { "Freshman", "Sophomore", "Junior", "senior" };

Student::Student()
{
name = "";
year = 0;
semester = "";
AmtClass = 0;
}

Student::Student(int amount)
{
AmtClass = amount;

string *pName;
pName = new string[AmtClass];

for(int i = 0; i < AmtClass; i++)
{
    pName[i] = "";
}
}

Skipping Accessors and Mutator functions...
void readStudentData(Student &);
void printStudentData(Student);

int main()
{
int amount;
cout << "How many courses are you currently taking? ";
cin >> amount;

Student kid;
kid.setAmtClass(amount);

readStudentData(kid);
}

void readStudentData(Student &kid)
{
cin.ignore(10000, '\n');

int amount = kid.getAmtClass();
string name = "";
string semester = "";
int year = 0;

cout << "What is your full name? ";
getline(cin,name);

cout << "\nHow many years have you been in college? ";
cin >> year;

cout << "\nWhat is your current semester? ";
getline(cin,semester);

Student kid1(amount);

cout << "Please enter the name of all your courses." << endl;
for(int i = 0; i < amount; i++)
{
    cout << "Course #" << i+1 << " : ";
    getline(cin,pName[i]);
}

}

Okay edited this program a bit after realizing my pName is a local variable in the constructor...I am supposed to create a constructor that received an integer parameter corresponding to the number of courses the student is taking.The function dynamically allocates the string array of courses and sets each element to "". And then I am supposed to use this to record the names of the courses the student is taking.
Comment: There is too much noise in the question. You should try to reduce the problem to a smaller test case that exhibits the same problem (which is really unclear in the question). In the process you might discover what the issue really is.
Comment: Can you format your code a little better?
Comment: You can start with the blatant memory leak in the `Student` constructor. The unnecessary for-loop to initialize said leaked `std::string` array can be thrown out while fixing that.
Comment: So to prevent this memory leak should I delete the old memory and then create a new one?
Comment: *What old memory?* And I only format code once. so you're up from here on out. This isn't going to turn into an online debugging session. After fixing what I already described, you may also consider how your semester-read operation doesn't work, since the `year` extraction never consumed the newline from the prior input. Best of luck.
Answer:
The Year array should simply be allocated to the amount, and that's it:
Student::Student(int amount)
    : Year(new std::string[amount]()), AmtClass(amount)
{
}

You can also use std::vector for this so you do not have to deal with deleting the memory yourself:
class Student
{
    std::vector<std::string> Year;
    // ...
};

Student::Student(int amount)
    : Year(amount), AmtClass(Year.size())
{
}

Localize my Constructor