Saturday, October 27, 2012

Lazy Coder Camp (Edition 1)


What is Lazy Coder Camp?

Lazy Coder Camp is a user generated conference primarily focused around technology that supports minimalistic programming/coding. The event will be dabbling on conducting camps and workshop events where there is little programming involved. This is an armchair approach to early stage web application development and open source technologies.

This is a community based event and anyone is welcome to join the team as volunteer in organizing future editions. The format of the Lazy Coder Camp will be both learning and hands on workshop focused on various domains.

Lazy Coder Camp (Edition 1)
 
Come and join us during the launch of Lazy Coder Camp!

The first edition of the camp is a daylong event that is totally free for IT enthusiasts and students to attend. We will be discussing about bootstrapping Drupal. The discussion will cover all aspects of Drupal installation, setting up a basic website and integrating all your social media streams to your basic site. The event will serve as a great learning opportunity for young professionals from other domains to come experience Drupal first hand with the PHP experts. The speakers will bring their unique experiences and insights to share with the audience and will be addressing all apprehensions related to taking up Drupal development.

Note :
  • All attendees who would like to come for the day long workshop cum training its mandatory to carry your laptop to experience installation and customisation first hand.
  • To attend register immediately as we have very limited seats and will be served on first come first basis.
  • Please check back regularly for the most recent updates to our agenda and list of speakers.
  • For any questions, or inquiries regarding speaking or exhibiting at future editions of Lazy Coder Camp, please contact lazycodercamp@phpfactory.com.

Monday, August 1, 2011

Truncate all tables in a particular database using a single line command.

Generally if you like to truncate or empty all the records in a database containing more no. of tables, use the below command to do it. It really helps to remove all the records completely only having the structure of the tables left in a database.

mysql -u {user-name} -p {database-name} -BNe "show tables" | awk '{print "TRUNCATE TABLE " $1 ";"}' | mysql -u {user-name} -p {database-name}

Let me know if it doesn't works you out.

Tuesday, May 17, 2011

Dumping Multiple Selected MySQL Tables as SQL


Not sure if anybody already figured out how to dump the selected mysql tables from a particular database. But after googling I found some way which helped me how to proceed and adding my thought little & attained what I need. Ok, not bugging you too much, here is my requirement:

I need to dump 5 tables (employee, address, salary, attendance, payslip) & the tables whose name starts with map_* in a single command.

Solution
What I know from the syntax is that I can append as many table name with the mysqldump to get the dump of all the tables.mysqldump -u{user} -p {database} {table1} {table2} {table3} > {destination}.sql
but what here missing is that I can add map_* tables which is really important for me to proceed further.

As said, after googling I got the site and understood how to get map_* tables include with the mysqldump.

The referred site provided me something like this..
mysql databasename -u [root] -p[password] -e 'show tables like "wp_153_%"' | grep -v Tables_in | xargs mysqldump [databasename] -u [root] -p[password] > [target_file]

but what I modified to get my requirement complete is
mysql {databasename} -u {root} -p{password} -e 'show tables like "wp_153_%"' | grep -v Tables_in | xargs mysqldump {databasename} -u {root} -p{password} {table1} {table2} {table3} > {destination}.sql

So my final output was
mysql employeeDB -u root -p -e 'show tables like "map_%"' | grep -v Tables_in | xargs mysqldump employeeDB -u root -p employee address salary attendance payslip > destination.sql

Hope NO other better option than this.


Note: I have remove {password} from my command as I think we should not execute the password in the command line instead asking us

Monday, May 16, 2011

Reading PDF and converting to CSV using RubyCode & pdf-reader plugin

I wanted to convert a PDF document into a XLS table and after a couple of searches I could easily able to write the code in ruby and converted a Citibank PDF Statement to CSV file. This gave me enough relief that I learnt how to read a PDF file if its not password protected.

