teleren/devto huggingface dataset:
ImageMagic эксперименты #2
Tags: fun, imagemagick
Published: 2013-04-03 15:58:00

---
date: "2013-04-02 21:58:00 +0600"
canonical_url: "https://vk.com/wall38057738_903"
series: "Эксперименты с картинками"
---

Сегодня была чудесная лекция по теории вероятностей. Там было что-то про ЦЕНТРАЛЬНУЮ ПРЕДЕЛЬНУЮ ТЕОРЕМУ, но не это важно. Главное то, что меня накрыло, что я понял!!! Нужно сравнить две картинки между собой.

# Сравнение картинок.

Итак найдем какая из картинок больше другой!
И самое интересное. Я решил расставить все штрихи в кси( ξ). Сравниваем, что лучше аниме или обычное жалкое тридэ.
Берём странную картинку кубиков.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/0jgo1gfzdlv8x9xtex6v.jpeg)

И милую картинку танцующих фигурок оригами.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/2vy54l3snollrp0vjel4.jpeg)

Получаем такое чудо.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/xcnw4h2fhe6lwih37873.jpeg)

Действительно очень красиво вышло. Это не просто какой-то xor или вычитание. А нежное сочетание цветов.

# Аниме vs ТриДэ.

Берём тридэ девушку, которая косплеит индианку.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/5xutv662nvuyqaca782r.jpeg)

И анимешную няшу.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/156acf6d26v0yyxt9cs7.jpeg)

В итоге получаем. Аниме побеждает с огромным отрывом. Ура!!

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/k87r0mfbdhaxxmoeg16m.jpeg)

# Исходники.

https://gist.github.com/senior-sigan/5293378
ImageMagick эксперименты #3
Tags: fun, imagemagick
Published: 2013-04-03 09:54:00

---
date: "2013-04-03 15:54:00 +0600"
canonical_url: "https://vk.com/wall38057738_904"
series: "Эксперименты с картинками"
---

Нет времени объяснять-через 20 минут начинается тренировка. Просто выкладываю новую порцию картинок. Теперь я произвёл случайное перемешивание каналов.

Берем 3 канала RGB. Существует всего {% katex inline %}3! = 6{% endkatex %} возможных перестановок. Каждую перестановку выбираем с равными вероятностями {% katex inline %}\frac{1}{6}{% endkatex %}. То есть равномерное дискретное распределение. Ожидается, что картинка становится почти монохромной. Так и оказалось.

![Перемешивание цветов. Увеличьте фотографию, для усиления эффекта.](https://dev-to-uploads.s3.amazonaws.com/i/mvhog1p7ji8o5405se7z.jpeg)

![Перемешивание цветов. Увеличьте фотографию, для усиления эффекта.](https://dev-to-uploads.s3.amazonaws.com/i/uc1hy1u30ivo9z3i1jhe.jpeg)

# Мультик-преобразование

Следующее преобразование- берем яркость канала, если она больше половины яркости, то делаем её максимальной, иначе минимальной. Я забыл как называется этот эффект, кто знает фотошоп скажите.

Усиление каналов. Получаем вроде всего 8 цветов — red green blue black white cyan magenta yellow.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/mcu487go6pep9wfagsox.jpeg)

Няшке опять не везет. Но когда-нибудь я найду эффект, который сделает картинку фееричной.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/91qkynvbr9uh1jbyh0ow.jpeg)

# Исходники.

https://gist.github.com/senior-sigan/5301188
ImageMagic эксперименты #1
Tags: fun, imagemagick
Published: 2013-04-01 15:48:00

---
date: "2013-04-01 21:48:00 +0600"
canonical_url: "https://vk.com/wall38057738_892"
series: "Эксперименты с картинками"
---

Фуууф, ребята. Опоздал к пятнице сделать, так хоть 1 апреля выложу. На днях мне пришла странная идея-умножать картинки. Ну как матрицы, вы в курсе. Так вот, пришлось сегодня вечерком быстренько поверхностно изучить библиотеку ImageMagick для Си и написать на коленке прогу без очистки памяти и прочего.

# Меняем местами.

Итак. Начинаем с простого - поменять RGB местами, например BRG или еще как. Оказывается это очень клево выглядит(да, такое в фотошопе наверное 10 лет назад есть).
Берём Марселину

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/c1cv9n3srwxx7kr1r6nm.jpg)

Получили синенькую Марселину. Няяяя

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/4gio3ung8j96d4wg9xui.jpg)

