Memory Game: JQUERY


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame
        Remove this if you use the .htaccess -->
        
        <meta http-equiv="pragma" content="no-cache" />
        <title>Memory Test</title>
        <meta name="description" content="" />
        <meta name="author" content="Mayank Johri" />

        <meta name="viewport" content="width=device-width; initial-scale=1.0" />

        <!-- Replace favicon.ico & apple-touch-icon.png in the root of your domain and delete these references -->
        <link rel="shortcut icon" href="/favicon.ico" />
        <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
        <style>
            #quest{
                width: 24em;
                height:24em;
                margin-left:auto;
                margin-right:auto;
                border: 1px solid #1E90FF;
            }
            .mango{
                height: 4em;
                width: 4em;
                margin: 1em;
                float: left;
                background: url(imgs/mango.svg) ;
                background-size: 4em 4em;                
            }
            .orange{
                height: 4em;
                width: 4em;
                margin: 1em;
                float: left;
                background: url(imgs/Orange_Icon.svg) ;
                background-size: 4em 4em;                
            }
            .grapes{
                height: 4em;
                width: 4em;
                margin: 1em;
                float: left;
                background: url(imgs/grape_red.svg) ;
                background-size: 4em 4em;                
            }
            .freshorange2{
                height: 4em;
                width: 4em;
                margin: 1em;
                float: left;
                background: url(imgs/freshorange2.svg) ;
                background-size: 4em 4em;                
            }
            .Peach{
                height: 4em;
                width: 4em;
                margin: 1em;
                float: left;
                background: url(imgs/Peach.svg) ;
                background-size: 4em 4em;                
            }
            .passion{
                height: 4em;
                width: 4em;
                margin: 1em;
                float: left;
                background: url(imgs/passion.svg) ;
                background-size: 4em 4em;                
            }
            .watermelon{
                height: 4em;
                width: 4em;
                margin: 1em;
                float: left;
                background: url(imgs/watermelon.svg) ;
                background-size: 4em 4em;                
            }
            .apple{
                height: 4em;
                width: 4em;
                margin: 1em;
                float: left;
                background: url(imgs/Red_Apple.svg) ;
                background-size: 4em 4em;                
            }
            .pineapple{
                height: 4em;
                width: 4em;
                margin: 1em;
                float: left;
                background: url(imgs/Pineapple.svg) ;
                background-size: 4em 4em;                
            }
            .box{
                /*background-color: #0000FF;*/                
                height: 4em;
                width: 4em;
            }
            .blank{
                background-color: #FF9933;
                
                height: 4em;
                width: 4em;
            }
        </style>
    </head>

    <body>
        <div style="text-align: center;">
            <header>
                <h1>Memory Game</h1>
            </header>
            <div id="quest">

            </div>
            <div style="clear: both;" style="text-color: blue" >Click Count: <span id="count">0</span> | Items Left: <snap id="left">16</span> </div>
            <footer>
                <p>
                    &copy; Copyright  by Mayank Johri
                </p>
            </footer>
        </div>
        

        <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
        <script>
            count = 0;
            Array.prototype.shuffle = function () {
                for (var i = this.length - 1; i > 0; i--) {
                    var j = Math.floor(Math.random() * (i + 1));
                    var tmp = this[i];
                    this[i] = this[j];
                    this[j] = tmp;
                }
            
                return this;
            }
            
            $().ready(function(){
                count = 0;
                objs = new Array("orange", "apple", "grapes", "freshorange2", "Peach","mango", "passion", "watermelon",
                             "orange", "apple", "grapes", "freshorange2", "Peach","mango", "passion", "watermelon")
                objs.shuffle();
                for (var index = 0; index < objs.length; ++index) {
                    $("#quest").append(
                        "<div class='" + objs[index] + "'> \
                        <div class='blank'>    </div>"
                    )
                }
                $("#quest>div").on("click", function(){
                    count++;
                    $("#count").text(count);
                    $(this).find(">div").toggleClass("blank box");
                    if($("#quest>div>.box").length == 2){
                        var other = $("#quest>div>.box").parent().not($(this)).attr("class");
                        if($(this).hasClass(other)){
                            $("#quest>div>.box").parent().css({"visibility":"hidden"});
                            $("#quest>div>.box").toggleClass("blank box");
                        }else{                        
                            $("#quest>div>.box").toggleClass("blank box");                
                        }
                    }else{
                    }
                })                
            })
        
        </script>
    </body>
