rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
replacements.append((templateR, ''))
replacements.append((templateRegex, ''))
def run(self): # regular expression to find the original template. # {{msg:vfd}} does the same thing as {{msg:Vfd}}, so both will be found. # The new syntax, {{vfd}}, will also be found. # The group 'parameters' will either match the parameters, or an # empty string if there are none. if not wikipedia.getSite().nocapit...
replacements.append((templateR, '{{subst:' + self.old + '\g<parameters>}}')) else: replacements.append((templateR, '{{' + self.new + '\g<parameters>}}'))
replacements.append((templateRegex, '{{subst:' + self.old + '\g<parameters>}}')) else: replacements.append((templateRegex, '{{' + self.new + '\g<parameters>}}'))
def run(self): # regular expression to find the original template. # {{msg:vfd}} does the same thing as {{msg:Vfd}}, so both will be found. # The new syntax, {{vfd}}, will also be found. # The group 'parameters' will either match the parameters, or an # empty string if there are none. if not wikipedia.getSite().nocapit...
gen = XmlTemplatePageGenerator(oldTemplate, xmlfilename)
gen = XmlDumpTemplatePageGenerator(oldTemplate, xmlfilename)
def main(): template_names = [] resolve = False remove = False # If xmlfilename is None, references will be loaded from the live wiki. xmlfilename = None new = None # read command line parameters for arg in sys.argv[1:]: arg = wikipedia.argHandler(arg, 'template') if arg: if arg == '-remove': remove = True elif arg.sta...
pass
print "NOTE: %s does not exist"% pl.asasciilink() except wikipedia.SubpageError: print "NOTE: %s subpage does not exist"% pl.asasciilink()
def workDone(self, counter): """This is called by a worker to tell us that the promised work was completed as far as possible. The only argument is an instance of a counter class, that has methods minus() and plus() to keep counts of the total work todo.""" # Loop over all the pages that should have been taken care of ...
if code == wikipedia.mylang and self.done[pl] is not None:
if code == wikipedia.mylang and pl.exists() and not pl.isRedirectPage():
def finish(self): """Round up the subject, making any necessary changes. This method should be called exactly once after the todo list has gone empty.""" if self.inpl.isRedirectPage(): return if not self.isDone(): raise "Bugcheck: finish called before done" print "======Post-processing %s======"%(self.inpl.asasciilink(...
self.add(self.generator.next())
pl=self.generator.next() while pl in globalvar.skip: pl=self.generator.next() self.add(pl)
def generateMore(self, number): """Generate more subjects. This is called internally when the list of subjects becomes to small, but only if there is a generator""" fs = self.firstSubject() if fs: print "NOTE: The first unfinished subject is:", fs.pl().asasciilink() print "NOTE: Number of pages queued is %d, trying to ...
except KeyboardInterrupt: print "Process was interrupted." print "The first unfinished subject is:",sa.firstSubject().pl().asasciilink()
except: sa.dump('interwiki.dump')
def compareLanguages(old, new): removing = [] adding = [] modifying = [] for code in old.keys(): if code not in new.keys(): removing.append(code) elif old[code] != new[code]: modifying.append(code) for code2 in new.keys(): if code2 not in old.keys(): adding.append(code2) s = "" if adding: s = s + " %s:" % (msg[msglang...
'_default': [u'Memory Alpha', self.namespaces[4]['_default']],
'_default': u'Memory Alpha',
def __init__(self): family.Family.__init__(self) self.name = 'memoryalpha' self.langs = { 'de': None, 'en': None, 'nl': None, 'sv': None, } # Most namespaces are inherited from family.Family. self.namespaces[4] = { '_default': [u'Memory Alpha', self.namespaces[4]['_default']], } self.namespaces[5] = { '_default': [u'...
'_default': [u'Memory Alpha talk', self.namespaces[5]['_default']],
'_default': u'Memory Alpha talk',
def __init__(self): family.Family.__init__(self) self.name = 'memoryalpha' self.langs = { 'de': None, 'en': None, 'nl': None, 'sv': None, } # Most namespaces are inherited from family.Family. self.namespaces[4] = { '_default': [u'Memory Alpha', self.namespaces[4]['_default']], } self.namespaces[5] = { '_default': [u'...
self.languages_by_size = ['en', 'de', 'nl', 'sv']
self.languages_by_size = ['en', 'de', 'es', 'nl', 'sv', 'fr', 'eo', 'pl'] alphabetic = ['de', 'en', 'es', 'eo', 'fr', 'nl', 'pl', 'sv']
def __init__(self): family.Family.__init__(self) self.name = 'memoryalpha' self.langs = { 'de': None, 'en': None, 'nl': None, 'sv': None, } # Most namespaces are inherited from family.Family. self.namespaces[4] = { '_default': [u'Memory Alpha', self.namespaces[4]['_default']], } self.namespaces[5] = { '_default': [u'...
def __init__(self, title, url):
def __init__(self, title, url, history):
def __init__(self, title, url): threading.Thread.__init__(self) self.title = title self.url = url
self.history = history
def __init__(self, title, url): threading.Thread.__init__(self) self.title = title self.url = url
if not ok:
if ok: self.history.linkAlive(self.url) pass else:
def run(self): linkChecker = LinkChecker(self.url) ok, message = linkChecker.check() if not ok: wikipedia.output('*[[%s]] links to %s - %s' % (self.title, self.url, message))
self.history.linkDead(self.url, message, self.title) class History: ''' Stores previously found dead links. The URLs are dict's keys, and values are lists of tuples where each tuple represents one time the URL was found dead. Tuples have the form (title, date, error) where title is the wiki page where the URL was foun...
def run(self): linkChecker = LinkChecker(self.url) ok, message = linkChecker.check() if not ok: wikipedia.output('*[[%s]] links to %s - %s' % (self.title, self.url, message))
self.history = History()
def __init__(self, generator, start ='!'): self.generator = generator self.start = start
for (title, text) in self.generator.generate(): self.checkLinksIn(title, text)
try: for (title, text) in self.generator.generate(): self.checkLinksIn(title, text) except: if threading.activeCount() > 1: wikipedia.output(u"Waiting for remaining %i threads to finish, please wait..." % threading.activeCount()) time.sleep(5) if threading.activeCount() > 1: wikipedia.output(u"Killing remaining %i thr...
def run(self): for (title, text) in self.generator.generate(): self.checkLinksIn(title, text)
while threading.activeCount() >= 10:
while threading.activeCount() >= 50:
def checkLinksIn(self, title, text): #wikipedia.output(title) linkR = re.compile(r'http://[^ \]\r\n]+') urls = linkR.findall(text) for url in urls: # Don't start more than 10 threads at once. Each thread will check # one page, then die. # TODO: Make number of threads a config variable. while threading.activeCount() >= ...
thread = LinkCheckThread(title, url)
thread = LinkCheckThread(title, url, self.history) thread.setDaemon(True)
def checkLinksIn(self, title, text): #wikipedia.output(title) linkR = re.compile(r'http://[^ \]\r\n]+') urls = linkR.findall(text) for url in urls: # Don't start more than 10 threads at once. Each thread will check # one page, then die. # TODO: Make number of threads a config variable. while threading.activeCount() >= ...
bot.run()
try: bot.run() finally: bot.history.save()
def main(): start = '!' sqlfilename = None for arg in sys.argv[1:]: arg = wikipedia.argHandler(arg, logname = 'weblinkchecker.log') if arg: if arg.startswith('-sql'): if len(arg) == 4: sqlfilename = wikipedia.input(u'Please enter the SQL dump\'s filename: ') else: sqlfilename = arg[5:] source = sqlfilename elif arg.sta...
print name
def getPage(code, name): """Get the contents of page 'name' from the 'code' language wikipedia""" host = langs[code] if host[-4:]=='.com': # Old algorithm name = re.sub('_', ' ', name) n=[] for x in name.split(): n.append(x.capitalize()) name='_'.join(n) print name else: name = re.sub(' ', '_', name) if not '%' in name...
sys.stdout.write(result)
sys.stdout.write(result.encode(config.console_encoding, 'replace'))
def printColorizedInUnix(self, text, colors): result = "" lastColor = None for i in range(0, len(colors)): if colors[i] != lastColor: # add an ANSI escape character result += unixColors[colors[i]] # append one text character result += text[i] lastColor = colors[i] if lastColor != None: # reset the color to default at t...
sys.stdout.write(text[i])
sys.stdout.write(text[i].encode(config.console_encoding, 'replace'))
def printColorizedInWindows(self, text, colors): """ This only works in Python 2.5 or higher. """ try: import ctypes std_out_handle = ctypes.windll.kernel32.GetStdHandle(-11) lastColor = None for i in range(0, len(colors)): if colors[i] != lastColor: #sys.stdout.flush() if colors[i] == None: ctypes.windll.kernel32.SetC...
sys.stdout.write(text)
sys.stdout.write(text.encode(config.console_encoding, 'replace'))
def printColorizedInWindows(self, text, colors): """ This only works in Python 2.5 or higher. """ try: import ctypes std_out_handle = ctypes.windll.kernel32.GetStdHandle(-11) lastColor = None for i in range(0, len(colors)): if colors[i] != lastColor: #sys.stdout.flush() if colors[i] == None: ctypes.windll.kernel32.SetC...
sys.stdout.write(text)
sys.stdout.write(text.encode(config.console_encoding, 'replace'))
def printColorized(self, text, colors): if colors and config.colorized_output: if sys.platform == 'win32': self.printColorizedInWindows(text, colors) else: self.printColorizedInUnix(text, colors) else: sys.stdout.write(text)
encodedText = text.encode(config.console_encoding, 'replace')
def output(self, text, colors = None, newline = True): """ If a character can't be displayed in the encoding used by the user's terminal, it will be replaced with a question mark or by a transliteration.
colors = colors or [None for char in encodedText] transliteratedTextList = []
codecedText = text.encode(config.console_encoding, 'replace').decode(config.console_encoding) colors = colors or [None for char in text] transliteratedText = ''
def output(self, text, colors = None, newline = True): """ If a character can't be displayed in the encoding used by the user's terminal, it will be replaced with a question mark or by a transliteration.
for i in xrange(len(encodedText)):
for i in xrange(len(codecedText)):
def output(self, text, colors = None, newline = True): """ If a character can't be displayed in the encoding used by the user's terminal, it will be replaced with a question mark or by a transliteration.
if encodedText[i] == '?' and text[i] != '?':
if codecedText[i] == '?' and text[i] != u'?':
def output(self, text, colors = None, newline = True): """ If a character can't be displayed in the encoding used by the user's terminal, it will be replaced with a question mark or by a transliteration.
transliteratedTextList += [char for char in transliterated]
transliteratedText += transliterated
def output(self, text, colors = None, newline = True): """ If a character can't be displayed in the encoding used by the user's terminal, it will be replaced with a question mark or by a transliteration.
transliteratedTextList.append('?')
transliteratedText += '?'
def output(self, text, colors = None, newline = True): """ If a character can't be displayed in the encoding used by the user's terminal, it will be replaced with a question mark or by a transliteration.
transliteratedTextList.append(encodedText[i]) encodedText = "".join(transliteratedTextList)
transliteratedText += codecedText[i] text = transliteratedText
def output(self, text, colors = None, newline = True): """ If a character can't be displayed in the encoding used by the user's terminal, it will be replaced with a question mark or by a transliteration.
encodedText += '\n'
text += u'\n'
def output(self, text, colors = None, newline = True): """ If a character can't be displayed in the encoding used by the user's terminal, it will be replaced with a question mark or by a transliteration.
self.printColorized(encodedText, colors)
self.printColorized(text, colors)
def output(self, text, colors = None, newline = True): """ If a character can't be displayed in the encoding used by the user's terminal, it will be replaced with a question mark or by a transliteration.
print "ERROR: ignoring link to obsolete language %s:%s"%( code, repr(t))
output(u"ERROR: ignoring link to obsolete language %s:%s" % (code, repr(t)))
def getLanguageLinks(text,incode=None): """Returns a dictionary of other language links mentioned in the text in the form {code:pagename}. Do not call this routine directly, use PageLink objects instead""" result = {} for code in family.langs: m=re.search(r'\[\['+code+':([^\]]*)\]\]', text) if m: if m.group(1): t=m.gro...
print "ERROR: ignoring impossible link to %s:%s"%(code,m.group(1))
output(u"ERROR: ignoring impossible link to %s:%s" % (code, m.group(1)))
def getLanguageLinks(text,incode=None): """Returns a dictionary of other language links mentioned in the text in the form {code:pagename}. Do not call this routine directly, use PageLink objects instead""" result = {} for code in family.langs: m=re.search(r'\[\['+code+':([^\]]*)\]\]', text) if m: if m.group(1): t=m.gro...
print dictionary
def get(key, lang = None): if lang == None: lang = wikipedia.mylang try: # find out how old our saved dump is (in seconds) file_age = time.time() - os.path.getmtime('mediawiki-messages/mediawiki-messages-%s.dat' % lang) # if it's older than 1 month, reload it if file_age > 30 * 24 * 60 * 60: print 'Current MediaWiki me...
'minnan' : lambda v: dh_noConv( v, u'%d nî' ),
def dh_knYearConverter( value ): if type(value) is int: # Encode an integer value into a textual form. return unicode(value).translate(_knDigitsToLocal) else: # First make sure there are no real digits in the string tmp = value.translate(_knDigitsToLocal) # Test if tmp == value: tmp = value.translate(_knLocalTo...
'nb' : dh_simpleInt,
def dh_knYearConverter( value ): if type(value) is int: # Encode an integer value into a textual form. return unicode(value).translate(_knDigitsToLocal) else: # First make sure there are no real digits in the string tmp = value.translate(_knDigitsToLocal) # Test if tmp == value: tmp = value.translate(_knLocalTo...
catlib.change_category(subcategory, self.cat.title(), None)
catlib.change_category(subcategory, self.cat, None)
def run(self): articles = self.cat.articles(recurse = 0) if len(articles) == 0: wikipedia.output(u'There are no articles in category %s' % self.cat.title()) else: for article in articles: catlib.change_category(article, self.cat, None) # Also removes the category tag from subcategories' pages subcategories = self.cat.s...
print interwiki_links
def replaceCategoryLinks(oldtext, new, code = None): """Replace the category links given in the wikitext given in oldtext by the new links given in new. 'new' should be a list of category pagelink objects. """ if code is None: code = mylang # first remove interwiki links and add them later, so that # interwiki tags ap...
wikipedia.setAction(editSummary)
wikipedia.setAction(self.editSummary)
def __init__(self, generator, old, new = None, remove = False, customSummary = False, editSummary = '', acceptAll = False): """ Arguments: * generator - A page generator. * old - The title of the old template (without namespace) * new - The title of the new template (without namespace), or None if you want ...
print status, reason
def fix_double_redirects(self): mysite = wikipedia.getSite() for redir_name in self.generator.retrieve_double_redirects(): print '' redir = wikipedia.Page(mysite, redir_name) try: target = redir.getRedirectTarget() except wikipedia.IsNotRedirectPage: wikipedia.output(u'%s is not a redirect.' % redir.title()) except wik...
'fr': 'Lien_AdQ',
'fr': 'lien AdQ',
def LINKS(site,name, ignore=[]): p=wikipedia.Page(site, name) links=p.linkedPages() for n in links[:]: if n.titleWithoutNamespace() in ignore: links.remove(n) links.sort() return links
pl = wikipedia.PageLink(mysite,title)
pl = wikipedia.PageLink(mysite,wikipedia.UnicodeToAsciiHtml(title)) print pl.linkname()
def findpage(t): try: location = re.search(starttext+"([^\Z]*?)"+endtext,t) if include: page = location.group() else: page = location.group(1) except AttributeError: return try: title = re.search("'''(.*?)'''",page).group(1) pl = wikipedia.PageLink(mysite,title) if pl.exists(): print "Page %s already exists, not adding...
if arg.startswith("-stop:"):
elif arg.startswith("-stop:"):
def findpage(t): try: location = re.search(starttext+"([^\Z]*?)"+endtext,t) if include: page = location.group() else: page = location.group(1) except AttributeError: return try: title = re.search("'''(.*?)'''",page).group(1) pl = wikipedia.PageLink(mysite,title) if pl.exists(): print "Page %s already exists, not adding...
if arg.startswith("-file:"):
elif arg.startswith("-file:"):
def findpage(t): try: location = re.search(starttext+"([^\Z]*?)"+endtext,t) if include: page = location.group() else: page = location.group(1) except AttributeError: return try: title = re.search("'''(.*?)'''",page).group(1) pl = wikipedia.PageLink(mysite,title) if pl.exists(): print "Page %s already exists, not adding...
if arg=="-include":
elif arg=="-include":
def findpage(t): try: location = re.search(starttext+"([^\Z]*?)"+endtext,t) if include: page = location.group() else: page = location.group(1) except AttributeError: return try: title = re.search("'''(.*?)'''",page).group(1) pl = wikipedia.PageLink(mysite,title) if pl.exists(): print "Page %s already exists, not adding...
try: addr = self.addr%special[self.code]
addr = self.addr%special[self.code]
def getData(self): import httplib try: addr = self.addr%special[self.code] pagenames = u'\r\n'.join([x.hashfreeLinkname() for x in self.pages]) pagenames = forCode(pagenames, self.code) data = urlencode(( ('action', 'submit'), ('pages', pagenames), ('curonly', 'True'), )) #print repr(data) headers = {"Content-type": "a...
continue i2 = re.search('</textarea>', text).start()
continue
def getEditPage(self, get_redirect=False, throttle = True, sysop = False): """ Get the contents of the Page via the edit page. Do not use this directly, use get() instead. Arguments: get_redirect - Get the contents, even if it is a redirect page This routine returns a unicode string containing the wiki text. """ isW...
print repr(fn)
def get_image(original_url, source_wiki, original_description, keep=False, debug=False): # work with a copy of argument variables so we can reuse the # original ones if the upload fails fn = original_url description = original_description # Get file contents uo = wikipedia.MyURLopener() file = uo.open(fn) contents = fi...
if not (dictName == 'yearsBC' and date.maxyearBC.has_key(pl.site().language()) and year > date.maxyearBC[pl.site().language()]) or (dictName == 'yearsAD' and date.maxyearAD.has_key(pl.site().language()) and year > date.maxyearAD[pl.site().language()]): wikipedia.output(u'TitleTranslate: %s was recognized as %s with val...
if not (dictName == 'yearsBC' and date.maxyearBC.has_key(pl.site().language()) and value > date.maxyearBC[pl.site().language()]) or (dictName == 'yearsAD' and date.maxyearAD.has_key(pl.site().language()) and value > date.maxyearAD[pl.site().language()]): wikipedia.output(u'TitleTranslate: %s was recognized as %s with v...
def translate(pl, arr, same = False, hints = None, auto = True): site = pl.site() if same: return sametranslate(pl, arr, same) if hints: for h in hints: if h.find(':') == -1: # argument given as -hint:xy where xy is a language code codes = h newname = '' else: codes, newname = h.split(':', 1) if newname == '': # if giv...
if dictName == 'yearsBC' and date.maxyearBC.has_key(entryLang) and year > date.maxyearBC[entryLang]:
if dictName == 'yearsBC' and date.maxyearBC.has_key(entryLang) and value > date.maxyearBC[entryLang]:
def translate(pl, arr, same = False, hints = None, auto = True): site = pl.site() if same: return sametranslate(pl, arr, same) if hints: for h in hints: if h.find(':') == -1: # argument given as -hint:xy where xy is a language code codes = h newname = '' else: codes, newname = h.split(':', 1) if newname == '': # if giv...
elif dictName == 'yearsAD' and date.maxyearAD.has_key(entryLang) and year > date.maxyearAD[entryLang]:
elif dictName == 'yearsAD' and date.maxyearAD.has_key(entryLang) and value > date.maxyearAD[entryLang]:
def translate(pl, arr, same = False, hints = None, auto = True): site = pl.site() if same: return sametranslate(pl, arr, same) if hints: for h in hints: if h.find(':') == -1: # argument given as -hint:xy where xy is a language code codes = h newname = '' else: codes, newname = h.split(':', 1) if newname == '': # if giv...
newname = entry(year)
newname = entry(value)
def translate(pl, arr, same = False, hints = None, auto = True): site = pl.site() if same: return sametranslate(pl, arr, same) if hints: for h in hints: if h.find(':') == -1: # argument given as -hint:xy where xy is a language code codes = h newname = '' else: codes, newname = h.split(':', 1) if newname == '': # if giv...
def appendFormatedDates( result, dictName, year ): for code, value in date.formats[dictName].iteritems(): result.append( u'[[%s:%s]]' % (code,value(year)) )
def appendFormatedDates( result, dictName, value ): for code, func in date.formats[dictName].iteritems(): result.append( u'[[%s:%s]]' % (code,func(value)) )
def appendFormatedDates( result, dictName, year ): for code, value in date.formats[dictName].iteritems(): result.append( u'[[%s:%s]]' % (code,value(year)) )
print "The filename on wikipedia will default to:",fn newfn = wikipedia.input(u'Better name : ', encode = wikipedia.myencoding())
print "The filename on wikipedia will default to:", fn newfn = wikipedia.input(u'Better name:') if newfn != '': fn = newfn
def get_image(original_url, source_wiki, original_description, keep=False, debug=False): # work with a copy of argument variables so we can reuse the # original ones if the upload fails fn = original_url description = original_description # Get file contents uo = wikipedia.MyURLopener() file = uo.open(fn) contents = fi...
fn = fn.encode(wikipedia.myencoding()) print repr(fn)
def get_image(original_url, source_wiki, original_description, keep=False, debug=False): # work with a copy of argument variables so we can reuse the # original ones if the upload fails fn = original_url description = original_description # Get file contents uo = wikipedia.MyURLopener() file = uo.open(fn) contents = fi...
start=link2url(start,code='nl',incode='nl')
start=link2url(start,code='nl')
def allnlpages(start='%20%200'): import sys start=link2url(start,code='nl',incode='nl') m=0 while 1: text=getPage('nl','Speciaal:Allpages&printable=yes&from=%s'%start,do_quote=0,do_edit=0) #print text R=re.compile('/wiki/(.*?)" *class=[\'\"]printable') n=0 for hit in R.findall(text): if not ':' in hit: if not hit in ['...
if code in ['meta','eo','ja','zh','hi','he','hu','ko']: return 'utf-8', elif code=='pl':
if code=='pl':
def code2encodings(code): if code in ['meta','eo','ja','zh','hi','he','hu','ko']: return 'utf-8', elif code=='pl': return 'utf-8','iso-8859-2' elif code=='ru': return 'utf-8','iso-8859-5' return 'iso-8859-1',
elif code=='ru':
if code=='ru':
def code2encodings(code): if code in ['meta','eo','ja','zh','hi','he','hu','ko']: return 'utf-8', elif code=='pl': return 'utf-8','iso-8859-2' elif code=='ru': return 'utf-8','iso-8859-5' return 'iso-8859-1',
return 'iso-8859-1',
return code2encoding(code),
def code2encodings(code): if code in ['meta','eo','ja','zh','hi','he','hu','ko']: return 'utf-8', elif code=='pl': return 'utf-8','iso-8859-2' elif code=='ru': return 'utf-8','iso-8859-5' return 'iso-8859-1',
def link2url(name,code,incode):
def link2url(name,code):
def link2url(name,code,incode): """Convert a interwiki link name of a page to the proper name to be used in a URL for that page. code should specify the language for the link, incode the language of the page the link is in.""" import urllib name=name[0].upper()+name[1:] name=name.strip() if '%' in name: name=url2unicod...
import urllib name=name[0].upper()+name[1:] name=name.strip()
def link2url(name,code,incode): """Convert a interwiki link name of a page to the proper name to be used in a URL for that page. code should specify the language for the link, incode the language of the page the link is in.""" import urllib name=name[0].upper()+name[1:] name=name.strip() if '%' in name: name=url2unicod...
import urllib name=html2unicode(name,language=code,inlanguage=incode)
name=html2unicode(name,language=code) name=name.strip() name=name[0].upper()+name[1:]
def link2url(name,code,incode): """Convert a interwiki link name of a page to the proper name to be used in a URL for that page. code should specify the language for the link, incode the language of the page the link is in.""" import urllib name=name[0].upper()+name[1:] name=name.strip() if '%' in name: name=url2unicod...
def aslink(self, forceInterwiki = False): """ A string representation in the form of a link. The link will be an interwiki link if needed. If you set forceInterwiki to True, the link will have the format of an interwiki link even if it points to the home wiki. Note that the family is never included. """ if self.sortK...
def aslink(self): """ A string representation in the form of a link. This method is different from Page.aslink() as the link will never have the form of an an interwiki link. """ if self.sortKey: titleWithSortKey = '%s|%s' % (self.title(), self.sortKey) else:
def aslink(self, forceInterwiki = False): """ A string representation in the form of a link. The link will be an interwiki link if needed.
if forceInterwiki or self.site() != wikipedia.getSite(): return '[[%s:%s]]' % (self.site().lang, titleWithSortKey) else: return '[[%s]]' % titleWithSortKey
return '[[%s]]' % titleWithSortKey
def aslink(self, forceInterwiki = False): """ A string representation in the form of a link. The link will be an interwiki link if needed.
except IOError: self.rebuild() else:
def __init__(self, rebuild = False, filename = 'category.dump'): if rebuild: self.rebuild() else: try: f = open(filename, 'r') except IOError: # Apparently the file category.dump does not exist self.rebuild() else: databases = pickle.load(f) f.close() # keys are categories, values are 2-tuples with lists as entries. se...
wikipedia.get_throttle.setDelay(5)
wikipedia.get_throttle.setDelay(1)
def __init__(self, catTitle, catDB): self.catTitle = catTitle self.catDB = catDB
catDB = CategoryDatabase()
def run(self): """ Prints the multi-line string generated by treeview or saves it to a file. Parameters: * catTitle - the title of the category which will be the tree's root * maxDepth - the limit beyond which no subcategories will be listed """ cat = catlib.CatLink(wikipedia.getSite(), self.catTitle) tree = self.tree...
cat_title = wikipedia.input(u'Which category do you want to tidy up?') tidy_category(catTitle)
catTitle = wikipedia.input(u'Which category do you want to tidy up?')
def run(self): """ Prints the multi-line string generated by treeview or saves it to a file. Parameters: * catTitle - the title of the category which will be the tree's root * maxDepth - the limit beyond which no subcategories will be listed """ cat = catlib.CatLink(wikipedia.getSite(), self.catTitle) tree = self.tree...
return "[[user:%s" % username.lower() in text.lower()
return "[[user:%s" % self.username.lower() in text.lower()
def botAllowed(self): """ Checks whether the bot is listed on Wikipedia:Bots to comply with the policy on the English Wikipedia. """ if self.site == wikipedia.getSite('en', 'wikipedia'): pl = wikipedia.Page(self.site, "Wikipedia:Bots") text = pl.get() return "[[user:%s" % username.lower() in text.lower() else: # No bot...
wikipedia.output(u'Your username is not listed on [[Wikipedia:Bots]]. Please make sure you are allowed to use the robot before actually using it!')
wikipedia.output(u'*** Your username is not listed on [[Wikipedia:Bots]].\n*** Please make sure you are allowed to use the robot before actually using it!')
def login(self): if not self.password: # As we don't want the password to appear on the screen, we use getpass(). self.password = getpass.getpass('Password for user %s on %s: ' % (self.username, self.site)) # Convert the password from the encoding your shell uses to the one your wiki # uses, via Unicode. This is the sa...
cnt = cnt + 9
cnt = cnt + 11
def generateOpcode(f, opNum, opName_): print >> f, ' // 0x%02X: %s' % (opNum, opName_) cnt = 0 opName = opName_[:3].lower() if opName_.__len__() > 3: operand = opName_[4:].lower() else: operand = '' if operand == '#nn': print >> f, ' CPU_OP_RD_TMP,' if opName == 'nop': pass elif opName[:2] != 'ld': print >> f, ' ...
print >> f, ' CPU_OP_LD_MEM_TMP,'
print >> f, ' CPU_OP_LD_MEM_TMP_NODEBUG,'
def generateOpcode(f, opNum, opName_): print >> f, ' // 0x%02X: %s' % (opNum, opName_) cnt = 0 opName = opName_[:3].lower() if opName_.__len__() > 3: operand = opName_[4:].lower() else: operand = '' writeInstructions = ['inc', 'dec', 'asl', 'lsr', 'rol', 'ror', 'rla', 'rra', 'slo', 'sre', 'sta'] if operand == '#nn':...
print >> f, ' CPU_OP_RD_TMP,'
print >> f, ' CPU_OP_RD_TMP_NODEBUG,'
def generateOpcode(f, opNum, opName_): print >> f, ' // 0x%02X: %s' % (opNum, opName_) cnt = 0 opName = opName_[:3].lower() if opName_.__len__() > 3: operand = opName_[4:].lower() else: operand = '' writeInstructions = ['inc', 'dec', 'asl', 'lsr', 'rol', 'ror', 'rla', 'rra', 'slo', 'sre', 'sta'] if operand == '#nn':...
print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_LD_MEM_TMP,' print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_RESET,' print >> f, ' CPU_OP_PUSH_TMP,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print...
cnt = cnt + 1
def generateOpcode(f, opNum, opName_): print >> f, ' // 0x%02X: %s' % (opNum, opName_) cnt = 0 opName = opName_[:3].lower() if opName_.__len__() > 3: operand = opName_[4:].lower() else: operand = '' writeInstructions = ['inc', 'dec', 'asl', 'lsr', 'rol', 'ror', 'rla', 'rra', 'slo', 'sre', 'sta'] if operand == '#nn':...
generateOpcode(f, 0xF2, '???')
generateOpcode(f, 0xF2, 'SYS')
def generateOpcode(f, opNum, opName_): print >> f, ' // 0x%02X: %s' % (opNum, opName_) cnt = 0 opName = opName_[:3].lower() if opName_.__len__() > 3: operand = opName_[4:].lower() else: operand = '' writeInstructions = ['inc', 'dec', 'asl', 'lsr', 'rol', 'ror', 'rla', 'rra', 'slo', 'sre', 'sta'] if operand == '#nn':...
progress (_ ("Assembling raw font to `%s'... ") % outname) system ('t1asm --pfa mftrace.t1asm %s' % outname + '.raw')
rawname = outname + '.raw' progress (_ ("Assembling raw font to `%s'... ") % rawname) system ('t1asm --pfa mftrace.t1asm %s' % rawname)
/.notdef { 0 0 hsbw endchar } |-
generate_cmds += 'Generate("%s");' % (filename + '.' + f)
generate_cmds += 'Generate("%s");' % (fontname + '.' + f)
def make_outputs (fontname, formats): """ run pfaedit to convert to other formats """ ff_command = get_fontforge_command () if not ff_command: shutil.copy2 (fontname + '.pfa.raw', fontname + '.pfa') return 0 # not used? if round_to_int : round_cmd = 'RoundToInt();\n' generate_cmds = '' for f in formats: generate_cmd...
(filename + '.pfa.raw'), tfmfile))
(fontname+ '.pfa.raw'), tfmfile))
def make_outputs (fontname, formats): """ run pfaedit to convert to other formats """ ff_command = get_fontforge_command () if not ff_command: shutil.copy2 (fontname + '.pfa.raw', fontname + '.pfa') return 0 # not used? if round_to_int : round_cmd = 'RoundToInt();\n' generate_cmds = '' for f in formats: generate_cmd...
('', '', 'keep-all', _ ("Really keep all output (implies --keep)")),
def strip_extension (f, ext): (p, e) = os.path.splitext (f) if e == ext: e = '' return p + e
command = "gf2pbm -n %d -o %s %s" % (char_number, outname, filename)
command = "%s/gf2pbm -n %d -o %s %s" % (exec_prefix, char_number, outname, filename)
def make_pbm (filename, outname, char_number): """ Extract bitmap from the PK file FILENAME (absolute) using `gf2pbm'. Return FALSE if the glyph is not valid. """ command = "gf2pbm -n %d -o %s %s" % (char_number, outname, filename) status = system (command, ignore_error = 1) return (status == 0)
str = popen ('gf2pbm -n %d -s %s' % (c, name)).read ()
str = popen ('%s/gf2pbm -n %d -s %s' % (exec_prefix, c, name)).read ()
def read_gf_dims (name, c): str = popen ('gf2pbm -n %d -s %s' % (c, name)).read () m = re.search ('size: ([0-9]+)+x([0-9]+), offset: \(([0-9-]+),([0-9-]+)\)', str) return tuple (map (string.atoi, m.groups ()))
def trace_font (fontname, gf_file, metric, glyphs, encoding, magnification):
def trace_font (fontname, gf_file, metric, glyphs, encoding, magnification, fontinfo):
def trace_font (fontname, gf_file, metric, glyphs, encoding, magnification): t1os = [] font_bbox = (10000, 10000, -10000, -10000) progress (_ ("Tracing bitmaps... ")) eps_lines = [] # for single glyph testing. # glyphs = [] for a in glyphs: valid = metric.has_char (a) if not valid: continue valid = make_pbm (gf_fil...
to_type1 (t1os, font_bbox, fontname, encoding, magnification)
to_type1 (t1os, font_bbox, fontname, encoding, magnification, fontinfo )
def trace_font (fontname, gf_file, metric, glyphs, encoding, magnification): t1os = [] font_bbox = (10000, 10000, -10000, -10000) progress (_ ("Tracing bitmaps... ")) eps_lines = [] # for single glyph testing. # glyphs = [] for a in glyphs: valid = metric.has_char (a) if not valid: continue valid = make_pbm (gf_fil...
def to_type1 (outlines, bbox, fontname, encoding, magnification):
def to_type1 (outlines, bbox, fontname, encoding, magnification, fontinfo):
def to_type1 (outlines, bbox, fontname, encoding, magnification): """ Fill in the header template for the font, append charstrings, and shove result through t1asm """ template = r"""%%!PS-AdobeFont-1.0: %(FontName)s %(VVV)s.%(WWW)s
'FontName': '%s' % fontinfo['FontName'],
/.notdef { 0 0 hsbw endchar } |-
'FullName': fontinfo['FullName'], 'FamilyName': fontinfo['FamilyName'], 'Weight': fontinfo['Weight'], 'ItalicAngle': fontinfo['ItalicAngle'], 'isFixedPitch': 'false',
/.notdef { 0 0 hsbw endchar } |-
fontinfo = {} def cm_guess_font_info (filename): """this function fills in sensible values for fontinfo. This should be tailored for each metafont font set. """ fontinfo = {"FontName": filename}
def derive_font_name (family, fullname): fullname = re.sub (family, '', fullname) fullname = re.sub ('Oldstyle Figures', 'OsF', fullname) fullname = re.sub ('Small Caps', 'SC', fullname) fullname = re.sub ('[Mm]edium', '', fullname) fullname = re.sub ('[^A-Za-z0-9]', '', fullname) return '%s-%s' % (family, fullname) d...
def abs_path (path, dir): # Python's ABSPATH means ABSDIR dir = os.path.abspath (dir) return string.join (map (lambda x: abs_dir (x, dir), string.split (path, os.pathsep)), os.pathsep)
design_size = m.group (1) prefixes = [("cmtt", "Computer Modern Typewriter Text"), ("cmvtt", "Computer Modern Variable Width Typewriter Text"), ("cmss", "Computer Modern Sans Serif"), ("cm", "Computer Modern")]
design_size = string.atoi (m.group (1)) fontinfo['DesignSize'] = design_size prefixes = [("cmtt", "CMTypewriter"), ("cmvtt", "CMVariableWidthTypewriter"), ("cmss", "CMSans"), ("cm", "CM")]
def cm_guess_font_info (filename): """this function fills in sensible values for fontinfo.
("csc", "Small caps"),
("csc", "Small Caps"),
def cm_guess_font_info (filename): """this function fills in sensible values for fontinfo.
prefixes = [("bx", "Bold Extended"), ("b", "Bold"), ("dc", "Demi Bold Condensed"),
prefixes = [("b", "Bold"),
def cm_guess_font_info (filename): """this function fills in sensible values for fontinfo.
weight = 'medium'
weight = 'Regular'
def cm_guess_font_info (filename): """this function fills in sensible values for fontinfo.
fontinfo['FullName'] = '%s %s %s designed at %spt' \ % (family, shape, weight, design_size)
full = '%s %s %s %s %dpt' \ % (family, shape, weight, stretch, design_size) full = re.sub (" +", ' ', full) fontinfo['FullName'] = full fontinfo['FontName'] = derive_font_name (family, full) return fontinfo def ec_guess_font_info (filename, fontinfo): design_size = 12 m = re.search ("([0-9]+)$", filename) if m: des...
def cm_guess_font_info (filename): """this function fills in sensible values for fontinfo.
'Weight': 'regular',
'Weight': 'Regular',
def guess_fontinfo (filename): fi = { 'FontName': filename, 'FamilyName': filename, 'Weight': 'regular', 'ItalicAngle': 0, 'FullName': filename, } if re.search ('^cm', filename): fi.update (cm_guess_font_info (filename)) return fi if read_afm_p: global afmfile if not afmfile: afmfile = find_file (filename + '.afm') ...
fi.update (cm_guess_font_info (filename)) return fi if read_afm_p:
fi.update (cm_guess_font_info (filename, fi)) elif re.search ("^ec", filename): fi.update (ec_guess_font_info (filename, fi)) elif read_afm_p:
def guess_fontinfo (filename): fi = { 'FontName': filename, 'FamilyName': filename, 'Weight': 'regular', 'ItalicAngle': 0, 'FullName': filename, } if re.search ('^cm', filename): fi.update (cm_guess_font_info (filename)) return fi if read_afm_p: global afmfile if not afmfile: afmfile = find_file (filename + '.afm') ...
magnification)
magnification, fontinfo)
def guess_fontinfo (filename): fi = { 'FontName': filename, 'FamilyName': filename, 'Weight': 'regular', 'ItalicAngle': 0, 'FullName': filename, } if re.search ('^cm', filename): fi.update (cm_guess_font_info (filename)) return fi if read_afm_p: global afmfile if not afmfile: afmfile = find_file (filename + '.afm') ...
if os.path.abspath (x) != x:
if x and os.path.abspath (x) != x:
def abs_dir (x, dir): if os.path.abspath (x) != x: return os.path.join (dir, x) return x
""" Extract bitmap from the PK file using `gf2pbm'
""" Extract bitmap from the PK file FILENAME (absolute) using `gf2pbm'.
def make_pbm (filename, outname, char_number): """ Extract bitmap from the PK file using `gf2pbm' Return FALSE if the glyph is not valid. """ status = system ("gf2pbm -n %d -o %s %s" %(char_number, outname, filename), ignore_error = 1) return (status == 0)
status = system ("gf2pbm -n %d -o %s %s" %(char_number, outname, filename), ignore_error = 1)
command = "gf2pbm -n %d -o %s %s" %(char_number, outname, filename) status = system (command, ignore_error = 1)
def make_pbm (filename, outname, char_number): """ Extract bitmap from the PK file using `gf2pbm' Return FALSE if the glyph is not valid. """ status = system ("gf2pbm -n %d -o %s %s" %(char_number, outname, filename), ignore_error = 1) return (status == 0)