02 3 / 2014

mallius:

16d7h50m

mallius:

16d7h50m

(via mallius)

Permalink 7,684 notes

15 2 / 2014

About Flappy Bike Saga

Click here to play Flappy Bike Saga

Flappy Bike Saga is a HTML5 (canvas) game I made, took me maybe a day or so. You can play it by clicking on the image above, it should work fine in Firefox, Chrome or IE9/10. I suck at drawing stuff so it is simple vector graphics, also features excellent sound generated with Bfxr

The goal of the game is to bike as far as possible and avoid hitting rocks and trees, getting the highest score possible. The original idea comes from the BMX part of California Games back from when I played it on the Atari 2600. The name is inspired by Flappy Bird and the current King.com spectacle

Stop reading, go play some Flappy Bike Saga :)

26 1 / 2014

Arachnid: Windows GUI development using .NET, Chromium, CefSharp and Nancy

I have done quite a bit of GUI development using .NET and Winforms and lately I’ve been building an application using WPF instead, but it doesn’t fit quite right with me.

What bugs me the most is how bloated and abstract everything is, it is as if you took something already over-engineered and handed it to a engineer who loved over-engineering and refactor stuff into oblivion. This, of course, is my own opinion and I’m sure you can create awesome applications using WPF as easily as you can write awful applications using Clojure or Elixir.

So I started thinking “wouldn’t it be possible to do front end stuff using regular html/javascript and css but still keep the feeling of a native app?”

So I decided to try it out by writing a simple text editor with a front end using html, css and javascript in an embedded browser that communicates with an embedded REST server.

Finding a suitable embedded browser

I started looking around after some good embedded browser solution for .NET and found this one called CefSharp that is a nice Winforms/WPF wrapper for the Chromium Embedded Framework. I did put some effort in finding a suitable wrapper for Mono but didn’t find anything apparently suitable.

Okay, so using CefSharp I could now create a simple Winforms application with a window and a single docked browser window in witch to display my application. CefSharp is available as a convenient nuget package so getting that into your project would be a breeze if it would not be dependent on non-managed binaries from the Chromium Embedded Framework so you will need to download the binary release for windows, unzip, include and mark them as “copy always” in your solution including the “locales” folder.

Nancy as a self hosted server

I’ve done a lot of stuff using Nancy and it is easy as pie to get a self hosted server up and running using Nancy in a .NET application. All you need to do is grab it from nuget using the package Nancy.Hosting.Self and look up the documentation on how to kickstart it.

Next is choosing what port to run the server at, it would be nice to just let the OS choose a random free port to use but I soon realized this would get kind of awkward because of Namespace Reservations so I just picked port 8686 for now.

Of course if you want to do so anyway you can grab a free port using something like


    static int GetFreeTcpPort()
    {
        // passing port 0 lets the OS choose a random free port
        var listener = new TcpListener(IPAddress.Loopback, 0);
        listener.Start();
        var port = ((IPEndPoint)listener.LocalEndpoint).Port;
        listener.Stop();
        return port;
    }

The server is created/started in the Winforms initialization method and a reference to the current form is passed into the server so it can be registered and later used for I/O and dialog stuff.

Front End (GUI stuff)

For the GUI parts of this application I’m using JQuery for general stuff, Twitter Bootstrap for basic layout/components/css and Ace that is a javascript based text editor with syntax highlighting and stuff.

The GUI is pretty basic, a dropdown menu for opening, saving files and exiting the application. All I/O call are AJAX requests to the embedded REST server.

As this application launches an embedded Nancy web server the html/javascript and css stuff can be developed with the help of a regular browser if you want to use firebug or whatever debugger.

Wrapping it up

One thing to keep in mind doing stuff like this is threading, REST requests coming in are all on a different thread from the Winforms/Window instance and can cause troubles when working dialogs and such. This is why we are passing the reference of our Winforms instance when creating the Nancy self hosted server. Using this we can invoke stuff on the Winforms (ui) thread.


    public class Default : NancyModule
    {
        public Default(Form applicationForm)
        {
            Get["/openfile"] = _ =>
            {
                var dialog = new OpenFileDialog();
                var result = applicationForm.Invoke(new Func((d) => d.ShowDialog()), dialog);
                if ((DialogResult)result == DialogResult.OK)
                {
                    var response = (
                    File.Exists(dialog.FileName)
                    ? new StreamResponse(File.OpenRead(dialog.FileName))
                    : Response.AsText(string.Empty)
                    )
                    .WithHeader("X-File-Path", dialog.FileName);
                    return response;
                }
                return Negotiate.WithStatusCode(HttpStatusCode.ClientClosedRequest).WithReasonPhrase("");
            };
        }
    }

