<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Automate this.]]></title><description><![CDATA[Automate this.]]></description><link>https://pretender-ghost.azurewebsites.net/</link><generator>Ghost 0.11</generator><lastBuildDate>Tue, 27 Jun 2017 00:19:33 GMT</lastBuildDate><atom:link href="https://pretender-ghost.azurewebsites.net/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[How to clone Windows virtual machine on Azure]]></title><description><![CDATA[In this post we will use a PowerShell script to create an exact copy of existing Azure virtual machine.]]></description><link>https://pretender-ghost.azurewebsites.net/how-to-clone-windows-virtual-machine-on-azure/</link><guid isPermaLink="false">b6a11c34-aed2-4349-a7cf-bbac53162d6e</guid><category><![CDATA[azure]]></category><dc:creator><![CDATA[Oleg Tarasov]]></dc:creator><pubDate>Sat, 01 Apr 2017 14:00:35 GMT</pubDate><content:encoded><![CDATA[<p>In this blog post we will learn how to clone a Windows virtual machine in Azure. It is important to know that there are two choices when it comes to cloning Azure VM:</p>

<ul>
<li>You can generalize the existing VM using <code>sysprep</code> and create a new virtual machine from this image.</li>
<li>You can copy the existing OS disk image to a new storage account and create a new virtual machine with this disk.</li>
</ul>

<p>Today we will cover the second option. Its upside is that you will get an <strong>exact</strong> copy of an existing VM. The downside is that you will need to copy a 130 GB disk image.</p>

<p>First of all, you will need <a href="https://www.microsoft.com/web/handlers/webpi.ashx/getinstaller/WindowsAzurePowershellGet.3f.3f.3fnew.appids">Azure Powershell tools</a> installed. You will also need to download and install <a href="http://aka.ms/downloadazcopy">AzCopy</a> — a tool to copy Azure storage blobs. After you've done all that, just save the following script to your hard drive and run it in PowerShell:</p>

<script src="https://gist.github.com/olegtarasov/f23dec1fa1494223f6b97462e35bf1a8.js"></script>

<p>The script will ask for various bits of information. The most important are an Uri for the source OS disk and storage account key. You can get both by navigating to your existing VM's storage account in Azure portal. First, open up a <code>Keys</code> pane and copy the <code>Key1</code> value. Then open the <code>Overview</code> pane, select <code>Blobs</code>, click the <code>vhds</code> container and choose <code>Properties</code>. Now you can copy the container Uri.</p>

<p>Note that the process of copying the OS disk image can take a very long time as all the VMs are created with the fixed-size disks of 130 GB. After the script finishes, you can go to your Azure portal and play with your new virtual machine.</p>]]></content:encoded></item><item><title><![CDATA[Build CUDA projects with AppVeyor]]></title><description><![CDATA[<p><a href="http://www.appveyor.com">AppVeyor</a> is a great continuous integration tool for Visual Studio projects. You can use it for free to build and deploy your open-source code. AppVeyor has a great integration with GitHub which allows you to create seamless CI scenarios.</p>

<p>Today we will configure AppVeyor to build an open-source project which</p>]]></description><link>https://pretender-ghost.azurewebsites.net/build-cuda-projects-with-appveyor/</link><guid isPermaLink="false">a236f160-23b8-49a9-8664-9447ca44b1a9</guid><category><![CDATA[cuda]]></category><category><![CDATA[gpu]]></category><category><![CDATA[cudnn]]></category><dc:creator><![CDATA[Oleg Tarasov]]></dc:creator><pubDate>Wed, 29 Mar 2017 09:26:49 GMT</pubDate><content:encoded><![CDATA[<p><a href="http://www.appveyor.com">AppVeyor</a> is a great continuous integration tool for Visual Studio projects. You can use it for free to build and deploy your open-source code. AppVeyor has a great integration with GitHub which allows you to create seamless CI scenarios.</p>

<p>Today we will configure AppVeyor to build an open-source project which uses CUDA Toolkit as well as CuDNN framework. As of now we can only use Visual Stdio 2015 build environment, since NVidia doesn't provide out-of-the-box integration with Visual Studio 2017 and <a href="https://www.olegtarasov.me/how-to-build-cuda-toolkit-projects-in-visual-studio-2017">my hack</a> doesn't work on AppVeyor.</p>

<p>Let's make a quick recap of how AppVeyor build environments work. When you start a new build, a new pre-configured virtual machine is deployed to the cloud. This machine has a lot of compilers, runtimes and toolkits installed. You can run some pre-build scripts and install custom tools that you need to build your project. Then an ordinary MSBuild is called to build the solution that you specify in project settings. After the solution is built and tests are run, virtual machine gets destroyed. As you can see, there is no persistent build environment that we can configure and run all our builds at. Instead, we need to setup the environment for each new build.</p>

<p>To build our project we need two things to be present in the environment: CUDA Toolkit and CuDNN framework. The easiest way to install CUDA Toolkit would be to download the whole distribution from NVidia's website and install the components that we need to build the project. The problem is that the whole distribution occupies 1.2G of disk space and it's highly inefficient to download it every time we want to build a project.</p>

<h4 id="customizedcudatoolkitdistribution">Customized CUDA Toolkit distribution</h4>

<p>The best way to circumvent the size problem is to create a custom CUDA Toolkit distribution that contains only the components we need. Here's how we are going to do this:</p>

<ul>
<li>Download current version of CUDA Toolkit from <a href="https://developer.nvidia.com/cuda-downloads">https://developer.nvidia.com/cuda-downloads</a>. Be sure to choose the <code>exe (local)</code> version to get the full distro.</li>
<li>Extract the distribution using 7Zip or another archive tool.</li>
<li>Create a new folder to hold your custom distro and copy the following files and folders from the original distro:</li>
</ul>

<pre><code>compiler\  
cublas\  
cublas_dev\  
CUDADevelopment\  
cudart\  
CUDARuntimes\  
curand\  
curand_dev\  
NVI2\  
cuda.zip  
EULA.txt  
license.txt  
ListDevices.txt  
NVMUP.cfg  
Setup.cfg  
setup.exe  
</code></pre>

