Coding – ChalamiuS' Blog http://blog.chalamius.se/ Yet another random blog on the internet Mon, 27 Mar 2017 18:23:38 +0000 en-US hourly 1 https://wordpress.org/?v=5.7.2 A smaller status update https://blog.chalamius.se/2011/03/a-smaller-status-update/ https://blog.chalamius.se/2011/03/a-smaller-status-update/#respond Thu, 03 Mar 2011 19:50:32 +0000 http://blog.chalamius.se/?p=336 Continue reading "A smaller status update"

]]>
Except for the ordinary slavery going on at school I’m working on a bunch of projects

Hecate

A rewrite of Lolikins’ rewrite (which I never finished), sort of.
Made in Python instead of PHP which gives a couple of quite nice advantages such as:

  • SSL support again
  • Clean code (PHP looks dirty for some reason, probably all those $)
  • Module reloading without the use of unsupported extensions

Oh and I have someone helping me out actively this time (which means it’ll probably be finished too).

Akyu

As usual there’s some changes I did to the quote database such as infi-scroll (you know, the thing that makes the page continue loading while you scroll on twitter and such) which… doesn’t work quite as I want it to just yet but oh well.

Lastly

There’s a project I’ll announce when it’s ready (some of you may already know but keep it to yourselves).

]]>
https://blog.chalamius.se/2011/03/a-smaller-status-update/feed/ 0
Some updates (and new creations) https://blog.chalamius.se/2010/09/some-updates-and-new-creations/ https://blog.chalamius.se/2010/09/some-updates-and-new-creations/#comments Sun, 05 Sep 2010 02:37:26 +0000 http://blog.chalamius.se/?p=277 Continue reading "Some updates (and new creations)"

]]>
The Quote Database

The quote database I work on (Akyu) have been updated to 0.2 recently (24th August).
This changed some things:

  • Voting buttons now actually tells you they are, i.e voting buttons
  • No text error messages, all error messages are displayed when you hover over the button you just clicked
  • Some minor changes to the layouts of some pages (for example the search page)

pIRC

A smaller bug fix a couple of days ago. The event handler couldn’t handle some constants as triggers.
Away has been added to the irc wrapper as well.

Going to try to get some sort of Admin module into it next time I have a longer weekend than I have now.

Voile

My little image gallery I work on every now and then.
It currently only generates cached thumbnails for what I upload and lists them on the index page; nothing fancy.

Feel free to take a look

One last thing

Thingie~
Rawr, I'm going to poke you with my antenna
]]>
https://blog.chalamius.se/2010/09/some-updates-and-new-creations/feed/ 2
Random updates https://blog.chalamius.se/2010/02/random-updates/ https://blog.chalamius.se/2010/02/random-updates/#comments Mon, 22 Feb 2010 23:07:45 +0000 http://blog.chalamius.se/?p=202 Continue reading "Random updates"

]]>
So… I just thought I’d post some updates to keep this blog from being idle for way too long.

As you might know (at least if you checked out the Projects tab) I’m working on an irclib, so I thought I’d give you a bit of a preview on how the actual ircbot looks from the command-line.

Sadly it seems like the coloring and stuff will be Linux only since it requires an extra (3rd-party, not Microsoft) executable for Windows.

pIRC - A screenshot
So, this is how it looks

An extensible IRC-bot made in PHP using as few PECL modules as possible.

The goal of pIRC is to have a fast lightweight bot that’s extensible.

And this is the current feature set:

– Event Handler

  • Supports both arrays and single arguments, if none are given upon registering the function will be passed the standard Message object.
  • Built-in flood protection

– Modules

  • All modules can be loaded, unloaded and reloaded during run-time
  • It checks the syntax before loading to prevent accidental crashing
  • Probably less leaky than the rename class method that others seems to use

Anyways,

I did some updates to the QDB to make it a bit faster along with fixing up a new theme for my #bakabt stats.

Sadly not much more to report, except the fact that I have math test on Wednesday so I wont get anything done on anything this week anyway :3

