Programs & Examples On #Jpopupmenu

JPopupMenu is the Java Swing implementation of a popup menu, a small window that pops up and displays a series of choices. A JPopupMenu is used for the menu that appears when the user selects an item on the menu bar. It is also used for "pull-right" menu that appears when the selects a menu item that activates it. Finally, a JPopupMenu can also be used anywhere else you want a menu to appear.

How do I create a right click context menu in Java Swing?

The following code implements a default context menu known from Windows with copy, cut, paste, select all, undo and redo functions. It also works on Linux and Mac OS X:

import javax.swing.*;
import javax.swing.text.JTextComponent;
import javax.swing.undo.UndoManager;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class DefaultContextMenu extends JPopupMenu
{
    private Clipboard clipboard;

    private UndoManager undoManager;

    private JMenuItem undo;
    private JMenuItem redo;
    private JMenuItem cut;
    private JMenuItem copy;
    private JMenuItem paste;
    private JMenuItem delete;
    private JMenuItem selectAll;

    private JTextComponent textComponent;

    public DefaultContextMenu()
    {
        undoManager = new UndoManager();
        clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

        addPopupMenuItems();
    }

    private void addPopupMenuItems()
    {
        undo = new JMenuItem("Undo");
        undo.setEnabled(false);
        undo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        undo.addActionListener(event -> undoManager.undo());
        add(undo);

        redo = new JMenuItem("Redo");
        redo.setEnabled(false);
        redo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        redo.addActionListener(event -> undoManager.redo());
        add(redo);

        add(new JSeparator());

        cut = new JMenuItem("Cut");
        cut.setEnabled(false);
        cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        cut.addActionListener(event -> textComponent.cut());
        add(cut);

        copy = new JMenuItem("Copy");
        copy.setEnabled(false);
        copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        copy.addActionListener(event -> textComponent.copy());
        add(copy);

        paste = new JMenuItem("Paste");
        paste.setEnabled(false);
        paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        paste.addActionListener(event -> textComponent.paste());
        add(paste);

        delete = new JMenuItem("Delete");
        delete.setEnabled(false);
        delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        delete.addActionListener(event -> textComponent.replaceSelection(""));
        add(delete);

        add(new JSeparator());

        selectAll = new JMenuItem("Select All");
        selectAll.setEnabled(false);
        selectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        selectAll.addActionListener(event -> textComponent.selectAll());
        add(selectAll);
    }

    private void addTo(JTextComponent textComponent)
    {
        textComponent.addKeyListener(new KeyAdapter()
        {
            @Override
            public void keyPressed(KeyEvent pressedEvent)
            {
                if ((pressedEvent.getKeyCode() == KeyEvent.VK_Z)
                        && ((pressedEvent.getModifiersEx() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0))
                {
                    if (undoManager.canUndo())
                    {
                        undoManager.undo();
                    }
                }

                if ((pressedEvent.getKeyCode() == KeyEvent.VK_Y)
                        && ((pressedEvent.getModifiersEx() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0))
                {
                    if (undoManager.canRedo())
                    {
                        undoManager.redo();
                    }
                }
            }
        });

        textComponent.addMouseListener(new MouseAdapter()
        {
            @Override
            public void mousePressed(MouseEvent releasedEvent)
            {
                handleContextMenu(releasedEvent);
            }

            @Override
            public void mouseReleased(MouseEvent releasedEvent)
            {
                handleContextMenu(releasedEvent);
            }
        });

        textComponent.getDocument().addUndoableEditListener(event -> undoManager.addEdit(event.getEdit()));
    }

    private void handleContextMenu(MouseEvent releasedEvent)
    {
        if (releasedEvent.getButton() == MouseEvent.BUTTON3)
        {
            processClick(releasedEvent);
        }
    }

    private void processClick(MouseEvent event)
    {
        textComponent = (JTextComponent) event.getSource();
        textComponent.requestFocus();

        boolean enableUndo = undoManager.canUndo();
        boolean enableRedo = undoManager.canRedo();
        boolean enableCut = false;
        boolean enableCopy = false;
        boolean enablePaste = false;
        boolean enableDelete = false;
        boolean enableSelectAll = false;

        String selectedText = textComponent.getSelectedText();
        String text = textComponent.getText();

        if (text != null)
        {
            if (text.length() > 0)
            {
                enableSelectAll = true;
            }
        }

        if (selectedText != null)
        {
            if (selectedText.length() > 0)
            {
                enableCut = true;
                enableCopy = true;
                enableDelete = true;
            }
        }

        if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor) && textComponent.isEnabled())
        {
            enablePaste = true;
        }

        undo.setEnabled(enableUndo);
        redo.setEnabled(enableRedo);
        cut.setEnabled(enableCut);
        copy.setEnabled(enableCopy);
        paste.setEnabled(enablePaste);
        delete.setEnabled(enableDelete);
        selectAll.setEnabled(enableSelectAll);

        // Shows the popup menu
        show(textComponent, event.getX(), event.getY());
    }

    public static void addDefaultContextMenu(JTextComponent component)
    {
        DefaultContextMenu defaultContextMenu = new DefaultContextMenu();
        defaultContextMenu.addTo(component);
    }
}

Usage:

JTextArea textArea = new JTextArea();
DefaultContextMenu.addDefaultContextMenu(textArea);

Now the textArea will have a context menu when it is right-clicked on.

Count the occurrences of DISTINCT values

What about something like this:

SELECT
  name,
  count(*) AS num
FROM
  your_table
GROUP BY
  name
ORDER BY
  count(*)
  DESC

You are selecting the name and the number of times it appears, but grouping by name so each name is selected only once.

Finally, you order by the number of times in DESCending order, to have the most frequently appearing users come first.

How to reload current page?

This is the most simple solution if you just need to refresh the entire page

   refreshPage() {
    window.location.reload();
   }

How can I find out if I have Xcode commandline tools installed?

Thanks to the folks on Freenode's #macdev, here is some information:

In the old days before Xcode was on the app-store, it included commandline tools.

Now you get it from the store, and with this new mechanism it can't install extra things outside of the Xcode.app, so you have to manually do it yourself, by:

xcode-select --install

On Xcode 4.x you can check to see if they are installed from within the Xcode UI:

enter image description here

On Xcode 5.x it is now here:

enter image description here

My problem of finding gcc/gdb is that they have been superseded by clang/lldb: GDB missing in OS X v10.9 (Mavericks)

Also note that Xcode contains compiler and debugger, so one of the things installing commandline tools will do is symlink or modify $PATH. It also downloads certain things like git.

OracleCommand SQL Parameters Binding

Oracle has a different syntax for parameters than Sql-Server. So use : instead of @

using(var con=new OracleConnection(connectionString))
{
   con.open();
   var sql = "insert into users values (:id,:name,:surname,:username)";

   using(var cmd = new OracleCommand(sql,con)
   {
      OracleParameter[] parameters = new OracleParameter[] {
             new OracleParameter("id",1234),
             new OracleParameter("name","John"),
             new OracleParameter("surname","Doe"),
             new OracleParameter("username","johnd")
      };

      cmd.Parameters.AddRange(parameters);
      cmd.ExecuteNonQuery();
   }
}

When using named parameters in an OracleCommand you must precede the parameter name with a colon (:).

http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oraclecommand.parameters.aspx

Reason for Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

Suppose I have the following table T:

a   b
--------
1   abc
1   def
1   ghi
2   jkl
2   mno
2   pqr

And I do the following query:

SELECT a, b
FROM T
GROUP BY a

The output should have two rows, one row where a=1 and a second row where a=2.

But what should the value of b show on each of these two rows? There are three possibilities in each case, and nothing in the query makes it clear which value to choose for b in each group. It's ambiguous.

This demonstrates the single-value rule, which prohibits the undefined results you get when you run a GROUP BY query, and you include any columns in the select-list that are neither part of the grouping criteria, nor appear in aggregate functions (SUM, MIN, MAX, etc.).

Fixing it might look like this:

SELECT a, MAX(b) AS x
FROM T
GROUP BY a

Now it's clear that you want the following result:

a   x
--------
1   ghi
2   pqr

JavaScript: remove event listener

I think you may need to define the handler function ahead of time, like so:

var myHandler = function(event) {
    click++; 
    if(click == 50) { 
        this.removeEventListener('click', myHandler);
    } 
}
canvas.addEventListener('click', myHandler);

This will allow you to remove the handler by name from within itself.

How do you divide each element in a list by an int?

The way you tried first is actually directly possible with numpy:

import numpy
myArray = numpy.array([10,20,30,40,50,60,70,80,90])
myInt = 10
newArray = myArray/myInt

If you do such operations with long lists and especially in any sort of scientific computing project, I would really advise using numpy.

What is the PHP syntax to check "is not null" or an empty string?

Use empty(). It checks for both empty strings and null.

if (!empty($_POST['user'])) {
  // do stuff
}

From the manual:

The following things are considered to be empty:

"" (an empty string)  
0 (0 as an integer)  
0.0 (0 as a float)  
"0" (0 as a string)    
NULL  
FALSE  
array() (an empty array)  
var $var; (a variable declared, but without a value in a class)  

linq query to return distinct field values from a list of objects

If just want to use Linq, you can override Equals and GetHashCode methods.

Product class:

public class Product
{
    public string ProductName { get; set; }
    public int Id { get; set; }


    public override bool Equals(object obj)
    {
        if (!(obj is Product))
        {
            return false;
        }

        var other = (Product)obj;
        return Id == other.Id;
    }

    public override int GetHashCode()
    {
        return Id.GetHashCode();
    }
}

Main Method:

static void Main(string[] args)
    {

        var products = new List<Product>
        {
            new Product{ ProductName="Product 1",Id = 1},
            new Product{ ProductName="Product 2",Id = 2},
            new Product{ ProductName="Product 4",Id = 5},
            new Product{ ProductName="Product 3",Id = 3},
            new Product{ ProductName="Product 4",Id = 4},
            new Product{ ProductName="Product 6",Id = 4},
            new Product{ ProductName="Product 6",Id = 4},
        };

        var itemsDistinctByProductName = products.Distinct().ToList();

        foreach (var product in itemsDistinctByProductName)
        {
            Console.WriteLine($"Product Id : {product.Id} ProductName : {product.ProductName} ");
        }

        Console.ReadKey();
    }

How to set a selected option of a dropdown list control using angular JS

JS:

$scope.options = [
  {
    name: "a", 
    id: 1 
  },
  {
    name: "b",
    id: 2 
  }
];
$scope.selectedOption = $scope.options[1];

Regex for 1 or 2 digits, optional non-alphanumeric, 2 known alphas

^[0-9]{1,2}[:.,-]?po$

Add any other allowable non-alphanumeric characters to the middle brackets to allow them to be parsed as well.

HTML5 required attribute seems not working

Make sure that novalidate attribute is not set to your form tag

Difference between JSON.stringify and JSON.parse

JavaScript Object <-> JSON String


JSON.stringify() <-> JSON.parse()

JSON.stringify(obj) - Takes any serializable object and returns the JSON representation as a string.

JSON.stringify() -> Object To String.

JSON.parse(string) - Takes a well formed JSON string and returns the corresponding JavaScript object.

JSON.parse() -> String To Object.

Explanation: JSON.stringify(obj [, replacer [, space]]);

Replacer/Space - optional or takes integer value or you can call interger type return function.

function replacer(key, value) {
    if (typeof value === 'number' && !isFinite(value)) {
        return String(value);
    }
    return value;
}
  • Replacer Just Use for replace non finite no with null.
  • Space use for indenting Json String by space

Why is my element value not getting changed? Am I using the wrong function?

How to address your textbox depends on the HTML-code:

<!-- 1 --><input type="textbox" id="Tue" />
<!-- 2 --><input type="textbox" name="Tue" />

If you use the 'id' attribute:

var textbox = document.getElementById('Tue');

for 'name':

var textbox = document.getElementsByName('Tue')[0]

(Note that getElementsByName() returns all elements with the name as array, therefore we use [0] to access the first one)

Then, use the 'value' attribute:

textbox.value = 'Foobar';

Python Unicode Encode Error

You can use something of the form

s.decode('utf-8')

which will convert a UTF-8 encoded bytestring into a Python Unicode string. But the exact procedure to use depends on exactly how you load and parse the XML file, e.g. if you don't ever access the XML string directly, you might have to use a decoder object from the codecs module.

Java 'file.delete()' Is not Deleting Specified File

As other answers indicate, on Windows you cannot delete a file that is open. However one other thing that can stop a file from being deleted on Windows is if it is is mmap'd to a MappedByteBuffer (or DirectByteBuffer) -- if so, the file cannot be deleted until the byte buffer is garbage collected. There is some relatively safe code for forcibly closing (cleaning) a DirectByteBuffer before it is garbage collected here: https://github.com/classgraph/classgraph/blob/master/src/main/java/nonapi/io/github/classgraph/utils/FileUtils.java#L606 After cleaning the ByteBuffer, you can delete the file. However, make sure you never use the ByteBuffer again after cleaning it, or the JVM will crash.

Python Progress Bar

for a similar application (keeping track of the progress in a loop) I simply used the python-progressbar:

Their example goes something like this,

from progressbar import *               # just a simple progress bar


widgets = ['Test: ', Percentage(), ' ', Bar(marker='0',left='[',right=']'),
           ' ', ETA(), ' ', FileTransferSpeed()] #see docs for other options

pbar = ProgressBar(widgets=widgets, maxval=500)
pbar.start()

for i in range(100,500+1,50):
    # here do something long at each iteration
    pbar.update(i) #this adds a little symbol at each iteration
pbar.finish()
print

GitHub README.md center image

Alternatively, if you have control of the css, you could get clever with url parameters and css.

Markdown:

![A cute kitten](http://placekitten.com/200/300?style=centerme)

And CSS:

img[src$="centerme"] {
  display:block;
  margin: 0 auto;
}

You could create a variety of styling options this way and still keep the markdown clean of extra code. Of course you have no control over what happens if someone else uses the markdown somewhere else but thats a general styling issue with all markdown documents one shares.

Log4net rolling daily filename with date in the file name

I ended up using (note the '.log' filename and the single quotes around 'myfilename_'):

  <rollingStyle value="Date" />
  <datePattern value="'myfilename_'yyyy-MM-dd"/>
  <preserveLogFileNameExtension value="true" />
  <staticLogFileName value="false" />
  <file type="log4net.Util.PatternString" value="c:\\Logs\\.log" />

This gives me:

myfilename_2015-09-22.log
myfilename_2015-09-23.log
.
.

How do I make a text go onto the next line if it overflows?

In order to use word-wrap: break-word, you need to set a width (in px). For example:

div {
    width: 250px;
    word-wrap: break-word;
}

word-wrap is a CSS3 property, but it should work in all browsers, including IE 5.5-9.

SQL: how to use UNION and order by a specific select?

@Adrien's answer is not working. It gives an ORA-01791.

The correct answer (for the question that is asked) should be:

select id
from 
 (SELECT id, 2 as ordered FROM a -- returns 1,4,2,3
  UNION ALL
  SELECT id, 1 as ordered FROM b -- returns 2,1
  )
group by id
order by min(ordered)

Explanation:

  1. The "UNION ALL" is combining the 2 sets. A "UNION" is wastefull because the 2 sets could not be the same, because the ordered field is different.
  2. The "group by" is then eliminating duplicates
  3. The "order by min (ordered)" is assuring the elements of table b are first

This solves all the cases, even when table b has more or different elements then table a

Understanding slice notation

And a couple of things that weren't immediately obvious to me when I first saw the slicing syntax:

>>> x = [1,2,3,4,5,6]
>>> x[::-1]
[6,5,4,3,2,1]

Easy way to reverse sequences!

And if you wanted, for some reason, every second item in the reversed sequence:

>>> x = [1,2,3,4,5,6]
>>> x[::-2]
[6,4,2]

Can't access to HttpContext.Current

Have you included the System.Web assembly in the application?

using System.Web;

If not, try specifying the System.Web namespace, for example:

 System.Web.HttpContext.Current

In AngularJS, what's the difference between ng-pristine and ng-dirty?

pristine tells us if a field is still virgin, and dirty tells us if the user has already typed anything in the related field:

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>_x000D_
<form ng-app="" name="myForm">_x000D_
  <input name="email" ng-model="data.email">_x000D_
  <div class="info" ng-show="myForm.email.$pristine">_x000D_
    Email is virgine._x000D_
  </div>_x000D_
  <div class="error" ng-show="myForm.email.$dirty">_x000D_
    E-mail is dirty_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

A field that has registred a single keydown event is no more virgin (no more pristine) and is therefore dirty for ever.

Bootstrap 3 Multi-column within a single ul not floating properly

Thanks, Varun Rathore. It works perfectly!

For those who want graceful collapse from 4 items per row to 2 items per row depending on the screen width:

<ul class="list-group row">
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_1</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_2</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_3</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_4</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_5</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_6</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_7</li>
</ul>

Stopping python using ctrl+c

If it is running in the Python shell use Ctrl + Z, otherwise locate the python process and kill it.

Must issue a STARTTLS command first

Adding

props.put("mail.smtp.starttls.enable", "true");

solved my problem ;)

My problem was :

com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. u186sm7971862pfu.82 - gsmtp

at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1609)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1117)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at com.example.sendmail.SendEmailExample2.main(SendEmailExample2.java:53)

