Thursday, November 5, 2015

Get the number of chracters in a string

With Swift 2, Apple has changed global functions to protocol extensions, extensions that match any type conforming to a protocol. Thus the new syntax is:

stringName.characters.count
Reference: http://stackoverflow.com/questions/24037711/get-the-length-of-a-string

Sunday, September 20, 2015

What is new in Swift 2.0 Part 1

Console logging:
Swift 1.2:
println("Hello World")
Swift 2.0:
print("Hello World")

P/S: Newline(\n) will automatically be appended

Control flow

Swift 1.2:
struct Person {
    let name: String
    let age: Int
    let address: String?

}

func createPerson(jsonDict: [String: AnyObject]) -> Person? {
    if let name: String = jsonDict["name"] as? String,
        let age: Int = jsonDict["age"] as? Int,
        let address: String = jsonDict["address"] as? String {
        return Person(name: name, age: age, address: address)
    } else {
        return nil
    }

}

P/S: There is a problem here, address is an optional, so it should not be in the optional chaining for the if let. So if we want to fit the code design, it would be like:

func createPerson(jsonDict: [String: AnyObject]) -> Person? {
    let name: String? = jsonDict["name"] as? String
    if name == nil {
        return nil
    }
    let age: Int? = jsonDict["age"] as? Int
    if age == nil {
        return nil
    }
    
    let address: String? = jsonDict["address"] as? String
    return Person(name: name!, age: age!, address: address)

}

This will generate the result that we wanted, Person will always be created so long as name and age is present, however, there are two problems:
1) In a bigger struct, the optional checks may be messy
2) we are forced to unwrap the name and age forcefully(even though it's safe, it's still ugly)

Swift 2.0 introduces Guard, which lets you execute the logic if the boolean expression is false and lets you exit earlier

func createPerson(jsonDict: [String: AnyObject]) -> Person? {

    guard let name = jsonDict["name"] as? String, let age = jsonDict["age"] as? String else {
        return nil
    }

    let address: String? = jsonDict["address"] as? String

    return Person(name: name, age: age, address: address)

}

Summary: if guard condition is met, the code outside the braces are executed, if it isn't then the code inside the braces will be executed
IMPORTANT: make sure a control transfer statement is added at the end of the else clause(return/break/continue), otherwise call a function or method that doesn't return to the normal scope


Do-while
Do-while has been renamed to repeat-while


Pattern Matching
Swift 1.2

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for n in numbers {
    if n % 2 == 0 {
        print(n)

    }
}

Swift 2.0
for n in numbers where n % 2 == 0 {
    println(n)
}

Swift 1.2
enum Directions {
    case Forward, Reverse, Left, Right
}
let movements: [Directions] = [.Forward, .Right, .Left, .Right, .Forward]

for movement in movements {
    if movement == .Right {
        println("Making a right turn")
    }
}

Swift 2.0

for case .Right in movements {
    println("Making a right turn")

}

Tuesday, September 15, 2015

Monday, September 7, 2015

Cannot add bar button item to view controller after segue

http://stackoverflow.com/questions/25587465/how-to-add-buttons-to-navigation-controller-visible-after-segueing

Monday, August 24, 2015

Class Form not found

Begin by installing this package through Composer. Edit your project's composer.json file to require laravelcollective/html.
"require": {
    "laravelcollective/html": "5.1.*"
}

Next, update Composer from the Terminal:

composer update


Next, add your new provider to the providers array of config/app.php:

  'providers' => [
    // ...
    Collective\Html\HtmlServiceProvider::class,
    // ...
  ],

Finally, add two class aliases to the aliases array of config/app.php:

  'aliases' => [
    // ...
      'Form' => Collective\Html\FormFacade::class,
      'Html' => Collective\Html\HtmlFacade::class,
    // ...
  ],

