Delphi ... Skype API
2:48 AM | Author: devista
//  Tested with Delphi 5, Skype4Com v.1.0.27, Skype v.3.5.0.95
//
// To use the code in this example:
// 1. Create new application. A form named Form1 should be created auttomatically.
// 2. Drag and drop a standard Memo onto Form1.
// 3. Copy & paste the code in this exaple into Form1's code editor.
// 4. Go to Form view and link following events:
// 4.1 Form1.OnCreate -> FormCreate;
// 4.2 Form1.OnClose -> FormClose.


Unit Unit1;

Interface

Uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ScktComp, StdCtrls, OleCtrls, SKYPE4COMLib_TLB, OleServer, CmAdmCtl;

Const PortNr = 37216;

Type
TForm1 = class(TForm)
Memo1: TMemo;
Procedure SkypeCallStatus(Sender: TObject; const pCall: ICall; Status: TOleEnum);
Procedure SkypeAttachmentStatus(Sender: TObject; Status: TOleEnum);
Procedure OnClientRead(Sender: TObject; Socket: TCustomWinSocket);
Procedure OnClientConnect (Sender: TObject; Socket: TCustomWinSocket);
Procedure OnClientDisConnect (Sender: TObject; Socket: TCustomWinSocket);
Procedure FormCreate(Sender: TObject);
Procedure FormClose(Sender: TObject; var Action: TCloseAction);
Private
Server : TServerSocket;
Skype : TSkype;
End;

Var
Form1: TForm1;

Implementation

{$R *.dfm}

Procedure TForm1.FormCreate(Sender: TObject);

Begin
// Creating and activating TCP server socket
Server := TServerSocket.Create(Self);
Server.Port := PortNr;
Server.Active := True;

// Assigning our own event handlers to Server object's event properties
Server.OnClientRead := OnClientRead;
Server.OnClientConnect := OnClientConnect;
Server.OnClientDisconnect := OnClientDisConnect;

// Creating and attaching Skype object
Skype := TSkype.Create(self);
Skype.Attach(7, false);



// Assigning our own event handlers to Skype object's properties
Skype.OnCallStatus := SkypeCallStatus;
Skype.OnAttachmentStatus := SkypeAttachmentStatus;

Memo1.Lines.Clear;
Memo1.Align := alClient;
Caption := 'Voice to port redirection demo';
End;


//------------------------------------------------------------------------------
// Fired when a client gets connected to our TCP server socket.
// In case of this example, this happens when pCall.OutputDevice property
// gets assigned a value in SkypeCallStatus procedure (incoming call detected).

Procedure TForm1.OnClientConnect (Sender: TObject; Socket: TCustomWinSocket);

Begin
Memo1.Lines.Add('Skype connected to port: ' + IntToSTr(PortNr));
End;


//------------------------------------------------------------------------------
// Fired when a client gets disconnected from our TCP server socket.

Procedure TForm1.OnClientDisConnect (Sender: TObject; Socket: TCustomWinSocket);

Begin
Memo1.Lines.Add('Skype disconnected from port: ' + IntToSTr(PortNr));
End;


//------------------------------------------------------------------------------
// Simple byte to hex conversion

Function ByteToHex (B : Byte) : String;

Const
Hex = '0123456789ABCDEF';

Var S : String[2];

Begin
S := '00';
S[1] := Hex[(B mod 16) + 1];
S[2] := Hex[(B div 16) + 1];
ByteToHex := S;
End;


//------------------------------------------------------------------------------
// OnClientRead is fired when a data packet is received.
// This procedure will read the data packet from the stream and
// hex dump it in Memo1.
//
// Note that while we declare the Buf variable with size 10 Kb, the actual
// size of the data packet can differ between systems. Usually the actual
// packet size is below 2 Kb. If your application excepts out in this procedure
// you may want to increase the buffer size to 20 Kb.
//
// We declare the Buf variable outside OnClientRead procedure to avoid
// having to allocate the buffer each time the procedure is executed.


Var Buf : Array[0..10*1024] of Byte;