How to force view controller orientation in iOS 8?

My solution

In AppDelegate:

func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
    if let topController = UIViewController.topMostViewController() {
        if topController is XXViewController {
            return [.Portrait, .LandscapeLeft]
        }
    }
    return [.Portrait]
}

XXViewController is the ViewController you want to support Landscape mode.

Then Sunny Shah's solution would work in your XXViewController on any iOS version:

let value = UIInterfaceOrientation.LandscapeLeft.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")

This is the utility function to find the top most ViewController.

extension UIViewController {

    /// Returns the current application's top most view controller.
    public class func topMostViewController() -> UIViewController? {
        let rootViewController = UIApplication.sharedApplication().windows.first?.rootViewController
        return self.topMostViewControllerOfViewController(rootViewController)
    }



    /// Returns the top most view controller from given view controller's stack.
    class func topMostViewControllerOfViewController(viewController: UIViewController?) -> UIViewController? {
        // UITabBarController
        if let tabBarController = viewController as? UITabBarController,
           let selectedViewController = tabBarController.selectedViewController {
            return self.topMostViewControllerOfViewController(selectedViewController)
        }

        // UINavigationController
        if let navigationController = viewController as? UINavigationController,
           let visibleViewController = navigationController.visibleViewController {
            return self.topMostViewControllerOfViewController(visibleViewController)
        }

        // presented view controller
        if let presentedViewController = viewController?.presentedViewController {
            return self.topMostViewControllerOfViewController(presentedViewController)
        }

        // child view controller
        for subview in viewController?.view?.subviews ?? [] {
            if let childViewController = subview.nextResponder() as? UIViewController {
                return self.topMostViewControllerOfViewController(childViewController)
            }
        }

        return viewController
    }

}

CASE WHEN statement for ORDER BY clause

Another simple example from here..

SELECT * FROM dbo.Employee
ORDER BY 
 CASE WHEN Gender='Male' THEN EmployeeName END Desc,
 CASE WHEN Gender='Female' THEN Country END ASC

Display rows with one or more NaN values in pandas dataframe

Suppose gamma1 and gamma2 are two such columns for which df.isnull().any() gives True value , the following code can be used to print the rows.

bool1 = pd.isnull(df['gamma1'])
bool2 = pd.isnull(df['gamma2'])
df[bool1]
df[bool2]

How can I do a BEFORE UPDATED trigger with sql server?

Remember that when you use an instead trigger, it will not commit the insert unless you specifically tell it to in the trigger. Instead of really means do this instead of what you normally do, so none of the normal insert actions would happen.

sqlite copy data from one table to another

I've been wrestling with this, and I know there are other options, but I've come to the conclusion the safest pattern is:

create table destination_old as select * from destination;

drop table destination;

create table destination as select
d.*, s.country
from destination_old d left join source s
on d.id=s.id;

It's safe because you have a copy of destination before you altered it. I suspect that update statements with joins weren't included in SQLite because they're powerful but a bit risky.

Using the pattern above you end up with two country fields. You can avoid that by explicitly stating all of the columns you want to retrieve from destination_old and perhaps using coalesce to retrieve the values from destination_old if the country field in source is null. So for example:

create table destination as select
d.field1, d.field2,...,coalesce(s.country,d.country) country
from destination_old d left join source s
on d.id=s.id;

Array versus List<T>: When to use which?

Arrays Vs. Lists is a classic maintainability vs. performance problem. The rule of thumb that nearly all developers follow is that you should shoot for both, but when they come in to conflict, choose maintainability over performance. The exception to that rule is when performance has already proven to be an issue. If you carry this principle in to Arrays Vs. Lists, then what you get is this:

Use strongly typed lists until you hit performance problems. If you hit a performance problem, make a decision as to whether dropping out to arrays will benefit your solution with performance more than it will be a detriment to your solution in terms of maintenance.

E: Unable to locate package npm

I had a similar issue and this is what worked for me.

Add the NodeSource package signing key:

curl -sSL https://deb.nodesource.com/gpgkey/nodesource.gpg.key | sudo apt-key add -
# wget can also be used:
# wget --quiet -O - https://deb.nodesource.com/gpgkey/nodesource.gpg.key | sudo apt-key add -

Add the desired NodeSource repository:

# Replace with the branch of Node.js or io.js you want to install: node_6.x, node_12.x, etc...
VERSION=node_12.x
# The below command will set this correctly, but if lsb_release isn't available, you can set it manually:
# - For Debian distributions: jessie, sid, etc...
# - For Ubuntu distributions: xenial, bionic, etc...
# - For Debian or Ubuntu derived distributions your best option is to use the codename corresponding to the upstream release your distribution is based off. This is an advanced scenario and unsupported if your distribution is not listed as supported per earlier in this README.
DISTRO="$(lsb_release -s -c)"
echo "deb https://deb.nodesource.com/$VERSION $DISTRO main" | sudo tee /etc/apt/sources.list.d/nodesource.list
echo "deb-src https://deb.nodesource.com/$VERSION $DISTRO main" | sudo tee -a /etc/apt/sources.list.d/nodesource.list

Update package lists and install Node.js:

sudo apt-get update
sudo apt-get install nodejs

Rename multiple files in a folder, add a prefix (Windows)

