text:
Q: Listar conteúdo de uma lista com um método Possuo o seguinte código:
using System;
using System.Collections.Generic;

public class Program
{
    class Candidato
    {
        public int numeroPartido {get;set;}
        public string nomeCandidato {get;set;}
        public int quantidadeVotos {get;set;}
    }
    class Eleitor
    {
        public string CPF {get;set;}
        public string nomeEleitor {get;set;}
        public Boolean votoRealizado {get;set;}
    }
    public static void Main()
    {
        var x = 0;
        var y = 0;
        var z = 0;
        var contador = 0;
        var opcao = 0;

        List<Candidato> listaCandidatos = new List<Candidato>();
        listaCandidatos.Add(new Candidato {numeroPartido = 17, nomeCandidato = "Fulano", quantidadeVotos = 0});
        listaCandidatos.Add(new Candidato {numeroPartido = 13, nomeCandidato = "Ciclano", quantidadeVotos = 0});
        listaCandidatos.Add(new Candidato {numeroPartido = 45, nomeCandidato = "Deltrano", quantidadeVotos = 0});
        listaCandidatos.Add(new Candidato {numeroPartido = 99, nomeCandidato = "Branco", quantidadeVotos = 0});
        listaCandidatos.Add(new Candidato {numeroPartido = 999, nomeCandidato = "Nulo", quantidadeVotos = 0});

        List<Eleitor> listaEleitores = new List<Eleitor>();
        listaEleitores.Add(new Eleitor {CPF = "1", nomeEleitor = "João", votoRealizado = false});
        listaEleitores.Add(new Eleitor {CPF = "2", nomeEleitor = "Maria", votoRealizado = false});
        listaEleitores.Add(new Eleitor {CPF = "3", nomeEleitor = "Antonio", votoRealizado = false});
        listaEleitores.Add(new Eleitor {CPF = "4", nomeEleitor = "Marcos", votoRealizado = false});
        listaEleitores.Add(new Eleitor {CPF = "5", nomeEleitor = "Ana", votoRealizado = false});
        listaEleitores.Add(new Eleitor {CPF = "6", nomeEleitor = "Marcia", votoRealizado = false});
        listaEleitores.Add(new Eleitor {CPF = "7", nomeEleitor = "Marcio", votoRealizado = false});
        listaEleitores.Add(new Eleitor {CPF = "8", nomeEleitor = "Carla", votoRealizado = false});
        listaEleitores.Add(new Eleitor {CPF = "9", nomeEleitor = "Bruna", votoRealizado = false});
        listaEleitores.Add(new Eleitor {CPF = "10", nomeEleitor = "Mara", votoRealizado = false});

        while (opcao == 1 || opcao == 2 || contador < 10){
            Console.WriteLine("DIGITE A OPÇÃO DESEJADA:");
            Console.WriteLine("1 - PARA VOTAR.");
            Console.WriteLine("2 - LISTAR VOTAÇÃO.");
            Console.WriteLine("------------------------");
            opcao = int.Parse(Console.ReadLine());
            if (opcao == 1){
                Console.Write("DIGITE SEU CPF PARA REALIZAR O VOTO: ");
                var CPFEleitor = Console.ReadLine();
                foreach (var itemEleitores in listaEleitores)
                {
                    if (itemEleitores.CPF.Equals(CPFEleitor) && itemEleitores.votoRealizado == true){
                        Console.WriteLine("ELEITOR: "+itemEleitores.nomeEleitor);
                        y = 1;
                    }
                    if (itemEleitores.CPF.Equals(CPFEleitor) && itemEleitores.votoRealizado == false){
                        Console.WriteLine("ELEITOR: "+itemEleitores.nomeEleitor.ToUpper());
                        contador++;
                        itemEleitores.votoRealizado = true;
                        Console.Write("DIGITE O NUMERO DO SEU CANDIDATO: ");
                        var numeroCandidato = Console.ReadLine();
                        if (!numeroCandidato.ToString().Equals("")){
                            foreach (var itemCandidados in listaCandidatos)
                            {
                                if (itemCandidados.numeroPartido.ToString().Equals(numeroCandidato)){
                                    Console.WriteLine("CANDIDATO: "+itemCandidados.nomeCandidato.ToUpper());
                                    Console.WriteLine("VOTAÇÃO CONCLUÍDA.");
                                    Console.WriteLine("------------------");
                                    itemCandidados.quantidadeVotos = itemCandidados.quantidadeVotos + 1;
                                    z = 1;
                                }
                            }
                            if (z == 0){
                                foreach (var itemCandidados in listaCandidatos)
                                {
                                    if (itemCandidados.numeroPartido == 999){
                                        itemCandidados.quantidadeVotos = itemCandidados.quantidadeVotos + 1;
                                    }
                                }
                            }
                            x = 1;
                        } else {
                            foreach (var itemCandidados in listaCandidatos)
                            {
                                if (itemCandidados.numeroPartido == 99){
                                    itemCandidados.quantidadeVotos = itemCandidados.quantidadeVotos + 1;
                                }
                            }
                        }
                    }
                }
                if (x == 0 && y == 0){
                    Console.WriteLine("CPF NÃO CADASTRADO");
                }
                if (y == 1){
                    Console.WriteLine("ELEITOR JÁ REALIZOU SEU VOTO");
                }
                x = 0;
                y = 0;
                z = 0;
            } else if (opcao == 2){
                foreach (var item in listaCandidatos)
                {
                    Console.WriteLine("Candidato {0} ({1}). Votos {2}.", item.nomeCandidato, item.numeroPartido, item.quantidadeVotos);
                }
                Console.WriteLine("------------------------");
            } else {
                Console.WriteLine("OPÇÃO INVÁLIDA. TENTE NOVAMENTE.");
            }
            opcao = 0;
        }
        if (contador == 10){
            Console.WriteLine("-------------------------------------------------");
            Console.WriteLine("VOTAÇÃO ENCERRADA. TODOS OS ELEITORES JÁ VOTARAM.");
            Console.WriteLine("-------------------------------------------------");
            foreach (var item in listaCandidatos)
            {
                Console.WriteLine("Candidato {0} ({1}). Votos {2}.", item.nomeCandidato, item.numeroPartido, item.quantidadeVotos);
            }
        }
    }
}

Gostaria de criar um método para listar o conteúdo de uma dessas minhas listas, como já faço aqui:
Console.WriteLine("VOTAÇÃO ENCERRADA. TODOS OS ELEITORES JÁ VOTARAM.");
Console.WriteLine("-------------------------------------------------");
foreach (var item in listaCandidatos)
{
    Console.WriteLine("Candidato {0} ({1}). Votos {2}.", item.nomeCandidato, item.numeroPartido, item.quantidadeVotos);
}

Porém não estou conseguindo passar essa minha lista como parâmetro para meu método para assim percorrer ela e exibir seu conteúdo.

A: Provavelmente você não está conseguindo passar como parâmetro por causa que a classe não é publica.
Alterei seu código para a seguinte forma:
Ajustei também os nomes das propriedades, em C# utilizamos Pascal Case e a classe Boolean tem um "apelido", bool que é mais fácil e curto de digitar ;)
using System;
using System.Collections.Generic;

public class Program
{
    public class Candidato
    {
        public int NumeroPartido { get; set; }
        public string NomeCandidato { get; set; }
        public int QuantidadeVotos { get; set; }
    }
    public class Eleitor
    {
        public string Cpf { get; set; }
        public string NomeEleitor { get; set; }
        public bool VotoRealizado { get; set; }
    }

    public static void ExibeResultado(List<Candidato> listaCandidatos)
    {
        Console.WriteLine("VOTAÇÃO ENCERRADA. TODOS OS ELEITORES JÁ VOTARAM.");
        Console.WriteLine("-------------------------------------------------");
        foreach (var item in listaCandidatos)
        {
            Console.WriteLine("Candidato {0} ({1}). Votos {2}.", item.NomeCandidato, item.NumeroPartido, item.QuantidadeVotos);
        }
    }

    public static void Main()
    {
        var x = 0;
        var y = 0;
        var z = 0;
        var contador = 0;
        var opcao = 0;

        List<Candidato> listaCandidatos = new List<Candidato>
        {
            new Candidato { NumeroPartido = 17, NomeCandidato = "Fulano", QuantidadeVotos = 0 },
            new Candidato { NumeroPartido = 13, NomeCandidato = "Ciclano", QuantidadeVotos = 0 },
            new Candidato { NumeroPartido = 45, NomeCandidato = "Deltrano", QuantidadeVotos = 0 },
            new Candidato { NumeroPartido = 99, NomeCandidato = "Branco", QuantidadeVotos = 0 },
            new Candidato { NumeroPartido = 999, NomeCandidato = "Nulo", QuantidadeVotos = 0 }
        };

        List<Eleitor> listaEleitores = new List<Eleitor>
        {
            new Eleitor { Cpf = "1", NomeEleitor = "João", VotoRealizado = false },
            new Eleitor { Cpf = "2", NomeEleitor = "Maria", VotoRealizado = false },
            new Eleitor { Cpf = "3", NomeEleitor = "Antonio", VotoRealizado = false },
            new Eleitor { Cpf = "4", NomeEleitor = "Marcos", VotoRealizado = false },
            new Eleitor { Cpf = "5", NomeEleitor = "Ana", VotoRealizado = false },
            new Eleitor { Cpf = "6", NomeEleitor = "Marcia", VotoRealizado = false },
            new Eleitor { Cpf = "7", NomeEleitor = "Marcio", VotoRealizado = false },
            new Eleitor { Cpf = "8", NomeEleitor = "Carla", VotoRealizado = false },
            new Eleitor { Cpf = "9", NomeEleitor = "Bruna", VotoRealizado = false },
            new Eleitor { Cpf = "10", NomeEleitor = "Mara", VotoRealizado = false }
        };

        while (opcao == 1 || opcao == 2 || contador < 10)
        {
            Console.WriteLine("DIGITE A OPÇÃO DESEJADA:");
            Console.WriteLine("1 - PARA VOTAR.");
            Console.WriteLine("2 - LISTAR VOTAÇÃO.");
            Console.WriteLine("------------------------");
            opcao = int.Parse(Console.ReadLine());
            if (opcao == 1)
            {
                Console.Write("DIGITE SEU CPF PARA REALIZAR O VOTO: ");
                var CPFEleitor = Console.ReadLine();
                foreach (var itemEleitores in listaEleitores)
                {
                    if (itemEleitores.Cpf.Equals(CPFEleitor) && itemEleitores.VotoRealizado == true)
                    {
                        Console.WriteLine("ELEITOR: " + itemEleitores.NomeEleitor);
                        y = 1;
                    }
                    if (itemEleitores.Cpf.Equals(CPFEleitor) && itemEleitores.VotoRealizado == false)
                    {
                        Console.WriteLine("ELEITOR: " + itemEleitores.NomeEleitor.ToUpper());
                        contador++;
                        itemEleitores.VotoRealizado = true;
                        Console.Write("DIGITE O NUMERO DO SEU CANDIDATO: ");
                        var numeroCandidato = Console.ReadLine();
                        if (!numeroCandidato.ToString().Equals(""))
                        {
                            foreach (var itemCandidados in listaCandidatos)
                            {
                                if (itemCandidados.NumeroPartido.ToString().Equals(numeroCandidato))
                                {
                                    Console.WriteLine("CANDIDATO: " + itemCandidados.NomeCandidato.ToUpper());
                                    Console.WriteLine("VOTAÇÃO CONCLUÍDA.");
                                    Console.WriteLine("------------------");
                                    itemCandidados.QuantidadeVotos = itemCandidados.QuantidadeVotos + 1;
                                    z = 1;
                                }
                            }
                            if (z == 0)
                            {
                                foreach (var itemCandidados in listaCandidatos)
                                {
                                    if (itemCandidados.NumeroPartido == 999)
                                    {
                                        itemCandidados.QuantidadeVotos = itemCandidados.QuantidadeVotos + 1;
                                    }
                                }
                            }
                            x = 1;
                        }
                        else
                        {
                            foreach (var itemCandidados in listaCandidatos)
                            {
                                if (itemCandidados.NumeroPartido == 99)
                                {
                                    itemCandidados.QuantidadeVotos = itemCandidados.QuantidadeVotos + 1;
                                }
                            }
                        }
                    }
                }
                if (x == 0 && y == 0)
                {
                    Console.WriteLine("CPF NÃO CADASTRADO");
                }
                if (y == 1)
                {
                    Console.WriteLine("ELEITOR JÁ REALIZOU SEU VOTO");
                }
                x = 0;
                y = 0;
                z = 0;
            }
            else if (opcao == 2)
            {
                foreach (var item in listaCandidatos)
                {
                    Console.WriteLine("Candidato {0} ({1}). Votos {2}.", item.NomeCandidato, item.NumeroPartido, item.QuantidadeVotos);
                }
                Console.WriteLine("------------------------");
            }
            else
            {
                Console.WriteLine("OPÇÃO INVÁLIDA. TENTE NOVAMENTE.");
            }
            opcao = 0;
        }
        if (contador == 10)
        {
            ExibeResultado(listaCandidatos);
        }
    }
}


