Programs & Examples On #Windows live writer

Windows Live Writer is a desktop blog-publishing application that is part of the Windows Live range of products. It features WYSIWYG authoring, photo-publishing and map-publishing functionality, and is currently compatible with a range of blogging platforms.

Change action bar color in android

 ActionBar actionBar;

 actionBar = getActionBar(); 
 ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#93E9FA"));     
 actionBar.setBackgroundDrawable(colorDrawable);

How can I hide the Android keyboard using JavaScript?

Simple jQuery plugin to prevent keyboard showing for inputs:

(function ($) {
    $.fn.preventKeyboard = function () {
        return this
            .filter('input')
            .on('focus', function () {
                $(this)
                    .attr('readonly', 'readonly')
                    .blur()
                    .removeAttr('readonly');
            });
    };
}(jQuery));

Usage

It's useful for date fields with some datepicker attached.

$('#my_datepicker_field').preventKeyboard();

Try the snippet below on your smartphone!

(or see it on https://jsfiddle.net/dtyzLjhw/)

_x000D_
_x000D_
(function($) {_x000D_
  // Create plugin that prevents showing the keyboard_x000D_
  $.fn.preventKeyboard = function() {_x000D_
    return this_x000D_
      .filter('input')_x000D_
      .on('focus', function() {_x000D_
        $(this)_x000D_
          .attr('readonly', 'readonly')_x000D_
          .blur()_x000D_
          .removeAttr('readonly');_x000D_
      });_x000D_
  };_x000D_
_x000D_
  $(document).ready(function($) {_x000D_
    // Date field has datepicker attached._x000D_
    $('input[name=date]').datepicker();_x000D_
_x000D_
    // Prevent showing keyboard for the date field._x000D_
    $('input[name=date]').preventKeyboard();_x000D_
  });_x000D_
}(jQuery));
_x000D_
/*!_x000D_
 * Datepicker for Bootstrap v1.8.0 (https://github.com/uxsolutions/bootstrap-datepicker)_x000D_
 *_x000D_
 * Licensed under the Apache License v2.0 (http://www.apache.org/licenses/LICENSE-2.0)_x000D_
 */_x000D_
_x000D_
.datepicker {_x000D_
  padding: 4px;_x000D_
  -webkit-border-radius: 4px;_x000D_
  -moz-border-radius: 4px;_x000D_
  border-radius: 4px;_x000D_
  direction: ltr;_x000D_
}_x000D_
_x000D_
.datepicker-inline {_x000D_
  width: 220px;_x000D_
}_x000D_
_x000D_
.datepicker-rtl {_x000D_
  direction: rtl;_x000D_
}_x000D_
_x000D_
.datepicker-rtl.dropdown-menu {_x000D_
  left: auto;_x000D_
}_x000D_
_x000D_
.datepicker-rtl table tr td span {_x000D_
  float: right;_x000D_
}_x000D_
_x000D_
.datepicker-dropdown {_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
}_x000D_
_x000D_
.datepicker-dropdown:before {_x000D_
  content: '';_x000D_
  display: inline-block;_x000D_
  border-left: 7px solid transparent;_x000D_
  border-right: 7px solid transparent;_x000D_
  border-bottom: 7px solid #999;_x000D_
  border-top: 0;_x000D_
  border-bottom-color: rgba(0, 0, 0, 0.2);_x000D_
  position: absolute;_x000D_
}_x000D_
_x000D_
.datepicker-dropdown:after {_x000D_
  content: '';_x000D_
  display: inline-block;_x000D_
  border-left: 6px solid transparent;_x000D_
  border-right: 6px solid transparent;_x000D_
  border-bottom: 6px solid #fff;_x000D_
  border-top: 0;_x000D_
  position: absolute;_x000D_
}_x000D_
_x000D_
.datepicker-dropdown.datepicker-orient-left:before {_x000D_
  left: 6px;_x000D_
}_x000D_
_x000D_
.datepicker-dropdown.datepicker-orient-left:after {_x000D_
  left: 7px;_x000D_
}_x000D_
_x000D_
.datepicker-dropdown.datepicker-orient-right:before {_x000D_
  right: 6px;_x000D_
}_x000D_
_x000D_
.datepicker-dropdown.datepicker-orient-right:after {_x000D_
  right: 7px;_x000D_
}_x000D_
_x000D_
.datepicker-dropdown.datepicker-orient-bottom:before {_x000D_
  top: -7px;_x000D_
}_x000D_
_x000D_
.datepicker-dropdown.datepicker-orient-bottom:after {_x000D_
  top: -6px;_x000D_
}_x000D_
_x000D_
.datepicker-dropdown.datepicker-orient-top:before {_x000D_
  bottom: -7px;_x000D_
  border-bottom: 0;_x000D_
  border-top: 7px solid #999;_x000D_
}_x000D_
_x000D_
.datepicker-dropdown.datepicker-orient-top:after {_x000D_
  bottom: -6px;_x000D_
  border-bottom: 0;_x000D_
  border-top: 6px solid #fff;_x000D_
}_x000D_
_x000D_
.datepicker table {_x000D_
  margin: 0;_x000D_
  -webkit-touch-callout: none;_x000D_
  -webkit-user-select: none;_x000D_
  -khtml-user-select: none;_x000D_
  -moz-user-select: none;_x000D_
  -ms-user-select: none;_x000D_
  user-select: none;_x000D_
}_x000D_
_x000D_
.datepicker td,_x000D_
.datepicker th {_x000D_
  text-align: center;_x000D_
  width: 20px;_x000D_
  height: 20px;_x000D_
  -webkit-border-radius: 4px;_x000D_
  -moz-border-radius: 4px;_x000D_
  border-radius: 4px;_x000D_
  border: none;_x000D_
}_x000D_
_x000D_
.table-striped .datepicker table tr td,_x000D_
.table-striped .datepicker table tr th {_x000D_
  background-color: transparent;_x000D_
}_x000D_
_x000D_
.datepicker table tr td.day:hover,_x000D_
.datepicker table tr td.day.focused {_x000D_
  background: #eee;_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
.datepicker table tr td.old,_x000D_
.datepicker table tr td.new {_x000D_
  color: #999;_x000D_
}_x000D_
_x000D_
.datepicker table tr td.disabled,_x000D_
.datepicker table tr td.disabled:hover {_x000D_
  background: none;_x000D_
  color: #999;_x000D_
  cursor: default;_x000D_
}_x000D_
_x000D_
.datepicker table tr td.highlighted {_x000D_
  background: #d9edf7;_x000D_
  border-radius: 0;_x000D_
}_x000D_
_x000D_
.datepicker table tr td.today,_x000D_
.datepicker table tr td.today:hover,_x000D_
.datepicker table tr td.today.disabled,_x000D_
.datepicker table tr td.today.disabled:hover {_x000D_
  background-color: #fde19a;_x000D_
  background-image: -moz-linear-gradient(to bottom, #fdd49a, #fdf59a);_x000D_
  background-image: -ms-linear-gradient(to bottom, #fdd49a, #fdf59a);_x000D_
  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#fdd49a), to(#fdf59a));_x000D_
  background-image: -webkit-linear-gradient(to bottom, #fdd49a, #fdf59a);_x000D_
  background-image: -o-linear-gradient(to bottom, #fdd49a, #fdf59a);_x000D_
  background-image: linear-gradient(to bottom, #fdd49a, #fdf59a);_x000D_
  background-repeat: repeat-x;_x000D_
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fdd49a', endColorstr='#fdf59a', GradientType=0);_x000D_
  border-color: #fdf59a #fdf59a #fbed50;_x000D_
  border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);_x000D_
  filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);_x000D_
  color: #000;_x000D_
}_x000D_
_x000D_
.datepicker table tr td.today:hover,_x000D_
.datepicker table tr td.today:hover:hover,_x000D_
.datepicker table tr td.today.disabled:hover,_x000D_
.datepicker table tr td.today.disabled:hover:hover,_x000D_
.datepicker table tr td.today:active,_x000D_
.datepicker table tr td.today:hover:active,_x000D_
.datepicker table tr td.today.disabled:active,_x000D_
.datepicker table tr td.today.disabled:hover:active,_x000D_
.datepicker table tr td.today.active,_x000D_
.datepicker table tr td.today:hover.active,_x000D_
.datepicker table tr td.today.disabled.active,_x000D_
.datepicker table tr td.today.disabled:hover.active,_x000D_
.datepicker table tr td.today.disabled,_x000D_
.datepicker table tr td.today:hover.disabled,_x000D_
.datepicker table tr td.today.disabled.disabled,_x000D_
.datepicker table tr td.today.disabled:hover.disabled,_x000D_
.datepicker table tr td.today[disabled],_x000D_
.datepicker table tr td.today:hover[disabled],_x000D_
.datepicker table tr td.today.disabled[disabled],_x000D_
.datepicker table tr td.today.disabled:hover[disabled] {_x000D_
  background-color: #fdf59a;_x000D_
}_x000D_
_x000D_
.datepicker table tr td.today:active,_x000D_
.datepicker table tr td.today:hover:active,_x000D_
.datepicker table tr td.today.disabled:active,_x000D_
.datepicker table tr td.today.disabled:hover:active,_x000D_
.datepicker table tr td.today.active,_x000D_
.datepicker table tr td.today:hover.active,_x000D_
.datepicker table tr td.today.disabled.active,_x000D_
.datepicker table tr td.today.disabled:hover.active {_x000D_
  background-color: #fbf069 \9;_x000D_
}_x000D_
_x000D_
.datepicker table tr td.today:hover:hover {_x000D_
  color: #000;_x000D_
}_x000D_
_x000D_
.datepicker table tr td.today.active:hover {_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
.datepicker table tr td.range,_x000D_
.datepicker table tr td.range:hover,_x000D_
.datepicker table tr td.range.disabled,_x000D_
.datepicker table tr td.range.disabled:hover {_x000D_
  background: #eee;_x000D_
  -webkit-border-radius: 0;_x000D_
  -moz-border-radius: 0;_x000D_
  border-radius: 0;_x000D_
}_x000D_
_x000D_
.datepicker table tr td.range.today,_x000D_
.datepicker table tr td.range.today:hover,_x000D_
.datepicker table tr td.range.today.disabled,_x000D_
.datepicker table tr td.range.today.disabled:hover {_x000D_
  background-color: #f3d17a;_x000D_
  background-image: -moz-linear-gradient(to bottom, #f3c17a, #f3e97a);_x000D_
  background-image: -ms-linear-gradient(to bottom, #f3c17a, #f3e97a);_x000D_
  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f3c17a), to(#f3e97a));_x000D_
  background-image: -webkit-linear-gradient(to bottom, #f3c17a, #f3e97a);_x000D_
  background-image: -o-linear-gradient(to bottom, #f3c17a, #f3e97a);_x000D_
  background-image: linear-gradient(to bottom, #f3c17a, #f3e97a);_x000D_
  background-repeat: repeat-x;_x000D_
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f3c17a', endColorstr='#f3e97a', GradientType=0);_x000D_
  border-color: #f3e97a #f3e97a #edde34;_x000D_
  border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);_x000D_
  filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);_x000D_
  -webkit-border-radius: 0;_x000D_
  -moz-border-radius: 0;_x000D_
  border-radius: 0;_x000D_
}_x000D_
_x000D_
.datepicker table tr td.range.today:hover,_x000D_
.datepicker table tr td.range.today:hover:hover,_x000D_
.datepicker table tr td.range.today.disabled:hover,_x000D_
.datepicker table tr td.range.today.disabled:hover:hover,_x000D_
.datepicker table tr td.range.today:active,_x000D_
.datepicker table tr td.range.today:hover:active,_x000D_
.datepicker table tr td.range.today.disabled:active,_x000D_
.datepicker table tr td.range.today.disabled:hover:active,_x000D_
.datepicker table tr td.range.today.active,_x000D_
.datepicker table tr td.range.today:hover.active,_x000D_
.datepicker table tr td.range.today.disabled.active,_x000D_
.datepicker table tr td.range.today.disabled:hover.active,_x000D_
.datepicker table tr td.range.today.disabled,_x000D_
.datepicker table tr td.range.today:hover.disabled,_x000D_
.datepicker table tr td.range.today.disabled.disabled,_x000D_
.datepicker table tr td.range.today.disabled:hover.disabled,_x000D_
.datepicker table tr td.range.today[disabled],_x000D_
.datepicker table tr td.range.today:hover[disabled],_x000D_
.datepicker table tr td.range.today.disabled[disabled],_x000D_
.datepicker table tr td.range.today.disabled:hover[disabled] {_x000D_
  background-color: #f3e97a;_x000D_
}_x000D_
_x000D_
.datepicker table tr td.range.today:active,_x000D_
.datepicker table tr td.range.today:hover:active,_x000D_
.datepicker table tr td.range.today.disabled:active,_x000D_
.datepicker table tr td.range.today.disabled:hover:active,_x000D_
.datepicker table tr td.range.today.active,_x000D_
.datepicker table tr td.range.today:hover.active,_x000D_
.datepicker table tr td.range.today.disabled.active,_x000D_
.datepicker table tr td.range.today.disabled:hover.active {_x000D_
  background-color: #efe24b \9;_x000D_
}_x000D_
_x000D_
.datepicker table tr td.selected,_x000D_
.datepicker table tr td.selected:hover,_x000D_
.datepicker table tr td.selected.disabled,_x000D_
.datepicker table tr td.selected.disabled:hover {_x000D_
  background-color: #9e9e9e;_x000D_
  background-image: -moz-linear-gradient(to bottom, #b3b3b3, #808080);_x000D_
  background-image: -ms-linear-gradient(to bottom, #b3b3b3, #808080);_x000D_
  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#b3b3b3), to(#808080));_x000D_
  background-image: -webkit-linear-gradient(to bottom, #b3b3b3, #808080);_x000D_
  background-image: -o-linear-gradient(to bottom, #b3b3b3, #808080);_x000D_
  background-image: linear-gradient(to bottom, #b3b3b3, #808080);_x000D_
  background-repeat: repeat-x;_x000D_
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#b3b3b3', endColorstr='#808080', GradientType=0);_x000D_
  border-color: #808080 #808080 #595959;_x000D_
  border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);_x000D_
  filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);_x000D_
  color: #fff;_x000D_
  text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);_x000D_
}_x000D_
_x000D_
.datepicker table tr td.selected:hover,_x000D_
.datepicker table tr td.selected:hover:hover,_x000D_
.datepicker table tr td.selected.disabled:hover,_x000D_
.datepicker table tr td.selected.disabled:hover:hover,_x000D_
.datepicker table tr td.selected:active,_x000D_
.datepicker table tr td.selected:hover:active,_x000D_
.datepicker table tr td.selected.disabled:active,_x000D_
.datepicker table tr td.selected.disabled:hover:active,_x000D_
.datepicker table tr td.selected.active,_x000D_
.datepicker table tr td.selected:hover.active,_x000D_
.datepicker table tr td.selected.disabled.active,_x000D_
.datepicker table tr td.selected.disabled:hover.active,_x000D_
.datepicker table tr td.selected.disabled,_x000D_
.datepicker table tr td.selected:hover.disabled,_x000D_
.datepicker table tr td.selected.disabled.disabled,_x000D_
.datepicker table tr td.selected.disabled:hover.disabled,_x000D_
.datepicker table tr td.selected[disabled],_x000D_
.datepicker table tr td.selected:hover[disabled],_x000D_
.datepicker table tr td.selected.disabled[disabled],_x000D_
.datepicker table tr td.selected.disabled:hover[disabled] {_x000D_
  background-color: #808080;_x000D_
}_x000D_
_x000D_
.datepicker table tr td.selected:active,_x000D_
.datepicker table tr td.selected:hover:active,_x000D_
.datepicker table tr td.selected.disabled:active,_x000D_
.datepicker table tr td.selected.disabled:hover:active,_x000D_
.datepicker table tr td.selected.active,_x000D_
.datepicker table tr td.selected:hover.active,_x000D_
.datepicker table tr td.selected.disabled.active,_x000D_
.datepicker table tr td.selected.disabled:hover.active {_x000D_
  background-color: #666666 \9;_x000D_
}_x000D_
_x000D_
.datepicker table tr td.active,_x000D_
.datepicker table tr td.active:hover,_x000D_
.datepicker table tr td.active.disabled,_x000D_
.datepicker table tr td.active.disabled:hover {_x000D_
  background-color: #006dcc;_x000D_
  background-image: -moz-linear-gradient(to bottom, #08c, #0044cc);_x000D_
  background-image: -ms-linear-gradient(to bottom, #08c, #0044cc);_x000D_
  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#08c), to(#0044cc));_x000D_
  background-image: -webkit-linear-gradient(to bottom, #08c, #0044cc);_x000D_
  background-image: -o-linear-gradient(to bottom, #08c, #0044cc);_x000D_
  background-image: linear-gradient(to bottom, #08c, #0044cc);_x000D_
  background-repeat: repeat-x;_x000D_
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#08c', endColorstr='#0044cc', GradientType=0);_x000D_
  border-color: #0044cc #0044cc #002a80;_x000D_
  border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);_x000D_
  filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);_x000D_
  color: #fff;_x000D_
  text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);_x000D_
}_x000D_
_x000D_
.datepicker table tr td.active:hover,_x000D_
.datepicker table tr td.active:hover:hover,_x000D_
.datepicker table tr td.active.disabled:hover,_x000D_
.datepicker table tr td.active.disabled:hover:hover,_x000D_
.datepicker table tr td.active:active,_x000D_
.datepicker table tr td.active:hover:active,_x000D_
.datepicker table tr td.active.disabled:active,_x000D_
.datepicker table tr td.active.disabled:hover:active,_x000D_
.datepicker table tr td.active.active,_x000D_
.datepicker table tr td.active:hover.active,_x000D_
.datepicker table tr td.active.disabled.active,_x000D_
.datepicker table tr td.active.disabled:hover.active,_x000D_
.datepicker table tr td.active.disabled,_x000D_
.datepicker table tr td.active:hover.disabled,_x000D_
.datepicker table tr td.active.disabled.disabled,_x000D_
.datepicker table tr td.active.disabled:hover.disabled,_x000D_
.datepicker table tr td.active[disabled],_x000D_
.datepicker table tr td.active:hover[disabled],_x000D_
.datepicker table tr td.active.disabled[disabled],_x000D_
.datepicker table tr td.active.disabled:hover[disabled] {_x000D_
  background-color: #0044cc;_x000D_
}_x000D_
_x000D_
.datepicker table tr td.active:active,_x000D_
.datepicker table tr td.active:hover:active,_x000D_
.datepicker table tr td.active.disabled:active,_x000D_
.datepicker table tr td.active.disabled:hover:active,_x000D_
.datepicker table tr td.active.active,_x000D_
.datepicker table tr td.active:hover.active,_x000D_
.datepicker table tr td.active.disabled.active,_x000D_
.datepicker table tr td.active.disabled:hover.active {_x000D_
  background-color: #003399 \9;_x000D_
}_x000D_
_x000D_
.datepicker table tr td span {_x000D_
  display: block;_x000D_
  width: 23%;_x000D_
  height: 54px;_x000D_
  line-height: 54px;_x000D_
  float: left;_x000D_
  margin: 1%;_x000D_
  cursor: pointer;_x000D_
  -webkit-border-radius: 4px;_x000D_
  -moz-border-radius: 4px;_x000D_
  border-radius: 4px;_x000D_
}_x000D_
_x000D_
.datepicker table tr td span:hover,_x000D_
.datepicker table tr td span.focused {_x000D_
  background: #eee;_x000D_
}_x000D_
_x000D_
.datepicker table tr td span.disabled,_x000D_
.datepicker table tr td span.disabled:hover {_x000D_
  background: none;_x000D_
  color: #999;_x000D_
  cursor: default;_x000D_
}_x000D_
_x000D_
.datepicker table tr td span.active,_x000D_
.datepicker table tr td span.active:hover,_x000D_
.datepicker table tr td span.active.disabled,_x000D_
.datepicker table tr td span.active.disabled:hover {_x000D_
  background-color: #006dcc;_x000D_
  background-image: -moz-linear-gradient(to bottom, #08c, #0044cc);_x000D_
  background-image: -ms-linear-gradient(to bottom, #08c, #0044cc);_x000D_
  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#08c), to(#0044cc));_x000D_
  background-image: -webkit-linear-gradient(to bottom, #08c, #0044cc);_x000D_
  background-image: -o-linear-gradient(to bottom, #08c, #0044cc);_x000D_
  background-image: linear-gradient(to bottom, #08c, #0044cc);_x000D_
  background-repeat: repeat-x;_x000D_
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#08c', endColorstr='#0044cc', GradientType=0);_x000D_
  border-color: #0044cc #0044cc #002a80;_x000D_
  border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);_x000D_
  filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);_x000D_
  color: #fff;_x000D_
  text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);_x000D_
}_x000D_
_x000D_
.datepicker table tr td span.active:hover,_x000D_
.datepicker table tr td span.active:hover:hover,_x000D_
.datepicker table tr td span.active.disabled:hover,_x000D_
.datepicker table tr td span.active.disabled:hover:hover,_x000D_
.datepicker table tr td span.active:active,_x000D_
.datepicker table tr td span.active:hover:active,_x000D_
.datepicker table tr td span.active.disabled:active,_x000D_
.datepicker table tr td span.active.disabled:hover:active,_x000D_
.datepicker table tr td span.active.active,_x000D_
.datepicker table tr td span.active:hover.active,_x000D_
.datepicker table tr td span.active.disabled.active,_x000D_
.datepicker table tr td span.active.disabled:hover.active,_x000D_
.datepicker table tr td span.active.disabled,_x000D_
.datepicker table tr td span.active:hover.disabled,_x000D_
.datepicker table tr td span.active.disabled.disabled,_x000D_
.datepicker table tr td span.active.disabled:hover.disabled,_x000D_
.datepicker table tr td span.active[disabled],_x000D_
.datepicker table tr td span.active:hover[disabled],_x000D_
.datepicker table tr td span.active.disabled[disabled],_x000D_
.datepicker table tr td span.active.disabled:hover[disabled] {_x000D_
  background-color: #0044cc;_x000D_
}_x000D_
_x000D_
.datepicker table tr td span.active:active,_x000D_
.datepicker table tr td span.active:hover:active,_x000D_
.datepicker table tr td span.active.disabled:active,_x000D_
.datepicker table tr td span.active.disabled:hover:active,_x000D_
.datepicker table tr td span.active.active,_x000D_
.datepicker table tr td span.active:hover.active,_x000D_
.datepicker table tr td span.active.disabled.active,_x000D_
.datepicker table tr td span.active.disabled:hover.active {_x000D_
  background-color: #003399 \9;_x000D_
}_x000D_
_x000D_
.datepicker table tr td span.old,_x000D_
.datepicker table tr td span.new {_x000D_
  color: #999;_x000D_
}_x000D_
_x000D_
.datepicker .datepicker-switch {_x000D_
  width: 145px;_x000D_
}_x000D_
_x000D_
.datepicker .datepicker-switch,_x000D_
.datepicker .prev,_x000D_
.datepicker .next,_x000D_
.datepicker tfoot tr th {_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
.datepicker .datepicker-switch:hover,_x000D_
.datepicker .prev:hover,_x000D_
.datepicker .next:hover,_x000D_
.datepicker tfoot tr th:hover {_x000D_
  background: #eee;_x000D_
}_x000D_
_x000D_
.datepicker .prev.disabled,_x000D_
.datepicker .next.disabled {_x000D_
  visibility: hidden;_x000D_
}_x000D_
_x000D_
.datepicker .cw {_x000D_
  font-size: 10px;_x000D_
  width: 12px;_x000D_
  padding: 0 2px 0 5px;_x000D_
  vertical-align: middle;_x000D_
}_x000D_
_x000D_
.input-append.date .add-on,_x000D_
.input-prepend.date .add-on {_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
.input-append.date .add-on i,_x000D_
.input-prepend.date .add-on i {_x000D_
  margin-top: 3px;_x000D_
}_x000D_
_x000D_
.input-daterange input {_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.input-daterange input:first-child {_x000D_
  -webkit-border-radius: 3px 0 0 3px;_x000D_
  -moz-border-radius: 3px 0 0 3px;_x000D_
  border-radius: 3px 0 0 3px;_x000D_
}_x000D_
_x000D_
.input-daterange input:last-child {_x000D_
  -webkit-border-radius: 0 3px 3px 0;_x000D_
  -moz-border-radius: 0 3px 3px 0;_x000D_
  border-radius: 0 3px 3px 0;_x000D_
}_x000D_
_x000D_
.input-daterange .add-on {_x000D_
  display: inline-block;_x000D_
  width: auto;_x000D_
  min-width: 16px;_x000D_
  height: 20px;_x000D_
  padding: 4px 5px;_x000D_
  font-weight: normal;_x000D_
  line-height: 20px;_x000D_
  text-align: center;_x000D_
  text-shadow: 0 1px 0 #fff;_x000D_
  vertical-align: middle;_x000D_
  background-color: #eee;_x000D_
  border: 1px solid #ccc;_x000D_
  margin-left: -5px;_x000D_
  margin-right: -5px;_x000D_
}_x000D_
_x000D_
.datepicker.dropdown-menu {_x000D_
  position: absolute;_x000D_
  top: 100%;_x000D_
  left: 0;_x000D_
  z-index: 1000;_x000D_
  float: left;_x000D_
  display: none;_x000D_
  min-width: 160px;_x000D_
  list-style: none;_x000D_
  background-color: #fff;_x000D_
  border: 1px solid #ccc;_x000D_
  border: 1px solid rgba(0, 0, 0, 0.2);_x000D_
  -webkit-border-radius: 5px;_x000D_
  -moz-border-radius: 5px;_x000D_
  border-radius: 5px;_x000D_
  -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);_x000D_
  -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);_x000D_
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);_x000D_
  -webkit-background-clip: padding-box;_x000D_
  -moz-background-clip: padding;_x000D_
  background-clip: padding-box;_x000D_
  *border-right-width: 2px;_x000D_
  *border-bottom-width: 2px;_x000D_
  color: #333333;_x000D_
  font-size: 13px;_x000D_
  line-height: 20px;_x000D_
}_x000D_
_x000D_
.datepicker.dropdown-menu th,_x000D_
.datepicker.datepicker-inline th,_x000D_
.datepicker.dropdown-menu td,_x000D_
.datepicker.datepicker-inline td {_x000D_
  padding: 4px 5px;_x000D_
}_x000D_
_x000D_
_x000D_
/*# sourceMappingURL=bootstrap-datepicker.standalone.css.map */
_x000D_
<!-- Require libs to show example -->_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/js/bootstrap-datepicker.min.js"></script>_x000D_
_x000D_
<!-- Simple form with two text fields -->_x000D_
<form>_x000D_
  <input name="foo" type=text value="Click to see keyboard" />_x000D_
  <br/><br/><br/>_x000D_
  <input name="date" type=text />_x000D_
</form>
_x000D_
_x000D_
_x000D_

How do I create a simple Qt console application in C++?

I managed to create a simple console "hello world" with QT Creator

used creator 2.4.1 and QT 4.8.0 on windows 7

two ways to do this

Plain C++

do the following

  1. File- new file project
  2. under projects select : other Project
  3. select "Plain C++ Project"
  4. enter project name 5.Targets select Desktop 'tick it'
  5. project managment just click next
  6. you can use c++ commands as normal c++

or

QT Console

  1. File- new file project
  2. under projects select : other Project
  3. select QT Console Application
  4. Targets select Desktop 'tick it'
  5. project managment just click next
  6. add the following lines (all the C++ includes you need)
  7. add "#include 'iostream' "
  8. add "using namespace std; "
  9. after QCoreApplication a(int argc, cghar *argv[]) 10 add variables, and your program code..

example: for QT console "hello world"

file - new file project 'project name '

other projects - QT Console Application

Targets select 'Desktop'

project management - next

code:

    #include <QtCore/QCoreApplication>
    #include <iostream>
    using namespace std;
    int main(int argc, char *argv[])
    {
     QCoreApplication a(argc, argv);
     cout<<" hello world";
     return a.exec();
     }

ctrl -R to run

compilers used for above MSVC 2010 (QT SDK) , and minGW(QT SDK)

hope this helps someone

As I have just started to use QT recently and also searched the Www for info and examples to get started with simple examples still searching...

UICollectionView - Horizontal scroll, horizontal layout?

You need to reduce the height of UICollectionView to its cell / item height and select "Horizontal" from the "Scroll Direction" as seen in the screenshot below. Then it will scroll horizontally depending on the numberOfItems you have returned in its datasource implementation.

enter image description here

How to set default text for a Tkinter Entry widget

Use Entry.insert. For example:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()

Or use textvariable option:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()

The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

- What is @objc inference? What is going on?

In Swift 3, the compiler infers @objc in a number of places so you wouldn't have to. In other words, it makes sure to add @objc for you!

In Swift 4, the compiler no longer does this (as much). You now must add @objc explicitly.

By default, if you have a pre-Swift 4 project, you will get warnings about this. In a Swift 4 project, you will get build errors. This is controlled via the SWIFT_SWIFT3_OBJC_INFERENCE build setting. In a pre-Swift 4 project this is set to On. I would recommend to set this to Default (or Off), which is now the default option on a new project.

It will take some time to convert everything, but since it's the default for Swift 4, it's worth doing it.

- How do I stop the compiler warnings/errors?

There are two ways to go about converting your code so the compiler doesn't complain.

One is to use @objc on each function or variable that needs to be exposed to the Objective-C runtime:

@objc func foo() {

}

The other is to use @objcMembers by a Class declaration. This makes sure to automatically add @objc to ALL the functions and variables in the class. This is the easy way, but it has a cost, for example, it can increase the size of your application by exposing functions that did not need to be exposed.

@objcMembers class Test {

}

- What is @objc and why is it necessary?

If you introduce new methods or variables to a Swift class, marking them as @objc exposes them to the Objective-C runtime. This is necessary when you have Objective-C code that uses your Swift class, or, if you are using Objective-C-type features like Selectors. For example, the target-action pattern: button.addTarget(self, action:#selector(didPressButton), for:.touchUpInside)

- Why would I not mark everything @objc?

There are negatives that come with marking something as @objc:

  • Increased application binary size
  • No function overloading

Please keep in mind that this is a very high-level summary and that it is more complicated than I wrote. I would recommend reading the actual proposal for more information.

Sources:

Returning a pointer to a vector element in c++

Say, you have the following:

std::vector<myObject>::const_iterator first = vObj.begin();

Then the first object in the vector is: *first. To get the address, use: &(*first).

However, in keeping with the STL design, I'd suggest return an iterator instead if you plan to pass it around later on to STL algorithms.

How to make a variable accessible outside a function?

Your variable declarations and their scope are correct. The problem you are facing is that the first AJAX request may take a little bit time to finish. Therefore, the second URL will be filled with the value of sID before the its content has been set. You have to remember that AJAX request are normally asynchronous, i.e. the code execution goes on while the data is being fetched in the background.

You have to nest the requests:

$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   obj = name;   // sID is only now available!   sID = obj.id;   console.log(sID); }); 


Clean up your code!

  • Put the second request into a function
  • and let it accept sID as a parameter, so you don't have to declare it globally anymore! (Global variables are almost always evil!)
  • Remove sID and obj variables - name.id is sufficient unless you really need the other variables outside the function.


$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   // We don't need sID or obj here - name.id is sufficient   console.log(name.id);    doSecondRequest(name.id); });  /// TODO Choose a better name function doSecondRequest(sID) {   $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function(stats){         console.log(stats);   }); } 

Hapy New Year :)

moving committed (but not pushed) changes to a new branch after pull

  1. Checkout fresh copy of you sources

    git clone ........

  2. Make branch from desired position

    git checkout {position} git checkout -b {branch-name}

  3. Add remote repository

    git remote add shared ../{original sources location}.git

  4. Get remote sources

    git fetch shared

  5. Checkout desired branch

    git checkout {branch-name}

  6. Merge sources

    git merge shared/{original branch from shared repository}

String Concatenation in EL

Since Expression Language 3.0, it is valid to use += operator for string concatenation.

${(empty value)? "none" : value += " enabled"}  // valid as of EL 3.0

Quoting EL 3.0 Specification.

String Concatenation Operator

To evaluate

A += B 
  • Coerce A and B to String.
  • Return the concatenated string of A and B.

Free space in a CMD shell

Using this command you can find all partitions, size & free space: wmic logicaldisk get size, freespace, caption

enable cors in .htaccess

Will be work 100%, Apply in .htaccess:

# Enable cross domain access control
SetEnvIf Origin "^http(s)?://(.+\.)?(1xyz\.com|2xyz\.com)$" REQUEST_ORIGIN=$0
Header always set Access-Control-Allow-Origin %{REQUEST_ORIGIN}e env=REQUEST_ORIGIN
Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header always set Access-Control-Allow-Headers "x-test-header, Origin, X-Requested-With, Content-Type, Accept"

# Force to request 200 for options
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule .* / [R=200,L]

Create sequence of repeated values, in sequence?

For your example, Dirk's answer is perfect. If you instead had a data frame and wanted to add that sort of sequence as a column, you could also use group from groupdata2 (disclaimer: my package) to greedily divide the datapoints into groups.

# Attach groupdata2
library(groupdata2)
# Create a random data frame
df <- data.frame("x" = rnorm(27))
# Create groups with 5 members each (except last group)
group(df, n = 5, method = "greedy")
         x .groups
     <dbl> <fct>  
 1  0.891  1      
 2 -1.13   1      
 3 -0.500  1      
 4 -1.12   1      
 5 -0.0187 1      
 6  0.420  2      
 7 -0.449  2      
 8  0.365  2      
 9  0.526  2      
10  0.466  2      
# … with 17 more rows

There's a whole range of methods for creating this kind of grouping factor. E.g. by number of groups, a list of group sizes, or by having groups start when the value in some column differs from the value in the previous row (e.g. if a column is c("x","x","y","z","z") the grouping factor would be c(1,1,2,3,3).

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?

The linked list holds operations on the shared data structure.

For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).

In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.

In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.

database attached is read only

Giving the sql service account 'NT SERVICE\MSSQLSERVER' "Full Control" of the database files

If you have access to the server files/folders you can try this solution that worked for me:

SQL Server 2012 on Windows Server 2008 R2

  1. Right click the database (mdf/ldf) file or folder and select "Properties".
  2. Select "Security" tab and click the "Edit" button.
  3. Click the "Add" button.
  4. Enter the object name to select as 'NT SERVICE\MSSQLSERVER' and click "Check Names" button.
  5. Select the MSSQLSERVER (RDN) and click the "OK" button twice.
  6. Give this service account "Full control" to the file or folder.
  7. Back in SSMS, right click the database and select "Properties".
  8. Under "Options", scroll down to the "State" section and change "Database Read-Only" from "True" to "False".

Trying to git pull with error: cannot open .git/FETCH_HEAD: Permission denied

This worked for me:

  1. Right click .git folder
  2. click get info
  3. set permission to your user
  4. click the Cog icon and click apply to enclosed items

No more permission denied errors in git.

How to catch all exceptions in c# using try and catch?

Both approaches will catch all exceptions. There is no significant difference between your two code examples except that the first will generate a compiler warning because ex is declared but not used.

But note that some exceptions are special and will be rethrown automatically.

ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block.

http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx


As mentioned in the comments, it is usually a very bad idea to catch and ignore all exceptions. Usually you want to do one of the following instead:

  • Catch and ignore a specific exception that you know is not fatal.

    catch (SomeSpecificException)
    {
        // Ignore this exception.
    }
    
  • Catch and log all exceptions.

    catch (Exception e)
    {
        // Something unexpected went wrong.
        Log(e);
        // Maybe it is also necessary to terminate / restart the application.
    }
    
  • Catch all exceptions, do some cleanup, then rethrow the exception.

    catch
    {
        SomeCleanUp();
        throw;
    }
    

Note that in the last case the exception is rethrown using throw; and not throw ex;.

Using sed, Insert a line above or below the pattern?

To append after the pattern: (-i is for in place replace). line1 and line2 are the lines you want to append(or prepend)

sed -i '/pattern/a \
line1 \
line2' inputfile

Output:

#cat inputfile
 pattern
 line1 line2 

To prepend the lines before:

sed -i '/pattern/i \
line1 \
line2' inputfile

Output:

#cat inputfile
 line1 line2 
 pattern

Convert String to double in Java

This is what I would do

    public static double convertToDouble(String temp){
       String a = temp;
       //replace all commas if present with no comma
       String s = a.replaceAll(",","").trim(); 
      // if there are any empty spaces also take it out.          
      String f = s.replaceAll(" ", ""); 
      //now convert the string to double
      double result = Double.parseDouble(f); 
    return result; // return the result
}

For example you input the String "4 55,63. 0 " the output will the double number 45563.0

Javascript: How to pass a function with string parameters as a parameter to another function

One way would be to just escape the quotes properly:

<input type="button" value="click" id="mybtn"
       onclick="myfunction('/myController/myAction', 
               'myfuncionOnOK(\'/myController2/myAction2\', 
                   \'myParameter2\');',
               'myfuncionOnCancel(\'/myController3/myAction3\', 
                   \'myParameter3\');');">

In this case, though, I think a better way to handle this would be to wrap the two handlers in anonymous functions:

<input type="button" value="click" id="mybtn"
       onclick="myfunction('/myController/myAction', 
                function() { myfuncionOnOK('/myController2/myAction2', 
                             'myParameter2'); },
                function() { myfuncionOnCancel('/myController3/myAction3', 
                             'myParameter3'); });">

And then, you could call them from within myfunction like this:

function myfunction(url, onOK, onCancel)
{
    // Do whatever myfunction would normally do...

    if (okClicked)
    {
        onOK();
    }

    if (cancelClicked)
    {
        onCancel();
    }
}

That's probably not what myfunction would actually look like, but you get the general idea. The point is, if you use anonymous functions, you have a lot more flexibility, and you keep your code a lot cleaner as well.

Show div on scrollDown after 800px

You can also, do this.

$(window).on("scroll", function () {
   if ($(this).scrollTop() > 800) {
      #code here
   } else {
      #code here
   }
});

How to debug on a real device (using Eclipse/ADT)

Sometimes you need to reset ADB. To do that, in Eclipse, go:

Window>> Show View >> Android (Might be found in the "Other" option)>>Devices

in the device Tab, click the down arrow, and choose reset adb.

SQL Statement with multiple SETs and WHEREs

No, you would need to create a seperate query for each update.

How do I use TensorFlow GPU?

Follow the steps in the latest version of the documentation. Note: GPU and CPU functionality is now combined in a single tensorflow package

pip install tensorflow

# OLDER VERSIONS pip install tensorflow-gpu

https://www.tensorflow.org/install/gpu

This is a great guide for installing drivers and CUDA if needed: https://www.quantstart.com/articles/installing-tensorflow-22-on-ubuntu-1804-with-an-nvidia-gpu/

Webdriver findElements By xpath

The XPath turns into this:

Get me all of the div elements that have an id equal to container.

As for getting the first etc, you have two options.

Turn it into a .findElement() - this will just return the first one for you anyway.

or

To explicitly do this in XPath, you'd be looking at:

(//div[@id='container'])[1]

for the first one, for the second etc:

(//div[@id='container'])[2]

Then XPath has a special indexer, called last, which would (you guessed it) get you the last element found:

(//div[@id='container'])[last()]

Worth mentioning that XPath indexers will start from 1 not 0 like they do in most programming languages.

As for getting the parent 'node', well, you can use parent:

//div[@id='container']/parent::*

That would get the div's direct parent.

You could then go further and say I want the first *div* with an id of container, and I want his parent:

(//div[@id='container'])[1]/parent::*

Hope that helps!

how to get all child list from Firebase android

your problem is why your code doesn't work.

this your code:

Firebase ref = new Firebase(FIREBASE_URL);

  ref.addValueEventListener(new ValueEventListener() {
      @Override
      public void onDataChange(DataSnapshot snapshot) {
          Log.e("Count " ,""+snapshot.getChildrenCount());
          for (DataSnapshot postSnapshot: snapshot.getChildren()) {
            <YourClass> post = postSnapshot.getValue(<YourClass>.class);
            Log.e("Get Data", post.<YourMethod>());
          }
      }
      @Override
      public void onCancelled(FirebaseError firebaseError) {
          Log.e("The read failed: " ,firebaseError.getMessage());
      }
  })

you miss the simplest thing: getChildren()

FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference reference = FirebaseAuth.getInstance().getReference("Donald Trump");

reference.addValueEventListener(new ValueEventListener() {
   @Override
   public void onDataChange(DataSnapshot dataSnapshot) {

            int count = (int) dataSnapshot.getChildrenCount(); // retrieve number of childrens under Donald Trump

            String[] hairColors = new String[count];

            index = 0;
            for (DataSnapshot datas : dataSnapshot.getChildren()){

                hairColors[index] = datas.getValue(String.class);

            }
            index ++

            for (int i = 0; i < count; i++)
            Toast(MainActivity.this, "hairColors : " + hairColors[i], toast.LENGTH_SHORT).show();

            }

    }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }

    });

Replace multiple strings at once

You could extend the String object with your own function that does what you need (useful if there's ever missing functionality):

String.prototype.replaceArray = function(find, replace) {
  var replaceString = this;
  for (var i = 0; i < find.length; i++) {
    replaceString = replaceString.replace(find[i], replace[i]);
  }
  return replaceString;
};

For global replace you could use regex:

String.prototype.replaceArray = function(find, replace) {
  var replaceString = this;
  var regex; 
  for (var i = 0; i < find.length; i++) {
    regex = new RegExp(find[i], "g");
    replaceString = replaceString.replace(regex, replace[i]);
  }
  return replaceString;
};

To use the function it'd be similar to your PHP example:

var textarea = $(this).val();
var find = ["<", ">", "\n"];
var replace = ["&lt;", "&gt;", "<br/>"];
textarea = textarea.replaceArray(find, replace);

LINQ select in C# dictionary

One way would be to first flatten the list with a SelectMany:

subList.SelectMany(m => m).Where(k => k.Key.Equals("valueTitle"));

JQUERY ajax passing value from MVC View to Controller

View Data
==============


 @model IEnumerable<DemoApp.Models.BankInfo>
<p>
    <b>Search Results</b>
</p>
@if (!Model.Any())
{
    <tr>
        <td colspan="4" style="text-align:center">
            No Bank(s) found
        </td>
    </tr>
}
else
{
    <table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Address)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Postcode)
            </th>
            <th></th>
        </tr>

        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Name)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Address)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Postcode)
                </td>
                <td>
                    <input type="button" class="btn btn-default bankdetails" value="Select" data-id="@item.Id" />
                </td>
            </tr>
        }
    </table>
}


<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("#btnSearch").off("click.search").on("click.search", function () {
            if ($("#SearchBy").val() != '') {
                $.ajax({
                    url: '/home/searchByName',
                    data: { 'name': $("#SearchBy").val() },
                    dataType: 'html',
                    success: function (data) {
                        $('#dvBanks').html(data);
                    }
                });
            }
            else {
                alert('Please enter Bank Name');
            }
        });
}
});


public ActionResult SearchByName(string name)
        {
            var banks = GetBanksInfo();
            var filteredBanks = banks.Where(x => x.Name.ToLower().Contains(name.ToLower())).ToList();
            return PartialView("_banks", filteredBanks);
        }

        /// <summary>
        /// Get List of Banks Basically it should get from Database 
        /// </summary>
        /// <returns></returns>
        private List<BankInfo> GetBanksInfo()
        {
            return new List<BankInfo>
            {
                new BankInfo {Id = 1, Name = "Bank of America", Address = "1438 Potomoc Avenue, Pittsburge", Postcode = "PA 15220"  },
                new BankInfo {Id = 2, Name = "Bank of America", Address = "643 River Hwy, Mooresville", Postcode = "NC 28117"  },
                new BankInfo {Id = 3, Name = "Bank of Barroda", Address = "643 Hyderabad", Postcode = "500061"  },
                new BankInfo {Id = 4, Name = "State Bank of India", Address = "AsRao Nagar", Postcode = "500061"  },
                new BankInfo {Id = 5, Name = "ICICI", Address = "AsRao Nagar", Postcode = "500061"  }
            };
        }

How to tell a Mockito mock object to return something different the next time it is called?

First of all don't make the mock static. Make it a private field. Just put your setUp class in the @Before not @BeforeClass. It might be run a bunch, but it's cheap.

Secondly, the way you have it right now is the correct way to get a mock to return something different depending on the test.

How can I develop for iPhone using a Windows development machine?

If you want it to be legitimate, you have two options, cloud based Mac solutions or cross-platform development tools. You may consider the hackintosh approach or virtual machines if you don't care about legal stuff. If you have a decent PC, running a virtual machine would be the easiest way to go. You may never know which hardware will have driver issues on a hackintosh.

I've tried all these approaches and they all have pros and cons, but for the second group, I feel kind of guilty. I develop apps to make a living and I wouldn't want to rip off someone else for it.

If you are making a small project, cloud based Macs may prove useful. Rent it for a short time, develop your project and off you go. Don't bother learning anything new.

However, if your project is getting big, cross-platform frameworks seem to be the only alternative. The critical thing is that you need to choose wisely. There are so many hybrid frameworks, but what they do can be summarized in one sentence as "diplaying web pages in an app wrapper" and developers' negative experience with hybrid frameworks also affects native frameworks.

I tried three of these (Titanium, Smartface and Xamarin) and they all claim to produce "real native output" and in my opinion their claims are correct. You need to test and see it yoursrlf, it's not easy to describe the native feeling. In a previous comment, it was indicated that it takes some effort to learn these platforms, but once you get to know them, you can develop not just iOS applications but Android applications as well, all with the common code base. And of course, they are much cheaper than a cloud Mac. Some of them are even free. You would need a Mac only for store submission.

If you know JavaScript, try Titanium and Smartface and if you know C#, try Xamarin. Just note that for the device simuator, Titanium is dependent on a Mac, but Smartface has a simulator app for Windows development and it works better than I expected. On the other hand, Xamarin requires a Mac in your network.

How do I determine the current operating system with Node.js

With Node.js v6 (and above) there is a dedicated os module, which provides a number of operating system-related utility methods.

On my Windows 10 machine it reports the following:

var os = require('os');

console.log(os.type()); // "Windows_NT"
console.log(os.release()); // "10.0.14393"
console.log(os.platform()); // "win32"

You can read it's full documentation here: https://nodejs.org/api/os.html#os_os_type

Alphanumeric, dash and underscore but no spaces regular expression check JavaScript

You shouldn't use String.match but RegExp.prototype.test (i.e. /abc/.test("abcd")) instead of String.search() if you're only interested in a boolean value. You also need to repeat your character class as explained in the answer by Andy E:

var regexp = /^[a-zA-Z0-9-_]+$/;

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Jaqen H'ghar is spot-on. A third way is to:

  1. Go to Manage NuGet Packages
  2. Install Microsoft.jQuery.Unobtrusive.Validation
  3. Open Global.asax.cs file and add this code inside the Application_Start method

Code that runs on application startup:

ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition {
    Path = "~/Scripts/jquery.validate.unobtrusive.min.js",
    DebugPath = "~/Scripts/jquery.validate.unobtrusive.min.js"
});

Using "like" wildcard in prepared statement

String fname = "Sam\u0025";

PreparedStatement ps= conn.prepareStatement("SELECT * FROM Users WHERE User_FirstName LIKE ? ");

ps.setString(1, fname);

jQuery multiple conditions within if statement

i == 'InvKey' && i == 'PostDate' will never be true, since i can never equal two different things at once.

You're probably trying to write

if (i !== 'InvKey' && i !== 'PostDate')) 

How connect Postgres to localhost server using pgAdmin on Ubuntu?

You haven't created a user db. If its just a fresh install, the default user is postgres and the password should be blank. After you access it, you can create the users you need.

How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?

let layout = myCollectionView.collectionViewLayout as? UICollectionViewFlowLayout
layout?.minimumLineSpacing = 8

MySQL: Invalid use of group function

You need to use HAVING, not WHERE.

The difference is: the WHERE clause filters which rows MySQL selects. Then MySQL groups the rows together and aggregates the numbers for your COUNT function.

HAVING is like WHERE, only it happens after the COUNT value has been computed, so it'll work as you expect. Rewrite your subquery as:

(                  -- where that pid is in the set:
SELECT c2.pid                  -- of pids
FROM Catalog AS c2             -- from catalog
WHERE c2.pid = c1.pid
HAVING COUNT(c2.sid) >= 2)

Visual Studio: How to show Overloads in IntelliSense?

  • The command Edit.ParameterInfo (mapped to Ctrl+Shift+Space by default) will show the overload tooltip if it's invoked when the cursor is inside the parameter brackets of a method call.

  • The command Edit.QuickInfo (mapped to Ctrl+KCtrl+I by default) will show the tooltip that you'd see if you moused over the cursor location.

Setting dynamic scope variables in AngularJs - scope.<some_string>

Please keep in mind: this is just a JavaScript thing and has nothing to do with Angular JS. So don't be confused about the magical '$' sign ;)

The main problem is that this is an hierarchical structure.

console.log($scope.life.meaning);  // <-- Nope! This is undefined.
=> a.b.c

This is undefined because "$scope.life" is not existing but the term above want to solve "meaning".

A solution should be

var the_string = 'lifeMeaning';
$scope[the_string] = 42;
console.log($scope.lifeMeaning);
console.log($scope['lifeMeaning']);

or with a little more efford.

var the_string_level_one = 'life';
var the_string_level_two = the_string_level_one + '.meaning';
$scope[the_string_level_two ] = 42;
console.log($scope.life.meaning);
console.log($scope['the_string_level_two ']);

Since you can access a structural objecte with

var a = {};
a.b = "ab";
console.log(a.b === a['b']);

There are several good tutorials about this which guide you well through the fun with JavaScript.

There is something about the

$scope.$apply();
do...somthing...bla...bla

Go and search the web for 'angular $apply' and you will find information about the $apply function. And you should use is wisely more this way (if you are not alreay with a $apply phase).

$scope.$apply(function (){
    do...somthing...bla...bla
})

Empty responseText from XMLHttpRequest

Had a similar problem to yours. What we had to do is use the document.domain solution found here:

Ways to circumvent the same-origin policy

We also needed to change thins on the web service side. Used the "Access-Control-Allow-Origin" header found here:

https://developer.mozilla.org/En/HTTP_access_control

Java 8 LocalDate Jackson format

annotation in Pojo without using additional dependencies

@DateTimeFormat (pattern = "yyyy/MM/dd", iso = DateTimeFormat.ISO.DATE)
private LocalDate enddate;

MySQL: determine which database is selected?

SELECT DATABASE() worked in PHPMyAdmin.

Accessing elements by type in javascript

The sizzle selector engine (what powers JQuery) is perfectly geared up for this:

var elements = $('input[type=text]');

Or

var elements = $('input:text');

Check if object is a jQuery object

You can check if the object is produced by JQuery with the jquery property:

myObject.jquery // 3.3.1

=> return the number of the JQuery version if the object produced by JQuery. => otherwise, it returns undefined

SQL Server - Convert date field to UTC

If they're all local to you, then here's the offset:

SELECT GETDATE() AS CurrentTime, GETUTCDATE() AS UTCTime

and you should be able to update all the data using:

UPDATE SomeTable
   SET DateTimeStamp = DATEADD(hh, DATEDIFF(hh, GETDATE(), GETUTCDATE()), DateTimeStamp)

Would that work, or am I missing another angle of this problem?

Linux Shell Script For Each File in a Directory Grab the filename and execute a program

for i in *.xls ; do 
  [[ -f "$i" ]] || continue
  xls2csv "$i" "${i%.xls}.csv"
done

The first line in the do checks if the "matching" file really exists, because in case nothing matches in your for, the do will be executed with "*.xls" as $i. This could be horrible for your xls2csv.

Struct memory layout in C

It's implementation-specific, but in practice the rule (in the absence of #pragma pack or the like) is:

  • Struct members are stored in the order they are declared. (This is required by the C99 standard, as mentioned here earlier.)
  • If necessary, padding is added before each struct member, to ensure correct alignment.
  • Each primitive type T requires an alignment of sizeof(T) bytes.

So, given the following struct:

struct ST
{
   char ch1;
   short s;
   char ch2;
   long long ll;
   int i;
};
  • ch1 is at offset 0
  • a padding byte is inserted to align...
  • s at offset 2
  • ch2 is at offset 4, immediately after s
  • 3 padding bytes are inserted to align...
  • ll at offset 8
  • i is at offset 16, right after ll
  • 4 padding bytes are added at the end so that the overall struct is a multiple of 8 bytes. I checked this on a 64-bit system: 32-bit systems may allow structs to have 4-byte alignment.

So sizeof(ST) is 24.

It can be reduced to 16 bytes by rearranging the members to avoid padding:

struct ST
{
   long long ll; // @ 0
   int i;        // @ 8
   short s;      // @ 12
   char ch1;     // @ 14
   char ch2;     // @ 15
} ST;

Java: Sending Multiple Parameters to Method

Suppose you have void method that prints many objects;

public static void print( Object... values){
   for(Object c : values){
      System.out.println(c);
   }
}

Above example I used vararge as an argument that accepts values from 0 to N.

From comments: What if 2 strings and 5 integers ??

Answer:

print("string1","string2",1,2,3,4,5);

Why, Fatal error: Class 'PHPUnit_Framework_TestCase' not found in ...?

If you have Centos or other Linux distribution you have to install phpunit package, I did that with yum install phpunit and it worked. Maybe you can have to add a repository, but I think it has to work smooth with the default ones (I have CentOS 7)

Regular Expressions and negating a whole character group

Using a character class such as [^ab] will match a single character that is not within the set of characters. (With the ^ being the negating part).

To match a string which does not contain the multi-character sequence ab, you want to use a negative lookahead:

^(?:(?!ab).)+$


And the above expression disected in regex comment mode is:

(?x)    # enable regex comment mode
^       # match start of line/string
(?:     # begin non-capturing group
  (?!   # begin negative lookahead
    ab  # literal text sequence ab
  )     # end negative lookahead
  .     # any single character
)       # end non-capturing group
+       # repeat previous match one or more times
$       # match end of line/string

How to update nested state properties in React

Create a copy of the state:

let someProperty = JSON.parse(JSON.stringify(this.state.someProperty))

make changes in this object:

someProperty.flag = "false"

now update the state

this.setState({someProperty})

How do I customize Facebook's sharer.php

UPDATE:

This answer is outdated.

Like @jack-marchetti stated in his comment, and @devantoine with the link: https://developers.facebook.com/x/bugs/357750474364812/

Facebook has changed how the sharer.php works, as Ibrahim Faour replies to the bug filed with Facebook.

The sharer will no longer accept custom parameters and facebook will pull the information that is being displayed in the preview the same way that it would appear on facebook as a post, from the url OG meta tags.


Try this (via Javascript in this example):

'http://www.facebook.com/sharer.php?s=100&p[title]='+encodeURIComponent('this is a title') + '&p[summary]=' + encodeURIComponent('description here') + '&p[url]=' + encodeURIComponent('http://www.nufc.com') + '&p[images][0]=' + encodeURIComponent('http://www.somedomain.com/image.jpg')

I tried this quickly without the image part and the sharer.php window appears pre-populated, so it looks like a solution.

I found this via this SO article:

Want custom title / image / description in facebook share link from a flash app

and this link contained in an answer from Lelis718:

http://www.daddydesign.com/wordpress/how-to-create-a-custom-facebook-share-button-for-your-iframe-tab/

so all credit to Lelis718 for this answer.

[EDIT 3rd May 2013] - seems like the original URL i had here no longer works for me without also including "s=100" in the query string - no idea why but have updated accordingly

XPath contains(text(),'some string') doesn't work when used with node with more than one Text subnode

The <Comment> tag contains two text nodes and two <br> nodes as children.

Your xpath expression was

//*[contains(text(),'ABC')]

To break this down,

  1. * is a selector that matches any element (i.e. tag) -- it returns a node-set.
  2. The [] are a conditional that operates on each individual node in that node set. It matches if any of the individual nodes it operates on match the conditions inside the brackets.
  3. text() is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.
  4. contains is a function that operates on a string. If it is passed a node set, the node set is converted into a string by returning the string-value of the node in the node-set that is first in document order. Hence, it can match only the first text node in your <Comment> element -- namely BLAH BLAH BLAH. Since that doesn't match, you don't get a <Comment> in your results.

You need to change this to

//*[text()[contains(.,'ABC')]]
  1. * is a selector that matches any element (i.e. tag) -- it returns a node-set.
  2. The outer [] are a conditional that operates on each individual node in that node set -- here it operates on each element in the document.
  3. text() is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.
  4. The inner [] are a conditional that operates on each node in that node set -- here each individual text node. Each individual text node is the starting point for any path in the brackets, and can also be referred to explicitly as . within the brackets. It matches if any of the individual nodes it operates on match the conditions inside the brackets.
  5. contains is a function that operates on a string. Here it is passed an individual text node (.). Since it is passed the second text node in the <Comment> tag individually, it will see the 'ABC' string and be able to match it.

Convenient way to parse incoming multipart/form-data parameters in a Servlet

Solutions:

Solution A:

  1. Download http://www.servlets.com/cos/index.html
  2. Invoke getParameters() on com.oreilly.servlet.MultipartRequest

Solution B:

  1. Download http://jakarta.Apache.org/commons/fileupload/
  2. Invoke readHeaders() in org.apache.commons.fileupload.MultipartStream

Solution C:

  1. Download http://users.boone.net/wbrameld/multipartformdata/
  2. Invoke getParameter on com.bigfoot.bugar.servlet.http.MultipartFormData

Solution D:

Use Struts. Struts 1.1 handles this automatically.

Reference: http://www.jguru.com/faq/view.jsp?EID=1045507

AJAX POST and Plus Sign ( + ) -- How to Encode?

my problem was with the accents (á É ñ ) and the plus sign (+) when i to try to save javascript "code examples" to mysql:

my solution (not the better way, but it works):

javascript:

function replaceAll( text, busca, reemplaza ){
  while (text.toString().indexOf(busca) != -1)
  text = text.toString().replace(busca,reemplaza);return text;
}


function cleanCode(cod){
code = replaceAll(cod , "|", "{1}" ); // error | palos de explode en java
code = replaceAll(code, "+", "{0}" ); // error con los signos mas   
return code;
}

function to save:

function save(pid,code){
code = cleanCode(code); // fix sign + and |
code = escape(code); // fix accents
var url = 'editor.php';
var variables = 'op=save';
var myData = variables +'&code='+ code +'&pid='+ pid +'&newdate=' +(new Date()).getTime();    
var result = null;
$.ajax({
datatype : "html",
data: myData,  
url: url,
success : function(result) {
    alert(result); // result ok                     
},
}); 
} // end function

function in php:

<?php
function save($pid,$code){
    $code= preg_replace("[\{1\}]","|",$code);
    $code= preg_replace("[\{0\}]","+",$code);
    mysql_query("update table set code= '" . mysql_real_escape_string($code) . "' where pid='$pid'");
}
?>

Adding two Java 8 streams, or an extra element to a stream

At the end of the day I'm not interested in combining streams, but in obtaining the combined result of processing each element of all those streams.

While combining streams might prove to be cumbersome (thus this thread), combining their processing results is fairly easy.

The key to solve is to create your own collector and ensure that the supplier function for the new collector returns the same collection every time (not a new one), the code below illustrates this approach.

package scratchpad;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Stream;

public class CombineStreams {
    public CombineStreams() {
        super();
    }

    public static void main(String[] args) {
        List<String> resultList = new ArrayList<>();
        Collector<String, List<String>, List<String>> collector = Collector.of(
                () -> resultList,
                (list, item) -> {
                    list.add(item);
                },
                (llist, rlist) -> {
                    llist.addAll(rlist);
                    return llist;
                }
        );
        String searchString = "Wil";

        System.out.println("After processing first stream\n"
                + createFirstStream().filter(name -> name.contains(searchString)).collect(collector));
        System.out.println();

        System.out.println("After processing second stream\n"
                + createSecondStream().filter(name -> name.contains(searchString)).collect(collector));
        System.out.println();

        System.out.println("After processing third stream\n"
                + createThirdStream().filter(name -> name.contains(searchString)).collect(collector));
        System.out.println();

    }

    private static Stream<String> createFirstStream() {
        return Arrays.asList(
                "William Shakespeare",
                "Emily Dickinson",
                "H. P. Lovecraft",
                "Arthur Conan Doyle",
                "Leo Tolstoy",
                "Edgar Allan Poe",
                "Robert Ervin Howard",
                "Rabindranath Tagore",
                "Rudyard Kipling",
                "Seneca",
                "John Donne",
                "Sarah Williams",
                "Oscar Wilde",
                "Catullus",
                "Alfred Tennyson",
                "William Blake",
                "Charles Dickens",
                "John Keats",
                "Theodor Herzl"
        ).stream();
    }

    private static Stream<String> createSecondStream() {
        return Arrays.asList(
                "Percy Bysshe Shelley",
                "Ernest Hemingway",
                "Barack Obama",
                "Anton Chekhov",
                "Henry Wadsworth Longfellow",
                "Arthur Schopenhauer",
                "Jacob De Haas",
                "George Gordon Byron",
                "Jack London",
                "Robert Frost",
                "Abraham Lincoln",
                "O. Henry",
                "Ovid",
                "Robert Louis Stevenson",
                "John Masefield",
                "James Joyce",
                "Clark Ashton Smith",
                "Aristotle",
                "William Wordsworth",
                "Jane Austen"
        ).stream();
    }

    private static Stream<String> createThirdStream() {
        return Arrays.asList(
                "Niccolò Machiavelli",
                "Lewis Carroll",
                "Robert Burns",
                "Edgar Rice Burroughs",
                "Plato",
                "John Milton",
                "Ralph Waldo Emerson",
                "Margaret Thatcher",
                "Sylvie d'Avigdor",
                "Marcus Tullius Cicero",
                "Banjo Paterson",
                "Woodrow Wilson",
                "Walt Whitman",
                "Theodore Roosevelt",
                "Agatha Christie",
                "Ambrose Bierce",
                "Nikola Tesla",
                "Franz Kafka"
        ).stream();
    }
}

Check if a file exists locally using JavaScript only

No need for an external library if you use Nodejs all you need to do is import the file system module. feel free to edit the code below: const fs = require('fs')

const path = './file.txt'

fs.access(path, fs.F_OK, (err) => {
  if (err) {
    console.error(err)
    return
  }

  //file exists
})

Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null

I have the same error only on the production build. In development was all right, no warning.

The problem was a comment line

ERROR

return ( // comment
  <div>foo</div>
)

OK

// comment
return (
  <div>foo</div>
)

Pad a string with leading zeros so it's 3 characters long in SQL Server 2008

If the field is already a string, this will work

 SELECT RIGHT('000'+ISNULL(field,''),3)

If you want nulls to show as '000'

It might be an integer -- then you would want

 SELECT RIGHT('000'+CAST(field AS VARCHAR(3)),3)

As required by the question this answer only works if the length <= 3, if you want something larger you need to change the string constant and the two integer constants to the width needed. eg '0000' and VARCHAR(4)),4

jquery draggable: how to limit the draggable area?

See excerpt from official documentation for containment option:

containment

Default: false

Constrains dragging to within the bounds of the specified element or region.
Multiple types supported:

  • Selector: The draggable element will be contained to the bounding box of the first element found by the selector. If no element is found, no containment will be set.
  • Element: The draggable element will be contained to the bounding box of this element.
  • String: Possible values: "parent", "document", "window".
  • Array: An array defining a bounding box in the form [ x1, y1, x2, y2 ].

Code examples:
Initialize the draggable with the containment option specified:

$( ".selector" ).draggable({
    containment: "parent" 
}); 

Get or set the containment option, after initialization:

// Getter
var containment = $( ".selector" ).draggable( "option", "containment" );
// Setter
$( ".selector" ).draggable( "option", "containment", "parent" );

Filter element based on .data() key/value

your filter would work, but you need to return true on matching objects in the function passed to the filter for it to grab them.

var $previous = $('.navlink').filter(function() { 
  return $(this).data("selected") == true 
});

Parsing PDF files (especially with tables) with PDFBox

How about printing to image and doing OCR on that?

Sounds terribly ineffective, but it's practically the very purpose of PDF to make text inaccessible, you gotta do what you gotta do.

Postgres could not connect to server

Found a solution that worked for me here:

https://dba.stackexchange.com/questions/75214/psql-could-not-connect-to-server-no-such-file-or-directory

You basically run the following command to manually start the server:

pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start

Run cmd commands through Java

One way to run a process from a different directory to the working directory of your Java program is to change directory and then run the process in the same command line. You can do this by getting cmd.exe to run a command line such as cd some_directory && some_program.

The following example changes to a different directory and runs dir from there. Admittedly, I could just dir that directory without needing to cd to it, but this is only an example:

import java.io.*;

public class CmdTest {
    public static void main(String[] args) throws Exception {
        ProcessBuilder builder = new ProcessBuilder(
            "cmd.exe", "/c", "cd \"C:\\Program Files\\Microsoft SQL Server\" && dir");
        builder.redirectErrorStream(true);
        Process p = builder.start();
        BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while (true) {
            line = r.readLine();
            if (line == null) { break; }
            System.out.println(line);
        }
    }
}

Note also that I'm using a ProcessBuilder to run the command. Amongst other things, this allows me to redirect the process's standard error into its standard output, by calling redirectErrorStream(true). Doing so gives me only one stream to read from.

This gives me the following output on my machine:

C:\Users\Luke\StackOverflow>java CmdTest
 Volume in drive C is Windows7
 Volume Serial Number is D8F0-C934

 Directory of C:\Program Files\Microsoft SQL Server

29/07/2011  11:03    <DIR>          .
29/07/2011  11:03    <DIR>          ..
21/01/2011  20:37    <DIR>          100
21/01/2011  20:35    <DIR>          80
21/01/2011  20:35    <DIR>          90
21/01/2011  20:39    <DIR>          MSSQL10_50.SQLEXPRESS
               0 File(s)              0 bytes
               6 Dir(s)  209,496,424,448 bytes free

How to preserve request url with nginx proxy_pass

In my scenario i have make this via below code in nginx vhost configuration

server {
server_name dashboards.etilize.com;

location / {
    proxy_pass http://demo.etilize.com/dashboards/;
    proxy_set_header Host $http_host;
}}

$http_host will set URL in Header same as requested

Android: Share plain text using intent (to all messaging apps)

This code is for sharing through sms

     String smsBody="Sms Body";
     Intent sendIntent = new Intent(Intent.ACTION_VIEW);
     sendIntent.putExtra("sms_body", smsBody);
     sendIntent.setType("vnd.android-dir/mms-sms");
     startActivity(sendIntent);

jQuery datepicker to prevent past date

Make sure you put multiple properties in the same line (since you only showed 1 line of code, you may have had the same problem I did).

Mine would set the default date, but didn't gray out old dates. This doesn't work:

$('#date_end').datepicker({ defaultDate: +31 })
$('#date_end').datepicker({ minDate: 1 })

This does both:

$('#date_end').datepicker({ defaultDate: +31, minDate: 1 })

1 and +1 work the same (or 0 and +0 in your case).

Me: Windows 7 x64, Rails 3.2.3, Ruby 1.9.3

Optimal number of threads per core

The actual performance will depend on how much voluntary yielding each thread will do. For example, if the threads do NO I/O at all and use no system services (i.e. they're 100% cpu-bound) then 1 thread per core is the optimal. If the threads do anything that requires waiting, then you'll have to experiment to determine the optimal number of threads. 4000 threads would incur significant scheduling overhead, so that's probably not optimal either.

Combining "LIKE" and "IN" for SQL Server

You need multiple LIKE clauses connected by OR.

SELECT * FROM table WHERE 
column LIKE 'Text%' OR 
column LIKE 'Link%' OR 
column LIKE 'Hello%' OR 
column LIKE '%World%' OR 

How to get data out of a Node.js http get request

Shorter example using http.get:

require('http').get('http://httpbin.org/ip', (res) => {
    res.setEncoding('utf8');
    res.on('data', function (body) {
        console.log(body);
    });
});

Execute write on doc: It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

In case this is useful to anyone I had this same issue. I was bringing in a footer into a web page via jQuery. Inside that footer were some Google scripts for ads and retargeting. I had to move those scripts from the footer and place them directly in the page and that eliminated the notice.

Facebook Callback appends '#_=_' to Return URL

I do not see how this problem is related to facebook AJAX. In fact the issue also occurs with JavaScript disabled and purely redirect based logins.

An example exchange with facebook:

1. GET <https://www.facebook.com/dialog/oauth?client_id=MY_APP_ID&scope=email&redirect_uri=MY_REDIRECT_URL> RESPONSE 302 Found Location: <https://www.facebook.com/connect/uiserver.php?[...]>  
2. GET <https://www.facebook.com/connect/uiserver.php?[...]> RESPONSE 302 Found MY_REDIRECT_URL?code=FB_CODE#_  
3. GET MY_REDIRECT_URL?code=FB_CODE#_  

Happens only with Firefox for me too.

FileNotFoundException while getting the InputStream object from HttpURLConnection

FileNotFound in this case means you got a 404 from your server - could it be that the server does not like "POST" requests?

Benefits of inline functions in C++?

Conclusion from another discussion here:

Are there any drawbacks with inline functions?

Apparently, There is nothing wrong with using inline functions.

But it is worth noting the following points!

  • Overuse of inlining can actually make programs slower. Depending on a function's size, inlining it can cause the code size to increase or decrease. Inlining a very small accessor function will usually decrease code size while inlining a very large function can dramatically increase code size. On modern processors smaller code usually runs faster due to better use of the instruction cache. - Google Guidelines

  • The speed benefits of inline functions tend to diminish as the function grows in size. At some point the overhead of the function call becomes small compared to the execution of the function body, and the benefit is lost - Source

  • There are few situations where an inline function may not work:

    • For a function returning values; if a return statement exists.
    • For a function not returning any values; if a loop, switch or goto statement exists.
    • If a function is recursive. -Source
  • The __inline keyword causes a function to be inlined only if you specify the optimize option. If optimize is specified, whether or not __inline is honored depends on the setting of the inline optimizer option. By default, the inline option is in effect whenever the optimizer is run. If you specify optimize , you must also specify the noinline option if you want the __inline keyword to be ignored. -Source

How to do a for loop in windows command line?

This may help you find what you're looking for... Batch script loop

My answer is as follows:

@echo off
:start
set /a var+=1
if %var% EQU 100 goto end
:: Code you want to run goes here
goto start

:end
echo var has reached %var%.
pause
exit

The first set of commands under the start label loops until a variable, %var% reaches 100. Once this happens it will notify you and allow you to exit. This code can be adapted to your needs by changing the 100 to 17 and putting your code or using a call command followed by the batch file's path (Shift+Right Click on file and select "Copy as Path") where the comment is placed.

In laymans terms, what does 'static' mean in Java?

In very laymen terms the class is a mold and the object is the copy made with that mold. Static belong to the mold and can be accessed directly without making any copies, hence the example above

How to upgrade rubygems

I found other answers to be inaccurate/outdated. Best is to refer to the actual documentation.

Short version: in most cases gem update --system will suffice.

You should not blindly use sudo. In fact if you're not required to do so you most likely should not use it.

How do I add a .click() event to an image?

First of all, this line

<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />.click()

You're mixing HTML and JavaScript. It doesn't work like that. Get rid of the .click() there.

If you read the JavaScript you've got there, document.getElementById('foo') it's looking for an HTML element with an ID of foo. You don't have one. Give your image that ID:

<img id="foo" src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />

Alternatively, you could throw the JS in a function and put an onclick in your HTML:

<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" onclick="myfunction()" />

I suggest you do some reading up on JavaScript and HTML though.


The others are right about needing to move the <img> above the JS click binding too.

How to install requests module in Python 3.4, instead of 2.7

You can specify a Python version for pip to use:

pip3.4 install requests

Python 3.4 has pip support built-in, so you can also use:

python3.4 -m pip install

If you're running Ubuntu (or probably Debian as well), you'll need to install the system pip3 separately:

sudo apt-get install python3-pip

This will install the pip3 executable, so you can use it, as well as the earlier mentioned python3.4 -m pip:

pip3 install requests

Composer could not find a composer.json

Simple solution is install via this command :

curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer

To install package it's very simple :

 composer global require "phpunit/php-invoker=1.1.*"

Ref : composer web site.

how to display a javascript var in html body

Try This...

_x000D_
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script>_x000D_
    function myFunction() {_x000D_
      var number = "123";_x000D_
      document.getElementById("myText").innerHTML = number;_x000D_
    }_x000D_
  </script>_x000D_
</head>_x000D_
_x000D_
<body onload="myFunction()">_x000D_
_x000D_
  <h1>"The value for number is: " <span id="myText"></span></h1>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do I split a string so I can access item x?

First, create a function (using CTE, common table expression does away with the need for a temp table)

 create function dbo.SplitString 
    (
        @str nvarchar(4000), 
        @separator char(1)
    )
    returns table
    AS
    return (
        with tokens(p, a, b) AS (
            select 
                1, 
                1, 
                charindex(@separator, @str)
            union all
            select
                p + 1, 
                b + 1, 
                charindex(@separator, @str, b + 1)
            from tokens
            where b > 0
        )
        select
            p-1 zeroBasedOccurance,
            substring(
                @str, 
                a, 
                case when b > 0 then b-a ELSE 4000 end) 
            AS s
        from tokens
      )
    GO

Then, use it as any table (or modify it to fit within your existing stored proc) like this.

select s 
from dbo.SplitString('Hello John Smith', ' ')
where zeroBasedOccurance=1

Update

Previous version would fail for input string longer than 4000 chars. This version takes care of the limitation:

create function dbo.SplitString 
(
    @str nvarchar(max), 
    @separator char(1)
)
returns table
AS
return (
with tokens(p, a, b) AS (
    select 
        cast(1 as bigint), 
        cast(1 as bigint), 
        charindex(@separator, @str)
    union all
    select
        p + 1, 
        b + 1, 
        charindex(@separator, @str, b + 1)
    from tokens
    where b > 0
)
select
    p-1 ItemIndex,
    substring(
        @str, 
        a, 
        case when b > 0 then b-a ELSE LEN(@str) end) 
    AS s
from tokens
);

GO

Usage remains the same.

Calling a function of a module by using its name (a string)

locals()["myfunction"]()

or

globals()["myfunction"]()

locals returns a dictionary with a current local symbol table. globals returns a dictionary with global symbol table.

Why specify @charset "UTF-8"; in your CSS file?

One reason to always include a character set specification on every page containing text is to avoid cross site scripting vulnerabilities. In most cases the UTF-8 character set is the best choice for text, including HTML pages.

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>

Update multiple values in a single statement

Have you tried with a sub-query for every field:

UPDATE
    MasterTbl
SET
    TotalX = (SELECT SUM(X) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID),
    TotalY = (SELECT SUM(Y) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID),
    TotalZ = (SELECT SUM(Z) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID)
WHERE
    ....

Why does the preflight OPTIONS request of an authenticated CORS request work in Chrome but not Firefox?

It was particular for me. I am sending a header named 'SESSIONHASH'. No problem for Chrome and Opera, but Firefox also wants this header in the list "Access-Control-Allow-Headers". Otherwise, Firefox will throw the CORS error.

SQL Server Insert if not exists

You could use the GO command. That will restart the execution of SQL statements after an error. In my case I have a few 1000 INSERT statements, where a handful of those records already exist in the database, I just don't know which ones. I found that after processing a few 100, execution just stops with an error message that it can't INSERT as the record already exists. Quite annoying, but putting a GO solved this. It may not be the fastest solution, but speed was not my problem.

GO
INSERT INTO mytable (C1,C2,C3) VALUES(1,2,3)
GO
INSERT INTO mytable (C1,C2,C3) VALUES(4,5,6)
 etc ...

Open a new tab on button click in AngularJS

You should use the $location service

Angular docs:

Is there any way to configure multiple registries in a single npmrc file

You can have multiple registries for scoped packages in your .npmrc file. For example:

@polymer:registry=<url register A>
registry=http://localhost:4873/

Packages under @polymer scope will be received from https://registry.npmjs.org, but the rest will be received from your local NPM.

Is there a "between" function in C#?

Except for the answer by @Ed G, all of the answers require knowing which bound is the lower and which is the upper one.

Here's a (rather non-obvious) way of doing it when you don't know which bound is which.

  /// <summary>
  /// Method to test if a value is "between" two other values, when the relative magnitude of 
  /// the two other values is not known, i.e., number1 may be larger or smaller than number2. 
  /// The range is considered to be inclusive of the lower value and exclusive of the upper 
  /// value, irrespective of which parameter (number1 or number2) is the lower or upper value. 
  /// This implies that if number1 equals number2 then the result is always false.
  /// 
  /// This was extracted from a larger function that tests if a point is in a polygon:
  /// http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
  /// </summary>
  /// <param name="testValue">value to be tested for being "between" the other two numbers</param>
  /// <param name="number1">one end of the range</param>
  /// <param name="number2">the other end of the range</param>
  /// <returns>true if testValue >= lower of the two numbers and less than upper of the two numbers,
  ///          false otherwise, incl. if number1 == number2</returns>
  private static bool IsInRange(T testValue, T number1, T number2)
  {
     return (testValue <= number1) != (testValue <= number2);
  }

Note: This is NOT a generic method; it is pseudo code. The T in the above method should be replaced by a proper type, "int" or "float" or whatever. (There are ways of making this generic, but they're sufficiently messy that it's not worth while for a one-line method, at least not in most situations.)

Set environment variables on Mac OS X Lion

More detail, which may perhaps be helpful to someone:

Due to my own explorations, I now know how to set environment variables in 7 of 8 different ways. I was trying to get an envar through to an application I'm developing under Xcode. I set "tracer" envars using these different methods to tell me which ones get it into the scope of my application. From the below, you can see that editing the "scheme" in Xcode to add arguments works, as does "putenv". What didn't set it in that scope: ~/.MACOS/environment.plist, app-specific plist, .profile, and adding a build phase to run a custom script (I found another way in Xcode [at least] to set one but forgot what I called the tracer and can't find it now; maybe it's on another machine....)

GPU_DUMP_DEVICE_KERNEL is 3

GPU_DUMP_TRK_ENVPLIST is (null)

GPU_DUMP_TRK_APPPLIST is (null)

GPU_DUMP_TRK_DOTPROFILE is (null)

GPU_DUMP_TRK_RUNSCRIPT is (null)

GPU_DUMP_TRK_SCHARGS is 1

GPU_DUMP_TRK_PUTENV is 1

... on the other hand, if I go into Terminal and say "set", it seems the only one it gets is the one from .profile (I would have thought it would pick up environment.plist also, and I'm sure once I did see a second tracer envar in Terminal, so something's probably gone wonky since then. Long day....)

Python/Json:Expecting property name enclosed in double quotes

As the other answers explain well the error occurs because of invalid quote characters passed to the json module.

In my case I continued to get the ValueError even after replacing ' with " in my string. What I finally realized was that some quote-like unicode symbols had found their way into my string:

 “  ”  '  ’  ‘  `  ´  "  ' 

To clean all of these you can just pass your string through a regular expression:

import re

raw_string = '{“key”:“value”}'

parsed_string = re.sub(r"[“|”|'|’|‘|`|´|"|'|']", '"', my_string)

json_object = json.loads(parsed_string)

Fixing Xcode 9 issue: "iPhone is busy: Preparing debugger support for iPhone"

I've faced the same problem because of a cable. I changed my third party USB/lighting cable into original Apple cable, and it worked.

Extract XML Value in bash script

I agree with Charles Duffy that a proper XML parser is the right way to go.

But as to what's wrong with your sed command (or did you do it on purpose?).

  • $data was not quoted, so $data is subject to shell's word splitting, filename expansion among other things. One of the consequences being that the spacing in the XML snippet is not preserved.

So given your specific XML structure, this modified sed command should work

title=$(sed -ne '/title/{s/.*<title>\(.*\)<\/title>.*/\1/p;q;}' <<< "$data")

Basically for the line that contains title, extract the text between the tags, then quit (so you don't extract the 2nd <title>)

How to set cornerRadius for only top-left and top-right corner of a UIView?

This is how you can set a corner radius for each corner of a button with Xamarin in C#:

var maskPath = UIBezierPath.FromRoundedRect(MyButton.Bounds, UIRectCorner.BottomLeft | UIRectCorner.BottomRight,
    new CGSize(10.0, 10.0));
var maskLayer = new CAShapeLayer
{
    Frame = MyButton.Bounds,
    Path = maskPath.CGPath
};
MyButton.Layer.Mask = maskLayer;

Checking host availability by using ping in bash scripts

This seems to work moderately well in a terminal emulator window. It loops until there's a connection then stops.

#!/bin/bash

# ping in a loop until the net is up

declare -i s=0
declare -i m=0
while ! ping -c1 -w2 8.8.8.8 &> /dev/null ;
do
  echo "down" $m:$s
  sleep 10
  s=s+10
  if test $s -ge 60; then
    s=0
    m=m+1;
  fi
done
echo -e "--------->>  UP! (connect a speaker) <<--------" \\a

The \a at the end is trying to get a bel char on connect. I've been trying to do this in LXDE/lxpanel but everything halts until I have a network connection again. Having a time started out as a progress indicator because if you look at a window with just "down" on every line you can't even tell it's moving.

Android: how to create Switch case from this?

@Override
public void onClick(View v)
{
    switch (v.getId())
    {
        case R.id.:

            break;
        case R.id.:

            break;
        default:
            break;
    }
}

Custom style to jquery ui dialogs

You can specify a custom class to the top element of the dialog via the option dialogClass

$("#success").dialog({
    ...
    dialogClass:"myClass",
    ...
});

Then you can target this class in CSS via .myClass.ui-dialog.

Best Regular Expression for Email Validation in C#

I would like to suggest new EmailAddressAttribute().IsValid(emailTxt) for additional validation before/after validating using RegEx

Remember EmailAddressAttribute is part of System.ComponentModel.DataAnnotations namespace.

Create list of object from another using Java 8 Streams

If you want to iterate over a list and create a new list with "transformed" objects, you should use the map() function of stream + collect(). In the following example I find all people with the last name "l1" and each person I'm "mapping" to a new Employee instance.

public class Test {

    public static void main(String[] args) {
        List<Person> persons = Arrays.asList(
                new Person("e1", "l1"),
                new Person("e2", "l1"),
                new Person("e3", "l2"),
                new Person("e4", "l2")
        );

        List<Employee> employees = persons.stream()
                .filter(p -> p.getLastName().equals("l1"))
                .map(p -> new Employee(p.getName(), p.getLastName(), 1000))
                .collect(Collectors.toList());

        System.out.println(employees);
    }

}

class Person {

    private String name;
    private String lastName;

    public Person(String name, String lastName) {
        this.name = name;
        this.lastName = lastName;
    }

    // Getter & Setter
}

class Employee extends Person {

    private double salary;

    public Employee(String name, String lastName, double salary) {
        super(name, lastName);
        this.salary = salary;
    }

    // Getter & Setter
}

Handling click events on a drawable within an EditText

That last contribution's use of contains(x,y) won't work directly on the result of getBounds() (except, by coincidence, when using "left" drawables). The getBounds method only provides the Rect defining points of the drawable item normalized with origin at 0,0 - so, you actually need to do the math of the original post to find out if the click is in the area of the drawable in the context of the containing EditText's dimensions, but change it for top, right, left etc. Alternatively you could describe a Rect that has coordinates actually relative to its position in the EditText container and use contains(), although in the end you're doing the same math.

Combining them both gives you a pretty complete solution, I only added an instance attribute consumesEvent that lets the API user decide if the click event should be passed on or not by using its result to set ACTION_CANCEL or not.

Also, I can't see why the bounds and actionX, actionY values are instance attributes rather than just local on the stack.

Here's a cutout from an implementation based on the above that I put together. It fixes an issue that to properly consume the event you need to return false. It adds a "fuzz" factor to. In my use case of a Voice control icon in an EditText field, I found it hard to click, so the fuzz increases the effective bounds that are considered clicking the drawable. For me 15 worked well. I only needed drawableRight so I didn't plug the math in the others, to save some space, but you see the idea.

package com.example.android;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.EditText;
import android.graphics.Rect;

import com.example.android.DrawableClickListener;

public class ClickableButtonEditText extends EditText {
  public static final String LOG_TAG = "ClickableButtonEditText";

  private Drawable drawableRight;
  private Drawable drawableLeft;
  private Drawable drawableTop;
  private Drawable drawableBottom;
  private boolean consumeEvent = false;
  private int fuzz = 0;

  private DrawableClickListener clickListener;

  public ClickableButtonEditText(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

  public ClickableButtonEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public ClickableButtonEditText(Context context) {
    super(context);
  }

  public void consumeEvent() {
    this.setConsumeEvent(true);
  }

  public void setConsumeEvent(boolean b) {
    this.consumeEvent = b;
  }

  public void setFuzz(int z) {
    this.fuzz = z;
  }

  public int getFuzz() {
    return fuzz;
  }

  @Override
  public void setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom) {
    if (right != null) {
      drawableRight = right;
    }

    if (left != null) {
      drawableLeft = left;
    }
    super.setCompoundDrawables(left, top, right, bottom);
  }

  @Override
  public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
      int x, y;
      Rect bounds;
      x = (int) event.getX();
      y = (int) event.getY();
      // this works for left since container shares 0,0 origin with bounds
      if (drawableLeft != null) {
        bounds = drawableLeft.getBounds();
        if (bounds.contains(x - fuzz, y - fuzz)) {
          clickListener.onClick(DrawableClickListener.DrawablePosition.LEFT);
          if (consumeEvent) {
            event.setAction(MotionEvent.ACTION_CANCEL);
            return false;
          }
        }
      } else if (drawableRight != null) {
        bounds = drawableRight.getBounds();
        if (x >= (this.getRight() - bounds.width() - fuzz) && x <= (this.getRight() - this.getPaddingRight() + fuzz) 
              && y >= (this.getPaddingTop() - fuzz) && y <= (this.getHeight() - this.getPaddingBottom()) + fuzz) {

          clickListener.onClick(DrawableClickListener.DrawablePosition.RIGHT);
          if (consumeEvent) {
            event.setAction(MotionEvent.ACTION_CANCEL);
            return false;
          }
        }
      } else if (drawableTop != null) {
        // not impl reader exercise :)
      } else if (drawableBottom != null) {
        // not impl reader exercise :)
      }
    }

    return super.onTouchEvent(event);
  }

  @Override
  protected void finalize() throws Throwable {
    drawableRight = null;
    drawableBottom = null;
    drawableLeft = null;
    drawableTop = null;
    super.finalize();
  }

  public void setDrawableClickListener(DrawableClickListener listener) {
    this.clickListener = listener;
  }
}

How to save a base64 image to user's disk using JavaScript?

In JavaScript you cannot have the direct access to the filesystem. However, you can make browser to pop up a dialog window allowing the user to pick the save location. In order to do this, use the replace method with your Base64String and replace "image/png" with "image/octet-stream":

"data:image/png;base64,iVBORw0KG...".replace("image/png", "image/octet-stream");

Also, W3C-compliant browsers provide 2 methods to work with base64-encoded and binary data:

Probably, you will find them useful in a way...


Here is a refactored version of what I understand you need:

_x000D_
_x000D_
window.addEventListener('DOMContentLoaded', () => {_x000D_
  const img = document.getElementById('embedImage');_x000D_
  img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' +_x000D_
    'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO' +_x000D_
    '9TXL0Y4OHwAAAABJRU5ErkJggg==';_x000D_
_x000D_
  img.addEventListener('load', () => button.removeAttribute('disabled'));_x000D_
  _x000D_
  const button = document.getElementById('saveImage');_x000D_
  button.addEventListener('click', () => {_x000D_
    window.location.href = img.src.replace('image/png', 'image/octet-stream');_x000D_
  });_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
  <img id="embedImage" alt="Red dot" />_x000D_
  <button id="saveImage" disabled="disabled">save image</button>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Find out who is locking a file on a network share

On Windows 2008 R2 servers you have two means of viewing what files are open and closing those connections.

Via Share and Storage Management

Server Manager > Roles > File Services > Share and Storage Management > right-click on SaSM > Manage Open File

Via OpenFiles

CMD > Openfiles.exe /query /s SERVERNAME

See http://technet.microsoft.com/en-us/library/bb490961.aspx.

How to join two sets in one line without using "|"

If you are fine with modifying the original set (which you may want to do in some cases), you can use set.update():

S.update(T)

The return value is None, but S will be updated to be the union of the original S and T.

PHP file_get_contents() and setting request headers

You can use this variable to retrieve response headers after file_get_contents() function.

Code:

  file_get_contents("http://example.com");
  var_dump($http_response_header);

Output:

array(9) {
  [0]=>
  string(15) "HTTP/1.1 200 OK"
  [1]=>
  string(35) "Date: Sat, 12 Apr 2008 17:30:38 GMT"
  [2]=>
  string(29) "Server: Apache/2.2.3 (CentOS)"
  [3]=>
  string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT"
  [4]=>
  string(27) "ETag: "280100-1b6-80bfd280""
  [5]=>
  string(20) "Accept-Ranges: bytes"
  [6]=>
  string(19) "Content-Length: 438"
  [7]=>
  string(17) "Connection: close"
  [8]=>
  string(38) "Content-Type: text/html; charset=UTF-8"
}

What are all the user accounts for IIS/ASP.NET and how do they differ?

This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....

To cover the identities listed:

IIS_IUSRS:

This is analogous to the old IIS6 IIS_WPG group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.

IUSR:

This account is analogous to the old IUSR_<MACHINE_NAME> local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).

For more information about IIS_IUSRS and IUSR see:

Understanding Built-In User and Group Accounts in IIS 7

DefaultAppPool:

If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name> will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>. You also won't see these pool accounts in your computers User Manager. See the following for more information:

Application Pool Identities

ASP.NET v4.0: -

This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool above.

NETWORK SERVICE: -

The NETWORK SERVICE account is a built-in identity introduced on Windows 2003. NETWORK SERVICE is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).

In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" /> setting in web.config file locally (if that setting is locked then it would need to be done by an admin in the machine.config file).

Setting <identity impersonate="true"> is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).

In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR or a specific custom anonymous account.

LOCAL SERVICE:

The LOCAL SERVICE account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:

LocalService Account

LOCAL SYSTEM:

You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.

LocalSystem Account

In Practice:

In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity:

enter image description here

In the website you should then configure the Authentication feature:

enter image description here

Right click and edit the Anonymous Authentication entry:

enter image description here

Ensure that "Application pool identity" is selected:

enter image description here

When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0 pool permissions then you can either do this via Explorer:

enter image description here

Click the "Check Names" button:

enter image description here

Or you can do this using the ICACLS.EXE utility:

icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)

...or...if you site's application pool is called BobsCatPicBlogthen:

icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)