Procedure TForm1.OnClientRead(Sender: TObject; Socket: TCustomWinSocket);

Var
Len, I, J : Integer;
OutStr : String;

Begin
Len := Socket.ReceiveLength;
Socket.ReceiveBuf(Buf, Len);

For I := 0 to (Len div 16) - 1 do
Begin
OutStr := '';
For J := 0 to 15 do
Begin
OutStr := OutStr + ByteToHex(Buf[(I * 16) + J]) + ' ';
End;
Memo1.Lines.Add(OutStr);
End;
End;


Procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);

Begin
Server.Active := False;
End;


//------------------------------------------------------------------------------
// Fired when status of a Skype Call object changes
// Here we use it to detect when calls start and finish

Procedure TForm1.SkypeCallStatus(Sender: TObject; const pCall: ICall; Status: TOleEnum);

Begin
// If a new call has started
if (Status = clsInProgress) Then
Begin
Memo1.Lines.Add('Call in progress..');
pCall.OutputDevice[callIoDeviceTypePort] := IntToStr(PortNr);

// To redirect Input or Microphone voice instead of Output to a port
// use one of following commands:
// pCall.InputDevice[callIoDeviceTypePort] := IntToStr(PortNr);
// pCall.CaptureMicDevice[callIoDeviceTypePort] := IntToStr(PortNr);
End;

// If a call has finished
if Status = clsFinished Then
Begin
Memo1.Lines.Add('Call finished.');
End;
End;


//------------------------------------------------------------------------------
// Fired when Skype attachment status changes. Note that this handler also
// automatically attempts to reattach to the API if connection was temporarily lost

Procedure TForm1.SkypeAttachmentStatus(Sender: TObject; Status: TOleEnum);

Begin
Memo1.Lines.Add('Attatchment status: ' + Skype.Convert.AttachmentStatusToText(Status));
if Status = apiAttachAvailable Then Skype.Attach(7, false);
End;

End.
python ... Proxy
2:27 AM | Author: devista
import sys, os, urllib, urllib2, re, httplib, sets, socket
from time import time, localtime, strftime
from socket import gethostbyaddr

nogeoip = 0
try:
import GeoIP
except:
nogeoip = 1
print "\nGeoIP Module/Database NOT found, try:"
print "sudo apt-get install libgeoip1 && sudo apt-get install python-geoip"
print "or visit www[.]maxmind[.]com for download"
print "GeoIP is not required but highly recommended!\n"

output = 'proxylist.txt'
sleeptimer = 3
socket.setdefaulttimeout(2)
alivelist = []
myipadress = urllib.urlopen('http://www.whatismyip.com/automation/n09230945.asp').read()
anon_list = []
trans_list = []
planetlab = []

sites = ['http://www.darkc0de.com/cgi-bin/proxies.py',
'http://www.1proxyfree.com/',
'http://www.atomintersoft.com/products/alive-proxy/socks5-list/',
'http://www.proxylist.net/',
'http://www.proxylists.net/http_highanon.txt']

def StripTags(text):
return re.sub(r'<[^>]*?>','', text)

def timer():
now = strftime('%H:%M:%S-%d/%b/%Y', localtime())
return now

def ipcheck(proxy):
try:
pxhandle = urllib2.ProxyHandler({"http": proxy})
opener = urllib2.build_opener(pxhandle)
urllib2.install_opener(opener)
myip = urllib2.urlopen('http://www.whatismyip.com/automation/n09230945.asp').read()
xs = re.findall(('\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}'), StripTags(myip))
if xs[0] == myipadress or myipadress == myip:
trans_list.append(proxy)
print proxy[:-1],"\t- ALIVE -", timer(), "- TRANSPARENT"
elif xs == None:
pass
else:
anon_list.append(proxy)
print proxy[:-1],"\t- ALIVE -", timer(), "- EXT-iP :",xs[0]
except KeyboardInterrupt:
print "\n\nCTRL+C - check temporary proxylist file\n\n"
sys.exit(0)
except:
pass

