text:
Q: Data Table Information not Populating to all Data Grid View's in Loop I've created an application that's reading workstation DNS names and pinging them to see if there are any workstations that are having network connectivity issues.
Everything is great up until the end, where I'm trying to read in the Output file information and display it in DataGridView (DGV).
The issue occurs when I'm trying to display the code created datatable from the read text file and populate different DataGridViews. It works fine with a single room selected. But when I try and output the data to multiple DataGridViews, only the last DataGridView is populated with it's data. None of the previous DGV's are populated.
A little more information, I have a TabControl with TabPages that correspond to each room, in those TabPages are where each separate DataGridView resides. So in total there are 12 DataGridViews that could need a datatables information assign to it's DataSource.
I've tried simply adding the data via DGV.Rows.Add() [this isn't actual code, just an explanation]. Now while this worked fine for outputting the information to the DataGridView with a single selection, I could not find a way to clear the DataGridView when I was simply adding Row Data to it. DGV<Name>.Rows.Clear() did nothing, DGV<Name>.Rows.Remove(#) erred out, DGV<Name>.DataSource = VbNull did nothing either, and I'm assuming that's because with that method I actually wasn't adding a datasource to the DGV in the first place.
Any assistance as to what I need to do to make sure that each Room's DGV has it's output information correctly in it's appropriate DGV would be greatly appreciated.
I'm using VS 2015 Community Edition if that makes any difference. And I do not have access to the LINQ plugin, just in-case people were thinking that might be a way to solve it.
Here's the associated code:
    Private Sub loadResults()

    Dim i As Integer = 0        'Counter variable
    Dim fName As String() = GlobalVariables.selectedRoomsList.ToArray
    Dim x As Integer = fName.Length         'Upper limit of the Array to be checked against
    Dim AppDir As String = Path.GetDirectoryName(Path.GetDirectoryName(Application.StartupPath))
    Dim dataName As String = "dgv" & fName(i)
    Dim resultFilePath As String = AppDir & "\data\output\" & fName(i) & ".txt"
    Dim fileExists As Boolean = File.Exists(resultFilePath)
    Dim rowvalue As String
    Dim cellvalue(5) As String
    Dim oDataTable As DataTable

    lblGoodPingTotal.Text = GlobalVariables.successfulPings
    lblBadPingTotal.Text = GlobalVariables.failedPings
    lblTimeElapsed.Text = GlobalVariables.elapsedTime

    Do Until i > x

        oDataTable = New DataTable("PingTable")

        Dim Column1 As DataColumn = New DataColumn("Computer Name")
        Column1.DataType = System.Type.GetType("System.String")
        Dim Column2 As DataColumn = New DataColumn("Status")
        Column2.DataType = System.Type.GetType("System.String")
        Dim Column3 As DataColumn = New DataColumn("IP Address")
        Column3.DataType = System.Type.GetType("System.String")
        Dim Column4 As DataColumn = New DataColumn("Bytes Sent")
        Column4.DataType = System.Type.GetType("System.String")
        Dim Column5 As DataColumn = New DataColumn("Round Trip")
        Column5.DataType = System.Type.GetType("System.String")
        Dim Column6 As DataColumn = New DataColumn("TTL")
        Column6.DataType = System.Type.GetType("System.String")

        oDataTable.Columns.Add(Column1)
        oDataTable.Columns.Add(Column2)
        oDataTable.Columns.Add(Column3)
        oDataTable.Columns.Add(Column4)
        oDataTable.Columns.Add(Column5)
        oDataTable.Columns.Add(Column6)

        If fileExists Then

            Using sReader As New StreamReader(resultFilePath)

                While sReader.EndOfStream = False

                    Dim rowAdd As DataRow
                    rowAdd = oDataTable.NewRow()

                    rowvalue = sReader.ReadLine()
                    cellvalue = rowvalue.Split(","c)

                    rowAdd.ItemArray = cellvalue

                    oDataTable.Rows.Add(rowAdd)

                End While

                sReader.Close()

            End Using

            dataPrint(dataName, oDataTable)

            i = i + 1

        Else
            MsgBox("Error! The file for Room" & fName(i) & "is not found.", vbOKOnly = MsgBoxStyle.Critical, "Error")

            Exit Do

        End If

    Loop

End Sub

Private Sub dataPrint(iName As String, iTableData As DataTable)

    Dim dgvName As String = iName
    Dim oDataTable As DataTable = iTableData

    If dgvName = "dgvA1402" Then

        dgvA1402.DataSource = oDataTable

    ElseIf dgvName = "dgvA1532" Then

        dgvA1532.DataSource = oDataTable

    ElseIf dgvName = "dgvA1D038" Then

        dgvA1D038.DataSource = oDataTable

    ElseIf dgvName = "dgvA1D042" Then

        dgvA1D042.DataSource = oDataTable

    ElseIf dgvName = "dgvA1D043B" Then

        dgvA1D043B.DataSource = oDataTable

    ElseIf dgvName = "dgvA1E014A" Then

        dgvA1E014A.DataSource = oDataTable

    ElseIf dgvName = "dgvA1E036" Then

        dgvA1E036.DataSource = oDataTable

    ElseIf dgvName = "dgvA1E047C" Then

        dgvA1E047C.DataSource = oDataTable

    ElseIf dgvName = "dgvA1E047D" Then

        dgvA1E047D.DataSource = oDataTable

    ElseIf dgvName = "dgvA1E047F" Then

        dgvA1E047F.DataSource = oDataTable

    ElseIf dgvName = "dgvA1E047G" Then

        dgvA1E047G.DataSource = oDataTable

    ElseIf dgvName = "dgvA1E048" Then

        dgvA1E048.DataSource = oDataTable

    End If

End Sub

A: First, I'd like to say thank you to Marc Lyon for responding. However, I don't think I took your way to producing the answer I found.
But after doing some research and then a lot of trial and error the following code is what I came up with that works completely and gives me the output I was looking for. There's probably a shorter way of achieving the answer, but for now this works.
Private Sub loadResults(aRooms As List(Of String), pingUp As Integer, pingDown As Integer)
    '//All passed variables
    Dim rmNames As List(Of String) = aRooms
    '//All file path and directory variables
    Dim AppDir As String = Path.GetDirectoryName(Path.GetDirectoryName(Application.StartupPath))
    Dim resultFilePath As String
    Dim fileExists As Boolean
    '//All row and row data variables
    Dim rowvalue As String
    Dim cellvalue(5) As String
    '//All datatable and dataset variables
    Dim dSet As DataSet
    Dim oDataTable As DataTable

    '//Displays the total number of ping Successes and Fails
    lblGoodPingTotal.Text = pingUp
    lblBadPingTotal.Text = pingDown
    lblTimeElapsed.Text = GlobalVariables.elapsedTime

    '//Sets the new dataset
    dSet = New DataSet()

    For Each fileName As String In rmNames

        oDataTable = New DataTable(fileName)
        '//Creating the columns and column names in code
        Dim Column1 As DataColumn = New DataColumn("Computer Name")
        Column1.DataType = System.Type.GetType("System.String")
        Dim Column2 As DataColumn = New DataColumn("Status")
        Column2.DataType = System.Type.GetType("System.String")
        Dim Column3 As DataColumn = New DataColumn("IP Address")
        Column3.DataType = System.Type.GetType("System.String")
        Dim Column4 As DataColumn = New DataColumn("Bytes Sent")
        Column4.DataType = System.Type.GetType("System.String")
        Dim Column5 As DataColumn = New DataColumn("Round Trip")
        Column5.DataType = System.Type.GetType("System.String")
        Dim Column6 As DataColumn = New DataColumn("TTL")
        Column6.DataType = System.Type.GetType("System.String")

        '//Setting the columns for the generated datatable
        oDataTable.Columns.Add(Column1)
        oDataTable.Columns.Add(Column2)
        oDataTable.Columns.Add(Column3)
        oDataTable.Columns.Add(Column4)
        oDataTable.Columns.Add(Column5)
        oDataTable.Columns.Add(Column6)

        '//Setting the output file path
        resultFilePath = AppDir & "\data\output\" & fileName & ".txt"

        '//Setting the path to test for file existence
        fileExists = File.Exists(resultFilePath)

        If fileExists Then
            '//If the file exists the file is read into memory and the datatable has it's values assigned to a row
            Using sReader As New StreamReader(resultFilePath)

                While sReader.EndOfStream = False

                    '//New row created
                    Dim rowAdd As DataRow
                    rowAdd = oDataTable.NewRow()

                    '//New row has the data read and assigned to it
                    rowvalue = sReader.ReadLine()
                    cellvalue = rowvalue.Split(","c)

                    rowAdd.ItemArray = cellvalue

                    '//Datatabl gets the row of data assigned to it, one at a time
                    oDataTable.Rows.Add(rowAdd)

                End While

                sReader.Close()

            End Using

            '//Commits the changes to each datatable that's created
            oDataTable.AcceptChanges()

            '//Adds each datatable that's created to the Dataset for use in output
            dSet.Tables.Add(oDataTable)

        Else

            '//Error message just incase a output file wasn't generated for the selected room
            MsgBox("Error! The file for Room " & fileName & " is not found.", vbOKOnly = MsgBoxStyle.Critical, "Error")

        End If

    Next

    '//Calling the sub-routine to output the date to the proper datagridview
    dataPrint(dSet)

End Sub

Private Sub dataPrint(iDataSet As DataSet)
    '//Variables cast for getting the Dataset and DataTable collections
    Dim datSet As DataSet = iDataSet
    Dim datTCollection As DataTableCollection = datSet.Tables
    '//Running the checks against the selected Dataset for Datatable names and information output
    For Each tbName As DataTable In datTCollection

        If tbName.TableName = "A1402" Then
            dgvA1402.DataSource = tbName
        ElseIf tbName.TableName = "A1532" Then
            dgvA1532.DataSource = tbName
        ElseIf tbName.TableName = "A1D038" Then
            dgvA1D038.DataSource = tbName
        ElseIf tbName.TableName = "A1D042" Then
            dgvA1D042.DataSource = tbName
        ElseIf tbName.TableName = "A1D043B" Then
            dgvA1D043B.DataSource = tbName
        ElseIf tbName.TableName = "A1E014A" Then
            dgvA1E014A.DataSource = tbName
        ElseIf tbName.TableName = "A1E036" Then
            dgvA1E036.DataSource = tbName
        ElseIf tbName.TableName = "A1E047C" Then
            dgvA1E047C.DataSource = tbName
        ElseIf tbName.TableName = "A1E047D" Then
            dgvA1E047D.DataSource = tbName
        ElseIf tbName.TableName = "A1E047F" Then
            dgvA1E047F.DataSource = tbName
        ElseIf tbName.TableName = "A1E047G" Then
            dgvA1E047G.DataSource = tbName
        ElseIf tbName.TableName = "A1E048" Then
            dgvA1E048.DataSource = tbName
        End If

    Next

End Sub

I went through and re-did a lot of code. I took the core ideas of what I was trying to do and then refined them (not just in these code blocks either). That helped quite a bit, as it flowed the data better than my original code segments.
Anyways, on to the main answer, I found information on DataSets with DataTables and used the DataSet to store multiple DataTables with different Names. The names were provided from the read-in output files themselves. So all I needed to do after that, was search through the DataSet as a Collection and match up the names to the names of the TabPages and then output that respective tables data as the DataSource with the corresponding DataGridView.


text:
Q: issue with a circle using tikz,beamer and pgfplots Im trying to make a circle like this

using the next code
\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.14}

