Tuesday 10 November 2015

XCODE clean cmd

#!/bin/bash
rm -frd ~/Library/Developer/Xcode/DerivedData/*
rm -frd ~/Library/Caches/com.apple.dt.Xcode/*
echo done

Wednesday 6 May 2015

OC: Swizzling: Category a class and override a method, not able to call super method, so Swizzling is the solution for you.

Hello Objective C, Apple iOS / Mac lovers,

Swizzling a technique may be useful for you in some scenario. Think a case If a super class method you want to override, but problem with that, That super class objects are already created in project. 
Now we have two ways: 
First: Traditional way, inherit that super class and override that method. But problem with this way is you have to manually change the new child class name from super class name. 
Class C1 has a method M1 which we want to override,
We made another class C2 : C1, and override method M1. 
In your project there are already many other classes have a object of C1. 
C1 *c11, *c12, *c13;
Now in find all class object which is Made of C1 and now replace to C2,
C2 *c11, *c12, *c13;
Don't you think it is too much of laborious work. Now consider the second way,

Second: Category concept in Objective C, Ok you can Category class C1 and override method M1. But Now there is another problem arises. You cannot call original method C1, because it is replaced by override method. It does mean, If you have 15 lines of code in M1 in C1, and Category CT1 override method M1, that 15 lines of codes is not available. So you have now two ways to solve:
A: You can rewrite those 25 lines of code in Category CT1 method M1. which is like again laborious work, less laborious but still you are a labour.
B: (RECOMMENDED Swizzling) Choose Swizzling technique to achieve that. In simple word, inheritance and category concept is now mix. In category if you will able to call super method then you don't have to write those 15 lines of code. This technique may be good for you if you are thinking of custom modification in lots of methods and you don't want to inherit because class name change is really pain. And you don't want to copy paste code of your super class overridden method. 
I think it is very approachable concept 

Wednesday 22 April 2015

Py: Xcode: Add ARC disable flag to multiple files in Xcode project

I'm assume that Cocos2d files need to be ARC disables and each file is start with CC. Then If you have hundreds of files and you want to add ARC disable flag to each file, then my method could help you in quick way. Thanks for reading.
Beware Please take backup of your project before running this script.

Monday 20 April 2015

Set UIImage by setting color name

#define UIColorFromRGBHex(rgbValue) \
  [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
                  green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
                   blue:((float)(rgbValue & 0xFF))/255.0 \
                  alpha:1.0]


#define UIColorFromRGB(nRed,nGreen,nBlue) \
  [UIColor colorWithRed:(nRed)/255.0 \
                  green:(nGreen)/255.0 \
                   blue:(nBlue)/255.0 \
                  alpha:1.0]

@interface UIImage (imageWithColor)

+ (UIImage *)imageWithColor:(UIColor *)color;

@end


@implementation UIImage (imageWithColor)

+ (UIImage *)imageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

@end


[imageView setImage:[UIImage imageWithColor:UIColorFromRGB(255,0,0)]];

Thursday 16 April 2015

What is Error *error, Error **error and &error?

Let us consider below code, here we are passing a NSString pointer to pointer object. Which is same as call by reference in C language. But in Objective C we are taking every Object as reference type so taking pointer of an pointer object we need to write it as NSString **, not like NSString *.

In simple word if you understand the below code as Call by reference and call by value concept in Objective C. You can easily find out that why most of the methods are defined as Error **error instead of Error *error. We all know that In C and Objective C method can return only single value as return type. So put value in Error we need a pointer of Error.
Therefore in Objective C we passing Error ** as &error. It is all syntactical thing related to Objective C. Concept is the same as C language calling by reference and value.
Voila for reading this

-(void)changePointerOfString:(NSString **)strVal {
        *strVal = @"New Value";
}

-(void)changeOfString:(NSString *)strVal {
        strVal = @"New Value";
}


-(void)caller {
        NSString *myStr = @"Old Value";
        // myStr has value 'Old Value'
        NSLog(@"%@", myStr);

       [self changeOfString:myStr];
       // myStr has value 'Old Value'
       NSLog(@"%@", myStr);
       
       [self changePointerOfString:&myStr];
       // myStr has value 'New Value'
       NSLog(@"%@", myStr);
}

Sunday 12 April 2015

Ultra sonic distance test on raspberry pi

Our Motive to test ultra sonic waves, when object detect blink a led to show. Print the distance of object.  I have added a LED to show up the power is ON, one LED is check for pulse checking, and last LED will blink when object will detect. Object detection distance is set to 75 cm (.75m).

Monday 30 March 2015

Py: Temperature info update speaker out after some time automatic in mac os x

Basically the concept is simple, we are going to write few lines of code in python to get temperature from some URL (openweathermap.org). Then make a string which should speak out by speaker.
Then finally make this python script into cron job into your Mac OS X.

Step 1: Write simple python script code

import urllib # Web service fetch
import json   # JSON parse 
import os     # text to speech convert

## get data from server
url = 'http://api.openweathermap.org/data/2.5/weather?q=Jaipur,In&units=metric'

u = urllib.urlopen(url)

## json parse 
data = json.load(u)


## make final string which should speak out
finalMessage = 'In '+data['name']+ ' temprature is '+ str(data['main']['temp']) + ' celcius. Forcasting says it is expacting '+data['weather'][0]['main']


### finally text to speak out
os.system("say "+ finalMessage)
#os.system("echo "+ finalMessage)

Step 2 : Check the program is working
python weather.py

Amazon EC2 Cloud setup (php+mysql)

Friday 27 March 2015

how can I check if a Gyroscope is present on iOS device?

- (BOOL) isGyroscopeAvailable
{
#ifdef __IPHONE_4_0
    CMMotionManager *motionManager = [[CMMotionManager alloc] init];
    BOOL gyroAvailable = motionManager.gyroAvailable;
    [motionManager release];
    return gyroAvailable;
#else
    return NO;
#endif

}

Get IP address of iOS Device though program

#include <ifaddrs.h>
#include <arpa/inet.h>

- (NSString *)getIPAddress {

    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];

                }

            }

            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;

} 

Sunday 22 March 2015

Parallax effect in iOS

Parallax effect demo

what is Parallax effect?
read from here : http://en.wikipedia.org/wiki/Parallax But in term of programming, we can simply say varing speed/size of two different visible objects shows parallax effect. Now a days in web sites and mobile application it is most common attractive point.
So How to achieve this?
One point is that just varing speed or size of two visible object, shows parallax effect. So lets assume a situation where scrollview has a image at top and when scroll down it must zoom up to center, and when scroll up image must be vary with different speed (should be slow).

Monday 16 March 2015

Use iOS 8 default blur view

// -- add blur effect
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    
    UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    
    [blurEffectView setFrame:self.view.bounds];
    
    
    [self.view addSubview:blurEffectView];

    //[self.view insertSubview:blurEffectView atIndex:0];

Thursday 12 March 2015

UIImagePickerController has iPad issue in iOS 8 : Attempt to present on which is already presenting (null)


I think this is because in iOS 8, alert views and action sheets are actually presented view controllers (UIAlertController). So, if you're presenting a new view controller in response to an action from the UIAlertView, it's being presented while the UIAlertController is being dismissed. I worked around this by delaying the presentation of the UIImagePickerController until the next iteration of the runloop, by doing this:

[[NSOperationQueue mainQueue] addOperationWithBlock:^{
    // just add picker code here and it will work fine.
}];

Image Popup in popover view : small popup in UIView

- (IBAction)btnShowImage:(UIButton*)sender
{
//    Declare below declaration in .h file
//    UIPopoverController  *popoverVC;
    
    
    if([popoverVC isPopoverVisible])
    {
        //close the popover view if toolbar button was touched
        //again and popover is already visible
        //Thanks to @chrisonhismac
        
        [popoverVC dismissPopoverAnimated:YES];
        return;
    }
    
    //build our custom popover view
    UIViewController* popoverContent = [[UIViewController alloc] init];
    
    UIView* popoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 250, 250)];
    
    popoverView.backgroundColor = [UIColor whiteColor];
    
    popoverContent.view = popoverView;
    
    
    
    ////-- show image in popover view
    GPImageView *imgView = [[GPImageView alloc] initWithFrame:CGRectMake(10, 10, 230, 230)];
    
    NSString *imgURL = [SiteAPIURL stringByAppendingFormat:@"resizeImage.php?width=460&height=460&imagename=%@", dictCustomer[@"photo"]];
    
    [imgView setImageFromURL:imgURL
       showActivityIndicator:YES
               setCacheImage:YES];
    
    [popoverView addSubview:imgView];
    
    
    
    //create a popover controller
    popoverVC = [[UIPopoverController alloc] initWithContentViewController:popoverContent];
    
    popoverVC.contentViewController.preferredContentSize =  CGSizeMake(250, 250);
    
    [popoverVC presentPopoverFromRect:sender.frame   // did you forget to call this method?
                               inView:self.view
             permittedArrowDirections:UIPopoverArrowDirectionLeft
                             animated:YES];
}

Tuesday 3 March 2015

SNV terminal command MacOSX Subversion-Client-1.8.11_10.10.x

SVN
export PATH=/opt/subversion/bin:$PATH

//check out to pwd (.)
svn --username test --password 123 co https://192.168.1.40/svn/android

//push android/ to server
svn import -m "New Import"  android/ https://test@192.168.1.40/svn/android
--------------------------------------------------------------------------------------------

Make another build SDK (like iOS 6.1 add to XCode 5 where iOS7 sdk already available) in exsiting XCode SDK

Macintosh HD ▸ Applications ▸ Xcode5.app ▸ Contents ▸ Developer ▸ Platforms
STEP 1 : OPEN FINDER
STEP 2 : PRESS
CMD+SHIFT+g  
STEP 3 : PASTE BELOW LINE
/Applications/Xcode.app/Contents/Developer/Platforms
STEP 4: PASTE THE COPIED FIELES ON THAT FOLDER

Monday 2 March 2015

get all files in nested directory in iOS Objective C

NSArray *arrayFilesPath = [self openEachFileAt:DOCUMENT_PATH];
NSLog(@"All path %@", arrayFilesPath);
- (NSMutableArray*)openEachFileAt:(NSString*)path {
    NSString* file;
    
    NSMutableArray *arrayFilePath = [NSMutableArray new];
    
    NSDirectoryEnumerator* enumerator = [[NSFileManager defaultManager] enumeratorAtPath:path];
    
    while (file = [enumerator nextObject])
    {
        // check if it's a directory
        BOOL isDirectory = NO;
        
        [[NSFileManager defaultManager] fileExistsAtPath: [NSString stringWithFormat:@"%@/%@",path,file]
                                             isDirectory: &isDirectory];
        if (!isDirectory)
        {
            // open your file …
            [arrayFilePath addObject:[NSString stringWithFormat:@"%@/%@",path,file]];
        }
        else
        {
            [arrayFilePath addObjectsFromArray:[self openEachFileAt: file]];
        }
    }
    
    return arrayFilePath;
}

Sunday 1 March 2015

rename files in folder using python script

import os
# a~ipad.png to a.png
[os.rename(f, f.replace('~ipad', '')) for f in os.listdir('.') if not f.startswith('.')]

Friday 13 February 2015

speaking ios iphone device ios8

#import 
-(void)speak:(NSString*)message {
    AVSpeechSynthesizer * synth = [[AVSpeechSynthesizer alloc] init];
    AVSpeechUtterance * utterance = [[AVSpeechUtterance alloc] initWithString:message];
    [utterance setRate:AVSpeechUtteranceMaximumSpeechRate *.3f];
    [utterance setVolume:1.0f];
    [utterance setPitchMultiplier:-3.0f];
    [utterance setVoice:[AVSpeechSynthesisVoice voiceWithLanguage:@"en-IE"]];
    [synth speakUtterance:utterance];
}

iOS8 / iOS 7 complete register for remote notifications

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
    if ([application respondsToSelector:@selector(registerUserNotificationSettings:)])
    {
        // use registerUserNotificationSettings
        ////---- push notification register
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
    else
    {
        // use registerForRemoteNotifications
        ////---- push notification register
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
         (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
        
    }
#else
    // use registerForRemoteNotifications
    ////---- push notification register
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
     (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
    
#endif

Tuesday 10 February 2015

matching UINavigationBar color to your view controller object

[[UINavigationBar appearance] setBarTintColor: UIColorFromRGB(0x00a2ff)];

[searchBar setBackgroundImage:[UIImage imageFromColor:UIColorFromRGB(0x17aafe)]];

17aafe − 00a2ff = 1707ff



remove 1px line under uinavigationbar ios

@implementation UINavigationController(removeLine)

- (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    
    for (UIView *subview in view.subviews)
    {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        
        if (imageView)
        {
            return imageView;
        }
    }
    
    return nil;
}

@end



// where you need to hide that line 
UIImageView *imgViewNav = [navController findHairlineImageViewUnder:navController.view];

// hide     
imgViewNav.hidden = YES;

// show
imgViewNav.hidden = NO;


Touch Id integration in iOS

#import <localauthentication ocalauthentication.h>

- (void)authenicateButtonTapped:(id)sender {
   LAContext *context = [[LAContext alloc] init];
 
   NSError *error = nil;
   if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
       [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
               localizedReason:@"Are you the device owner?"
                         reply:^(BOOL success, NSError *error) {
 
           if (error) {
               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                               message:@"There was a problem verifying your identity."
                                                              delegate:nil
                                                     cancelButtonTitle:@"Ok"
                                                     otherButtonTitles:nil];
               [alert show];
               return;
           }
 
           if (success) {
               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Success"
                                                               message:@"You are the device owner!"
                                                              delegate:nil
                                                     cancelButtonTitle:@"Ok"
                                                     otherButtonTitles:nil];
               [alert show];
 
           } else {
               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                               message:@"You are not the device owner."
                                                              delegate:nil
                                                     cancelButtonTitle:@"Ok"
                                                     otherButtonTitles:nil];
               [alert show];
           }
 
       }];
 
   } else {
 
       UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                       message:@"Your device cannot authenticate using TouchID."
                                                      delegate:nil
                                             cancelButtonTitle:@"Ok"
                                             otherButtonTitles:nil];
       [alert show];
 
   }
}

Monday 2 February 2015

Simple Neural Network training and testing in python

Other useful links

Good concept making
http://deeplearning.net/tutorial/

http://stackoverflow.com/questions/2276933/good-open-source-neural-network-python-library/3143318#3143318

https://code.google.com/p/neurolab/

http://stackoverflow.com/questions/13434854/how-to-create-basic-neural-network-in-python-pygame

http://pybrain.org/docs/

Lets make the world more beautiful. We are artist, lets code a new world. Hello world.
- Steve Jobs

We can use it to weather predication, forecasting models, stock market predictions etc.

Thursday 29 January 2015

Play Movie Player in landscape mode ios8

/*---------------------------------------------------------------------------
 *    Load movie player from your viewcontroller
 *--------------------------------------------------------------------------*/