</html>

TIPS: WMI: VBScript: Start a process with different priority


dim intProcessID
Const HIGH = 128
strComputer = “.”

Set objWMIService = GetObject(“winmgmts:\\” & strComputer & “\root\cimv2:Win32_Process”)
Set objStartup = GetObject(“winmgmts:\\” & strComputer & “\root\cimv2:Win32_ProcessStartup”)
objStartup.PriorityClass = HIGH          !!!!! ‘ Here you can define the priority of the process. !!!!!!
Set objConfig = objStartup.SpawnInstance_
objWMIService.Create( sCommand, sWorkingDir, objConfig, intProcessID)

TIPS: VBScript : Get Logged in username using VBScript.


  • Using Environment Variable

Set wshShell = WScript.CreateObject( “WScript.Shell” )
strUserName = wshShell.ExpandEnvironmentStrings( “%USERNAME%” )
WScript.Echo “User Name: ” & strUserName

  • Using WshNetwork

Set wshNetwork = WScript.CreateObject( “WScript.Network” )
strUserName = wshNetwork.UserName
WScript.Echo “User Name: ” & strUserName

  • Using ADSI (ADSystemInfo)

Set objSysInfo = CreateObject( “ADSystemInfo” )
strUserName = objSysInfo.UserName
WScript.Echo “User Name: ” & strUserName

  • ADSI (WinNTSystemInfo)

Set objSysInfo = CreateObject( “WinNTSystemInfo” )
strUserName = objSysInfo.UserName
WScript.Echo “User Name: ” & strUserName

  • WMI (Win32_ComputerSystem)

Set objWMI = GetObject( “winmgmts:\\.\root\cimv2” )
Set colItems = objWMI.ExecQuery( “Select * from Win32_ComputerSystem” )
For Each objItem in colItems
strUserName = objItem.UserName
Next

 

Code: Freebasic: runas


#Include "windows.bi"
#inclib "advapi32"

Declare FUNCTION CreateProcessWithLogonW LIB "ADVAPI32" ALIAS "CreateProcessWithLogonW" ( _
        byval lpUsername As LPCWSTR  , _
        BYVAL lpDomain AS LPCWSTR , _
        BYVAL lpPassword AS LPCWSTR, _
        BYVAL dwLogonFlags AS DWORD, _
        BYVAL lpApplicationName AS LPCWSTR , _
        BYVAL lpCommandLine AS LPCWSTR , _
        BYVAL dwCreationFlags AS DWORD, _
        BYVAL lpEnvironment AS DWORD, _
        BYVAL lpCurrentDirectory AS LPCWSTR , _
        lpStartupInfo AS STARTUPINFO, _
        lpProcessInfo AS PROCESS_INFORMATION) AS LONG

Const X_CJ_LOGON_WITH_PROFILE=1
Const X_CJ_CREATE_DEFAULT_ERROR_MODE = &H04000000

FUNCTION RunAsUser(BYVAL UserName AS STRING, _                   
        BYVAL Password AS STRING, _
        BYVAL DomainName AS STRING, _
        BYVAL CommandLine AS STRING, _
        BYVAL CurrentDirectory AS STRING) AS boolean

        Dim si AS STARTUPINFO
        Dim pi AS PROCESS_INFORMATION
        Dim AS String wCurrentDir,wCommandLine,wPassword,wUser,wDomain
        Dim R01 AS LONG

        si.cb = LEN(si)
        wUser = UserName
        wDomain = DomainName
        wPassword = Password
        wCommandLine = CommandLine
        wCurrentDir = CurrentDirectory
        Print wCommandLine & "TEST"
        R01 = CreateProcessWithLogonW(wUser,wDomain,wPassword, _
                        X_CJ_LOGON_WITH_PROFILE, 0&, wCommandLine, _
                        X_CJ_CREATE_DEFAULT_ERROR_MODE, 0&, wCurrentDir, si, pi)
        IF R01  0 THEN
                CloseHandle pi.hThread
                CloseHandle pi.hProcess
                Return TRUE
        ELSE
                Return FALSE
        END If
End FUNCTION

Dim As Long R01
Dim As String  user_name,password,domain,program,workingDir

user_name="username"
password="pa$$word"
domain="domain"
program="C:\\windows\\notepad.exe"
workingDir="C:\\windows"