text:
Q: Carl Friedrich Gauss and the 'useless' FFT in 1805 This is a history question, so you need to know something about math history to answer it.
There's a rumour that says that Carl Friedrich Gauss knew the FFT in 1805, but he thought it was useless, because the speedup wasn't very big for small numbers of N. And at that time there were no supercomputers, so you couldn't calculate large N's anyway.
But what's is the best evidence you can find that support this rumour?

A:
This is a history question, so you need to know something about math history to answer it.

Oh yeah? The first Google hit I get for "Gauss fast Fourier transform" is this paper, which says that Gauss wrote down something that looks like the FFT in an unpublished paper that appears in his collected works.

redpajama_set_name: RedPajamaStackExchange


text:
Q: сделать невидимым checkbox в listview как сделать невидимый checkbox в listview в первом item?
делаю это так, но ничего не происходит
 ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_multiple_choice, listFiles);
                m_listViewLocal.setAdapter(adapter);
                m_listViewLocal.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
                ((CheckBox)m_listViewLocal.getAdapter().getItem(0)).setVisibility(View.INVISIBLE);

A: Метод getItem() адаптера возвращает данные айтема , а не его View
Если видимостью надо управлять , то используйте следующий код:
mlistViewLocal.getChildAt(0).findViewById(R.id.checkbox).setVisibility(View.INVISIBLE);
то есть , мы получаем View из первой позиции списка , затем находим в нем наш чекбокс и ставим ему свойство INVISIBLE /
Следует заметить , что в стандартой разметке simple_list_item_multiple_choice.xml используется виджет CheckedTextView , для которого нельзя сделать невидимым только чекбокс без дополнительных ухищрений . Для того , чтобы получить этот элемент нужно искать его по android.R.id.text1 . Рекомендую использовать свою разметку с отдельным чекбоксом.
Если нужно просто отключить его в первом айтеме , то в методе getView() адаптера пишите (опять же для CheckedTextView это не подходит):
@Override
 public View getView(int position, View convertView, ViewGroup parent) {
 ...
  if (position==0) mCheckbox.setVisibility(View.INVISIBLE);
}

где mCheckbox - ссылка на чекбокс в адаптере
PS: согласно соглашений по обозначению полей классов в Java - имя поля класса начинается с m затем следует название поля с большой буквы , например - mCheckbox , никакого нижнего подчеркивания для разделения не надо - привыкайте сразу следовать этим принципам .


text:
Q: Alternative to scipy.cluster.hierarchy.cut_tree() I was doing an agglomerative hierarchical clustering experiment in Python 3 and I found scipy.cluster.hierarchy.cut_tree() is not returning the requested number of clusters for some input linkage matrices. So, by now I know there is a bug in the cut_tree() function (as described here).
However, I need to be able to get a flat clustering with an assignment of k different labels to my datapoints. Do you know the algorithm to get a flat clustering with k labels from an arbitrary input linkage matrix Z? My question boils down to: how can I compute what cut_tree() is computing from scratch with no bugs?
You can test your code with this dataset.
from scipy.cluster.hierarchy import linkage, is_valid_linkage
from scipy.spatial.distance import pdist

## Load dataset
X = np.load("dataset.npy")

## Hierarchical clustering
dists = pdist(X)
Z = linkage(dists, method='centroid', metric='euclidean')

print(is_valid_linkage(Z))

## Now let's say we want the flat cluster assignement with 10 clusters.
#  If cut_tree() was working we would do
from scipy.cluster.hierarchy import cut_tree
cut = cut_tree(Z, 10)

Sidenote: An alternative approach could maybe be using rpy2's cutree() as a substitute for scipy's cut_tree(), but I never used it. What do you think?

A: One way to obtain k flat clusters is to use scipy.cluster.hierarchy.fcluster with criterion='maxclust':
from scipy.cluster.hierarchy import fcluster
clust = fcluster(Z, k, criterion='maxclust')


text:
Q: React application - file upload works on localhost but not on nginx server Hope you can help.
the following code works when I run my application on local host, the file uploads correctly to the uploads folder in the root of the application.  However when I try uploading a file from my live website an error appears.
onst upload = multer({  // Set up multer module to move uploaded file an rename the file
  storage: multer.diskStorage({
    destination(req, file, cb) {
      cb(null, 'uploads/'); //Sets the destination for the new file
    },
    filename(req, file, cb) {
      cb(null, `${new Date().getTime()}_${file.originalname}`); // renames file with the date, time and its original name
    }
  }),
  limits: {
    fileSize: 1024 * 1024 * 5  // Sets the max file size
  },
  fileFilter: (req, file, cb) => {// Only allows image files uploaded
    if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg" || file.mimetype === 'image/gif' || file.mimetype ==='image/jfif' ) {
      cb(null, true);
    } else {
      cb(null, false);
      return cb( new Error('Only .png, .jpg and .jpeg format allowed!' ));

    }
  }
});

This is the error I get when it is live  Error: ENOENT: no such file or directory, open 'build/public/uploads/1619823055971_GettyImages-640318118-c83a508.jpg'
Is there a folder that I need to set up for uploads once I run the build for react.  Just now I just have an uploads folder at the root of the project.
Thanks for any advise

A: Looks like I wasn't restarting pm2 so it wasn't displaying any changes I was making to the express files.


text:
Q: Keep slider in usercontrol from scaling in WPF I have a user control which contains a media element to play a video, a slider used as a trackbar for the video and a text block that display the title of the video. These 3 controls are placed in a grid which in turn is placed inside a border.
I want the user to be able to translate, rotate and scale this control. The problem is that when the control scales it's content scales also and i want the slider control not to scale. Is it possible to somehow keep the slider control from scaling?
I should also mention that the manipulation of the control is handled by setting the control ismanipulationenabled to true and using the manipulation delta event.
EDIT:
This is how the xaml for the control looks like:
    <Grid Name="movieGrid" ShowGridLines="True">

        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
            <Border x:Name="moviePlayerBorder" Background="Black" BorderBrush="Blue" BorderThickness="2,2,2,2" CornerRadius="5,5,5,5"  Grid.RowSpan="2">

                <Grid Name="contentGrid">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="*"/>
                    </Grid.RowDefinitions>
                <WinControls:MediaElement x:Name="movieDisplay" ScrubbingEnabled="True" IsEnabled="True" Grid.RowSpan="2"
                                      LoadedBehavior="Manual" UnloadedBehavior="Manual"
                                      MediaOpened="movieDisplay_MediaOpened">
            </WinControls:MediaElement>

        <Image x:Name="btnPlay" Grid.Row="1" Height="60" Width="60" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="120,44,112,43" Grid.RowSpan="2">
                </Image>

                    <DockPanel LastChildFill="True" HorizontalAlignment="Stretch" Margin="6,2,6,0" Grid.Row="0">
                        <TextBlock Text="test" Margin="0,0,0,0" Name="txtBlockTitlu" HorizontalAlignment="Stretch"
                   FontSize="14" VerticalAlignment="Top" Foreground="White" TextWrapping="Wrap" Visibility="Collapsed"/>
                    </DockPanel>
                </Grid>
            </Border>

        <Slider x:Name="seekBar" VerticalAlignment="Bottom" HorizontalAlignment="Center" Width="299"
                         Thumb.DragStarted="seekBar_DragStarted" Thumb.DragCompleted="seekBar_DragCompleted" Thumb.DragDelta="seekBar_DragDelta" MaxHeight="33"

                         Minimum="0" Maximum="286" Height="33" Margin="0,0,0,0" Grid.Row="1"/>

</Grid>

A: if you want to build a fully scaleable user control you should define the layout only with the size values of a row column / row row eg. auto, x* or fixed values (if realy needed).
do not use fixed size values on elements.


text:
Q: JTable Is not Adding Vector on Click Event of Label I have a JTable And I have set Vector into the Header and Vector of Vector as Row content but it has to be add header onclick event. but when i tried to add String into the vector in click event its adding String into the Vector but that vector is not added to the Header so how can i make that i have Used firetablechanged event of model. but its not working some how.
here sample code.
Vector vector;
Vector<Vector> vector_content;
table = new javax.swing.JTable();

table.setModel(new DefaultTableModel(vector_content,vector){

    private static final long serialVersionUID = 1L;

    @Override
    public boolean isCellEditable(int row, int column) {
        return false;
    }
});

now i have click event like this where m adding data into the Header table of content.
            vector = new Vector();
            vector_content = new Vector<Vector>();
            vector.add("Employee Name");
            vector.add("Date");
            vector.add("Type");