<ul>
<li>Create a folder named <code>_vs</code> and copy files from the folder <code>CUDAVisualStudioIntegration\extras\visual_studio_integration\MSBuildExtensions\</code> in the original distribution.</li>
<li>Pack the contents of your custom distribution folder with your favorite archiving tool and upload it to some location from which you will be able to download the file. For my project I uploaded the distro to a Dropbox folder, created a sharing link and modified the link so that "dl" parameter at the end is "1": <code>https://www.dropbox.com/s/[some stuff]/cuda.zip?dl=1</code>. Now you can use this link for direct download.</li>
</ul>

<h4 id="cudnnframework">CuDNN framework</h4>

<p>The second component that you may require is CuDNN framework. Unfortunately, you can't download it with a direct link because NVidia wants you to register a free developer account. Since the download is actually free, you can upload the archive to your private Dropbox account providing you register at NVidia and download the archive yourself. Let's assume you've uploaded CuDNN somewhere and now have a private download link.</p>

<h4 id="configuringappveyorproject">Configuring AppVeyor project</h4>

<p>Now we will write a simple batch file to download and install CUDA Toolkit and CuDNN to AppVeyor environment. Go to your AppVeyor project settings, open the <code>Environment</code> pane and choose <code>cmd</code> in the <code>Install script</code> option. Paste the following script:</p>

<pre><code class="language-batch">echo Downloading CUDA toolkit 8  
appveyor DownloadFile  [link to CUDA Toolkit custom distribution]  
7z x cuda.zip -ocuda  
cd cuda  
echo Installing CUDA toolkit 8  
setup.exe -s compiler_8.0 cublas_8.0 cublas_dev_8.0 cudart_8.0 curand_8.0 curand_dev_8.0 

echo Installing VS integration  
copy _vs\*.* "c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\BuildCustomizations"

cd ..

echo Downloading cuDNN  
appveyor DownloadFile [link to CuDNN distribution]  
7z x cudnn-8.0-windows7-x64-v5.1.zip -ocudnn

copy cudnn\cuda\bin\*.* "%ProgramFiles%\NVIDIA GPU Computing Toolkit\CUDA\v8.0\bin"  
copy cudnn\cuda\lib\x64\*.* "%ProgramFiles%\NVIDIA GPU Computing Toolkit\CUDA\v8.0\lib\x64"  
copy cudnn\cuda\include\*.* "%ProgramFiles%\NVIDIA GPU Computing Toolkit\CUDA\v8.0\include"

set PATH=%ProgramFiles%\NVIDIA GPU Computing Toolkit\CUDA\v8.0\bin;%ProgramFiles%\NVIDIA GPU Computing Toolkit\CUDA\v8.0\libnvvp;%PATH%  
set CUDA_PATH=%ProgramFiles%\NVIDIA GPU Computing Toolkit\CUDA\v8.0  
set CUDA_PATH_V8_0=%ProgramFiles%\NVIDIA GPU Computing Toolkit\CUDA\v8.0

nvcc -V  
</code></pre>

<p>Substitute the URLs for your distributions and click <code>Save</code>. Now our AppVeyor environment is ready to build any project that uses CUDA Toolkit and CuDNN.</p>]]></content:encoded></item><item><title><![CDATA[How to build Cuda toolkit projects in Visual Studio 2017]]></title><description><![CDATA[In this post you will learn how to add CUDA Toolkit supoort to Visual Studio 2017 without official support from NVidia.]]></description><link>https://pretender-ghost.azurewebsites.net/how-to-build-cuda-toolkit-projects-in-visual-studio-2017/</link><guid isPermaLink="false">9febdc70-c4e9-45f8-bdda-3893955660b8</guid><category><![CDATA[cuda]]></category><category><![CDATA[gpu]]></category><dc:creator><![CDATA[Oleg Tarasov]]></dc:creator><pubDate>Sat, 25 Mar 2017 07:21:44 GMT</pubDate><content:encoded><![CDATA[<p>Visual Studio 2017 was released on March 7. Unfortunately, NVidia's CUDA toolkit still doesn't have official Visual Studio 2017 support. The good news are that you can at least build your CUDA projects that were created with Visual Studio 2015. Here's how:</p>

<ol>
<li><p>Install additional components for Visual Studio 2017. Open <code>Individual components</code> tab and select <code>VC++ 2015.3 v140 toolset</code> under <code>Compilers, build tools and runtimes</code>: <br>
<a href="https://pretender-ghost.azurewebsites.net/content/images/2017/03/vs.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2017/03/vs.png" alt="" title=""></a></p></li>
<li><p>Install .NET Framework 3.5 if you didn't have it installed. Open Classical Control Panel, go to <code>Programs and features</code> and press <code>Turn Windows features on or off</code>. Check <code>.NET Framework 3.5</code> and press OK. <br>
<a href="https://pretender-ghost.azurewebsites.net/content/images/2017/03/net35.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2017/03/net35.png" alt="" title=""></a></p></li>
<li><p>Download full CUDA toolkit distribution and extract it somewhere on your disk. The exe file is just a self-extracting archive, so use any advanced archive tool such as WinRAR or 7Zip.</p></li>
<li><p>If you didn't have CUDA toolkit installed, do it now. If you have only Visual Studio 2017 installed, unselect <code>Visual Studio integration</code> checkbox.</p></li>
<li><p>Go to the <code>CUDAVisualStudioIntegration\extras\visual_studio_integration\MSBuildExtensions</code> folder in your extracted distribution, copy all the files and paste them to <code>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\v140\BuildCustomizations</code>: <br>
<a href="https://pretender-ghost.azurewebsites.net/content/images/2017/03/msbuild.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2017/03/msbuild.png" alt="" title=""></a></p></li>
<li><p>In the last step you will need to edit your Cuda projects to recognize NVidia's build tasks from Visual Studio 2017. Open your <code>.vcxproj</code> file in a text editor and find all occurrences of <code>CUDA 8.0.props</code>. Replace the macro at the beginning of the string with <code>$(VCTargetsPath14)</code> so that XML snippet would look as follows:  </p></li>
</ol>

