Programs & Examples On #Nhibernate validator

NHibernate Validator is a powerful and extensible framework to validate objects using the .Net Platform. It is intended to be used to implement multi-layered data validation, where constraints are expressed in a single place and checked in various different layers of the application.

How to get a value from a cell of a dataframe?

Converting it to integer worked for me:


Internal vs. Private Access Modifiers

Find an explanation below. You can check this link for more details -

Private: - Private members are only accessible within the own type (Own class).

Internal: - Internal member are accessible only within the assembly by inheritance (its derived type) or by instance of class.

enter image description here

Reference :

dotnetbull - what is access modifier in c#

How to hide reference counts in VS2013?

In VSCode for Mac (0.10.6) I opened "Preferences -> User Settings" and placed the following code in the settings.json file

enter image description here

"editor.referenceInfos": false

enter image description here

User and Workspace Settings

Display a message in Visual Studio's output window when not debug mode?

For me this was the fact that debug.writeline shows in the Immediate window, not the Output. My installation of VS2013 by default doesn't even show an option to open the Immediate window, so you have to do the following:

Select Tools -> Customize 
Commands Tab
View | Other Windows menu bar dropdown
Add Command...
The Immediate option is in the Debug section.

Once you have Ok'd that, you can go to View -> Other Windows and select the Immediate Window and hey presto all of the debug output can be seen.

Unfortunately for me it also showed about 50 errors that I wasn't aware of in my project... maybe I'll just turn it off again :-)

Passing HTML to template using Flask/Jinja2

the ideal way is to

{{ something|safe }}

than completely turning off auto escaping.

Getting list of items inside div using Selenium Webdriver

Follow the code below exactly matched with your case.

  1. Create an interface of the web element for the div under div with class as facetContainerDiv

ie for

<div class="facetContainerDiv">


2. Create an IList with all the elements inside the second div i.e for,

<label class="facetLabel">
   <input class="facetCheck" type="checkbox" />
<label class="facetLabel">
   <input class="facetCheck" type="checkbox" />
<label class="facetLabel">
   <input class="facetCheck" type="checkbox" />
<label class="facetLabel">
   <input class="facetCheck" type="checkbox" />
<label class="facetLabel">
   <input class="facetCheck" type="checkbox" />

3. Access each check boxes using the index

Please find the code below

using System;
using System.Collections.Generic;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;

namespace SeleniumTests
  class ChechBoxClickWthIndex
        static void Main(string[] args)

            IWebDriver driver = new FirefoxDriver();


            // Create an interface WebElement of the div under div with **class as facetContainerDiv**
            IWebElement WebElement =    driver.FindElement(By.XPath("//div[@class='facetContainerDiv']/div"));
            // Create an IList and intialize it with all the elements of div under div with **class as facetContainerDiv**
            IList<IWebElement> AllCheckBoxes = WebElement.FindElements(By.XPath("//label/input"));
            int RowCount = AllCheckBoxes.Count;
            for (int i = 0; i < RowCount; i++)
            // Check the check boxes based on index



React: trigger onChange if input value is changing by state?

Solution Working in the Year 2020 and 2021:

I tried the other solutions and nothing worked. This is because of input logic in React.js has been changed. For detail, you can see this link:

In short, when we change the value of input by changing state and then dispatch a change event then React will register both the setState and the event and consider it a duplicate event and swallow it.

The solution is to call native value setter on input (See setNativeValue function in following code)

Example Code

import React, { Component } from 'react'
export class CustomInput extends Component {

    inputElement = null;
    setNativeValue(element, value) {
        const valueSetter = Object.getOwnPropertyDescriptor(element, 'value').set;
        const prototype = Object.getPrototypeOf(element);
        const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;

        if (valueSetter && valueSetter !== prototypeValueSetter) {
  , value);
        } else {
  , value);

