Categories
Code Snippets

Internet Shortcuts to HTML file – Python

I had problems with the DOS batch file version of this utility so decided to replace it with a more robust version written in Python.

import os
import time
import datetime

# Converting all url files in directory and sub-directories to a single html file

tim = datetime.datetime.now()
tim1 = tim.strftime("%d-%m-%Y")
day = tim.strftime("%d")
mth = tim.strftime("%m")
year = tim.strftime("%Y")

tim2 = tim.strftime("%H:%M:%S")
nameOutput = "Links"+day+mth+year+".html"
nameList = "Links"+day+mth+year+"_list.txt"
print 'Generating list ' + nameOutput +' at '+tim2+' on '+tim1

dir_path = os.getcwd()
listFile = open(nameList, 'w')

with open(nameOutput, 'w') as outputFile:
  outputFile.write( '<h1>List Generated at '+tim2+' on ' + tim1 +'</h1>')

  for dirName, subDirs, files in os.walk(dir_path):
    outputFile.write( '<h3>'+dirName+'</h3>\n' )
    outputFile.write( '<ol>\n' )
    for name in files:
      if name.endswith(".url"):
        with open(dirName+'\\'+name) as fh:
          base, ext = os.path.splitext(name)
          for line in fh:
            if line.startswith("URL="):
              href = line.split("URL=",1)[1].rstrip('\n')
              #href.rstrip('\n')
              outputFile.write( '<li><a href="'+href+'" target="_blank">'+base+'</a></li>\n' )
              listFile.write( href+'\n' )
              break
    outputFile.write( '</ol>\n' )

listFile.close()

When invoked, this version will go through the directory and all sub-directories to generate an html file of all the URLs it finds. It will also create a list of the URLs in a separate file.

Categories
Software

FreeCAD

freecad-logo

FreeCAD is a free open-source parametric 3D CAD system and can be used by anyone to create 3D models.

http://www.freecadweb.org/

The current version of FreeCAD (0.15) was released on April 8, 2015 and runs on Microsoft Windows, Mac OS X and Debian based Linux systems.

It has been developed since 2001 and uses Open CASCADE[1] as it’s geometric modelling kernel.

To install the program, download the relevant package for your machine and follow the installation instructions.
http://www.freecadweb.org/wiki/index.php?title=Download

Then go to the getting started page for a quick introduction to the available tools.
http://www.freecadweb.org/wiki/index.php?title=Getting_started

There are a number of workbenches available for you to use. They are designed to present the tools you are likely to use when modelling for various particular purposes. You can also customise any of the workbenches to suit your own particular needs.

workbenches

  • Use the PartDesign workbench for creating mechanical models or any small scale object.
  • For working in 2D use the Draft or Sketcher workbench.
  • The Arch workbench is the one to use for Architectural models
  • Designing ships? then use the Ship workbench
  • etc.

Here’s an approach for creating a simple model,

  • Start the program
  • Select the Part Design workbench
  • Create Sketch
  • Create some Geometry

  • Close the sketch
  • Select “pad” command
  • Specify the length required

freecad3

  • Select a face of the model
  • Create Sketch
  • Create some geometry
  • Close the sketch

freecad6

  • Select the “create pocket” command
  • Specify the length
  • Close the dialog

freecad7

  • Select a face
  • Select the make fillet” command
  • Specify the fillet radius
  • Close the dialog

freecad5

There are lots of features available in FreeCAD, one that caught my eye is the FEM (Finite Element Analysis) module. This module supports the linear analysis of isotropic (uniform in all directions) material and the calculation of resulting stress (v.-Mises) and displacement. This module uses the Calculix[2] free, open-source Finite Element Analysis application.

FEM

Another interesting module is the Robot workbench although I haven’t tried this one out (yet)

http://www.freecadweb.org/wiki/index.php?title=Robot_Workbench

FreeCAD also offers an alternative approach to driving FreeCAD using the in-built scripting language. Python[3] is used as the scripting language and this allows you to enter modelling commands directly into the python console window.