R01=RunAsUser(user_name,password,domain,program,workingDir)

Restarted working on mayaDeploy


I have restarted the coding of mayadeploy, a Full Package Management Solution for Small Business, It will be re-coded in Python & G++, using WX as GUI library.

Few silent features are as follows,

  1. Based on Server & Client architecture
  2. Using this managers will be able to deploy packages on to his reportee’s computer without any human intervention. (Only for App-V Packages for now)
  3. Will support following file types for deployment:- msi, exe, batch files, App-V Packages
  4. Ver: 2 will support even hardware & software reporting
  5. Will have entire Software Life cycle support.
    1. New Software request or Existing Software request
    2. Integration, packaging, UAT and Deployment lifecycle integrated.

as always i am requesting yours comments and suggestions to make it a success.

Tips: Python : wxFormBuilder v3.1.67-beta (Febuary 18, 2010) Python Update


Latest version of wxFormBuilder does not support wxAdditions fully, thus I have updated few XML files to support FlatNotebook & wx.propgrid widgets.

  1. Download wx.propgrid and install it.
  2. Download the XML.Zip folder and extract it in plugins\wxAdditions\xml folder.
  3. Restart the wxformbuilder.

I did not tried to update these files for other widgets but it should be similar.

Tips: MSI: Save differences between two msi as MST file using ruby & python


Ruby

require ‘win32ole’
msiClass = WIN32OLE.new(“WindowsInstaller.Installer”)
msidb = msiClass.OpenDatabase(“C:\\temp\\MountPointGenerator.msi”,0)
newmsidb = msiClass.OpenDatabase(“C:\\temp\\updatedMountPointGenerator.msi”,0)
transform = newmsidb.GenerateTransform(msidb,”c:\\temp\\newtest.mst”)

Python

import win32com.client
import os
import sys

msiOpenDatabaseModeReadOnly=0
msidb=r”c:\temp\MountPointGenerator.msi”
msiupdb=r”c:\temp\updatedMountPointGenerator.msi”
mstdb=r”C:\temp\MNPtrans.mst”

installer = win32com.client.Dispatch(“WindowsInstaller.Installer”)
database = installer.OpenDatabase(msidb, msiOpenDatabaseModeReadOnly)
updatedDB= installer.OpenDatabase(msiupdb , msiOpenDatabaseModeReadOnly)
updatedDB.GenerateTransform(database, mstdb)

Python: World Clock


import time
import wx
import wx.gizmos as gizmos
from datetime import datetime
from pytz import timezone
import pytz

utc = pytz.utc
    
