Bash Shell: Working with large text files

When working with multi-Gb text files I use these commands:

1. Get the first line which often contains column names and dump it into a small text file



uki $ head -n 1 source_file_name.txt > header_line.txt



2. Get first record after the headline and dump it into a small text file

uki $ head -n 2 source_file_name.txt | tail -1 > first_data_line.txt 

3. Finally, when developing using large files, I take SAMPLE 1000 records (out of millions) to speed up the dev time, I use 1000 because that is default SELECT * number of records in MySQL, but you can use any other if you want, but I would not go too small as you many not catch memory leak errors. The random number 2500 in this example I would change occasionally to pull different sample. You do want to sample your data in different places.


uki $ head -n 2500 source_file_name.txt | tail -1000 > sample_1000_records.txt 

Resulting files:



As an Amazon Associate I earn from qualifying purchases.

Eclipse: increase size of Console buffer size

Then you are executing applications that have a lot System.out.print.. output, you might want to increate size of your Console to hold more text.

Eclipse > Preferences > type in Console in search > Run/Debug > Console

Increase buffer size from default 80,000 characters to MAX 999999.




As an Amazon Associate I earn from qualifying purchases.

Java: importing data from a big text file to MySQL

These 2 classes show you how to read a HUGE TEXT file and insert data from each line to the MySQL database efficiently. The parsing of the lines is out of scope of this exercise as it will be different for each application.


package com.your_package.data;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;

public class YourClassName
{

public static void main(String[] args)
{
String db = "your_db_name";
String user = "root";
String password = "your_password";
Connection connection = makeDbConnection(db, user, password);

BigTextFile file = null;
try
{
file = new BigTextFile("/Users/uki/Documents/file_name.txt");
} catch (Exception e)
{
e.printStackTrace();
}

for (String line : file)
{
// process line here the way you want it
System.out.println(line.substring(line.lastIndexOf("|") + 1));

String partNumber = "0001";
String attributeName = "some name";
String attributeValue = "some value";

String sql = buildInsertSqlStatement(attributeName, attributeValue, partNumber);
insertIntoDb(connection, sql);

break; // remove after all works
}

}

private static String buildInsertSqlStatement(String attributeName, String attributeValue, String partNumber)
{
StringBuffer sql = new StringBuffer();
sql.append("INSERT INTO your_database_name.table_name VALUES (");
sql.append("'" + attributeName + "'");
sql.append(", '" + attributeValue + "'");
sql.append(", '" + partNumber + "' );");
return sql.toString();
}

private static void insertIntoDb(Connection connection, String sql)
{
final String TAG = YourClassName.class.getCanonicalName();
try
{
Statement st = connection.createStatement();

System.out.println(TAG + "Executing: " + sql);
int val = st.executeUpdate(sql.toString());
System.out.println(TAG + " Returned: " + val);

} catch (SQLException e)
{
System.out.println("SQL insert failed " + e);
}

System.out.println(TAG + "Finished " + new Date());
}

private static Connection makeDbConnection(String db, String user, String password)
{
Connection con = null;
try
{
String url = "jdbc:mysql://localhost:3306/";
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver);
con = DriverManager.getConnection(url + db, "root", "");
} catch (Exception e)
{
e.printStackTrace();
}
return con;
}
}





package com.your_package.data;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Iterator;

public class BigTextFile implements Iterable
{
private class FileIterator implements Iterator
{
private String line;

public boolean hasNext()
{
try
{
line = bufferedReader.readLine();
} catch (Exception ex)
{
line = null;
ex.printStackTrace();
}

return line != null;
}

public String next()
{
return line;
}

public void remove()
{
}
}

private BufferedReader bufferedReader;

public BigTextFile(String filePath) throws Exception
{
bufferedReader = new BufferedReader(new FileReader(filePath));
}

public void Close()
{
try
{
bufferedReader.close();
} catch (Exception ex)
{
}
}

public Iterator iterator()
{
return new FileIterator();
}
}



As an Amazon Associate I earn from qualifying purchases.

MySQL: importing table data from text file


You can import table data from text file.

If columns are matched in order to delimited file, then it is very easy, example data:

column1data|column2data|column3data| |column5data
column1data|column2data|column3data|column4data|column5data


Note that the file name should be the exact name of the table you are writing to:


uki: ~ $ mysqlimport --local -u root --fields-terminated-by="|" sears_product_info /Users/uki/Documents/XYZ/table_name.txt 

database_name. table_name: Records: 526733  Deleted: 0  Skipped: 526733  Warnings: 557695


Note that if the record already exists then it will not be imported again (a good feature for me).
If you want to clean the table content then you execute 
DELETE FROM database_name. table_name
The import of 500,000 records may take up to 10 minutes on MacBook Pro.



As an Amazon Associate I earn from qualifying purchases.

Android: obtaining Google Map apiKey

TO GET MD5 for DEVELOPERS (DEBUG):


STEP 1. Find you debug.keystore file 




STEP 2a. Open Terminal and execute keytool command

$ keytool -list -storepass android -keystore /Users/uki/.android/debug.keystore


androiddebugkey, Jan 21, 2010, PrivateKeyEntry, 
Certificate fingerprint (MD5): A0:AC:1A:E2:E7:06:C2:93:CF:9E:xxxxxxx.....

skip to STEP 3


STEP 2b.


FOR DEPLOYMENT (not local development):
Build (Export) your application for deployment at least once to you have your deployment signature. Follow the wizard and make certificate for 35 years.


Use the same keytool utility:

uki: ~ $  keytool -list -keystore /some_directory/keystore_name.keystore
Enter keystore password:

Keystore type: JKS
Keystore provider: SUN

Your keystore contains 13 entries

[...]
taxi share - national, Sep 21, 2011, PrivateKeyEntry,
Certificate fingerprint (MD5): 15:A1:16:70:.....................................................
[...]
uki: ~ $







4. Copy and paste the apiKey to your Maps





As an Amazon Associate I earn from qualifying purchases.

Select longest records from the database

To find the longest record in your table you can use this query:


SELECT max(length(column_name)) from table_name 
This can help you in optimizing the size of your tables.


SELECT column_name FROM table_nameWHERE length(column_name) =
( SELECT max(length(
( SELECT max(length(column_name)) from table_name );


Result is a list of records with the longest length





As an Amazon Associate I earn from qualifying purchases.

Execute SQL script (MySQL dump) from command line

1) Find you mysql installation directory:

uki: ~ $ cd /usr/local/mysql/bin

2) Start mysql shell
uki: ~ $ ./mysql -u root
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 238
Server version: 5.5.9 MySQL Community Server (GPL)
...

3) Select database you want to execute script agaist
mysql> use my_database_name
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed

4) Execute SQL script
in the next line notice "slash dot space"

mysql> \. /Users/uki/Documents/script_name.sql 


As an Amazon Associate I earn from qualifying purchases.

Add MySQL to PATH

1.  Open Terminal go to your home directory
uki: ~ $ cd ~

2. see if you already created .bash_profile


uki: ~ $ ls .bash*
.bash_history .bash_profile

3. if .bash_profile is not there execute
uki: ~ $ touch .bash_profile

4. open file for editing
uki: ~ $ open .bash_profile 

or using your favorite editor
uki: ~ $ bbedit .bash_profile 
5. add content to the file


# User specific Terminal config
if [ -n "$PS1" ]; then PS1='\u: \w \$ '; fi
shopt -s checkwinsize
date -u
export PATH=$PATH:/usr/local/bin
####### JAVA DEV #######
export JAVA_HOME=/Library/Java/Home/
export PATH=$PATH:$JAVA_HOME/bin
export PATH=$PATH:/usr/local/mysql/bin
6.  RE-OPEN the Terminal
7. try to run mysql command

uki: ~ $ mysql -u root
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 236
Server version: 5.5.9 MySQL Community Server (GPL)
Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> 





As an Amazon Associate I earn from qualifying purchases.

Placing Android pop-up toasts on the screen


You can place your toasts anywhere on the screen you want. In this case I put it in the center of the screen with 20 pixels off the left margin and 40 below the center line.

Toast toast = Toast.makeText(TrucksScreen.this, getString(R.string.fetching_map_details), Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, -20, -40);

