code
stringlengths
1
1.72M
language
stringclasses
1 value
#!/usr/bin/python import sys,time,socket,struct param = sys.argv[1:] IP,PACKAGE_SIZE,BUFFER,LOG = param Mcache = [] Buffer = [] PACKAGE_SIZE = int(PACKAGE_SIZE) PAYLOAD = PACKAGE_SIZE- 24 log = open(LOG+time.strftime('%Y%m%d%H%M%S')+'.txt','w') class csnode: sNode = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sNode.connect((IP, 50007)) sNode.send('PLAY') while 1: data = sNode.recv(PACKAGE_SIZE) dataRecv = time.strftime('%H:%M:%S') size_recv = len(data) if size_recv == PACKAGE_SIZE: id,chunk = struct.unpack('24s'+str(PAYLOAD)+'s',data) Buffer.append([id,chunk]) #Buffer.append(chunk) log.write(str(int(id))+';') log.write(str(size_recv)+';') log.write('recv'+dataRecv+';') #sys.stdout.write(chunk) if len(Buffer) > int(BUFFER): ID,CHUNK = Buffer.pop(0) sys.stdout.write(CHUNK) dataRead = time.strftime('%H:%M:%S') log.write('read'+dataRead+';\r\n') else: log.write('pacotePerdido;') log.write(str(size_recv)+';\r\n') break while len(Buffer) >0: ID,CHUNK = Buffer.pop(0) #sys.stdout.write(str(int(ID))+'\r\n') sys.stdout.write(CHUNK) dataReadBuffer = time.strftime('%H:%M:%S') log.write(str(int(ID))+';') log.write('readBuffer'+dataReadBuffer+';\r\n') sNode.close() node = csnode()
Python
#!/usr/bin/python import sys,time,socket,struct param = sys.argv[1:] IP,PACKAGE_SIZE,BUFFER,LOG = param Mcache = [] Buffer = [] PACKAGE_SIZE = int(PACKAGE_SIZE) PAYLOAD = PACKAGE_SIZE- 24 log = open(LOG+time.strftime('%Y%m%d%H%M%S')+'.txt','w') class csnode: sNode = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sNode.connect((IP, 50007)) sNode.send('PLAY') while 1: data = sNode.recv(PACKAGE_SIZE) dataRecv = time.strftime('%H:%M:%S') size_recv = len(data) if size_recv == PACKAGE_SIZE: id,chunk = struct.unpack('24s'+str(PAYLOAD)+'s',data) Buffer.append([id,chunk]) #Buffer.append(chunk) log.write(str(int(id))+';') log.write(str(size_recv)+';') log.write('recv'+dataRecv+';') #sys.stdout.write(chunk) if len(Buffer) > int(BUFFER): ID,CHUNK = Buffer.pop(0) sys.stdout.write(CHUNK) dataRead = time.strftime('%H:%M:%S') log.write('read'+dataRead+';\r\n') else: log.write('pacotePerdido;') log.write(str(size_recv)+';\r\n') break while len(Buffer) >0: ID,CHUNK = Buffer.pop(0) #sys.stdout.write(str(int(ID))+'\r\n') sys.stdout.write(CHUNK) dataReadBuffer = time.strftime('%H:%M:%S') log.write(str(int(ID))+';') log.write('readBuffer'+dataReadBuffer+';\r\n') sNode.close() node = csnode()
Python
#!/usr/bin/python import sys,time,socket,struct param = sys.argv[1:] IP,PACKAGE_SIZE,BUFFER,LOG = param Mcache = [] Buffer = [] PACKAGE_SIZE = int(PACKAGE_SIZE) PAYLOAD = PACKAGE_SIZE- 24 log = open(LOG+time.strftime('%Y%m%d%H%M%S')+'.txt','w') class csnode: sNode = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sNode.connect((IP, 50007)) sNode.send('PLAY') while 1: data = sNode.recv(PACKAGE_SIZE) dataRecv = time.strftime('%H:%M:%S') size_recv = len(data) if size_recv == PACKAGE_SIZE: id,chunk = struct.unpack('24s'+str(PAYLOAD)+'s',data) #Buffer.append(chunk) #log.write(str(int(id))+';') #log.write(str(size_recv)+';') #log.write('recv'+dataRecv+';') logdata = str(int(id))+';' logdata = logdata+str(size_recv)+';' logdata = logdata+'recv'+dataRecv+';' #sys.stdout.write(chunk) Buffer.append([logdata,id,chunk]) if len(Buffer) > int(BUFFER): LOGDATA,ID,CHUNK = Buffer.pop(0) sys.stdout.write(CHUNK) dataRead = time.strftime('%H:%M:%S') log.write(LOGDATA) log.write('read'+dataRead+';\r\n') else: log.write('pacotePerdido;') log.write(str(size_recv)+';\r\n') break while len(Buffer) >0: LOGDATA,ID,CHUNK = Buffer.pop(0) #sys.stdout.write(str(int(ID))+'\r\n') sys.stdout.write(CHUNK) dataReadBuffer = time.strftime('%H:%M:%S') #log.write(str(int(ID))+';') log.write(LOGDATA) log.write('readBuffer'+dataReadBuffer+';\r\n') sNode.close() node = csnode()
Python
#!/usr/bin/python import sys,time,socket,struct param = sys.argv[1:] IP,PACKAGE_SIZE,BUFFER,LOG = param Mcache = [] Buffer = [] PACKAGE_SIZE = int(PACKAGE_SIZE) PAYLOAD = PACKAGE_SIZE- 24 log = open(LOG+time.strftime('%Y%m%d%H%M%S')+'.txt','w') class csnode: sNode = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sNode.connect((IP, 50007)) sNode.send('PLAY') while 1: data = sNode.recv(PACKAGE_SIZE) dataRecv = time.strftime('%H:%M:%S') size_recv = len(data) if size_recv == PACKAGE_SIZE: id,chunk = struct.unpack('24s'+str(PAYLOAD)+'s',data) #Buffer.append(chunk) #log.write(str(int(id))+';') #log.write(str(size_recv)+';') #log.write('recv'+dataRecv+';') logdata = str(int(id))+';' logdata = logdata+str(size_recv)+';' logdata = logdata+'recv'+dataRecv+';' #sys.stdout.write(chunk) Buffer.append([logdata,id,chunk]) if len(Buffer) > int(BUFFER): LOGDATA,ID,CHUNK = Buffer.pop(0) sys.stdout.write(CHUNK) dataRead = time.strftime('%H:%M:%S') log.write(LOGDATA) log.write('read'+dataRead+';\r\n') else: log.write('pacotePerdido;') log.write(str(size_recv)+';\r\n') break while len(Buffer) >0: LOGDATA,ID,CHUNK = Buffer.pop(0) #sys.stdout.write(str(int(ID))+'\r\n') sys.stdout.write(CHUNK) dataReadBuffer = time.strftime('%H:%M:%S') #log.write(str(int(ID))+';') log.write(LOGDATA) log.write('readBuffer'+dataReadBuffer+';\r\n') sNode.close() node = csnode()
Python
import sys param = sys.argv[1:] ip,host,buffer,log = param print ip print host print buffer print log
Python
from socket import * import sys,struct,time myHost = '' myPort = 50007 param = sys.argv[1:] N_PEER,BUFFER,LOG = param print N_PEER print BUFFER sockobj = socket(AF_INET, SOCK_STREAM) sockobj.bind((myHost, myPort)) sockobj.listen(int(N_PEER)) #video = open('/home/zank/Desktop/tcc2/DESENVOLVIMENTO/provider/lost.avi', 'r') video = open('/home/zank/Desktop/pes2009.mpg', 'r') log = open('logs/'+LOG+time.strftime('%Y%m%d%H%M%S')+'.txt','w') Saida=False count = 0 lista = [] payload = int(BUFFER)-24 while len(lista) < int(N_PEER): connection, address = sockobj.accept() print 'Server connected by', address data = connection.recv(1024) print data if data.strip() == 'PLAY': lista.append([address,connection]) else: pass while 1: stream = video.read(payload) if len(stream) == 0: break count = count+1 id = str(count) id = id.rjust(24,'0') data = struct.pack('24s'+str(payload)+'s',id,stream) for sock_obj in lista: try: sock_obj[1].send(data) log.write(str(int(id))+';') log.write(str(len(data))+';') log.write(str(sock_obj[0])+';') log.write(time.strftime('%H:%M:%S')+'\r\n') except: lista.remove(sock_obj) log.close() sockobj.close()
Python
######################################################### # Server side: open a socket on a port, listen for # a message from a client, and send an echo reply; # this is a simple one-shot listen/reply per client, # but it goes into an infinite loop to listen for # more clients as long as this server script runs; ######################################################### from socket import * # get socket constructor and constants myHost = '' # server machine, '' means local host myPort = 50007 # listen on a non-reserved port number sockobj = socket(AF_INET, SOCK_STREAM) # make a TCP socket object sockobj.bind((myHost, myPort)) # bind it to server port number sockobj.listen(5) # listen, allow 5 pending connects while 1: # listen until process killed connection, address = sockobj.accept() # wait for next client connect print 'Server connected by', address # connection is a new socket while 1: data = connection.recv(1024) # read next line on client socket if not data: break # send a reply line to the client connection.send('Echo=>' + data) # until eof when socket closed connection.close()
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,random import struct, fcntl class Interface_ip: def set_interface(self,ifname): self.ifname = ifname def get_ip_address(self): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', self.ifname[:15]) )[20:24]) Mcache = [] class BootStrapHandler(SocketServer.BaseRequestHandler): def PadMsg(msg): while len(msg) < 1024: msg=msg+' ' return msg def server_bind(self): SocketServer.ThreadingTCPServer.server_bind(self) self.socket.setdefaulttimeout(5) self.run = True def setup(self): print 'BootStrap: ',self.client_address, ' conectou' def handle(self): try: global Mcache global McacheNode #Get command Saida=False while Saida!=True: data = self.request.recv(1024) if data.strip() != '': print 'BootStrap Recebeu: ',data.strip() else: pass if data.strip() == 'REGISTER': #Coloco o peer na lista de peers if Mcache.count(self.client_address[0]) <= 0: Mcache.append(str(self.client_address[0])) self.request.send('OK\r\n') else: pass elif data.strip() == 'REMOVE': data = self.request.recv(1024) while data.strip() != 'FINISH': print data.strip() if Mcache.count(data.strip()) > 0: Mcache.remove(data.strip()) else: print 'ERRO' data = self.request.recv(1024) elif data.strip() == 'LIST': Mcache = ['127.0.0.1','192.168.1.3','192.168.1.3','192.168.1.3','192.168.1.4','192.168.1.5','192.168.1.6','192.168.1.7'] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.12','192.168.1.15'] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3'] McacheNode = Mcache[:] McacheNode.remove(self.client_address[0]) if Mcache.count(self.client_address[0]) >0: if len(McacheNode) <= 5 and len(McacheNode) > 0: for Ip in McacheNode: self.request.send(str(Ip)+'\r\n') elif len(McacheNode) > 5: peerSelect = [] while len(peerSelect) < 5: peerIp = random.choice(McacheNode) print peerIp if peerSelect.count(peerIp) == 0: peerSelect.append(peerIp) for Ip in peerSelect: self.request.send(str(Ip)+'\r\n') else: IpServer = Interface_ip() IpServer.set_interface('eth0') Ip = IpServer.get_ip_address() self.request.send(str(Ip)+'\r\n') else: pass elif data.strip() == 'EXIT': Saida=True elif data.strip() == '': pass else: pass except : self.finish() def finish(self): print 'BootStrap: ',self.client_address,' desconectou' print repr(McacheNode) print repr(Mcache) def open_bootstrap(): SocketServer.ThreadingTCPServer.allow_reuse_address = 1 BootStrapPort = 7187 print 'BootStrap inicializado na porta: ' + str(BootStrapPort) bootstrap = SocketServer.ThreadingTCPServer(('',BootStrapPort), BootStrapHandler) try: bootstrap.serve_forever() except KeyboardInterrupt: sys.exit(0) def Initialize(): thread.start_new_thread(open_bootstrap,()) time.sleep(1) Initialize() while 1:pass
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,random Mcache = [] class csnode: def connect_bootstrap(self): global Mcache sBootStrap = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sBootStrap.connect(('127.0.0.1', 7187)) sBootStrap.send("REGISTER\r\n") time.sleep(0.2) resp = sBootStrap.recv(1024) #print 'Resposta: ',resp.strip() if resp.strip()=='OK': #print "REGISTER OK" sBootStrap.send("LIST\r\n") time.sleep(0.2) data = sBootStrap.recv(1024) data = data.strip().split('\r\n') sBootStrap.send("EXIT\r\n") sBootStrap.close() #print len(data) Mcache = data #Mcache = ['192.168.1.3','192.168.1.3'] offLine = [] for ip in Mcache: try: #print 'voce esta tentando conectar em '+ ip sNode = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sNode.connect((ip, 50007)) sNode.send('PLAY') #print sNode.recv(1024) while 1: sys.stdout.write(sNode.recv(1024)) except socket.error: offLine.append(ip) #print 'erro no socket' #print offLine node = csnode() node.connect_bootstrap()
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,random import struct Mcache = [] class csnode: def PadMsg(self,msg): self.msg =msg while len(self.msg) < 1024: self.msg=self.msg+' ' return self.msg def connect_bootstrap(self): global Mcache sBootStrap = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sBootStrap.connect(('127.0.0.1', 7187)) sBootStrap.send("REGISTER\r\n") time.sleep(0.2) resp = sBootStrap.recv(1024) #print 'Resposta: ',resp.strip() if resp.strip()=='OK': #print "REGISTER OK" sBootStrap.send("LIST\r\n") time.sleep(0.2) data = sBootStrap.recv(1024) data = data.strip().split('\r\n') sBootStrap.send("EXIT\r\n") sBootStrap.close() #print len(data) Mcache = data #Mcache = ['192.168.1.3','192.168.1.3'] offLine = [] for ip in Mcache: try: #print 'voce esta tentando conectar em '+ ip sNode = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sNode.connect((ip, 50007)) sNode.send('PLAY') #print sNode.recv(1024) while 1: #sys.stdout.write(sNode.recv(1024)[1]) #data = struct.unpack('>i4sh',sNode.recv(1024)) sys.stdout.write(data) except socket.error: offLine.append(ip) #print 'erro no socket' #print offLine node = csnode() node.connect_bootstrap()
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,random import struct, fcntl class Interface_ip: def set_interface(self,ifname): self.ifname = ifname def get_ip_address(self): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', self.ifname[:15]) )[20:24]) Mcache = [] class BootStrapHandler(SocketServer.BaseRequestHandler): def PadMsg(msg): while len(msg) < 1024: msg=msg+' ' return msg def server_bind(self): SocketServer.ThreadingTCPServer.server_bind(self) self.socket.setdefaulttimeout(5) self.run = True def setup(self): print 'BootStrap: ',self.client_address, ' conectou' def handle(self): try: global Mcache global McacheNode #Get command Saida=False while Saida!=True: data = self.request.recv(1024) if data.strip() != '': print 'BootStrap Recebeu: ',data.strip() else: pass if data.strip() == 'REGISTER': #Coloco o peer na lista de peers if Mcache.count(self.client_address[0]) <= 0: Mcache.append(str(self.client_address[0])) self.request.send('OK\r\n') else: pass elif data.strip() == 'REMOVE': data = self.request.recv(1024) while data.strip() != 'FINISH': print data.strip() if Mcache.count(data.strip()) > 0: Mcache.remove(data.strip()) else: print 'ERRO' data = self.request.recv(1024) elif data.strip() == 'LIST': Mcache = ['127.0.0.1','192.168.1.3','192.168.1.3','192.168.1.3','192.168.1.4','192.168.1.5','192.168.1.6','192.168.1.7'] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.12','192.168.1.15'] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3'] McacheNode = Mcache[:] McacheNode.remove(self.client_address[0]) if Mcache.count(self.client_address[0]) >0: if len(McacheNode) <= 5 and len(McacheNode) > 0: for Ip in McacheNode: self.request.send(str(Ip)+'\r\n') elif len(McacheNode) > 5: peerSelect = [] while len(peerSelect) < 5: peerIp = random.choice(McacheNode) print peerIp if peerSelect.count(peerIp) == 0: peerSelect.append(peerIp) for Ip in peerSelect: self.request.send(str(Ip)+'\r\n') else: IpServer = Interface_ip() IpServer.set_interface('eth0') Ip = IpServer.get_ip_address() self.request.send(str(Ip)+'\r\n') else: pass elif data.strip() == 'EXIT': Saida=True elif data.strip() == '': pass else: pass except : self.finish() def finish(self): print 'BootStrap: ',self.client_address,' desconectou' print repr(McacheNode) print repr(Mcache) def open_bootstrap(): SocketServer.ThreadingTCPServer.allow_reuse_address = 1 BootStrapPort = 7187 print 'BootStrap inicializado na porta: ' + str(BootStrapPort) bootstrap = SocketServer.ThreadingTCPServer(('',BootStrapPort), BootStrapHandler) try: bootstrap.serve_forever() except KeyboardInterrupt: sys.exit(0) def Initialize(): thread.start_new_thread(open_bootstrap,()) time.sleep(1) Initialize() while 1:pass
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,random import struct Mcache = [] Buffer = [] class csnode: def PadMsg(self,msg): self.msg =msg while len(self.msg) < 1024: self.msg=self.msg+' ' return self.msg def connect_bootstrap(self): global Mcache sBootStrap = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sBootStrap.connect(('127.0.0.1', 7187)) sBootStrap.send("REGISTER\r\n") time.sleep(0.2) resp = sBootStrap.recv(1024) #print 'Resposta: ',resp.strip() if resp.strip()=='OK': #print "REGISTER OK" sBootStrap.send("LIST\r\n") time.sleep(0.2) data = sBootStrap.recv(1024) data = data.strip().split('\r\n') sBootStrap.send("EXIT\r\n") sBootStrap.close() #print len(data) Mcache = data #Mcache = ['192.168.1.3','192.168.1.3'] offLine = [] for ip in Mcache: try: #print 'voce esta tentando conectar em '+ ip sNode = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sNode.connect((ip, 50007)) sNode.send('PLAY') #print sNode.recv(1024) while 1: #sys.stdout.write(sNode.recv(1024)[1]) #tam = sNode.recv(1024) data = sNode.recv(1024) #values = struct.unpack('i'+tam+'s',data) #sys.stdout.write(values[1]) sys.stdout.write(data) except socket.error: offLine.append(ip) #print 'erro no socket' #print offLine node = csnode() node.connect_bootstrap()
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,random import struct Mcache = [] Buffer = [] class csnode: def PadMsg(self,msg): self.msg =msg while len(self.msg) < 1024: self.msg=self.msg+' ' return self.msg def connect_bootstrap(self): global Mcache sBootStrap = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sBootStrap.connect(('127.0.0.1', 7187)) sBootStrap.send("REGISTER\r\n") time.sleep(0.2) resp = sBootStrap.recv(1024) #print 'Resposta: ',resp.strip() if resp.strip()=='OK': #print "REGISTER OK" sBootStrap.send("LIST\r\n") time.sleep(0.2) data = sBootStrap.recv(1024) data = data.strip().split('\r\n') sBootStrap.send("EXIT\r\n") sBootStrap.close() #print len(data) Mcache = data #Mcache = ['192.168.1.3','192.168.1.3'] offLine = [] for ip in Mcache: try: #print 'voce esta tentando conectar em '+ ip sNode = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sNode.connect((ip, 50007)) sNode.send('PLAY') #print sNode.recv(1024) while 1: #sys.stdout.write(sNode.recv(1024)[1]) #tam = sNode.recv(1024) data = sNode.recv(1024) #values = struct.unpack('i'+tam+'s',data) #sys.stdout.write(values[1]) sys.stdout.write(data) except socket.error: offLine.append(ip) #print 'erro no socket' #print offLine node = csnode() node.connect_bootstrap()
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,random import struct, fcntl class Interface_ip: def set_interface(self,ifname): self.ifname = ifname def get_ip_address(self): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', self.ifname[:15]) )[20:24]) Mcache = [] class BootStrapHandler(SocketServer.BaseRequestHandler): def PadMsg(msg): while len(msg) < 1024: msg=msg+' ' return msg def server_bind(self): SocketServer.ThreadingTCPServer.server_bind(self) self.socket.setdefaulttimeout(5) self.run = True def setup(self): print 'BootStrap: ',self.client_address, ' conectou' def handle(self): try: global Mcache global McacheNode #Get command Saida=False while Saida!=True: data = self.request.recv(1024) if data.strip() != '': print 'BootStrap Recebeu: ',data.strip() else: pass if data.strip() == 'REGISTER': #Coloco o peer na lista de peers if Mcache.count(self.client_address[0]) <= 0: Mcache.append(str(self.client_address[0])) self.request.send('OK\r\n') else: pass elif data.strip() == 'REMOVE': data = self.request.recv(1024) while data.strip() != 'FINISH': print data.strip() if Mcache.count(data.strip()) > 0: Mcache.remove(data.strip()) else: print 'ERRO' data = self.request.recv(1024) elif data.strip() == 'LIST': Mcache = ['127.0.0.1','192.168.1.3','192.168.1.3','192.168.1.3','192.168.1.4','192.168.1.5','192.168.1.6','192.168.1.7'] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.12','192.168.1.15'] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3'] McacheNode = Mcache[:] McacheNode.remove(self.client_address[0]) if Mcache.count(self.client_address[0]) >0: if len(McacheNode) <= 5 and len(McacheNode) > 0: for Ip in McacheNode: self.request.send(str(Ip)+'\r\n') elif len(McacheNode) > 5: peerSelect = [] while len(peerSelect) < 5: peerIp = random.choice(McacheNode) print peerIp if peerSelect.count(peerIp) == 0: peerSelect.append(peerIp) for Ip in peerSelect: self.request.send(str(Ip)+'\r\n') else: IpServer = Interface_ip() IpServer.set_interface('eth0') Ip = IpServer.get_ip_address() self.request.send(str(Ip)+'\r\n') else: pass elif data.strip() == 'EXIT': Saida=True elif data.strip() == '': pass else: pass except : self.finish() def finish(self): print 'BootStrap: ',self.client_address,' desconectou' print repr(McacheNode) print repr(Mcache) def open_bootstrap(): SocketServer.ThreadingTCPServer.allow_reuse_address = 1 BootStrapPort = 7187 print 'BootStrap inicializado na porta: ' + str(BootStrapPort) bootstrap = SocketServer.ThreadingTCPServer(('',BootStrapPort), BootStrapHandler) try: bootstrap.serve_forever() except KeyboardInterrupt: sys.exit(0) def Initialize(): thread.start_new_thread(open_bootstrap,()) time.sleep(1) Initialize() while 1:pass
Python
from socket import * import pickle def PadMsg(msg): while len(msg) < 1024: msg=msg+' ' return msg myHost = '' myPort = 50007 sockobj = socket(AF_INET, SOCK_STREAM) sockobj.bind((myHost, myPort)) sockobj.listen(5) video = open('/home/zank/Desktop/tcc2/DESENVOLVIMENTO/provider/lost.avi', 'r') Saida=False while 1: connection, address = sockobj.accept() print 'Server connected by', address data = connection.recv(1024) print data if data.strip() == 'PLAY': count = 0 while 1: for stream in video.readlines(): #count = count+1 #chunk = openfile('chunkfile','w') #data = [count,stream] #pickle.dump(data,chunk) #chunk.close #chunktosend = open('chunkfile') #for line in chunktosend.readlines(): # connection.send(line) connection.send(stream) #chunktosend.close() #data = struct.pack('i'+tam+'s',count,stream) #connection.send(data) else: pass
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,random Mcache = [] class csnode: def connect_bootstrap(self): global Mcache sBootStrap = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sBootStrap.connect(('127.0.0.1', 7187)) sBootStrap.send("REGISTER\r\n") time.sleep(0.2) resp = sBootStrap.recv(1024) #print 'Resposta: ',resp.strip() if resp.strip()=='OK': #print "REGISTER OK" sBootStrap.send("LIST\r\n") time.sleep(0.2) data = sBootStrap.recv(1024) data = data.strip().split('\r\n') sBootStrap.send("EXIT\r\n") sBootStrap.close() #print len(data) Mcache = data #Mcache = ['192.168.1.3','192.168.1.3'] offLine = [] for ip in Mcache: try: #print 'voce esta tentando conectar em '+ ip sNode = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sNode.connect((ip, 50007)) sNode.send('PLAY') #print sNode.recv(1024) while 1: sys.stdout.write(sNode.recv(1024)) except socket.error: offLine.append(ip) #print 'erro no socket' #print offLine node = csnode() node.connect_bootstrap()
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,random import struct Mcache = [] class csnode: def PadMsg(self,msg): self.msg =msg while len(self.msg) < 1024: self.msg=self.msg+' ' return self.msg def connect_bootstrap(self): global Mcache sBootStrap = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sBootStrap.connect(('127.0.0.1', 7187)) sBootStrap.send("REGISTER\r\n") time.sleep(0.2) resp = sBootStrap.recv(1024) #print 'Resposta: ',resp.strip() if resp.strip()=='OK': #print "REGISTER OK" sBootStrap.send("LIST\r\n") time.sleep(0.2) data = sBootStrap.recv(1024) data = data.strip().split('\r\n') sBootStrap.send("EXIT\r\n") sBootStrap.close() #print len(data) Mcache = data #Mcache = ['192.168.1.3','192.168.1.3'] offLine = [] for ip in Mcache: try: #print 'voce esta tentando conectar em '+ ip sNode = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sNode.connect((ip, 50007)) sNode.send('PLAY') #print sNode.recv(1024) while 1: #sys.stdout.write(sNode.recv(1024)[1]) #data = struct.unpack('>i4sh',sNode.recv(1024)) sys.stdout.write(data) except socket.error: offLine.append(ip) #print 'erro no socket' #print offLine node = csnode() node.connect_bootstrap()
Python
#!/usr/bin/python import sys,time,socket,struct param = sys.argv[1:] IP,PACKAGE_SIZE,LOG = param Mcache = [] Buffer = [] PACKAGE_SIZE = int(PACKAGE_SIZE) PAYLOAD = PACKAGE_SIZE- 24 log = open(LOG+time.strftime('%Y%m%d%H%M%S')+'.txt','w') class csnode: #print 'voce esta tentando conectar em '+ ip sNode = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sNode.connect((IP, 50007)) sNode.send('PLAY') while 1: data = sNode.recv(PACKAGE_SIZE) dataRecv = time.strftime('%H:%M:%S') size_recv = len(data) if size_recv == 1024: id,chunk = struct.unpack('24s'+str(PAYLOAD)+'s',data) log.write(str(int(id))+';') log.write(str(size_recv)+';') log.write('recv'+dataRecv+';') sys.stdout.write(chunk) dataRead = time.strftime('%H:%M:%S') log.write('read'+dataRead+';') else: log.write('pacotePerdido;') log.write(str(size_recv)+';') break sNode.close() node = csnode()
Python
#!/usr/bin/python import sys,time,socket,struct param = sys.argv[1:] IP,PACKAGE_SIZE,LOG = param Mcache = [] Buffer = [] PACKAGE_SIZE = int(PACKAGE_SIZE) PAYLOAD = PACKAGE_SIZE- 24 log = open(LOG+time.strftime('%Y%m%d%H%M%S')+'.txt','w') class csnode: sNode = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sNode.connect((IP, 50007)) sNode.send('PLAY') while 1: data = sNode.recv(PACKAGE_SIZE) dataRecv = time.strftime('%H:%M:%S') size_recv = len(data) if size_recv == PACKAGE_SIZE: id,chunk = struct.unpack('24s'+str(PAYLOAD)+'s',data) log.write(str(int(id))+';') log.write(str(size_recv)+';') log.write('recv'+dataRecv+';') sys.stdout.write(chunk) dataRead = time.strftime('%H:%M:%S') log.write('read'+dataRead+';\r\n') else: log.write('pacotePerdido;') log.write(str(size_recv)+';\r\n') break sNode.close() node = csnode()
Python
#!/usr/bin/python import sys,time,socket,struct param = sys.argv[1:] IP,PACKAGE_SIZE,LOG = param Mcache = [] Buffer = [] PACKAGE_SIZE = int(PACKAGE_SIZE) PAYLOAD = PACKAGE_SIZE- 24 log = open(LOG+time.strftime('%Y%m%d%H%M%S')+'.txt','w') class csnode: #print 'voce esta tentando conectar em '+ ip sNode = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sNode.connect((IP, 50007)) sNode.send('PLAY') while 1: data = sNode.recv(PACKAGE_SIZE) dataRecv = time.strftime('%H:%M:%S') size_recv = len(data) if size_recv == 1024: id,chunk = struct.unpack('24s'+str(PAYLOAD)+'s',data) log.write(str(int(id))+';') log.write(str(size_recv)+';') log.write('recv'+dataRecv+';') sys.stdout.write(chunk) dataRead = time.strftime('%H:%M:%S') log.write('read'+dataRead+';') else: log.write('pacotePerdido;') log.write(str(size_recv)+';') break sNode.close() node = csnode()
Python
#!/usr/bin/python import sys,time,socket,struct param = sys.argv[1:] IP,PACKAGE_SIZE,LOG = param Mcache = [] Buffer = [] PACKAGE_SIZE = int(PACKAGE_SIZE) PAYLOAD = PACKAGE_SIZE- 24 log = open(LOG+time.strftime('%Y%m%d%H%M%S')+'.txt','w') class csnode: sNode = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sNode.connect((IP, 50007)) sNode.send('PLAY') while 1: data = sNode.recv(PACKAGE_SIZE) dataRecv = time.strftime('%H:%M:%S') size_recv = len(data) if size_recv == PACKAGE_SIZE: id,chunk = struct.unpack('24s'+str(PAYLOAD)+'s',data) log.write(str(int(id))+';') log.write(str(size_recv)+';') log.write('recv'+dataRecv+';') sys.stdout.write(chunk) dataRead = time.strftime('%H:%M:%S') log.write('read'+dataRead+';\r\n') else: log.write('pacotePerdido;') log.write(str(size_recv)+';\r\n') break sNode.close() node = csnode()
Python
import sys param = sys.argv[1:] ip,host,buffer,log = param print ip print host print buffer print log
Python
from socket import * import sys,struct,time myHost = '' myPort = 50007 param = sys.argv[1:] N_PEER,BUFFER,LOG = param print N_PEER print BUFFER sockobj = socket(AF_INET, SOCK_STREAM) sockobj.bind((myHost, myPort)) sockobj.listen(int(N_PEER)) #video = open('/home/zank/Desktop/tcc2/DESENVOLVIMENTO/provider/lost.avi', 'r') video = open('/home/zank/Desktop/pes2009.mpg', 'r') log = open(LOG+time.strftime('%Y%m%d%H%M%S')+'.txt','w') Saida=False count = 0 lista = [] payload = int(BUFFER)-24 while len(lista) < int(N_PEER): connection, address = sockobj.accept() print 'Server connected by', address data = connection.recv(1024) print data if data.strip() == 'PLAY': lista.append([address,connection]) else: pass while 1: stream = video.read(payload) if len(stream) == 0: break count = count+1 id = str(count) id = id.rjust(24,'0') data = struct.pack('24s'+str(payload)+'s',id,stream) for sock_obj in lista: try: sock_obj[1].send(data) log.write(str(int(id))+';') log.write(str(len(data))+';') log.write(str(sock_obj[0])+';') log.write(time.strftime('%H:%M:%S')+'\r\n') except: lista.remove(sock_obj) log.close() sockobj.close()
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,random import struct, fcntl class Interface_ip: def set_interface(self,ifname): self.ifname = ifname def get_ip_address(self): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', self.ifname[:15]) )[20:24]) Mcache = [] class BootStrapHandler(SocketServer.BaseRequestHandler): def PadMsg(msg): while len(msg) < 1024: msg=msg+' ' return msg def server_bind(self): SocketServer.ThreadingTCPServer.server_bind(self) self.socket.setdefaulttimeout(5) self.run = True def setup(self): print 'BootStrap: ',self.client_address, ' conectou' def handle(self): try: global Mcache global McacheNode #Get command Saida=False while Saida!=True: data = self.request.recv(1024) if data.strip() != '': print 'BootStrap Recebeu: ',data.strip() else: pass if data.strip() == 'REGISTER': #Coloco o peer na lista de peers if Mcache.count(self.client_address[0]) <= 0: Mcache.append(str(self.client_address[0])) self.request.send('OK\r\n') else: pass elif data.strip() == 'REMOVE': data = self.request.recv(1024) while data.strip() != 'FINISH': print data.strip() if Mcache.count(data.strip()) > 0: Mcache.remove(data.strip()) else: print 'ERRO' data = self.request.recv(1024) elif data.strip() == 'LIST': Mcache = ['127.0.0.1','192.168.1.3','192.168.1.3','192.168.1.3','192.168.1.4','192.168.1.5','192.168.1.6','192.168.1.7'] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.12','192.168.1.15'] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3'] McacheNode = Mcache[:] McacheNode.remove(self.client_address[0]) if Mcache.count(self.client_address[0]) >0: if len(McacheNode) <= 5 and len(McacheNode) > 0: for Ip in McacheNode: self.request.send(str(Ip)+'\r\n') elif len(McacheNode) > 5: peerSelect = [] while len(peerSelect) < 5: peerIp = random.choice(McacheNode) print peerIp if peerSelect.count(peerIp) == 0: peerSelect.append(peerIp) for Ip in peerSelect: self.request.send(str(Ip)+'\r\n') else: IpServer = Interface_ip() IpServer.set_interface('eth0') Ip = IpServer.get_ip_address() self.request.send(str(Ip)+'\r\n') else: pass elif data.strip() == 'EXIT': Saida=True elif data.strip() == '': pass else: pass except : self.finish() def finish(self): print 'BootStrap: ',self.client_address,' desconectou' print repr(McacheNode) print repr(Mcache) def open_bootstrap(): SocketServer.ThreadingTCPServer.allow_reuse_address = 1 BootStrapPort = 7187 print 'BootStrap inicializado na porta: ' + str(BootStrapPort) bootstrap = SocketServer.ThreadingTCPServer(('',BootStrapPort), BootStrapHandler) try: bootstrap.serve_forever() except KeyboardInterrupt: sys.exit(0) def Initialize(): thread.start_new_thread(open_bootstrap,()) time.sleep(1) Initialize() while 1:pass
Python
from socket import * import struct myHost = '' myPort = 50007 sockobj = socket(AF_INET, SOCK_STREAM) sockobj.bind((myHost, myPort)) sockobj.listen(5) video = open('../../DESENVOLVIMENTO/provider/lost.avi', 'r') Saida=False while 1: connection, address = sockobj.accept() print 'Server connected by', address data = connection.recv(1024) print data if data.strip() == 'PLAY': count = 0 while 1: for stream in video.readlines(): #data = struct.pack('>i4sh',count,stream) count=count+1 connection.send(stream) # Saida = True else: pass
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,struct,fcntl class Interface_ip: def set_interface(self,ifname): self.ifname = ifname def get_ip_address(self): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', self.ifname[:15]) )[20:24]) Mcache = [] class BootStrapHandler(SocketServer.BaseRequestHandler): def PadMsg(self,msg): while len(msg) < 1024: self.msg=msg+' ' return self.msg def server_bind(self): SocketServer.ThreadingTCPServer.server_bind(self) self.socket.setdefaulttimeout(5) self.run = True def setup(self): print 'BootStrap: ',self.client_address, ' conectou' def handle(self): try: global Mcache global McacheNode global ipServer #Get command Saida=False while Saida!=True: data = self.request.recv(1024) if data.strip() != '': print 'BootStrap Recebeu: ',data.strip() else: pass if data.strip() == 'REGISTER': #Coloco o peer na lista de peers if Mcache.count(self.client_address[0]) <= 0: Mcache.append(str(self.client_address[0])) self.request.send('OK') else: self.request.send('ERR') pass elif data.strip() == 'REMOVE': data = self.request.recv(1024) while data.strip() != 'FINISH': print data.strip() if Mcache.count(data.strip()) > 0: Mcache.remove(data.strip()) else: print 'ERRO' data = self.request.recv(1024) elif data.strip() == 'LIST': #Mcacches criados estaticamente apenas para fins de testes durante a implementacao #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.4','192.168.1.5','192.168.1.6','192.168.1.7',] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.12','192.168.1.15'] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3'] McacheNode = [] for ip in Mcache: #O peer so pode listar se estiver registrado if ip != self.client_address[0]: McacheNode.append(ip) # print ip if Mcache.count(self.client_address[0]) >0: #McacheNode.remove(self.client_address[0]) if len(McacheNode) <= 5 and len(McacheNode) > 0: for Ip in McacheNode: self.request.send((str(Ip))+'\r\n') #self.request.send('FINISH') elif len(McacheNode) > 5: peerSelect = [] while len(peerSelect) < 5: peerIp = random.choice(McacheNode) print peerIp if peerSelect.count(peerIp) == 0: peerSelect.append(peerIp) for Ip in peerSelect: self.request.send(str(Ip)+'\r\n') else: ipServer = Interface_ip() ipServer.set_interface('eth0') self.request.send(str(ipServer.get_ip_address())) else: pass elif data.strip() == 'EXIT': Saida=True elif data.strip() == '': pass else: pass except : self.finish() def finish(self): print 'BootStrap: ',self.client_address,' desconectou' print repr(McacheNode) print repr(Mcache) def open_bootstrap(): SocketServer.ThreadingTCPServer.allow_reuse_address = 1 BootStrapPort = 7187 print 'BootStrap inicializado na porta: ' + str(BootStrapPort) bootstrap = SocketServer.ThreadingTCPServer(('',BootStrapPort), BootStrapHandler) try: bootstrap.serve_forever() except KeyboardInterrupt: sys.exit(0) def Initialize(): thread.start_new_thread(open_bootstrap,()) time.sleep(1) Initialize() while 1:pass
Python
import SocketServer,sys,re,time,thread,threading,os,socket,random s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 7187)) s.send("REGISTER\r\n") time.sleep(0.2) resp = s.recv(1024) print 'Resposta: ',resp.strip() #s.send("REGISTER\r\n") #time.sleep(0.2) #resp = s.recv(1024) #print 'Resposta: ',resp.strip() if resp.strip()=='OK': print "REGISTER OK" s.send("LIST\r\n") Mcache = [] time.sleep(0.2) data = s.recv(1024) data = data.strip().split('\r\n') print len(data) Mcache = data for ip in Mcache: print 'voce esta tentando conectar em '+ ip s.send("EXIT\r\n") # while data.strip() != 'FINISH': # Mcache.append(data.strip()) # data = s.recv(1024) # print Mcache # #else: # print "REGISTER Falhou" s.close() #while 1: # chunk = s.recv(1024) # if not chunk: # sys.stdout.write("@") # time.sleep(0.1) # #s.send("LIST\r\n") #data = s.recv(1024) #print data #time.sleep(0.1) #data = s.recv(1024) #print data
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,struct,fcntl class Interface_ip: def set_interface(self,ifname): self.ifname = ifname def get_ip_address(self): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', self.ifname[:15]) )[20:24]) Mcache = [] class BootStrapHandler(SocketServer.BaseRequestHandler): def PadMsg(self,msg): while len(msg) < 1024: self.msg=msg+' ' return self.msg def server_bind(self): SocketServer.ThreadingTCPServer.server_bind(self) self.socket.setdefaulttimeout(5) self.run = True def setup(self): print 'BootStrap: ',self.client_address, ' conectou' def handle(self): try: global Mcache global McacheNode global ipServer #Get command Saida=False while Saida!=True: data = self.request.recv(1024) if data.strip() != '': print 'BootStrap Recebeu: ',data.strip() else: pass if data.strip() == 'REGISTER': #Coloco o peer na lista de peers if Mcache.count(self.client_address[0]) <= 0: Mcache.append(str(self.client_address[0])) self.request.send('OK') else: self.request.send('ERR') pass elif data.strip() == 'REMOVE': data = self.request.recv(1024) while data.strip() != 'FINISH': print data.strip() if Mcache.count(data.strip()) > 0: Mcache.remove(data.strip()) else: print 'ERRO' data = self.request.recv(1024) elif data.strip() == 'LIST': #Mcacches criados estaticamente apenas para fins de testes durante a implementacao #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.4','192.168.1.5','192.168.1.6','192.168.1.7',] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.12','192.168.1.15'] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3'] McacheNode = [] for ip in Mcache: #O peer so pode listar se estiver registrado if ip != self.client_address[0]: McacheNode.append(ip) # print ip if Mcache.count(self.client_address[0]) >0: #McacheNode.remove(self.client_address[0]) if len(McacheNode) <= 5 and len(McacheNode) > 0: for Ip in McacheNode: self.request.send((str(Ip))+'\r\n') #self.request.send('FINISH') elif len(McacheNode) > 5: peerSelect = [] while len(peerSelect) < 5: peerIp = random.choice(McacheNode) print peerIp if peerSelect.count(peerIp) == 0: peerSelect.append(peerIp) for Ip in peerSelect: self.request.send(str(Ip)+'\r\n') else: ipServer = Interface_ip() ipServer.set_interface('eth0') self.request.send(str(ipServer.get_ip_address())) else: pass elif data.strip() == 'EXIT': Saida=True elif data.strip() == '': pass else: pass except : self.finish() def finish(self): print 'BootStrap: ',self.client_address,' desconectou' print repr(McacheNode) print repr(Mcache) def open_bootstrap(): SocketServer.ThreadingTCPServer.allow_reuse_address = 1 BootStrapPort = 7187 print 'BootStrap inicializado na porta: ' + str(BootStrapPort) bootstrap = SocketServer.ThreadingTCPServer(('',BootStrapPort), BootStrapHandler) try: bootstrap.serve_forever() except KeyboardInterrupt: sys.exit(0) def Initialize(): thread.start_new_thread(open_bootstrap,()) time.sleep(1) Initialize() while 1:pass
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,random import struct, fcntl class Interface_ip: def set_interface(self,ifname): self.ifname = ifname def get_ip_address(self): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', self.ifname[:15]) )[20:24]) Mcache = [] class BootStrapHandler(SocketServer.BaseRequestHandler): def PadMsg(msg): while len(msg) < 1024: msg=msg+' ' return msg def server_bind(self): SocketServer.ThreadingTCPServer.server_bind(self) self.socket.setdefaulttimeout(5) self.run = True def setup(self): print 'BootStrap: ',self.client_address, ' conectou' def handle(self): try: global Mcache global McacheNode #Get command Saida=False while Saida!=True: data = self.request.recv(1024) if data.strip() != '': print 'BootStrap Recebeu: ',data.strip() else: pass if data.strip() == 'REGISTER': #Coloco o peer na lista de peers if Mcache.count(self.client_address[0]) <= 0: Mcache.append(str(self.client_address[0])) self.request.send('OK\r\n') else: pass elif data.strip() == 'REMOVE': data = self.request.recv(1024) while data.strip() != 'FINISH': print data.strip() if Mcache.count(data.strip()) > 0: Mcache.remove(data.strip()) else: print 'ERRO' data = self.request.recv(1024) elif data.strip() == 'LIST': Mcache = ['127.0.0.1','192.168.1.3','192.168.1.3','192.168.1.3','192.168.1.4','192.168.1.5','192.168.1.6','192.168.1.7'] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.12','192.168.1.15'] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3'] McacheNode = Mcache[:] McacheNode.remove(self.client_address[0]) if Mcache.count(self.client_address[0]) >0: if len(McacheNode) <= 5 and len(McacheNode) > 0: for Ip in McacheNode: self.request.send(str(Ip)+'\r\n') elif len(McacheNode) > 5: peerSelect = [] while len(peerSelect) < 5: peerIp = random.choice(McacheNode) print peerIp if peerSelect.count(peerIp) == 0: peerSelect.append(peerIp) for Ip in peerSelect: self.request.send(str(Ip)+'\r\n') else: IpServer = Interface_ip() IpServer.set_interface('eth0') Ip = IpServer.get_ip_address() self.request.send(str(Ip)+'\r\n') else: pass elif data.strip() == 'EXIT': Saida=True elif data.strip() == '': pass else: pass except : self.finish() def finish(self): print 'BootStrap: ',self.client_address,' desconectou' print repr(McacheNode) print repr(Mcache) def open_bootstrap(): SocketServer.ThreadingTCPServer.allow_reuse_address = 1 BootStrapPort = 7187 print 'BootStrap inicializado na porta: ' + str(BootStrapPort) bootstrap = SocketServer.ThreadingTCPServer(('',BootStrapPort), BootStrapHandler) try: bootstrap.serve_forever() except KeyboardInterrupt: sys.exit(0) def Initialize(): thread.start_new_thread(open_bootstrap,()) time.sleep(1) Initialize() while 1:pass
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,random Mcache = [] class csnode: def connect_bootstrap(self): global Mcache sBootStrap = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sBootStrap.connect(('127.0.0.1', 7187)) sBootStrap.send("REGISTER\r\n") time.sleep(0.2) resp = sBootStrap.recv(1024) print 'Resposta: ',resp.strip() if resp.strip()=='OK': print "REGISTER OK" sBootStrap.send("LIST\r\n") time.sleep(0.2) data = sBootStrap.recv(1024) data = data.strip().split('\r\n') sBootStrap.send("EXIT\r\n") sBootStrap.close() print len(data) Mcache = data #Mcache = ['192.168.1.3','192.168.1.3'] offLine = [] for ip in Mcache: try: print 'voce esta tentando conectar em '+ ip sNode = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sNode.connect((ip, 50007)) sNode.send('SEND') print sNode.recv(1024) except socket.error: offLine.append(ip) print 'erro no socket' print offLine node = csnode() node.connect_bootstrap()
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,random Mcache = [] class csnode: def connect_bootstrap(self): global Mcache sBootStrap = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sBootStrap.connect(('127.0.0.1', 7187)) sBootStrap.send("REGISTER\r\n") time.sleep(0.2) resp = sBootStrap.recv(1024) print 'Resposta: ',resp.strip() if resp.strip()=='OK': print "REGISTER OK" sBootStrap.send("LIST\r\n") time.sleep(0.2) data = sBootStrap.recv(1024) data = data.strip().split('\r\n') sBootStrap.send("EXIT\r\n") sBootStrap.close() print len(data) Mcache = data #Mcache = ['192.168.1.3','192.168.1.3'] offLine = [] for ip in Mcache: try: print 'voce esta tentando conectar em '+ ip sNode = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sNode.connect((ip, 50007)) sNode.send('SEND') print sNode.recv(1024) except socket.error: offLine.append(ip) print 'erro no socket' print offLine node = csnode() node.connect_bootstrap()
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,random import struct, fcntl class Interface_ip: def set_interface(self,ifname): self.ifname = ifname def get_ip_address(self): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', self.ifname[:15]) )[20:24]) Mcache = [] class BootStrapHandler(SocketServer.BaseRequestHandler): def PadMsg(msg): while len(msg) < 1024: msg=msg+' ' return msg def server_bind(self): SocketServer.ThreadingTCPServer.server_bind(self) self.socket.setdefaulttimeout(5) self.run = True def setup(self): print 'BootStrap: ',self.client_address, ' conectou' def handle(self): try: global Mcache global McacheNode #Get command Saida=False while Saida!=True: data = self.request.recv(1024) if data.strip() != '': print 'BootStrap Recebeu: ',data.strip() else: pass if data.strip() == 'REGISTER': #Coloco o peer na lista de peers if Mcache.count(self.client_address[0]) <= 0: Mcache.append(str(self.client_address[0])) self.request.send('OK\r\n') else: pass elif data.strip() == 'REMOVE': data = self.request.recv(1024) while data.strip() != 'FINISH': print data.strip() if Mcache.count(data.strip()) > 0: Mcache.remove(data.strip()) else: print 'ERRO' data = self.request.recv(1024) elif data.strip() == 'LIST': Mcache = ['127.0.0.1','192.168.1.3','192.168.1.3','192.168.1.3','192.168.1.4','192.168.1.5','192.168.1.6','192.168.1.7'] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.12','192.168.1.15'] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3'] McacheNode = Mcache[:] McacheNode.remove(self.client_address[0]) if Mcache.count(self.client_address[0]) >0: if len(McacheNode) <= 5 and len(McacheNode) > 0: for Ip in McacheNode: self.request.send(str(Ip)+'\r\n') elif len(McacheNode) > 5: peerSelect = [] while len(peerSelect) < 5: peerIp = random.choice(McacheNode) print peerIp if peerSelect.count(peerIp) == 0: peerSelect.append(peerIp) for Ip in peerSelect: self.request.send(str(Ip)+'\r\n') else: IpServer = Interface_ip() IpServer.set_interface('eth0') Ip = IpServer.get_ip_address() self.request.send(str(Ip)+'\r\n') else: pass elif data.strip() == 'EXIT': Saida=True elif data.strip() == '': pass else: pass except : self.finish() def finish(self): print 'BootStrap: ',self.client_address,' desconectou' print repr(McacheNode) print repr(Mcache) def open_bootstrap(): SocketServer.ThreadingTCPServer.allow_reuse_address = 1 BootStrapPort = 7187 print 'BootStrap inicializado na porta: ' + str(BootStrapPort) bootstrap = SocketServer.ThreadingTCPServer(('',BootStrapPort), BootStrapHandler) try: bootstrap.serve_forever() except KeyboardInterrupt: sys.exit(0) def Initialize(): thread.start_new_thread(open_bootstrap,()) time.sleep(1) Initialize() while 1:pass
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,random import struct, fcntl class Interface_ip: def set_interface(self,ifname): self.ifname = ifname def get_ip_address(self): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', self.ifname[:15]) )[20:24]) Mcache = [] class BootStrapHandler(SocketServer.BaseRequestHandler): def PadMsg(msg): while len(msg) < 1024: msg=msg+' ' return msg def server_bind(self): SocketServer.ThreadingTCPServer.server_bind(self) self.socket.setdefaulttimeout(5) self.run = True def setup(self): print 'BootStrap: ',self.client_address, ' conectou' def handle(self): try: global Mcache global McacheNode #Get command Saida=False while Saida!=True: data = self.request.recv(1024) if data.strip() != '': print 'BootStrap Recebeu: ',data.strip() else: pass if data.strip() == 'REGISTER': #Coloco o peer na lista de peers if Mcache.count(self.client_address[0]) <= 0: Mcache.append(str(self.client_address[0])) self.request.send('OK\r\n') else: pass elif data.strip() == 'REMOVE': data = self.request.recv(1024) while data.strip() != 'FINISH': print data.strip() if Mcache.count(data.strip()) > 0: Mcache.remove(data.strip()) else: print 'ERRO' data = self.request.recv(1024) elif data.strip() == 'LIST': Mcache = ['127.0.0.1','192.168.1.3','192.168.1.3','192.168.1.3','192.168.1.4','192.168.1.5','192.168.1.6','192.168.1.7'] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.12','192.168.1.15'] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3'] McacheNode = Mcache[:] McacheNode.remove(self.client_address[0]) if Mcache.count(self.client_address[0]) >0: if len(McacheNode) <= 5 and len(McacheNode) > 0: for Ip in McacheNode: self.request.send(str(Ip)+'\r\n') elif len(McacheNode) > 5: peerSelect = [] while len(peerSelect) < 5: peerIp = random.choice(McacheNode) print peerIp if peerSelect.count(peerIp) == 0: peerSelect.append(peerIp) for Ip in peerSelect: self.request.send(str(Ip)+'\r\n') else: IpServer = Interface_ip() IpServer.set_interface('eth0') Ip = IpServer.get_ip_address() self.request.send(str(Ip)+'\r\n') else: pass elif data.strip() == 'EXIT': Saida=True elif data.strip() == '': pass else: pass except : self.finish() def finish(self): print 'BootStrap: ',self.client_address,' desconectou' print repr(McacheNode) print repr(Mcache) def open_bootstrap(): SocketServer.ThreadingTCPServer.allow_reuse_address = 1 BootStrapPort = 7187 print 'BootStrap inicializado na porta: ' + str(BootStrapPort) bootstrap = SocketServer.ThreadingTCPServer(('',BootStrapPort), BootStrapHandler) try: bootstrap.serve_forever() except KeyboardInterrupt: sys.exit(0) def Initialize(): thread.start_new_thread(open_bootstrap,()) time.sleep(1) Initialize() while 1:pass
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,random Mcache = [] class csnode: def connect_bootstrap(self): global Mcache sBootStrap = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sBootStrap.connect(('127.0.0.1', 7187)) sBootStrap.send("REGISTER\r\n") time.sleep(0.2) resp = sBootStrap.recv(1024) print 'Resposta: ',resp.strip() if resp.strip()=='OK': print "REGISTER OK" sBootStrap.send("LIST\r\n") time.sleep(0.2) data = sBootStrap.recv(1024) data = data.strip().split('\r\n') sBootStrap.send("EXIT\r\n") sBootStrap.close() print len(data) Mcache = data #Mcache = ['192.168.1.3','192.168.1.3'] offLine = [] for ip in Mcache: try: print 'voce esta tentando conectar em '+ ip sNode = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sNode.connect((ip, 50007)) sNode.send('SEND') print sNode.recv(1024) except socket.error: offLine.append(ip) print 'erro no socket' print offLine node = csnode() node.connect_bootstrap()
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,random Mcache = [] class csnode: def connect_bootstrap(self): global Mcache sBootStrap = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sBootStrap.connect(('127.0.0.1', 7187)) sBootStrap.send("REGISTER\r\n") time.sleep(0.2) resp = sBootStrap.recv(1024) print 'Resposta: ',resp.strip() if resp.strip()=='OK': print "REGISTER OK" sBootStrap.send("LIST\r\n") time.sleep(0.2) data = sBootStrap.recv(1024) data = data.strip().split('\r\n') sBootStrap.send("EXIT\r\n") sBootStrap.close() print len(data) Mcache = data #Mcache = ['192.168.1.3','192.168.1.3'] offLine = [] for ip in Mcache: try: print 'voce esta tentando conectar em '+ ip sNode = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sNode.connect((ip, 50007)) sNode.send('SEND') print sNode.recv(1024) except socket.error: offLine.append(ip) print 'erro no socket' print offLine node = csnode() node.connect_bootstrap()
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,random import struct, fcntl class Interface_ip: def set_interface(self,ifname): self.ifname = ifname def get_ip_address(self): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', self.ifname[:15]) )[20:24]) Mcache = [] class BootStrapHandler(SocketServer.BaseRequestHandler): def PadMsg(msg): while len(msg) < 1024: msg=msg+' ' return msg def server_bind(self): SocketServer.ThreadingTCPServer.server_bind(self) self.socket.setdefaulttimeout(5) self.run = True def setup(self): print 'BootStrap: ',self.client_address, ' conectou' def handle(self): try: global Mcache global McacheNode #Get command Saida=False while Saida!=True: data = self.request.recv(1024) if data.strip() != '': print 'BootStrap Recebeu: ',data.strip() else: pass if data.strip() == 'REGISTER': #Coloco o peer na lista de peers if Mcache.count(self.client_address[0]) <= 0: Mcache.append(str(self.client_address[0])) self.request.send('OK\r\n') else: pass elif data.strip() == 'REMOVE': data = self.request.recv(1024) while data.strip() != 'FINISH': print data.strip() if Mcache.count(data.strip()) > 0: Mcache.remove(data.strip()) else: print 'ERRO' data = self.request.recv(1024) elif data.strip() == 'LIST': Mcache = ['127.0.0.1','192.168.1.3','192.168.1.3','192.168.1.3','192.168.1.4','192.168.1.5','192.168.1.6','192.168.1.7'] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.12','192.168.1.15'] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3'] McacheNode = Mcache[:] McacheNode.remove(self.client_address[0]) if Mcache.count(self.client_address[0]) >0: if len(McacheNode) <= 5 and len(McacheNode) > 0: for Ip in McacheNode: self.request.send(str(Ip)+'\r\n') elif len(McacheNode) > 5: peerSelect = [] while len(peerSelect) < 5: peerIp = random.choice(McacheNode) print peerIp if peerSelect.count(peerIp) == 0: peerSelect.append(peerIp) for Ip in peerSelect: self.request.send(str(Ip)+'\r\n') else: IpServer = Interface_ip() IpServer.set_interface('eth0') Ip = IpServer.get_ip_address() self.request.send(str(Ip)+'\r\n') else: pass elif data.strip() == 'EXIT': Saida=True elif data.strip() == '': pass else: pass except : self.finish() def finish(self): print 'BootStrap: ',self.client_address,' desconectou' print repr(McacheNode) print repr(Mcache) def open_bootstrap(): SocketServer.ThreadingTCPServer.allow_reuse_address = 1 BootStrapPort = 7187 print 'BootStrap inicializado na porta: ' + str(BootStrapPort) bootstrap = SocketServer.ThreadingTCPServer(('',BootStrapPort), BootStrapHandler) try: bootstrap.serve_forever() except KeyboardInterrupt: sys.exit(0) def Initialize(): thread.start_new_thread(open_bootstrap,()) time.sleep(1) Initialize() while 1:pass
Python
######################################################### # Server side: open a socket on a port, listen for # a message from a client, and send an echo reply; # this is a simple one-shot listen/reply per client, # but it goes into an infinite loop to listen for # more clients as long as this server script runs; ######################################################### from socket import * # get socket constructor and constants myHost = '' # server machine, '' means local host myPort = 50007 # listen on a non-reserved port number sockobj = socket(AF_INET, SOCK_STREAM) # make a TCP socket object sockobj.bind((myHost, myPort)) # bind it to server port number sockobj.listen(5) # listen, allow 5 pending connects while 1: # listen until process killed connection, address = sockobj.accept() # wait for next client connect print 'Server connected by', address # connection is a new socket while 1: data = connection.recv(1024) # read next line on client socket if not data: break # send a reply line to the client connection.send('Echo=>' + data) # until eof when socket closed connection.close()
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,random Mcache = [] class BootStrapHandler(SocketServer.BaseRequestHandler): def PadMsg(msg): while len(msg) < 1024: msg=msg+' ' return msg def server_bind(self): SocketServer.ThreadingTCPServer.server_bind(self) self.socket.setdefaulttimeout(5) self.run = True def setup(self): print 'BootStrap: ',self.client_address, ' conectou' def handle(self): try: global Mcache global McacheNode #Get command Saida=False while Saida!=True: data = self.request.recv(1024) if data.strip() != '': print 'BootStrap Recebeu: ',data.strip() else: pass if data.strip() == 'REGISTER': #Coloco o peer na lista de peers if Mcache.count(self.client_address[0]) <= 0: Mcache.append(str(self.client_address[0])) self.request.send('OK') else: pass elif data.strip() == 'REMOVE': data = self.request.recv(1024) while data.strip() != 'FINISH': print data.strip() if Mcache.count(data.strip()) > 0: Mcache.remove(data.strip()) else: print 'ERRO' data = self.request.recv(1024) elif data.strip() == 'LIST': #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.4','192.168.1.5','192.168.1.6','192.168.1.7',] Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.12','192.168.1.15'] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3'] McacheNode = [] for ip in Mcache: #O peer so pode listar se estiver registrado if ip != self.client_address[0]: McacheNode.append(ip) # print ip if Mcache.count(self.client_address[0]) >0: #McacheNode.remove(self.client_address[0]) if len(McacheNode) < 5: for Ip in McacheNode: self.request.send((str(Ip))+'\r\n') #self.request.send('FINISH') else: peerSelect = [] while len(peerSelect) < 5: peerIp = random.choice(McacheNode) print peerIp if peerSelect.count(peerIp) == 0: peerSelect.append(peerIp) for Ip in peerSelect: self.request.send(str(Ip)+'\r\n') else: pass elif data.strip() == 'EXIT': Saida=True elif data.strip() == '': pass else: pass except : self.finish() def finish(self): print 'BootStrap: ',self.client_address,' desconectou' print repr(McacheNode) print repr(Mcache) def open_bootstrap(): SocketServer.ThreadingTCPServer.allow_reuse_address = 1 BootStrapPort = 7187 print 'BootStrap inicializado na porta: ' + str(BootStrapPort) bootstrap = SocketServer.ThreadingTCPServer(('',BootStrapPort), BootStrapHandler) try: bootstrap.serve_forever() except KeyboardInterrupt: sys.exit(0) def Initialize(): thread.start_new_thread(open_bootstrap,()) time.sleep(1) Initialize() while 1:pass
Python
import SocketServer,sys,re,time,thread,threading,os,socket,random s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 7187)) s.send("REGISTER\r\n") time.sleep(0.2) resp = s.recv(1024) print 'Resposta: ',resp.strip() #s.send("REGISTER\r\n") #time.sleep(0.2) #resp = s.recv(1024) #print 'Resposta: ',resp.strip() if resp.strip()=='OK': print "REGISTER OK" s.send("LIST\r\n") Mcache = [] time.sleep(0.2) data = s.recv(1024) data = data.strip().split('\r\n') print len(data) print data s.send("EXIT\r\n") # while data.strip() != 'FINISH': # Mcache.append(data.strip()) # data = s.recv(1024) # print Mcache # #else: # print "REGISTER Falhou" s.close() #while 1: # chunk = s.recv(1024) # if not chunk: # sys.stdout.write("@") # time.sleep(0.1) # #s.send("LIST\r\n") #data = s.recv(1024) #print data #time.sleep(0.1) #data = s.recv(1024) #print data
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,random Mcache = [] class BootStrapHandler(SocketServer.BaseRequestHandler): def PadMsg(msg): while len(msg) < 1024: msg=msg+' ' return msg def server_bind(self): SocketServer.ThreadingTCPServer.server_bind(self) self.socket.setdefaulttimeout(5) self.run = True def setup(self): print 'BootStrap: ',self.client_address, ' conectou' def handle(self): try: global Mcache global McacheNode #Get command Saida=False while Saida!=True: data = self.request.recv(1024) if data.strip() != '': print 'BootStrap Recebeu: ',data.strip() else: pass if data.strip() == 'REGISTER': #Coloco o peer na lista de peers if Mcache.count(self.client_address[0]) <= 0: Mcache.append(str(self.client_address[0])) self.request.send('OK') else: pass elif data.strip() == 'REMOVE': data = self.request.recv(1024) while data.strip() != 'FINISH': print data.strip() if Mcache.count(data.strip()) > 0: Mcache.remove(data.strip()) else: print 'ERRO' data = self.request.recv(1024) elif data.strip() == 'LIST': #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.4','192.168.1.5','192.168.1.6','192.168.1.7',] Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.12','192.168.1.15'] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3'] McacheNode = [] for ip in Mcache: #O peer so pode listar se estiver registrado if ip != self.client_address[0]: McacheNode.append(ip) # print ip if Mcache.count(self.client_address[0]) >0: #McacheNode.remove(self.client_address[0]) if len(McacheNode) < 5: for Ip in McacheNode: self.request.send((str(Ip))+'\r\n') #self.request.send('FINISH') else: peerSelect = [] while len(peerSelect) < 5: peerIp = random.choice(McacheNode) print peerIp if peerSelect.count(peerIp) == 0: peerSelect.append(peerIp) for Ip in peerSelect: self.request.send(str(Ip)+'\r\n') else: pass elif data.strip() == 'EXIT': Saida=True elif data.strip() == '': pass else: pass except : self.finish() def finish(self): print 'BootStrap: ',self.client_address,' desconectou' print repr(McacheNode) print repr(Mcache) def open_bootstrap(): SocketServer.ThreadingTCPServer.allow_reuse_address = 1 BootStrapPort = 7187 print 'BootStrap inicializado na porta: ' + str(BootStrapPort) bootstrap = SocketServer.ThreadingTCPServer(('',BootStrapPort), BootStrapHandler) try: bootstrap.serve_forever() except KeyboardInterrupt: sys.exit(0) def Initialize(): thread.start_new_thread(open_bootstrap,()) time.sleep(1) Initialize() while 1:pass
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,Interface_ip Mcache = [] class BootStrapHandler(SocketServer.BaseRequestHandler): def PadMsg(self,msg): while len(msg) < 1024: self.msg=msg+' ' return self.msg def server_bind(self): SocketServer.ThreadingTCPServer.server_bind(self) self.socket.setdefaulttimeout(5) self.run = True def setup(self): print 'BootStrap: ',self.client_address, ' conectou' def handle(self): try: global Mcache global McacheNode global ipServer #Get command Saida=False while Saida!=True: data = self.request.recv(1024) if data.strip() != '': print 'BootStrap Recebeu: ',data.strip() else: pass if data.strip() == 'REGISTER': #Coloco o peer na lista de peers if Mcache.count(self.client_address[0]) <= 0: Mcache.append(str(self.client_address[0])) self.request.send('OK') else: self.request.send('ERR') pass elif data.strip() == 'REMOVE': data = self.request.recv(1024) while data.strip() != 'FINISH': print data.strip() if Mcache.count(data.strip()) > 0: Mcache.remove(data.strip()) else: print 'ERRO' data = self.request.recv(1024) elif data.strip() == 'LIST': #Mcacches criados estaticamente apenas para fins de testes durante a implementacao #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.4','192.168.1.5','192.168.1.6','192.168.1.7',] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.12','192.168.1.15'] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3'] McacheNode = [] for ip in Mcache: #O peer so pode listar se estiver registrado if ip != self.client_address[0]: McacheNode.append(ip) # print ip if Mcache.count(self.client_address[0]) >0: #McacheNode.remove(self.client_address[0]) if len(McacheNode) <= 5 and len(McacheNode) > 0: for Ip in McacheNode: self.request.send((str(Ip))+'\r\n') #self.request.send('FINISH') elif len(McacheNode) > 5: peerSelect = [] while len(peerSelect) < 5: peerIp = random.choice(McacheNode) print peerIp if peerSelect.count(peerIp) == 0: peerSelect.append(peerIp) for Ip in peerSelect: self.request.send(str(Ip)+'\r\n') else: ipServer = Interface_ip.Interface_ip() ipServer.set_interface('eth0') self.request.send(str(ipServer.get_ip_address())) else: pass elif data.strip() == 'EXIT': Saida=True elif data.strip() == '': pass else: pass except : self.finish() def finish(self): print 'BootStrap: ',self.client_address,' desconectou' print repr(McacheNode) print repr(Mcache) def open_bootstrap(): SocketServer.ThreadingTCPServer.allow_reuse_address = 1 BootStrapPort = 7187 print 'BootStrap inicializado na porta: ' + str(BootStrapPort) bootstrap = SocketServer.ThreadingTCPServer(('',BootStrapPort), BootStrapHandler) try: bootstrap.serve_forever() except KeyboardInterrupt: sys.exit(0) def Initialize(): thread.start_new_thread(open_bootstrap,()) time.sleep(1) Initialize() while 1:pass
Python
import SocketServer,sys,re,time,thread,threading,os,socket,random s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 7187)) s.send("REGISTER\r\n") time.sleep(0.2) resp = s.recv(1024) print 'Resposta: ',resp.strip() #s.send("REGISTER\r\n") #time.sleep(0.2) #resp = s.recv(1024) #print 'Resposta: ',resp.strip() if resp.strip()=='OK': print "REGISTER OK" s.send("LIST\r\n") Mcache = [] time.sleep(0.2) data = s.recv(1024) data = data.strip().split('\r\n') print len(data) Mcache = data for ip in Mcache: print 'voce esta tentando conectar em '+ ip s.send("EXIT\r\n") # while data.strip() != 'FINISH': # Mcache.append(data.strip()) # data = s.recv(1024) # print Mcache # #else: # print "REGISTER Falhou" s.close() #while 1: # chunk = s.recv(1024) # if not chunk: # sys.stdout.write("@") # time.sleep(0.1) # #s.send("LIST\r\n") #data = s.recv(1024) #print data #time.sleep(0.1) #data = s.recv(1024) #print data
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,Interface_ip Mcache = [] class BootStrapHandler(SocketServer.BaseRequestHandler): def PadMsg(self,msg): while len(msg) < 1024: self.msg=msg+' ' return self.msg def server_bind(self): SocketServer.ThreadingTCPServer.server_bind(self) self.socket.setdefaulttimeout(5) self.run = True def setup(self): print 'BootStrap: ',self.client_address, ' conectou' def handle(self): try: global Mcache global McacheNode global ipServer #Get command Saida=False while Saida!=True: data = self.request.recv(1024) if data.strip() != '': print 'BootStrap Recebeu: ',data.strip() else: pass if data.strip() == 'REGISTER': #Coloco o peer na lista de peers if Mcache.count(self.client_address[0]) <= 0: Mcache.append(str(self.client_address[0])) self.request.send('OK') else: self.request.send('ERR') pass elif data.strip() == 'REMOVE': data = self.request.recv(1024) while data.strip() != 'FINISH': print data.strip() if Mcache.count(data.strip()) > 0: Mcache.remove(data.strip()) else: print 'ERRO' data = self.request.recv(1024) elif data.strip() == 'LIST': #Mcacches criados estaticamente apenas para fins de testes durante a implementacao #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.4','192.168.1.5','192.168.1.6','192.168.1.7',] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.12','192.168.1.15'] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3'] McacheNode = [] for ip in Mcache: #O peer so pode listar se estiver registrado if ip != self.client_address[0]: McacheNode.append(ip) # print ip if Mcache.count(self.client_address[0]) >0: #McacheNode.remove(self.client_address[0]) if len(McacheNode) <= 5 and len(McacheNode) > 0: for Ip in McacheNode: self.request.send((str(Ip))+'\r\n') #self.request.send('FINISH') elif len(McacheNode) > 5: peerSelect = [] while len(peerSelect) < 5: peerIp = random.choice(McacheNode) print peerIp if peerSelect.count(peerIp) == 0: peerSelect.append(peerIp) for Ip in peerSelect: self.request.send(str(Ip)+'\r\n') else: ipServer = Interface_ip.Interface_ip() ipServer.set_interface('eth0') self.request.send(str(ipServer.get_ip_address())) else: pass elif data.strip() == 'EXIT': Saida=True elif data.strip() == '': pass else: pass except : self.finish() def finish(self): print 'BootStrap: ',self.client_address,' desconectou' print repr(McacheNode) print repr(Mcache) def open_bootstrap(): SocketServer.ThreadingTCPServer.allow_reuse_address = 1 BootStrapPort = 7187 print 'BootStrap inicializado na porta: ' + str(BootStrapPort) bootstrap = SocketServer.ThreadingTCPServer(('',BootStrapPort), BootStrapHandler) try: bootstrap.serve_forever() except KeyboardInterrupt: sys.exit(0) def Initialize(): thread.start_new_thread(open_bootstrap,()) time.sleep(1) Initialize() while 1:pass
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,random Mcache = [] class BootStrapHandler(SocketServer.BaseRequestHandler): def server_bind(self): SocketServer.ThreadingTCPServer.server_bind(self) self.socket.setdefaulttimeout(5) self.run = True def setup(self): print 'BootStrap: ',self.client_address, ' conectou' def handle(self): try: global Mcache #Get command Saida=False while Saida!=True: data = self.request.recv(1024) print 'BootStrap Recebeu: ',data.strip() if data.strip() == 'REGISTER': #Coloco o peer na lista de peers if Mcache.count(self.client_address[0]) <= 0: Mcache.append(str(self.client_address[0])) else: pass elif data.strip() == 'REMOVE': data = self.request.recv(1024) while data.strip() != 'FINISH': print data.strip() if Mcache.count(data.strip()) > 0: Mcache.remove(data.strip()) else: print 'ERRO' data = self.request.recv(1024) elif data.strip() == 'LIST': #O peer so pode listar se estiver registrado #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.4','192.168.1.5','192.168.1.6','192.168.1.7',] Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3'] if Mcache.count(self.client_address[0]) >0: if len(Mcache) < 5: for Ip in Mcache: self.request.send(str(Ip)) self.request.send('\r\n') else: peerSelect = [] while len(peerSelect) != 5: peerIp = random.choice(Mcache) if peerSelect.count(peerIp) == 0: peerSelect.append(peerIp) for Ip in peerSelect: self.request.send(str(Ip)) self.request.send('\r\n') else: pass elif data.strip() == 'EXIT': Saida=True elif data.strip() == '': pass else: pass except : self.finish() def finish(self): print 'BootStrap: ',self.client_address,' desconectou' print repr(Mcache) def open_bootstrap(): SocketServer.ThreadingTCPServer.allow_reuse_address = 1 BootStrapPort = 7187 print 'BootStrap inicializado na porta: ' + str(BootStrapPort) bootstrap = SocketServer.ThreadingTCPServer(('',BootStrapPort), BootStrapHandler) try: bootstrap.serve_forever() except KeyboardInterrupt: sys.exit(0) def Initialize(): thread.start_new_thread(open_bootstrap,()) time.sleep(1) Initialize() while 1:pass
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,random Mcache = [] class BootStrapHandler(SocketServer.BaseRequestHandler): def server_bind(self): SocketServer.ThreadingTCPServer.server_bind(self) self.socket.setdefaulttimeout(5) self.run = True def setup(self): print 'BootStrap: ',self.client_address, ' conectou' def handle(self): try: global Mcache #Get command Saida=False while Saida!=True: data = self.request.recv(1024) print 'BootStrap Recebeu: ',data.strip() if data.strip() == 'REGISTER': #Coloco o peer na lista de peers if Mcache.count(self.client_address[0]) <= 0: Mcache.append(str(self.client_address[0])) else: pass elif data.strip() == 'REMOVE': data = self.request.recv(1024) while data.strip() != 'FINISH': print data.strip() if Mcache.count(data.strip()) > 0: Mcache.remove(data.strip()) else: print 'ERRO' data = self.request.recv(1024) elif data.strip() == 'LIST': #O peer so pode listar se estiver registrado #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.4','192.168.1.5','192.168.1.6','192.168.1.7',] Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3'] if Mcache.count(self.client_address[0]) >0: if len(Mcache) < 5: for Ip in Mcache: self.request.send(str(Ip)) self.request.send('\r\n') else: peerSelect = [] while len(peerSelect) != 5: peerIp = random.choice(Mcache) if peerSelect.count(peerIp) == 0: peerSelect.append(peerIp) for Ip in peerSelect: self.request.send(str(Ip)) self.request.send('\r\n') else: pass elif data.strip() == 'EXIT': Saida=True elif data.strip() == '': pass else: pass except : self.finish() def finish(self): print 'BootStrap: ',self.client_address,' desconectou' print repr(Mcache) def open_bootstrap(): SocketServer.ThreadingTCPServer.allow_reuse_address = 1 BootStrapPort = 7187 print 'BootStrap inicializado na porta: ' + str(BootStrapPort) bootstrap = SocketServer.ThreadingTCPServer(('',BootStrapPort), BootStrapHandler) try: bootstrap.serve_forever() except KeyboardInterrupt: sys.exit(0) def Initialize(): thread.start_new_thread(open_bootstrap,()) time.sleep(1) Initialize() while 1:pass
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,random,Interface_ip Mcache = [] class BootStrapHandler(SocketServer.BaseRequestHandler): def PadMsg(msg): while len(msg) < 1024: msg=msg+' ' return msg def server_bind(self): SocketServer.ThreadingTCPServer.server_bind(self) self.socket.setdefaulttimeout(5) self.run = True def setup(self): print 'BootStrap: ',self.client_address, ' conectou' def handle(self): try: global Mcache global McacheNode #Get command Saida=False while Saida!=True: data = self.request.recv(1024) if data.strip() != '': print 'BootStrap Recebeu: ',data.strip() else: pass if data.strip() == 'REGISTER': #Coloco o peer na lista de peers if Mcache.count(self.client_address[0]) <= 0: Mcache.append(str(self.client_address[0])) self.request.send('OK') else: pass elif data.strip() == 'REMOVE': data = self.request.recv(1024) while data.strip() != 'FINISH': print data.strip() if Mcache.count(data.strip()) > 0: Mcache.remove(data.strip()) else: print 'ERRO' data = self.request.recv(1024) elif data.strip() == 'LIST': Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.4','192.168.1.5','192.168.1.6','192.168.1.7'] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.12','192.168.1.15'] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3'] #McacheNode = [] McacheNode = Mcache[:] McacheNode.remove(self.client_address[0]) #for ip in Mcache: # #O peer so pode listar se estiver registrado # if ip != self.client_address[0]: # McacheNode.append(ip) # print ip if Mcache.count(self.client_address[0]) >0: #McacheNode.remove(self.client_address[0]) if len(McacheNode) <= 5 and len(McacheNode) > 0: for Ip in McacheNode: self.request.send(str(Ip)+'\r\n') elif len(McacheNode) > 5: peerSelect = [] while len(peerSelect) < 5: peerIp = random.choice(McacheNode) print peerIp if peerSelect.count(peerIp) == 0: peerSelect.append(peerIp) for Ip in peerSelect: self.request.send(str(Ip)+'\r\n') else: IpServer = Interface_ip.Interface_ip() IpServer.set_interface('eth0') Ip = IpServer.get_ip_address() self.request.send(str(Ip)+'\r\n') else: pass elif data.strip() == 'EXIT': Saida=True elif data.strip() == '': pass else: pass except : self.finish() def finish(self): print 'BootStrap: ',self.client_address,' desconectou' print repr(McacheNode) print repr(Mcache) def open_bootstrap(): SocketServer.ThreadingTCPServer.allow_reuse_address = 1 BootStrapPort = 7187 print 'BootStrap inicializado na porta: ' + str(BootStrapPort) bootstrap = SocketServer.ThreadingTCPServer(('',BootStrapPort), BootStrapHandler) try: bootstrap.serve_forever() except KeyboardInterrupt: sys.exit(0) def Initialize(): thread.start_new_thread(open_bootstrap,()) time.sleep(1) Initialize() while 1:pass
Python
import SocketServer,sys,re,time,thread,threading,os,socket,random s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 7187)) s.send("REGISTER\r\n") time.sleep(0.2) resp = s.recv(1024) print 'Resposta: ',resp.strip() #s.send("REGISTER\r\n") #time.sleep(0.2) #resp = s.recv(1024) #print 'Resposta: ',resp.strip() if resp.strip()=='OK': print "REGISTER OK" s.send("LIST\r\n") Mcache = [] time.sleep(0.2) data = s.recv(1024) data = data.strip().split('\r\n') print len(data) print data s.send("EXIT\r\n") # while data.strip() != 'FINISH': # Mcache.append(data.strip()) # data = s.recv(1024) # print Mcache # #else: # print "REGISTER Falhou" s.close() #while 1: # chunk = s.recv(1024) # if not chunk: # sys.stdout.write("@") # time.sleep(0.1) # #s.send("LIST\r\n") #data = s.recv(1024) #print data #time.sleep(0.1) #data = s.recv(1024) #print data
Python
import socket, struct, fcntl class Interface_ip: def set_interface(self,ifname): self.ifname = ifname def get_ip_address(self): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', self.ifname[:15]) )[20:24]) #ipServer = Interface_ip() #ipServer.set_interface('eth0') #print ipServer.get_ip_address()
Python
#!/usr/bin/python import SocketServer,sys,re,time,thread,threading,os,socket,random,Interface_ip Mcache = [] class BootStrapHandler(SocketServer.BaseRequestHandler): def PadMsg(msg): while len(msg) < 1024: msg=msg+' ' return msg def server_bind(self): SocketServer.ThreadingTCPServer.server_bind(self) self.socket.setdefaulttimeout(5) self.run = True def setup(self): print 'BootStrap: ',self.client_address, ' conectou' def handle(self): try: global Mcache global McacheNode #Get command Saida=False while Saida!=True: data = self.request.recv(1024) if data.strip() != '': print 'BootStrap Recebeu: ',data.strip() else: pass if data.strip() == 'REGISTER': #Coloco o peer na lista de peers if Mcache.count(self.client_address[0]) <= 0: Mcache.append(str(self.client_address[0])) self.request.send('OK') else: pass elif data.strip() == 'REMOVE': data = self.request.recv(1024) while data.strip() != 'FINISH': print data.strip() if Mcache.count(data.strip()) > 0: Mcache.remove(data.strip()) else: print 'ERRO' data = self.request.recv(1024) elif data.strip() == 'LIST': Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.4','192.168.1.5','192.168.1.6','192.168.1.7'] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.12','192.168.1.15'] #Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3'] #McacheNode = [] McacheNode = Mcache[:] McacheNode.remove(self.client_address[0]) #for ip in Mcache: # #O peer so pode listar se estiver registrado # if ip != self.client_address[0]: # McacheNode.append(ip) # print ip if Mcache.count(self.client_address[0]) >0: #McacheNode.remove(self.client_address[0]) if len(McacheNode) <= 5 and len(McacheNode) > 0: for Ip in McacheNode: self.request.send(str(Ip)+'\r\n') elif len(McacheNode) > 5: peerSelect = [] while len(peerSelect) < 5: peerIp = random.choice(McacheNode) print peerIp if peerSelect.count(peerIp) == 0: peerSelect.append(peerIp) for Ip in peerSelect: self.request.send(str(Ip)+'\r\n') else: IpServer = Interface_ip.Interface_ip() IpServer.set_interface('eth0') Ip = IpServer.get_ip_address() self.request.send(str(Ip)+'\r\n') else: pass elif data.strip() == 'EXIT': Saida=True elif data.strip() == '': pass else: pass except : self.finish() def finish(self): print 'BootStrap: ',self.client_address,' desconectou' print repr(McacheNode) print repr(Mcache) def open_bootstrap(): SocketServer.ThreadingTCPServer.allow_reuse_address = 1 BootStrapPort = 7187 print 'BootStrap inicializado na porta: ' + str(BootStrapPort) bootstrap = SocketServer.ThreadingTCPServer(('',BootStrapPort), BootStrapHandler) try: bootstrap.serve_forever() except KeyboardInterrupt: sys.exit(0) def Initialize(): thread.start_new_thread(open_bootstrap,()) time.sleep(1) Initialize() while 1:pass
Python
import sys,re,time,thread,threading,os,random from socket import * myHost = '' myPort = 50007 sockobj = socket(AF_INET, SOCK_STREAM) sockobj.bind((myHost, myPort)) sockobj.listen(5) lista = [] def thread1(): connection, address = sockobj.accept() print 'Server connected by', address lista.append(connection) data = connection.recv(1024) def thread2(): print 'imprimindo thread 2' for x in lista: try: x.send('se fudeu') except socket.error: lista.remove(x) def initialize(): while 1: thread.start_new_thread(thread1,()) time.sleep(1) thread.start_new_thread(thread2,()) time.sleep(1) initialize() while 1: pass
Python
import sys,re,time,thread,threading,os,random from socket import * myHost = '' myPort = 50007 sockobj = socket(AF_INET, SOCK_STREAM) sockobj.bind((myHost, myPort)) sockobj.listen(5) lista = [] def thread1(): connection, address = sockobj.accept() print 'Server connected by', address lista.append(connection) data = connection.recv(1024) def thread2(): print 'imprimindo thread 2' for x in lista: try: x.send('se fudeu') except : lista.remove(x) print len(lista) def initialize(): while 1: thread.start_new_thread(thread1,()) time.sleep(1) thread.start_new_thread(thread2,()) initialize() while 1: pass
Python
#!/usr/bin/python import sys,time,socket,struct param = sys.argv[1:] IP,PACKAGE_SIZE,LOG = param Mcache = [] Buffer = [] PACKAGE_SIZE = int(PACKAGE_SIZE) PAYLOAD = PACKAGE_SIZE- 24 log = open(LOG+time.strftime('%Y%m%d%H%M%S')+'.txt','w') class csnode: #print 'voce esta tentando conectar em '+ ip sNode = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sNode.connect((IP, 50007)) sNode.send('PLAY') while 1: data = sNode.recv(PACKAGE_SIZE) dataRecv = time.strftime('%H:%M:%S') size_recv = len(data) if size_recv > 1024: id,chunk = struct.unpack('24s'+str(PAYLOAD)+'s',data) log.write(str(int(id))+';') log.write(str(size_recv)+';') log.write('recv'+dataRecv+';') sys.stdout.write(chunk) dataRead = time.strftime('%H:%M:%S') log.write('read'+dataRead+';\r\n') else: log.write('pacotePerdido;') log.write(str(size_recv)+';\r\n') break sNode.close() node = csnode()
Python
#!/usr/bin/python import sys,time,socket,struct param = sys.argv[1:] IP,PACKAGE_SIZE,LOG = param Mcache = [] Buffer = [] PACKAGE_SIZE = int(PACKAGE_SIZE) PAYLOAD = PACKAGE_SIZE- 24 log = open(LOG+time.strftime('%Y%m%d%H%M%S')+'.txt','w') class csnode: #print 'voce esta tentando conectar em '+ ip sNode = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sNode.connect((IP, 50007)) sNode.send('PLAY') while 1: data = sNode.recv(PACKAGE_SIZE) dataRecv = time.strftime('%H:%M:%S') size_recv = len(data) if size_recv > 1024: id,chunk = struct.unpack('24s'+str(PAYLOAD)+'s',data) log.write(str(int(id))+';') log.write(str(size_recv)+';') log.write('recv'+dataRecv+';') sys.stdout.write(chunk) dataRead = time.strftime('%H:%M:%S') log.write('read'+dataRead+';\r\n') else: log.write('pacotePerdido;') log.write(str(size_recv)+';\r\n') break sNode.close() node = csnode()
Python
import sys param = sys.argv[1:] ip,host,buffer,log = param print ip print host print buffer print log
Python
from socket import * import sys,struct,time myHost = '' myPort = 50007 param = sys.argv[1:] N_PEER,BUFFER,LOG = param print N_PEER print BUFFER sockobj = socket(AF_INET, SOCK_STREAM) sockobj.bind((myHost, myPort)) sockobj.listen(int(N_PEER)) #video = open('/home/zank/Desktop/tcc2/DESENVOLVIMENTO/provider/lost.avi', 'r') video = open('/home/zank/Desktop/pes2009.mpg', 'r') log = open(LOG+time.strftime('%Y%m%d%H%M%S')+'.txt','w') Saida=False count = 0 lista = [] payload = int(BUFFER)-24 while len(lista) < int(N_PEER): connection, address = sockobj.accept() print 'Server connected by', address data = connection.recv(1024) print data if data.strip() == 'PLAY': lista.append([address,connection]) else: pass while 1: stream = video.read(payload) if len(stream) == 0: break count = count+1 id = str(count) id = id.rjust(24,'0') data = struct.pack('24s'+str(payload)+'s',id,stream) for sock_obj in lista: try: sock_obj[1].send(data) log.write(str(int(id))+';') log.write(str(len(data))+';') log.write(str(sock_obj[0])+';') log.write(time.strftime('%H:%M:%S')+'\r\n') except: lista.remove(sock_obj) log.close() sockobj.close()
Python
#!/usr/bin/env python import compizconfig context = compizconfig.Context() def CatSortCompare(v1, v2): if v1 == v2: return cmp(v1, v2) if context.Plugins['core'].Category == v1: return cmp('', v2 or 'zzzzzzzz') if context.Plugins['core'].Category == v2: return cmp(v1 or 'zzzzzzz', '') return cmp(v1 or 'zzzzzzzz', v2 or 'zzzzzzzz') pluginNames = [] pluginIcons = [] pluginDescs = [] for categ in sorted(context.Categories, CatSortCompare): for plugin in context.Categories[categ]: pluginNames.append([plugin.ShortDesc]) pluginIcons.append([plugin.Name]) pluginDescs.append([plugin.LongDesc]) categories = list(sorted(context.Categories, CatSortCompare)) plugins = list(context.Plugins) pl_categories = [] for categ in sorted(context.Categories, CatSortCompare): pl_categories.append(list([p.ShortDesc for p in context.Categories[categ]])) def getPluginNames(): return pluginNames def getPluginIconNames(): return pluginIcons def getPluginDescs(): return pluginDescs def getNumberOfPlugins(): return len(plugins) def getCategories(): return categories def getCategoryList(categ): return pl_categories[int(categ)] def getActivePluginList(): data = context.Plugins['core'].Display['active_plugins'].Value return data def enableDisablePlugin(plugin, status) : if context.Plugins[plugin[0]].Enabled != status: return "wrongStatus" else: if status == True: context.Plugins[plugin[0]].Enabled = False return context.Plugins[plugin[0]].Enabled else: context.Plugins[plugin[0]].Enabled = True return context.Plugins[plugin[0]].Enabled services = { 'getInfo.getNumberOfPlugins': getNumberOfPlugins, 'getInfo.getPluginNames' : getPluginNames, 'getInfo.getPluginIconNames' : getPluginIconNames, 'getInfo.getPluginDescs' : getPluginDescs, 'getInfo.getActivePluginList': getActivePluginList, 'getInfo.getCategoryList' : getCategoryList, 'getInfo.getCategories' : getCategories, 'getInfo.enableDisablePlugin' : enableDisablePlugin } if __name__ == '__main__': from pyamf.remoting.wsgigateway import WSGIGateway from wsgiref import simple_server gw = WSGIGateway(services) httpd = simple_server.WSGIServer( ('localhost', 8000), simple_server.WSGIRequestHandler, ) httpd.set_app(gw) print "Running Hello World AMF gateway on http://localhost:8000" httpd.serve_forever()
Python
#!/usr/bin/env python import compizconfig context = compizconfig.Context() def CatSortCompare(v1, v2): if v1 == v2: return cmp(v1, v2) if context.Plugins['core'].Category == v1: return cmp('', v2 or 'zzzzzzzz') if context.Plugins['core'].Category == v2: return cmp(v1 or 'zzzzzzz', '') return cmp(v1 or 'zzzzzzzz', v2 or 'zzzzzzzz') pluginNames = [] pluginIcons = [] pluginDescs = [] for categ in sorted(context.Categories, CatSortCompare): for plugin in context.Categories[categ]: pluginNames.append([plugin.ShortDesc]) pluginIcons.append([plugin.Name]) pluginDescs.append([plugin.LongDesc]) categories = list(sorted(context.Categories, CatSortCompare)) plugins = list(context.Plugins) pl_categories = [] for categ in sorted(context.Categories, CatSortCompare): pl_categories.append(list([p.ShortDesc for p in context.Categories[categ]])) def getPluginNames(): return pluginNames def getPluginIconNames(): return pluginIcons def getPluginDescs(): return pluginDescs def getNumberOfPlugins(): return len(plugins) def getCategories(): return categories def getCategoryList(categ): return pl_categories[int(categ)] def getActivePluginList(): data = context.Plugins['core'].Display['active_plugins'].Value return data def enableDisablePlugin(plugin, status) : if context.Plugins[plugin[0]].Enabled != status: return "wrongStatus" else: if status == True: context.Plugins[plugin[0]].Enabled = False return context.Plugins[plugin[0]].Enabled else: context.Plugins[plugin[0]].Enabled = True return context.Plugins[plugin[0]].Enabled services = { 'getInfo.getNumberOfPlugins': getNumberOfPlugins, 'getInfo.getPluginNames' : getPluginNames, 'getInfo.getPluginIconNames' : getPluginIconNames, 'getInfo.getPluginDescs' : getPluginDescs, 'getInfo.getActivePluginList': getActivePluginList, 'getInfo.getCategoryList' : getCategoryList, 'getInfo.getCategories' : getCategories, 'getInfo.enableDisablePlugin' : enableDisablePlugin } if __name__ == '__main__': from pyamf.remoting.wsgigateway import WSGIGateway from wsgiref import simple_server gw = WSGIGateway(services) httpd = simple_server.WSGIServer( ('localhost', 8000), simple_server.WSGIRequestHandler, ) httpd.set_app(gw) print "Running Hello World AMF gateway on http://localhost:8000" httpd.serve_forever()
Python
#!/usr/bin/env python import compizconfig context = compizconfig.Context() def CatSortCompare(v1, v2): if v1 == v2: return cmp(v1, v2) if context.Plugins['core'].Category == v1: return cmp('', v2 or 'zzzzzzzz') if context.Plugins['core'].Category == v2: return cmp(v1 or 'zzzzzzz', '') return cmp(v1 or 'zzzzzzzz', v2 or 'zzzzzzzz') def FirstItemSortCompare(sg1, sg2): return cmp(sg1[0], sg2[0]) def PluginSortCompare(p1, p2): return cmp(p1.ShortDesc, p2.ShortDesc) def SettingSortCompare(v1, v2): return cmp(v1.Plugin.Ranking[v1.Name], v2.Plugin.Ranking[v2.Name]) def fileExists(f): try: file = open(f) except IOError: exists = 0 else: exists = 1 return exists categories = [] for categ in list(sorted(context.Categories, CatSortCompare)): if categ is '': categ = 'Unknown' categories.append(categ) plugins = list(context.Plugins) categInfo = [] pluginInfo = [] categInfo.append(dict((k, v+1) for (v, k) in enumerate(categories))) categInfo[0]["allGroups"] = list(categories) categInfo[0]["activePlugins"] = list(context.Plugins['core'].Display['active_plugins'].Value) for categ in sorted(context.Categories, CatSortCompare): allPlugins = {} thePlugins = [] for plugin in context.Categories[categ]: thePlugins.append({"ShortDesc" : plugin.ShortDesc, "Name" : plugin.Name, "LongDesc" : plugin.LongDesc, "isEnabled" : plugin.Enabled, "Categ" : categ, "hasIcon" : fileExists('assets/icons/plugin-'+plugin.Name + '.png')}) allPlugins["plugins"] = thePlugins allPlugins["allPlugins"] = list(p.ShortDesc for p in context.Categories[categ]) pluginInfo.append(allPlugins); def getPluginInfo(): return pluginInfo def getCategInfo(): return categInfo def getStatus(plugin): return context.Plugins[plugin[0]].Enabled def getSettings(): allSettingsHolder = {} for nextPlugin in context.Plugins: settings = [] groupsSorted = sorted(context.Plugins[nextPlugin].Groups.items(), FirstItemSortCompare) for name, group in groupsSorted: if name is '': name = 'General' subGroupsSorted = sorted(group.items(), FirstItemSortCompare) theData = [] for subGroupName, subGroup in subGroupsSorted: subData = [] theSettings = sum((v.values() for v in [subGroup.Display]+[subGroup.Screens[0]]), []) theSettings = sorted(theSettings, SettingSortCompare) for setting in theSettings: subData.append({"Type" : setting.Type, "ShortDesc" : setting.ShortDesc, "info" : setting.Info, "Value" : setting.Value}) theData.append({"label" : subGroupName, "data" : subData}) settings.append({"label" : name, "data" : theData} ) allSettingsHolder[nextPlugin] = settings return allSettingsHolder def enableDisablePlugin(theParams) : # theParams is [plugin, status] plugin = theParams[0] status = theParams[1] if context.Plugins[plugin].Enabled == status: if status == True: context.Plugins[plugin].Enabled = False else: context.Plugins[plugin].Enabled = True if context.Plugins[plugin].Enabled == status: return "failed" else: return "succeeded" else: return "wrongStatus" services = { 'getPluginInfo': getPluginInfo, 'getCategInfo': getCategInfo, 'getSettings' : getSettings, 'enableDisablePlugin' : enableDisablePlugin, 'getStatus' : getStatus } if __name__ == '__main__': from pyamf.remoting.wsgigateway import WSGIGateway from wsgiref import simple_server gw = WSGIGateway(services) httpd = simple_server.WSGIServer( ('localhost', 8000), simple_server.WSGIRequestHandler, ) httpd.set_app(gw) print "Running Hello World AMF gateway on http://localhost:8000" httpd.serve_forever() proc = os.popen("""ps axo "%p,%a" | grep "server.py" | grep -v grep|cut -d',' -f1""").read() print proc procs = proc.split('\n') if len(procs) > 2: print "server already started" import sys sys.exit(1) else: print "no server yet" class GroupPage(Page): def __init__(self, name, group, filter=None): Page.__init__(self) self.subGroupAreas = [] if (group.has_key('')): sga = SubGroupArea('', group[''], filter) if not sga.Empty: self.SetContainer.pack_start(sga.Widget, False, False) self.Empty = False self.subGroupAreas = self.subGroupAreas + [sga] subGroupsSorted = sorted(group.keys(), cmp) for subGroup in subGroupsSorted: if not subGroup == '': sga = SubGroupArea(subGroup, group[subGroup], filter) if not sga.Empty: self.SetContainer.pack_start(sga.Widget, False, False) self.Empty = False self.subGroupAreas = self.subGroupAreas + [sga]
Python
#!/usr/bin/env python import compizconfig context = compizconfig.Context() def CatSortCompare(v1, v2): if v1 == v2: return cmp(v1, v2) if context.Plugins['core'].Category == v1: return cmp('', v2 or 'zzzzzzzz') if context.Plugins['core'].Category == v2: return cmp(v1 or 'zzzzzzz', '') return cmp(v1 or 'zzzzzzzz', v2 or 'zzzzzzzz') def FirstItemSortCompare(sg1, sg2): return cmp(sg1[0], sg2[0]) def PluginSortCompare(p1, p2): return cmp(p1.ShortDesc, p2.ShortDesc) def SettingSortCompare(v1, v2): return cmp(v1.Plugin.Ranking[v1.Name], v2.Plugin.Ranking[v2.Name]) allSettingsHolder = {} for nextPlugin in context.Plugins: settings = [] groupsSorted = sorted(context.Plugins[nextPlugin].Groups.items(), FirstItemSortCompare) for name, group in groupsSorted: if name is '': name = 'General' subGroupsSorted = sorted(group.items(), FirstItemSortCompare) theData = [] for subGroupName, subGroup in subGroupsSorted: subData = [] theSettings = sum((v.values() for v in [subGroup.Display]+[subGroup.Screens[0]]), []) theSettings = sorted(theSettings, SettingSortCompare) for setting in theSettings: subData.append({"Type" : setting.Type, "ShortDesc" : setting.ShortDesc, "info" : setting.Info, "Value" : setting.Value}) if setting.Type is "List": print setting.Info theData.append({"label" : subGroupName, "data" : subData}) settings.append({"label" : name, "data" : theData} ) allSettingsHolder[nextPlugin] = settings
Python
#!/usr/bin/env python import compizconfig context = compizconfig.Context() def CatSortCompare(v1, v2): if v1 == v2: return cmp(v1, v2) if context.Plugins['core'].Category == v1: return cmp('', v2 or 'zzzzzzzz') if context.Plugins['core'].Category == v2: return cmp(v1 or 'zzzzzzz', '') return cmp(v1 or 'zzzzzzzz', v2 or 'zzzzzzzz') def FirstItemSortCompare(sg1, sg2): return cmp(sg1[0], sg2[0]) def PluginSortCompare(p1, p2): return cmp(p1.ShortDesc, p2.ShortDesc) def SettingSortCompare(v1, v2): return cmp(v1.Plugin.Ranking[v1.Name], v2.Plugin.Ranking[v2.Name]) def fileExists(f): try: file = open(f) except IOError: exists = 0 else: exists = 1 return exists categories = [] for categ in list(sorted(context.Categories, CatSortCompare)): if categ is '': categ = 'Unknown' categories.append(categ) plugins = list(context.Plugins) categInfo = [] pluginInfo = [] categInfo.append(dict((k, v+1) for (v, k) in enumerate(categories))) categInfo[0]["allGroups"] = list(categories) categInfo[0]["activePlugins"] = list(context.Plugins['core'].Display['active_plugins'].Value) for categ in sorted(context.Categories, CatSortCompare): allPlugins = {} thePlugins = [] for plugin in context.Categories[categ]: thePlugins.append({"ShortDesc" : plugin.ShortDesc, "Name" : plugin.Name, "LongDesc" : plugin.LongDesc, "isEnabled" : plugin.Enabled, "Categ" : categ, "hasIcon" : fileExists('assets/icons/plugin-'+plugin.Name + '.png')}) allPlugins["plugins"] = thePlugins allPlugins["allPlugins"] = list(p.ShortDesc for p in context.Categories[categ]) pluginInfo.append(allPlugins); def getPluginInfo(): return pluginInfo def getCategInfo(): return categInfo def getStatus(plugin): return context.Plugins[plugin[0]].Enabled def getSettings(): allSettingsHolder = {} for nextPlugin in context.Plugins: settings = [] groupsSorted = sorted(context.Plugins[nextPlugin].Groups.items(), FirstItemSortCompare) for name, group in groupsSorted: if name is '': name = 'General' subGroupsSorted = sorted(group.items(), FirstItemSortCompare) theData = [] for subGroupName, subGroup in subGroupsSorted: subData = [] theSettings = sum((v.values() for v in [subGroup.Display]+[subGroup.Screens[0]]), []) theSettings = sorted(theSettings, SettingSortCompare) for setting in theSettings: subData.append({"Type" : setting.Type, "ShortDesc" : setting.ShortDesc, "info" : setting.Info, "Value" : setting.Value}) theData.append({"label" : subGroupName, "data" : subData}) settings.append({"label" : name, "data" : theData} ) allSettingsHolder[nextPlugin] = settings return allSettingsHolder def enableDisablePlugin(theParams) : # theParams is [plugin, status] plugin = theParams[0] status = theParams[1] if context.Plugins[plugin].Enabled == status: if status == True: context.Plugins[plugin].Enabled = False else: context.Plugins[plugin].Enabled = True if context.Plugins[plugin].Enabled == status: return "failed" else: return "succeeded" else: return "wrongStatus" services = { 'getPluginInfo': getPluginInfo, 'getCategInfo': getCategInfo, 'getSettings' : getSettings, 'enableDisablePlugin' : enableDisablePlugin, 'getStatus' : getStatus } if __name__ == '__main__': from pyamf.remoting.wsgigateway import WSGIGateway from wsgiref import simple_server gw = WSGIGateway(services) httpd = simple_server.WSGIServer( ('localhost', 8000), simple_server.WSGIRequestHandler, ) httpd.set_app(gw) print "Running Hello World AMF gateway on http://localhost:8000" httpd.serve_forever() proc = os.popen("""ps axo "%p,%a" | grep "server.py" | grep -v grep|cut -d',' -f1""").read() print proc procs = proc.split('\n') if len(procs) > 2: print "server already started" import sys sys.exit(1) else: print "no server yet" class GroupPage(Page): def __init__(self, name, group, filter=None): Page.__init__(self) self.subGroupAreas = [] if (group.has_key('')): sga = SubGroupArea('', group[''], filter) if not sga.Empty: self.SetContainer.pack_start(sga.Widget, False, False) self.Empty = False self.subGroupAreas = self.subGroupAreas + [sga] subGroupsSorted = sorted(group.keys(), cmp) for subGroup in subGroupsSorted: if not subGroup == '': sga = SubGroupArea(subGroup, group[subGroup], filter) if not sga.Empty: self.SetContainer.pack_start(sga.Widget, False, False) self.Empty = False self.subGroupAreas = self.subGroupAreas + [sga]
Python
#!/usr/bin/env python import compizconfig context = compizconfig.Context() def CatSortCompare(v1, v2): if v1 == v2: return cmp(v1, v2) if context.Plugins['core'].Category == v1: return cmp('', v2 or 'zzzzzzzz') if context.Plugins['core'].Category == v2: return cmp(v1 or 'zzzzzzz', '') return cmp(v1 or 'zzzzzzzz', v2 or 'zzzzzzzz') def FirstItemSortCompare(sg1, sg2): return cmp(sg1[0], sg2[0]) def PluginSortCompare(p1, p2): return cmp(p1.ShortDesc, p2.ShortDesc) def SettingSortCompare(v1, v2): return cmp(v1.Plugin.Ranking[v1.Name], v2.Plugin.Ranking[v2.Name]) allSettingsHolder = {} for nextPlugin in context.Plugins: settings = [] groupsSorted = sorted(context.Plugins[nextPlugin].Groups.items(), FirstItemSortCompare) for name, group in groupsSorted: if name is '': name = 'General' subGroupsSorted = sorted(group.items(), FirstItemSortCompare) theData = [] for subGroupName, subGroup in subGroupsSorted: subData = [] theSettings = sum((v.values() for v in [subGroup.Display]+[subGroup.Screens[0]]), []) theSettings = sorted(theSettings, SettingSortCompare) for setting in theSettings: subData.append({"Type" : setting.Type, "ShortDesc" : setting.ShortDesc, "info" : setting.Info, "Value" : setting.Value}) if setting.Type is "List": print setting.Info theData.append({"label" : subGroupName, "data" : subData}) settings.append({"label" : name, "data" : theData} ) allSettingsHolder[nextPlugin] = settings
Python
#!/usr/bin/env python import compizconfig context = compizconfig.Context() def CatSortCompare(v1, v2): if v1 == v2: return cmp(v1, v2) if context.Plugins['core'].Category == v1: return cmp('', v2 or 'zzzzzzzz') if context.Plugins['core'].Category == v2: return cmp(v1 or 'zzzzzzz', '') return cmp(v1 or 'zzzzzzzz', v2 or 'zzzzzzzz') categories = list(sorted(context.Categories, CatSortCompare)) plugins = list(context.Plugins) allPlugins = [] plugins={} for categ in sorted(context.Categories, CatSortCompare): plugins[categ] = [] for plugin in context.Categories[categ]: plugins[categ].append({"ShortDesc" : plugin.ShortDesc, "Name" : plugin.Name, "LongDesc" : plugin.LongDesc}) for categ in categories: allPlugins.append(plugins[categ]) def getPlugins(): return allPlugins def getActivePluginList(): data = context.Plugins['core'].Display['active_plugins'].Value return data def getCategories(): return categories services = { 'getPlugins': getPlugins, 'getActivePluginList': getActivePluginList, 'getCategories' : getCategories } if __name__ == '__main__': from pyamf.remoting.wsgigateway import WSGIGateway from wsgiref import simple_server gw = WSGIGateway(services) httpd = simple_server.WSGIServer( ('localhost', 8000), simple_server.WSGIRequestHandler, ) httpd.set_app(gw) print "Running Hello World AMF gateway on http://localhost:8000" httpd.serve_forever()
Python
#!/usr/bin/env python import compizconfig context = compizconfig.Context() def CatSortCompare(v1, v2): if v1 == v2: return cmp(v1, v2) if context.Plugins['core'].Category == v1: return cmp('', v2 or 'zzzzzzzz') if context.Plugins['core'].Category == v2: return cmp(v1 or 'zzzzzzz', '') return cmp(v1 or 'zzzzzzzz', v2 or 'zzzzzzzz') categories = list(sorted(context.Categories, CatSortCompare)) plugins = list(context.Plugins) allPlugins = [] plugins={} for categ in sorted(context.Categories, CatSortCompare): plugins[categ] = [] for plugin in context.Categories[categ]: plugins[categ].append({"ShortDesc" : plugin.ShortDesc, "Name" : plugin.Name, "LongDesc" : plugin.LongDesc}) for categ in categories: allPlugins.append(plugins[categ]) def getPlugins(): return allPlugins def getActivePluginList(): data = context.Plugins['core'].Display['active_plugins'].Value return data def getCategories(): return categories services = { 'getPlugins': getPlugins, 'getActivePluginList': getActivePluginList, 'getCategories' : getCategories } if __name__ == '__main__': from pyamf.remoting.wsgigateway import WSGIGateway from wsgiref import simple_server gw = WSGIGateway(services) httpd = simple_server.WSGIServer( ('localhost', 8000), simple_server.WSGIRequestHandler, ) httpd.set_app(gw) print "Running Hello World AMF gateway on http://localhost:8000" httpd.serve_forever()
Python
#!/usr/bin/env python def getList(): return list(["hello", "hi", "greetings"]) services = { 'getList': getList } if __name__ == '__main__': from pyamf.remoting.wsgigateway import WSGIGateway from wsgiref import simple_server gw = WSGIGateway(services) httpd = simple_server.WSGIServer( ('localhost', 8000), simple_server.WSGIRequestHandler, ) httpd.set_app(gw) print "Running Hello World AMF gateway on http://localhost:8000" httpd.serve_forever()
Python
#!/usr/bin/env python def getList(): return list(["hello", "hi", "greetings"]) services = { 'getList': getList } if __name__ == '__main__': from pyamf.remoting.wsgigateway import WSGIGateway from wsgiref import simple_server gw = WSGIGateway(services) httpd = simple_server.WSGIServer( ('localhost', 8000), simple_server.WSGIRequestHandler, ) httpd.set_app(gw) print "Running Hello World AMF gateway on http://localhost:8000" httpd.serve_forever()
Python
import compizconfig context = compizconfig.Context() def getInfoObject(): InfoObject = [] for category in sorted(context.Categories, CatSortCompare): nextCateg = {} nextCateg["Name"] = category nextCateg["Plugins"] = [] InfoObject.append(nextCateg) for plugin in sorted(context.Categories[category], PluginSortCompare): nextPlugin = getPluginInfo(plugin) nextCateg["Plugins"].append(nextPlugin) return InfoObject def getPluginInfo(plugin): infoObject = {} infoObject["Name"] = plugin.Name infoObject["ShortDesc"] = plugin.ShortDesc infoObject["LongDesc"] = plugin.LongDesc infoObject["Enabled"] = plugin.Enabled infoObject["Features"] = plugin.Features infoObject["Ranking"] = plugin.Ranking infoObject["Groups"] = [] for name, group in sorted(plugin.Groups.items(), FirstItemSortCompare): nextGroup = {} if name == '': nextGroup["Name"] = "General" else: nextGroup["Name"] = name nextGroup["SubGroups"] = [] infoObject["Groups"].append(nextGroup) for subGroupName, subGroup in sorted(group.items(), FirstItemSortCompare): nextSubGroup = {} nextSubGroup["Name"] = subGroupName nextSubGroup["Settings"] = [] nextGroup["SubGroups"].append(nextSubGroup) theSettings = sum((v.values() for v in [subGroup.Display]+[subGroup.Screens[0]]), []) for setting in sorted(theSettings, SettingSortCompare): nextSetting = getSettingInfo(setting) nextSubGroup["Settings"].append(nextSetting) return infoObject def getSettingInfo(setting): infoObject = {} infoObject["Name"] = setting.Name infoObject["ShortDesc"] = setting.ShortDesc infoObject["LongDesc"] = setting.LongDesc infoObject["Type"] = setting.Type infoObject["Hints"] = setting.Hints if setting.Type == "List": theInfo = {} theInfo["ListType"] = setting.Info[0] theInfo["ListInfo"] = list(setting.Info[1]) infoObject["Info"] = theInfo else: infoObject["Info"] = list(setting.Info) infoObject["Value"] = setting.Value infoObject["Default"] = setting.DefaultValue return infoObject def CatSortCompare(v1, v2): if v1 == v2: return cmp(v1, v2) if context.Plugins['core'].Category == v1: return cmp('', v2 or 'zzzzzzzz') if context.Plugins['core'].Category == v2: return cmp(v1 or 'zzzzzzz', '') return cmp(v1 or 'zzzzzzzz', v2 or 'zzzzzzzz') def FirstItemSortCompare(sg1, sg2): return cmp(sg1[0], sg2[0]) def PluginSortCompare(p1, p2): return cmp(p1.ShortDesc, p2.ShortDesc) def SettingSortCompare(v1, v2): return cmp(v1.Plugin.Ranking[v1.Name], v2.Plugin.Ranking[v2.Name])
Python
import settings import yaml import os import sys InfoObject = settings.getInfoObject() def writeYAMLToFile(): print "hello there" xml_file = os.path.abspath(__file__) xml_file = os.path.dirname(xml_file) xml_file = os.path.join(xml_file, "tester.yaml") testerXML = open(xml_file, 'w') yaml.dump(InfoObject, testerXML, default_flow_style=False) def getTheInfo(): return InfoObject services = { 'wrtieToFile' : writeYAMLToFile, 'getInfo': getTheInfo } if __name__ == '__main__': from pyamf.remoting.wsgigateway import WSGIGateway from wsgiref import simple_server gw = WSGIGateway(services) httpd = simple_server.WSGIServer( ('localhost', 8000), simple_server.WSGIRequestHandler, ) httpd.set_app(gw) print "Running Hello World AMF gateway on http://localhost:8000" httpd.serve_forever() proc = os.popen("""ps axo "%p,%a" | grep "server.py" | grep -v grep|cut -d',' -f1""").read() print proc procs = proc.split('\n') if len(procs) > 2: print "server already started" import sys sys.exit(1) else: print "no server yet"
Python
import compizconfig context = compizconfig.Context() def getInfoObject(): InfoObject = [] for category in sorted(context.Categories, CatSortCompare): nextCateg = {} nextCateg["Name"] = category nextCateg["Plugins"] = [] InfoObject.append(nextCateg) for plugin in sorted(context.Categories[category], PluginSortCompare): nextPlugin = getPluginInfo(plugin) nextCateg["Plugins"].append(nextPlugin) return InfoObject def getPluginInfo(plugin): infoObject = {} infoObject["Name"] = plugin.Name infoObject["ShortDesc"] = plugin.ShortDesc infoObject["LongDesc"] = plugin.LongDesc infoObject["Enabled"] = plugin.Enabled infoObject["Features"] = plugin.Features infoObject["Ranking"] = plugin.Ranking infoObject["Groups"] = [] for name, group in sorted(plugin.Groups.items(), FirstItemSortCompare): nextGroup = {} if name == '': nextGroup["Name"] = "General" else: nextGroup["Name"] = name nextGroup["SubGroups"] = [] infoObject["Groups"].append(nextGroup) for subGroupName, subGroup in sorted(group.items(), FirstItemSortCompare): nextSubGroup = {} nextSubGroup["Name"] = subGroupName nextSubGroup["Settings"] = [] nextGroup["SubGroups"].append(nextSubGroup) theSettings = sum((v.values() for v in [subGroup.Display]+[subGroup.Screens[0]]), []) for setting in sorted(theSettings, SettingSortCompare): nextSetting = getSettingInfo(setting) nextSubGroup["Settings"].append(nextSetting) return infoObject def getSettingInfo(setting): infoObject = {} infoObject["Name"] = setting.Name infoObject["ShortDesc"] = setting.ShortDesc infoObject["LongDesc"] = setting.LongDesc infoObject["Type"] = setting.Type infoObject["Hints"] = setting.Hints if setting.Type == "List": theInfo = {} theInfo["ListType"] = setting.Info[0] theInfo["ListInfo"] = list(setting.Info[1]) infoObject["Info"] = theInfo else: infoObject["Info"] = list(setting.Info) infoObject["Value"] = setting.Value infoObject["Default"] = setting.DefaultValue return infoObject def CatSortCompare(v1, v2): if v1 == v2: return cmp(v1, v2) if context.Plugins['core'].Category == v1: return cmp('', v2 or 'zzzzzzzz') if context.Plugins['core'].Category == v2: return cmp(v1 or 'zzzzzzz', '') return cmp(v1 or 'zzzzzzzz', v2 or 'zzzzzzzz') def FirstItemSortCompare(sg1, sg2): return cmp(sg1[0], sg2[0]) def PluginSortCompare(p1, p2): return cmp(p1.ShortDesc, p2.ShortDesc) def SettingSortCompare(v1, v2): return cmp(v1.Plugin.Ranking[v1.Name], v2.Plugin.Ranking[v2.Name])
Python
import settings import yaml import os import sys infoObject = settings.getInfoObject() def writeYAMLToFile(): print "hello there" xml_file = os.path.abspath(__file__) xml_file = os.path.dirname(xml_file) xml_file = os.path.join(xml_file, "tester.yaml") testerXML = open(xml_file, 'w') yaml.dump(infoObject, testerXML, default_flow_style=False) def getTheInfo(): return yaml.dump(infoObject, default_flow_style=False) services = { 'wrtieToFile' : writeYAMLToFile, 'getInfo': getTheInfo } if __name__ == '__main__': from pyamf.remoting.wsgigateway import WSGIGateway from wsgiref import simple_server gw = WSGIGateway(services) httpd = simple_server.WSGIServer( ('localhost', 8000), simple_server.WSGIRequestHandler, ) httpd.set_app(gw) print "Running Hello World AMF gateway on http://localhost:8000" httpd.serve_forever() proc = os.popen("""ps axo "%p,%a" | grep "server.py" | grep -v grep|cut -d',' -f1""").read() print proc procs = proc.split('\n') if len(procs) > 2: print "server already started" import sys sys.exit(1) else: print "no server yet"
Python
import compizconfig context = compizconfig.Context() def getInfoObject(): InfoObject = [] for category in sorted(context.Categories, CatSortCompare): nextCateg = {} nextCateg["Name"] = category nextCateg["Plugins"] = [] InfoObject.append(nextCateg) for plugin in sorted(context.Categories[category], PluginSortCompare): nextPlugin = getPluginInfo(plugin) nextCateg["Plugins"].append(nextPlugin) return InfoObject def getPluginInfo(plugin): infoObject = {} infoObject["Name"] = plugin.Name infoObject["ShortDesc"] = plugin.ShortDesc infoObject["LongDesc"] = plugin.LongDesc infoObject["Enabled"] = plugin.Enabled infoObject["Features"] = plugin.Features infoObject["Ranking"] = plugin.Ranking infoObject["Groups"] = [] for name, group in sorted(plugin.Groups.items(), FirstItemSortCompare): nextGroup = {} if name == '': nextGroup["Name"] = "General" else: nextGroup["Name"] = name nextGroup["SubGroups"] = [] infoObject["Groups"].append(nextGroup) for subGroupName, subGroup in sorted(group.items(), FirstItemSortCompare): nextSubGroup = {} nextSubGroup["Name"] = subGroupName nextSubGroup["Settings"] = [] nextGroup["SubGroups"].append(nextSubGroup) theSettings = sum((v.values() for v in [subGroup.Display]+[subGroup.Screens[0]]), []) for setting in sorted(theSettings, SettingSortCompare): nextSetting = getSettingInfo(setting) nextSubGroup["Settings"].append(nextSetting) return infoObject def getSettingInfo(setting): infoObject = {} infoObject["Name"] = setting.Name infoObject["ShortDesc"] = setting.ShortDesc infoObject["LongDesc"] = setting.LongDesc infoObject["Type"] = setting.Type infoObject["Hints"] = setting.Hints if setting.Type == "List": theInfo = {} theInfo["ListType"] = setting.Info[0] theInfo["ListInfo"] = list(setting.Info[1]) infoObject["Info"] = theInfo else: infoObject["Info"] = list(setting.Info) infoObject["Value"] = setting.Value infoObject["Default"] = setting.DefaultValue return infoObject def CatSortCompare(v1, v2): if v1 == v2: return cmp(v1, v2) if context.Plugins['core'].Category == v1: return cmp('', v2 or 'zzzzzzzz') if context.Plugins['core'].Category == v2: return cmp(v1 or 'zzzzzzz', '') return cmp(v1 or 'zzzzzzzz', v2 or 'zzzzzzzz') def FirstItemSortCompare(sg1, sg2): return cmp(sg1[0], sg2[0]) def PluginSortCompare(p1, p2): return cmp(p1.ShortDesc, p2.ShortDesc) def SettingSortCompare(v1, v2): return cmp(v1.Plugin.Ranking[v1.Name], v2.Plugin.Ranking[v2.Name])
Python
import settings import simplejson import cjson import os import sys infoObject = settings.getInfoObject() def writeJSONToFile(): print "hello there" xml_file = os.path.abspath(__file__) xml_file = os.path.dirname(xml_file) xml_file = os.path.join(xml_file, "tester.json") testerXML = open(xml_file, 'w') simplejson.dump(infoObject, testerXML, indent=4) def getTheInfo(): return infoObject services = { 'wrtieToFile' : writeYAMLToFile, 'getInfo': getTheInfo } if __name__ == '__main__': from pyamf.remoting.wsgigateway import WSGIGateway from wsgiref import simple_server gw = WSGIGateway(services) httpd = simple_server.WSGIServer( ('localhost', 8000), simple_server.WSGIRequestHandler, ) httpd.set_app(gw) print "Running Hello World AMF gateway on http://localhost:8000" httpd.serve_forever() proc = os.popen("""ps axo "%p,%a" | grep "server.py" | grep -v grep|cut -d',' -f1""").read() print proc procs = proc.split('\n') if len(procs) > 2: print "server already started" import sys sys.exit(1) else: print "no server yet"
Python
import compizconfig context = compizconfig.Context() def getInfoObject(): InfoObject = [] for category in sorted(context.Categories, CatSortCompare): nextCateg = {} nextCateg["Name"] = category nextCateg["Plugins"] = [] InfoObject.append(nextCateg) for plugin in sorted(context.Categories[category], PluginSortCompare): nextPlugin = getPluginInfo(plugin) nextCateg["Plugins"].append(nextPlugin) return InfoObject def getPluginInfo(plugin): infoObject = {} infoObject["Name"] = plugin.Name infoObject["ShortDesc"] = plugin.ShortDesc infoObject["LongDesc"] = plugin.LongDesc infoObject["Enabled"] = plugin.Enabled infoObject["Features"] = plugin.Features infoObject["Ranking"] = plugin.Ranking infoObject["Groups"] = [] for name, group in sorted(plugin.Groups.items(), FirstItemSortCompare): nextGroup = {} if name == '': nextGroup["Name"] = "General" else: nextGroup["Name"] = name nextGroup["SubGroups"] = [] infoObject["Groups"].append(nextGroup) for subGroupName, subGroup in sorted(group.items(), FirstItemSortCompare): nextSubGroup = {} nextSubGroup["Name"] = subGroupName nextSubGroup["Settings"] = [] nextGroup["SubGroups"].append(nextSubGroup) theSettings = sum((v.values() for v in [subGroup.Display]+[subGroup.Screens[0]]), []) for setting in sorted(theSettings, SettingSortCompare): nextSetting = getSettingInfo(setting) nextSubGroup["Settings"].append(nextSetting) return infoObject def getSettingInfo(setting): infoObject = {} infoObject["Name"] = setting.Name infoObject["ShortDesc"] = setting.ShortDesc infoObject["LongDesc"] = setting.LongDesc infoObject["Type"] = setting.Type infoObject["Hints"] = setting.Hints if setting.Type == "List": theInfo = {} theInfo["ListType"] = setting.Info[0] theInfo["ListInfo"] = list(setting.Info[1]) infoObject["Info"] = theInfo else: infoObject["Info"] = list(setting.Info) infoObject["Value"] = setting.Value infoObject["Default"] = setting.DefaultValue return infoObject def CatSortCompare(v1, v2): if v1 == v2: return cmp(v1, v2) if context.Plugins['core'].Category == v1: return cmp('', v2 or 'zzzzzzzz') if context.Plugins['core'].Category == v2: return cmp(v1 or 'zzzzzzz', '') return cmp(v1 or 'zzzzzzzz', v2 or 'zzzzzzzz') def FirstItemSortCompare(sg1, sg2): return cmp(sg1[0], sg2[0]) def PluginSortCompare(p1, p2): return cmp(p1.ShortDesc, p2.ShortDesc) def SettingSortCompare(v1, v2): return cmp(v1.Plugin.Ranking[v1.Name], v2.Plugin.Ranking[v2.Name])
Python
import settings import cjson import simplejson import os import sys infoObject = settings.getInfoObject() def writeJSONToFile(): print "hello there" xml_file = os.path.abspath(__file__) xml_file = os.path.dirname(xml_file) xml_file = os.path.join(xml_file, "tester.yaml") testerXML = open(xml_file, 'w') simplejson.dump(infoObject, testerXML, indent=4) def getTheInfo(): return cjson.encode(infoObject) services = { 'wrtieToFile' : writeYAMLToFile, 'getInfo': getTheInfo } if __name__ == '__main__': from pyamf.remoting.wsgigateway import WSGIGateway from wsgiref import simple_server gw = WSGIGateway(services) httpd = simple_server.WSGIServer( ('localhost', 8000), simple_server.WSGIRequestHandler, ) httpd.set_app(gw) print "Running Hello World AMF gateway on http://localhost:8000" httpd.serve_forever() proc = os.popen("""ps axo "%p,%a" | grep "server.py" | grep -v grep|cut -d',' -f1""").read() print proc procs = proc.split('\n') if len(procs) > 2: print "server already started" import sys sys.exit(1) else: print "no server yet"
Python
#!/usr/bin/env python import compizconfig import os from xml.etree import cElementTree as ET from lxml import etree import sys context = compizconfig.Context() def CatSortCompare(v1, v2): if v1 == v2: return cmp(v1, v2) if context.Plugins['core'].Category == v1: return cmp('', v2 or 'zzzzzzzz') if context.Plugins['core'].Category == v2: return cmp(v1 or 'zzzzzzz', '') return cmp(v1 or 'zzzzzzzz', v2 or 'zzzzzzzz') def FirstItemSortCompare(sg1, sg2): return cmp(sg1[0], sg2[0]) def PluginSortCompare(p1, p2): return cmp(p1.ShortDesc, p2.ShortDesc) def SettingSortCompare(v1, v2): return cmp(v1.Plugin.Ranking[v1.Name], v2.Plugin.Ranking[v2.Name]) def fileExists(f): try: file = open(f) except IOError: exists = 0 else: exists = 1 return exists def indent(elem, level=0): i = "\n" + level*" " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " for e in elem: indent(e, level+1) if not e.tail or not e.tail.strip(): e.tail = i + " " if not e.tail or not e.tail.strip(): e.tail = i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i if len(sys.argv) > 1: src = sys.argv[1] else: src = sys.stdin root = ET.Element("Everything") def createXML(): for categ in list(sorted(context.Categories, CatSortCompare)): if categ is '': categ = 'Unknown' nextCateg = ET.Element("Category", name=categ) root.append(nextCateg) for plugin in context.Categories[categ]: nextPlugin = plugin.xmlInfo # nextPlugin.set("isEnabled", plugin.Enabled) # nextPlugin.set("hasIcon", fileExists('assets/icons/plugin-'+plugin.Name + '.png')) nextCateg.append(nextPlugin) groupsSorted = sorted(plugin.Groups.items(), FirstItemSortCompare) for name, group in groupsSorted: if name is '': name = 'General' subGroupsSorted = sorted(group.items(), FirstItemSortCompare) nextGroup = ET.Element("Group", name=name) nextPlugin.append(nextGroup) for subGroupName, subGroup in subGroupsSorted: nextSubGroup = ET.Element("SubGroup", name=subGroupName) nextGroup.append(nextSubGroup) theSettings = sum((v.values() for v in [subGroup.Display]+[subGroup.Screens[0]]), []) theSettings = sorted(theSettings, SettingSortCompare) for setting in theSettings: nextSetting = setting.xmlInfo nextSubGroup.append(nextSetting) def main(): xml_file = os.path.abspath(__file__) xml_file = os.path.dirname(xml_file) xml_file = os.path.join(xml_file, "tester.xml") testerXML = open(xml_file, 'w') createXML() tree = ET.ElementTree(root) indent(tree.getroot()) tree.write(xml_file, encoding="utf-8",) if __name__ == "__main__": main()
Python
#!/usr/bin/env python import compizconfig import os from xml.etree import cElementTree as ET from lxml import etree import sys context = compizconfig.Context() def CatSortCompare(v1, v2): if v1 == v2: return cmp(v1, v2) if context.Plugins['core'].Category == v1: return cmp('', v2 or 'zzzzzzzz') if context.Plugins['core'].Category == v2: return cmp(v1 or 'zzzzzzz', '') return cmp(v1 or 'zzzzzzzz', v2 or 'zzzzzzzz') def FirstItemSortCompare(sg1, sg2): return cmp(sg1[0], sg2[0]) def PluginSortCompare(p1, p2): return cmp(p1.ShortDesc, p2.ShortDesc) def SettingSortCompare(v1, v2): return cmp(v1.Plugin.Ranking[v1.Name], v2.Plugin.Ranking[v2.Name]) def fileExists(f): try: file = open(f) except IOError: exists = 0 else: exists = 1 return exists def indent(elem, level=0): i = "\n" + level*" " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " for e in elem: indent(e, level+1) if not e.tail or not e.tail.strip(): e.tail = i + " " if not e.tail or not e.tail.strip(): e.tail = i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i if len(sys.argv) > 1: src = sys.argv[1] else: src = sys.stdin root = ET.Element("Everything") def createXML(): for categ in list(sorted(context.Categories, CatSortCompare)): if categ is '': categ = 'Unknown' nextCateg = ET.Element("Category", name=categ) root.append(nextCateg) for plugin in context.Categories[categ]: nextPlugin = plugin.xmlInfo # nextPlugin.set("isEnabled", plugin.Enabled) # nextPlugin.set("hasIcon", fileExists('assets/icons/plugin-'+plugin.Name + '.png')) nextCateg.append(nextPlugin) groupsSorted = sorted(plugin.Groups.items(), FirstItemSortCompare) for name, group in groupsSorted: if name is '': name = 'General' subGroupsSorted = sorted(group.items(), FirstItemSortCompare) nextGroup = ET.Element("Group", name=name) nextPlugin.append(nextGroup) for subGroupName, subGroup in subGroupsSorted: nextSubGroup = ET.Element("SubGroup", name=subGroupName) nextGroup.append(nextSubGroup) theSettings = sum((v.values() for v in [subGroup.Display]+[subGroup.Screens[0]]), []) theSettings = sorted(theSettings, SettingSortCompare) for setting in theSettings: nextSetting = setting.xmlInfo nextSubGroup.append(nextSetting) def main(): xml_file = os.path.abspath(__file__) xml_file = os.path.dirname(xml_file) xml_file = os.path.join(xml_file, "tester.xml") testerXML = open(xml_file, 'w') createXML() tree = ET.ElementTree(root) indent(tree.getroot()) tree.write(xml_file, encoding="utf-8",) if __name__ == "__main__": main()
Python
#!/usr/bin/env python def aString(theParams): return theParams[0] + "___" + theParams[1] def anArray(): return ["hello", "there", "this", "is", "an", "array"] def anObject(): return [{"var1": "hello", "var2": "hi", "var3": "etc"}, {"var1": "aslkd", "var2": "asdf", "var3": "etcafgb"}] services = { 'aString': aString, 'anArray': anArray, 'anObject': anObject } if __name__ == '__main__': from pyamf.remoting.wsgigateway import WSGIGateway from wsgiref import simple_server gw = WSGIGateway(services) httpd = simple_server.WSGIServer( ('localhost', 8000), simple_server.WSGIRequestHandler, ) httpd.set_app(gw) print "Running Hello World AMF gateway on http://localhost:8000" httpd.serve_forever()
Python
#!/usr/bin/env python def aString(theParams): return theParams[0] + "___" + theParams[1] def anArray(): return ["hello", "there", "this", "is", "an", "array"] def anObject(): return [{"var1": "hello", "var2": "hi", "var3": "etc"}, {"var1": "aslkd", "var2": "asdf", "var3": "etcafgb"}] services = { 'aString': aString, 'anArray': anArray, 'anObject': anObject } if __name__ == '__main__': from pyamf.remoting.wsgigateway import WSGIGateway from wsgiref import simple_server gw = WSGIGateway(services) httpd = simple_server.WSGIServer( ('localhost', 8000), simple_server.WSGIRequestHandler, ) httpd.set_app(gw) print "Running Hello World AMF gateway on http://localhost:8000" httpd.serve_forever()
Python
import settings import simplejson import cjson import os import sys infoObject = settings.getInfoObject() def writeJSONToFile(): print "hello there" xml_file = os.path.abspath(__file__) xml_file = os.path.dirname(xml_file) xml_file = os.path.join(xml_file, "json/allSettings.txt") testerXML = open(xml_file, 'w') simplejson.dump(infoObject, testerXML, indent=4) if __name__ == '__main__': writeJSONToFile()
Python
#!/usr/bin/env python import compizconfig context = compizconfig.Context() def CatSortCompare(v1, v2): if v1 == v2: return cmp(v1, v2) if context.Plugins['core'].Category == v1: return cmp('', v2 or 'zzzzzzzz') if context.Plugins['core'].Category == v2: return cmp(v1 or 'zzzzzzz', '') return cmp(v1 or 'zzzzzzzz', v2 or 'zzzzzzzz') categories = list(sorted(context.Categories, CatSortCompare)) plugins = list(context.Plugins) categInfo = [] pluginInfo = [] categInfo.append(dict((k, v) for (v, k) in enumerate(categories))) categInfo[0]["allGroups"] = categories categInfo[0]["activePlugins"] = list(context.Plugins['core'].Display['active_plugins'].Value) for categ in sorted(context.Categories, CatSortCompare): allPlugins = {} thePlugins = [] for plugin in context.Categories[categ]: thePlugins.append({"ShortDesc" : plugin.ShortDesc, "Name" : plugin.Name, "LongDesc" : plugin.LongDesc, "isEnabled" : plugin.Enabled}) allPlugins["plugins"] = thePlugins allPlugins["allPlugins"] = list(p.ShortDesc for p in context.Categories[categ]) pluginInfo.append(allPlugins) def getPluginInfo(): return pluginInfo def getCategInfo(): return categInfo services = { 'getPluginInfo': getPluginInfo, 'getCategInfo': getCategInfo } if __name__ == '__main__': from pyamf.remoting.wsgigateway import WSGIGateway from wsgiref import simple_server gw = WSGIGateway(services) httpd = simple_server.WSGIServer( ('localhost', 8000), simple_server.WSGIRequestHandler, ) httpd.set_app(gw) print "Running Hello World AMF gateway on http://localhost:8000" httpd.serve_forever()
Python
#!/usr/bin/env python import compizconfig context = compizconfig.Context() def CatSortCompare(v1, v2): if v1 == v2: return cmp(v1, v2) if context.Plugins['core'].Category == v1: return cmp('', v2 or 'zzzzzzzz') if context.Plugins['core'].Category == v2: return cmp(v1 or 'zzzzzzz', '') return cmp(v1 or 'zzzzzzzz', v2 or 'zzzzzzzz') categories = list(sorted(context.Categories, CatSortCompare)) plugins = list(context.Plugins) categInfo = [] pluginInfo = [] categInfo.append(dict((k, v) for (v, k) in enumerate(categories))) categInfo[0]["allGroups"] = categories categInfo[0]["activePlugins"] = list(context.Plugins['core'].Display['active_plugins'].Value) for categ in sorted(context.Categories, CatSortCompare): allPlugins = {} thePlugins = [] for plugin in context.Categories[categ]: thePlugins.append({"ShortDesc" : plugin.ShortDesc, "Name" : plugin.Name, "LongDesc" : plugin.LongDesc, "isEnabled" : plugin.Enabled}) allPlugins["plugins"] = thePlugins allPlugins["allPlugins"] = list(p.ShortDesc for p in context.Categories[categ]) pluginInfo.append(allPlugins) def getPluginInfo(): return pluginInfo def getCategInfo(): return categInfo services = { 'getPluginInfo': getPluginInfo, 'getCategInfo': getCategInfo } if __name__ == '__main__': from pyamf.remoting.wsgigateway import WSGIGateway from wsgiref import simple_server gw = WSGIGateway(services) httpd = simple_server.WSGIServer( ('localhost', 8000), simple_server.WSGIRequestHandler, ) httpd.set_app(gw) print "Running Hello World AMF gateway on http://localhost:8000" httpd.serve_forever()
Python
import wsgiref.handlers from google.appengine.ext import webapp from google.appengine.ext.webapp import template import logging from urlparse import urlparse import os class flashbsm(webapp.RequestHandler): def get(self): swf = 'http://' + urlparse(self.request.url).netloc + '/swfs/settings.swf'; template_values = { 'type': 'Flex', 'title': 'flashbsm', 'description': '', 'swf': swf, 'width': '100%', 'height': '100%' } path = os.path.join(os.path.dirname(__file__), 'templates/flashbsm.html') self.response.out.write(template.render(path, template_values, debug=True)) class NotFoundHandler(webapp.RequestHandler): def get(self): # Not found template_vars = { 'title': 'Error 404 Kitten: I\'m sorry, I tried really hard to find it.', 'content': '<img src="/images/404kitten.jpg" width="375" height="500" alt="404 Kitten."/><p><a href="http://flickr.com/photos/mydnight296/2343975616/">Photo</a> by <a href="http://flickr.com/people/mydnight296/">Vannessa</a>.</p>' } path = os.path.join(os.path.dirname(__file__), 'templates/simple.html') self.response.out.write(template.render(path, template_vars, debug=True)) def main(): application = webapp.WSGIApplication([ ('/', flashbsm), ('/.*', NotFoundHandler) ], debug=True) wsgiref.handlers.CGIHandler().run(application) if __name__ == '__main__': main()
Python
import settings import simplejson import cjson import os import sys infoObject = settings.getInfoObject() def writeJSONToFile(): print "hello there" xml_file = os.path.abspath(__file__) xml_file = os.path.dirname(xml_file) xml_file = os.path.join(xml_file, "tester.json") testerXML = open(xml_file, 'w') simplejson.dump(infoObject, testerXML, indent=4) def getTheInfo(): updateContext() return infoObject def updateContext(): settings.updateContext() def changeSetting(params): return settings.changeSetting(params) def renewValue(params): return settings.renewValue(params) def changePluginStatus(params): return settings.changePluginStatus(params) services = { 'writeToFile' : writeJSONToFile, 'getInfo': getTheInfo, 'updateContext': updateContext, 'settingsChange': changeSetting, 'pluginStatus' : changePluginStatus, 'renewValue': renewValue } if __name__ == '__main__': from pyamf.remoting.wsgigateway import WSGIGateway from wsgiref import simple_server gw = WSGIGateway(services) httpd = simple_server.WSGIServer( ('localhost', 8001), simple_server.WSGIRequestHandler, ) httpd.set_app(gw) print "Running Hello World AMF gateway on http://localhost:8000" httpd.serve_forever() proc = os.popen("""ps axo "%p,%a" | grep "server.py" | grep -v grep|cut -d',' -f1""").read() print proc procs = proc.split('\n') if len(procs) > 2: print "server already started" import sys sys.exit(1) else: print "no server yet"
Python
import settings import simplejson import cjson import os import sys infoObject = settings.getInfoObject() def writeJSONToFile(): print "hello there" xml_file = os.path.abspath(__file__) xml_file = os.path.dirname(xml_file) xml_file = os.path.join(xml_file, "assets/json/allSettings.txt") testerXML = open(xml_file, 'w') simplejson.dump(infoObject, testerXML, indent=4) if __name__ == '__main__': writeJSONToFile()
Python
import compizconfig import time import os from threading import Thread context = compizconfig.Context() globalInfoObject = [] settingsHolder = [] pluginsHolder = [] changed = [] def getInfoObject(): for category in sorted(context.Categories, CatSortCompare): nextCateg = {} nextCateg["Name"] = category nextCateg["Plugins"] = [] globalInfoObject.append(nextCateg) for plugin in sorted(context.Categories[category], PluginSortCompare): nextPlugin = getPluginInfo(plugin) nextCateg["Plugins"].append(nextPlugin) return globalInfoObject def getPluginInfo(plugin): infoObject = {} infoObject["Name"] = plugin.Name infoObject["ShortDesc"] = plugin.ShortDesc infoObject["LongDesc"] = plugin.LongDesc infoObject["Enabled"] = plugin.Enabled infoObject["Features"] = plugin.Features infoObject["Ranking"] = plugin.Ranking infoObject["PluginNumber"] = len(pluginsHolder) pluginsHolder.append(plugin) infoObject["Groups"] = [] infoObject["HasIcon"] = os.path.exists('assets/icons/plugin-'+plugin.Name + '.png') for name, group in sorted(plugin.Groups.items(), FirstItemSortCompare): nextGroup = {} if name == '': nextGroup["Name"] = "General" else: nextGroup["Name"] = name nextGroup["SubGroups"] = [] infoObject["Groups"].append(nextGroup) for subGroupName, subGroup in sorted(group.items(), FirstItemSortCompare): nextSubGroup = {} nextSubGroup["Name"] = subGroupName nextSubGroup["Settings"] = [] nextGroup["SubGroups"].append(nextSubGroup) theSettings = sum((v.values() for v in [subGroup.Display]+[subGroup.Screens[0]]), []) for setting in sorted(theSettings, SettingSortCompare): nextSetting = getSettingInfo(setting) nextSubGroup["Settings"].append(nextSetting) return infoObject def getSettingInfo(setting): infoObject = {} infoObject["Name"] = setting.Name infoObject["ShortDesc"] = setting.ShortDesc infoObject["LongDesc"] = setting.LongDesc infoObject["Type"] = setting.Type infoObject["Hints"] = setting.Hints infoObject["SettingNumber"] = len(settingsHolder) settingsHolder.append(setting) #if setting.Type == "List": # theInfo = {} # theInfo["ListType"] = setting.Info[0] # theInfo["ListInfo"] = list(setting.Info[1]) # infoObject["Info"] = theInfo #else: # infoObject["Info"] = list(setting.Info) infoObject["Value"] = setting.Value infoObject["Default"] = setting.DefaultValue return infoObject def updateContext(): context.ProcessEvents() return True def changeSetting(params): updateContext() settingNum = params[0] Value = params[1] settingsHolder[settingNum].Value = Value context.Write() return (Value == settingsHolder[settingNum].Value) def renewValue(params): settingNum = params[0] return settingsHolder[settingNum].Value def changePluginStatus(params): updateContext() pluginNum = params[0] Enabled = params[1] pluginsHolder[pluginNum].Enabled = Enabled context.Write() return (Enabled == pluginsHolder[pluginNum].Enabled); def CatSortCompare(v1, v2): if v1 == v2: return cmp(v1, v2) if context.Plugins['core'].Category == v1: return cmp('', v2 or 'zzzzzzzz') if context.Plugins['core'].Category == v2: return cmp(v1 or 'zzzzzzz', '') return cmp(v1 or 'zzzzzzzz', v2 or 'zzzzzzzz') def FirstItemSortCompare(sg1, sg2): return cmp(sg1[0], sg2[0]) def PluginSortCompare(p1, p2): return cmp(p1.ShortDesc, p2.ShortDesc) def SettingSortCompare(v1, v2): return cmp(v1.Plugin.Ranking[v1.Name], v2.Plugin.Ranking[v2.Name])
Python
import settings import simplejson import cjson import os import sys infoObject = settings.getInfoObject() def writeJSONToFile(): print "hello there" xml_file = os.path.abspath(__file__) xml_file = os.path.dirname(xml_file) xml_file = os.path.join(xml_file, "tester.json") testerXML = open(xml_file, 'w') simplejson.dump(infoObject, testerXML, indent=4) def getTheInfo(): updateContext() return infoObject def updateContext(): settings.updateContext() def changeSetting(params): return settings.changeSetting(params) def renewValue(params): return settings.renewValue(params) def changePluginStatus(params): return settings.changePluginStatus(params) services = { 'writeToFile' : writeJSONToFile, 'getInfo': getTheInfo, 'updateContext': updateContext, 'settingsChange': changeSetting, 'pluginStatus' : changePluginStatus, 'renewValue': renewValue } if __name__ == '__main__': from pyamf.remoting.wsgigateway import WSGIGateway from wsgiref import simple_server gw = WSGIGateway(services) httpd = simple_server.WSGIServer( ('localhost', 8001), simple_server.WSGIRequestHandler, ) httpd.set_app(gw) print "Running Hello World AMF gateway on http://localhost:8000" httpd.serve_forever() proc = os.popen("""ps axo "%p,%a" | grep "server.py" | grep -v grep|cut -d',' -f1""").read() print proc procs = proc.split('\n') if len(procs) > 2: print "server already started" import sys sys.exit(1) else: print "no server yet"
Python
import settings import simplejson import cjson import os import sys infoObject = settings.getInfoObject() def writeJSONToFile(): print "hello there" xml_file = os.path.abspath(__file__) xml_file = os.path.dirname(xml_file) xml_file = os.path.join(xml_file, "assets/json/allSettings.txt") testerXML = open(xml_file, 'w') simplejson.dump(infoObject, testerXML, indent=4) if __name__ == '__main__': writeJSONToFile()
Python
import compizconfig import time import os from threading import Thread context = compizconfig.Context() globalInfoObject = [] settingsHolder = [] pluginsHolder = [] changed = [] def getInfoObject(): for category in sorted(context.Categories, CatSortCompare): nextCateg = {} nextCateg["Name"] = category nextCateg["Plugins"] = [] globalInfoObject.append(nextCateg) for plugin in sorted(context.Categories[category], PluginSortCompare): nextPlugin = getPluginInfo(plugin) nextCateg["Plugins"].append(nextPlugin) return globalInfoObject def getPluginInfo(plugin): infoObject = {} infoObject["Name"] = plugin.Name infoObject["ShortDesc"] = plugin.ShortDesc infoObject["LongDesc"] = plugin.LongDesc infoObject["Enabled"] = plugin.Enabled infoObject["Features"] = plugin.Features infoObject["Ranking"] = plugin.Ranking infoObject["PluginNumber"] = len(pluginsHolder) pluginsHolder.append(plugin) infoObject["Groups"] = [] infoObject["HasIcon"] = os.path.exists('assets/icons/plugin-'+plugin.Name + '.png') for name, group in sorted(plugin.Groups.items(), FirstItemSortCompare): nextGroup = {} if name == '': nextGroup["Name"] = "General" else: nextGroup["Name"] = name nextGroup["SubGroups"] = [] infoObject["Groups"].append(nextGroup) for subGroupName, subGroup in sorted(group.items(), FirstItemSortCompare): nextSubGroup = {} nextSubGroup["Name"] = subGroupName nextSubGroup["Settings"] = [] nextGroup["SubGroups"].append(nextSubGroup) theSettings = sum((v.values() for v in [subGroup.Display]+[subGroup.Screens[0]]), []) for setting in sorted(theSettings, SettingSortCompare): nextSetting = getSettingInfo(setting) nextSubGroup["Settings"].append(nextSetting) return infoObject def getSettingInfo(setting): infoObject = {} infoObject["Name"] = setting.Name infoObject["ShortDesc"] = setting.ShortDesc infoObject["LongDesc"] = setting.LongDesc infoObject["Type"] = setting.Type infoObject["Hints"] = setting.Hints infoObject["SettingNumber"] = len(settingsHolder) settingsHolder.append(setting) if setting.Type == "List": theInfo = {} theInfo["ListType"] = setting.Info[0] theInfo["ListInfo"] = list(setting.Info[1]) infoObject["Info"] = theInfo else: infoObject["Info"] = list(setting.Info) infoObject["Value"] = setting.Value infoObject["Default"] = setting.DefaultValue return infoObject def updateContext(): context.ProcessEvents() return True def changeSetting(params): updateContext() settingNum = params[0] Value = params[1] settingsHolder[settingNum].Value = Value context.Write() return (Value == settingsHolder[settingNum].Value) def renewValue(params): settingNum = params[0] return settingsHolder[settingNum].Value def changePluginStatus(params): updateContext() pluginNum = params[0] Enabled = params[1] pluginsHolder[pluginNum].Enabled = Enabled context.Write() return (Enabled == pluginsHolder[pluginNum].Enabled); def CatSortCompare(v1, v2): if v1 == v2: return cmp(v1, v2) if context.Plugins['core'].Category == v1: return cmp('', v2 or 'zzzzzzzz') if context.Plugins['core'].Category == v2: return cmp(v1 or 'zzzzzzz', '') return cmp(v1 or 'zzzzzzzz', v2 or 'zzzzzzzz') def FirstItemSortCompare(sg1, sg2): return cmp(sg1[0], sg2[0]) def PluginSortCompare(p1, p2): return cmp(p1.ShortDesc, p2.ShortDesc) def SettingSortCompare(v1, v2): return cmp(v1.Plugin.Ranking[v1.Name], v2.Plugin.Ranking[v2.Name])
Python
#!/usr/bin/env python # # Copyright 2006, 2007 Google Inc. All Rights Reserved. # Author: danderson@google.com (David Anderson) # # Script for uploading files to a Google Code project. # # This is intended to be both a useful script for people who want to # streamline project uploads and a reference implementation for # uploading files to Google Code projects. # # To upload a file to Google Code, you need to provide a path to the # file on your local machine, a small summary of what the file is, a # project name, and a valid account that is a member or owner of that # project. You can optionally provide a list of labels that apply to # the file. The file will be uploaded under the same name that it has # in your local filesystem (that is, the "basename" or last path # component). Run the script with '--help' to get the exact syntax # and available options. # # Note that the upload script requests that you enter your # googlecode.com password. This is NOT your Gmail account password! # This is the password you use on googlecode.com for committing to # Subversion and uploading files. You can find your password by going # to http://code.google.com/hosting/settings when logged in with your # Gmail account. If you have already committed to your project's # Subversion repository, the script will automatically retrieve your # credentials from there (unless disabled, see the output of '--help' # for details). # # If you are looking at this script as a reference for implementing # your own Google Code file uploader, then you should take a look at # the upload() function, which is the meat of the uploader. You # basically need to build a multipart/form-data POST request with the # right fields and send it to https://PROJECT.googlecode.com/files . # Authenticate the request using HTTP Basic authentication, as is # shown below. # # Licensed under the terms of the Apache Software License 2.0: # http://www.apache.org/licenses/LICENSE-2.0 # # Questions, comments, feature requests and patches are most welcome. # Please direct all of these to the Google Code users group: # http://groups.google.com/group/google-code-hosting """Google Code file uploader script. """ __author__ = 'danderson@google.com (David Anderson)' import httplib import os.path import optparse import getpass import base64 import sys def upload(file, project_name, user_name, password, summary, labels=None): """Upload a file to a Google Code project's file server. Args: file: The local path to the file. project_name: The name of your project on Google Code. user_name: Your Google account name. password: The googlecode.com password for your account. Note that this is NOT your global Google Account password! summary: A small description for the file. labels: an optional list of label strings with which to tag the file. Returns: a tuple: http_status: 201 if the upload succeeded, something else if an error occured. http_reason: The human-readable string associated with http_status file_url: If the upload succeeded, the URL of the file on Google Code, None otherwise. """ # The login is the user part of user@gmail.com. If the login provided # is in the full user@domain form, strip it down. if user_name.endswith('@gmail.com'): user_name = user_name[:user_name.index('@gmail.com')] form_fields = [('summary', summary)] if labels is not None: form_fields.extend([('label', l.strip()) for l in labels]) content_type, body = encode_upload_request(form_fields, file) upload_host = '%s.googlecode.com' % project_name upload_uri = '/files' auth_token = base64.b64encode('%s:%s'% (user_name, password)) headers = { 'Authorization': 'Basic %s' % auth_token, 'User-Agent': 'Googlecode.com uploader v0.9.4', 'Content-Type': content_type, } server = httplib.HTTPSConnection(upload_host) server.request('POST', upload_uri, body, headers) resp = server.getresponse() server.close() if resp.status == 201: location = resp.getheader('Location', None) else: location = None return resp.status, resp.reason, location def encode_upload_request(fields, file_path): """Encode the given fields and file into a multipart form body. fields is a sequence of (name, value) pairs. file is the path of the file to upload. The file will be uploaded to Google Code with the same file name. Returns: (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' CRLF = '\r\n' body = [] # Add the metadata about the upload first for key, value in fields: body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="%s"' % key, '', value, ]) # Now add the file itself file_name = os.path.basename(file_path) f = open(file_path, 'rb') file_content = f.read() f.close() body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="filename"; filename="%s"' % file_name, # The upload server determines the mime-type, no need to set it. 'Content-Type: application/octet-stream', '', file_content, ]) # Finalize the form body body.extend(['--' + BOUNDARY + '--', '']) return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) def upload_find_auth(file_path, project_name, summary, labels=None, user_name=None, password=None, tries=3): """Find credentials and upload a file to a Google Code project's file server. file_path, project_name, summary, and labels are passed as-is to upload. Args: file_path: The local path to the file. project_name: The name of your project on Google Code. summary: A small description for the file. labels: an optional list of label strings with which to tag the file. config_dir: Path to Subversion configuration directory, 'none', or None. user_name: Your Google account name. tries: How many attempts to make. """ while tries > 0: if user_name is None: # Read username if not specified or loaded from svn config, or on # subsequent tries. sys.stdout.write('Please enter your googlecode.com username: ') sys.stdout.flush() user_name = sys.stdin.readline().rstrip() if password is None: # Read password if not loaded from svn config, or on subsequent tries. print 'Please enter your googlecode.com password.' print '** Note that this is NOT your Gmail account password! **' print 'It is the password you use to access Subversion repositories,' print 'and can be found here: http://code.google.com/hosting/settings' password = getpass.getpass() status, reason, url = upload(file_path, project_name, user_name, password, summary, labels) # Returns 403 Forbidden instead of 401 Unauthorized for bad # credentials as of 2007-07-17. if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: # Rest for another try. user_name = password = None tries = tries - 1 else: # We're done. break return status, reason, url def main(): parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' '-p PROJECT [options] FILE') parser.add_option('-s', '--summary', dest='summary', help='Short description of the file') parser.add_option('-p', '--project', dest='project', help='Google Code project name') parser.add_option('-u', '--user', dest='user', help='Your Google Code username') parser.add_option('-w', '--password', dest='password', help='Your Google Code password') parser.add_option('-l', '--labels', dest='labels', help='An optional list of comma-separated labels to attach ' 'to the file') options, args = parser.parse_args() if not options.summary: parser.error('File summary is missing.') elif not options.project: parser.error('Project name is missing.') elif len(args) < 1: parser.error('File to upload not provided.') elif len(args) > 1: parser.error('Only one file may be specified.') file_path = args[0] if options.labels: labels = options.labels.split(',') else: labels = None status, reason, url = upload_find_auth(file_path, options.project, options.summary, labels, options.user, options.password) if url: print 'The file was uploaded successfully.' print 'URL: %s' % url return 0 else: print 'An error occurred. Your file was not uploaded.' print 'Google Code upload server said: %s (%s)' % (reason, status) return 1 if __name__ == '__main__': sys.exit(main())
Python
#!/bin/env python import os import re import sys ws = re.compile(r'-') f = open("list.txt") names = f.readlines() f.close() for name in names: name = name[0:-1] newname = "" for token in ws.split(name): newname += token[0].upper() newname += token[1:] cmd = "cp %s %s" % (name,newname) print cmd os.system(cmd)
Python
#!/usr/bin/env python # # Copyright 2006, 2007 Google Inc. All Rights Reserved. # Author: danderson@google.com (David Anderson) # # Script for uploading files to a Google Code project. # # This is intended to be both a useful script for people who want to # streamline project uploads and a reference implementation for # uploading files to Google Code projects. # # To upload a file to Google Code, you need to provide a path to the # file on your local machine, a small summary of what the file is, a # project name, and a valid account that is a member or owner of that # project. You can optionally provide a list of labels that apply to # the file. The file will be uploaded under the same name that it has # in your local filesystem (that is, the "basename" or last path # component). Run the script with '--help' to get the exact syntax # and available options. # # Note that the upload script requests that you enter your # googlecode.com password. This is NOT your Gmail account password! # This is the password you use on googlecode.com for committing to # Subversion and uploading files. You can find your password by going # to http://code.google.com/hosting/settings when logged in with your # Gmail account. If you have already committed to your project's # Subversion repository, the script will automatically retrieve your # credentials from there (unless disabled, see the output of '--help' # for details). # # If you are looking at this script as a reference for implementing # your own Google Code file uploader, then you should take a look at # the upload() function, which is the meat of the uploader. You # basically need to build a multipart/form-data POST request with the # right fields and send it to https://PROJECT.googlecode.com/files . # Authenticate the request using HTTP Basic authentication, as is # shown below. # # Licensed under the terms of the Apache Software License 2.0: # http://www.apache.org/licenses/LICENSE-2.0 # # Questions, comments, feature requests and patches are most welcome. # Please direct all of these to the Google Code users group: # http://groups.google.com/group/google-code-hosting """Google Code file uploader script. """ __author__ = 'danderson@google.com (David Anderson)' import httplib import os.path import optparse import getpass import base64 import sys def upload(file, project_name, user_name, password, summary, labels=None): """Upload a file to a Google Code project's file server. Args: file: The local path to the file. project_name: The name of your project on Google Code. user_name: Your Google account name. password: The googlecode.com password for your account. Note that this is NOT your global Google Account password! summary: A small description for the file. labels: an optional list of label strings with which to tag the file. Returns: a tuple: http_status: 201 if the upload succeeded, something else if an error occured. http_reason: The human-readable string associated with http_status file_url: If the upload succeeded, the URL of the file on Google Code, None otherwise. """ # The login is the user part of user@gmail.com. If the login provided # is in the full user@domain form, strip it down. if user_name.endswith('@gmail.com'): user_name = user_name[:user_name.index('@gmail.com')] form_fields = [('summary', summary)] if labels is not None: form_fields.extend([('label', l.strip()) for l in labels]) content_type, body = encode_upload_request(form_fields, file) upload_host = '%s.googlecode.com' % project_name upload_uri = '/files' auth_token = base64.b64encode('%s:%s'% (user_name, password)) headers = { 'Authorization': 'Basic %s' % auth_token, 'User-Agent': 'Googlecode.com uploader v0.9.4', 'Content-Type': content_type, } server = httplib.HTTPSConnection(upload_host) server.request('POST', upload_uri, body, headers) resp = server.getresponse() server.close() if resp.status == 201: location = resp.getheader('Location', None) else: location = None return resp.status, resp.reason, location def encode_upload_request(fields, file_path): """Encode the given fields and file into a multipart form body. fields is a sequence of (name, value) pairs. file is the path of the file to upload. The file will be uploaded to Google Code with the same file name. Returns: (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' CRLF = '\r\n' body = [] # Add the metadata about the upload first for key, value in fields: body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="%s"' % key, '', value, ]) # Now add the file itself file_name = os.path.basename(file_path) f = open(file_path, 'rb') file_content = f.read() f.close() body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="filename"; filename="%s"' % file_name, # The upload server determines the mime-type, no need to set it. 'Content-Type: application/octet-stream', '', file_content, ]) # Finalize the form body body.extend(['--' + BOUNDARY + '--', '']) return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) def upload_find_auth(file_path, project_name, summary, labels=None, user_name=None, password=None, tries=3): """Find credentials and upload a file to a Google Code project's file server. file_path, project_name, summary, and labels are passed as-is to upload. Args: file_path: The local path to the file. project_name: The name of your project on Google Code. summary: A small description for the file. labels: an optional list of label strings with which to tag the file. config_dir: Path to Subversion configuration directory, 'none', or None. user_name: Your Google account name. tries: How many attempts to make. """ while tries > 0: if user_name is None: # Read username if not specified or loaded from svn config, or on # subsequent tries. sys.stdout.write('Please enter your googlecode.com username: ') sys.stdout.flush() user_name = sys.stdin.readline().rstrip() if password is None: # Read password if not loaded from svn config, or on subsequent tries. print 'Please enter your googlecode.com password.' print '** Note that this is NOT your Gmail account password! **' print 'It is the password you use to access Subversion repositories,' print 'and can be found here: http://code.google.com/hosting/settings' password = getpass.getpass() status, reason, url = upload(file_path, project_name, user_name, password, summary, labels) # Returns 403 Forbidden instead of 401 Unauthorized for bad # credentials as of 2007-07-17. if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: # Rest for another try. user_name = password = None tries = tries - 1 else: # We're done. break return status, reason, url def main(): parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' '-p PROJECT [options] FILE') parser.add_option('-s', '--summary', dest='summary', help='Short description of the file') parser.add_option('-p', '--project', dest='project', help='Google Code project name') parser.add_option('-u', '--user', dest='user', help='Your Google Code username') parser.add_option('-w', '--password', dest='password', help='Your Google Code password') parser.add_option('-l', '--labels', dest='labels', help='An optional list of comma-separated labels to attach ' 'to the file') options, args = parser.parse_args() if not options.summary: parser.error('File summary is missing.') elif not options.project: parser.error('Project name is missing.') elif len(args) < 1: parser.error('File to upload not provided.') elif len(args) > 1: parser.error('Only one file may be specified.') file_path = args[0] if options.labels: labels = options.labels.split(',') else: labels = None status, reason, url = upload_find_auth(file_path, options.project, options.summary, labels, options.user, options.password) if url: print 'The file was uploaded successfully.' print 'URL: %s' % url return 0 else: print 'An error occurred. Your file was not uploaded.' print 'Google Code upload server said: %s (%s)' % (reason, status) return 1 if __name__ == '__main__': sys.exit(main())
Python
#!/bin/env python import os import re import sys ws = re.compile(r'-') f = open("list.txt") names = f.readlines() f.close() for name in names: name = name[0:-1] newname = "" for token in ws.split(name): newname += token[0].upper() newname += token[1:] cmd = "cp %s %s" % (name,newname) print cmd os.system(cmd)
Python
#!/usr/bin/env python # # Copyright 2006, 2007 Google Inc. All Rights Reserved. # Author: danderson@google.com (David Anderson) # # Script for uploading files to a Google Code project. # # This is intended to be both a useful script for people who want to # streamline project uploads and a reference implementation for # uploading files to Google Code projects. # # To upload a file to Google Code, you need to provide a path to the # file on your local machine, a small summary of what the file is, a # project name, and a valid account that is a member or owner of that # project. You can optionally provide a list of labels that apply to # the file. The file will be uploaded under the same name that it has # in your local filesystem (that is, the "basename" or last path # component). Run the script with '--help' to get the exact syntax # and available options. # # Note that the upload script requests that you enter your # googlecode.com password. This is NOT your Gmail account password! # This is the password you use on googlecode.com for committing to # Subversion and uploading files. You can find your password by going # to http://code.google.com/hosting/settings when logged in with your # Gmail account. If you have already committed to your project's # Subversion repository, the script will automatically retrieve your # credentials from there (unless disabled, see the output of '--help' # for details). # # If you are looking at this script as a reference for implementing # your own Google Code file uploader, then you should take a look at # the upload() function, which is the meat of the uploader. You # basically need to build a multipart/form-data POST request with the # right fields and send it to https://PROJECT.googlecode.com/files . # Authenticate the request using HTTP Basic authentication, as is # shown below. # # Licensed under the terms of the Apache Software License 2.0: # http://www.apache.org/licenses/LICENSE-2.0 # # Questions, comments, feature requests and patches are most welcome. # Please direct all of these to the Google Code users group: # http://groups.google.com/group/google-code-hosting """Google Code file uploader script. """ __author__ = 'danderson@google.com (David Anderson)' import httplib import os.path import optparse import getpass import base64 import sys def upload(file, project_name, user_name, password, summary, labels=None): """Upload a file to a Google Code project's file server. Args: file: The local path to the file. project_name: The name of your project on Google Code. user_name: Your Google account name. password: The googlecode.com password for your account. Note that this is NOT your global Google Account password! summary: A small description for the file. labels: an optional list of label strings with which to tag the file. Returns: a tuple: http_status: 201 if the upload succeeded, something else if an error occured. http_reason: The human-readable string associated with http_status file_url: If the upload succeeded, the URL of the file on Google Code, None otherwise. """ # The login is the user part of user@gmail.com. If the login provided # is in the full user@domain form, strip it down. if user_name.endswith('@gmail.com'): user_name = user_name[:user_name.index('@gmail.com')] form_fields = [('summary', summary)] if labels is not None: form_fields.extend([('label', l.strip()) for l in labels]) content_type, body = encode_upload_request(form_fields, file) upload_host = '%s.googlecode.com' % project_name upload_uri = '/files' auth_token = base64.b64encode('%s:%s'% (user_name, password)) headers = { 'Authorization': 'Basic %s' % auth_token, 'User-Agent': 'Googlecode.com uploader v0.9.4', 'Content-Type': content_type, } server = httplib.HTTPSConnection(upload_host) server.request('POST', upload_uri, body, headers) resp = server.getresponse() server.close() if resp.status == 201: location = resp.getheader('Location', None) else: location = None return resp.status, resp.reason, location def encode_upload_request(fields, file_path): """Encode the given fields and file into a multipart form body. fields is a sequence of (name, value) pairs. file is the path of the file to upload. The file will be uploaded to Google Code with the same file name. Returns: (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' CRLF = '\r\n' body = [] # Add the metadata about the upload first for key, value in fields: body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="%s"' % key, '', value, ]) # Now add the file itself file_name = os.path.basename(file_path) f = open(file_path, 'rb') file_content = f.read() f.close() body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="filename"; filename="%s"' % file_name, # The upload server determines the mime-type, no need to set it. 'Content-Type: application/octet-stream', '', file_content, ]) # Finalize the form body body.extend(['--' + BOUNDARY + '--', '']) return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) def upload_find_auth(file_path, project_name, summary, labels=None, user_name=None, password=None, tries=3): """Find credentials and upload a file to a Google Code project's file server. file_path, project_name, summary, and labels are passed as-is to upload. Args: file_path: The local path to the file. project_name: The name of your project on Google Code. summary: A small description for the file. labels: an optional list of label strings with which to tag the file. config_dir: Path to Subversion configuration directory, 'none', or None. user_name: Your Google account name. tries: How many attempts to make. """ while tries > 0: if user_name is None: # Read username if not specified or loaded from svn config, or on # subsequent tries. sys.stdout.write('Please enter your googlecode.com username: ') sys.stdout.flush() user_name = sys.stdin.readline().rstrip() if password is None: # Read password if not loaded from svn config, or on subsequent tries. print 'Please enter your googlecode.com password.' print '** Note that this is NOT your Gmail account password! **' print 'It is the password you use to access Subversion repositories,' print 'and can be found here: http://code.google.com/hosting/settings' password = getpass.getpass() status, reason, url = upload(file_path, project_name, user_name, password, summary, labels) # Returns 403 Forbidden instead of 401 Unauthorized for bad # credentials as of 2007-07-17. if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: # Rest for another try. user_name = password = None tries = tries - 1 else: # We're done. break return status, reason, url def main(): parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' '-p PROJECT [options] FILE') parser.add_option('-s', '--summary', dest='summary', help='Short description of the file') parser.add_option('-p', '--project', dest='project', help='Google Code project name') parser.add_option('-u', '--user', dest='user', help='Your Google Code username') parser.add_option('-w', '--password', dest='password', help='Your Google Code password') parser.add_option('-l', '--labels', dest='labels', help='An optional list of comma-separated labels to attach ' 'to the file') options, args = parser.parse_args() if not options.summary: parser.error('File summary is missing.') elif not options.project: parser.error('Project name is missing.') elif len(args) < 1: parser.error('File to upload not provided.') elif len(args) > 1: parser.error('Only one file may be specified.') file_path = args[0] if options.labels: labels = options.labels.split(',') else: labels = None status, reason, url = upload_find_auth(file_path, options.project, options.summary, labels, options.user, options.password) if url: print 'The file was uploaded successfully.' print 'URL: %s' % url return 0 else: print 'An error occurred. Your file was not uploaded.' print 'Google Code upload server said: %s (%s)' % (reason, status) return 1 if __name__ == '__main__': sys.exit(main())
Python
#!/bin/env python import os import re import sys ws = re.compile(r'-') f = open("list.txt") names = f.readlines() f.close() for name in names: name = name[0:-1] newname = "" for token in ws.split(name): newname += token[0].upper() newname += token[1:] cmd = "cp %s %s" % (name,newname) print cmd os.system(cmd)
Python
#!/usr/bin/env python # # Copyright 2006, 2007 Google Inc. All Rights Reserved. # Author: danderson@google.com (David Anderson) # # Script for uploading files to a Google Code project. # # This is intended to be both a useful script for people who want to # streamline project uploads and a reference implementation for # uploading files to Google Code projects. # # To upload a file to Google Code, you need to provide a path to the # file on your local machine, a small summary of what the file is, a # project name, and a valid account that is a member or owner of that # project. You can optionally provide a list of labels that apply to # the file. The file will be uploaded under the same name that it has # in your local filesystem (that is, the "basename" or last path # component). Run the script with '--help' to get the exact syntax # and available options. # # Note that the upload script requests that you enter your # googlecode.com password. This is NOT your Gmail account password! # This is the password you use on googlecode.com for committing to # Subversion and uploading files. You can find your password by going # to http://code.google.com/hosting/settings when logged in with your # Gmail account. If you have already committed to your project's # Subversion repository, the script will automatically retrieve your # credentials from there (unless disabled, see the output of '--help' # for details). # # If you are looking at this script as a reference for implementing # your own Google Code file uploader, then you should take a look at # the upload() function, which is the meat of the uploader. You # basically need to build a multipart/form-data POST request with the # right fields and send it to https://PROJECT.googlecode.com/files . # Authenticate the request using HTTP Basic authentication, as is # shown below. # # Licensed under the terms of the Apache Software License 2.0: # http://www.apache.org/licenses/LICENSE-2.0 # # Questions, comments, feature requests and patches are most welcome. # Please direct all of these to the Google Code users group: # http://groups.google.com/group/google-code-hosting """Google Code file uploader script. """ __author__ = 'danderson@google.com (David Anderson)' import httplib import os.path import optparse import getpass import base64 import sys def upload(file, project_name, user_name, password, summary, labels=None): """Upload a file to a Google Code project's file server. Args: file: The local path to the file. project_name: The name of your project on Google Code. user_name: Your Google account name. password: The googlecode.com password for your account. Note that this is NOT your global Google Account password! summary: A small description for the file. labels: an optional list of label strings with which to tag the file. Returns: a tuple: http_status: 201 if the upload succeeded, something else if an error occured. http_reason: The human-readable string associated with http_status file_url: If the upload succeeded, the URL of the file on Google Code, None otherwise. """ # The login is the user part of user@gmail.com. If the login provided # is in the full user@domain form, strip it down. if user_name.endswith('@gmail.com'): user_name = user_name[:user_name.index('@gmail.com')] form_fields = [('summary', summary)] if labels is not None: form_fields.extend([('label', l.strip()) for l in labels]) content_type, body = encode_upload_request(form_fields, file) upload_host = '%s.googlecode.com' % project_name upload_uri = '/files' auth_token = base64.b64encode('%s:%s'% (user_name, password)) headers = { 'Authorization': 'Basic %s' % auth_token, 'User-Agent': 'Googlecode.com uploader v0.9.4', 'Content-Type': content_type, } server = httplib.HTTPSConnection(upload_host) server.request('POST', upload_uri, body, headers) resp = server.getresponse() server.close() if resp.status == 201: location = resp.getheader('Location', None) else: location = None return resp.status, resp.reason, location def encode_upload_request(fields, file_path): """Encode the given fields and file into a multipart form body. fields is a sequence of (name, value) pairs. file is the path of the file to upload. The file will be uploaded to Google Code with the same file name. Returns: (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' CRLF = '\r\n' body = [] # Add the metadata about the upload first for key, value in fields: body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="%s"' % key, '', value, ]) # Now add the file itself file_name = os.path.basename(file_path) f = open(file_path, 'rb') file_content = f.read() f.close() body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="filename"; filename="%s"' % file_name, # The upload server determines the mime-type, no need to set it. 'Content-Type: application/octet-stream', '', file_content, ]) # Finalize the form body body.extend(['--' + BOUNDARY + '--', '']) return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) def upload_find_auth(file_path, project_name, summary, labels=None, user_name=None, password=None, tries=3): """Find credentials and upload a file to a Google Code project's file server. file_path, project_name, summary, and labels are passed as-is to upload. Args: file_path: The local path to the file. project_name: The name of your project on Google Code. summary: A small description for the file. labels: an optional list of label strings with which to tag the file. config_dir: Path to Subversion configuration directory, 'none', or None. user_name: Your Google account name. tries: How many attempts to make. """ while tries > 0: if user_name is None: # Read username if not specified or loaded from svn config, or on # subsequent tries. sys.stdout.write('Please enter your googlecode.com username: ') sys.stdout.flush() user_name = sys.stdin.readline().rstrip() if password is None: # Read password if not loaded from svn config, or on subsequent tries. print 'Please enter your googlecode.com password.' print '** Note that this is NOT your Gmail account password! **' print 'It is the password you use to access Subversion repositories,' print 'and can be found here: http://code.google.com/hosting/settings' password = getpass.getpass() status, reason, url = upload(file_path, project_name, user_name, password, summary, labels) # Returns 403 Forbidden instead of 401 Unauthorized for bad # credentials as of 2007-07-17. if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: # Rest for another try. user_name = password = None tries = tries - 1 else: # We're done. break return status, reason, url def main(): parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' '-p PROJECT [options] FILE') parser.add_option('-s', '--summary', dest='summary', help='Short description of the file') parser.add_option('-p', '--project', dest='project', help='Google Code project name') parser.add_option('-u', '--user', dest='user', help='Your Google Code username') parser.add_option('-w', '--password', dest='password', help='Your Google Code password') parser.add_option('-l', '--labels', dest='labels', help='An optional list of comma-separated labels to attach ' 'to the file') options, args = parser.parse_args() if not options.summary: parser.error('File summary is missing.') elif not options.project: parser.error('Project name is missing.') elif len(args) < 1: parser.error('File to upload not provided.') elif len(args) > 1: parser.error('Only one file may be specified.') file_path = args[0] if options.labels: labels = options.labels.split(',') else: labels = None status, reason, url = upload_find_auth(file_path, options.project, options.summary, labels, options.user, options.password) if url: print 'The file was uploaded successfully.' print 'URL: %s' % url return 0 else: print 'An error occurred. Your file was not uploaded.' print 'Google Code upload server said: %s (%s)' % (reason, status) return 1 if __name__ == '__main__': sys.exit(main())
Python
#!/bin/env python import os import re import sys ws = re.compile(r'-') f = open("list.txt") names = f.readlines() f.close() for name in names: name = name[0:-1] newname = "" for token in ws.split(name): newname += token[0].upper() newname += token[1:] cmd = "cp %s %s" % (name,newname) print cmd os.system(cmd)
Python
#!/usr/bin/env python # # Copyright 2006, 2007 Google Inc. All Rights Reserved. # Author: danderson@google.com (David Anderson) # # Script for uploading files to a Google Code project. # # This is intended to be both a useful script for people who want to # streamline project uploads and a reference implementation for # uploading files to Google Code projects. # # To upload a file to Google Code, you need to provide a path to the # file on your local machine, a small summary of what the file is, a # project name, and a valid account that is a member or owner of that # project. You can optionally provide a list of labels that apply to # the file. The file will be uploaded under the same name that it has # in your local filesystem (that is, the "basename" or last path # component). Run the script with '--help' to get the exact syntax # and available options. # # Note that the upload script requests that you enter your # googlecode.com password. This is NOT your Gmail account password! # This is the password you use on googlecode.com for committing to # Subversion and uploading files. You can find your password by going # to http://code.google.com/hosting/settings when logged in with your # Gmail account. If you have already committed to your project's # Subversion repository, the script will automatically retrieve your # credentials from there (unless disabled, see the output of '--help' # for details). # # If you are looking at this script as a reference for implementing # your own Google Code file uploader, then you should take a look at # the upload() function, which is the meat of the uploader. You # basically need to build a multipart/form-data POST request with the # right fields and send it to https://PROJECT.googlecode.com/files . # Authenticate the request using HTTP Basic authentication, as is # shown below. # # Licensed under the terms of the Apache Software License 2.0: # http://www.apache.org/licenses/LICENSE-2.0 # # Questions, comments, feature requests and patches are most welcome. # Please direct all of these to the Google Code users group: # http://groups.google.com/group/google-code-hosting """Google Code file uploader script. """ __author__ = 'danderson@google.com (David Anderson)' import httplib import os.path import optparse import getpass import base64 import sys def upload(file, project_name, user_name, password, summary, labels=None): """Upload a file to a Google Code project's file server. Args: file: The local path to the file. project_name: The name of your project on Google Code. user_name: Your Google account name. password: The googlecode.com password for your account. Note that this is NOT your global Google Account password! summary: A small description for the file. labels: an optional list of label strings with which to tag the file. Returns: a tuple: http_status: 201 if the upload succeeded, something else if an error occured. http_reason: The human-readable string associated with http_status file_url: If the upload succeeded, the URL of the file on Google Code, None otherwise. """ # The login is the user part of user@gmail.com. If the login provided # is in the full user@domain form, strip it down. if user_name.endswith('@gmail.com'): user_name = user_name[:user_name.index('@gmail.com')] form_fields = [('summary', summary)] if labels is not None: form_fields.extend([('label', l.strip()) for l in labels]) content_type, body = encode_upload_request(form_fields, file) upload_host = '%s.googlecode.com' % project_name upload_uri = '/files' auth_token = base64.b64encode('%s:%s'% (user_name, password)) headers = { 'Authorization': 'Basic %s' % auth_token, 'User-Agent': 'Googlecode.com uploader v0.9.4', 'Content-Type': content_type, } server = httplib.HTTPSConnection(upload_host) server.request('POST', upload_uri, body, headers) resp = server.getresponse() server.close() if resp.status == 201: location = resp.getheader('Location', None) else: location = None return resp.status, resp.reason, location def encode_upload_request(fields, file_path): """Encode the given fields and file into a multipart form body. fields is a sequence of (name, value) pairs. file is the path of the file to upload. The file will be uploaded to Google Code with the same file name. Returns: (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' CRLF = '\r\n' body = [] # Add the metadata about the upload first for key, value in fields: body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="%s"' % key, '', value, ]) # Now add the file itself file_name = os.path.basename(file_path) f = open(file_path, 'rb') file_content = f.read() f.close() body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="filename"; filename="%s"' % file_name, # The upload server determines the mime-type, no need to set it. 'Content-Type: application/octet-stream', '', file_content, ]) # Finalize the form body body.extend(['--' + BOUNDARY + '--', '']) return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) def upload_find_auth(file_path, project_name, summary, labels=None, user_name=None, password=None, tries=3): """Find credentials and upload a file to a Google Code project's file server. file_path, project_name, summary, and labels are passed as-is to upload. Args: file_path: The local path to the file. project_name: The name of your project on Google Code. summary: A small description for the file. labels: an optional list of label strings with which to tag the file. config_dir: Path to Subversion configuration directory, 'none', or None. user_name: Your Google account name. tries: How many attempts to make. """ while tries > 0: if user_name is None: # Read username if not specified or loaded from svn config, or on # subsequent tries. sys.stdout.write('Please enter your googlecode.com username: ') sys.stdout.flush() user_name = sys.stdin.readline().rstrip() if password is None: # Read password if not loaded from svn config, or on subsequent tries. print 'Please enter your googlecode.com password.' print '** Note that this is NOT your Gmail account password! **' print 'It is the password you use to access Subversion repositories,' print 'and can be found here: http://code.google.com/hosting/settings' password = getpass.getpass() status, reason, url = upload(file_path, project_name, user_name, password, summary, labels) # Returns 403 Forbidden instead of 401 Unauthorized for bad # credentials as of 2007-07-17. if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: # Rest for another try. user_name = password = None tries = tries - 1 else: # We're done. break return status, reason, url def main(): parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' '-p PROJECT [options] FILE') parser.add_option('-s', '--summary', dest='summary', help='Short description of the file') parser.add_option('-p', '--project', dest='project', help='Google Code project name') parser.add_option('-u', '--user', dest='user', help='Your Google Code username') parser.add_option('-w', '--password', dest='password', help='Your Google Code password') parser.add_option('-l', '--labels', dest='labels', help='An optional list of comma-separated labels to attach ' 'to the file') options, args = parser.parse_args() if not options.summary: parser.error('File summary is missing.') elif not options.project: parser.error('Project name is missing.') elif len(args) < 1: parser.error('File to upload not provided.') elif len(args) > 1: parser.error('Only one file may be specified.') file_path = args[0] if options.labels: labels = options.labels.split(',') else: labels = None status, reason, url = upload_find_auth(file_path, options.project, options.summary, labels, options.user, options.password) if url: print 'The file was uploaded successfully.' print 'URL: %s' % url return 0 else: print 'An error occurred. Your file was not uploaded.' print 'Google Code upload server said: %s (%s)' % (reason, status) return 1 if __name__ == '__main__': sys.exit(main())
Python
#!/bin/env python import os import re import sys ws = re.compile(r'-') f = open("list.txt") names = f.readlines() f.close() for name in names: name = name[0:-1] newname = "" for token in ws.split(name): newname += token[0].upper() newname += token[1:] cmd = "cp %s %s" % (name,newname) print cmd os.system(cmd)
Python
#!/usr/bin/env python # # Copyright 2006, 2007 Google Inc. All Rights Reserved. # Author: danderson@google.com (David Anderson) # # Script for uploading files to a Google Code project. # # This is intended to be both a useful script for people who want to # streamline project uploads and a reference implementation for # uploading files to Google Code projects. # # To upload a file to Google Code, you need to provide a path to the # file on your local machine, a small summary of what the file is, a # project name, and a valid account that is a member or owner of that # project. You can optionally provide a list of labels that apply to # the file. The file will be uploaded under the same name that it has # in your local filesystem (that is, the "basename" or last path # component). Run the script with '--help' to get the exact syntax # and available options. # # Note that the upload script requests that you enter your # googlecode.com password. This is NOT your Gmail account password! # This is the password you use on googlecode.com for committing to # Subversion and uploading files. You can find your password by going # to http://code.google.com/hosting/settings when logged in with your # Gmail account. If you have already committed to your project's # Subversion repository, the script will automatically retrieve your # credentials from there (unless disabled, see the output of '--help' # for details). # # If you are looking at this script as a reference for implementing # your own Google Code file uploader, then you should take a look at # the upload() function, which is the meat of the uploader. You # basically need to build a multipart/form-data POST request with the # right fields and send it to https://PROJECT.googlecode.com/files . # Authenticate the request using HTTP Basic authentication, as is # shown below. # # Licensed under the terms of the Apache Software License 2.0: # http://www.apache.org/licenses/LICENSE-2.0 # # Questions, comments, feature requests and patches are most welcome. # Please direct all of these to the Google Code users group: # http://groups.google.com/group/google-code-hosting """Google Code file uploader script. """ __author__ = 'danderson@google.com (David Anderson)' import httplib import os.path import optparse import getpass import base64 import sys def upload(file, project_name, user_name, password, summary, labels=None): """Upload a file to a Google Code project's file server. Args: file: The local path to the file. project_name: The name of your project on Google Code. user_name: Your Google account name. password: The googlecode.com password for your account. Note that this is NOT your global Google Account password! summary: A small description for the file. labels: an optional list of label strings with which to tag the file. Returns: a tuple: http_status: 201 if the upload succeeded, something else if an error occured. http_reason: The human-readable string associated with http_status file_url: If the upload succeeded, the URL of the file on Google Code, None otherwise. """ # The login is the user part of user@gmail.com. If the login provided # is in the full user@domain form, strip it down. if user_name.endswith('@gmail.com'): user_name = user_name[:user_name.index('@gmail.com')] form_fields = [('summary', summary)] if labels is not None: form_fields.extend([('label', l.strip()) for l in labels]) content_type, body = encode_upload_request(form_fields, file) upload_host = '%s.googlecode.com' % project_name upload_uri = '/files' auth_token = base64.b64encode('%s:%s'% (user_name, password)) headers = { 'Authorization': 'Basic %s' % auth_token, 'User-Agent': 'Googlecode.com uploader v0.9.4', 'Content-Type': content_type, } server = httplib.HTTPSConnection(upload_host) server.request('POST', upload_uri, body, headers) resp = server.getresponse() server.close() if resp.status == 201: location = resp.getheader('Location', None) else: location = None return resp.status, resp.reason, location def encode_upload_request(fields, file_path): """Encode the given fields and file into a multipart form body. fields is a sequence of (name, value) pairs. file is the path of the file to upload. The file will be uploaded to Google Code with the same file name. Returns: (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' CRLF = '\r\n' body = [] # Add the metadata about the upload first for key, value in fields: body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="%s"' % key, '', value, ]) # Now add the file itself file_name = os.path.basename(file_path) f = open(file_path, 'rb') file_content = f.read() f.close() body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="filename"; filename="%s"' % file_name, # The upload server determines the mime-type, no need to set it. 'Content-Type: application/octet-stream', '', file_content, ]) # Finalize the form body body.extend(['--' + BOUNDARY + '--', '']) return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) def upload_find_auth(file_path, project_name, summary, labels=None, user_name=None, password=None, tries=3): """Find credentials and upload a file to a Google Code project's file server. file_path, project_name, summary, and labels are passed as-is to upload. Args: file_path: The local path to the file. project_name: The name of your project on Google Code. summary: A small description for the file. labels: an optional list of label strings with which to tag the file. config_dir: Path to Subversion configuration directory, 'none', or None. user_name: Your Google account name. tries: How many attempts to make. """ while tries > 0: if user_name is None: # Read username if not specified or loaded from svn config, or on # subsequent tries. sys.stdout.write('Please enter your googlecode.com username: ') sys.stdout.flush() user_name = sys.stdin.readline().rstrip() if password is None: # Read password if not loaded from svn config, or on subsequent tries. print 'Please enter your googlecode.com password.' print '** Note that this is NOT your Gmail account password! **' print 'It is the password you use to access Subversion repositories,' print 'and can be found here: http://code.google.com/hosting/settings' password = getpass.getpass() status, reason, url = upload(file_path, project_name, user_name, password, summary, labels) # Returns 403 Forbidden instead of 401 Unauthorized for bad # credentials as of 2007-07-17. if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: # Rest for another try. user_name = password = None tries = tries - 1 else: # We're done. break return status, reason, url def main(): parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' '-p PROJECT [options] FILE') parser.add_option('-s', '--summary', dest='summary', help='Short description of the file') parser.add_option('-p', '--project', dest='project', help='Google Code project name') parser.add_option('-u', '--user', dest='user', help='Your Google Code username') parser.add_option('-w', '--password', dest='password', help='Your Google Code password') parser.add_option('-l', '--labels', dest='labels', help='An optional list of comma-separated labels to attach ' 'to the file') options, args = parser.parse_args() if not options.summary: parser.error('File summary is missing.') elif not options.project: parser.error('Project name is missing.') elif len(args) < 1: parser.error('File to upload not provided.') elif len(args) > 1: parser.error('Only one file may be specified.') file_path = args[0] if options.labels: labels = options.labels.split(',') else: labels = None status, reason, url = upload_find_auth(file_path, options.project, options.summary, labels, options.user, options.password) if url: print 'The file was uploaded successfully.' print 'URL: %s' % url return 0 else: print 'An error occurred. Your file was not uploaded.' print 'Google Code upload server said: %s (%s)' % (reason, status) return 1 if __name__ == '__main__': sys.exit(main())
Python
#!/bin/env python import os import re import sys ws = re.compile(r'-') f = open("list.txt") names = f.readlines() f.close() for name in names: name = name[0:-1] newname = "" for token in ws.split(name): newname += token[0].upper() newname += token[1:] cmd = "cp %s %s" % (name,newname) print cmd os.system(cmd)
Python
#!/usr/bin/env python # # Copyright 2006, 2007 Google Inc. All Rights Reserved. # Author: danderson@google.com (David Anderson) # # Script for uploading files to a Google Code project. # # This is intended to be both a useful script for people who want to # streamline project uploads and a reference implementation for # uploading files to Google Code projects. # # To upload a file to Google Code, you need to provide a path to the # file on your local machine, a small summary of what the file is, a # project name, and a valid account that is a member or owner of that # project. You can optionally provide a list of labels that apply to # the file. The file will be uploaded under the same name that it has # in your local filesystem (that is, the "basename" or last path # component). Run the script with '--help' to get the exact syntax # and available options. # # Note that the upload script requests that you enter your # googlecode.com password. This is NOT your Gmail account password! # This is the password you use on googlecode.com for committing to # Subversion and uploading files. You can find your password by going # to http://code.google.com/hosting/settings when logged in with your # Gmail account. If you have already committed to your project's # Subversion repository, the script will automatically retrieve your # credentials from there (unless disabled, see the output of '--help' # for details). # # If you are looking at this script as a reference for implementing # your own Google Code file uploader, then you should take a look at # the upload() function, which is the meat of the uploader. You # basically need to build a multipart/form-data POST request with the # right fields and send it to https://PROJECT.googlecode.com/files . # Authenticate the request using HTTP Basic authentication, as is # shown below. # # Licensed under the terms of the Apache Software License 2.0: # http://www.apache.org/licenses/LICENSE-2.0 # # Questions, comments, feature requests and patches are most welcome. # Please direct all of these to the Google Code users group: # http://groups.google.com/group/google-code-hosting """Google Code file uploader script. """ __author__ = 'danderson@google.com (David Anderson)' import httplib import os.path import optparse import getpass import base64 import sys def upload(file, project_name, user_name, password, summary, labels=None): """Upload a file to a Google Code project's file server. Args: file: The local path to the file. project_name: The name of your project on Google Code. user_name: Your Google account name. password: The googlecode.com password for your account. Note that this is NOT your global Google Account password! summary: A small description for the file. labels: an optional list of label strings with which to tag the file. Returns: a tuple: http_status: 201 if the upload succeeded, something else if an error occured. http_reason: The human-readable string associated with http_status file_url: If the upload succeeded, the URL of the file on Google Code, None otherwise. """ # The login is the user part of user@gmail.com. If the login provided # is in the full user@domain form, strip it down. if user_name.endswith('@gmail.com'): user_name = user_name[:user_name.index('@gmail.com')] form_fields = [('summary', summary)] if labels is not None: form_fields.extend([('label', l.strip()) for l in labels]) content_type, body = encode_upload_request(form_fields, file) upload_host = '%s.googlecode.com' % project_name upload_uri = '/files' auth_token = base64.b64encode('%s:%s'% (user_name, password)) headers = { 'Authorization': 'Basic %s' % auth_token, 'User-Agent': 'Googlecode.com uploader v0.9.4', 'Content-Type': content_type, } server = httplib.HTTPSConnection(upload_host) server.request('POST', upload_uri, body, headers) resp = server.getresponse() server.close() if resp.status == 201: location = resp.getheader('Location', None) else: location = None return resp.status, resp.reason, location def encode_upload_request(fields, file_path): """Encode the given fields and file into a multipart form body. fields is a sequence of (name, value) pairs. file is the path of the file to upload. The file will be uploaded to Google Code with the same file name. Returns: (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' CRLF = '\r\n' body = [] # Add the metadata about the upload first for key, value in fields: body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="%s"' % key, '', value, ]) # Now add the file itself file_name = os.path.basename(file_path) f = open(file_path, 'rb') file_content = f.read() f.close() body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="filename"; filename="%s"' % file_name, # The upload server determines the mime-type, no need to set it. 'Content-Type: application/octet-stream', '', file_content, ]) # Finalize the form body body.extend(['--' + BOUNDARY + '--', '']) return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) def upload_find_auth(file_path, project_name, summary, labels=None, user_name=None, password=None, tries=3): """Find credentials and upload a file to a Google Code project's file server. file_path, project_name, summary, and labels are passed as-is to upload. Args: file_path: The local path to the file. project_name: The name of your project on Google Code. summary: A small description for the file. labels: an optional list of label strings with which to tag the file. config_dir: Path to Subversion configuration directory, 'none', or None. user_name: Your Google account name. tries: How many attempts to make. """ while tries > 0: if user_name is None: # Read username if not specified or loaded from svn config, or on # subsequent tries. sys.stdout.write('Please enter your googlecode.com username: ') sys.stdout.flush() user_name = sys.stdin.readline().rstrip() if password is None: # Read password if not loaded from svn config, or on subsequent tries. print 'Please enter your googlecode.com password.' print '** Note that this is NOT your Gmail account password! **' print 'It is the password you use to access Subversion repositories,' print 'and can be found here: http://code.google.com/hosting/settings' password = getpass.getpass() status, reason, url = upload(file_path, project_name, user_name, password, summary, labels) # Returns 403 Forbidden instead of 401 Unauthorized for bad # credentials as of 2007-07-17. if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: # Rest for another try. user_name = password = None tries = tries - 1 else: # We're done. break return status, reason, url def main(): parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' '-p PROJECT [options] FILE') parser.add_option('-s', '--summary', dest='summary', help='Short description of the file') parser.add_option('-p', '--project', dest='project', help='Google Code project name') parser.add_option('-u', '--user', dest='user', help='Your Google Code username') parser.add_option('-w', '--password', dest='password', help='Your Google Code password') parser.add_option('-l', '--labels', dest='labels', help='An optional list of comma-separated labels to attach ' 'to the file') options, args = parser.parse_args() if not options.summary: parser.error('File summary is missing.') elif not options.project: parser.error('Project name is missing.') elif len(args) < 1: parser.error('File to upload not provided.') elif len(args) > 1: parser.error('Only one file may be specified.') file_path = args[0] if options.labels: labels = options.labels.split(',') else: labels = None status, reason, url = upload_find_auth(file_path, options.project, options.summary, labels, options.user, options.password) if url: print 'The file was uploaded successfully.' print 'URL: %s' % url return 0 else: print 'An error occurred. Your file was not uploaded.' print 'Google Code upload server said: %s (%s)' % (reason, status) return 1 if __name__ == '__main__': sys.exit(main())
Python