def proxyvalidator(proxylist):
finalcount = 0
for proxy in proxylist:
proxy.replace('\n', '')
try:
proxies = {'http': "http://"+proxy[:-1]}
opener = urllib.FancyURLopener(proxies)
try:
loopchk = opener.open("http://www.google.com").read()
except:
pass
except(IOError,socket.timeout), detail:
pass
ipcheck(proxy)
alivelist.append(proxy)
finalcount += 1
return alivelist

def getsamairdotru():
counter = 1
pxycnt = 0
maxpages = 10
urls = []
pfile = file(output, 'a')
while counter <= maxpages:
if counter < 10: # workaround for page-01 to page-09
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
url = opener.open('http://www.samair.ru/proxy/proxy-0'+repr(counter)+'.htm').read()
else:
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
url = opener.open('http://www.samair.ru/proxy/proxy-'+repr(counter)+'.htm').read()
strings = re.findall(('\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}:\d{1,5}'), StripTags(url))
for string in strings:
pfile.write(string+"\n")
pxycnt = pxycnt+1
counter = counter+1
opener.close()
print pxycnt, "\t: Proxies received from : http://www.samair.ru/proxy/"
pfile.close()

def getsinglesitelist(site):
pxycnt = 0
urls = []
pfile = file(output, 'a')
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
url = opener.open(site).read()
strings = re.findall(('\d{1,3}[.]\d{1,3}[.]\d{1,3}[.]\d{1,3}[:]\d{1,5}'), StripTags(url))
for string in strings:
pfile.write(string+"\n")
pxycnt = pxycnt+1
print pxycnt, "\t: Proxies recieved from :", site.split("//",3)[1]
opener.close()
pfile.close()

def getplanetlabs():
opener = urllib2.build_opener()
url = opener.open('http://fall.cs.princeton.edu/codeen/tabulator.cgi?table=table_all').read()
strings = re.findall(('\d{1,3}[.]\d{1,3}[.]\d{1,3}[.]\d{1,3}'), StripTags(url))
for string in strings:
planetlab.append(string)
print len(planetlab), "\t: PlanetLab Proxylist Loaded", "\n"

def cleanup():
pfile = open(output, 'r').readlines()
outfile = file(output, 'w')
sorted = []
finalcount = 0
psremove = 0
for proxy in pfile:
if proxy.split(':',1)[0] not in planetlab:
if proxy not in sorted:
sorted.append(proxy)
outfile.write(proxy)
finalcount += 1
if proxy.split(':',1)[0] in planetlab:
psremove += 1
print "\n", psremove, "\t: PlanetLab (CoDeen) Proxies removed!"
print finalcount,"\t: unique Proxies found\n"
print "+-[Starting Validation]-----------------------------------------------------+"
outfile.close()

def fileConst():
fileC = open(output, 'w')
falive = []
fileC.write('+ This List has been generated with proxyharvest_1.1.py // www.darkc0de.com\n')
fileC.write('+ ANONYMOUS PROXIES\n\n')
for anon in anon_list:
fileC.write(anon)
if anon in alivelist:
alivelist.remove(anon)
fileC.write('\n\n+ TRANSPARENT PROXIES\n\n')
for trans in trans_list:
fileC.write(trans)
if trans in alivelist:
alivelist.remove(trans)
fileC.write('\n\n+ WORKING BUT UNCLEAR PROXIES\n\n')
alivelist.sort()
for alive in alivelist:
fileC.write(alive)
fileC.close()

def helpme():
print "| -s / -sitecollect :: gathers proxylists |"
print "| -m / -multipage :: get incremental pages |"
print "| -a / -all :: do ALL!!! |"
print "| -vl / - validatelist :: check a file |"
print "+-----------------------------------------------+"
try:
os.remove(output)
except:
pass
print "+-----------------------------------------------+"
print "| ProxyHarvest.py 1.1 |"
print "| low1z 2009 // darkc0de |"
print "+-----------------------------------------------+"
print "IP:", myipadress, "//", timer(), "\n"
getplanetlabs()

if len(sys.argv) <= 1:
print "\n\t < use -help to get options >\n"
sys.exit(1)