data is added to the Vector i can print data but some how its not set to the table how can i make it?
example
here its working because i have added Table model using that col vector and row but when i use that in some button click then its not working method name is ![setDate();][1]
public class Jtable_Column extends javax.swing.JFrame {

    public Vector col;
    public Vector<Vector> row;

    /**
     * Creates new form Jtable_Column
     */
    public Jtable_Column() {

        setData();
        initComponents();
    }

    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        jTable1.setModel(new javax.swing.table.DefaultTableModel(row,col
        ));
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 1, Short.MAX_VALUE))
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

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

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Jtable_Column.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Jtable_Column.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Jtable_Column.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Jtable_Column.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Jtable_Column().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration

    private void setData() {
        col = new Vector();
        row = new Vector<Vector>();
        col.add("first");
        col.add("Sec");
        col.add("third");
        col.add("third");
    }
}

A: DefaultTableModel has a number of helpful methods, one of which is addColumn...
TableModel model = (DefaultTableModel)table.getModel();
model.addColumn("Employee Name");
model.addColumn("Date");
model.addColumn("Type");

If you want to remove the existing columns, you can use setColumnCount and pass it 0 first
Updated based on additional example
Basically, I did this and it worked fine...
jTable1.getTableHeader().addMouseListener(new MouseAdapter() {

    @Override
    public void mouseClicked(MouseEvent e) {
        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
        model.setColumnCount(0);
        model.addColumn("Banans");
        model.addColumn("Apples");
        model.addColumn("Pears");
        model.addColumn("Fluffy");
        model.addColumn("Unicorns");
    }

});

You should never modify the state of any data that the model might be relying from out side the model, as doing so could potentially place the UI into an unstable state

A: jTable1.getTableHeader().addMouseListener(new MouseAdapter() {

    @Override
    public void mouseClicked(MouseEvent e) {
        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
        model.setColumnCount(0);
        model.addColumn("Banans");
        model.addColumn("Apples");
        model.addColumn("Pears");
        model.addColumn("Fluffy");
        model.addColumn("Unicorns");
        model.reload();
    }

});


text:
Q: access assets images from a vue instance within an array of objects I want to create a list of images. These images get stored into the data object of the vue instance. So within my HTML code I loop through this array and pass in the image path to the image source.
Unfortunately the images have a wrong asset path. An example code would be
<template>

</template>

None of these paths seem to work. I also created a code example to show the problem:
https://codesandbox.io/s/ryqrx5wym4
How can I access the images correctly?


text:
Q: Where is the Balance Between Dependency Injection and Abstraction? Many Architects and Engineers recommend Dependency Injection and other Inversion of Control patterns as a way to improve the testability of your code. There's no denying that Dependency Injection makes code more testable, however, isn't it also a completing goal to Abstraction in general?
I feel conflicted! I wrote an example to illustrate this; it's not super-realistic and I wouldn't design it this way, but I needed a quick and simple example of a class structure with multiple dependencies. The first example is without Dependency Injection, and the second uses Injected Dependencies.
Non-DI Example
package com.stackoverflow.di;

public class EmployeeInventoryAnswerer()
{
    /* In reality, at least the store name and product name would be
     * passed in, but this example can't be 8 pages long or the point
     * may be lost.
     */
    public void myEntryPoint()
    {
        Store oaklandStore = new Store('Oakland, CA');
        StoreInventoryManager inventoryManager = new StoreInventoryManager(oaklandStore);
        Product fancyNewProduct = new Product('My Awesome Product');

        if (inventoryManager.isProductInStock(fancyNewProduct))
        {
            System.out.println("Product is in stock.");
        }
    }
}

public class StoreInventoryManager
{
    protected Store store;
    protected InventoryCatalog catalog;

    public StoreInventoryManager(Store store)
    {
        this.store = store;
        this.catalog = new InventoryCatalog();
    }

    public void addProduct(Product product, int quantity)
    {
        this.catalog.addProduct(this.store, product, quantity);
    }

    public boolean isProductInStock(Product product)
    {
        return this.catalog.isInStock(this.store, this.product);
    }
}

public class InventoryCatalog
{
    protected Database db;

    public InventoryCatalog()
    {
        this.db = new Database('productReadWrite');
    }

    public void addProduct(Store store, Product product, int initialQuantity)
    {
        this.db.query(
            'INSERT INTO store_inventory SET store_id = %d, product_id = %d, quantity = %d'
        ).format(
            store.id, product.id, initialQuantity
        );
    }

    public boolean isInStock(Store store, Product product)
    {
        QueryResult qr;

        qr = this.db.query(
            'SELECT quantity FROM store_inventory WHERE store_id = %d AND product_id = %d'
        ).format(
            store.id, product.id
        );

        if (qr.quantity.toInt() > 0)
        {
            return true;
        }

        return false;
    }
}

Dependency-Injected Example
package com.stackoverflow.di;

public class EmployeeInventoryAnswerer()
{
    public void myEntryPoint()
    {
        Database db = new Database('productReadWrite');
        InventoryCatalog catalog = new InventoryCatalog(db);

        Store oaklandStore = new Store('Oakland, CA');
        StoreInventoryManager inventoryManager = new StoreInventoryManager(oaklandStore, catalog);
        Product fancyNewProduct = new Product('My Awesome Product');

        if (inventoryManager.isProductInStock(fancyNewProduct))
        {
            System.out.println("Product is in stock.");
        }
    }
}

public class StoreInventoryManager
{
    protected Store store;
    protected InventoryCatalog catalog;

    public StoreInventoryManager(Store store, InventoryCatalog catalog)
    {
        this.store = store;
        this.catalog = catalog;
    }

    public void addProduct(Product product, int quantity)
    {
        this.catalog.addProduct(this.store, product, quantity);
    }

    public boolean isProductInStock(Product product)
    {
        return this.catalog.isInStock(this.store, this.product);
    }
}

public class InventoryCatalog
{
    protected Database db;

    public InventoryCatalog(Database db)
    {
        this.db = db;
    }

    public void addProduct(Store store, Product product, int initialQuantity)
    {
        this.db.query(
            'INSERT INTO store_inventory SET store_id = %d, product_id = %d, quantity = %d'
        ).format(
            store.id, product.id, initialQuantity
        );
    }

    public boolean isInStock(Store store, Product product)
    {
        QueryResult qr;

        qr = this.db.query(
            'SELECT quantity FROM store_inventory WHERE store_id = %d AND product_id = %d'
        ).format(
            store.id, product.id
        );

        if (qr.quantity.toInt() > 0)
        {
            return true;
        }

        return false;
    }
}

(Please feel to make my example better if you have any ideas! It might not be the best example.)
In my example, I feel that Abstraction has been completely violated by EmployeeInventoryAnswerer having knowledge of underlying implementation details of StoreInventoryManager.
Shouldn't EmployeeInventoryAnswererhave the perspective of, "Okay, I'll just grab a StoreInventoryManager, give it the name of the product the customer is looking for, and what store I want to check, and it will tell me if the product is in stock."? Shouldn't it not know a single thing about Databases or InventoryCatalogs, as from its perspective, that's an implementation detail it need not concern itself with?
So, where's the balance between testable code with injected dependencies, and information-hiding as a principal of abstraction? Even if the middle-classes are merely passing-through dependencies, the constructor signature alone reveals irrelevant details, right?
More realistically, let's say this a long-running background application processing data from a DBMS; at what "layer" of the call-graph is it appropriate to create and pass around a database connector, while still making your code testable without a running DBMS?
I'm very interested in learning about both OOP theory and practicality here, as well as clarifying what seems to be a paradox between DI and Information Hiding/Abstraction.

A: The Dependency Inversion Principle and, more specifically, Dependency Injection tackle the problem of how make application code loosely coupled. This means that in many cases you want to prevent the classes in your application from depending on other concrete types, in case those dependent types contain volatile behavior. A volatile dependency is a dependency that, among other things, communicates with out-of-process resources, is non-deterministic, or needs to be replaceable. Tightly coupling to volatile dependencies hinders testability, but also limits the maintainability and flexibility of your application.
But no matter what you do, and no matter how many abstractions you introduce, somewhere in your application you need to take a dependency on a concrete type. So you can't get rid of this coupling completely—but this shouldn't be a problem: An application that is 100% abstract is also 100% useless.
What this means is that you want to reduce the amount of coupling between classes and modules in your application, and the best way of doing that is to have a single place in the application that depends on all concrete types and will instantiate that for you. This is most beneficial because:

*

*You will only have one place in the application that knows about the composition of object graphs, instead of having this knowledge scattered throughout the application

*You will only have one place to change if you want to change implementations, or intercept/decorate instances to apply cross-cutting concerns.

This place where you wire everything up should be in your entry-point assembly. It should be the entry-point assembly, because this assembly already depends on all other assemblies anyway, making it already the most volatile part of your application.
According to the Stable-Dependencies Principle (2) dependencies should point in direction of stability, and since the part of the application where you compose your object graphs will be the most volatile part, nothing should depend on it. That's why this place where you compose your object graphs should be in your entry point assembly.
This entry point in the application where you compose your object graphs is commonly referred to as the Composition Root.
If you feel that EmployeeInventoryAnswerer should not know anything about databases and InventoryCatalogs, it might be the case that the EmployeeInventoryAnswerer is mixing infrastructural logic (to build up the object graphs) and application logic. Iin other words, it might be violating the Single Responsibility Principle. In that case your EmployeeInventoryAnswerer should not be the entry point. Instead you should have a different entry point and the EmployeeInventoryAnswerer should only get a StoreInventoryManager injected. Your new entry point can than build up the object graph starting with EmployeeInventoryAnswerer and call its AnswerInventoryQuestion method (or whatever you decide to call it).

where's the balance between testable code with injected dependencies,
and information-hiding as a principal of abstraction?

The constructor is an implementation detail. Only the Composition Root knows about concrete types and it is, therefore, the only one calling those constructors. When a consuming class depends on abstractions as its incoming/injected dependencies (e.g. by specifying its constructor arguments as abstractions), the consumer knows nothing about the implementation and that makes it easier to prevent leaking implementation details onto the consumer. If the abstraction itself would leak implementation details, on the other hand, it would violate the Dependency Inversion Principle. And if the consumer would decide to cast the dependency back to the implementation, it would in turn violate the Liskov Substitition Principle. Both violations should be prevented.
But even if you would have a consumer that depends on a concrete component, that component can still do information-hiding—it doesn't have to expose its own dependencies (or other values) through public properties. And the fact that this component has a constructor that takes in the component's dependencies, does not make it violate information-hiding, because it is impossible to retrieve the component's dependencies through its constructor (you can only insert dependencies through the constructor; not receive them). And you can't change the component's dependencies, because that component itself will be injected into the consumer, and you can't call a constructor on an already created instance.
As I see it, when talking about a "balance," you are providing a false choice. Instead, it's a matter of applying the SOLID principles correctly, because without applying the SOLID principles, you'll be in a bad place (from a maintainability perspective) anyway—and application of the SOLID principles undoubtedly leads to Dependency Injection.