Reminder to myself (note the comments)


        var frame: CGRect = CGRectMake(0, 0, 0, 0)
        self.backButton.hidden = true
        self.navigationController?.setNavigationBarHidden(true, animated: true)
        
        UIApplication.sharedApplication().statusBarHidden = true
        
        self.scrollView.canCancelContentTouches = true
        
        scrollView.delegate = self
        self.scrollView.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
        let scrollViewHeight = self.scrollView.frame.height
        let scrollViewWidth = self.scrollView.frame.width
        // WASTING MEMORY. DO NOT "REDECLARE" THE VARIABLE THAT YOU CAN USE IT OUT OF THE BOX
        
        UIGraphicsBeginImageContext(self.view.frame.size)
        UIImage(named: "walkthroughBackground")?.drawInRect(self.scrollView.bounds)
        var backgroundImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        self.view.backgroundColor = UIColor(patternImage: backgroundImage)
        
        // WASTING MEMORY
        //declare all 6 steps as UIImage
//        let stepOneImage = UIImage(named: "step-1")
//        let stepTwoImage = UIImage(named: "step-2")
//        let stepThreeImage = UIImage(named: "step-3")
//        let stepFourImage = UIImage(named: "step-4")
//        let stepFiveImage = UIImage(named: "step-5")
//        let stepSixImage = UIImage(named: "step-6")
//        
//        self.images = [stepOneImage, stepTwoImage, stepThreeImage, stepFourImage, stepFiveImage, stepSixImage]
//        
//        let divideByTwo: CGFloat = 2.0
        
        let y = ((self.scrollView.frame.height - 325) / 2) - 20
        
        for index in 0..<6 {
//            var walkthroughImageView = UIImageView(image: images[index])
//            walkthroughImageView.contentMode = UIViewContentMode.ScaleAspectFit
            
            // DECLARATE A "STATIC" VARIABLE IN A LOOP IS HORRIBLE
            
//            let walkthroughImageViewWidth: CGFloat = 280
//            var walkthroughImageViewX = ((scrollViewWidth-walkthroughImageViewWidth)/divideByTwo) + (scrollViewWidth*CGFloat(index))
            
            
            //            println(walkthroughImageViewX)
            //
            //            if self.view.frame.size.height != 480 {
            //                walkthroughImageView.frame = CGRectMake((walkthroughImageViewX), 30, walkthroughImageViewWidth, 400)
            //                println(walkthroughImageView.frame)
            //            } else {
            //                walkthroughImageView.frame = CGRectMake((walkthroughImageViewX), 0, walkthroughImageViewWidth, 350)
            //                println(walkthroughImageView.frame)
            //            }
            //            
            
            var walkthroughImageView = UIImageView(image: UIImage(named: "step-\(index+1)"))
            walkthroughImageView.contentMode = UIViewContentMode.ScaleAspectFit
            walkthroughImageView.frame = CGRectMake(320 * CGFloat(index), y, 320, 325)

            self.scrollView.addSubview(walkthroughImageView)
            
        }
        
        self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.width * 6, self.scrollView.frame.height - 20)

        pageControl.addTarget(self, action: Selector("changePage:"), forControlEvents: UIControlEvents.ValueChanged)

Friday, August 21, 2015

Hide Tab Bar

You might have a table view in a tab bar controller, and in certain view you would like to hide the tab bar.

However, the scroll view's(table view)'s height/constraints have been defined when you enter the view controller, hence self.tabBarController?.tabBar.hidden = true will mess up your scrollable height

Add the following line to prepareforsegue when you enter that controller

segue.destinationViewController.hidesBottomBarWhenPushed = true

Monday, August 3, 2015

disable cell highlight/select color

We don't always want our SDK to "act smart" XD

In a table view cell there is always a highlight background color upon tap, if you don't like it simply disable selection style with


cell.selectionStyle = UITableViewCellSelectionStyle.None

How to call tableview controller method within cell class

I was removing cells from table view today with a button in the cell.

So after calling the remove function from the API, here comes the question, how do you refresh the table view's content.

Firstly, create a protocol method in your cell class

protocol BookingTableViewCellDelegate {
    func reloadTableViewData()

}

then 

var delegate: BookingTableViewCellDelegate?

in table view controller

    func reloadTableViewData() {
        println("reloading data")
        self.items.removeAllObjects()
        getBookings()
        self.myBookingTableView.reloadData()
    }

and add 

cell.delegate = self at cellForRowAtIndexPath

then finally, in your cell class:

self.delegate?.reloadTableViewData()

Wednesday, July 29, 2015

Storing date in database

If year < 1970
    type = varchar
else
    type = DATE/DATETIME

Persistent Annotations in MapKit with Core Data

Have yet to try this but good for future reference