require 'rubygems'
require 'pdf/reader'
class PageTextReceiver
  attr_accessor :content

  def initialize
    @content=[]
    @kk = "false"
    @i = 0
    @ptr_str = ""
  end

  def begin_page(arg=nil)
    puts ""
  end

  def show_text(string, *params)
    if string.strip=="Previous Balance"
      @kk="false"
    end
    if @i==4
      puts @ptr_str
      @ptr_str = ""
      @i=0
    end
    if string.strip=="Sale Date" or @kk == "true"
      @kk="true"
      if @i==0
        @ptr_str << string + "/2009,"
      else
        @ptr_str << string + ","
      end
      if (string.reverse.index(".")==2 or string=="Amount (in Rs)")
        @i=4
      else
        @i=@i+1
      end
    end
  end

  def move_to_next_line_and_show_text
    @i=0
    show_text
  end

  alias :super_show_text :show_text
  alias :set_spacing_next_line_show_text :show_text

  def show_text_with_positioning(*params)
    params=params.first
    params.each { |str| show_text(str) if str.kind_of?(String) }
  end
end

receiver = PageTextReceiver.new
(1..45).each do | x |
  pdf = PDF::Reader.file("#{x}.pdf", receiver)
  puts receiver.content.inspect
end

The above code use to read 45 pdf files. Say the above code is saved in read_pdf.rb

Below is the command to execute the file and store in a file (which I hope the easiest way)
ruby read_pdf.rb >> a.csv
hope it helps you ? or If you know how to read a PDF which is password protected thru code, where I can input the password of the file, please let me know.

Tuesday, January 4, 2011

rmagick installation for MacOSX

Try the below following steps to install rmagick using macports.

sudo port install tiff -macosx imagemagick

If you get an error like this..

Error: Checksum (md5) mismatch for lcms-1.19.tar.gz
Error: Checksum (sha1) mismatch for lcms-1.19.tar.gz
Error: Checksum (rmd160) mismatch for lcms-1.19.tar.gz

then execute the below commands
sudo port selfupdate
sudo port clean --all lcms
sudo port install tiff -macosx imagemagick

now try this below command to really work for Rails

sudo gem install rmagick

hope it helps you ?

Thursday, August 12, 2010

undefined method `stringify_keys!' for + attachment_fu


Today me & my friend were working on a simple attachment_fu plugin with the Rails. We had some trouble which we solved it too.

We followed http://clarkware.com/cgi/blosxom/2007/02/24#FileUploadFu to make the attachment_fu work with our application. Basically we have a company table & attachment table too which has a relation in between. Company table contains the list of companies & Attachment table contains the attachments for the individual companies.

The model looks like this.
class Company < ActiveRecord::Base
  has_one :attachment
  has_many :books
end


class Attachment < ActiveRecord::Base
  belongs_to :company
  has_attachment :content_type => ['application/zip']
  has_attachment :storage => :file_system, :path_prefix => 'public/files'
  validates_as_attachment
end

the view file looks like this

<% form_for(:mugshot, :url => "/companies", 
                  :html => { :multipart => true }) do |f| -%>
<!-- Form -->
<div class="form">
   <label>Company Title <span>(Required Field)</span></label>
   <input type="text" name="company_title" class="field size1" />
   <label>Upload the zip file <span>(Required Field)</span></label>
   <%= f.file_field :uploaded_data %>
</div>
<!-- End Form -->
<div class="buttons">
 <input type="button" class="button" value="[cancel]" />
 <input type="submit" class="button" value="[upload now]" />
</div>
<!-- End Form Buttons -->
<% end %>

The company_controller.rb looks like this.

def create
  company = Company.create(:title => params[:company_title], :from => params[:from_date], :to => params[:to_date], :comment => params[:comment])
  @zipfile = Attachment.new(params[:uploaded_data])
  @zipfile.company_id = company.id
  if @zipfile.save
     flash[:notice] = 'Company successfully created.'
     redirect_to :controller => "books", :action => "new"
   else
     flash[:error] = 'You must select a file to upload first!'
     company.destroy
     render :action => :new
   end
end

But strangely we got the error saying..
undefined method `stringify_keys!' for
which got rectified based on the changing one line in the view file, from
   <%= f.file_field :uploaded_data %>
