Como manter uma cópia original ao utilizar o sort em arrays do JavaScript?

Question: Preciso ordenar um array, mas não posso perder a sequencia original.
Para isso, criei uma nova variável e atribui o valor a ela, fazendo uma cópia da original. Entretanto, ao utilizar o método sort, percebi que ele modifica as duas variáveis. Segue o trecho do código:
var rank = [292, 130, 55, 232, 213, 62, 152], rankOdered = [];
rankOrdered = rank;

console.log("rankOdered: " + rankOrdered)
console.log("rank: " + rank)
console.log("")

rankOrdered.sort(function (a, b) { return b - a });

console.log("rankOdered: " + rankOrdered)
console.log("rank: " + rank)

Na tela do console:
rankOdered: 292,130,55,232,213,62,152
rank: 292,130,55,232,213,62,152
<empty string>
rankOdered: 292,232,213,152,130,62,55
rank: 292,232,213,152,130,62,55

Comment: Eu costumo chamar a função `.splice()` antes de `.sort()`
Answer: Isso acontece porque você não está fazendo, de fato, uma cópia do array. Repare aqui:
var rank = [292, 130, 55, 232, 213, 62, 152];
var rankOrdered = rank;

Quando você faz var rankOrdered = rank, você está atribuindo, à rankOrdered, a referência do array original, que no caso é rank.
Portanto, qualquer modificação feita no array rankOrdered também irá se refletir no array rank (e vice-versa), já que as duas variáveis apontam para o mesmo objeto (sim, arrays são objetos em JavaScript).
E o que ocorre é que o método Array.prototype.sort não realiza as modificações em um novo array. O sort faz as modificações in-place. Desse modo, o sort modificará o array que a ele for aplicado.
Então, o que você precisa fazer é uma cópia de fato. Existem várias formas de se fazer isso. Por exemplo, utilizando o spread operator:

var rank = [292, 130, 55, 232, 213, 62, 152];
var rankOrdered = [...rank]; // Agora sim, cria-se um novo array.

rankOrdered.sort((a, b) => b - a);

console.log(rank);
console.log(rankOrdered);


Would fishing wire work for strings on an electric guitar?

Question: So, I was browsing the Internet and stumbled across this video of someone using fishing wire as string replacements. This seemed to be kind of a gag just to see if it was actually even possible, but it got me thinking.
Obviously, I don't think fishing wire is a true replacement for actual guitar strings. Still, if I ever had a string snap on me and I didn't have anything else, I'd imagine it'd be better than nothing. Comparing prices with actual guitar strings, it's certainly not very expensive to keep some extra around.
However, that leaves me with a question. The video shows an acoustic guitar. I play an electric. I'm still relatively new to the instrument, so I don't know how everything works yet. However, a friend of mine who also plays the guitar told me that guitar pickups are usually based off of magnets. Then, because the strings are made of metal, the magnets in the pickups can detect the movement of the strings. Thus, the strings have to be made of metal.
That's a problem if I use fishing wire, because fishing wire is usually made of plastic (unless I'm mistaken). So am I correct to believe that using fishing wire on an electric guitar wouldn't work? Or perhaps does it depend on what kind of pickups I'm using and/or what fishing wire I would be using?
Comment: Fishing line is actually an excellent replacement or repair segment for (accoustic) instrument strings. Especially when you're out camping or hiking and don't have any actual strings with you! It's just nylon! Nylon string comes a wide variety of gauges and is a reasonable replacement for gut.
Comment: There's [fishing wire](https://www.amazon.com/Fishing-Tippet-Powerflex-15Ft-Clear/dp/B001T6I9T8) which is made of metal, and there's [fishing line](https://www.amazon.com/Berkley-BGQS20C-15-Trilene-Big-Game/dp/B001E3R3B6/ref=sr_1_5?dchild=1&keywords=fishing+line&qid=1601310561&sr=8-5) which is just a nylon string and has no metal.  The video shows fishing line made of nylon string.
Comment: Monofilament fishing line is often nylon, but it may also be polypropylene or a variety of copolymers.  Braided line is (usually) dacron and flourocarbon line is, well, flourocarbon.
Comment: @elemtilas to add that cheaper varieries of strings are not made of gut. They are nylon just like the fishing lines are.
Comment: FWIW I once saw an African harp from Gambia wired with fishing line. I think the bass strings were metal. Not really relevant since the player used a mic.
Comment: @elemtilas Yeah, I'm thinking that taking an *electric* guitar with you to go camping or hiking isn't likely to work anyhow - where are you going to plug in your amp?
Comment: @JRE That's a good point. Do you think the metal variation would work?
Comment: As far as I know, there are brands of fishing wire made of steel, so could work with an electric guitar.
Comment: @JRE Thanks, that's good to know. It might be worth putting that in an answer, but that's up to you.
Comment: Not just metal, it has to be a magnetic metal which means either iron (in the form of steel), nickel, or cobalt has to be in there somewhere. Probably steel though.
Comment: Potentially, if you really had to, you could string an electric guitar with fishing wire, and then wind some wire made from ferrous metal (e.g. from an electrical cable) around the part of the fishing wire that passes over the pickup. I doubt it would work very well at all, but in principle it should at least make some sound.
Answer: It won't work, unless you're using a piezo system which induces current from physical vibrations.
An electric guitar works because the magnetic field around the vibrating strings induces current in the coils of the pickup. So the strings must have some ferrous content for the EM-induction to take place.
It could conceivably work on a guitar like the Nylocaster which uses a piezo pickup.
Comment: As a further explanation should anybody be confused: contrary to how it might seem, most electric guitar pickups are not a microphone that capture the sound made when the strings vibrate.  Instead, the pickups are a magnet, and the manner in which the string vibration disrupts the magnetic field means the entire system of the strings and the magnet themselves form a microphone-like system.
Answer: Metal, but not just any metal. Both steel-string and classical acoustic guitars generally use metal, such as bronze or silver-played copper, for the windings to add mass and lower the frequency, but they don't have much magnetic metal, so they don't work well with soundhole pickups, which are magnetic like electric guitar pickups.
Most electrified acoustic guitars use piezoelectric pickups, which do not need magnets.
Some strings are wound with magnetically-active metal, like GHS White Bronze. Fishing line has nothing that an electric guitar could use, don't have enough mass or tension to move an acoustic guitar's top, and with classical guitar, maybe they'd be replacement for the E or B strings but not much lower.
Answer: Nylon fishing line is commonly used for African instruments such as the kora and ngoni, as a matter of convenience.  Strings were previously leather, but of course nylon is better.
Nylon fishing line would also work on the upper strings of classical guitars, with perhaps some issues on string tension if you can't get the right thickness of strings.  It would be a problem for the lower (wound) strings, so you might need to go for the same solution as the kora and twist two lengths of fishing line together.
On an electric, as previously said, it won't work.  You need metal strings for an electric (e.g. Stratocaster or Les Paul) to work, because they work on the same principle as an electric generator of moving a wire next to a magnet.  If by "electric" you mean an acoustic guitar with a piezo pickup, then that will work OK because the piezo pickup picks up the vibration of the guitar bridge and doesn't rely on the strings to have any magnetic qualities.
Comment: Ah, yeah, that wasn't what I had in mind by "electric." I meant the Les Paul type of electric. I really appreciate your answer nonetheless.
Answer: There's fishing wire which is made of metal, and there's fishing line which is just a nylon string and has no metal. The video shows fishing line made of nylon string.
Just as fishing line might work as a temporary string on an acoustic guitar, a length of fishing wire might work as a temporary string on an electric guitar.
Some brands (and/or models) of fishing wire are made of steel.  Fishing wire is available in various sizes (diameters) so you could (maybe) match a particular fishing wire to a particular string on your guitar. Some (if not many) fishing wires are made of stainless steel, which may not work well with the magnetic pickups of an electric guitar.
Fishing wire is also known as "leader wire."  It is used down by the hook for catching fish with sharp "teeth" which can cut nylon fishing line.
Comment: @barej:  Nylon fishing line won't exactly match the diameter and weight of a standard guitar string.  It won't properly fit in the grooves of the nut and saddle.  You'll have use a different tension on the string - maybe lower than normal, which wouldn't be bad, or maybe higher than normal which could cause problems with the machine heads or the neck.  You can play a guitar that way, but it'll be a bit more difficult and it may damage the guitar long term.
Comment: Why do you say fishing line nylon on an acoustic guitar is a "temporary" solution??
Answer:
Doubtful that the fishing line would endure the the "string tension" needed to tune to pitch.
For a standard electric pick-up, no.
Metal strings are needed.
Carry an extra set in a sealed baggie.
Keep playing :-)
Comment: I did (just like many others) on an acoustic guitar. It works. It wears out faster, but is pretty much good for 1-2 nights of camping.
Comment: Depends on the material and construction of the fishing line.  Nylon fishing line, or fluorocarbon, work just as well as commercial strings (usually). I experiment quite a bit with different string materials for my lyres, and seven strand stainless cable will also take the tension of a normal guitar high E string (just).  It sounds different than plain steel, though- wispier, and of course more surface noise when playing.  It probably doesn't last as long either, before one of the strands is worn through.  But it's quite serviceable.


Looking for class of functions $f_n$ with $n$ variables $(x_1,...,x_n)$ and $f_n=k_n a^{n−1}$ if $x_i=a\;\forall i$

Question: Is there a class of functions that fulfills or partly fulfills following conditions?
For any $n\in\mathbb{N}_{>1}$ there is a function $f_n$ with following properties:

$f_n$ is a function of $n$ variables, i.e. $f_n=f_n(x_1,...,x_n)$ with $x_i\ge0 \;\forall i$
if $x_i=a \;\forall i\;$ then $f_n=k_n a^{n-1}$ with $k_n>0$
$f_n\ge0$
$f_n=0$ iff $x_i=0 \;\forall i$

