Programs & Examples On #Sqlobject

SQLObject is a powerful ORM for Python

What's the simplest way to print a Java array?

If you're using Java 1.4, you can instead do:


(This works in 1.5+ too, of course.)

How to find a text inside SQL Server procedures / triggers?

Any searching with select statement yield you only object name, where search keyword contains. Easiest and efficient way is get script of procedure/function and then search in generated text file, I also follows this technique :) So you are exact pinpoint.

How to check if a column is empty or null using SQL query select statement?

An answer above got me 99% of the way there (thanks Denis Ivin!). For my PHP / MySQL implementation, I needed to change the syntax a little:

FROM UserProfile
WHERE PropertydefinitionID in (40, 53)
AND (LENGTH(IFNULL(PropertyValue,'')) = 0)

LEN becomes LENGTH and ISNULL becomes IFNULL.

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

Using alternative dplyr package:

library("dplyr") # or library("tidyverse")

df <- df %>% mutate(id = row_number())

How to add rows dynamically into table layout

You might be better off using a ListView with a CursorAdapter (or SimpleCursorAdapter).

These are built to show rows from a sqlite database and allow refreshing with minimal programming on your part.

Edit - here is a tutorial involving SimpleCursorAdapter and ListView including sample code.

What are some great online database modeling tools?

You may want to look at IBExpert Personal Edition. While not open source, this is a very good tool for designing, building, and administering Firebird and InterBase databases.

The Personal Edition is free, but some of the more advanced features are not available. Still, even without the slick extras, the free version is very powerful.

printing all contents of array in C#

If you want to get cute, you could write an extension method that wrote an IEnumerable<object> sequence to the console. This will work with enumerables of any type, because IEnumerable<T> is covariant on T:

using System;
using System.Collections.Generic;

namespace Demo
    internal static class Program
        private static void Main(string[] args)
            string[] array  = new []{"One", "Two", "Three", "Four"};


            object[] objArray = new object[] {"One", 2, 3.3, TimeSpan.FromDays(4), '5', 6.6f, 7.7m};

    public static class MyEnumerableExt
        public static void Print(this IEnumerable<object> @this)
            foreach (var obj in @this)

(I don't think you'd use this other than in test code.)

An Iframe I need to refresh every 30 seconds (but not the whole page)

You can put a meta refresh Tag in the irc_online.php

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

OR you can use Javascript with setInterval to refresh the src of the Source...

window.setInterval("reloadIFrame();", 30000);

function reloadIFrame() {

Django. Override save for model

Query the database for an existing record with the same PK. Compare the file sizes and checksums of the new and existing images to see if they're the same.

Setting timezone to UTC (0) in PHP

Is 'UTC' a valid timezone identifier on your system?

if (date_default_timezone_set('UTC')){
    echo "UTC is a valid time zone";
    echo "The system doesn't know WTFUTC.  Maybe try updating tzinfo with your package manager?";

How do I insert multiple checkbox values into a table?

I think you should $_POST[][], i tried it and it work :)), tks

What is SOA "in plain english"?

I see many answers explaining a Service Oriented Architecture (SOA) using even more advanced words and technical terms. I'd like to give a shot at explaining it for the layman, using an analogy in plain english.

But first a description of a SOA
SOA could be described in three layers as seen in the picture below. On one side we have the Provider and on the other side we have the Consumer, separated by a Bridge where the two sides communicate.

The consumer uses a number of Applications necessary for it's business and the provider uses Components that provide these applications with information. They communicate through a set of Services using a common architecture.

enter image description here

The analogy
Imagine a house on the country side, that in many ways is part of a larger community, like a city or town. The city has it's own complex systems for providing water and electricity, handling sanitation, providing transportation and other utilities. The House is the consumer in this model, the City (or community) is the provider and the pipes, sewers, powerlines, optical fibers etc. is the Infrastructure in which they communicate.

This model could loosely be compared to a SOA. The people in the house uses a number of different "applications" like radiators, computers, toilets, lamps, underfloor heating, bathtubs etc. These applications don't care how the city generates the water, creates the electricity or handles the waste as long as it works. The components of the city are generators, water pumps and sanitation areas. It provides the house with all these needs but it's up to the house to use it in what ever way it sees fit.

I hope this gave at least someone a better picture of a SOA.

Local storage in Angular 2

Here is an example of a simple service, that uses localStorage to persist data:

import { Injectable } from '@angular/core';

export class PersistanceService {
  constructor() {}