I hope this helps clear things up.

Update:

I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:

The difference between the 'Local System' account and the 'Network Service' account?

How to enter in a Docker container already running with a new TTY

Update

As of docker 0.9, for the steps below to now work, one now has to update the /etc/default/docker file with the '-e lxc' to the docker daemon startup option before restarting the daemon (I did this by rebooting the host).

update to the /etc/default/docker file

This is all because...

...it [docker 0.9] contains a new "engine driver" abstraction to make possible the use of other API than LXC to start containers. It also provide a new engine driver based on a new API library (libcontainer) which is able to handle Control Groups without using LXC tools. The main issue is that if you are relying on lxc-attach to perform actions on your container, like starting a shell inside the container, which is insanely useful for developpment environment...

source

Please note that this will prevent the new host only networking optional feature of docker 0.11 from "working" and you will only see the loopback interface. bug report


It turns out that the solution to a different question was also the solution to this one:

...you can use docker ps -notrunc to get the full lxc container ID and then use lxc-attach -n <container_id> run bash in that container as root.

Update: You will soon need to use ps --no-trunc instead of ps -notrunc which is being deprecated.

enter image description here Find the full container ID

enter image description here Enter the lxc attach command.

enter image description here Top shows my apache process running that docker started.

Eclipse fonts and background color

