Monthly Archives: January 2011

implicit declaration of function ‘sleep’

Following are the code which thorugh warning:

 sleep(2); //Warning: implicit declaration of function 'sleep'

<strong>Solution:<em>[NSThread sleepForTimeInterval:2.0];</em></strong>

Date Formatter

While working on an iPhone application recently, I needed to convert a date read from an XML stream that was in the following format: 20081122 to a nicely formatted string for display on the device: Saturday November 22, 2008.

How to get there from here is now obvious, however, when I first encountered this dilemma the solution wasn’t apparent. The reason being, there is significant depth in the Cocoa frameworks and half the battle in becoming proficient as an iPhone developer is to have an opportunity to explore the range of APIs. Albeit the solution was right under my nose the whole time, my first pass was to take a more traditional route of trying to parse the string and rebuild a more “traditional” date format which I could use to create a date object. So, skipping all that, here’s the proper solution…

If you’ve ever worked with dates in Cocoa, chances are you are familiar with the stringFromDate method of the NSDateFormatter. For example, the code below will convert the current date to a string that looks like this: Wednesday November 26, 2008

NSDate *date = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"EEEE MMMM d, YYYY"];
NSString *dateString = [dateFormat stringFromDate:date];  
[dateFormat release];

The trick is two-fold, the date format string to specify desired output, and the method stringFromDate to convert the date object to an NSString.

I’m sure you can see where I’m going with this…the solution I was looking for to convert a date (stored as a string) that was in a pre-defined format (i.e. 20081122) to a date object is as simple as using the method dateFromString. The primary difference is that the format string needs to represent the current format of the date that is to be read (versus the desired output format).

The code below converts a string that represents a date to an NSString object, with the output as follows: Saturday November 22, 2008:

NSString *dateStr = @"20081122";
 
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMdd"];
NSDate *date = [dateFormat dateFromString:dateStr];  
 
// Convert date object to desired output format
[dateFormat setDateFormat:@"EEEE MMMM d, YYYY"];
dateStr = [dateFormat stringFromDate:date];  
[dateFormat release];

How to proceed when MySQL is slow ?

It is of course too general a complain to say “MySQL is slow! What is wrong with my pages?”, but nonetheless, there exist a couple of things you can check if this happens to you

  • First obvious question: did your host upgrade or make changes to MySQL?
  • Second, any new or modified modules added?
  • Third, does your host have ‘log slow queries’ enabled for mysql so you can isolate which ones are causing the problems? When started with the –log-slow-queries[=file_name] option, mysqld writes a log file containing all SQL commands that took more than long_query_time seconds to execute. See The Slow Query Log.
  • Does this happen randomly or during certain time periods throughout the day?
  • Maybe you need to rebuild your indexes. To rebuild your indexes, the easiest way to do so for a MyISAM table is to use the following statement, which rebuilds the index file:
  • mysql&gt; REPAIR TABLE tbl_name QUICK;
    

    If you don’t have access to the MySQL prompt through a terminal, you can write a small PHP script that does the same. Copy the following code into a file and save it as, say, repair.php:

    &lt;?php
    require("config.php");
    $host = $dbhost;
    $database = $dbname;
    $username = $dbuname;
    $password = $dbpass;
    mysql_connect($host, $username, $password);
    @mysql_select_db($database);
    $res = mysql_query("repair table ".$prefix."_XXXX");
    if ($res) {
        echo $res;
    } else {
        print (mysql_error());
    }
    ?&gt;
    

    Dont’t forget to replace “XXXX” with the actual name (without the prefix!) of the table you are suspecting of causing you trouble. Read the table definitions in the nuke.sql file that came with your PHP-Nuke package under the sql directory (you used nuke.sql during installation to populate the database, see Section 3.2.4 and Section 3.4.5).

    Upload repair.php to the same directory on your web server where also config.php is in – and point your browser to it. Of course, you should delete it after you are done.

  • The phpBB software used for the standard Forum in PHP-Nuke, comes with a table, nuke_bbsearch_wordlist, that is used to store words that occur in forum posts. Due to the large size of your database, the nuke_bbsearch_wordlist table may have grown very large. By default phpBB does not include an index for that table. Lack of an index on nuke_bbsearch_wordlist can make your forum slow down. Running the SQL command below will increase the size of the nuke_bbsearch_wordlist table (could double it), but a performance increase is expected with the index.
    ALTER TABLE nuke_bbsearch_wordmatch ADD INDEX post_id (post_id);
    

    Run this during a time on your site when it is least busy. More records on that table means longer run time.

    If you find that this doesn’t work for you, you can remove the index with:

    ALTER TABLE nuke_search_wordmatch DROP INDEX post_id;
    
