Programs & Examples On #Pre commit

Pre-commit is an action taken prior to committing your code into a version control system.

SVN Error: Commit blocked by pre-commit hook (exit code 1) with output: Error: n/a (6)

A pre-commit hook is something that runs on the server, so this probably has nothing to do with your local setup. It could be that you changed something in a settings panel on that is implemented using a pre-commit hook or the myversioncontrol people made an error and added a non-functioning hook.

PHP array delete by value (not key)

$fields = array_flip($fields);
$fields = array_flip($fields);

How to hide underbar in EditText

I have something like this which is very very useful:

generalEditText.getBackground().mutate().setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);

where generalEditText is my EditText and color white is:

<color name="white">#ffffff</color>

This will not remove padding and your EditText will stay as is. Only the line at the bottom will be removed. Sometimes it is more useful to do it like this.

If you use android:background="@null" as many suggested you lose the padding and EditText becomes smaller. At least, it was my case.

A little side note is if you set background null and try the java code I provided above, your app will crash right after executing it. (because it gets the background but it is null.) It may be obvious but I think pointing it out is important.

How to restart kubernetes nodes?

In my case I am running 3 nodes in VM's by using Hyper-V. By using the following steps I was able to "restart" the cluster after restarting all VM's.

  1. (Optional) Swap off

    $ swapoff -a

  2. You have to restart all Docker containers

    $ docker restart $(docker ps -a -q)

  3. Check the nodes status after you performed step 1 and 2 on all nodes (the status is NotReady)

    $ kubectl get nodes

  4. Restart the node

    $ systemctl restart kubelet

  5. Check again the status (now should be in Ready status)

Note: I do not know if it does metter the order of nodes restarting, but I choose to start with the k8s master node and after with the minions. Also it will take a little bit to change the node state from NotReady to Ready

Python [Errno 98] Address already in use

This happens because you trying to run service at the same port and there is an already running application.

This can happen because your service is not stopped in the process stack. Then you just have to kill this process.

There is no need to install anything here is the one line command to kill all running python processes.

for Linux based OS:


kill -9 $(ps -A | grep python | awk '{print $1}')


kill -9 (ps -A | grep python | awk '{print $1}')

Best PHP IDE for Mac? (Preferably free!)

Here's the lowdown on Mac IDE's for PHP

NetBeans Free! Plus, the best functionality of all offerings. Includes inline database connections, code completion, syntax checking, color coding, split views etc. Downside: It's a memory hog on the Mac. Be prepared to allow half a gig of memory then you'll need to shut down and restart.

Komodo A step above a Text Editor. Does not support database connections or split views. Color coding and syntax checking are there to an extent. The project control on Komodo is very unwieldy and strange compared to the other IDEs.

Aptana The perfect solution. Eclipsed based and uses the Aptana PHP plug in. Real time syntax checking, word wrap, drag and drop split views, database connections and a slew of other excellent features. Downside: Not a supported product any more. Aptana Studio 2.0+ uses PDT which is a watered down, under-developed (at present) php plug in.

Zend Studio - Almost identical to Aptana, except no word wrap and you can't change alot of the php configuration on the MAC apparently due to bugs.

Coda Created by Panic, Coda has nice integration with source control and their popular FTP client, transmit. They also have a collaboration feature which is cool for pair-programming.

PhpEd with Parallels or Wine. The best IDE for Windows has all the feature you could need and is worth the effort to pass it through either Parallels or Wine.

Dreamweaver Good for Javascript/HTML/CSS, but only marginal for PHP. There is some color coding, but no syntax checking or code completion native to the package. Database connections are supported, and so are split views.

I'm using NetBeans, which is free, and feature rich. I can deal with the memory issues for a while, but it could be slow coming to the MAC.

Cheers! Korky Kathman Senior Partner Entropy Dynamics, LLC

jQuery: how to change title of document during .ready()?

I am using some nested layouts in Ruby on Rails, and in one of the layouts i have a need to read in a string from a div and set that as the title of the document.

The correct way to do this is on the server side.

In your layout, there at some point will be some code which puts the text in the div. Make this code also set some instance variable such as @page_title, and then in your outer layout have it do <%= @page_title || 'Default Title' %>

Git: how to reverse-merge a commit?

If you don't want to commit, or want to commit later (commit message will still be prepared for you, which you can also edit):

git revert -n <commit>

How to read and write xml files?

The answers only cover DOM / SAX and a copy paste implementation of a JAXB example.

However, one big area of when you are using XML is missing. In many projects / programs there is a need to store / retrieve some basic data structures. Your program has already a classes for your nice and shiny business objects / data structures, you just want a comfortable way to convert this data to a XML structure so you can do more magic on it (store, load, send, manipulate with XSLT).

This is where XStream shines. You simply annotate the classes holding your data, or if you do not want to change those classes, you configure a XStream instance for marshalling (objects -> xml) or unmarshalling (xml -> objects).

Internally XStream uses reflection, the readObject and readResolve methods of standard Java object serialization.

You get a good and speedy tutorial here:

To give a short overview of how it works, I also provide some sample code which marshalls and unmarshalls a data structure. The marshalling / unmarshalling happens all in the main method, the rest is just code to generate some test objects and populate some data to them. It is super simple to configure the xStream instance and marshalling / unmarshalling is done with one line of code each.

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.thoughtworks.xstream.XStream;

public class XStreamIsGreat {