Based on @ofer.sheffer answer, this is the CMD variant for adding an affix (this is not the question, but this page is still the #1 google result if you search affix). It is a bit different because of the extension.

for %a in (*.*) do ren "%~a" "%~na-affix%~xa"

You can change the "-affix" part.

How to get an element's top position relative to the browser's viewport?

The function on this page will return a rectangle with the top, left, height and width co ordinates of a passed element relative to the browser view port.

    localToGlobal: function( _el ) {
       var target = _el,
       target_width = target.offsetWidth,
       target_height = target.offsetHeight,
       target_left = target.offsetLeft,
       target_top = target.offsetTop,
       gleft = 0,
       gtop = 0,
       rect = {};

       var moonwalk = function( _parent ) {
        if (!!_parent) {
            gleft += _parent.offsetLeft;
            gtop += _parent.offsetTop;
            moonwalk( _parent.offsetParent );
        } else {
            return rect = {
            top: target.offsetTop + gtop,
            left: target.offsetLeft + gleft,
            bottom: (target.offsetTop + gtop) + target_height,
            right: (target.offsetLeft + gleft) + target_width
            };
        }
    };
        moonwalk( target.offsetParent );
        return rect;
}

Generate an integer sequence in MySQL

Warning: if you insert numbers one row at a time, you'll end up executing N commands where N is the number of rows you need to insert.

You can get this down to O(log N) by using a temporary table (see below for inserting numbers from 10000 to 10699):

mysql> CREATE TABLE `tmp_keys` (`k` INTEGER UNSIGNED, PRIMARY KEY (`k`));
Query OK, 0 rows affected (0.11 sec)

mysql> INSERT INTO `tmp_keys` VALUES (0),(1),(2),(3),(4),(5),(6),(7);
Query OK, 8 rows affected (0.03 sec)
Records: 8  Duplicates: 0  Warnings: 0

mysql> INSERT INTO `tmp_keys` SELECT k+8 from `tmp_keys`;
Query OK, 8 rows affected (0.02 sec)
Records: 8  Duplicates: 0  Warnings: 0

mysql> INSERT INTO `tmp_keys` SELECT k+16 from `tmp_keys`;
Query OK, 16 rows affected (0.03 sec)
Records: 16  Duplicates: 0  Warnings: 0

mysql> INSERT INTO `tmp_keys` SELECT k+32 from `tmp_keys`;
Query OK, 32 rows affected (0.03 sec)
Records: 32  Duplicates: 0  Warnings: 0

mysql> INSERT INTO `tmp_keys` SELECT k+64 from `tmp_keys`;
Query OK, 64 rows affected (0.03 sec)
Records: 64  Duplicates: 0  Warnings: 0

mysql> INSERT INTO `tmp_keys` SELECT k+128 from `tmp_keys`;
Query OK, 128 rows affected (0.05 sec)
Records: 128  Duplicates: 0  Warnings: 0

mysql> INSERT INTO `tmp_keys` SELECT k+256 from `tmp_keys`;
Query OK, 256 rows affected (0.03 sec)
Records: 256  Duplicates: 0  Warnings: 0

mysql> INSERT INTO `tmp_keys` SELECT k+512 from `tmp_keys`;
Query OK, 512 rows affected (0.11 sec)
Records: 512  Duplicates: 0  Warnings: 0

mysql> INSERT INTO inttable SELECT k+10000 FROM `tmp_keys` WHERE k<700;
Query OK, 700 rows affected (0.16 sec)
Records: 700  Duplicates: 0  Warnings: 0

edit: fyi, unfortunately this won't work with a true temporary table with MySQL 5.0 as it can't insert into itself (you could bounce back and forth between two temporary tables).

edit: You could use a MEMORY storage engine to prevent this from actually being a drain on the "real" database. I wonder if someone has developed a "NUMBERS" virtual storage engine to instantiate virtual storage to create sequences such as this. (alas, nonportable outside MySQL)

How to send POST request in JSON using HTTPClient in Android?

In this answer I am using an example posted by Justin Grammens.

About JSON

JSON stands for JavaScript Object Notation. In JavaScript properties can be referenced both like this object1.name and like this object['name'];. The example from the article uses this bit of JSON.

The Parts
A fan object with email as a key and [email protected] as a value

{
  fan:
    {
      email : '[email protected]'
    }
}

So the object equivalent would be fan.email; or fan['email'];. Both would have the same value of '[email protected]'.

About HttpClient Request

The following is what our author used to make a HttpClient Request. I do not claim to be an expert at all this so if anyone has a better way to word some of the terminology feel free.

public static HttpResponse makeRequest(String path, Map params) throws Exception 
{
    //instantiates httpclient to make request
    DefaultHttpClient httpclient = new DefaultHttpClient();

    //url with the post data
    HttpPost httpost = new HttpPost(path);

    //convert parameters into JSON object
    JSONObject holder = getJsonObjectFromMap(params);

    //passes the results to a string builder/entity
    StringEntity se = new StringEntity(holder.toString());

    //sets the post request as the resulting string
    httpost.setEntity(se);
    //sets a request header so the page receving the request
    //will know what to do with it
    httpost.setHeader("Accept", "application/json");
    httpost.setHeader("Content-type", "application/json");

    //Handles what is returned from the page 
    ResponseHandler responseHandler = new BasicResponseHandler();
    return httpclient.execute(httpost, responseHandler);
}

Map

If you are not familiar with the Map data structure please take a look at the Java Map reference. In short, a map is similar to a dictionary or a hash.

private static JSONObject getJsonObjectFromMap(Map params) throws JSONException {

    //all the passed parameters from the post request
    //iterator used to loop through all the parameters
    //passed in the post request
    Iterator iter = params.entrySet().iterator();

    //Stores JSON
    JSONObject holder = new JSONObject();

    //using the earlier example your first entry would get email
    //and the inner while would get the value which would be '[email protected]' 
    //{ fan: { email : '[email protected]' } }

    //While there is another entry
    while (iter.hasNext()) 
    {
        //gets an entry in the params
        Map.Entry pairs = (Map.Entry)iter.next();

        //creates a key for Map
        String key = (String)pairs.getKey();

        //Create a new map
        Map m = (Map)pairs.getValue();   

        //object for storing Json
        JSONObject data = new JSONObject();

        //gets the value
        Iterator iter2 = m.entrySet().iterator();
        while (iter2.hasNext()) 
        {
            Map.Entry pairs2 = (Map.Entry)iter2.next();
            data.put((String)pairs2.getKey(), (String)pairs2.getValue());
        }

        //puts email and '[email protected]'  together in map
        holder.put(key, data);
    }
    return holder;
}

Please feel free to comment on any questions that arise about this post or if I have not made something clear or if I have not touched on something that your still confused about... etc whatever pops in your head really.

(I will take down if Justin Grammens does not approve. But if not then thanks Justin for being cool about it.)

Update

I just happend to get a comment about how to use the code and realized that there was a mistake in the return type. The method signature was set to return a string but in this case it wasnt returning anything. I changed the signature to HttpResponse and will refer you to this link on Getting Response Body of HttpResponse the path variable is the url and I updated to fix a mistake in the code.

Foreach value from POST from form

Use array-like fields:

<input name="name_for_the_items[]"/>

You can loop through the fields:

foreach($_POST['name_for_the_items'] as $item)
{
  //do something with $item
}

Text not wrapping inside a div element

you can add this line: word-break:break-all; to your CSS-code

Android - default value in editText

Use android android:hint for set default value or android:text

Read Excel sheet in Powershell

There is the possibility of making something really more cool!

# Powershell 
$xl = new-object -ComObject excell.application
$doc=$xl.workbooks.open("Filepath")
$doc.Sheets.item(1).rows |
% { ($_.value2 | Select-Object -first 3 | Select-Object -last 2) -join "," }

How do I make a burn down chart in Excel?

No macros required. Data as below, two columns, dates don't need to be in order. Select range, convert to a Table (Ctrl+T). When data is added to the table, a chart based on the table will automatically include the added data.

Select table, insert a line chart. Right click chart, choose Select Data, click on Blank and Hidden Cells button, choose Interpolate option.

Burndown Chart of Pages Read

glm rotate usage in Opengl

I noticed that you can also get errors if you don't specify the angles correctly, even when using glm::rotate(Model, angle_in_degrees, glm::vec3(x, y, z)) you still might run into problems. The fix I found for this was specifying the type as glm::rotate(Model, (glm::mediump_float)90, glm::vec3(x, y, z)) instead of just saying glm::rotate(Model, 90, glm::vec3(x, y, z))

Or just write the second argument, the angle in radians (previously in degrees), as a float with no cast needed such as in:

glm::mat4 rotationMatrix = glm::rotate(glm::mat4(1.0f), 3.14f, glm::vec3(1.0));

You can add glm::radians() if you want to keep using degrees. And add the includes:

#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"

OpenCV Python rotate image by X degrees around specific point

import imutils

vs = VideoStream(src=0).start()
...

while (1):
   frame = vs.read()
   ...

   frame = imutils.rotate(frame, 45)

More: https://github.com/jrosebr1/imutils

How To limit the number of characters in JTextField?

Just put this code in KeyTyped event:

    if ((jtextField.getText() + evt.getKeyChar()).length() > 20) {
        evt.consume();
    }

Where "20" is the maximum number of characters that you want.

javascript window.location in new tab

I don't think there's a way to do this, unless you're writing a browser extension. You could try using window.open and hoping that the user has their browser set to open new windows in new tabs.

Angular 4: How to include Bootstrap?

Angular 4 - Bootstrap / @ng-bootstrap setup

First install bootstrap into your project using below command:

npm install --save bootstrap

Then add this line "../node_modules/bootstrap/dist/css/bootstrap.min.css" to angular-cli.json file (root folder) in styles

"styles": [
   "../node_modules/bootstrap/dist/css/bootstrap.min.css",
   "styles.css"
],

After installing the above dependencies, install ng-bootstrap via:

npm install --save @ng-bootstrap/ng-bootstrap

Once installed you need to import main module.

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

After this, you can use All the Bootstrap widgets (ex. carousel, modal, popovers, tooltips, tabs etc.) and several additional goodies ( datepicker, rating, timepicker, typeahead).

Get Bitmap attached to ImageView

Other way to get a bitmap of an image is doing this:

Bitmap imagenAndroid = BitmapFactory.decodeResource(getResources(),R.drawable.jellybean_statue);
imageView.setImageBitmap(imagenAndroid);

Remove icon/logo from action bar on android

Be aware that:

<item name="android:icon">@android:color/transparent</item>

Will also make your options items transparent.

Link to a section of a webpage

your jump link looks like this

<a href="#div_id">jump link</a>

Then make

<div id="div_id"></div>

the jump link will take you to that div

How can I remove a style added with .css() function?

There are several ways to remove a CSS property using jQuery:

1. Setting the CSS property to its default (initial) value

.css("background-color", "transparent")

See the initial value for the CSS property at MDN. Here the default value is transparent. You can also use inherit for several CSS properties to inherite the attribute from its parent. In CSS3/CSS4, you may also use initial, revert or unset but these keywords may have limited browser support.

2. Removing the CSS property

An empty string removes the CSS property, i.e.

.css("background-color","")

But beware, as specified in jQuery .css() documentation, this removes the property but it has compatibilty issues with IE8 for certain CSS shorthand properties, including background.

Setting the value of a style property to an empty string — e.g. $('#mydiv').css('color', '') — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's .css() method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or element. Warning: one notable exception is that, for IE 8 and below, removing a shorthand property such as border or background will remove that style entirely from the element, regardless of what is set in a stylesheet or element.

3. Removing the whole style of the element

.removeAttr("style")

Go to Matching Brace in Visual Studio?

On a Turkish keyboard, it is Ctrl + ü.

Replace a string in a file with nodejs

Perhaps the "replace" module (www.npmjs.org/package/replace) also would work for you. It would not require you to read and then write the file.

Adapted from the documentation:

// install:

npm install replace 

// require:

var replace = require("replace");

// use:

replace({
    regex: "string to be replaced",
    replacement: "replacement string",
    paths: ['path/to/your/file'],
    recursive: true,
    silent: true,
});

Datetime equal or greater than today in MySQL

If 'created' is datetime type

SELECT * FROM users WHERE created < DATE_ADD(CURDATE(), INTERVAL 1 DAY);

CURDATE() means also '2013-05-09 00:00:00'

How do I 'git diff' on a certain directory?

You should make a habit of looking at the documentation for stuff like this. It's very useful and will improve your skills very quickly. Here's the relevant bit when you do git help diff

   git diff [options] [--no-index] [--] <path> <path>

The two <path>s are what you need to change to the directories in question.

403 Forbidden vs 401 Unauthorized HTTP responses

  • 401 Unauthorized: I don't know who you are. This an authentication error.
  • 403 Forbidden: I know who you are, but you don't have permission to access this resource. This is an authorization error.

Byte Array and Int conversion in Java

You're swapping endianness between your two methods. You have intToByteArray(int a) assigning the low-order bits into ret[0], but then byteArrayToInt(byte[] b) assigns b[0] to the high-order bits of the result. You need to invert one or the other, like:

public static byte[] intToByteArray(int a)
{
    byte[] ret = new byte[4];
    ret[3] = (byte) (a & 0xFF);   
    ret[2] = (byte) ((a >> 8) & 0xFF);   
    ret[1] = (byte) ((a >> 16) & 0xFF);   
    ret[0] = (byte) ((a >> 24) & 0xFF);
    return ret;
}

setting the id attribute of an input element dynamically in IE: alternative for setAttribute method

This code work in IE7 and Chrome:

var hiddenInput = document.createElement("input");
    hiddenInput.setAttribute("id", "uniqueIdentifier");
    hiddenInput.setAttribute("type", "hidden");                     
    hiddenInput.setAttribute("value", 'ID');
    hiddenInput.setAttribute("class", "ListItem");

$('body').append(hiddenInput);

Maybe problem somewhere else ?

In NetBeans how do I change the Default JDK?

If I remember correctly, you'll need to set the netbeans_jdkhome property in your netbeans config file. Should be in your etc/netbeans.conf file.

C++ int float casting

You are performing calculations on integers and assigning its result to float. So compiler is implicitly converting your integer result into float

Why are the Level.FINE logging messages not showing?

The Why

java.util.logging has a root logger that defaults to Level.INFO, and a ConsoleHandler attached to it that also defaults to Level.INFO. FINE is lower than INFO, so fine messages are not displayed by default.


Solution 1

Create a logger for your whole application, e.g. from your package name or use Logger.getGlobal(), and hook your own ConsoleLogger to it. Then either ask root logger to shut up (to avoid duplicate output of higher level messages), or ask your logger to not forward logs to root.

public static final Logger applog = Logger.getGlobal();
...

// Create and set handler
Handler systemOut = new ConsoleHandler();
systemOut.setLevel( Level.ALL );
applog.addHandler( systemOut );
applog.setLevel( Level.ALL );

// Prevent logs from processed by default Console handler.
applog.setUseParentHandlers( false ); // Solution 1
Logger.getLogger("").setLevel( Level.OFF ); // Solution 2

Solution 2

Alternatively, you may lower the root logger's bar.

You can set them by code:

Logger rootLog = Logger.getLogger("");
rootLog.setLevel( Level.FINE );
rootLog.getHandlers()[0].setLevel( Level.FINE ); // Default console handler

Or with logging configuration file, if you are using it:

.level = FINE
java.util.logging.ConsoleHandler.level = FINE

By lowering the global level, you may start seeing messages from core libraries, such as from some Swing or JavaFX components. In this case you may set a Filter on the root logger to filter out messages not from your program.

Remove ALL white spaces from text

Use replace(/\s+/g,''),

for example:

const stripped = '    My String With A    Lot Whitespace  '.replace(/\s+/g, '')// 'MyStringWithALotWhitespace'

How to get the mysql table columns data type?

ResultSet rs = Sstatement.executeQuery("SELECT * FROM Table Name");

ResultSetMetaData rsMetaData = rs.getMetaData();

int numberOfColumns = rsMetaData.getColumnCount();
System.out.println("resultSet MetaData column Count=" + numberOfColumns);

for (int i = 1; i <= numberOfColumns; i++) {
 System.out.println("column number " + i);

  System.out.println(rsMetaData.getColumnTypeName(i));
}

libxml install error using pip

sudo apt install libxslt-dev libxml2-dev

and then try upgrading python setuptools

pip install -U pip setuptools

this should resolve it.

unix - count of columns in file

If you have python installed you could try:

python -c 'import sys;f=open(sys.argv[1]);print len(f.readline().split("|"))' \
    stores.dat

Java String new line

Example

System.out.printf("I %n am %n a %n boy");

Output

I 
 am 
 a 
 boy

Explanation

It's better to use %n as an OS independent new-line character instead of \n and it's easier than using System.lineSeparator()

Why to use %n, because on each OS, new line refers to a different set of character(s);

Unix and modern Mac's   :   LF     (\n)
Windows                 :   CR LF  (\r\n)
Older Macintosh Systems :   CR     (\r)

LF is the acronym of Line Feed and CR is the acronym of Carriage Return. The escape characters are written inside the parenthesis. So on each OS, new line stands for something specific to the system. %n is OS agnostic, it is portable. It stands for \n on Unix systems or \r\n on Windows systems and so on. Thus, Do not use \n, instead use %n.

How does numpy.histogram() work?

Another useful thing to do with numpy.histogram is to plot the output as the x and y coordinates on a linegraph. For example:

arr = np.random.randint(1, 51, 500)
y, x = np.histogram(arr, bins=np.arange(51))
fig, ax = plt.subplots()
ax.plot(x[:-1], y)
fig.show()

enter image description here

This can be a useful way to visualize histograms where you would like a higher level of granularity without bars everywhere. Very useful in image histograms for identifying extreme pixel values.

Strings and character with printf

If you try this:

#include<stdio.h>

void main()
{
 char name[]="siva";
 printf("name = %p\n", name);
 printf("&name[0] = %p\n", &name[0]);
 printf("name printed as %%s is %s\n",name);
 printf("*name = %c\n",*name);
 printf("name[0] = %c\n", name[0]);
}

Output is:

name = 0xbff5391b  
&name[0] = 0xbff5391b
name printed as %s is siva
*name = s
name[0] = s

So 'name' is actually a pointer to the array of characters in memory. If you try reading the first four bytes at 0xbff5391b, you will see 's', 'i', 'v' and 'a'

Location     Data
=========   ======

0xbff5391b    0x73  's'  ---> name[0]
0xbff5391c    0x69  'i'  ---> name[1]
0xbff5391d    0x76  'v'  ---> name[2]
0xbff5391e    0x61  'a'  ---> name[3]
0xbff5391f    0x00  '\0' ---> This is the NULL termination of the string

To print a character you need to pass the value of the character to printf. The value can be referenced as name[0] or *name (since for an array name = &name[0]).

To print a string you need to pass a pointer to the string to printf (in this case 'name' or '&name[0]').

Linux: is there a read or recv from socket with timeout?

Install a handler for SIGALRM, then use alarm() or ualarm() before a regular blocking recv(). If the alarm goes off, the recv() will return an error with errno set to EINTR.

compilation error: identifier expected

only variable/object declaration statement are written outside of method

public class details{
    public static void main(String arg[]){
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

here is example try to learn java book and see the syntax then try to develop the program

Iterate through pairs of items in a Python list

You can zip the list with itself sans the first element:

a = [5, 7, 11, 4, 5]

for previous, current in zip(a, a[1:]):
    print(previous, current)

This works even if your list has no elements or only 1 element (in which case zip returns an empty iterable and the code in the for loop never executes). It doesn't work on generators, only sequences (tuple, list, str, etc).

Explain the different tiers of 2 tier & 3 tier architecture?

First, we must make a distinction between layers and tiers. Layers are the way to logically break code into components and tiers are the physical nodes to place the components on. This question explains it better: What's the difference between "Layers" and "Tiers"?

A two layer architecture is usually just a presentation layer and data store layer. These can be on 1 tier (1 machine) or 2 tiers (2 machines) to achieve better performance by distributing the work load.

A three layer architecture usually puts something between the presentation and data store layers such as a business logic layer or service layer. Again, you can put this into 1,2, or 3 tiers depending on how much money you have for hardware and how much load you expect.

Putting multiple machines in a tier will help with the robustness of the system by providing redundancy.

Below is a good example of a layered architecture:

alt text
(source: microsoft.com)

A good reference for all of this can be found here on MSDN: http://msdn.microsoft.com/en-us/library/ms978678.aspx

'nuget' is not recognized but other nuget commands working

Retrieve nuget.exe from https://www.nuget.org/downloads. Copy it to a local folder and add that folder to the PATH environment variable.

This is will make nuget available globally, from any project.

"for" vs "each" in Ruby

One more different..

number = ["one", "two", "three"]
 => ["one", "two", "three"] 

loop1 = []
loop2 = []

number.each do |c|
  loop1 << Proc.new { puts c }
end
 => ["one", "two", "three"] 

for c in number
  loop2 << Proc.new { puts c }
end
 => ["one", "two", "three"] 

loop1[1].call
two
 => nil 

loop2[1].call
three
 => nil 

source: http://paulphilippov.com/articles/enumerable-each-vs-for-loops-in-ruby

for more clear: http://www.ruby-forum.com/topic/179264#784884

Eclipse comment/uncomment shortcut?

Ctrl + 7 to comment a selected text.

git stash changes apply to new branch?

Is the standard procedure not working?

  • make changes
  • git stash save
  • git branch xxx HEAD
  • git checkout xxx
  • git stash pop

Shorter:

  • make changes
  • git stash
  • git checkout -b xxx
  • git stash pop

Difference between @Before, @BeforeClass, @BeforeEach and @BeforeAll

Difference between each annotation are :

+-------------------------------------------------------------------------------------------------------+
¦                                       Feature                            ¦   Junit 4    ¦   Junit 5   ¦
¦--------------------------------------------------------------------------+--------------+-------------¦
¦ Execute before all test methods of the class are executed.               ¦ @BeforeClass ¦ @BeforeAll  ¦
¦ Used with static method.                                                 ¦              ¦             ¦
¦ For example, This method could contain some initialization code          ¦              ¦             ¦
¦-------------------------------------------------------------------------------------------------------¦
¦ Execute after all test methods in the current class.                     ¦ @AfterClass  ¦ @AfterAll   ¦
¦ Used with static method.                                                 ¦              ¦             ¦
¦ For example, This method could contain some cleanup code.                ¦              ¦             ¦
¦-------------------------------------------------------------------------------------------------------¦
¦ Execute before each test method.                                         ¦ @Before      ¦ @BeforeEach ¦
¦ Used with non-static method.                                             ¦              ¦             ¦
¦ For example, to reinitialize some class attributes used by the methods.  ¦              ¦             ¦
¦-------------------------------------------------------------------------------------------------------¦
¦ Execute after each test method.                                          ¦ @After       ¦ @AfterEach  ¦
¦ Used with non-static method.                                             ¦              ¦             ¦
¦ For example, to roll back database modifications.                        ¦              ¦             ¦
+-------------------------------------------------------------------------------------------------------+

Most of annotations in both versions are same, but few differs.

Reference

Order of Execution.

Dashed box -> optional annotation.

enter image description here

How can I make a list of installed packages in a certain virtualenv?

In Python3

pip list

Empty venv is

Package    Version
---------- ------- 
pip        19.2.3 
setuptools 41.2.0

To start a new environment

python3 -m venv your_foldername_here

Activate

cd your_foldername_here
source bin/activate

Deactivate

deactivate

You can also stand in the folder and give the virtual environment a name/folder (python3 -m venv name_of_venv).

Venv is a subset of virtualenv that is shipped with Python after 3.3.

Provide password to ssh command inside bash script, Without the usage of public keys and Expect

Install sshpass, then launch the command:

sshpass -p "yourpassword" ssh -o StrictHostKeyChecking=no yourusername@hostname

The #include<iostream> exists, but I get an error: identifier "cout" is undefined. Why?

cout is in std namespace, you shall use std::cout in your code. And you shall not add using namespace std; in your header file, it's bad to mix your code with std namespace, especially don't add it in header file.

is there a require for json in node.js

As of node v0.5.x yes you can require your JSON just as you would require a js file.

var someObject = require('./somefile.json')

In ES6:

import someObject from ('./somefile.json')

How to squash all git commits into one?

As of git 1.6.2, you can use git rebase --root -i.

For each commit except the first, change pick to squash.

How to configure welcome file list in web.xml

I simply declared as below in web.xml file and Its working for me :

 <welcome-file-list>
    <welcome-file>/WEB-INF/jsps/index.jsp</welcome-file>
</welcome-file-list>

And NO html/jsp pages present in public directory except static resources(css, js, images). Now I can access my index page with URL like : http://localhost:8080/app/ Its calling /WEB-INF/jsps/index.jsp page. When hosted live in production the final URL looks like https://eisdigital.com/

Get to UIViewController from UIView?

I think there is a case when the observed needs to inform the observer.

I see a similar problem where the UIView in a UIViewController is responding to a situation and it needs to first tell its parent view controller to hide the back button and then upon completion tell the parent view controller that it needs to pop itself off the stack.

I have been trying this with delegates with no success.

I don't understand why this should be a bad idea?

How do I make the method return type generic?

You could implement it like this:

@SuppressWarnings("unchecked")
public <T extends Animal> T callFriend(String name) {
    return (T)friends.get(name);
}

(Yes, this is legal code; see Java Generics: Generic type defined as return type only.)

The return type will be inferred from the caller. However, note the @SuppressWarnings annotation: that tells you that this code isn't typesafe. You have to verify it yourself, or you could get ClassCastExceptions at runtime.

Unfortunately, the way you're using it (without assigning the return value to a temporary variable), the only way to make the compiler happy is to call it like this:

jerry.<Dog>callFriend("spike").bark();

While this may be a little nicer than casting, you are probably better off giving the Animal class an abstract talk() method, as David Schmitt said.

How to set the color of "placeholder" text?

::-webkit-input-placeholder { /* WebKit browsers */
    color:    #999;
}
:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
    color:    #999;
}
::-moz-placeholder { /* Mozilla Firefox 19+ */
    color:    #999;
}
:-ms-input-placeholder { /* Internet Explorer 10+ */
    color:    #999;
}

Detect if the app was launched/opened from a push notification

When app is terminated, and user taps on push notification

public func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
   if launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] != nil {
      print("from push")
    }
}