Under Windows ? Preferences ? General ? Apperance you can find a dark theme.

Submit button doesn't work

I faced this problem today, and the issue was I was preventing event default action in document onclick:

document.onclick = function(e) {
    e.preventDefault();
}

Document onclick usually is used for event delegation but it's wrong to prevent default for every event, you must do it only for required elements:

document.onclick = function(e) {
    if (e.target instanceof HTMLAnchorElement) e.preventDefault();
}

Prevent form submission on Enter key press

Below code will add listener for ENTER key on entire page.

This can be very useful in screens with single Action button eg Login, Register, Submit etc.

<head>
        <!--Import jQuery IMPORTANT -->
        <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>

         <!--Listen to Enter key event-->
        <script type="text/javascript">

            $(document).keypress(function (e) {
                if (e.which == 13 || event.keyCode == 13) {
                    alert('enter key is pressed');
                }
            });
        </script>
    </head>

Tested on all browsers.

Why does configure say no C compiler found when GCC is installed?

Sometime gcc had created as /usr/bin/gcc32. so please create a ln -s /usr/bin/gcc32 /usr/bin/gcc and then compile that ./configure.

Install Chrome extension form outside the Chrome Web Store

For regular Windows users who are not skilled with computers, it is practically not possible to install and use extensions from outside the Chrome Web Store.