<pre><code class="language-xml">  &lt;ImportGroup Label="ExtensionSettings"&gt;
    &lt;Import Project="$(VCTargetsPath14)\BuildCustomizations\CUDA 8.0.props" /&gt;
  &lt;/ImportGroup&gt;
</code></pre>

<p>Don't forget to edit the custom targets path at the end of the file:  </p>

<pre><code class="language-xml">  &lt;ImportGroup Label="ExtensionTargets"&gt;
    &lt;Import Project="$(VCTargetsPath14)\BuildCustomizations\CUDA 8.0.targets" /&gt;
  &lt;/ImportGroup&gt;
</code></pre>

<p>And that's it! Now you can build your Cuda project from Visual Studio 2017 as well as Visual Studio 2015. This solution allows you only to build stuff and doesn't provide a way to use NVidia's debugging extensions. For those to work we will have to wait for official support from NVidia.</p>]]></content:encoded></item><item><title><![CDATA[Setting up Neon machine learning framework on Ubuntu with GPU support]]></title><description><![CDATA[<p><a href="https://www.nervanasys.com/technology/neon/">Neon</a> is one of the fastest neural network frameworks out there (see the <a href="https://github.com/soumith/convnet-benchmarks">benchmarks</a>). Today we are going to install it on Ubuntu 16.04 LTS with full GPU support.</p>

<p>I'm going to install Neon on a GPU-enabled Azure virtual machine, but the steps are universal. You can use this</p>]]></description><link>https://pretender-ghost.azurewebsites.net/setting-up-neon-machine-learning-framework-on-ubuntu-with-gpu-support/</link><guid isPermaLink="false">357c4da4-1e79-4a83-954a-d9a81026ddb0</guid><category><![CDATA[machine-learning]]></category><category><![CDATA[neural-nets]]></category><category><![CDATA[gpu]]></category><category><![CDATA[cuda]]></category><dc:creator><![CDATA[Oleg Tarasov]]></dc:creator><pubDate>Sat, 17 Dec 2016 16:12:48 GMT</pubDate><content:encoded><![CDATA[<p><a href="https://www.nervanasys.com/technology/neon/">Neon</a> is one of the fastest neural network frameworks out there (see the <a href="https://github.com/soumith/convnet-benchmarks">benchmarks</a>). Today we are going to install it on Ubuntu 16.04 LTS with full GPU support.</p>

<p>I'm going to install Neon on a GPU-enabled Azure virtual machine, but the steps are universal. You can use this manual to install the framework on Ubuntu running on regular PC, or even on “Ubuntu on Windows 10” (just skip the GPU part). I will cover all the required dependencies so you can install Neon on vanilla Ubuntu.</p>

<p>Let's get started.</p>

<h3 id="installnvidiacudalibraries">Install NVidia CUDA libraries</h3>

<p>First we will install CUDA libraries to add GPU support. If you wish to use only CPU, you can safely skip this section.</p>

<p>Download current DEB package:</p>

<pre><code class="language-bash">wget -O cuda-deb https://developer.nvidia.com/compute/cuda/8.0/prod/local_installers/cuda-repo-ubuntu1604-8-0-local_8.0.44-1_amd64-deb  
</code></pre>

<p>You can go to <a href="https://developer.nvidia.com/cuda-downloads">NVidia's website</a> to check for an updated download. Select <code>Linux → x86_64 → Ununtu → [your version] → deb (local)</code>, copy the link and replace one in the command above.</p>

<p>Now install CUDA:</p>

<pre><code class="language-bash">sudo dpkg -i cuda-deb  
sudo apt-get update  
sudo apt-get install cuda  
</code></pre>

<p>After installation is finished, add the path <code>/usr/local/cuda/bin:</code> to your <code>/etc/environment</code>'s PATH variable (just append to the beginning). </p>

<p>Then execute this commands to modify the <code>PATH</code> and <code>LD_LIBRARY_PATH</code> variables in your current session. You need to do this manually only once, these variables will work as expected after you reboot:</p>

<pre><code class="language-bash">export PATH="/usr/local/cuda/bin:"$PATH  
export LD_LIBRARY_PATH="/usr/local/cuda/lib64:/usr/local/cuda/lib:/usr/local/lib:"$LD_LIBRARY_PATH  
</code></pre>

<h4 id="installanaconda">Install Anaconda</h4>

<p>You might already have Python installed, but I strongly suggest to install Anaconda, since it comes with MKL support out of the box. You won't need to bother with OpenBLAS or MLK installation. All this stuff is important if you want to squeeze maximum performance while training you models on the CPU.</p>

<p>First, download Anaconda.</p>

<pre><code class="language-bash">wget https://repo.continuum.io/archive/Anaconda3-4.2.0-Linux-x86_64.sh  
</code></pre>

<p>For an updated version visit <a href="https://www.continuum.io/downloads#linux">https://www.continuum.io/downloads#linux</a> and choose a Python-3.5 installer, then copy the link and substitute into the command above.</p>

<p>Now execute</p>

<pre><code class="language-bash">bash Anaconda3-4.2.0-Linux-x86_64.sh  
</code></pre>

<p>Answer “yes” to all the questions. <mark>This will make Anaconda's Python the default Python installation for you</mark>. If you don't need this, answer “no” when the installer asks you to add Anaconda to PATH (“no” is the default option).</p>

<h3 id="installdevelopmentlibrariesandcompilers">Install development libraries and compilers</h3>

<p>With the next set of commands we will install all the libraries and compilers which are required to install Neon. All commands are rather self-explanatory.</p>

<pre><code class="language-bash">sudo apt-get install git  
sudo apt-get install libavdevice-dev libavformat-dev libavfilter-dev libavcodec-dev libswscale-dev libavutil-dev  
sudo apt-get install libsox-dev  
sudo apt-get install libopencv-dev  
sudo apt-get install libcurl4-gnutls-dev  
sudo apt-get install clang  
sudo apt-get install g++  
</code></pre>

<h3 id="createanacondaenvironmentandinstallneon">Create Anaconda environment and install Neon</h3>