toast.show();


As an Amazon Associate I earn from qualifying purchases.

Google Maps - Converting coordinates

We found that when converting the coordinates from Java double to Java int the notation makes all the difference:

When we used 1000000 instead of 1E6 the coordinates were rounded off and therefore up to one degree (110 km) off from the true location.


int lon = (int) item.getStatus().getGeo().mLongitude * 1000000
// rounded off coordinate lat :42000000 lon :-87000000

int lat = (int) (item.getStatus().getGeo().mLatitude * 1E6); 
// correct lat :42239902 lon :-87971504


Log.e("Map", "lat :" + lat + " lon :" + lon);
mPoints.put(item.getProfileImageUrl(), new GeoPoint(lat, lon));





As an Amazon Associate I earn from qualifying purchases.

Creating Google Maps Development Key


In Terminal execute below to get your MD5 fingerprint:

~ uki$ keytool -list -alias androiddebugkey  -keystore ~/.android/debug.keystore -storepass android -keypass android
androiddebugkey, Jun 29, 2011, PrivateKeyEntry,

Certificate fingerprint (MD5): 65:4D:21:AA...

Go to the site:

http://code.google.com/android/maps-api-signup.html

Copy the fingerprint: 65:4D:21:AA...


Your key is:
0wbj...
This key is good for all apps signed with your certificate whose fingerprint is:
65:4D:21:AA...
Here is an example xml layout to get you started on your way to mapping glory:
              <com.google.android.maps.MapView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="0wbj..."
/>




As an Amazon Associate I earn from qualifying purchases.

FoodTrucks on Chicago Local Guide - Twitter Geo-location

You can now help us locate your favorite food truck by tweeting from where they are at with GEO-location enabled. Your tweet will show on the map as a semi-transparent circle. The tweets from the food trucks will show as icons, but only for short time and when geo-location is on.


To turn on the geo-location when tweeting, find the toggle switch (upper left in Plume)...



... or in preferences for Twitter app.



So that is how it looks for real!





You can write your Twitter posts from the app, too.






Don't forget to ask your friends to download the app by scanning this QR code:




As an Amazon Associate I earn from qualifying purchases.

Programming for UI designers: Android Options Menu

Ins and outs of Android Options Menu

The standard Android Menu is one of the most common elements of an Android application, and provides users a familiar way to perform actions. It contains a collection of primary options and functionality which shows up when the user touches the MENU button on the device. 



In this article we will explore how to make this simple item of Android user experience perfect.


Step 1.  Create a menu icon
  • open Photoshop, create a file with canvas size 72x72 (Notice: always start from the larger size)
  • create your shape using Pen tool (P), or if you have it ready in some vector format paste it as a shape into your document. For the sake of sharpness it is important to use the shape tool and to adjust it, by moving its nods so that the margins fit to the pixel grid.
  • scale it to 48x48 and center it. Keep this size for more square icons but make them a little bigger in case you have a custom shape icon so they will appear visually approximately the same size
  • apply the following layer styles 




  • save it as *.png
  • scale and save the icon for  mdpi (48x38) and ldpi (36x36).
Note: The menu icons are not the case to improvise. The better we follow the guidelines the better and crisper they will look. I advise you to download the Icon Templates Pack - where you can find the PSD template for every screen size. Create your shape in Illustrator, paste it  in the PSD template, copy the layer styles from the template layer and paste it to yours. Voila, you got the icon.

Step 2. Copy the icon to an existing project
Import (Checkout) an existing project in Eclipse IDE (see Software Installation and set up for Android Development). If one is absent you might want to download an open source application.

In the project explorer take a look at the resources folder (/res/). Its content is of the most interest to us, designers.


Notice that we have a lot of drawable folders in which reside all our graphical assets as well as elements/shapes drawn in xml which we will explore another time.
When an application is downloaded on the device, the app performs a check of the screen size and density and runs using the graphics from the appropriate folder. If graphics for a given device is not found, or it deals with an element shared with all the screen sizes, then the app is looking for it in the default folder .../drawable/. 

To import the icons in the project just drag and drop them in the specific folders.

