Search This Blog

Wednesday, December 29, 2010

Generating runtime image in iPhone/ iPad

input color in int.

+ (UIImage *)shapeCircle:(int)color {

// create the bitmap context
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(nil,30,30,8,0, colorSpace,kCGImageAlphaPremultipliedLast);
CFRelease(colorSpace);

// set the fill color
//CGColorRef fillColor = [[UIColor blackColor] CGColor];
NSString *hexColor = [NSString stringWithFormat:@"%x", color];
hexColor = [[@"" stringByPaddingToLength:6 - [hexColor length] withString:@"0" startingAtIndex:0] stringByAppendingString:hexColor];
float r = [self hexToColorValue:[hexColor substringToIndex:2]];
float g = [self hexToColorValue:[hexColor substringWithRange:NSMakeRange(2, 2)]];
float b = [self hexToColorValue:[hexColor substringFromIndex:4]];

//fillColor = [[[UIColor alloc] initWithRed:1 green:0 blue:0 alpha:1] CGColor];
//CGContextSetFillColor(context, CGColorGetComponents(fillColor));
CGContextSetRGBFillColor(context, r, g, b, 1);
CGContextAddArc(context, 15.0f, 15.0f, 12.0f, 0, 360 * M_PI/180, 1);
CGContextFillPath(context);

//CGContextSetFillColor(context, CGColorGetComponents([[UIColor whiteColor] CGColor]));
CGContextSetRGBFillColor(context, 1, 1, 1, 1);
CGContextAddArc(context, 15.0f, 15.0f, 6.0f, 0, 360 * M_PI/180, 1);
CGContextFillPath(context);

// convert the context into a CGImageRef
CGImageRef imageRef = CGBitmapContextCreateImage(context);
CGContextRelease(context);
UIImage *image = [[UIImage alloc] initWithCGImage:imageRef];
CGImageRelease(imageRef);

return [image autorelease];
}

+ (float)hexToColorValue:(NSString *)color {
NSScanner* scanner = nil;
unsigned int cInt;
scanner = [NSScanner scannerWithString:color];
[scanner scanHexInt:&cInt];
return (float)cInt / 255;
}

Adding a toolbar to keyboard for textField and textView

textField and textView have a property inputAccessoryView which allows you to easily add a toolbar to the top of the keyboard to show your custom buttons.

- (IBAction)beginEditing: (id)sender {
CGFloat _width = self.view.frame.size.width;
CGFloat _height = 40.0;

// Create a new toolbar
UIToolbar *toolbar = [[[UIToolbar alloc] initWithFrame:CGRectMake(0, -_height, _width, _height)] autorelease];
// Create the necessary buttons
UIBarButtonItem *barButtonItemSubmit = [[[UIBarButtonItem alloc] initWithTitle:@"Submit" style:UIBarButtonItemStyleBordered target:self action:@selector(btnSubmitClicked:)] autorelease];
UIBarButtonItem *barButtonItemCancel = [[[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(btnCancelClicked:)] autorelease];
/*
By default the buttons that are added to the toolbar are left aligned.
To align them as you like, create a flexible space bar button and add it where you want.
*/
UIBarButtonItem *flexibleSpace = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease];
/*
Adding the flexible space in between will make both buttons float towards the opposite ends.
You can repeat the flexible space as many times and at positions to get the desired layout of buttons.
*/
[toolbar setItems:[[[NSArray alloc] initWithObjects:barButtonItemSubmit, flexibleSpace, barButtonItemCancel, nil] autorelease]];

if ([sender isEqual:myTextField]) {
myTextField.inputAccessoryView = toolbar;
}
else if ([sender isEqual:myTextView]) {
myTextView.inputAccessoryView = toolbar;
}
}


Assign the begin editing event of the text field to the above function.

For textview, you might need to do something like this:
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
if ([textView isEqual:myTextView]) {
[self beginEditing:myTextView];
}
return YES;
}

resignFirstResponder does not hide keyboard in presentModalViewController

For some great "Apple" reason, when the input elements are in a modal view controller, resignFirstResponder just loses the focus from the element. The keyboard stays visible.