It is not known that 1-4 are sufficient conditions to define a unique function class but it would be good to know at least one class that fulfills all conditions.
What is known?
Following function scheme fulfills conditions 1,2 but not conditions 3,4 and might be a starting point:
$$f_n=\frac{\prod_{i=1}^{n} x_i}{\frac{1}{n}\sum_{i=1}^{n} x_i}$$
As an expample $n=4$ is used:
condition 1 fulfilled:
$$f_4=\frac{x_1x_2x_3x_4}{\frac{1}{4}\left(x_1+x_2+x_3+x_4\right)}$$
condition 2 fulfilled:
$$f_4=\frac{a\cdot a\cdot a\cdot a}{\frac{1}{4}\left(a+a+a+a\right)}=a^3 \;\;\;\text{with}\;\;\; k_4=1$$
condition 3 only fulfilled if $\neg(x_i=0\; \forall i)$:
$$\sum_{i=1}^n x_i\ge0 \land \prod_{i=1}^n x_i\ge0 \to f_4\ge0$$
condition 4 not fulfilled:
$$f_4=\frac{0\cdot 1\cdot 1\cdot 1}{\frac{1}{4}\left(0+1+1+1\right)}=0 \nleftrightarrow x_i=0\; \forall i$$
Comment: (x_1 + x_2 ... +x_n)^(n-1)?
Comment: What about f_n= x_2 x_3 .... x_n?
Comment: Or f_n = (x_1 x_2 ... x_n )^((n-1)/n) ?
Comment: These functions do not fulfill condition 4.
Comment: $f_n(x)=  x_1^{n-1}\,k_n\frac{\|x\|}{\|a\|}$
Comment: Or simply take any function $g \colon [0,\infty) \to [0,\infty)$ which is $0$ only at $0$ (e.g. $g(x)=\tanh(x)$) and define $f_n(x)=  x_1^{n-1}\,k_n\frac{g(\|x\|)}{g(\|a\|)}$. Also, you can combine this with @RainerGlüge suggestion and take for instance $f_n(x)=  (\frac{x_1^p+x_2^p+x_8^p}{3})^{\frac{n-1}{p}}\,k_n\frac{g(\|x\|)}{g(\|a\|)}$ with $p>0$.
Answer: Accepting the comment from user Rainer Glüge following function class fulfills all conditions.
$$f_n=\left(\sum_{i=1}^n x_i\right)^{n-1}$$
It can easily be shown that the 4 conditions are fulfilled and it is exemplary shown for $n=4$.
condition 1 fulfilled:
$$f_n=(x_1+x_2+x_3+x_4)^3$$
condition 2 fulfilled:
$$f_n=(a+a+a+a)^3=k_4a^3\;\;\;\text{with}\;\;\;k_4=64$$
condition 3 fulfilled:
follows from definition of  $x_i\ge0\;\forall i$
condition 4 fulfilled:
follows from definition of  $x_i\ge0\;\forall i$,
$$x_1+x_2+x_3+x_4=0 \leftrightarrow x_i=0\;\forall i$$
$$0^3=0 $$

There might be other more complicated expressions that also fulfill all conditions.


class cannot be cast to class javax.swing.tree.DefaultTreeCellRenderer error

Question: public class jtre extends javax.swing.JFrame {
    static{

        try{

    UIManager.setLookAndFeel(NimbusLookAndFeel.class.getName());
        }catch (ClassNotFoundException ex){

        } catch (InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
            Logger.getLogger(jtre.class.getName()).log(Level.SEVERE, null, ex);}}

    public jtre() {
        initComponents();
         jTree1.setCellRenderer(new WarnaRender());

        DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer)jTree1.getCellRenderer();
         Icon closedIcon = new ImageIcon("/images/ve.png");
         Icon openIcon = new ImageIcon("/images/veya.png");
         Icon leafIcon = new ImageIcon("/images/xor.png");
         renderer.setClosedIcon(closedIcon);
         renderer.setOpenIcon(openIcon);
         renderer.setLeafIcon(leafIcon);   }

public class WarnaRender implements TreeCellRenderer{

    @Override
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
        JLabel label = new JLabel();
        label.setText(value.toString());
        label.setOpaque(true);
        if(row %2 == 1){
        label.setBackground(Color.RED);
        label.setForeground(Color.WHITE);
       } else {

        label.setBackground(Color.GREEN);
        label.setForeground(Color.RED); }
        return label;}}

I make a class which is called WarnaRender for coloring each node of jtree. My code is working. After that I want to add icons to jtree and I encountered an error which is "ClassCastException: class WarnaRender cannot be cast to class javax.swing.tree.DefaultTreeCellRenderer (WarnaRender is in unnamed module of loader 'app'; javax.swing.tree.DefaultTreeCellRenderer is in module java.desktop of loader 'bootstrap')". How can ı solve this problem? Can you help me. I investigated this error in the İnternet but I couldnt find the solution. Please help my code. Thank you.
Answer: Your class WarnaRender does not extends DefaultTreeCellRenderer so you can not cast it to this class.
So extend from it:
public class WarnaRender extends DefaultTreeCellRenderer {
Comment: I tryed this code. It works but icons does not appear in the Jtree. How can I solve this problem.
Comment: You override `getTreeCellRendererComponent` which renders the icons
Comment: How can I Override it ? Can you write me please..
Comment: You have overridden it. What would you archive
Comment: I dont understand what you mean. I couldt override tghe code because ı dont know how to override this code. Can you write me how to override this code for solution of icons problem. The code works but jtree 's nodes doesnt apppear icons.I want the icons in Jtree to appear. Please help me help my code. How can appear the jtree 's icons ?Write the code please ...
Comment: You **have** overridden the code `@Override
    public Component getTreeCellRendererComponent`
Comment: Jens thanks for everthing. I looked my code and "@Override     public Component getTreeCellRendererComponent "  is already written in my code.                                             public class WarnaRender extends DefaultTreeCellRenderer {

    @Override
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
my code is above the page. My code still doesn't show the icon.. How can ı show the icons .Please help me help my code.Thank you.
Comment: Don't ask questions in the comment that are not related to the original question. Ask a new question for the new problem.


Group Policy Map Drive to Display Name

Question: I'm trying to create a Group Policy to map users Home Drives among others when they login.  All the other drives are mapping fine, however because of the way in which the usernames are formatted, I've run into a conundrum trying to get the Home Drive Mapped.
In short, the usernames are formatted Firstname.Lastname, whereas the home folders on the server are formatted as Firstname Lastname (Note the space and not [dot])
So calling all Windows GPO Gurus - do you know of a way that I can create a GPO to map a users' Home Drive using their Name, rather than their username?
For reference, we are using Windows 7 Clients with the AD Server being Server 2008 R2.
Comment: Is there a reason that you're not simply using the AD attributes to map a home folder to a drive letter?
Comment: We aren't redirecting users Documents etc... to their home drives on the server.  Also, we would be in the same predicament, we would need to use something like %LogOnUser% for that, which won't work.  Another thing is that we will be mapping multiple drives, so a GPO was the easiest and quickest option I thought.
Comment: Mapping a home drive and redirecting My Documents are two different things. To map the home folder to a drive, simply modify the users' AD attributes using ADUC or PowerShell.

In ADUC, go to the account's Profile tab, look at the "Home Folder" section, select the Connect option, choose a drive letter, and then type the UNC of their home folder. This will be easier in PowerShell because you can script everything, using the first name and last name as variables to construct the home folder path.
Comment: OK, so have you got any links that you have seen for the PowerShell command(s) that I would be looking at using for this?  Thanks :)
Answer: Here's an example of how you can do this to a single user with a script. It's crude but it works well as an example to show the process.
$user = Get-ADUser James
$homeName = $user.GivenName + " " + $user.Surname
$user | Set-ADUser -HomeDirectory \\FileServer\Users\$homeName -HomeDrive H -Credential (Get-Credential)

Replace the UNC with your file share, and change the H drive letter to whatever drive letter you want to use for the user's home drive. Once you wrap your head around this code, your next step might be to figure out how to run it against all users at once.
Comment: Great, thanks very much, i'll have a look and a play about and let you know how I get on :)
Comment: Do you really need the Credential parameter?
Comment: Not if you have already launched your PowerShell session with an account that has Domain Admin or Account Operators permissions. Depends on how well you have pursued best practices for privileged accounts. :)
Comment: You're welcome! Let us know if you have any other questions about this script.

Group Policy Map Drive to Display Name


Symfony2 merge documents to PDF

Question: I need to merge various PDF and Excel documents in one PDF. For example I have:
 - A.pdf
 - B.pdf
 - D.xlsx
 - E.doc
Whats I need is to merge all 4 documents content to a one result.pdf document.
There is any bundle/library to achieve that? or maybe the best option is to create a python script and call it from symfony2 (how?) to generate that pdf?
Any help or clue?
Thanks in advance
Answer: Symfony provides a Process component that wraps nicely wraps around the native php exec/system functions.
Check it out on: https://github.com/symfony/Process
Another option would be to use the PDF Component from Zend Framework. I'm not sure if it allows merging of PDF's but it should only be a matter of reading through the documentation to find out.
Check out this tutorial about ZendPDF in symfony: http://www.craftitonline.com/2011/06/pdf-generation-with-symfony2-part-ii-zend-option/
Hope that helps.
Answer: The @DucTa's dead link was talking about pdftk, a binary with which you can merge multiple PDF documents.
Download it on your server using apt-get install pdftk.
For now, I think it doesn't exist any bundle using pdftk, but you can use something like exec() or passthru() to do the trick.
Example :
exec('pdftk doc1.pdf doc2.pdf doc3.pdf output merged.pdf');

Symfony2 merge documents to PDF


What is the convention for naming routes?

Question: Lets say I have these paths:
/admin
/admin/settings
/admin/settings/myentities
myentity/id
/admin/settings/myentities/id/edit
/admin/settings/myentities/id/delete

What would be the proper route names for each one of them?
My current usage is this:
admin
/admin

admin.settings
/admin/settings

admin.settings.myentities OR admin.myentities
/admin/settings/myentities

myentit OR myentity.view
/myentity/id

myentity.edit OR admin.myentities.edit OR admin.settings.myentities.edit
/admin/settings/myentities/id/edit

The things I mostly not sure about is whether I should use the path structure for the route name or not(ie. /path/to/some/where => path.somewhere OR path.to.some.where) and when it comes to entities if I should use admin.myentities + admin.myentities.myentity OR admin.myentity.edit) etc..
Answer: By design, the route name should NOT mirror the path.  You want to be able to change the path without breaking the route name, which is why other code in the system should refer to the route name only, not the path.  Having a route name that maps directly to the path is akin to a CSS class named .left-align-blue :-)
Some of these conventions are still shaking out.  However, for the typical case the recommended pattern is $module_name.$something_meaningful.  So in your mymodule module, you'd have routes like:
mymodule.settings
mymodule.advanced_settings
mymodule.status_page