Users of other operating systems (Linux, Mac, Chrome OS) can easily install unpacked extensions (in developer mode).
Windows users can also load an unpacked extension, but they will always see an information bubble with "Disable developer mode extensions" when they start Chrome or open a new incognito window, which is really annoying. The only way for Windows users to use unpacked extensions without such dialogs is to switch to Chrome on the developer channel, by installing https://www.google.com/chrome/browser/index.html?extra=devchannel#eula.

Extensions can be loaded in unpacked mode by following the following steps:

  1. Visit chrome://extensions (via omnibox or menu -> Tools -> Extensions).
  2. Enable Developer mode by ticking the checkbox in the upper-right corner.
  3. Click on the "Load unpacked extension..." button.
  4. Select the directory containing your unpacked extension.

If you have a crx file, then it needs to be extracted first. CRX files are zip files with a different header. Any capable zip program should be able to open it. If you don't have such a program, I recommend 7-zip.

These steps will work for almost every extension, except extensions that rely on their extension ID. If you use the previous method, you will get an extension with a random extension ID. If it is important to preserve the extension ID, then you need to know the public key of your CRX file and insert this in your manifest.json. I have previously given a detailed explanation on how to get and use this key at https://stackoverflow.com/a/21500707.

accessing a file using [NSBundle mainBundle] pathForResource: ofType:inDirectory:

well i found out the mistake i was committing i was adding a group to the project instead of adding real directory for more instructions

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.testing.models.Account

I had a similar exception (but different problem) - java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to org.bson.Document , and fortunately it's solved easier:

Instead of

List<Document> docs = obj.get("documents");
Document doc = docs.get(0)

which gives error on second line, One can use

List<Document> docs = obj.get("documents");
Document doc = new Document(docs.get(0));

Opening Chrome From Command Line

you can create batch file and insert into it the bellow line:

cmd /k start chrome "http://yourWebSite.com

after that you do just double click on this batch file.

Java: Replace all ' in a string with \'

You have to first escape the backslash because it's a literal (yielding \\), and then escape it again because of the regular expression (yielding \\\\). So, Try:

 s.replaceAll("'", "\\\\'");

output:

You\'ll be totally awesome, I\'m really terrible

center MessageBox in parent form

From a comment on Joel Spolsky's blog:

A Messagebox is always centered on the screen. You can provide an owner, but that is just for Z-order, not centering. The only way is to use Win32 hooks and center it yourself. You can find code doing that online if you search for it.

Much easier is to just write your own message box class and add centering functionality. Then you can also add default captioning, Do not show again-checkbox and making them modeless.

"Win32 hooks" probably refers to using SetWindowsHookEx as shown in this example.