http://juliusdanek.de/blog/coding/2015/07/14/persistent-pins-tutorial/

Design Interfaces (a good read)

https://medium.com/elepath-exports/spatial-interfaces-886bccc5d1e9

Monday, July 27, 2015

Removing text field border after applying it

I encountered this problem today

I wanted to show to the user that a particular text field could be edited. Hence, I added a borderStyle with


self.phoneCodeTextField.borderStyle = .Line

But the problem is, I cannot remove the borderStyle with 

self.phoneCodeTextField.borderStyle = .None

Solution:

Make the textfield border rounded rect first before removing the border
self.phoneCodeTextField.borderStyle = .RoundedRect
self.phoneCodeTextField.borderStyle = .None

Wednesday, July 22, 2015

bottom border for collection view

Picture a 3x3 grid, there is a high chance that the bottom row of the grid is 50% thinner than the other borders in the collectionview since there is only 1 border there(instead of 2)

            let border = CALayer()
            //width of border
            let width = CGFloat(1.0)
            //border color
            border.borderColor = UIColor(red: 216.0/255.0, green: 216.0/255.0, blue: 216.0/255.0, alpha: 1.0).CGColor

            border.frame = CGRect(x: 0, y: cell.frame.size.height - width, width:  cell.frame.size.width, height: cell.frame.size.height)


            border.borderWidth = width
            cell.layer.addSublayer(border)

            cell.layer.masksToBounds = true

Monday, July 20, 2015

Change the height of rounded rect UITextField

You might notice that Apple has decided that the height for ALL rounded corner(default) UITextField is 30.
So to change the height, fight change the type or the border(regardless of which, and define the height in your storyboard)

Then, in viewDidLoad {
    self.nameOfTextField.borderStyle = UITextBorderStyle.RoundedRect
}

Thursday, July 16, 2015

dismiss keyboard when touch on screen

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        view.endEditing(true)
        super.touchesBegan(touches, withEvent: event)

    }

deleteCookie in swift


var cookieJar:[NSHTTPCookie] = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies as! [NSHTTPCookie]
        
if cookieJar.isEmpty == false {
    println("\n\n\nnot null\n\n\n")
    for cookie in cookieJar {
        NSHTTPCookieStorage.sharedHTTPCookieStorage().deleteCookie(cookie as NSHTTPCookie)
    }
}

Wednesday, July 15, 2015

tokenmismatchexception for laravel 5

It's necessary to include

<input type="hidden" name="_token" value="{{ csrf_token() }}">
in your post form.

Checking for nil

This occurred to me for a week.
In Objective-C, to check for nil, we can just
if (varName) {
    //not nil
} else {
    //nil
}
and do note that one handy thing in objective-c is that when you declare a variable, it assigns 0.

But thanks to optionals in swift, variables are not supposed to be nil.
So I was checking if cookies are persisting. And found out that I always return true, even if the println(cookie) result is
[]


So in Swift, you have to either call isEmpty
if cookieArray?.isEmpty == false{
     //cookie stored
} else {
    //no cookie :(
}

Tuesday, July 14, 2015

Cookies stored in NSHTTPCookieStorage doesn't persist

You may notice that you manage to 

println(NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies!)
when you trigger setCookie(NSHTTPCookie!)

However,
If you're doing testing on a simulator, you may notice that your cookies doesn't persist through session.

Reason is the cookies are cached and not saved out to a file immediately.

It would only occur when the app receives a SIGKILL signal, like when the debugger is stopped from within Xcode. In my experiments, unhandled exceptions, crashes, exit() and abort() don't cause NSHTPPCookieStorage to loose data.

So if you want to test if your cookie storage is working fine, QUIT the simulator instead of killing the app from Xcode

Credits to: http://stackoverflow.com/questions/5747012/nshttpcookies-refuse-to-be-deleted/15198874#15198874

Monday, July 13, 2015

How to have 2 different UIPickerView for 2 different UITextField in the same UIViewController

Initial attempt:
drag 2 UIPickerView and control drag them and apply constraints to fit them to the bottom

However~
this will make your storyboard hard to maintain and messy, especially if you have UI elements that needed to be changed in the future.

The better solution could be:
Create 2 UIPickerView programatically

var statesPickerView: UIPickerView!
var phoneNumberPickerView: UIPickerView!