And so on.  Note those tell you little about the path.  That's by design, as above.
For entities it's a little bit trickier since core has the advantage that most entities are the same name as the module.  Contrib doesn't always have that.  I would recommend either $entityname.$operation or $module_name.$entityname_$operation.  (I don't think core has any double-period route names at present, but I could be wrong.)
So if I were writing a module with a new entity called "nerd" (it's a candy site), I'd have:
nerd.view (for the page that lets you view a nerd)
nerd.edit (for the edit page)
nerd.delete (for the delete confirmation page)

And so on.  Make sense?
Comment: why nerd.view why not just nerd? doesn't that imply that there is something on nerd too?
Comment: we should be really strict to never expect anything about the route name, even I fear that we can't keep that on the entity routes.


Pressing the power off button is registered in HP Active Health System logs?

Question: I have a customer which suffered an unexpected shutdown of one of his servers (Proliant DL320e Gen8 v2)
According logs inside the server it seems that someone pressed the power off button but the customer swears that is impossible.
I donwloaded logs inside ILO from Active Health System (AHS) but you need a valid maintenance contract and it is expired.
Before renewing the contract I would like to know if "pressing the power off button" like actions are registered in AHS logs.
Any HP employee here?
Comment: I made the same question in HP community forums and I get an afirmative answer.   https://community.hpe.com/t5/ProLiant-Servers-ML-DL-SL/Pressing-the-power-off-button-is-registered-in-HP-Active-Health/td-p/6966404
Answer: It seems that the answer is yes.
I made the same question at HP community forums
https://community.hpe.com/t5/ProLiant-Servers-ML-DL-SL/Pressing-the-power-off-button-is-registered-in-HP-Active-Health/td-p/6966404
Someone pasted an screenshot and it seems that pressing the power button is registered in the log.


Como pegar dados de uma JTable para armazenamento em um banco de dados?

Question: Eu estou a desenvolver um projecto chamado Lista de Cardápio com um banco de dados MySQL e em Java no NetBeans, com uma biblioteca adicionada de MySQL-Connector-Java. Eu quero que os nomes dos produtos selecionados, a quantidade de produtos e o preço total do modelo Cardapio.java sejam armazenados e impressos como texto num banco de dados pelo modelo Cadastro.java, conectando-se com os modelos Conexão.java e Teste.java.
Ainda não resolvi dois erros no Java.
Siga o código-fonte completo do Cardapio.java:
package br.com.cardapio.view;

/**
-- Autor: Gustavo Benedito Costa
-- Curso: Ciência da Computação
-- Disciplina: Análise de Programação Orientada a Objectos
-- Professor: Carlos Feichas
-- Ano: 2ºA
-- Semestre: 3º Semestre

***GEORGIANO*** — ***GEORGIAN*** — ***ქართული***
-- ავტორი: გუშტავუ ბენედიტუ კოსტა
-- კურსი: კომპიუტერული მეცნიერება
-- დისციპლინური: ორიენტირებული პროგრამირება ანალიზი ობიექტები
-- მასწავლებელი: კარლოს
-- წელი: მეორე წელს A
-- სემესტრი: მესამე სემესტრი
 **/

import java.awt.Color;
import java.awt.Font;
import java.sql.Array;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JSpinner;
import javax.swing.table.DefaultTableModel;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.awt.event.ActionEvent;
import br.com.control.Cadastro;

public class Cardápio extends javax.swing.JFrame {

    double valorTotal=0;    //valor dos pedidos
    DefaultTableModel tab1; // model da tabela Lanches
    DefaultTableModel tab2; //  model da tabela Lanches Selecionados

    public Cardápio() {
        initComponents();
        Tprodutos(); // inicializa a tabela Lanches
    }

    public void Tprodutos(){
        ArrayList<String> t = new ArrayList(); // lista dos produtos
        ArrayList<String> s = new ArrayList(); // lista dos preços

        t.add("X-salada");t.add("Mini pizza");t.add("Hamburguer");t.add("Suco de laranja"); t.add("Cappuccino"); // inserção de valores nas listas
        s.add("4.00");    s.add("3.25");       s.add("5.30");       s.add("5.00");          s.add("3.30"); //

        tab1=(DefaultTableModel) jTable1.getModel();    // model da tabela
        //tab1.setNumRows(0);               <-- limpa a tabela
        int b=t.size(); // numero de tuplas na tabela

        for(int i=0;i<b;i++)
        {               //ok
            String produto = t.get(i); // pegar o nome do produto
            String valor = s.get(i);   // pegar o valor do produto
            tab1.addRow(new String[]{produto,valor});    // inserção de valores na tabela
        }
    }

    public String[] pega_dadosT1() throws SQLException{
        String[] a=new String [2];  // armazenar resultado
        String produto = "";
        String valor = "";
        int indiceLinha = jTable1.getSelectedRow();  // pegar o indice da linha selecionada
        if(jTable1.getRowCount()>0){ // numero de linhas > 0
        if (indiceLinha!=-1)
        {
             a[0] = (String) jTable1.getValueAt(indiceLinha,0); //pegar valor(linha , primeira coluna)
             a[1] = (String) jTable1.getValueAt(indiceLinha,1); //pegar valor(linha , segunda coluna)
             //obs: o indice das colunas sempre começa no numero 0
        }
        else
        {
            JOptionPane.showMessageDialog(null,"Selecione um lanche da tabela Lanches!!!");// mensagem de erro
        }
        }else{JOptionPane.showMessageDialog(null,"Sem lanches Disponiveis!!!");}        // mensagem de erro
        return a; // retona vetor
    }

    public void TprodutoSelecionado(String nomeP,String q,String v){
        double valor=Double.parseDouble(v); //conversão de String pra Double
        int quant=Integer.parseInt(q);  //conversão de String pra Inteiro

        valor=valor*quant;  //

        tab2=(DefaultTableModel) jTable2.getModel(); // Model
        tab2.addRow(new String[]{nomeP,""+quant,""+valor}); // Add tuplas
        valorTotal=valorTotal+valor;    // Valor total dos pedidos
        jLValorTotal.setText(""+valorTotal); // inserindo valor no label(Valor Total: )
    }

    public void Tdelet_prodSelec(){
        int indiceLinha = jTable2.getSelectedRow();
        double valorProd=0;
        if(jTable2.getRowCount()>0){
            if (indiceLinha!=-1)
            {
                valorProd= Double.parseDouble(""+jTable2.getValueAt(indiceLinha, 2));
                           //converter        // converter e pela valor
                valorTotal=valorTotal-valorProd; // atualizar valor total
                jLValorTotal.setText(""+valorTotal); // atualizar label
                ((DefaultTableModel) jTable2.getModel()).removeRow(indiceLinha); // remover da tabela
            }
            else{
            JOptionPane.showMessageDialog(null,"Selecione um lanche da tabela dos lanches selecionados!");//
            }
        }else{
            JOptionPane.showMessageDialog(null,"Tabela Lanches selecionados está vazia");//
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        JBAdicionar = new javax.swing.JButton();
        jBDelete = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLValorTotal = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        Confirmacao = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        jPanel1.setBackground(new java.awt.Color(224, 237, 235));
        jPanel1.setMaximumSize(new java.awt.Dimension(550, 300));
        jPanel1.setMinimumSize(new java.awt.Dimension(550, 300));
        jPanel1.setPreferredSize(new java.awt.Dimension(551, 300));
        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jTable1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Produtos", "Valor"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setSelectionBackground(new java.awt.Color(0, 153, 153));
        jScrollPane1.setViewportView(jTable1);
        if (jTable1.getColumnModel().getColumnCount() > 0) {
            jTable1.getColumnModel().getColumn(0).setResizable(false);
            jTable1.getColumnModel().getColumn(1).setMinWidth(50);
            jTable1.getColumnModel().getColumn(1).setPreferredWidth(50);
            jTable1.getColumnModel().getColumn(1).setMaxWidth(50);
        }

        jPanel1.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 40, 230, 124));

        jTable2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Produtos", "Q", "Valor"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable2.setSelectionBackground(new java.awt.Color(0, 153, 153));
        jScrollPane2.setViewportView(jTable2);
        if (jTable2.getColumnModel().getColumnCount() > 0) {
            jTable2.getColumnModel().getColumn(0).setResizable(false);
            jTable2.getColumnModel().getColumn(1).setMinWidth(30);
            jTable2.getColumnModel().getColumn(1).setPreferredWidth(30);
            jTable2.getColumnModel().getColumn(1).setMaxWidth(30);
            jTable2.getColumnModel().getColumn(2).setMinWidth(50);
            jTable2.getColumnModel().getColumn(2).setPreferredWidth(50);
            jTable2.getColumnModel().getColumn(2).setMaxWidth(50);
        }

        jPanel1.add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 40, 230, 124));

        JBAdicionar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        JBAdicionar.setText("Adicionar");
        JBAdicionar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        JBAdicionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBAdicionarActionPerformed(evt);
            }
        });
        jPanel1.add(JBAdicionar, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 70, 101, 30));

        jBDelete.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jBDelete.setText("Deletar");
        jBDelete.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jBDelete.setMaximumSize(new java.awt.Dimension(101, 29));
        jBDelete.setMinimumSize(new java.awt.Dimension(101, 29));
        jBDelete.setPreferredSize(new java.awt.Dimension(101, 29));
        jBDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBDeleteActionPerformed(evt);
            }
        });
        jPanel1.add(jBDelete, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 110, 101, 30));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel1.setText("Valor Total:");
        jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(510, 170, -1, -1));

        jLValorTotal.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLValorTotal.setText("0.0");
        jPanel1.add(jLValorTotal, new org.netbeans.lib.awtextra.AbsoluteConstraints(590, 170, 50, -1));

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(67, 159, 137));
        jLabel3.setText("Lanches:");
        jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 20, -1, -1));

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(67, 159, 137));
        jLabel4.setText("Lanches selecionados:");
        jPanel1.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 20, -1, -1));

        Confirmacao.setBackground(new java.awt.Color(132, 196, 196));
        Confirmacao.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        Confirmacao.setText("Confirmar");
        Confirmacao.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        Confirmacao.setMaximumSize(new java.awt.Dimension(101, 30));
        Confirmacao.setMinimumSize(new java.awt.Dimension(101, 30));
        Confirmacao.setPreferredSize(new java.awt.Dimension(101, 30));
        Confirmacao.setSize(new java.awt.Dimension(101, 30));
        Confirmacao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ConfirmacaoActionPerformed(evt);
            }
        });
        jPanel1.add(Confirmacao, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 210, 101, 30));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 650, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 265, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void JBAdicionarActionPerformed(java.awt.event.ActionEvent evt) {
        try {
            String prod[]=pega_dadosT1(); // "pega_dadosT1"
            String nome=prod[0];
            String valor=prod[1];
            String quant;

            if (nome!=null){ //
                JSpinner spinner = new JSpinner(); // cria um spinner
                spinner.setValue(1); // inicializar com 1
                JOptionPane.showMessageDialog(null, spinner, "Quantidade/Porção", WIDTH);// adionando o spinner a mensagem
                //obs: não consegui add o spinner ao ...showInputDialog.. fica 2 campos na tela, ou seja, não tem botão cancelar
                quant=""+spinner.getValue(); //
                TprodutoSelecionado(nome,quant,valor);//
            }
        } catch (SQLException ex) {
            Logger.getLogger(Cardápio.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    private void jBDeleteActionPerformed(java.awt.event.ActionEvent evt) {
        Tdelet_prodSelec();//
    }

    private void ConfirmacaoActionPerformed(java.awt.event.ActionEvent evt) {
        Confirmacao.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                try {

                                    // jTable é incompatível com o método getText

                    Cadastro.cadastrar(tab2.getText(), jLValorTotal.getText());
                    tab2.setText("");
                    jLValorTotal.setText("");
                    System.out.println("Cadastrado");
                } catch (SQLException e) {
                    System.out.println("Deu erro");
                }
            }
        });
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Cardápio().setVisible(true);
            }
        });
    }

    /**
     *
     */

    // Variables declaration - do not modify
    private javax.swing.JButton Confirmacao;
    private javax.swing.JButton JBAdicionar;
    private javax.swing.JButton jBDelete;
    private javax.swing.JLabel jLValorTotal;
    private javax.swing.JLabel jLabel1;
    public javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    // End of variables declaration
}