- (void)loadMoviePlayer
{
 // Play movie from the bundle
    NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"mp4" inDirectory:nil];
    
 // Create custom movie player
    moviePlayer = [[CustomMoviePlayerViewController alloc] initWithPath:path];
    
 // Show the movie player as modal
  [self presentViewController:moviePlayer animated:YES completion:nil];
    
 // Prep and play the movie
    [moviePlayer readyPlayer];
}


Wednesday 28 January 2015

sizewithfont:constrainedToSize:lineBreakMode: deprectataed in HUD

replace this text
CGSize labelSize = [detailsLabel.text boundingRectWithSize:CGSizeMake(frame.size.width - 4*margin, maxHeight)
                                                               options:NSStringDrawingUsesLineFragmentOrigin
                                                            attributes:@{NSFontAttributeName:detailsLabel.font}
                                                               context:nil].size;

Tuesday 27 January 2015

Code execution time in ios

NSDate *methodStart = [NSDate date];

////---  code to calculate execution time

NSDate *methodFinish = [NSDate date];
NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:methodStart];
NSLog(@"executionTime(seconds) = %f", executionTime);

Tuesday 13 January 2015

Post data to server in iOS [Image + data fields ]


// URL
NSString *strURL = [SiteAPIURL stringByAppendingFormat:@"AddChild.php"];