Клевая тачка желтого цвета. Надо перекрасить.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/6kcmzkfuyndwy4o997fx.jpg)

Получилось круче, чем было.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/q0426ldnmz5d609cndga.jpg)

# XOR

Далее. По просьбам друзей впилил XOR. Но это совсем не интересно, результат вполне ожидаем.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zhla5l9d0jkblq3xvdbf.jpg)

**XOR**

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/izwpqkylp48v7gxcjq83.jpg)

Получаем после XOR.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/svw576nz25jfn00ors49.jpg)

Очевидно это просто наложение картинок. Ну так немного вещественно.

# Вычитание.

Подумал я после XOR — А что если вычитать цвета? Получилось еще вещественнее.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/wcqhllaxij6piwi1dh5i.jpg)

# Умножение.

И таки да. быстро написав построчечное умножение матриц, умножил картинку саму на себя. Ожидания оправдались. ПОЛУЧИЛОСЬ ШЕДЕВРАЛЬНО.

Берём квадратную картинку, для простоты. И умножаем на саму себя.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/epqlanhlsug9eezb91d0.jpg)

Результат умножения картинки саму на себя. Черт возьми, да это же офигенно. Я давно не видел такой игры цвета и формы. Как изящно верх картинки косплеет под баркод. Ах.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/sfnfj9pu5jpyt60r808s.jpg)

# Исходники.

И те кто хочет обхаять мой код. Сказать чтобы я проч шел с программирования вот исходник: https://gist.github.com/senior-sigan/5285689.
Unable to load DLL 'openal32.dll' The specified module could not be found.
Tags: monogame, openal
Published: 2013-03-25 12:00:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: Unable to load DLL 'openal32.dll' The specified module could not be found.
slug: unable-to-load-dll-openal32-dll-the-specified-module-could-n
date: 2013-03-25 12:00
tags:
 - monogame
 - openal
---
This appears to be a common problem encountered after having just installed MonoGame.

> Unable to load DLL 'openal32.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)

It's really easy to fix though, [download and install OpenAL](http://connect.creativelabs.com/openal/Downloads/oalinst.zip) and everything should work just fine.
Mega Mini Motor Shield (M^3)
Tags: robots, sn755410
Published: 2013-03-24 10:00:00

---
title: Mega Mini Motor Shield (M^3)
published: true
tags: robots, sn755410
published_at: 20130324T10:00Z
series: Custom PCBs
canonical_url: https://ladvien.com/mega-mini-motor-shield
main_image: https://ladvien.com/images/IMG_8629.jpg
---

