Windows Azure Toolkit for Mono for Android

I have just released MonoDroid.WAToolkit, which are some tools, which allows you to authenticate against Windows Azure on the Mono for Android platform.

Grab the code here: https://github.com/Cheesebaron/MonoDroid.WAToolkit

Shake detection using accelerometer on Windows Phone 7.1

I needed some shake detection on Windows Phone 7.1 only finding some examples using some deprecated events. So I have updated the sample found on Mark Monster's blog so that it works with Windows Phone 7.1.

To use this you need to add the references:
Microsoft.Devices.Sensors
Microsoft.Xna.Framework

Helper class:

using System;
using Microsoft.Devices.Sensors;

namespace Ostebaronen.ShakeShakeShake
{
    public class AccelerometerSensorShakeDetector : IDisposable
    {
        private const double ShakeThreshold = 0.7;
        private readonly Accelerometer _sensor = new Accelerometer();
        private AccelerometerReading _lastReading;
        private int _shakeCount;
        private bool _shaking;

        public AccelerometerSensorShakeDetector()
        {
            var sensor = new Accelerometer();
            if (sensor.State == SensorState.NotSupported)
                throw new NotSupportedException("Accelerometer not supported on this device");
            _sensor = sensor;
        }

        public SensorState State
        {
            get { return _sensor.State; }
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (_sensor != null)
                _sensor.Dispose();
        }

        #endregion

        private event EventHandler ShakeDetectedHandler;

        public event EventHandler ShakeDetected
        {
            add
            {
                ShakeDetectedHandler += value;
                _sensor.CurrentValueChanged += ReadingChanged;
            }
            remove
            {
                ShakeDetectedHandler -= value;
                _sensor.CurrentValueChanged -= ReadingChanged;
            }
        }

        public void Start()
        {
            if (_sensor != null)
                _sensor.Start();
        }

        public void Stop()
        {
            if (_sensor != null)
                _sensor.Stop();
        }

        private void ReadingChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e)
        {
            //Code for checking shake detection
            if (_sensor.State == SensorState.Ready)
            {
                AccelerometerReading reading = e.SensorReading;
                try
                {
                    if (!_lastReading.Equals(null))
                    {
                        if (!_shaking && CheckForShake(_lastReading, reading, ShakeThreshold) && _shakeCount >= 1)
                        {
                            //We are shaking
                            _shaking = true;
                            _shakeCount = 0;
                            OnShakeDetected();
                        }
                        else if (CheckForShake(_lastReading, reading, ShakeThreshold))
                        {
                            _shakeCount++;
                        }
                        else if (!CheckForShake(_lastReading, reading, 0.2))
                        {
                            _shakeCount = 0;
                            _shaking = false;
                        }
                    }
                    _lastReading = reading;
                }
                catch
                {
                    /* ignore errors */
                }
            }
        }

        private void OnShakeDetected()
        {
            if (ShakeDetectedHandler != null)
                ShakeDetectedHandler(this, EventArgs.Empty);
        }

        private static bool CheckForShake(AccelerometerReading last, AccelerometerReading current,
                                            double threshold)
        {
            double deltaX = Math.Abs((last.Acceleration.X - current.Acceleration.X));
            double deltaY = Math.Abs((last.Acceleration.Y - current.Acceleration.Y));
            double deltaZ = Math.Abs((last.Acceleration.Z - current.Acceleration.Z));

            return (deltaX > threshold && deltaY > threshold) ||
                    (deltaX > threshold && deltaZ > threshold) ||
                    (deltaY > threshold && deltaZ > threshold);
        }
    }
}

Using the class add this to the place you want to detect shakes:

            AccelerometerSensorShakeDetector shakeSensor = new AccelerometerSensorShakeDetector();
            Loaded += (sender, args) =>
            {
                shakeSensor.ShakeDetected += shakeSensor_ShakeDetected;
                shakeSensor.Start();
            };
            Unloaded += (sender, args) =>
            {
                shakeSensor.ShakeDetected -= shakeSensor_ShakeDetected;
                shakeSensor.Stop();
            };

        void shakeSensor_ShakeDetected(object sender, EventArgs e)
        {
                //Shake detected
                //Use Dispatcher.BeginInvoke() to run on UI thread.
        }

If you want to update UI elements remember to do it on the UI thread as this one returns on another one.

New YouTube Add-to box

So YouTube decided to style some of the things a bit differently in their default style. Such as the box appearing when pressing Add to under a video. One thing that annoys me is that it is so freaking small. I decided to dig a bit and made some small changes using StyleBot.

This is the CSS I ended up using, it is quite simple, but allows you to see more of your lists.

div#shared-addto-menu {
    height: 400px;
}

div#shared-addto-menu .playlists ul {
    height: 300px;
}

Matching two arrays and removing values from one of them

Nothing too exciting but here it comes.

