Programs & Examples On #Jtable

JTable is a Java Swing component used to display and edit regular two-dimensional tables of cells.

Change the background color of a row in a JTable

The call to getTableCellRendererComponent(...) includes the value of the cell for which a renderer is sought.

You can use that value to compute a color. If you're also using an AbstractTableModel, you can provide a value of arbitrary type to your renderer.

Once you have a color, you can setBackground() on the component that you're returning.

Load arrayList data into JTable

"The problem is that i cant find a way to set a fixed number of rows"

You don't need to set the number of rows. Use a TableModel. A DefaultTableModel in particular.

String col[] = {"Pos","Team","P", "W", "L", "D", "MP", "GF", "GA", "GD"};

DefaultTableModel tableModel = new DefaultTableModel(col, 0);
                                            // The 0 argument is number rows.

JTable table = new JTable(tableModel);

Then you can add rows to the tableModel with an Object[]

Object[] objs = {1, "Arsenal", 35, 11, 2, 2, 15, 30, 11, 19};

tableModel.addRow(objs);

You can loop to add your Object[] arrays.

Note: JTable does not currently allow instantiation with the input data as an ArrayList. It must be a Vector or an array.

See JTable and DefaultTableModel. Also, How to Use JTable tutorial

"I created an arrayList from it and I somehow can't find a way to store this information into a JTable."

You can do something like this to add the data

ArrayList<FootballClub> originalLeagueList = new ArrayList<FootballClub>();

originalLeagueList.add(new FootballClub(1, "Arsenal", 35, 11, 2, 2, 15, 30, 11, 19));
originalLeagueList.add(new FootballClub(2, "Liverpool", 30, 9, 3, 3, 15, 34, 18, 16));
originalLeagueList.add(new FootballClub(3, "Chelsea", 30, 9, 2, 2, 15, 30, 11, 19));
originalLeagueList.add(new FootballClub(4, "Man City", 29, 9, 2, 4, 15, 41, 15, 26));
originalLeagueList.add(new FootballClub(5, "Everton", 28, 7, 1, 7, 15, 23, 14, 9));
originalLeagueList.add(new FootballClub(6, "Tottenham", 27, 8, 4, 3, 15, 15, 16, -1));
originalLeagueList.add(new FootballClub(7, "Newcastle", 26, 8, 5, 2, 15, 20, 21, -1));
originalLeagueList.add(new FootballClub(8, "Southampton", 23, 6, 4, 5, 15, 19, 14, 5));

for (int i = 0; i < originalLeagueList.size(); i++){
   int position = originalLeagueList.get(i).getPosition();
   String name = originalLeagueList.get(i).getName();
   int points = originalLeagueList.get(i).getPoinst();
   int wins = originalLeagueList.get(i).getWins();
   int defeats = originalLeagueList.get(i).getDefeats();
   int draws = originalLeagueList.get(i).getDraws();
   int totalMatches = originalLeagueList.get(i).getTotalMathces();
   int goalF = originalLeagueList.get(i).getGoalF();
   int goalA = originalLeagueList.get(i).getGoalA();
   in ttgoalD = originalLeagueList.get(i).getTtgoalD();

   Object[] data = {position, name, points, wins, defeats, draws, 
                               totalMatches, goalF, goalA, ttgoalD};

   tableModel.add(data);

}

Programmatically select a row in JTable

It is an old post, but I came across this recently

Selecting a specific interval

As @aleroot already mentioned, by using

table.setRowSelectionInterval(index0, index1);

You can specify an interval, which should be selected.

Adding an interval to the existing selection

You can also keep the current selection, and simply add additional rows by using this here

table.getSelectionModel().addSelectionInterval(index0, index1);

This line of code additionally selects the specified interval. It doesn't matter if that interval already is selected, of parts of it are selected.

How to remove a row from JTable?

Look at the DefaultTableModel for a simple model that you can use:

http://java.sun.com/javase/6/docs/api/javax/swing/table/DefaultTableModel.html

This extends the AbstractTableModel, but should be sufficient for basic purposes. You can always extend AbstractTableModel and create your own. Make sure you set it on the JTable as well.

http://java.sun.com/javase/6/docs/api/javax/swing/table/AbstractTableModel.html

Look at the basic Sun tutorial for more information on using the JTable with the table model:

http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#data

How to make a JTable non-editable

just add

table.setEnabled(false);

it works fine for me.

How to add row in JTable?

To add row to JTable, one of the ways is:

1) Create table using DefaultTableModel:

        DefaultTableModel model = new DefaultTableModel();
        model.addColumn("Code");
        model.addColumn("Name");
        model.addColumn("Quantity");
        model.addColumn("Unit Price");
        model.addColumn("Price");
        JTable table = new JTable(model);

2) To add row:

        DefaultTableModel model = (DefaultTableModel) table.getModel();
        model.addRow(new Object[]{"Column 1", "Column 2", "Column 3","Column 4","Column 5"});

JTable won't show column headers

    public table2() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 485, 218);
    setTitle("jtable");
    getContentPane().setLayout(null);

    String data[][] = { { "Row1/1", "Row1/2", "Row1/3" },
            { "Row2/1", "Row2/2", "Row2/3" },
            { "Row3/1", "Row3/2", "Row3/3" },
            { "Row4/1", "Row4/2", "Row4/3" }, };

    String header[] = { "Column 1", "Column 2", "Column 3" };

    // Table
    JTable table = new JTable(data,header);


    // ScrollPane
    JScrollPane scrollPane = new JScrollPane(table);
    scrollPane.setBounds(36, 37, 407, 79);
    getContentPane().add(scrollPane);

   }

}

try this!!

How to add row of data to Jtable from values received from jtextfield and comboboxes

you can use this code as template please customize it as per your requirement.

DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();

list.add(textField.getText());
list.add(comboBox.getSelectedItem());

model.addRow(list.toArray());

table.setModel(model);

here DefaultTableModel is used to add rows in JTable, you can get more info here.

Display calendar to pick a date in java

I found JXDatePicker as a better solution to this. It gives what you need and very easy to use.

import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jdesktop.swingx.JXDatePicker;

public class DatePickerExample extends JPanel {

    public static void main(String[] args) {
        JFrame frame = new JFrame("JXPicker Example");
        JPanel panel = new JPanel();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(400, 400, 250, 100);

        JXDatePicker picker = new JXDatePicker();
        picker.setDate(Calendar.getInstance().getTime());
        picker.setFormats(new SimpleDateFormat("dd.MM.yyyy"));

        panel.add(picker);
        frame.getContentPane().add(panel);

        frame.setVisible(true);
    }
}

How to add checkboxes to JTABLE swing

1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,

2) AbstractTableModel should be useful, where is in the JTable required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel,

3) consider using DefaultTableModel, (if you are not sure about how to works) instead of AbstractTableModel,

table_with_BooleanType_column

could be generated from simple code:

import javax.swing.*;
import javax.swing.table.*;

public class TableCheckBox extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table;

    public TableCheckBox() {
        Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
        Object[][] data = {
            {"Buy", "IBM", new Integer(1000), new Double(80.50), false},
            {"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
            {"Sell", "Apple", new Integer(3000), new Double(7.35), true},
            {"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
        };
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        table = new JTable(model) {

            private static final long serialVersionUID = 1L;

            /*@Override
            public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
            }*/
            @Override
            public Class getColumnClass(int column) {
                switch (column) {
                    case 0:
                        return String.class;
                    case 1:
                        return String.class;
                    case 2:
                        return Integer.class;
                    case 3:
                        return Double.class;
                    default:
                        return Boolean.class;
                }
            }
        };
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        getContentPane().add(scrollPane);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                TableCheckBox frame = new TableCheckBox();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocation(150, 150);
                frame.setVisible(true);
            }
        });
    }
}

Most simple code to populate JTable from ResultSet

This is my approach:

String[] columnNames = {"id", "Nome", "Sobrenome","Email"};

List<Student> students = _repo.getAll();

Object[][] data = new Object[students.size()][4];

int index = 0;
for(Student s : students) {
    data[index][0] = s.getId();
    data[index][1] = s.getFirstName();
    data[index][2] = s.getLastName();
    data[index][3] = s.getEmail();
    index++;
}

DefaultTableModel model = new DefaultTableModel(data, columnNames);

table = new JTable(model);

JTable How to refresh table model after insert delete or update the data.

The faster way for your case is:

    jTable.repaint(); // Repaint all the component (all Cells).

The optimized way when one or few cell change:

    ((AbstractTableModel) jTable.getModel()).fireTableCellUpdated(x, 0); // Repaint one cell.

Java JTable setting Column Width

JTable.AUTO_RESIZE_LAST_COLUMN is defined as "During all resize operations, apply adjustments to the last column only" which means you have to set the autoresizemode at the end of your code, otherwise setPreferredWidth() won't affect anything!

So in your case this would be the correct way:

table.getColumnModel().getColumn(0).setPreferredWidth(27);
table.getColumnModel().getColumn(1).setPreferredWidth(120);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(3).setPreferredWidth(90);
table.getColumnModel().getColumn(4).setPreferredWidth(90);
table.getColumnModel().getColumn(6).setPreferredWidth(120);
table.getColumnModel().getColumn(7).setPreferredWidth(100);
table.getColumnModel().getColumn(8).setPreferredWidth(95);
table.getColumnModel().getColumn(9).setPreferredWidth(40);
table.getColumnModel().getColumn(10).setPreferredWidth(400);
table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);

Java JTable getting the data of the selected row

if you want to get the data in the entire row, you can use this combination below

tableModel.getDataVector().elementAt(jTable.getSelectedRow());

Where "tableModel" is the model for the table that can be accessed like so

(DefaultTableModel) jTable.getModel();

this will return the entire row data.

I hope this helps somebody

JTable - Selected Row click event

Here's how I did it:

table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
        public void valueChanged(ListSelectionEvent event) {
            // do some actions here, for example
            // print first column value from selected row
            System.out.println(table.getValueAt(table.getSelectedRow(), 0).toString());
        }
    });

This code reacts on mouse click and item selection from keyboard.

adding to window.onload event?

You can use attachEvent(ie8) and addEventListener instead

addEvent(window, 'load', function(){ some_methods_1() });
addEvent(window, 'load', function(){ some_methods_2() });

function addEvent(element, eventName, fn) {
    if (element.addEventListener)
        element.addEventListener(eventName, fn, false);
    else if (element.attachEvent)
        element.attachEvent('on' + eventName, fn);
}

jQuery lose focus event

Like this:

$(selector).focusout(function () {
    //Your Code
});

Count number of rows by group using dplyr

I think what you are looking for is as follows.

cars_by_cylinders_gears <- mtcars %>%
  group_by(cyl, gear) %>%
  summarise(count = n())

This is using the dplyr package. This is essentially the longhand version of the count () solution provided by docendo discimus.

Bootstrap - dropdown menu not working?

Double importing jquery can cause Error

<script src="static/public/js/jquery/jquery.min.js"></script>

OR

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="" crossorigin="anonymous"></script>

PHP: Call to undefined function: simplexml_load_string()

To fix this error on Centos 7:

  1. Install PHP extension:

    sudo yum install php-xml

  2. Restart your web server. In my case it's php-fpm:

    services php-fpm restart

How to print Unicode character in Python?

If you're trying to print() Unicode, and getting ascii codec errors, check out this page, the TLDR of which is do export PYTHONIOENCODING=UTF-8 before firing up python (this variable controls what sequence of bytes the console tries to encode your string data as). Internally, Python3 uses UTF-8 by default (see the Unicode HOWTO) so that's not the problem; you can just put Unicode in strings, as seen in the other answers and comments. It's when you try and get this data out to your console that the problem happens. Python thinks your console can only handle ascii. Some of the other answers say, "Write it to a file, first" but note they specify the encoding (UTF-8) for doing so (so, Python doesn't change anything in writing), and then use a method for reading the file that just spits out the bytes without any regard for encoding, which is why that works.

How to make sql-mode="NO_ENGINE_SUBSTITUTION" permanent in MySQL my.cnf

It should be:

[mysqld]
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

instead of

[mysqld]
sql_mode="NO_ENGINE_SUBSTITUTION"

then restart mysqld service.

Android Device Chooser -- device not showing up

And , if your device is a Sony Ericsson Xperia X8 with the original ROM (2.1) or similar, then use:

 

<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="17" />

in AndroidManifest.xml file

how do I strip white space when grabbing text with jQuery?

Actually, jQuery has a built in trim function:

 var emailAdd = jQuery.trim($(this).text());

See here for details.

How to put comments in Django templates

In contrast to traditional html comments like this:

<!-- not so secret secrets -->

Django template comments are not rendered in the final html. So you can feel free to stuff implementation details in there like so:

Multi-line:

{% comment %}
    The other half of the flexbox is defined 
    in a different file `sidebar.html`
    as <div id="sidebar-main">.
{% endcomment %}

Single line:

{# jquery latest #}

{#
    beware, this won't be commented out... 
    actually renders as regular body text on the page
#}

I find single line comments especially helpful for <a href="{% url 'view_name' %}" views that have not been created yet.

Can CSS detect the number of children an element has?

Clarification:

Because of a previous phrasing in the original question, a few SO citizens have raised concerns that this answer could be misleading. Note that, in CSS3, styles cannot be applied to a parent node based on the number of children it has. However, styles can be applied to the children nodes based on the number of siblings they have.


Original answer:

Incredibly, this is now possible purely in CSS3.

/* one item */
li:first-child:nth-last-child(1) {
/* -or- li:only-child { */
    width: 100%;
}

/* two items */
li:first-child:nth-last-child(2),
li:first-child:nth-last-child(2) ~ li {
    width: 50%;
}

/* three items */
li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li {
    width: 33.3333%;
}

/* four items */
li:first-child:nth-last-child(4),
li:first-child:nth-last-child(4) ~ li {
    width: 25%;
}

The trick is to select the first child when it's also the nth-from-the-last child. This effectively selects based on the number of siblings.

Credit for this technique goes to André Luís (discovered) & Lea Verou (refined).

Don't you just love CSS3?

CodePen Example:

Sources:

Query for documents where array size is greater than 1

I know its old question, but I am trying this with $gte and $size in find. I think to find() is faster.

db.getCollection('collectionName').find({ name : { $gte : {  $size : 1 } }})

How to add DOM element script to head section?

Best solution I've found:

AppendToHead('script', 'alert("hii"); ');
//or
AppendToHead('script', 'http://example.com/script.js');
//or
AppendToHead('style',  '#myDiv{color:red;} ');
//or
AppendToHead('style',  'http://example.com/style.css');



function AppendToHead(elemntType, content){
    // detect whether provided content is "link" (instead of inline codes)
    var Is_Link = content.split(/\r\n|\r|\n/).length <= 1  &&  content.indexOf("//") > -1 && content.indexOf(" ")<=-1;
    if(Is_Link){
        if (elemntType=='script')    { var x=document.createElement('script');x.id=id;  x.src=content;  x.type='text/javascript'; }
        else if (elemntType=='style'){ var x=document.createElement('link');  x.id=id;  x.href=content; x.type='text/css';  x.rel = 'stylesheet'; }
    }
    else{
        var x = document.createElement(elemntType);
        if (elemntType=='script')    { x.type='text/javascript';    x.innerHTML = content;  }
        else if (elemntType=='style'){ x.type='text/css';    if (x.styleSheet){ x.styleSheet.cssText=content; } else { x.appendChild(document.createTextNode(content)); }   }
    }
    //append in head
    (document.head || document.getElementsByTagName('head')[0]).appendChild(x);
}

When to use "new" and when not to, in C++?

You should use new when you want an object to be created on the heap instead of the stack. This allows an object to be accessed from outside the current function or procedure, through the aid of pointers.

It might be of use to you to look up pointers and memory management in C++ since these are things you are unlikely to have come across in other languages.

How to sort in-place using the merge sort algorithm?

Including its "big result", this paper describes a couple of variants of in-place merge sort (PDF):

http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.22.5514&rep=rep1&type=pdf

In-place sorting with fewer moves

Jyrki Katajainen, Tomi A. Pasanen

It is shown that an array of n elements can be sorted using O(1) extra space, O(n log n / log log n) element moves, and n log2n + O(n log log n) comparisons. This is the first in-place sorting algorithm requiring o(n log n) moves in the worst case while guaranteeing O(n log n) comparisons, but due to the constant factors involved the algorithm is predominantly of theoretical interest.

I think this is relevant too. I have a printout of it lying around, passed on to me by a colleague, but I haven't read it. It seems to cover basic theory, but I'm not familiar enough with the topic to judge how comprehensively:

http://comjnl.oxfordjournals.org/cgi/content/abstract/38/8/681

Optimal Stable Merging

Antonios Symvonis

This paper shows how to stably merge two sequences A and B of sizes m and n, m = n, respectively, with O(m+n) assignments, O(mlog(n/m+1)) comparisons and using only a constant amount of additional space. This result matches all known lower bounds...

PDO's query vs execute

No, they're not the same. Aside from the escaping on the client-side that it provides, a prepared statement is compiled on the server-side once, and then can be passed different parameters at each execution. Which means you can do:

$sth = $db->prepare("SELECT * FROM table WHERE foo = ?");
$sth->execute(array(1));
$results = $sth->fetchAll(PDO::FETCH_ASSOC);

$sth->execute(array(2));
$results = $sth->fetchAll(PDO::FETCH_ASSOC);

They generally will give you a performance improvement, although not noticeable on a small scale. Read more on prepared statements (MySQL version).

Errors: "INSERT EXEC statement cannot be nested." and "Cannot use the ROLLBACK statement within an INSERT-EXEC statement." How to solve this?

I recommend to read this entire article, but here is the most relevant section that addresses your question:

Rollback and Error Handling is Difficult

In my articles on Error and Transaction Handling in SQL Server, I suggest that > you should always have an error handler like

BEGIN CATCH
   IF @@trancount > 0 ROLLBACK TRANSACTION
   EXEC error_handler_sp
   RETURN 55555
END CATCH

The idea is that even if you do not start a transaction in the procedure, you should always include a ROLLBACK, because if you were not able to fulfil your contract, the transaction is not valid.

Unfortunately, this does not work well with INSERT-EXEC. If the called procedure executes a ROLLBACK statement, this happens:

Msg 3915, Level 16, State 0, Procedure SalesByStore, Line 9 Cannot use the ROLLBACK statement within an INSERT-EXEC statement.

The execution of the stored procedure is aborted. If there is no CATCH handler anywhere, the entire batch is aborted, and the transaction is rolled back. If the INSERT-EXEC is inside TRY-CATCH, that CATCH handler will fire, but the transaction is doomed, that is, you must roll it back. The net effect is that the rollback is achieved as requested, but the original error message that triggered the rollback is lost. That may seem like a small thing, but it makes troubleshooting much more difficult, because when you see this error, all you know is that something went wrong, but you don't know what.

RESTful URL design for search

I use two approaches to implement searches.

1) Simplest case, to query associated elements, and for navigation.

    /cars?q.garage.id.eq=1

This means, query cars that have garage ID equal to 1.

It is also possible to create more complex searches:

    /cars?q.garage.street.eq=FirstStreet&q.color.ne=red&offset=300&max=100

Cars in all garages in FirstStreet that are not red (3rd page, 100 elements per page).

2) Complex queries are considered as regular resources that are created and can be recovered.

    POST /searches  => Create
    GET  /searches/1  => Recover search
    GET  /searches/1?offset=300&max=100  => pagination in search

The POST body for search creation is as follows:

    {  
       "$class":"test.Car",
       "$q":{
          "$eq" : { "color" : "red" },
          "garage" : {
             "$ne" : { "street" : "FirstStreet" }
          }
       }
    }

It is based in Grails (criteria DSL): http://grails.org/doc/2.4.3/ref/Domain%20Classes/createCriteria.html

getElementsByClassName not working

If you want to do it by ClassName you could do:

<script type="text/javascript">
function hideTd(className){
    var elements;

    if (document.getElementsByClassName)
    {
        elements = document.getElementsByClassName(className);
    }
    else
    {
        var elArray = [];
        var tmp = document.getElementsByTagName(elements);  
        var regex = new RegExp("(^|\\s)" + className+ "(\\s|$)");
        for ( var i = 0; i < tmp.length; i++ ) {

            if ( regex.test(tmp[i].className) ) {
                elArray.push(tmp[i]);
            }
        }

        elements = elArray;
    }

    for(var i = 0, i < elements.length; i++) {
       if( elements[i].textContent == ''){
          elements[i].style.display = 'none';
       } 
    }

  }
</script>

Why would an Enum implement an Interface?

The Comparable example given by several people here is wrong, since Enum already implements that. You can't even override it.

A better example is having an interface that defines, let's say, a data type. You can have an enum to implement the simple types, and have normal classes to implement complicated types:

interface DataType {
  // methods here
}

enum SimpleDataType implements DataType {
  INTEGER, STRING;

  // implement methods
}

class IdentifierDataType implements DataType {
  // implement interface and maybe add more specific methods
}

When and why do I need to use cin.ignore() in C++?

Short answer

Why? Because there is still whitespace (carriage returns, tabs, spaces, newline) left in the input stream.

When? When you are using some function which does not on their own ignores the leading whitespaces. Cin by default ignores and removes the leading whitespace but getline does not ignore the leading whitespace on its own.

Now a detailed answer.

Everything you input in the console is read from the standard stream stdin. When you enter something, let's say 256 in your case and press enter, the contents of the stream become 256\n. Now cin picks up 256 and removes it from the stream and \n still remaining in the stream. Now next when you enter your name, let's say Raddicus, the new contents of the stream is \nRaddicus.

