Tekpub’s Mastering Linq Challenge

9. January 2010

Update 6: When you think you’re done, think twice. The code should be valid even when the range contains some negative value

var primes =
    Enumerable.Range(-10, 34).Aggregate<int , IEnumerable<int>>(new int[] {},
                         (list, x) =>
                         x >1 && list.All(y => x%y != 0)
                             ? list.Union(new[] {x})
                             : list);

End update

Update 5: Long story short, Linq is not the type of thing you’d use when finding primes.

Update 4: Removing “if” in expense of reduced speed

Enumerable.Range(1, 34).Aggregate<int , IEnumerable><int>>(new int[] {},
                         (list, x) =>
                         x != 1 && list.All(y => x%y != 0)
                             ? list.Union(new[] {x})
                             : list);

End update

Update 3: Making the code a bit faster by dividing only primes found so far

var primes =
    Enumerable.Range(1, 34).Aggregate(new List<int>(), (list, x) =>
{
    if(x!=1&&list.All(y=>x%y!=0))
    {
        list.Add(x);
    }
    return list;
});

End update

Update 2: Using all, one can have one step cleaner code.

var primes =
        Enumerable.Range(1, 34).Where(x =>
                         x == 2 || (x != 1 &&
                                    Enumerable.Range(2, (int) (Math.Sqrt(x)))
                                                           .All(y=>x%y!=0)));

End update

Update: Using any, one can make a bit faster implementation of it

var primes =
                Enumerable.Range(1, 34).Where(x =>
                                              x == 2 || (x != 1 &&
                                                         !Enumerable.Range(2, (int) (Math.Sqrt(x)))
                                                             .Any(y=>x%y==0)));

End update

Here is my solution to TekPub’s Mastering Linq Challenge appeared on Justin Etheredge’s blog

            var primes =
                Enumerable.Range(1, 34).Where(x =>
                                              x == 2 || (x != 1 &&
                                                         Enumerable.Range(2, (int) (Math.Sqrt(x)))
                                                             .Where(y => (x%y) == 0).Count() == 0));
Not very efficient, but simple :)

Testing on Android

6. January 2010

androidFor the last couple of months, I have been working on Android platform as part of Software Engineering course(more on that later, i hope). Even though there are a lot of things I don’t like about android (like XML layouts and the ids of widgets being held in some other class etc but perhaps this is just me), I overall find it a good platform to work with.

What I really liked in Android is that it provides an Out-of-the-box environment for easy testing android applications. I don’t know how Windows Mobile projects handle this situation, but what android does is that it executes the test in the context of virtual machine. Android integrates nicely with JUnit framework, which is the java brother of NUnit.

What is more interesting than this is that Android also has UI testing framework. Being a person who hasn’t written UI tests much (as in none), I can’t say if it is a good one or not. I just liked the feature that came out of the box.

I have created a simple Activity (you can think of it as a window, but not exactly)

public class SampleActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final Button b=(Button)findViewById(R.id.Button01);
        final EditText t=(EditText)findViewById(R.id.EditText01);
        b.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                t.setText(t.getText().toString()+"hello");
            }
        });
    }
}

And created the following test.

public class SampleActivityInstrumentation extends
		android.test.ActivityInstrumentationTestCase2 {

	public SampleActivityInstrumentation() {
		super("com.myandroid", SampleActivity.class);
		// TODO Auto-generated constructor stub
	}

	public void test_OK_button_appends_hello() throws Throwable {
		SampleActivity tne = (SampleActivity) getActivity();

		final Button btn=(Button) tne.findViewById(com.myandroid.R.id.Button01);
		final EditText titleEdit = (EditText) tne.findViewById(com.myandroid.R.id.EditText01);
		runTestOnUiThread(new Runnable() {
			public void run() {
				titleEdit.performClick();
			}
		});
		sendKeys("H E L L O");
		runTestOnUiThread(new Runnable() {
			public void run() {
				btn.performClick();
			}
		});
		assertEquals("hellohello",titleEdit.getText().toString());
		
	}

}

I found it very cool to have such a nice integration. More than that is that they use proven testing framework out of the box.

GRE Epic Fail

3. December 2009

I won’t write about how good or bad GRE exam is, I will write about how bad their customer service is.

In my previous post, I have written that they locked my account. It is probably 10+th call, and still my account is locked. Everytime I call, after approximately 20 mins of waiting, the customer representative sends an email to technical department about my issue, and I get my password has been reset. They don’t say what my new password is, and when i try forgotten password again, it again says your account has been locked.

I believe that the problem occurs because everytime I call, I talk with “different” representative. Presumably, everytime he mails to technical support, the mail is processed by another person. When I asked if I could talk directly with a technical support guy, or mail to a “specific” person, I get the answer “unfortunately”. This is a really bad way of serving to the customer.