at what "layer" of the call-graph is it appropriate to create and pass around a database connector

At the very least, the entry point knows about the database connection, because it is only the entry point that should read from the configuration file. Reading from the configuration file should be done up front and in one single place. This allows the application to fail fast if it is misconfigured and prevents you from having reads to the config file scattered throughout your application.
But whether the entry point should be responsible of creating the database connection, that can depend on a lot of factors. I usually have some sort of ConnectionFactory abstraction for this, but YMMV.
UPDATE

I don't want to pass around a Context or an AppConfig to everything and end up passing dependencies classes don't need

Passing dependencies a class itself doesn't need is typically not the best solution, and might indicate that you are violating the Dependency Inversion Principle and applying the Control Freak anti-pattern. Here's an example of such problem:
public class Service : ServiceAbs
{
    private IOtherService otherService;

    public Service(IDep1 dep1, IDep2 dep2, IDep3 dep3) {
        this.otherService = new OtherService(dep1, dep2, dep3);
    }
}

Here you see a class Service that takes in 3 dependencies, but it doesn't use them at all. It only forwards them to the OtherService's constructor which it creates. When OtherService is not local to Service (i.e. lives in a different module or layer), it means that Service violates the Dependency Inversion Principle—Service is now tightly coupled with OtherService. Instead, this is how Service should look like:
public class Service : IService
{
    private IOtherService otherService;

    public Service(IOtherService otherService) {
        this.otherService = otherService;
    }
}

Here Service only takes in what it really needs and doesn't depend on any concrete types.

but I also don't want to pass the same 4 things to several different classes

If you have a group of dependencies that are often all injected together into a consumer, changes are that you are violating the Single Responsibility Principle: the consumer might do too much—know too much.
There are several solutions for this, depending on the problem at hand. One thing that comes to mind is refactoring to Facade Services.
It might also be the case that those injected dependencies are cross-cutting concerns. It's often much better to apply cross-cutting concerns transparently, instead of injecting it into dozens or hundreds of consumers (which is a violation of the Open/Closed principle). You can use the Decorator design pattern, Chain-of-Responsibility design pattern, or dynamic interception for this.


text:
Q: How to split an array into multi arrays in java? I have an array
[2,5,7,9,1,3,4,6,8]

and I want a function
List<List<Integer>> split(List<Integer> list, int n)

which will separate the list intonarrays
for example:n=4,
result will be:
[2,1,8],
[5,3],
[7,4],
[9,6]

Note, the number was sampled averagely

A: Try this:
public static ArrayList<ArrayList<Integer>> split(ArrayList<Integer> list, int n){
    ArrayList<ArrayList<Integer>> resultArrays = new ArrayList<>();
    int pivot = 0;

    // Creates n ArrayLists.
    for(int i = 0 ; i < n ; i++){
        resultArrays.add(new ArrayList<>());
    }

    // Add element from list to new ArrayLists.
    while(pivot != list.size()){
        int p = pivot%n;
        resultArrays.get(p).add(list.get(pivot));
        pivot++;
    }

    return resultArrays;
}

The result is the one you exactly you want.
[2,1,8],
[5,3],
[7,4],
[9,6]

pivot points list's element.(from 0 to the size-1)
p points the ArrayList of ArrayList's index.(As big as n, here 4)
So,
num / *(pivot) / ArrayList[p]

1: [2,5,7,9,1,3,4,6,8] -> ArrayList[0]
    *
2: [2,5,7,9,1,3,4,6,8] -> ArrayList[1]
      *
3: [2,5,7,9,1,3,4,6,8] -> ArrayList[2]
        *
4: [2,5,7,9,1,3,4,6,8] -> ArrayList[3]
          *
5: [2,5,7,9,1,3,4,6,8] -> ArrayList[0]
            *
6: [2,5,7,9,1,3,4,6,8] -> ArrayList[1]
              *
7: [2,5,7,9,1,3,4,6,8] -> ArrayList[2]
                *
8: [2,5,7,9,1,3,4,6,8] -> ArrayList[3]
                  *
9: [2,5,7,9,1,3,4,6,8] -> ArrayList[0]
                    *

A: Given a number of bins.
List<List<Integer>> result = new ArrayList<>();
while(result.size()<bins){
    result.add(new ArrayList<>());
}

int counter = 0;
for(Integer i: input){
    result.get(counter++%bins).add(i);
}

A: In Guava library there is a List.Partition method.
List<List<Integer>> split(List<Integer> list, int n) {
 return Lists.partition(list, n);
}

A: List<List<Integer>> split(List<Integer> list, int n){
   List<List<Integer>> result = new ArrayList<>();
   //add n ArrayLists to the result list
   IntStream.range(0, n).forEach(k->result.add(new ArrayList<>()));
   //iterate over the input list and add one element to one of the inner list of the result array
   Iterator i = list.iterator();
   while(i.hasNext()){
        int count = 0;
        while(i.hasNext() && count < n){
            result.get(count).add((Integer) i.next());
            count++;
        }
   }
   return result;
}


text:
Q: Is it possible to dynamically create an array of constant size in C++? First of all, I want to reassure you all that I am asking this question out of curiosity. I mean, don't tell me that if I need this then my design has problems because I don't need this in real code. Hope I convinced you :) Now to the question:
For most types T we can write
T* p = new T;

now what if T is an array type?
int (*p)[3] =  new ???; //pointer to array of 3 = new ???

I tried this:
typedef int arr[3];
arr* p = new arr;

but this doesn't work.
Is there any valid syntax for this or it is impossible in C++. If it is impossible, then why? Thanks
Edit: i am guessing I wasn't clear enough. I want to be able to use it in this situation:
void f(int(&)[3]);
int (*p)[3] = new ???;
f(*p);

A: You could always use boost::array, which will be in C++0x.
Otherwise, any solution will be awkward at best: arrays are
broken in C, and C++ maintains compatilibity with C in this
respect.  Fred Overflow offered one solution; even easier (but
syntactically noisy) would be to wrap the array in a struct:
    struct A { int arr[3]; };
and allocate and manipulate this.

A: To get a pointer to an array from new, you have to dynamically allocate a two-dimensional array:
int (*p)[3] = new int[1][3];

A: The reason you can't do it is that new int[3] already allocates exactly what you want, an object of type int[3]. It's just that what the new-expression returns, is a pointer to its first element. 5.3.4/1:

If the entity is a non-array object,
  the new-expression returns a pointer
  to the object created. If it is an
  array, the new-expression returns a
  pointer to the initial element of the
  array.

Returning a pointer to the first element is what allows the 3 to be unknown until runtime, so I suppose that by knowing it in advance, you've tripped over flexibility that you aren't using.
I guess the ways around this are to reinterpret_cast back to the pointer type you want (not necessarily portable), or to allocate a struct containing an int[3] (and use a pointer to its data member).
[Edit: er, yeah, or FredOverflow's idea, which has neither disadvantage, but requires use of delete[] instead of delete.]
I guess the moral is, if you write templates that naively allocate some unknown type T with new, then the template won't work when someone passes an array type as T. You'll be assigning it to the wrong pointer type, and if you fix that (perhaps with auto), you'll be deleting it wrongly.
Edit in answer to j_kubik's question:
Here's one way to distinguish between array and non-array types. If you write a function like this, that returns an object that holds the pointer and is capable of correctly deleting it, then you have a generic new/delete for any type T.
#include <iostream>

template <typename T>
void make_thing_helper(T *) {
    std::cout << "plain version\n";
}

template <typename T, int N>
void make_thing_helper(T (*)[N]) {
    std::cout << "array version\n";
}

template <typename T>
void make_thing() {
    make_thing_helper((T*)0);
}

int main() {
    typedef int T1;
    typedef int T2[3];
    make_thing<T1>();
    make_thing<T2>();
}

A: You just do
int *p = new unsigned int [3]

You can then use *p as a pointer or an array i.e. *(p+1) or p[1]


text:
Q: what is the difference between using int and  I recently started learning about stacks in C++. While looking at an example, I noticed they used the following:
       void showstack(stack <int> s).

I was wondering what the <> did, and how is it different from just using int?

A: What you are looking at are template parameters.
Basically, stack is a template, declared (in a simplified manner) like this:
template <class T>
class stack { /*...*/ };

Thus, stack is not a class, you cannot talk about a stack type. It will only become a type once the template parameter is specified; for example: stack<int> is a stack of integers in this case.

A: stack just like many other containers is templated. You need to specify the type of elements you are going to store in the container.
template<
    class T, // this what you specified in your code
    class Container = std::deque<T>
> class stack;

There is no stack compiled in your code until you use one with a type, like you did.

A: It says that showstack's parameter is a stack of ints.

A: The <> are used for templates, which tell a class what kind of data to expect. You could replace int with string and you would have a stack of strings that way.
For more info


text:
Q: how to reduce mysql slow query time for big database I have almost 5 gb database on my mysql 5.5 myisam. My os architecture is fedora 64 bit. Now I if I do single query from  the table which holding large data query is being slow for more than 30 sec. Can any one please tell me how can I reduce the slow query? I have 2 gb memory and 6 gb swap.
[updated]
slow log out put is here
# Query_time: 19.367274  Lock_time: 0.000109 Rows_sent: 54  Rows_examined: 4263723
SET timestamp=1310052008;
SELECT timestamp FROM nse_data WHERE symbol='NIFTY'AND series='IN' AND timestamp BETWEEN '2011-04-07' AND '2011-07-07' ORDER BY timestamp;

Thanks

A: Every query is very different, but at first glance it seems that this particular query can run fastest with this index:
ALTER TABLE `nse_data` ADD INDEX `index_nse_data` (`timestamp` ASC, `symbol` ASC, `series` ASC);

Of course, it's just a guess, because I don't know anything about your data :)

A: The first thing to try is to add indexes for the columns you regularly search/order on.


text:
Q: OpenGraph Set a custom PLAY action Hi i've with success submitted my PLAY action on openGraph,
Just a question :
To submit sample i use that :
$facebook = new Facebook($config);
$user_id = $facebook->getUser();

if($user_id) {

 try {
    $ret_obj = $facebook->api('/me/mupizfb:play', 'POST',
        array(
            'song' => "http://www.mupiz.com/profil.php?id1=1"
        ));
    echo '
Post ID: ' . $ret_obj['id'] . '
';

  } catch(FacebookApiException $e) {
        error_log($e->getType());
        error_log($e->getMessage());

  }
} else echo"not connected with FB";

I get no errors.. But nothing was posted on facebook any ideas?
Thanks!