When app is in background, and user taps on push notificaion

If the user opens your app from the system-displayed alert, the system may call this method again when your app is about to enter the foreground so that you can update your user interface and display information pertaining to the notification.

public func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
  if application.applicationState == .inactive {
    print("from push")
  }
}

Depending on your app, it can also send you silent push with content-available inside aps, so be aware of this as well :) See https://stackoverflow.com/a/33778990/1418457

What is an application binary interface (ABI)?

One easy way to understand "ABI" is to compare it to "API".

You are already familiar with the concept of an API. If you want to use the features of, say, some library or your OS, you will program against an API. The API consists of data types/structures, constants, functions, etc that you can use in your code to access the functionality of that external component.

An ABI is very similar. Think of it as the compiled version of an API (or as an API on the machine-language level). When you write source code, you access the library through an API. Once the code is compiled, your application accesses the binary data in the library through the ABI. The ABI defines the structures and methods that your compiled application will use to access the external library (just like the API did), only on a lower level. Your API defines the order in which you pass arguments to a function. Your ABI defines the mechanics of how these arguments are passed (registers, stack, etc.). Your API defines which functions are part of your library. Your ABI defines how your code is stored inside the library file, so that any program using your library can locate the desired function and execute it.

ABIs are important when it comes to applications that use external libraries. Libraries are full of code and other resources, but your program has to know how to locate what it needs inside the library file. Your ABI defines how the contents of a library are stored inside the file, and your program uses the ABI to search through the file and find what it needs. If everything in your system conforms to the same ABI, then any program is able to work with any library file, no matter who created them. Linux and Windows use different ABIs, so a Windows program won't know how to access a library compiled for Linux.

Sometimes, ABI changes are unavoidable. When this happens, any programs that use that library will not work unless they are re-compiled to use the new version of the library. If the ABI changes but the API does not, then the old and new library versions are sometimes called "source compatible". This implies that while a program compiled for one library version will not work with the other, source code written for one will work for the other if re-compiled.

For this reason, developers tend to try to keep their ABI stable (to minimize disruption). Keeping an ABI stable means not changing function interfaces (return type and number, types, and order of arguments), definitions of data types or data structures, defined constants, etc. New functions and data types can be added, but existing ones must stay the same. If, for instance, your library uses 32-bit integers to indicate the offset of a function and you switch to 64-bit integers, then already-compiled code that uses that library will not be accessing that field (or any following it) correctly. Accessing data structure members gets converted into memory addresses and offsets during compilation and if the data structure changes, then these offsets will not point to what the code is expecting them to point to and the results are unpredictable at best.

An ABI isn't necessarily something you will explicitly provide unless you are doing very low-level systems design work. It isn't language-specific either, since (for example) a C application and a Pascal application can use the same ABI after they are compiled.