How to convert a time string to seconds?

For Python 2.7:

>>> import datetime
>>> import time
>>> x = time.strptime('00:01:00,000'.split(',')[0],'%H:%M:%S')
>>> datetime.timedelta(hours=x.tm_hour,minutes=x.tm_min,seconds=x.tm_sec).total_seconds()
60.0

Regexp Java for password validation

Java Method ready for you, with parameters

Just copy and paste and set your desired parameters.

If you don't want a module, just comment it or add an "if" as done by me for special char

//______________________________________________________________________________
/**
 * Validation Password     */
//______________________________________________________________________________
private static boolean validation_Password(final String PASSWORD_Arg)    {
    boolean result = false;
    try {
        if (PASSWORD_Arg!=null) {
            //_________________________
            //Parameteres
            final String MIN_LENGHT="8";
            final String MAX_LENGHT="20";
            final boolean SPECIAL_CHAR_NEEDED=true;

            //_________________________
            //Modules
            final String ONE_DIGIT = "(?=.*[0-9])";  //(?=.*[0-9]) a digit must occur at least once
            final String LOWER_CASE = "(?=.*[a-z])";  //(?=.*[a-z]) a lower case letter must occur at least once
            final String UPPER_CASE = "(?=.*[A-Z])";  //(?=.*[A-Z]) an upper case letter must occur at least once
            final String NO_SPACE = "(?=\\S+$)";  //(?=\\S+$) no whitespace allowed in the entire string
            //final String MIN_CHAR = ".{" + MIN_LENGHT + ",}";  //.{8,} at least 8 characters
            final String MIN_MAX_CHAR = ".{" + MIN_LENGHT + "," + MAX_LENGHT + "}";  //.{5,10} represents minimum of 5 characters and maximum of 10 characters

            final String SPECIAL_CHAR;
            if (SPECIAL_CHAR_NEEDED==true) SPECIAL_CHAR= "(?=.*[@#$%^&+=])"; //(?=.*[@#$%^&+=]) a special character must occur at least once
            else SPECIAL_CHAR="";
            //_________________________
            //Pattern
            //String pattern = "(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{8,}";
            final String PATTERN = ONE_DIGIT + LOWER_CASE + UPPER_CASE + SPECIAL_CHAR + NO_SPACE + MIN_MAX_CHAR;
            //_________________________
            result = PASSWORD_Arg.matches(PATTERN);
            //_________________________
        }    

    } catch (Exception ex) {
        result=false;
    }

    return result;
}        

How can I determine the direction of a jQuery scroll event?

In case you just want to know if you scroll up or down using a pointer device (mouse or track pad) you can use the deltaY property of the wheel event.

_x000D_
_x000D_
$('.container').on('wheel', function(event) {_x000D_
  if (event.originalEvent.deltaY > 0) {_x000D_
    $('.result').append('Scrolled down!<br>');_x000D_
  } else {_x000D_
    $('.result').append('Scrolled up!<br>');_x000D_
  }_x000D_
});
_x000D_
.container {_x000D_
  height: 200px;_x000D_
  width: 400px;_x000D_
  margin: 20px;_x000D_
  border: 1px solid black;_x000D_
  overflow-y: auto;_x000D_
}_x000D_
.content {_x000D_
  height: 300px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
  <div class="content">_x000D_
    Scroll me!_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<div class="result">_x000D_
  <p>Action:</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Excel SUMIF between dates

One more solution when you want to use data from any sell ( in the key C3)

=SUMIF(Sheet6!M:M;CONCATENATE("<";TEXT(C3;"dd.mm.yyyy"));Sheet6!L:L)

Making href (anchor tag) request POST instead of GET?

Using jQuery it is very simple assuming the URL you wish to post to is on the same server or has implemented CORS

$(function() {
  $("#employeeLink").on("click",function(e) {
    e.preventDefault(); // cancel the link itself
    $.post(this.href,function(data) {
      $("#someContainer").html(data);
    });
  });
});

If you insist on using frames which I strongly discourage, have a form and submit it with the link

<form action="employee.action" method="post" target="myFrame" id="myForm"></form>

and use (in plain JS)

 window.addEventListener("load",function() {
   document.getElementById("employeeLink").addEventListener("click",function(e) {
     e.preventDefault(); // cancel the link
     document.getElementById("myForm").submit(); // but make sure nothing has name or ID="submit"
   });
 });

Without a form we need to make one

 window.addEventListener("load",function() {
   document.getElementById("employeeLink").addEventListener("click",function(e) {
     e.preventDefault(); // cancel the actual link
     var myForm = document.createElement("form");
     myForm.action=this.href;// the href of the link
     myForm.target="myFrame";
     myForm.method="POST";
     myForm.submit();
   });
 });

AWK: Access captured group from line pattern

That was a stroll down memory lane...

I replaced awk by perl a long time ago.

Apparently the AWK regular expression engine does not capture its groups.

you might consider using something like :

perl -n -e'/test(\d+)/ && print $1'

the -n flag causes perl to loop over every line like awk does.

How can I lock a file using java (if possible)

FileChannel.lock is probably what you want.

try (
    FileInputStream in = new FileInputStream(file);
    java.nio.channels.FileLock lock = in.getChannel().lock();
    Reader reader = new InputStreamReader(in, charset)
) {
    ...
}

(Disclaimer: Code not compiled and certainly not tested.)

Note the section entitled "platform dependencies" in the API doc for FileLock.

How to download and save a file from Internet using Java?

Give Java NIO a try:

URL website = new URL("http://www.website.com/information.asp");
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream("information.html");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);

Using transferFrom() is potentially much more efficient than a simple loop that reads from the source channel and writes to this channel. Many operating systems can transfer bytes directly from the source channel into the filesystem cache without actually copying them.

Check more about it here.

Note: The third parameter in transferFrom is the maximum number of bytes to transfer. Integer.MAX_VALUE will transfer at most 2^31 bytes, Long.MAX_VALUE will allow at most 2^63 bytes (larger than any file in existence).

C# How do I click a button by hitting Enter whilst textbox has focus?

Add this to the Form's constructor:

this.textboxName.KeyDown += (sender, args) => {
    if (args.KeyCode == Keys.Return)
    {
        buttonName.PerformClick();
    }
};

Adding an arbitrary line to a matplotlib plot in ipython notebook

You can directly plot the lines you want by feeding the plot command with the corresponding data (boundaries of the segments):

plot([x1, x2], [y1, y2], color='k', linestyle='-', linewidth=2)

(of course you can choose the color, line width, line style, etc.)

From your example:

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")


# draw vertical line from (70,100) to (70, 250)
plt.plot([70, 70], [100, 250], 'k-', lw=2)

# draw diagonal line from (70, 90) to (90, 200)
plt.plot([70, 90], [90, 200], 'k-')

plt.show()

new chart

How to use a switch case 'or' in PHP

I won't repost the other answers because they're all correct, but I'll just add that you can't use switch for more "complicated" statements, eg: to test if a value is "greater than 3", "between 4 and 6", etc. If you need to do something like that, stick to using if statements, or if there's a particularly strong need for switch then it's possible to use it back to front:

switch (true) {
    case ($value > 3) :
        // value is greater than 3
    break;
    case ($value >= 4 && $value <= 6) :
        // value is between 4 and 6
    break;
}

but as I said, I'd personally use an if statement there.

Uncaught TypeError: undefined is not a function while using jQuery UI

I don't think jQuery itself includes datetimepicker. You must use jQuery UI instead (src="jquery.ui").

Convert string to Time

"16:23:01" doesn't match the pattern of "hh:mm:ss tt" - it doesn't have an am/pm designator, and 16 clearly isn't in a 12-hour clock. You're specifying that format in the parsing part, so you need to match the format of the existing data. You want:

DateTime dateTime = DateTime.ParseExact(time, "HH:mm:ss",
                                        CultureInfo.InvariantCulture);

(Note the invariant culture, not the current culture - assuming your input genuinely always uses colons.)

If you want to format it to hh:mm:ss tt, then you need to put that part in the ToString call:

lblClock.Text = date.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture);

Or better yet (IMO) use "whatever the long time pattern is for the culture":

lblClock.Text = date.ToString("T", CultureInfo.CurrentCulture);

Also note that hh is unusual; typically you don't want to 0-left-pad the number for numbers less than 10.

(Also consider using my Noda Time API, which has a LocalTime type - a more appropriate match for just a "time of day".)

Angular 2 Hover event

For handling the event on overing, you can try something like this (it works for me):

In the Html template:

<div (mouseenter)="onHovering($event)" (mouseleave)="onUnovering($event)">
  <img src="../../../contents/ctm-icons/alarm.svg" class="centering-me" alt="Alerts" />
</div>

In the angular component:

    onHovering(eventObject) {
    console.log("AlertsBtnComponent.onHovering:");
    var regExp = new RegExp(".svg" + "$");

    var srcObj = eventObject.target.offsetParent.children["0"];
    if (srcObj.tagName == "IMG") {
        srcObj.setAttribute("src", srcObj.getAttribute("src").replace(regExp, "_h.svg"));       
    }

   }
   onUnovering(eventObject) {
    console.log("AlertsBtnComponent.onUnovering:");
    var regExp = new RegExp("_h.svg" + "$");

    var srcObj = eventObject.target.offsetParent.children["0"];
    if (srcObj.tagName == "IMG") {
        srcObj.setAttribute("src", srcObj.getAttribute("src").replace(regExp, ".svg"));
    }
}

Which command in VBA can count the number of characters in a string variable?

Len is what you want.

word = "habit"  
length = Len(word)

Check if PHP-page is accessed from an iOS device

Use the user agent from $_SERVER['HTTP_USER_AGENT'], and for simple detection you can use this script:

<?php

//Detect special conditions devices
$iPod    = stripos($_SERVER['HTTP_USER_AGENT'],"iPod");
$iPhone  = stripos($_SERVER['HTTP_USER_AGENT'],"iPhone");
$iPad    = stripos($_SERVER['HTTP_USER_AGENT'],"iPad");
$Android = stripos($_SERVER['HTTP_USER_AGENT'],"Android");
$webOS   = stripos($_SERVER['HTTP_USER_AGENT'],"webOS");

//do something with this information
if( $iPod || $iPhone ){
    //browser reported as an iPhone/iPod touch -- do something here
}else if($iPad){
    //browser reported as an iPad -- do something here
}else if($Android){
    //browser reported as an Android device -- do something here
}else if($webOS){
    //browser reported as a webOS device -- do something here
}

?> 

If you want to know more details of the user device I recommended to use one of the following solutions: http://51degrees.mobi or http://deviceatlas.com

Check if file is already open

(The Q&A is about how to deal with Windows "open file" locks ... not how implement this kind of locking portably.)

This whole issue is fraught with portability issues and race conditions:

  • You could try to use FileLock, but it is not necessarily supported for your OS and/or filesystem.
  • It appears that on Windows you may be unable to use FileLock if another application has opened the file in a particular way.
  • Even if you did manage to use FileLock or something else, you've still got the problem that something may come in and open the file between you testing the file and doing the rename.

A simpler though non-portable solution is to just try the rename (or whatever it is you are trying to do) and diagnose the return value and / or any Java exceptions that arise due to opened files.

Notes:

  1. If you use the Files API instead of the File API you will get more information in the event of a failure.

  2. On systems (e.g. Linux) where you are allowed to rename a locked or open file, you won't get any failure result or exceptions. The operation will just succeed. However, on such systems you generally don't need to worry if a file is already open, since the OS doesn't lock files on open.

Send POST data via raw json with postman

Unlike jQuery in order to read raw JSON you will need to decode it in PHP.

print_r(json_decode(file_get_contents("php://input"), true));

php://input is a read-only stream that allows you to read raw data from the request body.

$_POST is form variables, you will need to switch to form radiobutton in postman then use:

foo=bar&foo2=bar2

To post raw json with jquery:

$.ajax({
    "url": "/rest/index.php",
    'data': JSON.stringify({foo:'bar'}),
    'type': 'POST',
    'contentType': 'application/json'
});

Return Boolean Value on SQL Select Statement

What you have there will return no row at all if the user doesn't exist. Here's what you need:

SELECT CASE WHEN EXISTS (
    SELECT *
    FROM [User]
    WHERE UserID = 20070022
)
THEN CAST(1 AS BIT)
ELSE CAST(0 AS BIT) END

Radio Buttons ng-checked with ng-model

[Personal Option] Avoiding using $scope, based on John Papa Angular Style Guide

so my idea is take advantage of the current model:

_x000D_
_x000D_
(function(){_x000D_
  'use strict';_x000D_
  _x000D_
   var app = angular.module('way', [])_x000D_
   app.controller('Decision', Decision);_x000D_
_x000D_
   Decision.$inject = [];     _x000D_
_x000D_
   function Decision(){_x000D_
     var vm = this;_x000D_
     vm.checkItOut = _register;_x000D_
_x000D_
     function _register(newOption){_x000D_
       console.log('should I stay or should I go');_x000D_
       console.log(newOption);  _x000D_
     }_x000D_
   }_x000D_
_x000D_
     _x000D_
     _x000D_
})();
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<div ng-app="way">_x000D_
  <div ng-controller="Decision as vm">_x000D_
    <form name="myCheckboxTest" ng-submit="vm.checkItOut(decision)">_x000D_
 <label class="radio-inline">_x000D_
  <input type="radio" name="option" ng-model="decision.myWay"_x000D_
                           ng-value="false" ng-checked="!decision.myWay"> Should I stay?_x000D_
                </label>_x000D_
                <label class="radio-inline">_x000D_
                    <input type="radio" name="option" ng-value="true"_x000D_
                           ng-model="decision.myWay" > Should I go?_x000D_
                </label>_x000D_
  _x000D_
</form>_x000D_
  </div>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

I hope I could help ;)

Measuring execution time of a function in C++

Easy way for older C++, or C:

#include <time.h> // includes clock_t and CLOCKS_PER_SEC

int main() {

    clock_t start, end;

    start = clock();
    // ...code to measure...
    end = clock();

    double duration_sec = double(end-start)/CLOCKS_PER_SEC;
    return 0;
}

Timing precision in seconds is 1.0/CLOCKS_PER_SEC

Integrating the ZXing library directly into my Android application

Have you seen the wiki pages on the zxing website? It seems you might find GettingStarted, DeveloperNotes and ScanningViaIntent helpful.

How to check for empty array in vba macro

I'll generalize the problem and the Question as intended. Test assingment on the array, and catch the eventual error

Function IsVarArrayEmpty(anArray as Variant)
Dim aVar as Variant

IsVarArrayEmpty=False
On error resume next
aVar=anArray(1)
If Err.number then '...still, it might not start at this index
    aVar=anArray(0)
    If Err.number then IsVarArrayEmpty=True ' neither 0 or 1 yields good assignment
EndIF
End Function

Sure it misses arrays with all negative indexes or all > 1... is that likely? in weirdland, yes.

android pinch zoom

Updated Answer

Code can be found here : official-doc

Answer Outdated

Check out the following links which may help you

Best examples are provided in the below links, which you can refactor to meet your requirements.

  1. implementing-the-pinch-zoom-gestur

  2. Android-pinch

  3. GestureDetector.SimpleOnGestureListener

How should I make my VBA code compatible with 64-bit Windows?

This answer is likely wrong wrong the context. I thought VBA now run on the CLR these days, but it does not. In any case, this reply may be useful to someone. Or not.


If you run Office 2010 32-bit mode then it's the same as Office 2007. (The "issue" is Office running in 64-bit mode). It's the bitness of the execution context (VBA/CLR) which is important here and the bitness of the loaded VBA/CLR depends upon the bitness of the host process.

Between 32/64-bit calls, most notable things that go wrong are using long or int (constant-sized in CLR) instead of IntPtr (dynamic sized based on bitness) for "pointer types".

The ShellExecute function has a signature of:

HINSTANCE ShellExecute(
  __in_opt  HWND hwnd,
  __in_opt  LPCTSTR lpOperation,
  __in      LPCTSTR lpFile,
  __in_opt  LPCTSTR lpParameters,
  __in_opt  LPCTSTR lpDirectory,
  __in      INT nShowCmd
);

In this case, it is important HWND is IntPtr (this is because a HWND is a "HANDLE" which is void*/"void pointer") and not long. See pinvoke.net ShellExecute as an example. (While some "solutions" are shady on pinvoke.net, it's a good place to look initially).

Happy coding.


As far as any "new syntax", I have no idea.

Finding all cycles in a directed graph

I was given this as an interview question once, I suspect this has happened to you and you are coming here for help. Break the problem into three questions and it becomes easier.

  1. how do you determine the next valid route
  2. how do you determine if a point has been used
  3. how do you avoid crossing over the same point again

Problem 1) Use the iterator pattern to provide a way of iterating route results. A good place to put the logic to get the next route is probably the "moveNext" of your iterator. To find a valid route, it depends on your data structure. For me it was a sql table full of valid route possibilities so I had to build a query to get the valid destinations given a source.

