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
Code Snippets

Internet Shortcuts to HTML file

While trawling around the web, I often save shortcuts to websites that I’ve visited .

Each shortcut is saved as a special filetype with the suffix .url and is recognised by Windows as an Internet Shortcut. The name of the file is a description of the link (usually) taken from the contents of the webpage title html tag and the contents of the file include the actual url.

For example,

openEyes – Eye tracking for the masses.url

has the following contents

[InternetShortcut]
URL=http://thirtysixthspan.com/openEyes/

I came across a technique for combining one or more .url files into a single .html file originally described on the mozillaZine website (http://mozillazine.org) in the forum post

Convert links: desktop shortcut to bookmark?

This describes a method using a DOS batch/cmd file to automate the process (I’d forgotten how powerful DOS batch/cmd files can be). Here is my modified version, saved into a file called url2html.cmd:


@echo off
setlocal enabledelayedexpansion

cd /d "%~dp1"
set output="LINKS_%RANDOM%.html"
echo ^<ol^> >> %output%
for /f "tokens=* delims=" %%t in ('dir /b "%~dp1*.url"') do (
   set strLine2=%%t
   type "%%t" | find "URL=" > u2htemp
   set /p strLine1= < u2htemp
   echo ^<li^>^<a href="!strLine1:~4!"^>!strLine2:~0,-4!^</a^>^</li^> >> %output%
)
echo ^<^/ol^> >> %output%
pause

del u2htemp

This code can be run as follows from a command line prompt:

C:\mutils\url2html.cmd "c:\urls\openEyes - Eye tracking for the masses.url" 

and will add all url files in the same directory of the specified url to a single html file.

It is set up in this way so that it can be easily invoked from Windows File Explorer from right clicking on a .url file and selecting the Send to option. This can be enabled as follows:

Open the Send to special folder ( e.g. by using WindowsKey-R and typing shell:SendTo ) and dragging a shortcut to your newly created .cmd file there. The command url2html will then be added to the Send to option.

There are some interesting points to note regarding some of the commands used in this script.

setlocal enabledelayedexpansion

I found a description of this, with an example, at EnableDelayedExpansion

Delayed Expansion will cause variables within a batch file to be expanded at execution time rather than at parse time, this option is turned on with the SETLOCAL EnableDelayedExpansion command.

Variable expansion means replacing a variable (e.g. %windir%) with its value C:\WINDOWS

By default expansion will happen just once, before each line is executed. The delayedexpansion is performed each time the line is executed, or for each loop in a FOR looping command. For simple commands this will make no noticable difference, but with loop commands like FOR, compound or bracketed expressions delayed expansion will allow you to always see the current value of the variable.

When delayed expansion is in effect, variables can be immediately read using !variable_name! you can still read and use %variable_name% but that will continue to show the initial value (expanded at the beginning of the line).

Another interesting concept is the handling/interpretation of arguments passed to the cmd file.

cd /d "%~dp1"

This is used to attach to the directory containing the url file passed as an argument when executing the cmd file.
The modifier %~dp1 expands the first argument – the url filename and extracts the drive letter and path.

Details can be found from Microsoft at
Using batch parameters

Categories
Code Snippets

Connecting to SolidWorks using c#

Code sample

public bool ConnectToSW(object ThisSW, int cookie)
{
iSwApp = (ISldWorks)ThisSW;
addinID = cookie;

//Setup callbacks
iSwApp.SetAddinCallbackInfo(0, this, addinID);

#region Setup the Command Manager
iCmdMgr = iSwApp.GetCommandManager(cookie);
AddCommandMgr();
#endregion

#region Setup the Event Handlers
SwEventPtr = (SldWorks.SldWorks)iSwApp;
openDocs = new Hashtable();
AttachEventHandlers();
#endregion

#region Setup Property Manager
AddPMP();
#endregion

return true;
}
Categories
Code Snippets

CComPtr – Return Value

Reminder – don’t forget to Detach() !!

IBody2 *SomeClass::getBody(int index)
{
  CComPtr<IBody2> target;
  target = CreateBody(index);
  return target.Detach();
}

Obvious perhaps, but the CComPtr will do a release as the function completes so if you’re returning the object remember to Detach it

 

Categories
Code Snippets WebGL

WebGL on the iPad

I recently wanted to access some WebGL based web-sites from my iPad and quickly discovered that WebGL is currently NOT supported, or at least not enabled, in the iPad’s version of Safari.

However, Nathan de Vries discovered that the UIWebView class does seem to have in-built support for WebGL. Read all the details at

http://atnan.com/blog/2011/11/03/enabling-and-using-webgl-on-ios/

This work evolved into GoWebGL, which  is an example of how a simple WebGL supported browser can be written for iOS5 devices

https://github.com/gauthiier/GoWebGL

In the example app, simple gestures and inputs are provided allowing a user to enter a required URL in a text edit box launched using a two finger double-tap, to browse forward by a swipe left or browse backwards with a swipe right.

Support for WebGL in UIWebView is enabled as shown in the following code extract

//-> init + setup UIWebView (from Nathan)
    UIWebView* webView = [[[UIWebView alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    id webDocumentView = [webView performSelector:@selector(_browserView)];
    id backingWebView = [webDocumentView performSelector:@selector(webView)];
    [backingWebView _setWebGLEnabled:YES]; //<-- !!!

Because this is an undocumented feature, using it is unlikely to be approved by Apple. It does enable me, however, to explore and research the potential for using WebGL applications on the iPad. In the future, I have no doubt that Apple will provide official support for using WebGL on the iPad.