and then your toolbar(for Done or maybe stepper for form input)

var keyboardToolbar: UIToolbar!
keyboardToolbar = UIToolbar()
        keyboardToolbar.sizeToFit()
        var flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
        var doneButton: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: Selector("dismissPickerView"))

        var barButtonItemsArray = NSMutableArray()
        barButtonItemsArray.addObject(flexSpace)
        barButtonItemsArray.addObject(doneButton)
        keyboardToolbar.items = barButtonItemsArray as [AnyObject]
        keyboardToolbar.sizeToFit()

add the toolbars to the inputview(picker view)
        self.phoneCodeTextField.inputAccessoryView = keyboardToolbar
        self.statesTextField.inputAccessoryView = keyboardToolbar
        self.phoneNumberPickerView = UIPickerView()
        self.statesPickerView = UIPickerView()

don't forget the delegates
        self.phoneNumberPickerView.dataSource = self
        self.statesPickerView.dataSource = self
        self.phoneNumberPickerView.delegate = self
        self.statesPickerView.delegate = self

 assign the pickerview as the inputview for the UITextFields
        self.phoneCodeTextField.inputView = phoneNumberPickerView
        self.statesTextField.inputView = statesPickerView


Another thing to note, you don't have to set the position or CGRectMake for your pickerview, thanks to the inputView property(e.g. your keyboard is at the bottom anyways).
Awesome <3

Wednesday, July 8, 2015

Steps for a session connection

/* 1. Set the parameters */ /* 2. Build the URL */ /* 3. Configure the request */ /* 4. Make the request */ /* 5. Parse the data */ /* 6. Use the data! */ /* 7. Start the request */

Friday, July 3, 2015

Problem installing homebrew(SSL certification error)

To install homebrew
$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" If you receive SSL certificate error

curl: (60) SSL certificate problem: unable to get local issuer certificate More details here: http://curl.haxx.se/docs/sslcerts.html curl performs SSL certificate verification by default, using a "bundle" of Certificate Authority (CA) public keys (CA certs). If the default bundle file isn't adequate, you can specify an alternate file using the --cacert option. If this HTTPS server uses a certificate signed by a CA represented in the bundle, the certificate verification probably failed due to a problem with the certificate (it might be expired, or the name might not match the domain name in the URL). If you'd like to turn off curl's verification of the certificate, use the -k (or --insecure) option. As mentioned in the error, you can bypass curl's verification. Hence use

$ ruby -e "$(curl -k -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Status bar text

Sometimes your design requires you to use a black navigation controller header. Which will camouflage your status' bar text.

So to change the status' bar text color you are required to do two things:

1) Go to info.plist(note it's the one in the ROOT folder, NOT the one in Supporting Files)
Add a new property "View controller-based status bar appearance" with the value NO

2) go to AppDelegate.swift and add in the following line

UIApplication.sharedApplication().setStatusBarStyle(.LightContent, animated: true)

phpmyadmin Existing configuration file (./config.inc.php) is not readable

Encountered this problem in the morning.

At first glance it looks like a permission issue, but after checking the file I realized that the file is empty, and there is a config.sample.inc.php that has full content.

Removing config.inc.php and renamed config.sample.inc.php to config.inc.php fixes the problem

Credits to https://forums.freebsd.org/threads/solved-apache-php-phpmyadmin-not-working-problem.45920/

Wednesday, April 8, 2015

Text field delegates

great resource

http://www.globalnerdy.com/2015/01/03/how-to-program-an-ios-text-field-that-takes-only-numeric-input-with-a-maximum-length/

Monday, March 30, 2015

Initializer

Recently picked up Swift, this is just something very fundamental but it's something I ended up spending time on so might as well keep it here for my future reference.

To initialize:

class RecordedAudio: NSObject {
    var filePathUrl: NSURL!
    var title:String!
    
    init(filePathUrl: NSURL!, title:String!) {
        self.filePathUrl=filePathUrl
        self.title=title
    }
    

}


recordedAudio = RecordedAudio(filePathUrl: recorder.url, title: recorder.url.lastPathComponent)


Credits to:
https://www.weheartswift.com/swift-classes-part-1/

Tuesday, February 24, 2015

Transitioning css