to
   <%= file_field :attachment, :uploaded_data %>
and also update the line in company_controller.rb from
  @zipfile = Attachment.new(params[:uploaded_data])
to
  @zipfile = Attachment.new(params[:attachment])


This made it work properly. Hope this helps you too, else let me know and will try to help you out.

Monday, August 2, 2010

Existing PHP / Ruby not working with MySQL installed with 'sudo port install'

By Default OSX 10.x contains PHP & Ruby installed already. I wanted to make work few applications which used MySQL, PHP & Ruby. So to do this, I installed Xcode & MacPorts too. Then installed mysql using 'sudo port install' and installed successfully. But when I executed the applications, I found that neither PHP nor Ruby could know which mysql.sock can be used to make the existing application work. After a deep search found that port install uses different location and stores the mysql socket. I tried to edit the php.ini file to make sure that it gets connected to the existing socket, but still it didn't worked.

When executed the PHP code I got this warning "Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in /Users" but without this solved I can't connect to DB and get the code working.

When I tried with Ruby also it gave me some weird error "ruby `initialize`: wrong number of arguments (4 for 0) (ArgumentError)" and I got frustrated little bit.

So instead of debugging more I thought I can remove the existing PHP & Ruby and install them using the port install command. So I followed the few steps like mentioned below:

sudo mv /System/Library/Frameworks/Ruby.framework/Versions/1.8 /System/Library/Frameworks/Ruby.framework/Versions/1.8.dead

sudo port install ruby
sudo port install rb-rubygems

sudo mv /usr/bin/ruby /usr/bin/old_ruby
sudo mv /usr/bin/gem /usr/bin/old_gem
sudo ln -s /opt/local/bin/ruby /usr/bin/ruby
sudo ln -s /opt/local/bin/gem /usr/bin/gem

sudo gem update --system

sudo gem install xml-simple
sudo gem install mysql

sudo port install php5
sudo port install php5-mysql
sudo port install php5-mbstring

sudo cp /opt/local/etc/php5/php.ini-production /opt/local/etc/php5/php.ini

locate mysqld.sock
==> /opt/local/var/run/mysql5/mysqld.sock (mostly this will be)

sudo vim /opt/local/etc/php5/php.ini

and change all mysql & mysqli default_socket = /opt/local/var/run/mysql5/mysqld.sock

sudo mv /usr/bin/php /usr/bin/old_php

The above commands will rename the existing PHP & Ruby and uses the new Ruby & PHP installed using the port install commands. After updating the php.ini my existing code worked perfectly as though there were no issues. Even the Ruby also didn't gave me any error, even that too worked fantastically.

I hope this will help you to resolve your problem easily rather than debugging the issue which might eat up your time.

Friday, July 30, 2010

Uninstall Ruby / PHP in existing Mac OS

Hi Guys, posting this after a long period as was little busy ;-). Anyways lets get into the subject.

Whenever OSX 10.x version installed, by default PHP / Ruby will also be installed. This is good but sometimes we don't want the particular version installed so to remove this we need to do the following steps.

For Ruby
sudo mv /System/Library/Frameworks/Ruby.framework/Versions/1.8 /System/Library/Frameworks/Ruby.framework/Versions/1.8.dead
sudo mv /usr/bin/ruby /usr/bin/old_ruby
sudo mv /usr/bin/gem /usr/bin/old_gem

For PHP
sudo mv /usr/bin/php /usr/bin/old_php

Wednesday, April 21, 2010

Drupal: Drush + CCK Import Module Code