  public static void main(String[] args) {
    XStream xStream = new XStream();
    xStream.alias("good", Good.class);
    xStream.alias("pRoDuCeR", Producer.class);
    xStream.alias("customer", Customer.class);

    Producer a = new Producer("Apple");
    Producer s = new Producer("Samsung");
    Customer c = new Customer("Someone").add(new Good("S4", 10, new BigDecimal(600), s))
        .add(new Good("S4 mini", 5, new BigDecimal(450), s)).add(new Good("I5S", 3, new BigDecimal(875), a));
    String xml = xStream.toXML(c); // objects -> xml
    System.out.println("Marshalled:\n" + xml);
    Customer unmarshalledCustomer = (Customer)xStream.fromXML(xml); // xml -> objects

  static class Good {
    Producer producer;

    String name;

    int quantity;

    BigDecimal price;

    Good(String name, int quantity, BigDecimal price, Producer p) {
      this.producer = p; = name;
      this.quantity = quantity;
      this.price = price;


  static class Producer {
    String name;

    public Producer(String name) { = name;

  static class Customer {
    String name;

    public Customer(String name) { = name;

    List<Good> stock = new ArrayList<Good>();

    Customer add(Good g) {
      return this;

How to check if the given string is palindrome?

Another one from Delphi, which I think is a little more rigorous than the other Delphi example submitted. This can easily turn into a golfing match, but I've tried to make mine readable.

Edit0: I was curious about the performance characteristics, so I did a little test. On my machine, I ran this function against a 60 character string 50 million times, and it took 5 seconds.

function TForm1.IsPalindrome(txt: string): boolean;
  i, halfway, len : integer;
  Result := True;
  len := Length(txt);

  special cases:
  an empty string is *never* a palindrome
  a 1-character string is *always* a palindrome
  case len of
    0 : Result := False;
    1 : Result := True;
    else begin
      halfway := Round((len/2) - (1/2));  //if odd, round down to get 1/2way pt

      //scan half of our string, make sure it is mirrored on the other half
      for i := 1 to halfway do begin
        if txt[i] <> txt[len-(i-1)] then begin
          Result := False;
        end;  //if we found a non-mirrored character
      end;  //for 1st half of string
    end;  //else not a special case
  end;  //case

And here is the same thing, in C#, except that I've left it with multiple exit points, which I don't like.

private bool IsPalindrome(string txt) {
  int len = txt.Length;

  Special cases:
  An empty string is *never* a palindrome
  A 1-character string is *always* a palindrome
  switch (len) {
    case 0: return false;
    case 1: return true;
  }  //switch
  int halfway = (len / 2);

  //scan half of our string, make sure it is mirrored on the other half
  for (int i = 0; i < halfway; ++i) {
    if (txt.Substring(i,1) != txt.Substring(len - i - 1,1)) {
      return false;
    }  //if
  }  //for
  return true;

Difference between "module.exports" and "exports" in the CommonJs Module System


module.exports.get = function () {};

exports.put = function () {};

// output: { get: [Function], put: [Function] }

exports and module.exports are the same and a reference to the same object. You can add properties by both ways as per your convenience.

How to replace part of string by position?

I believe the simplest way would be this:(without stringbuilder)

string myString = "ABCDEFGHIJ";
char[] replacementChars = {'Z', 'X'};
byte j = 0;

for (byte i = 3; i <= 4; i++, j++)  
myString = myString.Replace(myString[i], replacementChars[j]);  

This works because a variable of type string can be treated as an array of char variables. You can, for example refer to the second character of a string variable with name "myString" as myString[1]

How to uninstall with msiexec using product id guid without .msi file present

The good thing is, this one is really easily and deterministically to analyze: Either, the msi package is really not installed on the system or you're doing something wrong. Of course the correct call is:

msiexec /x {A4BFF20C-A21E-4720-88E5-79D5A5AEB2E8}

(Admin rights needed of course- With curly braces without any quotes here- quotes are only needed, if paths or values with blank are specified in the commandline.)
If the message is: "This action is only valid for products that are currently installed", then this is true. Either the package with this ProductCode is not installed or there is a typo.

To verify where the fault is:

  1. First try to right click on the (probably) installed .msi file itself. You will see (besides "Install" and "Repair") an Uninstall entry. Click on that.
    a) If that uninstall works, your msi has another ProductCode than you expect (maybe you have the wrong WiX source or your build has dynamic logging where the ProductCode changes).
    b) If that uninstall gives the same "...only valid for products already installed" the package is not installed (which is obviously a precondition to be able to uninstall it).

  2. If 1.a) was the case, you can look for the correct ProductCode of your package, if you open your msi file with Orca, Insted or another editor/tool. Just google for them. Look there in the table with the name "Property" and search for the string "ProductCode" in the first column. In the second column there is the correct value.

There are no other possibilities.

Just a suggestion for the used commandline: I would add at least the "/qb" for a simple progress bar or "/qn" parameter (the latter for complete silent uninstall, but makes only sense if you are sure it works).

Is it possible to style a mouseover on an image map using CSS?

With pseudo elements.


<div class="image-map-container">
    <img src="" alt="" usemap="#image-map" />
    <div class="map-selector"></div>

<map name="image-map" id="image-map">
    <area alt="" title="" href="#" shape="rect" coords="54,36,66,49" />
    <area alt="" title="" href="#" shape="rect" coords="72,38,83,48" />
    <area alt="" title="" href="#" shape="rect" coords="56,4,80,28" />
    <area alt="" title="" href="#" shape="rect" coords="7,7,45,46" />
    <area alt="" title="" href="#" shape="rect" coords="10,59,76,125" />
    <area alt="" title="" href="#" shape="rect" coords="93,9,199,122" />

some CSS:

.image-map-container {
    position: relative;
.image-map-container img {
.image-map-container .map-selector {
    transition-duration: .3s;
    transition-timing-function: ease-out;
    transition-property: top, left, right, bottom, color;
.image-map-container .map-selector.hover {

.map-selector:after {
    content: '';
    position: absolute;
    top: inherit;right: inherit;bottom: inherit;left: inherit;
    background: currentColor;
    transition-duration: .3s;
    transition-timing-function: ease-out;
    transition-property: top, left, right, bottom, background;
    pointer-events: none;


$('#image-map area').hover(
    function () { 
        var coords = $(this).attr('coords').split(','),
            width = $('.image-map-container').width(),
            height = $('.image-map-container').height();
        $('.image-map-container .map-selector').addClass('hover').css({
            'left': coords[0]+'px',
            'top': coords[1] + 'px',
            'right': width - coords[2],
            'bottom': height - coords[3]
    function () { 
        $('.image-map-container .map-selector').removeClass('hover').attr('style','');

len() of a numpy array in python

You can transpose the array if you want to get the length of the other dimension.

len(np.array([[2,3,1,0], [2,3,1,0], [3,2,1,1]]).T)

PHP to search within txt file and echo the whole line

Do it like this. This approach lets you search a file of any size (big size won't crash the script) and will return ALL lines that match the string you want.

$searchthis = "mystring";
$matches = array();

$handle = @fopen("path/to/inputfile.txt", "r");
if ($handle)
    while (!feof($handle))
        $buffer = fgets($handle);
        if(strpos($buffer, $searchthis) !== FALSE)
            $matches[] = $buffer;

//show results:

Note the way strpos is used with !== operator.

JavaScript regex for alphanumeric string with length of 3-5 chars

add {3,5} to your expression which means length between 3 to 5


Swift: Display HTML data in a label or textView

Display images and text paragraphs is not possible in a UITextView or UILabel, to this, you must use a UIWebView.

Just add the item in the storyboard, link to your code, and call it to load the URL.


NSString *fullURL = @"";
NSURL *url = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_viewWeb loadRequest:requestObj];


let url = NSURL (string: "");
let requestObj = NSURLRequest(URL: url!);

Step by step tutorial.

How to resolve TypeError: Cannot convert undefined or null to object

Generic answer

This error is caused when you call a function that expects an Object as its argument, but pass undefined or null instead, like for example

Object.assign(window.UndefinedVariable, {})

As that is usually by mistake, the solution is to check your code and fix the null/undefined condition so that the function either gets a proper Object, or does not get called at all.

Object.keys({'key': 'value'})
if (window.UndefinedVariable) {
    Object.assign(window.UndefinedVariable, {})

Answer specific to the code in question

The line if (obj === 'null') { return null;} // null unchanged will not evaluate when given null, only if given the string "null". So if you pass the actual null value to your script, it will be parsed in the Object part of the code. And Object.keys(null) throws the TypeError mentioned. To fix it, use if(obj === null) {return null} - without the qoutes around null.

Fixed page header overlaps in-page anchors

The way that I find being the cleanest is the following one :

  #bar::before {
    display: block;
    content: " ";
    margin-top: -150px;
    height: 150px;
    visibility: hidden;
    pointer-events: none;

Convert string to float?

Use Float.valueOf(String) to do the conversion.

The difference between valueOf() and parseFloat() is only the return. Use the former if you want a Float (object) and the latter if you want the float number.

How to select the first element with a specific attribute using XPath

/bookstore/book[@location='US'][1] works only with simple structure.

Add a bit more structure and things break.


  <book location="US">A1</book>
  <book location="FIN">A2</book>
  <book location="FIN">B1</book>
  <book location="US">B2</book>

/bookstore/category/book[@location='US'][1] yields

<book location="US">A1</book>
<book location="US">B2</book>

not "the first node that matches a more complicated condition". /bookstore/category/book[@location='US'][2] returns nothing.

With parentheses you can get the result the original question was for:

(/bookstore/category/book[@location='US'])[1] gives

<book location="US">A1</book>

and (/bookstore/category/book[@location='US'])[2] works as expected.

Smooth scrolling when clicking an anchor link

Well, the solution depends on the type of problem, I use the javascript animate method for the button click. and I use codes from bellow links for the navbar

$(document).ready(function () {
  $(".js--scroll-to-plans").click(function () {
        scrollTop: $(".js--section-plans").offset().top,
    return false;

  $(".js--scroll-to-start").click(function () {
        scrollTop: $(".js--section-features").offset().top,
    return false;

  // Remove links that don't actually link to anything
  .click(function(event) {
    // On-page links
    if (
      location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 
      location.hostname == this.hostname
    ) {
      // Figure out element to scroll to
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      // Does a scroll target exist?
      if (target.length) {
        // Only prevent default if animation is actually gonna happen
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000, function() {
          // Callback after animation
          // Must change focus!
          var $target = $(target);
          if ($":focus")) { // Checking if the target was focused
            return false;
          } else {
            $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
            $target.focus(); // Set focus again

How do I write a for loop in bash

From this site:

for i in $(seq 1 10);
    echo $i

Time complexity of accessing a Python dict

See Time Complexity. The python dict is a hashmap, its worst case is therefore O(n) if the hash function is bad and results in a lot of collisions. However that is a very rare case where every item added has the same hash and so is added to the same chain which for a major Python implementation would be extremely unlikely. The average time complexity is of course O(1).

The best method would be to check and take a look at the hashs of the objects you are using. The CPython Dict uses int PyObject_Hash (PyObject *o) which is the equivalent of hash(o).

After a quick check, I have not yet managed to find two tuples that hash to the same value, which would indicate that the lookup is O(1)

l = []
for x in range(0, 50):
    for y in range(0, 50):
        if hash((x,y)) in l:
            print "Fail: ", (x,y)
print "Test Finished"

CodePad (Available for 24 hours)

Stopping a JavaScript function when a certain condition is met

The return statement exits a function from anywhere within the function:

function something(x)
    if (x >= 10)
        // this leaves the function if x is at least 10.

    // this message displays only if x is less than 10.
    alert ("x is less than 10!");

php $_POST array empty upon form submission

My problem was that I was using the HTML <base> tag to change the base URL of my test site. Once I removed that tag from the header, the $_POST data came back.

Adding image to JFrame

Here is a simple example of adding an image to a JFrame:

frame.add(new JLabel(new ImageIcon("Path/To/Your/Image.png")));

Angular 5 Button Submit On Enter Key Press

Try to use keyup.enter but make sure to use it inside your input tag

  placeholder="enter key word"

ab load testing

Steps to set up Apache Bench(AB) on windows (IMO - Recommended).

Step 1 - Install Xampp.
Step 2 - Open CMD.
Step 3 - Go to the apache bench destination (cd C:\xampp\apache\bin) from CMD
Step 4 - Paste the command (ab -n 100 -c 10 -k -H "Accept-Encoding: gzip, deflate" http://localhost:yourport/)
Step 5 - Wait for it. Your done

Cannot stop or restart a docker container

in my case, i couldn't delete container created with nomad jobs, there's no output for the docker logs <ContainerID> and, in general, it looks like frozen.

until now the solution is: sudo service docker restart, may someone suggest better one?

How can I see the raw SQL queries Django is running?

For Django 2.2:

As most of the answers did not helped me much when using ./ shell. Finally i found the answer. Hope this helps to someone.

To view all the queries:

from django.db import connection

To view query for a single query:


q.query just displaying the object for me. Using the __str__()(String representation) displayed the full query.

How to generate a random number between 0 and 1?

Set the seed using srand(). Also, you're not specifying the max value in rand(), so it's using RAND_MAX. I'm not sure if it's actually 10000... why not just specify it. Although, we don't know what your "expected results" are. It's a random number generator. What are you expecting, and what are you seeing?

As noted in another comment, SA() isn't returning anything explicitly.

Edit: From Generating random number between [-1, 1] in C? ((float)rand())/RAND_MAX returns a floating-point number in [0,1]

How to get the selected radio button value using js


<input type="radio" id="gender0" name="gender" value="Male">Male<br>
<input type="radio" id="gender1" name="gender" value="Female">Female<br>


var gender = document.querySelector('input[name = "gender"]:checked').value;
document.writeln("You entered " + gender + " for your gender<br>");

.NET code to send ZPL to Zebra printers

VB Version (using port 9100 - tested on Zebra ZM400)

Sub PrintZPL(ByVal pIP As String, ByVal psZPL As String)
    Dim lAddress As Net.IPEndPoint
    Dim lSocket As System.Net.Sockets.Socket = Nothing
    Dim lNetStream As System.Net.Sockets.NetworkStream = Nothing
    Dim lBytes As Byte()

        lAddress = New Net.IPEndPoint(Net.IPAddress.Parse(pIP), 9100)
        lSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, _                       ProtocolType.Tcp)
        lNetStream = New NetworkStream(lSocket)

        lBytes = System.Text.Encoding.ASCII.GetBytes(psZPL)
        lNetStream.Write(lBytes, 0, lBytes.Length)
    Catch ex As Exception When Not App.Debugging
        Msgbox ex.message & vbnewline & ex.tostring
        If Not lNetStream Is Nothing Then
        End If
        If Not lSocket Is Nothing Then
        End If
    End Try
End Sub

Is it good practice to use the xor operator for boolean checks?

!= is OK to compare two variables. It doesn't work, though, with multiple comparisons.

Overcoming "Display forbidden by X-Frame-Options"

The only question that has a bunch of answers. WElcome to the guide i wish i had when i was scrambling for this to make it work at 10:30 at night on the deadline day... FB does some weird things with canvas apps, and well, you've been warned. If youa re still here and you have a Rails app that will appear behind a Facebook Canvas, then you will need:


gem "rack-facebook-signed-request", :git => 'git://'


  key: "123123123123"
  secret: "123123123123123123secret12312"


config.middleware.use Rack::Facebook::SignedRequest, app_id: "123123123123", secret: "123123123123123123secret12312", inject_facebook: false


OmniAuth.config.logger = Rails.logger
SERVICES = YAML.load("#{::Rails.root}/config/oauth.yml").read)
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :facebook, SERVICES['facebook']['key'], SERVICES['facebook']['secret'], iframe:   true


before_filter :add_xframe
def add_xframe
  headers['X-Frame-Options'] = 'GOFORIT'

You need a controller to call from Facebook's canvas settings, i used /canvas/ and made the route go the main SiteController for this app:

class SiteController < ApplicationController
  def index
    @user =
  def canvas
    redirect_to '/auth/failure' if request.params['error'] == 'access_denied'
    url = params['code'] ? "/auth/facebook?signed_request=#{params['signed_request']}&state=canvas" : "/login"
    redirect_to url
  def login


<% content_for :javascript do %>
  var oauth_url = '';
  oauth_url += '?client_id=471466299609256';
  oauth_url += '&redirect_uri=' + encodeURIComponent('');
  oauth_url += '&scope=email,status_update,publish_stream';
  top.location.href = oauth_url;
<% end %>


  • The config i think came from omniauth's example.
  • The gem file (which is key!!!) came from: slideshare things i learned...
  • This stack question had the whole Xframe angle, so you'll get a blank space, if you don't put this header in the app controller.
  • And my man @rafmagana wrote this heroku guide, which now you can adopt for rails with this answer and the shoulders of giants in which you walk with.

Update label from another thread

You cannot update UI from any other thread other than the UI thread. Use this to update thread on the UI thread.

 private void AggiornaContatore()
         this.lblCounter.BeginInvoke((MethodInvoker) delegate() {this.lblCounter.Text = this.index.ToString(); ;});    
         this.lblCounter.Text = this.index.ToString(); ;

Please go through this chapter and more from this book to get a clear picture about threading:

How can I kill a process by name instead of PID?

Strange, but I haven't seen the solution like this:

kill -9 `pidof firefox`

it can also kill multiple processes (multiple pids) like:

kill -9 `pgrep firefox`

I prefer pidof since it has single line output:

> pgrep firefox
> pidof firefox
6565 6316

Can you overload controller methods in ASP.NET MVC?

I needed an overload for:

public ActionResult Index(string i);
public ActionResult Index(int groupId, int itemId);

There were few enough arguments where I ended up doing this:

public ActionResult Index(string i, int? groupId, int? itemId)
    if (!string.IsNullOrWhitespace(i))
        // parse i for the id
    else if (groupId.HasValue && itemId.HasValue)
        // use groupId and itemId for the id

It's not a perfect solution, especially if you have a lot of arguments, but it works well for me.

Best practices for copying files with Maven

I was able to piece together a number of different sources for this answer:

    <name>Atlassian Repo</name>
        <resourceDest>opt/jira/webapps</resourceDest> <!-- note: no leading slash -->

From ~/.m2/settings.xml:


Then run the command: (the -X is for debug)

mvn -X upload:upload

Angular 2 @ViewChild annotation returns undefined

For me using ngAfterViewInit instead of ngOnInit fixed the issue :

export class AppComponent implements OnInit {
  @ViewChild('video') video;
    // <-- in here video is undefined
  public ngAfterViewInit()
    console.log( // <-- you can access it here

Pythonic way to add and datetime.time objects

It's in the python docs.

import datetime
datetime.datetime.combine(, 1, 1), 
                          datetime.time(10, 23))


datetime.datetime(2011, 1, 1, 10, 23)

C# using Sendkey function to send a key to another application

If notepad is already started, you should write:

// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);


Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
    IntPtr h = p.MainWindowHandle;

GetProcessesByName returns an array of processes, so you should get the first one (or find the one you want).

If you want to start notepad and send the key, you should write:

Process p = Process.Start("notepad.exe");
IntPtr h = p.MainWindowHandle;

The only situation in which the code may not work is when notepad is started as Administrator and your application is not.

jQuery: get parent, parent id?


PHP mail not working for some reason

This might be the issue of your SMTP config in your php.ini file.

Since you new to PHP, You can find php.ini file in your root directory of PHP installation folder and check for SMTP = and smtp_port= and change the value to

SMTP = your mail server e.g)
smtp_port = 25(check your admin for original port)

In case your server require authentication for sending mail, use PEAR mail function.

Can't connect to Postgresql on port 5432

I had this same issue. I originally installed version 10 because that was the default install with Ubuntu 18.04. I later upgraded to 13.2 because I wanted the latest version. I made all the config modifications, but it was still just binging to 1207.0.0.1 and then I thought - maybe it is looking at the config files for version 10. I modified those and restarted the postgres service. Bingo! It was binding to

I will need to completely remove 10 and ensure that I am forcing the service to run under version 13.2, so if you upgraded from another version, try updating the other config files in that older directory.

jQuery Mobile: Stick footer to bottom of page

I thought I'd share my CSS only solution here. This way you can avoid the extra overhead of using JS for this.

This isn't a fixed position footer. The footer will be offscreen if the page content is taller than the screen. I think it looks better this way.

The body and .ui-page min-height and height are necessary to prevent the footer from jumping up and down during transitions.

Works with the latest JQM version as of now, 1.4.0

.ui-page {
    min-height:100% !important;
    height:auto !important;

.ui-content {
    margin-bottom:42px; /* HEIGHT OF YOUR FOOTER */

.ui-footer {
    position:absolute !important;

refresh div with jquery

I tried the first solution and it works but the end user can easily identify that the div's are refreshing as it is fadeIn(), without fade in i tried .toggle().toggle() and it works perfect. you can try like this


it works perfectly for me as i'm developing a messenger and need to minimize and maximize the chat box's and this does it best rather than the above code.

Counting number of occurrences in column?

A simpler approach to this

At the beginning of column B, type


Then in column C, use


and copy them in all row column C.

Edit: If that doesn't work for you, try using semicolon instead of comma:


How to run a Command Prompt command with Visual Basic code?

Yes. You can use Process.Start to launch an executable, including a console application.

If you need to read the output from the application, you may need to read from it's StandardOutput stream in order to get anything printed from the application you launch.

Set select option 'selected', by value

For me the following did the job


How to Get a Sublist in C#

Use the Where clause from LINQ:

List<object> x = new List<object>();

var z = x.Where(p => p == "A");
z = x.Where(p => p == "B");

In the statements above "p" is the object that is in the list. So if you used a data object, i.e.:

public class Client
    public string Name { get; set; }

then your linq would look like this:

List<Client> x = new List<Client>();
x.Add(new Client() { Name = "A" });
x.Add(new Client() { Name = "B" });
x.Add(new Client() { Name = "C" });
x.Add(new Client() { Name = "D" });
x.Add(new Client() { Name = "B" });

var z = x.Where(p => p.Name == "A");
z = x.Where(p => p.Name == "B");

Why can I not push_back a unique_ptr into a vector?

std::unique_ptr has no copy constructor. You create an instance and then ask the std::vector to copy that instance during initialisation.

error: deleted function 'std::unique_ptr<_Tp, _Tp_Deleter>::uniqu
e_ptr(const std::unique_ptr<_Tp, _Tp_Deleter>&) [with _Tp = int, _Tp_D
eleter = std::default_delete<int>, std::unique_ptr<_Tp, _Tp_Deleter> =

The class satisfies the requirements of MoveConstructible and MoveAssignable, but not the requirements of either CopyConstructible or CopyAssignable.

The following works with the new emplace calls.

std::vector< std::unique_ptr< int > > vec;
vec.emplace_back( new int( 1984 ) );

See using unique_ptr with standard library containers for further reading.

What is the Angular equivalent to an AngularJS $watch?

You can use getter function or get accessor to act as watch on angular 2.

See demo here.

import {Component} from 'angular2/core';

  // Declare the tag name in index.html to where the component attaches
  selector: 'hello-world',

  // Location of the template for this component
  template: `
  <button (click)="OnPushArray1()">Push 1</button>
    I'm array 1 {{ array1 | json }}
  <button (click)="OnPushArray2()">Push 2</button>
    I'm array 2 {{ array2 | json }}
  I'm concatenated {{ concatenatedArray | json }}
    I'm length of two arrays {{ arrayLength | json }}
export class HelloWorld {
    array1: any[] = [];
    array2: any[] = [];

    get concatenatedArray(): any[] {
      return this.array1.concat(this.array2);

    get arrayLength(): number {
      return this.concatenatedArray.length;

    OnPushArray1() {

    OnPushArray2() {

WebSocket with SSL

1 additional caveat (besides the answer by kanaka/peter): if you use WSS, and the server certificate is not acceptable to the browser, you may not get any browser rendered dialog (like it happens for Web pages). This is because WebSockets is treated as a so-called "subresource", and certificate accept / security exception / whatever dialogs are not rendered for subresources.

Test only if variable is not null in if statement

I don't believe the expression is sensical as it is.

Elvis means "if truthy, use the value, else use this other thing."

Your "other thing" is a closure, and the value is status != null, neither of which would seem to be what you want. If status is null, Elvis says true. If it's not, you get an extra layer of closure.

Why can't you just use:

(it.description == desc) && ((status == null) || (it.status == status))

Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find calls, just use an intermediate variable.

How do I alter the precision of a decimal column in Sql Server?

ALTER TABLE `tableName` CHANGE  `columnName` DECIMAL(16,1) NOT NULL;

I uses This for the alterration

Android textview outline text

Here's the trick I found that works better than MagicTextView's stroke IMO

protected void onDraw(Canvas pCanvas) {
    int textColor = getTextColors().getDefaultColor();
    setTextColor(mOutlineColor); // your stroke's color

Count number of times a date occurs and make a graph out of it

If you have Excel 2010 you can copy your data into another column, than select it and choose Data -> Remove Duplicates. You can then write =COUNTIF($A$1:$A$100,B1) next to it and copy the formula down. This assumes you have your values in range A1:A100 and the de-duplicated values are in column B.

Write objects into file with Node.js

If you're geting [object object] then use JSON.stringify

fs.writeFile('./data.json', JSON.stringify(obj) , 'utf-8');

It worked for me.

Make REST API call in Swift

Here is the complete code for REST API requests using NSURLSession in swift

For GET Request

 let configuration = NSURLSessionConfiguration .defaultSessionConfiguration()
    let session = NSURLSession(configuration: configuration)

    let urlString = NSString(format: "your URL here")

    print("get wallet balance url string is \(urlString)")
    //let url = NSURL(string: urlString as String)
    let request : NSMutableURLRequest = NSMutableURLRequest()
    request.URL = NSURL(string: NSString(format: "%@", urlString) as String)
    request.HTTPMethod = "GET"
    request.timeoutInterval = 30

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let dataTask = session.dataTaskWithRequest(request) {
        (let data: NSData?, let response: NSURLResponse?, let error: NSError?) -> Void in

        // 1: Check HTTP Response for successful GET request
        guard let httpResponse = response as? NSHTTPURLResponse, receivedData = data
            else {
                print("error: not a valid http response")

        switch (httpResponse.statusCode)
        case 200:

            let response = NSString (data: receivedData, encoding: NSUTF8StringEncoding)
            print("response is \(response)")

            do {
                let getResponse = try NSJSONSerialization.JSONObjectWithData(receivedData, options: .AllowFragments)

                EZLoadingActivity .hide()

               // }
            } catch {
                print("error serializing JSON: \(error)")

        case 400:

            print("wallet GET request got response \(httpResponse.statusCode)")

For POST request ...

let configuration = NSURLSessionConfiguration .defaultSessionConfiguration()
    let session = NSURLSession(configuration: configuration)

    let params = ["username":bindings .objectForKey("username"), "provider":"walkingcoin", "securityQuestion":securityQuestionField.text!, "securityAnswer":securityAnswerField.text!] as Dictionary<String, AnyObject>

    let urlString = NSString(format: “your URL”);
    print("url string is \(urlString)")
    let request : NSMutableURLRequest = NSMutableURLRequest()
    request.URL = NSURL(string: NSString(format: "%@", urlString)as String)
    request.HTTPMethod = "POST"
    request.timeoutInterval = 30
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")      
    request.HTTPBody  = try! NSJSONSerialization.dataWithJSONObject(params, options: [])

    let dataTask = session.dataTaskWithRequest(request)
            (let data: NSData?, let response: NSURLResponse?, let error: NSError?) -> Void in
            // 1: Check HTTP Response for successful GET request
            guard let httpResponse = response as? NSHTTPURLResponse, receivedData = data
                else {
                    print("error: not a valid http response")

            switch (httpResponse.statusCode)
            case 200:

                let response = NSString (data: receivedData, encoding: NSUTF8StringEncoding)

                if response == "SUCCESS"


                print("save profile POST request got response \(httpResponse.statusCode)")

I hope it works.

Error in <my code> : object of type 'closure' is not subsettable

I had this issue was trying to remove a ui element inside an event reactive:

myReactives <- eventReactive(input$execute, {
    ... # Some other long running function here
    removeUI(selector = "#placeholder2")

I was getting this error, but not on the removeUI element line, it was in the next observer after for some reason. Taking the removeUI method out of the eventReactive and placing it somewhere else removed this error for me.

How do I read the source code of shell commands?

ls is part of coreutils. You can get it with git :

git clone git://

You'll find coreutils listed with other packages (scroll to bottom) on this page.

Simple argparse example wanted: 1 argument, 3 results

You could also use plac (a wrapper around argparse).

As a bonus it generates neat help instructions - see below.

Example script:

#!/usr/bin/env python3
def main(
    arg: ('Argument with two possible values', 'positional', None, None, ['A', 'B'])
    """General help for application"""
    if arg == 'A':
        print("Argument has value A")
    elif arg == 'B':
        print("Argument has value B")

if __name__ == '__main__':
    import plac

Example output:

No arguments supplied -

usage: [-h] {A,B} error: the following arguments are required: arg

Unexpected argument supplied - C:

usage: [-h] {A,B} error: argument arg: invalid choice: 'C' (choose from 'A', 'B')

Correct argument supplied - A :

Argument has value A

Full help menu (generated automatically) - -h:

usage: [-h] {A,B}

General help for application

positional arguments:
  {A,B}       Argument with two possible values

optional arguments:
  -h, --help  show this help message and exit

Short explanation:

The name of the argument usually equals the parameter name (arg).

The tuple annotation after arg parameter has the following meaning:

  • Description (Argument with two possible values)
  • Type of argument - one of 'flag', 'option' or 'positional' (positional)
  • Abbreviation (None)
  • Type of argument value - eg. float, string (None)
  • Restricted set of choices (['A', 'B'])


To learn more about using plac check out its great documentation:

Plac: Parsing the Command Line the Easy Way

How to get row number in dataframe in Pandas?

count_smiths = (df['LastName'] == 'Smith').sum()

Ball to Ball Collision - Detection and Handling

Well, years ago I made the program like you presented here.
There is one hidden problem (or many, depends on point of view):

  • If the speed of the ball is too high, you can miss the collision.

And also, almost in 100% cases your new speeds will be wrong. Well, not speeds, but positions. You have to calculate new speeds precisely in the correct place. Otherwise you just shift balls on some small "error" amount, which is available from the previous discrete step.

The solution is obvious: you have to split the timestep so, that first you shift to correct place, then collide, then shift for the rest of the time you have.

Bootstrap Element 100% Width


  1. Use multiple NOT NESTED .containers
  2. Wrap those .containers you want to have a full-width background in a div
  3. Add a CSS background to the wrapping div

Fiddles: Simple: , Container borders:

<div class="container">
  <h2>Section 1</h2>
<div class="specialBackground">
  <div class="container">
    <h2>Section 2</h2>

CSS: .specialBackground{ background-color: gold; /*replace with own background settings*/ }



Many people will (wrongly) suggest, that you should use nested containers.
Well, you should NOT.
They are not ment to be nested. (See to "Containers" section in the docs)


div is a block element, which by default spans to the full width of a document body - there is the full-width feature. It also has a height of it's content (if you don't specify otherwise).

The bootstrap containers are not required to be direct children of a body, they are just containers with some padding and possibly some screen-width-variable fixed widths.

If a basic grid .container has some fixed width it is also auto-centered horizontally.
So there is no difference whether you put it as a:

  1. Direct child of a body
  2. Direct child of a basic div that is a direct child of a body.

By "basic" div I mean div that does not have a CSS altering his border, padding, dimensions, position or content size. Really just a HTML element with display: block; CSS and possibly background.
But of course setting vertical-like CSS (height, padding-top, ...) should not break the bootstrap grid :-)

Bootstrap itself is using the same approach

...All over it's own website and in it's "JUMBOTRON" example:

How to mount host volumes into docker containers in Dockerfile during build

I think you can do what you want to do by running the build via a docker command which itself is run inside a docker container. See Docker can now run within Docker | Docker Blog. A technique like this, but which actually accessed the outer docker from with a container, was used, e.g., while exploring how to Create the smallest possible Docker container | Xebia Blog.

Another relevant article is Optimizing Docker Images | CenturyLink Labs, which explains that if you do end up downloading stuff during a build, you can avoid having space wasted by it in the final image by downloading, building and deleting the download all in one RUN step.

How to get first N number of elements from an array

Do not try doing that using a map function. Map function should be used to map values from one thing to other. When the number of input and output match.

In this case use filter function which is also available on the array. Filter function is used when you want to selectively take values maching certain criteria. Then you can write your code like

var items = list
             .filter((i, index) => (index < 3))
             .map((i, index) => {
                   return (
                     <myview item={i} key={} />

Convert iterator to pointer?

If you can, a better choice may be to change the function to take either an iterator to an element or a brand new vector (if it does not modify).

While you can do this sort of things with arrays since you know how they are stored, it's probably a bad idea to do the same with vectors. &foo[1] does not have the type vector<int>*.

Also, while the STL implementation is available online, it's usually risky to try and rely on the internal structure of an abstraction.

Inserting into Oracle and retrieving the generated sequence ID

You can do this with a single statement - assuming you are calling it from a JDBC-like connector with in/out parameters functionality:

insert into batch(batchid, batchname) 
values (batch_seq.nextval, 'new batch')
returning batchid into :l_batchid;

or, as a pl-sql script:

variable l_batchid number;

insert into batch(batchid, batchname) 
values (batch_seq.nextval, 'new batch')
returning batchid into :l_batchid;

select :l_batchid from dual;

Determining whether an object is a member of a collection in VBA

I wrote this code. I guess it can help someone...

Public Function VerifyCollection()
    For i = 1 To 10 Step 1
       MyKey = "A"
       On Error GoTo KillError:
       Dispersao.Add 1, MyKey
       GoTo KeepInForLoop
KillError: 'If My collection already has the key A Then...
        count = Dispersao(MyKey)
        Dispersao.Remove (MyKey)
        Dispersao.Add count + 1, MyKey 'Increase the amount in relationship with my Key
        count = Dispersao(MyKey) 'count = new amount
        On Error GoTo -1
End Function

Trouble setting up git with my GitHub Account error: could not lock config file

You can also try issuing the command while in your home directory.

How to position absolute inside a div?

  1. First all block level elements are postioned static to the 'document'. The default positioning for all elements is position: static, which means the element is not positioned and occurs where it normally would in the document. Normally you wouldn't specify this unless you needed to override a positioning that had been previously set.
  2. Relative position: If you specify position: relative, then you can use top or bottom, and left or right to move the element relative to where it would normally occur in the document.
  3. When you specify position: absolute, the element is removed from the document and placed exactly where you tell it to go.

So in regard to your question you should position the containing block relative, i.e:

#parent {
  position: relative;

And the child element you should position absolute to the parent element like this:

#child {
  position: absolute;

See: Learn CSS Positioning in Ten Steps

Explaining Apache ZooKeeper

I would suggest the following resources:

  1. The paper:
  2. The lecture offered by MIT 6.824 from 36:00:

I would suggest watching the video, read the paper, and then watch the video again. It would be easier to understand if you know Raft beforehand.

Android: How to detect double-tap?

While I liked the simplicity of the approach in the original answer

Here is my version

public abstract class OnDoubleClickListener implements View.OnClickListener {

    private static final int TIME_OUT = ViewConfiguration.getDoubleTapTimeout();
    private TapHandler tapHandler = new TapHandler();

    public abstract void onSingleClick(View v);
    public abstract void onDoubleClick(View v);

    public void onClick(View v) {
        if (tapHandler.isDoubleTap()){
        } else {

    private class TapHandler implements Runnable {
        public boolean isDoubleTap() {
            final long tapTime = System.currentTimeMillis();
            boolean doubleTap = tapTime - lastTapTime < TIME_OUT;
            lastTapTime = tapTime;
            return doubleTap;
        public void performSingleTap(View v) {
            view = v;
            v.postDelayed(this, TIME_OUT);
        public void cancelSingleTap(View v) {
            view = null;

        public void run() {
            if (view != null) {
        private View view;
        private long lastTapTime = 0;

Usage is same as the original

view.setOnClickListener(new OnDoubleClickListener() {

    public void onSingleClick(View v) {


    public void onDoubleClick(View v) {


Get current cursor position

You get the cursor position by calling GetCursorPos.

if (GetCursorPos(&p))
    //cursor position now in p.x and p.y

This returns the cursor position relative to screen coordinates. Call ScreenToClient to map to window coordinates.

if (ScreenToClient(hwnd, &p))
    //p.x and p.y are now relative to hwnd's client area

You hide and show the cursor with ShowCursor.

ShowCursor(FALSE);//hides the cursor
ShowCursor(TRUE);//shows it again

You must ensure that every call to hide the cursor is matched by one that shows it again.

How to get all child inputs of a div element (jQuery)

var i = $("#panel input");

should work :-)

the > will only fetch direct children, no children's children
the : is for using pseudo-classes, eg. :hover, etc.

you can read about available css-selectors of pseudo-classes here:

Force GUI update from UI Thread

you can try this

using System.Windows.Forms; // u need this to include.

MethodInvoker updateIt = delegate
                    this.label1.Text = "Started...";

See if it works.

C split a char array into different variables

This is how I do it.

void SplitBufferToArray(char *buffer, char * delim, char ** Output) {

    int partcount = 0;
    Output[partcount++] = buffer;

    char* ptr = buffer;
    while (ptr != 0) { //check if the string is over
        ptr = strstr(ptr, delim);
        if (ptr != NULL) {
            *ptr = 0;
            Output[partcount++] = ptr + strlen(delim);
            ptr = ptr + strlen(delim);

    Output[partcount++] = NULL;

How to get selenium to wait for ajax response?

This work for me

public  void waitForAjax(WebDriver driver) {
    new WebDriverWait(driver, 180).until(new ExpectedCondition<Boolean>(){
        public Boolean apply(WebDriver driver) {
            JavascriptExecutor js = (JavascriptExecutor) driver;
            return (Boolean) js.executeScript("return == 0");

How do I import a specific version of a package using go get?

Go 1.11 will have a feature called go modules and you can simply add a dependency with a version. Follow these steps:

go mod init .
go mod edit -require[email protected]
go get -v -t ./...   
go build
go install 

Here's more info on that topic -

varbinary to string on SQL Server

Try this

SELECT CONVERT(varchar(5000), yourvarbincolumn, 0)

How to add google-play-services.jar project dependency so my project will run and present map

Be Careful, Follow these steps and save your time

  1. Right Click on your Project Explorer.

  2. Select New-> Project -> Android Application Project from Existing Code

  3. Browse upto this path only - "C:\Users**your path**\Local\Android\android-sdk\extras\google\google_play_services"

  4. Be careful brose only upto - google_play_services and not upto google_play_services_lib

  5. And this way you are able to import the google play service lib.

Let me know if you have any queries regarding the same.


Best way to encode text data for XML in Java?

Just replace

 & with &amp;

And for other characters:

> with &gt;
< with &lt;
\" with &quot;
' with &apos;

How do I Convert to UTC in Ruby?

Unfortunately, the DateTime class doesn't have the convenience methods available in the Time class to do this. You can convert any DateTime object into UTC like this:

d =
d.new_offset(Rational(0, 24))

You can switch back from UTC to localtime using:


where d is a DateTime object in UTC time. If you'd like these as convenience methods, then you can create them like this:

class DateTime
  def localtime

  def utc
    new_offset(Rational(0, 24))

You can see this in action in the following irb session:

d =, 24))
 => #<DateTime: 106105391484260677/43200000000,-1/6,2299161> 
1.8.7 :185 > d.to_s
 => "2012-08-03T15:42:48-04:00" 
1.8.7 :186 > d.localtime.to_s
 => "2012-08-03T12:42:48-07:00" 
1.8.7 :187 > d.utc.to_s
 => "2012-08-03T19:42:48+00:00" 

As you can see above, the initial DateTime object has a -04:00 offset (Eastern Time). I'm in Pacific Time with a -07:00 offset. Calling localtime as described previously properly converts the DateTime object into local time. Calling utc on the object properly converts it to a UTC offset.

Why is there no xrange function in Python3?

Python3's range is Python2's xrange. There's no need to wrap an iter around it. To get an actual list in Python3, you need to use list(range(...))

If you want something that works with Python2 and Python3, try this

except NameError:
    xrange = range

Encode URL in JavaScript?

Encode URL String

    var url = $(location).attr('href'); //get current url
    var url = 'folder/index.html?param=#23dd&noob=yes'; //or specify one

var encodedUrl = encodeURIComponent(url); console.log(encodedUrl); //outputs folder%2Findex.html%3Fparam%3D%2323dd%26noob%3Dyes for more info go

Best way to get user GPS location in background in Android

--Kotlin Version


import android.content.Context
import android.content.Intent
import android.location.Location
import android.location.LocationManager
import android.os.Bundle
import android.os.IBinder
import android.util.Log

 class LocationService : Service() {
    private var mLocationManager: LocationManager? = null

    var mLocationListeners = arrayOf(LocationListener(LocationManager.GPS_PROVIDER), LocationListener(LocationManager.NETWORK_PROVIDER))

     class LocationListener(provider: String) : android.location.LocationListener {
        internal var mLastLocation: Location

        init {
            Log.e(TAG, "LocationListener $provider")
            mLastLocation = Location(provider)

        override fun onLocationChanged(location: Location) {
            Log.e(TAG, "onLocationChanged: $location")
            Log.v("LastLocation", mLastLocation.latitude.toString() +"  " + mLastLocation.longitude.toString())

        override fun onProviderDisabled(provider: String) {
            Log.e(TAG, "onProviderDisabled: $provider")

        override fun onProviderEnabled(provider: String) {
            Log.e(TAG, "onProviderEnabled: $provider")

        override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {
            Log.e(TAG, "onStatusChanged: $provider")

    override fun onBind(arg0: Intent): IBinder? {
        return null

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.e(TAG, "onStartCommand")
        super.onStartCommand(intent, flags, startId)
        return Service.START_STICKY

    override fun onCreate() {
        Log.e(TAG, "onCreate")
        try {
                    LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL.toLong(), LOCATION_DISTANCE,
        } catch (ex: java.lang.SecurityException) {
            Log.i(TAG, "fail to request location update, ignore", ex)
        } catch (ex: IllegalArgumentException) {
            Log.d(TAG, "network provider does not exist, " + ex.message)

        try {
                    LocationManager.GPS_PROVIDER, LOCATION_INTERVAL.toLong(), LOCATION_DISTANCE,
        } catch (ex: java.lang.SecurityException) {
            Log.i(TAG, "fail to request location update, ignore", ex)
        } catch (ex: IllegalArgumentException) {
            Log.d(TAG, "gps provider does not exist " + ex.message)


    override fun onDestroy() {
        Log.e(TAG, "onDestroy")
        if (mLocationManager != null) {
            for (i in mLocationListeners.indices) {
                try {
                } catch (ex: Exception) {
                    Log.i(TAG, "fail to remove location listners, ignore", ex)


    private fun initializeLocationManager() {
        Log.e(TAG, "initializeLocationManager")
        if (mLocationManager == null) {
            mLocationManager = applicationContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager

    companion object {
        private val TAG = "BOOMBOOMTESTGPS"
        private val LOCATION_INTERVAL = 1000
        private val LOCATION_DISTANCE = 0f

How to stop IIS asking authentication for default website on localhost

  1. Add Admin user with password
  2. Go to wwwroot props
  3. Give this user a full access to this folder and its children
  4. Change the user of the AppPool to the added user using this article
  5. Change the User of the website using this article Put the same username and password you have created at step (1).

It is working now congrats

How do I get the path of the Python script I am running in?

import os
print os.path.abspath(__file__)

What is InputStream & Output Stream? Why and when do we use them?

Stream: In laymen terms stream is data , most generic stream is binary representation of data.

Input Stream : If you are reading data from a file or any other source , stream used is input stream. In a simpler terms input stream acts as a channel to read data.

Output Stream : If you want to read and process data from a source (file etc) you first need to save the data , the mean to store data is output stream .

Remap values in pandas column with a dict

DSM has the accepted answer, but the coding doesn't seem to work for everyone. Here is one that works with the current version of pandas (0.23.4 as of 8/2018):

import pandas as pd

df = pd.DataFrame({'col1': [1, 2, 2, 3, 1],
            'col2': ['negative', 'positive', 'neutral', 'neutral', 'positive']})

conversion_dict = {'negative': -1, 'neutral': 0, 'positive': 1}
df['converted_column'] = df['col2'].replace(conversion_dict)


You'll see it looks like:

   col1      col2  converted_column
0     1  negative                -1
1     2  positive                 1
2     2   neutral                 0
3     3   neutral                 0
4     1  positive                 1

The docs for pandas.DataFrame.replace are here.

Manually type in a value in a "Select" / Drop-down HTML list?

ExtJS has a ComboBox control that can do this (and a whole host of other cool stuff!!)

EDIT: Browse all controls etc, here:

Use Awk to extract substring

Or just use cut:

echo aaa0.bbb.ccc | cut -d'.' -f1

Define global constants

The best way to create application wide constants in Angular 2 is by using environment.ts files. The advantage of declaring such constants is that you can vary them according to the environment as there can be a different environment file for each environment.

Javascript array value is undefined ... how do I test for that

try: typeof(predQuery[preId])=='undefined'
or more generally: typeof(yourArray[yourIndex])=='undefined'
You're comparing "undefined" to undefined, which returns false =)

How does an SSL certificate chain bundle work?

The original order is in fact backwards. Certs should be followed by the issuing cert until the last cert is issued by a known root per IETF's RFC 5246 Section 7.4.2

This is a sequence (chain) of certificates. The sender's certificate MUST come first in the list. Each following certificate MUST directly certify the one preceding it.

See also SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch for troubleshooting techniques.

But I still don't know why they wrote the spec so that the order matters.

Python Pandas merge only certain columns

You could merge the sub-DataFrame (with just those columns):

df2[list('xab')]  # df2 but only with columns x, a, and b


android image button

You can use the button :

1 - make the text empty

2 - set the background for it

+3 - you can use the selector to more useful and nice button

About the imagebutton you can set the image source and the background the same picture and it must be (*.png) when you do it you can make any design for the button

and for more beauty button use the selector //just Google it ;)

How to get equal width of input and select fields

Updated answer

Here is how to change the box model used by the input/textarea/select elements so that they all behave the same way. You need to use the box-sizing property which is implemented with a prefix for each browser


This means that the 2px difference we mentioned earlier does not exist..

example at

note: On IE it works from version 8 and upwards..


if you reset their borders then the select element will always be 2 pixels less than the input elements..


How to change the type of a field?

To convert int32 to string in mongo without creating an array just add "" to your number :-) { 'mynum' : { $type : 16 } } ).forEach( function (x) {   
  x.mynum = x.mynum + ""; // convert int32 to string;

How to sort rows of HTML table that are called from MySQL

//this is a php file

a:link {color:green;}
a:visited {color:purple;}
A:active {color: red;}
A:hover {color: red;}
    border:1px solid black;
<script type="text/javascript">
function working(str)
if (str=="")
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
<body bgcolor="pink">
<form method="post">
<select name="sortitems" onchange="working(this.value)">
<option value="">Select</option>
<option value="Id">Id</option>
<option value="Name">Name</option>
<option value="Email">Email</option>
<option value="Password">Password</option>
$sql=mysql_query("select * from mine");
echo "<center><br><br><br><br><table id='tump' border='1'>
echo "<tr>";
while ($row=mysql_fetch_array($sql))
<td><?php echo "$row[Id]";?></td>
<td><?php echo "$row[Name]";?></td>
<td><?php echo "$row[Email]";?></td>
<td><?php echo "$row[Password]";?></td>
<?php echo "</tr>";
echo "</table></center>";?>
<div id="tump"></div>
that is another php file

<body bgcolor="pink">
a:link {color:green;}
a:visited {color:purple;}
A:active {color: red;}
A:hover {color: red;}
    border:1px solid black;
$sql=mysql_query("select * from mine order by $q");
echo "<table id='tump' border='1'>
echo "<tr>";
while ($row=mysql_fetch_array($sql))
<td><?php echo "$row[Id]";?></td>
<td><?php echo "$row[Name]";?></td>
<td><?php echo "$row[Email]";?></td>
<td><?php echo "$row[Password]";?></td>
<?php echo "</tr>";
echo "</table>";?>

that will sort the table using ajax

Import PEM into Java Key Store

I'm always forgetting how to do this because it's something that I just do once in a while, this is one possible solution, and it just works:

  1. Go to your favourite browser and download the main certificate from the secured website.
  2. Execute the two following lines of code:

    $ openssl x509 -outform der -in GlobalSignRootCA.crt -out GlobalSignRootCA.der
    $ keytool -import -alias GlobalSignRootCA -keystore GlobalSignRootCA.jks -file GlobalSignRootCA.der
  3. If executing in Java SE environment add the following options:

    $ java -jar MyJar.jar
  4. Or add the following to the java code:

    System.setProperty("", "GlobalSignRootCA.jks");

The other option for step 2 is to just using the keytool command. Bellow is an example with a chain of certificates:

$ keytool -import -file -alias orgcrt -keystore globalsignrs.jks
$ keytool -import -file GlobalSignOrganizationValidationCA-SHA256-G2.crt -alias globalsignorgvalca -keystore globalsignrs.jks
$ keytool -import -file GlobalSignRootCA.crt -alias globalsignrootca -keystore globalsignrs.jks

How to find Port number of IP address?

The port is usually fixed, for DNS it's 53.

How to use JavaScript source maps (.map files)?

The .map files are for js and css (and now ts too) files that have been minified. They are called SourceMaps. When you minify a file, like the angular.js file, it takes thousands of lines of pretty code and turns it into only a few lines of ugly code. Hopefully, when you are shipping your code to production, you are using the minified code instead of the full, unminified version. When your app is in production, and has an error, the sourcemap will help take your ugly file, and will allow you to see the original version of the code. If you didn't have the sourcemap, then any error would seem cryptic at best.

Same for CSS files. Once you take a SASS or LESS file and compile it to CSS, it looks nothing like its original form. If you enable sourcemaps, then you can see the original state of the file, instead of the modified state.

So, to answer you questions in order:

  • What is it for? To de-reference uglified code
  • How can a developer use it? You use it for debugging a production app. In development mode you can use the full version of Angular. In production, you would use the minified version.
  • Should I care about creating a file? If you care about being able to debug production code easier, then yes, you should do it.
  • How does it get created? It is created at build time. There are build tools that can build your .map file for you as it does other files.

I hope this makes sense.

Remove all child nodes from a parent?

A other users suggested,


is good enought, because it removes all descendant nodes (both tag-nodes and text-nodes) AND all kind of data stored inside those nodes. See the JQuery's API empty documentation.

If you wish to keep data, like event handlers for example, you should use


as described on the JQuery's API detach documentation.

The method .remove() could be usefull for similar purposes.

Unable to start Genymotion Virtual Device - Virtualbox Host Only Ethernet Adapter Failed to start

Select yourVM -> Settings -> Network -> Disable the Network Adapter (It will be re-configured by Genymotion)

Start the Android Image again in Genymotion UI (not in Virtualbox), It should work now!

Pattern matching using a wildcard

If you really do want to use wildcards to identify specific variables, then you can use a combination of ls() and grep() as follows:

l = ls()
vars.with.result <- l[grep("result", l)]

Confirm button before running deleting routine from website

Call this function onclick of button

/*pass whatever you want instead of id */
function doConfirm(id) {
    var ok = confirm("Are you sure to Delete?");
    if (ok) {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                window.location = "create_dealer.php";
        }"GET", "delete_dealer.php?id=" + id);
        // file name where delete code is written

Delimiter must not be alphanumeric or backslash and preg_match

You need a delimiter for your pattern. It should be added at the start and end of the pattern like so:

$pattern = "/My name is '(.*)' and im fine/";  // With / as a delimeter 

POST an array from an HTML form without javascript

check this one out.

<input type="text" name="firstname">
<input type="text" name="lastname">
<input type="text" name="email">
<input type="text" name="address">

<input type="text" name="tree[tree1][fruit]">
<input type="text" name="tree[tree1][height]">

<input type="text" name="tree[tree2][fruit]">
<input type="text" name="tree[tree2][height]">

<input type="text" name="tree[tree3][fruit]">
<input type="text" name="tree[tree3][height]">

it should end up like this in the $_POST[] array (PHP format for easy visualization)

$_POST[] = array(
    'tree' => array(

Transition of background-color

Another way of accomplishing this is using animation which provides more control.

#content #nav a {
    background-color: #FF0;
    /* only animation-duration here is required, rest are optional (also animation-name but it will be set on hover)*/
    animation-duration: 1s; /* same as transition duration */
    animation-timing-function: linear; /* kind of same as transition timing */
    animation-delay: 0ms; /* same as transition delay */
    animation-iteration-count: 1; /* set to 2 to make it run twice, or Infinite to run forever!*/
    animation-direction: normal; /* can be set to "alternate" to run animation, then run it backwards.*/
    animation-fill-mode: none; /* can be used to retain keyframe styling after animation, with "forwards" */
    animation-play-state: running; /* can be set dynamically to pause mid animation*/
    /* declaring the states of the animation to transition through */
    /* optionally add other properties that will change here, or new states (50% etc) */
    @keyframes onHoverAnimation {
    0% {
      background-color: #FF0;  
    100% {
      background-color: #AD310B;

#content #nav a:hover {
    /* animation wont run unless the element is given the name of the animation. This is set on hover */
    animation-name: onHoverAnimation;

How to download file from database/folder using php


$file = "Bang.png"; //Let say If I put the file name Bang.png

Try this,



function download($name){
$file = $nama_fail;

Cannot import the keyfile 'blah.pfx' - error 'The keyfile may be password protected'

I got the same error. In my case, I tried all of the above, but I couldn't get the result.

I finally realized that in my case, the reason for the error was that the certificate password was not entered or entered incorrectly. The error disappeared when I entered the password dynamically correctly. successful

Error: getaddrinfo ENOTFOUND in nodejs for get call

getaddrinfo ENOTFOUND means client was not able to connect to given address. Please try specifying host without http:

var optionsget = {
    host : 'localhost',
    port : 3010,
    path : '/quote/random', // the rest of the url with parameters if needed
    method : 'GET' // do GET

Regarding learning resources, you won't go wrong if you start with and then go through some good book to get more in-depth knowledge - I recommend Professional Node.js , but there's many out there.

Firefox "ssl_error_no_cypher_overlap" error

Under advanced settings of firefox you should be able to set the encryption. By default SSL3.0 and TLS1.0 should be checked, so if firefox is trying to create ssl 3.0 connectons try unchecking the ssl 3.0s setting.

if that doesn't work, try searching the about:config page for "ssl2" My Firefox has settings with ssl2 set to false by default...

Bootstrap 3: Keep selected tab on page refresh

We used jquery trigger to onload have a script hit the button for us


if var == False

Since Python evaluates also the data type NoneType as False during the check, a more precise answer is:

var = False
if var is False:
    print('learnt stuff')

This prevents potentially unwanted behaviour such as:

var = []  # or None
if not var:
    print('learnt stuff') # is printed what may or may not be wanted

But if you want to check all cases where var will be evaluated to False, then doing it by using logical not keyword is the right thing to do.

How to inspect Javascript Objects

Use your console:


Or if you are inspecting html dom elements use console.dir(object). Example:

let element = document.getElementById('alertBoxContainer');

Or if you have an array of js objects you could use:


If you are outputting a lot of console.log(objects) you can also write

console.log({ objectName1 });
console.log({ objectName2 });

This will help you label the objects written to console.

C dynamically growing array

When you're saying

make an array holding an index number (int) of an indeterminate number of entities

you're basically saying you're using "pointers", but one which is a array-wide local pointer instead of memory-wide pointer. Since you're conceptually already using "pointers" (i.e. id numbers that refers to an element in an array), why don't you just use regular pointers (i.e. id numbers that refers to an element in the biggest array: the whole memory).

Instead of your objects storing a resource id numbers, you can make them store a pointer instead. Basically the same thing, but much more efficient since we avoid turning "array + index" into a "pointer".

Pointers are not scary if you think of them as array index for the whole memory (which is what they actually are)

Some dates recognized as dates, some dates not recognized. Why?

Here is what worked for me on a mm/dd/yyyy format:


Convert the cell with the formula to date format and drag the formula down.

Alter column, add default constraint

you can wrap reserved words in square brackets to avoid these kinds of errors:


How do I get the Session Object in Spring?

Your friend here is org.springframework.web.context.request.RequestContextHolder

// example usage
public static HttpSession session() {
    ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    return attr.getRequest().getSession(true); // true == allow create

This will be populated by the standard spring mvc dispatch servlet, but if you are using a different web framework you have add org.springframework.web.filter.RequestContextFilter as a filter in your web.xml to manage the holder.

EDIT: just as a side issue what are you actually trying to do, I'm not sure you should need access to the HttpSession in the retieveUser method of a UserDetailsService. Spring security will put the UserDetails object in the session for you any how. It can be retrieved by accessing the SecurityContextHolder:

public static UserDetails currentUserDetails(){
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    if (authentication != null) {
        Object principal = authentication.getPrincipal();
        return principal instanceof UserDetails ? (UserDetails) principal : null;
    return null;

How to Initialize char array from a string

Perhaps your character array needs to be constant. Since you're initializing your array with characters from a constant string, your array needs to be constant. Try this:

#define S "ABCD"
const char a[] = { S[0], S[1], S[2], S[3] };

Interpreting "condition has length > 1" warning from `if` function

The way I cam across this question was when I tried doing something similar where I was defining a function and it was being called with the array like others pointed out

You could do something like this however for this scenarios its less elegant compared to Sven's method.

sapply(a, function(x) afunc(x))

  if (a>0){
  else 1

Where does npm install packages?

Windows 10: When I ran npm prefix -g, I noticed that the install location was inside of the git shell's path that I used to install. Even when that location was added to the path, the command from the globally installed package would not be recognized. Fixed by:

  1. running npm config edit
  2. changing the prefix to 'C:\Users\username\AppData\Roaming\npm'
  3. adding that path to the system path variable
  4. reinstalling the package with -g.

How to select first parent DIV using jQuery?

This gets parent if it is a div. Then it gets class.

var div = $(this).parent("div");
var _class = div.attr("class");

Xcode 9 Swift Language Version (SWIFT_VERSION)

maybe you need to download toolchain. This error occurs when you don't have right version of swift compiler.

Convert string with commas to array

Split it on the , character;

var string = "0,1";
var array = string.split(",");

Javascript Regular Expression Remove Spaces

This works just as well:

var reg = new RegExp(" ","g"); //<< just look for a space.

Aligning a float:left div to center?

Perhaps this what you're looking for -


#container {
  display:                 flex;
  flex-wrap:               wrap;
  justify-content:         center;

.block {
  width:              150px;
  height:             150px;
  margin:             10px;        


<div id="container">
  <div class="block">1</div>    
  <div class="block">2</div>    
  <div class="block">3</div>          

How to send an email using PHP?

Using PHP's mail() function it's possible. Remember mail function will not work on a Local server.

$to      = '[email protected]';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: [email protected]' . "\r\n" .
    'Reply-To: [email protected]' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);


SQL Server NOLOCK and joins

Neither. You set the isolation level to READ UNCOMMITTED which is always better than giving individual lock hints. Or, better still, if you care about details like consistency, use snapshot isolation.

Test if a command outputs an empty string

Previously, the question asked how to check whether there are files in a directory. The following code achieves that, but see rsp's answer for a better solution.

Empty output

Commands don’t return values – they output them. You can capture this output by using command substitution; e.g. $(ls -A). You can test for a non-empty string in Bash like this:

if [[ $(ls -A) ]]; then
    echo "there are files"
    echo "no files found"

Note that I've used -A rather than -a, since it omits the symbolic current (.) and parent (..) directory entries.

Note: As pointed out in the comments, command substitution doesn't capture trailing newlines. Therefore, if the command outputs only newlines, the substitution will capture nothing and the test will return false. While very unlikely, this is possible in the above example, since a single newline is a valid filename! More information in this answer.

Exit code

If you want to check that the command completed successfully, you can inspect $?, which contains the exit code of the last command (zero for success, non-zero for failure). For example:

files=$(ls -A)
if [[ $? != 0 ]]; then
    echo "Command failed."
elif [[ $files ]]; then
    echo "Files found."
    echo "No files found."

More info here.

What's the most concise way to read query parameters in AngularJS?

I found that for an SPA HTML5Mode causes lots of 404 error problems, and it is not necessary to make $ work in this case. In my case I want to capture a URL query string parameter when a user comes to my site, regardless of which "page" they initially link to, AND be able to send them to that page once they log in. So I just capture all that stuff in

$rootScope.$on('$stateChangeStart', function (e, toState, toParams, fromState, fromParams) {
    if ( === "") {
        $rootScope.initialPage =;
        $rootScope.initialParams = toParams;
    if ($'role')) {
        $rootScope.roleParameter = $['role'];

then later after login I can say $state.go($rootScope.initialPage, $rootScope.initialParams)

How to animate CSS Translate


assembly to compare two numbers

In TASM (x86 assembly) it can look like this:

cmp BL, BH
je EQUAL       ; BL = BH
jg GREATER     ; BL > BH
jmp LESS       ; BL < BH

in this case it compares two 8bit numbers that we temporarily store in the higher and the lower part of the register B. Alternatively you might also consider using jbe (if BL <= BH) or jge/jae (if BL >= BH).

Hopefully someone finds it helpful :)

GIT: Checkout to a specific folder

Use git archive branch-index | tar -x -C your-folder-on-PC to clone a branch to another folder. I think, then you can copy any file that you need

How can I scroll to a specific location on the page using jquery?

Using jquery.easing.min.js, With fixed IE console Errors


<a class="page-scroll" href="#features">Features</a>
<section id="features" class="features-section">Features Section</section>

        <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
        <script src="js/jquery.js"></script>
        <!-- Include all compiled plugins (below), or include individual files as needed -->
        <script src="js/bootstrap.min.js"></script>

        <!-- Scrolling Nav JavaScript -->
        <script src="js/jquery.easing.min.js"></script>


//jQuery to collapse the navbar on scroll, you can use this code with in external file with name scrolling-nav.js
        $(window).scroll(function () {
            if ($(".navbar").offset().top > 50) {
            } else {
        //jQuery for page scrolling feature - requires jQuery Easing plugin
        $(function () {
            $('').bind('click', function (event) {
                var anchor = $(this);
                if ($(anchor).length > 0) {
                    var href = $(anchor).attr('href');
                    if ($(href.substring(href.indexOf('#'))).length > 0) {
                        $('html, body').stop().animate({
                            scrollTop: $(href.substring(href.indexOf('#'))).offset().top
                        }, 1500, 'easeInOutExpo');
                    else {
                        window.location = href;

How can I export data to an Excel file

I used interop to open Excel and to modify the column widths once the data was done. If you use interop to spit the data into a new Excel workbook (if this is what you want), it will be terribly slow. Instead, I generated a .CSV, then opened the .CSV in Excel. This has its own problems, but I've found this the quickest method.

First, convert the .CSV:

// Convert array data into CSV format.
// Modified from
private string GetCSV(List<string> Headers, List<List<double>> Data)
    // Get the bounds.
    var rows = Data[0].Count;
    var cols = Data.Count;
    var row = 0;

    // Convert the array into a CSV string.
    StringBuilder sb = new StringBuilder();

    // Add the first field in this row.

    // Add the other fields in this row separated by commas.
    for (int col = 1; col < cols; col++)
        sb.Append("," + Headers[col]);

    // Move to the next line.

    for (row = 0; row < rows; row++)
        // Add the first field in this row.

        // Add the other fields in this row separated by commas.
        for (int col = 1; col < cols; col++)
            sb.Append("," + Data[col][row]);

        // Move to the next line.

    // Return the CSV format string.
    return sb.ToString();

Then, export it to Excel:

public void ExportToExcel()
    // Initialize app and pop Excel on the screen.
    var excelApp = new Excel.Application { Visible = true };

    // I use unix time to give the files a unique name that's almost somewhat useful.
    DateTime dateTime = DateTime.UtcNow;
    long unixTime = ((DateTimeOffset)dateTime).ToUnixTimeSeconds();
    var path = @"C:\Users\my\path\here + unixTime + ".csv";

    var csv = GetCSV();
    File.WriteAllText(path, csv);

    // Create a new workbook and get its active sheet.

    var workSheet = (Excel.Worksheet)excelApp.ActiveSheet;

    // iterate over each value and throw it in the chart
    for (var column = 0; column < Data.Count; column++)
        ((Excel.Range)workSheet.Columns[column + 1]).AutoFit();

    currentSheet = workSheet;

You'll have to install some stuff, too...

  1. Right click on the solution from solution explorer and select "Manage NuGet Packages." - add Microsoft.Office.Interop.Excel

  2. It might actually work right now if you created the project the way interop wants you to. If it still doesn't work, I had to create a new project in a different category. Under New > Project, select Visual C# > Windows Desktop > Console App. Otherwise, the interop tools won't work.

In case I forgot anything, here's my 'using' statements:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;

Linker command failed with exit code 1 - duplicate symbol __TMRbBp

I faced the same problem with archiving on Xcode 8.1.

X Code Version: Version 8.2.1 (8C1002)

The following fix worked on Mar 2019

1) Go to Project & Select your Project

enter image description here

2) Select Build Settings -

Search for "Enable Bitcode" Set option as "NO"

enter image description here

3) Most of version will fix this issue, for few other XCode version try this option also,

Search for "Reflection Metadata Level" Set option as "NONE"

enter image description here

Actionbar notification count icon (badge) like Google has

Edit Since version 26 of the support library (or androidx) you no longer need to implement a custom OnLongClickListener to display the tooltip. Simply call this:

TooltipCompat.setTooltipText(menu_hotlist, getString(R.string.hint_show_hot_message));

I'll just share my code in case someone wants something like this: enter image description here

  • layout/menu/menu_actionbar.xml

    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="">
        <item android:id="@+id/menu_hotlist"
            android:title="@string/hotlist" />
  • layout/action_bar_notifitcation_icon.xml

    Note style and android:clickable properties. these make the layout the size of a button and make the background gray when touched.

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android=""
        <TextView xmlns:android=""
  • drawable-xhdpi/ic_bell.png

    A 64x64 pixel image with 10 pixel wide paddings from all sides. You are supposed to have 8 pixel wide paddings, but I find most default items being slightly smaller than that. Of course, you'll want to use different sizes for different densities.

  • drawable/rounded_square.xml

    Here, #ff222222 (color #222222 with alpha #ff (fully visible)) is the background color of my Action Bar.

    <?xml version="1.0" encoding="utf-8"?>
        <corners android:radius="2dp" />
        <solid android:color="#ffff0000" />
        <stroke android:color="#ff222222" android:width="2dp"/>
  • com/ubergeek42/WeechatAndroid/

    Here we make it clickable and updatable! I created an abstract listener that provides Toast creation on onLongClick, the code was taken from from the sources of ActionBarSherlock.

    private int hot_number = 0;
    private TextView ui_hot = null;
    @Override public boolean onCreateOptionsMenu(final Menu menu) {
        MenuInflater menuInflater = getSupportMenuInflater();
        menuInflater.inflate(, menu);
        final View menu_hotlist = menu.findItem(;
        ui_hot = (TextView) menu_hotlist.findViewById(;
        new MyMenuItemStuffListener(menu_hotlist, "Show hot message") {
            public void onClick(View v) {
        return super.onCreateOptionsMenu(menu);
    // call the updating code on the main thread,
    // so we can call this asynchronously
    public void updateHotCount(final int new_hot_number) {
        hot_number = new_hot_number;
        if (ui_hot == null) return;
        runOnUiThread(new Runnable() {
            public void run() {
                if (new_hot_number == 0)
                else {
    static abstract class MyMenuItemStuffListener implements View.OnClickListener, View.OnLongClickListener {
        private String hint;
        private View view;
        MyMenuItemStuffListener(View view, String hint) {
            this.view = view;
            this.hint = hint;
        @Override abstract public void onClick(View v);
        @Override public boolean onLongClick(View v) {
            final int[] screenPos = new int[2];
            final Rect displayFrame = new Rect();
            final Context context = view.getContext();
            final int width = view.getWidth();
            final int height = view.getHeight();
            final int midy = screenPos[1] + height / 2;
            final int screenWidth = context.getResources().getDisplayMetrics().widthPixels;
            Toast cheatSheet = Toast.makeText(context, hint, Toast.LENGTH_SHORT);
            if (midy < displayFrame.height()) {
                cheatSheet.setGravity(Gravity.TOP | Gravity.RIGHT,
                        screenWidth - screenPos[0] - width / 2, height);
            } else {
                cheatSheet.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, height);
            return true;

case-insensitive matching in xpath?

matches() is an XPATH 2.0 function that allows for case-insensitive regex matching.

One of the flags is i for case-insensitive matching.

The following XPATH using the matches() function with the case-insensitive flag:

//CD[matches(@title,'empire burlesque','i')]

How to call a Parent Class's method from Child Class in Python?

Here is an example of using super():

#New-style classes inherit from object, or from another new-style class
class Dog(object):

    name = ''
    moves = []

    def __init__(self, name): = name

    def moves_setup(self):

    def get_moves(self):
        return self.moves

class Superdog(Dog):

    #Let's try to append new fly ability to our Superdog
    def moves_setup(self):
        #Set default moves by calling method of parent class
        super(Superdog, self).moves_setup()

dog = Superdog('Freddy')
print # Freddy
print dog.get_moves() # ['walk', 'run', 'fly']. 
#As you can see our Superdog has all moves defined in the base Dog class

How to multiply individual elements of a list with a number?

Here is a functional approach using map, itertools.repeat and operator.mul:

import operator
from itertools import repeat

def scalar_multiplication(vector, scalar):
    yield from map(operator.mul, vector, repeat(scalar))

Example of usage:

>>> v = [1, 2, 3, 4]
>>> c = 3
>>> list(scalar_multiplication(v, c))
[3, 6, 9, 12]

Angular2 - Focusing a textbox on component load

Using simple autofocus HTML5 attribute works for 'on load' scenario

 <input autofocus placeholder="enter text" [(ngModel)]="test">


<button autofocus (click)="submit()">Submit</button>

webpack command not working

You can run npx webpack. The npx command, which ships with Node 8.2/npm 5.2.0 or higher, runs the webpack binary (./node_modules/.bin/webpack) of the webpack package. Source of info:

postgresql return 0 if returned value is null

(this answer was added to provide shorter and more generic examples to the question - without including all the case-specific details in the original question).

There are two distinct "problems" here, the first is if a table or subquery has no rows, the second is if there are NULL values in the query.

For all versions I've tested, postgres and mysql will ignore all NULL values when averaging, and it will return NULL if there is nothing to average over. This generally makes sense, as NULL is to be considered "unknown". If you want to override this you can use coalesce (as suggested by Luc M).

$ create table foo (bar int);

$ select avg(bar) from foo;

(1 row)

$ select coalesce(avg(bar), 0) from foo;
(1 row)

$ insert into foo values (3);
$ insert into foo values (9);
$ insert into foo values (NULL);
$ select coalesce(avg(bar), 0) from foo;
(1 row)

of course, "from foo" can be replaced by "from (... any complicated logic here ...) as foo"

Now, should the NULL row in the table be counted as 0? Then coalesce has to be used inside the avg call.

$ select coalesce(avg(coalesce(bar, 0)), 0) from foo;
(1 row)

Copy and paste content from one file to another file in vi

While editing the file, make marks where you want the start and end to be using

ma - sets the a mark

mb - sets the b mark

Then, to copy that into another file, just use the w command:

:'a,'bw /name/of/output/file.txt

php execute a background process

PHP scripting is not like other desktop application developing language. In desktop application languages we can set daemon threads to run a background process but in PHP a process is occuring when user request for a page. However It is possible to set a background job using server's cron job functionality which php script runs.

Can't import javax.servlet.annotation.WebServlet

If you are using IBM RAD, then ensure the to remove any j2ee.jar in your projects build path -> libraries tab, and then click on "add external jar" and select the j2ee.jar that is shipped with RAD.

Android Studio Gradle project "Unable to start the daemon process /initialization of VM"

You need to add the path to environment variables (Windows) like such:

Variable Name: GRADLE_HOME
Variable Value: path

Please check below image:

enter image description here

JVM property -Dfile.encoding=UTF8 or UTF-8?

This is not a direct answer, but very useful if you don't have access to how java starts: you can set the environment variable JAVA_TOOLS_OPTIONS to -Dfile.encoding="UTF-8" and every time the jvm starts it will pick up that option.

How to move table from one tablespace to another in oracle 11g

Try this:-


Very nice suggestion from IVAN in comments so thought to add in my answer

Note: this will invalidate all table's indexes. So this command is usually followed by

alter index <owner>."<index_name>" rebuild;

Trim string in JavaScript?

All browsers since IE9+ have trim() method for strings:

" \n test \n ".trim(); // returns "test" here

For those browsers who does not support trim(), you can use this polyfill from MDN:

if (!String.prototype.trim) {
    (function() {
        // Make sure we trim BOM and NBSP
        var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
        String.prototype.trim = function() {
            return this.replace(rtrim, '');

That said, if using jQuery, $.trim(str) is also available and handles undefined/null.

See this:

String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};

String.prototype.ltrim=function(){return this.replace(/^\s+/,'');};

String.prototype.rtrim=function(){return this.replace(/\s+$/,'');};

String.prototype.fulltrim=function(){return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');};

Using File.listFiles with FileNameExtensionFilter

With java lambdas (available since java 8) you can simply convert javax.swing.filechooser.FileFilter to in one line.

javax.swing.filechooser.FileFilter swingFilter = new FileNameExtensionFilter("jpeg files", "jpeg"); ioFilter = file -> swingFilter.accept(file);
new File("myDirectory").listFiles(ioFilter);

Excel column number from column name

Here's a pure VBA solution because Excel can hold joined cells:

Public Function GetIndexForColumn(Column As String) As Long
    Dim astrColumn()    As String
    Dim Result          As Long
    Dim i               As Integer
    Dim n               As Integer

    Column = UCase(Column)
    ReDim astrColumn(Len(Column) - 1)
    For i = 0 To (Len(Column) - 1)
        astrColumn(i) = Mid(Column, (i + 1), 1)
    n = 1
    For i = UBound(astrColumn) To 0 Step -1
        Result = (Result + ((Asc(astrColumn(i)) - 64) * n))
        n = (n * 26)
    GetIndexForColumn = Result
End Function

Basically, this function does the same as any Hex to Dec function, except that it only takes alphabetical chars (A = 1, B = 2, ...). The rightmost char counts single, each char to the left counts 26 times the char right to it (which makes AA = 27 [1 + 26], AAA = 703 [1 + 26 + 676]). The use of UCase() makes this function case-insensitive.

ExecutorService that interrupts tasks after a timeout

You can use this implementation that ExecutorService provides

invokeAll(Collection<? extends Callable<T>> tasks,long timeout, TimeUnit unit)

executor.invokeAll(Arrays.asList(task), 2 , TimeUnit.SECONDS);

However, in my case, I could not as Arrays.asList took extra 20ms.

How to write connection string in web.config file and read from it?

After opening the web.config file in application, add sample db connection in connectionStrings section like this:

    <add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System.Data.SqlClient" />   

Declaring connectionStrings in web.config file:

 <add name="dbconnection" connectionString="Data Source=Soumalya;Integrated Security=true;Initial Catalog=MySampleDB" providerName="System.Data.SqlClient" />   

There is no need of username and password to access the database server. Now, write the code to get the connection string from web.config file in our codebehind file. Add the following namespace in codebehind file.

using System.Configuration;

This namespace is used to get configuration section details from web.config file.

using System;  
using System.Data.SqlClient;  
using System.Configuration;  
public partial class _Default: System.Web.UI.Page {  
    protected void Page_Load(object sender, EventArgs e) {  
        //Get connection string from web.config file  
        string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;  
        //create new sqlconnection and connection to database by using connection string from web.config file  
        SqlConnection con = new SqlConnection(strcon);  

How do I "shake" an Android device within the Android emulator to bring up the dev menu to debug my React Native app

With a React Native running in the emulator,
Press ctrl+m (for Linux, I suppose it's the same for Windows and ?+m for Mac OS X) or run the following in terminal:

adb shell input keyevent 82

Array String Declaration

You can write like below. Check out the syntax guidelines in this thread

AClass[] array;
array = new AClass[]{object1, object2};

If you find arrays annoying better use ArrayList.

How do I install PHP cURL on Linux Debian?

Whatever approach you take, make sure in the end that you have an updated version of curl and libcurl. You can do curl --version and see the versions.

Here's what I did to get the latest curl version installed in Ubuntu:

  1. sudo add-apt-repository "deb wily main"
  2. sudo apt-get update
  3. sudo apt-get install curl

Amazon S3 upload file and get URL

No you cannot get the URL in single action but two :)

First of all, you may have to make the file public before uploading because it makes no sense to get the URL that no one can access. You can do so by setting ACL as Michael Astreiko suggested. You can get the resource URL either by calling getResourceUrl or getUrl.

AmazonS3Client s3Client = (AmazonS3Client)AmazonS3ClientBuilder.defaultClient();
s3Client.putObject(new PutObjectRequest("your-bucket", "some-path/some-key.jpg", new File("somePath/someKey.jpg")).withCannedAcl(CannedAccessControlList.PublicRead))
s3Client.getResourceUrl("your-bucket", "some-path/some-key.jpg");

Note1: The different between getResourceUrl and getUrl is that getResourceUrl will return null when exception occurs.

Note2: getUrl method is not defined in the AmazonS3 interface. You have to cast the object to AmazonS3Client if you use the standard builder.

What is the purpose of Android's <merge> tag in XML layouts?

<merge/> is useful because it can get rid of unneeded ViewGroups, i.e. layouts that are simply used to wrap other views and serve no purpose themselves.

For example, if you were to <include/> a layout from another file without using merge, the two files might look something like this:


   <include layout="@layout/layout2"/>


   <TextView />
   <TextView />

which is functionally equivalent to this single layout:

      <TextView />
      <TextView />

That FrameLayout in layout2.xml may not be useful. <merge/> helps get rid of it. Here's what it looks like using merge (layout1.xml doesn't change):


   <TextView />
   <TextView />

This is functionally equivalent to this layout:

   <TextView />
   <TextView />

but since you are using <include/> you can reuse the layout elsewhere. It doesn't have to be used to replace only FrameLayouts - you can use it to replace any layout that isn't adding something useful to the way your view looks/behaves.

How to fix missing dependency warning when using useEffect React Hook?

You can remove the 2nd argument type array [] but the fetchBusinesses() will also be called every update. You can add an IF statement into the fetchBusinesses() implementation if you like.

React.useEffect(() => {

The other one is to implement the fetchBusinesses() function outside your component. Just don't forget to pass any dependency arguments to your fetchBusinesses(dependency) call, if any.

function fetchBusinesses (fetch) {
  return fetch("theURL", { method: "GET" })
    .then(res => normalizeResponseErrors(res))
    .then(res => res.json())
    .then(rcvdBusinesses => {
      // some stuff
    .catch(err => {
      // some error handling

function YourComponent (props) {
  const { fetch } = props;

  React.useEffect(() => {
  }, [fetch]);

  // ...

Is there a php echo/print equivalent in javascript

You can use document.write or even console.write (this is good for debugging).

But your best bet and it gives you more control is to use DOM to update the page.

How to jQuery clone() and change id?

  // get the last DIV which ID starts with ^= "klon"_x000D_
  var $div = $('div[id^="klon"]:last');_x000D_
  // Read the Number from that DIV's ID (i.e: 3 from "klon3")_x000D_
  // And increment that number by 1_x000D_
  var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;_x000D_
  // Clone it and assign the new ID (i.e: from num 4 to ID "klon4")_x000D_
  var $klon = $div.clone().prop('id', 'klon'+num );_x000D_
  // Finally insert $klon wherever you want_x000D_
  $div.after( $klon.text('klon'+num) );_x000D_
<script src=""></script>_x000D_
<button id="cloneDiv">CLICK TO CLONE</button> _x000D_
<div id="klon1">klon1</div>_x000D_
<div id="klon2">klon2</div>

Scrambled elements, retrieve highest ID

Say you have many elements with IDs like klon--5 but scrambled (not in order). Here we cannot go for :last or :first, therefore we need a mechanism to retrieve the highest ID:

const $all = $('[id^="klon--"]');_x000D_
const maxID = Math.max.apply(Math, $, el) =>\d+$/g)[0]).get());_x000D_
const nextId = maxID + 1;_x000D_
console.log(`New ID is: ${nextId}`);
<div id="klon--12">12</div>_x000D_
<div id="klon--34">34</div>_x000D_
<div id="klon--8">8</div>_x000D_
<script src=""></script>

jQuery - Follow the cursor with a DIV

You can't follow the cursor with a DIV, but you can draw a DIV when moving the cursor!

$(document).on('mousemove', function(e){
       left:  e.pageX,
       top:   e.pageY

That div must be off the float, so position: absolute should be set.

Search and replace in bash using regular expressions

These examples also work in bash no need to use sed:

echo ${MYVAR//[0-9]/N}

you can also use the character class bracket expressions

echo ${MYVAR//[[:digit:]]/N}



What @Lanaru wanted to know however, if I understand the question correctly, is why the "full" or PCRE extensions \s\S\w\W\d\D etc don't work as supported in php ruby python etc. These extensions are from Perl-compatible regular expressions (PCRE) and may not be compatible with other forms of shell based regular expressions.

These don't work:

echo ${hello//\d/}

echo $hello | sed 's/\d//g'

output with all literal "d" characters removed


but the following does work as expected

echo $hello | perl -pe 's/\d//g'



Hope that clarifies things a bit more but if you are not confused yet why don't you try this on Mac OS X which has the REG_ENHANCED flag enabled:

echo $MYVAR | grep -o -E '\d'

On most flavours of *nix you will only see the following output:



This project references NuGet package(s) that are missing on this computer

These are the steps I used to fix the issue:

To add nuget packages to your solution:

  1. Right click on the project (not solution) you want to reference nuget packages.
  2. Choose: Manage nuget packages
  3. On the popup window, on the left you have three choices. If you choose Online > Microsoft & .NET, you will be able to install Microsoft ASP.NET Web API 2.2 package grouper (or whatever package you need - mine was this).
  4. Now right click on your solution (not project) and choose Enable nuget package restore. This will cause the packages to be automagically downloaded at compilation.

Filtering a data frame by values in a column

The subset command is not necessary. Just use data frame indexing

studentdata[studentdata$Drink == 'water',]

Read the warning from ?subset

This is a convenience function intended for use interactively. For programming it is better to use the standard subsetting functions like ‘[’, and in particular the non-standard evaluation of argument ‘subset’ can have unanticipated consequences.

How to send a message to a particular client with

When a user connects, it should send a message to the server with a username which has to be unique, like an email.

A pair of username and socket should be stored in an object like this:

var users = {
    '[email protected]': [socket object],
    '[email protected]': [socket object],
    '[email protected]': [socket object]

On the client, emit an object to the server with the following data:

    to:[the other receiver's username as a string],
    from:[the person who sent the message as string],
    message:[the message to be sent as string]

On the server, listen for messages. When a message is received, emit the data to the receiver.

users[].emit('receivedMessage', data)

On the client, listen for emits from the server called 'receivedMessage', and by reading the data you can handle who it came from and the message that was sent.

What is a Python equivalent of PHP's var_dump()?


For your own classes, just def a __str__ method

AngularJS: How do I manually set input to $valid in controller?

It is very simple. For example : in you JS controller use this:

$scope.inputngmodel.$valid = false;


$scope.inputngmodel.$invalid = true;


$scope.formname.inputngmodel.$valid = false;


$scope.formname.inputngmodel.$invalid = true;

All works for me for different requirement. Hit up if this solve your problem.

SQL Inner join more than two tables

FROM table1 
      ON table1.primaryKey=table2.table1Id
      ON table1.primaryKey=table3.table1Id

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed

As @swanliu pointed out it is due to a bad connection.
However before adjusting the server timing and client timeout , I would first try and use a better connection pooling strategy.

Connection Pooling

Hibernate itself admits that its connection pooling strategy is minimal

Hibernate's own connection pooling algorithm is, however, quite rudimentary. It is intended to help you get started and is not intended for use in a production system, or even for performance testing. You should use a third party pool for best performance and stability. Just replace the hibernate.connection.pool_size property with connection pool specific settings. This will turn off Hibernate's internal pool. For example, you might like to use c3p0.
As stated in Reference :

I personally use C3P0. however there are other alternatives available including DBCP.
Check out

Below is a minimal configuration of C3P0 used in my application:

<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="c3p0.acquire_increment">1</property> 
<property name="c3p0.idle_test_period">100</property> <!-- seconds --> 
<property name="c3p0.max_size">100</property> 
<property name="c3p0.max_statements">0</property> 
<property name="c3p0.min_size">10</property> 
<property name="c3p0.timeout">1800</property> <!-- seconds --> 

By default, pools will never expire Connections. If you wish Connections to be expired over time in order to maintain "freshness", set maxIdleTime and/or maxConnectionAge. maxIdleTime defines how many seconds a Connection should be permitted to go unused before being culled from the pool. maxConnectionAge forces the pool to cull any Connections that were acquired from the database more than the set number of seconds in the past.
As stated in Reference :

I updated the configuration file (Reference), as I had just copy pasted the one for my project earlier. The timeout should ideally solve the problem, If that doesn't work for you there is an expensive solution which I think you could have a look at:

Create a file “” which must be in the root of the classpath (i.e. no way to override it for particular parts of the application). (Reference)


With this configuration each connection is tested before being used. It however might affect the performance of the site.

How to change the background color on a input checkbox with css?

I always use pseudo elements :before and :after for changing the appearance of checkboxes and radio buttons. it's works like a charm.

Refer this link for more info



  1. Hide the default checkbox using css rules like visibility:hidden or opacity:0 or position:absolute;left:-9999px etc.
  2. Create a fake checkbox using :before element and pass either an empty or a non-breaking space '\00a0';
  3. When the checkbox is in :checked state, pass the unicode content: "\2713", which is a checkmark;
  4. Add :focus style to make the checkbox accessible.
  5. Done

Here is how I did it.

.box {_x000D_
  background: #666666;_x000D_
  color: #ffffff;_x000D_
  width: 250px;_x000D_
  padding: 10px;_x000D_
  margin: 1em auto;_x000D_
p {_x000D_
  margin: 1.5em 0;_x000D_
  padding: 0;_x000D_
input[type="checkbox"] {_x000D_
  visibility: hidden;_x000D_
label {_x000D_
  cursor: pointer;_x000D_
input[type="checkbox"] + label:before {_x000D_
  border: 1px solid #333;_x000D_
  content: "\00a0";_x000D_
  display: inline-block;_x000D_
  font: 16px/1em sans-serif;_x000D_
  height: 16px;_x000D_
  margin: 0 .25em 0 0;_x000D_
  padding: 0;_x000D_
  vertical-align: top;_x000D_
  width: 16px;_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
  background: #fff;_x000D_
  color: #333;_x000D_
  content: "\2713";_x000D_
  text-align: center;_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
  font-weight: bold;_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
    outline: rgb(59, 153, 252) auto 5px;_x000D_
<div class="content">_x000D_
  <div class="box">_x000D_
      <input type="checkbox" id="c1" name="cb">_x000D_
      <label for="c1">Option 01</label>_x000D_
      <input type="checkbox" id="c2" name="cb">_x000D_
      <label for="c2">Option 02</label>_x000D_
      <input type="checkbox" id="c3" name="cb">_x000D_
      <label for="c3">Option 03</label>_x000D_

Much more stylish using :before and :after

  font-family: sans-serif;  _x000D_
.container {_x000D_
    margin-top: 50px;_x000D_
    margin-left: 20px;_x000D_
    margin-right: 20px;_x000D_
.checkbox {_x000D_
    width: 100%;_x000D_
    margin: 15px auto;_x000D_
    position: relative;_x000D_
    display: block;_x000D_
.checkbox input[type="checkbox"] {_x000D_
    width: auto;_x000D_
    opacity: 0.00000001;_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    margin-left: -20px;_x000D_
.checkbox label {_x000D_
    position: relative;_x000D_
.checkbox label:before {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    top: 0;_x000D_
    margin: 4px;_x000D_
    width: 22px;_x000D_
    height: 22px;_x000D_
    transition: transform 0.28s ease;_x000D_
    border-radius: 3px;_x000D_
    border: 2px solid #7bbe72;_x000D_
.checkbox label:after {_x000D_
  content: '';_x000D_
    display: block;_x000D_
    width: 10px;_x000D_
    height: 5px;_x000D_
    border-bottom: 2px solid #7bbe72;_x000D_
    border-left: 2px solid #7bbe72;_x000D_
    -webkit-transform: rotate(-45deg) scale(0);_x000D_
    transform: rotate(-45deg) scale(0);_x000D_
    transition: transform ease 0.25s;_x000D_
    will-change: transform;_x000D_
    position: absolute;_x000D_
    top: 12px;_x000D_
    left: 10px;_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
    color: #7bbe72;_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
    -webkit-transform: rotate(-45deg) scale(1);_x000D_
    transform: rotate(-45deg) scale(1);_x000D_
.checkbox label {_x000D_
    min-height: 34px;_x000D_
    display: block;_x000D_
    padding-left: 40px;_x000D_
    margin-bottom: 0;_x000D_
    font-weight: normal;_x000D_
    cursor: pointer;_x000D_
    vertical-align: sub;_x000D_
.checkbox label span {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    -webkit-transform: translateY(-50%);_x000D_
    transform: translateY(-50%);_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
    outline: 0;_x000D_
<div class="container"> _x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox" name="" value="">_x000D_
     <label for="checkbox"><span>Checkbox</span></label>_x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox2" name="" value="">_x000D_
     <label for="checkbox2"><span>Checkbox</span></label>_x000D_

C/C++ NaN constant (literal)?

As others have pointed out you are looking for std::numeric_limits<double>::quiet_NaN() although I have to say I prefer the documents. Especially because this statement is a little vague:

Only meaningful if std::numeric_limits::has_quiet_NaN == true.

and it was simple to figure out what this means on this site, if you check their section on std::numeric_limits::has_quiet_NaN it says:

This constant is meaningful for all floating-point types and is guaranteed to be true if std::numeric_limits::is_iec559 == true.

which as explained here if true means your platform supports IEEE 754 standard. This previous thread explains this should be true for most situations.

Initialize a vector array of strings

In C++0x you will be able to initialize containers just like arrays

Hiding a sheet in Excel 2007 (with a password) OR hide VBA code in Excel


If the user is sophisticated or determined enough to:

  1. Open the Excel VBA editor
  2. Use the object browser to see the list of all sheets, including VERYHIDDEN ones
  3. Change the property of the sheet to VISIBLE or just HIDDEN

then they are probably sophisticated or determined enough to:

  1. Search the internet for "remove Excel 2007 project password"
  2. Apply the instructions they find.

So what's on this hidden sheet? Proprietary information like price formulas, or client names, or employee salaries? Putting that info in even an hidden tab probably isn't the greatest idea to begin with.

Open Cygwin at a specific folder

Probably the simplest one:

1) Create file foo.reg

2) Insert content:

Windows Registry Editor Version 5.00

@="open mintty"

@="cmd /C mintty"

3) Execute foo.reg

Now just right-click in any folder, click open mintty and it will spawn mintty in that folder.

Export to CSV using MVC, C# and jQuery

yan.kun was on the right track but this is much much easier.

    public FileContentResult DownloadCSV()
        string csv = "Charlie, Chaplin, Chuckles";
        return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "Report123.csv");

Sending GET request with Authentication headers using restTemplate

A simple solution would be to configure static http headers needed for all calls in the bean configuration of the RestTemplate:

public class RestTemplateConfig {

    public RestTemplate getRestTemplate(@Value("${did-service.bearer-token}") String bearerToken) {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getInterceptors().add((request, body, clientHttpRequestExecution) -> {
            HttpHeaders headers = request.getHeaders();
            if (!headers.containsKey("Authorization")) {
                String token = bearerToken.toLowerCase().startsWith("bearer") ? bearerToken : "Bearer " + bearerToken;
                request.getHeaders().add("Authorization", token);
            return clientHttpRequestExecution.execute(request, body);
        return restTemplate;

Batch File: ( was unexpected at this time

You are getting that error because when the param1 if statements are evaluated, param is always null due to being scoped variables without delayed expansion.

When parentheses are used, all the commands and variables within those parentheses are expanded. And at that time, param1 has no value making the if statements invalid. When using delayed expansion, the variables are only expanded when the command is actually called.

Also I recommend using if not defined command to determine if a variable is set.

@echo off
setlocal EnableExtensions EnableDelayedExpansion
title ~USB Wizard~
echo What do you want to do?
echo 1.Enable/Disable USB Storage Devices.
echo 2.Enable/Disable Writing Data onto USB Storage.
echo 3.~Yet to come~.

set "a=%globalparam1%"
goto :aCheck
set /p "a=Enter Choice: "
if not defined a goto :aPrompt
echo %a%

IF "%a%"=="2" (
    title USB WRITE LOCK
    echo What do you want to do?
    echo 1.Apply USB Write Protection
    echo 2.Remove USB Write Protection

    set "param1=%globalparam2%"
    goto :param1Check
    set /p "param1=Enter Choice: "
    if not defined param1 goto :param1Prompt
    echo !param1!

    if "!param1!"=="1" (
        REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000001 
        echo USB Write is Locked!
    if "!param1!"=="2" (
        REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000000
        echo USB Write is Unlocked! 

Good ways to sort a queryset? - Django

I just wanted to illustrate that the built-in solutions (SQL-only) are not always the best ones. At first I thought that because Django's QuerySet.objects.order_by method accepts multiple arguments, you could easily chain them:

ordered_authors = Author.objects.order_by('-score', 'last_name')[:30]

But, it does not work as you would expect. Case in point, first is a list of presidents sorted by score (selecting top 5 for easier reading):

>>> auths = Author.objects.order_by('-score')[:5]
>>> for x in auths: print x
James Monroe (487)
Ulysses Simpson (474)
Harry Truman (471)
Benjamin Harrison (467)
Gerald Rudolph (464)

Using Alex Martelli's solution which accurately provides the top 5 people sorted by last_name:

>>> for x in sorted(auths, key=operator.attrgetter('last_name')): print x
Benjamin Harrison (467)
James Monroe (487)
Gerald Rudolph (464)
Ulysses Simpson (474)
Harry Truman (471)

And now the combined order_by call:

>>> myauths = Author.objects.order_by('-score', 'last_name')[:5]
>>> for x in myauths: print x
James Monroe (487)
Ulysses Simpson (474)
Harry Truman (471)
Benjamin Harrison (467)
Gerald Rudolph (464)

As you can see it is the same result as the first one, meaning it doesn't work as you would expect.

Default Values to Stored Procedure in Oracle

Default-Values are only considered for parameters NOT given to the function.

So given a function

procedure foo( bar1 IN number DEFAULT 3,
     bar2 IN number DEFAULT 5,
     bar3 IN number DEFAULT 8 );

if you call this procedure with no arguments then it will behave as if called with

foo( bar1 => 3,
     bar2 => 5,
     bar3 => 8 );

but 'NULL' is still a parameter.

foo( 4,
     bar3 => NULL );

This will then act like

foo( bar1 => 4,
     bar2 => 5,
     bar3 => Null );

( oracle allows you to either give the parameter in order they are specified in the procedure, specified by name, or first in order and then by name )

one way to treat NULL the same as a default value would be to default the value to NULL

procedure foo( bar1 IN number DEFAULT NULL,
     bar2 IN number DEFAULT NULL,
     bar3 IN number DEFAULT NULL );

and using a variable with the desired value then

procedure foo( bar1 IN number DEFAULT NULL,
     bar2 IN number DEFAULT NULL,
     bar3 IN number DEFAULT NULL )
     v_bar1    number := NVL( bar1, 3);
     v_bar2    number := NVL( bar2, 5);
     v_bar3    number := NVL( bar3, 8);

How to create a drop shadow only on one side of an element?

This code pen (not by me) demonstrates a super simple way of doing this and the other sides by themselves quite nicely:

box-shadow: 0 5px 5px -5px #333;

Android: how to handle button click

#1 I use the last one frequently when having buttons on the layout which are not generated (but static obviously).

If you use it in practice and in a business application, pay extra attention here, because when you use source obfuscater like ProGuard, you'll need to mark these methods in your activity as to not be obfuscated.

For archiving some kind of compile-time-security with this approach, have a look at Android Lint (example).

#2 Pros and cons for all methods are almost the same and the lesson should be:

Use what ever is most appropriate or feels most intuitive to you.

If you have to assign the same OnClickListener to multiple button instances, save it in the class-scope (#1). If you need a simple listener for a Button, make an anonymous implementation:

button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
        // Take action.

I tend to not implement the OnClickListener in the activity, this gets a little confusing from time to time (especially when you implement multiple other event-handlers and nobody knows what this is all doing).

Remove all whitespace in a string

If you want to remove leading and ending spaces, use str.strip():

sentence = ' hello  apple'
>>> 'hello  apple'

If you want to remove all space characters, use str.replace():

(NB this only removes the “normal” ASCII space character ' ' U+0020 but not any other whitespace)

sentence = ' hello  apple'
sentence.replace(" ", "")
>>> 'helloapple'

If you want to remove duplicated spaces, use str.split():

sentence = ' hello  apple'
" ".join(sentence.split())
>>> 'hello apple'

What is sr-only in Bootstrap 3?

I found this in the navbar example, and simplified it.

<ul class="nav">
  <li><a>Static top</a></li>
  <li><b><a>Fixed top <span class="sr-only">(current)</span></a></b></li>

You see which one is selected (sr-only part is hidden):

  • Default
  • Static top
  • Fixed top

You hear which one is selected if you use screen reader:

  • Default
  • Static top
  • Fixed top (current)

As a result of this technique blind people supposed to navigate easier on your website.

How to change maven logging level to display only warning and errors?

Unfortunately, even with maven 3 the only way to do that is to patch source code.

Here is short instruction how to do that.

Clone or fork Maven 3 repo: "git clone"

Edit org.apache.maven.cli.MavenCli#logging, and change

cliRequest.request.setLoggingLevel( MavenExecutionRequest.LOGGING_LEVEL_INFO );


cliRequest.request.setLoggingLevel( MavenExecutionRequest.LOGGING_LEVEL_WARN );

In current snapshot version it's at line 270

Then just run "mvn install", your new maven distro will be located in "apache-maven\target\" folder

See this diff for the reference:

Vertically align text within a div

Create a container for your text content, a span perhaps.

#column-content {_x000D_
  display: inline-block;_x000D_
img {_x000D_
  vertical-align: middle;_x000D_
span {_x000D_
  display: inline-block;_x000D_
  vertical-align: middle;_x000D_
/* for visual purposes */_x000D_
#column-content {_x000D_
  border: 1px solid red;_x000D_
  position: relative;_x000D_
<div id="column-content">_x000D_
  <img src="">_x000D_
    yet another text content that should be centered vertically</span>_x000D_


Error You must specify a region when running command aws ecs list-container-instances

I think you need to use for example:

aws ecs list-container-instances --cluster default --region us-east-1

This depends of your region of course.

Database, Table and Column Naming Conventions?

Table names should always be singular, because they represent a set of objects. As you say herd to designate a group of sheep, or flock do designate a group of birds. No need for plural. When a table name is composition of two names and naming convention is in plural it becomes hard to know if the plural name should be the first word or second word or both. It’s the logic – Object.instance, not objects.instance. Or TableName.column, not TableNames.column(s). Microsoft SQL is not case sensitive, it’s easier to read table names, if upper case letters are used, to separate table or column names when they are composed of two or more names.

Running AMP (apache mysql php) on Android

In PHP I use Server For PHP app in playstore, for MySql I use MariaDB Server, and to connect to MariaDB with PHP 7 use this code:

$your_variable = mysqli_connect('your hostname', 'root(default)', 'leave this empty', 'the database you want to connect');