class LED_clock(wx.Frame):
    """
    Create nice LED clock showing the current time
    """
    def __init__(self, parent, id):
        pos = wx.DefaultPosition
        wx.Frame.__init__(self, parent, id, title='maya World Clock, Ver: 0.0.1', pos=pos, size=(200, 70))
        self.SetIcon(wx.Icon(r"clock.ico", wx.BITMAP_TYPE_ICO))
        size = wx.DefaultSize
        style = gizmos.LED_ALIGN_CENTER
        self.estLed = gizmos.LEDNumberCtrl(self, -1, pos, size, style)
        self.m_stESTTime = wx.StaticText( self, wx.ID_ANY, u"EST Time", wx.DefaultPosition, wx.DefaultSize, wx.ALIGN_CENTRE|wx.STATIC_BORDER )
        self.m_stESTTime.SetBackgroundColour( wx.Colour( 255, 221, 187 ) )
        bSizer4 = wx.BoxSizer( wx.HORIZONTAL )
        bSizer5 = wx.BoxSizer( wx.VERTICAL )
        bSizer5.Add(self.m_stESTTime, 0, wx.ALIGN_CENTER|wx.ALIGN_CENTER_VERTICAL|wx.ALL|wx.EXPAND, 0 
        bSizer5.Add(self.estLed, 1, wx.EXPAND, 5 )
        bSizer4.Add(bSizer5, 1, wx.EXPAND, 5 )
        self.m_stIndiaTime = wx.StaticText( self, wx.ID_ANY, u"IST Time", wx.DefaultPosition, wx.DefaultSize,  wx.ALIGN_CENTRE|wx.STATIC_BORDER )
        self.m_stIndiaTime.SetBackgroundColour( wx.Colour( 255, 221, 187 ) )
        self.indiaLed = gizmos.LEDNumberCtrl(self, -1, pos, size, style)
        bSizer1 = wx.BoxSizer( wx.VERTICAL )
        bSizer1.Add(self.m_stIndiaTime , 0, wx.EXPAND|wx.ALIGN_CENTER|wx.ALIGN_CENTRE_HORIZONTAL, 5 )
        bSizer1.Add(self.indiaLed, 1, wx.EXPAND, 5 )
        bSizer4.Add(bSizer1, 1, wx.EXPAND, 5 )
        self.SetSizer( bSizer4 )
        self.Layout()
        self.OnTimer(None)
        self.timer = wx.Timer(self, -1)
        self.timer.Start(1000)
        self.Bind(wx.EVT_TIMER, self.OnTimer)
        self.Centre()

    def GetIndiaTime(self):
        fmt = '%H %M %S'
        india = timezone('Asia/Kolkata') #('Asia/Kolkata')
        eastern = timezone('US/Eastern')
        loc_dt = eastern.localize(datetime.now())
        in_dt = loc_dt.astimezone(india)
        return (in_dt.strftime(fmt))

    def OnTimer(self, event):
        current = time.localtime(time.time())
        ts = time.strftime("%H %M %S", current)
        self.estLed.SetValue(ts)
        tst = self.GetIndiaTime()
        self.indiaLed.SetValue(tst)

if __name__ == '__main__':
    app = wx.App()
    frame = LED_clock(None, -1)
    frame.Show(True)
    app.SetTopWindow(frame)
    app.MainLoop()

Demo Calender in wx.python


This is my wx.Calender demo in wx.python

###########################################################################
# -*- coding: ISO-8859-1 -*-
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program.  If not, see <http://www.gnu.org/licenses>.
__author__ = "Mayank Johri"
__copyright__  = "2009"
__version__ = "0.0.1"
__date__ = "Oct 13 2009"
__license__ = "GNU 3 or latest."
###########################################################################
import re
import datetime
import calendar
import wx
import string
import wx.calendar as cal
import sys
import os
APPDIR = sys.path[0]
TBMENU_RESTORE = wx.NewId()
TBMENU_CLOSE   = wx.NewId()
year = ['January',
     'February',
     'March',
     'April',
     'May',
     'June',
     'July',
     'August',
     'September',
     'October',
     'November',
     'December']
def thismonth():
    """ Presently not using"""
    calendar.setfirstweekday(0)
    today = datetime.datetime.date(datetime.datetime.now())
    current = re.split('-', str(today))
    current_no = int(current[1])
    current_month = year[current_no-1]
    current_day = int(re.sub('\A0', '', current[2]))
    current_yr = int(current[0])
    myCal = '%s %s' %(current_month, current_yr)
    myCal = myCal + '\n' + "M  T  W  Th F  Sa Su" + '\n'
    month = calendar.monthcalendar(current_yr, current_no)
    nweeks = len(month)
    for w in range(0,nweeks):
        week = month[w]
        for x in xrange(0,7):
            day = week[x]
            if x == 5 or x == 6:
                classtype = 'weekend'
            else:
                classtype = 'day'
            if day == 0:
                classtype = 'X'
                myCal = myCal + str(classtype).ljust(3)
            elif day == current_day:
                myCal = myCal + str(day).ljust(3)
            else:
                myCal = myCal + str(day).ljust(3)
        myCal = myCal + '\n'
    return (myCal)
class MyTaskBarIcon(wx.TaskBarIcon):
    def __init__(self, frame):
        wx.TaskBarIcon.__init__(self)
        self.frame = frame
        icon = wx.Icon(os.path.join(APPDIR, 'clock.ico'), wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)
        self.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, self.OnTaskBarRightClick)
        self.Bind(wx.EVT_MENU, self.OnTaskBarActivate, id=1)
        self.Bind(wx.EVT_MENU, self.OnTaskBarClose, id=2)
    def OnTaskBarRightClick(self, event):
        if not self.frame.IsShown():
            self.frame.Show()
        else: self.frame.Hide()
    def CreatePopupMenu(self):
        menu = wx.Menu()
        menu.Append(1, 'Show/Hide')
        menu.Append(2, 'Close')
        return menu
    def OnTaskBarClose(self, event):
        self.Destroy()
        self.frame.Destroy()

    def OnTaskBarActivate(self, event):
        if not self.frame.IsShown():
            self.frame.Show()
        else: self.frame.Hide()
    def OnTaskBarDeactivate(self, event):
        if self.frame.IsShown():
            self.frame.Hide()
