Commits

Jason R. Coombs committed 639fe68 Merge

Merge

  • Participants
  • Parent commits 32e585d, c767599

Comments (0)

Files changed (10)

File cherrypy_iis.py

+#!python
+
+"""
+Things to remember:
+easy_install munges permissions on zip eggs.
+anything that's installed in a user folder (i.e. setup develop) will probably not work.
+There may still exist an issue with static files.
+"""
+
+
+import sys
+import os
+import isapi_wsgi
+
+# change this to '/myapp' to have the site installed to only a virtual
+#  directory of the site.
+site_root = '/'
+
+if hasattr(sys, "isapidllhandle"):
+	import win32traceutil
+
+appdir = os.path.dirname(__file__)
+egg_cache = os.path.join(appdir, 'egg-tmp')
+if not os.path.exists(egg_cache):
+	os.makedirs(egg_cache)
+os.environ['PYTHON_EGG_CACHE'] = egg_cache
+os.chdir(appdir)
+
+import cherrypy
+import traceback
+
+class Root(object):
+	@cherrypy.expose
+	def index(self):
+		return 'Hai Werld'
+
+def setup_application():
+	print "starting cherrypy application server"
+	#app_root = os.path.dirname(__file__)
+	#sys.path.append(app_root)
+	app = cherrypy.tree.mount(Root(), site_root)
+	print "successfully set up the application"
+	return app
+
+def __ExtensionFactory__():
+	"The entry point for when the ISAPIDLL is triggered"
+	try:
+		# import the wsgi app creator
+		app = setup_application()
+		return isapi_wsgi.ISAPISimpleHandler(app)
+	except:
+		import traceback
+		traceback.print_exc()
+		f = open(os.path.join(appdir, 'critical error.txt'), 'w')
+		traceback.print_exc(file=f)
+		f.close()
+
+def install_virtual_dir():
+	import isapi.install
+	params = isapi.install.ISAPIParameters()
+	# Setup the virtual directories - this is a list of directories our
+	# extension uses - in this case only 1.
+	# Each extension has a "script map" - this is the mapping of ISAPI
+	# extensions.
+	sm = [
+		isapi.install.ScriptMapParams(Extension="*", Flags=0)
+	]
+	vd = isapi.install.VirtualDirParameters(
+		Server="CherryPy Web Site",
+		Name=site_root,
+		Description = "CherryPy Application",
+		ScriptMaps = sm,
+		ScriptMapUpdate = "end",
+		)
+	params.VirtualDirs = [vd]
+	isapi.install.HandleCommandLine(params)
+
+if __name__=='__main__':
+	# If run from the command-line, install ourselves.
+	install_virtual_dir()

File cherrypy_session_auth.py

+import cherrypy
+
+def loadUserByUsername(login):
+	ulist=[("user1","pass1"),("user2","pass2")]
+	for u,p in ulist:
+		if u==login:
+			return (u,p)
+
+def checkLoginAndPassword(login, password):
+	user = loadUserByUsername(login)
+	if user==None:
+		return u'Wrong login/password'
+
+class Root:
+	_cp_config = {
+		'tools.sessions.on': True,
+		'tools.session_auth.on': True,
+		'tools.session_auth.check_username_and_password': checkLoginAndPassword,
+		'tools.session_auth.on_check': loadUserByUsername,
+	}
+
+	@cherrypy.expose
+	def index(self):
+		return " Hello, you passed auth"
+
+cherrypy.quickstart(Root())

File environ-getter.py