Stupid Password Policies

23. November 2009

In last few weeks, I have suffered from stupid imagepassword policies. One of them was a bank.

They have strange password policies, they require numbers, capital letter and a small letter in the password, and they limit their password to be 6 chars long.

The other one is for ETS GRE. Recently, they opened up a new web site through which you can learn your GRE scores and order test score submission. Once again, I forgot my password. This time, I tried the “Forgotten password” option and appearently, they failed providing a reliable system here. I entered everything right, and came to password change screen. When I submitted, I got “technical error occured”. After 3rd or 4th time, it now says “account locked”. Now I have to make international phone calls to order my GRE scores.

I just don’t remember this kind of passwords that have silly requirements. I had a password in mind that I use for my mail which is around 30 chars long, and it is strong enough for me. If I need to ensure security, i specialize them in a way that i remember. I don’t need your stupid policies to ensure my security. If you want your inexperienced users to have secure password, that is fine, but please don’t restrict me or have a reliable forgotten password system..

Feature Request For Visual Studio 2010: Local Revision History

19. November 2009

This feature is a life saver. I was working on my school project, and I was drawing UML Diagram with an Eclipse plugin. All of a sudden, the diagram went off, and all I saw was a screen with blank class boxes. I was going crazy, trying to find differences between a valid document and a buggy one with my eyes etc. Then i remembered a feature that Eclipse had: Local Revisions.

Every time you modify a file, Eclipse saves a copy of the old one in .metadata folder of the project. I was unable to reach the history in the IDE, but i can see the changes in the history folder.

image

The last version that worked was somewhere around 10 PM, and I manually copied the contents of that time period.

And now I can see my diagrams.

 

Admittedly, this is what SCM is for, but think of it that way: you wouldn’t commit a diagram until it is not near complete. You also wouldn’t want to waste 1 hour just to redraw the diagram.

My request is that they incorporate this small feature into VS 2010, or perhaps some good soul can do this as a free plugin into R# or directly into VS.

What was I up to? – 2 Months of no blogging?

19. October 2009

Long time no see… Things have been hectic in last 2 months. While I had a pretty good plan for the August and October, an unexpected internship opportunity in the US showed up. Thins like Visa interview and accommodation was almost a blocker, but I was able to dealt with them. I was lucky that I was qualified for an “Urgency Visa”.

Anyway, in the month of September, I was an intern in a university, and worked on several scientific projects. The lab that I worked at was mainly working on autonomous systems, and path planning algorithms. There I had studied those algorithms a bit and also involved in software design for several projects.

As soon as I went there, I found myself in an atmosphere of competition. The competition was about designing an algorithm so that the drone we own can go from one point to another without crashing any other drones or obstacles in the stage. The behavior of those drones was semi-stochastic and depending on that preknowledge given to us, we are asked to implement this algorithm. Even though we couldn’t make into competition, I can say that I learnt a lot.

My first task was to implement this semi-stochastic behaviors of enemy drones. It was pretty fun, and it taught me how seemingly easy thing can contain a lot of challenges. While dealing with this stuff, i learnt some other stuff regarding to games, which i hope to blog about.

Here is the work that I had after a short while

image

 

My other task was to implement a 2D visualizer for the drones. The data was coming from a system know as Vicon which is used to track objects. It could give the orientation data with up to 1 cm precision, which was pretty cool. This task took only a few days and it was easy.

In the last few weeks, while dealing with other minor tasks, like programming the rover, or fixing bugs in our competition code, I started designing a 3D visualizer using XNA for the lab as a hobby project.  Below is a view from one of the cameras. There are several other cameras and also a dirty console implementation.

image

The future of this project is more likely to be a simulator, with a physics engine.

Nowadays, I am really busy with doing homeworks and getting ready for graduate school applications. They take a lot of time and a lot of money (standardized tests like TOEFL, GRE). I hope to blog about those too.

I hope this feature will be my boost post, and i hope to continue blogging regularly.

My Thoughts on ORM comparisons

21. August 2009

I am a bit late to the party but there we go.

Last several days, there have been a hot debate on the performance and capability of NH vs some other commercial/noncommercial ORMs. This issue has been discussed both in NHibernate Developer List and in Ayende’s blog. I have recently noticed another benchmark between NH and EF, which I hope to address, too.

Fallacies of benchmark

What I have seen in those benchmarks is the wrong use of ORMs. This statement has two aspects: Wrong use of ORM and wrong use of NH itself.

In ORM, you don’t use it to do bulk operations. And 0.001 second difference will not differ anything in your application. If it does, you don’t also use RDBMS, you use something else.