{% embed https://www.youtube.com/embed/Ny9dN20BRA4 %}

I finally got in my Mega Mini Motor (M3) shield that I designed.  I was surprised, after populating the board: It actually worked.  The board came about after making the [Arduino Mega Mini](http://letsmakerobots.com/node/36273).  I noticed I wouldn't really be reducing the bulk of my [bot](http://letsmakerobots.com/node/35922) because of the amount of wiring it would take to get logic to the Arduino Motor Driver shield I was using.  Therefore, I set out to design a motor driver shield that would plug right into the MegaMini.  I broke out Eagle and some datasheets on an assortment of ICs.

I started out working with the L298D chip, but quickly got frustrated with the way it set on the MegaMini footprint.  Plus, the flyback diodes were pissing me off.  I had remembered reading that the [SN754410](http://www.ti.com/lit/ds/symlink/sn754410.pdf) had internal ESD diodes.  I started playing with the chip layout and got a board design I was pretty happy with.  

I'll attempt a full write up later;I'm pretty mentally fatigued from learning html/css (I know, easy.  But as many know by now, cognitively, I'm as slow as a snail on salt.)
FizzBuzz? More than one line doesn't count!
Tags: fizzbuzz, csharp
Published: 2013-03-21 11:54:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: FizzBuzz? More than one line doesn't count!
slug: fizzbuzz-more-than-one-line-doesn-t-count
date: 2013-03-21 11:54
tags:
 - fizzbuzz
 - csharp
---
Just doing *research* over at [r/cscareerquestions](http://www.reddit.com/r/cscareerquestions/) when I stumbled upon [a thread about FizzBuzz](http://www.reddit.com/r/cscareerquestions/comments/1ap4ev/do_people_really_fail_fizzbuzz_during_interviews/).

I've heard of it, but I've never actually done it. I decided to do it and put myself to the test.

Basically the rule is:

> Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".

Seems simple enough:

    static void EasyFizzBuzz()
    {
        for (int i = 1; i <= 100; i++)
        {
            if (i % 3 == 0 && i % 5 == 0) Debug.WriteLine("FizzBuzz");
            else if (i % 3 == 0) Debug.WriteLine("Fizz");
            else if (i % 5 == 0) Debug.WriteLine("Buzz");
            else Debug.WriteLine(i);
        }
    }

But that's too easy. I'm sure everyone comes up with *that* solution. I'd rather stand out if I ever get asked, and nothing stands out more than a giant line of ternary operators. (Does it count as one line if I've put it onto the next line for appearance sake? Only has one semi-colon!)

    static void OneLineFizzBuzz()
    {
        for (int i = 1; i <= 100; i++) Debug.WriteLine((i % 3 == 0 && i % 5 == 0) ?
            "FizzBuzz" : (i % 3 == 0) ? "Fizz" : (i % 5 == 0) ? "Buzz" : i.ToString());
    }

Maybe I can come up with something more inventitive yet, just how creative can you be with such a simple problem?
Using caller information for verbose logging
Tags: csharp, compilerservices, diagnostics
Published: 2013-03-21 10:35:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: Using caller information for verbose logging
slug: using-caller-information-for-verbose-logging
date: 2013-03-21 10:35
tags:
 - csharp
 - compilerservices
 - diagnostics
---
A cool feature that has been added in Visual Studio 2012 and C# 5.0 is Caller Information attributes. Basically it allows you to see where your method was called from without having to sift through stack traces upon stack traces.

You simply prefix an *optional* parameter with one of the three attributes:

`[CallerMemberName]` provides the method or property name of the caller as a `string`.  
`[CallerFilePath]` provides the full path of the source file that contains the caller as a `string`.  
`[CallerLineNumber]` provides the line number in the source file at which the method is called as an `int`.  

Learn by example. Here I've made a simple logging method, we pass to it a string, and the compiler will fill in the rest. Make sure to including `System.Runtime.CompilerServices` in your `using` statements.

    static void VerboseLog(string value,
        [CallerMemberName] string callerMemberName = "",
        [CallerFilePath] string callerFilePath = "",
        [CallerLineNumber] int callerLineNumber = -1)
    {
        int index = callerFilePath.LastIndexOf(Path.DirectorySeparatorChar);
        string localPath = callerFilePath.Substring(index + 1);
        Debug.WriteLine("{0} {1}:{2} {3}",
            localPath, callerMemberName, callerLineNumber, value);
    }

Let's test it with a simple Console Application. Notice in the above method that I remove the full path to make it more readable. Not necessarily needed but pleasant nonetheless.

    static void Main(string[] args)
    {
        VerboseLog("this is a test");
        DoSomething();
    }

    static void DoSomething()
    {
        for (int i = 0; i < 5; i++)
        {
            VerboseLog(string.Format("something {0}", i));
        }
    }

This outputs:

    Program.cs Main:16 this is a test
    Program.cs DoSomething:24 something 0
    Program.cs DoSomething:24 something 1
    Program.cs DoSomething:24 something 2
    Program.cs DoSomething:24 something 3
    Program.cs DoSomething:24 something 4

So very simple, and yet very, very useful.
Keyboard layout per device on Linux
Tags: linux
Published: 2020-06-15 17:42:20

---
title: Keyboard layout per device on Linux
published: true
date: 2013-01-09 00:00:00 UTC
tags: linux
canonical_url: https://lepovirta.org/posts/2013-01-09-separate-keyboard-layout-on-linux.html
---

I’ve been doing some pair programming where there are two sets of keyboards and mice connected to one computer. I prefer using a different keyboard layout than what my coworkers use. Fortunately, there is way to set a separate layout for each keyboard on Linux.

<!--more-->

For this setup you need `xinput` and `setxkbmap` commands. First, list all your input devices using command `xinput -list`. You should get a list that looks something like this:

```
⎡ Virtual core pointer                          id=2    [master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer                id=4    [slave  pointer  (2)]
⎜   ↳ ETPS/2 Elantech Touchpad                  id=12   [slave  pointer  (2)]
⎜   ↳ Logitech USB Receiver                     id=14   [slave  pointer  (2)]
⎜   ↳ Logitech USB Receiver                     id=15   [slave  pointer  (2)]
⎣ Virtual core keyboard                         id=3    [master keyboard (2)]
    ↳ Virtual core XTEST keyboard               id=5    [slave  keyboard (3)]
    ↳ Power Button                              id=6    [slave  keyboard (3)]
    ↳ Video Bus                                 id=7    [slave  keyboard (3)]
    ↳ Sleep Button                              id=8    [slave  keyboard (3)]
    ↳ USB2.0 0.3M UVC WebCam                    id=9    [slave  keyboard (3)]
    ↳ Asus Laptop extra buttons                 id=10   [slave  keyboard (3)]
    ↳ AT Translated Set 2 keyboard              id=11   [slave  keyboard (3)]
    ↳ ACPI Virtual Keyboard Device              id=13   [slave  keyboard (3)]
```

Next, look for the keyboard that you wish to change the layout for. In my example, I only have one keyboard device listed: AT Translated Set 2 keyboard. The list also tells us the ID the device is assigned to, which is 11 in my case. You need to pass the ID to the command `setxkbmap` using option `-device`. For example, if I wanted to switch my keyboard layout to a finnish layout, the command would be:

```
setxkbmap -device 11 us
```
Happy Birthday - programmer style.
Tags: random, csharp
Published: 2013-03-13 13:49:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: Happy Birthday - programmer style.
slug: happy-birthday-programmer-style
date: 2013-03-13 13:49
tags:
 - random
 - csharp
---
Today I decided to wish my good friend [@Farkie](https://twitter.com/Farkie) happy birthday: programmer style.

Here's to you, ol' bean.

    using System;
    using System.Text;

    public class HappyBirthday
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("{0} {1}{2} {3}",
                GetRandomString(-1045111850),
                GetRandomString(554696058),
                GetRandomString(99640),
                GetRandomString(-2146856402));

            Console.ReadKey();
        }

        public static string GetRandomString(int seed)
        {
            var rnd = new Random(seed);
            var sb = new StringBuilder();
            for (; ; )
            {
                int c = rnd.Next(0, 27);
                if (c == 0) break;
                sb.Append((char)(96 + c));
            }
            return sb.ToString();
        }
    }

And, because you probably won't be bothered to compile it, I've done that for you too.

![Happy Birthday Alan](http://i.imgur.com/wg2sI1q.png)
Keep focus on an input with jQuery
Tags: jquery, javascript
Published: 2013-03-12 22:22:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: Keep focus on an input with jQuery
slug: keep-focus-on-an-input-with-jquery
date: 2013-03-12 22:22
tags: 
 - jquery
 - javascript
---
The most hair-loss-inducing problems usually have the simplest solutions, and such can be said for my latest shortcut to male pattern baldness.

I'm working on my forever project, and part of it requires that an input keep focus *all of the time*. User experience out of the window, this is the way it has to be, but `.blur()` is not cancel-able, nor is `.focusout()`. This means you can't just call `.focus()` in the `.blur()` function. You have to trick it.

Set initial focus first:

    $("#input").focus();

And then set the `re-focus`:

    $("#input").blur(function() {
        setTimeout(function() { $("#input").focus(); }, 0);
    });

Works a treat.
Save nanoseconds with a quicker Enum.HasFlag
Tags: csharp, bitwise, enum, performance
Published: 2013-03-11 15:03:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: Save nanoseconds with a quicker Enum.HasFlag
slug: save-nanoseconds-with-a-quicker-enum-hasflag
date: 2013-03-11 15:03
tags:
 - csharp
 - bitwise
 - enum
 - performance
---
One of the easiest ways to manage security flags is to have an Enum and use bitwise comparisons, however you would expect .NET to make things a bit easier for you, afterall who wants to start littering the code with bitwise expressions?

.NET *does* actually make it easier for you, allowing you to check flags with the `Enum.HasFlag` method, but it has type checking and is generally slow. Like running through water slow.

Let's make a enum to begin with:

    [Flags]
    public enum UserFlag
    {
        User = 1,
        Moderator = 2,
        Administrator = 4,
        Developer = 8
    }

We can now give a hypothetical `User` some flags. We could make them just a `User`, or a `User` and a `Moderator`. We could make them all four. Let's just make them a user with moderation rights, a pretty popular choice.

    UserFlag flags = UserFlag.User | UserFlag.Moderator;

If we were to have a section that only allowed moderators in, we could perform a check with bitwise:

    if ((flags & UserFlag.Moderator) == UserFlag.Moderator)
    {
        ...
    }

Easy, but maybe confusing to a newbie reading the code. An easier way would be to use `HasFlag`:

    if (flags.HasFlag(UserFlag.Moderator))
    {
        ...
    }

Running through water, fully dressed whilst carrying a basket of bread. The reason that `HasFlag` is so slow is because of type checking, we really don't need that in place, we know the type, we just want the check made. An easier way would be to have an extension method:

    public static class UserFlagExtensions
    {
        public static bool HasFlagQuick(this UserFlag haystack, UserFlag needle)
        {
            return (haystack & needle) == needle;
        }
    }

How much quicker is this you may ask? I ran the check ten million times each, and the results are pretty visible. Removing the needless type checking gives us a method that is *15 times quicker*, saving us 32.8 nanoseconds per call.

    Method         Count        Elapsed Total   Elapsed Each
    HasFlag        10,000,000   0.390 s         39.0 nano seconds
    HasFlagQuick   10,000,000   0.062 s          6.2 nano seconds
Quickly and easily upload files with FtpWebRequest
Tags: ftp, ftpwebrequest, csharp
Published: 2013-03-08 13:29:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: Quickly and easily upload files with FtpWebRequest
slug: quickly-and-easily-upload-files-with-ftpwebrequest
date: 2013-03-08 13:29
tags:
 - ftp
 - ftpwebrequest
 - csharp
---
I've just been migrating the *systems* at work to a new host and it's mostly .NET 2.0 stuff, among the lot is some code which uploads images to a server, which for some strange reason has decided to stop working after 3 years and start uploading gobbledygook instead.

I decided to bypass the old clunky FTP class and just use `FtpWebRequest` instead, and thought I'd post here how easy it is (and for future reference! ha).

There are four input variables here: `requestUriString`, `filePath`, `username`, and `password`.

`requestUriString` should be in the format `ftp://10.10.10.10/path/filename.jpg` where the IP is your FTP hostname. The root of this FTP request will be the root of your FTP user account. If you want to upload the image to a directory, include that path in the Uri. Finally, put the desired filename on the end of your request Uri.

`filePath` should be the path to your local file, this is used by File.ReadAllBytes( ... ), and is only for getting the data from the local machine.

`username` and `password` are your FTP login credentials.

The following is an example of how you can quickly and easily upload files using `FtpWebRequest`.

    public static bool UploadExample(string requestUriString, string filePath,
        string username, string password)
    {
        bool success = true;

        try
        {
            var request = (FtpWebRequest)WebRequest.Create(requestUriString);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential(username, password);

            // we read the bytes directly, not with a StreamReader
            var fileContents = File.ReadAllBytes(filePath);
            request.ContentLength = fileContents.Length;

            var requestStream = request.GetRequestStream();
            requestStream.Write(fileContents, 0, fileContents.Length);
            requestStream.Close();

            // we don't need to use the return type
            // unless we want to make checks
            request.GetResponse();
        }
        catch (WebException)
        {
            success = false;
        }

        return success;
    }

Much easier than using/writing a clunky ol' FTP class yourself, no?
Set preferred domain for Google Webmaster Tools
Tags: google, webmastertools
Published: 2013-03-06 10:40:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: Set preferred domain for Google Webmaster Tools
slug: set-preferred-domain-for-google-webmaster-tools
date: 2013-03-06 10:40
tags: 
 - google
 - webmaster-tools
---
Adding this website to Google Webmaster Tools just presented me with a small but annoying problem of not being able to set the preferred domain to contain `www.` rather than just `adamkdean.co.uk`. I received an error message, but no instruction on how to do so:

> Part of the process of setting a preferred domain is to verify that you own http://adamkdean.co.uk/. Please verify http://adamkdean.co.uk/.

I tried to visit the verification file using no `www.` but no dice. I also tried adding the website as the root domain, `adamkdean.co.uk`, but still no luck. 

It turns out you have to add the website *twice*, both with and without the `www` subdomain, so two entries in your webmaster tools, and two verification steps.

Could have thrown me a bone, Google!
Zen Coding for Visual Studio 2012 via Web Essentials 2012
Tags: visualstudio11
Published: 2013-03-03 22:39:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: Zen Coding for Visual Studio 2012 via Web Essentials 2012
slug: zen-coding-for-visual-studio-2012-via-web-essentials-2012
date: 2013-03-03 22:39
tags: 
 - visual-studio-11
---
Something I have come across whilst building this new blog/website is *yet another extension* that among many others, contains a Zen Coding feature.

It's really neat, and you should total save all those five seconds so `click>this.link>now*1`:

[http://visualstudiogallery.msdn.microsoft.com/07d54d12-7133-4e15-becb-6f451ea3bea6](http://visualstudiogallery.msdn.microsoft.com/07d54d12-7133-4e15-becb-6f451ea3bea6)