Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

« Newer Snippets
Older Snippets »
Showing 11-20 of 32 total

Python - simplePing

// Verifica se un Server e' su o giu'

import pycurl

def nullFunc(args):
	pass

try:

	curl = pycurl.Curl()
	curl.setopt(pycurl.WRITEFUNCTION, nullFunc)
	curl.setopt(pycurl.URL, 'http://www.google.it')
	curl.perform()

	print "Server SU"

except Exception, error:

	print "Server GIU'"

Python - My External IP Address

// My external ip address

import urllib

url = urllib.URLopener()
resp = url.open('http://myip.dk')
html = resp.read(114)

end = html.find("</title>")
start = html.find("IP:") + 3

print html[start:end].strip()

Python - Change user-agent

// Cambiare user-agent con urllib

import urllib

class AppURLopener(urllib.FancyURLopener):

	version = 'Nokia6630/1.0 (2.3.129) SymbianOS/8.0 Series60/2.6 Profile/MIDP-2.0 Configuration/CLDC-1.1'

urllib._urlopener = AppURLopener()


// Cambiare user-agent con urllib2

import urllib2

headers = { 'user-agent':'Nokia6630/1.0 (2.3.129) SymbianOS/8.0 Series60/2.6 Profile/MIDP-2.0 Configuration/CLDC-1.1',
		    'keep-alive':'300',
		    'content-type':'application/x-www-form-urlencoded'
		  }

Python - Query BabelFish

//Example di POST HTTP

#!/usr/bin/python

import urllib

def translate(lang='it_en', text='ciao'):
	
	'''Converte delle frasi da una lingua sorgente ad una lingua destinazione'''

	url = urllib.URLopener()
	
	query = urllib.urlencode({'doit':'done', 'intl':'1', 'lp':lang, 'tt':'urltext', 'urltext':text})
	
	responde = url.open('http://babelfish.altavista.com/tr', query).read()

	start = responde.find('<div style=padding:10px;>') + 25
	stop = responde.find('</div>', start)

	print responde[start:stop]

Python - Copy List

// Copiare una Lista

a = [1, 2, 3]
b = a[:]

Python - eggs

1)

import __hello__

2)

from __future__ import braces

Python - Mouse Capture

// Minimo Esempio di pannello con evento

import wx

class MyFrame(wx.Frame):
    
    def __init__(self):
        
        # creo un frame
        wx.Frame.__init__(self, None, -1, 'My Frame', size=(300, 300))
        # aggiungo un pannello
        panel = wx.Panel(self, -1)
        # aggiungo un evento al pannello
        panel.Bind(wx.EVT_MOTION, self.OnMove)
        # aggiungo un controllo di testo
        self.posCtrl = wx.TextCtrl(panel, -1, 'Pos: ', pos=(40, 10))
        
    def OnMove(self, event):
        
        # catturo la posizione del mouse
        pos = event.GetPosition()
        # scrivo tale posizione nel controllo di testo
        self.posCtrl.SetValue('%s, %s' % (pos.x, pos.y))
        
if '__main__' == __name__:
    
    app = wx.PySimpleApp()
    frame = MyFrame()
    frame.Show()
    app.MainLoop()

Python - randomLocal

// Create a sample directory localIMGs

import os
import random

class localImages(object):
    
    def __init__(self, directory='/home/Foto'):
        
        self.directoryScan = directory # Cartella da cui cominciare a prelevare le foto
        self.directoryRemain = [self.directoryScan]
        self.filePath = {}
    
    def getRandomImages(self):
        '''
        Prelieva dal proprio disco delle immagini in maniera random...
        '''
        
        for i in range(5): # Scansiona 5 directory
            if len(self.directoryRemain) > 0:
                directory = random.choice(self.directoryRemain)
                self.directoryRemain.remove(directory)
                
                files = []
                
                try:
                    files = os.listdir(directory)
                except:
                    pass
                
                # Serve per aumentare il Random delle Foto
                # FIXME: cercare di aumentare questo random
                if len(files) > 0:
                    for i in range(len(files)/2):
                        files_remove = random.choice(files)
                        files.remove(files_remove)
                ##########################################
                
                for filename in files:
                    filepath = os.path.join(directory, filename)
                
                    if os.path.isdir(filepath):
                        self.directoryRemain.append(filepath)
                    elif os.path.isfile(filepath):
                        (name, ext) = os.path.splitext(filepath)
                        if ext.lower() in ('.jpg', '.gif'):
                            self.filePath[filepath] = 0
                  
        if len(self.directoryRemain) == 0: self.directoryRemain = [self.directoryScan]
        
    def downloadImages(self):
        '''
        Scarica nella cartella localIMGs le foto che vengono trovate nel disco...
        '''
        
        numberIMGs = len(self.filePath)
        posIMGs = 1
        
        for imageName in self.filePath:
            print '[' + str(posIMGs) + '/' + str(numberIMGs) + '] - ' + imageName
            fread = open(imageName, 'rb')
            fwrite = open('localIMGs' + os.sep + os.path.split(imageName)[1], 'wb')
            fwrite.write(fread.read())
            fread.close()
            fwrite.close()
            posIMGs += 1
                              