.

In the all in all it is fully possible to write a complete native application using these components. All this is missing is a reliable webkit/chromium/gecko wrapper for Mono/GTK# and this would get instant cross platform.

Here is a quick and dirty video of the app running both native and in a browser.

..

Source Code

You can find and download the source for Arachnid demo here

Make sure you set x86 as the target platform when building.

13 1 / 2014

C# Fluently Pattern

Once again I was setting up log4net in a application client I’m writing using in code configuration and thought I would spice it up a bit using a fluent pattern.

Instead of writing some kind of FluentLog4Net library I went for a more generic class wrapper using the pattern:

  • with<some instance>
  • do<some an arbitrary actions with the instance>
  • done<return instance>

At the moment the implementation of this fluent pattern is


    public class Fluently
    {
        public static Fluently<T> With<T>(T obj)
        {
            return Fluently<T>.With(obj);
        }

        public static Fluently With(Func f)
        {
            return Fluently<T>.With(f());
        }
    }

    public class Fluently<T> : Fluently
    {
        private readonly T _obj;
        private Fluently(T obj)
        {
            _obj = obj;
        }

        public static new Fluently<T2> With<T2>(T2 obj)
        {
            return new Fluently<T2>(obj);
        }

        public Fluently<T2> Cast<T2>() where T2 : class
        {
            return new Fluently<T2>(_obj as T2);
        }

        public Fluently<T> Do(Action<T> action)
        {
            action(_obj);
            return this;
        }

        public T Done()
        {
            return _obj;
        }
    }

.

Here is an example of configuring log4net using the Fluently implementation using a rolling file and memory appender.


    public void ApplicationStartup()
    {
        Fluently.With(LogManager.GetRepository() as Hierarchy)
        .Do(repo => repo.Root.AddAppender(
            Fluently.With(new RollingFileAppender())
            .Do(appender => appender.File = "logfile.txt")
            .Do(appender => appender.AppendToFile = true)
            .Do(appender => appender.StaticLogFileName = true)
            .Do(appender => appender.MaxSizeRollBackups = 10)
            .Do(appender => appender.MaximumFileSize = "10MB")
            .Do(appender => appender.RollingStyle = RollingFileAppender.RollingMode.Size)
            .Do(appender => appender.Layout = 
                Fluently.With(new PatternLayout())
                .Do(layout => layout.ConversionPattern = "%date [%thread] %-5level %logger - %message%newline")
                .Do(layout => layout.ActivateOptions())
                .Done())
            .Do(appender => appender.ActivateOptions())
            .Done()))
        .Do(repo => repo.Root.AddAppender(
            Fluently.With(new MemoryAppender())
            .Do(memory => memory.ActivateOptions())
            .Done()))
        .Do(repo => repo.Root.Level = Level.Info)
        .Do(repo => repo.Configured = true)
        .Done();
    }

.

And then you can just go ahead and log stuff as usual using log4net in your application.


    public class Foo
    {
        private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public void Bar() 
        {
            log.Info("Foo Bar");
        }
    }

17 11 / 2013

Games are not only fun and play

I was born in 1980, my first video game system was an Atari 2600 and on that system I played some great games. Games like Kangaroo, Vanguard, River Raid, Mario Bros and Defender. From that point on I was hooked and have both owned and played games on the majority of systems released up until now. Systems like MasterSystem, GameGear, Megadrive, Dreamcast, CD32, Jaguar, NES, Gameboy, SNES, Gamecube, GBA, DS, Wii, WiiU, Playstation, PS2, PS3. PS4, (Ouya..) and so on.

The games I played where and is an important part of my life and who I am. You can learn a lot from games but the memories of games also stick with you for the rest of your life and are bound to pop up whilst you least expect it. It can give you a feeling of recognition, approval or fear and disgust. Games are part of what help shape your thoughts and the actions you later take in life, much in the way literature or music does the same.