text:
Q: How to use existing CA and Server key with EasyRsa? i have an existing ca key and cert. how do i tell easyrsa to use that to generate server and client certs, instead of generating its own? All the docs seem to mention to do an init-pki to initialize a fresh PKI for it.

A: If you read the docs here you should see the files that are created by Easy RSA.  If you overwrite the private key and ca certificate, you should be able to replace the internally generated ones with your own.
The files are pki/ca.crt for the CA certificate and pki/private/ca.key for the private key.


text:
Q: The probability distribution of the sum of independent uniform random variables in $\left[0,1\right]$ Let me preface this by saying that this is not a question about the Irwin-Hall distribution , at least directly. Rather, in the proof of Lemma 1 in the appendix of this paper , the author shows that the joint density of $S_n:= \sum_{I=1}^{n}X_i$ where $X_i\stackrel{\rm i.i.d}{\sim}U\left[0,1\right]$ is given by $$f_n(s) = \frac{s^{n-1}}{(n-1)!}P\left(\max_{1\leq i\leq n} L_n \leq s^{-1}\right)$$ where $\{L_i\}_{i=1}^n$ are the lengths of consecutive sub-intervals of $\left[0,1\right]$ cut out by $(n-1)$ uniform random numbers in the interval. I know that the the joint density of the first $(n-1)$ such lengths is $(n-1)!$ on its support. However, I failed to follow the argument of the author to its conclusion.
Specifically, he argues that the joint density of $S_n,X_1,\ldots,X_{n-1}$ is the same as the joint density of the $n$ independent uniform which is 1 on its support. Then, applying a transformation, the joint density of $S_n,\frac{X_1}{S_n},\ldots,\frac{X_{n-1}}{S_n}$ can be found to be $s^{n-1}$. I cannot follow the argument from this point on, where he presumably integrates out the other variables to derive $f(s)$. If anyone could clarify this step for me, it'd be great.

