Programs & Examples On #Sticky windows

Execute stored procedure with an Output parameter?



How do I get the dialer to open with phone number displayed?

Okay, it is going to be extremely late answer to this question. But here is just one sample if you want to do it in Kotlin.

val intent = Intent(Intent.ACTION_DIAL) = Uri.parse("tel:<number>")

Thought it might help someone.

connecting to phpMyAdmin database with PHP/MySQL

The database is a MySQL database, not a phpMyAdmin database. phpMyAdmin is only PHP code that connects to the DB.

mysql_connect('localhost', 'username', 'password') or die (mysql_error());
mysql_select_database('db_name') or die (mysql_error());

// now you are connected

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

If you are using Unirest as the http library, using the GsonObjectMapper instead of the JacksonObjectMapper will also work.

<!-- -->
Unirest.config().objectMapper = GsonObjectMapper()

How to determine MIME type of file in android?

Detect mime type of any file

public String getMimeType(Uri uri) {           
    String mimeType = null;
    if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
        ContentResolver cr = getAppContext().getContentResolver();
        mimeType = cr.getType(uri);
    } else {
        String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri
        mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
    return mimeType;

Purpose of installing Twitter Bootstrap through npm?

Answer 1:

  • Downloading bootstrap through npm (or bower) permits you to gain some latency time. Instead of getting a remote resource, you get a local one, it's quicker, except if you use a cdn (check below answer)

  • "npm" was originally to get Node Module, but with the essort of the Javascript language (and the advent of browserify), it has a bit grown up. In fact, you can even download AngularJS on npm, that is not a server side framework. Browserify permits you to use AMD/RequireJS/CommonJS on client side so node modules can be used on client side.

Answer 2:

If you npm install bootstrap (if you dont use a particular grunt or gulp file to move to a dist folder), your bootstrap will be located in "./node_modules/bootstrap/bootstrap.min.css" if I m not wrong.

Convert UIImage to NSData and convert back to UIImage in Swift?

To save as data:

From StoryBoard, if you want to save "image" data on the imageView of MainStoryBoard, following codes will work.

let image = UIImagePNGRepresentation(imageView.image!) as NSData?

To load "image" to imageView: Look at exclamation point "!", "?" closely whether that is quite same as this one.

imageView.image = UIImage(data: image as! Data)

"NSData" type is converted into "Data" type automatically during this process.

How to get JSON from URL in JavaScript?

const fetchPromise1 = fetch(url);
    fetchPromise1.then(response => {

const fetchPromise = fetch(url);

"inconsistent use of tabs and spaces in indentation"

Solving this using Vim editor

  1. Open terminal (Ctrl + Alt + T).
  2. Go to the directory where the file is located (cd <path_to_your_directory>). Ex: cd /home/vineeshvs/work.
  3. Open the file in Vim (vim <file_name>). Ex: vim myfile.txt .
  4. [Optional step] Enable search keyword highlighting in Vim (ESC :set hlsearch)
  5. Go to the line where you have this problem (ESC :<line_number>). Ex: :53 in Vim editor after pressing ESC button once.
  6. Replace tabs using the required number of spaces in Vim (:.,$s/\t/<give_as_many_spaces_as_you_want_to_replace_tab>/gc). Ex: Tab will be replaced with four spaces using the following command: :.,$s/\t/ /gc after pressing ESC button once). This process is interactive. You may give y to replace the tab with spaces and n to skip a particular replacement. Press ESC when you are done with the required replacements.

How to make FileFilter in java?

Here you will find some working examples. This is also a good example of FileFilter used in JFileChooser.

The basics are, you need to override FileFilter class and write your custom code in its accpet method. The accept method in above example is doing filtration based on file types:

public boolean accept(File file) {
    if (file.isDirectory()) {
      return true;
    } else {
      String path = file.getAbsolutePath().toLowerCase();
      for (int i = 0, n = extensions.length; i < n; i++) {
        String extension = extensions[i];
        if ((path.endsWith(extension) && (path.charAt(path.length() 
                  - extension.length() - 1)) == '.')) {
          return true;
    return false;

Or more simpler to use is FileNameFilter which has accept method with filename as argument, so you don't need to get it manually.

What dependency is missing for org.springframework.web.bind.annotation.RequestMapping?

Thanks above all of you contributions! however for my case I finally realized that my dependency above "spring-web" was destroyed on my .m2/repository/org/springframework/spring-web, I just deleted the folder and update Maven again. it got fixed.

import httplib ImportError: No module named httplib

I had this issue when I was trying to make my Docker container smaller. It was because I'd installed Python 2.7 with:

apt-get install -y --no-install-recommends python

And I should not have included the --no-install-recommends flag:

apt-get install -y python

What's the proper value for a checked attribute of an HTML checkbox?

It's pretty crazy town that the only way to make checked false is to omit any values. With Angular 1.x, you can do this:

  <input type="radio" ng-checked="false">

which is a lot more sane, if you need to make it unchecked.

Paging UICollectionView by cells, not screen

Horizontal Paging With Custom Page Width (Swift 4 & 5)

Many solutions presented here result in some weird behaviour that doesn't feel like properly implemented paging.

The solution presented in this tutorial, however, doesn't seem to have any issues. It just feels like a perfectly working paging algorithm. You can implement it in 5 simple steps:

  1. Add the following property to your type: private var indexOfCellBeforeDragging = 0
  2. Set the collectionView delegate like this: collectionView.delegate = self
  3. Add conformance to UICollectionViewDelegate via an extension: extension YourType: UICollectionViewDelegate { }
  4. Add the following method to the extension implementing the UICollectionViewDelegate conformance and set a value for pageWidth:

    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        let pageWidth = // The width your page should have (plus a possible margin)
        let proportionalOffset = collectionView.contentOffset.x / pageWidth
        indexOfCellBeforeDragging = Int(round(proportionalOffset))
  5. Add the following method to the extension implementing the UICollectionViewDelegate conformance, set the same value for pageWidth (you may also store this value at a central place) and set a value for collectionViewItemCount:

    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        // Stop scrolling
        targetContentOffset.pointee = scrollView.contentOffset
        // Calculate conditions
        let pageWidth = // The width your page should have (plus a possible margin)
        let collectionViewItemCount = // The number of items in this section
        let proportionalOffset = collectionView.contentOffset.x / pageWidth
        let indexOfMajorCell = Int(round(proportionalOffset))
        let swipeVelocityThreshold: CGFloat = 0.5
        let hasEnoughVelocityToSlideToTheNextCell = indexOfCellBeforeDragging + 1 < collectionViewItemCount && velocity.x > swipeVelocityThreshold
        let hasEnoughVelocityToSlideToThePreviousCell = indexOfCellBeforeDragging - 1 >= 0 && velocity.x < -swipeVelocityThreshold
        let majorCellIsTheCellBeforeDragging = indexOfMajorCell == indexOfCellBeforeDragging
        let didUseSwipeToSkipCell = majorCellIsTheCellBeforeDragging && (hasEnoughVelocityToSlideToTheNextCell || hasEnoughVelocityToSlideToThePreviousCell)
        if didUseSwipeToSkipCell {
            // Animate so that swipe is just continued
            let snapToIndex = indexOfCellBeforeDragging + (hasEnoughVelocityToSlideToTheNextCell ? 1 : -1)
            let toValue = pageWidth * CGFloat(snapToIndex)
                withDuration: 0.3,
                delay: 0,
                usingSpringWithDamping: 1,
                initialSpringVelocity: velocity.x,
                options: .allowUserInteraction,
                animations: {
                    scrollView.contentOffset = CGPoint(x: toValue, y: 0)
                completion: nil
        } else {
            // Pop back (against velocity)
            let indexPath = IndexPath(row: indexOfMajorCell, section: 0)
            collectionView.scrollToItem(at: indexPath, at: .left, animated: true)

XAMPP PORT 80 is Busy / EasyPHP error in Apache configuration file:

Port 80 might be busy with other application like IIS. If you don't want to stop it, you can change the apache port. Here is the way..

  1. go to the C:\xampp\apache\conf (directory where you installed xampp). Now, locate the httpd.conf.
  2. Open it with any text editor (like notepad) and go the line that says Listen 80
  3. Change this with any other port (like Listen 1234)
  4. Save the file. Restart the server and go ahead.

How can I reset or revert a file to a specific revision?

Here is my way.

a) In Android Studio, open the file.

b) git -> Show History, find the previous commit I want to revert to. Get the commit_id (i.e. commit hash).

c) git checkout commit_id file_path

Visual Studio Code - Convert spaces to tabs

If you want to use tabs instead of spaces

Try this:

  1. Go to File ? Preferences ? Settings or just press Ctrl + ,
  2. In the Search settings bar on top insert editor.insertSpaces
  3. You will see something like this: Editor: Insert Spaces and it will be probably checked. Just uncheck it as show in image below

Editor: Insert Spaces

  1. Reload Visual Studio Code (Press F1 ? type reload window ? press Enter)

If it doesn't worked try this:

It's probably because of installed plugin JS-CSS-HTML Formatter

(You can check it by going to File ? Preferences ? Extensions or just pressing Ctrl + Shift + X, in the Enabled list you will find JS-CSS-HTML Formatter)

If so you can modify this plugin:

  1. Press F1 ? type Formatter config ? press Enter (it will open the file formatter.json)
  2. Modify the file like this:
 4|    "indent_size": 1,
 5|    "indent_char": "\t"
24|    "indent_size": 1,
25|    "indentCharacter": "\t",
26|    "indent_char": "\t",
34|    "indent_size": 1,
35|    "indent_char": "\t",
36|    "indent_character": "\t"
  1. Save it (Go to File ? Save or just press Ctrl + S)
  2. Reload Visual Studio Code (Press F1 ? type reload window ? press Enter)

Update style of a component onScroll in React.js

An example using classNames, React hooks useEffect, useState and styled-jsx:

import classNames from 'classnames'
import { useEffect, useState } from 'react'

const Header = _ => {
  const [ scrolled, setScrolled ] = useState()
  const classes = classNames('header', {
    scrolled: scrolled,
  useEffect(_ => {
    const handleScroll = _ => { 
      if (window.pageYOffset > 1) {
      } else {
    window.addEventListener('scroll', handleScroll)
    return _ => {
      window.removeEventListener('scroll', handleScroll)
  }, [])
  return (
    <header className={classes}>
      <h1>Your website</h1>
      <style jsx>{`
        .header {
          transition: background-color .2s;
        .header.scrolled {
          background-color: rgba(0, 0, 0, .1);
export default Header

Background Image for Select (dropdown) does not work in Chrome

you can use the below css styles for all browsers except Firefox 30

select {
  background: url(dropdown_arw.png) no-repeat right center;
  appearance: none;
  -moz-appearance: none;
  -webkit-appearance: none;
  width: 90px;
  text-indent: 0.01px;
  text-overflow: "";

demo page -


here is solution for Firefox 30. little trick for custom select elements in firefox :-moz-any() css pseudo class.

Retrieve column values of the selected row of a multicolumn Access listbox

For multicolumn listbox extract data from any column of selected row by


where col_num is required column ( 0 for first column)

set div height using jquery (stretch div height)

You can bind function as follows, instead of init on load

$("div").css("height", $(window).height());
$(?window?).bind("resize",function() {
    $("div").css("height", $(window).height());

Show/hide image with JavaScript


<img id="theImage" src="yourImage.png">
<a id="showImage">Show image</a>


document.getElementById("showImage").onclick = function() {
    document.getElementById("theImage").style.display = "block";


#theImage { display:none; }

How to check if command line tools is installed

Go to Applications > Xcode > preferences > downloads

You should see the command line tools there for you to install.

Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet

Your is "wrong"; I don't know where you got it from, but that's not a 1.7 - were you using some funky pre-release build or something?

Reset your to the conventional, as below, and things Should Just Work:

#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings")

    from import execute_from_command_line


How do I replace text in a selection?

1- Find: CTRL + F
2- Select-in: Alt + Enter

Now you can change all the selection in one shot like "seen-on-tv" ST homepage Spot.

Credit goes to :

Spring Boot REST API - request timeout?

You need to return a Callable<> if you want spring.mvc.async.request-timeout=5000 to work.

@RequestMapping(method = RequestMethod.GET)
public Callable<String> getFoobar() throws InterruptedException {
    return new Callable<String>() {
        public String call() throws Exception {
            Thread.sleep(8000); //this will cause a timeout
            return "foobar";

ReactJS SyntheticEvent stopPropagation() only works with React events?

A quick workaround is using window.addEventListener instead of document.addEventListener.

Want to move a particular div to right

For me, I used margin-left: auto; which is more responsive with horizontal resizing.

Return row number(s) for a particular value in a column in a dataframe

Use which(mydata_2$height_chad1 == 2585)

Short example

df <- data.frame(x = c(1,1,2,3,4,5,6,3),
                 y = c(5,4,6,7,8,3,2,4))
  x y
1 1 5
2 1 4
3 2 6
4 3 7
5 4 8
6 5 3
7 6 2
8 3 4

which(df$x == 3)
[1] 4 8

length(which(df$x == 3))
[1] 2

count(df, vars = "x")
  x freq
1 1    2
2 2    1
3 3    2
4 4    1
5 5    1
6 6    1

df[which(df$x == 3),]
  x y
4 3 7
8 3 4

As Matt Weller pointed out, you can use the length function. The count function in plyr can be used to return the count of each unique column value.

How can I enable CORS on Django REST Framework

Well, I don't know guys but:

using here python 3.6 and django 2.2


UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block

You are catching the error but then you are re throwing it. You should try and handle it more gracefully, otherwise your user is going to see 500, internal server, errors.

You may want to send back a response telling the user what went wrong as well as logging the error on your server.

I am not sure exactly what errors the request might return, you may want to return something like.

router.get("/emailfetch", authCheck, async (req, res) => {
  try {
    let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
      emailFetch =
   } catch(error) {
      return res.send(error.message);


This code will need to be adapted to match the errors that you get from the axios call.

I have also converted the code to use the try and catch syntax since you are already using async.

Scheduled run of stored procedure on SQL server

Yes, if you use the SQL Server Agent.

Open your Enterprise Manager, and go to the Management folder under the SQL Server instance you are interested in. There you will see the SQL Server Agent, and underneath that you will see a Jobs section.

Here you can create a new job and you will see a list of steps you will need to create. When you create a new step, you can specify the step to actually run a stored procedure (type TSQL Script). Choose the database, and then for the command section put in something like:

exec MyStoredProcedure

That's the overview, post back here if you need any further advice.

[I actually thought I might get in first on this one, boy was I wrong :)]

Which UUID version to use?

There are two different ways of generating a UUID.

If you just need a unique ID, you want a version 1 or version 4.

  • Version 1: This generates a unique ID based on a network card MAC address and a timer. These IDs are easy to predict (given one, I might be able to guess another one) and can be traced back to your network card. It's not recommended to create these.

  • Version 4: These are generated from random (or pseudo-random) numbers. If you just need to generate a UUID, this is probably what you want.

If you need to always generate the same UUID from a given name, you want a version 3 or version 5.

  • Version 3: This generates a unique ID from an MD5 hash of a namespace and name. If you need backwards compatibility (with another system that generates UUIDs from names), use this.

  • Version 5: This generates a unique ID from an SHA-1 hash of a namespace and name. This is the preferred version.

cannot find zip-align when publishing app

It becomes usable if you install

Android SDK Build-tools Rev.20

Evaluating a mathematical expression in a string

Use eval in a clean namespace:

>>> ns = {'__builtins__': None}
>>> eval('2 ** 4', ns)

The clean namespace should prevent injection. For instance:

>>> eval('__builtins__.__import__("os").system("echo got through")', ns)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute '__import__'

Otherwise you would get:

>>> eval('__builtins__.__import__("os").system("echo got through")')
got through

You might want to give access to the math module:

>>> import math
>>> ns = vars(math).copy()
>>> ns['__builtins__'] = None
>>> eval('cos(pi/3)', ns)

Complexities of binary tree traversals

Depth first traversal of a binary tree is of order O(n).

Algo -- <b>
    if root is null---------------O(1)<b>
      return null-----------------O(1)<b>

If the time complexity of the algo is T(n) then it can be written as T(n) = 2*T(n/2) + O(1). If we apply back substitution we will get T(n) = O(n).

UILabel with text of two different colors

In my case I'm using Xcode 10.1. There is a option of switching between plain text and Attributed text in Label text in Interface Builder

enter image description here

Hope this may help someone else..!

How do I get rid of the "cannot empty the clipboard" error?

I've read lots of blogs on this subject going back to 2005!!

I'm sure that Paul Simon is right (see his submission to this thread) and it's a question of finding which program on your machine is locking the clipboard. I do not run the programs listed in various solutons suggested (eg on Microsoft website) nor am I in a networked or virtual environment so for me those aren't the locking programs (but might be for you). Similarly I don't have the RDP task going in my processes. For me the locking program is the Skype Add-in.

I am not a sophisticated user and am scared of altering my registry so didn't want to go there.

I have now been able to reproduce accurately the "cannot clear the clipboard" message by turning on and off the skype addins in internet explorer. This is easy for amateurs to do and might be one of the more common clipboard locking programs:

I first confirmed that I can turn on/off the problem in Excel by opening/closing internet explorer.

Then I disabled the skype addins:

Internet Explorer: Tools menu --> Internet Options ; Programs Tab ; Manage Add-ons button; Toolbars and Extensions selected in panel on left - scroll down to find skype add ons. Press Disable button.

NB have to restart Internet explorer before this works.

.... 4 days later.... it's still working

How to set an iframe src attribute from a variable in AngularJS

You need also $sce.trustAsResourceUrl or it won't open the website inside the iframe:

angular.module('myApp', [])_x000D_
    .controller('dummy', ['$scope', '$sce', function ($scope, $sce) {_x000D_
    $scope.url = $sce.trustAsResourceUrl('');_x000D_
    $scope.changeIt = function () {_x000D_
        $scope.url = $sce.trustAsResourceUrl('');_x000D_
<script src=""></script>_x000D_
<div ng-app="myApp" ng-controller="dummy">_x000D_
    <iframe ng-src="{{url}}" width="300" height="200"></iframe>_x000D_
    <button ng-click="changeIt()">Change it</button>_x000D_

Create a mocked list by mockito

OK, this is a bad thing to be doing. Don't mock a list; instead, mock the individual objects inside the list. See Mockito: mocking an arraylist that will be looped in a for loop for how to do this.

Also, why are you using PowerMock? You don't seem to be doing anything that requires PowerMock.

But the real cause of your problem is that you are using when on two different objects, before you complete the stubbing. When you call when, and provide the method call that you are trying to stub, then the very next thing you do in either Mockito OR PowerMock is to specify what happens when that method is called - that is, to do the thenReturn part. Each call to when must be followed by one and only one call to thenReturn, before you do any more calls to when. You made two calls to when without calling thenReturn - that's your error.

socket.emit() vs. socket.send()

With socket.emit you can register custom event like that:


var io = require('').listen(80);

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {


var socket = io.connect('http://localhost');
socket.on('news', function (data) {
  socket.emit('my other event', { my: 'data' });

Socket.send does the same, but you don't register to 'news' but to message:


var io = require('').listen(80);

io.sockets.on('connection', function (socket) {


var socket = io.connect('http://localhost');
socket.on('message', function (message) {

Java Round up Any Number

The easiest way to do this is just: You will receive a float or double and want it to convert it to the closest round up then just do System.out.println((int)Math.ceil(yourfloat)); it'll work perfectly

How to add new DataRow into DataTable?

You can try with this code - based on Rows.Add method

DataTable table = new DataTable();
DataRow row = table.NewRow();

Link :

Eclipse error, "The selection cannot be launched, and there are no recent launches"

Eclipse can't work out what you want to run and since you've not run anything before, it can't try re-running that either.

Instead of clicking the green 'run' button, click the dropdown next to it and chose Run Configurations. On the Android tab, make sure it's set to your project. In the Target tab, set the tick box and options as appropriate to target your device. Then click Run. Keep an eye on your Console tab in Eclipse - that'll let you know what's going on. Once you've got your run configuration set, you can just hit the green 'run' button next time.

Sometimes getting everything to talk to your device can be problematic to begin with. Consider using an AVD (i.e. an emulator) as alternative, at least to begin with if you have problems. You can easily create one from the menu Window -> Android Virtual Device Manager within Eclipse.

To view the progress of your project being installed and started on your device, check the console. It's a panel within Eclipse with the tabs Problems/Javadoc/Declaration/Console/LogCat etc. It may be minimised - check the tray in the bottom right. Or just use Window/Show View/Console from the menu to make it come to the front. There are two consoles, Android and DDMS - there is a dropdown by its icon where you can switch.

Determining image file size + dimensions via Javascript?


To get the current in-browser pixel size of a DOM element (in your case IMG elements) excluding the border and margin, you can use the clientWidth and clientHeight properties.

var img = document.getElementById('imageId'); 

var width = img.clientWidth;
var height = img.clientHeight;

Now to get the file size, now I can only think about the fileSize property that Internet Explorer exposes for document and IMG elements...

Edit 2: Something comes to my mind...

To get the size of a file hosted on the server, you could simply make an HEAD HTTP Request using Ajax. This kind of request is used to obtain metainformation about the url implied by the request without transferring any content of it in the response.

At the end of the HTTP Request, we have access to the response HTTP Headers, including the Content-Length which represents the size of the file in bytes.

A basic example using raw XHR:

var xhr = new XMLHttpRequest();'HEAD', 'img/test.jpg', true);
xhr.onreadystatechange = function(){
  if ( xhr.readyState == 4 ) {
    if ( xhr.status == 200 ) {
      alert('Size in bytes: ' + xhr.getResponseHeader('Content-Length'));
    } else {

Note: Keep in mind that when you do Ajax requests, you are restricted by the Same origin policy, which allows you to make requests only within the same domain.

Check a working proof of concept here.

Edit 3:

1.) About the Content-Length, I think that a size mismatch could happen for example if the server response is gzipped, you can do some tests to see if this happens on your server.

2.) For get the original dimensions of a image, you could create an IMG element programmatically, for example:

var img = document.createElement('img');

img.onload = function () { alert(img.width + ' x ' + img.height); };


Getting values from query string in an url using AngularJS $location

you can use this as well

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(;
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));

var queryValue = getParameterByName('test_user_bLzgB');

How do I go about adding an image into a java project with eclipse?

You can resave the image and literally find the src file of your project and add it to that when you save. For me I had to go to netbeans and found my project and when that comes up it had 3 files src was the last. Don't click on any of them just save your pic there. That should work. Now resizing it may be a different issue and one I'm working on now lol

How to delete or add column in SQLITE?

I've wrote a Java implementation based on the Sqlite's recommended way to do this:

private void dropColumn(SQLiteDatabase db,
        ConnectionSource connectionSource,
        String createTableCmd,
        String tableName,
        String[] colsToRemove) throws java.sql.SQLException {

    List<String> updatedTableColumns = getTableColumns(tableName);
    // Remove the columns we don't want anymore from the table's list of columns

    String columnsSeperated = TextUtils.join(",", updatedTableColumns);

    db.execSQL("ALTER TABLE " + tableName + " RENAME TO " + tableName + "_old;");

    // Creating the table on its new format (no redundant columns)

    // Populating the table with the data
    db.execSQL("INSERT INTO " + tableName + "(" + columnsSeperated + ") SELECT "
            + columnsSeperated + " FROM " + tableName + "_old;");
    db.execSQL("DROP TABLE " + tableName + "_old;");

To get the table's column, I used the "PRAGMA table_info":

public List<String> getTableColumns(String tableName) {
    ArrayList<String> columns = new ArrayList<String>();
    String cmd = "pragma table_info(" + tableName + ");";
    Cursor cur = getDB().rawQuery(cmd, null);

    while (cur.moveToNext()) {

    return columns;

I actually wrote about it on my blog, you can see more explanations there:

android set button background programmatically

Further from @finnmglas, the Java answer as of 2021 is:

    if (Build.VERSION.SDK_INT >= 29)
        btn.getBackground().setColorFilter(new BlendModeColorFilter(color, BlendMode.MULTIPLY));
        btn.getBackground().setColorFilter(color, PorterDuff.Mode.MULTIPLY);

How to find Current open Cursors in Oracle

Here's how to find open cursors that have been parsed. You need to be logged in as a user with access to v$open_cursor and v$session.


SELECT s.machine, oc.user_name, oc.sql_text, count(1) 
FROM v$open_cursor oc, v$session s
WHERE oc.sid = s.sid
GROUP BY user_name, sql_text, machine
ORDER BY count(1) DESC

If gives you part of the SQL text so it can be useful for identifying leaky applications. If a cursor has not been parsed, then it does not appear here. Note that Oralce will sometimes keep things open longer than you do.

Decode JSON with unknown structure

You really just need a single struct, and as mentioned in the comments the correct annotations on the field will yield the desired results. JSON is not some extremely variant data format, it is well defined and any piece of json, no matter how complicated and confusing it might be to you can be represented fairly easily and with 100% accuracy both by a schema and in objects in Go and most other OO programming languages. Here's an example;

package main

import (

type Data struct {
    Votes *Votes `json:"votes"`
    Count string `json:"count,omitempty"`

type Votes struct {
    OptionA string `json:"option_A"`

func main() {
    s := `{ "votes": { "option_A": "3" } }`
    data := &Data{
        Votes: &Votes{},
    err := json.Unmarshal([]byte(s), data)
    s2, _ := json.Marshal(data)
    data.Count = "2"
    s3, _ := json.Marshal(data)

Based on your most recent comment you could address that by using an interface{} to represent data besides the count, making the count a string and having the rest of the blob shoved into the interface{} which will accept essentially anything. That being said, Go is a statically typed language with a fairly strict type system and to reiterate, your comments stating 'it can be anything' are not true. JSON cannot be anything. For any piece of JSON there is schema and a single schema can define many many variations of JSON. I advise you take the time to understand the structure of your data rather than hacking something together under the notion that it cannot be defined when it absolutely can and is probably quite easy for someone who knows what they're doing.

Angular 2 - Setting selected value on dropdown list

Thanks for the tip Günter, it got me moving in the right direction. There was a mis-matched spelling of 'color' in my solution which was causing issues and I needed to use 'ngValue' not 'value' in the template html.

Here is the complete solution using objects for the ngModel and select list options and avoiding use of the [selected] attribute.

I have updated the Plunker to show the full working solution.

Component template

        <div *ngIf="car != null">
            <select [(ngModel)]="car.colour">
                <option *ngFor="let x of colours" [ngValue]="x" >{{}}</option>


import { Component, OnInit } from '@angular/core';
import {AbstractControl,FORM_DIRECTIVES } from '@angular/common';

export class DropdownComponent implements OnInit
    colours: Array<Colour>;

    ngOnInit(): void {

        this.colours = Array<Colour>();
        this.colours.push(new Colour(-1, 'Please select'));
        this.colours.push(new Colour(1, 'Green'));
        this.colours.push(new Colour(2, 'Pink')); = new Car(); = this.colours[1];        

export class Car  

export class Colour
    constructor(id:number, name:string) {;;


Group by & count function in sqlalchemy

The documentation on counting says that for group_by queries it is better to use func.count():

from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()

What is the difference between parseInt() and Number()?

typeof parseInt("123") => number
typeof Number("123") => number
typeof new Number("123") => object (Number primitive wrapper object)

first two will give you better performance as it returns a primitive instead of an object.

batch file to check 64bit or 32bit OS

I usually do the following:

if /i "%processor_architecture%"=="x86" (
        REM Run 32 bit command

    ) ELSE (
        REM Run 64 bit command
) else (
        REM Run 64 bit command

Path of currently executing powershell script

Split-Path $MyInvocation.MyCommand.Path -Parent

Android ListView Selector Color

TO ADD: @Christopher's answer does not work on API 7/8 (as per @Jonny's correct comment) IF you are using colours, instead of drawables. (In my testing, using drawables as per Christopher works fine)

Here is the FIX for 2.3 and below when using colours:

As per @Charles Harley, there is a bug in 2.3 and below where filling the list item with a colour causes the colour to flow out over the whole list. His fix is to define a shape drawable containing the colour you want, and to use that instead of the colour.

I suggest looking at this link if you want to just use a colour as selector, and are targeting Android 2 (or at least allow for Android 2).

Get Cell Value from Excel Sheet with Apache Poi

You have to use the FormulaEvaluator, as shown here. This will return a value that is either the value present in the cell or the result of the formula if the cell contains such a formula :

FileInputStream fis = new FileInputStream("/somepath/test.xls");
Workbook wb = new HSSFWorkbook(fis); //or new XSSFWorkbook("/somepath/test.xls")
Sheet sheet = wb.getSheetAt(0);
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();

// suppose your formula is in B3
CellReference cellReference = new CellReference("B3"); 
Row row = sheet.getRow(cellReference.getRow());
Cell cell = row.getCell(cellReference.getCol()); 

if (cell!=null) {
    switch (evaluator.evaluateFormulaCell(cell)) {
        case Cell.CELL_TYPE_BOOLEAN:
        case Cell.CELL_TYPE_NUMERIC:
        case Cell.CELL_TYPE_STRING:
        case Cell.CELL_TYPE_BLANK:
        case Cell.CELL_TYPE_ERROR:

        // CELL_TYPE_FORMULA will never occur
        case Cell.CELL_TYPE_FORMULA: 

if you need the exact contant (ie the formla if the cell contains a formula), then this is shown here.

Edit : Added a few example to help you.

first you get the cell (just an example)

Row row = sheet.getRow(rowIndex+2);    
Cell cell = row.getCell(1);   

If you just want to set the value into the cell using the formula (without knowing the result) :

 String formula ="ABS((1-E"+(rowIndex + 2)+"/D"+(rowIndex + 2)+")*100)";    

if you want to change the message if there is an error in the cell, you have to change the formula to do so, something like

IF(ISERR(ABS((1-E3/D3)*100));"N/A"; ABS((1-E3/D3)*100))

(this formula check if the evaluation return an error and then display the string "N/A", or the evaluation if this is not an error).

if you want to get the value corresponding to the formula, then you have to use the evaluator.

Hope this help,

video as site background? HTML 5

Take a look at my jquery videoBG plugin

Make any HTML5 video a site background... has an image fallback for browsers that don't support html5

Really easy to use

Let me know if you need any help.

How to convert SSH keypairs generated using PuTTYgen (Windows) into key-pairs used by ssh-agent and Keychain (Linux)

Alternatively if you want to grab the private and public keys from a PuTTY formated key file you can use puttygen on *nix systems. For most apt-based systems puttygen is part of the putty-tools package.

Outputting a private key from a PuTTY formated keyfile:

$ puttygen keyfile.pem -O private-openssh -o avdev.pvk

For the public key:

$ puttygen keyfile.pem -L

Vba macro to copy row from table if value in table meets condition

Selects are slow and unnescsaary. The following code will be far faster:

Sub CopyRowsAcross() 
Dim i As Integer 
Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets("Sheet1") 
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("Sheet2") 

For i = 2 To ws1.Range("B65536").End(xlUp).Row 
    If ws1.Cells(i, 2) = "Your Critera" Then ws1.Rows(i).Copy ws2.Rows(ws2.Cells(ws2.Rows.Count, 2).End(xlUp).Row + 1) 
Next i 
End Sub 

How can I auto increment the C# assembly version via our CI platform (Hudson)?

So, we have a project with one solution that contains several projects that have assemblies with different version numbers.

After investigating several of the above methods, I just implemented a build step to run a Powershell script that does a find-and-replace on the AssemblyInfo.cs file. I still use the 1.0.* version number in source control, and Jenkins just manually updates the version number before msbuild runs.

dir **/Properties/AssemblyInfo.cs | %{ (cat $_) | %{$_ -replace '^(\s*)\[assembly: AssemblyVersion\("(.*)\.\*"\)', "`$1[assembly: AssemblyVersion(`"`$2.$build`")"} | Out-File $_ -Encoding "UTF8" }
dir **/Properties/AssemblyInfo.cs | %{ (cat $_) | %{$_ -replace '^(\s*)\[assembly: AssemblyFileVersion\("(.*)\.\*"\)', "`$1[assembly: AssemblyFileVersion(`"`$2.$build`")"} | Out-File $_ -Encoding "UTF8" }

I added the -Encoding "UTF8" option because git started treating the .cs file as binary files if I didn't. Granted, this didn't matter, since I never actually commit the result; it just came up as I was testing.

Our CI environment already has a facility to associate the Jenkins build with the particular git commit (thanks Stash plugin!), so I don't worry that there's no git commit with the version number attached to it.

Using sed and grep/egrep to search and replace

Another way to do this

find . -name *.xml -exec sed -i "s/4.6.0-SNAPSHOT/5.0.0-SNAPSHOT/" {} \;

Some help regarding the above command

The find will do the find for you on the current directory indicated by .

-name the name of the file in my case its pom.xml can give wild cards.

-exec execute

sed stream editor

-i ignore case

s is for substitute

/4.6.0.../ String to be searched

/5.0.0.../ String to be replaced

What are your favorite extension methods for C#? (

string.Format shortcut:

public static class StringExtensions
    // Enable quick and more natural string.Format calls
    public static string F(this string s, params object[] args)
        return string.Format(s, args);


var s = "The co-ordinate is ({0}, {1})".F(point.X, point.Y);

For quick copy-and-paste go here.

Don't you find it more natural to type "some string".F("param") instead of string.Format("some string", "param") ?

For a more readable name, try one of these suggestion:

s = "Hello {0} world {1}!".Fmt("Stack", "Overflow");
s = "Hello {0} world {1}!".FormatBy("Stack", "Overflow");
s = "Hello {0} world {1}!".FormatWith("Stack", "Overflow");
s = "Hello {0} world {1}!".Display("Stack", "Overflow");
s = "Hello {0} world {1}!".With("Stack", "Overflow");


Convert LocalDate to LocalDateTime or java.sql.Timestamp


The Joda-Time project is in maintenance-mode, now supplanted by java.time classes.

  • Just use java.time.Instant class.
  • No need for:
    • LocalDateTime
    • java.sql.Timestamp
    • Strings

Capture current moment in UTC.  

To store that moment in database:

myPreparedStatement.setObject( … , )  // Writes an `Instant` to database.

To retrieve that moment from datbase:

myResultSet.getObject( … , Instant.class )  // Instantiates a `Instant`

To adjust the wall-clock time to that of a particular time zone.

instant.atZone( z )  // Instantiates a `ZonedDateTime`

LocalDateTime is the wrong class

Other Answers are correct, but they fail to point out that LocalDateTime is the wrong class for your purpose.

In both java.time and Joda-Time, a LocalDateTime purposely lacks any concept of time zone or offset-from-UTC. As such, it does not represent a moment, and is not a point on the timeline. A LocalDateTime represents a rough idea about potential moments along a range of about 26-27 hours.

Use a LocalDateTime for either when the zone/offset is unknown (not a good situation), or when the zone-offset is indeterminate. For example, “Christmas starts at first moment of December 25, 2018” would be represented as a LocalDateTime.

Use a ZonedDateTime to represent a moment in a particular time zone. For example, Christmas starting in any particular zone such as Pacific/Auckland or America/Montreal would be represented with a ZonedDateTime object.

For a moment always in UTC, use Instant.

Instant instant = ;  // Capture the current moment in UTC.

Apply a time zone. Same moment, same point on the timeline, but viewed with a different wall-clock time.

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;  // Same moment, different wall-clock time.

So, if I can just convert between LocalDate and LocalDateTime,

No, wrong strategy. If you have a date-only value, and you want a date-time value, you must specify a time-of-day. That time-of-day may not be valid on that date for a particular zone – in which case ZonedDateTime class automatically adjusts the time-of-day as needed.

LocalDate ld = LocalDate.of( 2018 , Month.JANUARY , 23 ) ;
LocalTime lt = LocalTime.of( 14 , 0 ) ;  // 14:00 = 2 PM.
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;

If you want the first moment of the day as your time-of-day, let java.time determine that moment. Do not assume the day starts at 00:00:00. Anomalies such as Daylight Saving Time (DST) mean the day may start at another time such as 01:00:00.

ZonedDateTime zdt = ld.atStartOfDay( z ) ;

java.sql.Timestamp is the wrong class

The java.sql.Timestamp is part of the troublesome old date-time classes that are now legacy, supplanted entirely by the java.time classes. That class was used to represent a moment in UTC with a resolution of nanoseconds. That purpose is now served with java.time.Instant.

JDBC 4.2 with getObject/setObject

As of JDBC 4.2 and later, your JDBC driver can directly exchange java.time objects with the database by calling:

For example:

myPreparedStatement.setObject( … , instant ) ;

… and …

Instant instant = myResultSet.getObject( … , Instant.class ) ;

Convert legacy ? modern

If you must interface with old code not yet updated to java.time, convert back and forth using new methods added to the old classes.

Instant instant = myJavaSqlTimestamp.toInstant() ;  // Going from legacy class to modern class.


java.sql.Timestamp myJavaSqlTimestamp = java.sql.Timestamp.from( instant ) ;  // Going from modern class to legacy class.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

MySQL Join Where Not Exists

I'd use a 'where not exists' -- exactly as you suggest in your title:

SELECT `voter`.`ID`, `voter`.`Last_Name`, `voter`.`First_Name`,
       `voter`.`Middle_Name`, `voter`.`Age`, `voter`.`Sex`,
       `voter`.`Party`, `voter`.`Demo`, `voter`.`PV`,
       `household`.`Address`, `household`.`City`, `household`.`Zip`
FROM (`voter`)
JOIN `household` ON `voter`.`House_ID`=`household`.`id`
WHERE `CT` = '5'
AND `Precnum` = 'CTY3'
AND  `Last_Name`  LIKE '%Cumbee%'
AND  `First_Name`  LIKE '%John%'

  SELECT * FROM `elimination`
   WHERE `elimination`.`voter_id` = `voter`.`ID`

ORDER BY `Last_Name` ASC

That may be marginally faster than doing a left join (of course, depending on your indexes, cardinality of your tables, etc), and is almost certainly much faster than using IN.

Complex nesting of partials and templates

You may use ng-include to avoid using nested ng-views.

My index page I use ng-view. Then on my sub pages which I need to have nested frames. I use ng-include. The demo shows a dropdown. I replaced mine with a link ng-click. In the function I would put $scope.template = $scope.templates[0]; or $scope.template = $scope.templates[1];

$scope.clickToSomePage= function(){
  $scope.template = $scope.templates[0];

fetch gives an empty response body

fetch("http://localhost:8988/api", {
        //mode: "no-cors",
        method: "GET",
        headers: {
            "Accept": "application/json"
    .then(response => {
        return response.json();
    .then(data => {
        return data;
    .catch(error => {
        return error;

This works for me.

How can I add additional PHP versions to MAMP

If you need to be able to switch between more than two versions at a time, you can use the following to change the version of PHP manually.

MAMP automatically rewrites the following line in your /Applications/MAMP/conf/apache/httpd.conf file when it restarts based on the settings in preferences. You can comment out this line and add the second one to the end of your file:

# Comment this out just under all the modules loaded
# LoadModule php5_module        /Applications/MAMP/bin/php/php5.x.x/modules/

At the bottom of the httpd.conf file, you'll see where additional configurations are loaded from the extra folder. Add this to the bottom of the httpd.conf file

# PHP Version Change
Include /Applications/MAMP/conf/apache/extra/httpd-php.conf

Then create a new file here: /Applications/MAMP/conf/apache/extra/httpd-php.conf

# Uncomment the version of PHP you want to run with MAMP
# LoadModule php5_module /Applications/MAMP/bin/php/php5.2.17/modules/
# LoadModule php5_module /Applications/MAMP/bin/php/php5.3.27/modules/
# LoadModule php5_module /Applications/MAMP/bin/php/php5.4.19/modules/
LoadModule php5_module /Applications/MAMP/bin/php/php5.5.3/modules/

After you have this setup, just uncomment the version of PHP you want to use and restart the servers!

Image resolution for mdpi, hdpi, xhdpi and xxhdpi

Require Screen sizes for splash :

LDPI: Portrait: 200 X 320px
MDPI: Portrait: 320 X 480px
HDPI: Portrait: 480 X 800px
XHDPI: Portrait: 720 X 1280px
XXHDPI: Portrait: 960 X 1600px
XXXHDPI: Portrait: 1440 x 2560px

Require icon Sizes for App :

How to filter multiple values (OR operation) in angularJS

Lets assume you have two array, one for movie and one for genre

Just use the filter as: filter:{genres: genres.type}

Here genres being the array and type has value for genre

how to select rows based on distinct values of A COLUMN only

if you dont wanna use DISTINCT use GROUP BY


Javascript Regular Expression Remove Spaces

I would recommend you use the literal notation, and the \s character class:

return str.replace(/\s/g, '');

There's a difference between using the character class \s and just ' ', this will match a lot more white-space characters, for example '\t\r\n' etc.., looking for ' ' will replace only the ASCII 32 blank space.

The RegExp constructor is useful when you want to build a dynamic pattern, in this case you don't need it.

Moreover, as you said, "[\s]+" didn't work with the RegExp constructor, that's because you are passing a string, and you should "double escape" the back-slashes, otherwise they will be interpreted as character escapes inside the string (e.g.: "\s" === "s" (unknown escape)).

Passing variable number of arguments around

You can try macro also.

#define NONE    0x00
#define DBG     0x1F
#define INFO    0x0F
#define ERR     0x07
#define EMR     0x03
#define CRIT    0x01


#define WHERESTR "[FILE : %s, FUNC : %s, LINE : %d]: "
#define WHEREARG __FILE__,__func__,__LINE__
#define DEBUG(...)  fprintf(stderr, __VA_ARGS__)
#define DEBUG_PRINT(X, _fmt, ...)  if((DEBUG_LEVEL & X) == X) \
                                      DEBUG(WHERESTR _fmt, WHEREARG,__VA_ARGS__)

int main()
    int x=10;
    DEBUG_PRINT(DBG, "i am x %d\n", x);
    return 0;

How do I make a JAR from a .java file?

Often you will want to specify a manifest, like so:

jar -cvfm myJar.jar myManifest.txt myApp.class

Which reads: "create verbose jarFilename manifestFilename", followed by the files you want to include. Verbose means print messages about what it's doing.

Note that the name of the manifest file you supply can be anything, as jar will automatically rename it and put it into the right directory within the jar file.

Display image as grayscale using matplotlib

I would use the get_cmap method. Ex.:

import matplotlib.pyplot as plt

plt.imshow(matrix, cmap=plt.get_cmap('gray'))

Case insensitive searching in Oracle

maybe you can try using

SELECT user_name
FROM user_master
WHERE upper(user_name) LIKE '%ME%'

HTTP POST with Json on Body - Flutter/Dart

This works!

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;

Future<http.Response> postRequest () async {
  var url ='';

  Map data = {
    'apikey': '12345678901234567890'
  //encode Map to JSON
  var body = json.encode(data);

  var response = await,
      headers: {"Content-Type": "application/json"},
      body: body
  return response;

Convert integer value to matching Java Enum

There is no way to elegantly handle integer-based enumerated types. You might think of using a string-based enumeration instead of your solution. Not a preferred way all the times, but it still exists.

public enum Port {
   * The default port for the push server.

   * The alternative port that can be used to bypass firewall checks
   * made to the default <i>HTTPS</i> port.

  private final String portString;

  Port(final String portString) {
    this.portString = portString;

   * Returns the port for given {@link Port} enumeration value.
   * @return The port of the push server host.
  public Integer toInteger() {
    return Integer.parseInt(portString);

If REST applications are supposed to be stateless, how do you manage sessions?

REST is stateless and doesn’t maintain any states between the requests. Client cookies / headers are set to maintain the user state like authentication. Say Client username/password are validated by third part authentication mechanism – 2nd level OTP gerneation etc. Once user get authenticated – headers /cookies comes to rest service end point exposed and we can assume user as auth since user is coming with valid headers/cookies. Now certain info of user like IP is either maintained in the cache and after that if request is coming from same Ip (mac address) for listed resources User is allowed. And cache is maintained for some particular time which get invalidated once time lapses. So either cache can be used or DB entries can be used to persist info b/w the requests.

JQuery window scrolling event?

Check if the user has scrolled past the header ad, then display the footer ad.

if($(your header ad).position().top < 0) { $(your footer ad).show() }

Am I correct at what you are looking for?

How to crop an image using PIL?

You need to import PIL (Pillow) for this. Suppose you have an image of size 1200, 1600. We will crop image from 400, 400 to 800, 800

from PIL import Image
img ="ImageName.jpg")
area = (400, 400, 800, 800)
cropped_img = img.crop(area)

How to send email to multiple recipients with addresses stored in Excel?

Both answers are correct. If you user .TO -method then the semicolumn is OK - but not for the addrecipients-method. There you need to split, e.g. :

                Dim Splitter() As String
                Splitter = Split(AddrMail, ";")
                For Each Dest In Splitter
                    .Recipients.Add (Trim(Dest))

How to download an entire directory and subdirectories using wget?

you can also use this command :

wget --mirror -pc --convert-links -P ./your-local-dir/

so that you get the exact mirror of the website you want to download

How can I set the background color of <option> in a <select> element?

I had this problem too. I found setting the appearance to none helped.

.class {

    background-color: red;

gdb: how to print the current line or find the current line number?

I do get the same information while debugging. Though not while I am checking the stacktrace. Most probably you would have used the optimization flag I think. Check this link - something related.

Try compiling with -g3 remove any optimization flag. Then it might work. HTH!

Property 'value' does not exist on type 'Readonly<{}>'

If you don't want to pass interface state or props model you can try this

class App extends React.Component <any, any>

Configure Log4net to write to multiple files

These answers were helpful, but I wanted to share my answer with both the app.config part and the c# code part, so there is less guessing for the next person.

  <appender name="SomeName" type="log4net.Appender.RollingFileAppender">
    <file value="c:/Console.txt" />
    <appendToFile value="true" />
    <rollingStyle value="Composite" />
    <datePattern value="yyyyMMdd" />
    <maxSizeRollBackups value="10" />
    <maximumFileSize value="1MB" />
  <appender name="Summary" type="log4net.Appender.FileAppender">
    <file value="SummaryFile.log" />
    <appendToFile value="true" />
    <level value="ALL" />
    <appender-ref ref="SomeName" />
  <logger additivity="false" name="Summary">
    <level value="DEBUG"/>
    <appender-ref ref="Summary" />

Then in code:

ILog Log = LogManager.GetLogger("SomeName");
ILog SummaryLog = LogManager.GetLogger("Summary");

Here c:/Console.txt will contain "Processing" ... and \SummaryFile.log will contain "Processing2"

What’s the best way to check if a file exists in C++? (cross platform)

NO REQUIRED, which would be an overkill.

Use stat() (not cross platform though as mentioned by pavon), like this:

#include <sys/stat.h>
#include <iostream>

// true if file exists
bool fileExists(const std::string& file) {
    struct stat buf;
    return (stat(file.c_str(), &buf) == 0);

int main() {
    if(!fileExists("test.txt")) {
        std::cerr << "test.txt doesn't exist, exiting...\n";
        return -1;
    return 0;


C02QT2UBFVH6-lm:~ gsamaras$ ls test.txt
ls: test.txt: No such file or directory
C02QT2UBFVH6-lm:~ gsamaras$ g++ -Wall main.cpp
C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
test.txt doesn't exist, exiting...

Another version (and that) can be found here.

How do you put an image file in a json object?

To upload files directly to Mongo DB you can make use of Grid FS. Although I will suggest you to upload the file anywhere in file system and put the image's url in the JSON object for every entry and then when you call the data for specific object you can call for the image using URL.

Tell me which backend technology are you using? I can give more suggestions based on that.

How do you overcome the svn 'out of date' error?

Are you sure you've checked out the head and not a lower revision? Also, have you done an update to make sure you've got the latest version?

There's a discussion about this on

How to reset Django admin password?

If you forgot create admin user first build one with createsuperuser command on then change the password.

What's the difference between a mock & stub?

A stub is a test double that returns values to the SUT.

A mock is a test double that a test uses to verify that the SUT correctly invokes a dependency.

Also, a mock is often a stub

Add a CSS class to <%= f.submit %>

You can add a class declaration to the submit button of a form by doing the following:

<%= f.submit class: 'btn btn-default' %> <-- Note: there is no comma!

If you are altering a _form.html.erb partial of a scaffold and you want to keep the dynamic change of the button name between controller actions, DO NOT specify a name 'name'.

Without specifying a name and depending on the action the form is rendered the button will get the .class = "btn btn-default" (Bootstrap class)(or whatever .class you specify) with the following names:

  • Update model_name

  • Create model_name
    (where model_name the name of the scaffold's model)

clear data inside text file in c++

Deleting the file will also remove the content. See remove file.

Split string with string as delimiter

I recently discovered an interesting trick that allows to "Split String With String As Delimiter", so I couldn't resist the temptation to post it here as a new answer. Note that "obviously the question wasn't accurate. Firstly, both string1 and string2 can contain spaces. Secondly, both string1 and string2 can contain ampersands ('&')". This method correctly works with the new specifications (posted as a comment below Stephan's answer).

@echo off

set "str=string1&with spaces by string2&with spaces.txt"

set "string1=%str: by =" & set "string2=%"
set "string2=%string2:.txt=%"

echo "%string1%"
echo "%string2%"

For further details on the split method, see this post.

Checking length of dictionary object

This question is confusing. A regular object, {} doesn't have a length property unless you're intending to make your own function constructor which generates custom objects which do have it ( in which case you didn't specify ).

Meaning, you have to get the "length" by a statement on the object, since length is not set, and increment a counter.

I'm confused as to why you need the length. Are you manually setting 0 on the object, or are you relying on custom string keys? eg obj['foo'] = 'bar';. If the latter, again, why the need for length?

Edit #1: Why can't you just do this?

list = [ {name:'john'}, {name:'bob'} ];

Then iterate over list? The length is already set.

Convert char* to string C++

char *charPtr = "test string";
cout << charPtr << endl;

string str = charPtr;
cout << str << endl;

Combine Points with lines with ggplot2

The following example using the iris dataset works fine:

dat = melt(subset(iris, select = c("Sepal.Length","Sepal.Width", "Species")),
      id.vars = "Species")
ggplot(aes(x = 1:nrow(iris), y = value, color = variable), data = dat) +  
      geom_point() + geom_line()

enter image description here

Splitting string with pipe character ("|")

| is a metacharacter in regex. You'd need to escape it:

String[] value_split = rat_values.split("\\|");

Hash function that produces short hashes?

You can use the hashlib library for Python. The shake_128 and shake_256 algorithms provide variable length hashes. Here's some working code (Python3):

import hashlib
>>> my_string = 'hello shake'
>>> hashlib.shake_256(my_string.encode()).hexdigest(5)

Notice that with a length parameter x (5 in example) the function returns a hash value of length 2x.

Associating existing Eclipse project with existing SVN repository

I just wanted to add that if you don't see Team -> Share project, it's likely you have to remove the project from the workspace before importing it back in. This is what happened to me, and I had to remove and readd it to the workspace for it to fix itself. (This happened when moving from dramatically different Eclipse versions + plugins using the same workspace.)

subclipse not showing "share project" option on project context menu in eclipse

Getting a File's MD5 Checksum in Java

Another implementation: Fast MD5 Implementation in Java

String hash = MD5.asHex(MD5.getHash(new File(filename)));

The total number of locks exceeds the lock table size

It is worth saying that the figure used for this setting is in BYTES - found that out the hard way!

Add regression line equation and R^2 on graph

I changed a few lines of the source of stat_smooth and related functions to make a new function that adds the fit equation and R squared value. This will work on facet plots too!

df = data.frame(x = c(1:100))
df$y = 2 + 5 * df$x + rnorm(100, sd = 40)
df$class = rep(1:2,50)
ggplot(data = df, aes(x = x, y = y, label=y)) +
  stat_smooth_func(geom="text",method="lm",hjust=0,parse=TRUE) +
  geom_smooth(method="lm",se=FALSE) +
  geom_point() + facet_wrap(~class)

enter image description here

I used the code in @Ramnath's answer to format the equation. The stat_smooth_func function isn't very robust, but it shouldn't be hard to play around with it. Try updating ggplot2 if you get an error.

Convert np.array of type float64 to type uint8 scaling values

Considering that you are using OpenCV, the best way to convert between data types is to use normalize function.

img_n = cv2.normalize(src=img, dst=None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)

However, if you don't want to use OpenCV, you can do this in numpy

def convert(img, target_type_min, target_type_max, target_type):
    imin = img.min()
    imax = img.max()

    a = (target_type_max - target_type_min) / (imax - imin)
    b = target_type_max - a * imax
    new_img = (a * img + b).astype(target_type)
    return new_img

And then use it like this

imgu8 = convert(img16u, 0, 255, np.uint8)

This is based on the answer that I found on crossvalidated board in comments under this solution

How can I delete all of my Git stashes at once?

if you want to remove the latest stash or at any particular index -

git stash drop type_your_index

> git stash list

  stash@{0}: abc
  stash@{1}: xyz
  stash@{1}: pqr

> git stash drop 0

  Dropped refs/stash@{0}

> git stash list

  stash@{0}: xyz
  stash@{1}: pqr

if you want to remove all the stash at once -

> git stash clear

> git stash list

Warning : Once done you can not revert back your stash

Return a value of '1' a referenced cell is empty

Compare the cell with "" (empty line):


Illegal string offset Warning PHP

Just incase it helps anyone, I was getting this error because I forgot to unserialize a serialized array. That's definitely something I would check if it applies to your case.

How do I install a module globally using npm?

If you want to install a npm module globally, make sure to use the new -g flag, for example:

npm install forever -g

The general recommendations concerning npm module installation since 1.0rc (taken from

  • If you’re installing something that you want to use in your program, using require('whatever'), then install it locally, at the root of your project.
  • If you’re installing something that you want to use in your shell, on the command line or something, install it globally, so that its binaries end up in your PATH environment variable.

I just recently used this recommendations and it went down pretty smoothly. I installed forever globally (since it is a command line tool) and all my application modules locally.

However, if you want to use some modules globally (i.e. express or mongodb), take this advice (also taken from

Of course, there are some cases where you want to do both. Coffee-script and Express both are good examples of apps that have a command line interface, as well as a library. In those cases, you can do one of the following:

  • Install it in both places. Seriously, are you that short on disk space? It’s fine, really. They’re tiny JavaScript programs.
  • Install it globally, and then npm link coffee-script or npm link express (if you’re on a platform that supports symbolic links.) Then you only need to update the global copy to update all the symlinks as well.

The first option is the best in my opinion. Simple, clear, explicit. The second is really handy if you are going to re-use the same library in a bunch of different projects. (More on npm link in a future installment.)

I did not test one of those variations, but they seem to be pretty straightforward.

How to launch html using Chrome at "--allow-file-access-from-files" mode?

As of this writing, in OS X, it will usually look like this

"/Applications/Google Chrome" --allow-file-access-from-files

If you are a freak like me, and put your apps in ~/Applications, then it will be

"/Users/yougohere/Applications/Google Chrome" --allow-file-access-from-files

If neither of those are working, then type chrome://version in your Chrome address bar, and it will tell you what "command line" invocation you should be using. Just add --allow-file-access-from-files to that.

Half circle with CSS (border, outline only)

I use a percentage method to achieve

        border: 3px solid rgb(1, 1, 1);
        border-top-left-radius: 100% 200%;
        border-top-right-radius: 100% 200%;

How to work with progress indicator in flutter?

I suggest to use this plugin flutter_easyloading

flutter_easyloading is clean and lightweight Loading widget for Flutter App, easy to use without context, support iOS and Android

Add this to your package's pubspec.yaml file:

  flutter_easyloading: ^2.0.0

Now in your Dart code, you can use:

import 'package:flutter_easyloading/flutter_easyloading.dart';

To use First, initialize FlutterEasyLoading in MaterialApp/CupertinoApp

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter EasyLoading',
      theme: ThemeData(
      home: MyHomePage(title: 'Flutter EasyLoading'),
      builder: EasyLoading.init(),

EasyLoading is a singleton, so you can custom loading style any where like this:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import './custom_animation.dart';

void main() {

void configLoading() {
    ..displayDuration = const Duration(milliseconds: 2000)
    ..indicatorType = EasyLoadingIndicatorType.fadingCircle
    ..loadingStyle = EasyLoadingStyle.dark
    ..indicatorSize = 45.0
    ..radius = 10.0
    ..progressColor = Colors.yellow
    ..backgroundColor =
    ..indicatorColor = Colors.yellow
    ..textColor = Colors.yellow
    ..maskColor =
    ..userInteractions = true
    ..customAnimation = CustomAnimation();

Then, use per your requirement

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:dio/dio.dart';

class TestPage extends StatefulWidget {
  _TestPageState createState() => _TestPageState();

class _TestPageState extends State<TestPage> {
  void initState() {

  void deactivate() {

  void loadData() async {
    try {;
      Response response = await Dio().get('');
    } catch (e) {

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter EasyLoading'),
      body: Center(
        child: FlatButton(
          child: Text('loadData'),
          onPressed: () {
            // await Future.delayed(Duration(seconds: 2));
            // 'loading...');
            // await Future.delayed(Duration(seconds: 5));
            // EasyLoading.dismiss();

enter image description here

How to make borders collapse (on a div)?

Example of using border-collapse: separate; as

  • container displayed as table:

      display: table;
      border-collapse: separate;
      border-spacing: 1rem;
  • Responsive image map

    The following method works perfectly for me, so here's my full implementation:

    <img id="my_image" style="display: none;" src="my.png" width="924" height="330" border="0" usemap="#map" />
    <map name="map" id="map">
        <area shape="poly" coords="774,49,810,21,922,130,920,222,894,212,885,156,874,146" href="#mylink" />
        <area shape="poly" coords="649,20,791,157,805,160,809,217,851,214,847,135,709,1,666,3" href="#myotherlink" />
        var image_is_loaded = false;
        $("#my_image").on('load',function() {
            $(this).data('width', $(this).attr('width')).data('height', $(this).attr('height'));
            $($(this).attr('usemap')+" area").each(function(){
                $(this).data('coords', $(this).attr('coords'));
            $(this).css('width', '100%').css('height','auto').show();
            image_is_loaded = true;
        function ratioCoords (coords, ratio) {
            coord_arr = coords.split(",");
            for(i=0; i < coord_arr.length; i++) {
                coord_arr[i] = Math.round(ratio * coord_arr[i]);
            return coord_arr.join(',');
        $(window).on('resize', function(){
            if (image_is_loaded) {
                var img = $("#my_image");
                var ratio = img.width()/'width');
                $(img.attr('usemap')+" area").each(function(){
                    console.log('1: '+$(this).attr('coords'));
                    $(this).attr('coords', ratioCoords($(this).data('coords'), ratio));

    Loop through a comma-separated shell variable

    for i in $(echo $TESTSTR | tr ',' '\n')
    echo $i

    I prefer to use tr instead of sed, becouse sed have problems with special chars like \r \n in some cases.

    other solution is to set IFS to certain separator

    Continuous CSS rotation animation on hover, animated back to 0deg on hover out

    It took a few tries, but I was able to get your jsFiddle to work (for Webkit only).

    There's still an issue with the animation speed when the user re-enters the div.

    Basically, just set the current rotation value to a variable, then do some calculations on that value (to convert to degrees), then set that value back to the element on mouse move and mouse enter.

    Check out the jsFiddle:

    Check out this article for more information, including how to add cross-browser compatibility:

    Image Greyscale with CSS & re-color on mouse-over?

    I use the following code on

    Smooth transition from b/w to color with magnifying effect (scale)

        img.color_flip {
          filter: url(filters.svg#grayscale); /* Firefox 3.5+ */
          filter: gray; /* IE5+ */
          -webkit-filter: grayscale(1); /* Webkit Nightlies & Chrome Canary */
          -webkit-transition: all .5s ease-in-out;
        img.color_flip:hover {
          filter: none;
          -webkit-filter: grayscale(0);
          -webkit-transform: scale(1.1);

    Error in if/while (condition) {: missing Value where TRUE/FALSE needed

    The evaluation of condition resulted in an NA. The if conditional must have either a TRUE or FALSE result.

    if (NA) {}
    ## Error in if (NA) { : missing value where TRUE/FALSE needed

    This can happen accidentally as the results of calculations:

    if(TRUE && sqrt(-1)) {}
    ## Error in if (TRUE && sqrt(-1)) { : missing value where TRUE/FALSE needed

    To test whether an object is missing use rather than x == NA.

    See also the related errors:

    Error in if/while (condition) { : argument is of length zero

    Error in if/while (condition) : argument is not interpretable as logical

    if (NULL) {}
    ## Error in if (NULL) { : argument is of length zero
    if ("not logical") {}
    ## Error: argument is not interpretable as logical
    if (c(TRUE, FALSE)) {}
    ## Warning message:
    ## the condition has length > 1 and only the first element will be used

    How to copy marked text in notepad++

    This is similar to

    I hope you are trying to extract :
    "System Stability"

    Here is the way - Step 1/3: Open Search->Find->Replace Tab , select Regular Expression Radio button. Enter in Find what : (\"[a-zA-Z0-9\s]+\") and in Replace with : \n\1 and click Replace All buttton. Before Clicking Replace All

    Step 2/3: After first step your keywords will be in next lines.(as shown in next image). Now go to Mark tab and enter the same regex expression in Find what: Field. Put check mark on Bookmark Line. Then Click Mark All. Bookmark the lines

    Step 3/3 : Goto Search -> Bookmarks -> Remove unmarked lines.Remove Unmarked lines

    So you have the final result as belowFinal Result

    Command-line tool for finding out who is locking a file

    Handle didn't find that WhatsApp is holding lock on a file .tmp.node in temp folder. ProcessExplorer - Find works better Look at this answer

    Why doesn't JUnit provide assertNotEquals methods?

    Usually I do this when I expect two objects to be equal:




    when they are expected to be unequal. I am aware that this not an answer to your question but it is the closest I can get. It could help others searching for what they can do in JUnit versions before JUnit 4.11.

    How to disable 'X-Frame-Options' response header in Spring Security?

    If using XML configuration you can use

    <beans xmlns="" 
             <security:frame-options disabled="true"></security:frame-options>

    ImportError: No module named six

    For me the issue wasn't six but rst2pdf itself. head -1 $(which rst2pdf) (3.8) didn't match python3 --version (3.9). My solution:

    pip3 install rst2pdf

    Excel: Can I create a Conditional Formula based on the Color of a Cell?

    Unfortunately, there is not a direct way to do this with a single formula. However, there is a fairly simple workaround that exists.

    On the Excel Ribbon, go to "Formulas" and click on "Name Manager". Select "New" and then enter "CellColor" as the "Name". Jump down to the "Refers to" part and enter the following:


    Hit OK then close the "Name Manager" window.

    Now, in cell A1 enter the following:


    This will return FQS for red and SM for yellow. For any other color the cell will remain blank.

    ***If the value in A1 doesn't update, hit 'F9' on your keyboard to force Excel to update the calculations at any point (or if the color in B2 ever changes).

    Below is a reference for a list of cell fill colors (there are 56 available) if you ever want to expand things:



    The formula used in Name Manager can be further simplified if it helps your understanding of how it works (the version that I included above is a lot more flexible and is easier to use in checking multiple cell references when copied around as it uses its own cell address as a reference point instead of specifically targeting cell B2).

    Either way, if you'd like to simplify things, you can use this formula in Name Manager instead:


    Difference between two numpy arrays in python

    You can also use numpy.subtract

    It has the advantage over the difference operator, -, that you do not have to transform the sequences (list or tuples) into a numpy arrays — you save the two commands:

    array1 = np.array([1.1, 2.2, 3.3])
    array2 = np.array([1, 2, 3])

    Example: (Python 3.5)

    import numpy as np
    result = np.subtract([1.1, 2.2, 3.3], [1, 2, 3])
    print ('the difference =', result)

    which gives you

    the difference = [ 0.1  0.2  0.3]

    Remember, however, that if you try to subtract sequences (lists or tuples) with the - operator you will get an error. In this case, you need the above commands to transform the sequences in numpy arrays

    Wrong Code:

    print([1.1, 2.2, 3.3] - [1, 2, 3])

    FPDF utf-8 encoding (HOW-TO)

    just edit the function cell in the fpdf.php file, look for the line that looks like this

    function cell ($w, $h = 0, $txt = '', $border = 0, $ln = 0, $align = '', $fill = false, $link = '')

    after finding the line

    write after the {,

    $txt = utf8_decode($txt);

    save the file and ready, the accents and the utf8 encoding will be working :)

    Beamer: How to show images as step-by-step images

    This is a sample code I used to counter the problem.

    \begin{frame}{Topic 1}
    Topic of the figures
    \only<1>{\subfloat[Fig. 1]{\includegraphics{figure1.jpg}}}
    \only<2>{\subfloat[Fig. 2]{\includegraphics{figure2.jpg}}}
    \only<3>{\subfloat[Fig. 3]{\includegraphics{figure3.jpg}}}

    How to access host port from docker container

    I created a docker container for doing exactly that

    You can then simply use container name dns to access host system e.g. curl http://dockerhost:9200

    Parse RSS with jQuery

    jFeed is somewhat obsolete, working only with older versions of jQuery. It has been two years since it was updated.

    zRSSFeed is perhaps a little less flexible, but it is easy to use, and it works with the current version of jQuery (currently 1.4).

    Here's a quick example from the zRSSFeed docs:

    <div id="test"><div>
    <script type="text/javascript">
    $(document).ready(function () {
      $('#test').rssfeed('', {
        limit: 5

    Getting an "ambiguous redirect" error

    This might be the case too.

    you have not specified the file in a variable and redirecting output to it, then bash will throw this error.

    out_file = /path/to/output_file.t
    for i in `echo "$files"`;
        content=`cat $i` 
        echo "${content}  ${i}" >> ${out_file}

    out_file variable is not set up correctly so keep an eye on this too. BTW this code is printing all the content and its filename on the console.

    How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer?

    In some cases, DateTime.MinValue (or equivalenly, default(DateTime)) is used to indicate an unknown value.

    This simple extension method can help handle such situations:

    public static class DbDateHelper
        /// <summary>
        /// Replaces any date before 01.01.1753 with a Nullable of 
        /// DateTime with a value of null.
        /// </summary>
        /// <param name="date">Date to check</param>
        /// <returns>Input date if valid in the DB, or Null if date is 
        /// too early to be DB compatible.</returns>
        public static DateTime? ToNullIfTooEarlyForDb(this DateTime date)
            return (date >= (DateTime) SqlDateTime.MinValue) ? date : (DateTime?)null;


     DateTime? dateToPassOnToDb = tooEarlyDate.ToNullIfTooEarlyForDb();

    C++ JSON Serialization

    Not yet mentioned, though it was the first in my search result:

    Perks listed:

    • Intuitive syntax (looks great!)
    • Single header file to include, nothing else
    • Ridiculously tested

    Also, it's under the MIT License.

    I'll be honest: I have yet to use it, but through some experience I have a knack for determining when I come across a really well-made c++ library.

    Plot multiple boxplot in one graph

    You should get your data in a specific format by melting your data (see below for how melted data looks like) before you plot. Otherwise, what you have done seems to be okay.

    df <- read.csv("TestData.csv", header=T)
    # melting by "Label". `melt is from the reshape2 package. 
    # do ?melt to see what other things it can do (you will surely need it)
    df.m <- melt(df, id.var = "Label")
    > df.m # pasting some rows of the melted data.frame
    #     Label variable      value
    # 1    Good       F1 0.64778924
    # 2    Good       F1 0.54608791
    # 3    Good       F1 0.46134200
    # 4    Good       F1 0.79421221
    # 5    Good       F1 0.56919951
    # 6    Good       F1 0.73568570
    # 7    Good       F1 0.65094207
    # 8    Good       F1 0.45749702
    # 9    Good       F1 0.80861929
    # 10   Good       F1 0.67310067
    # 11   Good       F1 0.68781739
    # 12   Good       F1 0.47009455
    # 13   Good       F1 0.95859182
    # 14   Good       F1 1.00000000
    # 15   Good       F1 0.46908343
    # 16    Bad       F1 0.57875528
    # 17    Bad       F1 0.28938046
    # 18    Bad       F1 0.68511766
    ggplot(data = df.m, aes(x=variable, y=value)) + geom_boxplot(aes(fill=Label))


    Edit: I realise that you might need to facet. Here's an implementation of that as well:

    p <- ggplot(data = df.m, aes(x=variable, y=value)) + 
    p + facet_wrap( ~ variable, scales="free")


    Edit 2: How to add x-labels, y-labels, title, change legend heading, add a jitter?

    p <- ggplot(data = df.m, aes(x=variable, y=value)) 
    p <- p + geom_boxplot(aes(fill=Label))
    p <- p + geom_jitter()
    p <- p + facet_wrap( ~ variable, scales="free")
    p <- p + xlab("x-axis") + ylab("y-axis") + ggtitle("Title")
    p <- p + guides(fill=guide_legend(title="Legend_Title"))


    Edit 3: How to align geom_point() points to the center of box-plot? It could be done using position_dodge. This should work.

    p <- ggplot(data = df.m, aes(x=variable, y=value)) 
    p <- p + geom_boxplot(aes(fill = Label))
    # if you want color for points replace group with colour=Label
    p <- p + geom_point(aes(y=value, group=Label), position = position_dodge(width=0.75))
    p <- p + facet_wrap( ~ variable, scales="free")
    p <- p + xlab("x-axis") + ylab("y-axis") + ggtitle("Title")
    p <- p + guides(fill=guide_legend(title="Legend_Title"))


    Error occurred during initialization of boot layer FindException: Module not found

    I had the same issue and I fixed it this way:

    1. Deleted all projects from eclipse, not from the computer.
    2. Created a new project and as soon as you write the name of your project, you get another window, in which is written: "Create". I just clicked "don't create".
    3. Created a package. Let us call the package mywork.
    4. Created a Java class inside the package myWork. Let us call the class HelloWorld.
    5. I run the file normally and it was working fine.

    Note: First, make sure that Java is running properly using the CMD command in that way you will understand the problem is on eclipse and not on JDK.

    Could not connect to React Native development server on Android

    I got the same problem and resolve it by deleting node module package and then again install yarn. Simply on some changes we need to clear our.

    Comparing HTTP and FTP for transferring files

    Both of them uses TCP as a transport protocol, but HTTP uses a persistent connection, which makes the performance of the TCP better.

    How to create windows service from java jar?

    With procrun you need to copy prunsrv to the application directory (download), and create an install.bat like this:

    set PR_PATH=%CD%
    SET PR_JAR=MyService.jar
    SET STOP_CLASS=java.lang.System
    rem ; separated values
    rem ; separated values
    SET JVM_OPTIONS=-Dapp.home=%PR_PATH%
    prunsrv.exe //IS//%PR_SERVICE_NAME% --Install="%PR_PATH%\prunsrv.exe" --Jvm=auto --Startup=auto --StartMode=jvm --StartClass=%START_CLASS% --StartMethod=%START_METHOD% --StopMode=jvm --StopClass=%STOP_CLASS% --StopMethod=%STOP_METHOD% ++StopParams=%STOP_PARAMS% --Classpath="%PR_PATH%\%PR_JAR%" --DisplayName="%PR_SERVICE_NAME%" ++JvmOptions=%JVM_OPTIONS%

    I presume to

    • run this from the same directory where the jar and prunsrv.exe is
    • the jar has its working MANIFEST.MF
    • and you have shutdown hooks registered into JVM (for example with context.registerShutdownHook() in Spring)...
    • not using relative paths for files outside the jar (for example log4j should be used with log4j.appender.X.File=${app.home}/logs/my.log or something alike)

    Check the procrun manual and this tutorial for more information.

    Bash command to sum a column of numbers

    while read -r num; do ((sum += num)); done < inputfile; echo $sum

    how to make UITextView height dynamic according to text length?

    Swift 5, Use extension:

    extension UITextView {
        func adjustUITextViewHeight() {
            self.translatesAutoresizingMaskIntoConstraints = true
            self.isScrollEnabled = false



    And don't care about the height of texeView in the storyboard (just use a constant at first)

    Assign command output to variable in batch file

    This post has a method to achieve this

    from (zvrba) You can do it by redirecting the output to a file first. For example:

    echo zz > bla.txt
    set /p VV=<bla.txt
    echo %VV%

    Eclipse: Error ".. overlaps the location of another project.." when trying to create new project

    I know this is older, but wanted to contribute another possibly solution.

    If you want to keep the project location, as I did, I found that copying the .project file from another project into the project's directory, then editing the .project file to name it properly, then choosing the Import Existing Projects into Workspace option worked for me.

    In Windows, I used a file monitor to see what Eclipse was doing, and it was simply erroring out for some unknown reason when trying to create the .project file. So, I did that manually and it worked for me.

    How to return data from PHP to a jQuery ajax call

    I figured it out. Need to use echo in PHP instead of return.

      $output = some_function();
      echo $output;

    And the jQ:

    success: function(data) {

    Get child node index

    Use binary search algorithm to improve the performace when the node has large quantity siblings.

    function getChildrenIndex(ele){
        //IE use Element.sourceIndex
            var eles = ele.parentNode.children;
            var low = 0, high = eles.length-1, mid = 0;
            var esi = ele.sourceIndex, nsi;
            //use binary search algorithm
            while (low <= high) {
                mid = (low + high) >> 1;
                nsi = eles[mid].sourceIndex;
                if (nsi > esi) {
                    high = mid - 1;
                } else if (nsi < esi) {
                    low = mid + 1;
                } else {
                    return mid;
        //other browsers
        var i=0;
        while(ele = ele.previousElementSibling){
        return i;

    How to run multiple sites on one apache instance

    Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.

    Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.

    The best documentation you'll find on the topic is the virtual host documentation in the apache manual.

    There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.

    The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost entry for each port.

    Assuming you're starting from scratch, this is much simpler than it may seem.

    If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.

    NameVirtualHost *:80

    If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost directive, and it will be removed in a future version.

    Now your vhost definitions:

    <VirtualHost *:80>
        DocumentRoot "/home/user/site1/"
        ServerName site1
    <VirtualHost *:80>
        DocumentRoot "/home/user/site2/"
        ServerName site2

    You can run as many sites as you want on the same port. The ServerName being different is enough to tell Apache which vhost to use. Also, the ServerName directive is always the domain/hostname and should never include a path.

    If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to you would have to go to

    How can I generate a self-signed certificate with SubjectAltName using OpenSSL?

    Can someone help me with the exact syntax?

    It's a three-step process, and it involves modifying the openssl.cnf file. You might be able to do it with only command line options, but I don't do it that way.

    Find your openssl.cnf file. It is likely located in /usr/lib/ssl/openssl.cnf:

    $ find /usr/lib -name openssl.cnf

    On my Debian system, /usr/lib/ssl/openssl.cnf is used by the built-in openssl program. On recent Debian systems it is located at /etc/ssl/openssl.cnf

    You can determine which openssl.cnf is being used by adding a spurious XXX to the file and see if openssl chokes.

    First, modify the req parameters. Add an alternate_names section to openssl.cnf with the names you want to use. There are no existing alternate_names sections, so it does not matter where you add it.

    [ alternate_names ]
    DNS.1        =
    DNS.2        =
    DNS.3        =
    DNS.4        =

    Next, add the following to the existing [ v3_ca ] section. Search for the exact string [ v3_ca ]:

    subjectAltName      = @alternate_names

    You might change keyUsage to the following under [ v3_ca ]:

    keyUsage = digitalSignature, keyEncipherment

    digitalSignature and keyEncipherment are standard fare for a server certificate. Don't worry about nonRepudiation. It's a useless bit thought up by computer science guys/gals who wanted to be lawyers. It means nothing in the legal world.

    In the end, the IETF (RFC 5280), browsers and CAs run fast and loose, so it probably does not matter what key usage you provide.

    Second, modify the signing parameters. Find this line under the CA_default section:

    # Extension copying option: use with caution.
    # copy_extensions = copy

    And change it to:

    # Extension copying option: use with caution.
    copy_extensions = copy

    This ensures the SANs are copied into the certificate. The other ways to copy the DNS names are broken.

    Third, generate your self-signed certificate:

    $ openssl genrsa -out private.key 3072
    $ openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730
    You are about to be asked to enter information that will be incorporated
    into your certificate request.
    What you are about to enter is what is called a Distinguished Name or a DN.

    Finally, examine the certificate:

    $ openssl x509 -in certificate.pem -text -noout
            Version: 3 (0x2)
            Serial Number: 9647297427330319047 (0x85e215e5869042c7)
        Signature Algorithm: sha256WithRSAEncryption
            Issuer: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
                Not Before: Feb  1 05:23:05 2014 GMT
                Not After : Feb  1 05:23:05 2016 GMT
            Subject: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
            Subject Public Key Info:
                Public Key Algorithm: rsaEncryption
                    Public-Key: (3072 bit)
                    Exponent: 65537 (0x10001)
            X509v3 extensions:
                X509v3 Subject Key Identifier:
                X509v3 Authority Key Identifier:
                X509v3 Basic Constraints: critical
                X509v3 Key Usage:
                    Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign
                X509v3 Subject Alternative Name:
        Signature Algorithm: sha256WithRSAEncryption

    How do you properly use namespaces in C++?


    Yes, you can use several namespaces at a time, eg:

    using namespace boost;   
    using namespace std;  
    shared_ptr<int> p(new int(1));   // shared_ptr belongs to boost   
    cout << "cout belongs to std::" << endl;   // cout and endl are in std

    [Feb. 2014 -- (Has it really been that long?): This particular example is now ambiguous, as Joey points out below. Boost and std:: now each have a shared_ptr.]

    JavaScript object: access variable property by name as string

    Since I was helped with my project by the answer above (I asked a duplicate question and was referred here), I am submitting an answer (my test code) for bracket notation when nesting within the var:

      <script type="text/javascript">_x000D_
        function displayFile(whatOption, whatColor) {_x000D_
          var Test01 = {_x000D_
            rectangle: {_x000D_
              red: "RectangleRedFile",_x000D_
              blue: "RectangleBlueFile"_x000D_
            square: {_x000D_
              red: "SquareRedFile",_x000D_
              blue: "SquareBlueFile"_x000D_
          var filename = Test01[whatOption][whatColor];_x000D_
      <p onclick="displayFile('rectangle', 'red')">[ Rec Red ]</p>_x000D_
      <p onclick="displayFile('square', 'blue')">[ Sq Blue ]</p>_x000D_
      <p onclick="displayFile('square', 'red')">[ Sq Red ]</p>_x000D_

    Make a phone call programmatically

    The answers here are perfectly working. I am just converting Craig Mellon answer to Swift. If someone comes looking for swift answer, this will help them.

     var phoneNumber: String = "telprompt://".stringByAppendingString(titleLabel.text!) // titleLabel.text has the phone number.

    How do I get ruby to print a full backtrace instead of a truncated one?

    IRB has a setting for this awful "feature", which you can customize.

    Create a file called ~/.irbrc that includes the following line:

    IRB.conf[:BACK_TRACE_LIMIT] = 100

    This will allow you to see 100 stack frames in irb, at least. I haven't been able to find an equivalent setting for the non-interactive runtime.

    Detailed information about IRB customization can be found in the Pickaxe book.

    Looking for simple Java in-memory cache

    Try this:

    import java.util.*;
    public class SimpleCacheManager {
        private static SimpleCacheManager instance;
        private static Object monitor = new Object();
        private Map<String, Object> cache = Collections.synchronizedMap(new HashMap<String, Object>());
        private SimpleCacheManager() {
        public void put(String cacheKey, Object value) {
            cache.put(cacheKey, value);
        public Object get(String cacheKey) {
            return cache.get(cacheKey);
        public void clear(String cacheKey) {
            cache.put(cacheKey, null);
        public void clear() {
        public static SimpleCacheManager getInstance() {
            if (instance == null) {
                synchronized (monitor) {
                    if (instance == null) {
                        instance = new SimpleCacheManager();
            return instance;

    nodejs - first argument must be a string or Buffer - when using response.write with http.request

    response.statusCode is a number, e.g. response.statusCode === 200, not '200'. As the error message says, write expects a string or Buffer object, so you must convert it.


    You are also correct about your callback comment though. res.end(); should be inside the callback, just below your write calls.

    Difference between OpenJDK and Adoptium/AdoptOpenJDK

    Update: AdoptOpenJDK has changed its name to Adoptium, as part of its move to the Eclipse Foundation.

    OpenJDK ? source code
    Adoptium/AdoptOpenJDK ? builds

    Difference between OpenJDK and AdoptOpenJDK

    The first provides source-code, the other provides builds of that source-code.

    Several vendors of Java & OpenJDK

    Adoptium of the Eclipse Foundation, formerly known as AdoptOpenJDK, is only one of several vendors distributing implementations of the Java platform. These include:

    • Eclipse Foundation (Adoptium/AdoptOpenJDK)
    • Azul Systems
    • Oracle
    • Red Hat / IBM
    • BellSoft
    • SAP
    • Amazon AWS
    • … and more

    See this flowchart of mine to help guide you in picking a vendor for an implementation of the Java platform. Click/tap to zoom.

    Flowchart guiding you in choosing a vendor for a Java 11 implementation

    Another resource: This comparison matrix by Azul Systems is useful, and seems true and fair to my mind.

    Here is a list of considerations and motivations to consider in choosing a vendor and implementation.

    Motivations in choosing a vendor for Java

    Some vendors offer you a choice of JIT technologies.

    Diagram showing history of HotSpot & JRockit merging, and OpenJ9 both available in AdoptOpenJDK

    To understand more about this Java ecosystem, read Java Is Still Free

    Why is "cursor:pointer" effect in CSS not working

    My problem was using cursor: 'pointer' mistakenly instead of cursor: pointer. So, make sure you are not adding single or double quotes around pointer.

    Error when trying to access XAMPP from a network

    This answer is for XAMPP on Ubuntu.

    The manual for installation and download is on (site official)

    After to start XAMPP simply call this command:

    sudo /opt/lampp/lampp start

    You should now see something like this on your screen:

    Starting XAMPP 1.8.1...
    LAMPP: Starting Apache...
    LAMPP: Starting MySQL...
    LAMPP started.

    If you have this

    Starting XAMPP for Linux 1.8.1...                                                             
    XAMPP: Another web server daemon is already running.                                          
    XAMPP: Another MySQL daemon is already running.                                               
    XAMPP: Starting ProFTPD...                                                                    
    XAMPP for Linux started

    . The solution is

    sudo /etc/init.d/apache2 stop
    sudo /etc/init.d/mysql stop

    And the restast with sudo //opt/lampp/lampp restart

    You to fix most of the security weaknesses simply call the following command:

    /opt/lampp/lampp security

    After the change this file

    sudo kate //opt/lampp/etc/extra/httpd-xampp.conf

    Find and replace on

    # New XAMPP security concept
    <LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
        Order deny,allow
        Deny from all
        Allow from ::1 
        Allow from all
        #   fc00::/7 \
        #   fe80::/10
        ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var

    ORA-00932: inconsistent datatypes: expected - got CLOB

    You can't put a CLOB in the WHERE clause. From the documentation:

    Large objects (LOBs) are not supported in comparison conditions. However, you can use PL/SQL programs for comparisons on CLOB data.

    If your values are always less than 4k, you can use:

       SET TEST_Category           = 'just testing'  
     WHERE to_char(TEST_SCRIPT)    = 'something'
       AND ID                      = '10000239';

    It is strange to search by a CLOB anyways.. could you not just search by the ID column?

    Installation Issue with matplotlib Python

    Problem Cause

    In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.


    • I assume you have installed the pip matplotlib, there is a directory in your root called ~/.matplotlib.
    • Create a file ~/.matplotlib/matplotlibrc there and add the following code: backend: TkAgg

    From this link you can try different diagrams.

    Installing the Android USB Driver in Windows 7

    Just download and install "Samsung Kies" from this link. and everything would work as required.

    Before installing, uninstall the drivers you have installed for your device.


    Two possible solutions:

    1. Try with the Google USB driver which comes with the SDK.
    2. Download and install the Samsung USB driver from this link as suggested by Mauricio Gracia Gutierrez

    Get file content from URL?

    $url = "https://chart.googleapis....";
    $json = file_get_contents($url);

    Now you can either echo the $json variable, if you just want to display the output, or you can decode it, and do something with it, like so:

    $data = json_decode($json);

    How to convert/parse from String to char in java?

    You can do the following:

    String str = "abcd";
    char arr[] = new char[len]; // len is the length of the array
    arr = str.toCharArray();

    What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

    In my case (nginx on windows proxying an app while serving static assets on its own) page was showing multiple assets including 14 bigger pictures; those errors were shown for about 5 of those images exactly after 60 seconds; in my case it was a default send_timeout of 60s making those image requests fail; increasing the send_timeout made it work

    I am not sure what is causing nginx on windows to serve those files so slow - it is only 11.5MB of resources which takes nginx almost 2 minutes to serve but I guess it is subject for another thread

    How to get rid of `deprecated conversion from string constant to ‘char*’` warnings in GCC?

    Why don't you use the -Wno-deprecated option to ignore deprecated warning messages?

    Using AJAX to pass variable to PHP and retrieve those using AJAX again

    In your PhP file there's going to be a variable called $_REQUEST and it contains an array with all the data send from Javascript to PhP using AJAX.

    Try this: var_dump($_REQUEST); and check if you're receiving the values.

    no match for ‘operator<<’ in ‘std::operator

    You need to overload operator << for mystruct class

    Something like :-

    friend ostream& operator << (ostream& os, const mystruct& m)
        os << m.m_a <<" " << m.m_b << endl;
        return os ;

    See here

    View more than one project/solution in Visual Studio

    There is a way to store multiple solutions in one instance of VS.

    Attempt the following steps:

    1. File > Open > Project/Solution
    2. This will bring up the open project window, notice at the bottom where it says options, select add to solution

    Add to Solution

    1. Then select the file you want to add and click open
    2. This will then add the solution to your project. You still won't be able to run the same project in a single instance of VS, but you can have all your code organized in one place.

    NOTE: This worked for Visual Studio 2013 Professional

    Adding and reading from a Config file

    1. Add an Application Configuration File item to your project (Right -Click Project > Add item). This will create a file called app.config in your project.

    2. Edit the file by adding entries like <add key="keyname" value="someValue" /> within the <appSettings> tag.

    3. Add a reference to the System.Configuration dll, and reference the items in the config using code like ConfigurationManager.AppSettings["keyname"].

    JavaScript get clipboard data on paste event (Cross browser)

    Simple version:

    document.querySelector('[contenteditable]').addEventListener('paste', (e) => {
        const text = (e.originalEvent || e).clipboardData.getData('text/plain');
        window.document.execCommand('insertText', false, text);

    Using clipboardData

    Demo :,output

    Edge, Firefox, Chrome, Safari, Opera tested.

    ? Document.execCommand() is obsolete now.

    Note: Remember to check input/output at server-side also (like PHP strip-tags)

    How to convert Blob to File in JavaScript

    Use saveAs on FileSaver.js github project.

    FileSaver.js implements the saveAs() FileSaver interface in browsers that do not natively support it.

    How do I move a file (or folder) from one folder to another in TortoiseSVN?

    You have to drag the file using the right mouse button. The moment you release the file to the new destination you will observe the option:

    SVN move versioned files here.

    Just select this option and you are done !!

    Can't connect to Postgresql on port 5432

    I had the same problem after a MacOS system upgrade. Solved it by upgrading the postgres with brew. Details: it looks like the system was trying to access Postgres 11 using older Postgres 10 settings. I'm sure it was my mistake somewhere in the past, but luckily it all got sorted out with the upgrade above.

    How to validate domain name in PHP?

    Check the php function checkdnsrr

    function validate_email($email){
       $exp = "^[a-z\'0-9]+([._-][a-z\'0-9]+)*@([a-z0-9]+([._-][a-z0-9]+))+$";
            return true;
            return false;
          return false;

    Convert String to double in Java

    String double_string = "100.215";
    Double double = Double.parseDouble(double_string);

    How to check if smtp is working from commandline (Linux)

    Not sure if this help or not but this is a command line tool which let you simply send test mails from a SMTP server priodically.

    What is a NullReferenceException, and how do I fix it?

    You are using the object that contains the null value reference. So it's giving a null exception. In the example the string value is null and when checking its length, the exception occurred.


    string value = null;
    if (value.Length == 0) // <-- Causes exception
        Console.WriteLine(value); // <-- Never reached

    The exception error is:

    Unhandled Exception:

    System.NullReferenceException: Object reference not set to an instance of an object. at Program.Main()

    How do I refresh the page in ASP.NET? (Let it reload itself by code)

    You can use 2 ways for solve this problem: 1) After the head tag

    <meta http-equiv="refresh" content="600">

    2) If your page hasn't head tag you must use Javascript to implement

    <script type="text/javascript">
      function RefreshPage()

    My contact:

    Use placeholders in yaml

    With Yglu Structural Templating, your example can be written:

    foo: !()
      !? $.propname: 
         type: number 
         default: !? $.default
      !apply .foo: 
        propname: "some_prop"
        default: "some default"

    Disclaimer: I am the author or Yglu.

    Using for loop inside of a JSP

    You concrete problem is caused because you're mixing discouraged and old school scriptlets <% %> with its successor EL ${}. They do not share the same variable scope. The allFestivals is not available in scriptlet scope and the i is not available in EL scope.

    You should install JSTL (<-- click the link for instructions) and declare it in top of JSP as follows:

    <%@taglib prefix="c" uri=""%>

    and then iterate over the list as follows:

    <c:forEach items="${allFestivals}" var="festival">

    (beware of possible XSS attack holes, use <c:out> accordingly)

    Don't forget to remove the <jsp:useBean> as it has no utter value here when you're using a servlet as model-and-view controller. It would only lead to confusion. See also our servlets wiki page. Further you would do yourself a favour to disable scriptlets by the following entry in web.xml so that you won't accidently use them:


    Django: Redirect to previous page after login

    Django's built-in authentication works the way you want.

    Their login pages include a next query string which is the page to return to after login.

    Look at

    Unsupported major.minor version 52.0

    None of these answers helped me, but I found a solution.
    I had a webproject used in Wildfly 8.2, built with Maven, source and target was set to 1.8 on maven-compiler-plugin, as well as all Eclipse and Maven settings were set to Java 1.8. The problem was that Wildfly 8.2 cannot handle Java 1.8, so I had to set everything to 1.7 and it worked.

    How many characters can you store with 1 byte?

    1 byte may hold 1 character. For Example: Refer Ascii values for each character & convert into binary. This is how it works.

    enter image description here value 255 is stored as (11111111) base 2. Visit this link for knowing more about binary conversion.

    Size of Tiny Int = 1 Byte ( -128 to 127)

    Int = 4 Bytes (-2147483648 to 2147483647)

    Property 'catch' does not exist on type 'Observable<any>'

    In angular 8:

    //for catch:
    import { catchError } from 'rxjs/operators';
    //for throw:
    import { Observable, throwError } from 'rxjs';
    //and code should be written like this.
    getEmployees(): Observable<IEmployee[]> {
        return this.http.get<IEmployee[]>(this.url).pipe(catchError(this.erroHandler));
      erroHandler(error: HttpErrorResponse) {
        return throwError(error.message || 'server Error');

    How to insert an item into a key/value pair object?

    Hashtables are not inherently sorted, your best bet is to use another structure such as a SortedList or an ArrayList

    Run cron job only if it isn't already running

    I would recommend to use an existing tool such as monit, it will monitor and auto restart processes. There is more information available here. It should be easily available in most distributions.

    See line breaks and carriage returns in editor

    You can view break lines using gedit editor.

    First, if you don't have installed:

    sudo apt-get install gedit

    Now, install gedit plugins:

    sudo apt-get install gedit-plugins

    and select Draw Spaces plugin, enter on Preferences, and chose Draw new lines

    enter image description here

    enter image description here

    Using VSCode you can install Line endings extension.

    Sublime Text 3 has a plugin called RawLineEdit that will display line endings and allow the insertion of arbitrary line-ending type

    shift + ctrl + p and start type the name of the plugin, and toggle to show line ending.

    How to center a subview of UIView

    I would use: = CGPointMake(CGRectGetMidX(self.parentView.bounds),

    I like to use the CGRect options...

    SWIFT 3: = CGPoint(x: self.parentView.bounds.midX,
                                            y: self.parentView.bounds.midY);

    How can I catch all the exceptions that will be thrown through reading and writing a file?

    While I agree it's not good style to catch a raw Exception, there are ways of handling exceptions which provide for superior logging, and the ability to handle the unexpected. Since you are in an exceptional state, you are probably more interested in getting good information than in response time, so instanceof performance shouldn't be a big hit.

        // IO code
    } catch (Exception e){
        if(e instanceof IOException){
            // handle this exception type
        } else if (e instanceof AnotherExceptionType){
            //handle this one
        } else {
            // We didn't expect this one. What could it be? Let's log it, and let it bubble up the hierarchy.
            throw e;

    However, this doesn't take into consideration the fact that IO can also throw Errors. Errors are not Exceptions. Errors are a under a different inheritance hierarchy than Exceptions, though both share the base class Throwable. Since IO can throw Errors, you may want to go so far as to catch Throwable

        // IO code
    } catch (Throwable t){
        if(t instanceof Exception){
            if(t instanceof IOException){
                // handle this exception type
            } else if (t instanceof AnotherExceptionType){
                //handle this one
            } else {
                // We didn't expect this Exception. What could it be? Let's log it, and let it bubble up the hierarchy.
        } else if (t instanceof Error){
            if(t instanceof IOError){
                // handle this Error
            } else if (t instanceof AnotherError){
                //handle different Error
            } else {
                // We didn't expect this Error. What could it be? Let's log it, and let it bubble up the hierarchy.
        } else {
            // This should never be reached, unless you have subclassed Throwable for your own purposes.
            throw t;

    Close Android Application

    The answer depends on what you mean by "close app". In android's terms its either about an "activity", or a group of activities in a temporal/ancestral order called "task".

    End activity: just call finish()

    End task:

    1. clear activity task-stack
    2. navigate to root activity
    3. then call finish on it.

    This will end the entire "task"

    How to impose maxlength on textArea in HTML using JavaScript

    Update Use Eirik's solution using .live() instead as it is a bit more robust.

    Even though you wanted a solution that wasn't using jQuery, I thought I'd add one in for anyone finding this page via Google and looking for a jQuery-esque solution:

    $(function() {        
        // Get all textareas that have a "maxlength" property.
        $('textarea[maxlength]').each(function() {
            // Store the jQuery object to be more efficient...
            var $textarea = $(this);
            // Store the maxlength and value of the field.
            var maxlength = $textarea.attr('maxlength');
            var val = $textarea.val();
            // Trim the field if it has content over the maxlength.
            $textarea.val(val.slice(0, maxlength));
            // Bind the trimming behavior to the "keyup" event.
            $textarea.bind('keyup', function() {
                $textarea.val($textarea.val().slice(0, maxlength));

    Hope that is useful to you Googlers out there...

    Error when testing on iOS simulator: Couldn't register with the bootstrap server

    This error used to occur in older versions of the iOS Simulator because older instances of a job in another device that was shutting down could collide with the new instance.

    iOS 6.0 and later should not experience issues like this because iOS 6.0 introduced the usage of bootstrap subsets, and iOS 7.0 introduced the usage of a dedicated bootstrap server (launchd_sim) which is completely isolated from the host's bootstrap server.

    Can you force Vue.js to reload/re-render?

    Try to use this.$router.go(0); to manually reload the current page.

    How to get my activity context?

    In Kotlin will be :

    activity?.applicationContext?.let {
             it//<- you context

    Mac OS X - EnvironmentError: mysql_config not found

    Ok, well, first of all, let me check if I am on the same page as you:

    • You installed python
    • You did brew install mysql
    • You did export PATH=$PATH:/usr/local/mysql/bin
    • And finally, you did pip install MySQL-Python (or pip3 install mysqlclient if using python 3)

    If you did all those steps in the same order, and you still got an error, read on to the end, if, however, you did not follow these exact steps try, following them from the very beginning.

    So, you followed the steps, and you're still geting an error, well, there are a few things you could try:

    1. Try running which mysql_config from bash. It probably won't be found. That's why the build isn't finding it either. Try running locate mysql_config and see if anything comes back. The path to this binary needs to be either in your shell's $PATH environment variable, or it needs to be explicitly in the file for the module assuming it's looking in some specific place for that file.

    2. Instead of using MySQL-Python, try using 'mysql-connector-python', it can be installed using pip install mysql-connector-python. More information on this can be found here and here.

    3. Manually find the location of 'mysql/bin', 'mysql_config', and 'MySQL-Python', and add all these to the $PATH environment variable.

    4. If all above steps fail, then you could try installing 'mysql' using MacPorts, in which case the file 'mysql_config' would actually be called 'mysql_config5', and in this case, you would have to do this after installing: export PATH=$PATH:/opt/local/lib/mysql5/bin. You can find more details here.

    Note1: I've seen some people saying that installing python-dev and libmysqlclient-dev also helped, however I do not know if these packages are available on Mac OS.

    Note2: Also, make sure to try running the commands as root.

    I got my answers from (besides my brain) these places (maybe you could have a look at them, to see if it would help): 1, 2, 3, 4.

    I hoped I helped, and would be happy to know if any of this worked, or not. Good luck.

    How to Use Sockets in JavaScript\HTML?

    How to Use Sockets in JavaScript/HTML?

    There is no facility to use general-purpose sockets in JS or HTML. It would be a security disaster, for one.

    There is WebSocket in HTML5. The client side is fairly trivial:

    socket= new WebSocket('ws://');
    socket.onopen= function() {
    socket.onmessage= function(s) {
        alert('got reply '+s);

    You will need a specialised socket application on the server-side to take the connections and do something with them; it is not something you would normally be doing from a web server's scripting interface. However it is a relatively simple protocol; my noddy Python SocketServer-based endpoint was only a couple of pages of code.

    In any case, it doesn't really exist, yet. Neither the JavaScript-side spec nor the network transport spec are nailed down, and no browsers support it.

    You can, however, use Flash where available to provide your script with a fallback until WebSocket is widely available. Gimite's web-socket-js is one free example of such. However you are subject to the same limitations as Flash Sockets then, namely that your server has to be able to spit out a cross-domain policy on request to the socket port, and you will often have difficulties with proxies/firewalls. (Flash sockets are made directly; for someone without direct public IP access who can only get out of the network through an HTTP proxy, they won't work.)

    Unless you really need low-latency two-way communication, you are better off sticking with XMLHttpRequest for now.

    Where to find htdocs in XAMPP Mac

    At least for macbook (os high sierra) go to terminal and type or copy and paste:

    cd ~/.bitnami/stackman/machines/xampp/volumes/root/htdocs

    How do I check when a UITextField changes?

    textField(_:shouldChangeCharactersIn:replacementString:) worked for me in Xcode 8, Swift 3 if you want to check every single keypress.

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        // Whatever code you want to run here.
        // Keep in mind that the textfield hasn't yet been updated,
        // so use 'string' instead of 'textField.text' if you want to
        // access the string the textfield will have after a user presses a key
        var statusText = self.status.text
        var usernameText = self.username.text
        switch textField{
        case self.status:
            statusText = string
        case self.username:
            usernameText = string
        if statusText == "" && usernameText == "" {
            self.topRightButton.enabled = false
        } else {   
            self.topRightButton.enabled = true
        //Return false if you don't want the textfield to be updated
        return true