My opinion is that games are part of what help shape our minds and defines us as much as books, music or movies. They are equally important.

Everyone growing up playing games make them part of their thought process and occasional points of reference throughout their lives.

This is why it is so important that the makers of games realize this and also for those who fight for or against certain content in games.

In conclusion, games are made to be fun but they also impact a lot of lives and the choices we and future generations make.

Games are powerful and they empower us.

08 11 / 2013

A tale of when shit hit the fan

This is a tale from many many years ago, early in my career as a software engineer.

Many years ago I was part of a team of software engineers, project leaders and art directors. Our country was at the verge of a historic shift in information and communication technology.

In order to prepare for the onslaught of the looming demand of virtually every household in the country we where set to the task to construct a product and order management system accompanied by a website and integrated online-shop.

Using all of the latest and stable technologies available in .NET and with a SOA architecture we created something powerful, versatile and in our opinion rock solid. Our system was integrated with several business systems, payment providers, logistic providers and data warehouses. It featured a UX focused web interface for customer support making it super easy to find customers, orders and check the state and status of absolutely everything.

I also wrote a customized retailer application which was distributed to the thousands of retailer locations around the country. This with a authentication and authorization system allowing us to tailor fit who sold what where and for what.

After a few months after endless functionality and penetration testing, everything was put into production and we were pretty confident in this complex system and the punishment it could take.

Only that after a few days the system came crashing down, hard! And we had no idea of why. I was woken up by a phone call in the morning telling me that the shit was failing and fast! When logging on to the webservers I immediately noticed that the CPU was running at 100% and a quick glance at the access logs told me that this was some form of a DDOS attack.

Something else I noticed was that the IP ranges of the source addresses was insanely wide, it was like every single citizen of Sweden (and some outside) where part of this. All of these requests was a GET for a fairly large dynamic resource that wasn’t cached, it was also not part of the website and so it would not be requested by normal website visitors.

Project managers and upper management were screaming over the phones in endless discussions of where blame should be placed and who could fix this. heads where going to roll. I kept out of this as much as I could, trying to figure out what exactly was happening. What was causing all of this? Could it be some kind of distributed attack using a flash banner or something? turns out that it was!

The company we built this system for was running an ad-campaign at the top of one of Swedens most read online newspapers. The ad was a flash-banner that loaded data from our website at every page load and reload on the newspaper site. This of course resulted in millions and millions of requests as every visitor to the newspaper website resulted in a request to our website and a database query.

We temporarily removed the dynamic resource and a few phone calls later the banner was removed and later replaced with a better behaving version. The downtime was around 10 hours.

The system was running fine after this and as far as I know is still in use today.

What did I learn from all of this?

  1. Flash banners are evil
  2. Advertising agencies use shit coders
  3. Our system was not scaled to meet the demand of a million simultaneous users
  4. Never hand out your private phone numbers to project managers
  5. One cool head is better than 10 hot ones

26 10 / 2013

Getting started with Go

Note: go and golang are different names for the same thing.

This describes how to set up a golang project in Windows but you can use this setup on any platform you like that golang supports, just follow this guide and install the requirements in the “What do I need to get started?” section for your operating system and this will work just fine.

You can quickly get your own golang project up and running using the skeleton example.

What is go?

Go is a compiled language created by some guys over at Google in 2007. It has since then matured and gotten somewhat of a following (me included).

The syntax has the feel and looks of a dynamic language but Go is statically-typed. It is compiled into a statically linked native binary with a built in garbage collector. you do not need to worry about allocating and freeing up memory.

It has a built in package management system and the compile times are quite fast. Go is great for multi-threaded applications as it has strong mechanisms for thread safety and concurrency.

Not to mention the excellent work they are doing maintaining the online package documentation http://golang.org/pkg/

In my opinion Go is great for tooling and that is what I use it for.

What do I need to get started?

For my setup I use GNU Make as it is cross platform and your projects will build on Linux/OSX/Windows without modifications and it actually describes all the manual steps for those who are interested. You will also need to install GIT as this example uses a third party package hosted on Github. See https://code.google.com/p/go-wiki/wiki/GoGetTools for the list of all supported version control tools

  1. Go http://golang.org/doc/install
  2. GNU Make http://gnuwin32.sourceforge.net/packages/make.htm
  3. GIT http://git-scm.com/

