Thursday, 27 August 2015

Sleep() in JavaScript

"What do I do if I need a Sleep() function in JavaScript?"
I have a JavaScript code that I need to add a sleep() function to. The code I am running is already in a function, eg:
 
function myFunction(time)
{
    alert('time starts now');
    //code to make the program wait before continuing
    alert('time is up')
}
Well, JS does not have a sleep function, it has setTimeout() or setInterval() functions.
The code would be:
 
var timeoutID = window.setTimeout(func, [delay, param1, param2, ...]);
var timeoutID = window.setTimeout(code, [delay]);
The delay is given in miliseconds (see developer.mozilla.org/en-US/docs/Web/API/window.setTimeout or http://www.w3schools.com/js/js_timing.asp).

See example here: http://jsfiddle.net/forgery/02u8uwg1/

This won't halt the execution of your script, but as long as setTimeout() is an asynchronous function, this code
 
console.log("HELLO");
setTimeout(function(){
    console.log("THIS IS");
}, 2000);
console.log("ME");
will print this in the console:
 
HELLO
ME
THIS IS
*(note that ME is printed before THIS IS)
 
function sleep(ms) {
    ms += new Date().getTime();
    while (new Date() < ms) { }
}
now, if you want to sleep for 3 seconds, just use:
 
sleep(3000);
example: http://jsfiddle.net/forgery/8t0neran/

Please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.
If you do sleep more than 10 seconds, browser shows alert: "A script on this page may be busy, or it may have stopped responding. You can stop the script now, open the script in the debugger, or let the script continue."

Friday, 15 May 2015

How to format text in Skype

Today I found out some features of the Skype chat that must have sneaked in the last versions, since nobody has posted about it yet. I was having a hard time when pasting text into the chat which contained character that were easily misinterpreted as emoticons, e. g. (0) as well as using basic text formatting like bold, italic or strikethrough.

A * serounding text (*a*) bolds.
A _ serounding text (_a_) italics.
A ~ serounding text (~a~) strikethroughs.

If you start a message with "@@ " (two ats with a space), every formatting function in your message will be ignored except emoticons.

If you start a message with "!! " (two exclamations with a space), every formatting function in your message will be ignored and font will be switched to monospaced.

So here is my findings:
StyleExample
boldThis is *bold* text
italicAnd this _italic_
strikethroughAnd ~strikethrough~
no text formatting fullAnd full message @@ *no text formatting* but emoticons :D
plain text fullAnd full message !! no text formatting, no emoticons, monospaced
plain text inlineAnd inline {code}no text formatting, no emoticons, monospaced{code}

Monday, 30 March 2015

Replacing a standard WelcomeDlg with a custom one.

We all sometimes looking for solution how to customize the standard dialog in Windows Installer XML (WiX).

Overview

Usually we can easy select any of WiX standard dialog sets, from the WiX UI assembly. It could be one of these sets:
        <UIRef Id="WixUI_Minimal" />
        <UIRef Id="WixUI_Advanced" />
        <UIRef Id="WixUI_FeatureTree" />
        <UIRef Id="WixUI_InstallDir" />
        <UIRef Id="WixUI_Mondo" />
I selected one of them, it was WixUI_InstallDir dialog set. In case when I want add a new dialog I just following the manual on the WiX Toolset site where described how to customize the WixUI Dialog Sets.
It is not very hard.
As result I got a Welcome dialog:

On this dialog I see Major.Minor version of my "Super Product". But I want more...
I want to see which version of this product will be installed exactly. In the same time I don't like to change my Product Name for whole project.
    <Product Id="*"
             Name="$(var.ProductName)"
             Language="1033"
             Version="$(var.Version)"
             Manufacturer="$(var.Manufacturer)"
             UpgradeCode="$(var.UpgradeCode)">
Well, to avoid this I will replace my Welcome dialog with a custom one.

Replacing the first dialog

Replacing any dialog of this set is not problem, so lets do it. First of all I checked the first-time install dialog sequence. To do it I downloaded the source code of WiX. It's an open source project located on SourceForge. Once that's done, I located the file WixUI_InstallDir.wxs in the source folder (currently it is here \src\ext\UIExtension\wixlib\). So it is a sequence:

  • WixUI_WelcomeDlg
  • WixUI_LicenseAgreementDlg
  • WixUI_InstallDirDlg
  • WixUI_VerifyReadyDlg
  • WixUI_DiskCostDlg

Then I copied the original WelcomeDlg code into my project, gave it a new id, then made some modifications. I replaced InstallUISequence from
            <InstallUISequence>
                <Show Dialog="WelcomeDlg" Before="ProgressDlg" Overridable="yes">NOT Installed OR PATCH</Show>
            </InstallUISequence>
to my custom file name (new id)
            <InstallUISequence>
                <Show Dialog="CustomWelcomeDlg" Before="ProgressDlg" >NOT Installed OR PATCH</Show>
            </InstallUISequence>

Then I fixed up Back/Next buttons on neighboring dialogs so they ended up at my dialog instead of the built-in ones:
        <UI>
            <DialogRef Id="CustomWelcomeDlg" />
 
            <Publish Dialog="CustomWelcomeDlg" Control="Next" Event="NewDialog" Value="LicenseAgreementDlg">1</Publish>
            <Publish Dialog="LicenseAgreementDlg" Control="Back" Event="NewDialog" Value="CustomWelcomeDlg">1</Publish>
        </UI>

So, currently I initiated my CustomWelcomeDlg before ProgressDlg, and published new events for buttons on both dialogs Next for CustomWelcomeDlg and Back for LicenceAgreementDlg.

Now when I will run my Setup.msi I should got a new Welcome dialog. And of course I could not avoid some problem: all looked great, but after I pressed "Install" button I got a new window with an old Welcome dialog.

I don't want to describe all my steps to find a solution of this problem, just want to show how it could be fixed. So, I added a new row into InstallUISequence, where turned off event to show original Welcome dialog:
            <InstallUISequence>
                <Show Dialog="WelcomeDlg" Before="ProgressDlg" Overridable="no">0</Show>
                <Show Dialog="CustomWelcomeDlg" Before="ProgressDlg" >NOT Installed OR PATCH</Show>
            </InstallUISequence>
So as a result of my manipulations I got a Welcome dialog with some customization:
Work is done.

Interesting links to documentation about WiX.


Monday, 5 January 2015

Разрушение мифов: Голубь птица мира

Существует много мифов и легенд о птицах, но это все ерунда: многие из них совершенно не соответствуют действительности.

Трогательный белоснежный голубь стал символом мира с легкой руки Пабло Пикассо.

- На самом деле голуби - жестокие птицы. В борьбе с другими самцами за территорию они убивают друг друга. Клювы у них не мощные, но зато есть много энергии и огромное желание занять территорию. У голубя отсутствует чувство стайности и они вполне готовы заклевать своего собственного собрата.

Только человек и голубь, убивает себе подобных, не только в силу необходимости, но и просто так. Волк убивает волка, только из-за кормовой базы или из-за самки. А человек и голубь, еще и из-за удовольствия.

Я у Конрада Лоренца читал - голубь не "считывает" знаков примирения и подчинения - он будет добивать уже сдавшегося противника, будет бить до конца. Т.е. у ВСЕХ остальных есть момент - в случае конфликта физические действия прекращаются если один из противников сдается, признает превосходство другого (у тех же волков конфликт может закончится безконтактно, только демонстрацией), а у голубей нет...

Как-то видел один видеоролик, где на карнизе крыши сидят два голубя и один долбит другого в голову, разбивает голову в кровь да так, что этот второй просто падает без чувств (к сожалению, не могу найти, старый удалили).

Вот два видо, где голуби убивают своих собратьев:


Еще видео

Голуби добивают больного голубя
СМЕРТЕЛЬНАЯ СХВАТКА ГОЛУБЕЙ за моим окном | MORTAL PIGEON FIGHT 
Голуби дерутся
Даже голуби аки волки теперь добивают ослабшего...

Ссылки на другие источники

Голубь — птица кроткая?