Na parte: onde tem dois erros nesse arquivo Cardapio.java:
private void ConfirmacaoActionPerformed(java.awt.event.ActionEvent evt) {
        Confirmacao.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                try {

  // jTable2 ou tab2 são incompatíveis com o método getText

                    Cadastro.cadastrar(tab2.getText(), jLValorTotal.getText());
                    tab2.setText("");
                    jLValorTotal.setText("");
                    System.out.println("Cadastrado");
                } catch (SQLException e) {
                    System.out.println("Deu erro");
                }
            }
        });
    }

Eu uso tab2 (variável do componente table) ou jTable2 (variável do componente JTable) para pegar o nome dos produtos dos Lanches Selecionados para armazená-los num banco de dados e imprimi-los.

Os erros seguintes:

Num arquivo Cadastro.java:
package br.com.control;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import br.com.cardapio.view.Conexao;

public class Cadastro {
    public static void cadastrar(String produtos, String quantidade, String prestacao) throws SQLException{
        Conexao classeConexao = new Conexao();
        Connection c = classeConexao.getConnection();
        PreparedStatement stmt;
        String query = "insert into cadastrofiscal values (?,?,?)";
        stmt = c.prepareStatement(query);
        stmt.setString(1, produtos);
        stmt.setString(2, quantidade);
                stmt.setString(3, prestacao);
        System.out.println(query);
        stmt.executeUpdate();

    }
}

No arquivo Conexao.java:
package br.com.cardapio.view;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Conexao {

    Connection con = null;
    private static Conexao instance = null;

    public Conexao() {
        inicio();
    }

    public void inicio() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("Driver Carregado");
        } catch (ClassNotFoundException e) {
            System.out.println("O driver do Mysql n�o p�de ser carregado!");
        }
    }

    public static Conexao getInstance() {
        if (instance == null) {
            instance = new Conexao();
        }
        return instance;
    }

    public Connection getConnection() {
        try {
            if ((con == null) || (con.isClosed())) {
                con = DriverManager.getConnection("jdbc:mysql://localhost/agenda", "root", "");
                System.out.println("Conex�o Estabelecida");
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return con;
    }

    public void destroy() {
        try {
            con.close();
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }

}

No arquivo Teste.java:
package br.com.cardapio.view;

import java.sql.Connection;

public class Teste {
    public static void main (String [] args){
        Conexao c = new Conexao();
        Connection con = c.getConnection();

    }
}

Num arquivo SQL:
CREATE DATABASE cardapiofiscal;
USE cardapiofiscal;

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

CREATE TABLE `cadastrofiscal` (
  `produtos` TEXT COLLATE utf8_bin NOT NULL,
  `quantidade` INT(2) NOT NULL,
  `prestacao` INT(5) NOT NULL
);

insert into cadastrofiscal values ('X-salada, Suco de Laranja','2', '9.00');

select * from cadastrofiscal;

Agora, quero apenas que tab2ou jTable2 (table ou JTable) sejam pegos como texto pelo getText para armazená-los no banco de dados. Mas esses são incompatíveis com o getText porque parece que não são String(s). Por isso, tenho que encontrar os métodos dessas variáveis desses componentes.
Comment: Isso ta parecendo erro semântico. `tab2` é um JTable?
Comment: @diegofm Não, `tab2` é um "`table`" e está dentro da jTable2 que é um Veja a imagem: http://i.imgur.com/Z3XCchf.png
Comment: Nunca vi componente "table" no java. Só conheço JTable. Adicione um [mcve] para que seja possivel avaliar melhor o problema.
Comment: @diegofm Actualizei a pergunta e completei, não sei se ficou melhor.
Comment: Na verdade tab2 e tab1 são models, não tables, como você disse.
Comment: O que é model? Tem como fazer isso para pegar os nomes dos produtos para armazená-los num banco de dados?
Comment: Você quer pegar os dados da segunda tabela?
Comment: Sim, exactamente!
Answer: A classe DefaultTableModel não possui o método getText(). Para recuperar linhas e colunas selecionadas, você deve usar o método getValueAt(int row, int column), passando o número da linha e da coluna da JTable que você quer recuperar os dados.
É sempre interessante usar um Bean para guardar os dados antes de sair passando eles entre métodos, facilita o entendimento e manutenção do seu código.
Ex.:
public class Produto {

    private String nome;
    private double valor;
    private int quantidade;

    public int getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public double getValor() {
        return valor;
    }

    public void setValor(double valor) {
        this.valor = valor;
    }

    public int getQuantidade() {
        return quantidade;
    }

    public void setQuantidade(int quantidade) {
        this.quantidade = quantidade;
    }
}

Daí, bastaria popular um produto por linha, antes de passar pro cadastro. Você pode passar uma lista de produto pro cadastro também:
    ArrayList<Produto> produtos = new ArrayList<>();
    int totalRows = suaJtable.getRowCount();

    for (int i = 0; i < totalRows; i++) {
        Produto p = new Produto();
        p.setNome((String) suaJTable.getModel().getValueAt(i, 0));
        p.setValor((double) suaJTable.getModel().getValueAt(i, 2));
        p.setQuantidade((int) suaJTable.getModel().getValueAt(i, 3));

        produtos.add(p);
    }

Depois é só passar produtos para seu método de cadastro, e fazer um laço percorrendo a lista para pegar os produtos e inserir na tabela, algo mais ou menos assim:
for(Produto p : produtos){
    Cadastro.cadastrar(p.getNome(), p.getQuantidade(), p.getValor());
}

Implementado no seu código, ficaria algo assim:
private void ConfirmacaoActionPerformed(java.awt.event.ActionEvent evt) {
        Confirmacao.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                try {

                    ArrayList<Produto> produtos = new ArrayList<>();
                    int totalRows = suaJtable.getRowCount();

                    for (int i = 0; i < totalRows; i++) {
                        Produto p = new Produto();
                        p.setNome((String) suaJTable.getModel().getValueAt(i, 0));
                        p.setValor((double) suaJTable.getModel().getValueAt(i, 2));
                        p.setQuantidade((int) suaJTable.getModel().getValueAt(i, 3));

                        produtos.add(p);
                        }

                       //...

                    for(Produto p : produtos){
                        Cadastro.cadastrar(p.getNome(), p.getQuantidade(), p.getValor());
                    }

                    jLValorTotal.setText("");
                    System.out.println("Cadastrado");
                } catch (SQLException e) {
                    System.out.println("Deu erro");
                }
            }
        });
    }

Talvez seja até mais interessante você criar seu próprio model, dessa forma, ficará menos complicado desde popular sua tabela, até atualizar e capturar dados dela.
Comment: @GustavoReisCosta cara sinto muito mas não posso te ajudar :/ pegar um projeto assim já perto do fim para refatorá-lo quase que por completo exige muito tempo e estudo do caso. Em alguns casos, fazer do zero acaba sendo uma opção mais viável do que "consertar o que já está feito". É por esse risco e outros que podem surgir, e por demandar tempo(o meu está meio corrido ultimamente), até pelo seu prazo, vou ficar te devendo essa :/
Comment: `ArrayList(...)` e `for(Produto p : produtos)`são para o modelo `Cardápio.java` ou `Produto.java`?
Comment: @GustavoReisCosta essa ArrayList é pra você armazenar os produtos da tabela. Você pode fazer sem ela, passando direto no primeiro for, mas dessa forma, da pra adicionar algum tipo de validação ou checar algo nos produtos, antes de salvá-los. Os dois laços podem ser feitos seguidos na classe Cardapio.
Comment: Então quero adicionar. Mas esquecemo-nos da parte de `private void ConfirmacaoActionPerformed`. Então devo remover essa parte do código? Em qual parte da classe `Cardápio` coloco esses dois laços? Devo criar uma nova classe TableModel como a resposta sugeriu na questão que você postou?
Comment: @GustavoReisCosta você pode colocar no seu `actionPerformed` mesmo, já que é la que você precisa pegar os produtos e cadastra-los. Quanto ao TableModel, foi só uma dica. Só remova aquelas duas linhas no seu `try`, antes da linha `jLValorTotal.setText("");`. Veja a edição da resposta.
Comment: Ficou assim: http://i.imgur.com/5s0Beos.png? Apesar disso, um erro avisou que `p` já é definido e outro erro disse que os tipos incompatíveis não podem converter `int` para `String`.
Comment: @GustavoReisCosta veja o código da edição que fiz com seu actionPerformed, nesse seu você colou um laço dentro do outro, e o segundo nem foi fechado. Outro detalhes, você está guardando quantidade e valor como String no seu banco? Como você vai somar isso se precisar depois? Dá uma revisada nisso.
Comment: Eu corrigi, mas deu um erro quando eu executei o aplicativo e confirmei o cadastro. `Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - exception java.sql.SQLException is never thrown in body of corresponding try statement at br.com.cardapio.view.Cardápio$6.actionPerformed(Cardápio.java:305)`. O que significa esse erro? Quanto às perguntas, sim, mas eu não consegui por causa desse erro. Eu não entendi a pergunta. Se você quiser dizer a quantidade e o valor. Então pego apenas a quantidade total e o preço total. Não separo as quantidades e os preços.
Comment: @GustavoReisCosta como você irá saber a quantidade de cada produto, se você guarda todos juntos numa linha? Talvez seja mais interessante você rever a modelagem do seu banco, senão sua aplicação pode ter problemas no futuro, e dificultar sua manutenção. O mais comum é ter uma tabela apenas pra armazenar produtos, outra pra armazenar pedidos feitos, e uma terceira pra guardar quais produtos e sua quantidade pedida em cada pedido.
Comment: Isso quer dizer que eu tenho que criar 3 novas tabelas a partir do zero?!
Comment: @GustavoReisCosta basicamente isso. Eu posso até adaptar o código para sua aplicação como tá, e você pode implementar e tudo fucionar, mas acredite, no futuro, você terá problemas se quiser, por exemplo, implementar controle de estoque, já que você não controla agora a quantidade de produtos que estão sendo vendidos. Você também não conseguirá recuperar pedidos isolados, já que não usa ID pra cada um.
Comment: Obrigado pelo aviso e pelas informações. Estou perdido, porque o prazo do meu projecto expirará na próxima semana, pois terei de apresentar ao meu professor e aos clientes. Gastei 2 meses, construindo e reparando tantos erros da aplicação. Tem como eu adaptar tudo para a minha aplicação numa semana? Ou isso levará meses?
Comment: @GustavoReisCosta meio complicado responder isso, pois depende dos requisitos que lhe foram pedidos e da complexidade deles. Mas você pode tirar suas dúvidas aqui no [pt.so]  na medida em que elas forem surgindo, ou pesquisar sobre programas semelhantes e como funcionam também.
Comment: Fiz isso.Tem vários projectos prontos semelhantes ao meu projecto no GitHub, mas preciso ter um banco de dados nele porque meu professor pediu. Só não sei se esses projectos prontos semelhantes funcionam no Eclipse e NetBeans.
Comment: Quanto tempo você leva para adaptar uma aplicação num projecto muito pequeno igual a esse? O que falta mais no meu projecto? Tem como você adaptá-lo para meu projecto pronto (mas ainda um pouco incompleto)? Posso creditar você como autor e contribuidor se você quiser.
Comment: Tudo bem, não tem problema, já mudei de projecto e substituí-o pelo de emissor de cupom fiscal o qual encontrei no vídeo do Youtube, com a permissão do meu professor.