Note: The icon should have exactly the same file name for all the screen densities. After importing you should get the following structure:

  • /drawable-hdpi/ic_help.png
  • /drawable-mdpi/ic_help.png
  • /drawable-ldpi/ic_help.png

For the menu icons we will not consider screen sizes, only screen densities.


Step 3. Menu layout
Unfold the ../res/menu and ... /res/values:



In the menu.xml and events.xml, if we read attentively, even without knowing any programming its clear that we have a <menu> which contains <items>.


android:id="@+id/about_us" - is the name of the activity/functionality that will be started when we tap, until you do not get very comfortable with the programming part its better not to make changes here.

android:icon="@drawable/ic_help"  - notice that even if the icon is placed in different folders, we do refer to the "/drawable", this is why it is so important to keep the same filename for all the desnsities.

android:title="@string/home_about" - in the image of the folders above, in the values folder there is a strings.xml file. This file stores all the strings (titles, notification messages, etc.) we might need including the title of the menu elements. Notice that in the <menu> we refer to string title and not to its content. Knowing this you can change the content or correct spelling yourself. 


Note: Having an existing project with at least one menu item you should be able to add as many of them as you need to test. Just make copies of the <item> inside the <menu> in the xml menu file, and make sure to copy and create strings for the item title as well. As for android:id, you can copy the same value in all of them as our goal is to test the look of the icons and we do not care about the activity that follows, just be careful not to commit your experiments. If you want to temporally remove an item from the menu you can comment it out by selecting it in xml file and pressing command+shift+C.

Step 5. Run and test the application 
  • right click on the project and choose Refresh
  • connect the device to the computer or set up your emulator
  • right click on the project, select Run and choose as Android Project
Sucess!



As an Amazon Associate I earn from qualifying purchases.

Solr Search Engine

Starting the engine with Jetty (included J2EE container):

~ uki$ cd /Users/uki/solr/apache-solr-3.3.0/exampleexample uki$ java -jar start.jar


Indexing XML:

~ uki$ cd /Users/uki/solr/apache-solr-3.3.0/example/exampledocs

ushofml299009:exampledocs uki$ java -jar post.jar /Users/uki/Documents/workspace/Spin\ XSLT/SPIN_43.xml


Statistics:

http://localhost:8983/solr/admin/stats.jsp

numDocs : 17



As an Amazon Associate I earn from qualifying purchases.

Programming for UI designers: Software Installation and set up for Android Development

How many times the designs did not look exactly as your Photoshop files?
Let me guess - MOST OF THE TIME.

In this new series of articles I will try to share my experience on how to improve and adjust your UI designs for Android mobile apps. We will learn how to change colors, adjust margins, add shadows and at a higher level - how to create beautiful and flexible layouts for different screen sizes. So let's get started.

For the start let's make sure we have everything we need for our little journey into programming.

Software Installation and set up for Android Development
(find step by step instructions on http://chicago-gtug.com supported by ChicagoAndroid.com)
  • Install a development environment. On the Android platform most of the native apps are developed in Eclipse IDE for Java EE Developers.
  • In order to be able to import projects from the team's repository and to be able to share your changes in the code you need to install Install SVN plugin - Subclipse. (video by Uki D. Lucas http://youtu.be/pVBXfjc7QV4)
  • install Android SDK.
  • Android SDK and AVD Manager - updates - as for updates, you will see plenty, you will never go wrong by installing all of them
  • Create a virtual device - AVD - the virtual devices are very annoying and they load forever but they are very useful especially for testing your designs on various screen sizes.
The installation process might take you a few hours and cause you a lot of trouble. Ask the developers from your team for help if needed.




As an Amazon Associate I earn from qualifying purchases.

My favorite quotations..


“A man should be able to change a diaper, plan an invasion, butcher a hog, conn a ship, design a building, write a sonnet, balance accounts, build a wall, set a bone, comfort the dying, take orders, give orders, cooperate, act alone, solve equations, analyze a new problem, pitch manure, program a computer, cook a tasty meal, fight efficiently, die gallantly. Specialization is for insects.”  by Robert A. Heinlein

"We are but habits and memories we chose to carry along." ~ Uki D. Lucas


Popular Recent Articles