\begin{document}
    \begin{tikzpicture}
    \begin{axis}[
        axis lines = middle,
        xmin=-1, xmax=3, ymin=-1, ymax=7,
        axis equal,
        xlabel = {$x$},
        ylabel = {$y$},
        yticklabels={0,...,5},
        grid=both,
        ]
       \draw (axis cs: 1,4) circle [radius=sqrt(3)];
       \draw (1,4) node[circle,draw,inner sep=1pt,label=below:$\C_C$](z0) {};
       \draw[-stealth] (z0) -- (2.4,3) node[midway,above]{$\space\sqrt3$};
    \end{axis}
\end{tikzpicture}
\end{document}

but when I try to use the beamer class to build the same picture inside a column inside a frame it cant be compiled using pdflatex
   \documentclass{beamer}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.14}
\begin{document}
\begin{frame}\frametitle{Title}

  \begin{tikzpicture}
    \begin{axis}[
        axis lines = middle,
        xmin=-1, xmax=3, ymin=-1, ymax=7,
        axis equal,
        xlabel = {$x$},
        ylabel = {$y$},
        yticklabels={0,...,5},
        grid=both,
        ]
        %\draw[step=1cm,gray,very thin] grid ;
        \draw (axis cs: 1,4) circle [radius=sqrt(3)];
        \draw (1,4) node[circle,draw,inner sep=1pt,label=below:$\C_C$](z0) {};
        \draw[-stealth] (z0) -- (2.4,3) node[midway,above]{$\space\sqrt3$};
    \end{axis}
\end{tikzpicture}
\end{frame}
\end{document}

That gives me two issues one is to find what prevents the compilation and the other is the circle is supposed to be centered in (1,3) but when this coordinates is used the center in the picture appears in (1,2) so it must be compensated using \draw (axis cs: 1,4). What I'm missing in the code to compile and to assign coordinates?
UPDATE
As noted by abcdefg there was a undefined sequence in  \C after that it compile as

but the center is shifted where is supposed to be using the
    \draw (1,3) node[circle,draw,inner sep=1pt,label=below:$C$](z0) {};

and
yticklabels={0,1,2,3,4,5},
yticklabels={$\pgfmathprintnumber\tick$},

UPDATE 2
Well the center is right where is supposed to be, but the arrow isnt starting from the center, as I understand, it is defined the line to start in z0 and go to (2.4,3) . So it can be explicit done by
\draw[-stealth] (1,3) -- (2.4,3) node[midway,above]{$\space\sqrt3$};

but even so it seems not to be working.

A: Maybe you are looking for something of this sort (perhaps with \pgfplotsset{compat=1.14} instead of \pgfplotsset{compat=1.17}).
\documentclass{beamer}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.17}
\begin{document}
\begin{frame}
\frametitle{Title}

  \begin{tikzpicture}
    \begin{axis}[
        axis lines = middle,
        xmin=-1, xmax=3, ymin=-1, ymax=7,
        axis equal,
        xlabel = {$x$},
        ylabel = {$y$},
        yticklabel={$\pgfmathprintnumber\tick$},
        grid=both,
        ]
        %\draw[step=1cm,gray,very thin] grid ;
        \draw (1,3)  node[circle,draw,inner sep=1pt,label=below:{$C$}] (c0){}
             circle [radius={sqrt(3)}];
        \draw[-stealth] (c0) to[edge label={$\sqrt{3}$}] ++
        (axis direction cs:{sqrt(3)*cos(-45)},{sqrt(3)*sin(-45)}) ;
    \end{axis}
\end{tikzpicture}
\end{frame}
\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Manipulate Client Machine From Web Application - ASP.Net My company has several desktop applications that needs to be launched from an ASP.Net Core web application. Also the applications are going to be updated if there is a newer version. The web application would be working offline (only accessible to a specific LAN), and all the applications and clients would be in the same network. So basically, I am trying to create a Launcher/Updater Web Application.
The problem here is, web browsers are not capable manipulating (installing, launching or updating) applications that are on the client machine in a direct manner. We already checked Microsoft`s ClickOnce solution on updating applications but there are some reasons why we do not want to use it.
My question is, if there is any way to read, write and edit client side data, with or without an extra client side application from a Web application?

A: I had a similar problem. There is no way to update client without using an additional program (at least in my experience). You won't be able to delete and replace libs and executable when the files are in use (read the software is running).
I wrote a small application to handle restart, update, and monitoring of the main application.
If you need more info about the approach I used let me know.


text:
Q: Qt Connection conversion fail I try to connect a QGraphicsObject subclass and a QGraphicsView subclass (with the following line in the QGraphicsObject constructor)
connect(this, SIGNAL(paintImage(QPainter *, const QImage &)), this->scene()->views().front(), SLOT(paintImage(QPainter *, const QImage &)));

But I get the following error:
D:\Project\Scene\PointField.cpp:18: error : C2664: 'QMetaObject::Connection QObject::connect(const QObject *,const char *,const char *,Qt::ConnectionType) const: cannot convert 'QGraphicsView *' to 'const QObject *'
The point types are unrelated; conversion needs reinterpret_cast, C style cast or function style cast.

I see from the documentation that QGraphicsView inherits from QObject, and there is the Q_OBJECT macro in both subclass declaration... Does someone have an idea?

A: QGraphicsView is an incomplete type at the point where it is used in the connect() call.  The compiler doesn't know that it inherits from QObject, and this is why it reports

cannot convert 'QGraphicsView *' to 'const QObject *'

The solution is to #include <QGraphicsView> in the implementation file, somewhere before the connect() call.

A: I solved my problem by including my QGraphicsView sublass header at the top of the QGraphicsObject subclass header, then clean / execute qmake / rebuild.


text:
Q: Display collapsible content within a Div I've searched around the web for a solution to my problem and im getting pretty close to my desired design with Accordion JQuery but..
I have some extension to the JQuery template which I dont know how to implement, so here it goes:
This is how my Div looks when you enter the webpage:

When you hover over either the picture or the title/text the text will be underlined and italic so that the user know the feature with cliking on it.
What I would like see if the visitor clicks the picture/text is this:

This is my HTML for that specific Div

    DarkShift Studios Web

We are pleased to present our first release of the Web-headquarter. Everything you see on these webpages have been builed from scratch, HTML/CSS and JS code, no CMS programs have been used. ...

Code:
http://jsfiddle.net/VCDe2/1/
Appreciate any hints/tips!

A: Here's a JSFiddle to show you what's happening.
jQuery:
$('h1').click(function(){
    $(this).next('.hidden').slideToggle();
});

Simple enough!  Adaam's fiddle in the post above certainly does work, but I'd recommend not using it as it will only work for one item - you'll need to add more code for every new section you create.
This solution, however, will look for any h1 item when it is clicked, and then find the next .hidden class item closest to it, allowing you to add as many different areas as you want.
For instance, with the same code above, you can scale everything up to work like this with no extra jQuery script.
All you have to do to incorperate it into your project is make sure your .hidden equivalent is nested inside of a container with the rest of the section, and change h1 and .hidden to fit your proper classnames.  Make sure they're classnames, as IDs will not work.


text:
Q: How to initialize Money column with zero amount in Active Model? I have a new app (Rails 2.3.8) that uses lots of money fields. I'm using the money gem (3.0.5) and the acts_as_money plugin. I've written a number of rspec model examples and everything seems to be working fine there.
My problem is in defining forms for new & edit. As I've done in past projects for complex layouts, I extracted the basic form to a partial and include it in the new & edit views.
However, the model object is created and left with nulls in the fields, and causes the money gem to complain with: "undefined method `subunit_to_unit' for nil:NilClass".
I thought I could use something like after_initialize() to hook into the creation of a new object in Rails and set all the money attributes to zero, but that didn't work (and several posts recommended against that for performance reasons)...
Any suggestions on a clean way to hook my model object and make sure it's got zeros for all the money values?

A: after_initialize does not do what you think it does
the way too hook into init is as follows:
class MyModel < ActiveRecord::Base

  def initialize(*args, &block)
     super         # no () form is equivalent to super(*args, &block)
     set_defaults
  end

  private

  def set_defaults
    # Do your defaults here
  end

end


text:
Q: Woocommerce checkout only refresh on postcode I am trying to make checkout faster and my shipping is only based on the postcode so I do not want 'order review' to refresh when address, country, state is change.
I know I need to fiddle with: woocommerce/includes/class-wc-ajax.php
Specifically: update_order_review();
Is there a way to do this by adding code to my themes functions.php rather than comment out core code?

A: I don't think so that there is a legal way of doing it. But there is a work around to it. You can remove woocommerce default fields from your checkout form and add your custom fields. - This way it will not trigger ajax on its update.
You can add/remove custom fields on checkout this way:
add_filter( 'woocommerce_checkout_fields' , 'vid_remove_billing_postcode_checkout' );

function vid_remove_billing_postcode_checkout( $fields ) {
  unset($fields['billing']['billing_postcode']);
  $fields['shipping']['shipping_phone'] = array(
        'label'     => __('Phone', 'woocommerce'),
        'placeholder'   => _x('Phone', 'placeholder', 'woocommerce'),
        'required'  => false,
        'class'     => array('form-row-wide'),
        'clear'     => true
    );
  return $fields;
}