Edit: Regarding your question about the chapters regarding the ELF file format in the SysV ABI docs: The reason this information is included is because the ELF format defines the interface between operating system and application. When you tell the OS to run a program, it expects the program to be formatted in a certain way and (for example) expects the first section of the binary to be an ELF header containing certain information at specific memory offsets. This is how the application communicates important information about itself to the operating system. If you build a program in a non-ELF binary format (such as a.out or PE), then an OS that expects ELF-formatted applications will not be able to interpret the binary file or run the application. This is one big reason why Windows apps cannot be run directly on a Linux machine (or vice versa) without being either re-compiled or run inside some type of emulation layer that can translate from one binary format to another.

IIRC, Windows currently uses the Portable Executable (or, PE) format. There are links in the "external links" section of that Wikipedia page with more information about the PE format.

Also, regarding your note about C++ name mangling: When locating a function in a library file, the function is typically looked up by name. C++ allows you to overload function names, so name alone is not sufficient to identify a function. C++ compilers have their own ways of dealing with this internally, called name mangling. An ABI can define a standard way of encoding the name of a function so that programs built with a different language or compiler can locate what they need. When you use extern "c" in a C++ program, you're instructing the compiler to use a standardized way of recording names that's understandable by other software.

How to use adb pull command?

I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.

I found a link doing the same thing. Try following these steps.

How to copy selected files from Android with adb pull

File upload from <input type="file">

There is a slightly better way to access attached files. You could use template reference variable to get an instance of the input element.

Here is an example based on the first answer:

@Component({
  selector: 'my-app',
  template: `
    <div>
      <input type="file" #file (change)="onChange(file.files)"/>
    </div>
  `,
  providers: [ UploadService ]
})

export class AppComponent {
  onChange(files) {
    console.log(files);
  }
}

Here is an example app to demonstrate this in action.

Template reference variables might be useful, e.g. you could access them via @ViewChild directly in the controller.

How do you add multi-line text to a UIButton?

To restate Roger Nolan's suggestion, but with explicit code, this is the general solution:

button.titleLabel?.numberOfLines = 0

Linux shell script for database backup

#!/bin/sh
#Procedures = For DB Backup
#Scheduled at : Every Day 22:00

v_path=/etc/database_jobs/db_backup
logfile_path=/etc/database_jobs
v_file_name=DB_Production
v_cnt=0

MAILTO="[email protected]"
touch "$logfile_path/kaka_db_log.log"

#DB Backup
mysqldump -uusername -ppassword -h111.111.111.111 ddbname > $v_path/$v_file_name`date +%Y-%m-%d`.sql 
if [ "$?" -eq 0 ]
  then
   v_cnt=`expr $v_cnt + 1`
  mail -s "DB Backup has been done successfully" $MAILTO < $logfile_path/db_log.log
 else
   mail -s "Alert : kaka DB Backup has been failed" $MAILTO < $logfile_path/db_log.log
   exit
fi

How do I create a unique ID in Java?

Here's my two cent's worth: I've previously implemented an IdFactory class that created IDs in the format [host name]-[application start time]-[current time]-[discriminator]. This largely guaranteed that IDs were unique across JVM instances whilst keeping the IDs readable (albeit quite long). Here's the code in case it's of any use:

public class IdFactoryImpl implements IdFactory {
  private final String hostName;
  private final long creationTimeMillis;
  private long lastTimeMillis;
  private long discriminator;

  public IdFactoryImpl() throws UnknownHostException {
    this.hostName = InetAddress.getLocalHost().getHostAddress();
    this.creationTimeMillis = System.currentTimeMillis();
    this.lastTimeMillis = creationTimeMillis;
  }

  public synchronized Serializable createId() {
    String id;
    long now = System.currentTimeMillis();

    if (now == lastTimeMillis) {
      ++discriminator;
    } else {
      discriminator = 0;
    }

    // creationTimeMillis used to prevent multiple instances of the JVM
    // running on the same host returning clashing IDs.
    // The only way a clash could occur is if the applications started at
    // exactly the same time.
    id = String.format("%s-%d-%d-%d", hostName, creationTimeMillis, now, discriminator);
    lastTimeMillis = now;

    return id;
  }

  public static void main(String[] args) throws UnknownHostException {
    IdFactory fact = new IdFactoryImpl();

    for (int i=0; i<1000; ++i) {
      System.err.println(fact.createId());
    }
  }
}

Troubleshooting "Warning: session_start(): Cannot send session cache limiter - headers already sent"

I had the same issue, but my solution wasn't as obvious as the suggested ones. It turned out that my php-file was written in UTF-8, which caused issues. I copy/pasted the content of the entire file into a new php-file (Notepad++ tells me this is written in ANSI rather than UTF-8), and now it work flawlessly.

How to build PDF file from binary string returned from a web-service using javascript

Is there any solution like building a pdf file on file system in order to let the user download it?

Try setting responseType of XMLHttpRequest to blob , substituting download attribute at a element for window.open to allow download of response from XMLHttpRequest as .pdf file

var request = new XMLHttpRequest();
request.open("GET", "/path/to/pdf", true); 
request.responseType = "blob";
request.onload = function (e) {
    if (this.status === 200) {
        // `blob` response
        console.log(this.response);
        // create `objectURL` of `this.response` : `.pdf` as `Blob`
        var file = window.URL.createObjectURL(this.response);
        var a = document.createElement("a");
        a.href = file;
        a.download = this.response.name || "detailPDF";
        document.body.appendChild(a);
        a.click();
        // remove `a` following `Save As` dialog, 
        // `window` regains `focus`
        window.onfocus = function () {                     
          document.body.removeChild(a)
        }
    };
};
request.send();

Getting only hour/minute of datetime

Try this:

var src = DateTime.Now;
var hm = new DateTime(src.Year, src.Month, src.Day, src.Hour, src.Minute, 0);

Deleting a SQL row ignoring all foreign keys and constraints

On all tables with foreign keys pointing to this one, use:

ALTER TABLE MyOtherTable NOCHECK CONSTRAINT fk_name

Initial size for the ArrayList

Being late to this, but after Java 8, I personally find this following approach with the Stream API more concise and can be an alternative to the accepted answer.

For example,

Arrays.stream(new int[size]).boxed().collect(Collectors.toList())

where size is the desired List size and without the disadvantage mentioned here, all elements in the List are initialized as 0.

(I did a quick search and did not see stream in any answers posted - feel free to let me know if this answer is redundant and I can remove it)

Removing duplicates from rows based on specific columns in an RDD/Spark DataFrame

I used inbuilt function dropDuplicates(). Scala code given below

val data = sc.parallelize(List(("Foo",41,"US",3),
("Foo",39,"UK",1),
("Bar",57,"CA",2),
("Bar",72,"CA",2),
("Baz",22,"US",6),
("Baz",36,"US",6))).toDF("x","y","z","count")

data.dropDuplicates(Array("x","count")).show()

Output :

+---+---+---+-----+
|  x|  y|  z|count|
+---+---+---+-----+
|Baz| 22| US|    6|
|Foo| 39| UK|    1|
|Foo| 41| US|    3|
|Bar| 57| CA|    2|
+---+---+---+-----+

What are .a and .so files?

.a files are usually libraries which get statically linked (or more accurately archives), and
.so are dynamically linked libraries.

To do a port you will need the source code that was compiled to make them, or equivalent files on your AIX machine.

How to map a composite key with JPA and Hibernate?

To map a composite key, you can use the EmbeddedId or the IdClass annotations. I know this question is not strictly about JPA but the rules defined by the specification also applies. So here they are:

2.1.4 Primary Keys and Entity Identity

...

A composite primary key must correspond to either a single persistent field or property or to a set of such fields or properties as described below. A primary key class must be defined to represent a composite primary key. Composite primary keys typically arise when mapping from legacy databases when the database key is comprised of several columns. The EmbeddedId and IdClass annotations are used to denote composite primary keys. See sections 9.1.14 and 9.1.15.

...

The following rules apply for composite primary keys:

  • The primary key class must be public and must have a public no-arg constructor.
  • If property-based access is used, the properties of the primary key class must be public or protected.
  • The primary key class must be serializable.
  • The primary key class must define equals and hashCode methods. The semantics of value equality for these methods must be consistent with the database equality for the database types to which the key is mapped.
  • A composite primary key must either be represented and mapped as an embeddable class (see Section 9.1.14, “EmbeddedId Annotation”) or must be represented and mapped to multiple fields or properties of the entity class (see Section 9.1.15, “IdClass Annotation”).
  • If the composite primary key class is mapped to multiple fields or properties of the entity class, the names of primary key fields or properties in the primary key class and those of the entity class must correspond and their types must be the same.

With an IdClass

The class for the composite primary key could look like (could be a static inner class):

public class TimePK implements Serializable {
    protected Integer levelStation;
    protected Integer confPathID;

    public TimePK() {}

    public TimePK(Integer levelStation, Integer confPathID) {
        this.levelStation = levelStation;
        this.confPathID = confPathID;
    }
    // equals, hashCode
}

And the entity:

@Entity
@IdClass(TimePK.class)
class Time implements Serializable {
    @Id
    private Integer levelStation;
    @Id
    private Integer confPathID;

    private String src;
    private String dst;
    private Integer distance;
    private Integer price;

    // getters, setters
}

The IdClass annotation maps multiple fields to the table PK.

With EmbeddedId

The class for the composite primary key could look like (could be a static inner class):

@Embeddable
public class TimePK implements Serializable {
    protected Integer levelStation;
    protected Integer confPathID;

    public TimePK() {}

    public TimePK(Integer levelStation, Integer confPathID) {
        this.levelStation = levelStation;
        this.confPathID = confPathID;
    }
    // equals, hashCode
}

And the entity:

@Entity
class Time implements Serializable {
    @EmbeddedId
    private TimePK timePK;

    private String src;
    private String dst;
    private Integer distance;
    private Integer price;

    //...
}

The @EmbeddedId annotation maps a PK class to table PK.

Differences:

  • From the physical model point of view, there are no differences
  • @EmbeddedId somehow communicates more clearly that the key is a composite key and IMO makes sense when the combined pk is either a meaningful entity itself or it reused in your code.
  • @IdClass is useful to specify that some combination of fields is unique but these do not have a special meaning.

They also affect the way you write queries (making them more or less verbose):

  • with IdClass

    select t.levelStation from Time t
    
  • with EmbeddedId

    select t.timePK.levelStation from Time t
    

References

  • JPA 1.0 specification
    • Section 2.1.4 "Primary Keys and Entity Identity"
    • Section 9.1.14 "EmbeddedId Annotation"
    • Section 9.1.15 "IdClass Annotation"

Adding a 'share by email' link to website

Something like this might be the easiest way.

<a href="mailto:?subject=I wanted you to see this site&amp;body=Check out this site http://www.website.com."
   title="Share by Email">
  <img src="http://png-2.findicons.com/files/icons/573/must_have/48/mail.png">
</a>

You could find another email image and add that if you wanted.

How can I convert a Word document to PDF?

I agree with posters listing OpenOffice as a high-fidelity import/export facility of word / pdf docs with a Java API and it also works across platforms. OpenOffice import/export filters are pretty powerful and preserve most formatting during conversion to various formats including PDF. Docmosis and JODReports value-add to make life easier than learning the OpenOffice API directly which can be challenging because of the style of the UNO api and the crash-related bugs.

ASP.NET page life cycle explanation

Partial Class _Default
    Inherits System.Web.UI.Page
    Dim str As String

    Protected Sub Page_Disposed(sender As Object, e As System.EventArgs) Handles Me.Disposed

        str += "PAGE DISPOSED" & "<br />"
    End Sub

    Protected Sub Page_Error(sender As Object, e As System.EventArgs) Handles Me.Error
        str += "PAGE ERROR " & "<br />"
    End Sub

    Protected Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
        str += "PAGE INIT " & "<br />"
    End Sub

    Protected Sub Page_InitComplete(sender As Object, e As System.EventArgs) Handles Me.InitComplete
        str += "INIT Complte " & "<br />"
    End Sub

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        str += "PAGE LOAD " & "<br />"

    End Sub

    Protected Sub Page_LoadComplete(sender As Object, e As System.EventArgs) Handles Me.LoadComplete
        str += "PAGE LOAD Complete " & "<br />"
    End Sub

    Protected Sub Page_PreInit(sender As Object, e As System.EventArgs) Handles Me.PreInit
        str = ""
        str += "PAGE PRE INIT" & "<br />"
    End Sub

    Protected Sub Page_PreLoad(sender As Object, e As System.EventArgs) Handles Me.PreLoad
        str += "PAGE PRE LOAD " & "<br />"
    End Sub

    Protected Sub Page_PreRender(sender As Object, e As System.EventArgs) Handles Me.PreRender
        str += "PAGE PRE RENDER " & "<br />"
    End Sub

    Protected Sub Page_PreRenderComplete(sender As Object, e As System.EventArgs) Handles Me.PreRenderComplete
        str += "PAGE PRE RENDER COMPLETE " & "<br />"
    End Sub

    Protected Sub Page_SaveStateComplete(sender As Object, e As System.EventArgs) Handles Me.SaveStateComplete
        str += "PAGE SAVE STATE COMPLTE  " & "<br />"
        lbl.Text = str
    End Sub

    Protected Sub Page_Unload(sender As Object, e As System.EventArgs) Handles Me.Unload
        'Response.Write("PAGE UN LOAD\n")
    End Sub