I was trying to figure out if there are any modules which I can download for the Drupal 6 and try to use Drush command to do an CCK Import of a file which has been exported thru CCK Export. After a hard dig around, I couldn't find any one, so I started writing my own. Don't worry I have shared the code below. Anyway talks apart, below is the code which you put in a file called drush/commands/cck_import/cck_import.drush.inc




// $Id: cck_import.drush.inc,v 1.1 2010/04/21 03:03:39 kishore Exp $

/**
* @file
* Drush support for cck_import.
*/

/**
* Implementation of hook_drush_command().
*/
function cck_import_drush_command() {
$items = array();

$items['cck_import-import'] = array(
'callback' => 'cck_import_drush_callback_import',
'description' => "Import node code from a previous export.",
'options' => array(
'--uid' => "Uid of user to save nodes as. If not given will use 1. You may specify 0 for the Anonymous user.",
),
'examples' => array(
'drush cck_import import < filename' =>
'Import nodes from given filename.',
),
);

return $items;
}

/**
* Implementation of hook_drush_help().
*
* This function is called whenever a drush user calls
* 'drush help '
*
* @param
* A string with the help section (prepend with 'drush:')
*
* @return
* A string with the help text for your command.
*/
function cck_import_drush_help($section) {
switch ($section) {
case 'drush:cck_import-import':
return dt("Imports nodes that have been exported. Usage: 'drush cck_import import < filename'.");
}
}

/**
* Drush command callback.
*
*/
function cck_import_drush_callback_export() {
$commands = func_get_args();

$nids = array_filter($commands, 'is_numeric');

$data = cck_import_node_bulk($nids, TRUE);

$filename = drush_get_option('file');

if ($filename) {
// Output data to file. Note this only takes a flat filename for the current directory.
// If file exists, ask for whether to overwrite
if (file_exists($filename)) {
if (!drush_confirm(dt('File ' . $filename . ' exists. Do you really want to overwrite?'))) {
return;
}
}
// Write the file.
file_put_contents($filename, $data);
}
else {
// Print to terminal.
drush_print_r($data);
}
}

/**
* Drush command callback.
*
* Import nodes from data.
*/
function cck_import_drush_callback_import() {
$commands = func_get_args();

// Switch to admin or the specified user so imported nodes are not anonymous.
$uid = drush_get_option('uid');
// Test on NULL so uid may be given as 0.
if (is_null($uid)) {
$uid = 1;
}
// uid 0 is already loaded.
if ($uid != 0) {
global $user;
$user = user_load($uid);
}

$values = array();
$values['type_name'] = '';
$values['macro'] = file_get_contents("php://stdin", "r");
$form_state = array();
$form_state['values'] = $values;
if (!empty($form_state)) {
$result = drupal_execute("content_copy_import_form", $form_state);
if ($result === FALSE) {
// There was a problem with types?
drush_set_error('DRUSH_NOT_COMPLETED', 'Problem found with the import file. Check the node types exist.');
}
}

}




After saving this file, try to execute the below command



$ drush cck_import-import < filename.content



note filename.content should contain something which has been exported from the CCK Export.

Hope this would have solved your issues, I am in the process of developing the CCK Import / Export thru Drush commands and might update you soon with other version of the code. Not sure where to publish but thought of publishing in my own blog and in future might publish in a proper particular location where everybody gets benefited.

Feel free to ask me any queries.

Thursday, April 1, 2010

Gmail - April Fool


Hope everybody trying to find out what is the April Fool prank Google is going to play this time. Here G-King played the prank April Fool. GMail application misses all the vowels and wants people to think that there is some virus / some flaw in user's computer.. ;-) might be bad guess..

Anyway here is the screenshot of GMAIL Disemvowelling

Wednesday, November 11, 2009

Remove Extended attributes present in file permission in Mac OS

Hi Guys,