+from __future__ import print_function
+import sys
+import subprocess
+import itertools
+
+def validate_pair(ob):
+	try:
+		if not (len(ob) == 2):
+			print("Unexpected result:", ob, file=sys.stderr)
+			raise ValueError
+	except:
+		return False
+	return True
+
+def consume(iter):
+	try:
+		while True: next(iter)
+	except StopIteration:
+		pass
+
+def get_environment_from_batch_command(env_cmd, initial=None):
+	"""
+	Take a command (either a single command or list of arguments)
+	and return the environment created after running that command.
+	Note that if the command must be a batch file or .cmd file, or the
+	changes to the environment will not be captured.
+	
+	If initial is supplied, it is used as the initial environment passed
+	to the child process.
+	"""
+	if not isinstance(env_cmd, (list, tuple)):
+		env_cmd = [env_cmd]
+	# construct the command that will alter the environment
+	env_cmd = subprocess.list2cmdline(env_cmd)
+	# create a tag so we can tell in the output when the proc is done
+	tag = 'Done running command'
+	# construct a cmd.exe command to do accomplish this
+	cmd = 'cmd.exe /s /c "{env_cmd} && echo "{tag}" && set"'.format(**vars())
+	# launch the process
+	proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, env=initial)
+	# parse the output sent to stdout
+	lines = proc.stdout
+	# consume whatever output occurs until the tag is reached
+	consume(itertools.takewhile(lambda l: tag not in l, lines))
+	# define a way to handle each KEY=VALUE line
+	handle_line = lambda l: l.rstrip().split('=',1)
+	# parse key/values into pairs
+	pairs = map(handle_line, lines)
+	# make sure the pairs are valid
+	valid_pairs = filter(validate_pair, pairs)
+	# construct a dictionary of the pairs
+	result = dict(valid_pairs)
+	# let the process finish
+	proc.communicate()
+	return result
+
+def __test__():
+	# test it
+	cmd = [
+		r'c:\program files (x86)\Microsoft Visual Studio 9.0\VC\vcvarsall.bat',
+		'x86',
+		]
+	env = get_environment_from_batch_command(cmd)

File multiple-inheritance.py

+from __future__ import print_function
+
+class Alpha(object):
+	def output(self):
+		print('Alpha')
+		super(Alpha, self).output()
+
+class Beta(object):
+	def output(self):
+		print('Beta')
+
+class Gamma(Alpha, Beta):
+	def output(self):
+		print('Gamma')
+		super(Gamma, self).output()
+
+g = Gamma()
+g.output()

File round-robin.py

+from random import shuffle
+import itertools
+
+teams = 'ABCDEFG'
+
+fixed_pairs = list(itertools.combinations(teams, 2))
+shuffle(fixed_pairs)
+
+def print_pair(pair):
+	print(' vs '.join(pair))
+
+map(print_pair, fixed_pairs)

File split_in_place.py