Now here comes the catch. When you try to read a line using getline, if not provided any delimiter as the third argument, getline by default reads till the newline character and removes the newline character from the stream. So on calling new line, getline reads and discards \n from the stream and resulting in an empty string read in mystr which appears like getline is skipped (but it's not) because there was already an newline in the stream, getline will not prompt for input as it has already read what it was supposed to read.

Now, how does cin.ignore help here?

According to the ignore documentation extract from cplusplus.com-

istream& ignore (streamsize n = 1, int delim = EOF);

Extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim.

The function also stops extracting characters if the end-of-file is reached. If this is reached prematurely (before either extracting n characters or finding delim), the function sets the eofbit flag.

So, cin.ignore(256, '\n');, ignores first 256 characters or all the character untill it encounters delimeter (here \n in your case), whichever comes first (here \n is the first character, so it ignores until \n is encountered).

Just for your reference, If you don't exactly know how many characters to skip and your sole purpose is to clear the stream to prepare for reading a string using getline or cin you should use cin.ignore(numeric_limits<streamsize>::max(),'\n').

Quick explanation: It ignores the characters equal to maximum size of stream or until a '\n' is encountered, whichever case happens first.

Encode a FileStream to base64 with c#

Since the file will be larger, you don't have very much choice in how to do this. You cannot process the file in place since that will destroy the information you need to use. You have two options that I can see:

  1. Read in the entire file, base64 encode, re-write the encoded data.
  2. Read the file in smaller pieces, encoding as you go along. Encode to a temporary file in the same directory. When you are finished, delete the original file, and rename the temporary file.

Of course, the whole point of streams is to avoid this sort of scenario. Instead of creating the content and stuffing it into a file stream, stuff it into a memory stream. Then encode that and only then save to disk.

How to use wait and notify in Java without IllegalMonitorStateException?

You can only call notify on objects where you own their monitor. So you need something like

synchronized(threadObject)
{
   threadObject.notify();
}

How to modify the nodejs request default timeout time?

For specific request one can set timeOut to 0 which is no timeout till we get reply from DB or other server

request.setTimeout(0)

Git asks for username every time I push

To set the credentials for the entire day that is 24 hours.

git config --global credential.helper 'cache --timeout 86400'

Else for 1 hour replace the 86400 secs to 3600.

OR

all configuration options for the 'cache' authentication helper:

git help credential-cache

Java converting Image to BufferedImage

One way to handle this is to create a new BufferedImage, and tell it's graphics object to draw your scaled image into the new BufferedImage:

final float FACTOR  = 4f;
BufferedImage img = ImageIO.read(new File("graphic.png"));
int scaleX = (int) (img.getWidth() * FACTOR);
int scaleY = (int) (img.getHeight() * FACTOR);
Image image = img.getScaledInstance(scaleX, scaleY, Image.SCALE_SMOOTH);
BufferedImage buffered = new BufferedImage(scaleX, scaleY, TYPE);
buffered.getGraphics().drawImage(image, 0, 0 , null);

That should do the trick without casting.

How to get a subset of a javascript object's properties

Using the "with" statement with shorthand object literal syntax

Nobody has demonstrated this method yet, probably because it's terrible and you shouldn't do it, but I feel like it has to be listed.

_x000D_
_x000D_
var o = {a:1,b:2,c:3,d:4,e:4,f:5}
with(o){
  var output =  {a,b,f}
}
console.log(output)
_x000D_
_x000D_
_x000D_

Pro: You don't have to type the property names twice.

Cons: The "with" statement is not recommended for many reasons.

Conclusion: It works great, but don't use it.

How to get client IP address using jQuery

function GetUserIP(){
  var ret_ip;
  $.ajaxSetup({async: false});
  $.get('http://jsonip.com/', function(r){ 
    ret_ip = r.ip; 
  });
  return ret_ip;
}

If you want to use the IP and assign it to a variable, Try this. Just call GetUserIP()

Use mysql_fetch_array() with foreach() instead of while()

To use foreach would require you have an array that contains every row from the query result. Some DB libraries for PHP provide a fetch_all function that provides an appropriate array but I could not find one for mysql (however the mysqli extension does) . You could of course write your own, like so

function mysql_fetch_all($result) {
   $rows = array();
   while ($row = mysql_fetch_array($result)) {
     $rows[] = $row;
   }
   return $rows;
}

However I must echo the "why?" Using this function you are creating two loops instead of one, and requring the entire result set be loaded in to memory. For sufficiently large result sets, this could become a serious performance drag. And for what?

foreach (mysql_fetch_all($result) as $row)

vs

while ($row = mysql_fetch_array($result))

while is just as concise and IMO more readable.

EDIT There is another option, but it is pretty absurd. You could use the Iterator Interface

class MysqlResult implements Iterator {
  private $rownum = 0;
  private $numrows = 0;
  private $result;

  public function __construct($result) {
    $this->result = $result;
    $this->numrows = mysql_num_rows($result);
  }

  public function rewind() {
    $this->rownum = 0;
  }

  public function current() {
    mysql_data_seek($this->result, $this->rownum);
    return mysql_fetch_array($this->result);
  }

  public function key() {
    return $this->rownum;
  }

  public function next() {
    $this->rownum++;
  }

  public function valid() {
    return $this->rownum < $this->numrows ? true : false;
  }
}

$rows = new MysqlResult(mysql_query($query_select));

foreach ($rows as $row) {
  //code...
}

In this case, the MysqlResult instance fetches rows only on request just like with while, but wraps it in a nice foreach-able package. While you've saved yourself a loop, you've added the overhead of class instantiation and a boat load of function calls, not to mention a good deal of added code complexity.

But you asked if it could be done without using while (or for I imagine). Well it can be done, just like that. Whether it should be done is up to you.

Java: using switch statement with enum under subclass

Java infers automatically the type of the elements in case, so the labels must be unqualified.

int i;
switch(i) {
   case 5: // <- integer is expected
}
MyEnum e;
switch (e) {
   case VALUE_A: // <- an element of the enumeration is expected
}

How to automatically add user account AND password with a Bash script?

Single liner to create a sudo user with home directory and password.

useradd -m -p $(openssl passwd -1 ${PASSWORD}) -s /bin/bash -G sudo ${USERNAME}

Oracle date to string conversion

Try this. Oracle has this feature to distinguish the millennium years..

As you mentioned, if your column is a varchar, then the below query will yield you 1989..

select to_date(column_name,'dd/mm/rr') from table1;

When the format rr is used in year, the following would be done by oracle.

if rr->00 to 49 ---> result will be 2000 - 2049, if rr->50 to 99 ---> result will be 1950 - 1999

Excel: VLOOKUP that returns true or false?

You could wrap your VLOOKUP() in an IFERROR()

Edit: before Excel 2007, use =IF(ISERROR()...)

How to generate xsd from wsdl

  1. Soap ui -> New SOAPUI project -> use wsdl to create a project (lets assume we have a testService in it)
  2. you will have a folder called TestService and then inside it there will be tokenTestServiceSoapBinding (example) -> right click on it
  3. Export definition -> give location where you need to place the definition.
  4. Exported location will have xsd and wsdl files. Hope this helps!

Why would one mark local variables and method parameters as "final" in Java?

My personal opinion is that it is a waste of time. I believe that the visual clutter and added verbosity is not worth it.

I have never been in a situation where I have reassigned (remember, this does not make objects immutable, all it means is that you can't reassign another reference to a variable) a variable in error.

But, of course, it's all personal preference ;-)

Launch an app on OS X with command line

Why not just set add path to to the bin of the app. For MacVim, I did the following.

export PATH=/Applications/MacVim.app/Contents/bin:$PATH

An alias, is another option I tried.

alias mvim='/Applications/MacVim.app/Contents/bin/mvim'
alias gvim=mvim 

With the export PATH I can call all of the commands in the app. Arguments passed well for my test with MacVim. Whereas the alias, I had to alias each command in the bin.

mvim README.txt
gvim Anotherfile.txt

Enjoy the power of alias and PATH. However, you do need to monitor changes when the OS is upgraded.

"The system cannot find the file C:\ProgramData\Oracle\Java\javapath\java.exe"

There must be two or more PATH variables. Try merging all of them into one using semi-colon (;)

How do I extract text that lies between parentheses (round brackets)?

Here is a general purpose readable function that avoids using regex:

// Returns the text between 'start' and 'end'.
string ExtractBetween(string text, string start, string end)
{
  int iStart = text.IndexOf(start);
  iStart = (iStart == -1) ? 0 : iStart + start.Length;
  int iEnd = text.LastIndexOf(end);
  if(iEnd == -1)
  {
    iEnd = text.Length;
  }
  int len = iEnd - iStart;

  return text.Substring(iStart, len);
}

To call it in your particular example you can do:

string result = ExtractBetween("User name (sales)", "(", ")");

Android: keeping a background service alive (preventing process death)

Keep your service footprint small, this reduces the probability of Android closing your application. You can't prevent it from being killed because if you could then people could easily create persistent spyware

Warning "Do not Access Superglobal $_POST Array Directly" on Netbeans 7.4 for PHP

Just use

filter_input(INPUT_METHOD_NAME, 'var_name') instead of $_INPUT_METHOD_NAME['var_name'] filter_input_array(INPUT_METHOD_NAME) instead of $_INPUT_METHOD_NAME

e.g

    $host= filter_input(INPUT_SERVER, 'HTTP_HOST');
    echo $host;

instead of

    $host= $_SERVER['HTTP_HOST'];
    echo $host;

And use

    var_dump(filter_input_array(INPUT_SERVER));

instead of

    var_dump($_SERVER);

N.B: Apply to all other Super Global variable

HTTP redirect: 301 (permanent) vs. 302 (temporary)

301 is that the requested resource has been assigned a new permanent URI and any future references to this resource should be done using one of the returned URIs.

302 is that the requested resource resides temporarily under a different URI.

Since the redirection may be altered on occasion, the client should continue to use the Request-URI for future requests.

This response is only cachable if indicated by a Cache-Control or Expires header field.

Empty an array in Java / processing

If Array xco is not final then a simple reassignment would work:

i.e.

xco = new Float[xco .length];

This assumes you need the Array xco to remain the same size. If that's not necessary then create an empty array:

xco= new Float[0];

How to make war file in Eclipse

File -> Export -> Web -> WAR file

OR in Kepler follow as shown below :

enter image description here

JavaScript Chart.js - Custom data formatting to display on tooltip

You can give tooltipTemplate a function, and format the tooltip as you wish:

tooltipTemplate: function(v) {return someFunction(v.value);}
multiTooltipTemplate: function(v) {return someOtherFunction(v.value);}

Those given 'v' arguments contain lots of information besides the 'value' property. You can put a 'debugger' inside that function and inspect those yourself.

Error - replacement has [x] rows, data has [y]

You could use cut

 df$valueBin <- cut(df$value, c(-Inf, 250, 500, 1000, 2000, Inf), 
    labels=c('<=250', '250-500', '500-1,000', '1,000-2,000', '>2,000'))

data

 set.seed(24)
 df <- data.frame(value= sample(0:2500, 100, replace=TRUE))

Printing to the console in Google Apps Script?

Updated for 2020

In February of 2020, Google announced a major upgrade to the built-in Google Apps Script IDE, and it now supports console.log(). So, you can now use both:

  1. Logger.log()
  2. console.log()

Happy coding!

How can I read user input from the console?

I'm not sure what your problem is (since you haven't told us), but I'm guessing at

a = Console.Read();

This will only read one character from your Console.

You can change your program to this. To make it more robust, accept more than 1 char input, and validate that the input is actually a number:

double a, b;
Console.WriteLine("istenen sayiyi sonuna .00 koyarak yaz");
if (double.TryParse(Console.ReadLine(), out a)) {
  b = a * Math.PI;
  Console.WriteLine("Sonuç " + b); 
} else {
  //user gave an illegal input. Handle it here.
}

How do I convert between ISO-8859-1 and UTF-8 in Java?

Regex can also be good and be used effectively (Replaces all UTF-8 characters not covered in ISO-8859-1 with space):

String input = "€Tes¶ti©ng [§] al€l o€f i¶t _ - À ÆÑ with some 9umbers as"
            + " w2921**#$%!@# well Ü, or ü, is a chaŒracte?";
String output = input.replaceAll("[^\\u0020-\\u007e\\u00a0-\\u00ff]", " ");
System.out.println("Input = " + input);
System.out.println("Output = " + output);

C# Example of AES256 encryption using System.Security.Cryptography.Aes

Once I'd discovered all the information of how my client was handling the encryption/decryption at their end it was straight forward using the AesManaged example suggested by dtb.

The finally implemented code started like this:

    try
    {
        // Create a new instance of the AesManaged class.  This generates a new key and initialization vector (IV).
        AesManaged myAes = new AesManaged();

        // Override the cipher mode, key and IV
        myAes.Mode = CipherMode.ECB;
        myAes.IV = new byte[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // CRB mode uses an empty IV
        myAes.Key = CipherKey;  // Byte array representing the key
        myAes.Padding = PaddingMode.None;

        // Create a encryption object to perform the stream transform.
        ICryptoTransform encryptor = myAes.CreateEncryptor();

        // TODO: perform the encryption / decryption as required...

    }
    catch (Exception ex)
    {
        // TODO: Log the error 
        throw ex;
    }

Current timestamp as filename in Java

Improving the @Derek Springer post with fill length function:

public static String getFileWithDate(String fileName, String fileSaperator, String dateFormat) {
    String FileNamePrefix = fileName.substring(0, fileName.lastIndexOf(fileSaperator));
    String FileNameSuffix = fileName.substring(fileName.lastIndexOf(fileSaperator)+1, fileName.length());
    //System.out.println("File= Prefix~Suffix:"+FileNamePrefix +"~"+FileNameSuffix);
    
    String newFileName = new SimpleDateFormat("'"+FileNamePrefix+"_'"+dateFormat+"'"+fileSaperator+FileNameSuffix+"'").format(new Date());
    System.out.println("New File:"+newFileName);
    return newFileName;
}

Using the funciton and its Output:

String fileSaperator = ".", format = "yyyyMMMdd_HHmm";
getFileWithDate("Text1.txt", fileSaperator, format);
getFileWithDate("Text1.doc", fileSaperator, format);
getFileWithDate("Text1.txt.json", fileSaperator, format);

Output:

Old File:Text1.txt   New File:Text1_2020Nov11_1807.txt
Old File:Text1.doc   New File:Text1_2020Nov11_1807.doc
Old File:Text1.txt.json  New File:Text1.txt_2020Nov11_1807.json

Using Image control in WPF to display System.Drawing.Bitmap

It's easy for disk file, but harder for Bitmap in memory.

System.Drawing.Bitmap bmp;
Image image;
...
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
ms.Position = 0;
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = ms;
bi.EndInit();

image.Source = bi;

Stealed here

org.hibernate.PersistentObjectException: detached entity passed to persist

Most likely the problem lies outside the code you are showing us here. You are trying to update an object that is not associated with the current session. If it is not the Invoice, then maybe it is an InvoiceItem that has already been persisted, obtained from the db, kept alive in some sort of session and then you try to persist it on a new session. This is not possible. As a general rule, never keep your persisted objects alive across sessions.

The solution will ie in obtaining the whole object graph from the same session you are trying to persist it with. In a web environment this would mean:

  • Obtain the session
  • Fetch the objects you need to update or add associations to. Preferabley by their primary key
  • Alter what is needed
  • Save/update/evict/delete what you want
  • Close/commit your session/transaction

If you keep having issues post some of the code that is calling your service.

ip address validation in python using regex

The following will check whether an IP is valid or not: If the IP is within 0.0.0.0 to 255.255.255.255, then the output will be true, otherwise it will be false:

[0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4

Example:

your_ip = "10.10.10.10"
[0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4

Output:

>>> your_ip = "10.10.10.10"
>>> [0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
True
>>> your_ip = "10.10.10.256"
>>> [0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
False
>>>

Importing large sql file to MySql via command line

Importing large sql file to MySql via command line

  1. first download file .
  2. paste file on home.
  3. use following command in your terminals(CMD)
  4. Syntax: mysql -u username -p databsename < file.sql

Example: mysql -u root -p aanew < aanew.sql

How can we dynamically allocate and grow an array

You can do something like this:

String [] wordList;
int wordCount = 0;
int occurrence = 1;
int arraySize = 100;
int arrayGrowth = 50;
wordList = new String[arraySize];
while ((strLine = br.readLine()) != null)   {
     // Store the content into an array
     Scanner s = new Scanner(strLine);
     while(s.hasNext()) {
         if (wordList.length == wordCount) {
              // expand list
              wordList = Arrays.copyOf(wordList, wordList.length + arrayGrowth);
         }
         wordList[wordCount] = s.next();
         wordCount++;
     } 
}

Using java.util.Arrays.copyOf(String[]) is basically doing the same thing as:

if (wordList.length == wordCount) {
    String[] temp = new String[wordList.length + arrayGrowth];
    System.arraycopy(wordList, 0, temp, 0, wordList.length);
    wordList = temp;
}

except it is one line of code instead of three. :)

Easiest way to ignore blank lines when reading a file in Python

@S.Lott

The following code processes lines one at a time and produces a result that isn't memory eager:

filename = 'english names.txt'

with open(filename) as f_in:
    lines = (line.rstrip() for line in f_in)
    lines = (line for line in lines if line)
    the_strange_sum = 0
    for l in lines:
        the_strange_sum += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.find(l[0])

print the_strange_sum

So the generator (line.rstrip() for line in f_in) is quite the same acceptable than the nonblank_lines() function.

Program to find largest and second largest number in array

Here is an answer with a single for loop.

int array[] = { 10, 15, 13, 20, 21, 8, 6, 7, 9, 21, 23 };
const int count = sizeof(a) / sizeof(a[0]);
int lastMaxNumber = 0;
int maxNumber = 0;

for (int i = 0; i < count; i++) {

    // Current number
    int num = array[i];

    // Find the minimum and maximum from (num, max)
    int maxValue = (num > maxNumber) ? num : maxNumber;
    int minValue = (num < maxNumber) ? num : maxNumber;

    // If minValue is greater than lastMaxNumber, update the lastMaxNumber
    if minValue > lastMaxNumber {
        lastMaxNumber = minValue;
    }

    // Updating maxNumber
    maxNumber = maxValue;
}

printf("%d", lastMaxNumber);

Insert into ... values ( SELECT ... FROM ... )

This worked for me:

insert into table1 select * from table2

The sentence is a bit different from Oracle's.

javascript set cookie with expire time

Your browser may be configured to accept only session cookies; if this is your case, any expiry time is transformed into session by your browser, you can change this setting of your browser or try another browser without such a configuration

Where are environment variables stored in the Windows Registry?

Here's where they're stored on Windows XP through Windows Server 2012 R2:

User Variables

HKEY_CURRENT_USER\Environment

System Variables

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

Angular ng-click with call to a controller function not working

You should probably use the ngHref directive along with the ngClick:

 <a ng-href='#here' ng-click='go()' >click me</a>

Here is an example: http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview

<body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    {{msg}}
    <a ng-href='#here' ng-click='go()' >click me</a>
    <div style='height:1000px'>

      <a id='here'></a>

    </div>
     <h1>here</h1>
  </body>

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';

  $scope.go = function() {

    $scope.msg = 'clicked';
  }
});

I don't know if this will work with the library you are using but it will at least let you link and use the ngClick function.

** Update **

Here is a demo of the set and get working fine with a service.

http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, sharedProperties) {
  $scope.name = 'World';

  $scope.go = function(item) {
    sharedProperties.setListName(item);


  }

  $scope.getItem = function() {

    $scope.msg = sharedProperties.getListName();
  }
});

app.service('sharedProperties', function () {
    var list_name = '';

    return {

        getListName: function() {
            return list_name;
        },
        setListName: function(name) {
            list_name = name;
        }
    };


});

* Edit *

Please review https://github.com/centralway/lungo-angular-bridge which talks about how to use lungo and angular. Also note that if your page is completely reloading when browsing to another link, you will need to persist your shared properties into localstorage and/or a cookie.

Popup window in winform c#

This is not so easy because basically popups are not supported in windows forms. Although windows forms is based on win32 and in win32 popup are supported. If you accept a few tricks, following code will set you going with a popup. You decide if you want to put it to good use :

class PopupWindow : Control
{
    private const int WM_ACTIVATE = 0x0006;
    private const int WM_MOUSEACTIVATE = 0x0021;

    private Control ownerControl;

    public PopupWindow(Control ownerControl)
        :base()
    {
        this.ownerControl = ownerControl;
        base.SetTopLevel(true);
    }

    public Control OwnerControl
    {
        get
        {
            return (this.ownerControl as Control);
        }
        set
        {
            this.ownerControl = value;
        }
    }

    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams createParams = base.CreateParams;

            createParams.Style = WindowStyles.WS_POPUP |
                                 WindowStyles.WS_VISIBLE |
                                 WindowStyles.WS_CLIPSIBLINGS |
                                 WindowStyles.WS_CLIPCHILDREN |
                                 WindowStyles.WS_MAXIMIZEBOX |
                                 WindowStyles.WS_BORDER;
            createParams.ExStyle = WindowsExtendedStyles.WS_EX_LEFT |
                                   WindowsExtendedStyles.WS_EX_LTRREADING |
                                   WindowsExtendedStyles.WS_EX_RIGHTSCROLLBAR | 
                                   WindowsExtendedStyles.WS_EX_TOPMOST;

            createParams.Parent = (this.ownerControl != null) ? this.ownerControl.Handle : IntPtr.Zero;
            return createParams;
        }
    }

    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    public static extern IntPtr SetActiveWindow(HandleRef hWnd);

    protected override void WndProc(ref Message m)
    {
        switch (m.Msg)
        {
            case WM_ACTIVATE:
                {
                    if ((int)m.WParam == 1)
                    {
                        //window is being activated
                        if (ownerControl != null)
                        {
                            SetActiveWindow(new HandleRef(this, ownerControl.FindForm().Handle));
                        }
                    }
                    break;
                }
            case WM_MOUSEACTIVATE:
                {
                    m.Result = new IntPtr(MouseActivate.MA_NOACTIVATE);
                    return;
                    //break;
                }
        }
        base.WndProc(ref m);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        e.Graphics.FillRectangle(SystemBrushes.Info, 0, 0, Width, Height);
        e.Graphics.DrawString((ownerControl as VerticalDateScrollBar).FirstVisibleDate.ToLongDateString(), this.Font, SystemBrushes.InfoText, 2, 2);
    }
}

Experiment with it a bit, you have to play around with its position and its size. Use it wrong and nothing shows.

how to empty recyclebin through command prompt?

You can effectively "empty" the Recycle Bin from the command line by permanently deleting the Recycle Bin directory on the drive that contains the system files. (In most cases, this will be the C: drive, but you shouldn't hardcode that value because it won't always be true. Instead, use the %systemdrive% environment variable.)

The reason that this tactic works is because each drive has a hidden, protected folder with the name $Recycle.bin, which is where the Recycle Bin actually stores the deleted files and folders. When this directory is deleted, Windows automatically creates a new directory.

So, to remove the directory, use the rd command (r?emove d?irectory) with the /s parameter, which indicates that all of the files and directories within the specified directory should be removed as well:

rd /s %systemdrive%\$Recycle.bin

Do note that this action will permanently delete all files and folders currently in the Recycle Bin from all user accounts. Additionally, you will (obviously) have to run the command from an elevated command prompt in order to have sufficient privileges to perform this action.

Show/hide 'div' using JavaScript

I found this plain JavaScript code very handy!

#<script type="text/javascript">
    function toggle_visibility(id) 
    {
        var e = document.getElementById(id);
        if ( e.style.display == 'block' )
            e.style.display = 'none';
        else
            e.style.display = 'block';
    }
</script>

Is it possible to start activity through adb shell?

adb shell am broadcast -a android.intent.action.xxx

Mention xxx as the action that you mentioned in the manifest file.

Casting interfaces for deserialization in JSON.NET

(Copied from this question)

In cases where I have not had control over the incoming JSON (and so cannot ensure that it includes a $type property) I have written a custom converter that just allows you to explicitly specify the concrete type:

public class Model
{
    [JsonConverter(typeof(ConcreteTypeConverter<Something>))]
    public ISomething TheThing { get; set; }
}

This just uses the default serializer implementation from Json.Net whilst explicitly specifying the concrete type.

An overview are available on this blog post. Source code is below:

public class ConcreteTypeConverter<TConcrete> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        //assume we can convert to anything for now
        return true;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        //explicitly specify the concrete type we want to create
        return serializer.Deserialize<TConcrete>(reader);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        //use the default serialization - it works fine
        serializer.Serialize(writer, value);
    }
}

How to execute .sql script file using JDBC

Another option, this DOESN'T support comments, very useful with AmaterasERD DDL export for Apache Derby:

public void executeSqlScript(Connection conn, File inputFile) {

    // Delimiter
    String delimiter = ";";

    // Create scanner
    Scanner scanner;
    try {
        scanner = new Scanner(inputFile).useDelimiter(delimiter);
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
        return;
    }

    // Loop through the SQL file statements 
    Statement currentStatement = null;
    while(scanner.hasNext()) {

        // Get statement 
        String rawStatement = scanner.next() + delimiter;
        try {
            // Execute statement
            currentStatement = conn.createStatement();
            currentStatement.execute(rawStatement);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // Release resources
            if (currentStatement != null) {
                try {
                    currentStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            currentStatement = null;
        }
    }
scanner.close();
}

Which sort algorithm works best on mostly sorted data?

As everyone else said, be careful of naive Quicksort - that can have O(N^2) performance on sorted or nearly sorted data. Nevertheless, with an appropriate algorithm for choice of pivot (either random or median-of-three - see Choosing a Pivot for Quicksort), Quicksort will still work sanely.

In general, the difficulty with choosing algorithms such as insert sort is in deciding when the data is sufficiently out of order that Quicksort really would be quicker.

Appending items to a list of lists in python

import csv
cols = [' V1', ' I1'] # define your columns here, check the spaces!
data = [[] for col in cols] # this creates a list of **different** lists, not a list of pointers to the same list like you did in [[]]*len(positions) 
with open('data.csv', 'r') as f:
    for rec in csv.DictReader(f):
        for l, col in zip(data, cols):
            l.append(float(rec[col]))
print data

# [[3.0, 3.0], [0.01, 0.01]]

Functional programming vs Object Oriented programming

You don't necessarily have to choose between the two paradigms. You can write software with an OO architecture using many functional concepts. FP and OOP are orthogonal in nature.

Take for example C#. You could say it's mostly OOP, but there are many FP concepts and constructs. If you consider Linq, the most important constructs that permit Linq to exist are functional in nature: lambda expressions.

Another example, F#. You could say it's mostly FP, but there are many OOP concepts and constructs available. You can define classes, abstract classes, interfaces, deal with inheritance. You can even use mutability when it makes your code clearer or when it dramatically increases performance.

Many modern languages are multi-paradigm.

Recommended readings

As I'm in the same boat (OOP background, learning FP), I'd suggest you some readings I've really appreciated:

Controller 'ngModel', required by directive '...', can't be found

One possible solution to this issue is ng-model attribute is required to use that directive.

Hence adding in the 'ng-model' attribute can resolve the issue.

<input submit-required="true" ng-model="user.Name"></input>

Best way to check for IE less than 9 in JavaScript without library

You could do it in a quick and dirty fashion with a regular expression and .match():

if (navigator.userAgent.match(/MSIE\s(?!9.0)/)) {
    // ie less than version 9
}

How do I use TensorFlow GPU?

Follow the steps in the latest version of the documentation. Note: GPU and CPU functionality is now combined in a single tensorflow package

pip install tensorflow

# OLDER VERSIONS pip install tensorflow-gpu

https://www.tensorflow.org/install/gpu

This is a great guide for installing drivers and CUDA if needed: https://www.quantstart.com/articles/installing-tensorflow-22-on-ubuntu-1804-with-an-nvidia-gpu/

Changing CSS Values with Javascript

Please! Just ask w3 (http://www.quirksmode.org/dom/w3c_css.html)! Or actually, it took me five hours... but here it is!

function css(selector, property, value) {
    for (var i=0; i<document.styleSheets.length;i++) {//Loop through all styles
        //Try add rule
        try { document.styleSheets[i].insertRule(selector+ ' {'+property+':'+value+'}', document.styleSheets[i].cssRules.length);
        } catch(err) {try { document.styleSheets[i].addRule(selector, property+':'+value);} catch(err) {}}//IE
    }
}

The function is really easy to use.. example:

<div id="box" class="boxes" onclick="css('#box', 'color', 'red')">Click Me!</div>
Or:
<div class="boxes" onmouseover="css('.boxes', 'color', 'green')">Mouseover Me!</div>
Or:
<div class="boxes" onclick="css('body', 'border', '1px solid #3cc')">Click Me!</div>

Oh..


EDIT: as @user21820 described in its answer, it might be a bit unnecessary to change all stylesheets on the page. The following script works with IE5.5 as well as latest Google Chrome, and adds only the above described css() function.

(function (scope) {
    // Create a new stylesheet in the bottom
    // of <head>, where the css rules will go
    var style = document.createElement('style');
    document.head.appendChild(style);
    var stylesheet = style.sheet;
    scope.css = function (selector, property, value) {
        // Append the rule (Major browsers)
        try { stylesheet.insertRule(selector+' {'+property+':'+value+'}', stylesheet.cssRules.length);
        } catch(err) {try { stylesheet.addRule(selector, property+':'+value); // (pre IE9)
        } catch(err) {console.log("Couldn't add style");}} // (alien browsers)
    }
})(window);

How to create a generic array?

checked :

public Constructor(Class<E> c, int length) {

    elements = (E[]) Array.newInstance(c, length);
}

or unchecked :

public Constructor(int s) {
    elements = new Object[s];
}

Django database query: How to get object by id?

You can also use get_object_or_404 django shortcut. It raises a 404 error if object is not found.

Selenium: Can I set any of the attribute value of a WebElement in Selenium?

Fancy C# extension method based on previous answers:

public static IWebElement SetAttribute(this IWebElement element, string name, string value)
{
    var driver = ((IWrapsDriver)element).WrappedDriver;
    var jsExecutor = (IJavaScriptExecutor)driver;
    jsExecutor.ExecuteScript("arguments[0].setAttribute(arguments[1], arguments[2]);", element, name, value);

    return element;
}

Usage:

driver.FindElement(By.Id("some_option")).SetAttribute("selected", "selected");

How do I parse JSON in Android?

  1. Writing JSON Parser Class

    public class JSONParser {
    
        static InputStream is = null;
        static JSONObject jObj = null;
        static String json = "";
    
        // constructor
        public JSONParser() {}
    
        public JSONObject getJSONFromUrl(String url) {
    
            // Making HTTP request
            try {
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
    
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
    
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
    
            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
    
            // return JSON String
            return jObj;
    
        }
    }
    
  2. Parsing JSON Data
    Once you created parser class next thing is to know how to use that class. Below i am explaining how to parse the json (taken in this example) using the parser class.

    2.1. Store all these node names in variables: In the contacts json we have items like name, email, address, gender and phone numbers. So first thing is to store all these node names in variables. Open your main activity class and declare store all node names in static variables.

    // url to make request
    private static String url = "http://api.9android.net/contacts";
    
    // JSON Node names
    private static final String TAG_CONTACTS = "contacts";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_EMAIL = "email";
    private static final String TAG_ADDRESS = "address";
    private static final String TAG_GENDER = "gender";
    private static final String TAG_PHONE = "phone";
    private static final String TAG_PHONE_MOBILE = "mobile";
    private static final String TAG_PHONE_HOME = "home";
    private static final String TAG_PHONE_OFFICE = "office";
    
    // contacts JSONArray
    JSONArray contacts = null;
    

    2.2. Use parser class to get JSONObject and looping through each json item. Below i am creating an instance of JSONParser class and using for loop i am looping through each json item and finally storing each json data in variable.

    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();
    
    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);
    
        try {
        // Getting Array of Contacts
        contacts = json.getJSONArray(TAG_CONTACTS);
    
        // looping through All Contacts
        for(int i = 0; i < contacts.length(); i++){
            JSONObject c = contacts.getJSONObject(i);
    
            // Storing each json item in variable
            String id = c.getString(TAG_ID);
            String name = c.getString(TAG_NAME);
            String email = c.getString(TAG_EMAIL);
            String address = c.getString(TAG_ADDRESS);
            String gender = c.getString(TAG_GENDER);
    
            // Phone number is agin JSON Object
            JSONObject phone = c.getJSONObject(TAG_PHONE);
            String mobile = phone.getString(TAG_PHONE_MOBILE);
            String home = phone.getString(TAG_PHONE_HOME);
            String office = phone.getString(TAG_PHONE_OFFICE);
    
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    

How do I convert csv file to rdd

I think you can try to load that csv into a RDD and then create a dataframe from that RDD, here is the document of creating dataframe from rdd:http://spark.apache.org/docs/latest/sql-programming-guide.html#interoperating-with-rdds

How to update parent's state in React?

I like the answer regarding passing functions around, its a very handy technique.

On the flip side you can also achieve this using pub/sub or using a variant, a dispatcher, as Flux does. The theory is super simple, have component 5 dispatch a message which component 3 is listening for. Component 3 then updates its state which triggers the re-render. This requires stateful components, which, depending on your viewpoint, may or may not be an anti-pattern. I'm against them personally and would rather that something else is listening for dispatches and changes state from the very top-down (Redux does this, but adds additional terminology).

import { Dispatcher } from flux
import { Component } from React

const dispatcher = new Dispatcher()

// Component 3
// Some methods, such as constructor, omitted for brevity
class StatefulParent extends Component {
  state = {
    text: 'foo'
  } 

  componentDidMount() {
    dispatcher.register( dispatch => {
      if ( dispatch.type === 'change' ) {
        this.setState({ text: 'bar' })
      }
    }
  }

  render() {
    return <h1>{ this.state.text }</h1>
  }
}

// Click handler
const onClick = event => {
  dispatcher.dispatch({
    type: 'change'
  })
}

// Component 5 in your example
const StatelessChild = props => {
  return <button onClick={ onClick }>Click me</button> 
}

The dispatcher bundles with Flux is very simple, it simply registers callbacks and invokes them when any dispatch occurs, passing through the contents on the dispatch (in the above terse example there is no payload with the dispatch, simply a message id). You could adapt this to traditional pub/sub (e.g. using the EventEmitter from events, or some other version) very easily if that makes more sense to you.

Target Unreachable, identifier resolved to null in JSF 2.2

I want to share my experience with this Exception. My JSF 2.2 application worked fine with WildFly 8.0, but one time, when I started server, i got this "Target Unreacheable" exception. Actually, there was no problem with JSF annotations or tags.

Only thing I had to do was cleaning the project. After this operation, my app is working fine again.

I hope this will help someone!

javascript change background color on click

You can use setTimeout():

_x000D_
_x000D_
var addBg = function(e) {_x000D_
  e = e || window.event;_x000D_
  e.preventDefault();_x000D_
  var el = e.target || e.srcElement;_x000D_
  el.className = 'bg';_x000D_
  setTimeout(function() {_x000D_
    removeBg(el);_x000D_
  }, 10 * 1000); //<-- (in miliseconds)_x000D_
};_x000D_
_x000D_
var removeBg = function(el) {_x000D_
  el.className = '';_x000D_
};
_x000D_
div {_x000D_
  border: 1px solid grey;_x000D_
  padding: 5px 7px;_x000D_
  display: inline-block;_x000D_
  margin: 5px;_x000D_
}_x000D_
.bg {_x000D_
  background: orange;_x000D_
}
_x000D_
<body onclick='addBg(event);'>This is body_x000D_
  <br/>_x000D_
  <div onclick='addBg(event);'>This is div_x000D_
  </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Using jQuery:

_x000D_
_x000D_
var addBg = function(e) {_x000D_
  e.stopPropagation();_x000D_
  var el = $(this);_x000D_
  el.addClass('bg');_x000D_
  setTimeout(function() {_x000D_
    removeBg(el);_x000D_
  }, 10 * 1000); //<-- (in miliseconds)_x000D_
};_x000D_
_x000D_
var removeBg = function(el) {_x000D_
  $(el).removeClass('bg');_x000D_
};_x000D_
_x000D_
$(function() {_x000D_
  $('body, div').on('click', addBg);_x000D_
});
_x000D_
div {_x000D_
  border: 1px solid grey;_x000D_
  padding: 5px 7px;_x000D_
  display: inline-block;_x000D_
  margin: 5px;_x000D_
}_x000D_
.bg {_x000D_
  background: orange;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
_x000D_
<body>This is body_x000D_
  <br/>_x000D_
  <div>This is div</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to avoid installing "Unlimited Strength" JCE policy files when deploying an application?

This is now no longer needed for Java 9, nor for any recent release of Java 6, 7, or 8. Finally! :)

Per JDK-8170157, the unlimited cryptographic policy is now enabled by default.

Specific versions from the JIRA issue:

  • Java 9 (10, 11, etc..): Any official release!
  • Java 8u161 or later (Available now)
  • Java 7u171 or later (Only available through 'My Oracle Support')
  • Java 6u181 or later (Only available through 'My Oracle Support')

Note that if for some odd reason the old behavior is needed in Java 9, it can be set using:

Security.setProperty("crypto.policy", "limited");

How to compare two tables column by column in oracle

Using the minus operator was working but also it was taking more time to execute which was not acceptable. I have a similar kind of requirement for data migration and I used the NOT IN operator for that. The modified query is :

select * 
from A 
where (emp_id,emp_name) not in 
   (select emp_id,emp_name from B) 
   union all 
select * from B 
where (emp_id,emp_name) not in 
   (select emp_id,emp_name from A); 

This query executed fast. Also you can add any number of columns in the select query. Only catch is that both tables should have the exact same table structure for this to be executed.

How to switch between python 2.7 to python 3 from command line?

For Windows 7, I just rename the python.exe from the Python 3 folder to python3.exe and add the path into the environment variables. Using that, I can execute python test_script.py and the script runs with Python 2.7 and when I do python3 test_script.py, it runs the script in Python 3.

To add Python 3 to the environment variables, follow these steps -

  1. Right Click on My Computer and go to Properties.
  2. Go to Advanced System Settings.
  3. Click on Environment Variables and edit PATH and add the path to your Python 3 installation directory.

For example,

enter image description here

Best C# API to create PDF

My work uses Winnovative's PDF generator (We've used it mainly to convert HTML to PDF, but you can generate it other ways as well)

Convert JSON String to JSON Object c#

You can try like following:

string output = JsonConvert.SerializeObject(jsonStr);

Array Index Out of Bounds Exception (Java)

import java.io.*;
import java.util.Scanner;
class ar1 {
    public static void main(String[] args) {
        //Scanner sc=new Scanner(System.in);
        int[] a={10,20,30,40,12,32};
        int bi=0,sm=0;
        //bi=sc.nextInt();
        //sm=sc.nextInt();
        for(int i=0;i<=a.length-1;i++) {
            if(a[i]>a[i+1]) 
                bi=a[i];

            if(a[i]<a[i+1])
                sm=a[i];
        }
        System.out.println("big"+bi+"small"+sm);
    }
}

typescript - cloning object

For deep cloning an object that can contain another objects, arrays and so on i use:

const clone = <T>(source: T): T => {
  if (source === null) return source

  if (source instanceof Date) return new Date(source.getTime()) as any

  if (source instanceof Array) return source.map((item: any) => clone<any>(item)) as any

  if (typeof source === 'object' && source !== {}) {
    const clonnedObj = { ...(source as { [key: string]: any }) } as { [key: string]: any }
    Object.keys(clonnedObj).forEach(prop => {
      clonnedObj[prop] = clone<any>(clonnedObj[prop])
    })

    return clonnedObj as T
  }

  return source
}

Use:

const obj = {a: [1,2], b: 's', c: () => { return 'h'; }, d: null, e: {a:['x'] }}
const objClone = clone(obj)

SQL Server 2012 column identity increment jumping from 6 to 1000+ on 7th entry

While trace flag 272 may work for many, it definitely won't work for hosted Sql Server Express installations. So, I created an identity table, and use this through an INSTEAD OF trigger. I'm hoping this helps someone else, and/or gives others an opportunity to improve my solution. The last line allows returning the last identity column added. Since I typically use this to add a single row, this works to return the identity of a single inserted row.

The identity table:

CREATE TABLE [dbo].[tblsysIdentities](
[intTableId] [int] NOT NULL,
[intIdentityLast] [int] NOT NULL,
[strTable] [varchar](100) NOT NULL,
[tsConcurrency] [timestamp] NULL,
CONSTRAINT [PK_tblsysIdentities] PRIMARY KEY CLUSTERED 
(
    [intTableId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,  ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

and the insert trigger:

-- INSERT --
IF OBJECT_ID ('dbo.trgtblsysTrackerMessagesIdentity', 'TR') IS NOT NULL
   DROP TRIGGER dbo.trgtblsysTrackerMessagesIdentity;
GO
CREATE TRIGGER trgtblsysTrackerMessagesIdentity
ON dbo.tblsysTrackerMessages
INSTEAD OF INSERT AS 
BEGIN
    DECLARE @intTrackerMessageId INT
    DECLARE @intRowCount INT

    SET @intRowCount = (SELECT COUNT(*) FROM INSERTED)

    SET @intTrackerMessageId = (SELECT intIdentityLast FROM tblsysIdentities WHERE intTableId=1)
    UPDATE tblsysIdentities SET intIdentityLast = @intTrackerMessageId + @intRowCount WHERE intTableId=1

    INSERT INTO tblsysTrackerMessages( 
    [intTrackerMessageId],
    [intTrackerId],
    [strMessage],
    [intTrackerMessageTypeId],
    [datCreated],
    [strCreatedBy])
    SELECT @intTrackerMessageId + ROW_NUMBER() OVER (ORDER BY [datCreated]) AS [intTrackerMessageId], 
    [intTrackerId],
   [strMessage],
   [intTrackerMessageTypeId],
   [datCreated],
   [strCreatedBy] FROM INSERTED;

   SELECT TOP 1 @intTrackerMessageId + @intRowCount FROM INSERTED;
END

How can I query a value in SQL Server XML column

declare @T table(Roles xml)

insert into @T values
('<root>
   <role>Alpha</role>
   <role>Beta</role>
   <role>Gamma</role>
</root>')

declare @Role varchar(10)

set @Role = 'Beta'

select Roles
from @T
where Roles.exist('/root/role/text()[. = sql:variable("@Role")]') = 1

If you want the query to work as where col like '%Beta%' you can use contains

declare @T table(Roles xml)

insert into @T values
('<root>
   <role>Alpha</role>
   <role>Beta</role>
   <role>Gamma</role>
</root>')

declare @Role varchar(10)

set @Role = 'et'

select Roles
from @T
where Roles.exist('/root/role/text()[contains(., sql:variable("@Role"))]') = 1

How can one run multiple versions of PHP 5.x on a development LAMP server?

I have several projects running on my box. If you have already installed more than one version, this bash script should help you easily switch. At the moment I have php5, php5.6, and php7.0 which I often swtich back and forth depending on the project I am working on. Here is my code.

Feel free to copy. Make sure you understand how the code works. This is for the webhostin. my local box my mods are stored at /etc/apache2/mods-enabled/

    #!/bin/bash
# This file is for switching php versions.  
# To run this file you must use bash, not sh
# 
    # OS: Ubuntu 14.04 but should work on any linux
# Example: bash phpswitch.sh 7.0
# Written by Daniel Pflieger
# growlingflea at g mail dot com

NEWVERSION=$1  #this is the git directory target

#get the active php enabled mod by getting the array of files and store
#it to a variable
VAR=$(ls /etc/apache2/mods-enabled/php*)

#parse the returned variables and get the version of php that is active.
IFS=' ' read -r -a array <<< "$VAR"
array[0]=${array[0]#*php}
array[0]=${array[0]%.conf}


#confirm that the newversion veriable isn't empty.. if it is tell user 
#current version and exit
if [ "$NEWVERSION" = "" ]; then
echo current version is ${array[0]}.  To change version please use argument
exit 1
fi 

OLDVERSION=${array[0]}
#confirm to the user this is what they want to do
echo "Update php"  ${OLDVERSION} to ${NEWVERSION}


#give the user the opportunity to use CTRL-C to exit ot just hit return
read x

#call a2dismod function: this deactivate the current php version
sudo a2dismod php${OLDVERSION}

#call the a2enmod version.  This enables the new mode
sudo a2enmod php${NEWVERSION} 

echo "Restart service??"
read x

#restart apache
sudo service apache2 restart

Split text with '\r\n'

Following code gives intended results.

string text="some interesting text\nsome text that should be in the same line\r\nsome 
text should be in another line"
var results = text.Split(new[] {"\n","\r\n"}, StringSplitOptions.None);

How to change a css class style through Javascript?

I'd highly recommend jQuery. It then becomes as simple as:

$('#mydiv').addClass('newclass');

You don't have to worry about removing the old class then as addClass() will only append to it. You also have removeClass();

The other advantage over the getElementById() method is you can apply it to multiple elements at the same time with a single line of code.

$('div').addClass('newclass');
$('.oldclass').addClass('newclass');

The first example will add the class to all DIV elements on the page. The second example will add the new class to all elements that currently have the old class.

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?

First, create the derived value:

df.loc[0, 'C'] = df.loc[0, 'D']

Then iterate through the remaining rows and fill the calculated values:

for i in range(1, len(df)):
    df.loc[i, 'C'] = df.loc[i-1, 'C'] * df.loc[i, 'A'] + df.loc[i, 'B']


  Index_Date   A   B    C    D
0 2015-01-31  10  10   10   10
1 2015-02-01   2   3   23   22
2 2015-02-02  10  60  290  280

How do implement a breadth first traversal?

For implementing the breadth first search, you should use a queue. You should push the children of a node to the queue (left then right) and then visit the node (print data). Then, yo should remove the node from the queue. You should continue this process till the queue becomes empty. You can see my implementation of the BFS here: https://github.com/m-vahidalizadeh/foundations/blob/master/src/algorithms/TreeTraverse.java

react-router scroll to top on every transition

This is hacky (but works): I just add

window.scrollTo(0,0);

to render();

Best way to get the max value in a Spark dataframe column

I used another solution (by @satprem rath) already present in this chain.

To find the min value of age in the dataframe:

df.agg(min("age")).show()

+--------+
|min(age)|
+--------+
|      29|
+--------+

edit: to add more context.

While the above method printed the result, I faced issues when assigning the result to a variable to reuse later.

Hence, to get only the int value assigned to a variable:

from pyspark.sql.functions import max, min  

maxValueA = df.agg(max("A")).collect()[0][0]
maxValueB = df.agg(max("B")).collect()[0][0]

Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

This explains better: Postman docs

Request body

While constructing requests, you would be dealing with the request body editor a lot. Postman lets you send almost any kind of HTTP request (If you can't send something, let us know!). The body editor is divided into 4 areas and has different controls depending on the body type.

form-data

multipart/form-data is the default encoding a web form uses to transfer data. This simulates filling a form on a website, and submitting it. The form-data editor lets you set key/value pairs (using the key-value editor) for your data. You can attach files to a key as well. Do note that due to restrictions of the HTML5 spec, files are not stored in history or collections. You would have to select the file again at the time of sending a request.

urlencoded

This encoding is the same as the one used in URL parameters. You just need to enter key/value pairs and Postman will encode the keys and values properly. Note that you can not upload files through this encoding mode. There might be some confusion between form-data and urlencoded so make sure to check with your API first.

raw

A raw request can contain anything. Postman doesn't touch the string entered in the raw editor except replacing environment variables. Whatever you put in the text area gets sent with the request. The raw editor lets you set the formatting type along with the correct header that you should send with the raw body. You can set the Content-Type header manually as well. Normally, you would be sending XML or JSON data here.

binary

binary data allows you to send things which you can not enter in Postman. For example, image, audio or video files. You can send text files as well. As mentioned earlier in the form-data section, you would have to reattach a file if you are loading a request through the history or the collection.

UPDATE

As pointed out by VKK, the WHATWG spec say urlencoded is the default encoding type for forms.

The invalid value default for these attributes is the application/x-www-form-urlencoded state. The missing value default for the enctype attribute is also the application/x-www-form-urlencoded state.

Which to use <div class="name"> or <div id="name">?

class is used when u want to set properties for a group of elements, but id can be set for only one element.

Print directly from browser without print popup window

IE9 no longer supports triggering the Print() VBScript by calling window.print() like IE7 and IE8 do, and thus window.print() will now always trigger the print dialog in IE9.

The fix is pretty simple. You just need to call Print() itself, instead of window.print() in the onclick event.

I've described the fix in more detail in an answer to another question, with a working code example sporting slightly updated HTML syntax (as much as possible while still tested as working code).

You can find that sample code here:

Bypass Printdialog in IE9

pycharm convert tabs to spaces automatically

PyCharm 2019.1

If you want to change the general settings:

Open preferences, in macOS ?; or in Windows/Linux Ctrl + Alt + S.

Go to Editor -> Code Style -> Python, and if you want to follow PEP-8, choose Tab size: 4, Indent: 4, and Continuation indent: 8 as shown below:

enter image description here

Apply the changes, and click on OK.

If you want to apply the changes just to the current file

Option 1: You can choose in the navigation bar: Edit -> Convert Indent -> To Spaces. (see image below)

enter image description here

Option 2: You can execute "To Spaces" action by running the Find Action shortcut: ??A on macOS or ctrl?A on Windows/Linux. Then type "To Spaces", and run the action as shown in the image below.

enter image description here

Disable future dates after today in Jquery Ui Datepicker

You can simply do this

$(function() {
    $( "#datepicker" ).datepicker({  maxDate: new Date });
  });

JSFiddle

FYI: while checking the documentation, found that it also accepts numeric values too.

Number: A number of days from today. For example 2 represents two days from today and -1 represents yesterday.

so 0 represents today. Therefore you can do this too

 $( "#datepicker" ).datepicker({  maxDate: 0 });

Ansible: How to delete files and folders inside a directory?

Remove the directory (basically a copy of https://stackoverflow.com/a/38201611/1695680), Ansible does this operation with rmtree under the hood.

- name: remove files and directories
  file:
    state: "{{ item }}"
    path: "/srv/deleteme/"
    owner: 1000  # set your owner, group, and mode accordingly
    group: 1000
    mode: '0777'
  with_items:
    - absent
    - directory

If you don't have the luxury of removing the whole directory and recreating it, you can scan it for files, (and directories), and delete them one by one. Which will take a while. You probably want to make sure you have [ssh_connection]\npipelining = True in your ansible.cfg on.

- block:
  - name: 'collect files'
    find:
      paths: "/srv/deleteme/"
      hidden: True
      recurse: True
      # file_type: any  # Added in ansible 2.3
    register: collected_files

  - name: 'collect directories'
    find:
      paths: "/srv/deleteme/"
      hidden: True
      recurse: True
      file_type: directory
    register: collected_directories

  - name: remove collected files and directories
    file:
      path: "{{ item.path }}"
      state: absent
    with_items: >
      {{
        collected_files.files
        + collected_directories.files
      }}

Convert YYYYMMDD string date to a datetime value

You should have to use DateTime.TryParseExact.

var newDate = DateTime.ParseExact("20111120", 
                                  "yyyyMMdd", 
                                   CultureInfo.InvariantCulture);

OR

string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;

if (DateTime.TryParseExact(str, 
                           format, 
                           System.Globalization.CultureInfo.InvariantCulture,
                           System.Globalization.DateTimeStyles.None, 
                           out date))
{
     //valid
}

Android - save/restore fragment state

When a fragment is moved to the backstack, it isn't destroyed. All the instance variables remain there. So this is the place to save your data. In onActivityCreated you check the following conditions:

  1. Is the bundle != null? If yes, that's where the data is saved (probably orientation change).
  2. Is there data saved in instance variables? If yes, restore your state from them (or maybe do nothing, because everything is as it should be).
  3. Otherwise your fragment is shown for the first time, create everything anew.

Edit: Here's an example

public class ExampleFragment extends Fragment {
    private List<String> myData;

    @Override
    public void onSaveInstanceState(final Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable("list", (Serializable) myData);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (savedInstanceState != null) {
            //probably orientation change
            myData = (List<String>) savedInstanceState.getSerializable("list");
        } else {
            if (myData != null) {
                //returning from backstack, data is fine, do nothing
            } else {
                //newly created, compute data
                myData = computeData();
            }
        }
    }
}

Update Rows in SSIS OLEDB Destination

You can't do a bulk-update in SSIS within a dataflow task with the OOB components.

The general pattern is to identify your inserts, updates and deletes and push the updates and deletes to a staging table(s) and after the Dataflow Task, use a set-based update or delete in an Execute SQL Task. Look at Andy Leonard's Stairway to Integration Services series. Scroll about 3/4 the way down the article to "Set-Based Updates" to see the pattern.

Stage data

http://www.sqlservercentral.com/Images/11369.png

Set based updates

enter image description here

You'll get much better performance with a pattern like this versus using the OLE DB Command transformation for anything but trivial amounts of data.

If you are into third party tools, I believe CozyRoc and I know PragmaticWorks have a merge destination component.

Get the time difference between two datetimes

InTime=06:38,Outtime=15:40

 calTimeDifference(){
        this.start = dailyattendance.InTime.split(":");
        this.end = dailyattendance.OutTime.split(":");
        var time1 = ((parseInt(this.start[0]) * 60) + parseInt(this.start[1]))
        var time2 = ((parseInt(this.end[0]) * 60) + parseInt(this.end[1]));
        var time3 = ((time2 - time1) / 60);
        var timeHr = parseInt(""+time3);
        var  timeMin = ((time2 - time1) % 60);
    }

2 "style" inline css img tags?

You don't need 2 style attributes - just use one:

<img src="http://img705.imageshack.us/img705/119/original120x75.png" 
                                     style="height:100px;width:100px;" alt="25"/>

Consider, however, using a CSS class instead:

CSS:

.100pxSquare
{
  width: 100px;
  height: 100px;
}

HTML:

<img src="http://img705.imageshack.us/img705/119/original120x75.png" 
                                          class="100pxSquare" alt="25"/>

How do I truncate a .NET string?

For the sake of (over)complexity I'll add my overloaded version which replaces the last 3 characters with an ellipsis in respect with the maxLength parameter.

public static string Truncate(this string value, int maxLength, bool replaceTruncatedCharWithEllipsis = false)
{
    if (replaceTruncatedCharWithEllipsis && maxLength <= 3)
        throw new ArgumentOutOfRangeException("maxLength",
            "maxLength should be greater than three when replacing with an ellipsis.");

    if (String.IsNullOrWhiteSpace(value)) 
        return String.Empty;

    if (replaceTruncatedCharWithEllipsis &&
        value.Length > maxLength)
    {
        return value.Substring(0, maxLength - 3) + "...";
    }

    return value.Substring(0, Math.Min(value.Length, maxLength)); 
}

Add borders to cells in POI generated Excel File

HSSFCellStyle style=workbook.createCellStyle();
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);

How to read a single character at a time from a file in Python?

Just:

myfile = open(filename)
onecaracter = myfile.read(1)

How to increase time in web.config for executing sql query

You can do one thing.

  1. In the AppSettings.config (create one if doesn't exist), create a key value pair.
  2. In the Code pull the value and convert it to Int32 and assign it to command.TimeOut.

like:- In appsettings.config ->

<appSettings>    
   <add key="SqlCommandTimeOut" value="240"/>
</appSettings>

In Code ->

command.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SqlCommandTimeOut"]);

That should do it.

Note:- I faced most of the timeout issues when I used SqlHelper class from microsoft application blocks. If you have it in your code and are facing timeout problems its better you use sqlcommand and set its timeout as described above. For all other scenarios sqlhelper should do fine. If your client is ok with waiting a little longer than what sqlhelper class offers you can go ahead and use the above technique.

example:- Use this -

 SqlCommand cmd = new SqlCommand(completequery);

 cmd.CommandTimeout =  Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SqlCommandTimeOut"]);

 SqlConnection con = new SqlConnection(sqlConnectionString);
 SqlDataAdapter adapter = new SqlDataAdapter();
 con.Open();
 adapter.SelectCommand = new SqlCommand(completequery, con);
 adapter.Fill(ds);
 con.Close();

Instead of

DataSet ds = new DataSet();
ds = SqlHelper.ExecuteDataset(sqlConnectionString, CommandType.Text, completequery);

Update: Also refer to @Triynko answer below. It is important to check that too.

Move div to new line

What about something like this.

<div id="movie_item">
    <div class="movie_item_poster">
        <img src="..." style="max-width: 100%; max-height: 100%;">
    </div>

     <div id="movie_item_content">
        <div class="movie_item_content_year">year</div>
        <div class="movie_item_content_title">title</div>
        <div class="movie_item_content_plot">plot</div>
    </div>

    <div class="movie_item_toolbar">
        Lorem Ipsum...
    </div>
</div>

You don't have to float both movie_item_poster AND movie_item_content. Just float one of them...

#movie_item {
    position: relative;
    margin-top: 10px;
    height: 175px;
}

.movie_item_poster {
    float: left;
    height: 150px;
    width: 100px;
}

.movie_item_content {
    position: relative;
}

.movie_item_content_title {
}

.movie_item_content_year {
    float: right;
}

.movie_item_content_plot {
}

.movie_item_toolbar {
    clear: both;
    vertical-align: bottom;
    width: 100%;
    height: 25px;
}

Here it is as a JSFiddle.

What is the best way to find the users home directory in Java?

Actually with Java 8 the right way is to use:

System.getProperty("user.home");

The bug JDK-6519127 has been fixed and the "Incompatibilities between JDK 8 and JDK 7" section of the release notes states:

Area: Core Libs / java.lang

Synopsis

The steps used to determine the user's home directory on Windows have changed to follow the Microsoft recommended approach. This change might be observable on older editions of Windows or where registry settings or environment variables are set to other directories. Nature of Incompatibility

behavioral RFE

6519127

Despite the question being old I leave this for future reference.

ReactNative: how to center text?

Wherever you have Text component in your page just you need to set style of the Text component.

 <Text style={{ textAlign: 'center' }}> Text here </Text>

you don't need to add any other styling property, this is spectacular magic it will set you text in center of the your UI.

Change color when hover a font awesome icon?

use - !important - to override default black

_x000D_
_x000D_
.fa-heart:hover{_x000D_
   color:red !important;_x000D_
}_x000D_
.fa-heart-o:hover{_x000D_
   color:red !important;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">_x000D_
_x000D_
<i class="fa fa-heart fa-2x"></i>_x000D_
<i class="fa fa-heart-o fa-2x"></i>
_x000D_
_x000D_
_x000D_

Avoiding "resource is out of sync with the filesystem"

When you open an Eclipse workspace from within a clearcase view and try to rename the project, you will often get the pop-up warning ... “Resource ‘project’ is out of sync with the file system”. If refreshing the project does not fix the problem, then do the following workaround: a. Open workspace WITHOUT being in a view b. Select the project in Project Explorer c. ClearCase -> Associate Project (project should now look like project [] ) d. Right click project -> Refresh (vob sub-folders should now be empty) e. Right click project -> Rename ... f. Enter New name

Now you can close the workspace, reopen it in a view and refresh the project. You may also dissociate the project if you prefer the project not to be associated with the vob.

How can I iterate over the elements in Hashmap?

HashMap<Integer,Player> hash = new HashMap<Integer,Player>();
Set keys = hash.keySet();   
Iterator itr = keys.iterator();

while(itr.hasNext()){
    Integer key = itr.next();
    Player objPlayer = (Player) hash.get(key);
    System.out.println("The player "+objPlayer.getName()+" has "+objPlayer.getScore()+" points");
}

You can use this code to print all scores in your format.

What is the reason for a red exclamation mark next to my project in Eclipse?

I had a maven project giving me same thing. It showed that it couldnt find the jar with that version (dependency) and I knew its there and is correct -

So, for me the solution was to 1 delete the local repository. 2 Clean the project. 3 Disable the maven nature. 4 Generate eclipse artifacts and 5 re-configure as maven project.

(in order)

Calling multiple JavaScript functions on a button click

Try this .... I got it... onClientClick="var b=validateView();if(b) var b=ShowDiv1();return b;"

How should I read a file line-by-line in Python?

if you're turned off by the extra line, you can use a wrapper function like so:

def with_iter(iterable):
    with iterable as iter:
        for item in iter:
            yield item

for line in with_iter(open('...')):
    ...

in Python 3.3, the yield from statement would make this even shorter:

def with_iter(iterable):
    with iterable as iter:
        yield from iter

Structuring online documentation for a REST API

That's a very complex question for a simple answer.

You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.

Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.

At the very top level I think quality REST API docs require at least the following:

  • a list of all your API endpoints (base/relative URLs)
  • corresponding HTTP GET/POST/... method type for each endpoint
  • request/response MIME-type (how to encode params and parse replies)
  • a sample request/response, including HTTP headers
  • type and format specified for all params, including those in the URL, body and headers
  • a brief text description and important notes
  • a short code snippet showing the use of the endpoint in popular web programming languages

Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.

How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?

The project JsonSubTypes implement a generic converter that handle this feature with the helps of attributes.

For the concrete sample provided here is how it works:

    [JsonConverter(typeof(JsonSubtypes))]
    [JsonSubtypes.KnownSubTypeWithProperty(typeof(Employee), "JobTitle")]
    [JsonSubtypes.KnownSubTypeWithProperty(typeof(Artist), "Skill")]
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    public class Employee : Person
    {
        public string Department { get; set; }
        public string JobTitle { get; set; }
    }

    public class Artist : Person
    {
        public string Skill { get; set; }
    }

    [TestMethod]
    public void Demo()
    {
        string json = "[{\"Department\":\"Department1\",\"JobTitle\":\"JobTitle1\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}," +
                      "{\"Department\":\"Department1\",\"JobTitle\":\"JobTitle1\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}," +
                      "{\"Skill\":\"Painter\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}]";


        var persons = JsonConvert.DeserializeObject<IReadOnlyCollection<Person>>(json);
        Assert.AreEqual("Painter", (persons.Last() as Artist)?.Skill);
    }

Android design support library for API 28 (P) not working

Android documentation is clear on this.Go to the below page.Underneath,there are two columns with names "OLD BUILD ARTIFACT" and "AndroidX build artifact"

https://developer.android.com/jetpack/androidx/migrate

Now you have many dependencies in gradle.Just match those with Androidx build artifacts and replace them in the gradle.

That won't be enough.

Go to your MainActivity (repeat this for all activities) and remove the word AppCompact Activity in the statement "public class MainActivity extends AppCompatActivity " and write the same word again.But this time androidx library gets imported.Until now appcompact support file got imported and used (also, remove that appcompact import statement).

Also,go to your layout file. Suppose you have a constraint layout,then you can notice that the first line constraint layout in xml file have something related to appcompact.So just delete it and write Constraint layout again.But now androidx related constraint layout gets added.

repeat this for as many activities and as many xml layout files..

But don't worry: Android Studio displays all such possible errors while compiling.

How to fix Cannot find module 'typescript' in Angular 4?

Run: npm link typescript if you installed globally

But if you have not installed typescript try this command: npm install typescript

Owl Carousel Won't Autoplay

Owl Carousel version matters a lot, as of now (2nd Aug 2020) the version is 2.3.4 and the right options for autoplay are:

$(".owl-carousel").owlCarousel({
    autoplay : true,
    autoplayTimeout: 3000,//Autoplay interval timeout.
    loop:true,//Infinity loop. Duplicate last and first items to get loop illusion.
    items:1 //The number of items you want to see on the screen.
});

Read more Owl configurations

How can I connect to Android with ADB over TCP?

There are two ways to connect your Android device with ADB over TCP?

First way

Follow this steps

First use below command to get your device IP Address

adb shell ifconfig

OUTPUT of above command

wlan0     Link encap:UNSPEC    Driver icnss
          inet addr:XXX.XXX.X.XX  Bcast:XXX.XXX.X.XXX

With the help you above command you will find the IP Address of connected device

Now use below command

adb tcpip 5555

The above command will restart this TCP port: 5555

Now use below command to connect your device

adb connect XXX.XXX.X.XXX:5555
            ^^^ ^^^ ^ ^^^
        IP Address of device

Second way

You can use Android Studio Plugin Android device with ADB

Android WiFi ADB - IntelliJ/Android Studio Plugin

IntelliJ and Android Studio plugin created to quickly connect your Android device over WiFi to install, run and debug your applications without a USB connected. Press one button and forget about your USB cable

Please check this article for more information

Connect Android Device with Wifi within Android Studio

Eclipse java debugging: source not found

Attach source -> Add -> External Archive -> select the jar -> open -> done

the catch is look for the sources jar and attach this jar.

for example the jar ends with "-sources" Stax2-api-3.4.1-sources

Case-insensitive string comparison in C++

boost::iequals is not utf-8 compatible in the case of string. You can use boost::locale.

comparator<char,collator_base::secondary> cmpr;
cout << (cmpr(str1, str2) ? "str1 < str2" : "str1 >= str2") << endl;
  • Primary -- ignore accents and character case, comparing base letters only. For example "facade" and "Façade" are the same.
  • Secondary -- ignore character case but consider accents. "facade" and "façade" are different but "Façade" and "façade" are the same.
  • Tertiary -- consider both case and accents: "Façade" and "façade" are different. Ignore punctuation.
  • Quaternary -- consider all case, accents, and punctuation. The words must be identical in terms of Unicode representation.
  • Identical -- as quaternary, but compare code points as well.

What does the term "canonical form" or "canonical representation" in Java mean?

Wikipedia points to the term Canonicalization.

A process for converting data that has more than one possible representation into a "standard" canonical representation. This can be done to compare different representations for equivalence, to count the number of distinct data structures, to improve the efficiency of various algorithms by eliminating repeated calculations, or to make it possible to impose a meaningful sorting order.

The Unicode example made the most sense to me:

Variable-length encodings in the Unicode standard, in particular UTF-8, have more than one possible encoding for most common characters. This makes string validation more complicated, since every possible encoding of each string character must be considered. A software implementation which does not consider all character encodings runs the risk of accepting strings considered invalid in the application design, which could cause bugs or allow attacks. The solution is to allow a single encoding for each character. Canonicalization is then the process of translating every string character to its single allowed encoding. An alternative is for software to determine whether a string is canonicalized, and then reject it if it is not. In this case, in a client/server context, the canonicalization would be the responsibility of the client.

In summary, a standard form of representation for data. From this form you can then convert to any representation you may need.

Allow anonymous authentication for a single folder in web.config?

To make it work I build my directory like this:

Project Public Restrict

So I edited my webconfig for my public folder:

<location path="Project/Public">
    <system.web>
      <authorization>
        <allow users="?"/>
      </authorization>
    </system.web>
  </location>

And for my Restricted folder:

 <location path="Project/Restricted">
    <system.web>
      <authorization>
        <allow users="*"/>
      </authorizatio>
    </system.web>
  </location>

See here for the spec of * and ?:

https://docs.microsoft.com/en-us/iis/configuration/system.webserver/security/authorization/add

I hope I have helped.

How to convert wstring into string?

Solution from: http://forums.devshed.com/c-programming-42/wstring-to-string-444006.html

std::wstring wide( L"Wide" ); 
std::string str( wide.begin(), wide.end() );

// Will print no problemo!
std::cout << str << std::endl;

Beware that there is no character set conversion going on here at all. What this does is simply to assign each iterated wchar_t to a char - a truncating conversion. It uses the std::string c'tor:

template< class InputIt >
basic_string( InputIt first, InputIt last,
              const Allocator& alloc = Allocator() );

As stated in comments:

values 0-127 are identical in virtually every encoding, so truncating values that are all less than 127 results in the same text. Put in a chinese character and you'll see the failure.

-

the values 128-255 of windows codepage 1252 (the Windows English default) and the values 128-255 of unicode are mostly the same, so if that's teh codepage you're using most of those characters should be truncated to the correct values. (I totally expected á and õ to work, I know our code at work relies on this for é, which I will soon fix)

And note that code points in the range 0x80 - 0x9F in Win1252 will not work. This includes , œ, ž, Ÿ, ...

How to close a JavaFX application on window close?

Try

 System.exit(0);

this should terminate thread main and end the main program

Open multiple Eclipse workspaces on the Mac

This seems to be the supported native method in OS X:

cd /Applications/eclipse/

open -n Eclipse.app

Be sure to specify the ".app" version (directory); in OS X Mountain Lion erroneously using the symbolic link such as open -n eclipse, might get one GateKeeper stopping access:

"eclipse" can't be opened because it is from an unidentified developer.

Your security preferences allow installation of only apps from the Mac App Store and identified developers.

Even removing the extended attribute com.apple.quarantine does not fix that. Instead, simply using the ".app" version will rely on your previous consent, or prompt you once:

"Eclipse" is an application downloaded from the Internet. Are you sure you want to open it?

How to load a model from an HDF5 file in Keras?

According to official documentation https://keras.io/getting-started/faq/#how-can-i-install-hdf5-or-h5py-to-save-my-models-in-keras

you can do :

first test if you have h5py installed by running the

import h5py

if you dont have errors while importing h5py you are good to save:

from keras.models import load_model

model.save('my_model.h5')  # creates a HDF5 file 'my_model.h5'
del model  # deletes the existing model

# returns a compiled model
# identical to the previous one
model = load_model('my_model.h5')

If you need to install h5py http://docs.h5py.org/en/latest/build.html

How do you import an Eclipse project into Android Studio now?

Its Got simpler with Android Studio All you need is to first choose

  1. import project(eclipse.....) enter image description here
  2. then choose your folder eclipse based project.like this one below enter image description here

3.based on the type of project and library you used like (ActionBarSherlock) you may prompted special import wizard so go ahead and click next then finish. in this case it was simple one

enter image description here

4.And you are done. enter image description here

but sometimes the debug or Run options do not work and a error msg shows like

"this project structure is not gradle based or migrate it to gradle"

something to solve this close the opened eclipse project and reopen same project through the same process as we did before with import project (eclipse adt,gradle,etc)) this time android studio gonna add all necessary gradle files and green debug option will work too. i have did this somehow accidentally but it worked, i just hope it works for you too.

onclick event function in JavaScript

click() is a reserved word and already a function, change the name from click() to runclick() it works fine

How to get first and last element in an array in java?

This is the given array.

    int myIntegerNumbers[] = {1,2,3,4,5,6,7,8,9,10};

// If you want print the last element in the array.

    int lastNumerOfArray= myIntegerNumbers[9];
    Log.i("MyTag", lastNumerOfArray + "");

// If you want to print the number of element in the array.

    Log.i("MyTag", "The number of elements inside" +
            "the array " +myIntegerNumbers.length);

// Second method to print the last element inside the array.

    Log.i("MyTag", "The last elements inside " +
            "the array " + myIntegerNumbers[myIntegerNumbers.length-1]);

Reading a .txt file using Scanner class in Java

Use following codes to read the file

import java.io.File;
import java.util.Scanner;

public class ReadFile {

    public static void main(String[] args) {

        try {
            System.out.print("Enter the file name with extension : ");

            Scanner input = new Scanner(System.in);

            File file = new File(input.nextLine());

            input = new Scanner(file);


            while (input.hasNextLine()) {
                String line = input.nextLine();
                System.out.println(line);
            }
            input.close();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}

-> This application is printing the file content line by line

How to tell if a file is git tracked (by shell exit code)?

Try running git status on the file. It will print an error if it's not tracked by git

PS$> git status foo.txt
error: pathspec 'foo.txt' did not match any file(s) known to git.

How to enter in a Docker container already running with a new TTY

With docker 1.3, there is a new command docker exec. This allows you to enter a running container:

docker exec -it [container-id] bash

Find most frequent value in SQL column

If you have an ID column and you want to find most repetitive category from another column for each ID then you can use below query,

Table:

Table content

Query:

SELECT ID, CATEGORY, COUNT(*) AS FREQ
FROM TABLE
GROUP BY 1,2
QUALIFY ROW_NUMBER() OVER(PARTITION BY ID ORDER BY FREQ DESC) = 1;

Result:

Query result

What's the difference between StaticResource and DynamicResource in WPF?

What is the main difference. Like memory or performance implications

The difference between static and dynamic resources comes when the underlying object changes. If your Brush defined in the Resources collection were accessed in code and set to a different object instance, Rectangle will not detect this change.

Static Resources retrieved once by referencing element and used for the lifetime of the resources. Whereas, DynamicResources retrieve every time they are used.

The downside of Dynamic resources is that they tend to decrease application performance.

Are there rules in WPF like "brushes are always static" and "templates are always dynamic" etc.?

The best practice is to use Static Resources unless there is a specific reason like you want to change resource in the code behind dynamically. Another example of instance in which you would want t to use dynamic resoruces include when you use the SystemBrushes, SystenFonts and System Parameters.

Convert nullable bool? to bool

Something like:

if (bn.HasValue)
{
  b = bn.Value
}

How to base64 encode image in linux bash / shell

Base 64 for html:

file="DSC_0251.JPG"
type=$(identify -format "%m" "$file" | tr '[A-Z]' '[a-z]')
echo "data:image/$type;base64,$(base64 -w 0 "$file")"

Does JavaScript have a built in stringbuilder class?

When I find myself doing a lot of string concatenation in JavaScript, I start looking for templating. Handlebars.js works quite well keeping the HTML and JavaScript more readable. http://handlebarsjs.com

Call static methods from regular ES6 class methods

If you are planning on doing any kind of inheritance, then I would recommend this.constructor. This simple example should illustrate why:

class ConstructorSuper {
  constructor(n){
    this.n = n;
  }

  static print(n){
    console.log(this.name, n);
  }

  callPrint(){
    this.constructor.print(this.n);
  }
}

class ConstructorSub extends ConstructorSuper {
  constructor(n){
    this.n = n;
  }
}

let test1 = new ConstructorSuper("Hello ConstructorSuper!");
console.log(test1.callPrint());

let test2 = new ConstructorSub("Hello ConstructorSub!");
console.log(test2.callPrint());
  • test1.callPrint() will log ConstructorSuper Hello ConstructorSuper! to the console
  • test2.callPrint() will log ConstructorSub Hello ConstructorSub! to the console

The named class will not deal with inheritance nicely unless you explicitly redefine every function that makes a reference to the named Class. Here is an example:

class NamedSuper {
  constructor(n){
    this.n = n;
  }

  static print(n){
    console.log(NamedSuper.name, n);
  }

  callPrint(){
    NamedSuper.print(this.n);
  }
}

class NamedSub extends NamedSuper {
  constructor(n){
    this.n = n;
  }
}

let test3 = new NamedSuper("Hello NamedSuper!");
console.log(test3.callPrint());

let test4 = new NamedSub("Hello NamedSub!");
console.log(test4.callPrint());
  • test3.callPrint() will log NamedSuper Hello NamedSuper! to the console
  • test4.callPrint() will log NamedSuper Hello NamedSub! to the console

See all the above running in Babel REPL.

You can see from this that test4 still thinks it's in the super class; in this example it might not seem like a huge deal, but if you are trying to reference member functions that have been overridden or new member variables, you'll find yourself in trouble.

Using "like" wildcard in prepared statement

PreparedStatement ps = cn.prepareStatement("Select * from Users where User_FirstName LIKE ?");
ps.setString(1, name + '%');

Try this out.

How to print bytes in hexadecimal using System.out.println?

for (int j=0; j<test.length; j++) {
   System.out.format("%02X ", test[j]);
}
System.out.println();

How to parse JSON in Kotlin?

This uses kotlinx.serialization like Elisha's answer. Meanwhile the API is being stabilized for the upcoming 1.0 release. Note that e.g. JSON.parse was renamed to Json.parse and is now Json.decodeFromString. Also it is imported in gradle differently starting in Kotlin 1.4.0:

dependencies {
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-core:1.0.0-RC"
}
apply plugin: 'kotlinx-serialization'

Example usage:

@Serializable
data class Properties(val nid: Int, val tid: Int)
@Serializable
data class Feature(val pos: List<Double>, val properties: Properties? = null, 
    val count: Int? = null)
@Serializable
data class Root(val features: List<Feature>)


val root = Json.decodeFromString<Root>(jsonStr)
val rootAlt = Json.decodeFromString(Root.serializer(), jsonStr)  // equivalent

val str = Json.encodeToString(root)  // type 'Root' can be inferred!

// For a *top-level* list (does not apply in my case) you would use 
val fList = Json.decodeFromString<List<Feature>>(jsonStr)
val fListAlt = Json.decodeFromString(ListSerializer(Feature.serializer()), jsonStr)

Kotlin's data class defines a class that mainly holds data and has .toString() and other methods (e.g. destructuring declarations) automatically defined. I'm using nullable (?) types here for optional fields.

Convert regular Python string to raw string

For Python 3, the way to do this that doesn't add double backslashes and simply preserves \n, \t, etc. is:

a = 'hello\nbobby\nsally\n'
a.encode('unicode-escape').decode().replace('\\\\', '\\')
print(a)

Which gives a value that can be written as CSV:

hello\nbobby\nsally\n

There doesn't seem to be a solution for other special characters, however, that may get a single \ before them. It's a bummer. Solving that would be complex.

For example, to serialize a pandas.Series containing a list of strings with special characters in to a textfile in the format BERT expects with a CR between each sentence and a blank line between each document:

with open('sentences.csv', 'w') as f:

    current_idx = 0
    for idx, doc in sentences.items():
        # Insert a newline to separate documents
        if idx != current_idx:
            f.write('\n')
        # Write each sentence exactly as it appared to one line each
        for sentence in doc:
            f.write(sentence.encode('unicode-escape').decode().replace('\\\\', '\\') + '\n')

This outputs (for the Github CodeSearchNet docstrings for all languages tokenized into sentences):

Makes sure the fast-path emits in order.
@param value the value to emit or queue up\n@param delayError if true, errors are delayed until the source has terminated\n@param disposable the resource to dispose if the drain terminates

Mirrors the one ObservableSource in an Iterable of several ObservableSources that first either emits an item or sends\na termination notification.
Scheduler:\n{@code amb} does not operate by default on a particular {@link Scheduler}.
@param  the common element type\n@param sources\nan Iterable of ObservableSource sources competing to react first.
A subscription to each source will\noccur in the same order as in the Iterable.
@return an Observable that emits the same sequence as whichever of the source ObservableSources first\nemitted an item or sent a termination notification\n@see ReactiveX operators documentation: Amb


...

Convert unsigned int to signed int C

Since converting unsigned values use to represent positive numbers converting it can be done by setting the most significant bit to 0. Therefore a program will not interpret that as a Two`s complement value. One caveat is that this will lose information for numbers that near max of the unsigned type.

template <typename TUnsigned, typename TSinged>
TSinged UnsignedToSigned(TUnsigned val)
{
    return val & ~(1 << ((sizeof(TUnsigned) * 8) - 1));
}

Insert a background image in CSS (Twitter Bootstrap)

Is your image on the same folder/directory as your css file? If so, your image url is correct. Otherwise, it's not.

If by any chance your folder structure is like so...

webpage
-index.html
-css
- - style.css
- images
- - background.png

then to reference the image on your css file you should use the following path:

../images/background.png

So that would be background: url('../images/background.png');

The logic is simple: Go up one folder by typing "../" (as many times as you need). Go down one folder by specifying the folder you wish to go down to.

Sort Pandas Dataframe by Date

sort method has been deprecated and replaced with sort_values. After converting to datetime object using df['Date']=pd.to_datetime(df['Date'])

df.sort_values(by=['Date'])

Note: to sort in-place and/or in a descending order (the most recent first):

df.sort_values(by=['Date'], inplace=True, ascending=False)

How to center horizontal table-cell

Just add this class in your css

.column p{
   text-align:center;
}

Count how many files in directory PHP

$it = new filesystemiterator(dirname("Enter directory here"));
printf("There were %d Files", iterator_count($it));
echo("<br/>");
    foreach ($it as $fileinfo) {
        echo $fileinfo->getFilename() . "<br/>\n";
    } 

This should work enter the directory in dirname. and let the magic happen.

trigger click event from angularjs directive

This is more the Angular way to do it: http://plnkr.co/edit/xYNX47EsYvl4aRuGZmvo?p=preview

  1. I added $scope.selectedItem that gets you past your first problem (defaulting the image)
  2. I added $scope.setSelectedItem and called it in ng-click. Your final requirements may be different, but using a directive to bind click and change src was overkill, since most of it can be handled with template
  3. Notice use of ngSrc to avoid errant server calls on initial load
  4. You'll need to adjust some styles to get the image positioned right in the div. If you really need to use background-image, then you'll need a directive like ngSrc that defers setting the background-image style until after real data has loaded.

How to get relative path from absolute path

If you know that toPath is contained by fromPath then you can keep it simple. I'll leave out the asserts for brevity.

public static string MakeRelativePath(string fromPath, string toPath)
{
    // use Path.GetFullPath to canonicalise the paths (deal with multiple directory seperators, etc)
    return Path.GetFullPath(toPath).Substring(Path.GetFullPath(fromPath).Length + 1);
}

Split string into individual words Java

This regex will split word by space like space, tab, line break:

String[] str = s.split("\\s+");

How to do this in Laravel, subquery where in

You can use Eloquent in different queries and make things easier to understand and mantain:

$productCategory = ProductCategory::whereIn('category_id', ['223', '15'])
                   ->select('product_id'); //don't need ->get() or ->first()

and then we put all together:

Products::whereIn('id', $productCategory)
          ->where('active', 1)
          ->select('id', 'name', 'img', 'safe_name', 'sku', 'productstatusid')
          ->get();//runs all queries at once

This will generate the same query that you wrote in your question.

Start service in Android

Java code for start service:

Start service from Activity:

startService(new Intent(MyActivity.this, MyService.class));

Start service from Fragment:

getActivity().startService(new Intent(getActivity(), MyService.class));

MyService.java:

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {

    private static String TAG = "MyService";
    private Handler handler;
    private Runnable runnable;
    private final int runTime = 5000;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate");

        handler = new Handler();
        runnable = new Runnable() {
            @Override
            public void run() {

                handler.postDelayed(runnable, runTime);
            }
        };
        handler.post(runnable);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        if (handler != null) {
            handler.removeCallbacks(runnable);
        }
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.i(TAG, "onStart");
    }

}

Define this Service into Project's Manifest File:

Add below tag in Manifest file:

<service android:enabled="true" android:name="com.my.packagename.MyService" />

Done

Get the filePath from Filename using Java

Look at the methods in the java.io.File class:

File file = new File("yourfileName");
String path = file.getAbsolutePath();

How to copy JavaScript object to new variable NOT by reference?

Your only option is to somehow clone the object.

See this stackoverflow question on how you can achieve this.

For simple JSON objects, the simplest way would be:

var newObject = JSON.parse(JSON.stringify(oldObject));

if you use jQuery, you can use:

// Shallow copy
var newObject = jQuery.extend({}, oldObject);

// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);

UPDATE 2017: I should mention, since this is a popular answer, that there are now better ways to achieve this using newer versions of javascript:

In ES6 or TypeScript (2.1+):

var shallowCopy = { ...oldObject };

var shallowCopyWithExtraProp = { ...oldObject, extraProp: "abc" };

Note that if extraProp is also a property on oldObject, its value will not be used because the extraProp : "abc" is specified later in the expression, which essentially overrides it. Of course, oldObject will not be modified.

Python - How do you run a .py file?

If you want to run .py files in Windows, Try installing Git bash Then download python(Required Version) from python.org and install in the main c drive folder

For me, its :

"C:\Python38"

then open Git Bash and go to the respective folder where your .py file is stored :

For me, its :

File Location : "Downloads" File Name : Train.py

So i changed my Current working Directory From "C:/User/(username)/" to "C:/User/(username)/Downloads"

then i will run the below command

" /c/Python38/python Train.py "

and it will run successfully.

But if it give the below error :

from sklearn.model_selection import train_test_split ModuleNotFoundError: No module named 'sklearn'

Then Do not panic :

and use this command :

" /c/Python38/Scripts/pip install sklearn "

and after it has installed sklearn go back and run the previous command :

" /c/Python38/python Train.py "

and it will run successfully.

!!!!HAPPY LEARNING !!!!

Import txt file and having each line as a list

Do not create separate lists; create a list of lists:

results = []
with open('inputfile.txt') as inputfile:
    for line in inputfile:
        results.append(line.strip().split(','))

or better still, use the csv module:

import csv

results = []
with open('inputfile.txt', newline='') as inputfile:
    for row in csv.reader(inputfile):
        results.append(row)

Lists or dictionaries are far superiour structures to keep track of an arbitrary number of things read from a file.

Note that either loop also lets you address the rows of data individually without having to read all the contents of the file into memory either; instead of using results.append() just process that line right there.

Just for completeness sake, here's the one-liner compact version to read in a CSV file into a list in one go:

import csv

with open('inputfile.txt', newline='') as inputfile:
    results = list(csv.reader(inputfile))

How can I lock a file using java (if possible)

This may not be what you are looking for, but in the interest of coming at a problem from another angle....

Are these two Java processes that might want to access the same file in the same application? Perhaps you can just filter all access to the file through a single, synchronized method (or, even better, using JSR-166)? That way, you can control access to the file, and perhaps even queue access requests.

Remove empty space before cells in UITableView

I just found a solution for this. In my case, i was using TabBarViewController, A just uncheck the option 'Adjust Scroll View Insets'. Issues goes away. https://i.stack.imgur.com/vRNfV.png

Replace whitespaces with tabs in linux

This will replace consecutive spaces with one space (but not tab).

tr -s '[:blank:]'

This will replace consecutive spaces with a tab.

tr -s '[:blank:]' '\t'

find first sequence item that matches a criterion

If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:

next(obj for obj in objs if obj.val == 5)

This is however faster than a complete list comprehension. Compare these two:

[i for i in xrange(100000) if i == 1000][0]

next(i for i in xrange(100000) if i == 1000)

The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).

Run function in script from command line (Node JS)

Sometimes you want to run a function via CLI, sometimes you want to require it from another module. Here's how to do both.

// file to run
const runMe = () => {}
if (require.main === module) {
  runMe()
} 
module.exports = runMe

When to use AtomicReference in Java?

Here is a use case for AtomicReference:

Consider this class that acts as a number range, and uses individual AtmomicInteger variables to maintain lower and upper number bounds.

public class NumberRange {
    // INVARIANT: lower <= upper
    private final AtomicInteger lower = new AtomicInteger(0);
    private final AtomicInteger upper = new AtomicInteger(0);

    public void setLower(int i) {
        // Warning -- unsafe check-then-act
        if (i > upper.get())
            throw new IllegalArgumentException(
                    "can't set lower to " + i + " > upper");
        lower.set(i);
    }

    public void setUpper(int i) {
        // Warning -- unsafe check-then-act
        if (i < lower.get())
            throw new IllegalArgumentException(
                    "can't set upper to " + i + " < lower");
        upper.set(i);
    }

    public boolean isInRange(int i) {
        return (i >= lower.get() && i <= upper.get());
    }
}

Both setLower and setUpper are check-then-act sequences, but they do not use sufficient locking to make them atomic. If the number range holds (0, 10), and one thread calls setLower(5) while another thread calls setUpper(4), with some unlucky timing both will pass the checks in the setters and both modifications will be applied. The result is that the range now holds (5, 4)an invalid state. So while the underlying AtomicIntegers are thread-safe, the composite class is not. This can be fixed by using a AtomicReference instead of using individual AtomicIntegers for upper and lower bounds.

public class CasNumberRange {
    // Immutable
    private static class IntPair {
        final int lower;  // Invariant: lower <= upper
        final int upper;

        private IntPair(int lower, int upper) {
            this.lower = lower;
            this.upper = upper;
        }
    }

    private final AtomicReference<IntPair> values = 
            new AtomicReference<IntPair>(new IntPair(0, 0));

    public int getLower() {
        return values.get().lower;
    }

    public void setLower(int lower) {
        while (true) {
            IntPair oldv = values.get();
            if (lower > oldv.upper)
                throw new IllegalArgumentException(
                    "Can't set lower to " + lower + " > upper");
            IntPair newv = new IntPair(lower, oldv.upper);
            if (values.compareAndSet(oldv, newv))
                return;
        }
    }

    public int getUpper() {
        return values.get().upper;
    }

    public void setUpper(int upper) {
        while (true) {
            IntPair oldv = values.get();
            if (upper < oldv.lower)
                throw new IllegalArgumentException(
                    "Can't set upper to " + upper + " < lower");
            IntPair newv = new IntPair(oldv.lower, upper);
            if (values.compareAndSet(oldv, newv))
                return;
        }
    }
}

SFTP Libraries for .NET

We use WinSCP. Its free. Its not a lib, but has a well documented and full featured command line interface that you can use with Process.Start.

Update: with v.5.0, WinSCP has a .NET wrapper library to the scripting layer of WinSCP.

How to "inverse match" with regex?

(?!Andrea).{6}

Assuming your regexp engine supports negative lookaheads..

Edit: ..or maybe you'd prefer to use [A-Za-z]{6} in place of .{6}

Edit (again): Note that lookaheads and lookbehinds are generally not the right way to "inverse" a regular expression match. Regexps aren't really set up for doing negative matching, they leave that to whatever language you are using them with.

Are one-line 'if'/'for'-statements good Python style?

You could do all of that in one line by omitting the example variable:

if "exam" in "example": print "yes!"

throw checked Exceptions from mocks with Mockito

There is the solution with Kotlin :

given(myObject.myCall()).willAnswer {
    throw IOException("Ooops")
}

Where given comes from

import org.mockito.BDDMockito.given

How to convert a HTMLElement to a string

Suppose your element is entire [object HTMLDocument]. You can convert it to a String this way:

_x000D_
_x000D_
const htmlTemplate = `<!DOCTYPE html><html lang="en"><head></head><body></body></html>`;

const domparser = new DOMParser();
const doc = domparser.parseFromString(htmlTemplate, "text/html"); // [object HTMLDocument]

const doctype = '<!DOCTYPE html>';
const html = doc.documentElement.outerHTML;

console.log(doctype + html);
_x000D_
_x000D_
_x000D_

How to set Python's default version to 3.x on OS X?

I believe most of people landed here are using ZSH thorugh iterm or whatever, and that brings you to this answer.

You have to add/modify your commands in ~/.zshrc instead.

PHP, How to get current date in certain format

I belive the answer is:

echo date('Y-m-d H:i:s');

SQL: how to select a single id ("row") that meets multiple criteria from a single column

one of the approach if you want to get all user_id that satisfies all conditions is:

SELECT DISTINCT user_id FROM table WHERE ancestry IN ('England', '...', '...') GROUP BY user_id HAVING count(*) = <number of conditions that has to be satisfied> 

etc. If you need to take all user_ids that satisfies at least one condition, then you can do

SELECT DISTINCT user_id from table where ancestry IN ('England', 'France', ... , '...')

I am not aware if there is something similar to IN but that joins conditions with AND instead of OR

What's the difference between using CGFloat and float?

Objective-C

From the Foundation source code, in CoreGraphics' CGBase.h:

/* Definition of `CGFLOAT_TYPE', `CGFLOAT_IS_DOUBLE', `CGFLOAT_MIN', and
   `CGFLOAT_MAX'. */

#if defined(__LP64__) && __LP64__
# define CGFLOAT_TYPE double
# define CGFLOAT_IS_DOUBLE 1
# define CGFLOAT_MIN DBL_MIN
# define CGFLOAT_MAX DBL_MAX
#else
# define CGFLOAT_TYPE float
# define CGFLOAT_IS_DOUBLE 0
# define CGFLOAT_MIN FLT_MIN
# define CGFLOAT_MAX FLT_MAX
#endif

/* Definition of the `CGFloat' type and `CGFLOAT_DEFINED'. */

typedef CGFLOAT_TYPE CGFloat;
#define CGFLOAT_DEFINED 1

Copyright (c) 2000-2011 Apple Inc.

This is essentially doing:

#if defined(__LP64__) && __LP64__
typedef double CGFloat;
#else
typedef float CGFloat;
#endif

Where __LP64__ indicates whether the current architecture* is 64-bit.

Note that 32-bit systems can still use the 64-bit double, it just takes more processor time, so CoreGraphics does this for optimization purposes, not for compatibility. If you aren't concerned about performance but are concerned about accuracy, simply use double.

Swift

In Swift, CGFloat is a struct wrapper around either Float on 32-bit architectures or Double on 64-bit ones (You can detect this at run- or compile-time with CGFloat.NativeType) and cgFloat.native.

From the CoreGraphics source code, in CGFloat.swift.gyb:

public struct CGFloat {
#if arch(i386) || arch(arm)
  /// The native type used to store the CGFloat, which is Float on
  /// 32-bit architectures and Double on 64-bit architectures.
  public typealias NativeType = Float
#elseif arch(x86_64) || arch(arm64)
  /// The native type used to store the CGFloat, which is Float on
  /// 32-bit architectures and Double on 64-bit architectures.
  public typealias NativeType = Double
#endif

*Specifically, longs and pointers, hence the LP. See also: http://www.unix.org/version2/whatsnew/lp64_wp.html

Add column to dataframe with constant value

You can use insert to specify where you want to new column to be. In this case, I use 0 to place the new column at the left.

df.insert(0, 'Name', 'abc')

  Name        Date  Open  High  Low  Close
0  abc  01-01-2015   565   600  400    450

How can I search for a commit message on GitHub?

Using Advanced Search on Github seemed the easiest with a combination of other answers. It's basically a search string builder. https://github.com/search/advanced

For example I wanted to find all commits in Autodesk/maya-usd containing "USD" enter image description here

Then in the search results can choose Commits from the list on the left: enter image description here

Connection attempt failed with "ECONNREFUSED - Connection refused by server"

Use port number 22 (for sftp) instead of 21 (normal ftp). Solved this problem for me.

Retrieving an element from array list in Android?

public class DemoActivity extends Activity {
    /** Called when the activity is first created. */
    ArrayList<String> al = new ArrayList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);



        // add elements to the array list

        al.add("C");
        al.add("A");
        al.add("E");
        al.add("B");
        al.add("D");
        al.add("F");

        // retrieve elements from array

        String data = al.get(pass the index here);
        System.out.println("Data is "+ data);

This is another way of getting element

        Iterator<String> it = al.iterator();
        while (it.hasNext()) {
            System.out.println("Data is "+ it.next());
        }
    }

How to retrieve absolute path given relative

You could use bash string substitution for any relative path $line:

line=$(echo ${line/#..\//`cd ..; pwd`\/})
line=$(echo ${line/#.\//`pwd`\/})
echo $line

The basic front-of-string substitution follows the formula
${string/#substring/replacement}
which is discussed well here: https://www.tldp.org/LDP/abs/html/string-manipulation.html

The \ character negates the / when we want it to be part of the string that we find/replace.

$watch an object

As you are looking for form object changes, the best watching approach is to use
$watchCollection. Please have a look into official documentation for different performance characteristics.

How do I revert all local changes in Git managed project to previous state?

I searched for a similar issue,

Wanted to throw away local commits:

  1. cloned the repository (git clone)
  2. switched to dev branch (git checkout dev)
  3. did few commits (git commit -m "commit 1")
  4. but decided to throw away these local commits to go back to remote (origin/dev)

So did the below:

git reset --hard origin/dev

Check:

git status  

        On branch dev  
        Your branch is up-to-date with 'origin/dev'.  
        nothing to commit, working tree clean  

now local commits are lost, back to the initial cloned state, point 1 above.

Timestamp to human readable format

use Date.prototype.toLocaleTimeString() as documented here

please note the locale example en-US in the url.

Using a Loop to add objects to a list(python)

The problem appears to be that you are reinitializing the list to an empty list in each iteration:

while choice != 0:
    ...
    a = []
    a.append(s)

Try moving the initialization above the loop so that it is executed only once.

a = []
while choice != 0:
    ...
    a.append(s)

syntax error near unexpected token `('

Try

sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)

Hibernate: hbm2ddl.auto=update in production?

We do it in production albeit with an application that's not mission critical and with no highly paid DBAs on staff. It's just one less manual process that's subject to human error - the application can detect the difference and do the right thing, plus you've presumably tested it in various development and test environments.

One caveat - in a clustered environment you may want to avoid it because multiple apps can come up at the same time and try to modify the schema which could be bad. Or put in some mechanism where only one instance is allowed to update the schema.

Fatal error: Call to a member function fetch_assoc() on a non-object

Most likely your query failed, and the query call returned a boolean FALSE (or an error object of some sort), which you then try to use as if was a resultset object, causing the error. Try something like var_dump($result) to see what you really got.

Check for errors after EVERY database query call. Even if the query itself is syntactically valid, there's far too many reasons for it to fail anyways - checking for errors every time will save you a lot of grief at some point.

Set QLineEdit to accept only numbers

The Regex Validator

So far, the other answers provide solutions for only a relatively finite number of digits. However, if you're concerned with an arbitrary or a variable number of digits you can use a QRegExpValidator, passing a regex that only accepts digits (as noted by user2962533's comment). Here's a minimal, complete example:

#include <QApplication>
#include <QLineEdit>
#include <QRegExpValidator>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QLineEdit le;
    le.setValidator(new QRegExpValidator(QRegExp("[0-9]*"), &le));
    le.show();

    return app.exec();
}

The QRegExpValidator has its merits (and that's only an understatement). It allows for a bunch of other useful validations:

QRegExp("[1-9][0-9]*")    //  leading digit must be 1 to 9 (prevents leading zeroes).
QRegExp("\\d*")           //  allows matching for unicode digits (e.g. for 
                          //    Arabic-Indic numerals such as ???).
QRegExp("[0-9]+")         //  input must have at least 1 digit.
QRegExp("[0-9]{8,32}")    //  input must be between 8 to 32 digits (e.g. for some basic
                          //    password/special-code checks).
QRegExp("[0-1]{,4}")      //  matches at most four 0s and 1s.
QRegExp("0x[0-9a-fA-F]")  //  matches a hexadecimal number with one hex digit.
QRegExp("[0-9]{13}")      //  matches exactly 13 digits (e.g. perhaps for ISBN?).
QRegExp("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}")
                          //  matches a format similar to an ip address.
                          //    N.B. invalid addresses can still be entered: "999.999.999.999".     

More On Line-edit Behaviour

According to documentation:

Note that if there is a validator set on the line edit, the returnPressed()/editingFinished() signals will only be emitted if the validator returns QValidator::Acceptable.

Thus, the line-edit will allow the user to input digits even if the minimum amount has not yet been reached. For example, even if the user hasn't inputted any text against the regex "[0-9]{3,}" (which requires at least 3 digits), the line-edit still allows the user to type input to reach that minimum requirement. However, if the user finishes editing without satsifying the requirement of "at least 3 digits", the input would be invalid; the signals returnPressed() and editingFinished() won't be emitted.

If the regex had a maximum-bound (e.g. "[0-1]{,4}"), then the line-edit will stop any input past 4 characters. Additionally, for character sets (i.e. [0-9], [0-1], [0-9A-F], etc.) the line-edit only allows characters from that particular set to be inputted.

Note that I've only tested this with Qt 5.11 on a macOS, not on other Qt versions or operating systems. But given Qt's cross-platform schema...

Demo: Regex Validators Showcase

How to print a double with two decimals in Android?

textView2.setText(String.format("%.2f", result));

and

DecimalFormat form = new DecimalFormat("0.00");
         textView2.setText(form.format(result) );

...cause "NumberFormatException" error in locale for Europe because it sets result as comma instead of point decimal - error occurs when textView is added to number in editText. Both solutions are working excellent in locale US and UK.

One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?

I had the same problem and solved it by removing "Microsoft.CSharp" reference from the project and then added it again.

MySQLi prepared statements error reporting

Completeness

You need to check both $mysqli and $statement. If they are false, you need to output $mysqli->error or $statement->error respectively.

Efficiency

For simple scripts that may terminate, I use simple one-liners that trigger a PHP error with the message. For a more complex application, an error warning system should be activated instead, for example by throwing an exception.

Usage example 1: Simple script

# This is in a simple command line script
$mysqli = new mysqli('localhost', 'buzUser', 'buzPassword');
$q = "UPDATE foo SET bar=1";
($statement = $mysqli->prepare($q)) or trigger_error($mysqli->error, E_USER_ERROR);
$statement->execute() or trigger_error($statement->error, E_USER_ERROR);

Usage example 2: Application

# This is part of an application
class FuzDatabaseException extends Exception {
}

class Foo {
  public $mysqli;
  public function __construct(mysqli $mysqli) {
    $this->mysqli = $mysqli;
  }
  public function updateBar() {
    $q = "UPDATE foo SET bar=1";
    $statement = $this->mysqli->prepare($q);
    if (!$statement) {
      throw new FuzDatabaseException($mysqli->error);
    }

    if (!$statement->execute()) {
      throw new FuzDatabaseException($statement->error);
    }
  }
}

$foo = new Foo(new mysqli('localhost','buzUser','buzPassword'));
try {
  $foo->updateBar();
} catch (FuzDatabaseException $e)
  $msg = $e->getMessage();
  // Now send warning emails, write log
}

The ternary (conditional) operator in C

The fact that the ternary operator is an expression, not a statement, allows it to be used in macro expansions for function-like macros that are used as part of an expression. Const may not have been part of original C, but the macro pre-processor goes way back.

One place where I've seen it used is in an array package that used macros for bound-checked array accesses. The syntax for a checked reference was something like aref(arrayname, type, index), where arrayname was actually a pointer to a struct that included the array bounds and an unsigned char array for the data, type was the actual type of the data, and index was the index. The expansion of this was quite hairy (and I'm not going to do it from memory), but it used some ternary operators to do the bound checking.

You can't do this as a function call in C because of the need for polymorphism of the returned object. So a macro was needed to do the type casting in the expression. In C++ you could do this as a templated overloaded function call (probably for operator[]), but C doesn't have such features.

Edit: Here's the example I was talking about, from the Berkeley CAD array package (glu 1.4 edition). The documentation of the array_fetch usage is:

type
array_fetch(type, array, position)
typeof type;
array_t *array;
int position;

Fetch an element from an array. A runtime error occurs on an attempt to reference outside the bounds of the array. There is no type-checking that the value at the given position is actually of the type used when dereferencing the array.

and here is the macro defintion of array_fetch (note the use of the ternary operator and the comma sequencing operator to execute all the subexpressions with the right values in the right order as part of a single expression):

#define array_fetch(type, a, i)         \
(array_global_index = (i),              \
  (array_global_index >= (a)->num) ? array_abort((a),1) : 0,\
  *((type *) ((a)->space + array_global_index * (a)->obj_size)))

The expansion for array_insert ( which grows the array if necessary, like a C++ vector) is even hairier, involving multiple nested ternary operators.