  set(key: string, data: any): void {
    try {
      localStorage.setItem(key, JSON.stringify(data));
    } catch (e) {
      console.error('Error saving to localStorage', e);

  get(key: string) {
    try {
      return JSON.parse(localStorage.getItem(key));
    } catch (e) {
      console.error('Error getting data from localStorage', e);
      return null;

To use this services, provide it in some module in your app like normal, for example in core module. Then use like this:

import { Injectable } from '@angular/core';

export class SomeOtherService {

  constructor(private persister: PersistanceService) {}

  someMethod() {
    const myData = {foo: 'bar'};
    persister.set('SOME_KEY', myData);

  someOtherMethod() {
    const myData = persister.get('SOME_KEY');

Can Windows Containers be hosted on linux?

We can run Linux containers on Windows. Docker for Windows uses Hyper-v based Linux-Kit or WSL2 as backend to facilitate Linux containers.

If any Linux distribution having this kind of setup, we can run Windows containers. Docker for Linux supports only Linux containers.

How do I properly 'printf' an integer and a string in C?

scanf("%s",str) scans only until it finds a whitespace character. With the input "A 1", it will scan only the first character, hence s2 points at the garbage that happened to be in str, since that array wasn't initialised.

:after and :before pseudo-element selectors in Sass

Use ampersand to specify the parent selector.

SCSS syntax:

p {
    margin: 2em auto;

    > a {
        color: red;

    &:before {
        content: "";

    &:after {
        content: "* * *";

How can I print variable and string on same line in Python?

If you are using python 3.6 or latest, f-string is the best and easy one


ComboBox.SelectedText doesn't give me the SelectedText

From the documentation:

You can use the SelectedText property to retrieve or change the currently selected text in a ComboBox control. However, you should be aware that the selection can change automatically because of user interaction. For example, if you retrieve the SelectedText value in a button Click event handler, the value will be an empty string. This is because the selection is automatically cleared when the input focus moves from the combo box to the button.

When the combo box loses focus, the selection point moves to the beginning of the text and any selected text becomes unselected. In this case, getting the SelectedText property retrieves an empty string, and setting the SelectedText property adds the specified value to the beginning of the text.

How SQL query result insert in temp table?


exec('drop table #tab') -- you can add condition 'if table exists'
exec('select * into #tab from tab')

How to get error message when ifstream open fails

Every system call that fails update the errno value.

Thus, you can have more information about what happens when a ifstream open fails by using something like :

cerr << "Error: " << strerror(errno);

However, since every system call updates the global errno value, you may have issues in a multithreaded application, if another system call triggers an error between the execution of the and use of errno.

On system with POSIX standard:

errno is thread-local; setting it in one thread does not affect its value in any other thread.

Edit (thanks to Arne Mertz and other people in the comments):

e.what() seemed at first to be a more C++-idiomatically correct way of implementing this, however the string returned by this function is implementation-dependant and (at least in G++'s libstdc++) this string has no useful information about the reason behind the error...

How do I get next month date from today's date and insert it in my database?

Adding my solution here, as this is the thread that comes in google search. This is to get the next date of month, fixing any skips, keeping the next date within next month.

PHP adds current months total number of days to current date, if you do +1 month for example.

So applying +1 month to 30-01-2016 will return 02-03-2016. (Adding 31 days)

For my case, I needed to get 28-02-2016, so as to keep it within next month. In such cases you can use the solution below.

This code will identify if the given date's day is greater than next month's total days. If so It will subtract the days smartly and return the date within the month range.

Do note the return value is in timestamp format.

function getExactDateAfterMonths($timestamp, $months){
    $day_current_date            = date('d', $timestamp);
    $first_date_of_current_month = date('01-m-Y', $timestamp);
    // 't' gives last day of month, which is equal to no of days
    $days_in_next_month          = date('t',  strtotime("+".$months." months", strtotime($first_date_of_current_month)));

    $days_to_substract = 0;
    if($day_current_date > $days_in_next_month)
         $days_to_substract = $day_current_date - $days_in_next_month;

    $php_date_after_months   = strtotime("+".$months." months", $timestamp);
    $exact_date_after_months = strtotime("-".$days_to_substract." days", $php_date_after_months);

    return $exact_date_after_months;

getExactDateAfterMonths(strtotime('30-01-2016'), 1);
// $php_date_after_months   => 02-03-2016
// $exact_date_after_months => 28-02-2016

I need to round a float to two decimal places in Java

1.2975118E7 is scientific notation.

1.2975118E7 = 1.2975118 * 10^7 = 12975118

Also, Math.round(f) returns an integer. You can't use it to get your desired format x.xx.

You could use String.format.

String s = String.format("%.2f", 1.2975118);
// 1.30

Git Bash: Could not open a connection to your authentication agent

I would like to improve on the accepted answer

Downsides of using .bashrc with eval ssh-agent -s:

  1. Every git-bash will have it's own ssh-agent.exe process
  2. SSH key should be manually added every time you open git-bash

Here is my .bashrc that will eradicate above downsides

Put this .bashrc into your home directory (Windows 10: C:\Users\[username]\.bashrc) and it will be executed every time a new git-bash is opened and ssh-add will be working as a first class citizen

Read #comments to understand how it works

# Env vars used
# SSH_AUTH_SOCK - ssh-agent socket, should be set for ssh-add or git to be able to connect
# SSH_AGENT_PID - ssh-agent process id, should be set in order to check that it is running
# SSH_AGENT_ENV - env file path to share variable between instances of git-bash
# import env file and supress error message if it does not exist
. $SSH_AGENT_ENV 2> /dev/null

# if we know that ssh-agent was launched before ($SSH_AGENT_PID is set) and process with that pid is running 
if [ -n "$SSH_AGENT_PID" ] && ps -p $SSH_AGENT_PID > /dev/null 
  # we don't need to do anything, ssh-add and git will properly connect since we've imported env variables required
  echo "Connected to ssh-agent"
  # start ssh-agent and save required vars for sharing in $SSH_AGENT_ENV file
  eval $(ssh-agent) > /dev/null
  echo "Started ssh-agent"

Also this script uses a little trick to ensure that provided environment variables are shared between git-bash instances by saving them into an .env file.

What are the calling conventions for UNIX & Linux system calls (and user-space functions) on i386 and x86-64

Perhaps you're looking for the x86_64 ABI?

If that's not precisely what you're after, use 'x86_64 abi' in your preferred search engine to find alternative references.

HTTP POST Returns Error: 417 "Expectation Failed."

This same situation and error can also arise with a default wizard generated SOAP Web Service proxy (not 100% if this is also the case on the WCF System.ServiceModel stack) when at runtime:

  • the end user machine is configured (in the Internet Settings) to use a proxy that does not understand HTTP 1.1
  • the client ends up sending something that a HTTP 1.0 proxy doesnt understand (commonly an Expect header as part of a HTTP POST or PUT request due to a standard protocol convention of sending the request in two parts as covered in the Remarks here)

... yielding a 417.

As covered in the other answers, if the specific issue you run into is that the Expect header is causing the problem, then that specific problem can be routed around by doing a relatively global switching off of the two-part PUT/POST transmission via System.Net.ServicePointManager.Expect100Continue.

However this does not fix the complete underlying problem - the stack may still be using HTTP 1.1 specific things such as KeepAlives etc. (though in many cases the other answers do cover the main cases.)

The actual problem is however that the autogenerated code assumes that it's OK to go blindly using HTTP 1.1 facilities as everyone understands this. To stop this assumption for a specific Web Service proxy, one can change override the default underlying HttpWebRequest.ProtocolVersion from the default of 1.1 by creating a derived Proxy class which overrides protected override WebRequest GetWebRequest(Uri uri) as shown in this post:-

public class MyNotAssumingHttp11ProxiesAndServersProxy : MyWS
    protected override WebRequest GetWebRequest(Uri uri)
      HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(uri);
      request.ProtocolVersion = HttpVersion.Version10;
      return request;

(where MyWS is the proxy the Add Web Reference wizard spat out at you.)

UPDATE: Here's an impl I'm using in production:

class ProxyFriendlyXXXWs : BasicHttpBinding_IXXX
    public ProxyFriendlyXXXWs( Uri destination )
        Url = destination.ToString();

    // Make it squirm through proxies that don't understand (or are misconfigured) to only understand HTTP 1.0 without yielding HTTP 417s
    protected override WebRequest GetWebRequest( Uri uri )
        var request = (HttpWebRequest)base.GetWebRequest( uri );
        request.ProtocolVersion = HttpVersion.Version10;
        return request;

static class SoapHttpClientProtocolRealWorldProxyTraversalExtensions
    // OOTB, .NET 1-4 do not submit credentials to proxies.
    // This avoids having to document how to 'just override a setting on your default proxy in your app.config' (or machine.config!)
    public static void IfProxiedUrlAddProxyOverriddenWithDefaultCredentials( this SoapHttpClientProtocol that )
        Uri destination = new Uri( that.Url );
        Uri proxiedAddress = WebRequest.DefaultWebProxy.GetProxy( destination );
        if ( !destination.Equals( proxiedAddress ) )
            that.Proxy = new WebProxy( proxiedAddress ) { UseDefaultCredentials = true };

Java generating Strings with placeholders

See String.format method.

String s = "hello %s!";
s = String.format(s, "world");
assertEquals(s, "hello world!"); // should be true

Which JDK version (Language Level) is required for Android Studio?

Answer Clarification - Android Studio supports JDK8

The following is an answer to the question "What version of Java does Android support?" which is different from "What version of Java can I use to run Android Studio?" which is I believe what was actually being asked. For those looking to answer the 2nd question, you might find Using Android Studio with Java 1.7 helpful.

Also: See for Android Studio system requirements. JDK8 is actually a requirement for PC and linux (as of 5/14/16).

Java 8 update (3/19/14)

Because I'd assume this question will start popping up soon with the release yesterday: As of right now, there's no set date for when Android will support Java 8.

Here's a discussion over at /androiddev -

If you really want lambda support, you can checkout Retrolambda - I've never used it, but it seems fairly promising.

Another Update: Android added Java 7 support

Android now supports Java 7 (minus try-with-resource feature). You can read more about the Java 7 features here: If you're using gradle, you can add the following in your build.gradle:

android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7

Older response

I'm using Java 7 with Android Studio without any problems (OS X - 10.8.4). You need to make sure you drop the project language level down to 6.0 though. See the screenshot below.

enter image description here

What tehawtness said below makes sense, too. If they're suggesting JDK 6, it makes sense to just go with JDK 6. Either way will be fine.

enter image description here

Update: See this SO post --

Running an Excel macro via Python?

I did some modification to the SMNALLY's code so it can run in Python 3.5.2. This is my result:

#Import the following library to make use of the DispatchEx to run the macro
import win32com.client as wincl

def runMacro():

    if os.path.exists("C:\\Users\\Dev\\Desktop\\Development\\completed_apps\\My_Macr_Generates_Data.xlsm"):

    # DispatchEx is required in the newest versions of Python.
    excel_macro = wincl.DispatchEx("Excel.application")
    excel_path = os.path.expanduser("C:\\Users\\Dev\\Desktop\\Development\\completed_apps\\My_Macr_Generates_Data.xlsm")
    workbook = excel_macro.Workbooks.Open(Filename = excel_path, ReadOnly =1)
    #Save the results in case you have generated data
    del excel_macro

How do I create a ListView with rounded corners in Android?

The other answers are very useful, thanks to the authors!

But I could not see how to customise the rectangle when highlighting an item upon selection rather than disabling the highlighting @alvins @bharat dojeha.

The following works for me to create a rounded list view item container with no outline and a lighter grey when selected of the same shape:

Your xml needs to contain a selector such as e.g. ( in res/drawable/customshape.xml):

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="" >
<item android:state_pressed="true" >
    <shape xmlns:android="" >
        <stroke android:width="8dp" android:color="@android:color/transparent" />
        <padding android:left="14dp" android:top="14dp"
                android:right="14dp" android:bottom="14dp" />
        <corners android:radius="10dp" />
<item android:state_pressed="false">
    <shape xmlns:android="" >
        <stroke android:width="8dp" android:color="@android:color/transparent" />
        <padding android:left="14dp" android:top="14dp"
                android:right="14dp" android:bottom="14dp" />
        <corners android:radius="10dp" />

Then you need to implement a list adapter and override the getView method to set the custom selector as background

    public View getView(int position, View convertView, ViewGroup parent) {

and need to also 'hide' the default selector rectangle e.g in onCreate (I also hide my thin grey divider line between the items):


This approach solves a general solution for drawables, not just ListViewItem with various selection states.

What are the possible values of the Hibernate configuration and what do they do

To whomever searching for default value...

It is written in the source code at version 2.0.5 of spring-boot and 1.1.0 at JpaProperties:

     * DDL mode. This is actually a shortcut for the ""
     * property. Defaults to "create-drop" when using an embedded database and no
     * schema manager was detected. Otherwise, defaults to "none".
    private String ddlAuto;

No connection could be made because the target machine actively refused it

I had the same issue with a site which previously was running fine. I resolved the issue by deleting the temporary files from C:\WINDOWS\Microsoft.NET\Framework\v#.#.#####\Temporary ASP.NET Files\@projectName\###CC##C\###C#CC

Show red border for all invalid fields after submitting form angularjs

Reference article: Show red color border for invalid input fields angualrjs

I used ng-class on all input below

<input type="text" ng-class="{submitted:newEmployee.submitted}" placeholder="First Name" data-ng-model="model.firstName" id="FirstName" name="FirstName" required/>

when I click on save button I am changing newEmployee.submitted value to true(you can check it in my question). So when I click on save, a class named submitted gets added to all input fields(there are some other classes initially added by angularjs).

So now my input field contains classes like this

class="ng-pristine ng-invalid submitted"

now I am using below css code to show red border on all invalid input fields(after submitting the form)
  border:1px solid #f00;

Thank you !!


We can add the ng-class at the form element instead of applying it to all input elements. So if the form is submitted, a new class(submitted) gets added to the form element. Then we can select all the invalid input fields using the below selector

form.submitted .ng-invalid
    border:1px solid #f00;

Is Java a Compiled or an Interpreted programming language ?

Java does both compilation and interpretation,

In Java, programs are not compiled into executable files; they are compiled into bytecode (as discussed earlier), which the JVM (Java Virtual Machine) then interprets / executes at runtime. Java source code is compiled into bytecode when we use the javac compiler. The bytecode gets saved on the disk with the file extension .class.

When the program is to be run, the bytecode is converted the bytecode may be converted, using the just-in-time (JIT) compiler. The result is machine code which is then fed to the memory and is executed.

Javac is the Java Compiler which Compiles Java code into Bytecode. JVM is Java Virtual Machine which Runs/ Interprets/ translates Bytecode into Native Machine Code. In Java though it is considered as an interpreted language, It may use JIT (Just-in-Time) compilation when the bytecode is in the JVM. The JIT compiler reads the bytecodes in many sections (or in full, rarely) and compiles them dynamically into machine code so the program can run faster, and then cached and reused later without needing to be recompiled. So JIT compilation combines the speed of compiled code with the flexibility of interpretation.

An interpreted language is a type of programming language for which most of its implementations execute instructions directly and freely, without previously compiling a program into machine-language instructions. The interpreter executes the program directly, translating each statement into a sequence of one or more subroutines already compiled into machine code.

A compiled language is a programming language whose implementations are typically compilers (translators that generate machine code from source code), and not interpreters (step-by-step executors of source code, where no pre-runtime translation takes place)

In modern programming language implementations like in Java, it is increasingly popular for a platform to provide both options.

Convert xlsx to csv in Linux with command line

You can do this with LibreOffice:

libreoffice --headless --convert-to csv $filename --outdir $outdir

For reasons not clear to me, you might need to run this with sudo. You can make LibreOffice work with sudo without requiring a password by adding this line to you sudoers file:

users ALL=(ALL) NOPASSWD: libreoffice

Set attribute without value

Perhaps try:

var body = document.getElementsByTagName('body')[0];

What is a constant reference? (not a reference to a constant)

First I think int&const icr=i; is just int& icr = i, Modifier 'const' makes no sense(It just means you cannot make the reference refer to other variable).

const int x = 10;
// int& const y = x; // Compiler error here

Second, constant reference just means you cannot change the value of variable through reference.

const int x = 10;
const int& y = x;
//y = 20; // Compiler error here

Third, Constant references can bind right-value. Compiler will create a temp variable to bind the reference.

float x = 10;
const int& y = x;
const int& z = y + 10;
cout << (long long)&x << endl; //print 348791766212
cout << (long long)&y << endl; //print 348791766276
cout << (long long)&z << endl; //print 348791766340

HTTP client timeout and server timeout

According to, the pref network.http.connection-retry-timeout controls the amount of time in ms (Milliseconds !) to wait for success on the initial connection before beginning the second one. Setting it to 0 disables the parallel connection.

Text on image mouseover?

Here is one way to do this using css


<div class="imageWrapper">
    <img src="" alt="" />
    <a href="" class="cornerLink">Link</a>


.imageWrapper {
    position: relative;
    width: 300px;
    height: 300px;
.imageWrapper img {
    display: block;
.imageWrapper .cornerLink {
    opacity: 0;
    position: absolute;
    bottom: 0px;
    left: 0px;
    right: 0px;
    padding: 2px 0px;
    color: #ffffff;
    background: #000000;
    text-decoration: none;
    text-align: center;
    -webkit-transition: opacity 500ms;
    -moz-transition: opacity 500ms;
    -o-transition: opacity 500ms;
    transition: opacity 500ms;

.imageWrapper:hover .cornerLink {
    opacity: 0.8;


Or if you just want it in the bottom left corner:


Convert Java String to sql.Timestamp

You could use Timestamp.valueOf(String). The documentation states that it understands timestamps in the format yyyy-mm-dd hh:mm:ss[.f...], so you might need to change the field separators in your incoming string.

Then again, if you're going to do that then you could just parse it yourself and use the setNanos method to store the microseconds.

How do I tell matplotlib that I am done with a plot?

As stated from David Cournapeau, use figure().

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab

x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")

x = [10,100]
y = [10, 10000]
plt.loglog(x, y, basex=10, basey=10, ls="-")

Or subplot(121) / subplot(122) for the same plot, different position.

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab

x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")

x = [10,100]
y = [10, 10000]
plt.loglog(x, y, basex=10, basey=10, ls="-")

How to check if any Checkbox is checked in Angular

You can do something like:

function ChckbxsCtrl($scope, $filter) {
    $scope.chkbxs = [{
        label: "Led Zeppelin",
        val: false
    }, {
        label: "Electric Light Orchestra",
        val: false
    }, {
        label: "Mark Almond",
        val: false

    $scope.$watch("chkbxs", function(n, o) {
        var trues = $filter("filter")(n, {
            val: true
        $scope.flag = trues.length;
    }, true);

And a template:

<div ng-controller="ChckbxsCtrl">
    <div ng-repeat="chk in chkbxs">
        <input type="checkbox" ng-model="chk.val" />
    <div ng-show="flag">I'm ON when band choosed</div>


UPDATE: Or you can go little bit different way , without using $scope's $watch() method, like:

$scope.bandChoosed = function() {
    var trues = $filter("filter")($scope.chkbxs, {
        val: true
    return trues.length;

And in a template do:

<div ng-show="bandChoosed()">I'm ON when band choosed</div>


How to get the focused element with jQuery?

$( document.activeElement )

Will retrieve it without having to search the whole DOM tree as recommended on the jQuery documentation

How to have a drop down <select> field in a rails form?

Please have a look here

Either you can use rails tag Or use plain HTML tags

Rails tag

<%= select("Contact", "email_provider", Contact::PROVIDERS, {:include_blank => true}) %>

*above line of code would become HTML code(HTML Tag), find it below *

HTML tag

<select name="Contact[email_provider]">

Any way (or shortcut) to auto import the classes in IntelliJ IDEA like in Eclipse?

IntelliJ IDEA does not have an action to add imports. Rather it has the ability to do such as you type. If you enable the "Add unambiguous imports on the fly" in Settings > Editor > General > Auto Import, IntelliJ IDEA will add them as you type without the need for any shortcuts. You can also add classes and packages to exclude from auto importing to make a class you use heavily, that clashes with other classes of the same name, unambiguous.

For classes that are ambiguous (or is you prefer to have the "Add unambiguous imports on the fly" option turned off), just type the name of the class (just the name is OK, no need to fully qualify). Use code completion and select the particular class you want:

enter image description here

Notice the fully qualified names to the right. When I select the one I want and hit enter, IDEA will automatically add the import statement. This works the same if I was typing the name of a constructor. For static methods, you can even just keep typing the method you want. In the following screenshot, no "StringUtils" class is imported yet.

enter image description here

Alternatively, type the class name and then hit Alt+Enter or ?+Enter to "Show intention actions and quick-fixes" and then select the import option.

Although I've never used it, I think the Eclipse Code Formatter third party plug-in will do what you want. It lists "emulates Eclipse's imports optimizing" as a feature. See its instructions for more information. But in the end, I suspect you'll find the built in IDEA features work fine once you get use to their paradigm. In general, IDEA uses a "develop by intentions" concept. So rather than interrupting my development work to add an import statement, I just type the class I want (my intention) and IDEA automatically adds the import statement for the class for me.

how to get files from <input type='file' .../> (Indirect) with javascript

Based on Ray Nicholus's answer :

inputElement.onchange = function(event) {
   var fileList = inputElement.files;
   //TODO do something with fileList.  

using this will also work :

inputElement.onchange = function(event) {
   var fileList =;
   //TODO do something with fileList.  

Subtracting two lists in Python

To prove jkp's point that 'anything on one line will probably be helishly complex to understand', I created a one-liner. Please do not mod me down because I understand this is not a solution that you should actually use. It is just for demonstrational purposes.

The idea is to add the values in a one by one, as long as the total times you have added that value does is smaller than the total number of times this value is in a minus the number of times it is in b:

[ value for counter,value in enumerate(a) if a.count(value) >= b.count(value) + a[counter:].count(value) ]

The horror! But perhaps someone can improve on it? Is it even bug free?

Edit: Seeing Devin Jeanpierre comment about using a dictionary datastructure, I came up with this oneliner:

sum([ [value]*count for value,count in {value:a.count(value)-b.count(value) for value in set(a)}.items() ], [])

Better, but still unreadable.

Make div fill remaining space along the main axis in flexbox

Use the flex-grow property to make a flex item consume free space on the main axis.

This property will expand the item as much as possible, adjusting the length to dynamic environments, such as screen re-sizing or the addition / removal of other items.

A common example is flex-grow: 1 or, using the shorthand property, flex: 1.

Hence, instead of width: 96% on your div, use flex: 1.

You wrote:

So at the moment, it's set to 96% which looks OK until you really squash the screen - then the right hand div gets a bit starved of the space it needs.

The squashing of the fixed-width div is related to another flex property: flex-shrink

By default, flex items are set to flex-shrink: 1 which enables them to shrink in order to prevent overflow of the container.

To disable this feature use flex-shrink: 0.

For more details see The flex-shrink factor section in the answer here:

Learn more about flex alignment along the main axis here:

Learn more about flex alignment along the cross axis here:

C# - Simplest way to remove first occurrence of a substring from another string

If you'd like a simple method to resolve this problem. (Can be used as an extension)

See below:

    public static string RemoveFirstInstanceOfString(this string value, string removeString)
        int index = value.IndexOf(removeString, StringComparison.Ordinal);
        return index < 0 ? value : value.Remove(index, removeString.Length);


    string valueWithPipes = "| 1 | 2 | 3";
    string valueWithoutFirstpipe = valueWithPipes.RemoveFirstInstanceOfString("|");
    //Output, valueWithoutFirstpipe = " 1 | 2 | 3";

Inspired by and modified @LukeH's and @Mike's answer.

Don't forget the StringComparison.Ordinal to prevent issues with Culture settings.

How can I conditionally import an ES6 module?

I was able to achieve this using an immediately-invoked function and require statement.

const something = (() => (
  condition ? require('something') : null

if(something) {

How do I make WRAP_CONTENT work on a RecyclerView

This now works as they've made a release in version 23.2, as stated in this post. Quoting the official blogpost

This release brings an exciting new feature to the LayoutManager API: auto-measurement! This allows a RecyclerView to size itself based on the size of its contents. This means that previously unavailable scenarios, such as using WRAP_CONTENT for a dimension of the RecyclerView, are now possible. You’ll find all built in LayoutManagers now support auto-measurement.

What is the most "pythonic" way to iterate over a list in chunks?

Another approach would be to use the two-argument form of iter:

from itertools import islice

def group(it, size):
    it = iter(it)
    return iter(lambda: tuple(islice(it, size)), ())

This can be adapted easily to use padding (this is similar to Markus Jarderot’s answer):

from itertools import islice, chain, repeat

def group_pad(it, size, pad=None):
    it = chain(iter(it), repeat(pad))
    return iter(lambda: tuple(islice(it, size)), (pad,) * size)

These can even be combined for optional padding:

_no_pad = object()
def group(it, size, pad=_no_pad):
    if pad == _no_pad:
        it = iter(it)
        sentinel = ()
        it = chain(iter(it), repeat(pad))
        sentinel = (pad,) * size
    return iter(lambda: tuple(islice(it, size)), sentinel)

Run batch file as a Windows service

AlwaysUp will easily run your batch file as a service. It is similar to FireDaemon (mentioned above) and isn't free, but you may find the rich feature set to be an asset in a professional environment.

Good luck!

How to Solve the XAMPP 1.7.7 - PHPMyAdmin - MySQL Error #2002 in Ubuntu

Go to file using terminal by typing the following:

sudo gedit /opt/lampp/phpmyadmin/

The file will open in gedit.

Now open the file and edit

$cfg['Servers'][$i]['auth_type'] = 'localhost';


$cfg['Servers'][$i]['auth_type'] = 'cookie';

and keep the username as: root password:

Also make sure that the lines with username and password are not commented:

//$cfg['Servers'][$i]['user'] = 'root'; //$cfg['Servers'][$i]['password'] = '';

Make sure that // is removed from the above lines.

Finding the id of a parent div using Jquery

JQUery has a .parents() method for moving up the DOM tree you can start there.

If you're interested in doing this a more semantic way I don't think using the REL attribute on a button is the best way to semantically define "this is the answer" in your code. I'd recommend something along these lines:

<p id="question1">
    <label for="input1">Volume =</label> 
    <input type="text" name="userInput1" id="userInput1" />
    <button type="button">Check answer</button>
    <input type="hidden" id="answer1" name="answer1" value="3.93e-6" />


$("button").click(function () {
    var correctAnswer = $(this).parent().siblings("input[type=hidden]").val();
    var userAnswer = $(this).parent().siblings("input[type=text]").val();
    validate(userAnswer, correctAnswer);

Not quite sure how your validate and feedback are working, but you get the idea.

How store a range from excel into a Range variable?

What is currentWorksheet? It works if you use the built-in ActiveSheet.

Set currentWorksheet=ActiveSheet
dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, dataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))

How to compare two Carbon Timestamps?

First, Eloquent automatically converts it's timestamps (created_at, updated_at) into carbon objects. You could just use updated_at to get that nice feature, or specify edited_at in your model in the $dates property:

protected $dates = ['edited_at'];

Now back to your actual question. Carbon has a bunch of comparison functions:

  • eq() equals
  • ne() not equals
  • gt() greater than
  • gte() greater than or equals
  • lt() less than
  • lte() less than or equals


    // edited at is newer than created at

What is the keyguard in Android?

The lock screen works without keyguard i have tested it. The home button stops working and you can't get to task manager by holding the home key. I wish they didn't develop a new process when it used to be built into system ui or whatever. I don't see the need for the change and extra process

How to display list of repositories from subversion server

If you enable svn via apache and a SVNParentPath directive, you can add a SVNListParentPath On directive to your svn location to get a list of all repositories.

Your apache conf should look similar to this:

<Location /svn>
  DAV svn
  SVNParentPath         "/net/svn/repositories"
  # optional auth stuff     

  SVNListParentPath On    #  <--- Add this line to enable listing of all repos

How does cellForRowAtIndexPath work?

I'll try and break it down (example from documention)

 *   The cellForRowAtIndexPath takes for argument the tableView (so if the same object
 *   is delegate for several tableViews it can identify which one is asking for a cell),
 *   and an indexPath which determines which row and section the cell is returned for. 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

     *   This is an important bit, it asks the table view if it has any available cells
     *   already created which it is not using (if they are offScreen), so that it can
     *   reuse them (saving the time of alloc/init/load from xib a new cell ).
     *   The identifier is there to differentiate between different types of cells
     *   (you can display different types of cells in the same table view)

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];

     *   If the cell is nil it means no cell was available for reuse and that we should
     *   create a new one.
    if (cell == nil) {

         *   Actually create a new cell (with an identifier so that it can be dequeued). 

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"] autorelease];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;


     *   Now that we have a cell we can configure it to display the data corresponding to
     *   this row/section

    NSDictionary *item = (NSDictionary *)[self.content objectAtIndex:indexPath.row];
    cell.textLabel.text = [item objectForKey:@"mainTitleKey"];
    cell.detailTextLabel.text = [item objectForKey:@"secondaryTitleKey"];
    NSString *path = [[NSBundle mainBundle] pathForResource:[item objectForKey:@"imageKey"] ofType:@"png"];
    UIImage *theImage = [UIImage imageWithContentsOfFile:path];
    cell.imageView.image = theImage;

    /* Now that the cell is configured we return it to the table view so that it can display it */

    return cell;


This is a DataSource method so it will be called on whichever object has declared itself as the DataSource of the UITableView. It is called when the table view actually needs to display the cell onscreen, based on the number of rows and sections (which you specify in other DataSource methods).

Is a URL allowed to contain a space?

Can someone point to an RFC indicating that a URL with a space must be encoded?

URIs, and thus URLs, are defined in RFC 3986.

If you look at the grammar defined over there you will eventually note that a space character never can be part of a syntactically legal URL, thus the term "URL with a space" is a contradiction in itself.

Options for HTML scraping?

The Ruby world's equivalent to Beautiful Soup is why_the_lucky_stiff's Hpricot.

error MSB6006: "cmd.exe" exited with code 1

Navigate from Error List Tab to the Visual Studios Output folder by one of the following:

  • Select tab Output in standard VS view at the bottom
  • Click in Menubar View > Output or Ctrl+Alt+O

where Show output from <build> should be selected.

You can find out more by analyzing the output logs.

In my case it was an error in the Cmake step, see below. It could be in any build step, as described in the other answers.

> -- Build Type is debug 
> CMake Error in CMakeLists.txt:
>     A logical block opening on the line
>     <path_to_file:line_number>    
>     is not closed.

Explicitly calling return in a function or not

Question was: Why is not (explicitly) calling return faster or better, and thus preferable?

There is no statement in R documentation making such an assumption.
The main page ?'function' says:

function( arglist ) expr

Is it faster without calling return?

Both function() and return() are primitive functions and the function() itself returns last evaluated value even without including return() function.

Calling return() as .Primitive('return') with that last value as an argument will do the same job but needs one call more. So that this (often) unnecessary .Primitive('return') call can draw additional resources. Simple measurement however shows that the resulting difference is very small and thus can not be the reason for not using explicit return. The following plot is created from data selected this way:

bench_nor2 <- function(x,repeats) { system.time(rep(
# without explicit return
(function(x) vector(length=x,mode="numeric"))(x)
,repeats)) }

bench_ret2 <- function(x,repeats) { system.time(rep(
# with explicit return
(function(x) return(vector(length=x,mode="numeric")))(x)
,repeats)) }

maxlen <- 1000
reps <- 10000
along <- seq(from=1,to=maxlen,by=5)
ret <- sapply(along,FUN=bench_ret2,repeats=reps)
nor <- sapply(along,FUN=bench_nor2,repeats=reps)
res <- data.frame(N=along,ELAPSED_RET=ret["elapsed",],ELAPSED_NOR=nor["elapsed",])

# res object is then visualized
# R version 2.15

Function elapsed time comparison

The picture above may slightly difffer on your platform. Based on measured data, the size of returned object is not causing any difference, the number of repeats (even if scaled up) makes just a very small difference, which in real word with real data and real algorithm could not be counted or make your script run faster.

Is it better without calling return?

Return is good tool for clearly designing "leaves" of code where the routine should end, jump out of the function and return value.

# here without calling .Primitive('return')
> (function() {10;20;30;40})()
[1] 40
# here with .Primitive('return')
> (function() {10;20;30;40;return(40)})()
[1] 40
# here return terminates flow
> (function() {10;20;return();30;40})()
> (function() {10;20;return(25);30;40})()
[1] 25

It depends on strategy and programming style of the programmer what style he use, he can use no return() as it is not required.

R core programmers uses both approaches ie. with and without explicit return() as it is possible to find in sources of 'base' functions.

Many times only return() is used (no argument) returning NULL in cases to conditially stop the function.

It is not clear if it is better or not as standard user or analyst using R can not see the real difference.

My opinion is that the question should be: Is there any danger in using explicit return coming from R implementation?

Or, maybe better, user writing function code should always ask: What is the effect in not using explicit return (or placing object to be returned as last leaf of code branch) in the function code?

Where can I find error log files?

What OS you are using and which Webserver? On Linux and Apache you can find the apache error_log in /var/log/apache2/

Tool to convert java to c# code

For your reference:

Note: I had no experience on them.

Flexbox Not Centering Vertically in IE

I found that ie browser have problem to vertically align inner containers, when only the min-height style is set or when height style is missing at all. What I did was to add height style with some value and that fix the issue for me.

for example :

       display: -ms-flexbox;
       display: -webkit-flex;
       display: flex;

       /* Center vertically */
       align-items: center;

       /*Center horizontaly */
       justify-content: center;

       /*Center horizontaly ie */
       -ms-flex-pack: center;

        min-height: 220px; 

So now we have height style, but the min-height will overwrite it. That way ie is happy and we still can use min-height.

Hope this is helpful for someone.

Running Groovy script from the command line

You need to run the script like this:

groovy helloworld.groovy

Calling a JavaScript function returned from an Ajax response

If your AJAX script takes more than a couple milliseconds to run, eval() will always run ahead and evaluate the empty response element before AJAX populates it with the script you're trying to execute.

Rather than mucking around with timing and eval(), here is a pretty simple workaround that should work in most situations and is probably a bit more secure. Using eval() is generally frowned upon because the characters being evaluated as code can easily be manipulated client-side.


  1. Include your javascript function in the main page. Write it so that any dynamic elements can be accepted as arguments.
  2. In your AJAX file, call the function by using an official DOM event (onclick, onfocus, onblur, onload, etc.) Depending on what other elements are in your response, you can get pretty clever about making it feel seamless. Pass your dynamic elements in as arguments.
  3. When your response element gets populated and the event takes place, the function runs.


In this example, I want to attach a dynamic autocomplete list from the jquery-ui library to an AJAX element AFTER the element has been added to the page. Easy, right?


<!DOCTYPE html>
<!-- these libraries are for the autocomplete() function -->
<link rel="stylesheet" type="text/css" href="">
<script src=""></script>
<script src=""></script>
<script type="text/javascript">
// this is the ajax call
function editDemoText(ElementID,initialValue) {
    try { ajaxRequest = new XMLHttpRequest();
    } catch (e) {
    try { ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
    try { ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e) {
    return false;
    ajaxRequest.onreadystatechange = function() {
        if ( ajaxRequest.readyState == 4 ) {
            var ajaxDisplay = document.getElementById('responseDiv');
            ajaxDisplay.innerHTML = ajaxRequest.responseText;
    var queryString = "?ElementID="+ElementID+"&initialValue="+initialValue;"GET", "ajaxRequest.php"+queryString, true);

// this is the function we wanted to call in AJAX, 
// but we put it here instead with an argument (ElementID)
function AttachAutocomplete(ElementID) {
    // this list is static, but can easily be pulled in from 
    // a database using PHP. That would look something like this:
     * $list = "";
     * $r = mysqli_query($mysqli_link, "SELECT element FROM table");
     * while ( $row = mysqli_fetch_array($r) ) {
     *    $list .= "\".str_replace('"','\"',$row['element'])."\",";
     *    }
     * $list = rtrim($list,",");
    var availableIDs = ["Demo1","Demo2","Demo3","Demo4"];
    $("#"+ElementID).autocomplete({ source: availableIDs });
<!-- this is where the AJAX response sneaks in after DOM is loaded -->
<!-- we're using an onclick event to trigger the initial AJAX call -->
<div id="responseDiv"><a href="javascript:void(0);" onclick="editDemoText('EditableText','I am editable!');">I am editable!</a></div>


// for this application, onfocus works well because we wouldn't really 
// need the autocomplete populated until the user begins typing
echo "<input type=\"text\" id=\"".$_GET['ElementID']."\" onfocus=\"AttachAutocomplete('".$_GET['ElementID']."');\" value=\"".$_GET['initialValue']."\" />\n";

How to communicate between iframe and the parent site?

You can also use

postMessage(message, '*');

jquery animate .css

Just use .animate() instead of .css() (with a duration if you want), like this:

$('#hfont1').hover(function() {
    $(this).animate({"color":"#efbe5c","font-size":"52pt"}, 1000);
}, function() {
    $(this).animate({"color":"#e8a010","font-size":"48pt"}, 1000);

You can test it here. Note though, you need either the jQuery color plugin, or jQuery UI included to animate the color. In the above, the duration is 1000ms, you can change it, or just leave it off for the default 400ms duration.

How can I hide a TD tag using inline JavaScript or CSS?

You can simply hide the <td> tag content by just including a style attribute: style = "display:none"

For e.g

<td style = "display:none" >
<p> I'm invisible </p>

How to convert unsigned long to string

The standard approach is to use sprintf(buffer, "%lu", value); to write a string rep of value to buffer. However, overflow is a potential problem, as sprintf will happily (and unknowingly) write over the end of your buffer.

This is actually a big weakness of sprintf, partially fixed in C++ by using streams rather than buffers. The usual "answer" is to allocate a very generous buffer unlikely to overflow, let sprintf output to that, and then use strlen to determine the actual string length produced, calloc a buffer of (that size + 1) and copy the string to that.

This site discusses this and related problems at some length.

Some libraries offer snprintf as an alternative which lets you specify a maximum buffer size.

How do I break out of nested loops in Java?

Demo for break, continue, and label:

Java keywords break and continue have a default value. It's the "nearest loop", and today, after a few years of using Java, I just got it!

It's seem used rare, but useful.

import org.junit.Test;

 * Created by cui on 17-5-4.

public class BranchLabel {
    public void test() {



    public void testBreak() {
        for (int a = 0; a < 5; a++) {
            for (int b = 0; b < 5; b++) {
                if (b == 2) {
                System.out.println("a=" + a + ",b=" + b);

    public void testContinue() {
        for (int a = 0; a < 5; a++) {
            for (int b = 0; b < 5; b++) {
                if (b == 2) {
                System.out.println("a=" + a + ",b=" + b);

     * */
    public void testBreakLabel() {
        for (int a = 0; a < 5; a++) {
            for (int b = 0; b < 5; b++) {
                for (int c = 0; c < 5; c++) {
                    if (c == 2) {
                        break anyName;
                    System.out.println("a=" + a + ",b=" + b + ",c=" + c);

    public void testContinueLabel() {
        for (int a = 0; a < 5; a++) {
            for (int b = 0; b < 5; b++) {
                for (int c = 0; c < 5; c++) {
                    if (c == 2) {
                        continue anyName;
                    System.out.println("a=" + a + ",b=" + b + ",c=" + c);

"insufficient memory for the Java Runtime Environment " message in eclipse

Your application (Eclipse) needs more memory and JVM is not allocating enough.You can increase the amount of memory JVM allocates by following the answers given here

How to convert text to binary code in JavaScript?

  1. traverse the string
  2. convert every character to their char code
  3. convert the char code to binary
  4. push it into an array and add the left 0s
  5. return a string separated by space


function textToBin(text) {
  var length = text.length,
      output = [];
  for (var i = 0;i < length; i++) {
    var bin = text[i].charCodeAt().toString(2);
    output.push(Array(8-bin.length+1).join("0") + bin);
  return output.join(" ");
textToBin("!a") => "00100001 01100001"

Another way

function textToBin(text) {
  return (
      .reduce((acc, char) => acc.concat(char.charCodeAt().toString(2)), [])
      .map(bin => '0'.repeat(8 - bin.length) + bin )
      .join(' ')

Adding image inside table cell in HTML

You have a TH floating at the top of your table which isn't within a TR. Fix that.

With regards to your image problem you;re referencing the image absolutely from your computer's hard drive. Don't do that.

You also have a closing tag which shouldn't be there.

It should be:

<img src="h.gif" alt="" border="3" height="100" width="100" />

Also this:

<table border = 5 bordercolor = red align = center>

Your colspans are also messed up. You only seem to have three columns but have colspans of 14 and 4 in your code.

Should be:

<table border="5" bordercolor="red" align="center">

Also you have no DOCTYPE declared. You should at least add:

<!DOCTYPE html> 

Get full path of a file with FileUpload Control

I'm using IE 8 (on two separate machines). Each still uploads the full local file path. As suggested by Gabriël, Path.GetFileName(fileUploadControl.PostedFile.FileName) appears to be the only way to ensure that you only get the filename.

Using the AND and NOT Operator in Python

Use the keyword and, not & because & is a bit operator.

Be careful with this... just so you know, in Java and C++, the & operator is ALSO a bit operator. The correct way to do a boolean comparison in those languages is &&. Similarly | is a bit operator, and || is a boolean operator. In Python and and or are used for boolean comparisons.

How to add 10 minutes to my (String) time?

I used the code below to add a certain time interval to the current time.

    int interval = 30;  
    SimpleDateFormat df = new SimpleDateFormat("HH:mm");
    Calendar time = Calendar.getInstance();

    Log.i("Time ", String.valueOf(df.format(time.getTime())));

    time.add(Calendar.MINUTE, interval);

    Log.i("New Time ", String.valueOf(df.format(time.getTime())));

How to define the basic HTTP authentication using cURL correctly?

as header

AUTH=$(echo -ne "$BASIC_AUTH_USER:$BASIC_AUTH_PASSWORD" | base64 --wrap 0)

curl \
  --header "Content-Type: application/json" \
  --header "Authorization: Basic $AUTH" \
  --request POST \
  --data  '{"key1":"value1", "key2":"value2"}' \

javascript if number greater than number

You're comparing strings. JavaScript compares the ASCII code for each character of the string.

To see why you get false, look at the charCodes:


The comparison is false because, when comparing the strings, the character codes for 1 is not greater than that of 9.

The fix is to treat the strings as numbers. You can use a number of methods:

parseInt(string, radix)
parseInt("1300", 10);
> 1300 - notice the lack of quotes

> 1300

> 1300

How do I do an initial push to a remote repository with Git?

On server:

mkdir my_project.git
cd my_project.git
git --bare init

On client:

mkdir my_project
cd my_project
touch .gitignore
git init
git add .
git commit -m "Initial commit"
git remote add origin [email protected]:/path/to/my_project.git
git push origin master

Note that when you add the origin, there are several formats and schemas you could use. I recommend you see what your hosting service provides.

What does 'foo' really mean?

I think it's meant to mean nothing. The wiki says:

"Foo is commonly used with the metasyntactic variables bar and foobar."

How to give a Linux user sudo access?

This answer will do what you need, although usually you don't add specific usernames to sudoers. Instead, you have a group of sudoers and just add your user to that group when needed. This way you don't need to use visudo more than once when giving sudo permission to users.

If you're on Ubuntu, the group is most probably already set up and called admin:

$ sudo cat /etc/sudoers
# This file MUST be edited with the 'visudo' command as root.


# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL

# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL

# See sudoers(5) for more information on "#include" directives:

#includedir /etc/sudoers.d

On other distributions, like Arch and some others, it's usually called wheel and you may need to set it up: Arch Wiki

To give users in the wheel group full root privileges when they precede a command with "sudo", uncomment the following line: %wheel ALL=(ALL) ALL

Also note that on most systems visudo will read the EDITOR environment variable or default to using vi. So you can try to do EDITOR=vim visudo to use vim as the editor.

To add a user to the group you should run (as root):

# usermod -a -G groupname username

where groupname is your group (say, admin or wheel) and username is the username (say, john).

Return back to MainActivity from another activity

This usually works as well :)

navigateUpTo(new Intent(getBaseContext(), MainActivity.class));

HQL ERROR: Path expected for join

select u from UserGroup ug inner join ug.user u 
where ug.group_id = :groupId 
order by u.lastname

As a named query:

  name = "User.findByGroupId",
  query =
    "SELECT u FROM UserGroup ug " +
    "INNER JOIN ug.user u WHERE ug.group_id = :groupId ORDER BY u.lastname"

Use paths in the HQL statement, from one entity to the other. See the Hibernate documentation on HQL and joins for details.

Bind TextBox on Enter-key press

You could easily create your own control inheriting from TextBox and reuse it throughout your project.

Something similar to this should work:

public class SubmitTextBox : TextBox
    public SubmitTextBox()
        : base()
        PreviewKeyDown += new KeyEventHandler(SubmitTextBox_PreviewKeyDown);

    void SubmitTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
        if (e.Key == Key.Enter)
            BindingExpression be = GetBindingExpression(TextBox.TextProperty);
            if (be != null)

There may be a way to get around this step, but otherwise you should bind like this (using Explicit):

    Text="{Binding Path=BoundProperty, UpdateSourceTrigger=Explicit}" />

pythonw.exe or python.exe?

I was struggling to get this to work for a while. Once you change the extension to .pyw, make sure that you open properties of the file and direct the "open with" path to pythonw.exe.

What does it mean: The serializable class does not declare a static final serialVersionUID field?

Any class that can be serialized (i.e. implements Serializable) should declare that UID and it must be changed whenever anything changes that affects the serialization (additional fields, removed fields, change of field order, ...). The field's value is checked during deserialization and if the value of the serialized object does not equal the value of the class in the current VM, an exception is thrown.

Note that this value is special in that it is serialized with the object even though it is static, for the reasons described above.

Trigger a Travis-CI rebuild without pushing a commit?

Here's what worked for me to trigger a rebuild on a PR that Dependabot had opened, but failed due to errors in .travis.yml:

  1. Close the PR
  2. Wait for Dependabot to comment ("OK, I won't notify you again about this release, but will get in touch when a new version is available."). It will remove its branch.
  3. Restore the branch Dependabot removed (something like dependabot/cargo/tempfile-3.0.4).
  4. Open the PR again

How to extract a string using JavaScript Regex?

This code works:

  let str = "governance[string_i_want]"; 
  let res = str.match(/[^governance\[](.*)[^\]]/g);

res will equal "string_i_want". However, in this example res is still an array, so do not treat res like a string.

By grouping the characters I do not want, using [^string], and matching on what is between the brackets, the code extracts the string I want!

You can try it out here:

Good luck.

How to get an object's methods?

var funcs = []
for(var name in myObject) {
    if(typeof myObject[name] === 'function') {

I'm on a phone with no semi colons :) but that is the general idea.

When to use malloc for char pointers

Use malloc() when you don't know the amount of memory needed during compile time. In case if you have read-only strings then you can use const char* str = "something"; . Note that the string is most probably be stored in a read-only memory location and you'll not be able to modify it. On the other hand if you know the string during compiler time then you can do something like: char str[10]; strcpy(str, "Something"); Here the memory is allocated from stack and you will be able to modify the str. Third case is allocating using malloc. Lets say you don'r know the length of the string during compile time. Then you can do char* str = malloc(requiredMem); strcpy(str, "Something"); free(str);

How to get textLabel of selected row in swift?

In swift 4 : by overriding method

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let storyboard = UIStoryboard(name : "Main", bundle: nil)
        let next vc = storyboard.instantiateViewController(withIdentifier: "nextvcIdentifier") as! NextViewController

       self.navigationController?.pushViewController(prayerVC, animated: true)

Join vs. sub-query

  • A general rule is that joins are faster in most cases (99%).
  • The more data tables have, the subqueries are slower.
  • The less data tables have, the subqueries have equivalent speed as joins.
  • The subqueries are simpler, easier to understand, and easier to read.
  • Most of the web and app frameworks and their "ORM"s and "Active record"s generate queries with subqueries, because with subqueries are easier to split responsibility, maintain code, etc.
  • For smaller web sites or apps subqueries are OK, but for larger web sites and apps you will often have to rewrite generated queries to join queries, especial if a query uses many subqueries in the query.

Some people say "some RDBMS can rewrite a subquery to a join or a join to a subquery when it thinks one is faster than the other.", but this statement applies to simple cases, surely not for complicated queries with subqueries which actually cause a problems in performance.

How to set the style -webkit-transform dynamically using JavaScript?

To animate your 3D object, use the code:



    var x = 100;
    var y = 0;
    x += 1;
    y += 1;
    var element = document.getElementById('cube'); = "translateZ(-100px) rotateY("+x+"deg) rotateX("+y+"deg)"; //for safari and chrome = "translateZ(-100px) rotateY("+x+"deg) rotateX("+y+"deg)"; //for firefox
//for other browsers use:   "msTransform",    "OTransform",    "transform"



Change Bootstrap input focus blue glow

This will work 100% use this:

.form-control, .form-control:focus{
   box-shadow: 0 0 0 0 rgba(255, 255, 255, 0);
   border: rgba(255, 255, 255, 0);

How to use OUTPUT parameter in Stored Procedure

The SQL in your SP is wrong. You probably want

Select @code = RecItemCode from Receipt where RecTransaction = @id

In your statement, you are not setting @code, you are trying to use it for the value of RecItemCode. This would explain your NullReferenceException when you try to use the output parameter, because a value is never assigned to it and you're getting a default null.

The other issue is that your SQL statement if rewritten as

Select @code = RecItemCode, RecUsername from Receipt where RecTransaction = @id

It is mixing variable assignment and data retrieval. This highlights a couple of points. If you need the data that is driving @code in addition to other parts of the data, forget the output parameter and just select the data.

Select RecItemCode, RecUsername from Receipt where RecTransaction = @id

If you just need the code, use the first SQL statement I showed you. On the offhand chance you actually need the output and the data, use two different statements

Select @code = RecItemCode from Receipt where RecTransaction = @id
Select RecItemCode, RecUsername from Receipt where RecTransaction = @id

This should assign your value to the output parameter as well as return two columns of data in a row. However, this strikes me as terribly redundant.

If you write your SP as I have shown at the very top, simply invoke cmd.ExecuteNonQuery(); and then read the output parameter value.

Another issue with your SP and code. In your SP, you have declared @code as varchar. In your code, you specify the parameter type as Int. Either change your SP or your code to make the types consistent.

Also note: If all you are doing is returning a single value, there's another way to do it that does not involve output parameters at all. You could write

 Select RecItemCode from Receipt where RecTransaction = @id

And then use object obj = cmd.ExecuteScalar(); to get the result, no need for an output parameter in the SP or in your code.

Compiling problems: cannot find crt1.o

After reading the that jeremiah posted, i found the gcc flag that works without the symlink:

gcc -B/usr/lib/x86_64-linux-gnu hello.c

So, you can just add -B/usr/lib/x86_64-linux-gnu to the CFLAGS variable in your Makefile.

Percentage Height HTML 5/CSS

Hi! In order to use percentage(%), you must define the % of it parent element. If you use body{height: 100%} it will not work because it parent have no percentage in height. In that case in order to work that body height you must add this in html{height:100%}

In other case to get rid of that defining parent percentage you can use


vh stands for viewport height

I think it help

Capturing browser logs with Selenium WebDriver using Java

As a non-java selenium user, here is the python equivalent to Margus's answer:

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities    

class ChromeConsoleLogging(object):

    def __init__(self, ):
        self.driver = None

    def setUp(self, ):
        desired = DesiredCapabilities.CHROME
        desired ['loggingPrefs'] = { 'browser':'ALL' }
        self.driver = webdriver.Chrome(desired_capabilities=desired)

    def analyzeLog(self, ):
        data = self.driver.get_log('browser')

    def testMethod(self, ):


Edit: Keeping Python answer in this thread because it is very similar to the Java answer and this post is returned on a Google search for the similar Python question

Excel VBA date formats

Use value(cellref) on the side to evaluate the cells. Strings will produce the "#Value" error, but dates resolve to a number (e.g. 43173).

cURL equivalent in Node.js?

Uses reqclient, it's a small client module on top of request that allows you to log all the activity with cURL style (optional, for development environments). Also has nice features like URL and parameters parsing, authentication integrations, cache support, etc.

For example, if you create a client object an do a request:

var RequestClient = require("reqclient").RequestClient;
var client = new RequestClient({
        debugRequest:true, debugResponse:true

var resp ="client/orders", {"client":1234,"ref_id":"A987"}, {headers: {"x-token":"AFF01XX"}})

It will log within the console something like this:

[Requesting client/orders]-> -X POST -d '{"client": 1234, "ref_id": "A987"}' -H '{"x-token": "AFF01XX"}' -H Content-Type:application/json
[Response   client/orders]<- Status 200 - {"orderId": 1320934}

The request will return a Promise object, so you have to handle with then and catch what to do with the result.

reqclient is available with npm, you can install the module with: npm install reqclient.

React: "this" is undefined inside a component function

There are a couple of ways.

One is to add this.onToggleLoop = this.onToggleLoop.bind(this); in the constructor.

Another is arrow functions onToggleLoop = (event) => {...}.

And then there is onClick={this.onToggleLoop.bind(this)}.

What are the main differences between JWT and OAuth authentication?

It looks like everybody who answered here missed the moot point of OAUTH

From Wikipedia

OAuth is an open standard for access delegation, commonly used as a way for Internet users to grant websites or applications access to their information on other websites but without giving them the passwords.[1] This mechanism is used by companies such as Google, Facebook, Microsoft and Twitter to permit the users to share information about their accounts with third party applications or websites.

The key point here is access delegation. Why would anyone create OAUTH when there is an id/pwd based authentication, backed by multifactored auth like OTPs and further can be secured by JWTs which are used to secure the access to the paths (like scopes in OAUTH) and set the expiry of the access

There's no point of using OAUTH if consumers access their resources(your end points) only through their trusted websites(or apps) which are your again hosted on your end points

You can go OAUTH authentication only if you are an OAUTH provider in the cases where the resource owners (users) want to access their(your) resources (end-points) via a third-party client(external app). And it is exactly created for the same purpose though you can abuse it in general

Another important note:
You're freely using the word authentication for JWT and OAUTH but neither provide the authentication mechanism. Yes one is a token mechanism and the other is protocol but once authenticated they are only used for authorization (access management). You've to back OAUTH either with OPENID type authentication or your own client credentials

Task vs Thread differences

Usually you hear Task is a higher level concept than thread... and that's what this phrase means:

  1. You can't use Abort/ThreadAbortedException, you should support cancel event in your "business code" periodically testing token.IsCancellationRequested flag (also avoid long or timeoutless connections e.g. to db, otherwise you will never get a chance to test this flag). By the similar reason Thread.Sleep(delay) call should be replaced with Task.Delay(delay, token) call (passing token inside to have possibility to interrupt delay).

  2. There are no thread's Suspend and Resume methods functionality with tasks. Instance of task can't be reused either.

  3. But you get two new tools:

    a) continuations

    // continuation with ContinueWhenAll - execute the delegate, when ALL
    // tasks[] had been finished; other option is ContinueWhenAny
       () => {
           int answer = tasks[0].Result + tasks[1].Result;
           Console.WriteLine("The answer is {0}", answer);

    b) nested/child tasks

    //StartNew - starts task immediately, parent ends whith child
    var parent = Task.Factory.StartNew
    (() => {
              var child = Task.Factory.StartNew(() =>
  4. So system thread is completely hidden from task, but still task's code is executed in the concrete system thread. System threads are resources for tasks and ofcourse there is still thread pool under the hood of task's parallel execution. There can be different strategies how thread get new tasks to execute. Another shared resource TaskScheduler cares about it. Some problems that TaskScheduler solves 1) prefer to execute task and its conitnuation in the same thread minimizing switching cost - aka inline execution) 2) prefer execute tasks in an order they were started - aka PreferFairness 3) more effective distribution of tasks between inactive threads depending on "prior knowledge of tasks activity" - aka Work Stealing. Important: in general "async" is not same as "parallel". Playing with TaskScheduler options you can setup async tasks be executed in one thread synchronously. To express parallel code execution higher abstractions (than Tasks) could be used: Parallel.ForEach, PLINQ, Dataflow.

  5. Tasks are integrated with C# async/await features aka Promise Model, e.g there requestButton.Clicked += async (o, e) => ProcessResponce(await client.RequestAsync(e.ResourceName)); the execution of client.RequestAsync will not block UI thread. Important: under the hood Clicked delegate call is absolutely regular (all threading is done by compiler).

That is enough to make a choice. If you need to support Cancel functionality of calling legacy API that tends to hang (e.g. timeoutless connection) and for this case supports Thread.Abort(), or if you are creating multithread background calculations and want to optimize switching between threads using Suspend/Resume, that means to manage parallel execution manually - stay with Thread. Otherwise go to Tasks because of they will give you easy manipulate on groups of them, are integrated into the language and make developers more productive - Task Parallel Library (TPL) .

How to check for a valid Base64 encoded string

All answers were been digested into 1 function that ensures 100% that its results will be accurate.

1) Use function as below:

    string encoded = "WW91ckJhc2U2NHN0cmluZw==";
    msgbox("Is string base64=" + IsBase64(encoded));

2) Below is the function:

public bool IsBase64(string base64String)
        if (!base64String.Length < 1)
            if (!base64String.Equals(Convert.ToBase64String(Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(Convert.FromBase64String(base64String)))), StringComparison.InvariantCultureIgnoreCase) & !System.Text.RegularExpressions.Regex.IsMatch(base64String, @"^[a-zA-Z0-9\+/]*={0,2}$"))
                return false;
            if ((base64String.Length % 4) != 0 || string.IsNullOrEmpty(base64String) || base64String.Length % 4 != 0 || base64String.Contains(" ") || base64String.Contains(Constants.vbTab) || base64String.Contains(Constants.vbCr) || base64String.Contains(Constants.vbLf))
                return false;
            return false;
        return true;
    catch (FormatException ex)
            return false;

Counting in a FOR loop using Windows Batch script

for a = 1 to 100 step 1

Command line in Windows . Please use %%a if running in Batch file.

    for /L %a in (1,1,100) Do echo %a 

exclude @Component from @ComponentScan

Another approach is to use new conditional annotations. Since plain Spring 4 you can use @Conditional annotation:

class Foo {

and define conditional logic for registering Foo component:

public class FooCondition implements Condition{
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        // return [your conditional logic]

Conditional logic can be based on context, because you have access to bean factory. For Example when "Bar" component is not registered as bean:

    return !context.getBeanFactory().containsBean(Bar.class.getSimpleName());

With Spring Boot (should be used for EVERY new Spring project), you can use these conditional annotations:

  • @ConditionalOnBean
  • @ConditionalOnClass
  • @ConditionalOnExpression
  • @ConditionalOnJava
  • @ConditionalOnMissingBean
  • @ConditionalOnMissingClass
  • @ConditionalOnNotWebApplication
  • @ConditionalOnProperty
  • @ConditionalOnResource
  • @ConditionalOnWebApplication

You can avoid Condition class creation this way. Refer to Spring Boot docs for more detail.

How to change the commit author for one specific commit?

you can use these commands from official page of github

here is the commands


git filter-branch --env-filter '

OLD_EMAIL="[email protected]"
CORRECT_NAME="Your Correct Name"
CORRECT_EMAIL="[email protected]"

' --tag-name-filter cat -- --branches --tags

here u can change the old email to ur new user name and email address.

Which comment style should I use in batch files?

tl;dr: REM is the documented and supported way to embed comments in batch files.

:: is essentially a blank label that can never be jumped to, whereas REM is an actual command that just does nothing. In neither case (at least on Windows 7) does the presence of redirection operators cause a problem.

However, :: is known to misbehave in blocks under certain circumstances, being parsed not as a label but as some sort of drive letter. I'm a little fuzzy on where exactly but that alone is enough to make me use REM exclusively. It's the documented and supported way to embed comments in batch files whereas :: is merely an artifact of a particular implementation.

Here is an example where :: produces a problem in a FOR loop.

This example will not work in a file called test.bat on your desktop:

@echo off
for /F "delims=" %%A in ('type C:\Users\%username%\Desktop\test.bat') do (
    ::echo hello>C:\Users\%username%\Desktop\text.txt

While this example will work as a comment correctly:

@echo off
for /F "delims=" %%A in ('type C:\Users\%username%\Desktop\test.bat') do (
    REM echo hello>C:\Users\%username%\Desktop\text.txt

The problem appears to be when trying to redirect output into a file. My best guess is that it is interpreting :: as an escaped label called :echo.

How to convert UTF-8 byte[] to string?

There is also class UnicodeEncoding, quite simple in usage:

ByteConverter = new UnicodeEncoding();
string stringDataForEncoding = "My Secret Data!";
byte[] dataEncoded = ByteConverter.GetBytes(stringDataForEncoding);

Console.WriteLine("Data after decoding: {0}", ByteConverter.GetString(dataEncoded));

Excel Date to String conversion

Couldnt get the TEXT() formula to work

Easiest solution was to copy paste into Notepad and back into Excel with the column set to Text before pasting back

Or you can do the same with a formula like this

=DAY(A2)&"/"&MONTH(A2)&"/"&YEAR(A2)& " "&HOUR(B2)&":"&MINUTE(B2)&":"&SECOND(B2)

SQL LEFT JOIN Subquery Alias

I recognize that the answer works and has been accepted but there is a much cleaner way to write that query. Tested on mysql and postgres.

SELECT wpoi.order_id As No_Commande
FROM  wp_woocommerce_order_items AS wpoi
LEFT JOIN wp_postmeta AS wpp ON wpoi.order_id = wpp.post_id 
                            AND wpp.meta_key = '_shipping_first_name'
WHERE  wpoi.order_id =2198 

Basic authentication for REST API using spring restTemplate

Reference Spring Boot's TestRestTemplate implementation as follows:

Especially, see the addAuthentication() method as follows:

private void addAuthentication(String username, String password) {
    if (username == null) {
    List<ClientHttpRequestInterceptor> interceptors = Collections
            .<ClientHttpRequestInterceptor> singletonList(new BasicAuthorizationInterceptor(
                    username, password));
    setRequestFactory(new InterceptingClientHttpRequestFactory(getRequestFactory(),

Similarly, you can make your own RestTemplate easily

by inheritance like TestRestTemplate as follows:

Phonegap Cordova installation Windows

This answer was first posted here: cordova/phonegap does not make android directory

With the release of Cordova 3.3.0, it seems the PhoneGap team is trying to address the naming confusion. The documentations have been updated to recommend people using the cordova command instead. Do not use the phonegap command anymore.

Here is a fresh installation guide for a guaranteed trouble free set up:

  1. Install Cordova (forget the name PhoneGap from now on). For PC:

    C:> npm install -g cordova

  2. From command prompt, navigate to the folder you want to create your project using:

    cordova create hello com.example.hello HelloWorld
    cd hello

  3. Define the OS you want to suppport for example:

    cordova platform add wp8

  4. Install plugins (If needed). For example we want the following:

    cordova plugin add org.apache.cordova.device
    cordova plugin add
    cordova plugin add
    cordova plugin add

  5. Finally, generate the app using:
    cordova build wp8

Here is a link to the PhoneGapCordova 3.3.0 Documentation

How to run a script as root on Mac OS X?

Or you can access root terminal by typing sudo -s

how to use "AND", "OR" for RewriteCond on Apache?

Having trouble wrapping my head around this.

Have a rewrite rule with four conditions.
The first three conditions A, B, C are to be AND which is then OR with D

RewriteCond A       true
RewriteCond B       false
RewriteCond C [OR]  true
RewriteCond D       true
RewriteRule ...

But that seems to be an expression of A and B and (C or D) = false (don't rewrite)

How can I get to the desired expression? (A and B and C) or D = true (rewrite)

Preferably without using the additional steps of setting environment variables.


org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException:

You are trying to access an XLS file. However, you are using XSSFWorkbook and XSSFSheet class objects. These classes are mainly used for XLSX files.

For XLS file: HSSFWorkbook & HSSFSheet
For XLSX file: XSSFSheet & XSSFSheet

So in place of XSSFWorkbook use HSSFWorkbook and in place of XSSFSheet use HSSFSheet.

So your code should look like this after the changes are made:

HSSFWorkbook workbook = new HSSFWorkbook(file);

HSSFSheet sheet = workbook.getSheetAt(0);

Is there a link to the "latest" jQuery library on Google APIs?

jQuery also doesn't allow you to call their latest file over SSL, a consideration if you want to use jQuery in a shopping cart etc.


<script type="text/javascript" src=""></script>

will give you a security error.

Google's API will let you call over SSL:

<script type="text/javascript" src=""></script>
<script type="text/javascript">
  google.load("jquery", "1.7");

Escaping ampersand character in SQL string

I know it sucks. None of the above things were really working, but I found a work around. Please be extra careful to use spaces between the apostrophes [ ' ], otherwise it will get escaped.

SELECT 'Hello ' '&' ' World';

Hello & World

You're welcome ;)

How to restore a SQL Server 2012 database to SQL Server 2008 R2?

To: Killercam Thanks for your solutions. I tried the first solution for an hour, but didn't work for me.

I used scripts generate method to move data from SQL Server 2012 to SQL Server 2008 R2 as steps bellow:

In the 2012 SQL Management Studio

  1. Tasks -> Generate Scripts (in first wizard screen, click Next - may not show)
  2. Choose Script entire database and all database objects -> Next
  3. Click [Advanced] button 3.1 Change [Types of data to script] from "Schema only" to "Schema and data" 3.2 Change [Script for Server Version] "2012" to "2008"
  4. Finish next wizard steps for creating script file
  5. Use sqlcmd to import the exported script file to your SQL Server 2008 R2 5.1 Open windows command line 5.2 Type [sqlcmd -S -i Path to your file] (Ex: [sqlcmd -S localhost -i C:\mydatabase.sql])

It works for me.

Storing images in SQL Server?

When storing images in SQL Server do not use the 'image' datatype, according to MS it is being phased out in new versions of SQL server. Use varbinary(max) instead

How to link to a <div> on another page?

Take a look at anchor tags. You can create an anchor with

<div id="anchor-name">Heading Text</div>

and refer to it later with

<a href="http://server/page.html#anchor-name">Link text</a>

Convert varchar to uniqueidentifier in SQL Server

It would make for a handy function. Also, note I'm using STUFF instead of SUBSTRING.

create function str2uniq(@s varchar(50)) returns uniqueidentifier as begin
    -- just in case it came in with 0x prefix or dashes...
    set @s = replace(replace(@s,'0x',''),'-','')
    -- inject dashes in the right places
    set @s = stuff(stuff(stuff(stuff(@s,21,0,'-'),17,0,'-'),13,0,'-'),9,0,'-')
    return cast(@s as uniqueidentifier)

Component based game engine design

There does seem to be a lack of information on the subject. I recently implemented this system, and I found a really good GDC Powerpoint that explained the details that are often left behind quite well. That document is here: Theory and Practice of Game Object Component Architecture

In addition to that Powerpoint, there are some good resources and various blogs. PurplePwny has a good discussion and links to some other resources. Ugly Baby Studios has a bit of a discussion around the idea of how components interact with each other. Good luck!

Remove json element

var json = { ... };
var key = "foo";
delete json[key]; // Removes from the dictionary.

You can use splice to remove elements from an array.

How to fade changing background image

Can I offer an alternative solution?

I had this same issue, and fade didn't work because it faded the entire element, not just the background. In my case the element was body, so I only wanted to fade the background.

An elegant way to tackle this is to class the element and use CSS3 transition for the background.

transition: background 0.5s linear;

When you change the background, either with toggleClass or with your code, $("#large-img").css('background-image', 'url('+$img+')'); it will fade as defined by the class.

Where is the Global.asax.cs file?

That's because you created a Web Site instead of a Web Application. The cs/vb files can only be seen in a Web Application, but in a website you can't have a separate cs/vb file.

Edit: In the website you can add a cs file behavior like..

<%@ Application CodeFile="Global.asax.cs" Inherits="ApplicationName.MyApplication" Language="C#" %>


namespace ApplicationName
    public partial class MyApplication : System.Web.HttpApplication
        protected void Application_Start()

Using the RUN instruction in a Dockerfile with 'source' does not work

According to the default [Linux] shell for RUN is /bin/sh -c. You appear to be expecting bashisms, so you should use the "exec form" of RUN to specify your shell.

RUN ["/bin/bash", "-c", "source /usr/local/bin/"]

Otherwise, using the "shell form" of RUN and specifying a different shell results in nested shells.

# don't do this...
RUN /bin/bash -c "source /usr/local/bin/"
# because it is the same as this...
RUN ["/bin/sh", "-c", "/bin/bash" "-c" "source /usr/local/bin/"]

If you have more than 1 command that needs a different shell, you should read and change your default shell by placing this before your RUN commands:

SHELL ["/bin/bash", "-c"]

Finally, if you have placed anything in the root user's .bashrc file that you need, you can add the -l flag to the SHELL or RUN command to make it a login shell and ensure that it gets sourced.

Note: I have intentionally ignored the fact that it is pointless to source a script as the only command in a RUN.

Laravel Eloquent: How to get only certain columns from joined tables

On Laravel 5.5, the cleanest way to do this is:


You add a colon and the fields you wish to select separated by a comma and without a space between them.

How do I add a submodule to a sub-directory?

Note that starting git1.8.4 (July 2013), you wouldn't have to go back to the root directory anymore.

 cd ~/.janus/snipmate-snippets
 git submodule add <git@github ...> snippets

(Bouke Versteegh comments that you don't have to use /., as in snippets/.: snippets is enough)

See commit 091a6eb0feed820a43663ca63dc2bc0bb247bbae:

submodule: drop the top-level requirement

Use the new rev-parse --prefix option to process all paths given to the submodule command, dropping the requirement that it be run from the top-level of the repository.

Since the interpretation of a relative submodule URL depends on whether or not "remote.origin.url" is configured, explicitly block relative URLs in "git submodule add" when not at the top level of the working tree.

Signed-off-by: John Keeping

Depends on commit 12b9d32790b40bf3ea49134095619700191abf1f

This makes 'git rev-parse' behave as if it were invoked from the specified subdirectory of a repository, with the difference that any file paths which it prints are prefixed with the full path from the top of the working tree.

This is useful for shell scripts where we may want to cd to the top of the working tree but need to handle relative paths given by the user on the command line.

How can I remove a specific item from an array?

Splice, filter and delete to remove an element from an array

Every array has its index, and it helps to delete a particular element with their index.

The splice() method

array.splice(index, 1);    

The first parameter is index and the second is the number of elements you want to delete from that index.

So for a single element, we use 1.

The delete method

delete array[index]

The filter() method

If you want to delete an element which is repeated in an array then filter the array:

removeAll = array.filter(e => e != elem);

Where elem is the element you want to remove from the array and array is your array name.

How to sort by dates excel?

  1. Select the whole column
  2. Right click -> Format cells... -> Number -> Category: Date -> OK
  3. Data -> Text to Columns -> select Delimited -> Next -> in your case selection of Delimiters doesn't matter -> Next -> select Date: DMY -> Finish

Now you should be able to sort by this column either Oldest to Newest or Newest to Oldest

Difference between jQuery .hide() and .css("display", "none")

You can have a look at the source code (here it is v1.7.2).

Except for the animation that we can set, this also keep in memory the old display style (which is not in all cases block, it can also be inline, table-cell, ...).

Rendering an in React

Gosha Arinich is right, you should return your <li> element. But, nevertheless, you should get nasty red warning in the browser console in this case

Each child in an array or iterator should have a unique "key" prop.

so, you need to add "key" to your list:, i){
  return <li key={i}>Test</li>

or drop the console.log() and do a beautiful oneliner, using es6 arrow functions:,i) => <li key={i}>Test</li>)


The answer above is solving the current problem, but as Sergey mentioned in the comments: using the key depending on the map index is BAD if you want to do some filtering and sorting. In that case use the if id already there, or just generate unique ids for it.

Can I store images in MySQL

Yes, you can store images in the database, but it's not advisable in my opinion, and it's not general practice.

A general practice is to store images in directories on the file system and store references to the images in the database. e.g. path to the image,the image name, etc.. Or alternatively, you may even store images on a content delivery network (CDN) or numerous hosts across some great expanse of physical territory, and store references to access those resources in the database.

Images can get quite large, greater than 1MB. And so storing images in a database can potentially put unnecessary load on your database and the network between your database and your web server if they're on different hosts.

I've worked at startups, mid-size companies and large technology companies with 400K+ employees. In my 13 years of professional experience, I've never seen anyone store images in a database. I say this to support the statement it is an uncommon practice.

String contains - ignore case

You can use java.util.regex.Pattern with the CASE_INSENSITIVE flag for case insensitive matching:

Pattern.compile(Pattern.quote(strptrn), Pattern.CASE_INSENSITIVE).matcher(str1).find();

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

For Django 2.2:

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

To view all the queries:

from django.db import connection

To view query for a single query:


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

Filename timestamp in Windows CMD batch script getting truncated

BATCH/CMD FILE like DateAndTime.cmd (not in CMD-Console)


SETLOCAL EnableDelayedExpansion
(set d=%date:~8,2%-%date:~3,2%-%date:~0,2%) & (set t=%time::=.%) & (set t=!t: =0!) & (set STAMP=!d!__!t!)

Create output:

echo %stamp%



Or also possible in for lines in CMD-Console and BATCH/CMD File

set d=%date:~6,4%-%date:~3,2%-%date:~0,2%
set t=%time::=.%
set t=%t: =0%
set stamp=%d%__%t%

"Create output" and "Output" same as above

Correct way to write loops for promise.


  • asyncFn function
  • array of items


  • promise chaining .then()'s in series (in order)
  • native es6


let asyncFn = (item) => {
  return new Promise((resolve, reject) => {
    setTimeout( () => {console.log(item); resolve(true)}, 1000 )

// asyncFn('a')
// .then(()=>{return async('b')})
// .then(()=>{return async('c')})
// .then(()=>{return async('d')})

let a = ['a','b','c','d']

a.reduce((previous, current, index, array) => {
  return previous                                    // initiates the promise chain
  .then(()=>{return asyncFn(array[index])})      //adds .then() promise for each item
}, Promise.resolve())

select certain columns of a data table

You can create a method that looks like this:

  public static DataTable SelectedColumns(DataTable RecordDT_, string col1, string col2)
        DataTable TempTable = RecordDT_;

        System.Data.DataView view = new System.Data.DataView(TempTable);
        System.Data.DataTable selected = view.ToTable("Selected", false, col1, col2);
        return selected;

You can return as many columns as possible.. just add the columns as call parameters as shown below:

public DataTable SelectedColumns(DataTable RecordDT_, string col1, string col2,string col3,...)

and also add the parameters to this line:

System.Data.DataTable selected = view.ToTable("Selected", false,col1, col2,col3,...);

Then simply implement the function as:

 DataTable myselectedColumnTable=SelectedColumns(OriginalTable,"Col1","Col2",...);


how to convert a string to a bool

I used the below code to convert a string to boolean.


How to send control+c from a bash script?

ctrl+c and kill -INT <pid> are not exactly the same, to emulate ctrl+c we need to first understand the difference.

kill -INT <pid> will send the INT signal to a given process (found with its pid).

ctrl+c is mapped to the intr special character which when received by the terminal should send INT to the foreground process group of that terminal. You can emulate that by targetting the group of your given <pid>. It can be done by prepending a - before the signal in the kill command. Hence the command you want is:

kill -INT -<pid>

You can test it pretty easily with a script:

#!/usr/bin/env ruby

fork {
    trap(:INT) {
        puts 'signal received in child!'
    sleep 1_000

puts "run `kill -INT -#{}` in any other terminal window."


sqlite database default time value 'now'

It may be better to use REAL type, to save storage space.

Quote from 1.2 section of Datatypes In SQLite Version 3

SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values

    t REAL DEFAULT (datetime('now', 'localtime'))

see column-constraint .

And insert a row without providing any value.


Why XML-Serializable class need a parameterless constructor

During an object's de-serialization, the class responsible for de-serializing an object creates an instance of the serialized class and then proceeds to populate the serialized fields and properties only after acquiring an instance to populate.

You can make your constructor private or internal if you want, just so long as it's parameterless.

Finding the indices of matching elements in list in Python

You are using .index() which will only find the first occurrence of your value in the list. So if you have a value 1.0 at index 2, and at index 9, then .index(1.0) will always return 2, no matter how many times 1.0 occurs in the list.

Use enumerate() to add indices to your loop instead:

def find(lst, a, b):
    result = []
    for i, x in enumerate(lst):
        if x<a or x>b:
    return result

You can collapse this into a list comprehension:

def find(lst, a, b):
    return [i for i, x in enumerate(lst) if x<a or x>b]

Dependency Injection vs Factory Pattern

The reason Dependency Injection (DI) and Factory Patterns are similar is because they are two implementations of Inversion of Control (IoC) which is a software architecture. Put simply they are two solutions to the same problem.

So to answer the question the main difference between the Factory pattern and DI is how the object reference is obtained. With dependency injection as the name implies the reference is injected or given to your code. With Factory pattern your code must request the reference so your code fetches the object. Both implementations remove or decouple the linkage between the code and the underlying class or type of the object reference being used by the code.

It's worth noting that Factory patterns (or indeed Abstract Factory patterns which are factories that return new factories that return object references) can be written to dynamically choose or link to the type or class of object being requested at run time. This makes them very similar (even more so than DI) to Service Locator pattern which is another implementation of the IoC.

The Factory design pattern is quite old (in terms of Software) and has been around for a while. Since the recent popularity of the architectural pattern IoC it is having a resurgence.

I guess when it comes to IoC design patterns: injectors be injecting, locators be locating and the factories have been refactored.

How to display line numbers in 'less' (GNU)

You can also press = while less is open to just display (at the bottom of the screen) information about the current screen, including line numbers, with format:

myfile.txt lines 20530-20585/1816468 byte 1098945/116097872 1%  (press RETURN)

So here for example, the screen was currently showing lines 20530-20585, and the files has a total of 1816468 lines.

How can I find the OWNER of an object in Oracle?

You can query the ALL_OBJECTS view:

select owner
     , object_name
     , object_type
 where object_name = 'FOO'

To find synonyms:

select *
 where synonym_name = 'FOO'

Just to clarify, if a user user's SQL statement references an object name with no schema qualification (e.g. 'FOO'), Oracle FIRST checks the user's schema for an object of that name (including synonyms in that user's schema). If Oracle can't resolve the reference from the user's schema, Oracle then checks for a public synonym.

If you are looking specifically for constraints on a particular table_name:

select c.*
  from all_constraints c 
 where c.table_name = 'FOO'
 union all
select cs.*
  from all_constraints cs
  join all_synonyms s 
    on (s.table_name = cs.table_name
     and s.table_owner = cs.owner 
     and s.synonym_name = 'FOO'


-- addendum:

If your user is granted access to the DBA_ views (e.g. if your user has been granted SELECT_CATALOG_ROLE), you can substitute 'DBA_' in place of 'ALL_' in the preceding SQL examples. The ALL_x views only show objects which you have been granted privileges. The DBA_x views will show all database objects, whether you have privileges on them or not.

Excel date to Unix timestamp

None of the current answers worked for me because my data was in this format from the unix side:

2016-02-02 19:21:42 UTC

I needed to convert this to Epoch to allow referencing other data which had epoch timestamps.

  1. Create a new column for the date part and parse with this formula

    =DATEVALUE(MID(A2,6,2) & "/" & MID(A2,9,2) & "/" & MID(A2,1,4)) 
  2. As other Grendler has stated here already, create another column

  3. Create another column with just the time added together to get total seconds:

  4. Create a last column that just adds the last two columns together:


How to determine if a point is in a 2D triangle?

If you are looking for speed, here is a procedure that might help you.

Sort the triangle vertices on their ordinates. This takes at worst three comparisons. Let Y0, Y1, Y2 be the three sorted values. By drawing three horizontals through them you partition the plane into two half planes and two slabs. Let Y be the ordinate of the query point.

if Y < Y1
    if Y <= Y0 -> the point lies in the upper half plane, outside the triangle; you are done
    else Y > Y0 -> the point lies in the upper slab
    if Y >= Y2 -> the point lies in the lower half plane, outside the triangle; you are done
    else Y < Y2 -> the point lies in the lower slab

Costs two more comparisons. As you see, quick rejection is achieved for points outside of the "bounding slab".

Optionally, you can supply a test on the abscissas for quick rejection on the left and on the right (X <= X0' or X >= X2'). This will implement a quick bounding box test at the same time, but you'll need to sort on the abscissas too.

Eventually you will need to compute the sign of the given point with respect to the two sides of the triangle that delimit the relevant slab (upper or lower). The test has the form:

((X - Xi) * (Y - Yj) > (X - Xi) * (Y - Yj)) == ((X - Xi) * (Y - Yk) > (X - Xi) * (Y - Yk))

The complete discussion of i, j, k combinations (there are six of them, based on the outcome of the sort) is out of the scope of this answer and "left as an exercise to the reader"; for efficiency, they should be hard-coded.

If you think that this solution is complex, observe that it mainly involves simple comparisons (some of which can be precomputed), plus 6 subtractions and 4 multiplies in case the bounding box test fails. The latter cost is hard to beat as in the worst case you cannot avoid comparing the test point against two sides (no method in other answers has a lower cost, some make it worse, like 15 subtractions and 6 multiplies, sometimes divisions).

UPDATE: Faster with a shear transform

As explained just above, you can quickly locate the point inside one of the four horizontal bands delimited by the three vertex ordinates, using two comparisons.

You can optionally perform one or two extra X tests to check insideness to the bounding box (dotted lines).

Then consider the "shear" transform given by X'= X - m Y, Y' = Y, where m is the slope DX/DY for the highest edge. This transform will make this side of the triangle vertical. And since you know on what side of the middle horizontal you are, it suffices to test the sign with respect to a single side of the triangle.

enter image description here

Assuming you precomputed the slope m, as well as the X' for the sheared triangle vertices and the coefficients of the equations of the sides as X = m Y + p, you will need in the worst case

  • two ordinate comparisons for vertical classification;
  • optionally one or two abscissa comparisons for bounding box rejection;
  • computation of X' = X - m Y;
  • one or two comparisons with the abscissas of the sheared triangle;
  • one sign test X >< m' Y + p' against the relevant side of the sheared triangle.

Obtain form input fields using jQuery?

I hope this is helpful, as well as easiest one.

 $("#form").submit(function (e) { 
    input_values =  $(this).serializeArray();

Ansible date variable

The lookup module of ansible works fine for me. The yml is:

- hosts: test
    time: "{{ lookup('pipe', 'date -d \"1 day ago\" +\"%Y%m%d\"') }}"

You can replace any command with date to get result of the command.

Safely casting long to int in Java

I think I'd do it as simply as:

public static int safeLongToInt(long l) {
    if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
        throw new IllegalArgumentException
            (l + " cannot be cast to int without changing its value.");
    return (int) l;

I think that expresses the intent more clearly than the repeated casting... but it's somewhat subjective.

Note of potential interest - in C# it would just be:

return checked ((int) l);


Hai sridhar, I found an answer for your prob

ClientScript.RegisterClientScriptBlock(GetType(), "sas", "<script> alert('Inserted successfully');</script>", true);

change false to true

or try this

ScriptManager.RegisterClientScriptBlock(ursavebuttonID, typeof(LinkButton or button), "sas", "<script> alert('Inserted successfully');</script>", true);

How to read data from excel file using c#

CSharpJExcel for reading Excel 97-2003 files (XLS), ExcelPackage for reading Excel 2007/2010 files (Office Open XML format, XLSX), and ExcelDataReader that seems to have the ability to handle both formats

Good luck!

PHP filesize MB/KB conversion

function calcSize($size,$accuracy=2) {
    $units = array('b','Kb','Mb','Gb');
    foreach($units as $n=>$u) {
        $div = pow(1024,$n);
        if($size > $div) $output = number_format($size/$div,$accuracy).$u;
    return $output;

Connect to SQL Server Database from PowerShell

The answer are as below for Window authentication

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=$SQLServer;Database=$SQLDBName;Integrated Security=True;"

How can I delay a :hover effect in CSS?

You can use transitions to delay the :hover effect you want, if the effect is CSS-based.

For example

    transition: 0s background-color;


this will delay applying the the hover effects (background-color in this case) for one second.

Demo of delay on both hover on and off:

    border:1px solid #ccc;_x000D_
    transition: 0s background-color;_x000D_
<div>delayed hover</div>

Demo of delay only on hover on:

    border:1px solid #ccc;_x000D_
    transition: 0s background-color;_x000D_
    background-color:red;    _x000D_
<div>delayed hover</div>

Vendor Specific Extentions for Transitions and W3C CSS3 transitions

How to properly import a selfsigned certificate into Java keystore that is available to all Java applications by default?

I ended up writing a small script that adds the certificates to the keystores, so it is much easier to use.

You can get the latest version from

# version 1.0

KEYTOOL="sudo keytool"

# /etc/java-6-sun/security/cacerts

for CACERTS in  /usr/lib/jvm/java-8-oracle/jre/lib/security/cacerts \
    /usr/lib/jvm/java-7-oracle/jre/lib/security/cacerts \
    "/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/lib/security/cacerts" \

if [ -e "$CACERTS" ]
    echo --- Adding certs to $CACERTS

# FYI: the default keystore is located in ~/.keystore

if [ -z "$REMHOST" ]
    echo "ERROR: Please specify the server name to import the certificatin from, eventually followed by the port number, if other than 443."
    exit 1

set -e


if openssl s_client -connect $REMHOST:$REMPORT 1>/tmp/keytool_stdout 2>/tmp/output </dev/null
        cat /tmp/keytool_stdout
        cat /tmp/output
        exit 1

if sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' </tmp/keytool_stdout > /tmp/$REMHOST:$REMPORT.pem
        echo "ERROR: Unable to extract the certificate from $REMHOST:$REMPORT ($?)"
        cat /tmp/output

if $KEYTOOL -list -storepass ${KEYSTORE_PASS} -alias $REMHOST:$REMPORT >/dev/null
    echo "Key of $REMHOST already found, skipping it."
    $KEYTOOL -import -trustcacerts -noprompt -storepass ${KEYSTORE_PASS} -alias $REMHOST:$REMPORT -file /tmp/$REMHOST:$REMPORT.pem

if $KEYTOOL -list -storepass ${KEYSTORE_PASS} -alias $REMHOST:$REMPORT -keystore "$CACERTS" >/dev/null
    echo "Key of $REMHOST already found in cacerts, skipping it."
    $KEYTOOL -import -trustcacerts -noprompt -keystore "$CACERTS" -storepass ${KEYSTORE_PASS} -alias $REMHOST:$REMPORT -file /tmp/$REMHOST:$REMPORT.pem




How do I query for all dates greater than a certain date in SQL Server?

select *  
from dbo.March2010 A 
where A.Date >= Convert(datetime, '2010-04-01' )

In your query, 2010-4-01 is treated as a mathematical expression, so in essence it read

select *  
from dbo.March2010 A 
where A.Date >= 2005; 

(2010 minus 4 minus 1 is 2005 Converting it to a proper datetime, and using single quotes will fix this issue.)

Technically, the parser might allow you to get away with

select *  
from dbo.March2010 A 
where A.Date >= '2010-04-01'

it will do the conversion for you, but in my opinion it is less readable than explicitly converting to a DateTime for the maintenance programmer that will come after you.

How to replace all dots in a string using JavaScript

str.replace(new RegExp(".","gm")," ")

CSS3 equivalent to jQuery slideUp and slideDown?

I would recommend using the jQuery Transit Plugin which uses the CSS3 transform property, which works great on mobile devices due to the fact that most support hardware acceleration to give that native look and feel.

JS Fiddle Example


<div class="moveMe">
    <button class="moveUp">Move Me Up</button>
    <button class="moveDown">Move Me Down</button>
    <button class="setUp">Set Me Up</button>
    <button class="setDown">Set Me Down</button>


$(".moveUp").on("click", function() {
    $(".moveMe").transition({ y: '-=5' });

$(".moveDown").on("click", function() {
    $(".moveMe").transition({ y: '+=5' });

$(".setUp").on("click", function() {
    $(".moveMe").transition({ y: '0px' });

$(".setDown").on("click", function() {
    $(".moveMe").transition({ y: '200px' });

Action Image MVC3 Razor

This extension method also works (to be placed in an public static class):

    public static MvcHtmlString ImageActionLink(this AjaxHelper helper, string imageUrl, string altText, string actionName, object routeValues, AjaxOptions ajaxOptions)
        var builder = new TagBuilder("img");
        builder.MergeAttribute("src", imageUrl);
        builder.MergeAttribute("alt", altText);
        var link = helper.ActionLink("[replaceme]", actionName, routeValues, ajaxOptions);
        return new MvcHtmlString( link.ToHtmlString().Replace("[replaceme]", builder.ToString(TagRenderMode.SelfClosing)) );

JQuery create a form and add elements to it programmatically

function setValToAssessment(id)

     $.getJSON("<?= URL.$param->module."/".$param->controller?>/setvalue",{id: id}, function(response)
        var form = $('<form></form>').attr("id",'hiddenForm' ).attr("name", 'hiddenForm'); 
            $("<input type='text' value='"+value+"' >")
 .attr("id", key)
 .attr("name", key)


        // window.location.href = "<?=URL.$param->module?>/assessment";


How to correctly implement custom iterators and const_iterators?

They often forget that iterator must convert to const_iterator but not the other way around. Here is a way to do that:

template<class T, class Tag = void>
class IntrusiveSlistIterator
   : public std::iterator<std::forward_iterator_tag, T>
    typedef SlistNode<Tag> Node;
    Node* node_;

    IntrusiveSlistIterator(Node* node);

    T& operator*() const;
    T* operator->() const;

    IntrusiveSlistIterator& operator++();
    IntrusiveSlistIterator operator++(int);

    friend bool operator==(IntrusiveSlistIterator a, IntrusiveSlistIterator b);
    friend bool operator!=(IntrusiveSlistIterator a, IntrusiveSlistIterator b);

    // one way conversion: iterator -> const_iterator
    operator IntrusiveSlistIterator<T const, Tag>() const;

In the above notice how IntrusiveSlistIterator<T> converts to IntrusiveSlistIterator<T const>. If T is already const this conversion never gets used.

AngularJS: Uncaught Error: [$injector:modulerr] Failed to instantiate module?

it turns out that I got this error because my requested module is not bundled in the minification prosses due to path misspelling

so make sure that your module exists in minified js file (do search for a word within it to be sure)

Disable sorting for a particular column in jQuery DataTables

columnDefs now accepts a class. I'd say this is the preferred method if you'd like to specify columns to disable in your markup:

            <th class="datatable-nosort">Actions</th>

Then, in your JS:

    columnDefs: [{
        targets: "datatable-nosort",
        orderable: false

Split a string into array in Perl

Just use /\s+/ against '' as a splitter. In this case all "extra" blanks were removed. Usually this particular behaviour is required. So, in you case it will be:

my $line = "file1.gz file1.gz file3.gz";
my @abc = split(/\s+/, $line);

What does Java option -Xmx stand for?

Max heap Usage for the application is is 1024 MB

Send File Attachment from Form Using phpMailer and PHP

You'd use $_FILES['uploaded_file']['tmp_name'], which is the path where PHP stored the uploaded file (it's a temporary file, removed automatically by PHP when the script ends, unless you've moved/copied it elsewhere).

Assuming your client-side form and server-side upload settings are correct, there's nothing you have to do to "pull in" the upload. It'll just magically be available in that tmp_name path.

Note that you WILL have to validate that the upload actually succeeded, e.g.

if ($_FILES['uploaded_file']['error'] === UPLOAD_ERR_OK) {
    ... attach file to email ...

Otherwise you may try to do an attachment with a damaged/partial/non-existent file.

Unable to ping vmware guest from another vmware guest

On both Operation Systems, must turnoff firewall. I using MS SERVER 2012 R2 & MS WIN-7 as a client. First of all call "RUN BOX" window logo button+ R, once RUN box appeared type "firewall.cpl" at Window Firewall setting you will see "Turn Window Firewall On or Off" like this you click it & chose "turn off window firewall" on both Private and Public Setting then OK. Ping again on guests OS. GOOD-LUCK Aungkokokhant

How to check what version of jQuery is loaded?

Go to the developer's Tool > console and write one of the following command jQuery.fn.jquery console.log(jQuery().jquery);

document.all vs. document.getElementById

Specifically, document.all was introduced for IE4 BEFORE document.getElementById had been introduced.

So, the presence of document.all means that the code is intended to support IE4, or is trying to identify the browser as IE4 (though it could have been Opera), or the person who wrote (or copied and pasted) the code wasn't up on the latest.

In the highly unlikely event that you need to support IE4, then, you do need document.all (or a library that handles these ancient IE specs).

How to add onload event to a div element

I needed to have some initialization code run after a chunk of html (template instance) was inserted, and of course I didn't have access to the code that manipulates the template and modifies the DOM. The same idea holds for any partial modification of the DOM by insertion of an html element, usually a <div>.

Some time ago, I did a hack with the onload event of a nearly invisible <img> contained in a <div>, but discovered that a scoped, empty style will also do:

<div .... >
<style scoped="scoped" onload="dosomethingto(this.parentElement);" >   </style>

Update(Jul 15 2017) - The <style> onload is not supported in last version of IE. Edge does support it, but some users see this as a different browser and stick with IE. The <img> element seems to work better across all browsers.

<img onLoad="dosomthing(this.parentElement);" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" />

To minimize the visual impact and resource usage of the image, use an inline src that keeps it small and transparent.

One comment I feel I need to make about using a <script>is how much harder it is to determine which <div> the script is near, especially in templating where you can't have an identical id in each instance that the template generates. I thought the answer might be document.currentScript, but this is not universally supported. A <script> element cannot determine its own DOM location reliably; a reference to 'this' points to the main window, and is of no help.

I believe it is necessary to settle for using an <img> element, despite being goofy. This might be a hole in the DOM/javascript framework that could use plugging.

How to search through all Git and Mercurial commits in the repository for a certain string?

Building on rq's answer, I found this line does what I want:

git grep "search for something" $(git log -g --pretty=format:%h -S"search for something")

Which will report the commit ID, filename, and display the matching line, like this:

91ba969:testFile:this is a test

... Does anyone agree that this would be a nice option to be included in the standard git grep command?

How to change text color of cmd with windows batch script every 1 second

Try this script. This can write any text on any position of screen and don't use temporary files or ".com, .exe" executables. Just make shure you have the "debug.exe" executable in windows\system or windows\system32 folders.

@echo off
setlocal enabledelayedexpansion
set /a _er=0
set /a _n=0
set _ln=%~4
goto init

:howuse ---------------------------------------------------------------

    echo ------------------
    echo ECOL.BAT - ver 1.0
    echo ------------------
    echo Print colored text in batch script
    echo Written by BrendanLS -
    echo Syntax:
    echo ECOL.BAT [COLOR] [X] [Y] "Insert your text"
    echo COLOR value must be a hexadecimal number
    echo Example:
    echo ECOL.BAT F0 20 30 "The 640KB World Forum"
    echo Enjoy ;^)
    goto quit

:error ----------------------------------------------------------------

    set /a "_er=_er | (%~1)"
    goto quit

:geth -----------------------------------------------------------------

        set return=
        set bts=%~1

:hshift ---------------------------------------------------------------

        set /a "nn = bts & 0xff"
        set return=!h%nn%!%return%
        set /a "bts = bts >> 0x8"
        if %bts% gtr 0 goto hshift
        goto quit

:init -----------------------------------------------------------------

    if "%~4"=="" call :error 0xff

        set /a _cl=0x%1
        call :error !errorlevel!
        set _cl=%1
        call :error "0x!_cl! ^>^> 8"
        set /a _px=%2
        call :error !errorlevel!
        set /a _py=%3
        call :error !errorlevel!
    ) 2>nul 1>&2

    if !_er! neq 0 (
        echo ERROR: value exception "!_er!" occurred.
        goto howuse

    set nsys=0123456789abcdef
    set /a _val=-1

        for /l %%a in (0,1,15) do (
                for /l %%b in (0,1,15) do (
                        set /a "_val += 1"
                        set byte=!nsys:~%%a,1!!nsys:~%%b,1!
                        set h!_val!=!byte!

    set /a cnb=0
    set /a cnl=0

:parse ----------------------------------------------------------------

    set _ch=!_ln:~%_n%,1!
    if "%_ch%"=="" goto perform

    set /a "cnb += 1"
    if %cnb% gtr 7 (
        set /a cnb=0
        set /a "cnl += 1"

    set bln%cnl%=!bln%cnl%! "!_ch!" %_cl%
    set /a "_n += 1"
    goto parse

:perform --------------------------------------------------------------

    set /a "in = ((_py * 160) + (_px * 2)) & 0xffff"
    call :geth %in%
    set ntr=!return!
    set /a jmp=0xe

    @for /l %%x in (0,1,%cnl%) do (
        set bl8086%%x=eb800:!ntr! !bln%%x!
        set /a "in=!jmp! + 0x!ntr!"
        call :geth !in!
        set ntr=!return!
        set /a jmp=0x10

    )|debug >nul 2>&1


how to dynamically add options to an existing select in vanilla javascript

I guess something like this would do the job.

var option = document.createElement("option");
option.text = "Text";
option.value = "myvalue";
var select = document.getElementById("daySelect");

tkinter: how to use after method

I believe, the 500ms run in the background, while the rest of the code continues to execute and empties the list.

Then after 500ms nothing happens, as no function-call is implemented in the after-callup (same as frame.after(500, function=None))

Create a File object in memory from a string in Java

Usually when a method accepts a file, there's another method nearby that accepts a stream. If this isn't the case, the API is badly coded. Otherwise, you can use temporary files, where permission is usually granted in many cases. If it's applet, you can request write permission.

An example:

try {
    // Create temp file.
    File temp = File.createTempFile("pattern", ".suffix");

    // Delete temp file when program exits.

    // Write to temp file
    BufferedWriter out = new BufferedWriter(new FileWriter(temp));
} catch (IOException e) {

Adding attributes to an XML node

The latest and supposedly greatest way to construct the XML is by using LINQ to XML:

using System.Xml.Linq

       var xmlNode =
            new XElement("Login",
                         new XElement("id",
                             new XAttribute("userName", "Tushar"),
                             new XAttribute("password", "Tushar"),
                             new XElement("Name", "Tushar"),
                             new XElement("Age", "24")

Supposedly this way of coding should be easier, as the code closely resembles the output (which Jon's example above does not). However, I found that while coding this relatively easy example I was prone to lose my way between the cartload of comma's that you have to navigate among. Visual studio's auto spacing of code does not help either.

Find the day of a week

df = data.frame(date=c("2012-02-01", "2012-02-01", "2012-02-02")) 
df$day <- weekdays(as.Date(df$date))
##         date       day
## 1 2012-02-01 Wednesday
## 2 2012-02-01 Wednesday
## 3 2012-02-02  Thursday

Edit: Just to show another way...

The wday component of a POSIXlt object is the numeric weekday (0-6 starting on Sunday).

## [1] 3 3 4

which you could use to subset a character vector of weekday names

c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", 
    "Friday", "Saturday")[as.POSIXlt(df$date)$wday + 1]
## [1] "Wednesday" "Wednesday" "Thursday" 

Detect end of ScrollView

You can make use of the Support Library's NestedScrollView and it's NestedScrollView.OnScrollChangeListener interface.

Alternatively if your app is targeting API 23 or above, you can make use of the following method on the ScrollView:

View.setOnScrollChangeListener(OnScrollChangeListener listener) 

Then follow the example that @Fustigador described in his answer. Note however that as @Will described, you should consider adding a small buffer in case the user or system isn't able to reach the complete bottom of the list for any reason.

Also worth noting is that the scroll change listener will sometimes be called with negative values or values greater than the view height. Presumably these values represent the 'momentum' of the scroll action. However unless handled appropriately (floor / abs) they can cause problems detecting the scroll direction when the view is scrolled to the top or bottom of the range.

Iterating through all nodes in XML file

I think the fastest and simplest way would be to use an XmlReader, this will not require any recursion and minimal memory foot print.

Here is a simple example, for compactness I just used a simple string of course you can use a stream from a file etc.

  string xml = @"
        <nested />

  XmlReader rdr = XmlReader.Create(new System.IO.StringReader(xml));
  while (rdr.Read())
    if (rdr.NodeType == XmlNodeType.Element)

The result of the above will be


A list of all the elements in the XML document.

Spring boot - Not a managed type

I had some problem while migrating from Spring boot 1.3.x to 1.5, I got it working after updating entity package at EntityManagerFactory bean

  public LocalContainerEntityManagerFactoryBean defaultEntityManager() {
      Map map = new HashMap();
      map.put("hibernate.default_schema", env.getProperty("spring.datasource.username"));
      map.put("", env.getProperty("spring.jpa.hibernate.ddl-auto"));
      LocalContainerEntityManagerFactoryBean em = createEntityManagerFactoryBuilder(jpaVendorProperties())
      return em;

This bean referred in Application class as below

@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryDef")
public class SimpleApp {


"Active Directory Users and Computers" MMC snap-in for Windows 7?

I'm not allowed to use Turn Windows features on or off, but running all of these commands in an elevated command prompt (Run as Administrator) finally got Active Directory Users and Computers to show up under Administrative Tools on the start menu:

dism /online /enable-feature /featurename:RemoteServerAdministrationTools
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-DS
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-DS-SnapIns
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-DS-AdministrativeCenter
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-DS-NIS
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-LDS
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-Powershell

I had downloaded and installed the RSAT (Windows 7 Link, Windows Vista Link) before running these commands.

It's quite likely that this is more than you features than you actually need, but at least it's not too few.


Use { before $ sign. And also add addslashes function to escape special characters.

$sqlupdate1 = "UPDATE table SET commodity_quantity=".$qty."WHERE user=".addslashes($rows['user'])."'";

What is the difference between Hibernate and Spring Data JPA

I disagree SpringJPA makes live easy. Yes, it provides some classes and you can make some simple DAO fast, but in fact, it's all you can do. If you want to do something more than findById() or save, you must go through hell:

  • no EntityManager access in classes (this is basic JPA class!)
  • own transaction management (hibernate transactions disallowed)
  • huge problems with more than one datasources configuration
  • no datasource pooling (HikariCP must be in use as third party library)

Why own transaction management is an disadvantage? Since Java 1.8 allows default methods into interfaces, Spring annotation based transactions, simple doesn't work.

Unfortunately, SpringJPA is based on reflections, and sometimes you need to point a method name or entity package into annotations (!). That's why any refactoring makes big crash. Sadly, @Transactional works for primary DS only :( So, if you have more than one DataSources, remember - transactions works just for primary one :)

What are the main differences between Hibernate and Spring Data JPA?

Hibernate is JPA compatibile, SpringJPA Spring compatibile. Your HibernateJPA DAO can be used with JavaEE or Hibernate Standalone, when SpringJPA can be used within Spring - SpringBoot for example

When should we not use Hibernate or Spring Data JPA? Also, when may Spring JDBC template perform better than Hibernate / Spring Data JPA?

Use Spring JDBC only when you need to use much Joins or when you need to use Spring having multiple datasource connections. Generally, avoid JPA for Joins.

But my general advice, use fresh solution—Daobab ( Daobab is my Java and any JPA engine integrator, and I believe it will help much in your tasks :)

How to convert string to float?

By using sscanf we can convert string to float.


int main() 
    char str[100] ="4.0800" ;     
    const char s[2] = "-";   
    char *token;
    double x;
   /* get the first token */ 
   token = strtok(str, s);
    printf( " %f",x );

    return 0; 

How to add image to canvas

In my case, I was mistaken the function parameters, which are:

context.drawImage(image, left, top);
context.drawImage(image, left, top, width, height);

If you expect them to be

context.drawImage(image, width, height);

you will place the image just outside the canvas with the same effects as described in the question.

Toggle show/hide on click with jQuery

You can use .toggle() function instead of .click()....

Show Console in Windows Application?

What worked for me was to write a console app separately that did what I wanted it to do, compile it down to an exe, and then do Process.Start("MyConsoleapp.exe","Arguments")

CSS: auto height on containing div, 100% height on background div inside containing div

In 2018 a lot of browsers support the Flexbox and Grid which are very powerful CSS display modes that overshine classical methods such as Faux Columns or Tabular Displays (which are treated later in this answer).

In order to implement this with the Grid, it is enough to specify display: grid and grid-template-columns on the container. The grid-template-columns depends on the number of columns you have, in this example I will use 3 columns, hence the property will look: grid-template-columns: auto auto auto, which basically means that each of the columns will have auto width.

Full working example with Grid:

html, body {_x000D_
    padding: 0;_x000D_
    margin: 0;_x000D_
.grid-container {_x000D_
    display: grid;_x000D_
    grid-template-columns: auto auto auto;_x000D_
    width: 100%;_x000D_
.grid-item {_x000D_
    padding: 20px;_x000D_
.a {_x000D_
    background-color: DarkTurquoise;_x000D_
.b {_x000D_
    background-color: LightSalmon;_x000D_
.c {_x000D_
    background-color: LightSteelBlue;_x000D_
<!DOCTYPE html>_x000D_
    <title>Three Columns with Grid</title>_x000D_
    <link rel="stylesheet" type="text/css" href="style.css">_x000D_
    <div class="grid-container">_x000D_
        <div class="grid-item a">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis. Pellentesque accumsan nunc non arcu tincidunt auctor eget ut magna. In vel est egestas, ultricies dui a, gravida diam. Vivamus tempor facilisis lectus nec porta.</p>_x000D_
        <div class="grid-item b">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis. Pellentesque accumsan nunc non arcu tincidunt auctor eget ut magna. In vel est egestas, ultricies dui a, gravida diam. Vivamus tempor facilisis lectus nec porta. Donec commodo elit mattis, bibendum turpis eu, malesuada nunc. Vestibulum sit amet dui tincidunt, mattis nisl et, tincidunt eros. Vivamus eu ultrices sapien. Integer leo arcu, lobortis sed tellus in, euismod ultricies massa. Mauris gravida quis ligula nec dignissim. Proin elementum mattis fringilla. Donec id malesuada orci, eu aliquam ipsum. Vestibulum fermentum elementum egestas. Quisque sit amet tempor mi.</p>_x000D_
        <div class="grid-item c">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis.</p>_x000D_

Another way would be to use the Flexbox by specifying display: flex on the container of the columns, and giving the columns a relevant width. In the example that I will be using, which is with 3 columns, you basically need to split 100% in 3, so it's 33.3333% (close enough, who cares about 0.00003333... which isn't visible anyway).

Full working example using Flexbox:

html, body {_x000D_
    padding: 0;_x000D_
    margin: 0;_x000D_
.flex-container {_x000D_
    display: flex;_x000D_
    width: 100%;_x000D_
.flex-column {_x000D_
    padding: 20px;_x000D_
    width: 33.3333%;_x000D_
.a {_x000D_
    background-color: DarkTurquoise;_x000D_
.b {_x000D_
    background-color: LightSalmon;_x000D_
.c {_x000D_
    background-color: LightSteelBlue;_x000D_
<!DOCTYPE html>_x000D_
    <title>Three Columns with Flexbox</title>_x000D_
    <link rel="stylesheet" type="text/css" href="style.css">_x000D_
    <div class="flex-container">_x000D_
        <div class="flex-column a">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis. Pellentesque accumsan nunc non arcu tincidunt auctor eget ut magna. In vel est egestas, ultricies dui a, gravida diam. Vivamus tempor facilisis lectus nec porta.</p>_x000D_
        <div class="flex-column b">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis. Pellentesque accumsan nunc non arcu tincidunt auctor eget ut magna. In vel est egestas, ultricies dui a, gravida diam. Vivamus tempor facilisis lectus nec porta. Donec commodo elit mattis, bibendum turpis eu, malesuada nunc. Vestibulum sit amet dui tincidunt, mattis nisl et, tincidunt eros. Vivamus eu ultrices sapien. Integer leo arcu, lobortis sed tellus in, euismod ultricies massa. Mauris gravida quis ligula nec dignissim. Proin elementum mattis fringilla. Donec id malesuada orci, eu aliquam ipsum. Vestibulum fermentum elementum egestas. Quisque sit amet tempor mi.</p>_x000D_
        <div class="flex-column c">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis.</p>_x000D_

The Flexbox and Grid are supported by all major browsers since 2017/2018, fact also confirmed by Can I use grid, Can I use flex.

There are also a number of classical solutions, used before the age of Flexbox and Grid, like OneTrueLayout Technique, Faux Columns Technique, CSS Tabular Display Technique and there is also a Layering Technique.

I do not recommend using these methods for they have a hackish nature and are not so elegant in my opinion, but it is good to know them for academic reasons.

A solution for equally height-ed columns is the CSS Tabular Display Technique that means to use the display:table feature. It works for Firefox 2+, Safari 3+, Opera 9+ and IE8.

The code for the CSS Tabular Display:

#container {_x000D_
  display: table;_x000D_
  background-color: #CCC;_x000D_
  margin: 0 auto;_x000D_
.row {_x000D_
  display: table-row;_x000D_
.col {_x000D_
  display: table-cell;_x000D_
#col1 {_x000D_
  background-color: #0CC;_x000D_
  width: 200px;_x000D_
#col2 {_x000D_
  background-color: #9F9;_x000D_
  width: 300px;_x000D_
#col3 {_x000D_
  background-color: #699;_x000D_
  width: 200px;_x000D_
<div id="container">_x000D_
  <div id="rowWraper" class="row">_x000D_
    <div id="col1" class="col">_x000D_
      Column 1<br />Lorem ipsum<br />ipsum lorem_x000D_
    <div id="col2" class="col">_x000D_
      Column 2<br />Eco cologna duo est!_x000D_
    <div id="col3" class="col">_x000D_
      Column 3_x000D_

Even if there is a problem with the auto-expanding of the width of the table-cell it can be resolved easy by inserting another div withing the table-cell and giving it a fixed width. Anyway, the over-expanding of the width happens in the case of using extremely long words (which I doubt anyone would use a, let's say, 600px long word) or some div's who's width is greater than the table-cell's width.

The Faux Column Technique is the most popular classical solution to this problem, but it has some drawbacks such as, you have to resize the background tiled image if you want to resize the columns and it is also not an elegant solution.

The OneTrueLayout Technique consists of creating a padding-bottom of an extreme big height and cut it out by bringing the real border position to the "normal logical position" by applying a negative margin-bottom of the same huge value and hiding the extent created by the padding with overflow: hidden applied to the content wraper. A simplified example would be:

Working example:

.wraper {_x000D_
    overflow: hidden; /* This is important */_x000D_
.floatLeft {_x000D_
    float: left;_x000D_
.block {_x000D_
    padding-left: 20px;_x000D_
    padding-right: 20px;_x000D_
    padding-bottom: 30000px; /* This is important */_x000D_
    margin-bottom: -30000px; /* This is important */_x000D_
    width: 33.3333%;_x000D_
    box-sizing: border-box; /* This is so that the padding right and left does not affect the width */_x000D_
.a {_x000D_
    background-color: DarkTurquoise;_x000D_
.b {_x000D_
    background-color: LightSalmon;_x000D_
.c {_x000D_
    background-color: LightSteelBlue;_x000D_
    <div class="wraper">_x000D_
        <div class="block floatLeft a">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras malesuada ipsum pretium tellus condimentum aliquam. Donec eget tempor mi, a consequat enim. Mauris a massa id nisl sagittis iaculis.</p>_x000D_
        <div class="block floatLeft b">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras malesuada ipsum pretium tellus condimentum aliquam. Donec eget tempor mi, a consequat enim. Mauris a massa id nisl sagittis iaculis. Duis mattis diam vitae tellus ornare, nec vehicula elit luctus. In auctor urna ac ante bibendum, a gravida nunc hendrerit. Praesent sed pellentesque lorem. Nam neque ante, egestas ut felis vel, faucibus tincidunt risus. Maecenas egestas diam massa, id rutrum metus lobortis non. Sed quis tellus sed nulla efficitur pharetra. Fusce semper sapien neque. Donec egestas dolor magna, ut efficitur purus porttitor at. Mauris cursus, leo ac porta consectetur, eros quam aliquet erat, condimentum luctus sapien tellus vel ante. Vivamus vestibulum id lacus vel tristique.</p>_x000D_
        <div class="block floatLeft c">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras malesuada ipsum pretium tellus condimentum aliquam. Donec eget tempor mi, a consequat enim. Mauris a massa id nisl sagittis iaculis. Duis mattis diam vitae tellus ornare, nec vehicula elit luctus. In auctor urna ac ante bibendum, a gravida nunc hendrerit.</p>_x000D_

The Layering Technique must be a very neat solution that involves absolute positioning of div's withing a main relative positioned wrapper div. It basically consists of a number of child divs and the main div. The main div has imperatively position: relative to it's css attribute collection. The children of this div are all imperatively position:absolute. The children must have top and bottom set to 0 and left-right dimensions set to accommodate the columns with each another. For example if we have two columns, one of width 100px and the other one of 200px, considering that we want the 100px in the left side and the 200px in the right side, the left column must have {left: 0; right: 200px} and the right column {left: 100px; right: 0;}

In my opinion the unimplemented 100% height within an automated height container is a major drawback and the W3C should consider revising this attribute (which since 2018 is solvable with Flexbox and Grid).

Other resources: link1, link2, link3, link4, link5 (important)

How do I UPDATE from a SELECT in SQL Server?

UPDATE table AS a
INNER JOIN table2 AS b
ON a.col1 = b.col1
ON ... = ...
SET ...

How to get jQuery dropdown value onchange event

Add try this code .. Its working grt.......

 if (isset($_POST['nav'])) {_x000D_
   header("Location: $_POST[nav]");_x000D_
<form id="page-changer" action="" method="post">_x000D_
    <select name="nav">_x000D_
        <option value="">Go to page...</option>_x000D_
        <option value="">CSS-Tricks</option>_x000D_
        <option value="">Digging Into WordPress</option>_x000D_
        <option value="">Quotes on Design</option>_x000D_
    <input type="submit" value="Go" id="submit" />_x000D_
<script type="text/javascript" src="//"></script>_x000D_
$(function() {_x000D_
    $("#page-changer select").change(function() {_x000D_
        window.location = $("#page-changer select option:selected").val();_x000D_

Effective method to hide email from spam bots

I use a very simple combination of CSS and jQuery which displays the email address correctly to the user and also works when the anchor is clicked or hovered:


<a href="mailto:[email protected]" id="lnkMail">moc.elpmaxe@em</a>


#lnkMail {
    unicode-bidi: bidi-override;
    direction: rtl;


    // here you can use whatever replace you want
    var newHref = $(this).attr('href').replace('spam', 'com');
    $(this).attr('href', newHref);

Here is a working example.

How do I filter ForeignKey choices in a Django ModelForm?

In addition to S.Lott's answer and as becomingGuru mentioned in comments, its possible to add the queryset filters by overriding the ModelForm.__init__ function. (This could easily apply to regular forms) it can help with reuse and keeps the view function tidy.

class ClientForm(forms.ModelForm):
    def __init__(self,company,*args,**kwargs):
        super (ClientForm,self ).__init__(*args,**kwargs) # populates the post
        self.fields['rate'].queryset = Rate.objects.filter(company=company)
        self.fields['client'].queryset = Client.objects.filter(company=company)

    class Meta:
        model = Client

def addclient(request, company_id):
        the_company = get_object_or_404(Company, id=company_id)

        if request.POST:
            form = ClientForm(the_company,request.POST)  #<-- Note the extra arg
            if form.is_valid():
                return HttpResponseRedirect(the_company.get_clients_url())
            form = ClientForm(the_company)

        return render_to_response('addclient.html', 
                                  {'form': form, 'the_company':the_company})

This can be useful for reuse say if you have common filters needed on many models (normally I declare an abstract Form class). E.g.

class UberClientForm(ClientForm):
    class Meta:
        model = UberClient

def view(request):
    form = UberClientForm(company)

#or even extend the existing custom init
class PITAClient(ClientForm):
    def __init__(company, *args, **args):
        super (PITAClient,self ).__init__(company,*args,**kwargs)
        self.fields['support_staff'].queryset = User.objects.exclude(user='michael')

Other than that I'm just restating Django blog material of which there are many good ones out there.