+from __future__ import division
+import os
+import sys
+from win32file import CreateFile, SetEndOfFile, GetFileSize, SetFilePointer, ReadFile, WriteFile
+import win32con
+from itertools import tee, izip, imap
+
+def xfrange(start, stop=None, step=None):
+	"""
+	Like xrange(), but returns list of floats instead
+
+	All numbers are generated on-demand using generators
+	"""
+
+	if stop is None:
+		stop = float(start)
+		start = 0.0
+
+	if step is None:
+		step = 1.0
+
+	cur = float(start)
+
+	while cur < stop:
+		yield cur
+		cur += step
+
+
+# from Python 2.6 docs
+def pairwise(iterable):
+    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
+    a, b = tee(iterable)
+    next(b, None)
+    return izip(a, b)
+
+def get_one_hundred_pieces(size):
+	"""
+	Return start and stop extents for a file of given size
+	that will break the file into 100 pieces of approximately
+	the same length.
+	
+	>>> res = list(get_one_hundred_pieces(205))
+	>>> len(res)
+	100
+	>>> res[:3]
+	[(0, 2), (2, 4), (4, 6)]
+	>>> res[-3:]
+	[(199, 201), (201, 203), (203, 205)]
+	"""
+	step = size / 100
+	cap = lambda pos: min(pos, size)
+	approx_partitions = xfrange(0, size+step, step)
+	int_partitions = imap(lambda n: int(round(n)), approx_partitions)
+	partitions = imap(cap, int_partitions)
+	return pairwise(partitions)
+
+def save_file_bytes(handle, length, filename):
+	hr, data = ReadFile(handle, length)
+	assert len(data) == length, "%s != %s" % (len(data), length)
+	h_dest = CreateFile(
+		filename,
+		win32con.GENERIC_WRITE,
+		0,
+		None,
+		win32con.CREATE_NEW,
+		0,
+		None,
+		)
+	code, wbytes = WriteFile(h_dest, data)
+	assert code == 0
+	assert wbytes == len(data), '%s != %s' % (wbytes, len(data))
+
+def handle_command_line():
+	filename = sys.argv[1]
+	h = CreateFile(
+		filename,
+		win32con.GENERIC_WRITE | win32con.GENERIC_READ,
+		0,
+		None,
+		win32con.OPEN_EXISTING,
+		0,
+		None,
+		)
+	size = GetFileSize(h)
+	extents = get_one_hundred_pieces(size)
+	for start, end in reversed(tuple(extents)):
+		length = end - start
+		last = end - 1
+		SetFilePointer(h, start, win32con.FILE_BEGIN)
+		target_filename = '%s-%d' % (filename, start)
+		save_file_bytes(h, length, target_filename)
+		SetFilePointer(h, start, win32con.FILE_BEGIN)
+		SetEndOfFile(h)
+
+if __name__ == '__main__':
+	handle_command_line()
+#!python
+from __future__ import print_function
+
+import pickle
+import xlwt 
+from itertools import count, repeat
+import sys
+
+BLACK = 0
+class Topic(list):
+	def __str__(self):
+		return '{0} ({1})'.format(self.name, len(self))
+
+	def __init__(self, name):
+		super(Topic, self).__init__()
+		self.name = name
+
+	@classmethod
+	def from_questions(cls, raw_items=None):
+		items = raw_items or parse_questions()
+		topic = None
+		for item in items:
+			if cls.is_topic(item):
+				if topic: yield topic
+				topic = cls(item)
+			else:
+				topic.append(item)
+		if topic: yield topic
+
+	@staticmethod
+	def is_topic(text):
+		return len(text) < 50 and not '?' in text
+
+	def pretty_print(self, file=sys.stdout):
+		print(self.name, file=file)
+		for q in self:
+			q = q.encode('utf-8')
+			print('\t'+q, file=file)
+
+	@staticmethod
+	def save_topics(topics):
+		#pickle.dump(topics, open('topics.pickle', 'wb'))
+		f = open('topics.txt', 'w')
+		for t in topics:
+			t.pretty_print(f)
+
+	@staticmethod
+	def load_topics():
+		questions = open('topics.txt')
+		questions = map(str.strip, questions)
+		questions = [q.decode('utf-8') for q in questions]
+		return Topic.from_questions(questions)
+		#pickle.load(open('topics.pickle', 'rb'))
+
+all_thin_black = tuple(
+	zip('left bottom right top'.split(), repeat(xlwt.Formatting.Borders.THIN)) +
+	zip('left_colour bottom_colour right_colour top_colour'.split(), repeat(BLACK))
+	)
+				
+def generate_spreadsheet(topics):
+	import xlwt
+	wb = xlwt.Workbook()
+	for topic in topics:
+		sheet = wb.add_sheet(topic.name)
+		style = dict(
+			alignment = (('horz', xlwt.Alignment.HORZ_CENTER),),
+			font = (("bold", True),),
+			border = all_thin_black,
+			)
+		# this equation is supposed to get the value from the sheet name, but only seems
+		#  to get the last active sheet name
+		title = xlwt.Formula('RIGHT(CELL("filename"),LEN(CELL("filename"))-SEARCH("]",CELL("filename")))')
+		# override because the function doesn't work
+		title = topic.name
+		sheet.write_merge(0,0,0,2,title, get_style(style))
+		write(sheet, 1, 1, "Answer", style)
+		write(sheet, 1, 2, "Clarification", style)
+		sheet.panes_frozen = True
+		sheet.horz_split_pos = 2
+		sheet.fit_width_to_pages = 1
+		for row_n, q in zip(count(2), topic):
+			style = dict(
+				alignment = (("wrap", xlwt.Alignment.WRAP_AT_RIGHT),),
+				border = all_thin_black,
+			)
+			write(sheet, row_n, 0, q, style)
+			write(sheet, row_n, 1, '', style)
+			write(sheet, row_n, 2, '', style)
+		for col_n in range(3):
+			# width units are 1/256 the width of the zero character in the default font (first font record encountered).
+			width = 256*30
+			width += int(width*.5*bool(col_n)) # expand every column but the first
+			sheet.col(col_n).width = width
+			
+	wb.save('IT Audit Survey.xls')
+	return wb, sheet
+
+def parse_questions():
+	import xlrd
+	wb = xlrd.open_workbook('IT Audit Survey.xls')
+	s = wb.sheets()[0]
+	questions = [s.row(n)[0].value for n in range(s.nrows)]
+	return filter(None, questions)
+
+def print_all(x):
+	map(print, x)
+
+def write(ws, row, col, data, style=None):
+	"""
+	Write data to row, col of worksheet (ws) using the style
+	information.
+	Again, I'm wrapping this because you'll have to do it if you
+	create large amounts of formatted entries in your spreadsheet
+	(else Excel, but probably not OOo will crash).
+	"""
+	style = get_style(style) if style is not None else ws.write.im_func.func_defaults[1]
+	ws.write(row, col, data, style)
+
+STYLE_FACTORY = {}
+def get_style(style):
+	"""
+	Style is a dict maping key to values.
+	Valid keys are: background, format, alignment, border
+	The values for keys are lists of tuples containing (attribute,
+	value) pairs to set on model instances...
+	"""
+	#print "KEY", style
+	style_key = tuple(style.items())
+	s = STYLE_FACTORY.get(style_key, None)
+	if s is not None: return s
+
+	s = xlwt.XFStyle()
+	for key, values in style.items():
+		if key == "background":
+			p = xlwt.Pattern()
+			for attr, value in values:
+				p.__setattr__(attr, value)
+			s.pattern = p
+		elif key == "format":
+			s.num_format_str = values
+		elif key == "alignment":
+			a = xlwt.Alignment()
+			for attr, value in values:
+				a.__setattr__(attr, value)
+			s.alignment = a
+		elif key == "border":
+			b = xlwt.Formatting.Borders()
+			for attr, value in values:
+				b.__setattr__(attr, value)
+			s.borders = b
+		elif key == "font":
+			f = get_font(values)
+			s.font = f
+	STYLE_FACTORY[style_key] = s
+	return s
+
+FONT_FACTORY = {}
+def get_font(values):
+	"""
+	'height' 10pt = 200, 8pt = 160
+	"""
+	font_key = values
+	f = FONT_FACTORY.get(font_key, None)
+	if f is not None: return f
+	f = xlwt.Font()
+	for attr, value in values:
+		f.__setattr__(attr, value)
+	FONT_FACTORY[font_key] = f
+	return f
+
+def initial_import():
+	topics = tuple(Topic.from_questions())
+	print_all(topics)
+	Topic.save_topics(topics)
+
+
+if __name__ == '__main__':
+	topics = Topic.load_topics()
+	wb, sheet = generate_spreadsheet(topics)
+