Problem 2) Push each node as you find them into a collection as you get them, this means that you can see if you are "doubling back" over a point very easily by interrogating the collection you are building on the fly.

Problem 3) If at any point you see you are doubling back, you can pop things off the collection and "back up". Then from that point try to "move forward" again.

Hack: if you are using Sql Server 2008 there is are some new "hierarchy" things you can use to quickly solve this if you structure your data in a tree.

how to access downloads folder in android?

You need to set this permission in your manifest.xml file

android.permission.WRITE_EXTERNAL_STORAGE

Embed image in a <button> element

Add new folder with name of Images in your project. Put some images into Images folder. Then it will work fine.

<input type="image" src="~/Images/Desert.jpg" alt="Submit" width="48" height="48">

Difference between logger.info and logger.debug

This is a very old question, but i don't see my understanding here so I will add my 2 cents:

Every level corresponds/maps to a type of user:

  • debug : developer - manual debugging
  • trace : automated logging and step tracer - for 3rd level support
  • info : technician / support level 1 /2
  • warn : technician / user error : automated alert / support level 1
  • critical/fatal : depends on your setup - local IT

Skipping Incompatible Libraries at compile

Normally, that is not an error per se; it is a warning that the first file it found that matches the -lPI-Http argument to the compiler/linker is not valid. The error occurs when no other library can be found with the right content.

So, you need to look to see whether /dvlpmnt/libPI-Http.a is a library of 32-bit object files or of 64-bit object files - it will likely be 64-bit if you are compiling with the -m32 option. Then you need to establish whether there is an alternative libPI-Http.a or libPI-Http.so file somewhere else that is 32-bit. If so, ensure that the directory that contains it is listed in a -L/some/where argument to the linker. If not, then you will need to obtain or build a 32-bit version of the library from somewhere.

To establish what is in that library, you may need to do:

mkdir junk
cd junk
ar x /dvlpmnt/libPI-Http.a
file *.o
cd ..
rm -fr junk

The 'file' step tells you what type of object files are in the archive. The rest just makes sure you don't make a mess that can't be easily cleaned up.

How can I fix the Microsoft Visual Studio error: "package did not load correctly"?

I had this problem after installing Crystal Reports for Visual Studio. I solved it by closing all Visual Studio instances and reinstalling Crystal Reports.

Eclipse, regular expression search and replace

For someone who needs an explanation and an example of how to use a regxp in Eclipse. Here is my example illustrating the problem.

enter image description here

I want to rename

/download.mp4^lecture_id=271

to

/271.mp4

And there can be multiple of these.

Here is how it should be done.

enter image description here

Then hit find/replace button

Program to find largest and smallest among 5 numbers without using array

Heres what I did, without using an array. This was a method to return the highest number of 5 scores.

double findHighest(double score1, double score2, double score3, double score4, double score5)
 {
   double highest = score1;
   if (score2 > score1 && score2 > score3 && score2 > score4 && score2 > score5)
      highest = score2;
   if(score3 > score1 && score3 > score2 && score3 > score4 && score3 > score5)
      highest = score3;
   if(score4 > score1 && score4 > score2 && score4 > score3 && score4 > score5)
      highest = score4;
   if (score5 > score1 && score5 > score2 && score5 > score3 && score5 > score4)
      highest = score5;
   return highest;
 }

An array is going to be far more efficient, but I had to do it for homework without using an array.

Returning IEnumerable<T> vs. IQueryable<T>

Both will give you deferred execution, yes.

As for which is preferred over the other, it depends on what your underlying datasource is.

Returning an IEnumerable will automatically force the runtime to use LINQ to Objects to query your collection.

Returning an IQueryable (which implements IEnumerable, by the way) provides the extra functionality to translate your query into something that might perform better on the underlying source (LINQ to SQL, LINQ to XML, etc.).

What is the best way to extract the first word from a string in Java?

The simple one I used to do is

str.contains(" ") ? str.split(" ")[0] : str

Where str is your string or text bla bla :). So, if

  1. str is having empty value it returns as it is.
  2. str is having one word, it returns as it is.
  3. str is multiple words, it extract the first word and return.

Hope this is helpful.

Unable to create a constant value of type Only primitive types or enumeration types are supported in this context

I had this issue and what I did and solved the problem was that I used AsEnumerable() just before my Join clause. here is my query:

List<AccountViewModel> selectedAccounts;

 using (ctx = SmallContext.GetInstance()) {
                var data = ctx.Transactions.
                    Include(x => x.Source).
                    Include(x => x.Relation).
                    AsEnumerable().
                    Join(selectedAccounts, x => x.Source.Id, y => y.Id, (x, y) => x).
                    GroupBy(x => new { Id = x.Relation.Id, Name = x.Relation.Name }).
                    ToList();
            }

I was wondering why this issue happens, and now I think It is because after you make a query via LINQ, the result will be in memory and not loaded into objects, I don't know what that state is but they are in in some transitional state I think. Then when you use AsEnumerable() or ToList(), etc, you are placing them into physical memory objects and the issue is resolving.

How can I add or update a query string parameter?

I know this is quite old but i want to fires my working version in here.

_x000D_
_x000D_
function addOrUpdateUrlParam(uri, paramKey, paramVal) {_x000D_
  var re = new RegExp("([?&])" + paramKey + "=[^&#]*", "i");_x000D_
  if (re.test(uri)) {_x000D_
    uri = uri.replace(re, '$1' + paramKey + "=" + paramVal);_x000D_
  } else {_x000D_
    var separator = /\?/.test(uri) ? "&" : "?";_x000D_
    uri = uri + separator + paramKey + "=" + paramVal;_x000D_
  }_x000D_
  return uri;_x000D_
}_x000D_
_x000D_
jQuery(document).ready(function($) {_x000D_
  $('#paramKey,#paramValue').on('change', function() {_x000D_
    if ($('#paramKey').val() != "" && $('#paramValue').val() != "") {_x000D_
      $('#uri').val(addOrUpdateUrlParam($('#uri').val(), $('#paramKey').val(), $('#paramValue').val()));_x000D_
    }_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input style="width:100%" type="text" id="uri" value="http://www.example.com/text.php">_x000D_
<label style="display:block;">paramKey_x000D_
  <input type="text" id="paramKey">_x000D_
</label>_x000D_
<label style="display:block;">paramValue_x000D_
  <input type="text" id="paramValue">_x000D_
</label>
_x000D_
_x000D_
_x000D_

NOTE This is a modified version of @elreimundo

Where is Maven Installed on Ubuntu

$ mvn --version

and look for Maven home: in the output , mine is: Maven home: /usr/share/maven

SQL Developer is returning only the date, not the time. How do I fix this?

Can you try this?

Go to Tools> Preferences > Database > NLS and set the Date Format as MM/DD/YYYY HH24:MI:SS

How Spring Security Filter Chain works

The Spring security filter chain is a very complex and flexible engine.

Key filters in the chain are (in the order)

  • SecurityContextPersistenceFilter (restores Authentication from JSESSIONID)
  • UsernamePasswordAuthenticationFilter (performs authentication)
  • ExceptionTranslationFilter (catch security exceptions from FilterSecurityInterceptor)
  • FilterSecurityInterceptor (may throw authentication and authorization exceptions)

Looking at the current stable release 4.2.1 documentation, section 13.3 Filter Ordering you could see the whole filter chain's filter organization:

13.3 Filter Ordering

The order that filters are defined in the chain is very important. Irrespective of which filters you are actually using, the order should be as follows:

  1. ChannelProcessingFilter, because it might need to redirect to a different protocol

  2. SecurityContextPersistenceFilter, so a SecurityContext can be set up in the SecurityContextHolder at the beginning of a web request, and any changes to the SecurityContext can be copied to the HttpSession when the web request ends (ready for use with the next web request)

  3. ConcurrentSessionFilter, because it uses the SecurityContextHolder functionality and needs to update the SessionRegistry to reflect ongoing requests from the principal

  4. Authentication processing mechanisms - UsernamePasswordAuthenticationFilter, CasAuthenticationFilter, BasicAuthenticationFilter etc - so that the SecurityContextHolder can be modified to contain a valid Authentication request token

  5. The SecurityContextHolderAwareRequestFilter, if you are using it to install a Spring Security aware HttpServletRequestWrapper into your servlet container

  6. The JaasApiIntegrationFilter, if a JaasAuthenticationToken is in the SecurityContextHolder this will process the FilterChain as the Subject in the JaasAuthenticationToken

  7. RememberMeAuthenticationFilter, so that if no earlier authentication processing mechanism updated the SecurityContextHolder, and the request presents a cookie that enables remember-me services to take place, a suitable remembered Authentication object will be put there

  8. AnonymousAuthenticationFilter, so that if no earlier authentication processing mechanism updated the SecurityContextHolder, an anonymous Authentication object will be put there

  9. ExceptionTranslationFilter, to catch any Spring Security exceptions so that either an HTTP error response can be returned or an appropriate AuthenticationEntryPoint can be launched

  10. FilterSecurityInterceptor, to protect web URIs and raise exceptions when access is denied

Now, I'll try to go on by your questions one by one:

I'm confused how these filters are used. Is it that for the spring provided form-login, UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not? Does the form-login namespace element auto-configure these filters? Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

Once you are configuring a <security-http> section, for each one you must at least provide one authentication mechanism. This must be one of the filters which match group 4 in the 13.3 Filter Ordering section from the Spring Security documentation I've just referenced.

This is the minimum valid security:http element which can be configured:

<security:http authentication-manager-ref="mainAuthenticationManager" 
               entry-point-ref="serviceAccessDeniedHandler">
    <security:intercept-url pattern="/sectest/zone1/**" access="hasRole('ROLE_ADMIN')"/>
</security:http>

Just doing it, these filters are configured in the filter chain proxy:

{
        "1": "org.springframework.security.web.context.SecurityContextPersistenceFilter",
        "2": "org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter",
        "3": "org.springframework.security.web.header.HeaderWriterFilter",
        "4": "org.springframework.security.web.csrf.CsrfFilter",
        "5": "org.springframework.security.web.savedrequest.RequestCacheAwareFilter",
        "6": "org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter",
        "7": "org.springframework.security.web.authentication.AnonymousAuthenticationFilter",
        "8": "org.springframework.security.web.session.SessionManagementFilter",
        "9": "org.springframework.security.web.access.ExceptionTranslationFilter",
        "10": "org.springframework.security.web.access.intercept.FilterSecurityInterceptor"
    }

Note: I get them by creating a simple RestController which @Autowires the FilterChainProxy and returns it's contents:

    @Autowired
    private FilterChainProxy filterChainProxy;

    @Override
    @RequestMapping("/filterChain")
    public @ResponseBody Map<Integer, Map<Integer, String>> getSecurityFilterChainProxy(){
        return this.getSecurityFilterChainProxy();
    }

    public Map<Integer, Map<Integer, String>> getSecurityFilterChainProxy(){
        Map<Integer, Map<Integer, String>> filterChains= new HashMap<Integer, Map<Integer, String>>();
        int i = 1;
        for(SecurityFilterChain secfc :  this.filterChainProxy.getFilterChains()){
            //filters.put(i++, secfc.getClass().getName());
            Map<Integer, String> filters = new HashMap<Integer, String>();
            int j = 1;
            for(Filter filter : secfc.getFilters()){
                filters.put(j++, filter.getClass().getName());
            }
            filterChains.put(i++, filters);
        }
        return filterChains;
    }

Here we could see that just by declaring the <security:http> element with one minimum configuration, all the default filters are included, but none of them is of a Authentication type (4th group in 13.3 Filter Ordering section). So it actually means that just by declaring the security:http element, the SecurityContextPersistenceFilter, the ExceptionTranslationFilter and the FilterSecurityInterceptor are auto-configured.

In fact, one authentication processing mechanism should be configured, and even security namespace beans processing claims for that, throwing an error during startup, but it can be bypassed adding an entry-point-ref attribute in <http:security>

If I add a basic <form-login> to the configuration, this way:

<security:http authentication-manager-ref="mainAuthenticationManager">
    <security:intercept-url pattern="/sectest/zone1/**" access="hasRole('ROLE_ADMIN')"/>
    <security:form-login />
</security:http>

Now, the filterChain will be like this:

{
        "1": "org.springframework.security.web.context.SecurityContextPersistenceFilter",
        "2": "org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter",
        "3": "org.springframework.security.web.header.HeaderWriterFilter",
        "4": "org.springframework.security.web.csrf.CsrfFilter",
        "5": "org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter",
        "6": "org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter",
        "7": "org.springframework.security.web.savedrequest.RequestCacheAwareFilter",
        "8": "org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter",
        "9": "org.springframework.security.web.authentication.AnonymousAuthenticationFilter",
        "10": "org.springframework.security.web.session.SessionManagementFilter",
        "11": "org.springframework.security.web.access.ExceptionTranslationFilter",
        "12": "org.springframework.security.web.access.intercept.FilterSecurityInterceptor"
    }

Now, this two filters org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter and org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter are created and configured in the FilterChainProxy.

So, now, the questions:

Is it that for the spring provided form-login, UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not?

Yes, it is used to try to complete a login processing mechanism in case the request matches the UsernamePasswordAuthenticationFilter url. This url can be configured or even changed it's behaviour to match every request.

You could too have more than one Authentication processing mechanisms configured in the same FilterchainProxy (such as HttpBasic, CAS, etc).

Does the form-login namespace element auto-configure these filters?

No, the form-login element configures the UsernamePasswordAUthenticationFilter, and in case you don't provide a login-page url, it also configures the org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter, which ends in a simple autogenerated login page.

The other filters are auto-configured by default just by creating a <security:http> element with no security:"none" attribute.

Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

Every request should reach it, as it is the element which takes care of whether the request has the rights to reach the requested url. But some of the filters processed before might stop the filter chain processing just not calling FilterChain.doFilter(request, response);. For example, a CSRF filter might stop the filter chain processing if the request has not the csrf parameter.

What if I want to secure my REST API with JWT-token, which is retrieved from login? I must configure two namespace configuration http tags, rights? Other one for /login with UsernamePasswordAuthenticationFilter, and another one for REST url's, with custom JwtAuthenticationFilter.

No, you are not forced to do this way. You could declare both UsernamePasswordAuthenticationFilter and the JwtAuthenticationFilter in the same http element, but it depends on the concrete behaviour of each of this filters. Both approaches are possible, and which one to choose finnally depends on own preferences.

Does configuring two http elements create two springSecurityFitlerChains?

Yes, that's true

Is UsernamePasswordAuthenticationFilter turned off by default, until I declare form-login?

Yes, you could see it in the filters raised in each one of the configs I posted

How do I replace SecurityContextPersistenceFilter with one, which will obtain Authentication from existing JWT-token rather than JSESSIONID?

You could avoid SecurityContextPersistenceFilter, just configuring session strategy in <http:element>. Just configure like this:

<security:http create-session="stateless" >

Or, In this case you could overwrite it with another filter, this way inside the <security:http> element:

<security:http ...>  
   <security:custom-filter ref="myCustomFilter" position="SECURITY_CONTEXT_FILTER"/>    
</security:http>
<beans:bean id="myCustomFilter" class="com.xyz.myFilter" />

EDIT:

One question about "You could too have more than one Authentication processing mechanisms configured in the same FilterchainProxy". Will the latter overwrite the authentication performed by first one, if declaring multiple (Spring implementation) authentication filters? How this relates to having multiple authentication providers?

This finally depends on the implementation of each filter itself, but it's true the fact that the latter authentication filters at least are able to overwrite any prior authentication eventually made by preceding filters.

But this won't necesarily happen. I have some production cases in secured REST services where I use a kind of authorization token which can be provided both as a Http header or inside the request body. So I configure two filters which recover that token, in one case from the Http Header and the other from the request body of the own rest request. It's true the fact that if one http request provides that authentication token both as Http header and inside the request body, both filters will try to execute the authentication mechanism delegating it to the manager, but it could be easily avoided simply checking if the request is already authenticated just at the begining of the doFilter() method of each filter.

Having more than one authentication filter is related to having more than one authentication providers, but don't force it. In the case I exposed before, I have two authentication filter but I only have one authentication provider, as both of the filters create the same type of Authentication object so in both cases the authentication manager delegates it to the same provider.

And opposite to this, I too have a scenario where I publish just one UsernamePasswordAuthenticationFilter but the user credentials both can be contained in DB or LDAP, so I have two UsernamePasswordAuthenticationToken supporting providers, and the AuthenticationManager delegates any authentication attempt from the filter to the providers secuentially to validate the credentials.

So, I think it's clear that neither the amount of authentication filters determine the amount of authentication providers nor the amount of provider determine the amount of filters.

Also, documentation states SecurityContextPersistenceFilter is responsible of cleaning the SecurityContext, which is important due thread pooling. If I omit it or provide custom implementation, I have to implement the cleaning manually, right? Are there more similar gotcha's when customizing the chain?

I did not look carefully into this filter before, but after your last question I've been checking it's implementation, and as usually in Spring, nearly everything could be configured, extended or overwrited.

The SecurityContextPersistenceFilter delegates in a SecurityContextRepository implementation the search for the SecurityContext. By default, a HttpSessionSecurityContextRepository is used, but this could be changed using one of the constructors of the filter. So it may be better to write an SecurityContextRepository which fits your needs and just configure it in the SecurityContextPersistenceFilter, trusting in it's proved behaviour rather than start making all from scratch.

LDAP root query syntax to search more than one specific OU

I don't think this is possible with AD. The distinguishedName attribute is the only thing I know of that contains the OU piece on which you're trying to search, so you'd need a wildcard to get results for objects under those OUs. Unfortunately, the wildcard character isn't supported on DNs.

If at all possible, I'd really look at doing this in 2 queries using OU=Staff... and OU=Vendors... as the base DNs.

Converting JSON data to Java object

Bewaaaaare of Gson! It's very cool, very great, but the second you want to do anything other than simple objects, you could easily need to start building your own serializers (which isn't that hard).

Also, if you have an array of Objects, and you deserialize some json into that array of Objects, the true types are LOST! The full objects won't even be copied! Use XStream.. Which, if using the jsondriver and setting the proper settings, will encode ugly types into the actual json, so that you don't loose anything. A small price to pay (ugly json) for true serialization.

Note that Jackson fixes these issues, and is faster than GSON.

How to Customize a Progress Bar In Android

There are two types of progress bars called determinate progress bar (fixed duration) and indeterminate progress bar (unknown duration).

Drawables for both of types of progress bar can be customized by defining drawable as xml resource. You can find more information about progress bar styles and customization at http://www.zoftino.com/android-progressbar-and-custom-progressbar-examples.

Customizing fixed or horizontal progress bar :

Below xml is a drawable resource for horizontal progress bar customization.

 <?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background"
        android:gravity="center_vertical|fill_horizontal">
        <shape android:shape="rectangle"
            android:tint="?attr/colorControlNormal">
            <corners android:radius="8dp"/>
            <size android:height="20dp" />
            <solid android:color="#90caf9" />
        </shape>
    </item>
    <item android:id="@android:id/progress"
        android:gravity="center_vertical|fill_horizontal">
        <scale android:scaleWidth="100%">
            <shape android:shape="rectangle"
                android:tint="?attr/colorControlActivated">
                <corners android:radius="8dp"/>
                <size android:height="20dp" />
                <solid android:color="#b9f6ca" />
            </shape>
        </scale>
    </item>
</layer-list>

Customizing indeterminate progress bar

Below xml is a drawable resource for circular progress bar customization.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/progress"
        android:top="16dp"
        android:bottom="16dp">
                <rotate
                    android:fromDegrees="45"
                    android:pivotX="50%"
                    android:pivotY="50%"
                    android:toDegrees="315">
                    <shape android:shape="rectangle">
                        <size
                            android:width="80dp"
                            android:height="80dp" />
                        <stroke
                            android:width="6dp"
                            android:color="#b71c1c" />
                    </shape>
                </rotate>           
    </item>
</layer-list>

Get string between two strings in a string

You can use the extension method below:

public static string GetStringBetween(this string token, string first, string second)
    {            
        if (!token.Contains(first)) return "";

        var afterFirst = token.Split(new[] { first }, StringSplitOptions.None)[1];

        if (!afterFirst.Contains(second)) return "";

        var result = afterFirst.Split(new[] { second }, StringSplitOptions.None)[0];

        return result;
    }

Usage is:

var token = "super exemple of string key : text I want to keep - end of my string";
var keyValue = token.GetStringBetween("key : ", " - ");

How can I find a specific file from a Linux terminal?

In general, the best way to find any file in any arbitrary location is to start a terminal window and type in the classic Unix command "find":

find / -name index.html -print

Since the file you're looking for is the root file in the root directory of your web server, it's probably easier to find your web server's document root. For example, look under:

/var/www/*

Or type:

find /var/www -name index.html -print

C# code to validate email address

I use this single liner method which does the work for me-

using System.ComponentModel.DataAnnotations;
public bool IsValidEmail(string source)
{
    return new EmailAddressAttribute().IsValid(source);
}

Per the comments, this will "fail" if the source (the email address) is null.

public static bool IsValidEmailAddress(this string address) => address != null && new EmailAddressAttribute().IsValid(address);

how to make twitter bootstrap submenu to open on the left side?

The correct way to do the task is:

/* Submenu placement itself */
.dropdown-submenu > .dropdown-menu { left: auto; right: 100%; }
/* Arrow position */
.dropdown-submenu { position: relative; }
.dropdown-submenu > a:after { position: absolute; left: 7px; top: 3px; float: none; border-right-color: #cccccc; border-width: 5px 5px 5px 0; }
.dropdown-submenu:hover > a:after { border-right-color: #ffffff; }

Pylint "unresolved import" error in Visual Studio Code

If you are using pipenv then you need to specify the path to your virtual environment.in settings.json file. For example :

{
    "python.pythonPath": 
           "/Users/username/.local/share/virtualenvs/Your-Virual-Env/bin/python"
}

This can help.

Is it possible to use vh minus pixels in a CSS calc()?

It does work indeed. Issue was with my less compiler. It was compiled in to:

.container {
  min-height: calc(-51vh);
}

Fixed with the following code in less file:

.container {
  min-height: calc(~"100vh - 150px");
}

Thanks to this link: Less Aggressive Compilation with CSS3 calc

Get DataKey values in GridView RowCommand

foreach (GridViewRow gvr in gvMyGridView.Rows)
{
    string PrimaryKey = gvMyGridView.DataKeys[gvr.RowIndex].Values[0].ToString();
}

You can use this code while doing an iteration with foreach or for any GridView event like OnRowDataBound.

Here you can input multiple values for DataKeyNames by separating with comma ,. For example, DataKeyNames="ProductID,ItemID,OrderID".

You can now access each of DataKeys by providing its index like below:

string ProductID = gvMyGridView.DataKeys[gvr.RowIndex].Values[0].ToString();
string ItemID = gvMyGridView.DataKeys[gvr.RowIndex].Values[1].ToString();
string OrderID = gvMyGridView.DataKeys[gvr.RowIndex].Values[2].ToString();

You can also use Key Name instead of its index to get the values from DataKeyNames collection like below:

string ProductID = gvMyGridView.DataKeys[gvr.RowIndex].Values["ProductID"].ToString();
string ItemID = gvMyGridView.DataKeys[gvr.RowIndex].Values["ItemID"].ToString();
string OrderID = gvMyGridView.DataKeys[gvr.RowIndex].Values["OrderID"].ToString();

Use success() or complete() in AJAX call

Well, speaking from quarantine, the complete() in $.ajax is like finally in try catch block.

If you use try catch block in any programming language, it doesn't matter whether you execute a thing successfully or got an error in execution. the finally{} block will always be executed.

Same goes for complete() in $.ajax, whether you get success() response or error() the complete() function always will be called once the execution has been done.

Mac install and open mysql using terminal

  1. install homebrew via terminal

  2. brew install mysql

Update Git branches from master

  1. git checkout master
  2. git pull
  3. git checkout feature_branch
  4. git rebase master
  5. git push -f

You need to do a forceful push after rebasing against master

How to do a redirect to another route with react-router?

1) react-router > V5 useHistory hook:

If you have React >= 16.8 and functional components you can use the useHistory hook from react-router.

import React from 'react';
import { useHistory } from 'react-router-dom';

const YourComponent = () => {
    const history = useHistory();

    const handleClick = () => {
        history.push("/path/to/push");
    }

    return (
        <div>
            <button onClick={handleClick} type="button" />
        </div>
    );
}

export default YourComponent;

2) react-router > V4 withRouter HOC:

As @ambar mentioned in the comments, React-router has changed their code base since their V4. Here are the documentations - official, withRouter

import React, { Component } from 'react';
import { withRouter } from "react-router-dom";

class YourComponent extends Component {
    handleClick = () => {
        this.props.history.push("path/to/push");
    }

    render() {
        return (
            <div>
                <button onClick={this.handleClick} type="button">
            </div>
        );
    };
}

export default withRouter(YourComponent);

3) React-router < V4 with browserHistory

You can achieve this functionality using react-router BrowserHistory. Code below:

import React, { Component } from 'react';
import { browserHistory } from 'react-router';

export default class YourComponent extends Component {
    handleClick = () => {
        browserHistory.push('/login');
    };

    render() {
        return (
            <div>
                <button onClick={this.handleClick} type="button">
            </div>
        );
    };
}

4) Redux connected-react-router

If you have connected your component with redux, and have configured connected-react-router all you have to do is this.props.history.push("/new/url"); ie, you don't need withRouter HOC to inject history to the component props.

// reducers.js
import { combineReducers } from 'redux';
import { connectRouter } from 'connected-react-router';

export default (history) => combineReducers({
    router: connectRouter(history),
    ... // rest of your reducers
});


// configureStore.js
import { createBrowserHistory } from 'history';
import { applyMiddleware, compose, createStore } from 'redux';
import { routerMiddleware } from 'connected-react-router';
import createRootReducer from './reducers';
...
export const history = createBrowserHistory();

export default function configureStore(preloadedState) {
    const store = createStore(
        createRootReducer(history), // root reducer with router state
        preloadedState,
        compose(
            applyMiddleware(
                routerMiddleware(history), // for dispatching history actions
                // ... other middlewares ...
            ),
        ),
    );

    return store;
}


// set up other redux requirements like for eg. in index.js
import { Provider } from 'react-redux';
import { Route, Switch } from 'react-router';
import { ConnectedRouter } from 'connected-react-router';
import configureStore, { history } from './configureStore';
...
const store = configureStore(/* provide initial state if any */)

ReactDOM.render(
    <Provider store={store}>
        <ConnectedRouter history={history}>
            <> { /* your usual react-router v4/v5 routing */ }
                <Switch>
                    <Route exact path="/yourPath" component={YourComponent} />
                </Switch>
            </>
        </ConnectedRouter>
    </Provider>,
    document.getElementById('root')
);


// YourComponent.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
...

class YourComponent extends Component {
    handleClick = () => {
        this.props.history.push("path/to/push");
    }

    render() {
        return (
          <div>
            <button onClick={this.handleClick} type="button">
          </div>
        );
      }
    };

}