End Class

On Duplicate Key Update same as insert

Here is a solution to your problem:

I've tried to solve problem like yours & I want to suggest to test from simple aspect.

Follow these steps: Learn from simple solution.

Step 1: Create a table schema using this SQL Query:

CREATE TABLE IF NOT EXISTS `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(30) NOT NULL,
  `password` varchar(32) NOT NULL,
  `status` tinyint(1) DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `no_duplicate` (`username`,`password`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

A table <code>user</code> with data

Step 2: Create an index of two columns to prevent duplicate data using following SQL Query:

ALTER TABLE `user` ADD INDEX no_duplicate (`username`, `password`);

or, Create an index of two column from GUI as follows: Create index from GUI Select columns to create index Indexes of table <code>user</code>

Step 3: Update if exist, insert if not using following queries:

INSERT INTO `user`(`username`, `password`) VALUES ('ersks','Nepal') ON DUPLICATE KEY UPDATE `username`='master',`password`='Nepal';

INSERT INTO `user`(`username`, `password`) VALUES ('master','Nepal') ON DUPLICATE KEY UPDATE `username`='ersks',`password`='Nepal';

Table <code>user</code> after running above query

Compare two files line by line and generate the difference in another file

The Unix utility diff is meant for exactly this purpose.

$ diff -u file1 file2 > file3

See the manual and the Internet for options, different output formats, etc.

Django templates: If false?

I think this will work for you:

{% if not myvar %}

select a value where it doesn't exist in another table

SELECT ID 
  FROM A 
 WHERE NOT EXISTS( SELECT 1
                     FROM B
                    WHERE B.ID = A.ID
                 )

KnockoutJs v2.3.0 : Error You cannot apply bindings multiple times to the same element

Two things are important for above solutions to work:

  1. When applying bindings, you need to specify scope (element) !!

  2. When clearing bindings, you must specify exactly same element used for scope.

Code is below

Markup

<div id="elt1" data-bind="with: data">
    <input type="text" data-bind="value: text1" >
</form>

Binding view

var myViewModel = {
  "data" : {
    "text1" : "bla bla"
  }
}:

Javascript

ko.applyBindings(myViewModel, document.getElementById('elt1'));

Clear bindings

ko.cleanNode(document.getElementById('elt1'));

How/when to use ng-click to call a route?

Another solution but without using ng-click which still works even for other tags than <a>:

<tr [routerLink]="['/about']">

This way you can also pass parameters to your route: https://stackoverflow.com/a/40045556/838494

(This is my first day with angular. Gentle feedback is welcome)

Make HTML5 video poster be same size as video itself

You can use poster to show image instead of video on mobile device(or devices which doesn't support the video autoplay functionality). Because mobile devices not support video autoplay functionality.

<div id="wrap_video">
<video preload="preload" id="Video" autoplay="autoplay" loop="loop" poster="default.jpg">
<source src="Videos.mp4" type="video/mp4">
Your browser does not support the <code>video</code> tag.
</video>
</div>

Now you can just style the poster attribute which is inside the video tag for mobile device via media-query.

#wrap_video
{
width:480px;
height:360px;
position: relative;
} 
@media (min-width:360px) and (max-width:780px)
{
video[poster]
{
top:0 !important;
left:0 !important;
width:480px !important;
height:360px !important;
position: absolute !important;
}
}

How to get Git to clone into current directory

Further improving on @phatblat's answer:

git clone --no-checkout <repository> tmp \
  && mv tmp/.git . \
  && rmdir tmp \
  && git checkout master

as one liner:

git clone --no-checkout <repository> tmp && mv tmp/.git . && rmdir tmp && git checkout master

Is it possible to get multiple values from a subquery?

View this web: http://www.w3resource.com/sql/subqueries/multiplee-row-column-subqueries.php

Use example

select ord_num, agent_code, ord_date, ord_amount  
from orders  
where(agent_code, ord_amount) IN  
(SELECT agent_code, MIN(ord_amount)  
FROM orders   
GROUP BY agent_code);    

Any way to clear python's IDLE window?

"command + L" for MAC OS X.

"control + L" for Ubuntu

Clears the last line on the interactive session

Decode UTF-8 with Javascript

// String to Utf8 ByteBuffer

function strToUTF8(str){
  return Uint8Array.from(encodeURIComponent(str).replace(/%(..)/g,(m,v)=>{return String.fromCodePoint(parseInt(v,16))}), c=>c.codePointAt(0))
}

// Utf8 ByteArray to string

function UTF8toStr(ba){
  return decodeURIComponent(ba.reduce((p,c)=>{return p+'%'+c.toString(16),''}))
}

Create two blank lines in Markdown

If your Markdown compiler supports HTML, you can add <br/><br/> in the Markdown source.

How to find Max Date in List<Object>?

LocalDate maxDate = dates.stream()
                            .max( Comparator.comparing( LocalDate::toEpochDay ) )
                            .get();

LocalDate minDate = dates.stream()
                            .min( Comparator.comparing( LocalDate::toEpochDay ) )
                            .get();

jquery clear input default value

You may use this..

<body>
    <form method="" action="">
        <input type="text" name="email" class="input" />
        <input type="submit" value="Sign Up" class="button" />
    </form>
</body>

<script>
    $(document).ready(function() {
        $(".input").val("Email Address");
        $(".input").on("focus", function() {
            $(".input").val("");
        });
        $(".button").on("click", function(event) {
            $(".input").val("");
        });
    });
</script>

Talking of your own code, the problem is that the attr api of jquery is set by

$('.input').attr('value','Email Adress');

and not as you have done:

$('.input').attr('value') = 'Email address';

Iterating over dictionaries using 'for' loops

It's not that key is a special word, but that dictionaries implement the iterator protocol. You could do this in your class, e.g. see this question for how to build class iterators.

In the case of dictionaries, it's implemented at the C level. The details are available in PEP 234. In particular, the section titled "Dictionary Iterators":

  • Dictionaries implement a tp_iter slot that returns an efficient iterator that iterates over the keys of the dictionary. [...] This means that we can write

    for k in dict: ...
    

    which is equivalent to, but much faster than

    for k in dict.keys(): ...
    

    as long as the restriction on modifications to the dictionary (either by the loop or by another thread) are not violated.

  • Add methods to dictionaries that return different kinds of iterators explicitly:

    for key in dict.iterkeys(): ...
    
    for value in dict.itervalues(): ...
    
    for key, value in dict.iteritems(): ...
    

    This means that for x in dict is shorthand for for x in dict.iterkeys().

In Python 3, dict.iterkeys(), dict.itervalues() and dict.iteritems() are no longer supported. Use dict.keys(), dict.values() and dict.items() instead.

Boto3 to download all files from a S3 Bucket

It is a very bad idea to get all files in one go, you should rather get it in batches.

One implementation which I use to fetch a particular folder (directory) from S3 is,

def get_directory(directory_path, download_path, exclude_file_names):
    # prepare session
    session = Session(aws_access_key_id, aws_secret_access_key, region_name)

    # get instances for resource and bucket
    resource = session.resource('s3')
    bucket = resource.Bucket(bucket_name)

    for s3_key in self.client.list_objects(Bucket=self.bucket_name, Prefix=directory_path)['Contents']:
        s3_object = s3_key['Key']
        if s3_object not in exclude_file_names:
            bucket.download_file(file_path, download_path + str(s3_object.split('/')[-1])

and still if you want to get the whole bucket use it via CIL as @John Rotenstein mentioned as below,

aws s3 cp --recursive s3://bucket_name download_path

JavaScript associative array to JSON

There are no associative arrays in JavaScript. However, there are objects with named properties, so just don't initialise your "array" with new Array, then it becomes a generic object.

Sending multipart/formdata with jQuery.ajax

Devin Venable's answer was close to what I wanted, but I wanted one that would work on multiple forms, and use the action already specified in the form so that each file would go to the right place.

I also wanted to use jQuery's on() method so I could avoid using .ready().

That got me to this: (replace formSelector with your jQuery selector)

$(document).on('submit', formSelecter, function( e ) {
        e.preventDefault();
    $.ajax( {
        url: $(this).attr('action'),
        type: 'POST',
        data: new FormData( this ),
        processData: false,
        contentType: false
    }).done(function( data ) {
        //do stuff with the data you got back.
    });

});

Add custom header in HttpWebRequest

A simple method of creating the service, adding headers and reading the JSON response,

private static void WebRequest()
    {
        const string WEBSERVICE_URL = "<<Web service URL>>";
        try
        {
            var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
            if (webRequest != null)
            {
                webRequest.Method = "GET";
                webRequest.Timeout = 12000;
                webRequest.ContentType = "application/json";
                webRequest.Headers.Add("Authorization", "Basic dchZ2VudDM6cGFdGVzC5zc3dvmQ=");

                using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
                {
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
                    {
                        var jsonResponse = sr.ReadToEnd();
                        Console.WriteLine(String.Format("Response: {0}", jsonResponse));
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }

How to display binary data as image - extjs 4

The data URI format is:

data:<headers>;<encoding>,<data>

So, you need only append your data to the "data:image/jpeg;," string:

var your_binary_data = document.body.innerText.replace(/(..)/gim,'%$1'); // parse text data to URI format

window.open('data:image/jpeg;,'+your_binary_data);

Assert equals between 2 Lists in Junit

Don't transform to string and compare. This is not good for perfomance. In the junit, inside Corematchers, there's a matcher for this => hasItems

List<Integer> yourList = Arrays.asList(1,2,3,4)    
assertThat(yourList, CoreMatchers.hasItems(1,2,3,4,5));

This is the better way that I know of to check elements in a list.

How can I convert an MDB (Access) file to MySQL (or plain SQL file)?

OSX users can follow by Nicolay77 or mikkom that uses the mdbtools utility. You can install it via Homebrew. Just have your homebrew installed and then go

$ homebrew install mdbtools

Then create one of the scripts described by the guys and use it. I've used mikkom's one, converted all my mdb files into sql.

$ ./to_mysql.sh myfile.mdb > myfile.sql

(which btw contains more than 1 table)

How do I authenticate a WebClient request?

What kind of authentication are you using? If it's Forms authentication, then at best, you'll have to find the .ASPXAUTH cookie and pass it in the WebClient request.

At worst, it won't work.

Laravel Eloquent update just if changes have been made

You're already doing it!

save() will check if something in the model has changed. If it hasn't it won't run a db query.

Here's the relevant part of code in Illuminate\Database\Eloquent\Model@performUpdate:

protected function performUpdate(Builder $query, array $options = [])
{
    $dirty = $this->getDirty();

    if (count($dirty) > 0)
    {
        // runs update query
    }

    return true;
}

The getDirty() method simply compares the current attributes with a copy saved in original when the model is created. This is done in the syncOriginal() method:

public function __construct(array $attributes = array())
{
    $this->bootIfNotBooted();

    $this->syncOriginal();

    $this->fill($attributes);
}

public function syncOriginal()
{
    $this->original = $this->attributes;

    return $this;
}

If you want to check if the model is dirty just call isDirty():

if($product->isDirty()){
    // changes have been made
}

Or if you want to check a certain attribute:

if($product->isDirty('price')){
    // price has changed
}

Expand a div to fill the remaining width

If both of the widths are variable length why don't you calculate the width with some scripting or server side?

<div style="width: <=% getTreeWidth() %>">Tree</div>

<div style="width: <=% getViewWidth() %>">View</div>

PHP isset() with multiple parameters

Use the php's OR (||) logical operator for php isset() with multiple operator e.g

if (isset($_POST['room']) || ($_POST['cottage']) || ($_POST['villa'])) {

}

Create Git branch with current changes

Like stated in this question: Git: Create a branch from unstagged/uncommited changes on master: stash is not necessary.

Just use:

git checkout -b topic/newbranch

Any uncommitted work will be taken along to the new branch.

If you try to push you will get the following message

fatal: The current branch feature/NEWBRANCH has no upstream branch. To push the current branch and set the remote as upstream, use

git push --set-upstream origin feature/feature/NEWBRANCH

Just do as suggested to create the branch remotely:

git push --set-upstream origin feature/feature/NEWBRANCH

How to get the second column from command output?

If you could use something other than 'awk' , then try this instead

echo '1540 "A B"' | cut -d' ' -f2-

-d is a delimiter, -f is the field to cut and with -f2- we intend to cut the 2nd field until end.

How to round a number to significant figures in Python

Given a question so thoroughly answered why not add another

This suits my aesthetic a little better, though many of the above are comparable

import numpy as np

number=-456.789
significantFigures=4

roundingFactor=significantFigures - int(np.floor(np.log10(np.abs(number)))) - 1
rounded=np.round(number, roundingFactor)

string=rounded.astype(str)

print(string)

This works for individual numbers and numpy arrays, and should function fine for negative numbers.

There's one additional step we might add - np.round() returns a decimal number even if rounded is an integer (i.e. for significantFigures=2 we might expect to get back -460 but instead we get -460.0). We can add this step to correct for that:

if roundingFactor<=0:
    rounded=rounded.astype(int)

Unfortunately, this final step won't work for an array of numbers - I'll leave that to you dear reader to figure out if you need.

What is the difference between OFFLINE and ONLINE index rebuild in SQL Server?

In ONLINE mode the new index is built while the old index is accessible to reads and writes. any update on the old index will also get applied to the new index. An antimatter column is used to track possible conflicts between the updates and the rebuild (ie. delete of a row which was not yet copied). See Online Index Operations. When the process is completed the table is locked for a brief period and the new index replaces the old index. If the index contains LOB columns, ONLINE operations are not supported in SQL Server 2005/2008/R2.

In OFFLINE mode the table is locked upfront for any read or write, and then the new index gets built from the old index, while holding a lock on the table. No read or write operation is permitted on the table while the index is being rebuilt. Only when the operation is done is the lock on the table released and reads and writes are allowed again.

Note that in SQL Server 2012 the restriction on LOBs was lifted, see Online Index Operations for indexes containing LOB columns.

How to put a UserControl into Visual Studio toolBox

I'm assuming you're using VS2010 (that's what you've tagged the question as) I had problems getting them to add automatically to the toolbox as in VS2008/2005. There's actually an option to stop the toolbox auto populating!

Go to Tools > Options > Windows Forms Designer > General

At the bottom of the list you'll find Toolbox > AutoToolboxPopulate which on a fresh install defaults to False. Set it true and then rebuild your solution.

Hey presto they user controls in you solution should be automatically added to the toolbox. You might have to reload the solution as well.

Command to get latest Git commit hash from a branch

git log -n 1 [branch_name]

branch_name (may be remote or local branch) is optional. Without branch_name, it will show the latest commit on the current branch.

For example:

git log -n 1
git log -n 1 origin/master
git log -n 1 some_local_branch

git log -n 1 --pretty=format:"%H"  #To get only hash value of commit

How to make a TextBox accept only alphabetic characters?

You can try by handling the KeyPress event for the textbox

void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back);
}

Additionally say allow backspace in case you want to remove some text, this should work perfectly fine for you

EDIT

The above code won't work for paste in the field for which i believe you will have to use TextChanged event but then it would be a bit more complicated with you having to remove the incorrect char or highlight it and place the cursor for the user to make the correction Or maybe you could validate once the user has entered the complete text and tabs off the control.

Auto Resize Image in CSS FlexBox Layout and keeping Aspect Ratio?

You might want to try the very new and simple CSS3 feature:

img { 
  object-fit: contain;
}

It preserves the picture ratio (as when you use the background-picture trick), and in my case worked nicely for the same issue.

Be careful though, it is not supported by IE (see support details here).

Maximum call stack size exceeded on npm install

I tried everything to fix this issue on my windows 7 machine like

Reinstalling and rebuilding npm

At last, I fixed this small configuration setting issue by wasting my entire day.

How I resolved this issue

Removing my project specific configurations in global .npmrc at location like drive:/Windows/Users/../.npmrc

Reverse a string in Python

This is simple and meaningful reverse function, easy to understand and code

def reverse_sentence(text):
    words = text.split(" ")
    reverse =""
    for word in reversed(words):
        reverse += word+ " "
    return reverse

How to completely uninstall Android Studio from windows(v10)?

First go to android studio folder on location that you installed it ( It’s usually in this path by default ; C:\Program Files\Android\Android Studio, unless you change it when you install Android Studio). Find and run uninstall.exe file.

Wait until uninstallation complete successfully, just few minutes, and after click the close.

To delete any remains of Android Studio setting files, in File Explorer, go to C:\Users\%username%, and delete .android, .AndroidStudio(#version-number) and also .gradle, AndroidStudioProjects if they exist. If you want remain your projects, you’d like to keep AndroidStudioProjects folder.

Then, go to C:\Users\%username%\AppData\Roaming and delete the JetBrains directory.

Note that AppData folder is hidden by default, to make visible it go to view tab and check hidden items in windows8 and10 ( in windows7 Select Folder Options, then select the View tab. Under Advanced settings, select Show hidden files, folders, and drives, and then select OK.

Done, you can remove Android Studio successfully, if you plan to delete SDK tools too, it is enough to remove SDK folder completely.

How to select specific form element in jQuery?

although it is invalid html but you can use selector context to limit your selector in your case it would be like :

$("input[name='name']" , "#form2").val("Hello World! ");

http://api.jquery.com/jquery/#selector-context

Design Documents (High Level and Low Level Design Documents)

High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.

LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.

Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.

As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.

Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.

Repeat string to certain length

def extended_string (word, length) :

    extra_long_word = word * (length//len(word) + 1)
    required_string = extra_long_word[:length]
    return required_string

print(extended_string("abc", 7))

Signing a Windows EXE file

This is not a direct answer to the question, but it is closely related (and useful I hope) since sooner or later a programmer will have put his hand into the wallet:

So, prices for EV signature (OV doesn't help much):

1 Year 379 euro
en.sklep.certum.pl
(seems to be for Poland users only)

1 Year $350 + ($50 hidden fee)
2 Year $600
3 Year $750
(OV: $84 per year)
www.ksoftware.net
eToken sent as USB stick. No reader needed. You actually purchase from Comodo (Sectigo). They are veeeeerrry slow.

1 Year 364 euro+19%VAT
(OV 69+VAT)
www.leaderssl.de

1 Year $499 USD
3 Year $897 USD
sectigo.com

1 Year $410 total
2 Years $760 total
3 Years $950 total
www.globalsign.com

1 Year: $600 (it was $104)
3 Year: ?
www.digicert.com

1 Year: $700
3 Years: ridiculous expensive
[symantec.com]

More prices here:
cheapsslsecurity.com CodeSigning EV
cheapsslsecurity.com SSL only!


Oracle SQL update based on subquery between two tables

There are two ways to do what you are trying

One is a Multi-column Correlated Update

UPDATE PRODUCTION a
SET (name, count) = (
  SELECT name, count
  FROM STAGING b
  WHERE a.ID = b.ID);

DEMO

You can use merge

MERGE INTO PRODUCTION a
USING ( select id, name, count 
          from STAGING ) b
ON ( a.id = b.id )
WHEN MATCHED THEN 
UPDATE SET  a.name = b.name,
            a.count = b.count

DEMO

Generating UML from C++ code?

StarUML does just that and it is free. Unfortunately it hasn't been updated for a while. There were a couple of offshoot projects (as the project admins wouldn't allow it to be taken over) but they too have died a death.

Error 1022 - Can't write; duplicate key in table

This can also arise in connection with a bug in certain versions of Percona Toolkit's online-schema-change tool. To mutate a large table, pt-osc first creates a duplicate table and copies all the records into it. Under some circumstances, some versions of pt-osc 2.2.x will try to give the constraints on the new table the same names as the constraints on the old table.

A fix was released in 2.3.0.

See https://bugs.launchpad.net/percona-toolkit/+bug/1498128 for more details.

Java: how to import a jar file from command line

try

java -cp "your_jar.jar:lib/referenced_jar.jar" com.your.main.Main

If you are on windows, you should use ; instead of :

Run a .bat file using python code

python_test.py

import subprocess
a = subprocess.check_output("batch_1.bat")
print a

This gives output from batch file to be print on the python IDLE/running console. So in batch file you can echo the result in each step to debug the issue. This is also useful in automation when there is an error happening in the batch call, to understand and locate the error easily.(put "echo off" in batch file beginning to avoid printing everything)

batch_1.bat

echo off    
echo "Hello World" 
md newdir 
echo "made new directory"

How can I keep my branch up to date with master with git?

You can use the cherry-pick to get the particular bug fix commit(s)

$ git checkout branch
$ git cherry-pick bugfix

Can't bind to 'routerLink' since it isn't a known property

You need to add RouterMoudle into imports sections of the module containing the Header component

When using SASS how can I import a file from a different directory?

Gulp will do the job for watching your sass files and also adding paths of other file with includePaths. example:

gulp.task('sass', function() {
  return gulp.src('scss/app.scss')
    .pipe($.sass({
      includePaths: sassPaths
    })
    .pipe(gulp.dest('css'));
});

"Untrusted App Developer" message when installing enterprise iOS Application

Today, I was testing this with iOS 9 Beta and found the solution.

To solve it, go to:

  1. Settings -> General -> Profiles [Device Management on iOS 10]
  2. Under ENTERPRISE APP, choose your current developer account name.
  3. Tap Trust "Your developer account name"
  4. Tap "Trust" in pop up.
  5. Done

javascript regular expression to not match a word

function doesNotContainAbcOrDef(x) {
    return (x.match('abc') || x.match('def')) === null;
}

Reading from a text file and storing in a String

How can we read data from a text file and store in a String Variable?

Err, read data from the file and store it in a String variable. It's just code. Not a real question so far.

Is it possible to pass the filename in a method and it would return the String which is the text from the file.

Yes it's possible. It's also a very bad idea. You should deal with the file a part at a time, for example a line at a time. Reading the entire file into memory before you process any of it adds latency; wastes memory; and assumes that the entire file will fit into memory. One day it won't. You don't want to do it this way.

Error message "Linter pylint is not installed"

  1. Open a terminal (ctrl+~)
  2. Run the command pip install pylint

If that doesn't work: On the off chance you've configured a non-default Python path for your editor, you'll need to match that Python's install location with the pip executable you're calling from the terminal.

This is an issue because the Python extension's settings enable Pylint by default. If you'd rather turn off linting, you can instead change this setting from true to false in your user or workspace settings:

"python.linting.pylintEnabled": false

How to change onClick handler dynamically?

I agree that using jQuery is the best option. You should also avoid using body's onload function and use jQuery's ready function instead. As for the event listeners, they should be functions that take one argument:

document.getElementById("foo").onclick = function (event){alert('foo');};

or in jQuery:

$('#foo').click(function(event) { alert('foo'); }

How to get the current date/time in Java

Java 8 or above

LocalDateTime.now() and ZonedDateTime.now()

how to convert java string to Date object

You basically effectively converted your date in a string format to a date object. If you print it out at that point, you will get the standard date formatting output. In order to format it after that, you then need to convert it back to a date object with a specified format (already specified previously)

String startDateString = "06/27/2007";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); 
Date startDate;
try {
    startDate = df.parse(startDateString);
    String newDateString = df.format(startDate);
    System.out.println(newDateString);
} catch (ParseException e) {
    e.printStackTrace();
}

Center icon in a div - horizontally and vertically

Since they are already inline-block child elements, you can set text-align:center on the parent without having to set a width or margin:0px auto on the child. Meaning it will work for dynamically generated content with varying widths.

.img_container, .img_container2 {
    text-align: center;
}

This will center the child within both div containers.

UPDATE:

For vertical centering, you can use the calc() function assuming the height of the icon is known.

.img_container > i, .img_container2 > i {
    position:relative;
    top: calc(50% - 10px); /* 50% - 3/4 of icon height */
}

jsFiddle demo - it works.

For what it's worth - you can also use vertical-align:middle assuming display:table-cell is set on the parent.

py2exe - generate single executable file

As the other poster mention, py2exe, will generate an executable + some libraries to load. You can also have some data to add to your program.

Next step is to use an installer, to package all this into one easy-to-use installable/unistallable program.

I have used InnoSetup with delight for several years and for commercial programs, so I heartily recommend it.

Android requires compiler compliance level 5.0 or 6.0. Found '1.7' instead. Please use Android Tools > Fix Project Properties

Following worked for me

Enable project-specific settings and set the compliance level to 1.6

How can you do that?

In your Eclipse Package Explorer 3rd click on your project and select properties. Properties Window will open. Select Java Compiler on the left panel of the window. Now Enable project specific settings and set the Complier compliance level to 1.6. Select Apply and then OK.

JOptionPane Input to int

String String_firstNumber = JOptionPane.showInputDialog("Input  Semisecond");
int Int_firstNumber = Integer.parseInt(firstNumber);

Now your Int_firstnumber contains integer value of String_fristNumber.

hope it helped

Vue.js: Conditional class style binding

the problem is blade, try this

<i class="fa" v-bind:class="['{{content['cravings']}}' ? 'fa-checkbox-marked' : 'fa-checkbox-blank-outline']"></i>

how to check if List<T> element contains an item with a Particular Property Value

You don't actually need LINQ for this because List<T> provides a method that does exactly what you want: Find.

Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire List<T>.

Example code:

PricePublicModel result = pricePublicList.Find(x => x.Size == 200);

Accessing inventory host variable in Ansible playbook

You should be able to use the variable name directly

ansible_ssh_host

Or you can go through hostvars without having to specify the host literally by using the magic variable inventory_hostname

hostvars[inventory_hostname].ansible_ssh_host

How do you compare structs for equality in C?

You can't use memcmp to compare structs for equality due to potential random padding characters between field in structs.

  // bad
  memcmp(&struct1, &struct2, sizeof(struct1));

The above would fail for a struct like this:

typedef struct Foo {
  char a;
  /* padding */
  double d;
  /* padding */
  char e;
  /* padding */
  int f;
} Foo ;

You have to use member-wise comparison to be safe.

Error: Unable to run mksdcard SDK tool

Here's what you need to do to fix the issue on Arch Linux :

  1. Enable the multilib repository on your system if you have not already done so by uncommenting the [multilib] section in /etc/pacman.conf :

    [multilib]
    Include = /etc/pacman.d/mirrorlist
    
  2. Update pacman :

    # pacman -Suy
    
  3. Install the 32 bit version of libstdc++5 :

    # pacman -S lib32-libstdc++5
    

Giving multiple conditions in for loop in Java

You can also replace complicated condition with single method call to make it less evil in maintain.

Connect to SQL Server through PDO using SQL Server Driver

This works for me, and in this case was a remote connection: Note: The port was IMPORTANT for me

$dsn = "sqlsrv:Server=server.dyndns.biz,1433;Database=DBNAME";
$conn = new PDO($dsn, "root", "P4sw0rd");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

$sql = "SELECT * FROM Table";

foreach ($conn->query($sql) as $row) {
    print_r($row);
} 

How to export data as CSV format from SQL Server using sqlcmd?

You can run something like this:

sqlcmd -S MyServer -d myDB -E -Q "select col1, col2, col3 from SomeTable" 
       -o "MyData.csv" -h-1 -s"," -w 700
  • -h-1 removes column name headers from the result
  • -s"," sets the column seperator to ,
  • -w 700 sets the row width to 700 chars (this will need to be as wide as the longest row or it will wrap to the next line)

Check whether an array is empty

<?php
if(empty($myarray))
echo"true";
else
echo "false";
?>

Getting full URL of action in ASP.NET MVC

This may be just me being really, really picky, but I like to only define constants once. If you use any of the approaches defined above, your action constant will be defines multiple times.

To avoid this, you can do the following:

    public class Url
    {
        public string LocalUrl { get; }

        public Url(string localUrl)
        {
            LocalUrl = localUrl;
        }

        public override string ToString()
        {
            return LocalUrl;
        }
    }

    public abstract class Controller
    {
        public Url RootAction => new Url(GetUrl());

        protected abstract string Root { get; }

        public Url BuildAction(string actionName)
        {
            var localUrl = GetUrl() + "/" + actionName;
            return new Url(localUrl);
        }

        private string GetUrl()
        {
            if (Root == "")
            {
                return "";
            }

            return "/" + Root;
        }

        public override string ToString()
        {
            return GetUrl();
        }
    }

Then create your controllers, say for example the DataController:

    public static readonly DataController Data = new DataController();
    public class DataController : Controller
    {
        public const string DogAction = "dog";
        public const string CatAction = "cat";
        public const string TurtleAction = "turtle";

        protected override string Root => "data";

        public Url Dog => BuildAction(DogAction);
        public Url Cat => BuildAction(CatAction);
        public Url Turtle => BuildAction(TurtleAction);
    }

Then just use it like:

    // GET: Data/Cat
    [ActionName(ControllerRoutes.DataController.CatAction)]
    public ActionResult Etisys()
    {
        return View();
    }

And from your .cshtml (or any code)

<ul>
    <li><a href="@ControllerRoutes.Data.Dog">Dog</a></li>
    <li><a href="@ControllerRoutes.Data.Cat">Cat</a></li>
</ul>

This is definitely a lot more work, but I rest easy knowing compile time validation is on my side.

How can I flush GPU memory using CUDA (physical reset is unavailable)

One can also use nvtop, which gives an interface very similar to htop, but showing your GPU(s) usage instead, with a nice graph. You can also kill processes directly from here.

Here is a link to its Github : https://github.com/Syllo/nvtop

NVTOP interface

Screenshot sizes for publishing android app on Google Play

  • We require 2 screenshots.
  • Use: Displayed on the details page for your application in Google Play.
  • You may upload up to 8 screenshots each for phone, 7” tablet and 10” tablet.
  • Specs: Minimum dimension: 320 pixels. Maximum dimension: 3840 pixels. The maximum dimension of your screenshot cannot be more than twice as long as the minimum dimension. You may use 24 bit PNG or JPEG image (no alpha). Full bleed, no border in art.
  • We recommend adding screenshots of your app running on a 7" and 10" tablet. Go to ‘Store listing’ page in your Developer Console to add tablet apps screenshots.

https://support.google.com/googleplay/android-developer/answer/1078870?hl=en&ref_topic=2897459

Printing object properties in Powershell

# Json to object
$obj = $obj | ConvertFrom-Json
Write-host $obj.PropertyName

How do I check if an element is really visible with JavaScript?

Try element.getBoundingClientRect(). It will return an object with properties

  • bottom
  • top
  • right
  • left
  • width -- browser dependent
  • height -- browser dependent

Check that the width and height of the element's BoundingClientRect are not zero which is the value of hidden or non-visible elements. If the values are greater than zero the element should be visible in the body. Then check if the bottom property is less than screen.height which would imply that the element is withing the viewport. (Technically you would also have to account for the top of the browser window including the searchbar, buttons, etc.)

msvcr110.dll is missing from computer error while installing PHP

To identify which x86/x64 version of VC is needed:

Go to IIS Manager > Handler Mappings > right click then Edit *.php path. In the "Executable (optional)" field note in which version of Program Files is the php-cgi.exe installed.

How to check if matching text is found in a string in Lua?

There are 2 options to find matching text; string.match or string.find.

Both of these perform a regex search on the string to find matches.


string.find()

string.find(subject string, pattern string, optional start position, optional plain flag)

Returns the startIndex & endIndex of the substring found.

The plain flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger) being interpreted as a regex capture group matching for tiger, it instead looks for (tiger) within a string.

Going the other way, if you want to regex match but still want literal special characters (such as .()[]+- etc.), you can escape them with a percentage; %(tiger%).

You will likely use this in combination with string.sub

Example

str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

string.match()

string.match(s, pattern, optional index)

Returns the capture groups found.

Example

str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

align right in a table cell with CSS

How to position block elements in a td cell

The answers provided do a great job to right-align text in a td cell.

This might not be the solution when you're looking to align a block element as commented in the accepted answer. To achieve such with a block element, I have found it useful to make use of margins;

general syntax

selector {
  margin: top right bottom left;
}

justify right

td {
  /* there is a shorthand, TODO!  */
  margin: auto 0 auto auto;
}

justify center

td {
  margin: auto auto auto auto;
}

/* or the short-hand */
margin: auto;

align center

td {
  margin: auto;
}

JS Fiddle example

Alternatively, you could make you td content display inline-block if that's an option, but that may distort the position of its child elements.

Count the number of occurrences of a character in a string in Javascript

I'm using Node.js v.6.0.0 and the fastest is the one with index (the 3rd method in Lo Sauer's answer).

The second is:

_x000D_
_x000D_
function count(s, c) {_x000D_
  var n = 0;_x000D_
  for (let x of s) {_x000D_
    if (x == c)_x000D_
      n++;_x000D_
  }_x000D_
  return n;_x000D_
}
_x000D_
_x000D_
_x000D_

How can I decode HTML characters in C#?

For strings containing &#x20; I've had to double-decode the string. First decode would turn it into the second pass would correctly decode it to the expected character.

Prevent textbox autofill with previously entered values

Trying from the CodeBehind:

Textbox1.Attributes.Add("autocomplete", "off");

Array versus linked-list

For me it is like this,

  1. Access

    • Linked Lists allow only sequential access to elements. Thus the algorithmic complexities is order of O(n)
    • Arrays allow random access to its elements and thus the complexity is order of O(1)
  2. Storage

    • Linked lists require an extra storage for references. This makes them impractical for lists of small data items such as characters or boolean values.
    • Arrays do not need an extra storage to point to next data item. Each element can be accessed via indexes.
  3. Size

    • The size of Linked lists are dynamic by nature.
    • The size of array is restricted to declaration.
  4. Insertion/Deletion

    • Elements can be inserted and deleted in linked lists indefinitely.
    • Insertion/Deletion of values in arrays are very expensive. It requires memory reallocation.

Google Maps API v3: Can I setZoom after fitBounds?

If I'm not mistaken, I'm assuming you want all your points to be visible on the map with the highest possible zoom level. I accomplished this by initializing the zoom level of the map to 16(not sure if it's the highest possible zoom level on V3).

var map = new google.maps.Map(document.getElementById('map_canvas'), {
  zoom: 16,
  center: marker_point,
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

Then after that I did the bounds stuff:

var bounds = new google.maps.LatLngBounds();

// You can have a loop here of all you marker points
// Begin loop
bounds.extend(marker_point);
// End loop

map.fitBounds(bounds);

Result: Success!

Convert integer to class Date

You can use ymd from lubridate

lubridate::ymd(v)
#[1] "2008-11-01"

Or anytime::anydate

anytime::anydate(v)
#[1] "2008-11-01"

Recyclerview and handling different type of row inflation

You have to implement getItemViewType() method in RecyclerView.Adapter. By default onCreateViewHolder(ViewGroup parent, int viewType) implementation viewType of this method returns 0. Firstly you need view type of the item at position for the purposes of view recycling and for that you have to override getItemViewType() method in which you can pass viewType which will return your position of item. Code sample is given below

@Override
public MyViewholder onCreateViewHolder(ViewGroup parent, int viewType) {
    int listViewItemType = getItemViewType(viewType);
    switch (listViewItemType) {
         case 0: return new ViewHolder0(...);
         case 2: return new ViewHolder2(...);
    }
}

@Override
public int getItemViewType(int position) {   
    return position;
}

// and in the similar way you can set data according 
// to view holder position by passing position in getItemViewType
@Override
public void onBindViewHolder(MyViewholder viewholder, int position) {
    int listViewItemType = getItemViewType(position);
    // ...
}

How do you debug PHP scripts?

I use Netbeans with XDebug. Check it out at its website for docs on how to configure it. http://php.netbeans.org/

How to extract numbers from a string and get an array of ints?

What about to use replaceAll java.lang.String method:

    String str = "qwerty-1qwerty-2 455 f0gfg 4";      
    str = str.replaceAll("[^-?0-9]+", " "); 
    System.out.println(Arrays.asList(str.trim().split(" ")));

Output:

[-1, -2, 455, 0, 4]

Description

[^-?0-9]+
  • [ and ] delimites a set of characters to be single matched, i.e., only one time in any order
  • ^ Special identifier used in the beginning of the set, used to indicate to match all characters not present in the delimited set, instead of all characters present in the set.
  • + Between one and unlimited times, as many times as possible, giving back as needed
  • -? One of the characters “-” and “?”
  • 0-9 A character in the range between “0” and “9”

What does "Use of unassigned local variable" mean?

Give them a default value:

double lateFee=0.0;
double monthlyCharge = 0.0;
double annualRate = 0.0;

Basically, all possible paths don't initialize these variables.

Item frequency count in Python

defaultdict to the rescue!

from collections import defaultdict

words = "apple banana apple strawberry banana lemon"

d = defaultdict(int)
for word in words.split():
    d[word] += 1

This runs in O(n).

Good Free Alternative To MS Access

Much in line with Aurelio's answer, I now work in Ruby on Rails on some applications that I might formerly have done in MS Access. The back end database for a Rails App. is usually, MySql (works well enough and is available on most shared Web hosting) or PostgreSQL (the better choice when possible).

Evaluate if list is empty JSTL

There's also the function tags, a bit more flexible:

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:if test="${fn:length(list) > 0}">

And here's the tag documentation.

how to specify new environment location for conda create

I ran into a similar situation. I did have access to a larger data drive. Depending on your situation, and the access you have to the server you can consider

ln -s /datavol/path/to/your/.conda /home/user/.conda

Then subsequent conda commands will put data to the symlinked dir in datavol

HTTP Ajax Request via HTTPS Page

Make a bypass API in server.js. This works for me.

app.post('/by-pass-api',function(req, response){
  const url = req.body.url;
  console.log("calling url", url);
  request.get(
    url,
    (error, res, body) => {
      if (error) {
        console.error(error)
        return response.status(200).json({'content': "error"}) 
}
        return response.status(200).json(JSON.parse(body))
        },
      )
    })

And call it using axios or fetch like this:

const options = {
     method: 'POST',
     headers: {'content-type': 'application/json'},
     url:`http://localhost:3000/by-pass-api`, // your environment 
     data: { url },  // your https request here
    };

Running CMake on Windows

There is a vcvars32.bat in your Visual Studio installation directory. You can add call cmd.exe at the end of that batch program and launch it. From that shell you can use CMake or cmake-gui and cl.exe would be known to CMake.