A: Ok so this answer basically avoids what Pittel does (maybe that is easier but it's not obvious to me), and follows Feller's approach.
We have $X_1$, $\cdots$, $X_n$ independent uniform random variables on $[0,a]$. Let $S_n$ be their sum. We want the density of $S_n$, let's call that $f_{n,a}$. Obviously $f_{1,a}$ is $\frac{1}{a}$ on $[0,a]$ and $0$ on the rest of the positive real line. And the rest of the $f_{n,a}$ obey the convolution recurrence, so for $n \geq 2$,
$$f_{n,a}(x) = \frac{1}{a} \int_0^a f_{n-1,a}(x-y) \, dy.$$
Let's set this aside and turn to the other item Pittel uses. Say we partition $[0,t]$ into n intervals using independent uniform random points $Y_1, \cdots, Y_{n-1}$. We want to track the probability that none of the subintervals are larger than $a$, i.e. $P(\max_{1 \leq i \leq n-1} \left(Y_{i+1} - Y_i\right) \leq a)$. Call this thing $\varphi_{n,a}(t)$. By this definition, $\varphi_{1,a}(t)$ is clearly $1$ for $0 \leq t \leq a$, and $0$ on the rest of the positive real line.
What about for larger $n$? We have $n-1$ choices for a random point $Y_i$. Once we choose, call its position $x$. Then the probability that the $Y_i$ we chose is the leftmost one is $\left(\frac{t-x}{t}\right)^{n-2}$.
Also, this leftmost point must be less than $a$.  Now the remaining variables are distributed with the same conditions over $[x,t]$, so the conditional probability they satisfy the requisite conditions is $\varphi_{n-1,a}(t-x)$. Integrate this over the possible $x$ and get
$$\varphi_{n,a}(t) = (n-1) \int_0^a \varphi_{n-1,a}(t-x) \left(\frac{t-x}{t}\right)^{n-2} \, \frac{1}{t}dx.$$
Now set
$$u_{n,a}(t) = \frac{\varphi_{n,a}(t)t^{n-1}}{a^{n-1}(n-1)!},$$
and observe for $n \geq 2$,
$$ u_{n,a}(t) = \frac{1}{a} \int_0^a u_{n-1,a}(t-x) \, dx.$$
This matches our recurrence above and the initial condition matches as well when $a=1$. So $u_{n,1}$ is our desired density function. As the problem requires, we have $a=1$, then put $t = s$ to get what Pittel has:
$$ u_{n,1}(s) = \frac{s^{n-1}}{(n-1)!} \varphi_{n,1}(s),$$
where the $\varphi$ term is what you want: the probability that no sub-interval exceeds length $1$ when $[0,s]$ is cut up into $n$ sub-intervals, or after rescaling, the probability that no sub-interval exceeds length $\frac{1}{s}$ when $[0,1]$ is cut up into $n$ sub-intervals.


text:
Q: Filter based on counts django annotate query I need to filter records based on total counts of records for vehicle_owner_organization_id (non distinct) before the first annotate, i.e if total counts in the collection for vehicle_owner_organization_id are greater than 1, then only go ahead with the following query getting monthly distinct counts. Is there an easy way to do this. Or do I need to run another query to filter.
values = ['month', 'city_code']
transacting_users = list(FieldOpsBooking.objects.using(
    'analytics').filter(**filter_query).annotate(
    month=TruncMonth('pick_up_at')).values(*values).annotate(
    count=Count(
        'vehicle_owner_organization_id', distinct=True)).values(*values,
                                                                'count'))

A: You can filter with:
values = ['city_code']

FieldOpsBooking.objects.using('analytics').filter(**filter_query).values(
    *values, month=TruncMonth('pick_up_at')
).alias(
    ccount=Count('vehicle_owner_organization_id')
).annotate(
    count=Count('vehicle_owner_organization_id', distinct=True)
).order_by(*values, 'month').filter(
    ccount__gt=1
)


text:
Q: Extracting and Merge in R Below is a list that I have:
V1        V2
Zealous   Jane
Pretty    May
Smart     Kate
Place     China

Below is the data that I have:
Name     Source
JJ       Kate has a brother
Kl       May lives in China.

I would like to make use the list and data I have to extract the data that matches using R.
Below is the output I would like to get:
Name    Source                Words   Comments
JJ      Kate has a brother    Kate    Smart
Kl      May lives in China    May     Pretty
Kl      May lives in China    China   Place

Thank you.

A: We can use str_extract to extract the words from df2 and the match the 'nm1' with 'V2' column of 'df1' to index the 'V1' column of 'df1'
library(stringr)
nm1 <- str_extract(df2$Source, paste(df1$V2, collapse='|'))
df2$Words <- df1$V1[match(nm1, df1$V2)]
df2
#  Name              Source  Words
#1   JJ  Kate has a brother  Smart
#2   Kl May lives in China. Pretty

Update
For the updated dataset ('df1'), we can use str_extract_all to extract multiple words in a list, stack it to convert to data.frame, merge with df2 and match the 'values' column with 'V2' from 'df1' to create the 'Comments' column.
 nm1 <- str_extract_all(df2$Source, paste(df1$V2, collapse='|'))
 d1 <- stack(setNames(nm1, df2$Name))
 df2N <- merge(df2, d1, by.x='Name', by.y='ind')
 df2N$Comments <- df1$V1[match(df2N$values, df1$V2)]
 colnames(df2N)[3] <- 'Words'
 df2N
 #  Name              Source Words Comments
 #1   JJ  Kate has a brother  Kate    Smart
 #2   Kl May lives in China.   May   Pretty
 #3   Kl May lives in China. China    Place

data
df1 <- structure(list(V1 = c("Zealous", "Pretty", "Smart"),
V2 = c("Jane",
"May", "Kate")), .Names = c("V1", "V2"), class = "data.frame",
row.names = c(NA, -3L))

df2 <- structure(list(Name = c("JJ", "Kl"),
Source = c("Kate has a brother",
"May lives in China.")), .Names = c("Name", "Source"),
class = "data.frame", row.names = c(NA, -2L))

Updated data
df1 <- structure(list(V1 = c("Zealous", "Pretty", "Smart", "Place"),
V2 = c("Jane", "May", "Kate", "China")), .Names = c("V1",
"V2"), class = "data.frame", row.names = c(NA, -4L))


text:
Q: Network diagram meets Sankey chart Is there a way, in Highcharts, to create a network diagram where the connections are of width proportional to a data series (like a Sankey diagram?)
The application is a "traffic flow" visualisation (but between logical points, not physical ones, so overlaid onto a network diagram rather than a map.)

A: This is not supported by default, but you can easily get the wanted result by a small modification of getLinkAttribues method:
H.seriesTypes.networkgraph.prototype.pointClass.prototype.getLinkAttribues = function() {
    var linkOptions = this.series.options.link,
        maxValue,
        pointOptions = this.options;

    if (!this.linkWidth) {
        this.series.points.forEach(function(p) {
            maxValue = maxValue ?
                Math.max(maxValue, p.options.value) :
                p.options.value;
        });

        this.series.points.forEach(function(p) {
            p.linkWidth = p.options.value * 10 / maxValue;
        });
    }

    return {
        'stroke-width': this.linkWidth || 1,
        stroke: pointOptions.color || linkOptions.color,
        dashstyle: pointOptions.dashStyle || linkOptions.dashStyle
    };
}

Live demo: https://jsfiddle.net/BlackLabel/13zt8qds/
Docs: https://www.highcharts.com/docs/extending-highcharts


text:
Q: Is serverless in combination with event sourcing possible? I've been wanting to implement a mobile app using a complete serverless architecture for some time now and finally started looking into the details. So far, I've discovered that AWS offers most of the services that would be required for such a setup (API Gateway, Cognito, Lambda, DynamoDB, SQS, etc.), but I've yet to solve one (possibly theoretical) issue; event sourcing.
Since (historical) data is becoming more and more valuable these days, it's very important (in my humble opinion) to store historical data about your users. Current event sourcing offerings such as Akka Persistence achieve this goal by only persisting the events to a database and keeping the current state in memory (and saving snapshots to a database, etc.).
My problem with this, is that I don't have the ability to store such a state in memory since my Lambda functions terminate after their single purpose has been fulfilled. What my question boils down to, is there a framework currently out there that would support event sourcing (on Java) that saves the current state in something like ElastiCache (Redis). Since I have a lot of experience with Akka, is this something Persistence can already do? Is it worth chasing event sourcing in combination with a serverless backend (at this time) or is it simply not yet the right time this?
I haven't been able to find much in the Akka Persistence docs as of yet about this (possible non) issue. Please give me suggestions as to what I might have missed in my mission to a serverless universe; I'm still learning, as we all are.

A: This will be primarily opinion-based, so not the best fit for Stack Overflow, but I'll try to stay as factual as possible.
akka-persistence does not lend itself well to serverless deployment strategy, for the following reason. It relies on the strong assumption that at any one time there is only one PersistentActor for a given id. In a distributed environment enforcing this implies inter-node coordination, typically using akka-cluster-sharding. This doesn't yield itself to being deployed in a serverless environment that is meant to run simple functions.
In general, event sourcing implies rebuilding state from events stored in the journal (or latest snapshot + the events that followed) and doing that on top of a stateless environment means a lot of inefficiency for every single execution of the function, since there can be no local cache. Adding a distributed cache on top of event sourcing can mitigate that somewhat. However, you're still left with the challenge of coordination to prevent race-conditions between multiple instances of the function. These factors work against the operational simplicity that serverless is meant to provide.

A: Yes, you can do event-sourcing in Serverless.
One approach using AWS is to use DynamoDB as your Event Store. You can then use DynamoDB Streams with Lambda triggers to materialize them into your State Store (which can be any other DB).

A: You can do it with DynamoDB Streams, but only an Event Store is not enough. The code that generates the next event should be serialised, i.e. only one code instance at the time is allowed produce an event for a particular aggregate instance. Otherwise the order of the events may not be certain.
With event sourcing commands are sent to aggregates. When a command has an effect, i.e. modifies the aggregate, an event is generated, added to the log and usually published. Very often producing an event for a command requires the current state of the aggregate. This is why such code should not run in parallel for the same aggregate instance.
A solution is to have a "Command Store", which is a DynamoDB table that stores the last command for each aggregate instance. Thus, the associated stream consists of updates to that item. The Lambda trigger for this stream reconstructs the state of the aggregate instance using the Event Store and generates the new event. The event is then saved in the Event Store. The stream of the event store takes care of the publication of the event.
In order to speed up the reconstruction of the state of an aggregate, a snapshot table can be used. Every 100 events, for example, the complete aggregate can be updated in it. Reconstruction then consists of fetching the snapshot and then fetching only the events with a sequence number above the one in the snapshot.
Numbering the events and the associated aggregate copies, which may exist in various Read Stores, has the advantage of making idempotence easy. This way replay of events is possible.

A: You can do event-sourcing using akka-persistence in a Lambda, if you're fine with (some configurable) eventual consistency and willing to also apply CQRS.
How does such a setup look like?
You will have (1 or more) lambda functions that create n lambda instances (lets call them QUERY-Lambda; where n is basically unlimited or limited by the concurrency limit available in your account) that are able to handle your read-sides (handling queries by reading the journal/snapshot store and then answering), and max. 1 instance of the lambda per aggregate that is handling write-operations (ensure this using the concurrency parameter in the lambda's configuration) (lets call them COMMAND-Lambda). This is important to make sure that the journal does not get corrupt by having more than one actor writing to it.
Depending on your consistency guarantees, make sure to stop the actors in the QUERY-Lambdas either right after the query is handled or set the receive timeout to a value that is fine with your consistency guarantee, knowing that multiple actors could give you a different state.
If you have CRUD operations, make sure that Read operations that show the user the current state before applying a change (e.g. showing the current values of a customer object in a form before updating it) are also handled by the WRITE-Lambda so you are sure that the state you are changing is the last state available.
You don't have to create multiple jar-files for this, you can simply deploy the same jar file as multiple lambda functions. You need to make sure in your API Gateway, that the requests changing state are routed to the WRITE-Lambda(s) and those where consistency is not so important are routed to the READ-Lambda(s).
Also make sure that you're not creating snapshots while replaying the journal, but only when doing command processing (because the READ-Lambdas are also replaying the journal and thereby could corrupt your state if they would create snapshots)
For best performance, create a snapshot after every command that changed state or at least before shutting down the actor, that way the next invocations will have to do a minimal amount of reads. AFAIK the Lambdas in Java also stay active for a reasonable time, so the cold-restarts should not be that much of a problem. If they are for u, create some cron that every ~5-10 minutes calls into the lambda to keep it alive. Alternatively you can use https://doc.akka.io/docs/alpakka/current/awslambda.html to simply send a request to yourself every x minutes.. You can use Source.tick(3 minutes) and then just invoke your WRITE-Lambda function like its shown in the Alpakka documentation.
Also make sure that operations where you'd need to talk with two aggregates (Saga / Coordinator) are handled by the same WRITE-Lambda. This might become a bottleneck, but of course you still can apply some kind of sharding through routing in the API Gateway. Its just more effort than if you would have a normal Akka Cluster.
If something is unclear, please leave a comment and I'll try to answer.


text:
Q: How to read or download a file in React Native? I have a React-Native project and I need to read the data from a file which is on Internet, so, I need to read the data from the URL or download the file, read it and then delete the file.
Can anyone help me?
Thank you.

A: For native filesystem managing (creation of local files, deletion etc) you could use this module, https://github.com/johanneslumpe/react-native-fs
For downloading/uploading you could either use the react native fetch
https://facebook.github.io/react-native/docs/network.html
or the above fs module.

A: React Native provides the Fetch API for your networking needs. Fetch will seem familiar if you have used XMLHttpRequest or other networking APIs before. You may refer to MDN's guide on Using Fetch for additional information.
https://facebook.github.io/react-native/docs/network.html


text:
Q: How can I mock an attribute of a class using the mock decorator? #these classes live inside exchanges/impl/tse/mixins.py

class PacketContext:
    capture_tstamp = None
    def __init__(self, capture_tstamp=None):
        self.capture_tstamp = capture_tstamp

class SubParserMixin():
    def __init__(self):
        self.context = PacketContext()

    def on_packet(self, packet):
        self.context.capture_tstamp = packet.capture_timestamp
        self.parse_er_data(packet.payload)

#this mock test lives in another python file
from exchanges.impl.tse.mixins import PacketContext

@patch.object(PacketContext, 'capture_tstamp', 1655417400314635000)
def test_receive_timestamp(self):
    """
    test receive_timestamp is passed down correctly from PacketContext to on_packet()
    """
    assert self.context.capture_tstamp == 1655417400314635000

I am trying to mock the self.capture_tstamp attribute in the PacketContext() class.
But in the above, I am getting an error that says
    AssertionError: assert None == 1655417400314635000
E        +  where None = <exchanges.impl.tse.mixins.PacketContext object at 0x7fb324ac04c0>.capture_tstamp
E        +    where <exchanges.impl.tse.mixins.PacketContext object at 0x7fb324ac04c0> = <tests.unit.exchanges.tse.test_quote_write.TestTSE testMethod=test_receive_timestamp>.context

It seems very strange that the program is not recognising PacketContext().

A: You can make use of the patch.object decorator as below
class PacketContext:
    capture_tstamp = None
    def __init__(self, capture_tstamp=None):
        self.capture_tstamp = capture_tstamp

<import_PacketContext_here>

@patch.object(PacketContext, 'capture_tstamp', 1655417400314635000)
def test_receive_timestamp():
    test_instance = PacketContext()
    assert test_instance.capture_tstamp == 1655417400314635000


text:
Q: Is "which if you listen to will tell you" an acceptable construction?
God has equipped you with an internal compass which if you listen to will tell you if you are living to your full potential.Source: ect.org forum, topic: Does severe retrograde amnesia create a new soul?

A: It is formally grammatical; the which is represented in both the the condition and the consequence clause. This might be a tad clearer if the condition clause were set off in commas, but that is not necessary with so short a clause and would not in fact be represented by comma-intonation in speech
...       if you listen to it it will tell you if ...
       ↓  ←  ←  ←  ←  ←  ← ↵ ↵
       ↓
... which if you listen to       will tell you if ...

It is, however, an absurdly mixed metaphor: how does one "listen to" a "compass"?

A: No, it's not grammatical.

which if listened to will tell you

Would be correct.


text:
Q: wp_schedule_event is executing but the function related to the hook is not running I have an OOP plugin, The purpose of the plugin is to catch scheduled posts, save them in cron, then 2 minutes after they are published, to run a custom function on them.
This is the stripped-down class with the relevant parts to the question:
class fb_linter {

    function __construct() {

        add_action('init', array($this,'init') );
        add_action('admin_init', array($this,'admin_init') );
        add_action('admin_menu', array($this,'admin_menu') );

        add_action( 'future_post',  array(&$this, 'on_post_scheduled'), 10, 2 );
        add_action( 'activate_cron', array(&$this,'post_notification'), 10, 1);

        }

    function on_post_scheduled( $ID, $post ) {
        $title = $post->post_title;
        if ($post->post_status == 'future') {
            wp_schedule_single_event(get_post_time('U', true , $post->ID) + 120, 'activate_cron', array($post->ID));
        }
    }

    function post_notification($post_id) {
        $title = get_the_title($post_id);
        $permalink = get_permalink($post_id);
        $headers = 'From: My Name <myname@example.com>' . "\r\n";
        wp_mail('wp@gmail.com', 'Post ' . $title', $headers);
    }
}

I'm able to get the action in the cron, means I can see activate_cron inside Crontrol & Crony menus, but the function post_notification never executing.
When I transfer the add_action call of activate_cron and the function post_notifications to functions.php, everything works correctly.
I kept digging for the last 3 days for a solution, but I couldn't get it to work.
Any advices?

A: So your constructor is probably not being executed before the cron event is being run. If your instantiating the fb_linter class too late then your call to add_action won't happen in time. Try using the singleton design pattern for your class and then instantiate it right after you declare it and it should work just fine.
something like
class fb_linter {
    public static function get_instance(){
        static $instance;
        if( ! isset( $instance ) )
            $instance = new self();

        return $instance;
    }

    ...
}
fb_linter::get_instance();


text:
Q: Adding "mscorlib.dll" causing errors I added "mscorlib.dll" reference to VS2017 project to fix an issue.
I added the following line to my .csproj file to refer mscorlib
    <ItemGroup>
  <Reference Include="mscorlib">
    <!-- Replace with whatever your path to mscorlib is -->
    <HintPath>C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\mscorlib.dll</HintPath>
    <Private>True</Private>
  </Reference>
</ItemGroup>

After I add that reference I started getting errors that I'm missing predefined types like in the below, can some one let me know what is the cause for this.
 enter image description here


text:
Q: Is it possible to explicitly to refer to indexes by their name in pandas data frame? In pandas DataFrames allow a combination of columns to build an index (if every row has a unique combination of values from these columns). One of the benefits of doing that is simplification of the syntax, rather than:
my_data_frame[(my_data_frame['column_name_1']==0) & (my_data_frame['column_name_2']==1)]

We can use:
my_data_frame[(0,1)]

Here is an example of how I use several columns to build an index:
import pandas as pd

ls = [{'col1':10, 'col2':0, 'col3':0, 'col4':100}, {'col1':20, 'col2':0, 'col3':1, 'col4':200}, {'col1':30, 'col2':1, 'col3':0, 'col4':300}, {'col1':40, 'col2':1, 'col3':1, 'col4':400}]
df = pd.DataFrame(ls).set_index(['col2','col3'])

df.ix[(0,0)]['col1']  # returns 10
df.ix[('col3'=1, 'col2'=0)] # <----- This does not work. (SyntaxError: invalid syntax)

Is it possible to do something like given in the last line of the above code? Of course I can do:
df[(1, 2, 0, 'aaa', 10)]

But for that I always need to remember the order of the index. It would be nicer if I can do something like:
df[(age=10, scale=2, grade=0, name='aaa', size=1)]

A: You could write your own helper:
In [11]: df1
Out[11]:
           col1  col4
col2 col3
0    0       10   100
     1       20   200
1    0       30   300
     1       40   400

In [12]: d = {'col3': 1, 'col2': 0}

If you knew for certain you were passing all of the names, you could just put them in the correct order:
In [13]: t = tuple(map(d.get, df1.index.names))

In [14]: t
Out[14]: (0, 1)

In [15]: df1.loc[t]
Out[15]:
col1     20
col4    200
Name: (0, 1), dtype: int64

If you didn't, and wanted something a little more robust, you could do something a little trickier as follows (there's surely a more efficient way to do it though, without reducing). But here's one idea:
def reduce_kv(df, kv):
    try:
        return df.xs(kv[1], level=kv[0])
    except (AttributeError,):
        if df.index.name == kv[0]:
            return df.loc[kv[1]]
        else:
            raise AttributeError("Level %s not found" % kv[0])

In [17]: reduce(reduce_kv, d.items(), df1)
Out[17]:
col1     20
col4    200
Name: 1, dtype: int64

Note: the name probably also needs changing...


text:
Q: Why aren't Java references not null by default? I've seen this question for other languages (C and C++). But I still don't get why it is like this in Java as well. Where could it be useful that a reference is declared but not set to null?

A: Thing ref;
if (someCondition)
   ref = oneThing;
else
   ref = anotherThing;

There is no benefit in initializing 'ref' to null in the above code, at least not as long as neither assignment can throw an exception.
It's not "useful" that it is uninitialized, it's merely that there's no point in initializing it.
I wish it were not like that - I'd prefer initialization of local variables to work like member variables - but that is how it is.
I assume it's for efficiency reasons. If you don't have to initialize local variables, allocation is pretty much just an adjustment of the stack pointer.


text:
Q: plot.new has not been called yet when making tiff-file I am trying to add text (the nonlinearity p-value) to a plot of a restricted cubic spline regression model. When I try this in R studio it works fine, however the moment I try to add code to save it as a .tiff file, I get the following:

Error in strwidth(legend, units = "user", cex = cex, font = text.font) :
    plot.new has not been called yet

This is my code (for a restricted cubic spline regression model for the association between determinant labtsh and endpoint ecard with 3 knots):
spline <- cph(Surv(ecard_f,ecard_n)~rcs(labtsh,3)+age+gender+ckdepi+smoking, data=smart)

tiff(file ="H:/documents/test.tiff", width = 1000, height =1000, units = "px", res = 145)

plot(Predict(spline,labtsh,fun=exp), pch = 20, las = 1,
    conf.int=T,
    main="Relationship TSH and myocardial infarction",
    xlab="TSH (mIU/L)",
    ylab="Hazard Ratio")

my.p <- anova(spline)[2,3]  ##this is the value I want to add in the plot

rp = vector('expression',2)
rp[1] = substitute(expression(Non-linearity))[2]
rp[2] = substitute(expression(italic(p)-value == MYVALUE),
               list(MYVALUE = format(my.p, digits = 3)))[2]
legend('topleft', legend = rp, bty = 'n')

dev.off()

Like I said, if I take away the call to make it a .tiff-file and the dev.off() line, the code works fine.
I have searched multiple answers for similar questions here on stackoverflow, but the answers don't seem to help me.


text:
Q: Calculate the Discount Fitness Price (30%, 20% and 15% Off) User - Defined Functions
The cost to become a member of a fitness center is as follows:

*

*The senior citizens discount is 30%.

*If the membership is bought and paid for 12 or more months, the discount is 15%

*If more than five personal training sessions are bought and paid for, the discount on each session is 20%.

Write a menu-driven program that determines the cost of a new membership. Your program must contain a function that displays the general information about the fitness center and its charges, a function to get all of the necessary information to determine the membership cost, and a function to determine the membership cost. Use appropriate parameters to pass information in and out of a function. (Do not use any global variables.)
My codes:
#include <iostream>
#include <iomanip>

using namespace std;

// program constants

void setPrices(double&, double&);
void getInfo(bool&, bool&, bool&, int&, int&);
double membershipCost(double, int, double, int, bool, bool, bool);

void displayCenterInfo();

int main()
{
    bool seniorCitizen;
    bool boughtFiveOrMoreSessions;
    bool paidTwelveOrMoreMonths;

    int numberOfMembershipMonths;
    int numberOfPersonalTrainingSessions;
    double regularMembershipChargesPerMonth;
    double costOfOnePersonalTrainingSession;

    double memberCost;

    cout << fixed << showpoint << setprecision(2);

    displayCenterInfo();

    cout << endl;

    setPrices(regularMembershipChargesPerMonth, costOfOnePersonalTrainingSession);

    getInfo(seniorCitizen, boughtFiveOrMoreSessions, paidTwelveOrMoreMonths, numberOfMembershipMonths, numberOfPersonalTrainingSessions);

    // cal getInfo
    memberCost = membershipCost(regularMembershipChargesPerMonth, numberOfMembershipMonths, costOfOnePersonalTrainingSession,
        numberOfPersonalTrainingSessions, seniorCitizen, boughtFiveOrMoreSessions, paidTwelveOrMoreMonths);

    cout << "$" << memberCost;

    system("pause");
    return 0;
}

void displayCenterInfo()
{
    cout << "Welcome to Stay Healty and Fit center." << endl;
    cout << "This program determines the cost of a new membership." << endl;
    cout << "If you are a senior citizen, then the discount is 30% of "
        << "of the regular membership price." << endl;
    cout << "If you buy membership for twelve months and pay today, the "
        << "discount is 15%." << endl;
    cout << "If you buy and pay for 6 or more personal training session today, "
        << "the discount on each session is 20%." << endl;
}

void setPrices(double& regMemPrice, double& personalTrSesCost)
{

    cout << "Please enter the cost of regular Membership per month: " << endl;
    cin >> regMemPrice;

    cout << "Please enter the cost of one personal traning session: " << endl;
    cin >> personalTrSesCost;

}

void getInfo(bool& senCitizen, bool& bFiveOrMoreSess, bool& paidTwMnth,
    int& nOfMonths, int& nOfPersonalTrSess)
{
    //Senior Verification
    char userInputSenior;
    cout << "Are you Senior? Please enter 'Y' or 'N': ";
    cin >> userInputSenior;

    if (userInputSenior == 'y' && userInputSenior == 'Y')
    {
        senCitizen = true;
    }
    else
        senCitizen = false;

    cout << endl;

    //Number of personal training session.
    cout << "Enter the number of personal training sessions bought: ";
    cin >> nOfPersonalTrSess;

    if (nOfPersonalTrSess >= 5)
    {
        bFiveOrMoreSess = true;
    }
    else
        bFiveOrMoreSess = false;

    cout << endl;

    //Number of months
    cout << "Enter the number of months you are paying for: ";
    cin >> nOfMonths;

    if (nOfMonths >= 12)
    {
        paidTwMnth = true;
    }
    else
        paidTwMnth = false;

}

double membershipCost(double regMemPricePerMth, int nOfMonths,
    double personalTrSesCost, int nOfPersonalTrSess,
    bool senCitizen, bool bFiveOrMoreSess, bool paidTwMnth)
{
    double finalMembershipCost, finalSessionCost;

    //Session Discount
    if (bFiveOrMoreSess)
    {
        personalTrSesCost = personalTrSesCost * 0.8;
    }
    else
    {
        personalTrSesCost = personalTrSesCost;
    }

    //Month Discount
    if (paidTwMnth)
    {
        regMemPricePerMth = regMemPricePerMth * 0.85;
    }
    else
    {
        regMemPricePerMth = regMemPricePerMth;
    }

    finalMembershipCost = regMemPricePerMth * nOfMonths;
    finalSessionCost = personalTrSesCost * nOfPersonalTrSess;

    // Check if Senior Citizen Discount Applies
    if (senCitizen) {
        return (finalMembershipCost * 0.7) + finalSessionCost ;
    }
    else {
        return finalMembershipCost + finalSessionCost;
    }

}

My Test Result

An error occurs on "Senior Citizen Discount".

Green color - My output.
Red color - Its output (Correct Answer).
I don't know how to get that answer ($2260.00) with my code. I have checked many times and I couldn't solve the problem. Please help me!

A: You should use an or-Statement for detecting if its a senior citizen:
if (userInputSenior == 'y' || userInputSenior == 'Y')

BTW: You have another small bug when calculating the discount for personal lessons, you only get a discount for more than 5 sessions, so the corresponding if-statement should be
(nOfPersonalTrSess > 5)

A: Thank you guys so much, I solved my problem!
Here is my complete program:
#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

// program constants

void setPrices(double&, double&);
void getInfo(bool&, bool&, bool&, int&, int&);
double membershipCost(double, int, double, int, bool, bool, bool);

void displayCenterInfo();

int main()
{
    bool seniorCitizen;
    bool boughtSixOrMoreSessions;
    bool paidTwelveOrMoreMonths;

    int numberOfMembershipMonths;
    int numberOfPersonalTrainingSessions;
    double regularMembershipChargesPerMonth;
    double costOfOnePersonalTrainingSession;

    double memberCost;

    cout << fixed << showpoint << setprecision(2);

    displayCenterInfo();

    cout << endl;

    setPrices(regularMembershipChargesPerMonth, costOfOnePersonalTrainingSession);

    getInfo(seniorCitizen, boughtSixOrMoreSessions, paidTwelveOrMoreMonths, numberOfMembershipMonths, numberOfPersonalTrainingSessions);

    // cal getInfo
    memberCost = membershipCost(regularMembershipChargesPerMonth, numberOfMembershipMonths, costOfOnePersonalTrainingSession,
        numberOfPersonalTrainingSessions, seniorCitizen, boughtSixOrMoreSessions, paidTwelveOrMoreMonths);

    cout << "$" << memberCost;

    system("pause");
    return 0;

}

void displayCenterInfo()
{
    cout << "Welcome to Stay Healty and Fit center." << endl;
    cout << "This program determines the cost of a new membership." << endl;
    cout << "If you are a senior citizen, then the discount is 30% of "
        << "of the regular membership price." << endl;
    cout << "If you buy membership for twelve months and pay today, the "
        << "discount is 15%." << endl;
    cout << "If you buy and pay for 6 or more personal training session today, "
        << "the discount on each session is 20%." << endl;
}

void setPrices(double& regMemPrice, double& personalTrSesCost)
{

    cout << "Please enter the cost of regular Membership per month: " << endl;
    cin >> regMemPrice;

    cout << "Please enter the cost of one personal traning session: " << endl;
    cin >> personalTrSesCost;

}

void getInfo(bool& senCitizen, bool& bSixOrMoreSess, bool& paidTwMnth,
    int& nOfMonths, int& nOfPersonalTrSess)
{
    //Senior Verification
    char userInputSenior;
    cout << "Are you Senior? Please enter 'Y' or 'N': ";
    cin >> userInputSenior;

    if (userInputSenior == 'y' || userInputSenior == 'Y')
    {
        senCitizen = true;
    }
    else
        senCitizen = false;

    cout << endl;

    //Number of personal training session.
    cout << "Enter the number of personal training sessions bought: ";
    cin >> nOfPersonalTrSess;

    if (nOfPersonalTrSess > 5)
    {
        bSixOrMoreSess = true;
    }
    else
        bSixOrMoreSess = false;

    cout << endl;

    //Number of months
    cout << "Enter the number of months you are paying for: ";
    cin >> nOfMonths;

    if (nOfMonths >= 12)
    {
        paidTwMnth = true;
    }
    else
        paidTwMnth = false;

}

double membershipCost(double regMemPricePerMth, int nOfMonths,
    double personalTrSesCost, int nOfPersonalTrSess,
    bool senCitizen, bool bSixOrMoreSess, bool paidTwMnth)
{
    double finalMembershipCost, finalSessionCost;

    //Session Discount
    if (bSixOrMoreSess)
    {
        personalTrSesCost = (personalTrSesCost * 0.8);

    }
    else
    {
        personalTrSesCost = personalTrSesCost;

    }

    //Month Discount
    if (paidTwMnth)
    {
        regMemPricePerMth = regMemPricePerMth * 0.85;
    }
    else
    {
        regMemPricePerMth = regMemPricePerMth;
    }

    finalMembershipCost = regMemPricePerMth * nOfMonths;
    finalSessionCost = personalTrSesCost * nOfPersonalTrSess;

    // Check if Senior Citizen Discount Applies
    if (senCitizen) {
        return (finalMembershipCost * 0.7) + finalSessionCost;
    }
    else {
        return finalMembershipCost + finalSessionCost;
    }

}


text:
Q: Add new systemd unit file directory I'm working on an embedded system which mounts /etc as read-only, I'd like to add a new, additional directory in which I can add/modify systemd unit files.
So for example:
/mnt/flash/test/myservice.service

systemctl daemon-reload
How can I configure the /mnt/flash/test/ path to be searched by systemctl daemon-reload?
Thanks!

A: I found that /run/systemd/system/ can be used for runtime drop-ins and just linked my files there. Seems to work


text:
Q: Are memory leaks totally absent in Java applications?
Possible Duplicate:
Creating a memory leak with Java

There is a "Garbage Collector" in Java, but does this mean that memory leaks are totally absent in a Java applications? If not, how and why do they happen?
I am more interested in scenarios in applications using JavaSE.

A: Depends on how you define memory leak.
If you specifically mean having allocated memory that is no longer referenced by some memory root, then no, the garbage collector will eventually clean all of those up.
If you mean generally having your memory footprint grow without bound, that is easily possible. Just have some collection referenced by a static field and constantly added to.

A: No - memory leaks can still exists in Java. They are just of a "different kind".
Wiki: Memory Leak

A memory leak, in computer science (or leakage, in this context), occurs when a computer program consumes memory but is unable to release it [the memory] back to the operating system.

In the case of Java it (normally) is when an unused/unneeded object is never made eligible for reclamation. For instance, an object may be stashed in a global List and never removed even if the object is never accessed later. In this case the JVM won't release the object/memory - it can't - because the object might be needed later, even if it never is.
(As an aside, some objects, such as directly allocated ByteBuffers also consume "out of JVM heap" memory which might not be reclaimed in a timely manner due to the nature of finalizers and memory pressure.)
In the case of Java, a "memory leak" is a semantic issue and not so much an issue of "not being able to release under any circumstances". Of course, with buggy JNI/JNA code, all bets are off ;-)
Happy coding.

A: Memory leaks in java are very possible. Here is a good article which has an example using core java. Fundamentally, a memory leak happens in java when the garbage collector cannot reclaim an object because the application holds a reference to it that it won't release, even though the object itself might no longer be used. The easiest way to create a memory leak in java is to have your application hold a reference to something, but not using it.
In the example, the unused object is a static List, and adding things to that list will eventually cause the JVM to run out of memory. Static collections are a pretty common source of "leaks", as they are typically long lived and mutable.

A: There are a few good responses so far.  I don't want to recreate those posts, so I'll just add that one thing most people don't think about in connection with this subject is leaks in native code running via JNI.  Native code running via JNI uses the JVM's heap space to allocate memory.  So, if your application uses native code running via JNI that has a leak, your application has a leak.

A: Any object that has one or more live references to it will not be garbage-collected. So as long as some variable (either static, in the heap, or in the stack) refers to an object, that object will continue to occupy non-reclaimable memory space.
Unclosed resources (like sockets, JDBC connections, etc.) and constantly growing static collections are some of the better-known leak producers.


text:
Q: OOM when allocating tensor with shape[1,144,144,144,128] The computer I use is 1080 which has a GPU memory of 8 GB, the memory of my computer is 32 GB, but the array data might be to large for me to restore, the computer tells me resource exhausted. if there is anyway to solve this problem or evaluate the GPU memory i need for such a large numpy array so I can buy a better computer for calculate.by the way the batch_size I use is 1 so i have reduce the memory to the minimal, or i should consider to reduce the raw column and the height of my numpy array, and I think that would effect the resolution of my results that would be okay.
If anyone can answer my question. thanks

A: The tensor itself you are using is big, but not that big for a 8Gb GPU. 144 * 144 * 144 * 128 is ~380 million, so even with 32-bit items it requires 1.5GiB. I have a GeForce GTX 1070 with 8Gb (same size as you) and here's my Tensorflow experiment:
import numpy as np
import tensorflow as tf

X = tf.placeholder(dtype=tf.int32, shape=(1, 144, 144, 144, 128))
init = tf.global_variables_initializer()

with tf.Session() as session:
  session.run(init)
  value = session.run([X], feed_dict={X: np.zeros(shape=(1, 144, 144, 144, 128))})
  print np.array(value).shape

The output:
name: GeForce GTX 1070
major: 6 minor: 1 memoryClockRate (GHz) 1.7465
pciBusID 0000:01:00.0
Total memory: 7.92GiB
Free memory: 4.14GiB
2017-08-17 20:05:54.312424: I tensorflow/core/common_runtime/gpu/gpu_device.cc:908] DMA: 0
2017-08-17 20:05:54.312430: I tensorflow/core/common_runtime/gpu/gpu_device.cc:918] 0:   Y
2017-08-17 20:05:54.312444: I tensorflow/core/common_runtime/gpu/gpu_device.cc:977] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 1070, pci bus id: 0000:01:00.0)
(1, 1, 144, 144, 144, 128)

