Programs & Examples On #Concrete syntax tree

Anaconda version with Python 3.5

command install:

  • python3.5: conda install python=3.5
  • python3.6: conda install python=3.6

download the most recent Anaconda installer:

  • python3.5: Anaconda 4.2.0
  • python3.6: Anaconda 5.2.0

reference from anaconda doc:

Android AlertDialog Single Button


  val dialogBuilder = AlertDialog.Builder(this.context)
               .setPositiveButton("OK", null)

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

Please make sure that your applicationContext.xml file is loaded by specifying it in your web.xml file:


How to generate JAXB classes from XSD?

You can also generate source code from schema using jaxb2-maven-plugin plugin:


Regex to validate password strength

You can use zero-length positive look-aheads to specify each of your constraints separately:


If your regex engine doesn't support the \p notation and pure ASCII is enough, then you can replace \p{Lu} with [A-Z] and \p{Ll} with [a-z].

AngularJs .$setPristine to reset form

Just for those who want to get $setPristine without having to upgrade to v1.1.x, here is the function I used to simulate the $setPristine function. I was reluctant to use the v1.1.5 because one of the AngularUI components I used is no compatible.

var setPristine = function(form) {
    if (form.$setPristine) {//only supported from v1.1.x
    } else {
         *Underscore looping form properties, you can use for loop too like:
         *for(var i in form){ 
         *  var input = form[i]; ...
        _.each(form, function (input) {
            if (input.$dirty) {
                input.$dirty = false;

Note that it ONLY makes $dirty fields clean and help changing the 'show error' condition like $scope.myForm.myField.$dirty && $scope.myForm.myField.$invalid.

Other parts of the form object (like the css classes) still need to consider, but this solve my problem: hide error messages.

Append a tuple to a list - what's the difference between two ways?

I believe tuple() takes a list as an argument For example,

tuple([1,2,3]) # returns (1,2,3)

see what happens if you wrap your array with brackets

How can I recover the return value of a function passed to multiprocessing.Process?

For some reason, I couldn't find a general example of how to do this with Queue anywhere (even Python's doc examples don't spawn multiple processes), so here's what I got working after like 10 tries:

def add_helper(queue, arg1, arg2): # the func called in child processes
    ret = arg1 + arg2

def multi_add(): # spawns child processes
    q = Queue()
    processes = []
    rets = []
    for _ in range(0, 100):
        p = Process(target=add_helper, args=(q, 1, 2))
    for p in processes:
        ret = q.get() # will block
    for p in processes:
    return rets

Queue is a blocking, thread-safe queue that you can use to store the return values from the child processes. So you have to pass the queue to each process. Something less obvious here is that you have to get() from the queue before you join the Processes or else the queue fills up and blocks everything.

Update for those who are object-oriented (tested in Python 3.4):

from multiprocessing import Process, Queue

class Multiprocessor():

    def __init__(self):
        self.processes = []
        self.queue = Queue()

    def _wrapper(func, queue, args, kwargs):
        ret = func(*args, **kwargs)

    def run(self, func, *args, **kwargs):
        args2 = [func, self.queue, args, kwargs]
        p = Process(target=self._wrapper, args=args2)

    def wait(self):
        rets = []
        for p in self.processes:
            ret = self.queue.get()
        for p in self.processes:
        return rets

# tester
if __name__ == "__main__":
    mp = Multiprocessor()
    num_proc = 64
    for _ in range(num_proc): # queue up multiple tasks running `sum`, [1, 2, 3, 4, 5])
    ret = mp.wait() # get all results
    assert len(ret) == num_proc and all(r == 15 for r in ret)

SQL DROP TABLE foreign key constraint

If you want to DROP a table which has been referenced by other table using the foreign key use

I think it should work for you.

IIS_IUSRS and IUSR permissions in IIS8

I would use specific user (and NOT Application user). Then I will enable impersonation in the application. Once you do that whatever account is set as the specific user, those credentials would used to access local resources on that server (Not for external resources).

Specific User setting is specifically meant for accessing local resources.

How to install maven on redhat linux

I made the following script:


# Target installation location

# Link to binary tar.gz archive
# See

# Configuration parameters used to start up the JVM running Maven, i.e. "-Xms256m -Xmx512m"
# See
MAVEN_OPTS="" # Optional (not needed)

if [[ ! -d $MAVEN_HOME ]]; then
  # Create nonexistent subdirectories recursively
  mkdir -p $MAVEN_HOME

  # Curl location of tar.gz archive & extract without first directory
  curl -L $MAVEN_BINARY_TAR_GZ_ARCHIVE | tar -xzf - -C $MAVEN_HOME --strip 1

  # Creating a symbolic/soft link to Maven in the primary directory of executable commands on the system
  ln -s $MAVEN_HOME/bin/mvn /usr/bin/mvn

  # Permanently set environmental variable (if not null)
  if [[ -n $MAVEN_OPTS ]]; then
    echo "export MAVEN_OPTS=$MAVEN_OPTS" >> ~/.bashrc

  # Using MAVEN_HOME, MVN_HOME, or M2 as your env var is irrelevant, what counts
  # is your $PATH environment.
  # See
  echo "export PATH=$MAVEN_HOME/bin:$PATH" >> ~/.bashrc
  # Do nothing if target installation directory already exists
  echo "'$MAVEN_HOME' already exists, please uninstall existing maven first."

Set HTTP header for one request

Try this, perhaps it works ;)

.factory('authInterceptor', function($location, $q, $window) {

return {
    request: function(config) {
      config.headers = config.headers || {};

      config.headers.Authorization = 'xxxx-xxxx';

      return config;

.config(function($httpProvider) {

And make sure your back end works too, try this. I'm using RESTful CodeIgniter.

class App extends REST_Controller {
    var $authorization = null;

    public function __construct()
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
        if ( "OPTIONS" === $_SERVER['REQUEST_METHOD'] ) {

            $this->response(null, 400);    

        $this->authorization = $this->input->get_request_header('Authorization');


How do I get the App version and build number using Swift?

Having looked at the documentation, I believe that the following is cleaner:

let version = 
as? String

Source: "Use of this method is preferred over other access methods because it returns the localized value of a key when one is available."

Correct format specifier to print pointer or address?

As an alternative to the other (very good) answers, you could cast to uintptr_t or intptr_t (from stdint.h/inttypes.h) and use the corresponding integer conversion specifiers. This would allow more flexibility in how the pointer is formatted, but strictly speaking an implementation is not required to provide these typedefs.

test if display = none


Where will log4net create this log file?

Log4net is saving into your project folder. Something like: \SolutionFolder\ProjectFolder\bin\SolutionConfiguration\logs\log-file.txt.


  • SolutionFolder is where you save your solution
  • ProjectFolder is the folder where your project lives into the solution and
  • SolutionConfiguration is the folder that contais all the binaries of your project (the default is Debug or Release)

Hope this helps!

Using regular expression in css?

Try my generic CSS regular expression



Converting string into datetime

In [34]: import datetime

In [35]: _now =

In [36]: _now
Out[36]: datetime.datetime(2016, 1, 19, 9, 47, 0, 432000)

In [37]: print _now
2016-01-19 09:47:00.432000

In [38]: _parsed = datetime.datetime.strptime(str(_now),"%Y-%m-%d %H:%M:%S.%f")

In [39]: _parsed
Out[39]: datetime.datetime(2016, 1, 19, 9, 47, 0, 432000)

In [40]: assert _now == _parsed

SQLAlchemy create_all() does not create tables

If someone is having issues with creating tables by using files dedicated to each model, be aware of running the "create_all" function from a file different from the one where that function is declared. So, if the filesystem is like this:

Root     <-- file from which app will be run
--models      <-- file with "User" model    <-- file with "Order" model <-- file with database and "create_all" function declaration

Be careful about calling the "create_all" function from

This concept is explained better by the answer to this thread posted by @SuperShoot

Concatenate a list of pandas dataframes together

concat also works nicely with a list comprehension pulled using the "loc" command against an existing dataframe

df = pd.read_csv('./data.csv') # ie; Dataframe pulled from csv file with a "userID" column

review_ids = ['1','2','3'] # ie; ID values to grab from DataFrame

# Gets rows in df where IDs match in the userID column and combines them 

dfa = pd.concat([df.loc[df['userID'] == x] for x in review_ids])

Auto increment in MongoDB to store sequence of Unique User ID

I had a similar issue, namely I was interested in generating unique numbers, which can be used as identifiers, but doesn't have to. I came up with the following solution. First to initialize the collection:

fun create(mongo: MongoTemplate) {
                .insertOne(Document(mapOf("_id" to "globalCounter", "sequenceValue" to 0L)))

An then a service that return unique (and ascending) numbers:

class IdCounter(val mongoTemplate: MongoTemplate) {

    companion object {
        const val collection = "sequence"

    private val idField = "_id"
    private val idValue = "globalCounter"
    private val sequence = "sequenceValue"

    fun nextValue(): Long {
        val filter = Document(mapOf(idField to idValue))
        val update = Document("\$inc", Document(mapOf(sequence to 1)))
        val updated: Document = mongoTemplate.db.getCollection(collection).findOneAndUpdate(filter, update)!!
        return updated[sequence] as Long

I believe that id doesn't have the weaknesses related to concurrent environment that some of the other solutions may suffer from.

What is the difference between Html.Hidden and Html.HiddenFor

Most of the MVC helper methods have a XXXFor variant. They are intended to be used in conjunction with a concrete model class. The idea is to allow the helper to derive the appropriate "name" attribute for the form-input control based on the property you specify in the lambda. This means that you get to eliminate "magic strings" that you would otherwise have to employ to correlate the model properties with your views. For example:

Html.Hidden("Name", "Value")

Will result in:

<input id="Name" name="Name" type="hidden" value="Value">

In your controller, you might have an action like:

public ActionResult MyAction(MyModel model) 

And a model like:

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

The raw Html.Hidden we used above will get correlated to the Name property in the model. However, it's somewhat distasteful that the value "Name" for the property must be specified using a string ("Name"). If you rename the Name property on the Model, your code will break and the error will be somewhat difficult to figure out. On the other hand, if you use HiddenFor, you get protected from that:

Html.HiddenFor(x => x.Name, "Value");

Now, if you rename the Name property, you will get an explicit runtime error indicating that the property can't be found. In addition, you get other benefits of static analysis, such as getting a drop-down of the members after typing x..

Android: why setVisibility(View.GONE); or setVisibility(View.INVISIBLE); do not work

This is for someone who tried all the answers and still failed. Extending pierre's answer. If you are using animation, setting up the visibility to GONE or INVISIBLE or invalidate() will never work. Try out the below solution. `

btn2.getAnimation().setAnimationListener(new Animation.AnimationListener() {
     public void onAnimationStart(Animation animation) {
     public void onAnimationEnd(Animation animation) {
     public void onAnimationRepeat(Animation animation) {


Does JavaScript have a built in stringbuilder class?

In C# you can do something like

 String.Format("hello {0}, your age is {1}.",  "John",  29) 

In JavaScript you could do something like

 var x = "hello {0}, your age is {1}";
 x = x.replace(/\{0\}/g, "John");
 x = x.replace(/\{1\}/g, 29);

Argument list too long error for rm, cp, mv commands

Or you can try:

find . -name '*.pdf' -exec rm -f {} \;

Rename master branch for both local and remote Git repositories

I'm assuming you're still asking about the same situation as in your previous question. That is, master-new will not contain master-old in its history.* If you call master-new "master", you will effectively have rewritten history. It does not matter how you get into a state in which master is not a descendant of a previous position of master, simply that it is in that state.

Other users attempting to pull while master does not exist will simply have their pulls fail (no such ref on remote), and once it exists again in a new place, their pulls will have to attempt to merge their master with the new remote master, just as if you merged master-old and master-new in your repository. Given what you're trying to do here, the merge would have conflicts. (If they were resolved, and the result was pushed back into the repository, you'd be in an even worse state - both versions of history there.)

To answer your question simply: you should accept that sometimes there will be mistakes in your history. This is okay. It happens to everyone. There are reverted commits in the git.git repository. The important thing is that once we publish history, it is something everyone can trust.

*If it did, this would be equivalent to pushing some changes onto master, and then creating a new branch where it used to be. No problem.

TimeStamp on file name using PowerShell

Here's some PowerShell code that should work. You can combine most of this into fewer lines, but I wanted to keep it clear and readable.

[string]$filePath = "C:\";

[string]$directory = [System.IO.Path]::GetDirectoryName($filePath);
[string]$strippedFileName = [System.IO.Path]::GetFileNameWithoutExtension($filePath);
[string]$extension = [System.IO.Path]::GetExtension($filePath);
[string]$newFileName = $strippedFileName + [DateTime]::Now.ToString("yyyyMMdd-HHmmss") + $extension;
[string]$newFilePath = [System.IO.Path]::Combine($directory, $newFileName);

Move-Item -LiteralPath $filePath -Destination $newFilePath;

Finding row index containing maximum value using R

See ?which.max

> which.max( matrix[,2] )
[1] 2

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory

As of jackson 2.7.4 (or earlier maybe), the class is in jacskon-jaxrs-base.jar, which is contained in jackson-jaxrs-json-provider

How to change Screen buffer size in Windows Command Prompt from batch script

I was just searching for an answer to this exact question, come to find out the command itself adjusts the buffer!

mode con:cols=140 lines=70

The lines=70 part actually adjusts the Height in the 'Screen Buffer Size' setting, NOT the Height in the 'Window Size' setting.

Easily proven by running the command with a setting for 'lines=2500' (or whatever buffer you want) and then check the 'Properties' of the window, you'll see that indeed the buffer is now set to 2500.

My batch script ends up looking like this:

@echo off
cmd "mode con:cols=140 lines=2500"

Linux command line howto accept pairing for bluetooth device without pin

For Ubuntu 14.04 and Android try:

hcitool scan #get hardware address
sudo bluetooth-agent PIN HARDWARE-ADDRESS

PIN dialog pops up on Android device. Enter same PIN.

Note: sudo apt-get install bluez-utils might be necessary.

Note2: If PIN dialog does not appear, try pairing from Android first (will fail because of wrong PIN). Then try again as described above.

How to hide keyboard in swift on pressing return key?

  • Add UITextFieldDelegate to the class declaration:

    class ViewController: UIViewController, UITextFieldDelegate
  • Connect the textfield or write it programmatically

    @IBOutlet weak var userText: UITextField!
  • set your view controller as the text fields delegate in view did load:

    override func viewDidLoad() {
    self.userText.delegate = self
  • Add the following function

    func textFieldShouldReturn(userText: UITextField!) -> Bool {
        return true;

    with all this your keyboard will begin to dismiss by touching outside the textfield aswell as by pressing return key.

The activity must be exported or contain an intent-filter

just add intent-filter Tag inside your activity

for example ::

            <category android:name="android.intent.category.LAUNCHER" />

Simple linked list in C++



using namespace std;

struct Node
    int num;
    Node *next;

Node *head = NULL;
Node *tail = NULL;

void AddnodeAtbeggining(){
    Node *temp = new Node;
    cout << "Enter the item";
    cin >> temp->num;
    temp->next = NULL;
    if (head == NULL)
        head = temp;
        tail = temp;
        temp->next = head;
        head = temp;

void addnodeAtend()
    Node *temp = new Node;
    cout << "Enter the item";
    cin >> temp->num;
    temp->next = NULL;
    if (head == NULL){
        head = temp;
        tail = temp;
        tail->next = temp;
        tail = temp;

void displayNode()
    cout << "\nDisplay Function\n";
    Node *temp = head;
    for(Node *temp = head; temp != NULL; temp = temp->next)
        cout << temp->num << ",";

void deleteNode ()
    for (Node *temp = head; temp != NULL; temp = temp->next)
        delete head;

int main ()

CSS to set A4 paper size


body {
  background: rgb(204,204,204); 
page[size="A4"] {
  background: white;
  width: 21cm;
  height: 29.7cm;
  display: block;
  margin: 0 auto;
  margin-bottom: 0.5cm;
  box-shadow: 0 0 0.5cm rgba(0,0,0,0.5);
@media print {
  body, page[size="A4"] {
    margin: 0;
    box-shadow: 0;


<page size="A4"></page>
<page size="A4"></page>
<page size="A4"></page>


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

Two ways to achieve it.

1) Need to start the dialer via code, without user interaction.

You need Action_Dial,

use below code it will open Dialer with number specified

Intent intent = new Intent(Intent.ACTION_DIAL);

The 'tel:' prefix is required, otherwhise the following exception will be thrown: java.lang.IllegalStateException: Could not execute method of the activity.

Action_Dial doesn't require any permission.

If you want to initiate the call directly without user's interaction , You can use action Intent.ACTION_CALL. In this case, you must add the following permission in your AndroidManifest.xml:

<uses-permission android:name="android.permission.CALL_PHONE" />

2) Need user to click on Phone_Number string and start the call.


You need to use TextView with below property.

android:autoLink="phone" android:linksClickable="true" a textView property

You don't need to use intent or to get permission via this way.

C++ STL Vectors: Get iterator from index?

Or you can use std::advance

vector<int>::iterator i = L.begin();
advance(i, 2);

Visual Studio Code: format is not using indent settings

Most likely you have some formatting extension installed, e.g. JS-CSS-HTML Formatter.

If it is the case, then just open Command Palette, type "Formatter" and select Formatter Config. Then edit the value of "indent_size" as you like.

P.S. Don't forget to restart Visual Studio Code after editing :)

How to get the input from the Tkinter Text Widget?

I would argue that creating a simple extension of Text and turning text into a property is the cleanest way to go. You can then stick that extension in some file that you always import, and use it instead of the original Text widget. This way, instead of having to remember, write, repeat, etc all the hoops tkinter makes you jump through to do the simplest things, you have a butt-simple interface that can be reused in any project. You can do this for Entry, as well, but the syntax is slightly different.

import tkinter as tk

root = tk.Tk()    
class Text(tk.Text):
    def text(self) -> str:
        return self.get('1.0', 'end-1c')
    def text(self, value) -> None:
        self.replace('1.0', 'end-1c', value)
    def __init__(self, master, **kwargs):
        tk.Text.__init__(self, master, **kwargs)

#Entry version of the same concept as above      
class Entry(tk.Entry):
    def text(self) -> str:
        return self.get()
    def text(self, value) -> None:
        self.delete(0, 'end')
        self.insert(0, value)
    def __init__(self, master, **kwargs):
        tk.Entry.__init__(self, master, **kwargs)      
textbox = Text(root)

textbox.text = "this is text" #set
print(textbox.text)           #get  

entry = Entry(root)

entry.text = 'this is text'   #set
print(entry.text)             #get


Clearing localStorage in javascript?

This code here you give a list of strings of keys that you don't want to delete, then it filters those from all the keys in local storage then deletes the others.

const allKeys = Object.keys(localStorage);

const toBeDeleted = allKeys.filter(value => {
  return !this.doNotDeleteList.includes(value);

toBeDeleted.forEach(value => {

Do I need to close() both FileReader and BufferedReader?

I'm late, but:

public BufferedReader(Reader in) {
  this(in, defaultCharBufferSize);


public void close() throws IOException {
    synchronized (lock) {
        if (in == null)
        try {
        } finally {
            in = null;
            cb = null;

How to remove elements from a generic list while iterating over it?

foreach(var item in list.ToList())


if(item.Delete) list.Remove(item);


Simply create an entirely new list from the first one. I say "Easy" rather than "Right" as creating an entirely new list probably comes at a performance premium over the previous method (I haven't bothered with any benchmarking.) I generally prefer this pattern, it can also be useful in overcoming Linq-To-Entities limitations.

for(i = list.Count()-1;i>=0;i--)



if (item.Delete) list.Remove(item);


This way cycles through the list backwards with a plain old For loop. Doing this forwards could be problematic if the size of the collection changes, but backwards should always be safe.

Convert IEnumerable to DataTable

Firstly you need to add a where T:class constraint - you can't call GetValue on value types unless they're passed by ref.

Secondly GetValue is very slow and gets called a lot.

To get round this we can create a delegate and call that instead:

MethodInfo method = property.GetGetMethod(true);
Delegate.CreateDelegate(typeof(Func<TClass, TProperty>), method );

The problem is that we don't know TProperty, but as usual on here Jon Skeet has the answer - we can use reflection to retrieve the getter delegate, but once we have it we don't need to reflect again:

public class ReflectionUtility
    internal static Func<object, object> GetGetter(PropertyInfo property)
        // get the get method for the property
        MethodInfo method = property.GetGetMethod(true);

        // get the generic get-method generator (ReflectionUtility.GetSetterHelper<TTarget, TValue>)
        MethodInfo genericHelper = typeof(ReflectionUtility).GetMethod(
            BindingFlags.Static | BindingFlags.NonPublic);

        // reflection call to the generic get-method generator to generate the type arguments
        MethodInfo constructedHelper = genericHelper.MakeGenericMethod(

        // now call it. The null argument is because it's a static method.
        object ret = constructedHelper.Invoke(null, new object[] { method });

        // cast the result to the action delegate and return it
        return (Func<object, object>) ret;

    static Func<object, object> GetGetterHelper<TTarget, TResult>(MethodInfo method)
        where TTarget : class // target must be a class as property sets on structs need a ref param
        // Convert the slow MethodInfo into a fast, strongly typed, open delegate
        Func<TTarget, TResult> func = (Func<TTarget, TResult>) Delegate.CreateDelegate(typeof(Func<TTarget, TResult>), method);

        // Now create a more weakly typed delegate which will call the strongly typed one
        Func<object, object> ret = (object target) => (TResult) func((TTarget) target);
        return ret;

So now your method becomes:

public static DataTable ToDataTable<T>(this IEnumerable<T> items) 
    where T: class
    // ... create table the same way

    var propGetters = new List<Func<T, object>>();
foreach (var prop in props)
        Func<T, object> func = (Func<T, object>) ReflectionUtility.GetGetter(prop);

    // Add the property values per T as rows to the datatable
    foreach (var item in items) 
        var values = new object[props.Length];  
        for (var i = 0; i < props.Length; i++) 
            //values[i] = props[i].GetValue(item, null);   
            values[i] = propGetters[i](item);


    return table; 

You could further optimise it by storing the getters for each type in a static dictionary, then you will only have the reflection overhead once for each type.

Stacked Tabs in Bootstrap 3

Left, Right and Below tabs were removed from Bootstrap 3, but you can add custom CSS to achieve this..

.tabs-below > .nav-tabs,
.tabs-right > .nav-tabs,
.tabs-left > .nav-tabs {
  border-bottom: 0;

.tab-content > .tab-pane,
.pill-content > .pill-pane {
  display: none;

.tab-content > .active,
.pill-content > .active {
  display: block;

.tabs-below > .nav-tabs {
  border-top: 1px solid #ddd;

.tabs-below > .nav-tabs > li {
  margin-top: -1px;
  margin-bottom: 0;

.tabs-below > .nav-tabs > li > a {
  -webkit-border-radius: 0 0 4px 4px;
     -moz-border-radius: 0 0 4px 4px;
          border-radius: 0 0 4px 4px;

.tabs-below > .nav-tabs > li > a:hover,
.tabs-below > .nav-tabs > li > a:focus {
  border-top-color: #ddd;
  border-bottom-color: transparent;

.tabs-below > .nav-tabs > .active > a,
.tabs-below > .nav-tabs > .active > a:hover,
.tabs-below > .nav-tabs > .active > a:focus {
  border-color: transparent #ddd #ddd #ddd;

.tabs-left > .nav-tabs > li,
.tabs-right > .nav-tabs > li {
  float: none;

.tabs-left > .nav-tabs > li > a,
.tabs-right > .nav-tabs > li > a {
  min-width: 74px;
  margin-right: 0;
  margin-bottom: 3px;

.tabs-left > .nav-tabs {
  float: left;
  margin-right: 19px;
  border-right: 1px solid #ddd;

.tabs-left > .nav-tabs > li > a {
  margin-right: -1px;
  -webkit-border-radius: 4px 0 0 4px;
     -moz-border-radius: 4px 0 0 4px;
          border-radius: 4px 0 0 4px;

.tabs-left > .nav-tabs > li > a:hover,
.tabs-left > .nav-tabs > li > a:focus {
  border-color: #eeeeee #dddddd #eeeeee #eeeeee;

.tabs-left > .nav-tabs .active > a,
.tabs-left > .nav-tabs .active > a:hover,
.tabs-left > .nav-tabs .active > a:focus {
  border-color: #ddd transparent #ddd #ddd;
  *border-right-color: #ffffff;

.tabs-right > .nav-tabs {
  float: right;
  margin-left: 19px;
  border-left: 1px solid #ddd;

.tabs-right > .nav-tabs > li > a {
  margin-left: -1px;
  -webkit-border-radius: 0 4px 4px 0;
     -moz-border-radius: 0 4px 4px 0;
          border-radius: 0 4px 4px 0;

.tabs-right > .nav-tabs > li > a:hover,
.tabs-right > .nav-tabs > li > a:focus {
  border-color: #eeeeee #eeeeee #eeeeee #dddddd;

.tabs-right > .nav-tabs .active > a,
.tabs-right > .nav-tabs .active > a:hover,
.tabs-right > .nav-tabs .active > a:focus {
  border-color: #ddd #ddd #ddd transparent;
  *border-left-color: #ffffff;

Working example:


If you don't need the exact look of a tab (bordered appropriately on the left or right as each tab is activated), you can simple use nav-stacked, along with Bootstrap col-* to float the tabs to the left or right...

nav-stacked demo:

<ul class="nav nav-pills nav-stacked col-md-3">
    <li><a href="#a" data-toggle="tab">1</a></li>
    <li><a href="#b" data-toggle="tab">2</a></li>
    <li><a href="#c" data-toggle="tab">3</a></li>

text-align:center won't work with form <label> tag (?)

This is because label is an inline element, and is therefore only as big as the text it contains.

The possible is to display your label as a block element like this:

#formItem label {
    display: block;
    text-align: center;
    line-height: 150%;
    font-size: .85em;

However, if you want to use the label on the same line with other elements, you either need to set display: inline-block; and give it an explicit width (which doesn't work on most browsers), or you need to wrap it inside a div and do the alignment in the div.

Binary numbers in Python

I think you're confused about what binary is. Binary and decimal are just different representations of a number - e.g. 101 base 2 and 5 base 10 are the same number. The operations add, subtract, and compare operate on numbers - 101 base 2 == 5 base 10 and addition is the same logical operation no matter what base you're working in. The fact that your python interpreter may store things as binary internally doesn't affect how you work with it - if you have an integer type, just use +, -, etc.

If you have strings of binary digits, you'll have to either write your own implementation or convert them using the int(binaryString, 2) function.

filename.whl is not supported wheel on this platform

If you are totally new to python read step by step or go directly to 5th step directly. Follow the below method to install scipy 0.18.1 on Windows 64-bit , Python 64-bit . Be careful with the versions of 1. Python 2. Windows 3. .whl version of numpy and scipy files 4. First install numpy and then scipy.

pip install FileName.whl
  1. ForNumpy: ForScipy:

Be aware of the file name ( what I mean is check the cp no). Ex :scipy-0.18.1-cp35-cp35m-win_amd64.whl To check which cp is supported by your pip , go to point No 2 below.

If you are using .whl file . Following errors are likely to occur .

  1. You are using pip version 7.1.0, however version 8.1.2 is available.

You should consider upgrading via the 'python -m pip install --upgrade pip' command

  1. scipy-0.15.1-cp33-none-win_amd64.whl.whl is not supported wheel on this platform

For the above error : start Python(in my case 3.5), type : import pip print(pip.pep425tags.get_supported())

output :

[('cp35', 'cp35m', 'win_amd64'), ('cp35', 'none', 'win_amd64'), ('py3', 'none', 'win_amd64'), ('cp35', 'none', 'any'), ('cp3', 'none', 'any'), ('py35', 'none', 'any'), ('py3', 'none', 'any'), ('py34', 'none', 'any'), ('py33', 'none', 'any'), ('py32', 'none', 'any'), ('py31', 'none', 'any'), ('py30', 'none', 'any')]

In the output you will observe cp35 is there , so download cp35 for numpy as well as scipy. Further edits are most welcome !!!!

How can I find out which server hosts LDAP on my windows domain?

AD registers Service Location (SRV) resource records in its DNS server which you can query to get the port and the hostname of the responsible LDAP server in your domain.

Just try this on the command-line:

C:\> nslookup 
> set types=all
> _ldap._tcp.<<your.AD.domain>>
_ldap._tcp.<<your.AD.domain>>  SRV service location:
      priority       = 0
      weight         = 100
      port           = 389
      svr hostname   = <<ldap.hostname>>.<<your.AD.domain>>

(provided that your nameserver is the AD nameserver which should be the case for the AD to function properly)

Please see Active Directory SRV Records and Windows 2000 DNS white paper for more information.

Compare every item to every other item in ArrayList

This code helped me get this behaviour: With a list a,b,c, I should get compared ab, ac and bc, but any other pair would be excess / not needed.

import java.util.*;
import static java.lang.System.out;

// rl = rawList; lr = listReversed
ArrayList<String> rl = new ArrayList<String>();
ArrayList<String> lr = new ArrayList<String>();


for (String itemA : rl) {
        for (String itemZ : lr) {
        System.out.println(itemA + itemZ);

The loop goes as like in this picture: Triangular comparison visual example

or as this:

   |   f    e    d    c    b   a
a  |  af   ae   ad   ac   ab   ·
b  |  bf   be   bd   bc   ·   
c  |  cf   ce   cd   ·      
d  |  df   de   ·         
e  |  ef   ·            
f  |  ·               

total comparisons is a triangular number (n * n-1)/2

Tomcat is not running even though JAVA_HOME path is correct

To run Tomcat8 you need to have JRE_HOME defined in Env Variable.

JAVA_HOME alone will not do even if correctly set.

JRE_HOME = C:\Program Files\Java\jdk1.8.0_77\jre

You should select the JRE that is inside SDK, i.e. one with your JDK(SDK) installation. In other words your JAVA_HOME + \jre

When compiling JDK is needed to support JSP, to compile Servlets which are generated from *.jsp files. Otherwise to run JRE is needed. So when you develop you need JAVA_HOME and when you deploy you need JRE_HOME.

Android Studio Could not initialize class org.codehaus.groovy.runtime.InvokerHelper

For me the solution was to upgrade the gradle version to 6.3 from the android project structure (java 14.0.1 is already installed on my pc).

Center image using text-align center?

Use this to your img CSS:

img {
  margin-right: auto;
  margin-left: auto;

Entity Framework code first unique column

EF doesn't support unique columns except keys. If you are using EF Migrations you can force EF to create unique index on UserName column (in migration code, not by any annotation) but the uniqueness will be enforced only in the database. If you try to save duplicate value you will have to catch exception (constraint violation) fired by the database.

How do I size a UITextView to its content?

Using UITextViewDelegate is the easiest way:

func textViewDidChange(_ textView: UITextView) {
    textviewHeight.constant = textView.contentSize.height

HTTP GET request in JavaScript?

// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest()

// Open a new connection, using the GET request on the URL endpoint'GET', 'restUrl', true)

request.onload = function () {
  // Begin accessing JSON data here

// Send request

Android Layout Right Align

To support older version Space can be replaced with View as below. Add this view between after left most component and before right most component. This view with weight=1 will stretch and fill the space

        android:layout_weight="1" />

Complete sample code is given here. It has has 4 components. Two arrows will be on the right and left side. The Text and Spinner will be in the middle.

        android:src="@drawable/prev" />

        android:layout_weight="1" />

        android:textSize="25sp" />

        android:textSize="25sp" />

        android:layout_weight="1" />

        android:src="@drawable/next" />

How to parse a date?

The problem is that you have a date formatted like this:

Thu Jun 18 20:56:02 EDT 2009

But are using a SimpleDateFormat that is:


The two formats don't agree. You need to construct a SimpleDateFormat that matches the layout of the string you're trying to parse into a Date. Lining things up to make it easy to see, you want a SimpleDateFormat like this:

EEE MMM dd HH:mm:ss zzz yyyy
Thu Jun 18 20:56:02 EDT 2009

Check the JavaDoc page I linked to and see how the characters are used.

Getting specified Node values from XML document

Just like you do for getting something from the CNode you also need to do for the ANode

XmlNodeList xnList = xml.SelectNodes("/Element[@*]");
foreach (XmlNode xn in xnList)
  XmlNode anode = xn.SelectSingleNode("ANode");
    if (anode!= null)
        string id = anode["ID"].InnerText;
        string date = anode["Date"].InnerText;
        XmlNodeList CNodes = xn.SelectNodes("ANode/BNode/CNode");
        foreach (XmlNode node in CNodes)
         XmlNode example = node.SelectSingleNode("Example");
         if (example != null)
            string na = example["Name"].InnerText;
            string no = example["NO"].InnerText;

Does GPS require Internet?

There are two issues:

  1. Getting the current coordinates (longitude, latitude, perhaps altitude) based on some external signals received by your device, and
  2. Deriving a human-readable position (address) from the coordinates.

To get the coordinates you don't need the Internet. GPS is satellite-based. But to derive street/city information from the coordinates, you'd need either to implement the map and the corresponding algorithms yourself on the device (a lot of work!) or to rely on proven services, e.g. by Google, in which case you'd need an Internet connection.

As of recently, Google allows for caching the maps, which would at least allow you to show your current position on the map even without a data connection, provided, you had cached the map in advance, when you could access the Internet.

Putting text in top left corner of matplotlib plot

One solution would be to use the plt.legend function, even if you don't want an actual legend. You can specify the placement of the legend box by using the loc keyterm. More information can be found at this website but I've also included an example showing how to place a legend:

ax.scatter(xa,ya, marker='o', s=20, c="lightgreen", alpha=0.9)
ax.scatter(xb,yb, marker='o', s=20, c="dodgerblue", alpha=0.9)
ax.scatter(xc,yc marker='o', s=20, c="firebrick", alpha=1.0)
ax.scatter(xd,xd,xd, marker='o', s=20, c="goldenrod", alpha=0.9)
line1 = Line2D(range(10), range(10), marker='o', color="goldenrod")
line2 = Line2D(range(10), range(10), marker='o',color="firebrick")
line3 = Line2D(range(10), range(10), marker='o',color="lightgreen")
line4 = Line2D(range(10), range(10), marker='o',color="dodgerblue")
plt.legend((line1,line2,line3, line4),('line1','line2', 'line3', 'line4'),numpoints=1, loc=2) 

Note that because loc=2, the legend is in the upper-left corner of the plot. And if the text overlaps with the plot, you can make it smaller by using legend.fontsize, which will then make the legend smaller.

How can I get the MAC and the IP address of a connected client in PHP?

I don't think you can get MAC address in PHP, but you can get IP from $_SERVER['REMOTE_ADDR'] variable.

You don't have permission to access / on this server

Check file permissions of the /var/www/html and the ALLOW directive in your apache conf

Make sure all files are readable by the webserver and the allow directive is like

 <Directory "/var/www/html">
    Order allow,deny
    Allow from all

if you can see files then consider sorting the directive to be more restrictive

Python object.__repr__(self) should be an expression?

>>> from datetime import date
>>> repr(        # calls
', 1, 16)'
>>> eval(_)                   # _ is the output of the last command, 1, 16)

The output is a string that can be parsed by the python interpreter and results in an equal object.

If that's not possible, it should return a string in the form of <...some useful description...>.

target="_blank" vs. target="_new"

  • _blank as a target value will spawn a new window every time,
  • _new will only spawn one new window.

Also, every link clicked with a target value of _new will replace the page loaded in the previously spawned window.

You can click here When to use _blank or _new to try it out for yourself.

Rails formatting date

Since I18n is the Rails core feature starting from version 2.2 you can use its localize-method. By applying the forementioned strftime %-variables you can specify the desired format under config/locales/en.yml (or whatever language), in your case like this:

    default: '%FT%T'

Or if you want to use this kind of format in a few specific places you can refer it as a variable like this

    specific_format: '%FT%T'

After that you can use it in your views like this:

l(Mode.last.created_at, format: :specific_format)  

TestNG ERROR Cannot find class in classpath

I just had this problem and was because the skip test option in the run configuration was checked. made that unchecked and build, then run the testNg, worked.

How to calculate the CPU usage of a process by PID in Linux from C?

You need to parse out the data from /proc/<PID>/stat. These are the first few fields (from Documentation/filesystems/proc.txt in your kernel source):

Table 1-3: Contents of the stat files (as of 2.6.22-rc3)
 Field          Content
  pid           process id
  tcomm         filename of the executable
  state         state (R is running, S is sleeping, D is sleeping in an
                uninterruptible wait, Z is zombie, T is traced or stopped)
  ppid          process id of the parent process
  pgrp          pgrp of the process
  sid           session id
  tty_nr        tty the process uses
  tty_pgrp      pgrp of the tty
  flags         task flags
  min_flt       number of minor faults
  cmin_flt      number of minor faults with child's
  maj_flt       number of major faults
  cmaj_flt      number of major faults with child's
  utime         user mode jiffies
  stime         kernel mode jiffies
  cutime        user mode jiffies with child's
  cstime        kernel mode jiffies with child's

You're probably after utime and/or stime. You'll also need to read the cpu line from /proc/stat, which looks like:

cpu  192369 7119 480152 122044337 14142 9937 26747 0 0

This tells you the cumulative CPU time that's been used in various categories, in units of jiffies. You need to take the sum of the values on this line to get a time_total measure.

Read both utime and stime for the process you're interested in, and read time_total from /proc/stat. Then sleep for a second or so, and read them all again. You can now calculate the CPU usage of the process over the sampling time, with:

user_util = 100 * (utime_after - utime_before) / (time_total_after - time_total_before);
sys_util = 100 * (stime_after - stime_before) / (time_total_after - time_total_before);

Make sense?

AttributeError("'str' object has no attribute 'read'")

AttributeError("'str' object has no attribute 'read'",)

This means exactly what it says: something tried to find a .read attribute on the object that you gave it, and you gave it an object of type str (i.e., you gave it a string).

The error occurred here:

json.load (jsonofabitch)['data']['children']

Well, you aren't looking for read anywhere, so it must happen in the json.load function that you called (as indicated by the full traceback). That is because json.load is trying to .read the thing that you gave it, but you gave it jsonofabitch, which currently names a string (which you created by calling .read on the response).

Solution: don't call .read yourself; the function will do this, and is expecting you to give it the response directly so that it can do so.

You could also have figured this out by reading the built-in Python documentation for the function (try help(json.load), or for the entire module (try help(json)), or by checking the documentation for those functions on .

Check if returned value is not null and if so assign it, in one line, with one method call

Use your own

public static <T> T defaultWhenNull(@Nullable T object, @NonNull T def) {
    return (object == null) ? def : object;


defaultWhenNull(getNullableString(), "");



  • Works if you don't develop in Java8
  • Works for android development with support for pre API 24 devices
  • Doesn't need an external library


  • Always evaluates the default value (as oposed to cond ? nonNull() : notEvaluated())

    This could be circumvented by passing a Callable instead of a default value, but making it somewhat more complicated and less dynamic (e.g. if performance is an issue).

    By the way, you encounter the same disadvantage when using Optional.orElse() ;-)

Get scroll position using jquery

I believe the best method with jQuery is using .scrollTop():

var pos = $('body').scrollTop();

Failed to import new Gradle project: failed to find Build Tools revision *.0.0

Try to run gradle at the command line first. It might prompt you to setup and environment variable:

export _JAVA_OPTIONS="-Xms256m -Xmx1024m"

Read more here: 1, 2

Further make sure that the Android SDK build tools (adb, aapt, dx, dx.jar) are available in the PATH. If not you can create symlinks at the appropriate locations. They changed with the release of new SDK versions. Here is a shell script which creates the symlinks within the $ANDROID_HOME folder for you.

How to include a class in PHP

  1. require('/yourpath/yourphp.php');

  2. require_once('/yourpath/yourphp.php');

  3. include '/yourpath/yourphp.php';

  4. use \Yourapp\Yourname


Avoid using require_once because it is slow: Why is require_once so bad to use? Certificates does not conform to algorithm constraints

this is more likely happening because somewhere along your certificate chain you have a certificate, more likely an old root, which is still signed with the MD2RSA algorythm.

You need to locate it into your certificate store and delete it.

Then get back to your certification authority and ask them for then new root.

It will more likely be the same root with the same validity period but it has been recertified with SHA1RSA.

Hope this help.

How to get default gateway in Mac OSX

I would use something along these lines...

 netstat -rn | grep "default" | awk '{print $2}'

What is the difference between "word-break: break-all" versus "word-wrap: break-word" in CSS

There's a huge difference. break-all is basically unusable for rendering readable text.

Let's say you've got the string This is a text from an old magazine in a container which only fits 6 chars per row.

word-break: break-all

This i
s a te
xt fro
m an o
ld mag

As you can see the result is awful. break-all will try to fit as many chararacters into each row as possible, it will even split a 2 letter word like "is" onto 2 rows! It's ridiculous. This is why break-all is rarely ever used.

word-wrap: break-word

is a
an old

break-word will only break words which are too long to ever fit the container (like "magazine", which is 8 chars, and the container only fits 6 chars). It will never break words that could fit the container in their entirety, instead it will push them to a new line.

<div style="width: 100px; border: solid 1px black; font-family: monospace;">_x000D_
  <h1 style="word-break: break-all;">This is a text from an old magazine</h1>_x000D_
  <h1 style="word-wrap: break-word;">This is a text from an old magazine</h1>_x000D_

Get current NSDate in timestamp format

Can also use


for timestamp in seconds.

Checking for Undefined In React

In case you also need to check if is not undefined ; you can do that in a single if statement, like this:

if (typeof !== "undefined" && typeof !== "undefined") {

And, when an undefined , empty or null value is not expected; you can make it more concise:

if ( && {

How can I convert an HTML table to CSV?

This is a very old thread, but may be someone like me will bump into it. I have made some additions for the audiodude's script to read the html from file instead adding it to the code, and another parameter that controls printing of the header lines.

the script should be run like that

ruby <script_name> <file_name> [<print_headers>]

the code is:

require 'nokogiri'

print_header_lines = ARGV[1][0]) do |f|

  doc = Nokogiri::HTML(table_string)

  doc.xpath('//table//tr').each do |row|
    if print_header_lines
      row.xpath('th').each do |cell|
        print '"', cell.text.gsub("\n", ' ').gsub('"', '\"').gsub(/(\s){2,}/m, '\1'), "\", "
    row.xpath('td').each do |cell|
      print '"', cell.text.gsub("\n", ' ').gsub('"', '\"').gsub(/(\s){2,}/m, '\1'), "\", "
    print "\n"

How to execute a shell script from C in Linux?

A simple way is.....

#include <stdio.h>
#include <stdlib.h>

#define SHELLSCRIPT "\
#/bin/bash \n\
echo \"hello\" \n\
echo \"how are you\" \n\
echo \"today\" \n\
/*Also you can write using char array without using MACRO*/
/*You can do split it with many strings finally concatenate 
  and send to the system(concatenated_string); */

int main()
    puts("Will execute sh with the following script :");
    puts("Starting now:");
    system(SHELLSCRIPT);    //it will run the script inside the c code. 
    return 0;

Say thanks to
Yoda @

Change string color with NSAttributedString?

With Swift 4, NSAttributedStringKey has a static property called foregroundColor. foregroundColor has the following declaration:

static let foregroundColor: NSAttributedStringKey

The value of this attribute is a UIColor object. Use this attribute to specify the color of the text during rendering. If you do not specify this attribute, the text is rendered in black.

The following Playground code shows how to set the text color of an NSAttributedString instance with foregroundColor:

import UIKit

let string = "Some text"
let attributes = [NSAttributedStringKey.foregroundColor :]
let attributedString = NSAttributedString(string: string, attributes: attributes)

The code below shows a possible UIViewController implementation that relies on NSAttributedString in order to update the text and text color of a UILabel from a UISlider:

import UIKit

enum Status: Int {
    case veryBad = 0, bad, okay, good, veryGood

    var display: (text: String, color: UIColor) {
        switch self {
        case .veryBad:  return ("Very bad", .red)
        case .bad:      return ("Bad", .orange)
        case .okay:     return ("Okay", .yellow)
        case .good:     return ("Good", .green)
        case .veryGood: return ("Very good", .blue)

    static let minimumValue = Status.veryBad.rawValue
    static let maximumValue = Status.veryGood.rawValue
final class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var slider: UISlider!
    var currentStatus: Status = Status.veryBad {
        didSet {
            // currentStatus is our model. Observe its changes to update our display

    override func viewDidLoad() {

        // Prepare slider
        slider.minimumValue = Float(Status.minimumValue)
        slider.maximumValue = Float(Status.maximumValue)

        // Set display

    func updateDisplay() {
        let attributes = [NSAttributedStringKey.foregroundColor : currentStatus.display.color]
        let attributedString = NSAttributedString(string: currentStatus.display.text, attributes: attributes)
        label.attributedText = attributedString
        slider.value = Float(currentStatus.rawValue)

    @IBAction func updateCurrentStatus(_ sender: UISlider) {
        let value = Int(sender.value.rounded())
        guard let status = Status(rawValue: value) else { fatalError("Could not get Status object from value") }
        currentStatus = status


Note however that you don't really need to use NSAttributedString for such an example and can simply rely on UILabel's text and textColor properties. Therefore, you can replace your updateDisplay() implementation with the following code:

func updateDisplay() {
    label.text = currentStatus.display.text
    label.textColor = currentStatus.display.color
    slider.value = Float(currentStatus.rawValue)

How to check if the docker engine and a docker container are running?

on a Mac you might see the image:

enter image description here

if you right click on the docker icon then you see:

enter image description here


docker ps


docker run hello-world

HTML Table cell background image alignment

This works in IE9 (Compatibility View and Normal Mode), Firefox 17, and Chrome 23:

        <td style="background-image:url(untitled.png); background-position:right 0px; background-repeat:no-repeat;">
            Hello World

How to invert a grep expression

As stated multiple times, inversion is achieved by the -v option to grep. Let me add the (hopefully amusing) note that you could have figured this out yourself by grepping through the grep help text:

grep --help | grep invert

-v, --invert-match select non-matching lines

Bootstrap Element 100% Width

Sometimes it's not possible to close the content container. The solution we are using is a bit different but prevent a overflow because of the firefox scrollbar size!

.full-width {
 margin-top: 15px;
 margin-bottom: 15px;
 position: relative;
 width: calc(100vw - 10px);
 margin-left: calc(-50vw + 5px);
 left: 50%;

Here is a example:

How to Sign an Already Compiled Apk

fastest way is by signing with the debug keystore:

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore ~/.android/debug.keystore app.apk androiddebugkey -storepass android

or on Windows:

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore %USERPROFILE%/.android/debug.keystore test.apk androiddebugkey -storepass android

How to check if dropdown is disabled?

There are two options:


You can also use like is()



Using == true by checking if the attributes value is disabled. attr()


whatever you feel fits better , you can use :)


How to enable C++17 compiling in Visual Studio?

Visual studio 2019 version:

The drop down menu was moved to:

  • Right click on project (not solution)
  • Properties (or Alt + Enter)
  • From the left menu select Configuration Properties
  • General
  • In the middle there is an option called "C++ Language Standard"
  • Next to it is the drop down menu
  • Here you can select Default, ISO C++ 14, 17 or latest

How to open the second form?

If you need to show Form2 as a modal dialog, from within Form1 do:

var form2 = new Form2();
if (form2.ShowDialog() == DialogResult.OK) 
    // process results here

A modal dialog will retain focus while it is open; it will set the parent windows (Form1) "in the background" until it is closed, which is quite a common practice for settings windows.

Can't connect to MySQL server error 111

If all the previous answers didn't give any solution, you should check your user privileges.

If you could login as root to mysql then you should add this:


Then try to connect again using mysql -ubeer -pbeer -h192.168.1.100. It should work.

How to set default values in Go structs

There is a way of doing this with tags, which allows for multiple defaults.

Assume you have the following struct, with 2 default tags default0 and default1.

type A struct {
   I int    `default0:"3" default1:"42"`
   S string `default0:"Some String..." default1:"Some Other String..."`

Now it's possible to Set the defaults.

func main() {

ptr := &A{}

Set(ptr, "default0")
fmt.Printf("ptr.I=%d ptr.S=%s\n", ptr.I, ptr.S)
// ptr.I=3 ptr.S=Some String...

Set(ptr, "default1")
fmt.Printf("ptr.I=%d ptr.S=%s\n", ptr.I, ptr.S)
// ptr.I=42 ptr.S=Some Other String...

Here's the complete program in a playground.

If you're interested in a more complex example, say with slices and maps, then, take a look at creasty/defaultse

MongoDB and "joins"

The first example you link to shows how MongoDB references behave much like lazy loading not like a join. There isn't a query there that's happening on both collections, rather you query one and then you lookup items from another collection by reference.

Python Finding Prime Factors

This is my python code: it has a fast check for primes and checks from highest to lowest the prime factors. You have to stop if no new numbers came out. (Any ideas on this?)

import math

def is_prime_v3(n):
    """ Return 'true' if n is a prime number, 'False' otherwise """
    if n == 1:
        return False

    if n > 2 and n % 2 == 0:
        return False

    max_divisor = math.floor(math.sqrt(n))
    for d in range(3, 1 + max_divisor, 2):
        if n % d == 0:
            return False
    return True

number = <Number>

for i in range(1,math.floor(number/2)):
    if is_prime_v3(i):
        if number % i == 0:
            print("Found: {} with factor {}".format(number / i, i))

The answer for the initial question arrives in a fraction of a second.

jQuery ajax post file field

Try this...

<script type="text/javascript">
           var myData = $( form ).serialize(); 
                type: "POST", 
                contentType:attr( "enctype", "multipart/form-data" ),
                url: " URL Goes Here ",  
                data: myData,  
                success: function( data )  
                     alert( data );
           return false;  

Here the contentType is specified as multipart/form-data as we do in the form tag, this will work to upload simple file On server side you just need to write simple file upload code to handle this request with echoing message you want to show to user as a response.

How can I prevent a window from being resized with tkinter?

This is a variant of an existing solution already provided above:

import tkinter as tk

root = tk.Tk()
root.resizable(0, 0)

The advantage is that you type less.

How do I find what Java version Tomcat6 is using?

If tomcat did not start up yet , you can use the command \bin\cataline version to check which JVM will the tomcat use when you start tomcat using bin\startup

In fact ,\bin\cataline version just call the main class of org.apache.catalina.util.ServerInfo , which is located inside the \lib\catalina.jar . The org.apache.catalina.util.ServerInfo gets the JVM Version and JVM Vendor by the following commands:

System.out.println("JVM Version: " +System.getProperty("java.runtime.version"));
System.out.println("JVM Vendor: " +System.getProperty("java.vm.vendor")); 

So , if the tomcat is running , you can create a JSP page that call org.apache.catalina.util.ServerInfo or just simply call the above System.getProperty() to get the JVM Version and Vendor . Deploy this JSP to the running tomcat instance and browse to it to see the result.

Alternatively, you should know which port is the running tomcat instance using . So , you can use the OS command to find which process is listening to this port. For example in the window , you can use the command netstat -aon to find out the process ID of a process that is listening to a particular port . Then go to the window task manager to check the full file path of this process ID belongs to. .The java version can then be determined from that file path.

Safely remove migration In Laravel

 php artisan migrate:fresh

Should do the job, if you are in development and the desired outcome is to start all over.

In production, that maybe not the desired thing, so you should be adverted. (The migrate:fresh command will drop all tables from the database and then execute the migrate command).

Multiple files upload in Codeigniter

private function upload_files($path, $title, $files)
    $config = array(
        'upload_path'   => $path,
        'allowed_types' => 'jpg|gif|png',
        'overwrite'     => 1,

    $this->load->library('upload', $config);

    $images = array();

    foreach ($files['name'] as $key => $image) {
        $_FILES['images[]']['name']= $files['name'][$key];
        $_FILES['images[]']['type']= $files['type'][$key];
        $_FILES['images[]']['tmp_name']= $files['tmp_name'][$key];
        $_FILES['images[]']['error']= $files['error'][$key];
        $_FILES['images[]']['size']= $files['size'][$key];

        $fileName = $title .'_'. $image;

        $images[] = $fileName;

        $config['file_name'] = $fileName;


        if ($this->upload->do_upload('images[]')) {
        } else {
            return false;
    return true;

Replace multiple characters in one replace call

You could also try this :

function replaceStr(str, find, replace) {
    for (var i = 0; i < find.length; i++) {
        str = str.replace(new RegExp(find[i], 'gi'), replace[i]);
    return str;

var text = "#here_is_the_one#";
var find = ["#","_"];
var replace = ['',' '];
text = replaceStr(text, find, replace);

find refers to the text to be found and replace to the text to be replaced with

This will be replacing case insensitive characters. To do otherway just change the Regex flags as required. Eg: for case sensitive replace :

new RegExp(find[i], 'g')

How to pass object from one component to another in Angular 2?

From component

import { Component, OnInit, ViewChild} from '@angular/core';_x000D_
    import { HttpClient } from '@angular/common/http';_x000D_
    import { dataService } from "src/app/service/data.service";_x000D_
    @Component( {_x000D_
        selector: 'app-sideWidget',_x000D_
        templateUrl: './sideWidget.html',_x000D_
        styleUrls: ['./linked-widget.component.css']_x000D_
    } )_x000D_
    export class sideWidget{_x000D_
    TableColumnNames: object[];_x000D_
    SelectedtableName: string = "patient";_x000D_
    constructor( private LWTableColumnNames: dataService ) { _x000D_
    ngOnInit() {_x000D_ 'getColumns', this.SelectedtableName )_x000D_
            ( data: object[] ) => {_x000D_
                this.TableColumnNames = data;_x000D_
     this.LWTableColumnNames.refLWTableColumnNames = this.TableColumnNames; //this line of code will pass the value through data service_x000D_
            } );_x000D_
    }    _x000D_


import { Injectable } from '@angular/core';_x000D_
import { BehaviorSubject, Observable } from 'rxjs';_x000D_
export class dataService {_x000D_
    refLWTableColumnNames: object;//creating an object for the data_x000D_

To Component

import { Component, OnInit } from '@angular/core';_x000D_
import { dataService } from "src/app/service/data.service";_x000D_
@Component( {_x000D_
    selector: 'app-linked-widget',_x000D_
    templateUrl: './linked-widget.component.html',_x000D_
    styleUrls: ['./linked-widget.component.css']_x000D_
} )_x000D_
export class LinkedWidgetComponent implements OnInit {_x000D_
    constructor(private LWTableColumnNames: dataService) { }_x000D_
    ngOnInit() {_x000D_
        console.log(this.LWTableColumnNames.refLWTableColumnNames);// calling the object from another component_x000D_

How to truncate text in Angular2?

Like this:

{{ data.title | slice:0:20 }}

And if you want the ellipsis, here's a workaround

{{ data.title | slice:0:20 }}...

Recover unsaved SQL query scripts

SSMSBoost add-in (currently free)

  • keeps track on all executed statements (saves them do disk)
  • regulary saves snapshot of SQL Editor contents. You keep history of the modifications of your script. Sometimes "the best" version is not the last and you want to restore the intermediate state.
  • keeps track of opened tabs and allows to restore them after restart. Unsaved tabs are also restored.

+tons of other features. (I am the developer of the add-in)

How to call a function from a string stored in a variable?

Complementing the answer of @Chris K if you want to call an object's method, you can call it using a single variable with the help of a closure:

function get_method($object, $method){
    return function() use($object, $method){
        $args = func_get_args();
        return call_user_func_array(array($object, $method), $args);           

class test{        

    function echo_this($text){
        echo $text;

$test = new test();
$echo = get_method($test, 'echo_this');
$echo('Hello');  //Output is "Hello"

I posted another example here

C# "must declare a body because it is not marked abstract, extern, or partial"

You cannot provide your own implementation for the setter when using automatic properties. In other words, you should either do:

public int Hour { get;set;} // Automatic property, no implementation

or provide your own implementation for both the getter and setter, which is what you want judging from your example:

public int Hour  
    get { return hour; } 
        if (value < MIN_HOUR)
            hour = 0;
            MessageBox.Show("Hour value " + value.ToString() + " cannot be negative. Reset to " + MIN_HOUR.ToString(),
                    "Invalid Hour", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                //take the modulus to ensure always less than 24 hours
                //works even if the value is already within range, or value equal to 24
                hour = value % MAX_HOUR;

How to enable CORS in Core WebAPI

In my case only get request works well according to MindingData's answer. For other types of request you need to write:

app.UseCors(corsPolicyBuilder =>

Don't forget to add .AllowAnyHeader()

Change color of Label in C#

You can try this with Color.FromArgb:

Random rnd = new Random();
lbl.ForeColor = Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255));

How to vertically align elements in a div?

This is my personal solution for an i element inside a div

JSFiddle Example


<div class="circle">
    <i class="fa fa-plus icon">


.circle {
   border-radius: 50%;
   color: blue;
   background-color: red;
   text-align: center;
   line-height: 100px;

.icon {
  font-size: 50px;
  vertical-align: middle;

What is boilerplate code?

"boilerplate code" is any seemingly repetitive code that shows up again and again in order to get some result that seems like it ought to be much simpler.

It's a subjective definition.

The term comes from "boilerplate" in the newspaper industry: wiki

Format decimal for percentage values?

I have found the above answer to be the best solution, but I don't like the leading space before the percent sign. I have seen somewhat complicated solutions, but I just use this Replace addition to the answer above instead of using other rounding solutions.

String.Format("Value: {0:P2}.", 0.8526).Replace(" %","%") // formats as 85.26% (varies by culture)

Difference between .keystore file and .jks file

Ultimately, .keystore and .jks are just file extensions: it's up to you to name your files sensibly. Some application use a keystore file stored in $HOME/.keystore: it's usually implied that it's a JKS file, since JKS is the default keystore type in the Sun/Oracle Java security provider. Not everyone uses the .jks extension for JKS files, because it's implied as the default. I'd recommend using the extension, just to remember which type to specify (if you need).

In Java, the word keystore can have either of the following meanings, depending on the context:

When talking about the file and storage, this is not really a storage facility for key/value pairs (there are plenty or other formats for this). Rather, it's a container to store cryptographic keys and certificates (I believe some of them can also store passwords). Generally, these files are encrypted and password-protected so as not to let this data available to unauthorized parties.

Java uses its KeyStore class and related API to make use of a keystore (whether it's file based or not). JKS is a Java-specific file format, but the API can also be used with other file types, typically PKCS#12. When you want to load a keystore, you must specify its keystore type. The conventional extensions would be:

  • .jks for type "JKS",
  • .p12 or .pfx for type "PKCS12" (the specification name is PKCS#12, but the # is not used in the Java keystore type name).

In addition, BouncyCastle also provides its implementations, in particular BKS (typically using the .bks extension), which is frequently used for Android applications.

Pandas dataframe fillna() only some columns in place

You can avoid making a copy of the object using Wen's solution and inplace=True:

df.fillna({'a':0, 'b':0}, inplace=True)

Which yields:

     a    b    c
0  1.0  4.0  NaN
1  2.0  5.0  NaN
2  3.0  0.0  7.0
3  0.0  6.0  8.0

JavaScript string with new line - but not using \n

The reason it is not working is because javascript strings must be terminated before the next newline character (not a \n obviously). The reason \n exists is to allow developers an easy way to put the newline character (ASCII: 10) into their strings.

When you have a string which looks like this:

//Note lack of terminating double quote
var foo = "Bob 

Your code will have a syntax error at that point and cease to run.

If you wish to have a string which spans multiple lines, you may insert a backslash character '\' just before you terminate the line, like so:

//Perfectly valid code
var foo = "Bob \
is \

However that string will not contain \n characters in the positions where the string was broken into separate lines. The only way to insert a newline into a string is to insert a character with a value of 10, the easiest way of which is the \n escape character.

var foo = "Bob\nis\ncool.";

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object

I was getting the same error on a restored database when I tried to insert a new record using the EntityFramework. It turned out that the Indentity/Seed was screwing things up.

Using a reseed command fixed it.

DBCC CHECKIDENT ('[Prices]', RESEED, 4747030);GO

Symfony2 : How to get form validation errors after binding the request to the form


I simply implemented a static method to handle the display of errors

static function serializeFormErrors(Form\Form $form)
    $errors = array();
     * @var  $key
     * @var Form\Form $child
    foreach ($form->all() as $key => $child) {
        if (!$child->isValid()) {
            foreach ($child->getErrors() as $error) {
                $errors[$key] = $error->getMessage();

    return $errors;

Hoping to help

What's the default password of mariadb on fedora?

I believe I found the right answers from here.

GitHub Wnmp

So in general it says this:

user: root
password: password

That is for version 10.0.15-MariaDB, installed through Wnmp ver. on Windows 7 x86

convert string array to string

Like this:

string str= test[0]+test[1];

You can also use a loop:

for(int i=0; i<2; i++)
    str += test[i];

Stuck while installing Visual Studio 2015 (Update for Microsoft Windows (KB2999226))

I have the same problem today, stuck on the kb2999226 for over an hour. First, i thought it is because i am using a VM on my local machine. But decided to cancel the installation, then install kb2999226 first, then install the vs2015 community again, it works out much better, the installation move forward and progressing. thx.

Javascript ES6/ES5 find in array and change

Given a changed object and an array:

const item = {...}
let items = [{id:2}, {id:3}, {id:4}];

Update the array with the new object by iterating over the array:

items = => ( === ? item : x)

A non-blocking read on a subprocess.PIPE in Python

Use select & read(1).

import subprocess     #no new requirements
def readAllSoFar(proc, retVal=''): 
  while ([proc.stdout],[],[],0)[0]!=[]):
  return retVal
p = subprocess.Popen(['/bin/ls'], stdout=subprocess.PIPE)
while not p.poll():
  print (readAllSoFar(p))

For readline()-like:

lines = ['']
while not p.poll():
  lines = readAllSoFar(p, lines[-1]).split('\n')
  for a in range(len(lines)-1):
    print a
lines = readAllSoFar(p, lines[-1]).split('\n')
for a in range(len(lines)-1):
  print a

check / uncheck checkbox using jquery?

For jQuery 1.6+ :

.attr() is deprecated for properties; use the new .prop() function instead as:

$('#myCheckbox').prop('checked', true); // Checks it
$('#myCheckbox').prop('checked', false); // Unchecks it

For jQuery < 1.6:

To check/uncheck a checkbox, use the attribute checked and alter that. With jQuery you can do:

$('#myCheckbox').attr('checked', true); // Checks it
$('#myCheckbox').attr('checked', false); // Unchecks it

Cause you know, in HTML, it would look something like:

<input type="checkbox" id="myCheckbox" checked="checked" /> <!-- Checked -->
<input type="checkbox" id="myCheckbox" /> <!-- Unchecked -->

However, you cannot trust the .attr() method to get the value of the checkbox (if you need to). You will have to rely in the .prop() method.

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

To me it happened in DogController that autowired DogService that autowired DogRepository. Dog class used to have field name but I changed it to coolName, but didn't change methods in DogRepository: Dog findDogByName(String name). I change that method to Dog findDogByCoolName(String name) and now it works.

How to break out of a loop from inside a switch?

Even if you don't like goto, do not use an exception to exit a loop. The following sample shows how ugly it could be:

try {
  while ( ... ) {
    switch( ... ) {
      case ...:
        throw 777; // I'm afraid of goto
catch ( int )

I would use goto as in this answer. In this case goto will make code more clear then any other option. I hope that this question will be helpful.

But I think that using goto is the only option here because of the string while(true). You should consider refactoring of your loop. I'd suppose the following solution:

bool end_loop = false;
while ( !end_loop ) {
    switch( msg->state ) {
    case MSGTYPE: // ... 
    // ... more stuff ...
    case DONE:
        end_loop = true; break;

Or even the following:

while ( msg->state != DONE ) {
    switch( msg->state ) {
    case MSGTYPE: // ... 
    // ... more stuff ...

Compare 2 JSON objects

Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).

You need to do a deep equals.

From - which seems the use jQuery.

Object.extend(Object, {
   deepEquals: function(o1, o2) {
     var k1 = Object.keys(o1).sort();
     var k2 = Object.keys(o2).sort();
     if (k1.length != k2.length) return false;
     return, function(keyPair) {
       if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
         return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
       } else {
         return o1[keyPair[0]] == o2[keyPair[1]];


var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);

if (Object.deepEquals(anObj, anotherObj))

Eclipse "Invalid Project Description" when creating new project from existing source

paste the project source and support libs to any other newly created folder and try to import from there. It worked for me.

Operation Not Permitted when on root - El Capitan (rootless disabled)

If you want to take control of /usr/bin/

You will need to reboot your system:

Right after the boot sound, Hold down Command-R to boot into the Recovery System

Click the Utilities menu and select Terminal

Type csrutil disable and press return

Click the ? menu and select Restart

Once you have committed your changes, make sure to re-enable SIP! It does a lot to protect your system. (Same steps as above except type: csrutil enable)

nil detection in Go

You can also check like struct_var == (struct{}). This does not allow you to compare to nil but it does check if it is initialized or not. Be careful while using this method. If your struct can have zero values for all of its fields you won't have great time.

package main

import "fmt"

type A struct {
    Name string

func main() {
    a := A{"Hello"}
    var b A

    if a == (A{}) {
        fmt.Println("A is empty") // Does not print

    if b == (A{}) {
        fmt.Println("B is empty") // Prints

100% width in React Native Flexbox

Style ={{width : "100%"}}

try this:

StyleSheet generated: {
  "width": "80%",
  "textAlign": "center",
  "marginTop": 21.8625,
  "fontWeight": "bold",
  "fontSize": 16,
  "color": "rgb(24, 24, 24)",
  "fontFamily": "Trajan Pro",
  "textShadowColor": "rgba(255, 255, 255, 0.2)",
  "textShadowOffset": {
    "width": 0,
    "height": 0.5

Is a slash ("/") equivalent to an encoded slash ("%2F") in the path portion of an HTTP URL

I also have a site that has numerous urls with urlencoded characters. I am finding that many web APIs (including Google webmaster tools and several Drupal modules) trip over urlencoded characters. Many APIs automatically decode urls at some point in their process and then use the result as a URL or HTML. When I find one of these problems, I usually double encode the results (which turns %2f into %252f) for that API. However, this will break other APIs which are not expecting double encoding, so this is not a universal solution.

Personally I am getting rid of as many special characters in my URLs as possible.

Also, I am using id numbers in my URLs which do not depend on urldecoding:


in this case, my code only uses 12354 to look for the article, and the rest of the URL gets ignored by my system (but is still used for SEO.) Also, this number should appear BEFORE the unused URL components. that way, the url will still work, even if the %2f gets decoded incorrectly.

Also, be sure to use canonical tags to ensure that url mistakes don't translate into duplicate content.

Clear dropdown using jQuery Select2

This works for me:

 $remote.select2('data', {id: null, text: null})

It also works with jQuery validate when you clear it that way.

-- edit 2013-04-09

At the time of writing this response, it was the only way. With recent patches, a proper and better way is now available.

$remote.select2('data', null)

How to commit to remote git repository

git push


git push server_name master

should do the trick, after you have made a commit to your local repository.

Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)


On windows forms it is available, at the top of the class put

  static void Main(string[] args)
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
       //other stuff here

since windows is single threaded, its all you need, in the event its a service you need to put it right above the call to the service (since there is no telling what thread you'll be on).

using System.Security.Principal 

is also needed.

CSS3 gradient background set on body doesn't stretch but instead repeats?

Regarding a previous answer, setting html and body to height: 100% doesn't seem to work if the content needs to scroll. Adding fixed to the background seems to fix that - no need for height: 100%;


body {_x000D_
  background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#cbccc8)) fixed;_x000D_

Is there a color code for transparent in HTML?

There is not a Transparent color code, but there is an Opacity styling. Check out the documentation about it over at

You will probably want to set the color of the element and then apply the opacity to it.


    background-color: #ffffff;
    opacity: .4;


You can use some online transparancy generatory which will also give you browser specific stylings. e.g. take a look at

Note though that when you set the transparency of an element, any child element becomes transparent also. So you really need to overlay any other elements.

You may also want to try using an RGBA colour using the Alpha (A) setting to change the opacity. e.g.

    background-color: rgba(255, 255, 255, .4);

Using RGBA over opacity means that your child elements are not transparent.

cvc-elt.1: Cannot find the declaration of element 'MyElement'

After making the change suggested above by Martin, I was still getting the same error. I had to make an additional change to my parsing code. I was parsing the XML file via a DocumentBuilder as shown in the oracle docs:

// parse an XML document into a DOM tree
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = parser.parse(new File("example.xml"));

The problem was that DocumentBuilder is not namespace aware by default. The following additional change resolved the issue:

// parse an XML document into a DOM tree
DocumentBuilderFactory dmfactory = DocumentBuilderFactory.newInstance();

DocumentBuilder parser = dmfactory.newDocumentBuilder();
Document document = parser.parse(new File("example.xml"));

Deserialize JSON string to c# object

Same problem happened to me. So if the service returns the response as a JSON string you have to deserialize the string first, then you will be able to deserialize the object type from it properly:

string json= string.Empty;
using (var streamReader = new StreamReader(response.GetResponseStream(), true))
            json= new JavaScriptSerializer().Deserialize<string>(streamReader.ReadToEnd());

//To deserialize to your object type...
MyType myType;
using (var memoryStream = new MemoryStream())
            byte[] jsonBytes = Encoding.UTF8.GetBytes(@json);
            memoryStream.Write(jsonBytes, 0, jsonBytes.Length);
            memoryStream.Seek(0, SeekOrigin.Begin);
            using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(memoryStream, Encoding.UTF8,          XmlDictionaryReaderQuotas.Max, null))
                var serializer = new DataContractJsonSerializer(typeof(MyType));
                myType = (MyType)serializer.ReadObject(jsonReader);


4 Sure it will work.... ;)

How to return value from an asynchronous callback function?

This is impossible as you cannot return from an asynchronous call inside a synchronous method.

In this case you need to pass a callback to foo that will receive the return value

function foo(address, fn){
  geocoder.geocode( { 'address': address}, function(results, status) {

foo("address", function(location){
  alert(location); // this is where you get the return value

The thing is, if an inner function call is asynchronous, then all the functions 'wrapping' this call must also be asynchronous in order to 'return' a response.

If you have a lot of callbacks you might consider taking the plunge and use a promise library like Q.

How to make the checkbox unchecked by default always

One quick solution that came to mind :-

<input type="checkbox" id="markitem" name="markitem" value="1" onchange="GetMarkedItems(1)">
<label for="markitem" style="position:absolute; top:1px; left:165px;">&nbsp</label>
<!-- Fire the below javascript everytime the page reloads -->
<script type=text/javascript>
  document.getElementById("markitem").checked = false;
<!-- Tested on Latest FF, Chrome, Opera and IE. -->

JSF(Primefaces) ajax update of several elements by ID's

If the to-be-updated component is not inside the same NamingContainer component (ui:repeat, h:form, h:dataTable, etc), then you need to specify the "absolute" client ID. Prefix with : (the default NamingContainer separator character) to start from root.

<p:ajax process="@this" update="count :subTotal"/>

To be sure, check the client ID of the subTotal component in the generated HTML for the actual value. If it's inside for example a h:form as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.

<p:ajax process="@this" update="count :formId:subTotal"/>

Space separation of IDs is more recommended as <f:ajax> doesn't support comma separation and starters would otherwise get confused.

Stripping everything but alphanumeric chars from a string in Python

If i understood correctly the easiest way is to use regular expression as it provides you lots of flexibility but the other simple method is to use for loop following is the code with example I also counted the occurrence of word and stored in dictionary..

s = """An... essay is, generally, a piece of writing that gives the author's own 
argument — but the definition is vague, 
overlapping with those of a paper, an article, a pamphlet, and a short story. Essays 
have traditionally been 
sub-classified as formal and informal. Formal essays are characterized by "serious 
purpose, dignity, logical 
organization, length," whereas the informal essay is characterized by "the personal 
element (self-revelation, 
individual tastes and experiences, confidential manner), humor, graceful style, 
rambling structure, unconventionality 
or novelty of theme," etc.[1]"""

d = {}      # creating empty dic      
words = s.split() # spliting string and stroing in list
for word in words:
    new_word = ''
    for c in word:
        if c.isalnum(): # checking if indiviual chr is alphanumeric or not
            new_word = new_word + c
    print(new_word, end=' ')
    # if new_word not in d:
    #     d[new_word] = 1
    # else:
    #     d[new_word] = d[new_word] +1

please rate this if this answer is useful!

Hibernate Delete query

To understand this peculiar behavior of hibernate, it is important to understand a few hibernate concepts -

Hibernate Object States

Transient - An object is in transient status if it has been instantiated and is still not associated with a Hibernate session.

Persistent - A persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session.

Detached - A detached instance is an object that has been persistent, but its Session has been closed.

Transaction Write-Behind

The next thing to understand is 'Transaction Write behind'. When objects attached to a hibernate session are modified they are not immediately propagated to the database. Hibernate does this for at least two different reasons.

  • To perform batch inserts and updates.
  • To propagate only the last change. If an object is updated more than once, it still fires only one update statement.

First Level Cache

Hibernate has something called 'First Level Cache'. Whenever you pass an object to save(), update() or saveOrUpdate(), and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session. This is where it tracks changes to various objects.

Hibernate Intercepters and Object Lifecycle Listeners -

The Interceptor interface and listener callbacks from the session to the application, allow the application to inspect and/or manipulate properties of a persistent object before it is saved, updated, deleted or loaded.

This section Updated


Hibernate allows applications to define cascade relationships between associations. For example, 'cascade-delete' from parent to child association will result in deletion of all children when a parent is deleted.

So, why are these important.

To be able to do transaction write-behind, to be able to track multiple changes to objects (object graphs) and to be able to execute lifecycle callbacks hibernate needs to know whether the object is transient/detached and it needs to have the object in it's first level cache before it makes any changes to the underlying object and associated relationships.

That's why hibernate (sometimes) issues a 'SELECT' statement to load the object (if it's not already loaded) in to it's first level cache before it makes changes to it.

Why does hibernate issue the 'SELECT' statement only sometimes?

Hibernate issues a 'SELECT' statement to determine what state the object is in. If the select statement returns an object, the object is in detached state and if it does not return an object, the object is in transient state.

Coming to your scenario -

Delete - The 'Delete' issued a SELECT statement because hibernate needs to know if the object exists in the database or not. If the object exists in the database, hibernate considers it as detached and then re-attches it to the session and processes delete lifecycle.

Update - Since you are explicitly calling 'Update' instead of 'SaveOrUpdate', hibernate blindly assumes that the object is in detached state, re-attaches the given object to the session first level cache and processes the update lifecycle. If it turns out that the object does not exist in the database contrary to hibernate's assumption, an exception is thrown when session flushes.

SaveOrUpdate - If you call 'SaveOrUpdate', hibernate has to determine the state of the object, so it uses a SELECT statement to determine if the object is in Transient/Detached state. If the object is in transient state, it processes the 'insert' lifecycle and if the object is in detached state, it processes the 'Update' lifecycle.

Best way to store time (hh:mm) in a database

Just store a regular datetime and ignore everything else. Why spend extra time writing code that loads an int, manipulates it, and converts it into a datetime, when you could just load a datetime?

the best way to make codeigniter website multi-language. calling from lang arrays depends on lang session?

Also to add the language to the session, I would define some constants for each language, then make sure you have the session library autoloaded in config/autoload.php, or you load it whenever you need it. Add the users desired language to the session:

$this->session->set_userdata('language', ENGLISH);

Then you can grab it anytime like this:

$language = $this->session->userdata('language');

How to detect when an Android app goes to the background and come back to the foreground

i know its a little late but i think all these answers do have some problems while i did it like below and that works perfect.

create a activity life cycle callback like this:

 class ActivityLifeCycle implements ActivityLifecycleCallbacks{

    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {


    public void onActivityStarted(Activity activity) {


    Activity lastActivity;
    public void onActivityResumed(Activity activity) {
        //if (null == lastActivity || (activity != null && activity == lastActivity)) //use this condition instead if you want to be informed also when  app has been killed or started for the first time
        if (activity != null && activity == lastActivity) 
            Toast.makeText(MyApp.this, "NOW!", Toast.LENGTH_LONG).show();

        lastActivity = activity;

    public void onActivityPaused(Activity activity) {


    public void onActivityStopped(Activity activity) {


    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {


    public void onActivityDestroyed(Activity activity) {


and just register it on your application class like below:

public class MyApp extends Application {

public void onCreate() {
    registerActivityLifecycleCallbacks(new ActivityLifeCycle());

How to convert Base64 String to javascript file object like as from file input form?

Heads up,


   function readMtlAtClient(){

       mtlFileContent = '';

       var mtlFile = document.getElementById('mtlFileInput').files[0];
       var readerMTL = new FileReader();

       // Closure to capture the file information.
       readerMTL.onload = (function(reader) {
           return function() {
               mtlFileContent = reader.result;
               mtlFileContent = mtlFileContent.replace('data:;base64,', '');
               mtlFileContent = window.atob(mtlFileContent);




    <input class="FullWidth" type="file" name="mtlFileInput" value="" id="mtlFileInput" 
onchange="readMtlAtClient()" accept=".mtl"/>

Then mtlFileContent has your text as a decoded string !

How to calculate the number of occurrence of a given character in each row of a column of strings?

s <- "aababacababaaathhhhhslsls jsjsjjsaa ghhaalll"
p <- "a"
s2 <- gsub(p,"",s)
numOcc <- nchar(s) - nchar(s2)

May not be the efficient one but solve my purpose.

CSS customized scroll bar in div

Webkit browsers (such as Chrome, Safari and Opera) supports the non-standard ::-webkit-scrollbar pseudo element, which allows us to modify the look of the browser's scrollbar.

Note: The ::-webkit-scrollbar is not supported by Firefox or IE and Edge.

* {_x000D_
  box-sizing: border-box;_x000D_
  font-family: sans-serif;_x000D_
div {_x000D_
  width: 15rem;_x000D_
  height: 8rem;_x000D_
  padding: .5rem;_x000D_
  border: 1px solid #aaa;_x000D_
  margin-bottom: 1rem;_x000D_
  overflow: auto;_x000D_
.box::-webkit-scrollbar {_x000D_
  width: .8em;_x000D_
.box::-webkit-scrollbar-track {_x000D_
  box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);_x000D_
.box::-webkit-scrollbar-thumb {_x000D_
  background-color: dodgerblue;_x000D_
<div class="box">_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate</p>_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate</p>_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate</p>_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate</p>_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate</p>_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate</p>_x000D_

Reference: How To Create a Custom Scrollbar

Change fill color on vector asset in Android Studio

Update: AppCompat support

Other answers suspecting if android:tint will work on only 21+ devices only, AppCompat(v23.2.0 and above) now provides a backward compatible handling of tint attribute.

So, the course of action would be to use AppCompatImageView and app:srcCompat(in AppCompat namespace) instead of android:src(Android namespace).

Here is an example(AndroidX: This is androidx.appcompat.widget.AppCompatImageView ;)):

        app:srcCompat="@drawable/ic_dollar_coin_stack" />

And don't forget to enable vector drawable support in gradle:

vectorDrawables.useSupportLibrary = true 

Grant all on a specific schema in the db to a group role in PostgreSQL

My answer is similar to this one on

To Be Conservative

If you want to be more conservative than granting "all privileges", you might want to try something more like these.


The use of public there refers to the name of the default schema created for every new database/catalog. Replace with your own name if you created a schema.

Access to the Schema

To access a schema at all, for any action, the user must be granted "usage" rights. Before a user can select, insert, update, or delete, a user must first be granted "usage" to a schema.

You will not notice this requirement when first using Postgres. By default every database has a first schema named public. And every user by default has been automatically been granted "usage" rights to that particular schema. When adding additional schema, then you must explicitly grant usage rights.

GRANT USAGE ON SCHEMA some_schema_ TO some_user_ ;

Excerpt from the Postgres doc:

For schemas, allows access to objects contained in the specified schema (assuming that the objects' own privilege requirements are also met). Essentially this allows the grantee to "look up" objects within the schema. Without this permission, it is still possible to see the object names, e.g. by querying the system tables. Also, after revoking this permission, existing backends might have statements that have previously performed this lookup, so this is not a completely secure way to prevent object access.

For more discussion see the Question, What GRANT USAGE ON SCHEMA exactly do?. Pay special attention to the Answer by Postgres expert Craig Ringer.

Existing Objects Versus Future

These commands only affect existing objects. Tables and such you create in the future get default privileges until you re-execute those lines above. See the other answer by Erwin Brandstetter to change the defaults thereby affecting future objects.

Most efficient way to create a zero filled JavaScript array?

The fastest here is

(arr = []).length = len; arr.fill(0);

Checking out Git tag leads to "detached HEAD state"

Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.

But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)

How to convert array to a string using methods other than JSON?

Use the implode() function:

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone

Does Python have “private” variables in classes?

About sources (to change the access rights and thus bypass language encapsulation like java or C ++): You don't always have the sources and EVEN if you do, the sources are managed by a system that only allows certain programmers to access a source (in a professional context). Often, every programmer is responsible for certain classes and therefore knows what he can and cannot do. The source manager also locks the sources being modified and of course, manages the access rights of programmers.

So i trust more in software than in human, by experience. So convention is good but MULTIPLE protections are better, like access management (real private variable) + sources management.

How to set the font style to bold, italic and underlined in an Android TextView?

This is an easy way to add an underline, while maintaining other settings:

textView.setPaintFlags(textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

This is a briefer variation of the accepted answer: the function below extracts the bits from-to inclusive by creating a bitmask. After applying an AND logic over the original number the result is shifted so the function returns just the extracted bits. Skipped index/integrity checks for clarity.

uint16_t extractInt(uint16_t orig16BitWord, unsigned from, unsigned to) 
  unsigned mask = ( (1<<(to-from+1))-1) << from;
  return (orig16BitWord & mask) >> from;

ESLint - "window" is not defined. How to allow global variables in package.json

Your .eslintrc.json should contain the text below.
This way ESLint knows about your global variables.

  "env": {
    "browser": true,
    "node": true

IIS7 deployment - duplicate 'system.web.extensions/scripting/scriptResourceHandler' section

My resolution was kind of stupid.

  • I installed a copy of .net 3.5

  • Created another app pool and selected .net 3.5 (it says 2.0.5077 in the drop down)

  • Added my website to that app pool

  • Recycled the old and new pools and the site started working.

It came down to me not having 3.5 installed even though the turn on windows features said I did and creating another app pool to use. I hope this helps others.

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:


    echo "<p>Logged in as ".$user."</p>";
    echo "Please log in.";

How the same problem can be solved with an API centric approach by outputting JSON like this:


  user: {
      username: 'Joe', 
      securityToken: 'secret'

and in Angular you could do a get, and handle the response client side.

$"", {})
.success(function(data) {
    $scope.isLoggedIn = data.authorized;

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

Using braces with dynamic variable names in PHP

Wrap them in {}:

${"file" . $i} = file($filelist[$i]);

Working Example

Using ${} is a way to create dynamic variables, simple example:

${'a' . 'b'} = 'hello there';
echo $ab; // hello there

How to select rows with NaN in particular column?

@qbzenker provided the most idiomatic method IMO

Here are a few alternatives:

In [28]: df.query('Col2 != Col2') # Using the fact that: np.nan != np.nan
   Col1  Col2  Col3
1     0   NaN   0.0

In [29]: df[np.isnan(df.Col2)]
   Col1  Col2  Col3
1     0   NaN   0.0

How to open a page in a new window or tab from code-behind

You can use scriptmanager.registerstartupscript to call a JavaScript function.

Inside that function, you can open a new window.

SQL WITH clause example

This has been fully answered here.

See Oracle's docs on SELECT to see how subquery factoring works, and Mark's example:

WITH employee AS (SELECT * FROM Employees)
SELECT * FROM employee WHERE ID < 20
SELECT * FROM employee WHERE Sex = 'M'

Override hosts variable of Ansible playbook from the command line

I'm using another approach that doesn't need any inventory and works with this simple command:

ansible-playbook site.yml -e working_host=myhost

To perform that, you need a playbook with two plays:

  • first play runs on localhost and add a host (from given variable) in a known group in inmemory inventory
  • second play runs on this known group

A working example (copy it and runs it with previous command):

- hosts: localhost
  connection: local
  - add_host:
      name: "{{ working_host }}"
      groups: working_group
    changed_when: false

- hosts: working_group
  gather_facts: false
  - debug:
      msg: "I'm on {{ ansible_host }}"

I'm using ansible 2.4.3 and 2.3.3

What does "to stub" mean in programming?

In this context, the word "stub" is used in place of "mock", but for the sake of clarity and precision, the author should have used "mock", because "mock" is a sort of stub, but for testing. To avoid further confusion, we need to define what a stub is.

In the general context, a stub is a piece of program (typically a function or an object) that encapsulates the complexity of invoking another program (usually located on another machine, VM, or process - but not always, it can also be a local object). Because the actual program to invoke is usually not located on the same memory space, invoking it requires many operations such as addressing, performing the actual remote invocation, marshalling/serializing the data/arguments to be passed (and same with the potential result), maybe even dealing with authentication/security, and so on. Note that in some contexts, stubs are also called proxies (such as dynamic proxies in Java).

A mock is a very specific and restrictive kind of stub, because a mock is a replacement of another function or object for testing. In practice we often use mocks as local programs (functions or objects) to replace a remote program in the test environment. In any case, the mock may simulate the actual behaviour of the replaced program in a restricted context.

Most famous kinds of stubs are obviously for distributed programming, when needing to invoke remote procedures (RPC) or remote objects (RMI, CORBA). Most distributed programming frameworks/libraries automate the generation of stubs so that you don't have to write them manually. Stubs can be generated from an interface definition, written with IDL for instance (but you can also use any language to define interfaces).

Typically, in RPC, RMI, CORBA, and so on, one distinguishes client-side stubs, which mostly take care of marshaling/serializing the arguments and performing the remote invocation, and server-side stubs, which mostly take care of unmarshaling/deserializing the arguments and actually execute the remote function/method. Obviously, client stubs are located on the client side, while sever stubs (often called skeletons) are located on the server side.

Writing good efficient and generic stubs becomes quite challenging when dealing with object references. Most distributed object frameworks such as RMI and CORBA deal with distributed objects references, but that's something most programmers avoid in REST environments for instance. Typically, in REST environments, JavaScript programmers make simple stub functions to encapsulate the AJAX invocations (object serialization being supported by JSON.parse and JSON.stringify). The Swagger Codegen project provides an extensive support for automatically generating REST stubs in various languages.

Windows service with timer

Here's a working example in which the execution of the service is started in the OnTimedEvent of the Timer which is implemented as delegate in the ServiceBase class and the Timer logic is encapsulated in a method called SetupProcessingTimer():

public partial class MyServiceProject: ServiceBase

private Timer _timer;

public MyServiceProject()

private void SetupProcessingTimer()
    _timer = new Timer();
    _timer.AutoReset = true;
    double interval = Settings.Default.Interval;
    _timer.Interval = interval * 60000;
    _timer.Enabled = true;
    _timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

private void OnTimedEvent(object source, ElapsedEventArgs e)
    // begin your service work

protected override void OnStart(string[] args)


The Interval is defined in app.config in minutes:

        <setting name="Interval" serializeAs="String">

How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?

Unfortunately there is currently no designer support (unlike for SQL Server 2005) for building relationships between tables in SQL Server CE. To build relationships you need to use SQL commands such as:

FOREIGN KEY (CustomerId) REFERENCES Customers(CustomerId)

If you are doing CE development, i would recomend this FAQ:

EDIT: In Visual Studio 2008 this is now possible to do in the GUI by right-clicking on your table.

How to read xml file contents in jQuery and display in html elements?

First of all create on file and then convert your xml data in array and retrieve that data in json format for ajax success response.

Try as below:

$(document).ready(function () {
        type: "POST",
        url: "sample.php",            
        success: function (response) {
            var obj = $.parseJSON(response);
            for(var i=0;i<obj.length;i++){
                // here you can add html through loop


$json = json_encode((array)simplexml_load_string($xml)),1);
echo $json;

How can I open a link in a new window?

You can like:'url', 'window name', 'window settings')


$('a#link_id').click(function(){'url', 'window name', 'window settings');
  return false;

You could also set the target to _blank actually.

docker error: /var/run/docker.sock: no such file or directory

In Linux, first of all execute sudo service docker start in terminal.

Explaining Python's '__enter__' and '__exit__'

This is called context manager and I just want to add that similar approaches exist for other programming languages. Comparing them could be helpful in understanding the context manager in python. Basically, a context manager is used when we are dealing with some resources (file, network, database) that need to be initialized and at some point, tear downed (disposed). In Java 7 and above we have automatic resource management that takes the form of:

//Java code
try (Session session = new Session())
  // do stuff

Note that Session needs to implement AutoClosable or one of its (many) sub-interfaces.

In C#, we have using statements for managing resources that takes the form of:

//C# code
using(Session session = new Session())
  ... do stuff.

In which Session should implement IDisposable.

In python, the class that we use should implement __enter__ and __exit__. So it takes the form of:

#Python code
with Session() as session:
    #do stuff

And as others pointed out, you can always use try/finally statement in all the languages to implement the same mechanism. This is just syntactic sugar.

Convert javascript object or array to json for ajax data

I'm not entirely sure but I think you are probably surprised at how arrays are serialized in JSON. Let's isolate the problem. Consider following code:

var display = Array();
display[0] = "none";
display[1] = "block";
display[2] = "none";

console.log( JSON.stringify(display) );

This will print:


This is how JSON actually serializes array. However what you want to see is something like:


To get this format you want to serialize object, not array. So let's rewrite above code like this:

var display2 = {};
display2["0"] = "none";
display2["1"] = "block";
display2["2"] = "none";

console.log( JSON.stringify(display2) );

This will print in the format you want.

You can play around with this here:,console

sh: 0: getcwd() failed: No such file or directory on cited drive

In Ubuntu 16.04.3 LTS, the next command works for me:


Then I've login again.

How do you perform a left outer join using linq extension methods

Since this seems to be the de facto SO question for left outer joins using the method (extension) syntax, I thought I would add an alternative to the currently selected answer that (in my experience at least) has been more commonly what I'm after

// Option 1: Expecting either 0 or 1 matches from the "Right"
// table (Bars in this case):
var qry = Foos.GroupJoin(
          foo => foo.Foo_Id,
          bar => bar.Foo_Id,
          (f,bs) => new { Foo = f, Bar = bs.SingleOrDefault() });

// Option 2: Expecting either 0 or more matches from the "Right" table
// (courtesy of currently selected answer):
var qry = Foos.GroupJoin(
                  foo => foo.Foo_Id,
                  bar => bar.Foo_Id,
                  (f,bs) => new { Foo = f, Bars = bs })
                  fooBars => fooBars.Bars.DefaultIfEmpty(),
                  (x,y) => new { Foo = x.Foo, Bar = y });

To display the difference using a simple data set (assuming we're joining on the values themselves):

List<int> tableA = new List<int> { 1, 2, 3 };
List<int?> tableB = new List<int?> { 3, 4, 5 };

// Result using both Option 1 and 2. Option 1 would be a better choice
// if we didn't expect multiple matches in tableB.
{ A = 1, B = null }
{ A = 2, B = null }
{ A = 3, B = 3    }

List<int> tableA = new List<int> { 1, 2, 3 };
List<int?> tableB = new List<int?> { 3, 3, 4 };

// Result using Option 1 would be that an exception gets thrown on
// SingleOrDefault(), but if we use FirstOrDefault() instead to illustrate:
{ A = 1, B = null }
{ A = 2, B = null }
{ A = 3, B = 3    } // Misleading, we had multiple matches.
                    // Which 3 should get selected (not arbitrarily the first)?.

// Result using Option 2:
{ A = 1, B = null }
{ A = 2, B = null }
{ A = 3, B = 3    }
{ A = 3, B = 3    }    

Option 2 is true to the typical left outer join definition, but as I mentioned earlier is often unnecessarily complex depending on the data set.

How to horizontally align ul to center of div?

You can check this solved your problem...

    #headermenu ul{ 
        text-align: center;
    #headermenu li { 
list-style-type: none;
        display: inline-block;
    #headermenu ul li a{
        float: left;

How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest

Define width of .absorbing-column

Set table-layout to auto and define an extreme width on .absorbing-column.

Here I have set the width to 100% because it ensures that this column will take the maximum amount of space allowed, while the columns with no defined width will reduce to fit their content and no further.

This is one of the quirky benefits of how tables behave. The table-layout: auto algorithm is mathematically forgiving.

You may even choose to define a min-width on all td elements to prevent them from becoming too narrow and the table will behave nicely.

table {_x000D_
    table-layout: auto;_x000D_
    border-collapse: collapse;_x000D_
    width: 100%;_x000D_
table td {_x000D_
    border: 1px solid #ccc;_x000D_
table .absorbing-column {_x000D_
    width: 100%;_x000D_
      <th>Column A</th>_x000D_
      <th>Column B</th>_x000D_
      <th>Column C</th>_x000D_
      <th class="absorbing-column">Column D</th>_x000D_
      <td>Data A.1 lorem</td>_x000D_
      <td>Data B.1 ip</td>_x000D_
      <td>Data C.1 sum l</td>_x000D_
      <td>Data D.1</td>_x000D_
      <td>Data A.2 ipsum</td>_x000D_
      <td>Data B.2 lorem</td>_x000D_
      <td>Data C.2 some data</td>_x000D_
      <td>Data D.2 a long line of text that is long</td>_x000D_
      <td>Data A.3</td>_x000D_
      <td>Data B.3</td>_x000D_
      <td>Data C.3</td>_x000D_
      <td>Data D.3</td>_x000D_

How can I mark a foreign key constraint using Hibernate annotations?

@Column is not the appropriate annotation. You don't want to store a whole User or Question in a column. You want to create an association between the entities. Start by renaming Questions to Question, since an instance represents a single question, and not several ones. Then create the association:

@Table(name = "UserAnswer")
public class UserAnswer {

    // this entity needs an ID:
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @JoinColumn(name = "user_id")
    private User user;

    @JoinColumn(name = "question_id")
    private Question question;

    @Column(name = "response")
    private String response;

    //getter and setter 

The Hibernate documentation explains that. Read it. And also read the javadoc of the annotations.

Redirect echo output in shell script to logfile

exec >> $LOG_LOCATION/mylogfile.log 2>&1

In PHP, what is a closure and why does it use the "use" identifier?

closures are beautiful! they solve a lot of problems that come with anonymous functions, and make really elegant code possible (at least as long as we talk about php).

javascript programmers use closures all the time, sometimes even without knowing it, because bound variables aren't explicitly defined - that's what "use" is for in php.

there are better real-world examples than the above one. lets say you have to sort an multidimensional array by a sub-value, but the key changes.

    function generateComparisonFunctionForKey($key) {
        return function ($left, $right) use ($key) {
            if ($left[$key] == $right[$key])
                return 0;
                return ($left[$key] < $right[$key]) ? -1 : 1;

    $myArray = array(
        array('name' => 'Alex', 'age' => 70),
        array('name' => 'Enrico', 'age' => 25)

    $sortByName = generateComparisonFunctionForKey('name');
    $sortByAge  = generateComparisonFunctionForKey('age');

    usort($myArray, $sortByName);

    usort($myArray, $sortByAge);

warning: untested code (i don't have php5.3 installed atm), but it should look like something like that.

there's one downside: a lot of php developers may be a bit helpless if you confront them with closures.

to understand the nice-ty of closures more, i'll give you another example - this time in javascript. one of the problems is the scoping and the browser inherent asynchronity. especially, if it comes to window.setTimeout(); (or -interval). so, you pass a function to setTimeout, but you can't really give any parameters, because providing parameters executes the code!

function getFunctionTextInASecond(value) {
    return function () {
        document.getElementsByName('body')[0].innerHTML = value; // "value" is the bound variable!

var textToDisplay = prompt('text to show in a second', 'foo bar');

// this returns a function that sets the bodys innerHTML to the prompted value
var myFunction = getFunctionTextInASecond(textToDisplay);

window.setTimeout(myFunction, 1000);

myFunction returns a function with a kind-of predefined parameter!

to be honest, i like php a lot more since 5.3 and anonymous functions/closures. namespaces may be more important, but they're a lot less sexy.

How can I update a row in a DataTable in VB.NET?

Dim myRow() As Data.DataRow
myRow = dt.Select("MyColumnName = 'SomeColumnTitle'")
myRow(0)("SomeOtherColumnTitle") = strValue

Code above instantiates a DataRow. Where "dt" is a DataTable, you get a row by selecting any column (I know, sounds backwards). Then you can then set the value of whatever row you want (I chose the first row, or "myRow(0)"), for whatever column you want.

java.lang.IllegalArgumentException: No converter found for return value of type

In my case, I was returning Boolean in Response Entity and had :

produces = MediaType.TEXT_PLAIN_VALUE,

When i changed it to below


It worked!

Example of what i had.

@PostMapping(value = "/xxx-xxxx",
            produces = MediaType.APPLICATION_JSON_VALUE,
            consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Boolean> yyyy(

SQL Server tables: what is the difference between @, # and ##?

if you need a unique global temp table, create your own with a Uniqueidentifier Prefix/Suffix and drop post execution if an if object_id(.... The only drawback is using Dynamic sql and need to drop explicitly.

GDB: break if variable equal value

There are hardware and software watchpoints. They are for reading and for writing a variable. You need to consult a tutorial:

To set a watchpoint, first you need to break the code into a place where the varianle i is present in the environment, and set the watchpoint.

watch command is used to set a watchpoit for writing, while rwatch for reading, and awatch for reading/writing.

error code 1292 incorrect date value mysql

I happened to be working in localhost , in windows 10, using WAMP, as it turns out, Wamp has a really accessible configuration interface to change the MySQL configuration. You just need to go to the Wamp panel, then to MySQL, then to settings and change the mode to sql-mode: none.(essentially disabling the strict mode) The following picture illustrates this.

enter image description here

LINQ orderby on date field in descending order

env.OrderByDescending(x => x.ReportDate)

A transport-level error has occurred when receiving results from the server

For those not using IIS, I had this issue when debugging with Visual Studio 2010. I ended all of the debugger processes: WebDev.WebServer40.EXE which solved the issue.

Resync git repo with new .gitignore file

I might misunderstand, but are you trying to delete files newly ignored or do you want to ignore new modifications to these files ? In this case, the thing is working.

If you want to delete ignored files previously commited, then use

git rm –cached `git ls-files -i –exclude-standard`
git commit -m 'clean up'

How to pass variable number of arguments to printf/sprintf

void Error(const char* format, ...)
    va_list argptr;
    va_start(argptr, format);
    vfprintf(stderr, format, argptr);

If you want to manipulate the string before you display it and really do need it stored in a buffer first, use vsnprintf instead of vsprintf. vsnprintf will prevent an accidental buffer overflow error.

python ignore certificate validation urllib2

According to @Enno Gröper 's post, I've tried the SSLContext constructor and it works well on my machine. code as below:

import ssl
ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
urllib2.urlopen("https://your-test-server.local", context=ctx)

if you need opener, just added this context like:

opener = urllib2.build_opener(urllib2.HTTPSHandler(context=ctx))

NOTE: all above test environment is python 2.7.12. I use PROTOCOL_SSLv23 here since the doc says so, other protocol might also works but depends on your machine and remote server, please check the doc for detail.

Create SQLite database in android

Why not refer to the documentation or the sample code shipping with the SDK? There's code in the samples on how to create/update/fill/read databases using the helper class described in the document I linked.

What exactly does big ? notation represent?

It means that the algorithm is both big-O and big-Omega in the given function.

For example, if it is ?(n), then there is some constant k, such that your function (run-time, whatever), is larger than n*k for sufficiently large n, and some other constant K such that your function is smaller than n*K for sufficiently large n.

In other words, for sufficiently large n, it is sandwiched between two linear functions :

For k < K and n sufficiently large, n*k < f(n) < n*K

How do I clear the previous text field value after submitting the form with out refreshing the entire page?

I had that issue and I solved by doing this:

.done(function() {

I added this code after my script as I used jQuery. Try same)

<script type="text/JavaScript">

        $(document).ready(function() {
            $("#feedback").submit(function(event) {
                    url: "feedback_lib.php",
                    type: "post",
                    data: $("#feedback").serialize()
                }).done(function() {
    <form id="feedback" action="" name="feedback" method="post">
        <input id="name" name="name" placeholder="name" />
        <br />
        <input id="surname" name="surname" placeholder="surname" />
        <br />
        <input id="enquiry" name="enquiry" placeholder="enquiry" />
        <br />
        <input id="organisation" name="organisation" placeholder="organisation" />
        <br />
        <input id="email" name="email" placeholder="email" />
        <br />
        <textarea id="message" name="message" rows="7" cols="40" placeholder="?????????"></textarea>
        <br />
        <button id="send" name="send">send</button>

Convert YYYYMMDD string date to a datetime value

You should have to use DateTime.TryParseExact.

var newDate = DateTime.ParseExact("20111120", 


string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;

if (DateTime.TryParseExact(str, 
                           out date))

Calculate cosine similarity given 2 sentence strings

The short answer is "no, it is not possible to do that in a principled way that works even remotely well". It is an unsolved problem in natural language processing research and also happens to be the subject of my doctoral work. I'll very briefly summarize where we are and point you to a few publications:

Meaning of words

The most important assumption here is that it is possible to obtain a vector that represents each word in the sentence in quesion. This vector is usually chosen to capture the contexts the word can appear in. For example, if we only consider the three contexts "eat", "red" and "fluffy", the word "cat" might be represented as [98, 1, 87], because if you were to read a very very long piece of text (a few billion words is not uncommon by today's standard), the word "cat" would appear very often in the context of "fluffy" and "eat", but not that often in the context of "red". In the same way, "dog" might be represented as [87,2,34] and "umbrella" might be [1,13,0]. Imagening these vectors as points in 3D space, "cat" is clearly closer to "dog" than it is to "umbrella", therefore "cat" also means something more similar to "dog" than to an "umbrella".

This line of work has been investigated since the early 90s (e.g. this work by Greffenstette) and has yielded some surprisingly good results. For example, here is a few random entries in a thesaurus I built recently by having my computer read wikipedia:

theory -> analysis, concept, approach, idea, method
voice -> vocal, tone, sound, melody, singing
james -> william, john, thomas, robert, george, charles

These lists of similar words were obtained entirely without human intervention- you feed text in and come back a few hours later.

The problem with phrases

You might ask why we are not doing the same thing for longer phrases, such as "ginger foxes love fruit". It's because we do not have enough text. In order for us to reliably establish what X is similar to, we need to see many examples of X being used in context. When X is a single word like "voice", this is not too hard. However, as X gets longer, the chances of finding natural occurrences of X get exponentially slower. For comparison, Google has about 1B pages containing the word "fox" and not a single page containing "ginger foxes love fruit", despite the fact that it is a perfectly valid English sentence and we all understand what it means.


To tackle the problem of data sparsity, we want to perform composition, i.e. to take vectors for words, which are easy to obtain from real text, and to put the together in a way that captures their meaning. The bad news is nobody has been able to do that well so far.

The simplest and most obvious way is to add or multiply the individual word vectors together. This leads to undesirable side effect that "cats chase dogs" and "dogs chase cats" would mean the same to your system. Also, if you are multiplying, you have to be extra careful or every sentences will end up represented by [0,0,0,...,0], which defeats the point.

Further reading

I will not discuss the more sophisticated methods for composition that have been proposed so far. I suggest you read Katrin Erk's "Vector space models of word meaning and phrase meaning: a survey". This is a very good high-level survey to get you started. Unfortunately, is not freely available on the publisher's website, email the author directly to get a copy. In that paper you will find references to many more concrete methods. The more comprehensible ones are by Mitchel and Lapata (2008) and Baroni and Zamparelli (2010).

Edit after comment by @vpekar: The bottom line of this answer is to stress the fact that while naive methods do exist (e.g. addition, multiplication, surface similarity, etc), these are fundamentally flawed and in general one should not expect great performance from them.

Why can't Python parse this JSON data?

As a python3 user,

The difference between load and loads methods is important especially when you read json data from file.

As stated in the docs:


Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to a Python object using this conversion table.


json.loads: Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table.

json.load method can directly read opened json document since it is able to read binary file.

with open('./recipes.json') as data:
  all_recipes = json.load(data)

As a result, your json data available as in a format specified according to this conversion table:

Launching an application (.EXE) from C#?

Additionally you will want to use the Environment Variables for your paths if at all possible:


  • %WINDIR% = Windows Directory
  • %APPDATA% = Application Data - Varies alot between Vista and XP.

There are many more check out the link for a longer list.

How to prevent form from submitting multiple times from client side?

Use this code in your will handle multiple clicks.

<script type="text/javascript">
    $(document).ready(function() {
        $("form").submit(function() {
            $(this).submit(function() {
                return false;
            return true;

it will work for sure.

How to get Latitude and Longitude of the mobile device in android?

Above solutions is also correct, but some time if location is null then it crash the app or not working properly. The best way to get Latitude and Longitude of android is:

 Geocoder geocoder;
     String bestProvider;
     List<Address> user = null;
     double lat;
     double lng;

    LocationManager lm = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);

     Criteria criteria = new Criteria();
     bestProvider = lm.getBestProvider(criteria, false);
     Location location = lm.getLastKnownLocation(bestProvider);

     if (location == null){
         Toast.makeText(activity,"Location Not found",Toast.LENGTH_LONG).show();
        geocoder = new Geocoder(activity);
        try {
            user = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
        System.out.println(" DDD lat: " +lat+",  longitude: "+lng);

        }catch (Exception e) {

Change auto increment starting number?

just export the table with data .. then copy its sql like

  `emp_badgenumber` int(20) NOT NULL AUTO_INCREMENT,
  `emp_fullname` varchar(100) NOT NULL,
  `emp_father_name` varchar(30) NOT NULL,
  `emp_mobile` varchar(20) DEFAULT NULL,
  `emp_cnic` varchar(20) DEFAULT NULL,
  `emp_gender` varchar(10) NOT NULL,
  `emp_is_deleted` tinyint(4) DEFAULT '0',
  `emp_registration_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `emp_overtime_allowed` tinyint(4) DEFAULT '1',
  PRIMARY KEY (`emp_badgenumber`),
  UNIQUE KEY `bagdenumber` (`emp_badgenumber`),
  KEY `emp_badgenumber` (`emp_badgenumber`),
  KEY `emp_badgenumber_2` (`emp_badgenumber`)

now change auto increment value and execute sql.

Auto-increment primary key in SQL tables

I think there is a way to do it at definition stage like this

create table employee( id int identity, name varchar(50), primary key(id) ).. I am trying to see if there is a way to alter an existing table and make the column as Identity which does not look possible theoretically (as the existing values might need modification)

Sorting a list with stream.sorted() in Java

Collection<Map<Item, Integer>> itemCollection = basket.values();
Iterator<Map<Item, Integer>> itemIterator = TestComparator()).collect(Collectors.toList()).iterator();



import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class TestComparator implements Comparator<Map<Item, Integer>> {

// comparator is used to sort the Items based on the price

    public int compare(Map<Item, Integer> o1, Map<Item, Integer> o2) {

      //  System.out.println("*** compare method will be called *****");

        Item item1 = null;
        Item item2 = null;

        Set<Item> itemSet1 = o1.keySet();
        Iterator<Item> itemIterator1 = itemSet1.iterator();
           item1 =;

        Set<Item> itemSet2 = o2.keySet();
        Iterator<Item> itemIterator2 = itemSet2.iterator();
            item2 =;

        return -item1.getPrice().compareTo(item2.getPrice());


**** this is helpful to sort the nested map objects like Map> here i sorted based on the Item object price .