text:
Q: Show NSWindow on right click in NSTableView I'd like to display an NSWindow when right clicking an item in an NSTableView, similarly to how the available outlets are shown in Interface Builder when you right click an object:

Unfortunately you can only use an NSMenu subclass as the menu property.
I also didn't find a delegate method of NSTableView that notifies about right clicks.
I was able to subclass NSTableView and implement rightMouseDown: and rightMouseUp: to be notified about those events, but if I set the menu property of the row cells to nil, they are not highlighted when right clicked, even though I call the super implementation):
- (void)rightMouseDown:(NSEvent *)theEvent {
    [super rightMouseDown:theEvent];
    NSPoint eventLocation = [theEvent locationInWindow];
    eventLocation = [self convertPoint:eventLocation fromView:nil];
    NSInteger rowIndex = [self rowAtPoint:eventLocation];
    NSLog(@"Right clicked at row index %d", rowIndex);
}

I would like to have the highlight effect in the image below but display a window instead of the context menu:

A: You can use an NSPopover, which works quite nicely. A popover creates a window for you, even if it is somewhat hidden. You'll get it from your controls if you send them the window message, and can register to listen for events, for instance.
The whole popover can be created in IB, and just have to implement the showRelativeToRect:ofView:preferredEdge: method in code.
To catch the right click event, you can use rightMouseDown:, which is originally defined in NSResponder, but is overridden in NSView to simply catch the event and show menu and it doesn't pass the event upwards in the responder chain (or the inheritance chain, for that matter). Hence, you simply implement that method to call showRelativeToRect:ofView:preferredEdge:.
You will typically need to have the contents in an NSViewController and its own accompanying nib file.
The NSPopover's contentViewController property can be set in IB, too.
All in all, not much code needed.
This tutorial is useful.

A: First for the right click: explicitly select the row on right click (e.g. via this message). Then create your own NSWindow descendant, set an own NSView class as contentView and in the view you can draw the black background, rounded borders and what not. Show this window in your right click handler.


text:
Q: Echo multiple variables to one div class I'm trying to echo a user name and a greeting from IF statement i made.
<?php
                global $current_user;
                get_currentuserinfo();
                echo get_avatar( $current_user->ID, 64 );
                $hour = date('G');
                if ($hour < 12) {
                    $greeting = 'Good Morning';
              } else if ($hour < 18) {
                    $greeting = 'Good Evening';
              } else {
                    $greeting = 'Good Night';
        }

    echo '
'.($greeting). , .$current_user->user_login. '
';
?>

but i'm getting syntax error:

syntax error, unexpected ','

How can i echo 2 variables into one div?

A: Your comma should be enclosed in a string:
echo '
'.$greeting.' , '.$current_user->user_login. '
';


text:
Q: JTable column display problem using rs2xml The column from my database do not show , i only get the rows with correct data but no column headers . does someone know the answer to this problem? thank you
public class interftable extends JFrame {

private static JFrame frame;
public static JButton valider;
public JTable jt ;
public static JPanel panel;

public interftable() {

    JTable jt = new JTable();
    jt.setBounds(20, 20, 700, 400);

    JFrame frame= new JFrame();
    frame.setSize(800,500);
    frame.setLayout(null);
    frame.setSize(800, 500);

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(20, 20, 700, 400);
    frame.add(scrollPane);

    frame.add(jt);
    frame.setVisible(true);

    try {

////database connection
        Class c = Class.forName("com.mysql.jdbc.Driver");
        Driver pilote = (Driver)c.newInstance();
        DriverManager.registerDriver(pilote);

        String conString ="jdbc:mysql://localhost:8889/user";
        String nomConnexion = "root";
        String motDePasse = "123";
        Connection con= DriverManager.getConnection(conString,nomConnexion,motDePasse);

        String sql="select * from users ";
        Statement smt = con.createStatement();
        ResultSet rs = smt.executeQuery(sql);

        jt.setModel(DbUtils.resultSetToTableModel(rs));
    }
    catch(Exception e)
    {}

        frame.add(jt);
        frame.setVisible(true);
    }

//main
public static void main (String[]args) {
                interftable f=new interftable();
            }
}

A: JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(20, 20, 700, 400);
frame.add(scrollPane);

frame.add(jt);

Frist of all don't use a null layout. Swing was designed to be used with layout managers.
So get rid of all the setBounds() statements. In this simple example the scrollpane/table will be added to the BorderLayout.CENTER, which means it will fill the entire frame.
If you want the header to be displayed, then the table must be added to a JScrollPane.
Your code should be:
JScrollPane scrollPane = new JScrollPane(jt);
//scrollPane.setBounds(20, 20, 700, 400);
frame.add(scrollPane);

//frame.add(jt);

Also don't know why you repeat this code again:
    frame.add(jt);
    frame.setVisible(true);

Get rid of it.
You should not add the table to the frame. It only belongs in the scrollpane.
Read the section from the Swing tutorial on How to Use Tables for the basics of using a JTable. You should understand the basics before you attempt to use a database and a 3rd part class to create the TableModel.


text:
Q: Result of a definite integral as a function of extra parameters I am trying to integrate a definite integral with respect to dE for a function that depends on E and x, x being another parameter that I will use later. I defined a function of x that could help me with this, but it does not seem to work. When I give the new function a certain value--such as 1 or 10--it always returns 0. Here is my code:
%matplotlib inline
import matplotlib.pyplot as plt
from scipy.integrate import quad
import numpy as np
from numpy import pi
from numpy import arange

gg=100.0
ms=100.0

def integrand(E, xx):
    return (gg/2*pi)*E*(E**2-ms**2)**(1/2)/(np.exp(E*xx*ms)-1)

def nn(x):
    return quad(integrand, ms, np.inf, args=(x))  ## quad(funcion, lim inf, lim sup, args)

What I need is to be able to later call the function nn with the parameter x being the variable.

A: You could simply define all the values outside of the function:
from scipy.integrate import quad
import numpy as np
from numpy import pi

gg = 100.0
ms = 100.0
xx = 5.0
ms = 1.0

def integrand(E):
    return (gg / 2 * pi) * E * (E ** 2 - ms ** 2) ** (1 / 2) / (np.exp(E * xx * ms) - 1)

val, err = quad(integrand, ms, np.inf)
print(val)

0.16712443596152543


text:
Q: jQuery - How to find a class outside the parent div and click on a child class of another parent? I'm using jQuery to close the navigation in responsive view by triggering $(".navbar-toggle").click(). However I can't find a way to close the nav on click of drop down links and on click of the logo.
As this web app has been developed in Meteor the pages do not reload hence the navigation remains expanded.
The Problem:

*

*How to collapse the navigation on click of dropdown links?

*How to collapse the navigation on click of the logo if navigation is opened?

*How to collapse the navigation on click of the right nav dropdown links?

as .navbar-toggle is outside their respective parent divs I am not able to target them.
Below is my code :

