Change the color of address bar in mobile Chrome for Android browser

Зададим цвет адресной строки для Chrome под Android на примере WordPress.
В файл схемы …./header.php в тег добавим <meta name="theme-color" content="#ff66ee"> и увидим такой результат Screenshot_2016-08-30-20-44-13_com.android.chrome

Век живи, век учись, вариант выделения дробной части

Задача, положить дробное число раздельно в два столбца, воспользуемся оператором взятия остатка от деления %, это Лёха подсказал
drop table #test17;

create table #test17(c1 int, c2 decimal(10,10) /*отдадим все 10 знаков на хранение дробной части*/);

insert into #test17
 select c,c from (select 12.34567 c) tt;
-- для MSSQL Arithmetic overflow error converting numeric to data type numeric.
-- The statement has been terminated.
-- или в MySQL Data truncation: Out of range value for column 'c2' at row 1

insert into #test17
 select c,c%1 from (select 12.34567 c) tt;

select * from #test17;

c1	c2
12	0.3456700000

для Оракла функция mod(c, d)

Select a particular option in a SELECT element in jQuery

Выбрать элемент списка с помощью jQuery, столько разных усложнений, а ведь на то она и библиотека, чтобы сделать код проще.
$("#selId").val‌​("val1").cha‌​nge();
-- или если с мультивыбором
$("#selId").val‌​(["val3", "val5"]).cha‌​nge();
а можно и всяко разно
$('#selId option[value="val1"]').‌​attr('selected', 'selected');
$('#selId option').filter(function(i, o) { return $(o).val() == "val1"})
по этому поводу часто идут холивары, но можно заглянуть в код jQuery и увидеть что присвоение значения списку установит свойство selected = true для элемента списка с равным значением.
jQuery.fn.extend({
	val: function( value ) {
		var hooks, ret, isFunction,
			elem = this[0];
......................
		return this.each(function( i ) {
			var val;

......................
			hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];

			// If set returns undefined, fall back to normal setting
			if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
				this.value = val;
			}
		});
......................
jQuery.extend({
	valHooks: {
		option: {
			get: function( elem ) {
				var val = jQuery.find.attr( elem, "value" );
				return val != null ?
					val :
					// Support: IE10-11+
					// option.text throws exceptions (#14686, #14858)
					jQuery.trim( jQuery.text( elem ) );
			}
		},
		select: {
			get: function( elem ) {
				var value, option,
					options = elem.options,
					index = elem.selectedIndex,
					one = elem.type === "select-one" || index < 0,
					values = one ? null : [],
					max = one ? index + 1 : options.length,
					i = index < 0 ?
						max :
						one ? index : 0;

				// Loop through all the selected options
				for ( ; i < max; i++ ) {
					option = options[ i ];

					// oldIE doesn't update selected after form reset (#2551)
					if ( ( option.selected || i === index ) &&
							// Don't return options that are disabled or in a disabled optgroup
							( support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
							( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {

						// Get the specific value for the option
						value = jQuery( option ).val();

						// We don't need an array for one selects
						if ( one ) {
							return value;
						}

						// Multi-Selects return an array
						values.push( value );
					}
				}

				return values;
			},

			set: function( elem, value ) {
				var optionSet, option,
					options = elem.options,
					values = jQuery.makeArray( value ),
					i = options.length;

				while ( i-- ) {
					option = options[ i ];

					if ( jQuery.inArray( jQuery.valHooks.option.get( option ), values ) >= 0 ) {

						// Support: IE6
						// When new option element is added to select box we need to
						// force reflow of newly added node in order to workaround delay
						// of initialization properties
						try {
							option.selected = optionSet = true;

						} catch ( _ ) {

							// Will be executed only in IE6
							option.scrollHeight;
						}

					} else {
						option.selected = false;
					}
				}

				// Force browsers to behave consistently when non-matching value is set
				if ( !optionSet ) {
					elem.selectedIndex = -1;
				}

				return options;
			}

......................

Difference between decodeURIComponent and decodeURI

Различия в decodeURI и decodeURIComponent, в последнем нет исключений он декодирует все символы.
tt1 = encodeURI(" ; / ? : @ & = + $ , # ")
"%20;%20/%20?%20:%20@%20&%20=%20+%20$%20,%20#%20"
tt2 = encodeURIComponent(" ; / ? : @ & = + $ , # ")
"%20%3B%20%2F%20%3F%20%3A%20%40%20%26%20%3D%20%2B%20%24%20%2C%20%23%20"
tt3 = decodeURI(tt1)
" ; / ? : @ & = + $ , # "
tt4 = decodeURI(tt2)
" %3B %2F %3F %3A %40 %26 %3D %2B %24 %2C %23 "
tt5 = decodeURIComponent(tt1)
" ; / ? : @ & = + $ , # "
tt6 = decodeURIComponent(tt2)
" ; / ? : @ & = + $ , # "
const jschar js_uriReservedPlusPound_ucstr[] =
    {';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '#', 0};

static JSBool
str_decodeURI(JSContext *cx, uintN argc, jsval *vp) {
    JSString *str;

    str = ArgToRootedString(cx, argc, vp, 0);
    if (!str)
        return JS_FALSE;
    return Decode(cx, str, js_uriReservedPlusPound_ucstr, vp);
}

static JSBool
str_decodeURI_Component(JSContext *cx, uintN argc, jsval *vp) {
    JSString *str;

    str = ArgToRootedString(cx, argc, vp, 0);
    if (!str)
        return JS_FALSE;
    return Decode(cx, str, js_empty_ucstr, vp);
}

Transforming XML data into a rowset using the nodes() method and Performance

Преобразуем XML данные из столбца таблицы в табличные используя метод xml nodes() и cross apply.
Пример, три варианта, в первых двух сгенерирована XML с 1000 узлов, в последнем 10000, первый и второй варианты отличаются представлением XML, значения в атрибутах или в тэгах. В третьем, главное отличие, XML сохраняется в переменную, и результат, производительность на несколько порядков выше.
Итог: 8 сек, 12 сек, и 125 мс, если хмл-ка маленькая 10-50 узлов можно и не использовать переменную, иначе придется, или использовать OpenXML.
Если запустить первый вариант с 10К, то будем ждать долго, минут 10 (не дождался прервал на 5), деградация в прогрессии.
with 
t as (
 select * from (values(1),(2),(3),(4),(5),(6),(7),(8),(9))t(gid)
), t2 as (
 select row_number() over (order by t.gid) r,t.* from t, t tt1, t tt2, t tt3, t tt4--, t tt5
), t_xml as (
 select cast((select top(1000) * from t2 for xml raw) as xml) xmlData -- всего 1000 нод
), t_from_xml as (
 select
  x.xCol.value('@r','int') id
   ,x.xCol.value('@gid','int') gid 
from  t_xml b
 cross apply b.xmlData.nodes('/row') as x(xCol)  
)
--select top(1000) * from t2
--select * from t_xml
select * from t_from_xml
with 
t as (
 select * from (values(1),(2),(3),(4),(5),(6),(7),(8),(9))t(gid)
), t2 as (
 select row_number() over (order by t.gid) r,t.* from t, t tt1, t tt2, t tt3, t tt4--, t tt5
), t_xml as (
 select cast((select top(1000) * from t2 for xml path('row')) as xml) xmlData -- всего 1000 нод
), t_from_xml as (
 select
  x.xCol.value('(r/text())[1]','int') id
   ,x.xCol.value('(gid/text())[1]','int') gid 
from  t_xml b
 cross apply b.xmlData.nodes('/row') as x(xCol)  
)
--select top(1000) * from t2
--select * from t_xml
select * from t_from_xml
DECLARE @data xml
with 
t as (
 select * from (values(1),(2),(3),(4),(5),(6),(7),(8),(9))t(gid)
), t2 as (
 select row_number() over (order by t.gid) r,t.* from t, t tt1, t tt2, t tt3, t tt4--, t tt5
), t_xml as (
 select cast((select top(10000) * from t2 for xml path('row')) as xml) xmlData -- всего 1000 нод
), t_from_xml as (
 select
  x.xCol.value('(r/text())[1]','int') id
   ,x.xCol.value('(gid/text())[1]','int') gid 
from  t_xml b
 cross apply b.xmlData.nodes('/row') as x(xCol)  
)
--select top(1000) * from t2
select @data = (select xmlData from t_xml)

select
 x.xCol.value('(r/text())[1]','int') id
  ,x.xCol.value('(gid/text())[1]','int') gid 
from  @data.nodes('/row') as x(xCol)  
sql xml

Update XML stored in a XML column in SQL Server

Изменяем XML в столбце с типом XML, в нашем случае изменяем атрибут и усложнение уровня с сохраненной XML содержится описание схемы, так что мы должны указать пространство имен, иначе получим сообщение что обновили одну строку, но реального обновления данных не будет.

update [MetrologDev].[dbo].[m_PWStatus]
 set xmlData.modify('replace value of (/rows/row[@id=("2686")]/@selectedCnt)[1] with "0"')
  output inserted.xmlData
   where deleted is null and pfId=12 and statusId=2

update [MetrologDev].[dbo].[m_PWStatus]
 set xmlData.modify('declare namespace ttt="urn:metrolog.mneti.ru"; replace value of (/rows/ttt:row[@id=("2686")]/@selectedCnt)[1] with "0"')
  where deleted is null and pfId=12 and statusId=2


Дружим postfix & courier-imap с Let’s Encrypt with auto update

1. Автоматизация letsencrypt.sh

/usr/local/etc/letsencrypt.sh/domains.txt список MX доменов, через пробел. /usr/local/etc/letsencrypt.sh/config.sh добавляем вызов внешнего скрипта:
HOOK=${BASEDIR}/hook.sh
Даем права на выполнения скрипта:
root# chmod 750 /usr/local/etc/letsencrypt.sh/hook.sh
Правим функцию deploy_cert в файле /usr/local/etc/letsencrypt.sh/hook.sh:
function deploy_cert {
 local DOMAIN="${1}" KEYFILE="${2}" CERTFILE="${3}" FULLCHAINFILE="${4}" CHAINFILE="${5}" TIMESTAMP="${6}"

 TLS_DHPARAMS="/usr/local/etc/letsencrypt.sh/dhparams.pem"
 if test ! -f $TLS_DHPARAMS
 then
 /usr/bin/openssl dhparam -outform PEM 4096 > "$TLS_DHPARAMS"
 fi

 cat "${FULLCHAINFILE}" "${KEYFILE}" "$TLS_DHPARAMS" > "/usr/local/etc/letsencrypt.sh/certs/${DOMAIN}/combined.pem"
}
Обновляемся:
root# /usr/local/bin/letsencrypt.sh -c
2. Настройка courier-imap Правим конфигурационные фалы связанные с ssl:
/usr/local/etc/courier-imap/imapd-ssl
/usr/local/etc/courier-imap/pop3d-ssl
TLS_CERTFILE=/usr/local/etc/letsencrypt.sh/certs/mx/combined.pem
TLS_DHPARAMS=/usr/local/etc/letsencrypt.sh/dhparams.pem
3. Настройка postfix Правим конфигурационный файл:
/usr/local/etc/postfix/main.cf
smtpd_tls_cert_file= /usr/local/etc/letsencrypt.sh/certs/mx/cert.pem
smtpd_tls_key_file= /usr/local/etc/letsencrypt.sh/certs/mx/privkey.pem
4. Перегружаем демоны
root# /usr/local/etc/rc.d/courier-imap-imapd-ssl restart
root# /usr/local/etc/rc.d/courier-imap-pop3d-ssl restart
root# /usr/local/etc/rc.d/postfix restart

FreeBSD 10 & Midnight Commander 4.8. Сохранение экрана при переключении в subshell (Ctrl+o).

Поломали демоны сохранение экрана. Старый рецепт в виде патча не работает.
--- lib/tty/tty-ncurses.c.orig<>2016-05-07 15:42:52 UTC
+++ lib/tty/tty-ncurses.c
@@ -233,7 +233,7 @@ tty_shutdown (void)
 void
 tty_enter_ca_mode (void)
 {
- if (mc_global.tty.xterm_flag && smcup != NULL)
+ if (mc_global.tty.xterm_flag)
 {
 fprintf (stdout, /* ESC_STR ")0" */ ESC_STR "7" ESC_STR "[?47h");
 fflush (stdout);
@@ -245,7 +245,7 @@ tty_enter_ca_mode (void)
 void
 tty_exit_ca_mode (void)
 {
- if (mc_global.tty.xterm_flag && rmcup != NULL)
+ if (mc_global.tty.xterm_flag)
 {
 fprintf (stdout, ESC_STR "[?47l" ESC_STR "8" ESC_STR "[m");
 fflush (stdout);
Вариант 1
Самое простое лечение для админа /etc/termcap:
 3010 # This is the only entry which you should have to customize, since "xterm"
 3011 # is widely used for a variety of incompatible terminal emulations including
 3012 # color_xterm and rxvt.
 3013 xterm|X11 terminal emulator:\
 3014 <------>:te=\E[?1049l:ti=\E[?1049h:\
 3015 <------>:tc=xterm-new:
 3016 #<----->:tc=xterm-r6:
Добавляем строчку 3014 и перестраиваем базу.
root# cap_mkdb -f /usr/share/misc/termcap /etc/termcap
Вариант 2
Меняем в клиенте тип терминала, на примере putty: putty на:
xterm-clear
Для исправление проблем с клавиатурой, в настройках Midnight Commander /usr/local/share/mc/mc.lib добавляем:
...
[terminal:xterm-clear]
copy=xterm