So while I was doing some scraping, I had this small problem where I already had some data, which didn't exactly match up with the new stuff I had scraped, but parts of it was contained in the new stuff. So what I needed to do was to find all the occurrences of the old data in the new data and remove it, because I already had that lying around.

I had two files with the two data sets to be matched, each of them with their data separated by a line break

<?php
//load data
$dataset1 = file_get_contents('data1.csv');
$dataset2 = file_get_contents('data2.csv');

//make data into arrays
$dataarr1 = explode("\n", $dataset1);
$dataarr2 = explode("\n", $dataset2);

foreach($dataarr1 as $d1) { //shoop da loop!
        foreach($dataarr2 as $d2key => $d2) {
                preg_match("/".$d1."/", $d2, $matches);
                if (!empty($matches) && $matches[0] != "") {
                        unset($dataset2[$d2key]);
                }
        }
}

//write the data
$fileres = fopen("outdata.csv", "w+");
fwrite($fileres, implode("\n", $dataset2));
fclose($fileres);
?>

So what this essentially does is to take two datasets. It takes the first and matches up against the second. If the first one is contained in the second one, delete the data from the second dataset. Try all possibilities. Afterwards it just writes it to a file.

Scraping web pages with PHP

So recently I had to scrape some information of a website and found out that it is actually quite easy. Only problems I encountered was that I ran out of heap space because of one of the webpages I was scraping had a lot of junk HTML in it. My approach was to use the PHP Simple HTML DOM library, which took care of all the hard work.

Let me show you an example using Slashdot.org to show you how easy it is to grab elements using Simple HTML DOM. Here I want all the headings for the news on Slashdot. I know this could be done by grabbing the RSS, but this is just to demonstrate.

 <?php
include_once 'simple_html_dom.php';

$url = "http://slashdot.org/";
$html = file_get_html($url);

$pat[0] = "/^\s+/";
$pat[1] = "/\s{2,}/";
$pat[2] = "/\s+\$/";
$rep[0] = "";
$rep[1] = " ";
$rep[2] = "";

foreach($html->find('h2') as $heading) { //for each header
        echo preg_replace($pat, $rep, $heading->find('span a', 0)->plaintext) . "\n"; //echo the text inside
}
?>

So in the example above. What I am doing is finding all the H2 occurrences in the HTML code, which is how Slashdot presents their headings for their news entries. Inside the H2 tags there is a span and a link, where the link is containing the heading. I am just grabbing that heading and removing all unnecessary spacing, because I don't need that. The output of running the script is like shown below.

5.8 Earthquake Hits East Coast of the US
Origins of Lager Found In Argentina
Inside Oregon State University's Open Source Lab
WebAPI: Mozilla Proposes Open App Interface For Smartphones
Using Tablets Becoming Popular Bathroom Activity
The Syrian Government's Internet Strategy
Deus Ex: Human Revolution Released
Taken Over By Aliens? Google Has It Covered
The GIMP Now Has a Working Single-Window Mode
Zombie Cookies Just Won't Die
Motorola's Most Important 18 Patents
MK-1 Robotic Arm Capable of Near-Human Dexterity, Dancing
Evangelical Scientists Debate Creation Story
Android On HP TouchPad
Google Street View Gets Israeli Government's Nod
Internet Restored In Tripoli As Rebels Take Control
GA Tech: Internet's Mid-Layers Vulnerable To Attack
Serious Crypto Bug Found In PHP 5.3.7
Twitter To Meet With UK Government About Riots
EU Central Court Could Validate Software Patents

I call that easy! The script would of course need to be modified if you are trying to scrape something else. The Simple HTML DOM can find all sorts of information for you. I.e. paths to images from img tags, content in specific divs so on and so forth. Be warned, you might run into zend mm heap problems if you are trying to load a lot of data to be scraped. If you are doing so, I suggest you doing your scraping in iterations.

Reuploading failed Endomondo tracks

Sometimes Endomondo claims it has uploaded a track to the webpage while it hasn't, sometimes it also uploads them partially, which is quite annoying. There is no built in reupload feature. But if you really want to reupload a track I found out you can do it as follows. This requires that you have access to modify files in /data/data. I also used android-sdk to push and pull files from the device. It also requires an SQLite database browser i used http://sqlitebrowser.sourceforge.net/

  • First thing I did was to go to the settings in Endomondo and disable auto upload.
  • Next thing start a new track and just stop it after a couple of seconds.
  • Shutdown Endomondo and pull the Endomondo database from /data/data/com.endomondo.android/databases/EndomondoDatabase
  • Locate the recently created track in the workout table. It should have the highest time stamp number. Remember the workoutId
  • Delete all the entries for the recently created workout:
    DELETE FROM workout WHERE workoutId = <remembered workoutid>; 
    DELETE FROM trackpoint WHERE workoutId = <remembered workoutid>; 
    DELETE FROM laptimes WHERE workoutId = <remembered workoutid>; 
  • Now locate the workout which you want to reupload.
  • Update the workoutId for the workout that you want to reupload:
    UPDATE workout SET workoutId = <remembered workoutid> WHERE workoutId = <reupload workoutid>; 
    UPDATE trackpoint SET workoutId = <remembered workoutid> WHERE workoutId = <reupload workoutid>; 
    UPDATE laptimes SET workoutId = <remembered workoutid> WHERE workoutId = <reupload workoutid>; 
  • Last thing is to update upLoadStatus and lastUpload so that Endomondo thinks it has not yet been uploaded.
    UPDATE workout SET upLoadStatus = 0 WHERE workoutId = <remembered workoutid>; 
    UPDATE workout SET lastUpload = -1 WHERE workoutId = <remembered workoutid>; 
  • Save the database and push it back to the device. Start Endomondo, go to the History tab and long-press the workout and choose Manual Upload.