for arg in sys.argv[1:]:
if arg.lower() == "-h" or arg.lower() == "-help":
helpme()
if arg.lower() == "-s" or arg.lower() == "-sitecollect":
for site in sites:
try:
getsinglesitelist(site)
except:
print "Error :", site
cleanup()
proxylist = open(output, 'r').readlines()
proxyvalidator(proxylist)
if arg.lower() == "-m" or arg.lower() == "-multipage":
getsamairdotru()
cleanup()
print "may take some time to print out good proxies, be patient"
try:
proxylist = open(output, 'r').readlines()
proxyvalidator(proxylist)
except:
pass
if arg.lower() == "-a" or arg.lower() == "-all":
try:
for site in sites:
getsinglesitelist(site)
getsamairdotru()
cleanup()
proxylist = open(output, 'r').readlines()
proxyvalidator(proxylist)
except:
print "something went wront... using -a is seems a bit buggy"
if arg.lower() == "-vl" or arg.lower() == "-validatelist":
try:
proxyfile = open(sys.argv[2], 'r').readlines()
proxyvalidator(proxyfile)
except(IndexError):
print "Error: check you proxy file ...\n"
sys.exit(0)

print "\n+-[ANON LIST]-------------------------------------------------------------+\n"
for anon_proxy in anon_list:
try:
haddr = gethostbyaddr(anon_proxy.split(':',1)[0])
except:
haddr = '-'
if nogeoip == 1:
print anon_proxy.replace('\n',''),"\t| HostAdress:", haddr[0]
pass
elif nogeoip == 0:
gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
gx = gi.country_code_by_addr(anon_proxy.split(':',1)[0])
print anon_proxy.replace('\n',''), "\t| Country:", gx,"\t| HostAdress:", haddr[0]
print "\n\t", len(anon_list), ": Total tested AnonProxies\n"
print "+-[TRANS LIST]--------------------------------------------------------------+\n"
for trans_proxy in trans_list:
if nogeoip == 1:
print trans_proxy.replace('\n','')
pass
elif nogeoip == 0:
gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
gx = gi.country_code_by_addr(trans_proxy.split(':',1)[0])
print trans_proxy.replace('\n',''), "\t| Country:", gx
print "\n\t", len(trans_list), ": Total tested Transparent Proxies\n"
print "+-[OTHER SERVERS]-----------------------------------------------------------+\n"
if len(alivelist) > 16:
print len(alivelist), "Alive but unverified Servers, check", output
else:
for alive in alivelist:
if alive not in trans_list:
if alive not in anon_list:
print alive.replace('\n','')
fileConst()
python ... Serial Port Communication
2:21 AM | Author: devista
import urllib
import serial
import re

MAXLENGTH = 512
BANNER = " Sent. "

def getmessages():
# Get a file-like object for the Python Web site's home page.
f = urllib.urlopen("http://etharooni.polorix.net/messages.txt")
# Read from the object, storing the page's contents in 's'.
s = f.read()
f.close()
return s

def formatmessage(msg):
msg = msg.upper()
p = re.compile('[^0-9^A-Z^ ^\n]')
msg = p.sub(' ', msg)

ret = ''
lines = msg.split('\n')
for s in lines:
if (len(s) > 0):
if (len(ret) + len(s) < MAXLENGTH):
ret = ret + s
if (len(ret) + len(BANNER) < MAXLENGTH):
ret = ret + BANNER
ret = chr(len(ret) >> 8) + chr(len(ret) & 0xFF) + ret
return ret

def waitfor(port, msg):
line = ''
while line.lower() != msg.lower():
line = port.readline()
print line
print "waitfor done!"
#
#
def mainstuff():
oldmessage = ''
while True:
msg = getmessages()

ser = serial.Serial('COM4', 9600) # open first serial port
print ser.portstr # check which port was really used

if (msg != oldmessage):
oldmessage = msg
msg = formatmessage(msg)
print len(msg)-2
print msg
ser.write(msg)

waitfor(ser, 'done!\r\n')