1) First of all you need to install Go, obviously since this is the whole point of this. Also make sure to add the Go bin/ directory to your system PATH variable. On my system Go installs to C:\Go\bin

2) Secondly you will need to install GNU Make by following the above link. After this is done make sure to add the GNU bin directory to your system PATH. On my computer GNU installs to C:\Program Files (x86)\GnuWin32\bin

3) Lastly, install GIT by following the above link. Like the rest make sure to add the GIT bin/ directory to your system PATH variable. On my system GIT install to C:\Program Files (x86)\Git\bin

Make sure everything is set up correctly by starting a command prompt and verify that it can find the following commands: go, make and git

Setting up your project

You can get this basic skeleton project on github : https://github.com/creamdog/golang.skeleton

The project directory will look like this.


PS D:\Projects\skeleton> ls

    Directory: D:\Projects\skeleton

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----        2013-10-26     08:14            src
-a---        2013-10-25     15:10         70 main.go
-a---        2013-10-25     15:10        164 makefile

PS D:\Projects\skeleton>

.

The src/ directory is where you will put your own code that you do not want in main.go. it is also where third party sources ends up and where go looks for additional source files/packages for this project.

The main.go is the application entry point, it contains the main function and is where you set everything up. here is an example:


    package main

    import  (
                "log"
                "github.com/nu7hatch/gouuid"
            )

    func main() {
        uuid, _ := uuid.NewV4()
        log.Printf(uuid.String())
    }


.

As you can see it imports the standard Go log package and the third party package github.com/nu7hatch/gouuid

How do we get that package you say? This is where the makefile comes in.

The makefile is where you set up all your build targets and where you tell Go what to do. here is the example project makefile:



    export GOPATH=$(CURDIR)

    default: main.go
        go build -v -o skeleton.exe

    run: default
        skeleton.exe

    dep-install:
        go get github.com/nu7hatch/gouuid


.

The first line of this makefile is very important. export GOPATH=$(CURDIR) makes sure to set the system variable GOPATH to the current directory before calling any Go functions. This makes sure that go knows where to look for our source code and where to install third party packages for this project.

The default target basically compiles the project using go build with a verbose flag and specific output file.

The run target first compiles and then runs the compiled executable.

The dep-install downloads any third party packages we want for this project using go get

If you want to use additional third party packages you can just add them as a new line under the makefile target dep-install

So, with this you can install all dependencies by calling the make target make dep-install and then build the project by calling make and lastly run the executable by calling make run


    PS D:\Projects\skeleton> make dep-install
    go get github.com/nu7hatch/gouuid
    PS D:\Projects\skeleton> make
    go build -v -o skeleton.exe
    _/D_/Projects/skeleton
    PS D:\Projects\skeleton> make run
    go build -v -o skeleton.exe
    _/D_/Projects/skeleton
    skeleton.exe
    2013/10/26 08:50:32 e730395b-254e-4e43-55aa-b2eb4ba323fd
    PS D:\Projects\skeleton>

.

Wrapping it up

With this basic structure as your launch pad you can go ahead and write awesome applications of your own in golang using your favorite editor. I myself use http://www.sublimetext.com

You can find and download the example skeleton project at my github https://github.com/creamdog/golang.skeleton

14 9 / 2013

generating ten million unique alphanumeric codes in random order without collisions

Thought I should follow up and do some collision checking and stuff regarding my previous post cyclic alphanumeric code generation using quadratic residue

So I wrote the following up real quick and ran it using Node.js and it found no collisions in that set of ten million codes.

sidenote: I really like Node.js to write experiments like this in as it has like no boilerplate and very little ceremony if any at all. /endsidenote

It generates 10 000 000 codes in random order using the fairly large prime number 685420678114303 and outputs them like the following:


    5LCR4QPB7SU8W
    5LANR471ERDC8
    5LAWMK1O0940G
    5LB5HZWALQUOO
    5LBEDFQX78LCW
    5LBN8VLJSQBK4
    5LBROLIV3H6O4
    5LC0K1DHOYXCC
    5LC9FH84AGO0K
    5LCIAX2QVYEOS
    5LCR6CXDHG5C0
    5LANSQF3OEOGC
    5LAWO69Q9WF4K
    5LB5JM4CVE5SS