    constructor(props) {

        this.state = {
            inputValue: this.props.value,

    addToInput = (valueToAdd) => {
        this.setNativeValue(this.inputElement, +this.state.inputValue + +valueToAdd);
        this.inputElement.dispatchEvent(new Event('input', { bubbles: true }));

    handleChange = e => {
        this.setState({ inputValue: });

    render() {
        return (
                <button type="button" onClick={() => this.addToInput(-1)}>-</button>
                    ref={input => { this.inputElement = input }}
                <button type="button" onClick={() => this.addToInput(+1)}>+</button>

export default CustomInput


enter image description here

How to check if IEnumerable is null or empty?

I used simple if to check for it

check out my solution

foreach (Pet pet in v.Pets)
    if (pet == null)
        Console.WriteLine(" No pet");// enumerator is empty
    Console.WriteLine("  {0}", pet.Name);

What is "stdafx.h" used for in Visual Studio?

"Stdafx.h" is a precompiled header.It include file for standard system include files and for project-specific include files that are used frequently but are changed infrequently.which reduces compile time and Unnecessary Processing.

Precompiled Header stdafx.h is basically used in Microsoft Visual Studio to let the compiler know the files that are once compiled and no need to compile it from scratch. You can read more about it

android button selector

You can use this code:

android:visibility="visible" />

(Selector File) img_sublist_carat_selector.xml:

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="">
 <item android:state_focused="true" 
       android:drawable="@drawable/img_sublist_carat_highlight" />
 <item android:state_pressed="true" 
       android:drawable="@drawable/img_sublist_carat_highlight" />
 <item android:drawable="@drawable/img_sublist_carat_normal" />

How do I get the SelectedItem or SelectedIndex of ListView in

If you want to select the same item in a listbox using a listview, you can use:

Private Sub ListView1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListView1.SelectedIndexChanged
    For aa As Integer = 0 To ListView1.SelectedItems.Count - 1
        ListBox1.SelectedIndex = ListView1.SelectedIndices(aa)
End Sub

Default keystore file does not exist?

In macOS, open the Terminal and type below command


It will navigate to the folder that containing Keystore file (You can confirm it with 'ls' command)

In my case, there is a file named 'debug.keystore'. Then type below command in the terminal from the ~/.android directory.

keytool -list -v -keystore debug.keystore

You will get the expected output.

How to get a path to the desktop for current user in C#?

 string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
 string extension = ".log";
 filePath += @"\Error Log\" + extension;
 if (!Directory.Exists(filePath))

How to disable RecyclerView scrolling?

For whom want's to just prevent the user to scroll the RecyclerView, without loose the smoothScrollToPosition or any other "go to position" method, I'd recommend rather extending the RecyclerView class, overriding the onTouchEvent. Like this:

            public class HardwareButtonsRecyclerView extends RecyclerView {
                    public HardwareButtonsRecyclerView(@NonNull Context context) {
                    public HardwareButtonsRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) {
                        super(context, attrs);
                    public HardwareButtonsRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
                        super(context, attrs, defStyleAttr);
                public boolean onTouchEvent(MotionEvent e) {
                    return false;

Should I test private methods or only public ones?

I see many people are in the same line of thinking: test at the public level. but isn't that what our QA team does? They test input and expected output. If as developers we only test the public methods then we are simply redoing QA's job and not adding any value by "unit testing".

How to remove Left property when position: absolute?

left: initial

This will also set left back to the browser default.

But important to know property: initial is not supported in IE.

Getting visitors country from their IP

I have a short answer which I have used in a project. In my answer, I consider that you have visitor IP address.

$ip = "";
$ipdat = @json_decode(file_get_contents("" . $ip));
//get ISO2 country code
if(property_exists($ipdat, 'geoplugin_countryCode')) {
    echo $ipdat->geoplugin_countryCode;
//get country full name
if(property_exists($ipdat, 'geoplugin_countryName')) {
    echo $ipdat->geoplugin_countryName;

Smooth GPS data

What you are looking for is called a Kalman Filter. It's frequently used to smooth navigational data. It is not necessarily trivial, and there is a lot of tuning you can do, but it is a very standard approach and works well. There is a KFilter library available which is a C++ implementation.

My next fallback would be least squares fit. A Kalman filter will smooth the data taking velocities into account, whereas a least squares fit approach will just use positional information. Still, it is definitely simpler to implement and understand. It looks like the GNU Scientific Library may have an implementation of this.

What is the equivalent of the C++ Pair<L,R> in Java?

Here are some libraries that have multiple degrees of tuples for your convenience:

  • JavaTuples. Tuples from degree 1-10 is all it has.
  • JavaSlang. Tuples from degree 0-8 and lots of other functional goodies.
  • jOO?. Tuples from degree 0-16 and some other functional goodies. (Disclaimer, I work for the maintainer company)
  • Functional Java. Tuples from degree 0-8 and lots of other functional goodies.

Other libraries have been mentioned to contain at least the Pair tuple.

Specifically, in the context of functional programming which makes use of a lot of structural typing, rather than nominal typing (as advocated in the accepted answer), those libraries and their tuples come in very handy.

How to convert a table to a data frame

If you are using the tidyverse, you can use


to get a tibble (i.e. a data frame with some minor variations from the base class)

HTML5 iFrame Seamless Attribute

Use the frameborder attribute on your iframe and set it to frameborder="0" . That produces the seamless look. Now you maybe saying I want the nested iframe to control rather I have scroll bars. Then you need to whip up a JavaScript script file that calculates height minus any headers and set the height. Debounce is javascript plugin needed to make sure resize works appropriately in older browsers and sometimes chrome. That will get you in the right direction.

Android Studio rendering problems

Rendering didn't work for me too. I had <null> value on the right side of the android icon. I ran

sudo apt-get install gradle

I restarted Android studio then and <null> value changed to 23.

Voila, it renders now! :)

enter image description here

How to remove duplicates from a list?

Does Customer implement the equals() contract?

If it doesn't implement equals() and hashCode(), then listCustomer.contains(customer) will check to see if the exact same instance already exists in the list (By instance I mean the exact same object--memory address, etc). If what you are looking for is to test whether or not the same Customer( perhaps it's the same customer if they have the same customer name, or customer number) is in the list already, then you would need to override equals() to ensure that it checks whether or not the relevant fields(e.g. customer names) match.

Note: Don't forget to override hashCode() if you are going to override equals()! Otherwise, you might get trouble with your HashMaps and other data structures. For a good coverage of why this is and what pitfalls to avoid, consider having a look at Josh Bloch's Effective Java chapters on equals() and hashCode() (The link only contains iformation about why you must implement hashCode() when you implement equals(), but there is good coverage about how to override equals() too).

By the way, is there an ordering restriction on your set? If there isn't, a slightly easier way to solve this problem is use a Set<Customer> like so:

Set<Customer> noDups = new HashSet<Customer>();
return new ArrayList<Customer>(noDups);

Which will nicely remove duplicates for you, since Sets don't allow duplicates. However, this will lose any ordering that was applied to tmpListCustomer, since HashSet has no explicit ordering (You can get around that by using a TreeSet, but that's not exactly related to your question). This can simplify your code a little bit.

How to get Linux console window width in Python

If you're using Python 3.3 or above, I'd recommend the built-in get_terminal_size() as already recommended. However if you are stuck with an older version and want a simple, cross-platform way of doing this, you could use asciimatics. This package supports versions of Python back to 2.7 and uses similar options to those suggested above to get the current terminal/console size.

Simply construct your Screen class and use the dimensions property to get the height and width. This has been proven to work on Linux, OSX and Windows.

Oh - and full disclosure here: I am the author, so please feel free to open a new issue if you have any problems getting this to work.

HTTP Error 500.30 - ANCM In-Process Start Failure

I had an issue in my Program.cs file. I was trying to connect with AddAzureKeyVault that had been deleted long time ago.


This error could come to due to any silly error in the application. Debug step by step your application startup process.

How do you post to the wall on a facebook page (not profile)

Harish has the answer here - except you need to request manage_pages permission when authenticating and then using the page-id instead of me when posting....

$result = $facebook->api('page-id/feed/','post',$attachment);

CSS fill remaining width

Include your image in the searchBar div, it will do the task for you

<div id="searchBar">
    <img src="img/logo.png" />                
    <input type="text" />

How to multiply values using SQL

Here it is:

select player_name, player_salary, (player_salary * 1.1) as player_newsalary
from player 
order by player_name, player_salary, player_newsalary desc

You don't need to "group by" if there is only one instance of a player in the table.

LISTAGG in Oracle to return distinct values

listagg() ignores NULL values, so in a first step you could use the lag() function to analyse whether the previous record had the same value, if yes then NULL, else 'new value'.

WITH tab AS 
          SELECT 1 as col1, 2 as col2, 'Smith' as created_by FROM dual
UNION ALL SELECT 1 as col1, 2 as col2, 'John'  as created_by FROM dual
UNION ALL SELECT 1 as col1, 3 as col2, 'Ajay'  as created_by FROM dual
UNION ALL SELECT 1 as col1, 4 as col2, 'Ram'   as created_by FROM dual
UNION ALL SELECT 1 as col1, 5 as col2, 'Jack'  as created_by FROM dual
     , CASE 
       WHEN lag(col2) OVER (ORDER BY col2) = col2 THEN 
       END as col2_with_nulls
     , created_by
  FROM tab;


---------- --------------- -----
         1               2 Smith
         1                 John
         1               3 Ajay
         1               4 Ram
         1               5 Jack

Note that the second 2 is replaced by NULL. Now you can wrap a SELECT with the listagg() around it.

WITH tab AS 
          SELECT 1 as col1, 2 as col2, 'Smith' as created_by FROM dual
UNION ALL SELECT 1 as col1, 2 as col2, 'John'  as created_by FROM dual
UNION ALL SELECT 1 as col1, 3 as col2, 'Ajay'  as created_by FROM dual
UNION ALL SELECT 1 as col1, 4 as col2, 'Ram'   as created_by FROM dual
UNION ALL SELECT 1 as col1, 5 as col2, 'Jack'  as created_by FROM dual
SELECT listagg(col2_with_nulls, ',') WITHIN GROUP (ORDER BY col2_with_nulls) col2_list
  FROM ( SELECT col1
              , CASE WHEN lag(col2) OVER (ORDER BY col2) = col2 THEN NULL ELSE col2 END as col2_with_nulls
              , created_by
           FROM tab );



You can do this over multiple columns too.

WITH tab AS 
          SELECT 1 as col1, 2 as col2, 'Smith' as created_by FROM dual
UNION ALL SELECT 1 as col1, 2 as col2, 'John'  as created_by FROM dual
UNION ALL SELECT 1 as col1, 3 as col2, 'Ajay'  as created_by FROM dual
UNION ALL SELECT 1 as col1, 4 as col2, 'Ram'   as created_by FROM dual
UNION ALL SELECT 1 as col1, 5 as col2, 'Jack'  as created_by FROM dual
SELECT listagg(col1_with_nulls, ',') WITHIN GROUP (ORDER BY col1_with_nulls) col1_list
     , listagg(col2_with_nulls, ',') WITHIN GROUP (ORDER BY col2_with_nulls) col2_list
     , listagg(created_by, ',')      WITHIN GROUP (ORDER BY created_by) created_by_list
  FROM ( SELECT CASE WHEN lag(col1) OVER (ORDER BY col1) = col1 THEN NULL ELSE col1 END as col1_with_nulls
              , CASE WHEN lag(col2) OVER (ORDER BY col2) = col2 THEN NULL ELSE col2 END as col2_with_nulls
              , created_by
           FROM tab );


--------- --------- -------------------------
1         2,3,4,5   Ajay,Jack,John,Ram,Smith

Null & empty string comparison in Bash

fedorqui has a working solution but there is another way to do the same thing.

Chock if a variable is set

# This will be true if the variable has a value
if [ $amIEmpty ]; then
    echo 'No, I am not!';

Or to verify that a variable is empty

# This will be true if the variable is empty
if [ ! $amIEmpty ]; then
    echo 'Yes I am!';
fi has good documentation about if in bash:

Java - get index of key in HashMap?

If all you are trying to do is get the value out of the hashmap itself, you can do something like the following:

for (Object key : map.keySet()) {
    Object value = map.get(key);
    //TODO: this

Or, you can iterate over the entries of a map, if that is what you are interested in:

for (Map.Entry<Object, Object> entry : map.entrySet()) {
    Object key = entry.getKey();
    Object value = entry.getValue();
    //TODO: other cool stuff

As a community, we might be able to give you better/more appropriate answers if we had some idea why you needed the indexes or what you thought the indexes could do for you.

How to concatenate string variables in Bash

Bash also supports a += operator as shown in this code:

A="X Y"
A+=" Z"
echo "$A"



Getting "method not valid without suitable object" error when trying to make a HTTP request in VBA?

For reading REST data, at least OData Consider Microsoft Power Query. You won't be able to write data. However, you can read data very well.

Use of def, val, and var in scala

There are three ways of defining things in Scala:

  • def defines a method
  • val defines a fixed value (which cannot be modified)
  • var defines a variable (which can be modified)

Looking at your code:

def person = new Person("Kumar",12)

This defines a new method called person. You can call this method only without () because it is defined as parameterless method. For empty-paren method, you can call it with or without '()'. If you simply write:


then you are calling this method (and if you don't assign the return value, it will just be discarded). In this line of code:

person.age = 20

what happens is that you first call the person method, and on the return value (an instance of class Person) you are changing the age member variable.

And the last line:


Here you are again calling the person method, which returns a new instance of class Person (with age set to 12). It's the same as this:


how to change default python version?

Navigate to:

My Computer -> Properties -> Advanced -> Environment Variables -> System Variables

Suppose you had already having python 2.7 added in path variable and you want to change default path to python 3.x

then add path of python3.5.x folder before python2.7 path.

open cmd: type "python --version"

python version will be changed to python 3.5.x

How to fill the whole canvas with specific color?

Yes, fill in a Rectangle with a solid color across the canvas, use the height and width of the canvas itself:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);
canvas{ border: 1px solid black; }
<canvas width=300 height=150 id="canvas">

Placing/Overlapping(z-index) a view above another view in android

I solved the same problem by add android:elevation="1dp" to which view you want it over another. But it can't display below 5.0, and it will have a little shadow, if you can accept it, it's OK.

So, the most correct solution which is @kcoppock said.

Obtain smallest value from array in Javascript?

function tinyFriends() {
    let myFriends = ["Mukit", "Ali", "Umor", "sabbir"]
    let smallestFridend = myFriends[0];
    for (i = 0; i < myFriends.length; i++) {
        if (myFriends[i] < smallestFridend) {
            smallestFridend = myFriends[i];
    return smallestFridend   

Proxy with urllib2

In Addition to the accepted answer: My scipt gave me an error

File "c:\Python23\lib\", line 580, in proxy_open
    if '@' in host:
TypeError: iterable argument required

Solution was to add http:// in front of the proxy string:

proxy = urllib2.ProxyHandler({'http': 'http://proxy.xy.z:8080'})
opener = urllib2.build_opener(proxy)

CSS - Make divs align horizontally

You can do something like this:

#container {_x000D_
  background-color: red;_x000D_
  width: 200px;_x000D_
.child {_x000D_
  background-color: blue;_x000D_
  width: 150px;_x000D_
  height: 50px;_x000D_
<div id="container">_x000D_
  <div id="inner">_x000D_
    <div class="child"></div>_x000D_
    <div class="child"></div>_x000D_
    <div class="child"></div>_x000D_

Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

same issue i have.

i tired all possible solutions that i found. but non were worked.

always got this error

Cannot add task ':processDebugGoogleServices' as a task with that name already exists

Now, i solved it.

1) first i checked my config.xml

2) and removed unnecessary plugin. (I used firebase fcm plugin for pushnotification, but there was two unnecessary plugin phonegap-plugin-push and cordova-plugin-customurlscheme. I removed both these plugins)

3) then removed platform.

4) then add platform

5) then build it.

6) now it build successfully.

Error: Execution failed for task ':app:clean'. Unable to delete file

if you're still having issues then update to the latest version of Android Studio(its 2.1 as of now), might be it was a bug with older version of Android Studio. Its resolved for me now.

How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?

If your jar file already has an absolute pathname as shown, it is particularly easy:

cd /where/you/want/it; jar xf /path/to/jarfile.jar

That is, you have the shell executed by Python change directory for you and then run the extraction.

If your jar file does not already have an absolute pathname, then you have to convert the relative name to absolute (by prefixing it with the path of the current directory) so that jar can find it after the change of directory.

The only issues left to worry about are things like blanks in the path names.

How to Apply Mask to Image in OpenCV?

While @perrejba s answer is correct, it uses the legacy C-style functions. As the question is tagged C++, you may want to use a method instead:

inputMat.copyTo(outputMat, maskMat);

All objects are of type cv::Mat.

Please be aware that the masking is binary. Any non-zero value in the mask is interpreted as 'do copy'. Even if the mask is a greyscale image.

Also be aware that the .copyTo() function does not clear the output before copying.

If you want to permanently alter the original Image, you have to do an additional copy/clone/assignment. The copyTo() function is not defined for overlapping input/output images. So you can't use the same image as both input and output.

str_replace with array

Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements.

    // Outputs F because A is replaced with B, then B is replaced with C, and so on...
    // Finally E is replaced with F, because of left to right replacements.
    $search  = array('A', 'B', 'C', 'D', 'E');
    $replace = array('B', 'C', 'D', 'E', 'F');
    $subject = 'A';
    echo str_replace($search, $replace, $subject);

Convert List to Pandas Dataframe Column

if your list looks like this: [1,2,3] you can do:

lst = [1,2,3]
df = pd.DataFrame([lst])
df.columns =['col1','col2','col3']

to get this:

    col1    col2    col3
0   1       2       3

alternatively you can create a column as follows:

import numpy as np
df = pd.DataFrame(np.array([lst]).T)
df.columns =['col1']

to get this:

0   1
1   2
2   3

How to change root logging level programmatically for logback

Try this:

import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;

Logger root = (Logger)LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);

Note that you can also tell logback to periodically scan your config file like this:

<configuration scan="true" scanPeriod="30 seconds" > 

Using CookieContainer with WebClient class

The HttpWebRequest modifies the CookieContainer assigned to it. There is no need to process returned cookies. Simply assign your cookie container to every web request.

public class CookieAwareWebClient : WebClient
    public CookieContainer CookieContainer { get; set; } = new CookieContainer();

    protected override WebRequest GetWebRequest(Uri uri)
        WebRequest request = base.GetWebRequest(uri);
        if (request is HttpWebRequest)
            (request as HttpWebRequest).CookieContainer = CookieContainer;
        return request;

test attribute in JSTL <c:if> tag

All that the test attribute looks for to determine if something is true is the string "true" (case in-sensitive). For example, the following code will print "Hello world!"

<c:if test="true">Hello world!</c:if>

The code within the <%= %> returns a boolean, so it will either print the string "true" or "false", which is exactly what the <c:if> tag looks for.

How can I use a carriage return in a HTML tooltip?

I don't believe it is. Firefox 2 trims long link titles anyway and they should really only be used to convey a small amount of help text. If you need more explanation text I would suggest that it belongs in a paragraph associated with the link. You could then add the tooltip javascript code to hide those paragraphs and show them as tooltips on hover. That's your best bet for getting it to work cross-browser IMO.

Display a RecyclerView in Fragment

You should retrieve RecyclerView in a Fragment after inflating core View using that View. Perhaps it can't find your recycler because it's not part of Activity

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_artist_tracks, container, false);
    final FragmentActivity c = getActivity();
    final RecyclerView recyclerView = (RecyclerView) view.findViewById(;
    LinearLayoutManager layoutManager = new LinearLayoutManager(c);

    new Thread(new Runnable() {
        public void run() {
            final RecyclerAdapter adapter = new RecyclerAdapter(c);
            c.runOnUiThread(new Runnable() {
                public void run() {

    return view;

Java: Integer equals vs. ==

The issue is that your two Integer objects are just that, objects. They do not match because you are comparing your two object references, not the values within. Obviously .equals is overridden to provide a value comparison as opposed to an object reference comparison.

How to discard uncommitted changes in SourceTree?

Do as follow,

  • Click on commit
  • Select all by pressing CMD+A that you want to delete or discard
  • Right click on the selected uncommitted files that you want to delete
  • Select Remove from the drop-down list

Java string to date conversion

Simple two formatters we have used:

  1. Which format date do we want?
  2. Which format date is actually present?

We parse the full date to time format:

date="2016-05-06 16:40:32";

public static String setDateParsing(String date) throws ParseException {

    // This is the format date we want
    DateFormat mSDF = new SimpleDateFormat("hh:mm a");

    // This format date is actually present
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd hh:mm");
    return mSDF.format(formatter.parse(date));

How to force 'cp' to overwrite directory instead of creating another one inside?

You can do this using -T option in cp.
See Man page for cp.

-T, --no-target-directory
    treat DEST as a normal file

So as per your example, following is the file structure.

$ tree test
|-- bar
|   |-- a
|   `-- b
`-- foo
    |-- a
    `-- b
2 directories, 4 files

You can see the clear difference when you use -v for Verbose.
When you use just -R option.

$ cp -Rv foo/ bar/
`foo/' -> `bar/foo'
`foo/b' -> `bar/foo/b'
`foo/a' -> `bar/foo/a'
 $ tree
 |-- bar
 |   |-- a
 |   |-- b
 |   `-- foo
 |       |-- a
 |       `-- b
 `-- foo
     |-- a
     `-- b
3 directories, 6 files

When you use the option -T it overwrites the contents, treating the destination like a normal file and not directory.

$ cp -TRv foo/ bar/
`foo/b' -> `bar/b'
`foo/a' -> `bar/a'

$ tree
|-- bar
|   |-- a
|   `-- b
`-- foo
    |-- a
    `-- b
2 directories, 4 files

This should solve your problem.

Get source JARs from Maven repository

if you're using eclipse you could also open Preferences > Maven and select Download Artifact Sources, this would let the pom.xml intact and keep your sources or java docs (if selected) just for development right at your machine location ~/.m2

How to get current user in core


EDIT for constructor

Below code works:

public Controller(IHttpContextAccessor httpContextAccessor)
    var userId = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value 

Edit for RTM

You should register IHttpContextAccessor:

    public void ConfigureServices(IServiceCollection services)

facebook Uncaught OAuthException: An active access token must be used to query information about the current user

After a certain amount of time, your access token expires.

To prevent this, you can request the 'offline_access' permission during the authentication, as noted here: Do Facebook Oauth 2.0 Access Tokens Expire?

Windows batch script to unhide files hidden by virus

Try this one. Hope this is working fine.. :)

@ECHO off



set drvltr=

set /p drvltr=Enter Drive letter: 

attrib -s -h -a /s /d  %drvltr%:\*.*

ECHO Unhide Completed


Converting Epoch time into the datetime

First a bit of info in epoch from man gmtime

The ctime(), gmtime() and localtime() functions all take an argument of data type time_t which represents calendar  time.   When  inter-
       preted  as  an absolute time value, it represents the number of seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal
       Time (UTC).

to understand how epoch should be.

>>> time.time()
>>> time.gmtime(time.time())
(2012, 9, 13, 6, 19, 34, 3, 257, 0)

just ensure the arg you are passing to time.gmtime() is integer.

Syntax error on print with Python 3

It looks like you're using Python 3.0, in which print has turned into a callable function rather than a statement.

print('Hello world!')

how can I set visible back to true in jquery

Depends, if i remember correctly i think won't render the html object out when you set visible to false.

If you want to be able to control it from the client side, then you better just include the css value to set it invisible rather than using visible =false.

SQL set values of one column equal to values of another column in the same table

I don't think that other example is what you're looking for. If you're just updating one column from another column in the same table you should be able to use something like this.

update some_table set null_column = not_null_column where null_column is null

How to increment a number by 2 in a PHP For Loop

Another simple solution with +=:

$y = 1;

for ($x = $y; $x <= 15; $y++) {
  printf("The number of first paragraph is: $y <br>");
  printf("The number of second paragraph is: $x+=2 <br>");

How to create empty folder in java?

Looks file you use the .mkdirs() method on a File object:

// Create a directory; all non-existent ancestor directories are
// automatically created
success = (new File("../potentially/long/pathname/without/all/dirs")).mkdirs();
if (!success) {
    // Directory creation failed

How can I use LEFT & RIGHT Functions in SQL to get last 3 characters?

Here an alternative using SUBSTRING

            SUBSTRING([Field], LEN([Field]) - 2, 3) [Right3],
            SUBSTRING([Field], 0, LEN([Field]) - 2) [TheRest]

with fiddle

How get an apostrophe in a string in javascript

You can put an apostrophe in a single quoted JavaScript string by escaping it with a backslash, like so:

theAnchorText = 'I\'m home';

Submit two forms with one button

A form submission causes the page to navigate away to the action of the form. So, you cannot submit both forms in the traditional way. If you try to do so with JavaScript by calling form.submit() on each form in succession, each request will be aborted except for the last submission. So, you need to submit the first form asynchronously via JavaScript:

var f = document.forms.updateDB;
var postData = [];
for (var i = 0; i < f.elements.length; i++) {
    postData.push(f.elements[i].name + "=" + f.elements[i].value);
var xhr = new XMLHttpRequest();"POST", "mypage.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");


Finding the last index of an array

To compute the index of the last item:

int index = array.Length - 1;

Will get you -1 if the array is empty - you should treat it as a special case.

To access the last index:

array[array.Length - 1] = ...


... = array[array.Length - 1]

will cause an exception if the array is actually empty (Length is 0).

using .join method to convert array to string without commas

The .join() method has a parameter for the separator string. If you want it to be empty instead of the default comma, use


What causes this error? "Runtime error 380: Invalid property value"

error 380 windows 7 solution very easy just check your date time & regional setting do them correct.

SEVERE: ContainerBase.addChild: start:org.apache.catalina.LifecycleException: Failed to start error

In my case the servlet name defined in the web.xml was not same as the sevlet name in the servlet mapping tag. I have corrected this and the WAR was deployed successfully.

Selenium WebDriver findElement(By.xpath()) not working for me

You haven't specified what kind of html element you are trying to do an absolute xpath search on. In your case, it's the input element.

Try this:

element = findElement(By.xpath("//input[@class='t-TextBox' and @type='email' and @test-    

Difference between "move" and "li" in MIPS assembly language

The move instruction copies a value from one register to another. The li instruction loads a specific numeric value into that register.

For the specific case of zero, you can use either the constant zero or the zero register to get that:

move $s0, $zero
li   $s0, 0

There's no register that generates a value other than zero, though, so you'd have to use li if you wanted some other number, like:

li $s0, 12345678

Loop through files in a folder in matlab

At first, you must specify your path, the path that your *.csv files are in there

path = 'f:\project\dataset'

You can change it based on your system.


use dir function :

files = dir (strcat(path,'\*.csv'))

L = length (files);

for i=1:L
   % process the image in here

pwd also can be used.

How to export data to CSV in PowerShell?

simply use the Out-File cmd but DON'T forget to give an encoding type: -Encoding UTF8

so use it so:

$log | Out-File -Append C:\as\whatever.csv -Encoding UTF8

-Append is required if you want to write in the file more then once.

invalid_client in google oauth2

I accidentally had a value in the Client Secret part of the URL, but Google Credential does not need a Client Secret for Android OAuth 2 Client IDs. Simply leaving the value blank in the URL did the trick for me.

Pandas "Can only compare identically-labeled DataFrame objects" error

When you compare two DataFrames, you must ensure that the number of records in the first DataFrame matches with the number of records in the second DataFrame. In our example, each of the two DataFrames had 4 records, with 4 products and 4 prices.

If, for example, one of the DataFrames had 5 products, while the other DataFrame had 4 products, and you tried to run the comparison, you would get the following error:

ValueError: Can only compare identically-labeled Series objects

this should work

import pandas as pd
import numpy as np

firstProductSet = {'Product1': ['Computer','Phone','Printer','Desk'],
                   'Price1': [1200,800,200,350]
df1 = pd.DataFrame(firstProductSet,columns= ['Product1', 'Price1'])

secondProductSet = {'Product2': ['Computer','Phone','Printer','Desk'],
                    'Price2': [900,800,300,350]
df2 = pd.DataFrame(secondProductSet,columns= ['Product2', 'Price2'])

df1['Price2'] = df2['Price2'] #add the Price2 column from df2 to df1

df1['pricesMatch?'] = np.where(df1['Price1'] == df2['Price2'], 'True', 'False')  #create new column in df1 to check if prices match
df1['priceDiff?'] = np.where(df1['Price1'] == df2['Price2'], 0, df1['Price1'] - df2['Price2']) #create new column in df1 for price diff 
print (df1)

example from

Converting rows into columns and columns into rows using R

Simply use the base transpose function t, wrapped with

final_df <-
     A    B    C    D
a    1    2    3    4
b 0.02 0.04 0.06 0.08
c Aaaa Bbbb Cccc Dddd

Above updated. As docendo discimus pointed out, t returns a matrix. As Mark suggested wrapping it with gets back a data frame instead of a matrix. Thanks!

Laravel 4: how to "order by" using Eloquent ORM

This is how I would go about it.

$posts = $this->post->orderBy('id', 'DESC')->get();

Setting selection to Nothing when programming Excel

If using a button to call the paste procedure,

try activating the button after the operation. this successfully clears the selection


  • having to mess around with hidden things
  • selecting another cell (which is exactly the opposite of what was asked)
  • affecting the clipboard mode
  • having the hacky method of pressing escape which doesn't always work


Sub BtnCopypasta_Worksheet_Click()
End sub


Where does Git store files?

In a .git directory in the root of the project. Unlike some other version control systems, notably CVS, there are no additional directories in any of the subdirectories.

Making HTTP Requests using Chrome Developer tools

If your web page has jquery in your page, then you can do it writing on chrome developers console:

    {paramOne : 1, paramX : 'abc'},
    function(data) {
       alert('page content: ' + data);

Its jquery way of doing it!

Convert/cast an stdClass object to another class

See the manual on Type Juggling on possible casts.

The casts allowed are:

  • (int), (integer) - cast to integer
  • (bool), (boolean) - cast to boolean
  • (float), (double), (real) - cast to float
  • (string) - cast to string
  • (array) - cast to array
  • (object) - cast to object
  • (unset) - cast to NULL (PHP 5)

You would have to write a Mapper that does the casting from stdClass to another concrete class. Shouldn't be too hard to do.

Or, if you are in a hackish mood, you could adapt the following code:

function arrayToObject(array $array, $className) {
    return unserialize(sprintf(
        strstr(serialize($array), ':')

which pseudocasts an array to an object of a certain class. This works by first serializing the array and then changing the serialized data so that it represents a certain class. The result is unserialized to an instance of this class then. But like I said, it's hackish, so expect side-effects.

For object to object, the code would be

function objectToObject($instance, $className) {
    return unserialize(sprintf(
        strstr(strstr(serialize($instance), '"'), ':')

Updating a local repository with changes from a GitHub repository

With an already-set origin master, you just have to use the below command -

git pull ""

MySQL SELECT query string matching


SELECT * FROM customers WHERE name LIKE '%Bob Smith%';


select count(*)
from rearp.customers c
where  LIKE '%Bob smith.8%';

select count will just query (totals)

C will link the db.table to the names row you need this to index

LIKE should be obvs

8 will call all references in DB 8 or less (not really needed but i like neatness)

How to turn on/off MySQL strict mode in localhost (xampp)?

You can check the local and global value of it with:


Can RDP clients launch remote applications and not desktops

Yes, you can change the default shell from Explorer.exe to a specific application.

In Regedit, navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon. The current shell should be Explorer.exe. Change it to YourApp.exe. That will change the shell for all users who log on to the machine. If you only want to change it for a specific user, go to the same key in HKEY_CURRENT_USER instead.

Declaring a python function with an array parameters and passing an array argument to the function call?

Maybe you want unpack elements of array, I don't know if I got it, but below a example:

def my_func(*args):
    for a in args:
        print a

my_list = ['a','b','c']

localhost refused to connect Error in visual studio

I ran into a similar problem when I started working this morning, using Visual Studio Community 2019, Debug configuration. The IIS Express (Google Chrome) site was unreachable. When I terminated program execution via the red stop button in Visual Studio, I was rewarded with a windows error message stating "process with an id of 4### is not running".

The computer had been left on overnight.

I looked through the answers here and the solutions looked complicated. I tried closing and reopening the solution, restarting Visual Studio and, finally, restarting the computer.

Restarting the computer resolved my issue. I did not delete any files or change any other settings.

H2 database error: Database may be already in use: "Locked by another process"

I ran into similar problems running with ORMLite from a web application. I initially got stuck on the syntax to use server mode in the url. The answers above helped with that. Then I had the similar user/password error which was easier to figure out. I did not have to shut anything down or erase any files. The following code worked:

protected ConnectionSource getConnectionSource() throws SQLException {
    String databaseUrl = "jdbc:h2:tcp://localhost/~/test";
    return new JdbcConnectionSource(databaseUrl,"sa","sa");

To use H2 in server mode on wildfly, I Modifed connection-url in standalone.xml

<datasource jndi-name="java:jboss/datasources/ExampleDS" pool- name="ExampleDS" enabled="true" use-java-context="true">

CreateProcess error=2, The system cannot find the file specified

I used ProcessBuilder but had the same issue. The issue was with using command as one String line (like I would type it in cmd) instead of String array. In example from above. If I ran

ProcessBuilder pb = new ProcessBuilder("C:/Program Files/WinRAR/winrar x myjar.jar *.* new"); File("H:/"));
pb. redirectErrorStream(true);

Process p = pb.start();

I got an error. But if I ran

ProcessBuilder pb = new ProcessBuilder("C:/Program Files/WinRAR/winrar", "x", "myjar.jar", "*.*", "new"); File("H:/"));
pb. redirectErrorStream(true);

Process p = pb.start();

everything was OK.

Get only specific attributes with from Laravel Collection

this seems to work, but not sure if it's optimized for performance or not.



array:2 [
  0 => 4
  1 => 1

if (select count(column) from table) > 0 then

You cannot directly use a SQL statement in a PL/SQL expression:

SQL> begin
  2     if (select count(*) from dual) >= 1 then
  3        null;
  4     end if;
  5  end;
  6  /
        if (select count(*) from dual) >= 1 then
ERROR at line 2:
ORA-06550: line 2, column 6:
PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:

You must use a variable instead:

SQL> set serveroutput on
SQL> declare
  2     v_count number;
  3  begin
  4     select count(*) into v_count from dual;
  6     if v_count >= 1 then
  7             dbms_output.put_line('Pass');
  8     end if;
  9  end;
 10  /

PL/SQL procedure successfully completed.

Of course, you may be able to do the whole thing in SQL:

update my_table
set x = y
where (select count(*) from other_table) >= 1;

It's difficult to prove that something is not possible. Other than the simple test case above, you can look at the syntax diagram for the IF statement; you won't see a SELECT statement in any of the branches.

Getting "type or namespace name could not be found" but everything seems ok?

[Facepalm] My issue was that I had added the dependency in the C++ way of doing things.

Go to the project that won't build, open up the 'References' folder in Solution Explorer, and see if your dependency is listed.

If not, you can 'Add Reference' and choose the dependency on the Projects tab.

Boom Shankar.

Using group by on multiple columns

Group By X means put all those with the same value for X in the one group.

Group By X, Y means put all those with the same values for both X and Y in the one group.

To illustrate using an example, let's say we have the following table, to do with who is attending what subject at a university:

Table: Subject_Selection

| Subject | Semester | Attendee |
| ITB001  |        1 | John     |
| ITB001  |        1 | Bob      |
| ITB001  |        1 | Mickey   |
| ITB001  |        2 | Jenny    |
| ITB001  |        2 | James    |
| MKB114  |        1 | John     |
| MKB114  |        1 | Erica    |

When you use a group by on the subject column only; say:

select Subject, Count(*)
from Subject_Selection
group by Subject

You will get something like:

| Subject | Count |
| ITB001  |     5 |
| MKB114  |     2 |

...because there are 5 entries for ITB001, and 2 for MKB114

If we were to group by two columns:

select Subject, Semester, Count(*)
from Subject_Selection
group by Subject, Semester

we would get this:

| Subject | Semester | Count |
| ITB001  |        1 |     3 |
| ITB001  |        2 |     2 |
| MKB114  |        1 |     2 |

This is because, when we group by two columns, it is saying "Group them so that all of those with the same Subject and Semester are in the same group, and then calculate all the aggregate functions (Count, Sum, Average, etc.) for each of those groups". In this example, this is demonstrated by the fact that, when we count them, there are three people doing ITB001 in semester 1, and two doing it in semester 2. Both of the people doing MKB114 are in semester 1, so there is no row for semester 2 (no data fits into the group "MKB114, Semester 2")

Hopefully that makes sense.

Replace multiple characters in one replace call

For replacing with nothing, tckmn's answer is the best.

If you need to replace with specific strings corresponding to the matches, here's a variation on Voicu's and Christophe's answers that avoids duplicating what's being matched, so that you don't have to remember to add new matches in two places:

const replacements = {
  '’': "'",
  '“': '"',
  '”': '"',
  '—': '---',
  '–': '--',
const replacement_regex = new RegExp(Object
  // escape any regex literals found in the replacement keys:
  .map(e => e.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
, 'g');
return text.replace(replacement_regex, e => replacements[e]);

Make function wait until element exists

Here's a minor improvement over Jamie Hutber's answer

const checkElement = async selector => {
  while ( document.querySelector(selector) === null) {
    await new Promise( resolve =>  requestAnimationFrame(resolve) )
  return document.querySelector(selector); 

To use:

checkElement('.myElement').then((selector) => {

Failed to locate the winutils binary in the hadoop binary path

winutils.exe are required for hadoop to perform hadoop related commands. please download hadoop-common-2.2.0 zip file. winutils.exe can be found in bin folder. Extract the zip file and copy it in the local hadoop/bin folder.

In practice, what are the main uses for the new "yield from" syntax in Python 3.3?

Let's get one thing out of the way first. The explanation that yield from g is equivalent to for v in g: yield v does not even begin to do justice to what yield from is all about. Because, let's face it, if all yield from does is expand the for loop, then it does not warrant adding yield from to the language and preclude a whole bunch of new features from being implemented in Python 2.x.

What yield from does is it establishes a transparent bidirectional connection between the caller and the sub-generator:

  • The connection is "transparent" in the sense that it will propagate everything correctly too, not just the elements being generated (e.g. exceptions are propagated).

  • The connection is "bidirectional" in the sense that data can be both sent from and to a generator.

(If we were talking about TCP, yield from g might mean "now temporarily disconnect my client's socket and reconnect it to this other server socket".)

BTW, if you are not sure what sending data to a generator even means, you need to drop everything and read about coroutines first—they're very useful (contrast them with subroutines), but unfortunately lesser-known in Python. Dave Beazley's Curious Course on Coroutines is an excellent start. Read slides 24-33 for a quick primer.

Reading data from a generator using yield from

def reader():
    """A generator that fakes a read from a file, socket, etc."""
    for i in range(4):
        yield '<< %s' % i

def reader_wrapper(g):
    # Manually iterate over data produced by reader
    for v in g:
        yield v

wrap = reader_wrapper(reader())
for i in wrap:

# Result
<< 0
<< 1
<< 2
<< 3

Instead of manually iterating over reader(), we can just yield from it.

def reader_wrapper(g):
    yield from g

That works, and we eliminated one line of code. And probably the intent is a little bit clearer (or not). But nothing life changing.

Sending data to a generator (coroutine) using yield from - Part 1

Now let's do something more interesting. Let's create a coroutine called writer that accepts data sent to it and writes to a socket, fd, etc.

def writer():
    """A coroutine that writes data *sent* to it to fd, socket, etc."""
    while True:
        w = (yield)
        print('>> ', w)

Now the question is, how should the wrapper function handle sending data to the writer, so that any data that is sent to the wrapper is transparently sent to the writer()?

def writer_wrapper(coro):
    # TBD

w = writer()
wrap = writer_wrapper(w)
wrap.send(None)  # "prime" the coroutine
for i in range(4):

# Expected result
>>  0
>>  1
>>  2
>>  3

The wrapper needs to accept the data that is sent to it (obviously) and should also handle the StopIteration when the for loop is exhausted. Evidently just doing for x in coro: yield x won't do. Here is a version that works.

def writer_wrapper(coro):
    coro.send(None)  # prime the coro
    while True:
            x = (yield)  # Capture the value that's sent
            coro.send(x)  # and pass it to the writer
        except StopIteration:

Or, we could do this.

def writer_wrapper(coro):
    yield from coro

That saves 6 lines of code, make it much much more readable and it just works. Magic!

Sending data to a generator yield from - Part 2 - Exception handling

Let's make it more complicated. What if our writer needs to handle exceptions? Let's say the writer handles a SpamException and it prints *** if it encounters one.

class SpamException(Exception):

def writer():
    while True:
            w = (yield)
        except SpamException:
            print('>> ', w)

What if we don't change writer_wrapper? Does it work? Let's try

# writer_wrapper same as above

w = writer()
wrap = writer_wrapper(w)
wrap.send(None)  # "prime" the coroutine
for i in [0, 1, 2, 'spam', 4]:
    if i == 'spam':

# Expected Result
>>  0
>>  1
>>  2
>>  4

# Actual Result
>>  0
>>  1
>>  2
Traceback (most recent call last):
  ... redacted ...
  File ... in writer_wrapper
    x = (yield)

Um, it's not working because x = (yield) just raises the exception and everything comes to a crashing halt. Let's make it work, but manually handling exceptions and sending them or throwing them into the sub-generator (writer)

def writer_wrapper(coro):
    """Works. Manually catches exceptions and throws them"""
    coro.send(None)  # prime the coro
    while True:
                x = (yield)
            except Exception as e:   # This catches the SpamException
        except StopIteration:

This works.

# Result
>>  0
>>  1
>>  2
>>  4

But so does this!

def writer_wrapper(coro):
    yield from coro

The yield from transparently handles sending the values or throwing values into the sub-generator.

This still does not cover all the corner cases though. What happens if the outer generator is closed? What about the case when the sub-generator returns a value (yes, in Python 3.3+, generators can return values), how should the return value be propagated? That yield from transparently handles all the corner cases is really impressive. yield from just magically works and handles all those cases.

I personally feel yield from is a poor keyword choice because it does not make the two-way nature apparent. There were other keywords proposed (like delegate but were rejected because adding a new keyword to the language is much more difficult than combining existing ones.

In summary, it's best to think of yield from as a transparent two way channel between the caller and the sub-generator.


  1. PEP 380 - Syntax for delegating to a sub-generator (Ewing) [v3.3, 2009-02-13]
  2. PEP 342 - Coroutines via Enhanced Generators (GvR, Eby) [v2.5, 2005-05-10]

How to read from a file or STDIN in Bash?

How about

for line in `cat`; do

HttpServletRequest - how to obtain the referring URL?

It's available in the HTTP referer header. You can get it in a servlet as follows:

String referrer = request.getHeader("referer"); // Yes, with the legendary misspelling.

You, however, need to realize that this is a client-controlled value and can thus be spoofed to something entirely different or even removed. Thus, whatever value it returns, you should not use it for any critical business processes in the backend, but only for presentation control (e.g. hiding/showing/changing certain pure layout parts) and/or statistics.

For the interested, background about the misspelling can be found in Wikipedia.

Can regular expressions be used to match nested patterns?

The Pumping lemma for regular languages is the reason why you can't do that.

The generated automaton will have a finite number of states, say k, so a string of k+1 opening braces is bound to have a state repeated somewhere (as the automaton processes the characters). The part of the string between the same state can be duplicated infinitely many times and the automaton will not know the difference.

In particular, if it accepts k+1 opening braces followed by k+1 closing braces (which it should) it will also accept the pumped number of opening braces followed by unchanged k+1 closing brases (which it shouldn't).

disable past dates on datepicker

To disable all previous dates, give start date as today date

startDate: new Date()

Solution: disable all previous dates from today

$(function() {_x000D_
    $( "#datepicker" ).datepicker({ startDate: new Date()});_x000D_
<script src=""></script>_x000D_
<link href="" rel="stylesheet"/>_x000D_
<script src=""></script>_x000D_
<div> Select Date <input type="text" id="datepicker" /></div>

Solution: disable all past dates from a particular date.

$(function() {_x000D_
    $( "#datepicker" ).datepicker({ startDate: new Date("2019-10-15")});_x000D_
<script src=""></script>_x000D_
<link href="" rel="stylesheet"/>_x000D_
<script src=""></script>_x000D_
<div> Select Date <input type="text" id="datepicker" /></div>

This will disable all days before the date 15th October 2019 (2019-10-15)

javax.xml.bind.JAXBException: Class *** nor any of its super class is known to this context

I had faced the similar error when supporting one application. It was about the generated classes for a SOAP Webservice.

The issue was caused due to the missing classes. When javax.xml.bind.Marshaller was trying to marshal the jaxb object it was not finding all dependent classes which were generated by using wsdl and xsd. after adding the jar with all the classes at the class path the issue was resolved.

How can I play sound in Java?

I didn't want to have so many lines of code just to play a simple damn sound. This can work if you have the JavaFX package (already included in my jdk 8).

private static void playSound(String sound){
    // cl is the ClassLoader for the current class, ie. CurrentClass.class.getClassLoader();
    URL file = cl.getResource(sound);
    final Media media = new Media(file.toString());
    final MediaPlayer mediaPlayer = new MediaPlayer(media);;

Notice : You need to initialize JavaFX. A quick way to do that, is to call the constructor of JFXPanel() once in your app :

    JFXPanel fxPanel = new JFXPanel();

python variable NameError

I would approach it like this:

sizes = [100, 250] print "How much space should the random song list occupy?" print '\n'.join("{0}. {1}Mb".format(n, s)                 for n, s in enumerate(sizes, 1)) # present choices choice = int(raw_input("Enter choice:")) # throws error if not int size = sizes[0] # safe starting choice if choice in range(2, len(sizes) + 1):     size = sizes[choice - 1] # note index offset from choice print "You  want to create a random song list that is {0}Mb.".format(size) 

You could also loop until you get an acceptable answer and cover yourself in case of error:

choice = 0 while choice not in range(1, len(sizes) + 1): # loop     try: # guard against error         choice = int(raw_input(...))     except ValueError: # couldn't make an int         print "Please enter a number"         choice = 0 size = sizes[choice - 1] # now definitely valid 

How to create the branch from specific commit in different branch

You can do this locally as everyone mentioned using

git checkout -b <branch-name> <sha1-of-commit>

Alternatively, you can do this in github itself, follow the steps:

1- In the repository, click on the Commits.

2- on the commit you want to branch from, click on <> to browse the repository at this point in the history.

commits history

3- Click on the tree: xxxxxx in the upper left. Just type in a new branch name there click Create branch xxx as shown below.

create new branch

Now you can fetch the changes from that branch locally and continue from there.

Can I exclude some concrete urls from <url-pattern> inside <filter-mapping>?

This approach works when you want to prevent a certain filter and all the following ones. It should work well if you eg. want to serve some content as static resources within your servlet container instead of letting your application logic (through a filter like GuiceFilter):

Map the folder with your static resource files to the default servlet. Create a servlet filter and put it before the GuiceFilter in your web.xml. In your created filter, you can separate between forwarding some requests to the GuiceFilter and others directly to the dispatcher. Example follows...






public class StaticResourceFilter implements Filter {

    private final static Logger LOGGER = LoggerFactory.getLogger(StaticResourceFilter.class);

    private static final String RESOURCE_PATH = "/static/";
    public void init(final FilterConfig filterConfig) throws ServletException {"StaticResourceFilter initialized");

    public void doFilter(final ServletRequest request, final ServletResponse response,
                         final FilterChain chain) throws IOException, ServletException {

        String path = ((HttpServletRequest) request).getServletPath();
        if (path.toLowerCase().startsWith(RESOURCE_PATH)) {
            request.getRequestDispatcher(path).forward(request, response);
        } else {
            chain.doFilter(request, response);

    public void destroy() {"StaticResourceFilter destroyed");

Unfortunately if you just want to skip a single step in the filter chain while keeping those that follows, this will not work.

Uninstall Django completely

open the CMD and use this command :


pip uninstall django


it will easy uninstalled .

H.264 file size for 1 hr of HD video

It would be a couple of gigs per hour.

MPEG-4 (of which H.264 is a sub-part) define high quality as around 4Mbps. which would be 1.8GB per hour.

This can vary depending on the type of video and the type of compression used.

Difference between style = "position:absolute" and style = "position:relative"

Relative positioning: The element creates its own coordinate axes, at a location offset from the viewport coordinate axis. It is Part of document flow but shifted.

Absolute positioning: An element searches for the nearest available coordinate axes among its parent elements. The element is then positioned by specifying offsets from this coordinate axis. It is removed from document normal flow.

enter image description here


AttributeError: Module Pip has no attribute 'main'

I faced the same error while using pip on anaconda3 4.4.0 (python 3.6) on windows.

I fixed the problem by the following command:

easy_install pip==18.*  ### installing the latest version pip

Or if lower version pip required, mention the same in the command.

Or you can try installing the lower version and then upgrading the same to latest version as follow:

easy_install pip==9.0.1

easy_install --upgrade pip

.NET NewtonSoft JSON deserialize map to a different property name

If you'd like to use dynamic mapping, and don't want to clutter up your model with attributes, this approach worked for me


var settings = new JsonSerializerSettings();
settings.DateFormatString = "YYYY-MM-DD";
settings.ContractResolver = new CustomContractResolver();
this.DataContext = JsonConvert.DeserializeObject<CountResponse>(jsonString, settings);


public class CustomContractResolver : DefaultContractResolver
    private Dictionary<string, string> PropertyMappings { get; set; }

    public CustomContractResolver()
        this.PropertyMappings = new Dictionary<string, string> 
            {"Meta", "meta"},
            {"LastUpdated", "last_updated"},
            {"Disclaimer", "disclaimer"},
            {"License", "license"},
            {"CountResults", "results"},
            {"Term", "term"},
            {"Count", "count"},

    protected override string ResolvePropertyName(string propertyName)
        string resolvedName = null;
        var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
        return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);

How can I show an image using the ImageView component in javafx and fxml?

ImageView image;

public void initialize(URL url, ResourceBundle rb) {
  image.setImage(new Image ("/about.jpg"));

How to force DNS refresh for a website?

you can't force refresh but you can forward all old ip requests to new one. for a website:

replace [OLD_IP] with old server's ip

replace [NEW_IP] with new server's ip

run & win.

echo "1" > /proc/sys/net/ipv4/ip_forward

iptables -t nat -A PREROUTING -d [OLD_IP] -p tcp --dport 80 -j DNAT --to-destination [NEW_IP]:80

iptables -t nat -A PREROUTING -d [OLD_IP] -p tcp --dport 443 -j DNAT --to-destination [NEW_IP]:443

iptables -t nat -A POSTROUTING -j MASQUERADE

Catch multiple exceptions in one line (except block)

If you frequently use a large number of exceptions, you can pre-define a tuple, so you don't have to re-type them many times.

#This example code is a technique I use in a library that connects with websites to gather data

ConnectErrs  = (URLError, SSLError, SocketTimeoutError, BadStatusLine, ConnectionResetError)

def connect(url, data):
    #do connection and return some data

def some_function(var_a, var_b, ...):
    try: o = connect(url, data)
    except ConnectErrs as e:
        #do the recovery stuff
    blah #do normal stuff you would do if no exception occurred


  1. If you, also, need to catch other exceptions than those in the pre-defined tuple, you will need to define another except block.

  2. If you just cannot tolerate a global variable, define it in main() and pass it around where needed...

How to create timer in angular2

With rxjs 6.2.2 and Angular 6.1.7, I was getting an:

Observable.timer is not a function

error. This was resolved by replacing Observable.timer with timer:

import { timer, Subscription } from 'rxjs';

private myTimerSub: Subscription;    

    const ti = timer(2000,1000);    
    this.myTimerSub = ti.subscribe(t => {    

ngOnDestroy() {    

How do I push a local Git branch to master branch in the remote?

As people mentioned in the comments you probably don't want to do that... The answer from mipadi is absolutely correct if you know what you're doing.

I would say:

git checkout master
git pull               # to update the state to the latest remote master state
git merge develop      # to bring changes to local master from your develop branch
git push origin master # push current HEAD to remote master branch


How to set up Automapper in ASP.NET Core

I want to extend @theutz's answers - namely this line :

// services.AddAutoMapper(typeof(Startup));  // <-- newer automapper version uses this signature.

There is a bug (probably) in AutoMapper.Extensions.Microsoft.DependencyInjection version 3.2.0. (I'm using .NET Core 2.0)

This is tackled in this GitHub issue. If your classes inheriting AutoMapper's Profile class exist outside of assembly where you Startup class is they will probably not be registered if your AutoMapper injection looks like this:


unless you explicitly specify which assemblies to search AutoMapper profiles for.

It can be done like this in your Startup.ConfigureServices:

services.AddAutoMapper(<assembies> or <type_in_assemblies>);

where "assemblies" and "type_in_assemblies" point to the assembly where Profile classes in your application are specified. E.g:

services.AddAutoMapper(typeof(ProfileInOtherAssembly), typeof(ProfileInYetAnotherAssembly));

I suppose (and I put emphasis on this word) that due to following implementation of parameterless overload (source code from GitHub) :

public static IServiceCollection AddAutoMapper(this IServiceCollection services)
     return services.AddAutoMapper(null, AppDomain.CurrentDomain.GetAssemblies());

we rely on CLR having already JITed assembly containing AutoMapper profiles which might be or might not be true as they are only jitted when needed (more details in this StackOverflow question).

<div style display="none" > inside a table not working

Semantically what you are trying is invalid html, table element cannot have a div element as a direct child. What you can do is, get your div element inside a td element and than try to hide it

Excel formula to get week number in month (having Monday)

Jonathan from the ExcelCentral forums suggests:


This formula extracts the week of the year [...] and then subtracts it from the week of the first day in the month to get the week of the month. You can change the day that weeks begin by changing the second argument of both WEEKNUM functions (set to 2 [for Monday] in the above example). For weeks beginning on Sunday, use:


For weeks beginning on Tuesday, use:



I like it better because it's using the built in week calculation functionality of Excel (WEEKNUM).

Replace a string in shell script using a variable

Use this instead

echo $LINE | sed -e 's/12345678/$replace/g'

this works for me just simply remove the quotes

How to use a variable for the database name in T-SQL?

You can also use sqlcmd mode for this (enable this on the "Query" menu in Management Studio).

:setvar dbname "TEST" 



Check this MSDN article to set parameters via the SQLCMD tool.

How to use ImageBackground to set background image for screen in react-native

You have to import background component first to use backgroundimage on your code

Set timeout for webClient.DownloadFile()

My answer comes from here

You can make a derived class, which will set the timeout property of the base WebRequest class:

using System;
using System.Net;

public class WebDownload : WebClient
    /// <summary>
    /// Time in milliseconds
    /// </summary>
    public int Timeout { get; set; }

    public WebDownload() : this(60000) { }

    public WebDownload(int timeout)
        this.Timeout = timeout;

    protected override WebRequest GetWebRequest(Uri address)
        var request = base.GetWebRequest(address);
        if (request != null)
            request.Timeout = this.Timeout;
        return request;

and you can use it just like the base WebClient class.

React component initialize state from props

you could use key value to reset state when need, pass props to state it's not a good practice , because you have uncontrolled and controlled component in one place. Data should be in one place handled read this

How to uncheck a radio button?

function clearForm(){
  $('#frm input[type="text"]').each(function(){
  $('#frm input[type="radio":checked]').each(function(){
      $(this).attr('checked', false);  

The correct selector is: #frm input[type="radio"]:checked not #frm input[type="radio":checked]

jQuery Validation using the class instead of the name value

Here's my solution (requires no jQuery... just JavaScript):

function argsToArray(args) {
  var r = []; for (var i = 0; i < args.length; i++)
  return r;
function bind() {
  var initArgs = argsToArray(arguments);
  var fx =        initArgs.shift();
  var tObj =      initArgs.shift();
  var args =      initArgs;
  return function() {
    return fx.apply(tObj, args.concat(argsToArray(arguments)));
var salutation = argsToArray(document.getElementsByClassName('salutation'));
salutation.forEach(function(checkbox) {
  checkbox.addEventListener('change', bind(function(checkbox, salutation) {
    var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
    if (numChecked >= 4)
      checkbox.checked = false;
  }, null, checkbox, salutation), false);

Put this in a script block at the end of <body> and the snippet will do its magic, limiting the number of checkboxes checked in maximum to three (or whatever number you specify).

Here, I'll even give you a test page (paste it into a file and try it):

<!DOCTYPE html><html><body>
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
    function argsToArray(args) {
      var r = []; for (var i = 0; i < args.length; i++)
      return r;
    function bind() {
      var initArgs = argsToArray(arguments);
      var fx =        initArgs.shift();
      var tObj =      initArgs.shift();
      var args =      initArgs;
      return function() {
        return fx.apply(tObj, args.concat(argsToArray(arguments)));
    var salutation = argsToArray(document.getElementsByClassName('salutation'));
    salutation.forEach(function(checkbox) {
      checkbox.addEventListener('change', bind(function(checkbox, salutation) {
        var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
        if (numChecked >= 3)
          checkbox.checked = false;
      }, null, checkbox, salutation), false);

How do I find which rpm package supplies a file I'm looking for?

The most popular answer is incomplete:

Since this search will generally be performed only for files from installed packages, yum whatprovides is made blisteringly fast by disabling all external repos (the implicit "installed" repo can't be disabled).

yum --disablerepo=* whatprovides <file>

Access cell value of datatable

If you need a weak reference to the cell value:

object field = d.Rows[0][3]


object field = d.Rows[0].ItemArray[3]

Should do it

If you need a strongly typed reference (string in your case) you can use the DataRowExtensions.Field extension method:

string field = d.Rows[0].Field<string>(3);

(make sure System.Data is in listed in the namespaces in this case)

Indexes are 0 based so we first access the first row (0) and then the 4th column in this row (3)

CSS text-decoration underline color

(for fellow googlers, copied from duplicate question) This answer is outdated since text-decoration-color is now supported by most modern browsers.

You can do this via the following CSS rule as an example:


If this rule isn't supported by an older browser, you can use the following solution:

Setting your word with a border-bottom:

a:link {
  color: red;
  text-decoration: none;
  border-bottom: 1px solid blue;
a:hover {
 border-bottom-color: green;

Vue.js get selected option on @change

Use v-model to bind the value of selected option's value. Here is an example.

<select name="LeaveType" @change="onChange($event)" class="form-control" v-model="key">
   <option value="1">Annual Leave/ Off-Day</option>
   <option value="2">On Demand Leave</option>
var vm = new Vue({
    data: {
        key: ""
    methods: {
        onChange(event) {

More reference can been seen from here.

How to rotate portrait/landscape Android emulator?

See the Android documentation on controlling the emulator; it's Ctrl + F11 / Ctrl + F12.

On ThinkPad running Ubuntu, you may try CTRL + Left Arrow Key or Right Arrow Key

Unable to launch the IIS Express Web server

i will suggest one way to fix this issue:

1.Delete the \Documents\IISExpress folder using the following console command: rmdir /s /q "%userprofile%\Documents\IISExpress"

  1. Delete the applicationhost.config file which is placed within the .vs\Config\ folder in your Visual Studio project root folder.

  2. Change the project’s website random URL: within Visual Studio, right-click to the project node in Solution Explorer, then select Properties; navigate through the Web panel, then change the number in the Project Url textbox value.

  3. Add the _CSRUN_DISABLE_WORKAROUNDS Environment System variable with the value of 1 as shown in the following screenshot (thanks to Juan M. Elosegui for reporting this on this SO thread and for the image):

enter image description here

Good Luck !

Avoid trailing zeroes in printf()

I search the string (starting rightmost) for the first character in the range 1 to 9 (ASCII value 49-57) then null (set to 0) each char right of it - see below:

void stripTrailingZeros(void) { 
    //This finds the index of the rightmost ASCII char[1-9] in array
    //All elements to the left of this are nulled (=0)
    int i = 20;
    unsigned char char1 = 0; //initialised to ensure entry to condition below

    while ((char1 > 57) || (char1 < 49)) {
        char1 = sprintfBuffer[i];

    //null chars left of i
    for (int j = i; j < 20; j++) {
        sprintfBuffer[i] = 0;

How to iterate through two lists in parallel?

You want the zip function.

for (f,b) in zip(foo, bar):
    print "f: ", f ,"; b: ", b

Using json_encode on objects in PHP (regardless of scope)

for an array of objects, I used something like this, while following the custom method for php < 5.4:


//transaction is an array of the class transaction
//which implements the method to_json

foreach($transactions as $tran)

echo json_encode($jsArray);

Set height of <div> = to height of another <div> through .css

I am assuming that you have used height attribute at both so i am comparing it with a height left do it with JavaScript.

var right=document.getElementById('rightdiv').style.height;
var left=document.getElementById('leftdiv').style.height;

Another idea can be found here HTML/CSS: Making two floating divs the same height.

How to convert all text to lowercase in Vim

Usually Vu (or VU for uppercase) is enough to turn the whole line into lowercase as V already selects the whole line to apply the action against.

Tilda (~) changes the case of the individual letter, resulting in camel case or the similar.

It is really great how Vim has many many different modes to deal with various occasions and how those modes are neatly organized.

For instance, v - the true visual mode, and the related V - visual line, and Ctrl+Q - visual block modes (what allows you to select blocks, a great feature some other advanced editors also offer usually by holding the Alt key and selecting the text).

Extract Data from PDF and Add to Worksheet

This doesn't seem to work with the Adobe Type library. As soon as it gets to Open, I get a 429 error. Acrobat works fine though...

What is the best way to paginate results in SQL Server

You didn't specify the language nor which driver you are using. Therefore I'm describing it abstractly.

  • Create a scrollable resultset / dataset. This required a primary on the table(s)
  • jump to the end
  • request the row count
  • jump to the start of the page
  • scroll through the rows until the end of the page

How to set default values in Go structs

  1. Force a method to get the struct (the constructor way).

    From this post:

    A good design is to make your type unexported, but provide an exported constructor function like NewMyType() in which you can properly initialize your struct / type. Also return an interface type and not a concrete type, and the interface should contain everything others want to do with your value. And your concrete type must implement that interface of course.

    This can be done by simply making the type itself unexported. You can export the function NewSomething and even the fields Text and DefaultText, but just don't export the struct type something.

  2. Another way to customize it for you own module is by using a Config struct to set default values (Option 5 in the link). Not a good way though.

Password hash function for Excel VBA

Here's a module for calculating SHA1 hashes that is usable for Excel formulas eg. '=SHA1HASH("test")'. To use it, make a new module called 'module_sha1' and copy and paste it all in. This is based on some VBA code from, with changes to support passing it a string, and executable from formulas in Excel cells.

' Based on:
Option Explicit

Private Type FourBytes
    A As Byte
    B As Byte
    C As Byte
    D As Byte
End Type
Private Type OneLong
    L As Long
End Type

Function HexDefaultSHA1(Message() As Byte) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 DefaultSHA1 Message, H1, H2, H3, H4, H5
 HexDefaultSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Function HexSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 xSHA1 Message, Key1, Key2, Key3, Key4, H1, H2, H3, H4, H5
 HexSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Sub DefaultSHA1(Message() As Byte, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 xSHA1 Message, &H5A827999, &H6ED9EBA1, &H8F1BBCDC, &HCA62C1D6, H1, H2, H3, H4, H5
End Sub

Sub xSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 'CA62C1D68F1BBCDC6ED9EBA15A827999 + "abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"
 '"abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"

 Dim U As Long, P As Long
 Dim FB As FourBytes, OL As OneLong
 Dim i As Integer
 Dim W(80) As Long
 Dim A As Long, B As Long, C As Long, D As Long, E As Long
 Dim T As Long

 H1 = &H67452301: H2 = &HEFCDAB89: H3 = &H98BADCFE: H4 = &H10325476: H5 = &HC3D2E1F0

 U = UBound(Message) + 1: OL.L = U32ShiftLeft3(U): A = U \ &H20000000: LSet FB = OL 'U32ShiftRight29(U)

 ReDim Preserve Message(0 To (U + 8 And -64) + 63)
 Message(U) = 128

 U = UBound(Message)
 Message(U - 4) = A
 Message(U - 3) = FB.D
 Message(U - 2) = FB.C
 Message(U - 1) = FB.B
 Message(U) = FB.A

 While P < U
     For i = 0 To 15
         FB.D = Message(P)
         FB.C = Message(P + 1)
         FB.B = Message(P + 2)
         FB.A = Message(P + 3)
         LSet OL = FB
         W(i) = OL.L
         P = P + 4
     Next i

     For i = 16 To 79
         W(i) = U32RotateLeft1(W(i - 3) Xor W(i - 8) Xor W(i - 14) Xor W(i - 16))
     Next i

     A = H1: B = H2: C = H3: D = H4: E = H5

     For i = 0 To 19
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key1), ((B And C) Or ((Not B) And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 20 To 39
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key2), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 40 To 59
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key3), ((B And C) Or (B And D) Or (C And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 60 To 79
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key4), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i

     H1 = U32Add(H1, A): H2 = U32Add(H2, B): H3 = U32Add(H3, C): H4 = U32Add(H4, D): H5 = U32Add(H5, E)
End Sub

Function U32Add(ByVal A As Long, ByVal B As Long) As Long
 If (A Xor B) < 0 Then
     U32Add = A + B
     U32Add = (A Xor &H80000000) + B Xor &H80000000
 End If
End Function

Function U32ShiftLeft3(ByVal A As Long) As Long
 U32ShiftLeft3 = (A And &HFFFFFFF) * 8
 If A And &H10000000 Then U32ShiftLeft3 = U32ShiftLeft3 Or &H80000000
End Function

Function U32ShiftRight29(ByVal A As Long) As Long
 U32ShiftRight29 = (A And &HE0000000) \ &H20000000 And 7
End Function

Function U32RotateLeft1(ByVal A As Long) As Long
 U32RotateLeft1 = (A And &H3FFFFFFF) * 2
 If A And &H40000000 Then U32RotateLeft1 = U32RotateLeft1 Or &H80000000
 If A And &H80000000 Then U32RotateLeft1 = U32RotateLeft1 Or 1
End Function
Function U32RotateLeft5(ByVal A As Long) As Long
 U32RotateLeft5 = (A And &H3FFFFFF) * 32 Or (A And &HF8000000) \ &H8000000 And 31
 If A And &H4000000 Then U32RotateLeft5 = U32RotateLeft5 Or &H80000000
End Function
Function U32RotateLeft30(ByVal A As Long) As Long
 U32RotateLeft30 = (A And 1) * &H40000000 Or (A And &HFFFC) \ 4 And &H3FFFFFFF
 If A And 2 Then U32RotateLeft30 = U32RotateLeft30 Or &H80000000
End Function

Function DecToHex5(ByVal H1 As Long, ByVal H2 As Long, ByVal H3 As Long, ByVal H4 As Long, ByVal H5 As Long) As String
 Dim H As String, L As Long
 DecToHex5 = "00000000 00000000 00000000 00000000 00000000"
 H = Hex(H1): L = Len(H): Mid(DecToHex5, 9 - L, L) = H
 H = Hex(H2): L = Len(H): Mid(DecToHex5, 18 - L, L) = H
 H = Hex(H3): L = Len(H): Mid(DecToHex5, 27 - L, L) = H
 H = Hex(H4): L = Len(H): Mid(DecToHex5, 36 - L, L) = H
 H = Hex(H5): L = Len(H): Mid(DecToHex5, 45 - L, L) = H
End Function

' Convert the string into bytes so we can use the above functions
' From Chris Hulbert:

Public Function SHA1HASH(str)
  Dim i As Integer
  Dim arr() As Byte
  ReDim arr(0 To Len(str) - 1) As Byte
  For i = 0 To Len(str) - 1
   arr(i) = Asc(Mid(str, i + 1, 1))
  Next i
  SHA1HASH = Replace(LCase(HexDefaultSHA1(arr)), " ", "")
End Function

get unique machine id

edit: I just saw you meant in c#. Here is a better way with unmanaged code:

ManagementClass oMClass = new ManagementClass ("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection colMObj = oMCLass.GetInstances();
foreach(ManagementObject objMO in colMObj)

Array.sort() doesn't sort numbers correctly

You can use a sort function :

var myarray=[25, 8, 7, 41]
myarray.sort( function(a,b) { return b - a; } );
// 7 8 25 41

Look at

Opening a .ipynb.txt File

Try the following steps:

  1. Download the file open it in the Juypter Notebook.
  2. Go to File -> Rename and remove the .txt extension from the end; so now the file name has just .ipynb extension.
  3. Now reopen it from the Juypter Notebook.

How to get the next auto-increment id in mysql

This will return auto increment value for the MySQL database and I didn't check with other databases. Please note that if you are using any other database, the query syntax may be different.

FROM information_schema.tables
WHERE table_name = 'your_table_name'
     and table_schema = 'your_database_name';

FROM information_schema.tables
WHERE table_name = 'your_table_name'
     and table_schema = database();

PHP check whether property exists in object or class

If you want to know if a property exists in an instance of a class that you have defined, simply combine property_exists() with isset().

public function hasProperty($property)
    return property_exists($this, $property) && isset($this->$property);

execute shell command from android

Process p;
StringBuffer output = new StringBuffer();
try {
    p = Runtime.getRuntime().exec(params[0]);
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(p.getInputStream()));
    String line = "";
    while ((line = reader.readLine()) != null) {
        output.append(line + "\n");
catch (IOException e) {
} catch (InterruptedException e) {
String response = output.toString();
return response;

How do I find out which computer is the domain controller in Windows programmatically?

With the most simple programming language: DOS batch


Array versus List<T>: When to use which?

Really just answering to add a link which I'm surprised hasn't been mentioned yet: Eric's Lippert's blog entry on "Arrays considered somewhat harmful."

You can judge from the title that it's suggesting using collections wherever practical - but as Marc rightly points out, there are plenty of places where an array really is the only practical solution.

Debug vs Release in CMake

A lot of the answers here are out of date/bad. So I'm going to attempt to answer it better. Granted I'm answering this question in 2020, so it's expected things would change.

How do I run CMake for each target type (debug/release)?

First off Debug/Release are called configurations in cmake (nitpick).

If you are using a single configuration generator (Ninja/Unix-Makefiles)

Then you need a build folder for each configuration.

Like this:

# Configure the build
cmake -S . -B build/Debug -D CMAKE_BUILD_TYPE=Release

# Actually build the binaries
cmake --build build/Debug

For multi-configuration generators it's slightly different (Ninja Multi-Config, Visual Studio)

# Configure the build
cmake -S . -B build

# Actually build the binaries
cmake --build build --config Debug

If you are wondering why this is necessary it's because cmake isn't a build system. It's a meta-build system (IE a build system that build's build systems). This is basically the result of handling build systems that support multiple-configurations in 1 build. If you'd like a deeper understanding I'd suggest reading a bit about cmake in Craig Scott's book "Professional CMake: A Practical Guide

How do I specify debug and release C/C++ flags using CMake?

The modern practice is to use target's and properties.

Here is an example:


# Add this compile definition for debug builds, this same logic works for
# target_compile_options, target_link_options, etc.
target_compile_definitions(foobar PRIVATE

NOTE: How I'm using generator expressions to specify the configuration! Using CMAKE_BUILD_TYPE will result in bad builds for any multi-configuration generator!

Further more sometimes you need to set things globally and not just for one target. Use add_compile_definitions, add_compile_options, etc. Those functions support generator expressions. Don't use old style cmake unless you have to (that path is a land of nightmares)

How do I express that the main executable will be compiled with g++ and one nested library with gcc?

Your last question really doesn't make sense.

How to exclude particular class name in CSS selector?

Method 1

The problem with your code is that you are selecting the .remode_hover that is a descendant of .remode_selected. So the first part of getting your code to work correctly is by removing that space


Then, in order to get the style to not work, you have to override the style set by the :hover. In other words, you need to counter the background-color property. So the final code will be

.reMode_selected.reMode_hover:hover {
.reMode_hover:hover {
  background-color: #f0ac00;


Method 2

An alternative method would be to use :not(), as stated by others. This will return any element that doesn't have the class or property stated inside the parenthesis. In this case, you would put .remode_selected in there. This will target all elements that don't have a class of .remode_selected


However, I would not recommend this method, because of the fact that it was introduced in CSS3, so browser support is not ideal.

Method 3

A third method would be to use jQuery. You can target the .not() selector, which would be similar to using :not() in CSS, but with much better browser support


Permission denied (publickey,keyboard-interactive)

You need to change the sshd_config file in the remote server (probably in /etc/ssh/sshd_config).


PasswordAuthentication no


PasswordAuthentication yes

And then restart the sshd daemon.

Meaning of $? (dollar question mark) in shell scripts

Outputs the result of the last executed unix command

0 implies true
1 implies false

How to get file extension from string in C++

I'd go with boost::filesystem::extension (std::filesystem::path::extension with C++17) but if you cannot use Boost and you just have to verify the extension, a simple solution is:

bool ends_with(const std::string &filename, const std::string &ext)
  return ext.length() <= filename.length() &&
         std::equal(ext.rbegin(), ext.rend(), filename.rbegin());

if (ends_with(filename, ".conf"))
{ /* ... */ }

How to force garbage collection in Java?

YES it is almost possible to forced you have to call to methods in the same order and at the same time this ones are:

System.gc ();
System.runFinalization ();

even if is just one object to clean the use of this two methods at the same time force the garbage collector to use the finalise() method of unreachable object freeing the memory assigned and doing what the finalize() method states.

HOWEVER it is a terrible practice to use the garbage collector because the use of it could introduce an over load to the software that may be even worst than on the memory, the garbage collector has his own thread which is not possible to control plus depending on the algorithm used by the gc could take more time and is consider very inefficient, you should check your software if it worst with the help of the gc because it is definitely broke, a good solution must not depend on the gc.

NOTE: just to keep on mind this will works only if in the finalize method is not a reassignment of the object, if this happens the object will keep alive an it will have a resurrection which is technically possible.

Excel VBA: Copying multiple sheets into new workbook

Rethink your approach. Why would you copy only part of the sheet? You are referring to a named range "WholePrintArea" which doesn't exist. Also you should never use activate, select, copy or paste in your script. These make the "script" vulnerable to user actions and other simultaneous executions. In worst case scenario data ends up in wrong hands.

Storing Images in DB - Yea or Nay?

I would go with the file system approach. As noted by a few others, most web servers are built to send images from a file path. You'll have much higher performance if you don't have to write or stream out BLOB fields from the database. Having filesystem storage for the images makes it easier to setup static pages when the content isn't changing or you want limit the load on the database.

Converting from IEnumerable to List

If you're using an implementation of System.Collections.IEnumerable you can do like following to convert it to a List. The following uses Enumerable.Cast method to convert IEnumberable to a Generic List.

//ArrayList Implements IEnumerable interface
ArrayList _provinces = new System.Collections.ArrayList();

List<string> provinces = _provinces.Cast<string>().ToList();

If you're using Generic version IEnumerable<T>, The conversion is straight forward. Since both are generics, you can do like below,

IEnumerable<int> values = Enumerable.Range(1, 10);
List<int> valueList = values.ToList();

But if the IEnumerable is null, when you try to convert it to a List, you'll get ArgumentNullException saying Value cannot be null.

IEnumerable<int> values2 = null;
List<int> valueList2 = values2.ToList();

enter image description here

Therefore as mentioned in the other answer, remember to do a null check before converting it to a List.

Javascript - removing undefined fields from an object

I prefer to use something like Lodash:

import { pickBy, identity } from 'lodash'

const cleanedObject = pickBy(originalObject, identity)

Note that the identity function is just x => x and its result will be false for all falsy values. So this removes undefined, "", 0, null, ...

If you only want the undefined values removed you can do this:

const cleanedObject = pickBy(originalObject, v => v !== undefined)

It gives you a new object, which is usually preferable over mutating the original object like some of the other answers suggest.

Location of WSDL.exe

And on my Windows 7 machine it is here:

C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools

Note that the file wsdl.exe is portable, in that you can copy it to another windows machine and it works. I have not tried to see if the 4.5 exe will work on a machine that only have .NET 2.0, but this would be interesting to know.

How to label scatterplot points by name?

For all those who don't have the option in Excel (like me), there is a macro which works and is explained here: Very useful

How do I delete all messages from a single queue using the CLI?

IMPORTANT NOTE: This will delete all users and config.



I don't suggest this answer until unless you want to delete data from all of the queues, including users and configs. Just Reset it !!!

rabbitmqctl stop_app
rabbitmqctl reset
rabbitmqctl start_app

How to create a label inside an <input> element?

In my opinion, the best solution involves neither images nor using the input's default value. Rather, it looks something like David Dorward's solution.

It's easy to implement and degrades nicely for screen readers and users with no javascript.

Take a look at the two examples here:

I usually use the second method (labels2) on my forms.

How do I include a pipe | in my linux find -exec command?

You can also pipe to a while loop that can do multiple actions on the file which find locates. So here is one for looking in jar archives for a given java class file in folder with a large distro of jar files

find /usr/lib/eclipse/plugins -type f -name \*.jar | while read jar; do echo $jar; jar tf $jar | fgrep IObservableList ; done

the key point being that the while loop contains multiple commands referencing the passed in file name separated by semicolon and these commands can include pipes. So in that example I echo the name of the matching file then list what is in the archive filtering for a given class name. The output looks like:

/usr/lib/eclipse/plugins/org.eclipse.core.contenttype.source_3.4.1.R35x_v20090826-0451.jar /usr/lib/eclipse/plugins/org.eclipse.core.databinding.observable_1.2.0.M20090902-0800.jar org/eclipse/core/databinding/observable/list/IObservableList.class /usr/lib/eclipse/plugins/ /usr/lib/eclipse/plugins/org.eclipse.jdt.apt.core.source_3.3.202.R35x_v20091130-2300.jar /usr/lib/eclipse/plugins/org.eclipse.cvs.source_1.0.400.v201002111343.jar /usr/lib/eclipse/plugins/

in my bash shell (xubuntu10.04/xfce) it really does make the matched classname bold as the fgrep highlights the matched string; this makes it really easy to scan down the list of hundreds of jar files that were searched and easily see any matches.

on windows you can do the same thing with:

for /R %j in (*.jar) do @echo %j & @jar tf %j | findstr IObservableList

note that in that on windows the command separator is '&' not ';' and that the '@' suppresses the echo of the command to give a tidy output just like the linux find output above; although findstr is not make the matched string bold so you have to look a bit closer at the output to see the matched class name. It turns out that the windows 'for' command knows quite a few tricks such as looping through text files...


The action or event has been blocked by Disabled Mode

On the ribbon,Go to Database Tools under "Show/Hide", make sure the Message bar is checked (turned on) Then click on the gray message bar, click database options. From there you can modify your security options. Just enable these types of content.

You should be good to go after this.

Can I call a base class's virtual function if I'm overriding it?

Sometimes you need to call the base class' implementation, when you aren't in the derived function...It still works:

struct Base
    virtual int Foo()
        return -1;

struct Derived : public Base
    virtual int Foo()
        return -2;

int main(int argc, char* argv[])
    Base *x = new Derived;

    ASSERT(-2 == x->Foo());

    //syntax is trippy but it works
    ASSERT(-1 == x->Base::Foo());

    return 0;

Using Javascript can you get the value from a session attribute set by servlet in the HTML page

Below code may help you to achieve session attribution inside java script:

var name = '<%= session.getAttribute("username") %>';

python pip: force install ignoring dependencies

pip has a --no-dependencies switch. You should use that.

For more information, run pip install -h, where you'll see this line:

--no-deps, --no-dependencies
                        Ignore package dependencies

How to echo out the values of this array?

foreach ($array as $key => $val) {
   echo $val;

How can I get a process handle by its name in C++?

If you don't mind using system(), doing system("taskkill /f /im process.exe") would be significantly easier than these other methods.

Print an integer in binary format in Java

The question is tricky in java (and probably also in other language).

A Integer is a 32-bit signed data type, but Integer.toBinaryString() returns a string representation of the integer argument as an unsigned integer in base 2.

So, Integer.parseInt(Integer.toBinaryString(X),2) can generate an exception (signed vs. unsigned).

The safe way is to use Integer.toString(X,2); this will generate something less elegant:


But it works!!!

jQuery: get parent, parent id?


Is how you would get the id of the parent's parent.



Is a more foolproof solution for your case.

Python - Dimension of Data Frame

Summary of all ways to get info on dimensions of DataFrame or Series

There are a number of ways to get information on the attributes of your DataFrame or Series.

Create Sample DataFrame and Series

df = pd.DataFrame({'a':[5, 2, np.nan], 'b':[ 9, 2, 4]})

     a  b
0  5.0  9
1  2.0  2
2  NaN  4

s = df['a']

0    5.0
1    2.0
2    NaN
Name: a, dtype: float64

shape Attribute

The shape attribute returns a two-item tuple of the number of rows and the number of columns in the DataFrame. For a Series, it returns a one-item tuple.

(3, 2)


len function

To get the number of rows of a DataFrame or get the length of a Series, use the len function. An integer will be returned.



size attribute

To get the total number of elements in the DataFrame or Series, use the size attribute. For DataFrames, this is the product of the number of rows and the number of columns. For a Series, this will be equivalent to the len function:



ndim attribute

The ndim attribute returns the number of dimensions of your DataFrame or Series. It will always be 2 for DataFrames and 1 for Series:



The tricky count method

The count method can be used to return the number of non-missing values for each column/row of the DataFrame. This can be very confusing, because most people normally think of count as just the length of each row, which it is not. When called on a DataFrame, a Series is returned with the column names in the index and the number of non-missing values as the values.

df.count() # by default, get the count of each column

a    2
b    3
dtype: int64

df.count(axis='columns') # change direction to get count of each row

0    2
1    2
2    1
dtype: int64

For a Series, there is only one axis for computation and so it just returns a scalar:


Use the info method for retrieving metadata

The info method returns the number of non-missing values and data types of each column

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
a    2 non-null float64
b    3 non-null int64
dtypes: float64(1), int64(1)
memory usage: 128.0 bytes

"Prevent saving changes that require the table to be re-created" negative effects

SQL Server drops and recreates the tables only if you:

  • Add a new column
  • Change the Allow Nulls setting for a column
  • Change the column order in the table
  • Change the column data type

Using ALTER is safer, as in case the metadata is lost while you re-create the table, your data will be lost.

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

Try using No Wrap - In Head or No wrap - in body in your fiddle:

Working fiddle:


Angular begins compiling the DOM when the DOM is fully loaded. You register your code to run onLoad (onload option in fiddle) => it's too late to register your myApp module because angular begins compiling the DOM and angular sees that there is no module named myApp and throws an exception.

By using No Wrap - In Head, your code looks like this:


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

    <script type='text/javascript'>
      //Your script.


Your script has a chance to run before angular begins compiling the DOM and myApp module is already created when angular starts compiling the DOM.

Conditional statement in a one line lambda function in python?

In case you want to be lazier:

#syntax lambda x : (false,true)[Condition]

In your case:

rate = lambda(T) : (400*exp(-T),200*exp(-T))[T>200]

Limiting Powershell Get-ChildItem by File Creation Date Range

Fixed it...

Get-ChildItem C:\Windows\ -recurse -include @("*.txt*","*.pdf") |
Where-Object {$_.CreationTime -gt "01/01/2013" -and $_.CreationTime -lt "12/02/2014"} | 
Select-Object FullName, CreationTime, @{Name="Mbytes";Expression={$_.Length/1Kb}}, @{Name="Age";Expression={(((Get-Date) - $_.CreationTime).Days)}} | 
Export-Csv C:\search_TXT-and-PDF_files_01012013-to-12022014_sort.txt

Laravel Request getting current path with query string

Similar to Yada's answer: $request->url() will also work if you are injecting Illuminate\Http\Request

Edit: The difference between fullUrl and url is the fullUrl includes your query parameters

Eloquent Collection: Counting and Detect Empty

You can use: $counter = count($datas);

Url.Action parameters?

Here is another simple way to do it

<a class="nav-link"
   href='@Url.Action("Print1", "DeviceCertificates", new { Area = "Diagnostics"})\@Model.ID'>Print</a>

Where is @Model.ID is a parameter

And here there is a second example.

<a class="nav-link"
   href='@Url.Action("Print1", "DeviceCertificates", new { Area = "Diagnostics"})\@Model.ID?param2=ViewBag.P2&param3=ViewBag.P3'>Print</a>

Is it possible to get only the first character of a String?

The string has a substring method that returns the string at the specified position.

String name="123456789";

Sending email through Gmail SMTP server with C#

I was getting the same error and none of the above solutions helped.

My problem was that I was running the code from a remote server, which had never been used to log into the gmail account.

I opened a browser on the remote server and logged into gmail from there. It asked a security question to verify it was me since this was a new location. After doing the security check I was able to authenticate through code.

Create PDF from a list of images

I know the question has been answered but one more way to solve this is using the pillow library. To convert a whole directory of images:

from PIL import Image
import os

def makePdf(imageDir, SaveToDir):
        imageDir: Directory of your images
        SaveToDir: Location Directory for your pdfs
        for j in os.listdir(os.getcwd()):
            fname, fext = os.path.splitext(j)
            newfilename = fname + ".pdf"
            im = + fext)
            if im.mode == "RGBA":
                im = im.convert("RGB")
            if not os.path.exists(newfilename):
      , "PDF", resolution=100.0)
    except Exception as e:

imageDir = r'____' # your imagedirectory path
SaveToDir = r'____' # diretory in which you want to save the pdfs
makePdf(imageDir, SaveToDir)

For using it on an single image:

From PIL import Image
import os

filename = r"/Desktop/document/dog.png"
im =
if im.mode == "RGBA":
    im = im.convert("RGB")
new_filename = r"/Desktop/document/dog.pdf"
if not os.path.exists(new_filename):,"PDF",resolution=100.0)

Django Reverse with arguments '()' and keyword arguments '{}' not found

Resolve is also more straightforward

from django.urls import resolve

resolve('edit_project', project_id=4)

Documentation on this shortcut

How to find the privileges and roles granted to a user in Oracle?

always make SQL re-usuable: -:)

-- ===================================================
-- &role_name will be "enter value for 'role_name'".
-- Date:  2015 NOV 11.

-- sample code:   define role_name=&role_name
-- sample code:   where role like '%&&role_name%'
-- ===================================================

define role_name=&role_name

select * from ROLE_ROLE_PRIVS where ROLE = '&&role_name';
select * from ROLE_SYS_PRIVS  where ROLE = '&&role_name';

select role, privilege,count(*)
where ROLE = '&&role_name'
group by role, privilege
order by role, privilege asc

How to disable an Android button?

In Java, once you have the reference of the button:

Button button = (Button) findviewById(;

To enable/disable the button, you can use either:




Since you want to disable the button from the beginning, you can use button.setEnabled(false); in the onCreate method. Otherwise, from XML, you can directly use:

android:clickable = "false"


        android:clickable = "false" />

Cannot read property 'addEventListener' of null

It's just bcz your JS gets loaded before the HTML part and so it can't find that element. Just put your whole JS code inside a function which will be called when the window gets loaded.

You can also put your Javascript code below the html.

Permission is only granted to system app

To ignore this error for one instance only, add the tools:ignore="ProtectedPermissions" attribute to your permission declaration. Here is an example:

<uses-permission android:name="android.permission.READ_PRIVILEGED_PHONE_STATE"
    tools:ignore="ProtectedPermissions" />

You have to add tools namespace in the manifest root element

<manifest xmlns:android=""

Apply CSS rules if browser is IE

In browsers up to and including IE9, this is done through conditional comments.

<!--[if IE]>
<style type="text/css">
  IE specific CSS rules go here

Google Geocoding API - REQUEST_DENIED

I got this problem as well using the drupal 7 Location module. Autofilling all empty locations resulted in this error. Executing one of the requests to the location api manually resulted in this error in the returned JSON:

"Browser API keys cannot have referer restrictions when used with this API."

Resolving the problem then was easy: create a new key without any restrictions and use it only for Geocoding.

Note for those new to google api keys: by restrictions they mean limiting requests using an api key to specific domains / subdomains. (eg. only request from are allowed).

How to convert list of key-value tuples into dictionary?

Another way using dictionary comprehensions,

>>> t = [('A', 1), ('B', 2), ('C', 3)]
>>> d = { i:j for i,j in t }
>>> d
{'A': 1, 'B': 2, 'C': 3}

Querying date field in MongoDB with Mongoose

{ "date" : "1000000" } in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }

It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback) and if that works, you have a typing issue.

How to check if array is not empty?

with a as a numpy array, use:

if a.size:
   print('array is not empty')

(in Python, objects like [1,2,3] are called lists, not arrays.)

Using JQuery hover with HTML image map

You should check out this plugin:

and the demo:

if anything, you might be able to borrow some code from it to fix yours.

How to access POST form fields

I could find all parameters by using following code for both POST and GET requests.

var express = require('express');
var app = express();
const util = require('util');'/', function (req, res) {
    console.log("Got a POST request for the homepage");

How to build a 'release' APK in Android Studio?

Click \Build\Select Build Variant... in Android Studio. And choose release.