<p>Now we've got everything we need to install and run Neon. Let's create a virtual environment first. Python virtual environments are like sandboxes. You create an environment for something, you install and remove stuff, and and all your other environments remain untouched. So let's create an Anaconda environment called “Neon” and activate it:</p>

<pre><code class="language-bash">conda create -n neon pip  
source activate neon  
</code></pre>

<p>After that we will clone Neon's Git repository and run the installation:</p>

<pre><code class="language-bash">git clone https://github.com/NervanaSystems/neon.git  
cd neon &amp;&amp; make sysinstall  
</code></pre>

<p>There should be no errors and Neon should be up and running. To test the installation, execute</p>

<pre><code class="language-bash">examples/mnist_mlp.py  
</code></pre>

<p>Congratulations! You've just taught a small perceptron to recognize MNIST numbers! :)</p>]]></content:encoded></item><item><title><![CDATA[How to upgrade Windows 10 Enterprise to Anniversary update]]></title><description><![CDATA[<p>This will be a short post. You might've tried to update your copy of Windows 10 Enterprise, but the updater said you should contact your system administrator in order to update. If you download the full Windows 10 1607 image, it doesn't give you an option to save your files</p>]]></description><link>https://pretender-ghost.azurewebsites.net/how-to-update-windows-10-enterprise-to-anniversary-update/</link><guid isPermaLink="false">fe7d934c-2f36-4b18-bac5-a3d233edf815</guid><category><![CDATA[windows]]></category><dc:creator><![CDATA[Oleg Tarasov]]></dc:creator><pubDate>Thu, 18 Aug 2016 08:47:16 GMT</pubDate><content:encoded><![CDATA[<p>This will be a short post. You might've tried to update your copy of Windows 10 Enterprise, but the updater said you should contact your system administrator in order to update. If you download the full Windows 10 1607 image, it doesn't give you an option to save your files and apps. The only option is the full reinstall.</p>

<p>To fix this issue, I had to temporarily change my serial number to this one: <code>NPPR9-FWDCX-D2C8J-H872K-2YT43</code>. You can change in your <code>Settings → Update and Security → Activation</code> app. Never mind that Windows doesn't activate with this serial number — you just need to upgrade.</p>

<p>After I changed my serial number, I just mounted the full 1607 image and ran <code>Setup.exe</code> from image root. The installer checked for updates and then suggested that I install the update saving all my files and apps, just as you would expect.</p>

<p>After installing the update, change your serial number again to one you legally own.</p>]]></content:encoded></item><item><title><![CDATA[Установка и настройка Windows 10]]></title><description><![CDATA[Установить Windows 10 и настроить её для быстрой и стабильной работы очень легко. Хочешь узнать как? Читай здесь :)]]></description><link>https://pretender-ghost.azurewebsites.net/ustanovka-i-nastroika-windows-10/</link><guid isPermaLink="false">f41c61ab-c15a-42e1-b32c-62a9d4ebfdc6</guid><category><![CDATA[windows]]></category><dc:creator><![CDATA[Oleg Tarasov]]></dc:creator><pubDate>Wed, 27 Jul 2016 09:59:41 GMT</pubDate><content:encoded><![CDATA[<p>В этом посте мы рассмотрим пошаговый процесс установки Windows 10, а также, настроим систему так, чтобы она работала быстро и стабильно.</p>

<p>Пост разбит на несколько этапов. Мы начнём с того момента, когда на экране появляется первый экран установщика. Если вы не знаете, как запустить установку Windows с флэшки, то прочитайте этот пост: <a href="http://www.olegtarasov.me/ustanovka-windows-s-fleshki/">Установка Windows с флэшки</a>.</p>

<p>Все настройки будут снабжены скриншотами. Формат простой: сначала идёт скриншот, а потом — объяснение.</p>

<p>Многие настройки, которые я опишу, необязательны. Их нужно применять в том случае, если вы преследуете определённую цель. Такие цели будут выделены в отдельные блоки:</p>

<div class="alert alert-success" role="alert"><b>Режим параноика</b> — позволяет отключить большинство функций слежения в Windows 10. Если вы хотите быть уверены, что система не отправляет в Microsoft данные о вашей активности за компьютером, используйте эти настройки.</div>

<div class="alert alert-info" role="alert"><b>Режим инквизитора</b> — подходит тем, кто хочет избавиться от максимального количества «ненужного» софта, который идёт в комплекте с Windows.</div>

<div class="alert alert-danger" role="alert"><b>Опасный режим</b> — хорошенько подумайте, стоит ли использовать эти настройки. Они могут поставить безопасность вашего компьютера под угрозу. Подходит только тем, кто знает, что делает.</div>

<h3 id="">Начальная установка</h3>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/1.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/1.png" alt="" title=""></a></p>

<p>Итак, приступим. В самом начале Windows предлагает нам выбрать язык системы и раскладку клавиатуры.</p>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/2.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/2.png" alt="" title=""></a></p>

<p>На следующем экране нам предлагают ввести ключ продукта. Если он есть, вводим сразу; если нет — нажимаем <code>У меня нет ключа продукта</code> рядом с кнопкой <code>Далее</code>. Windows можно установить без ключа и использовать с ограниченным функционалом.</p>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/3.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/3.png" alt="" title=""></a></p>

<p>Далее нам нужно выбрать тип установки: <code>Обновление</code> или <code>Выборочная</code>. Если у вас уже установлена Windows, и вы хотите сохранить большую часть программ и настроек, можно выбрать опцию <code>Обновление</code>. Если вы уверены, что забэкапили все данные и хотите установить систему «начисто», жмём <code>Выборочную</code> установку. Далее рассмотрим именно этот вариант.</p>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/4.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/4.png" alt="" title=""></a></p>

<p>Прошли времена, когда при установке Windows нужно было выбирать миллиард опций. Теперь нужно только выбрать диск, на который будет установлена система. Если у вас новый жёсткий диск, то всё пространство на нём, скорее всего, будет не размечено. В этом случае, выделите в списке незанятое пространство и нажмите кнопку <code>Создать</code>. По умолчанию, Windows захочет создать один раздел, который будет занимать весь жёсткий диск. Для большинства случаев это оптимальный сценарий, поэтому просто нажимаем <code>Применить</code>. Здесь есть нюанс: Windows создаст ещё один маленький раздел примерно на 350 Мб. Это нормально — раздел системный и служит для того, чтобы при неполадках можно было легко восстановить работоспособность Windows.</p>