After searching for a long time, I found 2 explanations for the same.
1. Its a bug!
2. Its a feature! Apple kept it that way to avoid the keyboard coming up and going down when switching between input elements in the modal form. B******T!

So the workaround I came up with is:
- (BOOL)textViewShouldEndEditing:(UITextView *)textView {
NSArray *arrWindows = [[UIApplication sharedApplication] windows];

if ([arrWindows count] > 1) {
UIWindow *keyboardWindow = [arrWindows objectAtIndex:1];
[keyboardWindow setHidden:YES];
}
return YES;
}

Monday, November 22, 2010

Adding new view to RootViewController in UISplitViewController

  1. Right click the blue icon in Xcode.
  2. Add new file > Cocoa Touch Classes > UIViewController subclass.
  3. Select all 3 checkbox options (Targetted for iPad, UITableViewController subclass, with XIB for user interface) (You could rearrange the file in correct locations under classes and resources).
  4. Open NewView.h. Add NSArray variable for populating the UITableView.
  5. Open NewView.m. Edit numberOfSectionsInTableView, numberOfRowsInSectioncellForRowAtIndexPath to populate the table form the NSArray variable.
  6. Open RootViewController.h. Add #import "NewView.h".
  7. Open RootViewController.m. Edit

    - (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NewView * NewView = [[NewView alloc] initWithNibName:@"NewView" bundle:nil];
    NewView.arrData = [[dataHolder objectAtIndex:indexPath.row] objectForKey:@"subdata"];
    [[NewView navigationItem] setTitle: @"Subdata"];
    [self.navigationController pushViewController:NewView animated:YES];
    [NewView release];
    /* When a row is selected, set the detail view controller's detail item to the item associated with the selected row.*/
    detailViewController.detailItem = [dataHolder objectAtIndex:indexPath.row];
    }
    Save and Run.

When an item is selected from the main root view, the table will slide to left to give way to your new view, with a back button. If the RootViewController is given a title, the title will be used for the back button.

To provide a title:
Open RootViewController.m In viewDidLoad, add
[self.navigationItem setTitle: @"Main View"];

Wednesday, June 09, 2010

Showing tabs of open sessions in screen

Screen is a very good terminal-multiplexer to allow multiple terminal sessions.

It is very useful when you are working on a remote machine through ssh.

More info about screen at: https://help.ubuntu.com/community/Screen

But it could be quite irritating when you have multiple sessions open and you have to cycle through them frequently since there are no tabs or status bar.

But, there is a solution for the same :)

Edit /etc/screenrc or ~/.screenrc and add the following line. Then start screen.

caption always '%{= kG}[ %{G}%H %{g}][%= %{= kw}%?%-Lw%?%{r}(%{W}%n*%f%t%?(%u)%?%{r})%{w}%?%+Lw%?%?%= %{g}][%{B} %D %Y-%m-%d %c:%s %{g}]'

Tuesday, February 23, 2010

PHP mail returns false on Fedora linux

While helping out a friend on a PHP installation, came across this issue.

Everything worked fine on his development server. But on his deployment server, the mail function returned false and hence no mails were sent out.

After some debugging found that the issue was with permission for httpd on sendmail.

vim /var/log/maillog had error NOQUEUE: SYSERR(apache): /etc/mail/sendmail.cf: line 0: cannot open: Permission denied

After spending some time on Google, came across this command.
# getsebool -a | grep sendmail
httpd_can_sendmail --> off

So the issue was that the apache user did not have permissions to send mails using sendmail.

Ran the following command
# togglebool httpd_can_sendmail

and everything worked fine.

Friday, February 12, 2010

Clone input element and add to hidden form using jQuery

If a file input element is placed in a form and you would like to upload it using a hidden form, the first thought would be


var file_elem = jQuery('#fileElem');
var cloned = file_elem.clone();

var hdn_frm = jQuery('#frm');
hdn_frm.append(cloned);

hdn_frm.submit();


This would work in firefox. But it would not work in IE.

Editing the file form field is a security risk and thus is disabled on most browsers.

A workaround would be:


var file_elem = jQuery('#fileElem');
var cloned = file_elem.clone();
cloned.id = 'fileElem1';
var hdn_frm = jQuery('#frm');