,

By picking the prime number 685420678114303 I am making sure I can generate 685420678114303 unique codes in seemingly random order. if you need to generate a smaller or larger set of codes you only need to pick any fitting prime.

The prime (P) you pick needs to satisfy P ≡ 3 mod 4

Also, in the example below I generate 10000000 codes from a set of 685420678114303 possible codes starting at index 0. you can start from any index you want or change the number of codes to generate to anything that fits within the range of your chosen prime.

You can also generate say, the first 10 codes (0 to 10) and later generate (10 to 20), the generated codes for each index are always the same based on what prime number you are using.

And here’s the code, enjoy!


    // Shuffled Unique Number Sequence Generator
    // Author: Christian Westman 2013
    // the following javascript program will generate ten million unique codes - 
    // in seemingly random order using quadratic residue permutation.
    // it checks if any generated code has been generated before and throws - 
    // an exception that halts execution if that is the case

    // a nice large prime from http://primes.utm.edu/primes/lists/all.txt
    var prime = 685420678114303;

    // baseCode: used as a base for your generated code
    // should be at least one character longer than the length of (prime) in base 36
    // nice to have if you wish to pad all codes to the same length
    var baseCode = '5A89FG89D5KAL';

    // the magic quadratic residue permutation algorithm
    function permutate(i, prime) {
        var i2 = prime - i;
        if(i2 < 0) {
            return i;
        }
        var num = Math.pow(i2, 2) % prime;
        num = i2 <= prime/2 ? num : prime - num;
        return num;
    }

    // converts num back into a base 10 number
    // snips N+1 characters at the tail of base where N is the length of (prime) in base 36
    // converts the snippet to base 10, adds num and converts result back into base 36
    // returns result padded with head
    function base36addition(prime, base, num) {
        var inputNumber = parseInt(num, 36);
        var head = base.substring(0, base.length-prime.toString(36).length-1);
        var tail = parseInt(base.split("").reverse().join("").substring(0, prime.toString(36).length+1), 36);
        return head + (tail += inputNumber).toString(36).toUpperCase();
    }

    // code below will loop from 0 to ten million -
    // and check if any generated code has been generated before.
    // throw an exception that halts execution if that is the case.
    var collisionObject = {};
    var outputBuffer = [];
    var startIndex = 0;
    var codesToGenerate = 10000000;
    for(var i=startIndex;i<startIndex+codesToGenerate; i++) {
        
        var n36 = permutate(i, prime).toString(36);
        var code = n36.length < baseCode.length ? base36addition(prime, baseCode, n36) : n36.toUpperCase();

        if(collisionObject[code] === true) {
            throw 'collision! code: '+code+', index: '+i;
        } else collisionObject[code] = true;

        outputBuffer.push(i+': '+code);

        if(outputBuffer.length > 32768) {
            console.log(outputBuffer.join('\n'));
            outputBuffer.length = 0;
        }
    }

    // flush buffer to console
    if(outputBuffer.length > 0) {
        console.log(outputBuffer.join('\n'));
        outputBuffer.length = 0;
    }

14 9 / 2013

cyclic alphanumeric code generation using quadratic residue

update: wrote another post generating ten million unique codes in random order without collisions

That’s right.

Say you want to generate a set of coupon codes where each code is unique and they are generated in a random order as to not be totally predictable.

Lets say that you later want to generate another set of coupon codes where each code is unique and not present in any previously generated set.

example:

  1. 5A85D98GFI
  2. 5A85D98GFP
  3. 5A85D98GFY
  4. 5A85D98GG9
  5. 5A85D98GGM
  6. 5A85D98GH1
  7. 5A85D98GHI
  8. 5A85D98GI1
  9. 5A85D98GIM

Lets also say that you do not want to utilize the brute force technique by generating random codes and compare them to previously generated codes until you have a new set of unique codes.

fine? next I will describe a method that achieves this.

Quadratic residue

In mathematics there’s such a thing called Quadratic residue where a prime number (P) used in the formula (N*N % P) generates a seemingly randomized number between 0 and P based on N where N is less than P.