If this does not work the first time try again. I had to try uploading it a couple of times as it got interrupted in the middle of the upload.

SSH Tunneling

Sometimes it can be very useful to tunnel you traffic to another server. For instance if you want to stream content from another country, when the content is restricted to that country. This requires that you actually have an available server in that country. Lets assume you have, how do you tunnel your traffic to that server then? One solution is by creating a SSH tunnel, which I will talk briefly about here.

Windows users, I recommend using PuTTY, which I also will base this small howto upon, which can be acquired from their official download page.
Linux users can use their normally built in SSH client.

The method I will use for this is called SSH dynamic tunneling, and will allow your own computer to act as a Proxy.

Windows

  1. Open up PuTTY
  2. Expand Connection
  3. Expand SSH
  4. Choose Tunnels
  5. In here you can choose which local port you want to act as Proxy for the traffic you want to tunnel.
    • In the Source Port field choose the port you want to use as Proxy, i.e. 8080
    • Leave Destination blank and tick Dynamic
    • Press Add
  6. Now go back to Session
  7. In the Host Name field enter the host name or IP address of the SSH server you want to connect to
  8. In the Port field enter the Port of the SSH server
     
  9. (Optional) If you want to save this for next time you want to use it in the Saved Sessions field write the name of this session and press Save.
  10. Now press Open. (Log in and so on)


Now you have sucessfully created a tunnel. Now we need to configure Windows to use this Proxy.

  1. Go to your Control Panel
  2. In Vista and Win7 choose Network and Internet
  3. Choose Internet Options
  4. A new window should appear. Go to the Connections tab
  5. Press LAN Settings
  6. Tick Use a proxy server...
  7. Go to Advanced and untick Use the same proxy for all protocols
  8. Fill out Socks with 127.0.0.1 and the Port you choose
  9. Press OK and OK and OK

Now you should be done!

Linux

  1. Open the command line
  2. Type in ssh -p <host port> -D <proxy port> <hostname or IP> (replace stuff in <>. -p <host port> is only necessary when SSH server is running on another port than 22)
  3. Configure your applications to use SOCKSv5 using localhost and the proxy port you choose. (Systemwide configuration can be done with IPtables, proxychains and other applications).

Have fun with your proxy.

Osterock, a phpBB3 theme for Hoved-fi.dk

I recently joined the forum Hoved-fi.dk, which focuses on headphones and accessories, which a cool guy named Claus runs. You might also know him as Claus-dk. But I've been a head-fier for some time and the forum was running some stock theme. Not suitable for a such a great initiative, so I decided to give a hand creating a new. After some discussion with Claus about the theme we found out that we wanted to use the Rock'n'roll phpBB3 theme as base.

To see the current state of the theme go to http://hoved-fi.dk
Latest code can be obtained from github: https://github.com/Cheesebaron/osterock

Feel free to fork :)

GitHub goodness

I created a GitHub repository a long time ago when I was supposed to use it for a project at DTU, but we dropped git in favor of SVN. Though I kind of like Git better and hence I am now uploading a lot of my previous and current project to GitHub.

https://github.com/Cheesebaron/

Feel free to fork!

Lottery Winner

My brother (xodeus.dk) is doing some contests and needs to pick a winner from list of people with multiple lots. For the purpose of choosing a winner I have made a small application to help him do this easily.

The application source code can be found here: https://github.com/Cheesebaron/LotteryWinner
The latest application binary can be found here: http://dokyou.eu/LotteryWinner.jar

To run the application java must be installed. The data set to use with the application has to be in the following form:

Name,lots
Name,lots

I.e.:

John Doe,4
Jane Doe,2

The application is run from the command line using: java -jar LotteryWinner.jar dataFile


License

I, the copyright holder of this work, hereby release it into the public domain. This applies worldwide.
In case this is not legally possible, I grant any entity the right to use this work for any purpose, without any conditions, unless such conditions are required by law.