Note that free memory is much lower than 8Gb, because I use 2 UHD monitors. So this might be the first cause in your case: other processes can consume a lot of GPU resources.
Next, you didn't provide your Neural Network architecture, but if you are using, for instance, Deep Convolutional Neural Networks, note that the first layers are consuming a lot of memory for parameters and gradients. You might want to read this helpful page for details. If this is the case, you might need to plug in another GPU and split the graph across all available GPUs (here's how you can do it). There are 12Gb memory GPUs available from NVidia.
Finally, you can always consider reducing the floating precision tf.float64 -> tf.float32 -> tf.float16 for all your variables. This can save 8x memory, which sometimes is just enough to run on a GPU.


text:
Q: Windows 10 Explorer doesn't start This problem has persisted for several months but it comes up periodically. My temporary fix is to restart but I've gotten annoyed.
When I click on a folder, it starts but when I start up explorer.exe itself, it wont work. Also when I right click on a folder or file, it crashes explorer and restarts it.
I've tried restarting the process and chosen the Launch Folder In Different Process and always use Icons, Never Thumbnails.
I have tried disabling shell extensions with third party software but no luck.


text:
Q: Alignment of Navigation Menu I'm trying to get my sub-menu to align left.  The team names are spilling over.  Either it needs aligned left or I need to widen the sub-menu.  I think I am just over-looking what needs to be done, but I just can't figure it out.