The prime (P) you pick needs to satisfy P ≡ 3 mod 4

Another interesting read is http://preshing.com/20121224/how-to-generate-a-sequence-of-unique-random-integers

This means that this can be used to generate a sequence of unique numbers in a controlled “random” order where the length of the sequence is the the greatest known prime number (257,885,161 − 1)

This is also known as a form of permutation

The following example demonstrates this by generating a complete sequence using the prime 19, printing the scrambled list, sorting the list and printing it again.


    // JAVASCRIPT
    
    var prime = 19;

    function permutate(index, prime) {
        if(index >= prime) {
            return i;
        }
        var num = Math.pow(index, 2) % prime;
        num = index <= prime/2 ? num : prime - num;
        return num;
    }

    var list = [];
    for(var i=0;i<prime;i++) {
        list.push(permutate(i, prime));
    }
    console.log('scrambled: ', list.join(', '));
    // sort and print
    console.log('sorted:    ', list.sort(function(a, b){return a-b;}).join(', '));

Running the above script will output:


    scrambled:  0, 1, 4, 9, 16, 6, 17, 11, 7, 5, 14, 12, 8, 2, 13, 3, 10, 15, 18
    sorted:     0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18

,

As you can see the sequence is scrambled except for the first two indexes.

using this code lets generate a complete sequence using prime number 503


    scrambled:  0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 26, 73,
     122, 173, 226, 281, 338, 397, 458, 18, 83, 150, 219, 290, 363, 438, 12, 91, 172, 255, 340, 427, 13, 104, 197, 292, 389,
     488, 86, 189, 294, 401, 7, 118, 231, 346, 463, 79, 200, 323, 448, 72, 201, 332, 465, 97, 234, 373, 11, 154, 299, 446, 9
    2, 243, 396, 48, 205, 364, 22, 185, 350, 14, 183, 354, 24, 199, 376, 52, 233, 416, 98, 285, 474, 162, 355, 47, 244, 443,
     141, 344, 46, 253, 462, 170, 383, 95, 312, 28, 249, 472, 194, 421, 147, 378, 108, 343, 77, 316, 54, 297, 39, 286, 32, 2
    83, 33, 288, 42, 301, 59, 322, 84, 351, 117, 388, 158, 433, 207, 486, 264, 44, 329, 113, 402, 190, 483, 275, 69, 368, 16
    6, 469, 271, 75, 384, 192, 2, 317, 131, 450, 268, 88, 413, 237, 63, 394, 224, 56, 393, 229, 67, 410, 252, 96, 445, 293,
    143, 498, 352, 208, 66, 429, 291, 155, 21, 392, 262, 134, 8, 387, 265, 145, 27, 414, 300, 188, 78, 473, 367, 263, 161, 6
    1, 466, 370, 276, 184, 94, 6, 423, 339, 257, 177, 99, 23, 452, 380, 310, 242, 176, 112, 50, 493, 435, 379, 325, 273, 223
    , 175, 129, 85, 43, 3, 468, 432, 398, 366, 336, 308, 282, 258, 236, 216, 198, 182, 168, 156, 146, 138, 132, 128, 126, 37
    7, 375, 371, 365, 357, 347, 335, 321, 305, 287, 267, 245, 221, 195, 167, 137, 105, 71, 35, 500, 460, 418, 374, 328, 280,
     230, 178, 124, 68, 10, 453, 391, 327, 261, 193, 123, 51, 480, 404, 326, 246, 164, 80, 497, 409, 319, 227, 133, 37, 442,
     342, 240, 136, 30, 425, 315, 203, 89, 476, 358, 238, 116, 495, 369, 241, 111, 482, 348, 212, 74, 437, 295, 151, 5, 360,
     210, 58, 407, 251, 93, 436, 274, 110, 447, 279, 109, 440, 266, 90, 415, 235, 53, 372, 186, 501, 311, 119, 428, 232, 34,
     337, 135, 434, 228, 20, 313, 101, 390, 174, 459, 239, 17, 296, 70, 345, 115, 386, 152, 419, 181, 444, 202, 461, 215, 47
    0, 220, 471, 217, 464, 206, 449, 187, 426, 160, 395, 125, 356, 82, 309, 31, 254, 475, 191, 408, 120, 333, 41, 250, 457,
    159, 362, 60, 259, 456, 148, 341, 29, 218, 405, 87, 270, 451, 127, 304, 479, 149, 320, 489, 153, 318, 481, 139, 298, 455
    , 107, 260, 411, 57, 204, 349, 492, 130, 269, 406, 38, 171, 302, 431, 55, 180, 303, 424, 40, 157, 272, 385, 496, 102, 20
    9, 314, 417, 15, 114, 211, 306, 399, 490, 76, 163, 248, 331, 412, 491, 65, 140, 213, 284, 353, 420, 485, 45, 106, 165, 2
    22, 277, 330, 381, 430, 477, 19, 62, 103, 142, 179, 214, 247, 278, 307, 334, 359, 382, 403, 422, 439, 454, 467, 478, 487
    , 494, 499, 502
    sorted:     0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29
    , 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59
    , 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89
    , 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115
    , 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139
    , 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163
    , 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187
    , 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211
    , 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235
    , 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259
    , 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283
    , 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307
    , 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331
    , 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355
    , 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379
    , 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403
    , 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427
    , 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451
    , 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475
    , 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499
    , 500, 501, 502