I  receive a task from the designer today to change background color of a nav bar when user scrolls down.
Cause without changing the background color things look pretty bad as the logo on the top left corner is white, hence it "hides" when you scroll through whitespace.

But then when I change background color, things happens too instantly and I find it pretty uncomfortable, hence after some digging and enquiring my senior, I found this.

http://css-tricks.com/almanac/properties/t/transition/

Which works like a charm :)

The syntax is

.example { transition: [transition-property] [transition-duration] [transition-timing-function] [transition-delay]; }
Hence the code is as follows:

.example { -webkit-transition: background-color 500ms ease; -moz-transition: background-color 500ms ease; -o-transition: background-color 500ms ease; transition: background-color 500ms ease; }


Monday, February 16, 2015

Using google fonts

I made this mistake for awhile now.
Anyways, the main point for this post is to highlight one thing.

DON'T TRUST firebug/inspect element's computed output blindly.

Here is the story, my boss asked me to use Google font's Roboto for the website that I am developing on. So I simply did:

h3 {

    font-family: Roboto;

}

And because using firebug tells me that I already applied Roboto, I didn't question anything further.
But the problem is, my site doesn't know what Roboto is, despite showing that it is Roboto, it is actually another(I don't know what family is that) font, and definitely not the default assigned font for our webpage(Helvetica).

So the problem is actually very simply, I didn't import the font to my laravel program (Because it is an external api's font (Google API).

So here is the main point, regarding how to implement Google's font, one can simply :

1) visit https://www.google.com/fonts/

2) Search the font that you wanted

3) Select the "quick-use" button when hovering over the font's row.

4) Select the weight of the font (Note that only select the options that you will be using to reduce performance impact)

5) Copy the import command and add the CSS as shown in the page. (Paste it on a parent view so it can be inherited)

And again, don't blindly trust the Computed tab.

Sunday, February 8, 2015

Creating default object from empty value in PHP

Add this to BaseController

$identity = Auth::user();

if (!isset($identity)) $identity = new stdClass();

Then throughout the laravel program user->info can be accessed with identity->info instead of constantly Auth::user->info




Wednesday, February 4, 2015

Foreach alternative for query in laravel

Instead of
$items = Item::getAll()
->get()
;

foreach ($items as $item){
     $itemNames[$item->id] = $item->name;
}

It can simply be

$itemNames = Item::getAll()
    ->orderBy('name')
    ->lists('name', id)
;

Thursday, January 29, 2015

Tip for CSS text transform

A tip my superior posted in group

Use text-transform: uppercase;

Reminder of laravel variables

Just a reminder from my boss just now

Do not use
<?php echo Config::get('project.name'); ?>

instead use

{{Config::get('project.name') }}

Styling pagination for laravel

Laravel pagination is done pretty much automatically for you behind the scenes by calling ->paginate(x)
from your controller and return it to the view.
Aside from that simply go to your view and create a php block with the line $var->links();

Working behind the scenes is cool, but what if you want to style it to fit your liking or even to fit the design of your page.

After some searching I found a solution that works quite elegantly, I'll credit the source from below. The purpose of this blog entry is simply for my future reference.

Firstly, notice there is a file called
app/config/view.php
with a 'pagination' key and a value.
Change it to
'pagination' => 'file/path'.
 
Then, create app/views/file/path.blade.php and paste the following.
From there, freely modify the style name et cetera.

Credits to:

Wednesday, January 28, 2015

CALayer alpha

I come across this problem today where I am supposed to change the opacity of an image (It is actually an UIImage)

The problem is that there is no alpha or opacity property for UIImage, if I want to mess with the opacity of the image, I would have to add it to a UIImageView and change the opacity level of the UIImageView.

And then I realized that, the image is sitting on top of a CALayer, and after checking the documentation, I noticed that CALayer has an opacity property (Note: NOT alpha).

So to change the opacity of my CALayer,
layer.opacity = (float);

Laravel route auth

Just a reminder from today morning

Do it using filter.php instead of
if(!(isset(Auth::user()->id)) {
    return Redirect::route('users.log')
    ->with('alert.danger', 'Please login first');
}

Monday, January 26, 2015

Regarding special characters

Avoid using special characters when doing HTML, use HTML entities instead.
Example: &copy;

Note that they are case sensitive.

Navbar transparency bootstrap

Took me two hours to find this =w=. Just putting it here for future reference.

.navbar {
         background-color: transparent;
         background: transparent;
         border-width: 0;
     }

Friday, January 23, 2015

Vertical alignment in bootstrap

Since bootstrap itself doesn't have a vertical alignment feature (At least I haven't find any good results after some search), I came into a forum that posted this CSS that solved my problem.