nav {
  background-color: #000;
  border: 1px solid #000;
  border-radius: 4px;
  box-shadow: 0 2px 2px -1px rgba(0, 0, 0, 0.055);
  color: #888;
  display: block;
  margin: 8px 22px 8px 22px;
  overflow: hidden;
  width: 90%;
  text-align: center;
}
nav ul {
  margin: 0;
  padding: 0;
}
nav ul li {
  display: inline-block;
  list-style-type: none;
  -webkit-transition: all 0.2s;
  -moz-transition: all 0.2s;
  -ms-transition: all 0.2s;
  -o-transition: all 0.2s;
  transition: all 0.2s;
}
nav > ul > li > a > .caret {
  border-top: 4px solid #FFF;
  border-right: 4px solid transparent;
  border-left: 4px solid transparent;
  content: "";
  display: inline-block;
  height: 0;
  width: 0;
  vertical-align: middle;
  -webkit-transition: color 0.1s linear;
  -moz-transition: color 0.1s linear;
  -o-transition: color 0.1s linear;
  transition: color 0.1s linear;
}
nav > ul > li > a {
  color: #FFF;
  display: block;
  line-height: 56px;
  padding: 0 24px;
  text-decoration: none;
}
nav > ul > li:hover {
  background-color: rgb(40, 44, 47);
}
nav > ul > li:hover > a {
  color: rgb(255, 255, 255);
}
nav > ul > li:hover > a > .caret {
  border-top-color: rgb(255, 255, 255);
}
nav > ul > li > div {
  background-color: rgb(40, 44, 47);
  border-top: 0;
  border-radius: 0 0 4px 4px;
  box-shadow: 0 2px 2px -1px rgba(0, 0, 0, 0.055);
  display: none;
  margin: 0;
  opacity: 0;
  position: absolute;
  width: 165px;
  visibility: hidden;
  z-index: 100;
  -webkit-transiton: opacity 0.2s;
  -moz-transition: opacity 0.2s;
  -ms-transition: opacity 0.2s;
  -o-transition: opacity 0.2s;
  -transition: opacity 0.2s;
}
nav > ul > li:hover > div {
  display: block;
  opacity: 1;
  visibility: visible;
}
nav > ul > li > div ul > li {
  display: block;
}
nav > ul > li > div ul > li > a {
  color: #fff;
  display: block;
  padding: 12px 24px;
  text-decoration: none;
}
nav > ul > li > div ul > li:hover > a {
  background-color: rgba(255, 255, 255, 0.1);
}

Home

Teams

Link

Link

Link

Link

Link

Link

Link

Link

Link

Link

Link

Link

Link

Link