<p>Если у вас на жёстком диске уже есть разделы, и вы хотите установить Windows в тот раздел, где она была раньше, то просто выберите этот раздел и нажмите <code>Форматировать</code>. <mark>Внимение! Эта операция уничтожит все файлы на этом разделе!</mark></p>

<p>После того, как все операции с диском будут закончены, можно нажимать <code>Далее</code>. Windows начнёт копировать свои файлы на жёсткий диск, после чего несколько раз перезагрузится.</p>

<h3 id="">Настройка перед запуском</h3>

<p>После всех перезагрузок наступает этап предварительной настройки системы. </p>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/5.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/5.png" alt="" title=""></a></p>

<p>Как вы уже заметили, кнопка «Использовать стандартные параметры» большая и заманчивая :). Но лучше её не нажимать, а вместо этого нажать незаметную ссылку <code>Настройка параметров</code>. Даже если вы ничего не будете менять, полезно знать, какие настройки Windows хотела всучить вам по умолчанию.</p>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/6.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/6.png" alt="" title=""></a></p>

<div class="alert alert-success" role="alert"><b>Параноик.</b> Именно здесь отключаются многие настройки «слежения».</div>

<p>Как известно, если вы не параноик, это не значит, что за вами не следят ;). Вы можете прочитать объяснение под каждым из этих пунктов, но лично я всегда отключаю все опции на этом экране.</p>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/7-1.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/7-1.png" alt="" title=""></a></p>

<p>На этом экране настраивается автоматическое подключение к Wi-Fi сетям. Это очень спорная фича, которую я также всегда отключаю. Опасность открытых сетей значительно перевешивает необходимость сделать два клика, чтобы подключиться к нужной. Если оставить эти опции включёнными, ваш ноут или планшет может автоматически подключиться к открытой сети, которую выставили злоумышленники с тем, чтобы автоматически проснифать все ваши явки-пароли.</p>

<p>Сведения об ошибках также можно не отправлять. Когда-то Microsoft дизайнил эту фичу как центральный хаб для сбора и диагностики ошибок для экосистемы Windows, но свой потенциал идея так и не реализовала. Как минимум, отключив эту опцию, мы сэкономим трафик.</p>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/8.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/8.png" alt="" title=""></a></p>

<div class="alert alert-danger" role="alert"><b>Галактеко опасносте!</b> Первую опцию лучше оставить включённой. Она поможет защитить компьютер от страшных вирусов.</div>

<p>Две другие опции тоже можно оставить включенными. Третья опция позволяет получать обновления с большей скоростью, нежели при использовании только централизованного сервера обновлений.</p>

<p><mark>Внимание! Никогда не отключайте автоматические обновления! Это ставит под угрозу безопасность компьютера.</mark> Не питайте иллюзий по поводу того, что вы сами знаете, какие обновления нужно ставить, а какие — нет. В итоге, вы либо не будете ставить обновления вообще, чем откроете свой компьютер для 0-day атак, либо будете ставить все, но в ручном режиме.</p>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/9.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/9.png" alt="" title=""></a></p>

<p>Этот экран очень хитрый: он предлагает нам создать учётку в Microsoft, которая будет использоваться для входа в Windows, и пытается дать понять, что другого пути нет :)  На самом деле, решать вам. Ничего страшного в учётке Microsoft нет, а пользы довольно много. Если вы хотите синхронизировать настройки между несколькими компьютерами с Windows 10, учётка подойдёт как нельзя лучше.</p>

<p>Если вы всё же хотите «по старинке» иметь локальный аккаунт, нажмите на неприметную ссылку <code>Пропустить этот шаг</code>.</p>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/10.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/10.png" alt="" title=""></a></p>

<p>Если вы решили не создавать учётку Microsoft, то на этом шаге вам предложат создать обычный аккаунт Windows, как в старые-добрые времена.</p>

<p>После выполнения всех этих настроек нас, наконец пустят на Рабочий стол.</p>

<h3 id="">Настройка в панели управления</h3>

<p>Настало время настроить Windows в панели управления. Как известно, со времён Windows 8 появилась новая модная панель управления. Однако многие опции из неё настроить нельзя, поэтому мы начнём настройку с классической панели.</p>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/12.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/12.png" alt="" title=""></a></p>

<p>Чтобы попасть в классическую панель управления, щёлкните правой кнопкой на кнопке <code>Пуск</code> и выберите <code>Панель управления</code>.</p>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/13.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/13.png" alt="" title=""></a></p>

<p>В меню <code>Просмотр</code> в правом верхнем углу выберите <code>Крупные значки</code>, чтобы не лазить в дебрях разных категорий.</p>

<h5 id="">Как отключить запрос на повышение прав</h5>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/14.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/14.png" alt="" title=""></a></p>

<div class="alert alert-danger" role="alert"><b>Галактеко опасносте!</b> Отключение User Account Control может открыть врата в ад, откуда в ваш компьютер набегут страшные вирусы. Я не шучу.</div>

<p>На этом скриншоте показано, как отключить окошко «подтверждение изменений» для администраторов (учётка по умолчанию — администратор). Каким бы надоедливым не было это окно, оно очень неплохо защищает от глупости и отваги. Если вы точно знаете, что делаете, то перейдите в раздел <code>Администрирование</code>, откройте <code>Локальная политика безопасности</code>, в дереве слева найдите <code>Локальные политики → Параметры безопасности</code>. После этого в списке справа найдите пункт <code>Контроль учётных записей: поведение запроса на повышение прав для администраторов…</code>. Дважды нажмите на него и в открывшемся окне выберите первый пункт: <code>Повышать права без запроса</code>.</p>

<h5 id="">Как отключить автозапуск дисков и флэшек</h5>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/07/15.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/07/15.png" alt="" title=""></a></p>