# get one rotation out!
waitfor(ser, 'EOM\r\n')
ser.close() # close port

mainstuff()
python ... Implementation of Simhashes
2:15 AM | Author: devista
# Implementation of Charikar simhashes in Python

# See: http://dsrg.mff.cuni.cz/~holub/sw/shash/#a1

def simhash(tokens, hashbits=32):
if hashbits > 64: hashbits = 64
v = [0]*hashbits

for t in [x.__hash__() for x in tokens]:
bitmask = 0
for i in xrange(hashbits):
bitmask = 1 << i
if t & bitmask:
v[i] += 1
else:
v[i] -= 1

fingerprint = 0
for i in xrange(hashbits):
if v[i] >= 0:
fingerprint += 1 << i

return fingerprint

def similarity(a, b, hashbits=32):
# Use Hamming Distance to return % of similar bits
x = (a ^ b) & ((1 << hashbits) - 1)
tot = 0
while x:
tot += 1
x &= x-1
return float(hashbits-tot)/hashbits


test_set = ["zomg hai 2 u 2! I lub j00 so hard.",
"zomg bai 2 u 2? I haet j00 hard."
,
"G fj sdlfjdjlfjsljdf sdkfj s sla r"
,
"g fJ sdlfjdjlfjsljdf sdkfj s sla r"
,
"wainscoating"
,]


last = None
for t in test_set:
fingerprint = hex(simhash(t.split()))
print "%35s = %s" % (t, fingerprint)

print "\nHow similar are these?"
a = 'aaaaaaaaaaaaa 111111111111111'
b = 'aaaabaaaaaaaa 111111161111111'
print "'%s' and '%s'? %.2f%%" % ( a, b, similarity(simhash(a), simhash(b))*100 )
a = 'The Pursuit of HAPPINESS'
print "'%s' and '%s'? %.2f%%" % ( a, b, similarity(simhash(a), simhash(b))*100 )
b = 'the pursuit of happiness'
print "'%s' and '%s'? %.2f%%" % ( a, b, similarity(simhash(a), simhash(b))*100 )
b = 'HAPPINESS pursuit'
print "'%s' and '%s'? %.2f%%" % ( a, b, similarity(simhash(a), simhash(b))*100 )
b = 'happiness pursuit'
print "'%s' and '%s'? %.2f%%" % ( a, b, similarity(simhash(a), simhash(b))*100 )

by : andhy as, Jakarta, Indnesia, 08 2010
b = 'happiness pursuit of the WHATEVER'
print "'%s' and '%s'? %.2f%%" % ( a, b, similarity(simhash(a), simhash(b))*100 )

python ... WSDL SOAP
2:10 AM | Author: devista
import SOAPpy

from SOAPpy import WSDL

if __name__ == '__main__':
#SOAPpy.Config.debug = 1
url = '???'
server = WSDL.Proxy(url)

#print server.methods.keys()
#returns: [u'Echo']

server.Echo('Testing')

### OUTPUT BELOW

Traceback (most recent call last):
File "test_api.py", line 12, in <module>
server.Echo('Testing')
File "/usr/lib/pymodules/python2.6/SOAPpy/Client.py", line 470, in __call__
return self.__r_call(*args, **kw)
File "/usr/lib/pymodules/python2.6/SOAPpy/Client.py", line 492, in __r_call
self.__hd, self.__ma)
File "/usr/lib/pymodules/python2.6/SOAPpy/Client.py", line 363, in __call
config = self.config)
File "/usr/lib/pymodules/python2.6/SOAPpy/Client.py", line 187, in call
r.endheaders()
File "/usr/lib/python2.6/httplib.py", line 892, in endheaders
self._send_output()
File "/usr/lib/python2.6/httplib.py", line 764, in _send_output
self.send(msg)
File "/usr/lib/python2.6/httplib.py", line 723, in send
self.connect()
File "/usr/lib/python2.6/httplib.py", line 704, in connect
self.timeout)
File "/usr/lib/python2.6/socket.py", line 500, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno -2] Name or service not known