// Put the cloned element directly after the real element
// (the cloned element will take the real input element's place in your UI
// after you move the real element in the next step)
cloned.insertAfter(file_elem);
file_elem.hide();

file_elem.appendTo(hdn_frm);
hnd_frm.submit();


If you are using ajaxSubmit for form, in case error message is returned or if you stay on the form, the user could change the file being uploaded. Since the current element being seen is the cloned one, the desired result would not be achieved.

For this, after the form submit, reset the file elements.


var file_elem = jQuery('#fileElem');
var cloned = jQuery('#fileElem');

file_elem.insertBefore(cloned);
file_elem.show();
cloned.remove();

Rename Drupal core module tab titles

Drupal default user profile page shows tabs "View" & "Edit". If you want to add tab to the user profile page the original tabs could be confusing. Copy the following function to your custom module and it should rename the original tabs.


function user_menu_alter(&$items) {
$items['user/%user/view']['title'] = 'View Profile';
$items['user/%user_category/edit']['title'] = 'Edit Profile';
}


To remove tabs completely refer http://drupal.org/node/483324

Tuesday, February 02, 2010

HipHop for PHP: Move Fast

http://developers.facebook.com/news.php?blog=1&story=358

<CLIP>
With HipHop we've reduced the CPU usage on our Web servers on average by about fifty percent, depending on the page. Less CPU means fewer servers, which means less overhead.
</CLIP>
<CLIP>
HipHop for PHP isn't technically a compiler itself. Rather it is a source code transformer. HipHop programmatically transforms your PHP source code into highly optimized C++ and then uses g++ to compile it. HipHop executes the source code in a semantically equivalent manner and sacrifices some rarely used features - such as eval() - in exchange for improved performance. HipHop includes a code transformer, a reimplementation of PHP's runtime system, and a rewrite of many common PHP Extensions to take advantage of these performance optimizations.
</CLIP>

Interesting thing to observe here is that people find it less expensive (and quicker) to develope applications in 'simple' languages like PHP. For speed, rather than (mannually) porting application code which is expensive in terms of time and money (and also error prone), people prefer to change the runtimes, use automated porting (HipHop style) or even throw more hardware at it.

Slash doted at
http://developers.slashdot.org/story/10/02/03/003249/Facebooks-HipHop-Also-a-PHP-Webserver?art_pos=2

<Slashdot>
"As expected, Facebook today announced a new runtime for PHP, called HipHop. What wasn't expected were a few key revelationsdisclosed today by Facebook developer David Recordan. As it turns out Facebook has been running HipHop for months and it now power 90 percent of their servers - it's not a skunkworks project it's a Live production technology. It's also not just a runtime, it's also a new webserver. 'In general, Apache is a great Web server, but when we were looking at how we get the next half percent or percent of performance, we didn't need all the features that Apache offers," Recordon said. He added, however, that he hopes an open source project will one day emerge around making HipHop work with Apache Web servers.'"
</Slashdot>

Previous related news:
http://www.sdtimes.com/blog/post/2010/01/30/Facebook-rewrites-PHP-runtime.aspx

It would be interesting to see it's made available in open-source and can be applied to drupal.

<from slashdot>
Facebook has gotten fed up with the speed of PHP. The company has been working on a skunkworks project to rewrite the PHP runtime, and on Tuesday of this week, they will be announcing the availability of their new PHP runtime as an open source project. The rumor around this began last week when the Facebook team invited some of the core PHP contributors to their campus to discuss some new open source project.
</from slashdot>

Slash doted at
http://developers.slashdot.org/story/10/01/31/0252201/Facebook-Rewrites-PHP-Runtime-For-Speed?art_pos=14

Saturday, January 30, 2010

How to check if an element is in current viewport of webpage using jQuery

var $elem = jQuery('#myElem');

jQuery(window).scrollTop() > $elem.offset().top
checks if the element has been scrolled up.

($elem.offset().top + $elem.height()) > jQuery(window).height()
checks if the element is below the current view port.

If any of the conditions is true, the element is currently not visible completely.

You can bring it in view using
jQuery('html,body').animate({scrollTop: $elem.offset().top}, 500);