rabid logic

    • 0
      23 Aug 2012

      To Remove Extra Spaces From A String in Python

      • Edit
      • Delete
      • Tags
      • Autopost

      >>> a='To be    or      not to   be'
      >>> ' '.join(a.split())
      'To be or not to be'

       

      Use ' '.join(a.split())

      • views
      • Tweet
    • 0
      23 Aug 2012

      Print an amount in words using Python - Indian Format

      • Edit
      • Delete
      • Tags
      • Autopost

      A little script i've written to convert an amount of upto 14 digits before the decimal into words.I have a 14 digit limit which conforms with the accounting package tally which is predominantly used here.Million, billions trillions etc aren't used to decribe large sums of money but lakhs and crores are used instead..

      XX,XX,XXX

      The indian format does not seperate the number in 3's as done in the US here its 2-2-3

      So for 14 digits the separation is as follows

      XX,XX,XXX,XX,XX,XXX

       

      instructions: paste the code and call the the in_words() function passing it a float formatted to 2 digits after the decimal.

       

      #Constants
      ONES={0:'',1:'One',2:'Two',3:'Three',4:'Four',
            5:'Five',6:'Six',7:'Seven',8:'Eight',
            9:'Nine',10:'Ten',11:'Eleven',12:'Twelve',
            13:'Thirteen',14:'Fourteen',15:'Fifteen',
            16:'Sixteen',17:'Seventeen',18:'Eighteen',19:'Nineteen'}

      TENS={2:'Twenty',3:'Thirty',4:'Forty',5:'Fifty',6:'Sixty',7:'Seventy',8:'Eighty',9:'Ninety'}

      #Functions
      def parse_amt2words(ns):
          ns1=ns[-3:]
          ns2=ns[-5:-3]
          ns3=ns[-7:-5]
          if len(ns1)>0 and int(ns1)>0:
              if len(ns1[-2:-1])>0 and int(ns1[-2:-1])>1:
                  a= '%s %s'%(TENS[int(ns1[-2:-1])],ONES[int(ns1[-1:])])
              else:
                  a= '%s'%(ONES[int(ns1[-2:])],)
                 
                 
              if len(ns1[-3:-2])>0 and int(ns1[-3:-2])>0:
                  a= '%s Hundred %s'%(ONES[int(ns1[-3:-2])],a)
             
          if len(ns2)>0 and int(ns2)>0:
              if len(ns2[-2:-1])>0 and int(ns2[-2:-1])>1:
                  a= '%s %s Thousand %s'%(TENS[int(ns2[-2:-1])],ONES[int(ns2[-1:])],a)
              else:
                  a= '%s Thousand %s'%(ONES[int(ns2[-2:])],a)
         
          if len(ns3)>0 and int(ns3)>0:
              if len(ns3[-2:-1])>0 and int(ns3[-2:-1])>1:
                  a= '%s %s Lakh %s'%(TENS[int(ns3[-2:-1])],ONES[int(ns3[-1:])],a)
              else:
                  a= '%s Lakh %s'%(ONES[int(ns3[-2:])],a)
          return ' '.join(a.split())

       

      #split into 7 chunks.. since its to be used with tally which supports 14 digits -done manually

      def amt2words(n): 
          ns=str(n)
          if len(ns)>14:
              return 'Number too large'
          if len(ns)<=7:
              return '%s'%(parse_amt2words(ns[-7:]),)
          else:
              return '%s Crore %s'%(parse_amt2words(ns[-14:-7]),parse_amt2words(ns[-7:]))

       

      #take the number seperate at decimal point for decimal use 2 digits only
      def in_words(x):
              #return mdc_report_func.amt2words(int(x))
              if isinstance(x,float):
                  rs=int(x)
                  ps=int(str(x)[-2:])
              elif isinstance(x,int):
                  rs=int(x)
                  ps=0
              else:
                  return x
              if rs>0:
                  rs1=amt2words(rs)
              else:
                  rs1=''
              if ps>0:
                  ps1=' And %s Paise'%(amt2words(ps),)
              else:
                  ps1='' 
              y = '%s%s Only'%(rs1,ps1)
              return y

      print in_words(50430112.55)

       

      May not the best or even the best piece of code to do this task but it took me about 20 minutes to do and it works so.. use it at your own risk if you need help to understand it drop me a line..

      • views
      • Tweet
    • 0
      14 Sep 2011

      SQL Differences in PostgreSQL

      • Edit
      • Delete
      • Tags
      • Autopost
      1. NO TOP, so SELECT TOP 10 * FROM table, becomes SELECT * FROM table LIMIT 10 you can also use the maxrows attribute of CFQUERY to do this, if you want cross db code (which is good). MySQL also uses the LIMIT sytax, but Oracle uses yet another syntax
      2. LIKE statements are case sensitive in postgresql, they can be made case insensitive like this: SELECT * FROM table WHERE LOWER(column) LIKE '%#LCase(var)#%' (Or you can use the ILIKE operator)
      3. The plus operator cannot be used for concatination so SELECT firstname + ' ' + lastname AS fullname becomes SELECT firstname || ' ' || lastname AS fullname this way works on both servers.

      sourced from:
      http://www.petefreitag.com/item/5.cfm

      • views
      • Tweet
    • 0
      5 Sep 2011

      Removing list elements by looping

      • Edit
      • Delete
      • Tags
      • Autopost
      While looping through a list - list index nos. 0- n are used to iterate through the list items

      parent = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
      child = ['a', 'b', 'c', 'd']

      child index nos.
      a = 0
      b = 1
      c=  2
      d = 3

      If there is a need to remove items from one list based on those present in another (parent) - logically it would require iterating through the child list and removing those items that exist in the parent list

      so the foll code should do the trick..

      parent = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
      child = ['a', 'b', 'c', 'd']

      for c in child:
       if c in parent:
        child.remove(c)

      however if you print child it will output [b,d]

      The reason is that python resets the index nos. of the list after the removal of an item. 
      So in effect after 'a' (index 0) is removed from the child list - 'b' is set as index 0. The next loop by will pass index 1 which is now 'c'. As a consequence 'b' never enters the loop and therefore not checked if it exists in the parent list and hence not removed.

      Solution:
      Instead of using the actual list in the for loop, iterate through a copy of the list using [:] and carry out the removal from the original list.

      parent = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
      child = ['a', 'b', 'c', 'd']

      for c in child[:]:
       if c in parent:
        child.remove(c)

      now when you print child the output is as expected an empty list []
      • views
      • Tweet
    • 0
      8 Aug 2011

      PyImportScript

      • Edit
      • Delete
      • Tags
      • Autopost
      -:WIP:-

      Part A
      1
      Get List of Machines from mdc_mach table on postgresql
      select name from
      mdc_machines where type = 1 

      Store each machine type in a sep List inside a Dictionary
      {
      'Ex':[MDC Excavator 1, .....],
      'WL':[],
      'Trucks':[]....
      }

      2
      Check returned list in Access Db for new Machines
      select mach.name, owner from
      mdc_machines as mm where mach.name not in (RETURNED LIST)

      This has to be done for each mach_type as the tables in access are separate for each.

      The new Machines should be appended into a List
      [['0981','GA-09-0981','Owner'],['WL223','', 'Owner'],...]

      And a second List with only Owner Names

      Check if all owners are present: [What about change in owners?]

      Query Postgresql to see if all the names are present

      select name from
      res_partner where lower(name) in (lower('AsUstek'))

      Count of the rows should be equal to that of the owner list

      If less then then some owners are not present in openerp
      Compare list to query result and find the missing owner add to owner_exlist

      For each Owner in the exlist get - Name, Address, Phone details and create a Partner in Openerp

      Now that all Owners are in the system Start Import of machines


      Insert New Machines into mdc_machines directly and assoc with the site in mdc_site_machines


      4
      Check all Machines in access are assoc with the same site in Postgres
      select mach.name from
      mdc_site_machines as msm
      inner join
      mdc_machines as mach
      on msm.mach_id = mach.id
      where msm.site_id = 1

      5
      Check returned list in Access Db - The Result should be 0
      In the previous steps all machines in the access db were updated in Postgres. If a machine is returned here then that mach exists in the Openerp but is assoc with another site.
      This has to be rectified manually as the reason for this move needs to be obtained

      select mach.name, owner from
      mdc_machines as mm where mach.name not in (RETURNED LIST)


      IF STEP 5 returns 0 then Proceed or Terminate Here


      Part B
      B-1
      Check if the Dist Codes are in the System

      B-2 ====>not a good idea - add manually -awareness
      Import New Dist Codes


      B-3
      Check if the Ore Types are in the system


      B-4 ====>not a good idea - add manually -awareness
      Import New Ore Types


      site pits?
      operator?
      supervisor?


      Part
      -1
      Check for New MDLs

      1
      Get List of MDL + Date + Machine Names in Postgresql db

      select mdl.date, mach.name from mdc_mdl as mdl inner join mdc_machines
      as mach on mdl.mach_id = mach.id where mdl.site_id = 1


      2
      Compare the Returned list with the access db

      *select mdl.date, mach.name from mdc_mdl as mdl inner join mdc_machines
      as mach on mdl.mach_id = mach.id where mdl.site_id = 1 and date not in (RETURNED LIST - DATE VAUES)


      3
      Store List of MDL Date- Machines that need to be imported from Access

      4
      For each (One Transaction if Possible):
      Get the MDL and Trips for the New MDL
      Ex/WL
      PV
      Wtanker

      Insert the New MDL+Trips directly into MDL/Trips/Log Hours on Postgresql

      • views
      • Tweet
    • 0
      4 Aug 2011

      Connecting & Querying from MS Access (accdb) in python

      • Edit
      • Delete
      • Tags
      • Autopost

      Ive got an MS Access accdb file that from which I need to extract data programatically and insert it into Postgresql
      This post deals with connecting to and querying data from MS Access 2007 on Windows 7 using Python 2.7

      The simplest approach is to use pyodbc - a python package which is based on the Open Database Connectivity (ODBC) API

      First get pyodbc: http://code.google.com/p/pyodbc/

      Its available as an exe so simply double click to install on windows. For linux the source is available and is installed via distutils by running...

      sudo python setup.py install

      ...from within the pyodbc directory


      A connection is made to the access database by

      connection = pyodbc.connect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=path_to_file;")

      A query is executed via a cursor object

      eg:

      Start python within cmd or terminal and enter the following:


      >>> import pyodbc
      >>> conn = pyodbc.connect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ
      =C:\\access\\site_be.accdb;")
      >>> cursor = conn.cursor()
      >>> sql = "select * from dist_code;"
      >>> for row in cursor.execute(sql):
      ...  print row.dist_code
      ...
      250
      500
      750
      1000
      1250
      1500
      1750
      2000
      2250
      2500
      2750
      3000
      WT140
      WT180
      >>> cursor.close()
      >>> conn.close()
      >>>

      Note: For this eg to work "literally" you would need to create an access db site_be.accdb and place it in C:\access\
      The database should contain atleast one table - dist_code and this table would need to contain one column dist_code

      Notice the escaped backslashes in the connection assignment - "C:\\access\\site_be.accdb"
      If \ is used instead of \\ you would get an error:

      Traceback (most recent call last):
      File "", line 1, in conn = pyodbc.connect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=;")

      Error: ('HY000', "[HY000] [Microsoft][ODBC Microsoft Access Driver]General error Unable to open registry key Temporary (volatile) Ace DSN for process 0x167c Thread 0x1568 DBC 0x1c67a5c

      Jet'. (63) (SQLDriverConnectW); [HY000] [Microsoft][ODBC Microsoft Access Driver]General error Unable to open registry key Temporary (volatile) Ace DSN for process 0x167c Thread 0x1568 DBC 0x1c67a5c

      Jet'. (63); [HY000] [Microsoft][ODBC Microsoft Access Driver] Not a valid file name. (-1044); [HY000] [Microsoft][ODBC Microsoft Access Driver]General error Unable to open registry key Temporary (volatile) Ace DSN for process 0x167c Thread 0x1568 DBC 0x1c67a5c

      Jet'. (63); [HY000] [Microsoft][ODBC Microsoft Access Driver]General error Unable to open registry key Temporary (volatile) Ace DSN for process 0x167c Thread 0x1568 DBC 0x1c67a5c

      Jet'. (63); [HY000] [Microsoft][ODBC Microsoft Access Driver] Not a valid file name. (-1044)")

       
      Compiled from:
      http://en.wikibooks.org/wiki/Python_Programming/Database_Programming
      http://code.google.com/p/pyodbc/wiki/GettingStarted

       

      • views
      • Tweet
    • 0
      3 Aug 2011

      View Listening Ports on Linux

      • Edit
      • Delete
      • Tags
      • Autopost

      Find Out What Ports Are Listening / Open On My Linux & FreeBSD Server

      How do I find open ports on Linux / FreeBSD server?

      There are different commands on both Linux and UNIX server to find out what tcp/udp ports are listening or open on your own server. You can use netstat command, which print network connections, routing tables, interface statistics, masquerade connections, and multicast memberships etc. Another (and suggested) option is to use lsof command, which list open files, and ports on Linux, FreeBSD, Solaris and other Unixish systems.

      netstat command to find open ports

      # netstat --listen
      To display open ports and established TCP connections, enter:
      $ netstat -vatn
      To display only open UDP ports try the following command:
      $ netstat -vaun
      If you want to see FQDN (full dns hostname), try removing the -n flag:
      $ netstat -vat

      lsof Command Examples

      To display the list of open ports, enter:
      # lsof -i
      To display all open files, use:
      # lsof
      To display all open IPv4 network files in use by the process whose PID is 9255, use:
      # lsof -i 4 -a -p 9255

      A Note About FreeBSD Users

      You can use the sockstat command lists open Internet or UNIX domain sockets, enter:
      $ sockstat
      $ sockstat -l
      $ sockstat -4 -l
      $ sockstat -6 -l


      From: http://www.cyberciti.biz/faq/how-do-i-find-out-what-ports-are-listeningopen-on-my-linuxfreebsd-server/

      • views
      • Tweet
    • 0
      3 Aug 2011

      Kill Linux Processes

      • Edit
      • Delete
      • Tags
      • Autopost
      From: http://www.cyberciti.biz/faq/kill-process-in-linux-or-terminate-a-process-in-unix-or-linux-systems/

      Kill process in Linux or terminate a process in UNIX or Linux systems

      Q. How do I kill process in Linux?

      A. Linux and all other UNIX like oses comes with kill command. The command kill sends the specified signal (such as kill process) to the specified process or process group. If no signal is specified, the TERM signal is sent.

      Kill process using kill command under Linux/UNIX

      kill command works under both Linux and UNIX/BSD like operating systems.

      Step #1: First, you need to find out process PID (process id)

      Use ps command or pidof command to find out process ID (PID). Syntax:
      ps aux | grep processname
      pidof processname

      For example if process name is lighttpd, you can use any one of the following command to obtain process ID:
      # ps aux | grep lighttpdOutput:

      lighttpd 3486 0.0 0.1 4248 1432 ? S Jul31 0:00 /usr/sbin/lighttpd -f /etc/lighttpd/lighttpd.conflighttpd 3492 0.0 0.5 13752 3936 ? Ss Jul31 0:00 /usr/bin/php5-cg

      OR use pidof command which is use to find the process ID of a running program:
      # pidof lighttpdOutput:

      3486

      Step #2: kill process using PID (process id)

      Above command tell you PID (3486) of lighttpd process. Now kill process using this PID:
      # kill 3486
      OR
      # kill -9 3486
      Where,

      • -9 is special Kill signal, which will kill the process.

      killall command examples

      DO NOT USE killall command on UNIX system (Linux only command). You can also use killall command. The killall command kill processes by name (no need to find PID):
      # killall -9 lighttpd
      Kill Firefox process:
      # killall -9 firefox-bin
      As I said earlier killall on UNIX system does something else. It kills all process and not just specific process. Do not use killall on UNIX system (use kill -9).

      • views
      • Tweet
    • 0
      30 Jul 2011

      Shared Folders in Virtual Box

      • Edit
      • Delete
      • Tags
      • Autopost

      After installing the Guest Additions I managed to get the screen resizing/ full screen functionality to work. However I wasn't able to share the clipboard between the Host and the Guest OS.
      My next best option was using the 'Shared Folder' functionality which wasn't very intuitive

      Some points of note:
      Firstly, the shared folders are made available under /media/ directory in the guest OS
      Secondly, you do not need to allow sharing of a folder on the Host OS inorder to access it from the guest
      Thirdly, in order to access the shares your guest OS user needs to be a member of the group 'vboxsf'
      My Host OS is Ubuntu 11.04 and the Guest is Ubuntu 10.04.3 LTS

      Steps,
      1) Start up and log in to the guest OS
      2) Add yourself to the group vboxsf (System>Users& Groups)
      3) Right Click the blue foder icon and click 'Shared Folders' or Devices>Shared Folders
      4) Add a folder to share. Check make permanent (transient ie only available for this session didn't feel like working for me). Also check Automount.
      5) Log out and back in to let the group permissions set
      6) Browse over to /media/.. The folders that were shared should be available here

      • views
      • Tweet
    • 0
      29 Jul 2011

      Getting around the VBoxGuestAdditions_4.0.4.iso' (VERR_NOT_SUPPORTED) Error

      • Edit
      • Delete
      • Tags
      • Autopost

      I was trying out VirtualBox on ubuntu 11.04 and I wanted to install the "Guest Additions" package in order to increase the screen size of the guest which was ubuntu 10.04.
      So i got the guest os running and then clicked on Devices>Install Guest Additions (Note: the Devices Menu is on the common menu bar on the top in 11.04 and not on the window for Vbox)
      A prompt asked me to download the VBoxGuestAdditions_4.0.4.iso and then another prompt asked to mount it..
      Here i got an error

      "Failed to open the CD/DVD image (then indicated the file path for the ISO)

      Could not get Storage format of the medium (again indicated the file path of the ISO)

      VERR_NOT_SUPPORTED"

      I retried the process about 3 times but in vain..

      Basically the iso file was not downloaded completely.. its about 36 mb and only 10 mb was downloaded before the prompt to mount came up.

      The solution to this is pretty simple.
      Click on install guest additions again.. In the prompt copy the url that its says its goin to get the iso file from.
      Download the file in the Host ie ur desktop
      Shut down the guest os
      Configure the guest os to use the downloaded iso file as the secondary drive.. (under Settings for the Guest in Vbox)
      Start the Guest os
      Now the iso file will be available under places.. Autorun..
      Restart the guest and autoresize screen will now be available..


      • views
      • Tweet
    « Previous 1 2 Next »
    • Search

    • Tags

      • Ubuntu
      • Virtualbox
      • python
      • work around
      • authetication
      • remove spaces
      • convert to words
      • currency
      • format
      • format string
      • indian
      • jasper
      • jasper server
      • lists
      • openerp
      • remove()
    • Obox Design
  • rabid logic


    364 Views
  • Get Updates

    Subscribe via RSS