There is no point on making a loop of thousands of iterations which saves an entity. Davy has well pointed out that this has a lot of implications in NHibernate, unlike some other ORMs. First of all, NHibernate first-level cache will be in action and it will fill the cache with each item saved. Secondly, as NH makes use of POCO it has no mechanism of things like INotifyPropertyChanged, it has to compare the old to the new value. As you may guess, the more entity you have, the longer it will take. No exception. If you want to leave first-level cache out of the game, you use StatelessSession feature of NHibernate, no exception. Actually when you check Fabio Maulo’s post you’ll see it can even become faster without Stateless Session.

Another point I have noticed in both benchmarks is that they are/were not fair. If I compare it to EF, lets say, ctx.SaveChanges() will batch the chages and send the query to the database in one go. NH has this feature, as Ayende already pointed out, since 2006. However, NH by default doesn’t make use of it, and this is not a bug, it is a feature. You have to use setting to enable it.

Benchmark the community, too

NHibernate has a big community, and great minds as committers. It really does matter. Let me give you some statistics about NHibernate development and its community

Here is the commit statistics.

image 

It is one of the most active projects in .net environment. The image above doesn’t include the contrib projects. A great kiss goes  to Fabio Maulo for his massive efforts.

Let’s look at discussion group, shall we?

image

Do you know any other group with that activity? I don’t know.

 

In addition, NHibernate gives you more than _ANY_ ORM can give. It gives you a lot of extensibility points which can be used in a lot of scenario. Validator, Search, Spatial, Shards to name a few.

In conclusion

NHibernate is the obvious winner.

Even Developers Make Art

12. August 2009

poster1ciktigh6

Found this today last month. If you click on the picture, you’ll see that there are parts that are composed of other images.

I prepared a folder with full of small pictures, and a preprocessor scanned all files in that folder, took their R G and B averages and saved it to a database.

I then divided the big picture into small chunks (the small, the better, but also requires more photos in order not to have repetitions). I took R G B averages of each part and computed the distance from each of the items stored in DB(for efficient access, they are fetched to memory). The distance formula is simply the Pythagoras theorem.

clip_image002[6]

The closer it is, the better it fits to the place. However, there is one problem. Neighbor parts tend to have a correlation (they share similar colors), and if we use the same picture for neighboring cells, it doesn’t look good(above probably left from an early version). What I did was to take closest 10 and select randomly.

The rest is a bit of Image processing(not processing but replacing, lets say)

I had fun doing it :) Art is everywhere even if I don’t think I like it :)

YAGNI in Real Life

6. August 2009

One of my friends wanted to have a cheap SVN hosting (actually wanted to install svn to his hosting, but this part is irrelevant to what I am going to say). I offered him some alternatives including Assembla.

Then the topic came to OpenSource SVN hosting, and he believed SourceForge is superior to Google Code. While I can understand his claims, I have objections to it. As I am contributing to various opensource projects, and being an active user of opensource, I have a bunch of projects in my “OpenSourceProjects” folder. Most of them use SVN, rarely CVS. Most SVN projects was hosted under either Google Code or Sourceforge, some Codeplex.

To begin with, having used’em all, I have pretty much experience with both, at least as a user.

One argument that my friend used that SF has many features. Looking at google code interface, I have to admit that this is true. However, those blown features are not at my center of interest. When I develop the project, I want speed. SF doesn’t give me that much smooth experience, I remember having to update a project 5+ times just to download, and less frequently trying to commit 2+ times. Google, on the other hand, didn’t cause any problem regarding to its SVN usage.

Another problem that we faced recently is that the download counts of NHibernate.Linq project was shown as 0 a week after we released it. I am pretty sure (:) ) that it had thousands of downloads since then, but it is not seen on SF.

To sum up what I have said, I prefer quality of service over the features provided most of the time. Having features that I perhaps will never ever use is “relevant” to this story, it is YAGNI.

DELL increases the Fan speed to hide problems - Yet Another Dell Fail?!

6. August 2009

I got my laptop repaired, thankfully, with the help of the Customer Care (Thank you Mustafa!)

It seems like my laptop suffered from the same problem many others faced. I had my warranty information disappearing from time to time. Because of this reason, I had chance (?) to make phone calls to the USA DELL, and learnt at that time that the issue occurred due to non-updated BIOS. I thought it was something different but now I see that that new BIOS version just increases the fan speed in order to postpone the problem, perhaps till the warranty expires. I am not an expert on Ethics but I believe that this issue is non ethical as they try to hide the real problem instead of fixing it. Another drawback of increased fan is the increased power consumption and therefore less battery life.

As a result of many many complaints, DELL decides to add 1 year extension to limited warranty. Mine still shows 2010 but I hope i’ll figure it out.

Dell lost my respect, even if this is NVIDIA’s fault, Dell’s attitude toward customers is not acceptable.

I hope that I won’t have to buy DELL in some near future.

, ,