Programs & Examples On #Bluedragon

BlueDragon is an alternative to ColdFusion, providing an environment to develop CFML-based applications. NOTE: It is useful to also use the `coldfusion` tag for any BlueDragon questions that focus on CFML syntax/language.

Getting list of tables, and fields in each, in a database


Is there any way to change input type="date" format?

As previously mentioned it is officially not possible to change the format. However it is possible to style the field, so (with a little JS help) it displays the date in a format we desire. Some of the possibilities to manipulate the date input is lost this way, but if the desire to force the format is greater, this solution might be a way. A date fields stays only like that:

<input type="date" data-date="" data-date-format="DD MMMM YYYY" value="2015-08-09">

The rest is a bit of CSS and JS:

$("input").on("change", function() {_x000D_
        moment(this.value, "YYYY-MM-DD")_x000D_
        .format( this.getAttribute("data-date-format") )_x000D_
input {_x000D_
    position: relative;_x000D_
    width: 150px; height: 20px;_x000D_
    color: white;_x000D_
input:before {_x000D_
    position: absolute;_x000D_
    top: 3px; left: 3px;_x000D_
    content: attr(data-date);_x000D_
    display: inline-block;_x000D_
    color: black;_x000D_
input::-webkit-datetime-edit, input::-webkit-inner-spin-button, input::-webkit-clear-button {_x000D_
    display: none;_x000D_
input::-webkit-calendar-picker-indicator {_x000D_
    position: absolute;_x000D_
    top: 3px;_x000D_
    right: 0;_x000D_
    color: black;_x000D_
    opacity: 1;_x000D_
<script src=""></script>_x000D_
<script src=""></script>_x000D_
<input type="date" data-date="" data-date-format="DD MMMM YYYY" value="2015-08-09">

It works nicely on Chrome for desktop, and Safari on iOS (especially desirable, since native date manipulators on touch screens are unbeatable IMHO). Didn't check for others, but don't expect to fail on any Webkit.

How to create JSON Object using String?

JSONArray may be what you want.

String message;
JSONObject json = new JSONObject();
json.put("name", "student");

JSONArray array = new JSONArray();
JSONObject item = new JSONObject();
item.put("information", "test");
item.put("id", 3);
item.put("name", "course1");

json.put("course", array);

message = json.toString();

// message
// {"course":[{"id":3,"information":"test","name":"course1"}],"name":"student"}

Difference between UTF-8 and UTF-16?

This is unrelated to UTF-8/16 (in general, although it does convert to UTF16 and the BE/LE part can be set w/ a single line), yet below is the fastest way to convert String to byte[]. For instance: good exactly for the case provided (hash code). String.getBytes(enc) is relatively slow.

static byte[] toBytes(String s){
        byte[] b=new byte[s.length()*2];
        return b;

How to hash some string with sha256 in Java?

In Java 8

import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import javax.xml.bind.DatatypeConverter;

Scanner scanner = new Scanner(;
String password = scanner.nextLine();

MessageDigest digest = null;
try {
    digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
    // TODO Auto-generated catch block
byte[] hash = digest.digest(password.getBytes(StandardCharsets.UTF_8));
String encoded = DatatypeConverter.printHexBinary(hash);        

Omitting the second expression when using the if-else shorthand

This is also an option:

x==2 && dosomething();

dosomething() will only be called if x==2 is evaluated to true. This is called Short-circuiting.

It is not commonly used in cases like this and you really shouldn't write code like this. I encourage this simpler approach:

if(x==2) dosomething();

You should write readable code at all times; if you are worried about file size, just create a minified version of it with help of one of the many JS compressors. (e.g Google's Closure Compiler)

Please run `npm cache clean`

As of npm@5, the npm cache self-heals from corruption issues and data extracted from the cache is guaranteed to be valid. If you want to make sure everything is consistent, use npm cache verify instead. On the other hand, if you're debugging an issue with the installer, you can use npm install --cache /tmp/empty-cache to use a temporary cache instead of nuking the actual one.

If you're sure you want to delete the entire cache, rerun:

npm cache clean --force

A complete log of this run can be found in /Users/USERNAME/.npm/_logs/2019-01-08T21_29_30_811Z-debug.log.

JavaScript TypeError: Cannot read property 'style' of null

For me my Script tag was outside the body element. Copied it just before closing the body tag. This worked

enter code here

<h1 id = 'title'>Black Jack</h1>
<h4> by Meg</h4>

<p id="text-area">Welcome to blackJack!</p>
<button id="new-button">New Game</button>
<button id="hitbtn">Hit!</button>
<button id="staybtn">Stay</button>

 <script src="script.js"></script>

Render basic HTML view?

I usually use this

app.configure(function() {
    app.use(express.static(__dirname + '/web'));

Just be careful because that'll share anything in the /web directory.

I hope it helps

Is there a portable way to get the current username in Python?

I wrote the plx module some time ago to get the user name in a portable way on Unix and Windows (among other things):


import plx

username = plx.get_username()

(it requires win32 extensions on Windows)

Python Array with String Indices

Even better, try an OrderedDict (assuming you want something like a list). Closer to a list than a regular dict since the keys have an order just like list elements have an order. With a regular dict, the keys have an arbitrary order.

Note that this is available in Python 3 and 2.7. If you want to use with an earlier version of Python you can find installable modules to do that.

jQuery show/hide options from one select drop down, when option on other select dropdown is slected

Try -

$("#column_select").change(function () {
    $("#layout_select").children("option[value^=" + $(this).val() + "]").show()

If you were going to use this solution you'd need to hide all of the elements apart from the one with the 'none' value in your document.ready function -

$(document).ready(function() {
    $("#column_select").change(function() {
        $("#layout_select").children("option[value^=" + $(this).val() + "]").show()

Demo -


I might have got a bit carried away with this, but here's a further example that uses a cache of the original select list options to ensure that the 'layout_select' list is completely reset/cleared (including the 'none' option) after the 'column_select' list is changed -

$(document).ready(function() {
    var optarray = $("#layout_select").children('option').map(function() {
        return {
            "value": this.value,
            "option": "<option value='" + this.value + "'>" + this.text + "</option>"

    $("#column_select").change(function() {
        var addoptarr = [];
        for (i = 0; i < optarray.length; i++) {
            if (optarray[i].value.indexOf($(this).val()) > -1) {

Demo -

What is the use of the init() usage in JavaScript?

In JavaScript when you create any object through a constructor call like below

step 1 : create a function say Person..

function Person(name){;

step 2 : create an instance for this function..

var obj=new Person('venkat')

//above line will instantiate this function(Person) and return a brand new object called Person {name:'venkat'}

if you don't want to instantiate this function and call at same time.we can also do like below..

var Person = {
  init: function(name){;
  print: function(){
var obj=Object.create(Person);

in the above method init will help in instantiating the object properties. basically init is like a constructor call on your class.

Import CSV file as a pandas DataFrame

Try this

import pandas as pd

Replace the file target location, with where your data set is found, refer this url

How do I use a 32-bit ODBC driver on 64-bit Server 2008 when the installer doesn't create a standard DSN?

A lot of these answers are pretty old, so I thought I would update with a solution that I think is helpful.

Our issue was similar to OP's, we upgraded 32 bit XP machines to 64 bit windows 7 and our application software that uses a 32 bit ODBC driver stopped being able to write to our database.

Turns out, there are two ODBC Data Source Managers, one for 32 bit and one for 64 bit. So I had to run the 32 bit version which is found in C:\Windows\SysWOW64\odbcad32.exe. Inside the ODBC Data Source Manager, I was able to go to the System DSN tab and Add my driver to the list using the Add button. (You can check the Drivers tab to see a list of the drivers you can add, if your driver isn't in this list then you may need to install it).

The next issue was the software that we ran was compiled to use 'Any CPU'. This would see the operating system was 64 bit, so it would look at the 64 bit ODBC Data Sources. So I had to force the program to compile as an x86 program, which then tells it to look at the 32 bit ODBC Data Sources. To set your program to x86, in Visual Studio go to your project properties and under the build tab at the top there is a platform drop down list, and choose x86. If you don't have the source code and can't compile the program as x86, you might be able to right click the program .exe and go to the compatibility tab and choose a compatibility that works for you.

Once I had the drivers added and the program pointing to the right drivers, everything worked like it use to. Hopefully this helps anyone working with older software.

How can I insert a line break into a <Text> component in React Native?

Another way to insert <br> between text lines that are defined in an array:

import react, { Fragment } from 'react';

const lines = [
  'One line',
  'Another line',

const textContent =
  lines.reduce(items, line, index) => {
    if (index > 0) {
      items.push(<br key={'br-'+index}/>);
    items.push(<Fragment key={'item-'+index}>{line}</Fragment>);
    return items;
  }, []);

Then the text can be used as variable:


If not available, Fragment can be defined this way:

const Fragment = (props) => props.children;

Create a Cumulative Sum Column in MySQL

You could also create a trigger that will calculate the sum before each insert

delimiter |


  SET cumulative_sum = (
     SELECT SUM(x.count)
        FROM someTable x
        WHERE <=

    set  NEW.cumulative_sum = cumulative_sum;

I have not tested this

How to catch exception correctly from http.request()?

in the latest version of angular4 use

import { Observable } from 'rxjs/Rx'

it will import all the required things.

How to read if a checkbox is checked in PHP?

Well, the above examples work only when you want to INSERT a value, not useful for UPDATE different values to different columns, so here is my little trick to update:

$queryMU ='UPDATE '.$db->dbprefix().'settings SET menu_news = 0, menu_gallery = 0, menu_events = 0, menu_contact = 0';
            $stmtMU = $db->prepare($queryMU);
if(!empty($_POST['check_menus'])) {
    foreach($_POST['check_menus'] as $checkU) {
try {
//UPDATE only the values checked
    $queryMU ='UPDATE '.$db->dbprefix().'settings SET '.$checkU.'= 1';
            $stmtMU = $db->prepare($queryMU);
        } catch(PDOException $e) {
          $msg = 'Error: ' . $e->getMessage();}

<input type="checkbox" value="menu_news" name="check_menus[]" />
<input type="checkbox" value="menu_gallery" name="check_menus[]" />


The secret is just update all VALUES first (in this case to 0), and since the will only send the checked values, that means everything you get should be set to 1, so everything you get set it to 1.

Example is PHP but applies for everything.

Have fun :)

Is there a performance difference between i++ and ++i in C?

I always prefer pre-increment, however ...

I wanted to point out that even in the case of calling the operator++ function, the compiler will be able to optimize away the temporary if the function gets inlined. Since the operator++ is usually short and often implemented in the header, it is likely to get inlined.

So, for practical purposes, there likely isn't much of a difference between the performance of the two forms. However, I always prefer pre-increment since it seems better to directly express what I"m trying to say, rather than relying on the optimizer to figure it out.

Also, giving the optmizer less to do likely means the compiler runs faster.


ran across this page and several like it all talking about the GIT_DISCOVERY_ACROSS_FILESYSTEM not set message. In my case our sys admin had decided that the apache2 directory needed to be on a mounted filesystem in case the disk for the server stopped working and had to get rebuilt. I found this with a simple df command:

-->  UBIk  <--:root@ns1:[/etc]
--PRODUCTION--(16:48:43)--> df -h
Filesystem                           Size  Used Avail Use% Mounted on
/dev/mapper/vgraid-lvapache           63G   54M   60G   1% /etc/apache2

To fix this I just put the following in the root user's shell (as they are the only ones who need to be looking at etckeeper revisions:


and all was well and good...much joy.

More notes:

-->  UBIk  <--:root@ns1:[/etc]

-->  UBIk  <--:root@ns1:[/etc]
--PRODUCTION--(16:57:35)--> git status
On branch master
nothing to commit, working tree clean

-->  UBIk  <--:root@ns1:[/etc]
--PRODUCTION--(16:57:40)--> touch apache2/me

-->  UBIk  <--:root@ns1:[/etc]
--PRODUCTION--(16:57:45)--> git status
On branch master
Untracked files:
  (use "git add <file>..." to include in what will be committed)


nothing added to commit but untracked files present (use "git add" to track)

-->  UBIk  <--:root@ns1:[/etc]
--PRODUCTION--(16:57:47)--> cd apache2

-->  UBIk  <--:root@ns1:[/etc/apache2]
--PRODUCTION--(16:57:50)--> git status
fatal: Not a git repository (or any parent up to mount point /etc/apache2)
Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).
-->  UBIk  <--:root@ns1:[/etc/apache2]

-->  UBIk  <--:root@ns1:[/etc/apache2]
--PRODUCTION--(16:58:59)--> git status
On branch master
Untracked files:
  (use "git add <file>..." to include in what will be committed)


nothing added to commit but untracked files present (use "git add" to track)

Hopefully that will help someone out somewhere... -wc

What is the meaning of "int(a[::-1])" in Python?

Assuming a is a string. The Slice notation in python has the syntax -


So, when you do a[::-1], it starts from the end towards the first taking each element. So it reverses a. This is applicable for lists/tuples as well.

Example -

>>> a = '1234'
>>> a[::-1]

Then you convert it to int and then back to string (Though not sure why you do that) , that just gives you back the string.

Change width of select tag in Twitter Bootstrap

with bootstrap use class input-md = medium, input-lg = large, for more info see

Custom CSS for <audio> tag?

There are CSS options for the audio tag.

Like: html 5 audio tag width

But if you play around with it you'll see results can be unexpected - as of August 2012.

Convert Datetime column from UTC to local time in select statement

For Azure SQL and @@Version >= SQL Server 2016 users, Below is a simple function using AT TIME ZONE.

CREATE FUNCTION [dbo].[Global_Convert_UTCTimeTo_LocalTime]
   @LocalTimeZone        VARCHAR(50),
   @UTCDateTime          DATETIME
   DECLARE @ConvertedDateTime DATETIME;

   SELECT @ConvertedDateTime = @UTCDateTime AT TIME ZONE 'UTC' AT TIME ZONE @LocalTimeZone
   RETURN @ConvertedDateTime


For types of values that @LocalTimeZone can take, please go to this link or Go to KEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones

How to select multiple files with <input type="file">?

Copy and paste this into your html:

<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>

function handleFileSelect(evt) {
var files =; // FileList object

// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
  output.push('<li><strong>', escape(, '</strong> (', f.type || 'n/a', ') - ',
              f.size, ' bytes, last modified: ',
              f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';

This comes to you, through me, from this webpage:

How to parse XML in Bash?

Yuzem's method can be improved by inversing the order of the < and > signs in the rdom function and the variable assignments, so that:

rdom () { local IFS=\> ; read -d \< E C ;}


rdom () { local IFS=\< ; read -d \> C E ;}

If the parsing is not done like this, the last tag in the XML file is never reached. This can be problematic if you intend to output another XML file at the end of the while loop.

"ImportError: no module named 'requests'" after installing with pip

Run in command prompt.

pip list

Check what version you have installed on your system if you have an old version.

Try to uninstall the package...

pip uninstall requests

Try after to install it:

pip install requests

You can also test if pip does not do the job.

easy_install requests

error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token

  1. You seem to be including one C file from anther. #include should normally be used with header files only.

  2. Within the definition of struct ast_node you refer to struct AST_NODE, which doesn't exist. C is case-sensitive.

How can I do width = 100% - 100px in CSS?

my code, and it works for IE6:

#container {margin:0 auto; width:100%;}
#header { height:100px; background:#9c6; margin-bottom:5px;}
#mainContent { height:500px; margin-bottom:5px;}
#sidebar { float:left; width:100px; height:500px; background:#cf9;}
#content { margin-left:100px; height:500px; background:#ffa;}


<div id="container">
  <div id="header">header</div>
  <div id="mainContent">
    <div id="sidebar">left</div>
    <div id="content">right 100% - 100px</div>
  <span style="display:none"></span></div>

enter image description here

checking if a number is divisible by 6 PHP

$num += (6-$num%6)%6;

no need for a while loop! Modulo (%) returns the remainder of a division. IE 20%6 = 2. 6-2 = 4. 20+4 = 24. 24 is divisible by 6.

Soft Edges using CSS?

You can use CSS gradient - although there are not consistent across browsers so You would have to code it for every one

Like that: CSS3 Transparency + Gradient

Gradient should be more transparent on top or on top right corner (depending on capabilities)

Same font except its weight seems different on different browsers

Try -webkit-font-smoothing: subpixel-antialiased;

How to read file from relative path in Java project? cannot find the path specified

I wanted to parse 'command.json' inside src/main//js/ For that I copied json file in src folder and gave the absolute path like this :

Object obj  = parser.parse(new FileReader("./src/command.json"));

How to check if a string array contains one string in JavaScript?

You can use the indexOfmethod and "extend" the Array class with the method contains like this:

Array.prototype.contains = function(element){
    return this.indexOf(element) > -1;

with the following results:

["A", "B", "C"].contains("A") equals true

["A", "B", "C"].contains("D") equals false

Java: using switch statement with enum under subclass

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

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

Instagram API to fetch pictures with specific hashtags

It is not possible yet to search for content using multiple tags, for now only single tags are supported.

Firstly, the Instagram API endpoint "tags" required OAuth authentication.

This is not quite true, you only need an API-Key. Just register an application and add it to your requests. Example:

Also note that the username is not the user-id. You can look up user-Id`s here.

A workaround for searching multiple keywords would be if you start one request for each tag and compare the results on your server. Of course this could slow down your site depending on how much keywords you want to compare.

Convert date to YYYYMM format

You can convert your date in many formats, for example :

CONVERT(NVARCHAR(10), DATE_OF_DAY, 103) => 15/09/2016
CONVERT(NVARCHAR(10), DATE_OF_DAY, 3) => 15/09/16

Syntaxe :

CONVERT('TheTypeYouWant', 'TheDateToConvert', 'TheCodeForFormating' * )
  • The code is an integer, here 3 is the third formating without century, if you want the century just change the code to 103.

In your case, i've just converted and restrict size by nvarchar(6) like this :

CONVERT(NVARCHAR(6), DATE_OF_DAY, 112) => 201609

See more at :

How to debug a Flask app

with virtual env activate

export FLASK_DEBUG=true

you can configure

export  #
export FLASK_ENV = "development"

to start

flask run

the result

 * Environment: development
 * Debug mode: on
 * Running on (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: xxx-xxx-xxx

and if you change

export FLASK_DEBUG=false

 * Environment: development
 * Debug mode: off
 * Running on (Press CTRL+C to quit)

Swift - How to detect orientation changes

I believe the correct answer is actually a combination of both approaches: viewWIllTransition(toSize:) and NotificationCenter's UIDeviceOrientationDidChange.

viewWillTransition(toSize:) notifies you before the transition.

NotificationCenter UIDeviceOrientationDidChange notifies you after.

You have to be very careful. For example, in UISplitViewController when the device rotates into certain orientations, the DetailViewController gets popped off the UISplitViewController's viewcontrollers array, and pushed onto the master's UINavigationController. If you go searching for the detail view controller before the rotation has finished, it may not exist and crash.

Javascript split regex question

or just (anything but numbers):


How I can get web page's content and save it into the string variable

You can use the WebClient

Using System.Net;
WebClient client = new WebClient();
string downloadString = client.DownloadString("");

Getting value from appsettings.json in .net core

    public static void GetSection()
        Configuration = new ConfigurationBuilder()

        string BConfig = Configuration.GetSection("ConnectionStrings")["BConnection"];


php exec command (or similar) to not wait for result

I know this question has been answered but the answers i found here didn't work for my scenario ( or for Windows ).

I am using windows 10 laptop with PHP 7.2 in Xampp v3.2.4.

$command = 'php Cron.php send_email "'. $id .'"';
if ( substr(php_uname(), 0, 7) == "Windows" )
    pclose(popen("start /B " . $command . " 1> temp/update_log 2>&1 &", "r"));
    shell_exec( $command . " > /dev/null 2>&1 &" );

This worked perfectly for me.

I hope it will help someone with windows. Cheers.

Adding minutes to date time in PHP

$newtimestamp = strtotime('2011-11-17 05:05 + 16 minute');
echo date('Y-m-d H:i:s', $newtimestamp);

result is

2011-11-17 05:21:00

Live demo is here

If you are no familiar with strtotime yet, you better head to to discover it's great power :-)

Copying the cell value preserving the formatting from one cell to another in excel using VBA

I prefer to avoid using select

     With sheets("sheetname").range("I10") 
          .PasteSpecial Paste:=xlPasteValues, _
                  Operation:=xlNone, _
                  SkipBlanks:=False, _
          .PasteSpecial Paste:=xlPasteFormats, _
                  Operation:=xlNone, _
                  SkipBlanks:=False, _
          .font.color = sheets("sheetname").range("F10").font.color
      End With

How to create an 2D ArrayList in java?

This can be achieve by creating object of List data structure, as follows

List list = new ArrayList();

For more information refer this link

How to create a Multidimensional ArrayList in Java?

How to get folder directory from HTML input type "file" or any other way?

Stumbled on this page as well, and then found out this is possible with just javascript (no plugins like ActiveX or Flash), but just in chrome:

Basically, they added support for a new attribute on the file input element "webkitdirectory". You can use it like this:

<input type="file" id="ctrl" webkitdirectory directory multiple/>

It allows you to select directories. The multiple attribute is a good fallback for browsers that support multiple file selection but not directory selection.

When you select a directory the files are available through the dom object for the control (document.getElementById('ctrl')), just like they are with the multiple attribute. The browsers adds all files in the selected directory to that list recursively.

You can already add the directory attribute as well in case this gets standardized at some point (couldn't find any info regarding that)

How do I get bit-by-bit data from an integer value in C?

If you don't want any loops, you'll have to write it out:

#include <stdio.h>
#include <stdbool.h>

int main(void)
    int num = 7;

    #if 0
        bool arr[4] = { (num&1) ?true: false, (num&2) ?true: false, (num&4) ?true: false, (num&8) ?true: false };
        #define BTB(v,i) ((v) & (1u << (i))) ? true : false
        bool arr[4] = { BTB(num,0), BTB(num,1), BTB(num,2), BTB(num,3)};
        #undef BTB

    printf("%d %d %d %d\n", arr[3], arr[2], arr[1], arr[0]);

    return 0;

As demonstrated here, this also works in an initializer.

Can't install via pip because of egg_info error

I was trying to install pyautogui and followed instructions from the first answer but was unsuccessful. The difference for me was running pip install pillow and then running pip install pyautogui

I don't know what this means, but I hope this helps some people out.

How do I implement basic "Long Polling"?

Below is a long polling solution I have developed for Inform8 Web. Basically you override the class and implement the loadData method. When the loadData returns a value or the operation times out it will print the result and return.

If the processing of your script may take longer than 30 seconds you may need to alter the set_time_limit() call to something longer.

Apache 2.0 license. Latest version on github


abstract class LongPoller {

  protected $sleepTime = 5;
  protected $timeoutTime = 30;

  function __construct() {

  function setTimeout($timeout) {
    $this->timeoutTime = $timeout;

  function setSleep($sleep) {
    $this->sleepTime = $sleepTime;

  public function run() {
    $data = NULL;
    $timeout = 0;

    set_time_limit($this->timeoutTime + $this->sleepTime + 15);

    //Query database for data
    while($data == NULL && $timeout < $this->timeoutTime) {
      $data = $this->loadData();
      if($data == NULL){

        //No new orders, flush to notify php still alive

        //Wait for new Messages
        $timeout += $this->sleepTime;
        echo $data;


  protected abstract function loadData();


What's the most useful and complete Java cheat sheet?

  1. I have personally found the dzone cheatsheet on core java to be really handy in the beginning. However the needs change as we grow and get used to things.

  2. There are a few listed (at the end of the post) in on this java learning resources article too

  3. For the most practical use, in recent past I have found Java API doc to be the best place to cheat code and learn new api. This helps specially when you want to focus on latest version of java.

  4. mkyong - is one my fav places to cheat a lot of code for quick start -

  5. And last but not the least, Stackoverflow is king of all small handy code snippets. Just google a stuff you are trying and there is a chance that a page will be top of search results, most of my google search results end at stackoverflow. Many of the common questions are available here -

UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128)

An easy solution to overcome this problem is to set your default encoding to utf8. Follow is an example

import sys


How to change color of ListView items on focus and on click

<selector xmlns:android="" >    
    <item android:state_pressed="true" android:drawable="@drawable/YOUR DRAWABLE XML" /> 
    <item android:drawable="@drawable/YOUR DRAWABLE XML" />

How to use underscore.js as a template engine?

with express it's so easy. all what you need is to use the consolidate module on node so you need to install it :

npm install consolidate --save

then you should change the default engine to html template by this:

app.set('view engine', 'html');

register the underscore template engine for the html extension:

app.engine('html', require('consolidate').underscore);

it's done !

Now for load for example an template called 'index.html':

res.render('index', { title : 'my first page'});

maybe you will need to install the underscore module.

npm install underscore --save

I hope this helped you!

Running powershell script within python script, how to make python print the powershell output while it is running

I don't have Python 2.7 installed, but in Python 3.3 calling Popen with stdout set to sys.stdout worked just fine. Not before I had escaped the backslashes in the path, though.

>>> import subprocess
>>> import sys
>>> p = subprocess.Popen(['powershell.exe', 'C:\\Temp\\test.ps1'], stdout=sys.stdout)
>>> Hello World

A select query selecting a select statement

Not sure if Access supports it, but in most engines (including SQL Server) this is called a correlated subquery and works fine:

SELECT  TypesAndBread.Type, TypesAndBread.TBName,
        SELECT  Count(Sandwiches.[SandwichID]) As SandwichCount
        FROM    Sandwiches
        WHERE   (Type = 'Sandwich Type' AND Sandwiches.Type = TypesAndBread.TBName)
                OR (Type = 'Bread' AND Sandwiches.Bread = TypesAndBread.TBName)
        ) As SandwichCount
FROM    TypesAndBread

This can be made more efficient by indexing Type and Bread and distributing the subqueries over the UNION:

SELECT  [Sandwiches Types].[Sandwich Type] As TBName, "Sandwich Type" As Type,
        SELECT  COUNT(*) As SandwichCount
        FROM    Sandwiches
        WHERE   Sandwiches.Type = [Sandwiches Types].[Sandwich Type]
FROM    [Sandwiches Types]
SELECT  [Breads].[Bread] As TBName, "Bread" As Type,
        SELECT  COUNT(*) As SandwichCount
        FROM    Sandwiches
        WHERE   Sandwiches.Bread = [Breads].[Bread]
FROM    [Breads]

Delete directories recursively in Java

In Java 7+ you can use Files class. Code is very simple:

Path directory = Paths.get("/tmp");
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
   public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
       return FileVisitResult.CONTINUE;

   public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
       return FileVisitResult.CONTINUE;

Pure CSS collapse/expand div

Using <summary> and <details>

Using <summary> and <details> elements is the simplest but see browser support as current IE is not supporting it. You can polyfill though (most are jQuery-based). Do note that unsupported browser will simply show the expanded version of course, so that may be acceptable in some cases.

/* Optional styling */_x000D_
summary::-webkit-details-marker {_x000D_
  color: blue;_x000D_
summary:focus {_x000D_
  outline-style: none;_x000D_
  <summary>Summary, caption, or legend for the content</summary>_x000D_
  Content goes here._x000D_

See also how to style the <details> element (HTML5 Doctor) (little bit tricky).

Pure CSS3

The :target selector has a pretty good browser support, and it can be used to make a single collapsible element within the frame.

.hide:target {_x000D_
  display: none;_x000D_
.hide:target + .show,_x000D_
.hide:target ~ .details {_x000D_
  display: block;_x000D_
  <a id="hide1" href="#hide1" class="hide">+ Summary goes here</a>_x000D_
  <a id="show1" href="#show1" class="show">- Summary goes here</a>_x000D_
  <div class="details">_x000D_
    Content goes here._x000D_
  <a id="hide2" href="#hide2" class="hide">+ Summary goes here</a>_x000D_
  <a id="show2" href="#show2" class="show">- Summary goes here</a>_x000D_
  <div class="details">_x000D_
    Content goes here._x000D_

How to get distinct results in hibernate with joins and row-based limiting (paging)?

session = (Session) getEntityManager().getDelegate();
Criteria criteria = session.createCriteria(ComputedProdDaily.class);
ProjectionList projList = Projections.projectionList();
projList.add(""), "userid");
projList.add("loanState"), "state");

This helped me :D

How to navigate through a vector using iterators? (C++)

In C++-11 you can do:

std::vector<int> v = {0, 1, 2, 3, 4, 5};
for (auto i : v)
   // access by value, the type of i is int
   std::cout << i << ' ';
std::cout << '\n';

See here for variations:

Why is a ConcurrentModificationException thrown and how to debug it

I ran into this exception when try to remove x last items from list. myList.subList(lastIndex, myList.size()).clear(); was the only solution that worked for me.

How to check if object property exists with a variable holding the property name?

You can use hasOwnProperty, but based on the reference you need quotes when using this method:

if (myObj.hasOwnProperty('myProp')) {
    // do something

Another way is to use in operator, but you need quotes here as well:

if ('myProp' in myObj) {
    // do something

python modify item in list, save back in list

For Python 3:

ListOfStrings = []
for idx, item in enumerate(ListOfStrings):
if 'foo' in item:
    ListOfStrings[idx] = "bar"

Rails Active Record find(:all, :order => ) issue

I understand why the Rails devs went with sqlite3 for an out-of-the-box implementation, but MySQL is so much more practical, IMHO. I realize it depends on what you are building your Rails app for, but most people are going to switch the default database.yml file from sqlite3 to MySQL.

Glad you resolved your issue.

How do I disable Git Credential Manager for Windows?

In case you do not want to remove or uninstall the credentials manager: see for the solution that worked for me.

Explanations, etc. in that page (linked to prevent duplicate content in the same website family).

TL;DR: this now sits on top of my automated bash scripts:

# next env var doesn't help...
export GIT_SSH_COMMAND='ssh -oBatchMode=yes'
# these should shut up git asking, but only partly: the X-windows-like dialog doesn't pop up no more, but ...
export GIT_ASKPASS=echo
export SSH_ASKPASS=echo
# We needed to find *THIS* to shut up the bloody git-for-windows credential manager: 
export GCM_INTERACTIVE=never

The final nail in the coffin of that credentials manager was the unique bit (GCM_INTERACTIVE) in Martin Ba's answer above: How do I disable Git Credential Manager for Windows?

Find the number of employees in each department - SQL Oracle

Try the query below:

select count(*),d.dname from emp e , dept d where d.deptno = e.deptno
group by d.dname

Pair/tuple data type in Go

You could do something like this if you wanted

package main

import "fmt"

type Pair struct {
    a, b interface{}

func main() {
    p1 := Pair{"finished", 42}
    p2 := Pair{6.1, "hello"}
    fmt.Println("p1=", p1, "p2=", p2)
    fmt.Println("p1.b", p1.b)
    // But to use the values you'll need a type assertion
    s := p1.a.(string) + " now"
    fmt.Println("p1.a", s)

However I think what you have already is perfectly idiomatic and the struct describes your data perfectly which is a big advantage over using plain tuples.

Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

Sorry, misunderstood your question.

According to Javascript - capturing onsubmit when calling form.submit():

I was recently asked: "Why doesn't the form.onsubmit event get fired when I submit my form using javascript?"

The answer: Current browsers do not adhere to this part of the html specification. The event only fires when it is activated by a user - and does not fire when activated by code.

(emphasis added).

Note: "activated by a user" also includes hitting submit buttons (probably including default submit behaviour from the enter key but I haven't tried this). Nor, I believe, does it get triggered if you (with code) click a submit button.

How to merge many PDF files into a single one?

First, get Pdftk:

sudo apt-get install pdftk

Now, as shown on example page, use

pdftk 1.pdf 2.pdf 3.pdf cat output 123.pdf

for merging pdf files into one.

how to read a long multiline string line by line in python

by splitting with newlines.

for line in wallop_of_a_string_with_many_lines.split('\n'):

if you iterate over a string, you are iterating char by char in that string, not by line.

>>>string = 'abc'
>>>for line in string:
    print line


How to name variables on the fly?

Use assign:

assign(paste("orca", i, sep = ""), list_name[[i]])

In Python, can I call the main() of an imported module?

Assuming you are trying to pass the command line arguments as well.

import sys
import myModule

def main():
    # this will just pass all of the system arguments as is

    # all the argv but the script name

How can I remove the extension of a filename in a shell script?

As pointed out by Hawker65 in the comment of chepner answer, the most voted solution does neither take care of multiple extensions (such as filename.tar.gz), nor of dots in the rest of the path (such as this.path/with.dots/ A possible solution is:

echo $(dirname $a)/$(basename $a | cut -d. -f1)

Create a asmx web service in C# using visual studio 2013

  1. Create Empty ASP.NET Project enter image description here
  2. Add Web Service(asmx) to your project
    enter image description here

Java Minimum and Maximum values in Array

You are doing two mistakes here.
1. calling getMaxValue(),getMinValue() methods before array initialization completes.
2.Not storing return value returned by the getMaxValue(),getMinValue() methods.
So try this code

   for (int i = 0 ; i < array.length; i++ ) 
       int next = input.nextInt();
       // sentineil that will stop loop when 999 is entered
       if (next == 999)
       array[i] = next;
  // get biggest number
  int maxValue = getMaxValue(array);
  System.out.println(maxValue );

  // get smallest number
  int minValue = getMinValue(array);

How do I restart nginx only after the configuration test was successful on Ubuntu?

alias nginx.start='sudo nginx -c /etc/nginx/nginx.conf'
alias nginx.stop='sudo nginx -s stop'
alias nginx.reload='sudo nginx -s reload'
alias nginx.config='sudo nginx -t'
alias nginx.restart='nginx.config && nginx.stop && nginx.start'
alias nginx.errors='tail -250f /var/logs/nginx.error.log'
alias nginx.access='tail -250f /var/logs/nginx.access.log'
alias nginx.logs.default.access='tail -250f /var/logs/nginx.default.access.log'
alias nginx.logs.default-ssl.access='tail -250f /var/logs/nginx.default.ssl.log'

and then use commands "nginx.reload" etc..

Get combobox value in Java swing

Method Object JComboBox.getSelectedItem() returns a value that is wrapped by Object type so you have to cast it accordingly.


YourType varName = (YourType)comboBox.getSelectedItem();`
String value = comboBox.getSelectedItem().toString();

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

Please make sure you are using latest jdbc connector as per the mysql. I was facing this problem and when I replaced my old jdbc connector with the latest one, the problem was solved.

You can download latest jdbc driver from

Select Operating System as Platform Independent. It will show you two options. One as tar and one as zip. Download the zip and extract it to get the jar file and replace it with your old connector.

This is not only for hibernate framework, it can be used with any platform which requires a jdbc connector.

use Lodash to sort array of object by value

This method orderBy does not change the input array, you have to assign the result to your array :

var chars = this.state.characters;

chars = _.orderBy(chars, ['name'],['asc']); // Use Lodash to sort array by 'name'

 this.setState({characters: chars})

How to do an update + join in PostgreSQL?

Here's a simple SQL that updates Mid_Name on the Name3 table using the Middle_Name field from Name:

update name3
set mid_name = name.middle_name
from name
where name3.person_id = name.person_id;

PHP Function Comments


 * Does something interesting
 * @param Place   $where  Where something interesting takes place
 * @param integer $repeat How many times something interesting should happen
 * @throws Some_Exception_Class If something interesting cannot happen
 * @author Monkey Coder <[email protected]>
 * @return Status


 * Short description for class
 * Long description for class (if any)...
 * @copyright  2006 Zend Technologies
 * @license   PHP License 3.0
 * @version    Release: @package_version@
 * @link
 * @since      Class available since Release 1.2.0

Sample File:


 * Short description for file
 * Long description for file (if any)...
 * PHP version 5.6
 * LICENSE: This source file is subject to version 3.01 of the PHP license
 * that is available through the world-wide-web at the following URI:
 *  If you did not receive a copy of
 * the PHP License and are unable to obtain it through the web, please
 * send a note to [email protected] so we can mail you a copy immediately.
 * @category   CategoryName
 * @package    PackageName
 * @author     Original Author <[email protected]>
 * @author     Another Author <[email protected]>
 * @copyright  1997-2005 The PHP Group
 * @license  PHP License 3.01
 * @version    SVN: $Id$
 * @link
 * @see        NetOther, Net_Sample::Net_Sample()
 * @since      File available since Release 1.2.0
 * @deprecated File deprecated in Release 2.0.0

 * This is a "Docblock Comment," also known as a "docblock."  The class'
 * docblock, below, contains a complete description of how to write these.
require_once 'PEAR.php';

// {{{ constants

 * Methods return this if they succeed
define('NET_SAMPLE_OK', 1);

// }}}
// {{{ GLOBALS

 * The number of objects created
 * @global int $GLOBALS['_NET_SAMPLE_Count']
$GLOBALS['_NET_SAMPLE_Count'] = 0;

// }}}
// {{{ Net_Sample

 * An example of how to write code to PEAR's standards
 * Docblock comments start with "/**" at the top.  Notice how the "/"
 * lines up with the normal indenting and the asterisks on subsequent rows
 * are in line with the first asterisk.  The last line of comment text
 * should be immediately followed on the next line by the closing asterisk
 * and slash and then the item you are commenting on should be on the next
 * line below that.  Don't add extra lines.  Please put a blank line
 * between paragraphs as well as between the end of the description and
 * the start of the @tags.  Wrap comments before 80 columns in order to
 * ease readability for a wide variety of users.
 * Docblocks can only be used for programming constructs which allow them
 * (classes, properties, methods, defines, includes, globals).  See the
 * phpDocumentor documentation for more information.
 * The Javadoc Style Guide is an excellent resource for figuring out
 * how to say what needs to be said in docblock comments.  Much of what is
 * written here is a summary of what is found there, though there are some
 * cases where what's said here overrides what is said there.
 * The first line of any docblock is the summary.  Make them one short
 * sentence, without a period at the end.  Summaries for classes, properties
 * and constants should omit the subject and simply state the object,
 * because they are describing things rather than actions or behaviors.
 * Below are the tags commonly used for classes. @category through @version
 * are required.  The remainder should only be used when necessary.
 * Please use them in the order they appear here.  phpDocumentor has
 * several other tags available, feel free to use them.
 * @category   CategoryName
 * @package    PackageName
 * @author     Original Author <[email protected]>
 * @author     Another Author <[email protected]>
 * @copyright  1997-2005 The PHP Group
 * @license  PHP License 3.01
 * @version    Release: @package_version@
 * @link
 * @see        NetOther, Net_Sample::Net_Sample()
 * @since      Class available since Release 1.2.0
 * @deprecated Class deprecated in Release 2.0.0
class Net_Sample
    // {{{ properties

     * The status of foo's universe
     * Potential values are 'good', 'fair', 'poor' and 'unknown'.
     * @var string $foo
    public $foo = 'unknown';

     * The status of life
     * Note that names of private properties or methods must be
     * preceeded by an underscore.
     * @var bool $_good
    private $_good = true;

    // }}}
    // {{{ setFoo()

     * Registers the status of foo's universe
     * Summaries for methods should use 3rd person declarative rather
     * than 2nd person imperative, beginning with a verb phrase.
     * Summaries should add description beyond the method's name. The
     * best method names are "self-documenting", meaning they tell you
     * basically what the method does.  If the summary merely repeats
     * the method name in sentence form, it is not providing more
     * information.
     * Summary Examples:
     *   + Sets the label              (preferred)
     *   + Set the label               (avoid)
     *   + This method sets the label  (avoid)
     * Below are the tags commonly used for methods.  A @param tag is
     * required for each parameter the method has.  The @return
     * and @access tags are mandatory.  The @throws tag is required if
     * the method uses exceptions.  @static is required if the method can
     * be called statically.  The remainder should only be used when
     * necessary.  Please use them in the order they appear here.
     * phpDocumentor has several other tags available, feel free to use
     * them.
     * The @param tag contains the data type, then the parameter's
     * name, followed by a description.  By convention, the first noun in
     * the description is the data type of the parameter.  Articles like
     * "a", "an", and  "the" can precede the noun.  The descriptions
     * should start with a phrase.  If further description is necessary,
     * follow with sentences.  Having two spaces between the name and the
     * description aids readability.
     * When writing a phrase, do not capitalize and do not end with a
     * period:
     *   + the string to be tested
     * When writing a phrase followed by a sentence, do not capitalize the
     * phrase, but end it with a period to distinguish it from the start
     * of the next sentence:
     *   + the string to be tested. Must use UTF-8 encoding.
     * Return tags should contain the data type then a description of
     * the data returned.  The data type can be any of PHP's data types
     * (int, float, bool, string, array, object, resource, mixed)
     * and should contain the type primarily returned.  For example, if
     * a method returns an object when things work correctly but false
     * when an error happens, say 'object' rather than 'mixed.'  Use
     * 'void' if nothing is returned.
     * Here's an example of how to format examples:
     * <code>
     * require_once 'Net/Sample.php';
     * $s = new Net_Sample();
     * if (PEAR::isError($s)) {
     *     echo $s->getMessage() . "\n";
     * }
     * </code>
     * Here is an example for non-php example or sample:
     * <samp>
     * pear install net_sample
     * </samp>
     * @param string $arg1 the string to quote
     * @param int    $arg2 an integer of how many problems happened.
     *                     Indent to the description's starting point
     *                     for long ones.
     * @return int the integer of the set mode used. FALSE if foo
     *             foo could not be set.
     * @throws exceptionclass [description]
     * @access public
     * @static
     * @see Net_Sample::$foo, Net_Other::someMethod()
     * @since Method available since Release 1.2.0
     * @deprecated Method deprecated in Release 2.0.0
    function setFoo($arg1, $arg2 = 0)
         * This is a "Block Comment."  The format is the same as
         * Docblock Comments except there is only one asterisk at the
         * top.  phpDocumentor doesn't parse these.
        if ($arg1 == 'good' || $arg1 == 'fair') {
            $this->foo = $arg1;
            return 1;
        } elseif ($arg1 == 'poor' && $arg2 > 1) {
            $this->foo = 'poor';
            return 2;
        } else {
            return false;

    // }}}

// }}}

 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * c-hanging-comment-ender-p: nil
 * End:


Source: PEAR Docblock Comment standards

Free Rest API to retrieve current datetime as string (timezone irrelevant)

If you're using Rails, you can just make an empty file in the public folder and use ajax to get that. Then parse the headers for the Date header. Files in the Public folder bypass the Rails stack, and so have lower latency.

UIButton: how to center an image and a text using imageEdgeInsets and titleEdgeInsets?

Subclass UIButton

- (void)layoutSubviews {
    [super layoutSubviews];
    CGFloat spacing = 6.0;
    CGSize imageSize = self.imageView.image.size;
    CGSize titleSize = [self.titleLabel sizeThatFits:CGSizeMake(self.frame.size.width, self.frame.size.height - (imageSize.height + spacing))];
    self.imageView.frame = CGRectMake((self.frame.size.width - imageSize.width)/2, (self.frame.size.height - (imageSize.height+spacing+titleSize.height))/2, imageSize.width, imageSize.height);
    self.titleLabel.frame = CGRectMake((self.frame.size.width - titleSize.width)/2, CGRectGetMaxY(self.imageView.frame)+spacing, titleSize.width, titleSize.height);

How to get a unix script to run every 15 seconds?

To avoid possible overlapping of execution, use a locking mechanism as described in that thread.

jQuery find parent form

As of HTML5 browsers one can use inputElement.form - the value of the attribute must be an id of a <form> element in the same document. More info on MDN.

Axios Delete request with body and headers?

i found a way that's works:

      .delete(URL, {
        params: { id: 'IDDataBase'},
        headers: {
          token: 'TOKEN',
      .then(function (response) {
      .catch(function (error) {

I hope this work for you too.

Eclipse: Set maximum line length for auto formatting?

For HTML / PHP / JSP / JSPF: Web -> HTML Files -> Editor -> Line width

How to convert SQL Server's timestamp column to datetime format

My coworkers helped me with this:

select CONVERT(VARCHAR(10), <tms_column>, 112), count(*)
from table where <tms_column> > '2012-09-10'
group by CONVERT(VARCHAR(10), <tms_column>, 112);


select CONVERT(DATE, <tms_column>, 112), count(*)
from table where <tms_column> > '2012-09-10'
group by CONVERT(DATE, <tms_column>, 112);

MSSQL Error 'The underlying provider failed on Open'

I had a similar issue with the SQL Server Express Edition on Windows Server 2003. I simply added the network service as a user in the database security.

How can I add a PHP page to WordPress?

The widely accepted answer by Adam Hopkinson is not a fully automated method of creating a page! It requires a user to manually create a page in the back-end of WordPress (in the wp-admin dash). The problem with that is, a good plugin should have a fully automated setup. It should not require clients to manually create pages.

Also, some of the other widely accepted answers here involve creating a static page outside of WordPress, which then include only some of the WordPress functionality to achieve the themed header and footer. While that method may work in some cases, this can make integrating these pages with WordPress very difficult without having all its functionality included.

I think the best, fully automated, approach would be to create a page using wp_insert_post and have it reside in the database. An example and a great discussion about that, and how to prevent accidental deletion of the page by a user, can be found here: wordpress-automatically-creating-page

Frankly, I'm surprised this approach hasn't already been mentioned as an answer to this popular question (it has been posted for 7 years).

How to run a hello.js file in Node.js on windows?

I had such problem for windows. And I decided it so: startApp.cmd:

@set JAVA_HOME=C:\jdk160_24
@set PATH=%JAVA_HOME%/bin;%PATH%
@cd /D C:\app\

@start /b C:\WINDOWS\system32\cscript.exe 

and saved it cmd file in dir C:\scripts next file is runApp.bat:


Convert International String to \u Codes in java

Just some basic Methods for that (inspired from native2ascii tool):

 * Encode a String like äöü to \u00e4\u00f6\u00fc
 * @param text
 * @return
public String native2ascii(String text) {
    if (text == null)
        return text;
    StringBuilder sb = new StringBuilder();
    for (char ch : text.toCharArray()) {
    return sb.toString();

 * Encode a Character like ä to \u00e4
 * @param ch
 * @return
public String native2ascii(char ch) {
    if (ch > '\u007f') {
        StringBuilder sb = new StringBuilder();
        // write \udddd
        StringBuffer hex = new StringBuffer(Integer.toHexString(ch));
        int length = 4 - hex.length();
        for (int j = 0; j < length; j++) {
        for (int j = 0; j < 4; j++) {
            sb.append(hex.charAt(3 - j));
        return sb.toString();
    } else {
        return Character.toString(ch);

(Deep) copying an array using jQuery

Everything in JavaScript is pass by reference, so if you want a true deep copy of the objects in the array, the best method I can think of is to serialize the entire array to JSON and then de-serialize it back.

How to run TestNG from command line

Thanks a lot it was really very helpful.. I was able to run my TestNG classes using command line, but still I would like to wrap-up the things one last time as follows..

1) Set the classpath for the testng.jar in the environment variables
(either manually or via command line).

2) Create a new folder "MyTest".

3) Compile all your classes(testNG+java) and put them(.class files )
in a new folder "Mytest\bin".

4) Put your 'testng.xml' and '.properties' files to "Mytest\bin"

5) Put all the .jar files (testng,selenium... etc) in a new folder

6) Browse to the folder "bin" via command line and run the command
java -cp "..\lib\*;" org.testng.TestNG testng.xml

this should run your testNG cases.

What is the difference between SessionState and ViewState?

Session is used mainly for storing user specific data [ session specific data ]. In the case of session you can use the value for the whole session until the session expires or the user abandons the session. Viewstate is the type of data that has scope only in the page in which it is used. You canot have viewstate values accesible to other pages unless you transfer those values to the desired page. Also in the case of viewstate all the server side control datas are transferred to the server as key value pair in __Viewstate and transferred back and rendered to the appropriate control in client when postback occurs.

Run a Docker image as a container

Here is an example to run a webdev service in Docker. The image's name is morrisjobke/webdav. You can pull it from Docker Hub.

After you run these images, you can then access the WebDAV instance at http://localhost:8888/webdav. Internally the folder /var/webdav is used as the WebDAV root.

You can run this container in the following way:

$ docker run -d -e USERNAME=test -e PASSWORD=test -p 8888:80 morrisjobke/webdav

Creating a LINQ select from multiple tables

If the anonymous type causes trouble for you, you can create a simple data class:

public class PermissionsAndPages
     public ObjectPermissions Permissions {get;set}
     public Pages Pages {get;set}

and then in your query:

select new PermissionsAndPages { Permissions = op, Page = pg };

Then you can pass this around:

return queryResult.SingleOrDefault(); // as PermissionsAndPages

Difference between HashMap and Map in Java..?

Map is an interface; HashMap is a particular implementation of that interface.

HashMap uses a collection of hashed key values to do its lookup. TreeMap will use a red-black tree as its underlying data store.

Change first commit of project with Git?

As stated in 1.7.12 Release Notes, you may use

$ git rebase -i --root

Autoincrement VersionCode with gradle extra properties

To increment versionCode only in release version do it:

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    def versionPropsFile = file('')
    def code = 1;
    if (versionPropsFile.canRead()) {
        def Properties versionProps = new Properties()

        versionProps.load(new FileInputStream(versionPropsFile))
        List<String> runTasks = gradle.startParameter.getTaskNames();
        def value = 0
        for (String item : runTasks)
        if ( item.contains("assembleRelease")) {
            value = 1;
        code = Integer.parseInt(versionProps['VERSION_CODE']).intValue() + value
        versionProps['VERSION_CODE']=code.toString(), null)
    else {
        throw new GradleException("Could not read!")

    defaultConfig {
        applicationId "com.pack"
        minSdkVersion 14
        targetSdkVersion 21
        versionName "1.0."+ code
        versionCode code

expects an existing c://YourProject/app/ file, which you would create by hand before the first build to have VERSION_CODE=8



Boolean operators ( &&, -a, ||, -o ) in Bash

-a and -o are the older and/or operators for the test command. && and || are and/or operators for the shell. So (assuming an old shell) in your first case,

[ "$1" = 'yes' ] && [ -r $2.txt ]

The shell is evaluating the and condition. In your second case,

[ "$1" = 'yes' -a $2 -lt 3 ]

The test command (or builtin test) is evaluating the and condition.

Of course in all modern or semi-modern shells, the test command is built in to the shell, so there really isn't any or much difference. In modern shells, the if statement can be written:

[[ $1 == yes && -r $2.txt ]]

Which is more similar to modern programming languages and thus is more readable.

Easy way to use variables of enum types as string in C?

There is definitely a way to do this -- use X() macros. These macros use the C preprocessor to construct enums, arrays and code blocks from a list of source data. You only need to add new items to the #define containing the X() macro. The switch statement would expand automatically.

Your example can be written as follows:

 // Source data -- Enum, String
 #define X_NUMBERS \
    X(ONE,   "one") \
    X(TWO,   "two") \
    X(THREE, "three")


 // Use preprocessor to create the Enum
 typedef enum {
  #define X(Enum, String)       Enum,
  #undef X
 } Numbers;


 // Use Preprocessor to expand data into switch statement cases
 #define X(Enum, String) \
     case Enum:  strcpy(num_str, String); break;
 #undef X

     default: return 0; break;
 return 1;

There are more efficient ways (i.e. using X Macros to create an string array and enum index), but this is the simplest demo.

Add JsonArray to JsonObject

Just try below a simple solution:

JsonObject body=new JsonObject();
body.add("orders", (JsonElement) orders);

whenever my JSON request is like:

      "role": "RT",
      "orders": [
          "order_id": "ORDER201908aPq9Gs",
          "cart_id": 164444,
          "affiliate_id": 0,
          "orm_order_status": 9,
          "status_comments": "IC DUE - Auto moved to Instruction Call Due after 48hrs",
          "status_date": "2020-04-15",

Multi-gradient shapes

You CAN do it using only xml shapes - just use layer-list AND negative padding like this:


                <solid android:color="#ffffff" />

                <padding android:top="20dp" />

                <gradient android:endColor="#ffffff" android:startColor="#efefef" android:type="linear" android:angle="90" />

                <padding android:top="-20dp" />


What is MVC and what are the advantages of it?

![mvc architecture][1]

Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces. It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented to or accepted from the user.

How to compile python script to binary executable

I recommend PyInstaller, a simple python script can be converted to an exe with the following commands:

utils/ [--onefile]

which creates a yourprogram.spec file which is a configuration for building the final exe. Next command builds the exe from the configuration file:

utils/ oldlogs.spec

More can be found here

Swift alert view with OK and Cancel: which button tapped?

var refreshAlert = UIAlertController(title: "Log Out", message: "Are You Sure to Log Out ? ", preferredStyle: UIAlertControllerStyle.Alert)

refreshAlert.addAction(UIAlertAction(title: "Confirm", style: .Default, handler: { (action: UIAlertAction!) in

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in

    refreshAlert .dismissViewControllerAnimated(true, completion: nil)


presentViewController(refreshAlert, animated: true, completion: nil)

Getting the difference between two repositories

I use PyCharm which has great capabilities to compare between folders and files.

Just open the parent folder for both repos and wait until it indexes. Then you can use right click on a folder or file and Compare to... and pick the corresponding folder / file on the other side.

It shows not only what files are different but also their content. Much easier than command line.

How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3?

Anyone looking for this functionality past 2018: it's much cleaner to do this with just CSS using position: sticky.

position: sticky doesn't work with some table elements (thead/tr) in Chrome. You can move sticky to tds/ths of tr you need to be sticky. Like this:

thead tr:nth-child(1) th {
  background: white;
  position: sticky;
  top: 0;
  z-index: 10;

Eclipse jump to closing brace

Press Ctrl + Shift + P.

Before Eclipse Juno you need to place the cursor just beyond an opening or closing brace.

In Juno cursor can be anywhere in the code block.

Show a div with Fancybox

You just use this and it will be helpful for you

$("#btnForm").click(function (){

    'padding':  0,
    'width':    1087,
    'height':   610,
    'type':     'iframe',
    content:   $('#divForm').show();


How can I create a product key for my C# application?

If you want a simple solution just to create and verify serial numbers, try Ellipter. It uses elliptic curves cryptography and has an "Expiration Date" feature so you can create trial verisons or time-limited registration keys.

How can I solve the error 'TS2532: Object is possibly 'undefined'?

With the release of TypeScript 3.7, optional chaining (the ? operator) is now officially available.

As such, you can simplify your expression to the following:

const data = change?.after?.data();

You may read more about it from that version's release notes, which cover other interesting features released on that version.

Run the following to install the latest stable release of TypeScript.

npm install typescript

That being said, Optional Chaining can be used alongside Nullish Coalescing to provide a fallback value when dealing with null or undefined values

const data = change?.after?.data() ?? someOtherData();

Using jQuery to build table rows from AJAX response(json)

Try it like this:

$.each(response, function(i, item) {
    $('<tr>').html("<td>" + response[i].rank + "</td><td>" + response[i].content + "</td><td>" + response[i].UID + "</td>").appendTo('#records_table');


SELECTING with multiple WHERE conditions on same column

SELECT contactid, Count(*) 
FROM <YOUR_TABLE> WHERE flag in ('Volunteer','Uploaded')  
GROUP BY contactid 
HAVING count(*)>1;

Using sendmail from bash script for multiple recipients

Try doing this :

recipients="[email protected],[email protected],[email protected]"

And another approach, using shell here-doc :

/usr/sbin/sendmail "$recipients" <<EOF

Example Message

Be sure to separate the headers from the body with a blank line as per RFC 822.

Indent List in HTML and CSS

li {
  padding-left: 30px;
<p>Some text to show left edge of container.<p>
  <li>List item</li>
_x000D_ The above will add 30px of space between the bullet or number and your text.

li {
  margin-left: 30px;
<p>Some text to show left edge of container.<p>
  <li>List item</li>
_x000D_ The above will add 30px of space between the bullet or number and the left edge of the container.

What is token-based authentication?


Token-Based Authentication, relies on a signed token that is sent to the server on each request.

What are the benefits of using a token-based approach?

  • Cross-domain / CORS: cookies + CORS don't play well across different domains. A token-based approach allows you to make AJAX calls to any server, on any domain because you use an HTTP header to transmit the user information.

  • Stateless (a.k.a. Server side scalability): there is no need to keep a session store, the token is a self-contained entity that conveys all the user information. The rest of the state lives in cookies or local storage on the client side.

  • CDN: you can serve all the assets of your app from a CDN (e.g. javascript, HTML, images, etc.), and your server side is just the API.

  • Decoupling: you are not tied to any particular authentication scheme. The token might be generated anywhere, hence your API can be called from anywhere with a single way of authenticating those calls.

  • Mobile ready: when you start working on a native platform (iOS, Android, Windows 8, etc.) cookies are not ideal when consuming a token-based approach simplifies this a lot.

  • CSRF: since you are not relying on cookies, you don't need to protect against cross site requests (e.g. it would not be possible to sib your site, generate a POST request and re-use the existing authentication cookie because there will be none).

  • Performance: we are not presenting any hard perf benchmarks here, but a network roundtrip (e.g. finding a session on database) is likely to take more time than calculating an HMACSHA256 to validate a token and parsing its contents.

Maven - Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.4.1:clean

Delete the java.exe process in Task Manager and re-execute.It worked for me.

Count characters in textarea

$.fn.extend( {
       limiter: function(limit, elem) {
            $(this).on("keyup focus", function() {
               setCount(this, elem);
            function setCount(src, elem) {
               var chars = src.value.length;
                if (chars > limit) {
                    src.value = src.value.substr(0, limit);
                    chars = limit;
                elem.html( limit - chars );
            setCount($(this)[0], elem);

    var elem = $("#cntr");  
    $("#status_txt").limiter(160, elem);

Get Current date & time with [NSDate date]

NSLocale* currentLocale = [NSLocale currentLocale];
[[NSDate date] descriptionWithLocale:currentLocale];  

or use

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM 
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);

Interfaces — What's the point?

For me, when starting out, the point to these only became clear when you stop looking at them as things to make your code easier/faster to write - this is not their purpose. They have a number of uses:

(This is going to lose the pizza analogy, as it's not very easy to visualise a use of this)

Say you are making a simple game on screen and It will have creatures with which you interact.

A: They can make your code easier to maintain in the future by introducing a loose coupling between your front end and your back end implementation.

You could write this to start with, as there are only going to be trolls:

// This is our back-end implementation of a troll
class Troll
    void Walk(int distance)
        //Implementation here

Front end:

function SpawnCreature()
    Troll aTroll = new Troll();


Two weeks down the line, marketing decide you also need Orcs, as they read about them on twitter, so you would have to do something like:

class Orc
    void Walk(int distance)
        //Implementation (orcs are faster than trolls)

Front end:

void SpawnCreature(creatureType)
         case Orc:

           Orc anOrc = new Orc();

          case Troll:

            Troll aTroll = new Troll();

And you can see how this starts to get messy. You could use an interface here so that your front end would be written once and (here's the important bit) tested, and you can then plug in further back end items as required:

interface ICreature
    void Walk(int distance)

public class Troll : ICreature
public class Orc : ICreature 


Front end is then:

void SpawnCreature(creatureType)
    ICreature creature;

         case Orc:

           creature = new Orc();

          case Troll:

            creature = new Troll();


The front end now only cares about the interface ICreature - it's not bothered about the internal implementation of a troll or an orc, but only on the fact that they implement ICreature.

An important point to note when looking at this from this point of view is that you could also easily have used an abstract creature class, and from this perspective, this has the same effect.

And you could extract the creation out to a factory:

public class CreatureFactory {

 public ICreature GetCreature(creatureType)
    ICreature creature;

         case Orc:

           creature = new Orc();

          case Troll:

            creature = new Troll();

    return creature;

And our front end would then become:

CreatureFactory _factory;

void SpawnCreature(creatureType)
    ICreature creature = _factory.GetCreature(creatureType);


The front end now does not even have to have a reference to the library where Troll and Orc are implemented (providing the factory is in a separate library) - it need know nothing about them whatsoever.

B: Say you have functionality that only some creatures will have in your otherwise homogenous data structure, e.g.

interface ICanTurnToStone
   void TurnToStone();

public class Troll: ICreature, ICanTurnToStone

Front end could then be:

void SpawnCreatureInSunlight(creatureType)
    ICreature creature;

         case Orc:

           creature = new Orc();

          case Troll:

            creature = new Troll();


    if (creature is ICanTurnToStone)

C: Usage for dependency injection

Most dependency injection frameworks are easier to work with when there is a very loose coupling between the front end code and the back end implementation. If we take our factory example above and have our factory implement an interface:

public interface ICreatureFactory {
     ICreature GetCreature(string creatureType);

Our front end could then have this injected (e.g an MVC API controller) through the constructor (typically):

public class CreatureController : Controller {

   private readonly ICreatureFactory _factory;

   public CreatureController(ICreatureFactory factory) {
     _factory = factory;

   public HttpResponseMessage TurnToStone(string creatureType) {

       ICreature creature = _factory.GetCreature(creatureType);


       return Request.CreateResponse(HttpStatusCode.OK);

With our DI framework (e.g. Ninject or Autofac), we can set them up so that at runtime a instance of CreatureFactory will be created whenever an ICreatureFactory is needed in an constructor - this makes our code nice and simple.

It also means that when we write a unit test for our controller, we can provide a mocked ICreatureFactory (e.g. if the concrete implementation required DB access, we don't want our unit tests dependent on that) and easily test the code in our controller.

D: There are other uses e.g. you have two projects A and B that for 'legacy' reasons are not well structured, and A has a reference to B.

You then find functionality in B that needs to call a method already in A. You can't do it using concrete implementations as you get a circular reference.

You can have an interface declared in B that the class in A then implements. Your method in B can be passed an instance of a class that implements the interface with no problem, even though the concrete object is of a type in A.

Upgrade version of Pandas

According to an article on Medium, this will work:

install --upgrade pandas==1.0.0rc0

I want to exception handle 'list index out of range.'

for i in range (1, len(list))
        print (list[i])

    except ValueError:
        print("Error Value.")
    except indexError:
        print("Erorr index")
    except :
        print('error ')

Unable to add window -- token null is not valid; is your activity running?

This error happens when you are trying to show popUpWindow too early ,to fix it, give Id to main layout as main_layout and use below code


 findViewById( Runnable() {
   public void run() {
       popupWindow.showAtLocation(findViewById(, Gravity.CENTER, 0, 0);

Kotlin: {
      popupWindow?.showAtLocation(main_layout, Gravity.CENTER, 0, 0)

Credit to @kordzik

Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?

Some convenience functions:

public static void silentCloseResultSets(Statement st) {
    try {
        while (!(!st.getMoreResults() && (st.getUpdateCount() == -1))) {}
    } catch (SQLException ignore) {}
public static void silentCloseResultSets(Statement ...statements) {
    for (Statement st: statements) silentCloseResultSets(st);

JavaScript chop/slice/trim off last character in string

Use substring to get everything to the left of _bar. But first you have to get the instr of _bar in the string:

str.substring(3, 7);

3 is that start and 7 is the length.

How to measure time taken between lines of code in python?

Putting the code in a function, then using a decorator for timing is another option. (Source) The advantage of this method is that you define timer once and use it with a simple additional line for every function.

First, define timer decorator:

import functools
import time

def timer(func):
    def wrapper(*args, **kwargs):
        start_time = time.perf_counter()
        value = func(*args, **kwargs)
        end_time = time.perf_counter()
        run_time = end_time - start_time
        print("Finished {} in {} secs".format(repr(func.__name__), round(run_time, 3)))
        return value

    return wrapper

Then, use the decorator while defining the function:

def doubled_and_add(num):
    res = sum([i*2 for i in range(num)])
    print("Result : {}".format(res))

Let's try:



Result : 9999900000
Finished 'doubled_and_add' in 0.0119 secs
Result : 999999000000
Finished 'doubled_and_add' in 0.0897 secs

Note: I'm not sure why to use time.perf_counter instead of time.time. Comments are welcome.

Oracle - Insert New Row with Auto Incremental ID

This is a simple way to do it without any triggers or sequences:

insert into WORKQUEUE (ID, facilitycode, workaction, description)
  values ((select max(ID)+1 from WORKQUEUE), 'J', 'II', 'TESTVALUES')

It worked for me but would not work with an empty table, I guess.

Codeigniter LIKE with wildcard(%)

I'm using

$this->db->query("SELECT * FROM film WHERE film.title LIKE '%$query%'"); for such purposes

How do I check for null values in JavaScript?

Checking error conditions:

// Typical API response data
let data = {
  status: true,
  user: [],
  total: 0,
  activity: {sports: 1}

// A flag that checks whether all conditions were met or not
var passed = true;

// Boolean check
if (data['status'] === undefined || data['status'] == false){
  console.log("Undefined / no `status` data");
  passed = false;

// Array/dict check
if (data['user'] === undefined || !data['user'].length){
  console.log("Undefined / no `user` data");
  passed = false;

// Checking a key in a dictionary
if (data['activity'] === undefined || data['activity']['time'] === undefined){
   console.log("Undefined / no `time` data");
   passed = false;

// Other values check
if (data['total'] === undefined || !data['total']){
  console.log("Undefined / no `total` data");
  passed = false;

// Passed all tests?
if (passed){
  console.log("Passed all tests");

How to scale images to screen size in Pygame

You can scale the image with pygame.transform.scale:

import pygame
picture = pygame.image.load(filename)
picture = pygame.transform.scale(picture, (1280, 720))

You can then get the bounding rectangle of picture with

rect = picture.get_rect()

and move the picture with

rect = rect.move((x, y))
screen.blit(picture, rect)

where screen was set with something like

screen = pygame.display.set_mode((1600, 900))

To allow your widgets to adjust to various screen sizes, you could make the display resizable:

import os
import pygame
from pygame.locals import *

screen = pygame.display.set_mode((500, 500), HWSURFACE | DOUBLEBUF | RESIZABLE)
pic = pygame.image.load("image.png")
screen.blit(pygame.transform.scale(pic, (500, 500)), (0, 0))
while True:
    event = pygame.event.wait()
    if event.type == QUIT:
    elif event.type == VIDEORESIZE:
        screen = pygame.display.set_mode(
            event.dict['size'], HWSURFACE | DOUBLEBUF | RESIZABLE)
        screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0))

How can I create a border around an Android LinearLayout?

you can do it Pragmatically also

  GradientDrawable gradientDrawable=new GradientDrawable();

Then set the background of layout as :

LinearLayout layout = (LinearLayout ) findViewById(; layout .setBackground(gradientDrawable);

How to create a static library with g++?

You can create a .a file using the ar utility, like so:

ar crf lib/libHeader.a header.o

lib is a directory that contains all your libraries. it is good practice to organise your code this way and separate the code and the object files. Having everything in one directory generally looks ugly. The above line creates libHeader.a in the directory lib. So, in your current directory, do:

mkdir lib

Then run the above ar command.

When linking all libraries, you can do it like so:

g++ test.o -L./lib -lHeader -o test  

The -L flag will get g++ to add the lib/ directory to the path. This way, g++ knows what directory to search when looking for libHeader. -llibHeader flags the specific library to link.

where test.o is created like so:

g++ -c test.cpp -o test.o 

How to convert an OrderedDict into a regular dict in python3

It is easy to convert your OrderedDict to a regular Dict like this:

dict(OrderedDict([('method', 'constant'), ('data', '1.225')]))

If you have to store it as a string in your database, using JSON is the way to go. That is also quite simple, and you don't even have to worry about converting to a regular dict:

import json
d = OrderedDict([('method', 'constant'), ('data', '1.225')])
dString = json.dumps(d)

Or dump the data directly to a file:

with open('outFile.txt','w') as o:
    json.dump(d, o)

Replace non ASCII character from string

This would be the Unicode solution

String s = "A função, Ãugent";
String r = s.replaceAll("\\P{InBasic_Latin}", "");

\p{InBasic_Latin} is the Unicode block that contains all letters in the Unicode range U+0000..U+007F (see

\P{InBasic_Latin} is the negated \p{InBasic_Latin}

In Angular, I need to search objects in an array

Your solutions are correct but unnecessary complicated. You can use pure javascript filter function. This is your model:

     $scope.fishes = [{category:'freshwater', id:'1', name: 'trout', more:'false'},  {category:'freshwater', id:'2', name:'bass', more:'false'}];

And this is your function:

     $scope.showdetails = function(fish_id){
         var found = $scope.fishes.filter({id : fish_id});
         return found;

You can also use expression:

     $scope.showdetails = function(fish_id){
         var found = $scope.fishes.filter(function(fish){ return === fish_id });
         return found;

More about this function: LINK

Can't open config file: /usr/local/ssl/openssl.cnf on Windows

In my case I used the binaries from Shining Light and the environment variables were already updated. But still had the issue until I ran a command window with elevated privileges.

When you open the CMD window be sure to run it as Administrator. (Right click the Command Prompt in Start menu and choose "Run as administrator")

I think it can't read the files due to User Account Control.

Can HTML checkboxes be set to readonly?

you can use this:

<input type="checkbox" onclick="return false;"/>

This works because returning false from the click event stops the chain of execution continuing.

How to make a simple rounded button in Storyboard?

To do it in the storyboard, you need to use an image for the button.

Alternatively you can do it in code:

 btn.layer.cornerRadius = 10
 btn.clipsToBounds = true

how to call javascript function in html.actionlink in mvc?

<a onclick="MyFunc()">blabla..</a>

There is nothing more in @Html.ActionLink that you could utilize in this case. And razor is evel by itself, drop it from where you can.

Break when a value changes using the Visual Studio debugger

Update in 2019:

This is now officially supported in Visual Studio 2019 Preview 2 for .Net Core 3.0 or higher. Of course, you may have to put some thoughts in potential risks of using a Preview version of IDE. I imagine in the near future this will be included in the official Visual Studio.

Fortunately, data breakpoints are no longer a C++ exclusive because they are now available for .NET Core (3.0 or higher) in Visual Studio 2019 Preview 2!

XSL if: test with multiple test conditions

Thanks to @IanRoberts, I had to use the normalize-space function on my nodes to check if they were empty.

<xsl:if test="((node/ABC!='') and (normalize-space(node/DEF)='') and (normalize-space(node/GHI)=''))">
  This worked perfectly fine.

wp_nav_menu change sub-menu class name?

I had to change:

function start_lvl(&$output, $depth)


function start_lvl( &$output, $depth = 0, $args = array() )

Because I was getting an incompatibility error:

Strict Standards: Declaration of My_Walker_Nav_Menu::start_lvl() should be compatible with Walker_Nav_Menu::start_lvl(&$output, $depth = 0, $args = Array)

An internal error occurred during: "Updating Maven Project". java.lang.NullPointerException

I had the same issue ... solution at the end !

here the eclipse log:


... it comes from "appengine maven wtp plugin" that try to get the type of GAE runtime, but seems to be null here (... getRuntimeType() --> NPE):

see class

  private static IRuntime getGaeRuntime(String sdkVersion) {
    IRuntime[] runtimes = ServerCore.getRuntimes();
    for (IRuntime runtime : runtimes) {
      if (runtime != null &&  **runtime.getRuntimeType()**.equals(GAE_RUNTIME_TYPE)) {

So, if you check in eclipse, Google App Engine is visible , but when you select it you'll see that no SDK is associated ... preference/Server/Runtime environments

SOLUTION: in red on the screenshot ;-)

How do I initialize a byte array in Java?

My preferred option in this circumstance is to use org.apache.commons.codec.binary.Hex which has useful APIs for converting between Stringy hex and binary. For example:

  1. Hex.decodeHex(char[] data) which throws a DecoderException if there are non-hex characters in the array, or if there are an odd number of characters.

  2. Hex.encodeHex(byte[] data) is the counterpart to the decode method above, and spits out the char[].

  3. Hex.encodeHexString(byte[] data) which converts back from a byte array to a String.

Usage: Hex.decodeHex("dd645a2564cbe648c8336d2be5eafaa6".toCharArray())

SQL Query to fetch data from the last 30 days?

select status, timeplaced 
from orders 
where TIMEPLACED>'2017-06-12 00:00:00' 

Regex pattern for checking if a string starts with a certain substring?

I really recommend using the String.StartsWith method over the Regex.IsMatch if you only plan to check the beginning of a string.

  • Firstly, the regular expression in C# is a language in a language with does not help understanding and code maintenance. Regular expression is a kind of DSL.
  • Secondly, many developers does not understand regular expressions: it is something which is not understandable for many humans.
  • Thirdly, the StartsWith method brings you features to enable culture dependant comparison which regular expressions are not aware of.

In your case you should use regular expressions only if you plan implementing more complex string comparison in the future.

How to unlock a file from someone else in Team Foundation Server

In my case, I tried unlocking the file with tf lock but was told I couldn't because the stale workspace on an old computer that no longer existed was a local workspace. I then tried deleting the workspace with tf workspace /delete, but deleting the workspace did not remove the lock (and then I couldn't try to unlock it again because I just got an error saying the workspace no longer existed).

I ended up tf destroying the file and checking it in again, which was pretty silly and had the undesirable effect of removing\ it from previous changesets, but at least got us working again. It wasn't that big a deal in this case since the file had never been changed since being checked in.

Automated way to convert XML files to SQL database?

If there is XML file with 2 different tables then will:



Performing a Stress Test on Web Application?

Visual Studio Test Edition 2010 (2008 good too). This is a really easy and powerful tool to create web/load tests with.

The bonus with this tool when using against Windows servers is that you get integrated access to all the perfmon server stats in your report. Really useful.

The other bonus is that with Visual Studio project you can integrate a "Performance Session" that will profile the code execution of your website.

If you are serving webpages from a windows server, this is the best tool out there.

There is a separate and expensive licence required to use several machines to load test the application however.

Pad left or right with string.format (not padleft or padright) with arbitrary string

There is another solution.

Implement IFormatProvider to return a ICustomFormatter that will be passed to string.Format :

public class StringPadder : ICustomFormatter
  public string Format(string format, object arg,
       IFormatProvider formatProvider)
     // do padding for string arguments
     // use default for others

public class StringPadderFormatProvider : IFormatProvider
  public object GetFormat(Type formatType)
     if (formatType == typeof(ICustomFormatter))
        return new StringPadder();

     return null;
  public static readonly IFormatProvider Default =
     new StringPadderFormatProvider();

Then you can use it like this :

string.Format(StringPadderFormatProvider.Default, "->{0:x20}<-", "Hello");

What is the difference between CHARACTER VARYING and VARCHAR in PostgreSQL?

The short answer: there is no difference.

The long answer: CHARACTER VARYING is the official type name from the ANSI SQL standard, which all compliant databases are required to support. VARCHAR is a shorter alias which all modern databases also support. I prefer VARCHAR because it's shorter and because the longer name feels pedantic. However, postgres tools like pg_dump and \d will output character varying.

Ansible: how to get output to display

Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register parameter, independently of the module used.

Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:

- hosts: localhost
    - shell: ls
      register: shell_result

    - debug:
        var: shell_result.stdout_lines

Here register tells ansible to save the response of the module into the shell_result variable, and then we use the debug module to print the variable out.

An example run would look like the this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
changed: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "shell_result.stdout_lines": [

Responses can contain multiple fields. stdout_lines is one of the default fields you can expect from a module's response.

Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout or stdout_lines values, however the msg field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.

Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v, -vvv and -vvvv. For example when running the playbook with verbosity (-vvv) you get this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
changed: [localhost] => {
    "changed": true,
    "cmd": "ls",
    "delta": "0:00:00.007621",
    "end": "2017-02-17 23:04:41.912570",
    "invocation": {
        "module_args": {
            "_raw_params": "ls",
            "_uses_shell": true,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "warn": true
        "module_name": "command"
    "rc": 0,
    "start": "2017-02-17 23:04:41.904949",
    "stderr": "",
    "stdout": "play.retry\nplay.yml",
    "stdout_lines": [
    "warnings": []

As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines is available, and its contents are what we expect.

To answer your main question about the jenkins_script module, if you check its documentation, you can see that it returns the output in the output field, so you might want to try the following:

  - jenkins_script:
      script: (...)
    register: jenkins_result

  - debug:
      var: jenkins_result.output

ASP.NET Identity reset password

Create method in UserManager<TUser, TKey>

public Task<IdentityResult> ChangePassword(int userId, string newPassword)
     var user = Users.FirstOrDefault(u => u.Id == userId);
     if (user == null)
          return new Task<IdentityResult>(() => IdentityResult.Failed());

     var store = Store as IUserPasswordStore<User, int>;
     return base.UpdatePassword(store, user, newPassword);

Converting a POSTMAN request to Curl

Starting from Postman 8 you need to visit here

enter image description here

How to query between two dates using Laravel and Eloquent?

The whereBetween method verifies that a column's value is between two values.

$from = date('2018-01-01');
$to = date('2018-05-02');

Reservation::whereBetween('reservation_from', [$from, $to])->get();

In some cases you need to add date range dynamically. Based on @Anovative's comment you can do this:

Reservation::all()->filter(function($item) {
  if (Carbon::now->between($item->from, $item->to) {
    return $item;

If you would like to add more condition then you can use orWhereBetween. If you would like to exclude a date interval then you can use whereNotBetween.

Reservation::whereBetween('reservation_from', [$from1, $to1])
  ->orWhereBetween('reservation_to', [$from2, $to2])
  ->whereNotBetween('reservation_to', [$from3, $to3])

Other useful where clauses: whereIn, whereNotIn, whereNull, whereNotNull, whereDate, whereMonth, whereDay, whereYear, whereTime, whereColumn, whereExists, whereRaw.

Laravel docs about Where Clauses.

Convert HH:MM:SS string to seconds only in javascript

Convert hh:mm:ss string to seconds in one line. Also allowed h:m:s format and mm:ss, m:s etc

'08:45:20'.split(':').reverse().reduce((prev, curr, i) => prev + curr*Math.pow(60, i), 0)

What is the difference between CloseableHttpClient and HttpClient in Apache HttpClient API?

  • The main entry point of the HttpClient API is the HttpClient interface.
  • The most essential function of HttpClient is to execute HTTP methods.
  • Execution of an HTTP method involves one or several HTTP request / HTTP response exchanges, usually handled internally by HttpClient.

  • CloseableHttpClient is an abstract class which is the base implementation of HttpClient that also implements
  • Here is an example of request execution process in its simplest form:

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet("http://localhost/");
    CloseableHttpResponse response = httpclient.execute(httpget);
    try {
        //do something
    } finally {

  • HttpClient resource deallocation: When an instance CloseableHttpClient is no longer needed and is about to go out of scope the connection manager associated with it must be shut down by calling the CloseableHttpClient#close() method.

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        //do something
    } finally {

see the Reference to learn fundamentals.

@Scadge Since Java 7, Use of try-with-resources statement ensures that each resource is closed at the end of the statement. It can be used both for the client and for each response

try(CloseableHttpClient httpclient = HttpClients.createDefault()){

    // e.g. do this many times
    try (CloseableHttpResponse response = httpclient.execute(httpget)) {
    //do something

    //do something else with httpclient here

jquery animate background position

Since jQuery doesn't support this out of the box, the best solution I have come across so far is to define your own CSS hooks in jQuery. Essentially, this means to define custom methods to get and set CSS values which also works with jQuery.animate().

There is already a very handy implementation for this on github:

With this plugin in place, you can do something like this:

  function() {
      backgroundPositionX: '100%',
      backgroundPositionY: '100%'
  function () {
      backgroundPositionX: '105%',
      backgroundPositionY: '105%'

For me, this worked on all browsers tested so far including IE6+.

I did put a quick demo online a while ago and you can rip it apart if you need further guidance.

Jenkins, specifying JAVA_HOME

On CentOS 6.x and Redhat 6.x systems, the openjdk-devel package contains the jdk. It's sensible enough if you are familiar with the -devel pattern used in RedHat, but confusing if you're looking for a jdk package that conforms to java naming standards.

oracle.jdbc.driver.OracleDriver ClassNotFoundException

try to add ojdbc6.jar or other version through the server lib "C:\apache-tomcat-7.0.47\lib",

Then restart the server in eclipse.

TCPDF output without saving file

If You want to open dialogue window in browser to save, not open with PDF browser viewer (I was looking for this solution for a while), You should use 'D':

$pdf->Output('name.pdf', 'D');

HTML Tags in Javascript Alert() method

alert() doesn't support HTML, but you have some alternatives to format your message.

You can use Unicode characters as others stated, or you can make use of the ES6 Template literals. For example:

.catch(function (error) {
  const alertMessage = `Error retrieving resource. Please make sure:
    • the resource server is accessible
    • you're logged in

    Error: ${error}`;

Output: enter image description here

As you can see, it maintains the line breaks and spaces that we included in the variable, with no extra characters.

How to get HttpClient returning status code and response body?

Fluent facade API:

Response response = Request.Get(uri)
HttpResponse httpResponse = response.returnResponse();
StatusLine statusLine = httpResponse.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
    // ??????????(???????)
    String responseContent = EntityUtils.toString(

Accessing localhost:port from Android emulator

After running your local host you get http://localhost:[port number]/ here you found your port number.

Then get your IP address from Command, Open your windows command and type ipconfig enter image description here

In my case, IP was so my URL will be[port number]/. In Android, the studio uses this URL as your URL. And after that set your URL and your port number in manual proxy for the emulator.

enter image description here

how to use html2canvas and jspdf to export to pdf in a proper and simple way

This one shows how to print only selected element on the page with dpi/resolution adjustments



    <header>This is the header</header>
    <div id="content">
      This is the element you only want to capture
    <button id="print">Download Pdf</button>
    <footer>This is the footer</footer>



body {
  background: beige;

header {
  background: red;

footer {
  background: blue;

#content {
  background: yellow;
  width: 70%;
  height: 100px;
  margin: 50px auto;
  border: 1px solid orange;
  padding: 20px;


$('#print').click(function() {

  var w = document.getElementById("content").offsetWidth;
  var h = document.getElementById("content").offsetHeight;
  html2canvas(document.getElementById("content"), {
    dpi: 300, // Set to 300 DPI
    scale: 3, // Adjusts your resolution
    onrendered: function(canvas) {
      var img = canvas.toDataURL("image/jpeg", 1);
      var doc = new jsPDF('L', 'px', [w, h]);
      doc.addImage(img, 'JPEG', 0, 0, w, h);'sample-file.pdf');


What is the difference between partitioning and bucketing a table in Hive ?

I think I am late in answering this question, but it keep coming up in my feed.

Navneet has provided excellent answer. Adding to it visually.

Partitioning helps in elimination of data, if used in WHERE clause, where as bucketing helps in organizing data in each partition into multiple files, so as same set of data is always written in same bucket. Helps a lot in joining of columns.

Suppose, you have a table with five columns, name, server_date, some_col3, some_col4 and some_col5. Suppose, you have partitioned the table on server_date and bucketed on name column in 10 buckets, your file structure will look something like below.

  1. server_date=xyz
    • 00000_0
    • 00001_0
    • 00002_0
    • ........
    • 00010_0

Here server_date=xyz is the partition and 000 files are the buckets in each partition. Buckets are calculated based on some hash functions, so rows with name=Sandy will always go in same bucket.

ASP.NET MVC: No parameterless constructor defined for this object

All of the answers say to create a parameters less constructor which isn't ideal if you don't want any other devs using it and only the model binder.

The attribute [Obsolete("For model binding only", true)] above a public constructor will throw a compiler error if another dev tries to use this. Took me ages to find this, hope it helps someone.

Encapsulation vs Abstraction?

Abstraction is a very general term, and abstraction in software is not limited to object-oriented languages. A dictionary definition: "the act of considering something as a general quality or characteristic, apart from concrete realities, specific objects, or actual instances".

Assembly language can be thought of as an abstraction of machine code -- assembly expresses the essential details and structure of the machine code, but frees you from having to think about the opcodes used, the layout of the code in memory, making jumps go to the right address, etc.

Your operating system's API is an abstraction of the underlying machine. Your compiler provides a layer of abstraction which shields you from the details of assembly language. The TCP/IP stack built into your operating system abstracts away the details of transmitting bits over a network. If you go down all the way to the raw silicon, the people who designed your CPU did so using circuit diagrams written in terms of "diodes" and "transistors", which are abstractions of how electrons travel through semiconductor crystals.

In software, everything is an abstraction. We build programs which simulate or model some aspect of reality, but by necessity our models always abstract away some details of the "real thing". We build layer on layer on layer of abstractions, because it is the only way we get anything done. (Imagine you were trying to make, say, a sudoku solver, and you had to design it using only semiconductor crystals. "OK, I need a piece of N-type silicon here...")

In comparison, "encapsulation" is a very specific and limited term. Some of the other answers to this question have already given good definitions for it.

Adding placeholder attribute using Jquery

You just need this:

$(".hidden").attr("placeholder", "Type here to search");

classList is used for manipulating classes and not attributes.

How do I install opencv using pip?

Install opencv-python (which is an unofficial pre-built OpenCV package for Python) by issuing the following command:

pip install opencv-python

How to limit the maximum files chosen when using multiple file input

On change of the input track how many files are selected:

$("#image").on("change", function() {_x000D_
    if ($("#image")[0].files.length > 2) {_x000D_
        alert("You can select only 2 images");_x000D_
    } else {_x000D_
<script src=""></script>_x000D_
<strong>On change of the input track how many files are selected:</strong>_x000D_
<input name="image[]" id="image" type="file"  multiple="multiple" accept="image/jpg, image/jpeg" >

HTML5 required attribute seems not working

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

cannot make a static reference to the non-static field

Just write:

private static double balance = 0;

and you could also write those like that:

private static int id = 0;
private static double annualInterestRate = 0;
public static java.util.Date dateCreated;

XPath query to get nth instance of an element

This is a FAQ:


means "Find every node selected by //somexpression that is the $Nth child of its parent".

What you want is:


Remember: The [] operator has higher precedence (priority) than the // abbreviation.

How to compare only date in moment.js

The docs are pretty clear that you pass in a second parameter to specify granularity.

If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.

moment('2010-10-20').isAfter('2010-01-01', 'year'); // false
moment('2010-10-20').isAfter('2009-12-31', 'year'); // true

As the second parameter determines the precision, and not just a single value to check, using day will check for year, month and day.

For your case you would pass 'day' as the second parameter.

How to retrieve form values from HTTPPOST, dictionary or?

You could have your controller action take an object which would reflect the form input names and the default model binder will automatically create this object for you:

public ActionResult SubmitAction(SomeModel model)
    var value1 = model.SimpleProp1;
    var value2 = model.SimpleProp2;
    var value3 = model.ComplexProp1.SimpleProp1;

    ... return something ...

Another (obviously uglier) way is:

public ActionResult SubmitAction()
    var value1 = Request["SimpleProp1"];
    var value2 = Request["SimpleProp2"];
    var value3 = Request["ComplexProp1.SimpleProp1"];

    ... return something ...

ReDim Preserve to a Multi-Dimensional Array in Visual Basic 6

I stumbled across this question while hitting this road block myself. I ended up writing a piece of code real quick to handle this ReDim Preserve on a new sized array (first or last dimension). Maybe it will help others who face the same issue.

So for the usage, lets say you have your array originally set as MyArray(3,5), and you want to make the dimensions (first too!) larger, lets just say to MyArray(10,20). You would be used to doing something like this right?

 ReDim Preserve MyArray(10,20) '<-- Returns Error

But unfortunately that returns an error because you tried to change the size of the first dimension. So with my function, you would just do something like this instead:

 MyArray = ReDimPreserve(MyArray,10,20)

Now the array is larger, and the data is preserved. Your ReDim Preserve for a Multi-Dimension array is complete. :)

And last but not least, the miraculous function: ReDimPreserve()

'redim preserve both dimensions for a multidimension array *ONLY
Public Function ReDimPreserve(aArrayToPreserve,nNewFirstUBound,nNewLastUBound)
    ReDimPreserve = False
    'check if its in array first
    If IsArray(aArrayToPreserve) Then       
        'create new array
        ReDim aPreservedArray(nNewFirstUBound,nNewLastUBound)
        'get old lBound/uBound
        nOldFirstUBound = uBound(aArrayToPreserve,1)
        nOldLastUBound = uBound(aArrayToPreserve,2)         
        'loop through first
        For nFirst = lBound(aArrayToPreserve,1) to nNewFirstUBound
            For nLast = lBound(aArrayToPreserve,2) to nNewLastUBound
                'if its in range, then append to new array the same way
                If nOldFirstUBound >= nFirst And nOldLastUBound >= nLast Then
                    aPreservedArray(nFirst,nLast) = aArrayToPreserve(nFirst,nLast)
                End If
        'return the array redimmed
        If IsArray(aPreservedArray) Then ReDimPreserve = aPreservedArray
    End If
End Function

I wrote this in like 20 minutes, so there's no guarantees. But if you would like to use or extend it, feel free. I would've thought that someone would've had some code like this up here already, well apparently not. So here ya go fellow gearheads.

How can I rotate an HTML <div> 90 degrees?

Use the css "rotate()" method:

div {
  width: 100px;
  height: 100px;
  background-color: yellow;
  border: 1px solid black;

  transform: rotate(90deg);
normal div

<div id="rotate">
This div is rotated 90 degrees

Add an index (numeric ID) column to large data frame

You can add a sequence of numbers very easily with

data$ID <-

If you are already using library(tidyverse), you can use

data <- tibble::rowid_to_column(data, "ID")

Convert base64 string to image

ImageIO.write() will compress the image by default - the compressed image has a smaller size but looks strange sometimes. I use BufferedOutputStream to save the byte array data - this will keep the original image size.

Here is the code:

import javax.xml.bind.DatatypeConverter;

public class ImageTest {
    public static void main(String[] args) {
        String base64String = "data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAHkAAAB5C...";
        String[] strings = base64String.split(",");
        String extension;
        switch (strings[0]) {//check image's extension
            case "data:image/jpeg;base64":
                extension = "jpeg";
            case "data:image/png;base64":
                extension = "png";
            default://should write cases for more images types
                extension = "jpg";
        //convert base64 string to binary data
        byte[] data = DatatypeConverter.parseBase64Binary(strings[1]);
        String path = "C:\\Users\\Ene\\Desktop\\test_image." + extension;
        File file = new File(path);
        try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file))) {
        } catch (IOException e) {

wget ssl alert handshake failure

It works from here with same OpenSSL version, but a newer version of wget (1.15). Looking at the Changelog there is the following significant change regarding your problem:

1.14: Add support for TLS Server Name Indication.

Note that this site does not require SNI. But requires it. And if you would call wget with -v --debug (as I've explicitly recommended in my comment!) you will see:

$ wget
HTTP request sent, awaiting response...
  HTTP/1.1 302 Found
Location: [following]
Connecting to (||:443... connected.
OpenSSL: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure
Unable to establish SSL connection.

So the error actually happens with and the reason is missing support for SNI. You need to upgrade your version of wget.

Running Selenium WebDriver python bindings in chrome

Mac OSX only

An easier way to get going (assuming you already have homebrew installed, which you should, if not, go do that first and let homebrew make your life better) is to just run the following command:

brew install chromedriver

That should put the chromedriver in your path and you should be all set.

Catching "Maximum request length exceeded"

I'm using a FileUpload control and client side script to check the file size.
HTML (note the OnClientClick - executed before OnClick):

<asp:FileUpload ID="FileUploader" runat="server" />
<br />
<asp:Button ID="btnUpload" Text="Upload" runat="server" OnClientClick="return checkFileSize()" OnClick="UploadFile" />
<br />
<asp:Label ID="lblMessage" runat="server" CssClass="lblMessage"></asp:Label>

Then the script (note the 'return false' if the size is too big: this is to cancel the OnClick):

function checkFileSize() 
    var input = document.getElementById("FileUploader");
    var lbl = document.getElementById("lblMessage");
    if (input.files[0].size < 4194304)
        lbl.className = "lblMessage";
        lbl.innerText = "File was uploaded";
        lbl.className = "lblError";
        lbl.innerText = "Your file cannot be uploaded because it is too big (4 MB max.)";
        return false;

How to add a JAR in NetBeans

Project Files Services Tabls

go files tabs

drag drop file to libs files hover.

return project tabs and what are you see :)

How to sort by two fields in Java?

Arrays.sort(persons, new PersonComparator());

import java.util.Comparator;

public class PersonComparator implements Comparator<? extends Person> {

    public int compare(Person o1, Person o2) {
        if(null == o1 || null == o2  || null == o1.getName() || null== o2.getName() ){
            throw new NullPointerException();
            int nameComparisonResult = o1.getName().compareTo(o2.getName());
            if(0 == nameComparisonResult){
                return o1.getAge()-o2.getAge();
                return nameComparisonResult;

class Person{
    int age; String name;

    public int getAge() {
        return age;

    public void setAge(int age) {
        this.age = age;

    public String getName() {
        return name;

    public void setName(String name) { = name;


Updated version:

public class PersonComparator implements Comparator<? extends Person> {

   public int compare(Person o1, Person o2) {

      int nameComparisonResult = o1.getName().compareToIgnoreCase(o2.getName());
      return 0 == nameComparisonResult?o1.getAge()-o2.getAge():nameComparisonResult;


Is there any way to redraw tmux window when switching smaller monitor to bigger one?

This is still the top post when searching, but it's no longer valid. Best answer is here, but the TLDR is

<c-b>:resize-window -A

Why is python saying invalid command 'bdist_wheel' on Travis CI?

pip install wheel

worked for me, but you can also add this


to and save yourself a pip install command

Access to Image from origin 'null' has been blocked by CORS policy

Try to bypass CORS:

For Chrome: edit shortcut or with cmd: C:\Chrome.exe --disable-web-security

For Firefox: Open Firefox and type about:config into the URL bar. search for: security.fileuri.strict_origin_policy set to false

What should be the values of GOPATH and GOROOT?

If you are using the distro go, you should point to where the include files are, for example:

$ rpm -ql golang | grep include

(This is for Fedora 20)

How to display tables on mobile using Bootstrap?

You might also consider trying one of these approaches, since larger tables aren't exactly friendly on mobile even if it works:

I'm partial to 'No More Tables' but that obviously depends on your application.

Using "Object.create" instead of "new"

With only one level of inheritance, your example may not let you see the real benefits of Object.create.

This methods allows you to easily implement differential inheritance, where objects can directly inherit from other objects.

On your userB example, I don't think that your init method should be public or even exist, if you call again this method on an existing object instance, the id and name properties will change.

Object.create lets you initialize object properties using its second argument, e.g.:

var userB = {
  sayHello: function() {
    console.log('Hello '+;

var bob = Object.create(userB, {
  'id' : {
    value: MY_GLOBAL.nextId(),
    enumerable:true // writable:false, configurable(deletable):false by default
  'name': {
    value: 'Bob',
    enumerable: true

As you can see, the properties can be initialized on the second argument of Object.create, with an object literal using a syntax similar to the used by the Object.defineProperties and Object.defineProperty methods.

It lets you set the property attributes (enumerable, writable, or configurable), which can be really useful.

Add a fragment to the URL without causing a redirect?

For straight HTML, with no JavaScript required:

<a href="#something">Add '#something' to URL</a>

Or, to take your question more literally, to just add '#' to the URL:

<a href="#">Add '#' to URL</a>