if __name__ == '__main__':
    
    test = localImages()
    
    test.getRandomImages()
    test.downloadImages()
    
    print 'Finito...'

Python - randomYahoo

// Create a sample directory yahooIMGs

import os
import random
import re
import urllib
import urllib2

class yahooImages(object):
    
    RE_IMAGEURL = re.compile('&imgurl=(.+?)&', re.DOTALL | re.IGNORECASE)
    
    def __init__(self):
        
        self.imagesURLs = {}
    
    def getRandomImages(self, imageName=None):
        '''
        imageName = Nome dell'immagine da cercare, se non impostato viene generato un nome Random
        
        Scarica dal sito YahooImages delle immagini in maniera random...
        '''
        
        htmlPage = ''
        request = ''
        
        if imageName == None: imageName = self._randomWords()
        
        requestURL = 'http://it.search.yahoo.com/search/images?p=%s&b=%d' % (imageName, (random.randint(0, 50)*10))
        requestHeaders = {'User-Agent':'yahooImages/1.0'}
        
        try:
            request = urllib2.Request(requestURL, None, requestHeaders)
            htmlPage = urllib2.urlopen(request).read(500000)
        except:
            pass
        
        results = yahooImages.RE_IMAGEURL.findall(htmlPage)
        
        if len(results) > 0:
            for image in results:
                imageURL = urllib.unquote_plus(image)
                if not imageURL.startswith('http://'): imageURL = 'http://'+imageURL
                self.imagesURLs[imageURL] = 0
    
    def _randomWords(self):
        '''
        Viene generata una parola in maniera Random...
        '''
        
        words = ''
        charset = 'abcdefghijklmnopqrtuvwxyz'*2 + '0123456789'
        
        for i in range(random.randint(2, 7)): words += random.choice(charset)
                
        return words
    
    def downloadImages(self):
        '''
        Scarica nella cartella yahooIMGs le foto che vengono trovate in rete...
        '''
        
        numberIMGs = len(self.imagesURLs)
        posIMGs = 1
        
        for imageName in self.imagesURLs:
            print '[' + str(posIMGs) + '/' + str(numberIMGs) + '] - ' + imageName
            urllib.urlretrieve(imageName, 'yahooIMGs' + os.sep + os.path.split(imageName)[1])
            posIMGs += 1
        
if __name__ == '__main__':
    
    test = yahooImages()
    
    test.getRandomImages()
    test.downloadImages()
    
    print 'Finito...'

Python - randomGoogle

// Create a sample directory googleIMGs

import os
import random
import re
import urllib
import urllib2

class googleImages(object):
    
    RE_IMAGEURL = re.compile('imgurl=(http://.+?)&', re.DOTALL | re.IGNORECASE)
    
    def __init__(self):
        
        self.imagesURLs = {}
    
    def getRandomImages(self, imageName=None):
        '''
        imageName = Nome dell'immagine da cercare, se non impostato viene generato un nome Random
        
        Scarica dal sito GoogleImages delle immagini in maniera random...
        '''
        
        htmlPage = ''
        request = ''
        
        if imageName == None: imageName = self._randomWords()
        
        requestURL = 'http://images.google.it/images?q=%s&hl=it&start=%d' % (imageName, (random.randint(0, 50)*10))
        requestHeaders = {'User-Agent':'googleImages/1.0'}
        
        try:
            request = urllib2.Request(requestURL, None, requestHeaders)
            htmlPage = urllib2.urlopen(request).read(500000)
        except:
            pass
        
        results = googleImages.RE_IMAGEURL.findall(htmlPage)
        
        if len(results) > 0:
            for image in results:
                imageURL = urllib.unquote_plus(image)
                if not imageURL.startswith('http://'): imageURL = 'http://'+imageURL
                self.imagesURLs[imageURL] = 0
    
    def _randomWords(self):
        '''
        Viene generata una parola in maniera Random...
        '''
        
        words = ''
        charset = 'abcdefghijklmnopqrtuvwxyz'*2 + '0123456789'
        
        for i in range(random.randint(2, 7)): words += random.choice(charset)
                
        return words
    
    def downloadImages(self):
        '''
        Scarica nella cartella googleIMGs le foto che vengono trovate in rete...
        '''
        
        numberIMGs = len(self.imagesURLs)
        posIMGs = 1
        
        for imageName in self.imagesURLs:
            print '[' + str(posIMGs) + '/' + str(numberIMGs) + '] - ' + imageName
            urllib.urlretrieve(imageName, 'googleIMGs' + os.sep + os.path.split(imageName)[1])
            posIMGs += 1
    
if __name__ == '__main__':
    
    test = googleImages()
    
    test.getRandomImages()
    test.downloadImages()
    
    print 'Finito...'
« Newer Snippets
Older Snippets »
Showing 11-20 of 32 total