Also, if you have any suggestions to the QDB or similar, feel free, suggestions are always welcome.

This post is pretty much a post to remind myself to work on this crap when I get the time to >_>
also, todo: Add more stuff to this update post.
]]>
https://blog.chalamius.se/2010/02/random-updates/feed/ 3
C#: Lambda Expressions https://blog.chalamius.se/2010/01/c-lambda-expressions/ https://blog.chalamius.se/2010/01/c-lambda-expressions/#respond Fri, 08 Jan 2010 22:47:05 +0000 http://blog.chalamius.se/?p=183 Continue reading "C#: Lambda Expressions"

]]>
As a belated follow up to my post on C# Anonymous Methods, let’s look at a closely related feature of the CLS: lambda expressions.  Then let’s use a lambda expression to improve the code example from that earlier article.

Lambda Expressions were introduced in the 3.0 version of the Common Language Specification.  Lambdas are essentially a refinement of anonymous methods.  They allow you to define a block of code which operates on one or more input variables and returns a single result.  Let’s break down a simple lambda example, from the MSDN page on Lambda Expressions:

delegate int del(int i);
static void Main(string[] args)
{
    del myDelegate = x => x * x;
    int j = myDelegate(5); //j = 25
}

In this example, a delegate type is defined, del.  Then an instance of the delegate is created using a lambda expression.  Finally, the delegate is executed, and the return value is assigned to the integer variable j.  Let’s ignore everything but the lambda expression itself: x => x * x.

The first character of the expression actually defines a variable named x, which only exists inside the lambda expression.  In the MSDN example, when the lambda is actually executed, x will be assigned the input value of 5.

The => character sequence tells C# that your lambda expression operates on the variable x.  To oversimplify, everything to the left of => is an input variable declaration, and everything on the right is an expression which determines the return value.  In our examples, there will only ever be one input variable.

The x * x character sequence is the actual expression, the bit of code that gets executed.  So we could rewrite down the code above to this:

int x = 5;
int j = x * x;

…and achieve the same result.

Filtering Cars with Lambda Expressions

Returning to our anonymous methods example, we found that the FindAll method of the List<> generic class can take a delegate. The delegate is used to filter which items in the list are returned.

With Anonymous Methods

static void Main(string[] args)
{
    // Create a list of cars meeting criteria by calling the FindAll()
    // method of the List returned by CreateCars().
    List cars = CreateCars().FindAll(delegate(Car candidate)
    {
        // Return whether the car matches our criteria.  FindAll()
        // expects our anonymous method to return a boolean, and
        // the compiler makes sure this is the case.
        return
            candidate.Manufacturer == "Toyota" ||
            candidate.Manufacturer == "Nissan" &&
            candidate.Turbocharged == false;
    });

    foreach(Car car in cars)
    {
        Console.WriteLine(car.ToString());
    }
}

Instead, let’s replace that anonymous method block with a lambda expression.

With Lambda Expressions

static void Main(string[] args)
{
    List cars = CreateCars().FindAll(car =>
        car.Manufacturer == "Toyota" ||
        car.Manufacturer == "Nissan" &&
        car.Turbocharged == false );

    car.Turbocharged = true; // Invalid code, "car" does not exist.
}

In this case, our lambda expression creates the variable car, and then does the same set of conditional tests as the old example. Note that the car variable only exists in the scope of the lambda expression, just like in the anonymous method. For that reason, the second to last line of code would be a compiler error.

So What’s the Difference?

For the purposes of our example, not a whole lot:

  • The input variable and return types are inferred. C# is able to figure out what type car is by looking at where the lambda is used.   The type is actually defined in the CreateCars() method of our earlier example. C# looks at the return type of List<Car> and infers (or deduces) that a lambda expression operating on the FindAll method of that List<Car> would operate on a single input variable of type Car. Note that in the old anonymous methods example, C# was only able to infer the return type.
  • The lambda expression does not need curly braces, since it is a basic expression.
  • The lambda expression does not use the ugly delegate() syntax, thanks to the type inference.

