Programs & Examples On #Clientaccesspolicy.xml

clientaccesspolicy.xml file enables cross-domain access in Silverlight

Import SQL dump into PostgreSQL database

Just for funsies, if your dump is compressed you can do something like

gunzip -c filename.gz | psql dbname

As Jacob mentioned, the PostgreSQL docs describe all this quite well.

Changing cursor to waiting in javascript/jquery

In your jQuery use:

$("body").css("cursor", "progress");

and then back to normal again

$("body").css("cursor", "default");

Servlet for serving static content

Judging from the example information above, I think this entire article is based on a bugged behavior in Tomcat 6.0.29 and earlier. See Upgrade to Tomcat 6.0.30 and the behavior between (Tomcat|Jetty) should merge.

Richtextbox wpf binding

Most of my needs were satisfied by this answer by krzysztof. But one issue with that code (i faced was), the binding won't work with multiple controls. So I changed _recursionProtection with a Guid based implementation. So it's working for Multiple controls in same window as well.

 public class RichTextBoxHelper : DependencyObject
        private static List<Guid> _recursionProtection = new List<Guid>();

        public static string GetDocumentXaml(DependencyObject obj)
            return (string)obj.GetValue(DocumentXamlProperty);

        public static void SetDocumentXaml(DependencyObject obj, string value)
            var fw1 = (FrameworkElement)obj;
            if (fw1.Tag == null || (Guid)fw1.Tag == Guid.Empty)
                fw1.Tag = Guid.NewGuid();
            obj.SetValue(DocumentXamlProperty, value);

        public static readonly DependencyProperty DocumentXamlProperty = DependencyProperty.RegisterAttached(
            new FrameworkPropertyMetadata(
                FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
                (obj, e) =>
                    var richTextBox = (RichTextBox)obj;
                    if (richTextBox.Tag != null && _recursionProtection.Contains((Guid)richTextBox.Tag))

                    // Parse the XAML to a document (or use XamlReader.Parse())

                        string docXaml = GetDocumentXaml(richTextBox);
                        var stream = new MemoryStream(Encoding.UTF8.GetBytes(docXaml));
                        FlowDocument doc;
                        if (!string.IsNullOrEmpty(docXaml))
                            doc = (FlowDocument)XamlReader.Load(stream);
                            doc = new FlowDocument();

                        // Set the document
                        richTextBox.Document = doc;
                    catch (Exception)
                        richTextBox.Document = new FlowDocument();

                    // When the document changes update the source
                    richTextBox.TextChanged += (obj2, e2) =>
                            RichTextBox richTextBox2 = obj2 as RichTextBox;
                            if (richTextBox2 != null)
                                SetDocumentXaml(richTextBox, XamlWriter.Save(richTextBox2.Document));

For completeness sake, let me add few more lines from original answer by ray-burns. This is how to use the helper.

<RichTextBox local:RichTextBoxHelper.DocumentXaml="{Binding Autobiography}" />

String comparison: InvariantCultureIgnoreCase vs OrdinalIgnoreCase?

You seem to be doing file name comparisons, so I would just add that OrdinalIgnoreCase is closest to what NTFS does (it's not exactly the same, but it's closer than InvariantCultureIgnoreCase)

Java: Reading integers from a file into an array

You must have an empty line in your file.

You may want to wrap your parseInt calls in a "try" block:

try {
  tall[i++] = Integer.parseInt(s);
catch (NumberFormatException ex) {

Or simply check for empty strings before parsing:

if (s.length() == 0) 

Note that by initializing your index variable i inside the loop, it is always 0. You should move the declaration before the while loop. (Or make it part of a for loop.)

How do I open port 22 in OS X 10.6.7

I couldn't solve the problem; Then I did the following and the issue was resolved: Refer here:

sudo launchctl unload -w /System/Library/LaunchDaemons/ssh.plist  
    (Supply your password when it is requested)   
sudo launchctl load -w /System/Library/LaunchDaemons/ssh.plist  
ssh -v localhost  
sudo launchctl list | grep "sshd"  
    46427   -   com.openssh.sshd  

Twitter Bootstrap - how to center elements horizontally or vertically

I like this solution from a similar question. Use bootstraps text-center class on the actual table data <td> and table header <th> elements. So

<td class="text-center">Cell data</td>


<th class="text-center">Header cell data</th>

Android SDK Setup under Windows 7 Pro 64 bit

When it says JDK not found, just press ‘back’ button and then press again ‘next’ button..

I got this from the bottom of this post:

Maven dependency update on commandline

Simple run your project online i.e mvn clean install . It fetches all the latest dependencies that you mention in your pom.xml and built the project

How do you convert WSDLs to Java classes using Eclipse?

You need to do next in command line:

wsimport -keep -s (name of folder where you want to store generated code) urlToWsdl

for example:

wsimport -keep -s C://NewFolder

Place API key in Headers or URL

It is better to use API Key in header, not in URL.

URLs are saved in browser's history if it is tried from browser. It is very rare scenario. But problem comes when the backend server logs all URLs. It might expose the API key.

In two ways, you can use API Key in header

Basic Authorization:

Example from stripe:

curl -u sk_test_BQokikJOvBiI2HlWgH4olfQ2:

curl uses the -u flag to pass basic auth credentials (adding a colon after your API key will prevent it from asking you for a password).

Custom Header

curl -H "X-API-KEY: 6fa741de1bdd1d91830ba"

What is "entropy and information gain"?

I can't give you graphics, but maybe I can give a clear explanation.

Suppose we have an information channel, such as a light that flashes once every day either red or green. How much information does it convey? The first guess might be one bit per day. But what if we add blue, so that the sender has three options? We would like to have a measure of information that can handle things other than powers of two, but still be additive (the way that multiplying the number of possible messages by two adds one bit). We could do this by taking log2(number of possible messages), but it turns out there's a more general way.

Suppose we're back to red/green, but the red bulb has burned out (this is common knowledge) so that the lamp must always flash green. The channel is now useless, we know what the next flash will be so the flashes convey no information, no news. Now we repair the bulb but impose a rule that the red bulb may not flash twice in a row. When the lamp flashes red, we know what the next flash will be. If you try to send a bit stream by this channel, you'll find that you must encode it with more flashes than you have bits (50% more, in fact). And if you want to describe a sequence of flashes, you can do so with fewer bits. The same applies if each flash is independent (context-free), but green flashes are more common than red: the more skewed the probability the fewer bits you need to describe the sequence, and the less information it contains, all the way to the all-green, bulb-burnt-out limit.

It turns out there's a way to measure the amount of information in a signal, based on the the probabilities of the different symbols. If the probability of receiving symbol xi is pi, then consider the quantity

-log pi

The smaller pi, the larger this value. If xi becomes twice as unlikely, this value increases by a fixed amount (log(2)). This should remind you of adding one bit to a message.

If we don't know what the symbol will be (but we know the probabilities) then we can calculate the average of this value, how much we will get, by summing over the different possibilities:

I = -Σ pi log(pi)

This is the information content in one flash.

Red bulb burnt out: pred = 0, pgreen=1, I = -(0 + 0)  = 0
Red and green equiprobable: pred = 1/2, pgreen = 1/2, I = -(2 * 1/2 * log(1/2)) = log(2)
Three colors, equiprobable: pi=1/3, I = -(3 * 1/3 * log(1/3)) = log(3)
Green and red, green twice as likely: pred=1/3, pgreen=2/3, I = -(1/3 log(1/3) + 2/3 log(2/3)) = log(3) - 2/3 log(2)

This is the information content, or entropy, of the message. It is maximal when the different symbols are equiprobable. If you're a physicist you use the natural log, if you're a computer scientist you use log2 and get bits.

Disabling radio buttons with jQuery

You can try this code.

var radioBtn = $('<input type="radio" name="ticketID1" value="myvalue1">');
if('some condition'){
    $(radioBtn).attr('disabled', true); // Disable the radio button.
    $('.span_class').css('opacity', '.2'); // Set opacity to .2 to mute the text in front of the radio button.
    $(radioBtn).attr('disabled', false);
    $('.span_class').css('opacity', '1');

Ignore outliers in ggplot2 boxplot

Here is a solution using boxplot.stats

# create a dummy data frame with outliers
df = data.frame(y = c(-100, rnorm(100), 100))

# create boxplot that includes outliers
p0 = ggplot(df, aes(y = y)) + geom_boxplot(aes(x = factor(1)))

# compute lower and upper whiskers
ylim1 = boxplot.stats(df$y)$stats[c(1, 5)]

# scale y limits based on ylim1
p1 = p0 + coord_cartesian(ylim = ylim1*1.05)

Search for executable files using find command

On GNU versions of find you can use -executable:

find . -type f -executable -print

For BSD versions of find, you can use -perm with + and an octal mask:

find . -type f -perm +111 -print

In this context "+" means "any of these bits are set" and 111 is the execute bits.

Note that this is not identical to the -executable predicate in GNU find. In particular, -executable tests that the file can be executed by the current user, while -perm +111 just tests if any execute permissions are set.

Older versions of GNU find also support the -perm +111 syntax, but as of 4.5.12 this syntax is no longer supported. Instead, you can use -perm /111 to get this behavior.

How to get element by classname or id

If you want to find the button only by its class name and using jQLite only, you can do like below:

var myListButton = $document.find('button').filter(function() {
    return angular.element(this).hasClass('multi-files');

Hope this helps. :)

document.createElement("script") synchronously

You can create your <script> element with an "onload" handler, and that will be called when the script has been loaded and evaluated by the browser.

var script = document.createElement('script');
script.onload = function() {
  alert("Script loaded and ready");
script.src = "";

You can't do it synchronously.

edit — it's been pointed out that, true to form, IE doesn't fire a "load" event on <script> tags being loaded/evaluated. Thus I suppose the next thing to do would be to fetch the script with an XMLHttpRequest and then eval() it yourself. (Or, I suppose, stuff the text into a <script> tag you add; the execution environment of eval() is affected by the local scope, so it won't necessarily do what you want it to do.)

editAs of early 2013, I'd strongly advise looking into a more robust script loading tool like Requirejs. There are a lot of special cases to worry about. For really simple situations, there's yepnope, which is now built into Modernizr.

Programmatically create a UIView with color gradient

I've extended the accepted answer a little using Swift's extension functionality as well as an enum.

Oh and if you are using Storyboard like I do, make sure to call gradientBackground(from:to:direction:) in viewDidLayoutSubviews() or later.

Swift 3

enum GradientDirection {
    case leftToRight
    case rightToLeft
    case topToBottom
    case bottomToTop

extension UIView {
    func gradientBackground(from color1: UIColor, to color2: UIColor, direction: GradientDirection) {
        let gradient = CAGradientLayer()
        gradient.frame = self.bounds
        gradient.colors = [color1.cgColor, color2.cgColor]

        switch direction {
        case .leftToRight:
            gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
            gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
        case .rightToLeft:
            gradient.startPoint = CGPoint(x: 1.0, y: 0.5)
            gradient.endPoint = CGPoint(x: 0.0, y: 0.5)
        case .bottomToTop:
            gradient.startPoint = CGPoint(x: 0.5, y: 1.0)
            gradient.endPoint = CGPoint(x: 0.5, y: 0.0)

        self.layer.insertSublayer(gradient, at: 0)

How to give the background-image path in CSS?

Your css is here: Project/Web/Support/Styles/file.css

1 time ../ means Project/Web/Support and 2 times ../ i.e. ../../ means Project/Web


background-image: url('../../images/image.png');

How do you define a class of constants in Java?

My suggestions (in decreasing order of preference):

1) Don't do it. Create the constants in the actual class where they are most relevant. Having a 'bag of constants' class/interface isn't really following OO best practices.

I, and everyone else, ignore #1 from time to time. If you're going to do that then:

2) final class with private constructor This will at least prevent anyone from abusing your 'bag of constants' by extending/implementing it to get easy access to the constants. (I know you said you wouldn't do this -- but that doesn't mean someone coming along after you won't)

3) interface This will work, but not my preference giving the possible abuse mention in #2.

In general, just because these are constants doesn't mean you shouldn't still apply normal oo principles to them. If no one but one class cares about a constant - it should be private and in that class. If only tests care about a constant - it should be in a test class, not production code. If a constant is defined in multiple places (not just accidentally the same) - refactor to eliminate duplication. And so on - treat them like you would a method.

How do I extract data from a DataTable?

You can set the datatable as a datasource to many elements.

For eg




etc etc

If you need to extract data from each row then you can use



if you know the column name


If you need to iterate the table then you can either use a for loop or a foreach loop like

for ( int i = 0; i < table.rows.length; i ++ )
    string name = table.rows[i]["columnname"].ToString();

foreach ( DataRow dr in table.Rows )
    string name = dr["columnname"].ToString();

How can JavaScript save to a local file?

It all depends on what you are trying to achieve with "saving locally". Do you want to allow the user to download the file? then <a download> is the way to go. Do you want to save it locally, so you can restore your application state? Then you might want to look into the various options of WebStorage. Specifically localStorage or IndexedDB. The FilesystemAPI allows you to create local virtual file systems you can store arbitrary data in.

How to find serial number of Android device?

TelephonyManager tManager = (TelephonyManager)myActivity.getSystemService(Context.TELEPHONY_SERVICE);
String uid = tManager.getDeviceId();

getSystemService is a method from the Activity class. getDeviceID() will return the MDN or MEID of the device depending on which radio the phone uses (GSM or CDMA).

Each device MUST return a unique value here (assuming it's a phone). This should work for any Android device with a sim slot or CDMA radio. You're on your own with that Android powered microwave ;-)

use jQuery to get values of selected checkboxes

So all in one line:

var checkedItemsAsString = $('[id*="checkbox"]:checked').map(function() { return $(this).val().toString(); } ).get().join(",");

..a note about the selector [id*="checkbox"] , it will grab any item with the string "checkbox" in it. A bit clumsy here, but really good if you are trying to pull the selected values out of something like a .NET CheckBoxList. In that case "checkbox" would be the name that you gave the CheckBoxList control.

How to check if JSON return is empty with jquery

Below code(jQuery.isEmptyObject(anyObject) function is already provided) works perfectly fine, no need to write one of your own.

   // works for any Object Including JSON(key value pair) or Array.
  //  var arr = [];
  //  var jsonObj = {};
    if (jQuery.isEmptyObject(anyObjectIncludingJSON))
       console.log("Empty Object");

Is there a "not equal" operator in Python?

There's the != (not equal) operator that returns True when two values differ, though be careful with the types because "1" != 1. This will always return True and "1" == 1 will always return False, since the types differ. Python is dynamically, but strongly typed, and other statically typed languages would complain about comparing different types.

There's also the else clause:

# This will always print either "hi" or "no hi" unless something unforeseen happens.
if hi == "hi":     # The variable hi is being compared to the string "hi", strings are immutable in Python, so you could use the 'is' operator.
    print "hi"     # If indeed it is the string "hi" then print "hi"
else:              # hi and "hi" are not the same
    print "no hi"

The is operator is the object identity operator used to check if two objects in fact are the same:

a = [1, 2]
b = [1, 2]
print a == b # This will print True since they have the same values
print a is b # This will print False since they are different objects.

Run-time error '3061'. Too few parameters. Expected 1. (Access 2007)

My problem was also solved by the Single Quotes around the variable name

Sending an Intent to browser to open specific URL

The shortest version.

startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("")));

Search an Oracle database for tables with specific column names?

The data you want is in the "cols" meta-data table:


This one will give you a list of tables that have all of the columns you want:

select distinct
  cols c1
  inner join
  cols c2
  inner join
  cols c3
  inner join
  cols c4
  inner join
  tab t
where T.TABTYPE = 'TABLE' --could be 'VIEW' if you wanted
  and upper(C1.COLUMN_NAME) like upper('%id%')
  and upper(C2.COLUMN_NAME) like upper('%fname%')
  and upper(C3.COLUMN_NAME) like upper('%lname%')
  and upper(C4.COLUMN_NAME) like upper('%address%')  

To do this in a different schema, just specify the schema in front of the table, as in


If you want to combine the searches of many schemas into one output result, then you could do this:


Unable to run 'adb root' on a rooted Android phone

I finally found out how to do this! Basically you need to run adb shell first and then while you're in the shell run su, which will switch the shell to run as root!

$: adb shell
$: su

The one problem I still have is that sqlite3 is not installed so the command is not recognized.

How to extract a string between two delimiters

Try as

String s = "ABC[ This is to extract ]";
        Pattern p = Pattern.compile(".*\\[ *(.*) *\\].*");
        Matcher m = p.matcher(s);
        String text =;

implementing merge sort in C++

The problem with merge sort is the merge, if you don't actually need to implement the merge, then it is pretty simple (for a vector of ints):

#include <algorithm>
#include <vector>
using namespace std;

typedef vector<int>::iterator iter;

void mergesort(iter b, iter e) {
    if (e -b > 1) {
        iter m = b + (e -b) / 2;
        mergesort(b, m);
        mergesort(m, e);
        inplace_merge(b, m, e);

How do I adb pull ALL files of a folder present in SD Card

if your using jellybean just start cmd, type adb devices to make sure your readable, type adb pull sdcard/ sdcard_(the date or extra) <---this file needs to be made in adb directory beforehand. PROFIT!

In other versions type adb pull mnt/sdcard/ sdcard_(the date or extra)

Remember to make file or your either gonna have a mess or it wont work.

Linux shell sort file according to the second column?

sort -nk2 file.txt

Accordingly you can change column number.

Make TextBox uneditable

Use the ReadOnly property on the TextBox.

myTextBox.ReadOnly = true;

But Remember: TextBoxBase.ReadOnly Property

When this property is set to true, the contents of the control cannot be changed by the user at runtime. With this property set to true, you can still set the value of the Text property in code. You can use this feature instead of disabling the control with the Enabled property to allow the contents to be copied and ToolTips to be shown.

Difference between text and varchar (character varying)

text and varchar have different implicit type conversions. The biggest impact that I've noticed is handling of trailing spaces. For example ...

select ' '::char = ' '::varchar, ' '::char = ' '::text, ' '::varchar = ' '::text

returns true, false, true and not true, true, true as you might expect.

Jquery/Ajax Form Submission (enctype="multipart/form-data" ). Why does 'contentType:False' cause undefined index in PHP?

contentType option to false is used for multipart/form-data forms that pass files.

When one sets the contentType option to false, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multipart/form-data, one must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.

To try and fix your issue:

Use jQuery's .serialize() method which creates a text string in standard URL-encoded notation.

You need to pass un-encoded data when using contentType: false.

Try using new FormData instead of .serialize():

  var formData = new FormData($(this)[0]);

See for yourself the difference of how your formData is passed to your php page by using console.log().

  var formData = new FormData($(this)[0]);

  var formDataSerialized = $(this).serialize();

Can't connect to local MySQL server through socket '/tmp/mysql.sock

Using MacOS Mojave 10.14.6 for MySQL 8.0.19 installed via Homebrew

  • Ran sudo find / -name my.cnf
  • File found at /usr/local/etc/my.cnf

Worked for a time then eventually the error returned. Uninstalled the Homebrew version of MySQL and installed the .dmg file directly from here

Happily connecting since then.

Add column to SQL query results

Manually add it when you build the query:

SELECT 'Site1' AS SiteName, t1.column, t1.column2

SELECT 'Site2' AS SiteName, t2.column, t2.column2



DECLARE @t1 TABLE (column1 int, column2 nvarchar(1))
DECLARE @t2 TABLE (column1 int, column2 nvarchar(1))

SELECT 1, 'a'

SELECT 3, 'c'

SELECT 'Site1' AS SiteName, t1.column1, t1.column2
FROM @t1 t1

SELECT 'Site2' AS SiteName, t2.column1, t2.column2
FROM @t2 t2


SiteName  column1  column2
Site1       1      a
Site1       2      b
Site2       3      c
Site2       4      d

What are static factory methods?

We avoid providing direct access to database connections because they're resource intensive. So we use a static factory method getDbConnection that creates a connection if we're below the limit. Otherwise, it tries to provide a "spare" connection, failing with an exception if there are none.

public class DbConnection{
   private static final int MAX_CONNS = 100;
   private static int totalConnections = 0;

   private static Set<DbConnection> availableConnections = new HashSet<DbConnection>();

   private DbConnection(){
     // ...

   public static DbConnection getDbConnection(){

     if(totalConnections < MAX_CONNS){
       return new DbConnection();

     }else if(availableConnections.size() > 0){
         DbConnection dbc = availableConnections.iterator().next();
         return dbc;

     }else {
         throw new NoDbConnections();

   public static void returnDbConnection(DbConnection dbc){

Invoke-WebRequest, POST with parameters

For some picky web services, the request needs to have the content type set to JSON and the body to be a JSON string. For example:

Invoke-WebRequest -UseBasicParsing -ContentType "application/json" -Method POST -Body "{ 'ItemID':3661515, 'Name':'test'}"

or the equivalent for XML, etc.

Python error: AttributeError: 'module' object has no attribute

The way I would do it is to leave the __ files empty, and do:

import lib.mod1.mod11


from lib.mod1.mod11 import mod12

You may find that the mod1 dir is unnecessary, just have in lib.

Android check internet connection

Use this method:

public static boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) context
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();

This is the permission needed:

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

How to select all instances of a variable and edit variable name in Sublime

It's mentioned by @watsonic that in Sublime Text 3 on Mac OS, starting with an empty selection, simply ^?G (AltF3 on Windows) does the trick, instead of ?D + ^?G in Sublime Text 2.

Compare two different files line by line in python

Try this:

from __future__ import with_statement

filename1 = "G:\\test1.TXT"
filename2 = "G:\\test2.TXT"

with open(filename1) as f1:
   with open(filename2) as f2:
      file1list =
      file2list =
      list1length = len(file1list)
      list2length = len(file2list)
      if list1length == list2length:
          for index in range(len(file1list)):
              if file1list[index] == file2list[index]:
                  print file1list[index] + "==" + file2list[index]
                  print file1list[index] + "!=" + file2list[index]+" Not-Equel"
          print "difference inthe size of the file and number of lines"

How to create two columns on a web page?

i recommend to look this article

see 4. Place the columns side by side special

To make the two columns (#main and #sidebar) display side by side we float them, one to the left and the other to the right. We also specify the widths of the columns.

    #main {
    #sidebar {

Note that the sum of the widths should be equal to the width given to #wrap in Step 3.

HTTP vs HTTPS performance

The overhead is NOT due to the encryption. On a modern CPU, the encryption required by SSL is trivial.

The overhead is due to the SSL handshakes, which are lengthy and drastically increase the number of round-trips required for a HTTPS session over a HTTP one.

Measure (using a tool such as Firebug) the page load times while the server is on the end of a simulated high-latency link. Tools exist to simulate a high latency link - for Linux there is "netem". Compare HTTP with HTTPS on the same setup.

The latency can be mitigated to some extent by:

  • Ensuring that your server is using HTTP keepalives - this allows the client to reuse SSL sessions, which avoids the need for another handshake
  • Reducing the number of requests to as few as possible - by combining resources where possible (e.g. .js include files, CSS) and encouraging client-side caching
  • Reduce the number of page loads, e.g. by loading data not required into the page (perhaps in a hidden HTML element) and then showing it using client-script.

Node.js Error: connect ECONNREFUSED

Run server.js from a different command line and client.js from a different command line

How to compile and run C in sublime text 3?

The code that worked for me on a Windows 10 machine using Sublime Text 3

 "cmd" : "gcc $file_name -o ${file_base_name}",
 "selector" : "source.c",
 "shell" : true,
 "working_dir" : "$file_path",
      "name": "Run",
      "cmd": "${file_base_name}"

Create XML in Javascript

xml-writer(npm package) I think this is the good way to create and write xml file easy. Also it can be used on server side with nodejs.

var XMLWriter = require('xml-writer');
xw = new XMLWriter;
xw.writeAttribute('foo', 'value');
xw.text('Some content');

Add a fragment to the URL without causing a redirect?

For straight HTML, with no JavaScript required:

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

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

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

Pretty printing XML with javascript

Xml-to-json library has method formatXml(xml). I am the maintainer of the project.

var prettyXml = formatXml("<a><b/></a>");

// <a>
//   <b/>
// </a>

Exit Shell Script Based on Process Exit Code

  1. How do I get the exit code of cmd1 in cmd1|cmd2

    First, note that cmd1 exit code could be non-zero and still don't mean an error. This happens for instance in

    cmd | head -1

    You might observe a 141 (or 269 with ksh93) exit status of cmd1, but it's because cmd was interrupted by a SIGPIPE signal when head -1 terminated after having read one line.

    To know the exit status of the elements of a pipeline cmd1 | cmd2 | cmd3

    a. with Z shell (zsh):

    The exit codes are provided in the pipestatus special array. cmd1 exit code is in $pipestatus[1], cmd3 exit code in $pipestatus[3], so that $? is always the same as $pipestatus[-1].

    b. with Bash:

    The exit codes are provided in the PIPESTATUS special array. cmd1 exit code is in ${PIPESTATUS[0]}, cmd3 exit code in ${PIPESTATUS[2]}, so that $? is always the same as ${PIPESTATUS: -1}.


    For more details see Z shell.

Use of ~ (tilde) in R programming Language

The thing on the right of <- is a formula object. It is often used to denote a statistical model, where the thing on the left of the ~ is the response and the things on the right of the ~ are the explanatory variables. So in English you'd say something like "Species depends on Sepal Length, Sepal Width, Petal Length and Petal Width".

The myFormula <- part of that line stores the formula in an object called myFormula so you can use it in other parts of your R code.

Other common uses of formula objects in R

The lattice package uses them to specify the variables to plot.
The ggplot2 package uses them to specify panels for plotting.
The dplyr package uses them for non-standard evaulation.

What is “2's Complement”?

Looking at the two's complement system from a math point of view it really makes sense. In ten's complement, the idea is to essentially 'isolate' the difference.

Example: 63 - 24 = x

We add the complement of 24 which is really just (100 - 24). So really, all we are doing is adding 100 on both sides of the equation.

Now the equation is: 100 + 63 - 24 = x + 100, that is why we remove the 100 (or 10 or 1000 or whatever).

Due to the inconvenient situation of having to subtract one number from a long chain of zeroes, we use a 'diminished radix complement' system, in the decimal system, nine's complement.

When we are presented with a number subtracted from a big chain of nines, we just need to reverse the numbers.

Example: 99999 - 03275 = 96724

That is the reason, after nine's complement, we add 1. As you probably know from childhood math, 9 becomes 10 by 'stealing' 1. So basically it's just ten's complement that takes 1 from the difference.

In Binary, two's complement is equatable to ten's complement, while one's complement to nine's complement. The primary difference is that instead of trying to isolate the difference with powers of ten (adding 10, 100, etc. into the equation) we are trying to isolate the difference with powers of two.

It is for this reason that we invert the bits. Just like how our minuend is a chain of nines in decimal, our minuend is a chain of ones in binary.

Example: 111111 - 101001 = 010110

Because chains of ones are 1 below a nice power of two, they 'steal' 1 from the difference like nine's do in decimal.

When we are using negative binary number's, we are really just saying:

0000 - 0101 = x

1111 - 0101 = 1010

1111 + 0000 - 0101 = x + 1111

In order to 'isolate' x, we need to add 1 because 1111 is one away from 10000 and we remove the leading 1 because we just added it to the original difference.

1111 + 1 + 0000 - 0101 = x + 1111 + 1

10000 + 0000 - 0101 = x + 10000

Just remove 10000 from both sides to get x, it's basic algebra.

What is Express.js?

Express is a module framework for Node that you can use for applications that are based on server/s that will "listen" for any input/connection requests from clients. When you use it in Node, it is just saying that you are requesting the use of the built-in Express file from your Node modules.

Express is the "backbone" of a lot of Web Apps that have their back end in NodeJS. From what I know, its primary asset being the providence of a routing system that handles the services of "interaction" between 2 hosts. There are plenty of alternatives for it, such as Sails.

Transposing a 2D-array in JavaScript

shortest way with lodash/underscore and es6:

where matrix could be:

const matrix = [[1,2,3], [1,2,3], [1,2,3]];

Java: Array with loop

I'm not sure what structure you want your resulting array in, but the following code will do what I think you're asking for:

int sum = 0;
int[] results = new int[100];
for (int i = 0; i < 100; i++) {
  sum += (i+1);
  results[i] = sum;

Gives you an array of the sum at each point in the loop [1, 3, 6, 10...]

Keyboard shortcut to comment lines in Sublime Text 3

In Windows use ctrl + shift + : to comment for Python.

How can I create a carriage return in my C# string

Along with Environment.NewLine and the literal \r\n or just \n you may also use a verbatim string in C#. These begin with @ and can have embedded newlines. The only thing to keep in mind is that " needs to be escaped as "". An example:

string s = @"This is a string
that contains embedded new lines,
that will appear when this string is used."

Reference - What does this error mean in PHP?

MySQL: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ... at line ...

This error is often caused because you forgot to properly escape the data passed to a MySQL query.

An example of what not to do (the "Bad Idea"):

$query = "UPDATE `posts` SET my_text='{$_POST['text']}' WHERE id={$_GET['id']}";
mysqli_query($db, $query);

This code could be included in a page with a form to submit, with an URL such as (to edit the post n°10)

What will happen if the submitted text contains single quotes? $query will end up with:

$query = "UPDATE `posts` SET my_text='I'm a PHP newbie' WHERE id=10';

And when this query is sent to MySQL, it will complain that the syntax is wrong, because there is an extra single quote in the middle.

To avoid such errors, you MUST always escape the data before use in a query.

Escaping data before use in a SQL query is also very important because if you don't, your script will be open to SQL injections. An SQL injection may cause alteration, loss or modification of a record, a table or an entire database. This is a very serious security issue!


Setting a JPA timestamp column to be generated by the database?

Add the @CreationTimestamp annotation:

@Column(name="timestamp", nullable = false, updatable = false, insertable = false)
private Timestamp timestamp;

is of a type that is invalid for use as a key column in an index

A unique constraint can't be over 8000 bytes per row and will only use the first 900 bytes even then so the safest maximum size for your keys would be:

create table [misc_info]
    [key] nvarchar(450) UNIQUE NOT NULL, 
    [value] nvarchar(max) NOT NULL

i.e. the key can't be over 450 characters. If you can switch to varchar instead of nvarchar (e.g. if you don't need to store characters from more than one codepage) then that could increase to 900 characters.

Are there any SHA-256 javascript implementations that are generally considered trustworthy?

No, there's no way to use browser JavaScript to improve password security. I highly recommend you read this article. In your case, the biggest problem is the chicken-egg problem:

What's the "chicken-egg problem" with delivering Javascript cryptography?

If you don't trust the network to deliver a password, or, worse, don't trust the server not to keep user secrets, you can't trust them to deliver security code. The same attacker who was sniffing passwords or reading diaries before you introduce crypto is simply hijacking crypto code after you do.


Why can't I use TLS/SSL to deliver the Javascript crypto code?

You can. It's harder than it sounds, but you safely transmit Javascript crypto to a browser using SSL. The problem is, having established a secure channel with SSL, you no longer need Javascript cryptography; you have "real" cryptography.

Which leads to this:

The problem with running crypto code in Javascript is that practically any function that the crypto depends on could be overridden silently by any piece of content used to build the hosting page. Crypto security could be undone early in the process (by generating bogus random numbers, or by tampering with constants and parameters used by algorithms), or later (by spiriting key material back to an attacker), or --- in the most likely scenario --- by bypassing the crypto entirely.

There is no reliable way for any piece of Javascript code to verify its execution environment. Javascript crypto code can't ask, "am I really dealing with a random number generator, or with some facsimile of one provided by an attacker?" And it certainly can't assert "nobody is allowed to do anything with this crypto secret except in ways that I, the author, approve of". These are two properties that often are provided in other environments that use crypto, and they're impossible in Javascript.

Basically the problem is this:

  • Your clients don't trust your servers, so they want to add extra security code.
  • That security code is delivered by your servers (the ones they don't trust).

Or alternatively,

  • Your clients don't trust SSL, so they want you use extra security code.
  • That security code is delivered via SSL.

Note: Also, SHA-256 isn't suitable for this, since it's so easy to brute force unsalted non-iterated passwords. If you decide to do this anyway, look for an implementation of bcrypt, scrypt or PBKDF2.

How to get first and last day of week in Oracle?

Another solution is


You must concat the cantweek with the year

Powershell Execute remote exe with command line arguments on remote computer

$sb = ScriptBlock::Create("$command")
Invoke-Command -ScriptBlock $sb

This should work and avoid misleading the beginners.

How to sort a List of objects by their date (java collections, List<Object>)

In Java 8, it's now as simple as:


No mapping found for HTTP request with URI.... in DispatcherServlet with name

If you are using maven as build tool for project , build your project properly,your changes in the code and xml files are not reflecting after compilations.

How to remove pip package after deleting it manually

packages installed using pip can be uninstalled completely using

pip uninstall <package>

refrence link

pip uninstall is likely to fail if the package is installed using python install as they do not leave behind metadata to determine what files were installed.

packages still show up in pip list if their paths(.pth file) still exist in your site-packages or dist-packages folder. You'll need to remove them as well in case you're removing using rm -rf

Python Finding Prime Factors

This question was the first link that popped up when I googled "python prime factorization". As pointed out by @quangpn88, this algorithm is wrong (!) for perfect squares such as n = 4, 9, 16, ... However, @quangpn88's fix does not work either, since it will yield incorrect results if the largest prime factor occurs 3 or more times, e.g., n = 2*2*2 = 8 or n = 2*3*3*3 = 54.

I believe a correct, brute-force algorithm in Python is:

def largest_prime_factor(n):
    i = 2
    while i * i <= n:
        if n % i:
            i += 1
            n //= i
    return n

Don't use this in performance code, but it's OK for quick tests with moderately large numbers:

In [1]: %timeit largest_prime_factor(600851475143)
1000 loops, best of 3: 388 µs per loop

If the complete prime factorization is sought, this is the brute-force algorithm:

def prime_factors(n):
    i = 2
    factors = []
    while i * i <= n:
        if n % i:
            i += 1
            n //= i
    if n > 1:
    return factors

How to check if a textbox is empty using javascript

You can also check it using jQuery.. It's quite easy:

        <title>jQuery: Check if Textbox is empty</title>
        <script type="text/javascript" src="js/jquery_1.7.1_min.js"></script>
        <form name="form1" method="post" action="">
            <label for="city">City:</label>
            <input type="text" name="city" id="city">
        <button id="check">Check</button>
        <script type="text/javascript">
             $('#check').click(function () {
                 if ($('#city').val() == '') {
                 } else {
                     alert('Contains: ' + $('#city').val());

Execute a command line binary with Node.js

If you want something that closely resembles the top answer but is also synchronous then this will work.

var execSync = require('child_process').execSync;
var cmd = "echo 'hello world'";

var options = {
  encoding: 'utf8'

console.log(execSync(cmd, options));

How to check if a database exists in SQL Server?


     SELECT name FROM master.dbo.sysdatabases 
    WHERE name = N'New_Database'
    SELECT 'Database Name already Exist' AS Message
    CREATE DATABASE [New_Database]
    SELECT 'New Database is Created'

Standard deviation of a list

In python 2.7 you can use NumPy's numpy.std() gives the population standard deviation.

In Python 3.4 statistics.stdev() returns the sample standard deviation. The pstdv() function is the same as numpy.std().

'negative' pattern matching in python

You can also do it without negative look ahead. You just need to add parentheses to that part of expression which you want to extract. This construction with parentheses is named group.

Let's write python code:

string = """OK SYS 10 LEN 20 12 43
1233a.fdads.txt,23 /data/a11134/a.txt
3232b.ddsss.txt,32 /data/d13f11/b.txt
3452d.dsasa.txt,1234 /data/c13af4/f.txt

search_result ="^OK.*\n((.|\s)*).", string)

if search_result:

Output is:

1233a.fdads.txt,23 /data/a11134/a.txt
3232b.ddsss.txt,32 /data/d13f11/b.txt
3452d.dsasa.txt,1234 /data/c13af4/f.txt

^OK.*\n will find first line with OK statement, but we don't want to extract it so leave it without parentheses. Next is part which we want to capture: ((.|\s)*), so put it inside parentheses. And in the end of regexp we look for a dot ., but we also don't want to capture it.

P.S: I find this answer is super helpful to understand power of groups.

Execute curl command within a Python script


I know, that's the "answer" nobody wants. But if something's worth doing, it's worth doing right, right?

This seeming like a good idea probably stems from a fairly wide misconception that shell commands such as curl are anything other than programs themselves.

So what you're asking is "how do I run this other program, from within my program, just to make a measly little web request?". That's crazy, there's got to be a better way right?

Uxio's answer works, sure. But it hardly looks very Pythonic, does it? That's a lot of work just for one little request. Python's supposed to be about flying! Anyone writing that is probably wishing they just call'd curl!

it works, but is there a better way?

Yes, there is a better way!

Requests: HTTP for Humans

Things shouldn’t be this way. Not in Python.

Let's GET this page:

import requests
res = requests.get('')

That's it, really! You then have the raw res.text, or res.json() output, the res.headers, etc.

You can see the docs (linked above) for details of setting all the options, since I imagine OP has moved on by now, and you - the reader now - likely need different ones.

But, for example, it's as simple as:

url     = 'http://example.tld'
payload = { 'key' : 'val' }
headers = {}
res =, data=payload, headers=headers)

You can even use a nice Python dict to supply the query string in a GET request with params={}.

Simple and elegant. Keep calm, and fly on.

How to alter SQL in "Edit Top 200 Rows" in SSMS 2008

Ctrl+3 in SQL Server 2012. Might work in 2008 too

What is the method for converting radians to degrees?

360 degrees = 2*pi radians

That means deg2rad(x) = x*pi/180 and rad2deg(x) = 180x/pi;

How to remove any URL within a string in Python

You could also look at it from the other way around...

from urlparse import urlparse
[el for el in ['text1', 'FTP://', 'text2', ''] if not urlparse(el).scheme]

How can I disable a tab inside a TabControl?

The only way is to catch the Selecting event and prevent a tab from being activated.

How do you set up use HttpOnly cookies in PHP

You can use this in a header file.

// setup session enviroment

This way all future session cookies will use httponly.

  • Updated.

What is a superfast way to read large files line-by-line in VBA?

Be careful when using Application.Transpose with a huge number of values. If you transpose values to a column, excel will assume you are assuming you transposed them from rows.

Max Column Limit < Max Row Limit, and it will only display the first (Max Column Limit) values, and anithing after that will be "N/A"

Switching to a TabBar tab view programmatically?

Like Stuart Clark's solution but for Swift 3 and using restoration identifier to find correct tab:

private func setTabById(id: String) {
  var i: Int = 0
  if let controllers = self.tabBarController?.viewControllers {
    for controller in controllers {
      if let nav = controller as? UINavigationController, nav.topViewController?.restorationIdentifier == id {
      i = i+1
  self.tabBarController?.selectedIndex = i

Use it like this ("Humans" and "Robots" must also be set in storyboard for specific viewController and it's Restoration ID, or use Storyboard ID and check "use storyboard ID" as restoration ID):

struct Tabs {
    static let Humans = "Humans"
    static let Robots = "Robots"
setTabById(id: Tabs.Robots)

Please note that my tabController links to viewControllers behind navigationControllers. Without navigationControllers it would look like this:

if controller.restorationIdentifier == id {

Insert, on duplicate update in PostgreSQL?

There is no simple command to do it.

The most correct approach is to use function, like the one from docs.

Another solution (although not that safe) is to do update with returning, check which rows were updates, and insert the rest of them

Something along the lines of:

update table
set column = x.column
from (values (1,'aa'),(2,'bb'),(3,'cc')) as x (id, column)
where =
returning id;

assuming id:2 was returned:

insert into table (id, column) values (1, 'aa'), (3, 'cc');

Of course it will bail out sooner or later (in concurrent environment), as there is clear race condition in here, but usually it will work.

Here's a longer and more comprehensive article on the topic.

trace a particular IP and port

it can be done by using this command: tcptraceroute -p destination port destination IP. like: tcptraceroute -p 9100 but don't forget to install tcptraceroute package on your system. tcpdump and nc by default installed on the system. regards

How do I append a node to an existing XML file in java

You can parse the existing XML file into DOM and append new elements to the DOM. Very similar to what you did with creating brand new XML. I am assuming you do not have to worry about duplicate server. If you do have to worry about that, you will have to go through the elements in the DOM to check for duplicates.

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

/* parse existing file to DOM */
Document document = documentBuilder.parse(new File("exisgint/xml/file"));

Element root = document.getDocumentElement();

for (Server newServer : Collection<Server> bunchOfNewServers){
  Element server = Document.createElement("server");
  /* create and setup the server node...*/


/* use whatever method to output DOM to XML (for example, using transformer like you did).*/

Mocking static methods with Mockito

Mocking of static methods in Mockito is possible since Mockito 3.4.0. For more details see:

In your case, something like this:

  public void testStaticMockWithVerification() throws SQLException {
    try (MockedStatic<DriverManager> dummy = Mockito.mockStatic(DriverManager.class)) {
      DatabaseConnectionFactory factory = new MySQLDatabaseConnectionFactory();
      dummy.when(() -> DriverManager.getConnection("arg1", "arg2", "arg3"))
        .thenReturn(new Connection() {/*...*/});


      dummy.verify(() -> DriverManager.getConnection(eq("arg1"), eq("arg2"), eq("arg3")));

NOTE: this feature requires mockito-inline dependency.

'python3' is not recognized as an internal or external command, operable program or batch file

There is no python3.exe file, that is why it fails.




py is just a launcher for python.exe. If you have more than one python versions installed on your machine (2.x, 3.x) you can specify what version of python to launch by

py -2 or py -3

Setting the correct encoding when piping stdout in Python


do the job, but can't set it on python itself ...

what we can do is verify if isn't setting and tell the user to set it before call script with :

if __name__ == '__main__':
    if (sys.stdout.encoding is None):
        print >> sys.stderr, "please set python env PYTHONIOENCODING=UTF-8, example: export PYTHONIOENCODING=UTF-8, when write to stdout."

Update to reply to the comment: the problem just exist when piping to stdout . I tested in Fedora 25 Python 2.7.13

python --version
Python 2.7.13


#!/usr/bin/env python
#-*- coding: utf-8 -*-
import sys

print sys.stdout.encoding

running ./


running ./ | less


WampServer: php-win.exe The program can't start because MSVCR110.dll is missing

Windows 10 x64 released August 2015 - same issue arising. MSVCR110.dll is also found in the sysWOW64 folder (which is where I found it, copying to system32 does not help). To resolve:

  1. uninstall the x86 versions of VC 11 vcredist_x64/86.exe for 2012 and 2013
  2. uninstall WAMP Server 2.5
  3. delete (maybe back up first) the WAMP folder
  4. restart windows
  5. reinstall WAMP 2.5

Hopefully like me you have a MySQL database backup handy!

Permission denied when launch python script via bash

Check for id. It may have root permissions.

So type su and then execute the script as ./scripts/

It works.

Warning: mysql_connect(): Access denied for user 'root'@'localhost' (using password: YES)

try $conn = mysql_connect("localhost", "root") or $conn = mysql_connect("localhost", "root", "")

Import numpy on pycharm

I added Anaconda3/Library/Bin to the environment path and PyCharm no longer complained with the error.

Stated by

Java 8 stream map on entry set

Simply translating the "old for loop way" into streams:

private Map<String, String> mapConfig(Map<String, Integer> input, String prefix) {
    int subLength = prefix.length();
    return input.entrySet().stream()
                   entry -> entry.getKey().substring(subLength), 
                   entry -> AttributeType.GetByName(entry.getValue())));

ValueError: all the input arrays must have same number of dimensions

You can also cast (n,) to (n,1) by enclosing within brackets [ ].

e.g. Instead of np.append(b,a,axis=0) use np.append(b,[a],axis=0)



array([[5, 6],
       [7, 8],
       [1, 2]])

Declaring variables inside loops, good practice or bad practice?

Declaring variables inside or outside of a loop, It's the result of JVM specifications But in the name of best coding practice it is recommended to declare the variable in the smallest possible scope (in this example it is inside the loop, as this is the only place where the variable is used). Declaring objects in the smallest scope improve readability. The scope of local variables should always be the smallest possible. In your example I presume str is not used outside of the while loop, otherwise you would not be asking the question, because declaring it inside the while loop would not be an option, since it would not compile.

Does it make a difference if I declare variables inside or outside a , Does it make a difference if I declare variables inside or outside a loop in Java? Is this for(int i = 0; i < 1000; i++) { int At the level of the individual variable there is no significant difference in effeciency, but if you had a function with 1000 loops and 1000 variables (never mind the bad style implied) there could be systemic differences because all the lives of all the variables would be the same instead of overlapped.

Declaring Loop Control Variables Inside the for Loop, When you declare a variable inside a for loop, there is one important point to remember: the scope of that variable ends when the for statement does. (That is, the scope of the variable is limited to the for loop.) This Java Example shows how to declare multiple variables in Java For loop using declaration block.

How to use parameters with HttpPost

To set parameters to your HttpPostRequest you can use BasicNameValuePair, something like this :

    HttpClient httpclient;
    HttpPost httpPost;
    ArrayList<NameValuePair> postParameters;
    httpclient = new DefaultHttpClient();
    httpPost = new HttpPost("your login link");

    postParameters = new ArrayList<NameValuePair>();
    postParameters.add(new BasicNameValuePair("param1", "param1_value"));
    postParameters.add(new BasicNameValuePair("param2", "param2_value"));

    httpPost.setEntity(new UrlEncodedFormEntity(postParameters, "UTF-8"));

    HttpResponse response = httpclient.execute(httpPost);

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

I was getting same kinda error but after copying the ojdbc14.jar into lib folder, no more exception.(copy ojdbc14.jar from somewhere and paste it into lib folder inside WebContent.)

How to select <td> of the <table> with javascript?

try document.querySelectorAll("#table td");

HTML radio buttons allowing multiple selections

They all need to have the same name attribute.

The radio buttons are grouped by the name attribute. Here's an example:

    <legend>Please select one of the following</legend>
    <input type="radio" name="action" id="track" value="track" /><label for="track">Track Submission</label><br />
    <input type="radio" name="action" id="event" value="event"  /><label for="event">Events and Artist booking</label><br />
    <input type="radio" name="action" id="message" value="message" /><label for="message">Message us</label><br />

Removing duplicate elements from an array in Swift

This works in Swift 4, if you do not want/need to convert the result to an Array, but can do with a Set. The result is not sorted by default, but you can do that with sorted(), which returns an array, as shown in the print statement.

let array = [1, 4, 2, 2, 6, 24, 15, 2, 60, 15, 6]

var result = Set<Int>()
_ ={ result.insert($0) }

print(result.sorted())  // [1, 2, 4, 6, 15, 24, 60]

How to avoid warning when introducing NAs by coercion

In general suppressing warnings is not the best solution as you may want to be warned when some unexpected input will be provided.
Solution below is wrapper for maintaining just NA during data type conversion. Doesn't require any package.

as.num = function(x, na.strings = "NA") {
    na = x %in% na.strings
    x[na] = 0
    x = as.numeric(x)
    x[na] = NA_real_
as.num(c("1", "2", "X"), na.strings="X")
#[1]  1  2 NA

How to display an alert box from C# in ASP.NET?

After insertion code,

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);

How do you change library location in R?

You can edit Rprofile in the base library (in 'C:/Program Files/R.Files/library/base/R' by default) to include code to be run on startup. Append

########        User code        ########

to Rprofile using any text editor (like Notepad) to cause R to add 'C:/my/dir' to the list of libraries it knows about.

(Notepad can't save to Program Files, so save your edited Rprofile somewhere else and then copy it in using Windows Explorer.)

Generate random number between two numbers in JavaScript

function randomIntFromInterval(min, max) { // min and max included 
  return Math.floor(Math.random() * (max - min + 1) + min);

What it does "extra" is it allows random intervals that do not start with 1. So you can get a random number from 10 to 15 for example. Flexibility.

What is the meaning of curly braces?

Dictionaries in Python are data structures that store key-value pairs. You can use them like associative arrays. Curly braces are used when declaring dictionaries:

d = {'One': 1, 'Two' : 2, 'Three' : 3 }
print d['Two'] # prints "2"

Curly braces are not used to denote control levels in Python. Instead, Python uses indentation for this purpose.

I think you really need some good resources for learning Python in general. See

Android Preventing Double Click On A Button

This solution (Kotlin) works on me:

abstract class SingleClickListener : View.OnClickListener {
    private val MIN_CLICK_INTERVAL: Long = 1000
    private var mLastClickTime: Long = 0

    abstract fun onSingleClick(v: View?)

    override fun onClick(v: View?) {
        if (mLastClickTime <= 0) {
            mLastClickTime = SystemClock.uptimeMillis()

        if (SystemClock.uptimeMillis() - mLastClickTime <= MIN_CLICK_INTERVAL) {

        mLastClickTime = SystemClock.uptimeMillis()



someView.setOnClickListener(object : SingleClickListener() {
    override fun onSingleClick(v: View?) {
        v?.also { klik(it) }

Or also create extension function for adding ClickListener on view easily:

fun (View) -> Unit) {
    this.setOnClickListener(object : SingleClickListener() {
        override fun onSingleClick(v: View?) {
            v?.also { klik(it) }

// Usage
class XPerimentActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        setContentView(R.layout.activity_xperiment_layout) {
           // do your magic

XMLHttpRequest blocked by CORS Policy

I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer

Getting key with maximum value in dictionary?

max(stats, key=stats.get) if stats else None

stats can be an empty dictionary as well and max(stats, key=stats.get) will break in that situation.

Error QApplication: no such file or directory

You can change build versiyon.For example i tried QT 5.6.1 but it didn't work.Than i tried QT 5.7.0 .So it worked , Good Luck! :)

Inserting one list into another list in java?

Excerpt from the Java API for addAll(collection c) in Interface List see here

"Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator (optional operation)."

You you will have as much object as you have in both lists - the number of objects in your first list plus the number of objects you have in your second list - in your case 100.

Getting the parent div of element

The property pDoc.parentElement or pDoc.parentNode will get you the parent element.

Removing certain characters from a string in R

try: gsub('\\$', '', '$5.00$')

Get HTML code from website in C#

You can use WebClient to download the html for any url. Once you have the html, you can use a third-party library like HtmlAgilityPack to lookup values in the html as in below code -

public static string GetInnerHtmlFromDiv(string url)
        string HTML;
        using (var wc = new WebClient())
            HTML = wc.DownloadString(url);
        var doc = new HtmlAgilityPack.HtmlDocument();
        HtmlNode element = doc.DocumentNode.SelectSingleNode("//div[@id='<div id here>']");
        if (element != null)
            return element.InnerHtml.ToString();
        return null;            

Prevent Default on Form Submit jQuery

I believe that the above answers is all correct, but that doesn't point out why the submit method doesn't work.

Well, the submit method will not work if jQuery can't get the form element, and jQuery doesn't give any error about that. If your script is placed in the head of the document, make sure the code runs after DOM is ready. So, $(document).ready(function () { // your code here // }); will solve the problem.

The best practice is, always put your script in the bottom of the document.

Conditional formatting using AND() function

I was having the same problem with the AND() breaking the conditional formatting. I just happened to try treating the AND as multiplication, and it works! Remove the AND() function and just multiply your arguments. Excel will treat the booleans as 1 for true and 0 for false. I just tested this formula and it seems to work.


How to normalize a histogram in MATLAB?

hist can not only plot an histogram but also return you the count of elements in each bin, so you can get that count, normalize it by dividing each bin by the total and plotting the result using bar. Example:

Y = rand(10,1);
C = hist(Y);
C = C ./ sum(C);

or if you want a one-liner:

bar(hist(Y) ./ sum(hist(Y)))


Edit: This solution answers the question How to have the sum of all bins equal to 1. This approximation is valid only if your bin size is small relative to the variance of your data. The sum used here correspond to a simple quadrature formula, more complex ones can be used like trapz as proposed by R. M.

Does a foreign key automatically create an index?

I notice that Entity Framework 6.1 pointed at MSSQL does automatically add indexes on foreign keys.

How much should a function trust another function

Typically this is bad practice. Since it is possible to call addEdge before addNode and have a NullPointerException (NPE) thrown, addEdge should check if the result is null and throw a more descriptive Exception. In my opinion, the only time it is acceptable not to check for nulls is when you expect the result to never be null, in which case, an NPE is plenty descriptive.

How to style readonly attribute with CSS?

Note that textarea[readonly="readonly"] works if you set readonly="readonly" in HTML but it does NOT work if you set the readOnly-attribute to true or "readonly" via JavaScript.

For the CSS selector to work if you set readOnly with JavaScript you have to use the selector textarea[readonly].

Same behavior in Firefox 14 and Chrome 20.

To be on the safe side, i use both selectors.

textarea[readonly="readonly"], textarea[readonly] {

How do Common Names (CN) and Subject Alternative Names (SAN) work together?

To be absolutely correct you should put all the names into the SAN field.

The CN field should contain a Subject Name not a domain name, but when the Netscape found out this SSL thing, they missed to define its greatest market. Simply there was not certificate field defined for the Server URL.

This was solved to put the domain into the CN field, and nowadays usage of the CN field is deprecated, but still widely used. The CN can hold only one domain name.

The general rules for this: CN - put here your main URL (for compatibility) SAN - put all your domain here, repeat the CN because its not in right place there, but its used for that...

If you found a correct implementation, the answers for your questions will be the followings:

  • Has this setup a special meaning, or any [dis]advantages over setting both CNs? You cant set both CNs, because CN can hold only one name. You can make with 2 simple CN certificate instead one CN+SAN certificate, but you need 2 IP addresses for this.

  • What happens on server-side if the other one, host.domain.tld, is being requested? It doesn't matter whats happen on server side.

In short: When a browser client connects to this server, then the browser sends encrypted packages, which are encrypted with the public key of the server. Server decrypts the package, and if server can decrypt, then it was encrypted for the server.

The server doesn't know anything from the client before decrypt, because only the IP address is not encrypted trough the connection. This is why you need 2 IPs for 2 certificates. (Forget SNI, there is too much XP out there still now.)

On client side the browser gets the CN, then the SAN until all of the are checked. If one of the names matches for the site, then the URL verification was done by the browser. (im not talking on the certificate verification, of course a lot of ocsp, crl, aia request and answers travels on the net every time.)

What is the apply function in Scala?

1 - Treat functions as objects.

2 - The apply method is similar to __call __ in Python, which allows you to use an instance of a given class as a function.

How to Animate Addition or Removal of Android ListView Rows

I haven't tried it but it looks like animateLayoutChanges should do what you're looking for. I see it in the ImageSwitcher class, I assume it's in the ViewSwitcher class as well?

How do you prevent install of "devDependencies" NPM modules for Node.js (package.json)?

The new option is:

npm install --only=prod

If you want to install only devDependencies:

npm install --only=dev

Find the most popular element in int[] array

Comparing two arrays, I Hope for that this is useful for you.

public static void main(String []args){

        int primerArray [] = {1,2,1,3,5};
        int arrayTow [] = {1,6,7,8};

       int numberMostRepetly =  validateArrays(primerArray,arrayTow);



public static int validateArrays(int primerArray[], int arrayTow[]){

    int numVeces = 0;

    for(int i = 0; i< primerArray.length; i++){

        for(int c = i+1; c < primerArray.length; c++){

            if(primerArray[i] == primerArray[c]){
                numVeces = primerArray[c];
                // System.out.println("Numero que mas se repite");

        for(int a = 0; a < arrayTow.length; a++){

            if(numVeces == arrayTow[a]){
               // System.out.println(numVeces);
                return numVeces;

    return 0;


Printing out all the objects in array list

Override toString() method in Student class as below:

   public String toString() {
        return ("StudentName:"+this.getStudentName()+
                    " Student No: "+ this.getStudentNo() +
                    " Email: "+ this.getEmail() +
                    " Year : " + this.getYear());

Turning off eslint rule for a specific line

To disable a single rule for the rest of the file below:

/* eslint no-undef: "off"*/
const uploadData = new FormData();

How can I format bytes a cell in Excel as KB, MB, GB etc?

Paste this next to your values(bytes) and this will automatically change it to whatever your size of value is.

=IF(G10>=1099511627776,CONCATENATE(ROUND((G10/1024/1024/1024/1024),1)," TB"),IF(G10>=1073741824,CONCATENATE(ROUND((G10/1024/1024/1024),1)," GB"),IF(G10>=1048576,CONCATENATE(ROUND((G10/1024/1024),1)," MB"),IF(G10>=1024,CONCATENATE(ROUND((G10/1024),1)," KB"),IF(G10>=1,CONCATENATE((G10)," BYTES"),0)))))

Request Permission for Camera and Library in iOS 10 - Info.plist

To ask permission for the photo app you need to add this code (Swift 3):

       (newStatus) in 
         if newStatus ==  PHAuthorizationStatus.authorized { 
          /* do stuff here */ 

python NameError: global name '__file__' is not defined

If all you are looking for is to get your current working directory os.getcwd() will give you the same thing as os.path.dirname(__file__) as long as you have not changed the working directory elsewhere in your code. os.getcwd() also works in interactive mode.

So os.path.join(os.path.dirname(__file__)) becomes os.path.join(os.getcwd())

Creating a div element in jQuery

simply if you want to create any HTML tag you can try this for example

var selectBody = $('body');
var div = $('<div>');
var h1  = $('<h1>');
var p   = $('<p>');

if you want to add any element on the flay you can try this


bower proxy configuration

Inside your local project open the .bowerrc that contains:

   "directory": "bower_components"

and add the following code-line:

   "directory": "bower_components",
  "proxy": "http://yourProxy:yourPort",

bower version: 1.7.1


Align Div at bottom on main Div

I guess you'll need absolute position

.vertical_banner {position:relative;}
#bottom_link{position:absolute; bottom:0;}

What is the worst real-world macros/pre-processor abuse you've ever come across?

Any macro that uses the token concatenation operator ##.

I saw one that a colleague of mine had the pleasure of working with. They tried to make a custom-implementation of string interning, so they re-implemented strings using a massive number of macros that (of course) didn't work properly. Trying to figure out what it did made my eyes explode because of all the ##'s scattered about.

How does Google reCAPTCHA v2 work behind the scenes?

This is speculation, but based on Google's reference to the "risk analysis engine" they use (

I would assume it looks at how you behaved prior to clicking, how your cursor moved on its way to the check (organic path/acceleration), which part of the checkbox was clicked (random places, or dead on center every time), browser fingerprint, Google cookies & contents, click location history tied to your fingerprint or account if it detects one etc.

It's fairly difficult to fake "organic" behavior in such a way that it would fool a continuously learning pattern detection engine. In the cases where it's not sure, it still prompts you to match an actual CAPTCHA string.

Center align "span" text inside a div

If you know the width of the span you could just stuff in a left margin.

Try this:

.center { text-align: center} span { display: table; }

Add the "center: class to your .

If you want some spans centered, but not others, replace the " span" in your style sheet to a class (e.g "center-span") and add that class to the span.

Format Instant to String


This saves you from having to convert to UTC. However, some other language's time frameworks may not support the milliseconds so you should do


Codesign error: Provisioning profile cannot be found after deleting expired profile

At least in Xcode 5, this is the thing that solved the problem for me:

Under provisioning profile, select the offending provisioning profile and then select a valid provisioning profile in the pull-down menu.

enter image description here

What's the best way to store co-ordinates (longitude/latitude, from Google Maps) in SQL Server?

SQL Server has support for spatial related information. You can see more at

Alternativly you can store the information as two basic fields, usually a float is the standard data type reported by most devices and is accurate enough for within an inch or two - more than adequate for Google Maps.

how to avoid extra blank page at end while printing?

After struggling with various page-break settings and heights and a million various CSS rules on the body tag, I finally solved it over a year later.

I have a div which is supposed to be the only thing on the page which prints, but I was getting several blank pages after it. My body tag is set to visibility:hidden; but that wasn't enough. Vertically tall page elements still take up 'space'. So I added this in my print CSS rules:

#header, #menu, #sidebar{ height:1px; display:none;}

to target specific divs by their ids which contain tall page layout elements. I shrunk the height and then removed them from the layout. No more blank pages. Years later I'm happy to tell my client I cracked it. Hope this helps someone.

Correct way to write loops for promise.

There is a new way to solve this and it's by using async/await.

async function myFunction() {
  while(/* my condition */) {
    const res = await db.getUser(email);

myFunction().then(() => {
  /* do other stuff */

python list in sql query as parameter

If you're using PostgreSQL with the Psycopg2 library you can let its tuple adaption do all the escaping and string interpolation for you, e.g:

ids = [1,2,3]
  "SELECT * FROM foo WHERE id IN %s",

i.e. just make sure that you're passing the IN parameter as a tuple. if it's a list you can use the = ANY array syntax:

  "SELECT * FROM foo WHERE id = ANY (%s)",

note that these both will get turned into the same query plan so you should just use whichever is easier. e.g. if your list comes in a tuple use the former, if they're stored in a list use the latter.

jQuery DatePicker with today as maxDate

$( ".selector" ).datepicker( "option", "maxDate", '+0m +0w' );

Select all where [first letter starts with B]

Following your comment posted to ceejayoz's answer, two things are messed up a litte:

  1. $first is not an array, it's a string. Replace $first = $first[0] . "%" by $first .= "%". Just for simplicity. (PHP string operators)

  2. The string being compared with LIKE operator should be quoted. Replace LIKE ".$first."") by LIKE '".$first."'"). (MySQL String Comparison Functions)

How to checkout in Git by date?

To those who prefer a pipe to command substitution

git rev-list -n1 --before=2013-7-4 master | xargs git checkout

Given an array of numbers, return array of products of all other numbers (no division)

Sneakily circumventing the "no divisions" rule:

sum = 0.0
for i in range(a):
  sum += log(a[i])

for i in range(a):
  output[i] = exp(sum - log(a[i]))

In Python, how do you convert a `datetime` object to seconds?

Maybe off-the-topic: to get UNIX/POSIX time from datetime and convert it back:

>>> import datetime, time
>>> dt = datetime.datetime(2011, 10, 21, 0, 0)
>>> s = time.mktime(dt.timetuple())
>>> s

# and back
>>> datetime.datetime.fromtimestamp(s)
datetime.datetime(2011, 10, 21, 0, 0)

Note that different timezones have impact on results, e.g. my current TZ/DST returns:

>>>  time.mktime(datetime.datetime(1970, 1, 1, 0, 0).timetuple())
-3600 # -1h

therefore one should consider normalizing to UTC by using UTC versions of the functions.

Note that previous result can be used to calculate UTC offset of your current timezone. In this example this is +1h, i.e. UTC+0100.



Just to clarify the best practice:

  1. Text format messages should almost always be stored as TEXT (they end up being arbitrarily long)

  2. String attributes should be stored as VARCHAR (the destination user name, the subject, etc...).

I understand that you've got a front end limit, which is great until it isn't. *grin* The trick is to think of the DB as separate from the applications that connect to it. Just because one application puts a limit on the data, doesn't mean that the data is intrinsically limited.

What is it about the messages themselves that forces them to never be more then 3000 characters? If it's just an arbitrary application constraint (say, for a text box or something), use a TEXT field at the data layer.

How to return a dictionary | Python

def prepare_table_row(row):
    lst = [i.text for i in row if i != u'\n']
    return dict(rank = int(lst[0]),
                grade = str(lst[1]),
                videos = float(lst[3].replace(",", " ")),
                subscribers = float(lst[4].replace(",", "")),
                views = float(lst[5].replace(",", "")))

Representing null in JSON

null is not zero. It is not a value, per se: it is a value outside the domain of the variable indicating missing or unknown data.

There is only one way to represent null in JSON. Per the specs (RFC 4627 and

2.1.  Values

A JSON value MUST be an object, array, number, or string, or one of
the following three literal names:

  false null true

enter image description here

"Input string was not in a correct format."

whenever i try to compile the code it says "{"Input string was not in a correct format."}"

This error won't come on compiling.

Now the error comese because you are trying to parse an invalid string to integer. To do it in a safe manner, you should do it like this

int questionID;
if(int.TryParse(vTwoOrMoreOptions.SelectedItems[0].Text.ToString(),out questionID))
//success code
 //failure code

Difference between Git and GitHub

In plain English:

  1. They are all source control as we all know.
  2. In an analogy, if Git is a standalone computer, then GitHub is a network of computers connected by web with bells and whistlers.
  3. So unless you open a GitHub acct and specifically tell VSC or any editor to use GitHub, you'll see your source code up-there otherwise they are only down here, - your local machine.

What is the difference between declarations, providers, and import in NgModule?

imports are used to import supporting modules like FormsModule, RouterModule, CommonModule, or any other custom-made feature module.

declarations are used to declare components, directives, pipes that belong to the current module. Everyone inside declarations knows each other. For example, if we have a component, say UsernameComponent, which displays a list of the usernames and we also have a pipe, say toupperPipe, which transforms a string to an uppercase letter string. Now If we want to show usernames in uppercase letters in our UsernameComponent then we can use the toupperPipe which we had created before but the question is how UsernameComponent knows that the toupperPipe exists and how it can access and use that. Here come the declarations, we can declare UsernameComponent and toupperPipe.

Providers are used for injecting the services required by components, directives, pipes in the module.

How to display both icon and title of action inside ActionBar?

Some of you guys have great answers, but I found some additional thing. If you want create a MenuItem with some SubMenu programmatically:

    public boolean onCreateOptionsMenu(Menu menu) {

        SubMenu subMenu = menu.addSubMenu(0, Menu.NONE, 0, "Menu title");

        subMenu.add(0, Menu.NONE, 0, "Subitem 1");
        subMenu.add(0, Menu.NONE, 1, "Subitem 2");
        subMenu.add(0, Menu.NONE, 2, "Subitem 3");

        return true;

Conversion from byte array to base64 and back

The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.

The way you get your original array back is by using Convert.FromBase64String:

 byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);

Close Window from ViewModel

I know this is an old post, probably no one would scroll this far, I know I didn't. So, after hours of trying different stuff, I found this blog and dude killed it. Simplest way to do this, tried it and it works like a charm.


In the ViewModel:


public bool CanClose { get; set; }

private RelayCommand closeCommand;
public ICommand CloseCommand
        if(closeCommand == null)
            closeCommand = new RelayCommand(param => Close(), param => CanClose);

public void Close()


add an Action property to the ViewModel, but define it from the View’s code-behind file. This will let us dynamically define a reference on the ViewModel that points to the View.

On the ViewModel, we’ll simply add:

public Action CloseAction { get; set; }

And on the View, we’ll define it as such:

public View()
    InitializeComponent() // this draws the View
    ViewModel vm = new ViewModel(); // this creates an instance of the ViewModel
    this.DataContext = vm; // this sets the newly created ViewModel as the DataContext for the View
    if ( vm.CloseAction == null )
        vm.CloseAction = new Action(() => this.Close());

Grouped bar plot in ggplot

First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:

raw <- read.csv("",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)

raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it

freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level

Then you need to create a data frame out of it, melt it and plot it:

Names=c("Food","Music","People")     # create list of names
data=data.frame(cbind(freq),Names)   # combine them into a data frame
data=data[,c(5,3,1,2,4)]             # sort columns

# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')

# plot everything
ggplot(data.m, aes(Names, value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat="identity")

Is this what you're after?

enter image description here

To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:

> head(df)
1  1    A  1980   450   338   154    36    13     9
2  2    A  2000   288   407   212    54    16    23
3  3    A  2020   196   434   246    68    19    36
4  4    B  1980   111   326   441    90    21    11
5  5    B  2000    63   298   443   133    42    21
6  6    B  2020    36   257   462   162    55    30

Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape and plotted.

For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw)) to get this:

> data
   Names Very.Bad Bad Good Very.Good
1   Food        7   6    5         2
2  Music        5   5    7         3
3 People        6   3    7         4

Just imagine you have Very.Bad, Bad, Good and so on instead of X1PCE, X2PCE, X3PCE. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw)).

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

Try to import


instead of


Why an interface can not implement another interface?

Conceptually there are the two "domains" classes and interfaces. Inside these domains you are always extending, only a class implements an interface, which is kind of "crossing the border". So basically "extends" for interfaces mirrors the behavior for classes. At least I think this is the logic behind. It seems than not everybody agrees with this kind of logic (I find it a little bit contrived myself), and in fact there is no technical reason to have two different keywords at all.

How are VST Plugins made?

Start with this link to the wiki, explains what they are and gives links to the sdk. Here is some information regarding the deve

How to compile a plugin - For making VST plugins in C++Builder, first you need the VST sdk by Steinberg. It's available from the Yvan Grabit's site (the link is at the top of the page).

The next thing you need to do is create a .def file (for example : myplugin.def). This needs to contain at least the following lines:

EXPORTS main=_main

Borland compilers add an underscore to function names, and this exports the main() function the way a VST host expects it. For more information about .def files, see the C++Builder help files.

This is not enough, though. If you're going to use any VCL element (anything to do with forms or components), you have to take care your plugin doesn't crash Cubase (or another VST host, for that matter). Here's how:

  1. Include float.h.
  2. In the constructor of your effect class, write


That should do the trick.

Here are some more useful sites:

how to write a vst plugin (pdf) via

"Access is denied" JavaScript error when trying to access the document object of a programmatically-created <iframe> (IE-only)

Following the exceedingly simple method from Andralor here fixed the issue for me:

Essentially, call the iframe again onUpdate:

    type: 'iframe',
    scrolling : 'visible',
    autoHeight: true,
    onUpdate: function(){

MySQL Query GROUP BY day / month / year

I wanted to get similar data per day, after experimenting a bit, this is the fastest I could find for my scenario

FROM stats
GROUP BY record_date DIV 1000000;

If you want to have it per month, add additional zeroes (00) I would not recommend this since it is not clear why or how this works, it might also break in different versions. But in our case this took less then half the time compared to some other more clearer queries that I tested.

Android Studio : unmappable character for encoding UTF-8

If above answeres did not work, then you can try my answer because it worked for me.
Here's what worked for me.

  1. Close Android Studio
  2. Go to C:\Usersyour username
  3. Locate the Android Studio settings directory named .AndroidStudioX.X (X.X being the version)
  4. C:\Users\my_user_name.AndroidStudio4.0\system\caches
  5. Delete the caches folder and open android studio

This should fix the issue.

npm ERR! network getaddrinfo ENOTFOUND

Maybe it's because the proxy do not stand for https. What I do is clear the proxy content of ~/.npmrc, or use

    npm config delete proxy

What's more, nrm is recommended for this problem.

Enum ToString with user friendly strings

This is an update to Ray Booysen's code that uses the generic GetCustomAttributes method and LINQ to make things a bit tidier.

    /// <summary>
    /// Gets the value of the <see cref="T:System.ComponentModel.DescriptionAttribute"/> on an struct, including enums.  
    /// </summary>
    /// <typeparam name="T">The type of the struct.</typeparam>
    /// <param name="enumerationValue">A value of type <see cref="T:System.Enum"/></param>
    /// <returns>If the struct has a Description attribute, this method returns the description.  Otherwise it just calls ToString() on the struct.</returns>
    /// <remarks>Based on, but useful for any struct.</remarks>
    public static string GetDescription<T>(this T enumerationValue) where T : struct
        return enumerationValue.GetType().GetMember(enumerationValue.ToString())
                .SelectMany(mi => mi.GetCustomAttributes<DescriptionAttribute>(false),
                    (mi, ca) => ca.Description)
                .FirstOrDefault() ?? enumerationValue.ToString();

Difference between Inheritance and Composition

Inheritances Vs Composition.

Inheritances and composition both are used to re-usability and extension of class behavior.

Inheritances mainly use in a family algorithm programming model such as IS-A relation type means similar kind of object. Example.

  1. Duster is a Car
  2. Safari is a Car

These are belongs to Car family.

Composition represents HAS-A relationship Type.It shows the ability of an object such as Duster has Five Gears , Safari has four Gears etc. Whenever we need to extend the ability of an existing class then use composition.Example we need to add one more gear in Duster object then we have to create one more gear object and compose it to the duster object.

We should not make the changes in base class until/unless all the derived classes needed those functionality.For this scenario we should use Composition.Such as

class A Derived by Class B

Class A Derived by Class C

Class A Derived by Class D.

When we add any functionality in class A then it is available to all sub classes even when Class C and D don't required those functionality.For this scenario we need to create a separate class for those functionality and compose it to the required class(here is class B).

Below is the example:

          // This is a base class
                 public abstract class Car
                       //Define prototype
                       public abstract void color();
                       public void Gear() {
                           Console.WriteLine("Car has a four Gear");

           // Here is the use of inheritence
           // This Desire class have four gears.
          //  But we need to add one more gear that is Neutral gear.

          public class Desire : Car
                       Neutral obj = null;
                       public Desire()
     // Here we are incorporating neutral gear(It is the use of composition). 
     // Now this class would have five gear. 

                           obj = new Neutral();

                       public override void color()
                           Console.WriteLine("This is a white color car");


             // This Safari class have four gears and it is not required the neutral
             //  gear and hence we don't need to compose here.

                   public class Safari :Car{
                       public Safari()
                       { }

                       public override void color()
                           Console.WriteLine("This is a red color car");


   // This class represents the neutral gear and it would be used as a composition.

   public class Neutral {
                      public void NeutralGear() {
                           Console.WriteLine("This is a Neutral Gear");

Using VBA to get extended file attributes

You can get this with .BuiltInDocmementProperties.

For example:

Public Sub PrintDocumentProperties()
    Dim oApp As New Excel.Application
    Dim oWB As Workbook
    Set oWB = ActiveWorkbook

    Dim title As String
    title = oWB.BuiltinDocumentProperties("Title")

    Dim lastauthor As String
    lastauthor = oWB.BuiltinDocumentProperties("Last Author")

    Debug.Print title
    Debug.Print lastauthor
End Sub

See this page for all the fields you can access with this:

If you're trying to do this outside of the client (i.e. with Excel closed and running code from, say, a .NET program), you need to use DSOFile.dll.

How can I pad a value with leading zeros?

Even later to the party.

function zfill(num, len) {
  return(0 > num ? "-" : "") + (Math.pow(10, len) <= Math.abs(num) ? "0" + Math.abs(num) : Math.pow(10, len) + Math.abs(num)).toString().substr(1)

This handles negatives and situations where the number is longer than the field width. And floating-point.

How to include duplicate keys in HashMap?

You can't have duplicate keys in a Map. You can rather create a Map<Key, List<Value>>, or if you can, use Guava's Multimap.

Multimap<Integer, String> multimap = ArrayListMultimap.create();
multimap.put(1, "rohit");
multimap.put(1, "jain");

System.out.println(multimap.get(1));  // Prints - [rohit, jain]

And then you can get the java.util.Map using the Multimap#asMap() method.

Converting double to integer in Java

is there a possibility that casting a double created via Math.round() will still result in a truncated down number

No, round() will always round your double to the correct value, and then, it will be cast to an long which will truncate any decimal places. But after rounding, there will not be any fractional parts remaining.

Here are the docs from Math.round(double):

Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression:

(long)Math.floor(a + 0.5d)

How to make the python interpreter correctly handle non-ASCII characters in string operations?

Python 2 uses ascii as the default encoding for source files, which means you must specify another encoding at the top of the file to use non-ascii unicode characters in literals. Python 3 uses utf-8 as the default encoding for source files, so this is less of an issue.


To enable utf-8 source encoding, this would go in one of the top two lines:

# -*- coding: utf-8 -*-

The above is in the docs, but this also works:

# coding: utf-8

Additional considerations:

  • The source file must be saved using the correct encoding in your text editor as well.

  • In Python 2, the unicode literal must have a u before it, as in s.replace(u"Â ", u"") But in Python 3, just use quotes. In Python 2, you can from __future__ import unicode_literals to obtain the Python 3 behavior, but be aware this affects the entire current module.

  • s.replace(u"Â ", u"") will also fail if s is not a unicode string.

  • string.replace returns a new string and does not edit in place, so make sure you're using the return value as well

How to use private Github repo as npm dependency

With git there is a https format

This format accepts User + password

https://bot-user:[email protected]/equivalent/we_demand_serverless_ruby.git

So what you can do is create a new user that will be used just as a bot, add only enough permissions that he can just read the repository you want to load in NPM modules and just have that directly in your packages.json

 Github > Click on Profile > Settings > Developer settings > Personal access tokens > Generate new token

In Select Scopes part, check the on repo: Full control of private repositories

This is so that token can access private repos that user can see

Now create new group in your organization, add this user to the group and add only repositories that you expect to be pulled this way (READ ONLY permission !)

You need to be sure to push this config only to private repo

Then you can add this to your / packages.json (bot-user is name of user, xxxxxxxxx is the generated personal token)

// packages.json

  // ....
    "name_of_my_lib": "https://bot-user:[email protected]/ghuser/name_of_my_lib.git"
  // ...

What is an Endpoint?

Come on guys :) We could do it simpler, by examples:


and when put under a domain, it would look like:

Can be either http or https, we use https in the example.

Also endpoint can be different for different HTTP methods, for example:

GET /item/{id}
PUT /item/{id}

would be two different endpoints - one for retrieving (as in "cRud" abbreviation), and the other for updating (as in "crUd")

And that's all, really that simple!

Create Log File in Powershell

You might just want to use the new TUN.Logging PowerShell module, this can also send a log mail. Just use the Start-Log and/or Start-MailLog cmdlets to start logging and then just use Write-HostLog, Write-WarningLog, Write-VerboseLog, Write-ErrorLog etc. to write to console and log file/mail. Then call Send-Log and/or Stop-Log at the end and voila, you got your logging. Just install it from the PowerShell Gallery via

Install-Module -Name TUN.Logging

Or just follow the link:

Documentation of the module can be found here:

How to show current time in JavaScript in the format HH:MM:SS?

This code will output current time in HH:MM:SS format in console, it takes into account GMT timezones.

var currentTime =
var GMT = -(new Date()).getTimezoneOffset()/60;
var totalSeconds = Math.floor(currentTime/1000);
seconds = ('0' + totalSeconds % 60).slice(-2);
var totalMinutes = Math.floor(totalSeconds/60);
minutes = ('0' + totalMinutes % 60).slice(-2);
var totalHours = Math.floor(totalMinutes/60);
hours = ('0' + (totalHours+GMT) % 24).slice(-2);
var timeDisplay = hours + ":" + minutes + ":" + seconds;
//Output is: 11:16:55

"int cannot be dereferenced" in Java




id == list[pos].getItemNumber()

For more details, you should learn the difference between the primitive types like int, char, and double and reference types.

what is the difference between XSD and WSDL

XSD (XML schema definition) defines the element in an XML document. It can be used to verify if the elements in the xml document adheres to the description in which the content is to be placed. While wsdl is specific type of XML document which describes the web service. WSDL itself adheres to a XSD.

How to reset / remove chrome's input highlighting / focus border?

This will definitely work. Orange outline won't show up anymore.. Common for all tags:

*:focus {
    outline: none;

Specific to some tag, ex: input tag


How to pass data using NotificationCenter in swift 3.0 and NSNotificationCenter in swift 2.0?

Swift 2.0

Pass info using userInfo which is a optional Dictionary of type [NSObject : AnyObject]?

  let imageDataDict:[String: UIImage] = ["image": image]

  // Post a notification
  NSNotificationCenter.defaultCenter().postNotificationName(notificationName, object: nil, userInfo: imageDataDict)

 // Register to receive notification in your class
 NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: notificationName, object: nil)

 // handle notification
 func showSpinningWheel(notification: NSNotification) { 

  if let image = notification.userInfo?["image"] as? UIImage {
  // do something with your image   

Swift 3.0 version and above

The userInfo now takes [AnyHashable:Any]? as an argument, which we provide as a dictionary literal in Swift

  let imageDataDict:[String: UIImage] = ["image": image]

  // post a notification NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict) 
  // `default` is now a property, not a method call

 // Register to receive notification in your class
 NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

 // handle notification
 // For swift 4.0 and above put @objc attribute in front of function Definition  
 func showSpinningWheel(_ notification: NSNotification) {

  if let image = notification.userInfo?["image"] as? UIImage {
  // do something with your image   

NOTE: Notification “names” are no longer strings, but are of type Notification.Name, hence why we are using NSNotification.Name(rawValue:"notificationName") and we can extend Notification.Name with our own custom notifications.

extension Notification.Name {
static let myNotification = Notification.Name("myNotification")

// and post notification like this .myNotification, object: nil)

Convert 24 Hour time to 12 Hour plus AM/PM indication Oracle SQL

For the 24-hour time, you need to use HH24 instead of HH.

For the 12-hour time, the AM/PM indicator is written as A.M. (if you want periods in the result) or AM (if you don't). For example:

SELECT invoice_date,
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
  FROM invoices

For more information on the format models you can use with TO_CHAR on a date, see

Where does R store packages?

Thanks for the direction from the above two answerers. James Thompson's suggestion worked best for Windows users.

  1. Go to where your R program is installed. This is referred to as R_Home in the literature. Once you find it, go to the /etc subdirectory.

  2. Select the file in this folder named I open it with VIM. You will find this is a bare-bones file with less than 20 lines of code. I inserted the following inside the code:

    # my custom library path

    (The comment added to keep track of what I did to the file.)

  3. In R, typing the .libPaths() function yields the first target at C:/R/Library

NOTE: there is likely more than one way to achieve this, but other methods I tried didn't work for some reason.

Getting list of parameter names inside python function

import inspect

def func(a,b,c=5):

inspect.getargspec(func)  # inspect.signature(func) in Python 3

(['a', 'b', 'c'], None, None, (5,))

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

This answer is rather late given the question date, but someone may find it useful.

None of the above solutions worked for me in Visual Studio 2012 on a local project, Net Framework 4.5 MVC 4. For context, I was following a tutorial on creating a barebones Web Api on CodeProject ( when I ran into this problem.

What did work for me was explicitly adding "System.Web.Mvc" to my application's references, even though the application already did reference "System.Web".

Extracting time from POSIXct

You can use strftime to convert datetimes to any character format:

> t <- strftime(times, format="%H:%M:%S")
> t
 [1] "02:06:49" "03:37:07" "00:22:45" "00:24:35" "03:09:57" "03:10:41"
 [7] "05:05:57" "07:39:39" "06:47:56" "07:56:36"

But that doesn't help very much, since you want to plot your data. One workaround is to strip the date element from your times, and then to add an identical date to all of your times:

> xx <- as.POSIXct(t, format="%H:%M:%S")
> xx
 [1] "2012-03-23 02:06:49 GMT" "2012-03-23 03:37:07 GMT"
 [3] "2012-03-23 00:22:45 GMT" "2012-03-23 00:24:35 GMT"
 [5] "2012-03-23 03:09:57 GMT" "2012-03-23 03:10:41 GMT"
 [7] "2012-03-23 05:05:57 GMT" "2012-03-23 07:39:39 GMT"
 [9] "2012-03-23 06:47:56 GMT" "2012-03-23 07:56:36 GMT"

Now you can use these datetime objects in your plot:

plot(xx, rnorm(length(xx)), xlab="Time", ylab="Random value")

enter image description here

For more help, see ?DateTimeClasses

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

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

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

ASP.NET: Session.SessionID changes between requests

My issue was with a Microsoft MediaRoom IPTV application. It turns out that MPF MRML applications don't support cookies; changing to use cookieless sessions in the web.config solved my issue

<sessionState cookieless="true"  />

Here's a REALLY old article about it: Cookieless ASP.NET

How to create a MySQL hierarchical recursive query?

Its a little tricky one, check this whether it is working for you

select,if(a.parent = 0,@varw:=concat(,','),@varw:=concat(,',',@varw)) as list from (select * from recursivejoin order by if(parent=0,id,parent) asc) a left join recursivejoin b on ( = b.parent),(select @varw:='') as c  having list like '%19,%';

SQL fiddle link!2/e3cdf/2

Replace with your field and table name appropriately.

Setting action for back button in navigation controller

The answer from @William is correct however, if the user starts a swipe-to-go-back gesture the viewWillDisappear method is called and even self won't be in the navigation stack (that is, self.navigationController.viewControllers won't contain self), even if the swipe is not completed and the view controller is not actually popped. Thus, the solution would be to:

  1. Disable the swipe-to-go-back gesture in viewDidAppear and only allow using the back button, by using:

    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)])
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
  2. Or simply use viewDidDisappear instead, as follows:

    - (void)viewDidDisappear:(BOOL)animated
        [super viewDidDisappear:animated];
        if (![self.navigationController.viewControllers containsObject:self])
            // back button was pressed or the the swipe-to-go-back gesture was
            // completed. We know this is true because self is no longer
            // in the navigation stack.

VBScript: Using WScript.Shell to Execute a Command Line Program That Accesses Active Directory

This is not a reply (I cant post comments), just few random ideas might be helpful. Unfortunately I've never dealt with citrix, only with regular windows servers.

_0. Ensure you're not a victim of Windows Firewall, or any other personal firewall that selectively blocks processes.

Add 10 minutes Sleep() to the first line of your .NET app, then run both VBScript file and your stand-alone application, run sysinternals process explorer, and compare 2 processes.

_1. Same tab, "command line" and "current directory". Make sure they are the same.

_2. "Environment" tab. Make sure they are the same. Normally child processes inherit the environment, but this behaviour can be easily altered.

The following check is required if by "run my script" you mean anything else then double-clicking the .VBS file:

_3. Image tab, "User". If they differ - it may mean user has no access to the network (like localsystem), or user token restricted to delegation and thus can only access local resources (like in the case of IIS NTLM auth), or user has no access to some local files it wants.

Regex Letters, Numbers, Dashes, and Underscores

You can indeed match all those characters, but it's safer to escape the - so that it is clear that it be taken literally.

If you are using a POSIX variant you can opt to use:


But a since you are including the underscore I would simply use:


(works in all variants)

Evaluating string "3*(4+2)" yield int 18

Many thanks to Ramesh. I used a version of his simple code to pull a string out a database and use it to do boolean operations in my code.

x is a number like 1500 or 2100 or whatever.

function would be a stored evaluation like x > 1400 and x < 1600

function = relation[0].Replace("and","&&").Replace("x",x);

DataTable f_dt = new DataTable();
var f_var = f_dt.Compute(function,"");

if (bool.Parse(f_var.ToString()) { do stuff  }

var self = this?

Just adding to this that in ES6 because of arrow functions you shouldn't need to do this because they capture the this value.

Which HTML Parser is the best?

The best I've seen so far is HtmlCleaner:

HtmlCleaner is open-source HTML parser written in Java. HTML found on Web is usually dirty, ill-formed and unsuitable for further processing. For any serious consumption of such documents, it is necessary to first clean up the mess and bring the order to tags, attributes and ordinary text. For the given HTML document, HtmlCleaner reorders individual elements and produces well-formed XML. By default, it follows similar rules that the most of web browsers use in order to create Document Object Model. However, user may provide custom tag and rule set for tag filtering and balancing.

With HtmlCleaner you can locate any element using XPath.

For other html parsers see this SO question.

Javascript "Not a Constructor" Exception while creating objects

Sometimes it is just how you export and import it. For this error message it could be, that the default keyword is missing.

export default SampleClass {}

Where you instantiate it:

import SampleClass from 'path/to/class';
let sampleClass = new SampleClass();

Option 2, with curly braces:

export SampleClass {}
import { SampleClass } from 'path/to/class';
let sampleClass = new SampleClass();

Curl not recognized as an internal or external command, operable program or batch file

Method 1:\

add "C:\Program Files\cURL\bin" path into system variables Path right-click My Computer and click Properties >advanced > Environment Variables enter image description here

Method 2: (if method 1 not work then)

simple open command prompt with "run as administrator"

ISO time (ISO 8601) in Python

ISO 8601 Time Representation

The international standard ISO 8601 describes a string representation for dates and times. Two simple examples of this format are

2010-12-16 17:22:15

(which both stand for the 16th of December 2010), but the format also allows for sub-second resolution times and to specify time zones. This format is of course not Python-specific, but it is good for storing dates and times in a portable format. Details about this format can be found in the Markus Kuhn entry.

I recommend use of this format to store times in files.

One way to get the current time in this representation is to use strftime from the time module in the Python standard library:

>>> from time import strftime
>>> strftime("%Y-%m-%d %H:%M:%S")
'2010-03-03 21:16:45'

You can use the strptime constructor of the datetime class:

>>> from datetime import datetime
>>> datetime.strptime("2010-06-04 21:08:12", "%Y-%m-%d %H:%M:%S")
datetime.datetime(2010, 6, 4, 21, 8, 12)

The most robust is the Egenix mxDateTime module:

>>> from mx.DateTime.ISO import ParseDateTimeUTC
>>> from datetime import datetime
>>> x = ParseDateTimeUTC("2010-06-04 21:08:12")
>>> datetime.fromtimestamp(x)
datetime.datetime(2010, 3, 6, 21, 8, 12)