Show that the Gelfand transform is a morphism?

Question:
Let $A$ be a commutative Banach algebra and let $x \in A$. We define the Gelfan transform of $x$ by $$\hat{x} (\chi)= \chi (x)$$ where $\chi$ is a nonzero multiplicative linear functional on $A$.

I need to show that $x \mapsto\hat{x}$ is a morphism, i.e if we define $$F(x)=\hat{x}$$ then we need to show that $$F(xy)= \hat{xy}=\hat{x}\hat{y}=F(x)F(y)$$
How can I go about showing this?
Comment: by [definition](https://en.wikipedia.org/wiki/Gelfand_representation#Gelfand_representation_of_a_commutative_Banach_algebra) of characters
Answer: Given a (nonzero) multiplicative linear functional $\chi$ on $A$ and $x,y\in A$, we have
\begin{align*}
\hat{xy}(\chi)&=\chi(xy)=\chi(x)\chi(y)=\hat{x}(\chi)\hat{y}(\chi) \\
\hat{(x+y)}(\chi)&=\chi(x+y)=\chi(x)+\chi(y)=\hat{x}(\chi)+\hat{y}(\chi)
\end{align*}
Furthermore, for any scalar $\alpha$, we have
$$ \hat{(\alpha x)}(\chi)=\chi(\alpha x)=\alpha\chi(x)=a\hat{x}(\chi) $$
Since $\chi$ was arbitrary, we see that
$$F(xy)=F(x)F(y),\qquad F(x+y)=F(x)+F(y), \qquad F(\alpha x)=\alpha F(x).$$
Comment: @user229672 The Gelfand transform is a morphism of *algebras*, which have both linear and multiplicative structures.  To be a morphsim of algebras, you must preserve both of these.
Comment: Thank you! :). I have not shown it to be linear yet. Can you please show that to me as well? I really appreciate it
Comment: @user229672 Does that help?
Comment: That certainly does! :). Thank you! Do you please mind explaining to me (in a comment will be fine) why we needed to show linearity as well? :).
Comment: Thank you! :). This makes perfect sense! :)
Comment: @user229672 Glad to help!


PyTest-Django Failing on missing django_migration table

Question: I'm trying to add pytest-django to my current pytest3/Django1.7 environment.
Currently we have not been using the plugin and have been suffering from shared state between certain tests
Everything seems to visually look good and the tests seem to pass until the end when I get the following error messages:
request = <SubRequest '_django_db_marker' for <Function 'test_filter_recurring_outside_sync_window'>>

    @pytest.fixture(autouse=True)
    def _django_db_marker(request):
        """Implement the django_db marker, internal to pytest-django.

        This will dynamically request the ``db`` or ``transactional_db``
        fixtures as required by the django_db marker.
        """
        marker = request.keywords.get('django_db', None)
        if marker:
            validate_django_db(marker)
            if marker.transaction:
                getfixturevalue(request, 'transactional_db')
            else:
                getfixturevalue(request, 'db')

ve/lib/python2.7/site-packages/pytest_django/plugin.py:376:

self = <django.db.backends.sqlite3.base.SQLiteCursorWrapper object at 0x11976a478>
query = 'SELECT "django_migrations"."app", "django_migrations"."name" FROM "django_migrations"', params = ()

    def execute(self, query, params=None):
        if params is None:
            return Database.Cursor.execute(self, query)
        query = self.convert_query(query)
>       return Database.Cursor.execute(self, query, params)
E       OperationalError: no such table: django_migrations

ve/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py:485: OperationalError

I tried creating the table with ensure_schema in the conftest.py.
I've tried every option of --nomigrations and --create-db to pytest.
I'm guessing it's a weird configuration problem I have with a legacy system, but I'm not sure where to start looking. Anyone have suggestions?
Comment: have you tried makemigrations and migrate for each of the app separately?
this might resolve your issues at times
Comment: Are you using something like `py.test /path/to/django/project --nomigrations --ds=myproject.settings.test`? What's the command you're running?
Answer: It looks like may be an issue with migration.
Running ./manage.py schemamigration research --auto shows that most of the fields don't have any defaults specified.
Next, you then run ./manage.py schemamigration research --init followed by ./manage.py migrate research
This worked for me after I created the table:
python manage.py migrate --run-syncdb

NOTE: Don't forget to run python makemigrations first, i.e. python manage.py makemigrations {name of the app where patients model is}

Helpful tips: There is a table generated by django called django_migrations which keeps track of what migrations have
    been
    applied. If you delete your migrations, re-generate them and try to
    migrate without deleting the records from the table, then django will
    think it already applied them. You should never delete your
    migrations, as it will cause django to get confused.
You can skip the migrations step if you are actively developing If you are actively developing and want to skip the entire migrations
    system you can, but once you start using migrations, never delete
    them. Here is what I use while developing a new project:

dropdb mydb && createdb mydb && python manage.py migrate --run-syncdb && python manage.py loaddata initial

First, it drops the database and all data. Then it creates an empty
  one. The --run-syncdb generates the schema and the loaddata loads
  data from a fixtures file.
So, if you are still developing and can delete all your data and move
  what you care about to a fixtures file, then you can delete all your
  migration folders. You then can run the command above each time you change your
  model.


Changing the field separator for multivalue fields

Question: I have a problem which should have a simple solution, but I simply can't figure it out. Perhaps I'm overthinking it or missing some piece of information. Being new to drupal it's not unlikely at all.
I'm trying to output a list of links through a View. No matter which Format I chose (unformatted list, grid, etc.), Drupal never fails to add a comma between each link. I'm having a great deal of trouble removing this comma.
Setting a separator under Field Settings have no effect, but I guess that's only applicable if I had another list of links.
I have tried editting 'views-view-field.tpl.php' by adding the line:
<code><?php $field->field_associated_quicklinks->separator = ""; ?>
</code>
But it doesn't seem to work. PHP and I aren't on friendly terms, so I'm loathe to start messing too much with the scripts - unless I got some helpful tips from you guys.
All in all I'm stuck on this, and frustrated that I'm having this problem in the first place. Drupal shouldn't go around adding content to my output.
------ EDIT:
Well, after several hours and a few tufts of hair, I found this great vid: http://www.youtube.com/watch?v=sxZQqgvJk3sI believe it's exactly what I needed to know, but I still can't make it work.
I did as prescriped:
1) Copied the field.tpl.php file, removed the comment and changed the mark-up a bit.
2) I named the file 'field--field_associated_links.tpl.php' and copied it into the templates folder of my sub-theme.
I get no reaction whatsoever. Could it be confused by the fact that my field name starts with 'field' as well?
Any and all suggestions are very welcome!
Answer: Normally you can control this separator directly in the views field option in the multiple field settings.

Have you tried to change this ?
Comment: My Saviour! I -knew- I was missing something very basic, and this was it. Can't believe I spend the whole darn day on this, only to learn I had to uncheck a box. Well, on the plus side, I now know a lot more about overriding fields and views now. Thanks so much tostinni, you really did save my day! :-)
Comment: PS: The override for the field as mentioned in the edit did actually work, but only for the output to the page itself - not when rendered through the view. I spend the last hour or so trying to override that.


Rotas do Codeigniter

Question: Estou usando o Codeigniter e só a rota
$route['default_controller'] = 'welcome';
está funcionando, quando eu faço uma exemplo:
$route['teste'] = "welcome";
ele me dá a seguinte mensagem
Cannot GET /codeigniter/index.php/teste .
Alguém saberia me informar o que pode ser ? Essa pasta que contem o codeigniter está dentro de outra aplicação
Answer: As rotas no codeigniter são para dar nome a caminhos, por exemplo no seu caso a rota padrão ao se abrir a index da pagina é:
$route['default_controller'] = 'welcome';
Onde default_controller significa que é o nome para o novo caminho e welcome e o controller deste caminho, no controller que se carrega as view que no caso é a pagina visual.
Também pode ser um erro por você fazer duas chamadas ao um controller em rotas diferentes, neste caso não sei se é possível ou não utilizar, provavelmente seja possível.
no seu caso ele esta informando que não conseguiu encontrar a controller welcome. Tente mudar de "welcome"para 'welcome' e ver se a controller welcome ainda existe dentro da pasta application/controller.
para mais duvidas talvez este link te ajude:
http://codeigniterbrasil.com/configuracoes/configuracao-rotas-routes-codeigniter/
Porem se você não sabe como se trabalha com MVC e codeigniter terá algum trabalho para conseguir fazer o que se deseja.
Porem este site tem grande conteúdo sobre codeigniter e pessoas que já trabalham a um bom tempo com este, eu prefiro laravel principalmente para se trabalhar com rotas, mas já utilizei codeigniter em dois trabalhos anteriores.
Att.
Thiago Prado
Comment: O problema é só que ele não está localizando as rotas, o conceito e tudo mais , eu entendo e consigo fazer de outras formas, acredito eu que esteja dando algum erro , porque estou usando o yeoman com php-cgi junto para conseguir executar. Também uso o Laravel, mas nesse caso, tenho que usar o Codeigniter.
Comment: Sem adicionar a nova rota ainda existe o problema? Ou só começou quando se criou esta nova rota?
Comment: Aproveitando qual foi a forma que você fez a chamada a teste?
Você fez: `http://meusite/teste` ou `http://meusite/index.php/teste`?
Comment: Tentei criar um vhost aqui com uma aplicação codeigniter zerada e foi tudo certo.

`$route['default_controller'] = "welcome";`
`$route['404_override'] = '';`
`$route['teste'] = "welcome";`

acessei por `http://codeigniter.app/index.php/teste` e o acesso se sucedeu normalmente sem erros, provavelmente alguma modificação nos configs do codeigniter causaram o crash, ou esta faltando alguma informação neste arquivo de rotas.
Answer: Você já declarou sua rota padrão.
 $route['default_controller'] = 'welcome';

Caso queira chamar o controler teste deve trocar o controle padrão para
$route['default_controller'] = 'teste';

Rotas do Codeigniter


Correctly writing a Zone File for a nameserver

Question: I need to write a zone file for a new company domain. Let's say the company owns company.com and I need to write a zone file for 2 domains play1.playground.company.com and play2.playground.company.com . When defining the zone file Origin line, do I need to put in the whole FQDN play1.playground.company.com. or just play1.playground is enough? Will the following zone file work out?
$ORIGIN play1.playground.company.com.
$TTL 3600
@        IN    SOA      ns hostmaster ( 1614244859 7200 3600 1209600 3600 )
@        IN     NS    ns
@        IN     A    126.96.36.199
@        IN    MX    10 mail
ns       IN    A    10.0.0.2
mail     IN    A    10.0.0.1
www      IN    CNAME    play1.playground.company.com.
wwwtest  IN     CNAME    www