<div class="alert alert-success" role="alert"><b>Параноик.</b> Если отключить автозапуск, вирусы с флэшек вас не достанут!</div>

<p>В разделе <code>Автозапуск</code> можно отключить автозапуск дисков и флэшек. Необходимость вручную запускать программы с дисков — малая плата за безопасность вашего компьютера.</p>

<h5 id="">Как отключить диагностические сообщения</h5>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/17.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/17.png" alt="" title=""></a></p>

<div class="alert alert-danger" role="alert"><b>Галактеко опасносте!</b> Отключение сообщений о проблемах может скрыть от вас потенциальные векторы атаки на ваш компьютер!</div>

<p>На этом скриншоте мы отключаем все сообщения о безопасности, до которых можем дотянуться. В Панели управления перейдите в раздел <code>Безопасность и обслуживание</code>, и снимите все галки.</p>

<h5 id="smartscreen">Как отключить SmartScreen</h5>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/07/16.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/07/16.png" alt="" title=""></a></p>

<div class="alert alert-danger" role="alert"><b>Галактеко опасносте!</b> Отключение SmartScreen сделает ваш компьютер более уязвимым.</div>

<p>Также в разделе <code>Безопасность и обслуживание</code> можно выключить SmartScreen.</p>

<h5 id="">Как отключить восстановление системы</h5>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/18.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/18.png" alt="" title=""></a></p>

<div class="alert alert-danger" role="alert"><b>Галактеко опасносте!</b> Если вы отключите восстановление системы, то не сможете откатиться к рабочему состоянию, если что-то пойдёт не так.</div>

<p>Если же вы используете фиксированный набор софта, и не экспериментируете с новыми программами и настройками, можно отключить создание точек восстановления. Для этого выбираем пункт <code>Восстановление</code> в Панели управления, и далее действуем по скриншоту. Чтобы зачистить занятое бэкапами место, можно нажать кнопку <code>Удалить</code>.</p>

<h5 id="">Как показать скрытые файлы и расширения</h5>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/20.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/20.png" alt="" title=""></a></p>

<p>Если вы хотите видеть все файлы и папки в Проводнике, а также видеть расширения файлов, следуйте настройкам на этом скриншоте (раздел <code>Параметры Проводника</code> в Панели управления).</p>

<h5 id="">Как скрыть Корзину с рабочего стола</h5>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/21.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/21.png" alt="" title=""></a></p>

<p>Если вы не хотите использовать Корзину, а удалять файлы сразу и навсегда, вы можете выбрать опцию <code>Удалять файлы без использования корзины</code>, щёлкнув правой кнопкой по Корзине и нажав <code>Свойства</code>. В этом случае Корзина теряет свой смысл и её можно скрыть с рабочего стола. Это делается в разделе <code>Персонализация</code> Панели управления, как показано на скриншоте.</p>

<h5 id="">Как отключить удалённого помощника</h5>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/22.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/22.png" alt="" title=""></a></p>

<p>Теперь произведём некоторые настройки в разделе <code>Система</code>. Для начала, отключим совершенно бесполезного Удалённого Помощника.</p>

<h5 id="">Как отключить анимацию при прокручивании списков</h5>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/23.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/23.png" alt="" title=""></a></p>

<p>После этого на закладке <code>Дополнительно</code> можно отключить анимацию при прокручивании списков. Кому как, а мне эта анимация кажется медленной и раздражающей. Без неё работать гораздо приятнее.</p>

<h5 id="">Как отключить автоматическую перезагрузку при ошибке</h5>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/24.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/24.png" alt="" title=""></a></p>

<p>Также на закладке <code>Дополнительно</code> можно отключить автоматическую перезагрузку при появлении «Синего экрана смерти». Это полезно, так как вы будете понимать, что у вас какая-то серьёзная проблема, а не просто электричество скакнуло.</p>

<h5 id="">Как отключить отправку отчёта об ошибках</h5>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/25.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/25.png" alt="" title=""></a></p>

<p>Чтобы окончательно отключить отправку отчётов об ошибках, перейдём в раздел <code>Устранение неполадок → Настройка</code>. Выбираем опции как на скриншоте.</p>

<h5 id="">Как отключить домашнюю группу</h5>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/26.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/26.png" alt="" title=""></a></p>

<p>Далее мы можем отключить «Домашнюю группу», которой мало кто пользуется, и которую сам Microsoft потихоньку начинает выводить из эксплуатации. Перейдём в <code>Центр управления сетями</code> и в разделе <code>Дополнительные параметры</code> выставим переключали как на скриншоте. Первый переключатель разрешает классический шаринг файлов вместо домашних групп, а второй — отключает собственно домашнюю группу. Если вы не хотите шарить файлы, то первый переключатель можно оставить как есть.</p>

<h3 id="">Настройка в новой панели управления</h3>

<p>Теперь перейдём к настройке в новой панели управления. Чтобы туда попасть, нужно просто нажать <code>Настройки</code> в меню <code>Пуск</code>.</p>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/27.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/27.png" alt="" title=""></a></p>

<p>Для начала, отключим советы по работе с Windows в разделе <code>Система</code>.</p>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/28.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/28.png" alt="" title=""></a></p>

<p>Затем в разделе <code>Питание и спящий режим</code> выключим режим сна при питании от сети. Это полезно для тех, кто всегда держит компьютер включённым.</p>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2017/02/39.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2017/02/39.png" alt="" title=""></a></p>

<p>Также можно сделать так, чтобы жёсткие диски не отключались через 20 минут простоя. Это очень раздражает, когда традиционный жёсткий диск используется как дополнительный и доступ к нему происходит редко. В этом случае каждый раз придётся ждать, пока жёсткий диск раскрутится и придёт в состояние готовности. Чтобы запретить отключение жёстких дисков, нужно нажать ссылку <code>Дополнительные параметры питания</code>, в классической панели управления нажать ссылку <code>Настройка схемы электропитания</code> напротив активной схемы. Далее нужно нажать ссылку <code>Изменить дополнительные параметры питания</code> и выставить значение <code>0</code> для настройки <code>Жёсткий диск → Отключать жёсткий диск через</code>.</p>