Tip Large Slow Query Logs
The slow query log can be used to find queries that take a long time to execute and are thus candidates for optimization . With a large log, that can become a difficult task. You can pipe the slow query log through the mysqldumpslow command to get a summary of the queries which appear in the log.

MySQL: Reset Auto Increament Number

I have a database table with a auto increment column for primary key. As the records being add and delete many times, the auto increment value will keep increasing.

Problem One:
If I have entered 10 records, and deleted 9th, 10th records. The next auto increment value will be 11, not 9.

Solution:
Run a query: ALTER TABLE tablename AUTO_INCREMENT = 1

This will reset the next auto increment value to current largest value in the auto increment column + 1. So, the auto increment value of next inserted record will start from 9.

Problem Two:
If I have entered 10 records, and deleted center records – 4th, 5th. I want to insert next record as 4th not 11th.

Solution:
Run the following query:
SET insert_id = 4;
INSERT INTO tablename VALUES ('blah', '...');

This will add the next record into record 4th.

The SET insert_id = #(where # is the next auto increment value you want to use) will reset the next auto increament value, the next query(INSERT) you run will use your choice of value.

Note: only effective for the immediate next query, one time.

How to get the DeviceId of iPhone from objective C

UIDevice *device = [UIDevice currentDevice];
NSString *deviceID = [device uniqueIdentifier];    //get the deviceID of the Phone

NSLog(“My Device ID is: %@”,deviceID); //print the device id in the console

iPhone Coding: Use NSBundle and avoid hard-coded paths

Listen up, iPhone coders, NSBundle is your friend. It lets you look in your main .app bundle and retrieve files without hardcoding paths. Avoid “/Application/MyProg.app/foo.png” and replace your absolute references with relative ones. This lets your users install your applications wherever they wish.

An NSBundle object locates your app in the local file system so you can access resources and use them in your programs. [NSBundle mainBundle] returns the object for your app. When you use the pathForResource: ofType: inDirectory: method, you can easily find the path to those resources. For example, to find the Default.png file in the top level of an iPhone or iPod touch application, use: [[NSBundle mainBundle] pathForResource:@"Default" ofType:@"png" inDirectory:@""]]. Couldn’t be simpler.

Skip the type argument (use @””) for resources without extensions.

How to capitalize the first word of the sentece in Objective C?

<code>NSString *nameStr = @"mohammad kalim !!"
</code>
<pre><code>nameStr </code><code>= [nameStr stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[nameStr substringToIndex:1] uppercaseString]];
</code>

How to calculate Rating in SQL

Rating Calculate formula?

You are probably better off having a single table in your database that just contains the votes of each user on each item being rated. This way you can ensure that each voter can only vote once for something. In order to calculate the total score, number of votes and average rating, you can do this:

sql Syntax
<ol>

	<li>

<div><strong>SELECT SUM(Votes), COUNT(Votes), AVG(Votes) FROM UserVotes</strong></div></li>


	<li>

<div><strong>WHERE Item = Whatever</strong></div></li>

</ol>

or something similar…

The Formula Used to Calculate Ratings

We are using the same true Bayesian estimate formula used by the Web Rating for calculating average ratings. The only difference is that our rating system uses multiple dimensions (presentation, graphics, usability, technical, and personal slant), so we apply the formula to each dimension by using the respective mean value of that particular dimension (C), take the sum of individual results, and divide this sum by the number of dimensions, which is five.

<span>   weighted rank (WR) = (v / (v+m)) * R + (m / (v+m)) * C

   where:
      R = average for the design (mean) = (Rating)
      v = number of votes for the design = (votes)
      m = minimum votes required to be listed in top 25 (currently 6)
      C = the mean vote across dimension
</span>

This formula normalizes scores, that is it pulls a particular score (R) to the mean (C) if the number of votes is not well above m. In other words, if a particular design has only a few votes above the minimum required votes to be listed in top 25 (m), the average score is decreased a little if it is above the mean, or increased a little if it is below the mean in accordance with the normal distribution rule of statistics.

Here is an example for a single dimension:

<span>   WR = (6 / 10) * 5.33 + (4 / 10) * 7.18 = 6.07
         |    |      |     |    |      |
         v   v+m     R     m   v+m     C
</span>

The formula normalizes the average rating of a relatively low rated design from 5.33 to 6.07 since the number of votes (v=6) is only slightly above the minumum required votes (m=4) and the mean across the dimension (C=7.18) is quite high. If, in the future, this particular design gets more votes, the difference between R and C will increase as the number of votes increase. The idea is that the more the votes, the more representative the average rating is. Please note that this example is only for one dimension. Different dimensions have different means (C).