export default connect(mapStateToProps = {}, mapDispatchToProps = {})(YourComponent);

How to disable manual input for JQuery UI Datepicker field?

I think you should add style="background:white;" to make looks like it is writable

<input type="text" size="23" name="dateMonthly" id="dateMonthly" readonly="readonly"   style="background:white;"/>

How to drop a unique constraint from table column?

This statement works for me

  ALTER TABLE table_name DROP UNIQUE (column_name);

Numpy: find index of the elements within range

s=[52, 33, 70, 39, 57, 59, 7, 2, 46, 69, 11, 74, 58, 60, 63, 43, 75, 92, 65, 19, 1, 79, 22, 38, 26, 3, 66, 88, 9, 15, 28, 44, 67, 87, 21, 49, 85, 32, 89, 77, 47, 93, 35, 12, 73, 76, 50, 45, 5, 29, 97, 94, 95, 56, 48, 71, 54, 55, 51, 23, 84, 80, 62, 30, 13, 34]

dic={}

for i in range(0,len(s),10):
    dic[i,i+10]=list(filter(lambda x:((x>=i)&(x<i+10)),s))
print(dic)

for keys,values in dic.items():
    print(keys)
    print(values)

Output:

(0, 10)
[7, 2, 1, 3, 9, 5]
(20, 30)
[22, 26, 28, 21, 29, 23]
(30, 40)
[33, 39, 38, 32, 35, 30, 34]
(10, 20)
[11, 19, 15, 12, 13]
(40, 50)
[46, 43, 44, 49, 47, 45, 48]
(60, 70)
[69, 60, 63, 65, 66, 67, 62]
(50, 60)
[52, 57, 59, 58, 50, 56, 54, 55, 51]  

Default username password for Tomcat Application Manager

The admin and manager apps are two separate things. Here's a snapshot of a tomcat-users.xml file that works, try this:

<?xml version='1.0' encoding='utf-8'?>  
<tomcat-users>  
    <role rolename="tomcat"/>  
    <role rolename="role1"/>  
    <role rolename="manager"/>  
    <user username="tomcat" password="tomcat" roles="tomcat"/>  
    <user username="both" password="tomcat" roles="tomcat,role1"/>  
    <user username="role1" password="tomcat" roles="role1"/>  
    <user username="USERNAME" password="PASSWORD" roles="manager,tomcat,role1"/>  
</tomcat-users>  

It works for me very well

How do I redirect to another webpage?

You can write the Url.Action for the Button click event in the script section as follows.

function onclick() {
    location.href = '@Url.Action("Index", "Home")';
}

Use of REPLACE in SQL Query for newline/ carriage return characters

There are probably embedded tabs (CHAR(9)) etc. as well. You can find out what other characters you need to replace (we have no idea what your goal is) with something like this:

DECLARE @var NVARCHAR(255), @i INT;

SET @i = 1;

SELECT @var = AccountType FROM dbo.Account
  WHERE AccountNumber = 200
  AND AccountType LIKE '%Daily%';

CREATE TABLE #x(i INT PRIMARY KEY, c NCHAR(1), a NCHAR(1));

WHILE @i <= LEN(@var)
BEGIN
  INSERT #x 
    SELECT SUBSTRING(@var, @i, 1), ASCII(SUBSTRING(@var, @i, 1));

  SET @i = @i + 1;
END

SELECT i,c,a FROM #x ORDER BY i;

You might also consider doing better cleansing of this data before it gets into your database. Cleaning it every time you need to search or display is not the best approach.

What do *args and **kwargs mean?

Putting *args and/or **kwargs as the last items in your function definition’s argument list allows that function to accept an arbitrary number of arguments and/or keyword arguments.

For example, if you wanted to write a function that returned the sum of all its arguments, no matter how many you supply, you could write it like this:

def my_sum(*args):
    return sum(args)

It’s probably more commonly used in object-oriented programming, when you’re overriding a function, and want to call the original function with whatever arguments the user passes in.

You don’t actually have to call them args and kwargs, that’s just a convention. It’s the * and ** that do the magic.

The official Python documentation has a more in-depth look.

How to add facebook share button on my website?

You can do this by using asynchronous Javascript SDK provided by facebook

Have a look at the following code

FB Javascript SDK initialization

<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'YOUR APP ID', status: true, cookie: true,
xfbml: true});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>

Note: Remember to replace YOUR APP ID with your facebook AppId. If you don't have facebook AppId and you don't know how to create please check this

Add JQuery Library, I would preferred Google Library

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>

Add share dialog box (You can customize this dialog box by setting up parameters

<script type="text/javascript">
$(document).ready(function(){
$('#share_button').click(function(e){
e.preventDefault();
FB.ui(
{
method: 'feed',
name: 'This is the content of the "name" field.',
link: 'http://www.groupstudy.in/articlePost.php?id=A_111213073144',
picture: 'http://www.groupstudy.in/img/logo3.jpeg',
caption: 'Top 3 reasons why you should care about your finance',
description: "What happens when you don't take care of your finances? Just look at our country -- you spend irresponsibly, get in debt up to your eyeballs, and stress about how you're going to make ends meet. The difference is that you don't have a glut of taxpayers…",
message: ""
});
});
});
</script>

Now finally add image button

<img src = "share_button.png" id = "share_button">

For more detailed kind of information. please click here

I want to delete all bin and obj folders to force all projects to rebuild everything

http://vsclean.codeplex.com/

Command line tool that finds Visual Studio solutions and runs the Clean command on them. This lets you clean up the /bin/* directories of all those old projects you have lying around on your harddrive

How to insert a value that contains an apostrophe (single quote)?

Single quotes are escaped by doubling them up,

The following SQL illustrates this functionality.

declare @person TABLE (
    [First] nvarchar(200),
    [Last] nvarchar(200)
)

insert into @person 
    (First, Last)
values
    ('Joe', 'O''Brien')

select * from @person

Results

First   | Last
===================
Joe     | O'Brien

is there any PHP function for open page in new tab

You can simply use target="_blank" to open a page in a new tab

<a href="whatever.php" target="_blank">Opens On Another Tab</a>

Or you can simply use a javascript for onload

<body onload="window.open(url, '_blank');">

Structs data type in php?

I cobbled together a 'dynamic' struct class today, had a look tonight and someone has written something similar with better handling of constructor parameters, it might be worth a look:

http://code.activestate.com/recipes/577160-php-struct-port/

One of the comments on this page mentions an interesting thing in PHP - apparently you're able to cast an array as an object, which lets you refer to array elements using the arrow notation, as you would with a Struct pointer in C. The comment's example was as follows:

$z = array('foo' => 1, 'bar' => true, 'baz' => array(1,2,3));
//accessing values as properties
$y = (object)$z;
echo $y->foo;

I haven't tried this myself yet, but it may be that you could get the desired notation by just casting - if that's all you're after. These are of course 'dynamic' data structures, just syntactic sugar for accessing key/value pairs in a hash.

If you're actually looking for something more statically typed, then ASpencer's answer is the droid you're looking for (as Obi-Wan might say.)

When is the finalize() method called in Java?

finalize() is called just before garbage collection. It is not called when an object goes out of scope. This means that you cannot know when or even if finalize() will be executed.

Example:

If your program end before garbage collector occur, then finalize() will not execute. Therefore, it should be used as backup procedure to ensure the proper handling of other resources, or for special use applications, not as the means that your program uses in its normal operation.

CSS: Center block, but align contents to the left

I've found the easiest way to centre and left-align text inside a container is the following:

HTML:

<div>
  <p>Some interesting text.</p>
</div>

CSS:

P {
  width: 50%; //or whatever looks best
  margin: auto; //top and bottom margin can be added for aesthetic effect
}

Hope this is what you were looking for as it took me quite a bit of searching just to figure out this pretty basic solution.

Using jQuery UI sortable with HTML tables

You can call sortable on a <tbody> instead of on the individual rows.

<table>
    <tbody>
        <tr> 
            <td>1</td>
            <td>2</td>
        </tr>
        <tr>
            <td>3</td>
            <td>4</td> 
        </tr>
        <tr>
            <td>5</td>
            <td>6</td>
        </tr>  
    </tbody>    
</table>?

<script>
    $('tbody').sortable();
</script> 

_x000D_
_x000D_
$(function() {_x000D_
  $( "tbody" ).sortable();_x000D_
});
_x000D_
 _x000D_
table {_x000D_
    border-spacing: collapse;_x000D_
    border-spacing: 0;_x000D_
}_x000D_
td {_x000D_
    width: 50px;_x000D_
    height: 25px;_x000D_
    border: 1px solid black;_x000D_
}
_x000D_
 _x000D_
_x000D_
<link href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet">_x000D_
<script src="//code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>_x000D_
_x000D_
<table>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <td>1</td>_x000D_
            <td>2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>3</td>_x000D_
            <td>4</td>_x000D_
        </tr>_x000D_
        <tr> _x000D_
            <td>5</td>_x000D_
            <td>6</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>7</td>_x000D_
            <td>8</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>9</td> _x000D_
            <td>10</td>_x000D_
        </tr>  _x000D_
    </tbody>    _x000D_
</table>
_x000D_
_x000D_
_x000D_

Get pandas.read_csv to read empty values as empty string instead of nan

I added a ticket to add an option of some sort here:

https://github.com/pydata/pandas/issues/1450

In the meantime, result.fillna('') should do what you want

EDIT: in the development version (to be 0.8.0 final) if you specify an empty list of na_values, empty strings will stay empty strings in the result

How to return images in flask response?

You use something like

from flask import send_file

@app.route('/get_image')
def get_image():
    if request.args.get('type') == '1':
       filename = 'ok.gif'
    else:
       filename = 'error.gif'
    return send_file(filename, mimetype='image/gif')

to send back ok.gif or error.gif, depending on the type query parameter. See the documentation for the send_file function and the request object for more information.

What is the difference between --save and --save-dev?

By default, NPM simply installs a package under node_modules. When you're trying to install dependencies for your app/module, you would need to first install them, and then add them to the dependencies section of your package.json.

--save-dev adds the third-party package to the package's development dependencies. It won't be installed when someone runs npm install directly to install your package. It's typically only installed if someone clones your source repository first and then runs npm install in it.

--save adds the third-party package to the package's dependencies. It will be installed together with the package whenever someone runs npm install package.

Dev dependencies are those dependencies that are only needed for developing the package. That can include test runners, compilers, packagers, etc. Both types of dependencies are stored in the package's package.json file. --save adds to dependencies, --save-dev adds to devDependencies

npm install documentation can be referred here.

--

Please note that --save is now the default option, since NPM 5. Therefore, it is not explicitly needed anymore. It is possible to run npm install without the --save to achieve the same result.