For the past two days I was struggling to get rid of the '@' character which is appended in the permission for a file whenever used using the TextMate Editor in the Mac OS. I opened TextMate Editor and created a file called "test.txt" which is created successfully but unfortunately the permissions saved are


-rw-r--r--@ 1 kishorekumar admin 5 Nov 11 13:56 test.txt


Now I felt strange regarding this why this @ came and what is that exactly. Later after two days of digging I found the answer and now I am relaxed. Oops sorry to continue my story.. continuing back..

What I understood regarding the '@' is that it is file extended attributes for the Mac files. You can see them with the -@ flag to ls, or with the new xattr command:


ls -al test.txt
-rw-r--r--@ 1 kishorekumar admin 5 Nov 11 13:56 test.txt



ls -al@ test.txt
-rwxr-xr-x@ 1 kishorekumar admin 11614 Nov 11 12:27 test.txt
com.macromates.caret 35



xattr -l test.txt
com.apple.FinderInfo:
0000 00 00 00 00 54 78 4D 74 00 00 00 00 00 00 00 00 ....TxMt........
0010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................

com.macromates.caret: {
column = 7;
line = 295;
}


So now, how to get rid of the '@' and the com.apple.FinderInfo & com.macromates.caret so here is the simple and fastest solution which works faster.

To Disable the Extra Attributes which gets attached to the file is just run this below command in the Terminal.

defaults write com.macromates.textmate OakDocumentDisableFSMetaData 1


To Enable the Extra Attributes which gets attached to the file is just run this below command in the Terminal.

defaults write com.macromates.textmate OakDocumentDisableFSMetaData 0


Note: Make sure that you restart the TextMate Application else it might not work perfectly.

Hope this might help you easily. If not please let me know I will try to help you :-)

Tuesday, September 15, 2009

Missing Attachment in Outlook but present in Web Gmail

While coding send mail functionality, found that the attachment functionality is not working properly. The attachment is displayed in the Web browser Gmail / Mozilla Thunderbird but when tested with Microsoft Outlook, Apple Mail for a strange it didn't showed any attachment. After a long debug we found that instead of

Content-Type : multipart/related;

it should be

Content-Type : multipart/mixed;

I am not sure what exactly the difference but it worked out to be a wonder for us. So Please make sure that whenever Attachment is attached thru coding we should use only

Content-Type : multipart/mixed;

Hope this might help you whenever you face this kind of problem.

Monday, September 14, 2009

Useful ISERR function - Microsoft Excel

I feel most of the non-IT people & few of the IT people use the Microsoft Excel. Have you any time tried to use the formula to find a value in some cell, have used ? SEARCH or FIND function. Ok if you have used you might have found that it returns 1 if it has found an #VALUE! if it returns false.

i hope you have used something like this right ?
=SEARCH("Party",C9)

returns <1

where C9 contains "Party in Melbourne"

Now if C9 contains "Dance in Melbourne"

then it returns

#VALUE!

Here is a quick and fast solution to fix this and return TRUE or FALSE instead of 1 or #VALUE! which is not useful for further purpose.

=NOT(ISERR(SEARCH("Party",C9)))

Hope this might have solved your purpose, by the way I was using the below line to check whether the Finding string is present then return the cell content else return some other cell content.

=IF(NOT(ISERR(SEARCH("Party",C9))),C9,B9)

hey, I am here to help you...

Thursday, September 10, 2009

Best 1 line command to rename extenstions for multiple files.

One of the best command to rename all the files having same extensions. This is one line command. Say you have 100 files with same extension jpg and you want to convert all the jpg files to gif files so here is the below command to do it.


ls -d *.jpg | sed -e 's/.*/mv & &/' -e 's/jpg$/gif/' | sh


you just need to replace jpg instead of the extension you have and replace gif value with what extension you want to replace.

Hope this might be definitely helpful for you.

Monday, September 7, 2009

svn: Can't copy 'models/.svn/tmp/text-base/comments.php.svn-base' to 'models/.svn/tmp/comments.php.tmp.tmp': No such file or directory