$('.nav-link').on('click', function() {
  if ($(window).width() <= 990){
     $('.navbar-toggle').click()
  };
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        Toggle navigation

      </button>

        LOGO

          Dashboard

          Community

Teams

Events

Events

          User name

Profile settings

Change password

Sign out

A: All your points are working, Except one was partially working.  That is the point 3. How to collapse the navigation on click of the right nav dropdown links?
It was partially working because the links under the section community has the class nav-link-outside and not nav-link. So use the below selector in your jquery.

$('.nav-link,.nav-link-outside').on('click', function() {
  if ($(window).width() <= 990){
     $('.navbar-toggle').click()
  };
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        Toggle navigation

      </button>

        LOGO

          Dashboard

          Community

Teams

Events

Events

          User name

Profile settings

Change password

Sign out


text:
Q: Find nearby restaurants using MKLocalSearch/MapKit? I am using an MKLocalSearch to show nearby locations using Apple Maps and cannot find a way to filter for a specific type of place (restaurant/bar/eatery in my case). Is there a way to filter the results similarly to how Apple Maps App shows restaurants with an icon? I am currently filtering out empty subtitles and search nearby subtitles but this is not nearly specific enough. Code for the MKLocalSearch:
extension LocationService: MKLocalSearchCompleterDelegate {

    func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
        self.searchResults = completer.results.filter({ $0.subtitle != "Search Nearby" && $0.subtitle != "" })
        self.status = completer.results.isEmpty ? .noResults : .result
    }

    func completer(_ completer: MKLocalSearchCompleter, didFailWithError error: Error) {
        self.status = .error(error.localizedDescription)
    }
}

A: You are thinking about the wrong place in the search. You need to set the search request's pointOfInterestFilter before doing the search.


text:
Q: Call stored procedure from dapper which accept list of user defined table type I have a stored procedure InsertCars which accepts list of user defined table type CarType.
CREATE TYPE dbo.CarType
AS TABLE
(
    CARID int null,
    CARNAME varchar(800) not null,
);

CREATE PROCEDURE dbo.InsertCars
    @Cars AS CarType READONLY
AS
-- RETURN COUNT OF INSERTED ROWS
END

I need call this stored procedure from Dapper. I googled it and found some solutions.
 var param = new DynamicParameters(new{CARID= 66, CARNAME= "Volvo"});

 var result = con.Query("InsertCars", param, commandType: CommandType.StoredProcedure);

But I get an error:

Procedure or function InsertCars has too many arguments specified

Also stored procedure InsertCars returns the count of inserted rows; I need get this value.
Where is the root of problem?
My problem is also that I have cars in generic list List<Car> Cars and I want pass this list to store procedure. It exist elegant way how to do it ?
public class Car
{
    public CarId { get; set; }
    public CarName { get; set; }
}

Thank you for help
EDITED
I found solutions
Does Dapper support SQL 2008 Table-Valued Parameters?
or
Does Dapper support SQL 2008 Table-Valued Parameters 2?
So I try make own stupid helper class
class CarDynamicParam : Dapper.SqlMapper.IDynamicParameters
{
    private Car car;

    public CarDynamicParam(Car car)
    {
        this.car = car;
    }

    public void AddParameters(IDbCommand command, SqlMapper.Identity identity)
    {
        var sqlCommand = (SqlCommand)command;

        sqlCommand.CommandType = CommandType.StoredProcedure;

        var carList = new List<Microsoft.SqlServer.Server.SqlDataRecord>();

        Microsoft.SqlServer.Server.SqlMetaData[] tvpDefinition =
                                                                {

                                                                    new Microsoft.SqlServer.Server.SqlMetaData("CARID", SqlDbType.Int),
                                                                    new Microsoft.SqlServer.Server.SqlMetaData("CARNAME", SqlDbType.NVarChar, 100),
                                                                };

        var rec = new Microsoft.SqlServer.Server.SqlDataRecord(tvpDefinition);
        rec.SetInt32(0, car.CarId);
        rec.SetString(1, car.CarName);

        carList.Add(rec);

        var p = sqlCommand.Parameters.Add("Cars", SqlDbType.Structured);
        p.Direction = ParameterDirection.Input;
        p.TypeName = "CarType";
        p.Value = carList;
    }
}

Use
var result = con.Query("InsertCars", new CarDynamicParam(car), commandType: CommandType.StoredProcedure);

I get exception

When using the multi-mapping APIs ensure you set the splitOn param if you have keys other than Id.

StackTrace:
   at Dapper.SqlMapper.GetDynamicDeserializer(IDataRecord reader, Int32 startBound, Int32 length, Boolean returnNullIfFirstMissing) in c:\Dev\Dapper\Dapper\SqlMapper.cs:line 1308
   at Dapper.SqlMapper.GetDeserializer(Type type, IDataReader reader, Int32 startBound, Int32 length, Boolean returnNullIfFirstMissing) in c:\Dev\Dapper\Dapper\SqlMapper.cs:line 1141
   at Dapper.SqlMapper.<QueryInternal>d__d`1.MoveNext() in c:\Dev\Dapper\Dapper\SqlMapper.cs:line 819
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at Dapper.SqlMapper.Query[T](IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType) in c:\Dev\Dapper\Dapper\SqlMapper.cs:line 770
   at Dapper.SqlMapper.Query(IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType) in c:\Dev\Dapper\Dapper\SqlMapper.cs:line 715

What is wrong?
FIXED:
Call con.Execute instead con.Query

A: You can use Query methods, too, as well as Execute. The parameter has to be of type DataTable and it can be provided as a part of an anonymous parameter collection. And if your need is simple and you don't need a generic solution to building the DataTable, a small non-generic function is the easiest:
private DataTable CreateDataTable( IEnumerable<AlertChannelContainer> alertData )
{
    DataTable table = new DataTable();
    table.Columns.Add( "ChannelOrdinal", typeof( int ) );
    table.Columns.Add( "Value", typeof( decimal ) );

    foreach ( var alertChannel in alertData )
    {
        var dataRow = table.NewRow();
        dataRow["ChannelOrdinal"] = alertChannel.ChannelOrdinal;
        dataRow["Value"] = alertChannel.Value;
            table.Rows.Add( dataRow );
    }

    return table;
}

Then just call it like this:
var result = await connection.QuerySingleAsync<AlertMetadata>(
    "[dbo].[InsertAlert]",
    new
    {
        eventId,
        deviceId,
        timestamp,
        alertThresholds = JsonConvert.SerializeObject( rules ),
        data = CreateDataTable( alertData )
    },
    commandType: CommandType.StoredProcedure );

A:
My problem is also that I have cars in generic list List Cars and I want pass this list to stored procedure. It exist elegant way how to do it ?

You need to convert your generic list Car to a datatable and then pass it to storedprocedure.  A point to note is that the order of your fields must be same as defined in the user defined table type in database. Otherwise data will not save properly. And it must have same number of columns as well.
I use this method to convert List to DataTable. You can call it like yourList.ToDataTable()
public static DataTable ToDataTable<T>(this List<T> iList)
    {
        DataTable dataTable = new DataTable();
        PropertyDescriptorCollection propertyDescriptorCollection =
            TypeDescriptor.GetProperties(typeof(T));
        for (int i = 0; i < propertyDescriptorCollection.Count; i++)
        {
            PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
            Type type = propertyDescriptor.PropertyType;

            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                type = Nullable.GetUnderlyingType(type);

            dataTable.Columns.Add(propertyDescriptor.Name, type);
        }
        object[] values = new object[propertyDescriptorCollection.Count];
        foreach (T iListItem in iList)
        {
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = propertyDescriptorCollection[i].GetValue(iListItem);
            }
            dataTable.Rows.Add(values);
        }
        return dataTable;
    }

A: I know this is a little old, but I thought I would post on this anyway since I sought out to make this a little easier.  I hope I have done so with a NuGet package I create that will allow for code like:
public class CarType
{
  public int CARID { get; set; }
  public string CARNAME{ get; set; }
}

var cars = new List<CarType>{new CarType { CARID = 1, CARNAME = "Volvo"}};

var parameters = new DynamicParameters();
parameters.AddTable("@Cars", "CarType", cars)

 var result = con.Query("InsertCars", parameters, commandType: CommandType.StoredProcedure);

NuGet package: https://www.nuget.org/packages/Dapper.ParameterExtensions/0.2.0
Still in its early stages so may not work with everything!
Please read the README and feel free to contribute on GitHub: https://github.com/RasicN/Dapper-Parameters

A: Using reflection to map object properties to datatable columns is expensive. Taking Ehsan's solution further, where performance is a concern you can cache the type property mappings. As Ehsan also pointed out, the order in the class must be the same as in the database and there must be an equal number of columns. This can be overcome by reordering the columns according to the type definition.
public static class DataTableExtensions
{
    private static readonly EntityPropertyTypeMap PropertyTypeMap = new EntityPropertyTypeMap();

    public static DataTable ToDataTable<T>(this ICollection<T> values)
    {
        if (values is null)
        {
            throw new ArgumentNullException(nameof(values));
        }

        var table = new DataTable();

        var properties = PropertyTypeMap.GetPropertiesForType<T>().Properties;

        foreach (var prop in properties)
        {
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        }

        foreach (var value in values)
        {
            var propertyCount = properties.Count();
            var propertyValues = new object[propertyCount];

            if (value != null)
            {
                for (var i = 0; i < propertyCount; i++)
                {
                    propertyValues[i] = properties[i].GetValue(value);
                }
            }

            table.Rows.Add(propertyValues);
        }

        return table;
    }
}

public static class DapperExtensions
{
    private static readonly SqlSchemaInfo SqlSchemaInfo = new SqlSchemaInfo();

    public static DataTable ConvertCollectionToUserDefinedTypeDataTable<T>(this SqlConnection connection, ICollection<T> values, string dataTableType = null)
    {
        if (dataTableType == null)
        {
            dataTableType = typeof(T).Name;
        }

        var data = values.ToDataTable();

        data.TableName = dataTableType;

        var typeColumns = SqlSchemaInfo.GetUserDefinedTypeColumns(connection, dataTableType);

        data.SetColumnsOrder(typeColumns);

        return data;
    }

    public static DynamicParameters AddTableValuedParameter(this DynamicParameters source, string parameterName, DataTable dataTable, string dataTableType = null)
    {
        if (dataTableType == null)
        {
            dataTableType = dataTable.TableName;
        }

        if (dataTableType == null)
        {
            throw new NullReferenceException(nameof(dataTableType));
        }

        source.Add(parameterName, dataTable.AsTableValuedParameter(dataTableType));

        return source;
    }

    private static void SetColumnsOrder(this DataTable table, params string[] columnNames)
    {
        int columnIndex = 0;

        foreach (var columnName in columnNames)
        {
            table.Columns[columnName].SetOrdinal(columnIndex);
            columnIndex++;
        }
    }
}

class EntityPropertyTypeMap
{
    private readonly ConcurrentDictionary<Type, TypePropertyInfo> _mappings;

    public EntityPropertyTypeMap()
    {
        _mappings = new ConcurrentDictionary<Type, TypePropertyInfo>();
    }

    public TypePropertyInfo GetPropertiesForType<T>()
    {
        var type = typeof(T);
        return GetPropertiesForType(type);
    }

    private TypePropertyInfo GetPropertiesForType(Type type)
    {
        return _mappings.GetOrAdd(type, (key) => new TypePropertyInfo(type));
    }
}

class TypePropertyInfo
{
    private readonly Lazy<PropertyInfo[]> _properties;
    public PropertyInfo[] Properties => _properties.Value;

    public TypePropertyInfo(Type objectType)
    {
        _properties = new Lazy<PropertyInfo[]>(() => CreateMap(objectType), true);
    }

    private PropertyInfo[] CreateMap(Type objectType)
    {
        var typeProperties = objectType
            .GetProperties(BindingFlags.DeclaredOnly |
                           BindingFlags.Public |
                           BindingFlags.Instance)
            .ToArray();

        return typeProperties.Where(property => !IgnoreProperty(property)).ToArray();
    }

    private static bool IgnoreProperty(PropertyInfo property)
    {
        return property.SetMethod == null || property.GetMethod.IsPrivate || HasAttributeOfType<IgnorePropertyAttribute>(property);
    }

    private static bool HasAttributeOfType<T>(MemberInfo propInfo)
    {
        return propInfo.GetCustomAttributes().Any(a => a is T);
    }
}

public class SqlSchemaInfo
{
    private readonly ConcurrentDictionary<string, string[]> _udtColumns = new ConcurrentDictionary<string, string[]>();

    public string[] GetUserDefinedTypeColumns(SqlConnection connection, string dataTableType)
    {
        return _udtColumns.GetOrAdd(dataTableType, (x) =>
            connection.Query<string>($@"
                    SELECT name FROM
                    (
                        SELECT column_id, name
                        FROM sys.columns
                        WHERE object_id IN (
                          SELECT type_table_object_id
                          FROM sys.table_types
                          WHERE name = '{dataTableType}'
                        )
                    ) Result
                    ORDER BY column_id").ToArray());
    }
}

[AttributeUsage(AttributeTargets.Property)]
public sealed class IgnorePropertyAttribute : Attribute
{

}

A: Adding to Ehsan & Pawan Nepal answer above, I came up with a solution which works for .NET Core and .NET both. Below are the steps to do this.
1.Create Extension method to convert model to Data Table ( Thanks to Ehsan for providing extension method above).
public static DataTable ToDataTable<T>(this List<T> iList)
    {
        DataTable dataTable = new DataTable();
        PropertyDescriptorCollection propertyDescriptorCollection =
            TypeDescriptor.GetProperties(typeof(T));
        for (int i = 0; i < propertyDescriptorCollection.Count; i++)
        {
            PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
            Type type = propertyDescriptor.PropertyType;

            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                type = Nullable.GetUnderlyingType(type);

            dataTable.Columns.Add(propertyDescriptor.Name, type);
        }
        object[] values = new object[propertyDescriptorCollection.Count];
        foreach (T iListItem in iList)
        {
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = propertyDescriptorCollection[i].GetValue(iListItem);
            }
            dataTable.Rows.Add(values);
        }
        return dataTable;
    }

2.Convert model to data table.
var cars = new List<CarType>{new CarType { CARID = 1, CARNAME = "Volvo"}};
DataTable dt = cars.ToDataTable();

3.Finally add UDT as Dynamic parameter & pass it to the Query
 var parameters = new DynamicParameters();
 parameters.Add("@paramFromStoredProcedure",
 dt.AsTableValuedParameter("YourUDTNameInDataBase"));
 //Pass it to query
var result = con.Query<dynamic>("InsertCars", parameters , commandType: CommandType.StoredProcedure);

A: The other solution would be to call it like this
var param = new DynamicParameters(new{CARID= 66, CARNAME= "Volvo"});

var result = con.Query<dynamic>("InsertCars", param);

Remove : new CarDynamicParam(car), commandType: CommandType.StoredProcedure
Use the parameter of table type directly, it will work.
If you can use Datatable(.net core does not support it), then its very easy.
Create DataTable -> Add required columns to match with your table type -> Add required rows. Finally just call it using dapper like this.
var result = con.Query<dynamic>("InsertCars", new{paramFromStoredProcedure=yourDataTableInstance}, commandType: CommandType.StoredProcedure);

A: Adding to JCisar result above, you can create a generic function which can be used both for single parameters and list here it is. You can set return type to your expected result.
to call it you can do
var cars = new List<CarType>{new CarType { CARID = 1, CARNAME = "Volvo"}};
var parameters = new DynamicParameters();
parameters.AddTable("@Cars", "CarType", cars)

//Call Function
ExecuteStordProcedureDynamic("ProcedureName", parameters)

public IEnumerable<T> ExecuteStordProcedureDynamic<T>(String ProcedureName, DynamicParameters Param) where T : class
        {
            using (SqlConnection conn = new SqlConnection(ConnectionString))
            {
                conn.Open();

                var result= conn.Query<T>(ProcedureName, Param, commandType: CommandType.StoredProcedure);
                return result;
            }
        }


text:
Q: SQL sum statement works weirdly I am trying to use the sum statement in mysql but with no luck . Below is my query , I just want the qty field in the production order to get added up when the sales order number field and item matches ,the below query returns only one row adding up all the production order qty issued so far . I do have around 2000 sales orders and 3500 productions orders were issued pertaining to the sales order .
Any help would really be a life saver .
select
 `tabSales Order`.`name` as "Sales Order:Link/Sales Order:120",
`tabSales Order`.`customer` as "Customer:Link/Customer:120",
 `tabSales Order Item`.item_code as "Item:Link/Item:120",
`tabSales Order Item`.item_name as "Des:Link/Item:120",
`tabSales Order Item`.qty as "Qty:Float:100",
 `tabSales Order Item`.delivered_qty as "Delivered Qty:Float:100",
 (`tabSales Order Item`.qty - ifnull(`tabSales Order Item`.delivered_qty, 0)) as "Qty to Deliver:Float:140",
`tabSales Order Item`.date as "Sch date:Date:100",
`tabItem`.thumbnail as "Cut wt:Data:60",
`tabProduct master`.grade as "Grade:Data:100",
`tabProduct master`.dieno as "Die no:Data:100",
`tabProduct master`.hammer as "Hammer:Data:50",
`tabProduct master`.rm_idl_cs as "Idl sec:Data:60",
`tabProduct master`.rm_alt_cs as "Alt sec:Data:60",
SUM(CASE WHEN `tabSales Order`.`name` = `tabProduction Order`.`sales_order` and `tabSales Order Item`.`item_code` = `tabProduction Order`.`production_item`
         THEN `tabProduction Order`.`qty`
    END) as "Issued:Int:80"

from
 `tabSales Order`
LEFT JOIN `tabSales Order Item` ON ( `tabSales Order Item`.`parent` = `tabSales Order`.`name`
 and `tabSales Order`.docstatus = 1 and `tabSales Order`.status not in ("Stopped", "Closed") and ifnull(`tabSales Order Item`.delivered_qty,0) < ifnull(`tabSales Order Item`.qty,0))
LEFT JOIN `tabItem` ON `tabItem`.`item_code` = `tabSales Order Item`.`item_code`
LEFT JOIN `tabProduct master` ON `tabProduct master`.`part_no` = `tabSales Order Item`.`item_code`
LEFT JOIN `tabProduction Order` ON (`tabSales Order Item`.`item_code` = `tabProduction Order`.`production_item` and `tabSales Order`.`name` = `tabProduction Order`.`sales_order`)

Thanks in advance

A: if you query return only one row it's because you are using aggregate function without group by statement.
if you want to put a condition based on aggregate function you should use
having after group by

group by  col1, col2,..
having sum(col1) > 1


text:
Q: Neural Net Matrix Multiplication I'm trying to figure out the matrix multiplications for the implementation of a single hidden layer neural net for MNIST digit recognition in Python.
Like the following:
               h1
x1                            z1
               h2
x2                            z2
 1             h3

                1

I'm using a hidden layer of size 200.
The number of features for the digits is 784.
The number of classes is 10.
Each label is transformed to a vector of length 10 which has a single 1 in the position of the true class and 0 elsewhere.
Between the input and the hidden layer, I'm going to use a 200 by 785 matrix V.
Matrix V: the i, j - entry represents the weight connecting the jth unit in the input layer to the ith unit in the hidden layer. The ith row of V represents the ensemble of weights feeding into the ith hidden unit.
Between the hidden the the output layer, I'm going to apply a matrix W, which is 10 by 201.
Matrix W: the i, j - entry represents the weight connecting the jth unit in the hidden layer to the ith unit in the output layer. The ith row of W is the emsemble of weights feeding into the ith output unit.
So I start with the input matrix, which is n by 784. Can someone explain what to do? What do I need to multiply it by, and then what/how do I multiply the result by? I'm not sure how exactly to multiply these matrices.
(Let's just call the activation functions f().)
I'm a bit confused by the dimensions of the matrices and not sure when /where/ how exactly to use V and W.

A: I assume you are just asking how to perform a feedforward pass.
Let's say your input matrix is X [n by 784]

*

*add a column of ones on the left of X to make it [n by 785] for the biases

*Hidden weighted input are Z = X*V' [n by 200]

*Apply non-linearity to all elements of H to get hidden activations A = f(Z)

*Get output as f(A*W') [n by 10] where this last f is probably a softmax output layer computation to get posterior probabilites for every class


text:
Q: Python: function to Add logging for SQL queries to web server I Need to add logging all SQL queries to database with timings.

This log should be in csv format with columns:
url
datasource name
SQL content     parameters
username
start time of query execution (accuracy in ms)
end time of query execution (accuracy in ms)

I Need an example for this that How can I do this?
This logfile can be used to analyze timings for execution all SQL queries and optimize most long queries.


text:
Q: How to determinate the minimum period of oscillation for a physical pendulum?
A physical pendulum consists of a thin homogeneous rod of length $l$, suspended by a point $O$ at a distance $x$ from the center of gravity ($x<\frac{l}{2}$), oscillating in a vertical plane. For which value of $x$ the period of oscillation is minimum?

I'm having trouble to solve this.
Denoting the torque by $\Gamma$ and the angular displacement by $\theta$, we would have:
$$ \Gamma = I\ddot\theta$$
$$ \Gamma = -mgx\sin\theta \approx -mgx\theta$$  (considering $\theta \ll 1$)
Both equations give the O.D.E
$$\ddot\theta+\frac{mgx}{I}\theta = 0$$
We would have solutions of the form $$\theta = A\cos(\omega t+\phi)$$ where $$\omega = \sqrt{\frac{mgx}{I}}$$
The period is $$\tau =\frac{ 2\pi}{|\omega|} = 2\pi\sqrt{\frac{I}{mgx}}$$
The moment of inertia $I$ would be $\frac{ml^2}{12}+mx^2$, by the parallel axis theorem.
I stopped here because I can't find what value of $x$ would minimize the period $\tau$.
How should I continue? If someone knows a different approach to solve this, it would be also welcome.

A: You are really close. At this point you have an expression for $\tau$ which you need to minimize with respect to $x$ - you just didn't take the last step, which is writing $I$ as a function of $x$ in that expression:
$$\tau = 2\pi \sqrt{\frac{\ell^2/12 + x^2}{gx}}$$
A minimum / maximum will occur when $\frac{d\tau}{dx}=0$. To keep your life simple it's worth noticing that if $f(x)$ has a maximum at $x_0$, then $\sqrt{f(x)}$ will also have a maximum at $x_0$. So we can take away some of the fluff and look for the maximum of
$$\frac{\ell^2/12 + x^2}{gx}$$
I trust you can differentiate this w.r.t. x and set the result = 0 and solve. Finally, you need to convince yourself that you have found a maximum (either by plotting the graph, or by computing the second derivative and showing it's <0).

A: You may want to put the moment of inertia $$I(x) = a + b  x ^ 2$$ into the formula for $\tau$, then differentiate with respect to $x$ and find out the $x$, for which $$\frac{d \tau}{dx} = 0$$


text:
Q: Pointwise limit of the sequence of functions $h_n(x)=1,\, \forall x\ge 1/n$ and $h_n(x)=nx,\,\forall x\in[0,1/n)$ Pointwise limit of the sequence of functions
$$h_n(x)=\begin{cases}1,&\text{if }x\ge \frac1n\\nx,&\text{if }x\in[0,\frac1n)\end{cases}$$
The trouble with this question is that I think that $h(0)$ is not defined but Im not completely sure. We can see that for any $n\in\Bbb N$ we have that $h_n(0)=0$. But the sequence $h_n(x)=1$ is approaching to zero as well but only reach zero in the limit cause $\lim 1/n=0$.
Are my assumptions correct? It is $h(0)$ undefined?

A: Assuming that by $h$ you mean the pointwise limit of $(h_n)$: no, $h(0)$ is defined. In fact, $h(0) :=\lim_{n \to \infty} h_n(0) = 0$.
What is confusing you is that $h$ is not continuous. We have for $x > 0$, there exists $k \in \Bbb N$ such that $x > 1/k$, so $h_n(x) = 1$ for all $n \ge k$, thus $h_n(x) \to 1$. This shows that:
$$h(x) = \begin{cases} 0, x = 0 \\ 1, x > 0 \end{cases}$$

A: You have $h_1(0)=0$, $h_2(0)=0$, $h_3(0)=0$, $h_4(0)= 0$, etc.  So the sequence $h_1(0), h_2(0), h_3(0), h_4(0), h_5(0),\ldots$ is just the sequence $0,0,0,0,0,\ldots$ in which every term is $0$.  That sequence does have a limit and the limit is $0$.  In other words $\lim_{n\to\infty} h_n(0) = 0$.  The limit does exist and is $0$.
If $x>0$, then $\lim_{n\to\infty} h_n(x)=1$.  So this is an example of a sequence of continuous functions converging pointwise to a discontinuous function.


text:
Q: Mongoid find or create with embedded hash Using Mongoid (3.1.6)
I have a collection with the following fields:
field :project, type: String
field :date_hierarchy, type: Hash, default: {year: 0, semester: 0, quarter: 0, month: 0, day: 0}

I want to find a document with project: "1", date_hierarchy: {year: 2013, semester:2, quarter: 4, month: 11, day: 12}
and if the document is not found the i want it to be created
How can I do this?
I have tried these and non of them work
MyModel.where(:project=>"1", "date_hierarchy.year"=>2013, "date_hierarchy.semester"=>2, "date_hierarchy.quarter"=>4, "date_hierarchy.month"=>11, "date_hierarchy.day"=>25).first_or_create!

MyModel.where(:project=>"1", "date_hierarchy.year"=>2013, "date_hierarchy.semester"=>2, "date_hierarchy.quarter"=>4, "date_hierarchy.month"=>11, "date_hierarchy.day"=>25).find_or_create_by("date_hierarchy.year"=>2013, "date_hierarchy.semester"=>2, "date_hierarchy.quarter"=>4, "date_hierarchy.month"=>11, "date_hierarchy.day"=>25).

A: You need pass the date_hierarchy value as a hash, as you would pass to new() or create():
MyModel.find_or_create_by({
  project: '1',
  date_hierarchy: {year: 2013, semester: 2, quarter: 4, month: 11, day: 25}
})


text:
Q: Ormlite and PostgreSQL - Error inserting text array with custom persister I have been working to setup Ormlite as the primary data access layer between a PostgreSQL database and Java application.  Everything has been fairly straightforward, until I started messing with PostgreSQL's array types.  In my case, I have two tables that make use of text[] array type.  Following the documentation, I created a custom data persister as below:
public class StringArrayPersister extends StringType {

    private static final StringArrayPersister singleTon = new StringArrayPersister();

    private StringArrayPersister() {
        super(SqlType.STRING, new Class<?>[]{String[].class});
    }

    public static StringArrayPersister getSingleton() {
        return singleTon;
    }

    @Override
    public Object javaToSqlArg(FieldType fieldType, Object javaObject) {
        String[] array = (String[]) javaObject;

        if (array == null) {
            return null;
        } else {

            String join = "";
            for (String str : array) {
                join += str +",";
            }

            return "'{" + join.substring(0,join.length() - 1) + "}'";
        }

    }

    @Override
    public Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos) {
        String string = (String) sqlArg;

        if (string == null) {
            return null;
        } else {
            return string.replaceAll("[{}]","").split(",");
        }
    }
}

And then in my business object implementation, I set up the persister class on the column likeso:
   @DatabaseField(columnName = TAGS_FIELD, persisterClass = StringArrayPersister.class)
    private String[] tags;

When ever I try inserting a new record with the Dao.create statement, I get an error message saying tags is of type text[], but got character varying... However, when querying existing records from the database, the business object (and text array) load just fine.
Any ideas?
UPDATE:
PostGresSQL 9.2.  The exact error message:

Caused by: org.postgresql.util.PSQLException: ERROR: column "tags" is
  of type text[] but expression is of type character varying   Hint: You
  will need to rewrite or cast the expression.

A: I've not used ormlite before (I generally use MyBatis), however, I believe the proximal issue is this code:
 private StringArrayPersister() {
        super(SqlType.STRING, new Class<?>[]{String[].class});
    }

SqlType.String is mapped to varchar in SQL in the ormlite code, and so therefore I believe is the proximal cause of the error you're getting. See ormlite SQL Data Types info for more detail on that.
Try changing it to this:
private StringArrayPersister() {
        super(SqlType.OTHER, new Class<?>[]{String[].class});
    }

There may be other tweaks necessary as well to get it fully up and running, but that should get you passed this particular error with the varchar type mismatch.


text:
Q: Updating badge in a timed notification in swift 3? I have been trying out  Notification coding just to be able to add some to my app, however the big issue is,  I can say ,

something.badge = 3

and such, but I can't say

something.badge +=1

or

something.badge = badge +1

so far, my code is like this
@IBAction func sendNotification(_ sender: Any) {// in this button you make a notification

      UIApplication.shared.applicationIconBadgeNumber = 1
    let asnwer1 = UNNotificationAction(identifier: "asnwer1",  title: "You are",  options: UNNotificationActionOptions.foreground)
    let asnwer2 = UNNotificationAction(identifier: "asnwer2", title: "Obviously you fucking are!" , options: UNNotificationActionOptions.foreground)
    let category = UNNotificationCategory(identifier: "myCategory", actions: [asnwer1, asnwer2], intentIdentifiers: [], options: [])
    UNUserNotificationCenter.current().setNotificationCategories([category])
   // created nitification

    let content = UNMutableNotificationContent()
    content.title = "Are you pathetic for not working out??"
    content.subtitle = "are you?? "
    content.body = "Are you sure?"
    content.categoryIdentifier = "myCategory"
    /////// THIS NEEDS IMPROVEMENT
    if  UIApplication.shared.applicationIconBadgeNumber == 1{
            content.badge = 2
    }
    if  UIApplication.shared.applicationIconBadgeNumber == 2{
        content.badge = 3
    }
    if  UIApplication.shared.applicationIconBadgeNumber == 3{
        content.badge = 4
    }
    if  UIApplication.shared.applicationIconBadgeNumber == 4{
        content.badge = 5
    }
    if  UIApplication.shared.applicationIconBadgeNumber == 5{
        content.badge = 6
    }
    if  UIApplication.shared.applicationIconBadgeNumber == 6{
        content.badge = 7
    }
    if  UIApplication.shared.applicationIconBadgeNumber == 7{
        content.badge = 8
    }
    if  UIApplication.shared.applicationIconBadgeNumber >= 8{
        content.badge = 9
    }

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
    let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)// the previous lne created a let named request...youre using it here
}

The problem here is, I keep on saying, if       the badge number is THAT specific number, make it That other specific number....is there any other way around it?

A: I assume you want to simplify how to write all those conditions.
How about:
content.badge = Swift.min(9, UIApplication.shared.applicationIconBadgeNumber + 1)

Then no if clause needs to be written.


text:
Q: Data recovery after Copying file to block device I have an NTFS formatted USB Hard drive that has my personal files backup.
Today I mounted the drive to an Oracle Linux system and copied a regular file using the below command (please see below commands). By mistake I used the device file /dev/sdb1 during copy.
mount -t ntfs-3g /dev/sdb1 /sample
cp file1 /dev/sdb1

After this I unmounted the drive and connected to Windows system. Now Windows system complains that the drive need to be formatted and/or corrupted.
My question is: can we recover this drive without losing any personal data? How can I view the files available on this drive? Just mounting back to Linux system will show the files?

A: I answered to a very similar question on the Software Recommendations Q&A website.
The files you lost

Can we recover this drive without losing any personal data?

If by "personal data" you mean user generated data (excluding system files) then this might be the case, however only if your NTFS drive contained a OS (probably Windows). Assuming the file you wrote was not very big, you didn't overwrite more than the first 4-5 GB of the file system, which would have been occupied by Windows.
If your drive contained user files only, then it's almost sure you lost a few of them, to say the least.
Do not try to mount the partition

How can I view the files available on this drive? Just mounting back to Linux system will show the files?

No, don't do that. If you want to maximize the amount of data recovered, do not try to access the drive again using normal tools. Do not try to fix it using fsck or similar programs.
Clone the drive
You should first clone the drive and avoid attempting recovery on the original one. You can use ddrescue to perform a copy even if the drive has hardware damages (yours doesn't, but it is still a useful tool):
ddrescue /dev/sda /media/user/External/copy.img /media/user/External/status.log

See my answer to Raw copy from failed hard disk for a detailed explanation.
Restore files from the copy

Disclaimer: I am the author of RecuperaBit.

Now you can try to recover files from copy.img. If you ruined only the very beginning of the partition, let's say up to a few megabytes, you will probably be able to restore it with testdisk:
testdisk copy.img

The program searches for the backup NTFS boot sector and it tries to read the partition contents. You can list the files by pressing P after it has analyzed the drive and you are highlighting the right partition.
If this works, you can use the C button to copy one or more files/folders. The textual interface shows a step-by-step process which is not difficult to follow.
If the damage is severe and Testdisk cannot mount the partition, you can recover the files using RecuperaBit, but the process will take more time. RecuperaBit attempts to reconstruct file system structures and recover files. Currently it supports only NTFS. RecuperaBit attempts reconstruction of the directory structure regardless of:

*

*missing partition table

*unknown partition boundaries

*partially-overwritten metadata

*quick format

You can start the analysis with:
mkdir /media/user/External/recovered_files
cd [full path of recuperabit]
pypy main.py /media/user/External/copy.img -o /media/user/External/recovered_files -s /media/user/External/savefile.save

Then type recoverable and detect the id of your partition. Assuming it is 2, type:
restore 2 5
restore 2 -1

To restore the files that are reachable from the root (5) and those that are not (-1). Again, see my original answer for additional details and a few caveats that you may encounter.

A: You definitively overwrote/corrupted the partition. No need trying to mount it elsewhere. It won't mount in Linux.
Whether or not you are lucky is highly dependent on the size of the file.
If the file is (very) small (KB), I would try in Windows software to try to fix the partition. For instance, http://www.ntfs.com/recovery-toolkit.htm
If the file is reasonably big, all bets are off. It would have erased the major blocks of the start of your filesystem, and whilst the files are still there, it won't be a simple task getting them back. Usually that involves specialised professional services that are (very) well paid.

A: To recover files you need to use file recovery software:
https://www.runtime.org/data-recovery-software.htm - for windows
is a good choice from old experience, there might be better ones nowadays.
As it is NTFS, I'd avoid Linux software for that particular partition.
And with all this; you always need enough extra disk space to save the recovered files while you're doing the recovery.


text:
Q: Connect existing Drupal page with PhoneGap iOS App Case:
I have an existing page based on Drupal and going to develop a phoneGap iOS App. That means I just need the information of the existing page and want to fill these data in the new app.
My Question is now, do somebody know weather there is a work around or work flow to do so resp. how can I connect the existing page with another page or in my case phoneGap to get just the data? I'm new with Drupal and phoneGap so maybe you have some pages with information, tutorials or some help how to do this.
Thanks in advance yves

A: Drupal offers a module called "Services" which will allow you to get data or services from your website. You may need to create your own methods on that module to get the information you want to retrieve.
As for the iOS side, you can retrieve the data via XML-RPC, Rest or whatever communication protocol you choose at the server side, or go all the way with drupal-ios.
https://github.com/workhabitinc/drupal-ios-sdk/
You should start looking for the Services module and play with it. You will have an embedded console on that module to test the methods.
Once you're finish with that, take a look at drupal-ios or go deep with your own implementation via XML-RPC or whatever.


text:
Q: Symfony 3.4 No Metadata Classes to process Error I have installed symfony 3.4 and doctrine packages
"php": ">=5.5.9",
        "doctrine/doctrine-bundle": "^1.8",
        "doctrine/doctrine-migrations-bundle": "^1.3",
        "doctrine/orm": "^2.5",
        "incenteev/composer-parameter-handler": "^2.0",
        "sensio/distribution-bundle": "^5.0.19",
        "sensio/framework-extra-bundle": "^5.0.0",
        "symfony/monolog-bundle": "^3.1.0",
        "symfony/polyfill-apcu": "^1.0",
        "symfony/swiftmailer-bundle": "^2.6.4",
        "symfony/symfony": "3.4.*",
        "twig/twig": "^1.0||^2.0"

Created database using following command
php bin/console doctrine:database:create

G:\XAMPP\htdocs\project>php bin/console doctrine:schema:validate
[Mapping]  OK - The mapping files are correct.
[Database] OK - The database schema is in sync with the mapping files.

G:\XAMPP\htdocs\project>php bin/console doctrine:schema:validate
[Mapping]  OK - The mapping files are correct.
[Database] OK - The database schema is in sync with the mapping files.

G:\XAMPP\htdocs\project>php bin/console doctrine:schema:update --force
No Metadata Classes to process.

G:\XAMPP\htdocs\project>

Whenever i ran php bin/console doctrine:schema:update --force command it will throw an error like

No Metadata Classes to process.

I created entity class as in the documentation
http://symfony.com/doc/3.4/doctrine.html
Product Entity class
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="product")
 */
class Product
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=100)
     */
    private $name;

    /**
     * @ORM\Column(type="decimal", scale=2)
     */
    private $price;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Product
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set price
     *
     * @param integer $price
     *
     * @return Product
     */
    public function setPrice($price)
    {
        $this->price = $price;

        return $this;
    }

    /**
     * Get price
     *
     * @return int
     */
    public function getPrice()
    {
        return $this->price;
    }
}

A: Yes finally i found the issue is with  John.orm.php file which will generated when i ran  php bin/console doctrine:generate:entity
I have created Entity class using following command
php bin/console doctrine:generate:entity

Then it will prompt to
Welcome to the Doctrine2 entity generator

This command helps you generate Doctrine2 entities.

First, you need to give the entity name you want to generate.
You must use the shortcut notation like AcmeBlogBundle:Post.

The Entity shortcut name: AppBundle:John

Determine the format to use for the mapping information.

Configuration format (yml, xml, php, or annotation) [annotation]: php

Instead of starting with a blank entity, you can add some fields now.
Note that the primary key will be added automatically (named id).

Available types: array, simple_array, json_array, object,
boolean, integer, smallint, bigint, string, text, datetime, datetimetz,
date, time, decimal, float, binary, blob, guid.

New field name (press <return> to stop adding fields): id
 Field "id" is already defined.
New field name (press <return> to stop adding fields): username
Field type [string]: string
Field length [255]:
Is nullable [false]: true
Unique [false]: false

New field name (press <return> to stop adding fields): password
Field type [string]:
Field length [255]:
Is nullable [false]: true
Unique [false]:

New field name (press <return> to stop adding fields): dob
Field type [string]: date
Is nullable [false]: true
Unique [false]:

New field name (press <return> to stop adding fields):

  Entity generation

  created .\src\AppBundle/Entity/John.php
  created .\src\AppBundle/Resources/config/doctrine/
  created .\src\AppBundle/Resources/config/doctrine/John.orm.php
> Generating entity class G:\XAMPP\htdocs\project\src\AppBundle\Entity\John.php:
 OK!
> Generating repository class G:\XAMPP\htdocs\project\src\AppBundle\Repository\J
ohnRepository.php: OK!
> Generating mapping file G:\XAMPP\htdocs\project\src\AppBundle\Resources\config
\doctrine\John.orm.php: OK!

  Everything is OK! Now get to work :).

G:\XAMPP\htdocs\project>

And after success it will will create entity class in  AppBundle\Entity;  folder and repository class in AppBundle\Repository; also it will generate John.orm.php in AppBundle\Resources\config\doctrine\John.orm.php
After deleting John.orm.php file if i run php bin/console doctrine:schema:update --force then it will generate tables.

A: Most of the time This error come because of entity path issue and cache. Entity php files must be in your specific folder. Normally we generate entities by command :
 doctrine:generate:entity

run command first
doctrine:cache:clear-metadata

and then try


text:
Q: If an element is wrapped by a label, does the label require the "for" attribute? Say I have a set of radio <input>s. I'm not a caveman, so I know I need to associate  with those <input>s. I'm fond of wrapping the radio buttons within their corresponding labels, for reasons enumerated here.
So, for example:
<fieldset>
    <legend>Should I provide a "for" attribute?</legend>
    <input type="radio" name="define_the_for_attribute" id="define_the_for_attribute_yes" value="yes" />Yep, if you know what's good for you
    <input type="radio" name="define_the_for_attribute" id="define_the_for_attribute_no" value="no" />Nah, that would be redundant and repetitive
</fieldset>

This wrapping associates the corresponding radio button with the label. Do I also need to define the label's for attribute?
<fieldset>
    <legend>Should I provide a "for" attribute?</legend>
    <input type="radio" name="define_the_for_attribute" id="define_the_for_attribute_yes" value="yes" />Yep, if you know what's good for you
    <input type="radio" name="define_the_for_attribute" id="define_the_for_attribute_no" value="no" />Nah, that would be redundant and repetitive
</fieldset>

As pointed out by @Peter, "The for attribute of the label element must refer to a form control" (see http://www.w3.org/TR/html-markup/label.html), but this could be read to mean "if you specify the optional for attribute, it must refer to a valid form control".

A: According to the HTML5 spec - "If the for attribute is not specified, but the label element has a labelable element descendant, then the first such descendant in tree order is the label element's labeled control."
http://www.w3.org/TR/html5/forms.html#category-label
So basically, no it is not required as long as it is wrapping any of these elements: button, input (if the type attribute is not in the hidden state), keygen, meter, output, progress, select, or textarea

A: By the specifications, you don't need the for attribute when the control element is wrapped inside a label element. This principle also applies to all modern browsers, though some very old versions of IE supported only the explicit association with for attributes.
People may still prefer to use the for attribute on logical grounds: a control is logically not part of a label, so it should be placed outside it. And then you need the for attribute in order to benefit from label markup at all.
The for attribute is necessarily when the control cannot be a descendant of a label element, e.g. when you have labels in one column of a table element, controls in another column.


text:
Q: Unique FormControl Names I upgraded my Angular project from 7 to 9. The upgrade has broken my custom directive because it appears that the lifecycle of objects is different.
My original problem is that I need to be to access form controls uniquely based on the data that is loaded. For example, the user loads 11 records and changes the name on record 8. I need to be able to access the form control for the 8th record.
I found a solution from a tutorial a while back. (I don't have the link anymore.) It uses a custom directive to add the form controls when the data is changed. The form control names have a unique name, such as "record8" for the 8th record. (My actual numbers aren't sequential.) It accesses formGroupDirective.form to get the FormGroup that contains the controls. In the newer Angular versions, the form property is null at this point.
I either need to fix my code or find a completely new solution to accomplish the same thing.
Here is a general look at my current solution:
my.component.ts
ngOnInit{
  // Build an empty array for the form controls
  this.myForm = this.formBuilder.group({
    records: this.formBuilder.group([])
  });
}

my.component.html
<form [connectMyForm]="myRecords$ | async" ...>
  ...
</form>

myconnect.directive.ts
@Directive({
  selector: '[connectMyForm]'
})

export class MyConnectDirective {
    constructor(private formGroupDirective: FormGroupDirective) { }

    @Input('connectMyForm')
    set data(values: any) {
        // Add uniquely named form controls based on the data that is passed in.
        // PROBLEM: this.formGroupDirective.form is now null at this point.
        let recordGroup = this.formGroupDirective.form.get('records') as FormGroup; //FAIL form is null
        recordGroup.controls = {}; //Remove anything existing.

        for (let value of values) {
            // Add form control with unique name.
        }
    }
}

Any help would be greatly appreciated.

A: In Angular 9 you can make sure that your component binding is executed after FormGroupDirective binding by placing [formGroup] before your directive binding:
<form [formGroup]="myForm" [connectMyForm]="myRecords$ | async">
      ^^^^^^^^^^^^^^
       goes first

Ng-run Example


text:
Q: What is the command to return to your main screen in an app? How do I have an app return to the 'Home' screen when the user is on a different class and they click the back/return button on their phone?
Right now, when they access a different class and hit the back button, it goes back to the Home screen on the Droid rather than the Home screen on the app - how do I get it to go back to the Home Screen on the app?
Thanks!

A: you can't,
the home button is the only you can't prevent form closing your app. Its done so that you can't block the user inside your applications (like a virus).
the other keys like back menu and research are possible
in your activity
@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN){
            if(keyCode == 82){
               Log.i("jason","released on menu");
               //change view
               //return so that the other behavior (leaving the activity) is not tirggered
               return false;
        }
        }
        Log.i("jason","actual key code "+keyCode);
        return super.onKeyDown(keyCode, event);
    }

A: Use OnBackPressed() method of Activity class.
Make conditions like :
public void onBackPressed(){
if(conditon)
  {
    detailInfoList.setVisibility(View.VISIBLE);//or anything that you want to show
  }
}


text:
Q: Get host from NodeJS request I have a basic http server that runs on a server where multiple domains point to. I need to find the host of the request (the domain where the request is coming from).
 require("http").createServer(function (req, res) {
     console.log(req.headers.host);
     res.end("Hello World!");
 }).listen(9000);

req.headers.host's value is 127.0.0.1:9000 instead of the domain name (example.com or so).
How can I get the domain name from request object?
The node server is proxied via nginx. The configuration is like this:
server {
   listen 80;
   server_name ~.*;
   location / {
       proxy_pass http://127.0.0.1:9000;
   }
}

A: The issue is that proxy_pass in nginx rewrites the host header to whatever host is referenced in your rewrite. If you want to override that behavior, you can manually override the host header of the outgoing - proxied - request using proxy_set_header;
server {
   listen 80;
   server_name ~.*;
   location / {
       proxy_pass http://127.0.0.1:9000;
       proxy_set_header Host $http_host;
   }
}

A somewhat more detailed explanation is available here.


text:
Q: Format the output of cputime for ps I'm trying to write a script that can monitor a process's CPU usage over an interval (to create a graph).
So far, this is the command I'm using
ps -p $PROCID -o cputime,etimes

My only concern is that the output of cputime appears to be [dd]hh:mm (or something similar, can't remember off the top of my head now)
Is there a way to format cputime in seconds, kind of like etime -> etimes to get elapsed time in seconds?
Edit: This is the output that I'm currently receiving
2-03:01:33 2653793

I'd like the first parameter to be formatted in seconds, not days-hours:minutes:seconds.

A: This converts the first time to seconds:
ps -p $PROCID -o cputime,etimes | awk -F'[: ]+' '/:/ {t=$3+60*($2+60*$1); print t,$NF}'

As an example, the ps command produces:
$ ps -p 5403 -o cputime,etimes
    TIME ELAPSED
01:33:38 1128931

The awk command processes that and returns:
ps -p 5403 -o cputime,etimes | awk -F'[: ]+' '/:/ {t=$3+60*($2+60*$1); print t,$NF}'
5618 1128931

Explanation

*

*-F'[: ]+'
This tells awk to treat both colons and spaces as field separators.  This way, the hours, minutes, and seconds appear as separate fields.

*/:/ {t=$3+60*($2+60*$1); print t,$NF}
The initial /:/ restricts the code to working only on lines that include a colon.  This removes the header lines.  The number of seconds is calculated from hours, minutes, seconds via t=$3+60*($2+60*$1).  The resulting value for t is then printed along side with the elapsed time.
Handling days
If ps produces days,hours,minutes,seconds, as in:
2-03:01:33

Then, use this code instead:
ps -p $PROCID -o cputime,etimes | awk -F'[-: ]+' '/:/ {t=$4+60*($3+60*($2+24*$1)); print t,$NF}'

If days may or may not be prepended to the output, then use this combination command:
ps -p $PROCID -o cputime,etimes | awk -F'[-: ]+' '/:/ && NF==5 { t=$4+60*($3+60*($2+24*$1)); print t,$NF} /:/ && NF==4 {t=$3+60*($2+60*$1); print t,$NF}'

A: If you don't want to bring awk in the game, a pure bash solution (t_str contains the formated string, t_sec the decoded time in seconds):
# Decode the CPU time format [dd-]hh:mm:ss.
IFS="-:" read c1 c2 c3 c4 <<< "$t_str"
if [ -n "$c4" ]
then
  t_sec=$((10#$c4+60*(10#$c3+60*(10#$c2+24*10#$c1))))
else
  t_sec=$((10#$c3+60*(10#$c2+60*10#$c1)))
fi

A: You don't specify which operating system this is for; if it is Linux, and given that you're interested in monitoring a specific process, you might find it more worthwhile to parse /proc/$PROCID/stat - see the proc(5) manual page for details.


text:
Q: How to save a Date in Firebase using Kotlin I am trying to save the date in Firebase and my app is crashing. Could someone please let me know what I'm doing wrong?
Here is my model
class Date (val id: String, val mDate: String)

Here is my MainActivity.kt
class MainActivity : AppCompatActivity() {
    internal lateinit var dpDate: DatePicker

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        dpDate = findViewById(R.id.dpDate) as DatePicker
    }

    private fun saveDate(v: View) {
        val builder = StringBuilder()
        builder.append("Current Date: ")
        builder.append((dpDate.month + 1).toString() + "/")//month is 0 based
        builder.append(dpDate.dayOfMonth.toString() + "/")
        builder.append(dpDate.year)

        val ref = FirebaseDatabase.getInstance().getReference("dates")
        val dateID = ref.push().key
        val mDate = builder.toString()
        val date = Date(dateID!!, mDate)
        ref.child(dateID).setValue(date).addOnCompleteListener {
            Toast.makeText(this, builder.toString(), Toast.LENGTH_SHORT).show()
        }
    }
}

Here is my main_activity.xml
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:padding="5dp"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

    <DatePicker
            android:id="@+id/dpDate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:datePickerMode="spinner"
            android:calendarViewShown="false"
    />

    <Button
            android:id="@+id/btnGet"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Save"
            android:onClick="saveDate"/>
</LinearLayout>

Here is what the error is in the logcat:

Process: com.simona.kotlin.datepicker, PID: 23537
     java.lang.IllegalStateException: Could not find method saveDate(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'btnGet'
          at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:424)
          at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:381)


text:
Q: passing the value of an array to a method in javascript I have to create an HTML table in which I will have images to display. further I want to pass this path to the next servlet page. for this I have created a separate method in javascript. Now the problem is this, whenever I click on any image it passes the same path everytime. please give me any solutions for this problem or tell me any alternate of passing the path to next page.
my code is--->
<%@page import = "java.util.*" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

        <link href="Style.css" rel="stylesheet" type="text/css"/>
        <title>Home</title>

${requestScope.payment}

            <jsp:include page="Header.jsp"/>
            <jsp:include page="Menu2.jsp"></jsp:include>
            <form method="post" action="ProductFeatures" id="myform">

            </form>
            <%
             ArrayList<String> l = null;
             if(request.getAttribute("list") instanceof ArrayList<?>){
                 l = (ArrayList<String>)request.getAttribute("list");
             }
             %>

            <jsp:include page="Footer.jsp"/>

Here in this code in function getDetails variable imagepath always contains the same value. please somebody tell me wheres the bug in this code. I am not getting it properly.

A: Change the following line:
image.setAttribute("onclick",function(){getDetails(data);});

into:
image.setAttribute("onclick",(function(d){return function(){getDetails(d);}}(data));

Also, the line:
row.appendChild(cell);

is redondant because the cell was inserted with row.insertCell(k)


text:
Q: How to print each element of a list on a new line in a nested list I wanted to print each individual element of a list that's in nested list. it should also print symbols to show where the different lists end. There are only going to be 3 lists total in the big list.
For Example,
list1 = [['assign1', 'assign2'], ['final,'assign4'], ['exam','study']]

Output should be:
######################
assign1
assign2
######################
----------------------
final
assign4
----------------------
*************************
exam
study
*************************

I know that to print an element in a normal list it is:
for element in list1:
print element
I am unaware of what steps to take next.

A: You can create another for loop around the one you know how to create. So:
for list2 in list1:
  # print some stuff here
  for word in list2:
    print(word)
  # print some more stuff

A: Assuming that there is a single nesting level.
symbols = "#-*"
list1 = [['assign1', 'assign2'], ['final', 'assign4'], ['exam','study']]
for i, element in enumerate(list1):
    symbol = symbols[i%len(symbols)]
    print(symbol*20)
    print('\n'.join(element))
    print(symbol*20)


text:
Q: dynamic buttons Android Layout I want to create a layout in Android in a java class. I need that the user introduce a number between 1 to 20 and this create the number of butttons that the user has chosen.I want to create dynamic buttons and I have this code:
package com.example.nuevo;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;

public class ControladorResuelto extends Activity {

protected Controlador controlador;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
     requestWindowFeature(Window.FEATURE_NO_TITLE);
      getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                         WindowManager.LayoutParams.FLAG_FULLSCREEN);

        LinearLayout buttonsLayout =  (LinearLayout)findViewById(R.id.linearlayoutUp);

    int nMallas = controlador.getnMallas();

    LinearLayout.LayoutParams layoutParams = new     LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    for(int i=0;i<nMallas;i++){
        Button button = new Button(this);
        button.setText("Buttin "+(i+1));
        buttonsLayout.addView(button, layoutParams);******
    }

    setContentView(R.layout.panel_resuelto);
}

I have an error at the line with asterisks

A: I'm pretty sure it's because you have setContentView(R.layout.panel_resuelto); at the end of your onCreate. Put it at the beginning, else findViewById won't work. I'm guessing you're getting a null pointer exception because the LinearLayout couldn't successfully be created since the content view wasn't set yet.


text:
Q: Redirect Page in PHP with User Input and new Session I need to get back to my previous page and display the input of user with display error.
What I did was this
pageone.php
$_SESSION['serial_validation']='validation';
header("location:javascript://history.go(-1)");

page2.php
if(isset($_SESSION["serial_validation"]))
{
echo $_SESSION["serial_validation"];
}

But the redirected page doesnt read the session, any idea on how to prompt this validation ?

A: Try something like this:
Data processing page:
<?php
session_start();

$_SESSION['errorMSg'] = 'Your message';
// set the error msg in session

$_SESSION['oldValue'] = 'Old value inputted by user';
// Old value inputted by user

header('location:url.php');
// redirect user to specified location

?>

url.php
<?php
session_start();

// check if error msg exist
if(isset($_SESSION['errorMSg']))
{
    echo $_SESSION['errorMSg'];
    // display error message

    echo '<input type="text" value="'. $_SESSION['oldValue'] .'" />';
    // In the same way you can get all old input value and set them
}

?>