Mittwoch, 13. Mai 2015

PT1 & PT2 Filtering/Damping

The functions below can be used to perform PT1 and PT2 damping of input values, which is, smoothing a potentially cluttered input.
Electrically speaking, the PT1 filter acts as a low-pass filter.
For continuous damping, the output of the last operation (outValue) must be stored and used for the next operation. This leads to a result history of 1 value which is enough to damp the input. The functions utilize a conversion of the 2byte input to 4byte to gain precision for division operations.

uint16 dampPT1( uint16 inValue,
                uint16* outValue,
                const uint16 riseFactor,
                const uint16 fallFactor)
{
    if(outValue == NULL)
    {
        return;
    }
    // Transformation of input to 32 bit internal format to gain precision and add remainder
    uint32 calcValue = (((uint32) inValue) << 16) + 32768;
    if (*outValue < calcValue)
    {
        if (m_riseFactor == 0)
        {
            *outValue = calcValue;
        }
        else
        {
            calcValue -= m_dampBuffer;
            calcValue /= m_riseFactor;
            if (calcValue == 0)
            {
                calcValue = 1;
            }
            *outValue += calcValue;
        }
    }
    else
    {
        if (outValue > calcValue)
        {
            if (fallFactor == 0)
            {
                *outValue = calcValue;
            }
            else
            {
                calcValue = *outValue - calcValue;
                calcValue /= fallFactor;
                if (calcValue == 0)
                {
                    calcValue = 1;
                }
                *outValue -= calcValue;
            }
        }
    }
    return (uint16) ((*outValue) >> 16);
}

uint16 dampLimitPT1(uint16 inValue,
                    uint16* outValue,
                    const uint16 riseFactor,
                    const uint16 fallFactor,
                    const uint16 riseLimit, const uint16 fallLimit)
{
    if(outValue == NULL)
    {
        return;
    }
    // Transformation of input to 32 bit internal format to gain precision and add remainder
    uint32 calcValue = (((uint32) inValue) << 16) + 32768;

    //  Check if characteristic is rising or falling
    if (*outValue < calcValue)
    {
        // Calculate differnce between old and new value
        calcValue -= *outValue;
        if (riseFactor != 0)
        {
            // division of the difference by k
            calcValue /= (uint32) riseFactor;
        }
        else
        {
            // do nothing here
        }
        // Check if limit reached
        if ((riseLimit != 0xFFFF) && (calcValue > ((uint32) riseLimit << 16)))
        {
            // Limit reached, set Delta to the maximum
            calcValue = ((uint32) riseLimit << 16);
        }
        *outValue += calcValue;
    }
    else
    {
        // Calculate differnce between old and new value
        calcValue -= *outValue;
        if (fallFactor != 0)
        {
            // division of the difference by k
            calcValue /= (uint32) fallFactor;
        }
        else
        {
            // do nothing here
        }
        // Check if limit reached
        if ((fallLimit != 0xFFFF) && calcValue > ((uint32) fallLimit << 16))
        {
            // Limit reached, set Delta to the maximum
            calcValue = ((uint32) fallLimit << 16);
        }
        *outValue -= calcValue;
    }
    return (uint16) (*outValue >> 16);
}

uint16 dampPT2(uint16 inValue,
               uint16* bufferPT1,
               uint16* bufferPT2,
               const uint16 riseFactor,
               const uint16 fallFactor)
{
    // perform PT1 limited damping on a PT1 damped input
    // first damping is configured using rising factor,
    // second damping is configured using falling factor
    return dampPT1(
               dampPT1(inValue, bufferPT1, riseFactor, riseFactor),
               bufferPT2, fallFactor, fallFactor);
}

uint16 dampLimitPT2( uint16 inValue,
                     uint16* bufferPT1,
                     uint16* bufferPT2,
                     const uint16 riseFactor,
                     const uint16 fallFactor,
                     const uint16 riseLimit,
                     const uint16 fallLimit)
{
    // perform PT1 limited damping on a PT1 damped input
    // first damping is configured using rising factor,
    // second damping is configured using falling factor and the limits
    return dampLimitPT1(
              dampPT1(inValue, bufferPT1, riseFactor, riseFactor),
              bufferPT2, fallFactor, fallFactor, riseLimit, fallLimit);
}

Montag, 2. Februar 2015

Simple CSS Parser in C#

The example below describes a simple CSS text parser to get certain values from CSS-class definitions:

using System.Collections.Generic;

namespace CSS
{
    public class Item
    {
        public string Class { get; set; }
        public int Left { get; set; }
        public int Top { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }
        public string Image { get; set; }
    }

    public class Parser
    {
        string m_cssString;
        List m_items;

        public Parser()
        {
            m_items = new List();
        }