Answer: $ORIGIN defines how unqualified names in your zone file should be completed.
You can use anything and even redefine  $ORIGIN to change that substitution behavior for subsequent records in the same zone file.
But that will probably lead to a complete mess.
$ORIGIN should be fully qualified and end in . dot.
By convention $ORIGIN should be set to zone name that zone file belongs to and that is what Bind will do when it is not explicitly defined.
See also https://www.zytrax.com/books/dns/ch8/origin.html
Afterthought: I have also seen zonefiles where $ORIGIN is set to only the dot ..
That has the result that effectively no substitution takes place. That forces an zone administrator to always use FQDN's everywhere and means you can't use the @ shorthand but also prevents situations such as the example below where a missing full stop after what was intended as an FQDN results in a CNAME record pointing to play1.playground.company.com.play1.playground.company.com.
$ORIGIN play1.playground.company.com.
www      IN    CNAME    play1.playground.company.com

I don't know if doing that makes a lot more sense but it does make both the record with and without the terminating . behave identical and as a sloppy zone administrator expects :
$ORIGIN .
www.play1.playground.company.com   IN  CNAME  play1.playground.company.com
www.play1.playground.company.com.  IN  CNAME  play1.playground.company.com.


Rails 4.0.0 jQuery Mobile button icons not showing in production

Question: I have decided to host my own jQuery mobile files as the gem jquery_mobile_rails only includes version 1.3.0 while I want to ensure I always have the latest version of jQM. This proved surprisingly easy as i just added the js file under javascripts and the css under stylesheets in my assets folder.
I copied the icon buttons to both /assets/images and to /assets/stylesheets/images. They are displayed properly in development but not in production. My console is showing the images being precompiled.
I have the following in production.rb
config.assets.precompile += %w(*.png *.jpg *.jpeg *.gif application-print.css)

Answer: Whereas Rails 3.2 would generate both a fingerprinted (picture-df71a1234da231a124a.png) and non-fingerprinted (picture.png) asset during precompilation, Rails 4 no longer generates non-fingerprinted versions.
Most likely, the CSS file from jQuery Mobile contains references such as this:
background-image: url(images/icons-18-white.png)

The problem being that the CSS file has no clue what the fingerprint should be. The best solution would be to use Rails' asset path helpers. First, make sure the file is an SCSS file (just rename it so it's something like jquery.mobile-1.3.1.css.scss). This will tell rails to compile it using Sass.
Next, change all of the url(...) entries in the css file to image-url(...). Make sure to add quotes around the path. For example, this would load the file at app/assets/images/images/icons-18-white.png (which becomes public/assets/images/icons-18-white.png in production).
background-image: image-url("images/icons-18-white.png")