// field values to post [text]
NSDictionary *parameterToAdd = @{@"UserId":userID,
@"ChildFName":[txtViewFName.text trim],
@"ChildLName":[txtViewLName.text trim],
@"SafetyZone":isSafetyZone?@"YES":@"NO",
@"AlarmTone":lblAlarmToneName.text,
@"ChildId":@"0"};

// image to post [Data / image ] ==>>is used to send image;
UIImage *imgToSend = imgViewPickerPhoto.image;
[postBody appendData:[@"Content-Disposition: form-data; name=\"Image\"; filename=\"image.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];


whole code

Wednesday 7 January 2015

Python web server

from pprint import pformat
from wsgiref.simple_server import make_server

def app(environ, start_response):
    headers = {'Content-Type': 'text/plain; charset=utf-8'}
    start_response('200 OK', list(headers.items()))
    #yield is used to send back response
    yield 'Here is the WSGI environment:\r\n\r\n'.encode('utf-8')
    yield pformat(environ).encode('utf-8')
    path = environ.get('PATH_INFO', '/')
    print path


if __name__ == '__main__':
    httpd = make_server('', 8000, app)
    host, port = httpd.socket.getsockname()
    print('Serving on', host, 'port', port)
    httpd.serve_forever()
python Server.py
run at browser as http://ip:8000/ ===>>> http://localhost:8000/