,

Lets say we have already generated the first 25 numbers and want the next five, easy as:


    // *snip*
    var list = [];
    for(var i=25;i<30;i++) {
        list.push(permutate(i, prime));
    }
    console.log(list.join(', '));

,

Running the above script will output:


    122, 173, 226, 281, 338

Lets move on to generating some nice looking alphanumeric codes.

cyclic alphanumeric code generation using quadratic residue

First pick a arbitrary large prime, say 982451653. this is the maximum number of codes you will be able to generate using this prime.

Then pick a random alphanumeric code for padding, for example “5A89FG89D5” if you want all codes to be 10 characters long.

The below code snippet will generate and print the first 20 codes from a pool of 982451650 unique and shuffled codes.


    //JAVASCRIPT
    
    var prime = 982451653;
    // baseCode: used as a base for your generated code
    // should be at least one character longer than the length of (prime) in base 36
    var baseCode = '5A89FG89D5';

    function permutate(i, prime) {
        n = !n ? 0 : n;
        if(i >= prime) {
            return i;
        }
        var num = Math.pow(i, 2) % prime;
        num = i <= prime/2 ? num : prime - num;
        return num;
    }

    // converts num back into a base 10 number
    // snips N+1 characters at the tail of base where N is the length of (prime) in base 36
    // converts the snippet to base 10, adds num and converts result back into base 36
    // returns result padded with head
    function base36addition(prime, base, num) {
        var inputNumber = parseInt(num, 36);
        var head = base.substring(0, base.length-prime.toString(36).length-1);
        var tail = parseInt(base.split("").reverse().join("").substring(0, prime.toString(36).length+1), 36);
        return head + (tail += inputNumber).toString(36).toUpperCase();
    }

    // skip first three indexes as they are not scrambled
    for(var a=3;a<23; a++) {
        var n = permutate(a, prime);
        // convert to base 36 (0-9 + a-z) string
        r = base36addition(prime, baseCode, n.toString(36));
        console.log(r); 
    }

,

the code above outputs:


    5A85D98GFI
    5A85D98GFP
    5A85D98GFY
    5A85D98GG9
    5A85D98GGM
    5A85D98GH1
    5A85D98GHI
    5A85D98GI1
    5A85D98GIM
    5A85D98GJ9
    5A85D98GJY
    5A85D98GKP
    5A85D98GLI
    5A85D98GMD
    5A85D98GNA
    5A85D98GO9
    5A85D98GPA
    5A85D98GQD
    5A85D98GRI
    5A85D98GSP

08 9 / 2013

Update: CyanogenMod 10.1 Android 4.2.2 on the Samsung Galaxy Tab 10.1 P7500

I recently purchased an Asus MeMo Pad FHD 10 and decided to update our old Samsung Tab 10.1 P7500 to the latest available Cyanogenmod.

Since I wrote a guide earlier on how to perform such an update on the Samsung Tab I just updated some dead links.

The Samsung Galaxy Tab 10.1 runs just fine after the update and the guide is available here