        public void parseCss(string css)
        {
            // remove all useless stuff and get the relevant tokens
            string[] tokens = css.Replace("\n", "").Replace("\t", "").Replace("\r", "").Replace(" ", "").Replace("px", "").Split('{', '}', ';');
            m_cssString = css;

            foreach (string token in tokens)
            {
                Item last = null;
                if (m_items.Count > 0)
                {
                    last = m_items[m_items.Count - 1];
                }

                if (token != string.Empty)
                {
                    if (token.StartsWith("."))
                    {
                        // class found
                        m_items.Add(new Item() { Class = token.Substring(1) });
                    }
                    else if (token.StartsWith("left") && last != null)
                    {
                        last.Left = int.Parse(token.Split(':')[1]);
                    }
                    else if (token.StartsWith("top") && last != null)
                    {
                        last.Top = int.Parse(token.Split(':')[1]);
                    }
                    else if (token.StartsWith("width") && last != null)
                    {
                        last.Width = int.Parse(token.Split(':')[1]);
                    }
                    else if (token.StartsWith("height") && last != null)
                    {
                        last.Height = int.Parse(token.Split(':')[1]);
                    }
                    else if (token.StartsWith("background-image") && last != null)
                    {
                        last.Image = token.Split('"')[1];
                    }
                }
            }
        }

        public List getItems()
        {
            return m_items;
        }

    }
}

Samstag, 24. November 2012

Common Algorithms from Wikibooks

Cheers!
I found a nice link from Wikibooks where one can find many common algorithm implementations that occur in frequent tasks of programming:

Although most of them may be implemented in standard libraries of the different languages, it is a great repository of procedures for any purpose. Furthermore you may find it a nice way to learn how these are actually implemented in your framework.

Have a good time while exploring the contents!

Mittwoch, 7. November 2012

Split line in C++

inline vector split(string line, size_t minWordLength) {
  vector ret;
  size_t pos = 0;
  while (pos < line.size()) {
    while (pos < line.size() && !isalpha(line[pos]))
      pos++;
    size_t wordStart = pos;
    while (pos < line.size() && isalpha(line[pos]))
      pos++;
    size_t wordEnd = pos;
    if (wordEnd >= wordStart + minWordLength) {
      string word = line.substr(wordStart, wordEnd - wordStart);
      ret.push_back(word);
    }
  }
  return ret;
}
This inline helper function splits a line of characters (string) and returns a list (vector) of words the line consists of. Given the minWordLength parameter only words with a minimum length of this size will be considered for the output.
The line is split by delimiters being of non-character type like a space or dashes. Of course, one could also use a delimiter as parameter or a list of those to determine the separators within the line...
To use this function string and vector from the STL are required.

Measuring time in C++

inline double startTime() {
  struct timeval tp;
  double sec, usec;
  // Time stamp before the computations
  gettimeofday(&tp, NULL);
  sec = static_cast(tp.tv_sec);
  usec = static_cast(tp.tv_usec) / 1E6;
  return sec + usec;
}

inline double elapsedTime(double starttime) {
  struct timeval tp;
  double sec, usec;
  // Time stamp after the computations
  gettimeofday(&tp, NULL);
  sec = static_cast(tp.tv_sec);
  usec = static_cast(tp.tv_usec) / 1E6;
  // Time calculation (in seconds)
  return sec + usec - starttime;
}
A relatively easy way to measure time in C++ is to use standard linux libraries:
#include <sys/time.h>
#include <sys/types.h>
The first function (that can e.g. be global) returns the system time as double in microseconds. The second one computes the elapsed time according to the measurement given by the first function.
Application example:
...
double start = startTime();
// do something time consuming...
double elapsed = elapsedTime(start);
cout << "The operation took " << elapsed << "µs" << endl;
...

Dienstag, 10. Juli 2012

Java long-time formatting

public static String formatTime(long milliseconds){
    int seconds = (int) (milliseconds / 1000) % 60 ;
    int minutes = (int) ((milliseconds / (1000*60)) % 60);
    int hours   = (int) ((milliseconds / (1000*60*60)) % 24);
    return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}
This method converts a given time (as long) to a readable time string of the format hh:mm:ss. Sometimes pretty useful for performance measures (System.currentTimeMillis()) and easy formatting of java.util.Date.
Inline Version
public static String formatTime(long m){
    return String.format("%02d:%02d:%02d", (m/1E3)%60, ((m/(6*1E4))%60, (m/(3.6*1E6))%24);
}

Montag, 9. Juli 2012

Java Google Maps Route Information

static String getGoogleMapsRoute(float startLat, float startLng, float endLat, float endLng)
throws Exception {
    // build a search query for google maps:
    String query = "http://maps.googleapis.com/maps/api/directions/xml?origin="
        + startLat + "," + startLng + "&destination="
        + endLat + "," + endLng + "&sensor=false";
    XPath xPath = XPathFactory.newInstance().newXPath();
    org.xml.sax.InputSource source = new org.xml.sax.InputSource(new URL(url).openStream());
    // parse the received reply (XML) for the information we want:
    org.w3c.dom.Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(source);
    String length = xPath.evaluate("/DirectionsResponse/route/leg/distance/text", doc);
    String duration = xPath.evaluate("/DirectionsResponse/route/leg/duration/text", doc);
    String start = xPath.evaluate("/DirectionsResponse/route/leg/start_address", doc);
    String end = xPath.evaluate("/DirectionsResponse/route/leg/end_address", doc);
    return "(length = " + length + ", duration = " + duration + ") Start: " + start + ", End: " + end;
}
This nice java method retrieves information of a GoogleMaps route from the given start location to the end/target location (latitude + longitude). It is possible to write addresses or names of important places to the 'origin' and 'destination' parameters.
For this method one have to import some stuff from javax.xml.