<h5 id="windows10">Как удалить ненужные компоненты Windows 10</h5>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/31.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/31.png" alt="" title=""></a>
<a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/32.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/32.png" alt="" title=""></a></p>

<div class="alert alert-info" role="alert"><b>Burn them all!</b> Если вы не хотите оставлять врагу ни мегабайта, можете удалить эти компоненты.</div>

<p>В разделе <code>Приложения и возможности</code> можно удалить некоторые ненужные компоненты, нажав на ссылку <code>Управление дополнительными компонентами</code>.</p>

<h5 id="">Как отключить рекомендации в меню Пуск</h5>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/29.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/29.png" alt="" title=""></a></p>

<p>Чтобы Windows не рекламировала приложения в вашем собственном меню Пуск, перейдите в раздел <code>Персонализация → Пуск</code> и снимите галку, как показано на скриншоте.</p>

<h5 id="windowsdefenderwindows">Как отключить Windows Defender (Защитник Windows)</h5>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/19.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/19.png" alt="" title=""></a></p>

<div class="alert alert-danger" role="alert"><b>Галактеко опасносте!</b> Если у вас нет другого антивируса, не отключайте Защитник Windows!</div>

<p>В разделе <code>Обновление и безопасность → Защитник Windows</code> можно отключить антивирус, который поставляется в комплекте с Windows.</p>

<h5 id="windows10">Как удалить предустановленные приложения Windows 10</h5>

<div class="alert alert-info" role="alert"><b>Burn them all!</b> Если вы не пользуетесь приложениями, которые идут в составе Windows 10, их можно удалить. Для этого нам понадобится запустить PowerShell.</div>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/33.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/33.png" alt="" title=""></a></p>

<p>Откройте меню <code>Пуск</code> и начните вводить <code>power</code> с клавиатуры. Когда в меню появится пункт <code>Windows PowerShell</code>, щёлкните по нему правой кнопкой и выберите <code>Запустить от имени администратора</code>.</p>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/34.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/34.png" alt="" title=""></a></p>

<p>В открывшейся командной строке введите команду <code>Get-AppxPackage | Foreach {Write-Host $_.Name}</code>. Эта команда выведет все приложения из Магазина, установленные в Windows.</p>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2016/05/35.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/05/35.png" alt="" title=""></a></p>

<p>Чтобы удалить приложение, введите команду <code>Get-AppxPackage [имя приложения] | Remove-AppxPackage</code>. Вы также можете использовать шаблоны. Например, команда <code>Get-AppxPackage *Bing* | Remove-AppxPackage</code> удалит все приложения, в имени которых содержится “Bing”.</p>

<p><mark>Внимание! Некоторые приложения нельзя удалить даже этим способом.</mark> Придётся смириться.</p>

<p>Следующий набор команд удалит практически все приложения, которые идут в комплекте с Windows 10:</p>

<script src="https://gist.github.com/olegtarasov/06f21cf7f52b399fe0d34a048dc6a9f6.js"></script>

<h5 id="">Как отключить режим гибернации</h5>

<p>Режим гибернации позволяет сохранять полное состояние оперативной памяти на жёсткий диск, и затем выключать компьютер. Следующее включение компьютера должно происходить гораздо быстрее, т. к. состояние оперативной памяти восстанавливается напрямую с диска, пропуская долгие этапы загрузки. С помощью этой функции также можно сохранить открытые программы и после включения компьютера продолжить работу с того места, на котором её закончили. Однако в век SSD-дисков, которые сокращают время «холодного» запуска Windows до нескольких секунд, эта функция уже не так важна. Тем не менее, система резервирует на жёстком диске место для содержимого оперативной памяти. Файл <code>hyberfil.sys</code> занимает место, пропорциональное объёму установленной оперативной памяти. </p>

<p><a href="https://pretender-ghost.azurewebsites.net/content/images/2017/02/40.png"><img src="https://pretender-ghost.azurewebsites.net/content/images/2017/02/40.png" alt="" title=""></a></p>

<p>Если вы не пользуетесь режимом гибернации, то можете избавиться от этого файла. Для этого запустите командную строку от имени администратора и выполните команду</p>

<pre><code class="language-bat">powercfg -h off  
</code></pre>]]></content:encoded></item><item><title><![CDATA[Установка Windows с флешки]]></title><description><![CDATA[В этом посте мы научимся ставить любую версию Windows с USB-флешки за 4 простых шага.]]></description><link>https://pretender-ghost.azurewebsites.net/ustanovka-windows-s-fleshki/</link><guid isPermaLink="false">e80436ac-76af-4e91-ad69-d30aeb2bdc78</guid><category><![CDATA[windows]]></category><dc:creator><![CDATA[Oleg Tarasov]]></dc:creator><pubDate>Thu, 14 Jul 2016 08:07:27 GMT</pubDate><content:encoded><![CDATA[<p>Установить Windows с флэшки очень просто. Нам понадобятся:</p>

<ul>
<li>Чистая флэшка размером не менее 8 Гб</li>
<li>Компьютер с Windows на борту (если вы юзаете линукс, вам не нужна эта инструкция ;) )</li>
<li>Установочный образ Windows в виде файла ISO, который вы честно <del>скачали с торрентов</del> принесли из магазина на дискетках.</li>
</ul>

<p>Мы начнём с того, что скачаем пакет Easy2Boot по этой <a href="http://files.easy2boot.com/200001811-3907f3a035/Easy2Boot%20v1.81A.7z">ссылке</a>. Если хотите скачать самую последнюю версию, то можете зайти на сайт <a href="http://www.easy2boot.com/download">http://www.easy2boot.com/download</a>. Нас интересует пункт 1b: "Download E2B".</p>

<p>Теперь распакуйте скачанный архив в любую папку, вставьте флэшку и запустите файл <code>MAKE_E2B_USB_DRIVE (run as admin).cmd</code> от имени администратора:</p>

<p><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/07/1.png" alt=""></p>

<p>В появившемся окне отобразятся все флэшки, которые можно сделать загрузочными. Вводим номер нашей флэшки:</p>

<p><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/07/2.png" alt=""></p>