class MayaCalendar(wx.Dialog):
    def __init__(self, parent, id, title):
        wx.Dialog.__init__(self, parent, title="Maya Calender, Ver: 0.0.1")
        vbox = wx.BoxSizer(wx.VERTICAL)
        calend = cal.CalendarCtrl(self, -1, wx.DateTime_Now(),
            style = cal.CAL_SHOW_HOLIDAYS|cal.CAL_SEQUENTIAL_MONTH_SELECTION)
        vbox.Add(calend, 0, wx.EXPAND | wx.ALL, 20)
        self.Bind(cal.EVT_CALENDAR, self.OnCalSelected, id=calend.GetId())
        self.SetSizerAndFit(vbox)
        self.Show(True)
        self.tskic = MyTaskBarIcon(self)
        self.Centre()
    def OnCalSelected(self, event):
        date = event.GetDate()
        dt = string.split(str(date), ' ')
        s = ' '.join([str(s) for s in dt])
        self.text.SetLabel(s)
class MyApp(wx.App):
    def OnInit(self):
        frame = MayaCalendar(None, -1, 'Maya Calender, Ver: 0.0.1')
        frame.Show(True)
        self.SetTopWindow(frame)
        return True
app = MyApp(0)
app.MainLoop()

demo code for wx.TaskBarIcon


Below is the demo code for wx.TaskBarIcon,

import wx
class sysTrayDemo(wx.Frame):
    def __init__(self, parent, id, title):
        pass
        wx.Frame.__init__(self, parent, -1, title, size = (800, 600),
                         style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE)
        # FIXME: substitute your icon file here.
        icon = wx.Icon('systray.ico', wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)
        if wx.Platform == '__WXMSW__':
            # setup a taskbar icon, and catch some events from it
            self.tbicon = wx.TaskBarIcon()
            self.tbicon.SetIcon(icon, "SysTray Demo")
            wx.EVT_TASKBAR_LEFT_DCLICK(self.tbicon, self.OnTaskBarActivate)
            wx.EVT_TASKBAR_RIGHT_UP(self.tbicon, self.OnTaskBarMenu)
            wx.EVT_MENU(self.tbicon, self.TBMENU_RESTORE, self.OnTaskBarActivate)
            wx.EVT_MENU(self.tbicon, self.TBMENU_CLOSE, self.OnTaskBarClose)
        wx.EVT_ICONIZE(self, self.OnIconify)
        return
    def OnIconify(self, evt):
        self.Hide()
        return
    def OnTaskBarActivate(self, evt):
        if self.IsIconized():
            self.Iconize(False)
        if not self.IsShown():
            self.Show(True)
        self.Raise()
        return
    def OnCloseWindow(self, event):
        if hasattr(self, "tbicon"):
            del self.tbicon
        self.Destroy()
    TBMENU_RESTORE = 1000
    TBMENU_CLOSE   = 1001
    def OnTaskBarMenu(self, evt):
        menu = wx.Menu()
        menu.Append(self.TBMENU_RESTORE, "Restore SysTray Demo")
        menu.Append(self.TBMENU_CLOSE,   "Close")
        self.tbicon.PopupMenu(menu)
        menu.Destroy()
    #---------------------------------------------
    def OnTaskBarClose(self, evt):
        self.Close()
        # because of the way wx.TaskBarIcon.PopupMenu is implemented we have to
        # prod the main idle handler a bit to get the window to actually close
        wx.GetApp().ProcessIdle()
class MyApp(wx.App):
    def OnInit(self):
        self.redirect=True
        frame = sysTrayDemo(None, -1, "SysTray Demo")
        frame.Show(True)
        return True
def main():
    app = MyApp()
    app.MainLoop()
if __name__ == '__main__':
    main()

Howto: Delete Rows in wx.Grid