FreeCAD source code is also available[4] and can be downloaded if you need it.

Footnotes:

  1. Open Cascade In 1993, Matra Datavision first created a software development platform for developing CAD applications called CAS.CADE – Computer Aided Software for Computer Aided Design and Engineering. Matra Datavision have a long history in CAD software dating back to the 1980’s and are perhaps best known for a CAD system called Euclid. In 1999 they published CAS.CADE as open-source software known as Open CASCADE and later, in 2004, it was renamed Open CASCADE Technology. Read more about the history of Open Cascade Technology at
    http://www.opencascade.org/about/profile/history/
  2. Calculix Find out more about Calculix at:
    http://www.calculix.de/
    http://www.dhondt.de/
  3. Python Read more about python in Wikipedia
    http://en.wikipedia.org/wiki/Python_%28programming_language%29
    or on the python web-site at
    https://www.python.org/
  4. Compiling the source code Detailed instructions for compiling the source code are available from the FreeCAD website.
    http://www.freecadweb.org/wiki/index.php?title=Compiling
    http://www.freecadweb.org/wiki/index.php?title=CompileOnWindows
    http://www.freecadweb.org/wiki/index.php?title=CompileOnUnix
    http://www.freecadweb.org/wiki/index.php?title=CompileOnMac
Categories
Tools

Extract Preview Image from SolidWorks document

SolidWorks documents (Parts, Assemblies and Drawings) contain a preview image of their content.

The documents use the Structured Storage mechanism from Microsoft,

http://en.wikipedia.org/wiki/COM_Structured_Storage

and have an element called PreviewPNG which contains the image.

You can use an application such as the Structured Storage Viewer from MiTeC

http://www.mitec.cz/ssv.html

to view the contents of any document based on structured storage.

Alternatively, you may want to access the image directly, and this can be done, for example in Python, as follows.

Here is a code snippet showing how to extract the relevant data.

import glob
import os
import pythoncom
from win32com import storagecon

# =============================================================================
def read_png_from_model( filename ):

    flags = storagecon.STGM_READ | storagecon.STGM_SHARE_EXCLUSIVE

    try:
        stg = pythoncom.StgOpenStorage( filename, None, flags )

        size = 0
        for e in stg.EnumElements():
            if e[0] == 'PreviewPNG':
                size = e[2]
                break
        else:
            return None

        png = stg.OpenStream( 'PreviewPNG', None, flags ).Read( size )

        del stg

        return png

    except:
        return None

and here is a snippet  showing how to use that code on a directory of SolidWorks documents

if len(sys.argv) < 2:
    print "Specify Directory Path containing SolidWorks Documents."
    sys.exit()
print sys.argv[1]
if os.path.exists(sys.argv[1]) and os.path.isdir(sys.argv[1]):
    os.chdir(sys.argv[1])
    FILE = open(cubewindow,'w')
    FILE.write('var myCubeMenu = new CubeMenu({\n')
    FILE.write('items: [\n')

    for path in glob.glob( '*.sld*'):
        if path[0] == '~':
            print 'Ignoring '+path
            continue
        cubewindow = 'cubeinit.txt'

        name = os.path.splitext( path )[0]
        exten = (os.path.splitext( path )[1]).lower()
        #print 'extension '+exten
        prefix = 'PART_'
        if exten == '.sldasm':
            prefix='ASSM_'
        if exten == '.slddrw':
            prefix='DRAW_'

        filnam=prefix+name+'.png'
        print "filename ",filnam
        bytes = read_png_from_model( path )
        if( bytes ):
            file( filnam, 'wb').write( bytes )
            FILE.write("['"+name+"', 'data/"+filnam+"', function(){Message.show('Open "+name+"'); }],\n")
    FILE.write("]\n")
    FILE.write("});\n")
    FILE.close()
else:
    print "Cannot attach to directory ", sys.argv[1]