While doing checkout of a project from the repository I got some errors which has been solved very easily.


[mnto]$ svn delete comments.php
D comments.php
[mnto]$ svn commit -m "No Need for comments.php will commit back sometime later" .


I did this and solved the issue and it worked out easily.

Saturday, August 22, 2009

BASH Script to copy a particular file to different directories having the same pattern folder structure

One of the module which was done has to be copied to many directories say roughly around 50 inner directories. I did that by replicating it, but when i tested it i found that I have to change a file in all the 50 directories. I knew there is definitely a way out which can do this job easily and did some googling and used the bash script to write a small program which will do a small wonder for me.

The below bash script will loop thru all the directories (eg., abc, def, mmm ) and copies a file from turn/site/newfile.txt to all site directories which has been looped thru now.


#!/bin/bash
for directory in abc def mmm
do
  echo $directory
  cp trunk/site/newfile.txt $directory/site/somefile.txt
done


Note: While reading some sites, I found interesting bash shell script: copy only files modifed after specified date

Hope this might help you to save time.

Friday, August 21, 2009

ER Diagram Tool for Mac

Have you ever did an ER Diagram for the Tables ? hmm, I hope yes, you might have did in your schoolings. Did you thought at that time how much it will be useful later ? Ok, Ok, coming straight to the point, I was figuring out any tool which might do the ER Diagram easily without straining too much. Atlast I found one for Mac.

SQLEditor for Mac

I have downloaded the 30 Day trial and tested it and works fine. I was in search for this which accepts the MySQL exported SQL file and it draws the ER Diagram for it.

Thursday, August 20, 2009

Easy Steps to remove "Read More" , Published by author - Drupal 6

One of the ticket raised in Drupal community was, how to remove the "Read More" link & "Published by Author" with date for a story / page while listing the stories in the website. I just digged the code for exactly 1 min and found an easy solution. Drupal 6 is as good as you think good. But really speaking its really damn good. I went to the garland folder present in the themes folder. I just removed the below two blocks and saved the node.tpl.php file.


<?php if ($submitted): ?>
<span class="submitted"><?php print $submitted; ?></span>
<?php endif; ?>


<?php if ($links): ?>
<div class="links"><?php print $links; ?></div>
<?php endif; ?>


I definitely hope that this might have solve his issue who has raised it in Drupal Themes community. If you feel any issues, please let me know I will try to help as much as possible.

Wednesday, August 19, 2009

Clear Cache in Mac OS X might increase fast bootup

Last week I went to a service center to ask why my Mac book is slow only while booting. One of the suggestion was that RAM present in the Mac to be increased which might cost little expensive. This was definite but spending money would mean that we need to think really is that needed ? Anyway I also asked him is there any other way without spending money really much. He suggested two ways which help to improve the Mac performance better.

a) To clear the caches

To clear the cache you need to move all the files from /Library/Caches to Trash
Also Move all the files from /Users//Library/Caches to Trash

b) Need to have 60 GB of free space

I have a HDD of 200 GB and 2GB RAM in which 1GB RAM is fully utilized by the Mac Leopard itself. Whenever I have less than 40GB of space, my Mac drive slowly and sometimes i feel its hanged but never.

Hope this might solve you too.

Friday, August 14, 2009

use sed to find and replace a particular text

One of my colleague asked me how to find and replace a particular text in a remote shell where X Windows / any IDE is not available. I just googled for sometime and then I tried my self with only one hint to use the sed command. You will not believe I tried it for 5 times and I got the thing working at the 6 attempt, wow i felt so happy. Anyway back to the command, please use the below command to find and replace in any file.

sed -i "s/example/sample/g" *

The above command will find "example" text in all the files present in the current directory and replaces them with "sample" text. The text example / sample not only accepts exact words but regular expression is also possible.

Please feel free to ask me if you need any help regarding this.