position: absolute;
  top: 50%;
  left:50%;
  transform: translate(-50%,-50%);

Thursday, January 22, 2015

Changing permission

This is just a simple thing but I noticed that I checked the net too many times for this particular terminal command, better note it down instead.

To change permission settings through terminal do:
chmod -R <permissionsettings> <dirname>

Note the capital R 

P/S: make sure that permissionsettings in server side is 755 

Tuesday, January 20, 2015

Laravel error with save()

Ok so I spent loads of time with this problem today which it is actually just a small problem(and it is a problem from my side)

I have trouble with $var->save(), with the error code 500.

And the biggest problem is that, using a RAW query is fine =.=

After going to start->global.php and turning on the error logging, apparently it is because I didn't create a created_by column when I create this new table. (Confirmed by checking BaseModel)

The purpose of this blog is mainly to tell myself that I can turn on error logging by visiting start->global.php

Monday, January 19, 2015

Some notes about LESS

Just to note what I did on last Friday.

This is definitely my first time messing with bootstrap.

> means subset.
& means append

Thursday, January 15, 2015

CVS to SQL (Part 2 of yesterday)

This is pretty awkward

As it turns out, my task yesterday wasn't complete.

The reason is this. The data I pulled has 2 kinds of delimiter, 1 for column_name(in this case, comma) and a second delimiter for values(in my case, bar-|)

So at the end what I imported to my db is

id        code        name
1         AB          value1|value2|value3
2         CD          value4|value5|value6

Which is obviously not what I want.
Just in case I myself forget what I am looking for in the future, I am hoping that the name column gets broken down, and get the following

id        code        name
1         AB          value1
2         AB          value2
3         AB          value3
4         CD          value4

Hence, what I ended up doing is break this table to 2 separate tables manually. A code table and a name table. P/S: Similar to countries vs states

So the approach here is to create a dummy route, link to that function, and create the function just for the sake of writing this to the database (make sure to remove this route and function afterwards.

Due to NDA, I decided to name the variables foo for table1, bar for table2 and foo_bar for the combined table that I imported initially.

    public function getFoo(){

$jsonResponse = new JsonResponse();
$response = '';

$barName = Bar::getFooByBar();



for($i = 0; $i < count($barName); $i++){

$fooArray = explode('|', $barName[$i]->foo);




foreach ($FooArray as $FooName) {

if($FooName != ''){
$foo_database = new Foo();
DB::table('foo')->insert(
array('bar_id' => $i+1, 'name' => $fooName)
);
}
}
}

$jsonResponse->setResponse($fooArray);

return $jsonResponse
->get();

}

The idea here is to get everything($barName), loop it and tokenize the index with Bar-| and write it to the database.
Don't mind the setResponse($fooArray), I simply use that for debugging process, not wise, but just for convenience since this function is to be removed immediately after I wrote everything to database.

Oh oh! And I just experimented something neat today. After importing foo_bar, since it is only foo that has everything concatenated, I ended up cloning foo_bar,(let's call it foo_bar2 here) then drop foo from foo_bar2, and add a primary key(id), set it to auto increment, it will intelligently assign the ID to existing rows in foo_bar2. Which is neat cause this means that I immediately have 1 table done :)

Wednesday, January 14, 2015

JSON to cvs

Today I received a task which is to pull state and area into a cvs file to be used for our database down the road.

My senior taught me a few ways to look for where are the data so I know where to retrieve.

If it is from the server side, during inspect element the console will have logged out the actions.
if it is hard-coded in the HTML in the dropdown selection etc, I should see the data by inspecting the element of the form.
And finally, which is what happened today. The data is in the javascript. Firstly I hit view source so I can view the entire HTML file. From there I search for .js and look for the js file that is triggered to load the information.

I then copied the JSON and went to http://www.convertcsv.com/ to convert the JSON to CSV.

Also, my senior taught me that I should always visit jsonlint.com to validate JSON before attempting to do anything with it.

Credits to my senior.