<p>Соглашаемся с форматированием диска (вводим <code>Y</code>). <mark>Все существующие на флэшке файлы будут удалены!</mark></p>

<p>Далее выбираем файловую систему NTFS, просто нажав Enter. Ещё раз соглашаемся с форматированием. Дожидаемся, когда закончится форматирование и копирование файлов на флэшку.</p>

<p><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/07/3.png" alt=""></p>

<p>Далее программа спросит, какой язык мы хотим использовать. Можно просто нажать <code>Enter</code> для английского или ввести <code>15</code> для русского языка. Далее ещё четыре раза  нажимаем <code>Enter</code> для выбора английской клавиатуры, чтобы не показывать расширения файлов и анимированный логотип в меню загрузчика. После всех проделанных операций нас порадуют зелёным экраном:</p>

<p><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/07/4.png" alt=""></p>

<p>Теперь нам нужно скопировать образ ISO, с которого мы будем устанавливать Windows. Для этого мы открываем флэшку в Проводнике и переходим в папку <code>[диск]\_ISO\WINDOWS\[версия Windows]</code>. Копируем в эту папку наш образ:</p>

<p><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/07/5.png" alt=""></p>

<p>После этого можно перезагрузить компьютер и загрузиться с флэшки (зажать F8, F10, F12 — у всех по-разному). Перед вами появится меню загрузчика. В нём нужно выбрать пункт <code>3 WINDOWS INSTALL menu</code>, затем <code>INSTALL Windows [версия]</code>, и после этого выбрать образ, который мы сохранили на флэшку:</p>

<p><img src="https://pretender-ghost.azurewebsites.net/content/images/2016/07/6.png" alt=""></p>

<p>В ответ на вопрос о режиме запуска установки нужно выбрать пункт <code>No serial number</code> — у нас же есть абсолютно легальный серийник ;)</p>

<p>После всех этих манипуляций загружается стандартный установщик Windows как если бы мы устанавливали её с диска.</p>

<p>И ещё один <mark>важный момент</mark>. Иногда большие файлы образов могут фрагментироваться, и это не нравится загрузчику. Если вы получаете ошибки, в которых есть фраза <code>not contiguous</code>, вам нужно загрузиться в Windows и выполнить от имени администратора файл <code>MAKE_THIS_DRIVE_CONTIGUOUS.cmd</code>, который находится в корне флэшки.</p>]]></content:encoded></item><item><title><![CDATA[Thread-safe random number generator with unit testing support in C#]]></title><description><![CDATA[In this post I present a complete solution to safely generate high-quality random numbers in C# with an ability to mock the generator in unit tests.]]></description><link>https://pretender-ghost.azurewebsites.net/thread-safe-random-number-generator-with-unit-testing-support-in-c/</link><guid isPermaLink="false">c9e438b8-7fbc-4278-bfdb-a34fce6e6487</guid><category><![CDATA[c#]]></category><category><![CDATA[.net]]></category><dc:creator><![CDATA[Oleg Tarasov]]></dc:creator><pubDate>Wed, 13 Jul 2016 08:55:26 GMT</pubDate><content:encoded><![CDATA[<p>In a current project I have to deal with lots of multithreaded random number generation. The first challenge that I came upon was that standard .NET <code>Random</code> implementation is not thread-safe. When you call its methods from different threads, <code>Random</code>'s inner state becomes mangled at some point and then all you get are zeroes. Uniform probability distribution? Yes. Random? Not so much :)</p>

<p>The obvious choice for me was to wrap <code>Random</code> instances in a <code>ThreadLocal</code> container and get and instance for each thread. Container had to be accessed with a static property on a static class. This solution worked flawlessly for some time, but then, as the project grew, it became obvious that some unit tests are in order.</p>

<p>As my friend said recently, there are two instruments of torture in programmers' hell: random numbers and parallelism. In my project I hit a jackpot. So I decided that in order to write simple and manageable tests, I need to exclude the randomness component from random number generation. And so I created a wrapper interface which I can easily mock in my tests.</p>

<p>First of all, I defined a non thread-safe interface and RNG implementation based on standard .NET implementation:</p>

<script src="https://gist.github.com/olegtarasov/eb74526dbcffed9de8d09156c0c9a3c1.js"></script>

<p>Note that in this implementation I use <code>RNGCryptoServiceProvider</code> to generate a random seed. This gives us a very good quality starting point without the performance impact of calling <code>RNGCryptoServiceProvider</code> all the time.</p>

<p>Now we must ensure actual thread safety. Let's create a simple wrapper to get us a different instance of <code>IRandom</code> for each thread:</p>

<script src="https://gist.github.com/olegtarasov/2734bfd539cddfcd77b3d4b811d27e61.js"></script>

<p>Note the <code>TestGenerator</code> property. This is how we are going to inject a fake generator inside our unit tests.</p>

<p>Now let's create our fake RNG:</p>

<script src="https://gist.github.com/olegtarasov/b1f84d3911f57c191a6af44bb342cd13.js"></script>

<p>This class allows us to define a sequence of numbers that will appear through a series of calls to any method of <code>IRandom</code>. This gives us an ability to easily design predictable and simple unit tests.</p>

<p>Note that this class is disposable. We always need to use it in a <code>using</code> block so that our test random sequence doesn't affect other tests that maybe don't want to override the RNG.</p>

<p>So let's use our fake generator:</p>

<script src="https://gist.github.com/olegtarasov/5f4260be74ddd0c02cc7145da5585e03.js"></script>

<p>This test checks that a genetic algorithm selector can in fact select the right individual from a population (I know, right? :) ). As you can see, we don't explicitly use RNG in our test. Instead, it is used implicitly in our selector:</p>

<script src="https://gist.github.com/olegtarasov/a25bfaf120e02964d5be44d6a55cffb5.js"></script>

<p>As you can see, this selector chooses a random item from the list using a uniform probability distribution. But when we override the RNG in our test, it always chooses an item number 2.</p>

<p>So this is quite simple but powerful technique which can completely remove such an undesirable factor as randomness in unit tests.</p>]]></content:encoded></item></channel></rss>