def fm_bDeleteServerDetails(self, event):
lst = self.m_gdServerDetails.GetNumberRows()
selected = []
for r in range(lst):
if self.m_gdServerDetails.IsInSelection(r, 0) == True:
selected.append(r)
selected.reverse()
for r in selected:
self.m_gdServerDetails.DeleteRows(r,1)
	def fm_bDeleteServerDetails(self, event):
		lst = self.m_gdServerDetails.GetNumberRows()
		selected = []
		for r in range(lst):
			if self.m_gdServerDetails.IsInSelection(r, 0) == True:
				selected.append(r)
		selected.reverse()
		for r in selected:
			self.m_gdServerDetails.DeleteRows(r,1)

creating windows service using pyinstaller


copied from http://www.nabble.com/windows-service-sample-using-pyInstaller-td16626208.html

# Usage: 
# service.exe install
# service.exe start
# service.exe stop
# service.exe remove

# you can see output of this program running python site-packages\win32\lib\win32traceutil 

import win32service

import win32serviceutil
import win32event
import win32evtlogutil
import win32traceutil
import servicemanager
import winerror
import time
import sys

class aservice(win32serviceutil.ServiceFramework):

    _svc_name_ = "aservice"
    _svc_display_name_ = "aservice - It Does nothing"
    _svc_deps_ = ["EventLog"]

    def __init__(self,args):
        win32serviceutil.ServiceFramework.__init__(self,args)

        self.hWaitStop=win32event.CreateEvent(None, 0, 0, None)
    self.isAlive=True

    def SvcStop(self):

        # tell Service Manager we are trying to stop (required)
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)


    # write a message in the SM (optional)
        # import servicemanager
        # servicemanager.LogInfoMsg("aservice - Recieved stop signal")

    # set the event to call
        win32event.SetEvent(self.hWaitStop)


    self.isAlive=False

    def SvcDoRun(self):
        import servicemanager
        # Write a 'started' event to the event log... (not required)
       
#
win32evtlogutil.ReportEvent(self._svc_name_,servicemanager.PYS_SERVICE_STARTED,0,
servicemanager.EVENTLOG_INFORMATION_TYPE,(self._svc_name_, ''))


        # methode 1: wait for beeing stopped ... 
        # win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)

        # methode 2: wait for beeing stopped ...
        self.timeout=1000  # In milliseconds (update every second) 


        while self.isAlive:

            # wait for service stop signal, if timeout, loop again
            rc=win32event.WaitForSingleObject(self.hWaitStop, self.timeout) 

            print "looping"


        # and write a 'stopped' event to the event log (not required)
       
#
win32evtlogutil.ReportEvent(self._svc_name_,servicemanager.PYS_SERVICE_STOPPED,0,
servicemanager.EVENTLOG_INFORMATION_TYPE,(self._svc_name_, ''))


        self.ReportServiceStatus(win32service.SERVICE_STOPPED)

    return

if __name__ == '__main__':

    # if called without argvs, let's run !

    if len(sys.argv) == 1:
        try:

        evtsrc_dll = os.path.abspath(servicemanager.__file__)
        servicemanager.PrepareToHostSingle(aservice)
        servicemanager.Initialize('aservice', evtsrc_dll)
            servicemanager.StartServiceCtrlDispatcher()

        except win32service.error, details:
            if details[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
                win32serviceutil.usage()
    else:
        win32serviceutil.HandleCommandLine(aservice)

Get the windows service state using Python


following code can be used to find if any service is installed and if so then return the state of the service.

import wmi

class servicePython():
    def __init__(self, serviceName):
        self.c = wmi.WMI ()
        self.serviceName = serviceName

    def setServiceName(self, serviceName):
        self.serviceName = serviceName

    def getStatus(self):    
        srv = c.Win32_Service (name=self.serviceName)
        if srv != []:
            return c.Status
        return False

recursive list files in a dir using Python


use the following code to list the files in a dir tree

import os
import sys
fileList = []
rootdir = sys.argv[1]
for root, subFolders, files in os.walk(rootdir):
    for file in files:
        fileList.append(os.path.join(root,file))
print fileList

#================================================================================
# List of all the files, total count of files and folders & Total size of files.
#================================================================================
import os
import sys

fileList = []
fileSize = 0
folderCount = 0
rootdir = sys.argv[1]

for root, subFolders, files in os.walk(rootdir):
    folderCount += len(subFolders)
    for file in files:
        f = os.path.join(root,file)
        fileSize = fileSize + os.path.getsize(f)
        #print(f)
        fileList.append(f)

print("Total Size is {0} bytes".format(fileSize))
print(“Total Files “, len(fileList))
print(“Total Folders “, folderCount)