File wireless/adhoc.tlb

Binary file added.

File wireless/enable-pioneer.py

+from comtypes.client import GetModule
+GetModule('adhoc.tlb')
+from comtypes.gen import ADHOCLib
+from comtypes import GUID
+from ctypes import POINTER
+
+# fails with
+"""
+{45357166-FF38-4302-8F5C-DF5B703A6E3D}
+Traceback (most recent call last):
+  File "C:\Python\lib\pdb.py", line 1283, in main
+    pdb._runscript(mainpyfile)
+  File "C:\Python\lib\pdb.py", line 1202, in _runscript
+    self.run(statement)
+  File "C:\Python\lib\bdb.py", line 368, in run
+    exec cmd in globals, locals
+  File "<string>", line 1, in <module>
+  File ".\enable-pioneer.py", line 7, in <module>
+    mgr = ADHOCLib.Dot11AdHocManager()
+  File "C:\Python\lib\site-packages\comtypes-0.6.3dev-py2.6.egg\comtypes\_comobject.py", line 348, in __new__
+    self.__prepare_comobject()
+  File "C:\Python\lib\site-packages\comtypes-0.6.3dev-py2.6.egg\comtypes\_comobject.py", line 375, in __prepare_comobject
+    self._COMObject__typelib = LoadRegTypeLib(*self._reg_typelib_)
+  File "C:\Python\lib\site-packages\comtypes-0.6.3dev-py2.6.egg\comtypes\typeinfo.py", line 473, in LoadRegTypeLib
+    _oleaut32.LoadRegTypeLib(byref(GUID(guid)), wMajorVerNum, wMinorVerNum, lcid, byref(tlib))
+  File "_ctypes/callproc.c", line 925, in GetResult
+WindowsError: [Error -2147319779] Library not registered"""
+mgr = ADHOCLib.Dot11AdHocManager()
+networks = mgr.GetIEnumDot11AdHocNetworks()

File wireless/gen_lib.py

+from comtypes.client import GetModule
+GetModule('adhoc.tlb')