Upon deploying these changes, the jQuery mobile css file should get precompiled and the resulting file should include the proper fingerprinted URLs.
Comment: How about this one? .ui-popup-screen {
 background-image: url(data:image/gif;base64,R
Comment: data:image urls should not be converted, only url() items referencing an actual filename.


What does "dynamic permissions" mean?

Question: What does dynamic permission mean, in Drupal 8?
When should I use this?
Answer: I consider it generating permissions based on some data within your site.
For instance, I wanted to create permissions based on terms or vocabularies for roles, in regards to if they could use the functionality a contrib module I maintain provides:
http://kevinquillen.com/drupal/2016/02/21/dynamic-permissions-in-drupal-8
If you look at the NodePermissions class, it does something similar.
Answer: In Drupal 8, the permissions a module defines are defined in a .permissions.yml file (such as the user.permissions.yml file used from the User module), which doesn't contain PHP code. As such, those are static permissions because they don't depend from any runtime condition, such as the node bundles defined from modules, the user roles present in the site, or the input filters implemented by modules.
Dynamic permissions are those permissions that depends from runtime conditions. For example, the Node module defines a set of permissions for each node bundle defined from modules. They cannot be statically set because the number and the type of node bundles can change from site to site.
In this case, Drupal allows to define in the .permissions.yml file a list of methods that return a list of extra permissions. This is what done, for example, in node.permissions.yml and filter.permissions.yml, where you find the following line.
permission_callbacks:
  - Drupal\filter\FilterPermissions::permissions

If you look at the code for Drupal\filter\FilterPermissions::permissions(), you will see how easy defining new dynamic permissions is: Return an array containing the title and description keys, keyed by the permission name.
  foreach ($formats as $format) {
    if ($permission = $format->getPermissionName()) {
      $permissions[$permission] = [
        'title' => $this->t('Use the @label text format', [':url' => $format->url(), '@label' => $format->label()]),
        'description' => [
          '#prefix' => '',
          '#markup' => $this->t('Warning: This permission may have security implications depending on how the text format is configured.'),
          '#suffix' => ''
        ],
      ];
    }
  }

What does "dynamic permissions" mean?


Finding the median of a set of data from a cumulative frequency graph GCSE level

Question: 200 students estimate the volume, V of a classroom.
The cumulative frequency diagram shows their results.
You are told at GCSE level to find the median by dividing 200 by 2, finding it on the y axis and reading off the value of the estimated volume on the x axis.  Why do you not find the average of the estimated volume for the 100th and 101st student?
Comment: Translation for international audience: GCSE is a secondary school examination in Britain and some other countries taken around age 16. In Britain it commonly marks the last shared point of students' mathematical education, except that some flavours are even less demanding than others.
Answer: The usual definition of a cumulative probability distribution for sample size $n$ is asymmetric, probabilities running from $1/n$ to $n/n$, so $0$ is not a plotted point but $1$ is. With this convention the median for even $n$ would (or should) plot just above $0.5$, but the discrepancy is only noticeable for a small sample size. If there were only $10$ values, the median would by this convention be plotted at $0.55$ cumulative probability, as it is at rank $5.5$. $100.5/200 = 0.5025$ is hardly discernible from $0.5$ except on a very large graph.
The difference is thus between a graphical approximation good and practical for at least moderate sample size and a numerical convention, which is exact in its own terms. (Mathematical groups are taught that the taking the midpoint  $y_{(n/2)} + y_{(n/2 + 1)}$ when $n$ is even in sample $y$ is a convention, and non-mathematical groups that it is a rule.)
Other way round, on quantile plots rather than cumulative distribution plots, it is common to plot ordered values (quantiles wide sense) against so-called plotting  positions, usually but not universally one member of a family $(i - a) / (n -2a + 1)$ for rank $i = 1, \dots, n$ and some $a$. Common choices for $a$ are $a = 0, a = 1/2, a = 1/3$. With such recipes, plotting positions are all symmetric about $0.5$, so that the median should always plot at probability $0.5$, either if it is a single value for odd sample size or if it is a midpoint for even sample size. For example, given a sample size of $200$, $(100.5 - 0.5) / (200 - 1 + 1), 100.5/201, $ and $(100.5 - 1/3) / (201 - 2/3)$ all reduce to $0.5$.


Display Rate module results via Panels

Question: So many of us know that the Rate module does not smoothly integrate with Panels.
I discovered out a way to get the voting widget to show using a custom content with the following PHP code:
<?php
if (arg(0) == 'node' && is_numeric(arg(1)) && ($node = node_load(arg(1)))) {
   print rate_embed($node, 'bias', RATE_FULL);
}
?>

Has anyone had any luck with doing something similar to display only the vote results (i.e. display total percent of that vote)?
I'm not a PHP wizard, but I think there is way by doing something like the following.
<?php
if (arg(0) == 'node' && is_numeric(arg(1)) && ($node = node_load(arg(1)))) {
   print get_rate_resluts($node, 'bias', RATE_FULL);
}
?>

But end up getting either blank pages or some fatal database errors. Thoughts?
Update:
I think I figured out that I need to create a custom content to print the output after reading it here. Tried this:
$block['content'] = rate_get_results('bias', $nid, $widget_id) $output['rating'];

But it looks like it does not do anything which is better then seeing a blank page.
Comment: `rate_get_results('node', $nid, $widget_id)` found here http://drupal.stackexchange.com/a/2483/12342 is what sparked the idea that this could be done.
Answer: print rate_embed($node, 'NAME', RATE_FULL);

Replace NAME with the machine name of the widget; the view mode can be RATE_FULL, RATE_COMPACT, RATE_DISABLED, RATE_CLOSED, RATE_COMPACT_DISABLED.

Display Rate module results via Panels


open a man page in linux terminal

Question: How to open then man page of mkdir from terminal . I want the manual entry given in the following link.
Answer: Simply give like this.
  man 2 mkdir

From the man page of man

1   Executable programs or shell commands
2   System calls (functions provided by the kernel)
3   Library calls (functions within program libraries)
4   Special files (usually found in /dev)
5   File formats and conventions eg /etc/passwd
6   Games
7   Miscellaneous (including macro packages and conventions), e.g. man(7), groff(7)
8   System administration commands (usually only for root)
9   Kernel routines [Non standard]

You need to open the system call , so you have to mention that as 2. If you give like this, man mkdir then it will open the man page of mkdir command.
Answer: You can open the man page from the terminal using the man command.
man 2 mkdir

For more details you can use man man.

open a man page in linux terminal


Variance of estimator for mean of bag of unfair coins

Question: Consider a bag of coins containing some fixed, large number of unfair coins. Each coin has a different probability $p$ for heads. The estimation task is to estimate the mean probability of heads
$$\mathbb{E}[p_{heads}]$$
with respect to the entire bag of coins. This can be done by randomly drawing individual coins from the bag with replacement and tossing those coins a couple of times to estimate their individual probabilities of head.
More specifically, let' say we draw $s$ coins from the bag and toss each of these $m$ times to obtain $X_{i,j}\in \{0,1\}$ where $i\in \{1,\dots,s\}$ and $j\in \{1,\dots ,m\}$. The unbiased estimator for the mean probability of heads of the bag is then
$$\hat{p}_{heads} =\frac{1}{s}\frac{1}{m}\sum_{i=1}^s \sum_{j=1}^m X_{i,j}$$.
My question is: What is the variance of this estimator as a function of $s$ and $m$?
Motivation: In particular, I am trying to understand if the variance actually gets at all better when increasing $m$ and keeping $s$ fixed, i.e. is there any merit to estimating individual coins more precisely. This question is motivated by a setting where drawing new coins from the bag is a lot more costly than just tossing a coin that has already been drawn a lot of times. One might think that one could get away with a trade off: Either draw a lot of coins and estimate them very roughly or draw few coins and estimate those very accurately to form an average.
Answer: We can write $\hat{p} = \frac{1}{s}\frac{1}{m} \sum_{i = 1}^s X_i$, where $X_i | p_i \sim B(m, p_i)$ is a binomial random variable counting the number of heads thrown on the $i$-th coin, whose probability of success is itself a random variable (that we don't know much about). Then each of the $X_i$ is independent of each other (since the coin draws are being made with replacement), so we know from standard variance properties that:
$$Var(\hat{p}) = \frac{1}{s^2} \frac{1}{m^2} \sum_{i = 1}^s Var(X_i)$$
Then, since each $X_i$ has two separate random processes involved in it, we can invoke the law of total variance to better understand it, noting that if $p_i$ were fixed, then $E(X_i) = m p_i (1 - p_i)$ and $Var(X_i) = m p_i$ per standard properties of the binomial distribution:
$$\begin{eqnarray}Var(X_i) & = & E_{p_i}[Var(X_i | p_i)] + Var_{p_i}[E(X_i | p_i)] \\
& = & E[m p_i (1 - p_i)] + Var(m p_i) \\
& = & m (E(p_i) - E(p_i^2)) + m^2 Var(p_i) \\
& = & m E(p_i) - m(Var(p_i) + E(p_i)^2) + m^2 Var(p_i) \\
& = & m E(p_i) (1 - E(p_i)) + m(m - 1) Var(p_i) \\
& = & m E(p) (1 - E(p)) + m(m - 1) Var(p)
\end{eqnarray}$$
Since each $p_i$ is just an i.i.d. draw from the possible coins in the bag, for which we can say that the probability of heads is distributed per the random variable $p$.
Putting this back into the original variance calculation gives us:
$$\begin{eqnarray}Var(\hat{p}) & = & \frac{1}{s^2} \frac{1}{m^2} \sum_{i = 1}^2 Var(X_i) \\
& = & \frac{1}{s^2} \frac{1}{m^2} s \left[m E(p) (1 - E(p)) + m(m - 1) Var(p) \right] \\
& = & \frac{1}{s m} \left[ E(p) (1 - E(p)) + (m - 1) Var(p) \right]
\end{eqnarray}$$
So, to answer your question - is it better to flip more coins, or to flip the same coins more times? Well, notice that as $m$ increases, the expression will tend asymptotically to $\frac{1}{s} Var(p)$, meaning that more flips of the same coins gives you diminishing returns - you'll become very certain of how those coins will flip, but you still have a finite amount of information about the bag in general. On the other hand, increasing $s$ will make the variance tend to 0, so you will always get a more accurate result.
However, if you have some information about $E(p)$ and $Var(p)$, as well as the relative "cost" of drawing more coins versus flipping the same coins, then you can properly optimise the process. For example, if you know that the coins are probably fairly similar (i.e. $Var(p)$ is small-ish), then the overall variance is essentially $\frac{K}{s m}$ and you can try to minimise that value subject to a total fixed cost of $C = c_1 s + c_2 m$ via, say, Lagrange multipliers to find that you should perform them in inverse relation to their cost (i.e. $\frac{s}{m} = \frac{c_2}{c_1}$).


When to test For Equality of Medians, and when Stochastic Equality?

Question: In statistics, we are very often interested in investigating whether some score (let's say life satisfaction) tends to be bigger in one population (let's say rich people) compared to another population (let's say poor people). Most often, this research question is formalized by testing the null hypothesis of equal means. However, for a comparison of means to be sensible, the variable of interest must be at least on an interval scale. So, for ordinal data, other formalizations should be used.
Two formalizations are generally used for ordinal data. Equality of medians and stochastic equality, which is defined as $P(X<Y)=P(X>Y)$, where $X,Y$ are the random variables representing the two populations. Many papers argue that stochastic equality is the better formalization. The core argument is that the medians can be equal even if the scores in one population are clearly bigger. Consider as an example the following mixture distributions for $X$ and $Y$. With probability .5 $X$ is just $1$, and with probability $.5$ it is sampled from $\text{Uniform}[0,1)$. Similarly, with probability .5 $Y$ is just $1$, and with probability $.5$ it is sampled from $\text{Uniform}(1,2]$. Thus, $\text{Median}(X)=1=\text{Median}(Y)$, while no realization of $Y$ is smaller than any realization of $X$ and $50\%$ of the realizations of $Y$ are bigger than all realizations of $X$.
Thus, should we stop testing for equality of medians, or are there research questions for which the equality of medians is the appropriate question? If yes, what are those?
Comment: I like this because it says that asking the right questions is very important.  I would look at geometric means instead of medians or means.  I might also consider harmonic means when thinking about trajectories over time, especially if trying to select a treatment to engage inequality.
Comment: I would say that stochastic equality is often also a better alternative to tests of means. Many, many papers show that two groups A and B differ on the mean of some variable, but for any such given difference in the mean, people will vastly overestimate how likely it is that a randomly drawn instance of A is larger than one from B.
Comment: The question just is whether this is answerable here at CV. Yes, we should answer the right questions, but which question is the right one will depend on your application. I imagine this might be closed as opinion-based.
Comment: @StephanKolassa: I completely agree with you.  Stochastic equality is often also a better alternative to tests of means. This is nicely argued in the literature, and guidelines for choosing between the two are presented, whereas I found nothing for the comparison of equality of medians and stochastic equality.
Comment: I also completely agree that essentially the application should dictate the question you ask. In that sense, my question is, are there applications for which the equality of medians is a sensible question, and if yes can we provide guidelines for practitioners of how to choose between stochastic equality and equality of medians.
Comment: I like the question. Still, I have rarely seen a two sample median test in practical applications (except when people *think* they compare medians when using rank tests).
Answer: This depends, in part, on the number of ordinal categories.
If the number of categories is small, then comparing the medians may be uninformative. Suppose the categories are Like/Like Somewhat/Neutral/Dislike Somewhat/Dislike, the
poor group's answers are distributed 20%-20%-20%-20%-20%, and the rich group's answers are distributed 10%-20%-25%-25%-20%. Then both groups have a median response of Neutral, but the comparison of random pairs shows that a rich person will probably be more negative than the poor person. Depending on the size of the groups, that might be significant.
If the number of categories is large, then comparing the medians may be more useful. Suppose twelve people from groups A and B all start a task at the same time, and the only data available is that they finish in the order ABABBBAAABAB. Then a random pair from the two groups is equally likely to have the A or B person finish first, but the median person in group B finished earlier than the median person in group A. Again, with enough people in the groups, the difference in medians might be significant.
More generally, if you don't care about small perturbations in the tails of the two grops, or if you think that there's more noise or measurement error in those tails, then the medians are more robust and it would be appropriate to test the significance of their difference.


Fatal error: 'ext/standard/php_smart_str.h' file not found

Question: I downloaded MacOS Mojave and did a clean installation on my mid 2012 macbook Pro. Installed XCode with command line tools. Got native Apache and PHP working, with PEARL, PECL and last version of ICU (63.1) for later use of Intl extension.
But every attempt of Intl instalation has failed. Before the clean instalation, i found a intl.so on a pen drive and used ICU version 54, but isn't the best way to get things working for a development enviroment.
In the end, i'm stuck with PECL incapable of finish intall of Intl because can't find php_smart_str.h file.
I've reinstalled the developer tools header files too:
$ sudo installer -pkg /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg -target /
Is it possible to have a development enviroment without Homebrew?
When i run at the terminal:
sudo pecl install intl
Returns the following:
/private/tmp/pear/install/intl/intl_error.h:24:10: fatal error: 'ext/standard/php_smart_str.h' file not found
Right after creating libtool and running: make.
Comment: Try running `sudo pecl update-channels` first. ([src](http://darraghenright.tumblr.com/post/22027208929/installing-intl-package-on-osx-lion))
Comment: Thanks @aynber but i tried this too and didn't work, same error.
Answer: Ok, instead of using homebrew, i really wanted to use only native apache and php pre-installed on my MacBook Pro with Mac OS Mojave, trying to maintain the most clean development environment possible for CakePHP use.
So, on Pecl Official site ( https://pecl.php.net/package/intl ), it's clear that Intl package is not maintained anymore and has been superseded. Since PHP 5.3.0 you don't need to use Pecl to install intl extension, it's bundled with PHP.
But, it's missing on native instalation of PHP 7.1.24 on Mac OS Mojave.
Then i downloaded PHP 7.1 from php.net, installed XCode Command Line Tools, ICU (http://site.icu-project.org/), Autoconf, reinstalled the developer tools header files, and finally installed Intl extension using phpize.
Important: you'll have to disable SIP.


Show $E[(M_n-M_m)M_k]=0$

Question:
Let $M_n$ be an $(\mathcal{F}_n)$ - martingale on $\left(\Omega,\mathcal{F},P\right)$, show that
$$E[(M_n-M_m)M_k]=0,\qquad 0\leq k\leq m \leq n.$$

I want to know if this is correct:
By the multi-step property of a martingale we have that
$$E[M_n|\mathcal{F}_m]=M_m\implies E[M_n-M_m|\mathcal{F}_m]=0,\qquad 0\leq m\leq n.$$
Multiplying my $M_k$ gives
$$M_kE[M_n-M_m|\mathcal{F}_m]=0.$$
Since $\mathcal{F}_k\subseteq \mathcal{F}_m$, then
$$E[(M_n-M_m)M_k|\mathcal{F}_m]=0$$
and taking expectations gives
$$E[E[(M_n-M_m)M_k|\mathcal{F}_m]]=E[(M_n-M_m)M_k]=0.$$
Is this correct?
Answer: It looks fine to me.  The only criticism I'd make is that your last line has the wrong order on the equalities, and
$$E[(M_n-M_m)M_k]=E[E[(M_n-M_m)M_k|\mathcal{F}_m]]=0$$
reflects your logical argument better (to someone who knows the subject, your intent is clear, but to someone learning it, it might look like you're begging the question).

On a sidenote, I'm assuming your martingale is $L^2$.  Otherwise, there's a problem when you first write $E[(M_n-M_m)M_k|\mathcal{F}_m]=0$

Show $E[(M_n-M_m)M_k]=0$


Morphism of ringed spaces not induced by homomorphism of rings

Question: I would like to see a bit more detailed explanation why the example in
this thread is a example for a morphism of ringed spaces not induced by homomorphism of rings:
Here we have $R = \mathbb{C}[T]_p $ as localisation at $p =(T)$. Let be $F = Frac(R) = \mathbb{C}(T)$. As topological spaces we choose $X,Y = Spec(R)= \{x_{(T)}, x_0\}$. Let $V = D(1), U = D(T)$. Obviosly $\Gamma(V, O_Y) =R,  \Gamma(U, O_Y) =F $. Now there is a morphism of ringed spaces which should become a conterexample:
Because of inclusions $R \subset F \subset \mathbb{C}$ we define the ringhomomorphisms as folows:
$ \phi_V : \Gamma(V, O_Y) \to \Gamma(V, O_Y)$ for $\phi_V := R \subset F \subset \mathbb{C} \subset R$ and $ \phi_U : \Gamma(U, O_Y) \to \Gamma(U, O_Y)$ for $\phi_U := F \subset \mathbb{C} \subset R\subset F$. That's clear that $ R \xrightarrow{\phi_V} R \subset F = R \subset F \xrightarrow{\phi_U} F$, so with $f: X \xrightarrow{id} Y$ the pair $(f, \phi)$ would become a morphism between ringed spaces.
That's clear to me that because of definition of $\phi_V$ as a composition through a field and the fact that $Spec(F) = {x_0} $ the induced morphism $Spec(\phi_V): Spec(R) \to Spec(R)$ maps $x_{(T)}, x_0 \to x_0$ but thats not clear why this construction provide a conterexample, so that it is not induced by a ringhomomorphism or aquivalent: there not exist a ringhomom $\psi: R \to R$ that for $ U = D(s)$ the maps $\phi_U$ have the shape $R_s = \Gamma(U, O_Y) \xrightarrow{\phi_U} \Gamma(U, O_X), \frac{a}{s^n} \to \frac{\psi(a)}{\psi(s)^n}$.
Answer: I'm honestly getting a little lost in your argument. For one thing, at the beginning you include $\Bbb C(T)$ into $\Bbb C$, which is possible, but not natural and I don't see the benefit (nowhere do you need to perform such an unnatural operation to see the counterexample!). In fact, the map you're trying to write down is not the counterexample of the linked question at all: the counterexample map from the other question does not have the same domain and codomain, as you do here! So I'll try to explain the counterexample of the linked question in more detail, and while this won't address your argument explicitly, I hope it can clear up some of your confusion.
Let $(A,\mathfrak{m})$ be a DVR, so that $\operatorname{Spec} A = \{s,\eta\}$ ($s$ is the closed point corresponding to the ideal $\mathfrak{m}$, and $\eta$ is the generic point corresponding to $(0)$), and let $K = \operatorname{Frac}A$, so $\operatorname{Spec} K = \{\sigma\}$. As in the example in the other question, we define the map of ringed spaces $f : (\operatorname{Spec} K,\mathcal{O}_K)\to(\operatorname{Spec} A,\mathcal{O}_A)$ as follows:
\begin{align*}
f : \sigma &\mapsto s,\\
f^\sharp(\operatorname{Spec} A) : \mathcal{O}_A(\operatorname{Spec} A)\cong A&\to K\cong f_\ast\mathcal{O}_K(\operatorname{Spec} A)\quad\textrm{is the natural inclusion }\iota,\\
f^\sharp(\{\eta\}) : \mathcal{O}_A(\{\eta\})\cong K&\to 0\cong f_\ast\mathcal{O}_K(\{\eta\})\quad\textrm{is the unique map to $0$},\\
f^\sharp(\emptyset) : \mathcal{O}_A(\emptyset)\cong 0&\to 0\cong f_\ast\mathcal{O}_K(\emptyset).
\end{align*}
Because the restriction map on the structure sheaf of $\operatorname{Spec} A$ from $\operatorname{Spec} A$ to $\{\eta\}$ is the inclusion $\iota : A\to K$, we see that this is indeed a map of ringed spaces.
However, this is not a map of locally ringed spaces. Since the only open set containing $s$ is all of $\operatorname{Spec} A$, the stalk map
$$
f^\sharp_\sigma : \mathcal{O}_{A,f(\sigma)}\to\mathcal{O}_{K,\sigma}
$$
is simply the map on global sections; i.e.,
$$
f^\sharp_\sigma = f^\sharp(\operatorname{Spec} A) : A\to K.
$$
This is a ring homomorphism, but the maximal ideal $\mathfrak{m}\subseteq A$ is not mapped into the maximal ideal $(0)\subseteq K$. Hence, the map of ringed spaces defined above cannot be induced by a ring morphism $\phi : A\to K$, because any ring homomorphism induces a morphism of locally ringed spaces $(\operatorname{Spec} K,\mathcal{O}_K)\to(\operatorname{Spec} A,\mathcal{O}_A)$.
Another way to argue that the map $f$ is not induced by a ring homomorphism $\phi : A\to K$ is to first show that if $f$ is induced by $\phi$, then the map of structure sheaves on global sections $f^\sharp(\operatorname{Spec} A) : \mathcal{O}_A(\operatorname{Spec} A)\to f_\ast\mathcal{O}_K(\operatorname{Spec} A)$ is in fact the map $\phi$. That is, the diagram
$$
\require{AMScd}
\begin{CD}
\mathcal{O}_A(\operatorname{Spec} A) @>{f^\sharp(\operatorname{Spec} A)}>> f_\ast\mathcal{O}_K(\operatorname{Spec} A);\\
@VVV @VVV \\
A @>{\phi}>> K;
\end{CD}
$$
whose vertical arrows are the natural isomorphisms commutes. However, the map on global sections $f^\sharp(\operatorname{Spec} A)$ for the map defined above is the inclusion, and the map on topological spaces induced by the inclusion sends $\sigma$ to $\eta$.
Comment: I also think that $f_{*}\mathcal{O}_{K}(\{\eta\})=\{0\}$, since $f^{-1}(\{\eta\})=\emptyset$.
Comment: @JanBakfiets1, I also think your last comment is correct. Can we have confirmation of this?
Comment: is the map $f^{\#}(\operatorname{Spec}(A): A\rightarrow K$ given by the inclusion map unique? Or are there also other possibilties to define that homomorphism?
Comment: @janbakfiets1 and kamil, you're absolutely right that $f_*\mathcal{O}_K(\{\eta\})$ should be $0.$ Thanks for the catch!


Active Directory shortcut failing to create

Question: Background: I am making a GPO with desktop shortcuts for users. The GPO has a few links to websites like our help desk that it places.  It also has a shortcut to a network location for a file share.
The Issue: The shortcuts that go to URLs apply just fine.  The one that goes to the network location doesn't work.  The offending one is, as far as I can tell, configured entirely correctly.
Here you can see the configuration:

The shortcut path is \\SERVER.  Using the same configuration, I was able to make it work with \\SERVER\SUBFOLDER, but can't get it to work with the top level.
On the client computer I see this error:

What I've Tried:  When I research this issue I found a lot of people saying it an issue with the security context so I tried checking/unchecking the Security Context settings in the common tab for the shortcut and running a gpupdate /force.  I also found people saying that it might not like the name of the server, but that can't be it because it resolves subfolders.
What I Want: I want to be able to map this shortcut directly to \\SERVER directly with group policy.  I can't map it to a subfolder and deploy it because of the way the server is configured for files.  I know that I could deploy it with a login script that just places a shortcut on the desktop, but I'd like to keep everything vanilla group policy.
Comment: My guess is that it's because \\server isn't technically a UNC path for which a file system object shortcut can be created. A UNC path must contain at least two path components, such as \\server\share. - https://msdn.microsoft.com/en-us/library/cc227007.aspx
Comment: If \\server isn't a valid UNC path then I don't see how you can make it work.
Comment: The problem is that GPP can't create the shortcut because it isn't valid, but there's nothing stopping you from manually creating the shortcut and then copying the shortcut to the client machines with GPP.
Comment: I think that's what I'll do. I'll make a login script that copies a shortcut from a network location. Thanks!
Comment: @joeqwerty That would make sense. Is there a way to make it work anyway or will I need to take a different approach?
Answer: My guess is that it's because \\server isn't technically a UNC path for which a file system object shortcut can be created. A UNC path must contain at least two path components, such as \\server\share.
If \\server isn't a valid UNC path then I don't see how you can make it work as is, but there's nothing stopping you from manually creating the shortcut and then copying the shortcut to the client machines with GPP.
https://msdn.microsoft.com/en-us/library/cc227007.aspx


Advantage of Bernoulli Naive Bayes over Multinomial in Text Classification

Question: While I understand the difference between Multinomial Naive Bayes algorithm and Bernoulli, based on my understanding, Multinomial is always a preferred method for any sort of Text classification(Spam detection, topic categorization, sentiment analysis) as taking the frequency of the word into consideration will have better accuracy than just checking for word occurrence.
Is there any practical use case where Bernoulli will be preferred over Multinomial? Is there any real world example that favors Bernoulli over Multinomial?
Answer:
taking the frequency of the word into consideration will have better accuracy than just checking for word occurrence.

Not necessarily. Multinomial Naive Bayes is in a sense more complex model (you can reduce it to Bernoulli).
Because of that, Bernoulli model can be trained using less data and be less prone to overfitting. You might want to read on bias-variance tradeoff if you want to get more technical explanation why sometimes it's better to use simpler model.
For a concrete example see this notebook that compares aforementioned methods on  SMS Spam Collection Data Set. It seems like Bernoulli NB performs better.


Meteor JS: How to use Spacebars to display contents inside an array retrieved from Meteor Collection

Question: I have a collection:
MenuItems = new Mongo.Collection('menu_items');

and I also have an array:
var arrayToInsert = ['Gemstone', 'Rings'];

I then insert this array into the collection via:
MenuItems.insert(arrayToInsert);

The resulting document inside my mongodb as shown in RoboMongo is:
{
    "_id" : "yRXmFGxLCZXLf9Ynh",
    "0" : "Gemstone",
    "1" : "Rings"
}

In my Template Helper I have:
menuItems: function(){
    return MenuItems.find();
  },

In my .html file I do this:
{{#each menuItems}}
  {{this}}
{{/each}}

But I only get this output:
[object Object]

How do I use Spacebars to iterate through this array of data so I may get it to display 'Gemstone' and 'Rings'????
Thank you very much.
Comment: oops its {{this.[1]}} forgot that the result is an array of objects
Comment: Hi, {{this[1]}}  doesn't work....{{this[0]}} also does not work....
Answer: If you want the array to represent the menu items value, you should insert them into the collection like this :
arrayToInsert.forEach(function(menuItem){
  MenuItems.insert({
    label: menuItem
  });
});

Then you can display the menu items in your template :
JS
Template.menu.helpers(function(){
  menuItems: function(){
    return MenuItems.find();
  }
});

HTML
<template name="menu">

    {{#each menuItems}}

{{label}}

    {{/each}}

</template>

If you want to store the array as part of the collection documents, use this code :
JS
MenuItems.insert({
  items:arrayToInsert
});

HTML
<template name="menu">
  {{#each menuItems}}

      {{#each items}}

{{this}}

      {{/each}}

  {{/each}}
</template>

Comment: Assigning the array to a key is a lot easier to manipulate, you won't have to deal with the `this.[index]` syntax.
Comment: Ok, so with its current form of insertion e.g. MenuItems.insert(arrayToInsert); there is no way of displaying the data using spacebars??? It really has to be assigned to a 'key' like ur example above???   Thank you


Java - Looking for example comparing nested class with anonymous inner class

Question: Can someone provide me with a good simple example of a regular nested class and then the same class re-written as an anonymous inner class?
Comment: You can get your IDE to do this.  Create an anonymous inner class and when get your IDE to move the class and refactor it for you.
Comment: stack overflow has lots of answer regarding this i think
Answer: Here are examples:
<code> public class Outer {
     public static class NestedStatic implements Runnable {

         public void run(){
             doSomething();

         }
     public static void main(String[] args){
         Thread nestThread=new Thread(new NestedStatic());
         nestThread.start();

         // now anonymous:
         Thread anonThread=new Thread(new Runnable(){
             public void run(){
                 doSomethingElse();
             });
         anonThread.start();
     }
}
</code>