Of course lambda expressions are a bit more complicated than I let on; they can declare multiple input variables, and they can also contain normal procedural code statements (such as calling a method — and that does require using curly braces).

]]>
https://blog.chalamius.se/2010/01/c-lambda-expressions/feed/ 0
C#: Anonymous Methods https://blog.chalamius.se/2009/06/c-anonymous-methods/ https://blog.chalamius.se/2009/06/c-anonymous-methods/#comments Tue, 02 Jun 2009 15:54:39 +0000 http://blog.chalamius.se/?p=146 Continue reading "C#: Anonymous Methods"

]]>
To continue ChalamiuS’ theme of C# goodness, let’s explore a feature of C# introduced in version 2 of the CLS: the anonymous method. Along the way we’ll also encounter Generics and Object Initializers, but they are not the focus of this post.

Anonymous methods and other features of C# 2.0 and 3.0 incorporate paradigms from functional programming and other (relatively) exotic notions. The full implications of this are and the theory behind it are only minimally covered in this post. It should also be noted that in C# 3.0, lambda expressions were introduced, which work similarly to anonymous methods and look a whole lot cooler.

What is an anonymous method?

To answer this question, let’s first define what a named (eg, not anonymous) method is, using Object.ToString() as an example:

  • A method name.
  • A return type. Object.ToString, unsurprisingly, returns a string. Note that void is a type.
  • A parameter list. Object.ToString does not take any parameters.
  • A method body. The default Object.ToString implementation returns the type name.

Without all of these elements, we cannot have a method. Let’s similarly analyze the makeup of an anonymous method:

  • A return type.
  • A parameter list.
  • A method body.

The major difference is, of course, the lack of a method name. Another significant difference not apparent in our comparison is that the return type of parameter list of an anonymous method is declared in a delegate. Any number of anonymous methods may conform to the same delegate. This is a very basic look at anonymous methods. I suggest you read more by people who actually know what they’re talking about.

Why use an anonymous method?

There are any number of reasons to use an anonymous method instead of a regular named method, but my favorite is to help organize small blocks of specialized code. Instead of declaring a very short method and then calling it from only one place in your code, you can put the anonymous method code right inside the method that needs it. Anonymous methods are also a great way of sharing information between blocks of code without having use classes or complex method declarations.

We must be careful to not declare anonymous methods when the code they contain may be used in more than once place. While this can be fixed by refactoring the anonymous method into a named method, it’s best to avoid this pitfall in the first place.

Wait, what?

Instead of drowning in theory and technical arcana, let’s see a (highly contrived) example. In this example, we create a list of cars and print out any car meeting a certain criteria. The code declaring the Car class and filling the list of cars is at the end of this post.

Example without anonymous method

 
static void Main(string[] args)
{
    List cars = CreateCars();

    foreach (Car car in cars)
    {
        if (DoesCarMeetCriteria(car))
            Console.WriteLine(car.ToString());
    }
}

static bool DoesCarMeetCriteria(Car car)
{
    return
        car.Manufacturer == "Toyota" ||
        car.Manufacturer == "Nissan" &&
        car.Turbocharged == false;
}

Example with anonymous method

static void Main(string[] args)
{
    // Create a list of cars meeting criteria by calling the FindAll()
    // method of the List returned by CreateCars().
    List cars = CreateCars().FindAll(delegate(Car candidate)
    {
        // Return whether the car matches our criteria.  FindAll()
        // expects our anonymous method to return a boolean, and
        // the compiler makes sure this is the case.
        return
            candidate.Manufacturer == "Toyota" ||
            candidate.Manufacturer == "Nissan" &&
            candidate.Turbocharged == false;
    });

    foreach(Car car in cars)
    {
        Console.WriteLine(car.ToString());
    }
}

Conclusion

Which do you prefer? I like the anonymous method; while the syntax may seem strange it becomes quite natural after using it a few times. Sadly this example is somewhat weak; using an anonymous method doesn’t really gain us anything. However, showing the true power would touch on language design paradigms and the like, which I am avoiding in this post.

Here’s the rest of the code required to compile and run the example:

The Car class

class Car
{
    public string Manufacturer, Model;
    public bool Turbocharged;

    public override string ToString()
    {
        return String.Format(
            "{0} {1} ({2}Turbo)", 
            Manufacturer, 
            Model, 
            Turbocharged ? "" : "Non-");
    }
}

Creating the Car list

static List CreateCars()
{
    List cars = new List();
    cars.Add(new Car()
    {
        Manufacturer = "Toyota",
        Model = "AE-86 Trueno GT-APEX",
        Turbocharged = false
    });

    cars.Add(new Car()
    {
        Manufacturer = "Toyota",
        Model = "MR2",
        Turbocharged = false
    });

    cars.Add(new Car()
    {
        Manufacturer = "Nissan",
        Model = "180SX",
        Turbocharged = false
    }); // Some models are turbo-charged.

    cars.Add(new Car()
    {
        Manufacturer = "Nissan",
        Model = "Sileighty",
        Turbocharged = true
    });
    return cars;
}
]]>
https://blog.chalamius.se/2009/06/c-anonymous-methods/feed/ 1
Exploding Rats and the C++ Standard Vector https://blog.chalamius.se/2009/02/exploding-rats-and-the-c-standard-vector/ https://blog.chalamius.se/2009/02/exploding-rats-and-the-c-standard-vector/#respond Sat, 21 Feb 2009 17:12:54 +0000 http://blog.chalamius.se/?p=133 Continue reading "Exploding Rats and the C++ Standard Vector"

]]>

Rats are small, cheap, easy to maintain and transport.

Mine-sniffing ratsAs many are aware, land mines present a significant danger in many war-ravaged countries around the world. Numerous innovative techniques have been developed to clear mine fields, rendering the land once again usable and preventing tragic injuries and deaths. A Belgian non-profit organization, APOPO, began a unique program to develop a new method — using Giant Pouched Rats (Nesomyidae Cricetomyinae) to detect mines — dubbed HeroRATS in 2004, and has now deployed the intrepid rodents in Mozambique.

The rats are too light to set off mines, so disappointingly they are not destroyed in the process (sorry, I lied). Instead, the rats are attached to guide lines and trained to scratch at the ground when they sniff out explosives. The mine is then flagged for removal using more appropriate tools.

A zebra is a horse designed by a committee.

I’ll be the first to admit that I am not an expert with the C++ language. In fact, I can use all the practice I can get. I’ve been using the Standard Template Library on and off for almost 3 years now, but know embarrassingly little about it’s full capabilities. In that vein, I will (hopefully) be posting a series of snippets and short programs about the STL. I plan to start simple, and work my way up. Without further ado, the very basics of the STL vector and it’s iterator.

#include <iostream>
#include <vector>
#include <string>

int main()
{
   // Define a vector, which is an array-like container of items.
   // Unlike std::set, vectors can contain the same element any
   // number of times.
   std::vector<std::string> strings;

   // Add some strings to the vector.
   strings.push_back("foo");
   strings.push_back("bar");

   // Insert a string at a specific point in the vector.  Here "baz"
   // is appended to the vector.
   strings.insert(strings.end(), "baz");

   // STL containers (such as vector, set, hash, etc) can be iterated
   // in a manner almost like foreach some in other languages.  First
   // an iterator must be declared.
   std::vector<std::string>::iterator iter = strings.begin();

   // The iterator can be used to access each element of the vector.
   for(;
       iter != strings.end(); /* Don't iterate past the end. */
       iter++) /* iters overload the increment (++) operator. */
   {
      // To retrieve the value at the index represented by the
      // iterator, some more STL syntactical sugar makes it a
      // simply matter of using the dereference (*) operator.
      std::cout << *iter;
      std::cout << std::endl;
   }
}
$ g++ vector.cpp -o vector && ./vector
foo
bar
baz
$

Let me know if I’ve made obvious mistakes, which I tend to do frequently!

]]>
https://blog.chalamius.se/2009/02/exploding-rats-and-the-c-standard-vector/feed/ 0