code
stringlengths
1
1.72M
language
stringclasses
1 value
#! /usr/bin/env python #coding=utf-8 # -*- coding: utf-8 -*- import log # # transitionMap = { # (fromState, event):toState, # (fromState, event):toState, # ... # } # # # class IFsmCallbackObj(object): def __init__(self): pass def OnEnterState(self, state): pass def OnLeaveState(s...
Python
#! /usr/bin/env python #coding=utf-8 # 道具类,道具使用,效果,影响
Python
#! /usr/bin/env python #coding=utf-8 # tgame_entity import tgame_player import tgame_map import tgame_mapmgr g_builds = {} g_entitys = {} g_phys = {} g_items = {} ET_Player = 0x01 ET_Zombie = 0x02 ET_Barrier = 0x03 ET_Other = 0x04 def init(): pass def addentity(playerinfo, AItype = None): imp...
Python
#! /usr/bin/env python #coding=utf-8 import tgame_fsm class PlayerFSMClass(tgame_fsm.IFsmCallbackObj): TransitionMap = { ('stand', 'onMove'):'move', ('move', 'stopMove'):'stand', ('stand', 'Fire'):'atk', } MapState2Look = { 'move' : 'anim_stand_clip1', 'walk' : 'anim_walk_clip1', ...
Python
#! /usr/bin/env python #coding=utf-8 # 道具类,道具使用,效果,影响
Python
# 战争迷雾系统 import iworld2d import math3d # 小迷雾块大小 fogsize = 30 # 累计器 visionsum = 0 # 迷雾数量 h = 768/fogsize+1 w = 1024/fogsize+1 # 视野 class tgame_vision(object): def __init__(self, vision = 20, pos = (0,0) , mode = "pos", name = ""): # 累计器加1 global visionsum visionsum += 1 # 视野范围 self....
Python
#! /usr/bin/env python #coding=utf-8 # -*- coding: utf-8 -*- import log # # transitionMap = { # (fromState, event):toState, # (fromState, event):toState, # ... # } # # # class IFsmCallbackObj(object): def __init__(self): pass def OnEnterState(self, state): pass def OnLeaveState(s...
Python
#! /usr/bin/env python #coding=utf-8 import math3d,math LEFT_SIDE = 0x01 RIGHT_SIDE = 0x02 NONE_SIDE = 0x03 def angle(o, s, e): cosfi = 0 fi = 0 norm = 0 dsx = s[0] - o[0] dsy = s[1] - o[1] dex = e[0] - o[0] dey = e[1] - o[1] cosfi = dsx * dex + dsy * dey norm = (dsx * dsx + dsy * dsy)...
Python
#-- coding: utf-8 -*- import utils, sys lstDir = utils.listdir("tgame/script/") print "lstDir = %s" % str(lstDir) sys.path.extend(lstDir) import tgame_net_handler, t_cmd import tgame_room_logic import iapi import tgame_ready import tgame_menu tgame_API = None GAMEID = -1 GAME_MODE = None UID = None GA...
Python
#! /usr/bin/env python #coding=utf-8 #-- coding: utf-8 -*- import tgame_room_logic, t_cmd def init(): #网络消息到具体回调函数的映射表 global MSG_MAP MSG_MAP = { #游戏模式信息 "game_s_game_mode" : tgame_room_logic.inst.s_game_mode, \ #玩家进入 "game_s_user_in_game" : tgame_room_logic.inst.s_user_in_game, \ #玩家退出 "g...
Python
#-- coding: utf-8 -*- #游戏客户端的入口函数,当使用独立公共大厅的时候,这个函数将在玩家登陆游戏房间的时候被调用,从此程序逻辑将交给各个游戏自己完成 def init(**kargs): #进入游戏自己的初始化函数 import tgame_game tgame_game.start_from_init(int(kargs["gameid"]), int(kargs["gamemode"]), int(kargs["uid"])) #游戏客户端的退出函数,当玩家从游戏房间退出时,公共大厅逻辑会调用这个函数,游戏逻辑需要在这个函数里完成游戏对象的释放工作,防止内存泄漏 def force_...
Python
#! /usr/bin/env python #coding=utf-8 #-- coding: utf-8 -*- import tgame_room_logic, t_cmd def init(): #网络消息到具体回调函数的映射表 global MSG_MAP MSG_MAP = { #游戏模式信息 "game_s_game_mode" : tgame_room_logic.inst.s_game_mode, \ #玩家进入 "game_s_user_in_game" : tgame_room_logic.inst.s_user_in_game, \ #玩家退出 "g...
Python
import iapi API = None def init(): global API API = iapi.API()
Python
from t_const import * #关卡开启需求信息,key是关卡id,value是一个列表,表示开启关卡必须完成的其他关卡的id列表 STAGE_REQUIRE = { 1 : [], } DATA = { 1 : { "monster" : "tgame_map_demo", }, } def set_stage_info(): global DATA for value in DATA.values(): tgame_map = value["monster"] tgame_map = __import__(tgame_map) s...
Python
# 事件定义 # 转向 C_TUREND = 0x01 S_TUREND = 0x01 # 移动 C_MOVE = 0x02 S_MOVE = 0x02 # 移动2 C_RUN = 0x03 S_RUN = 0x03 # 攻击 C_ATK = 0x04 S_ATK = 0X04 # 拾取 C_PICKITEM = 0X05 S_PICKITEM = 0X05 # 使用物品 C_USEITEM = 0X06 S_USEITEM = 0X06 # 游戏时间 S_GAMETIME = 0x91 # 出现僵尸 S_GAME_BULZB = 0x71 # 事件 S_GAME_EVENT = 0x...
Python
#-- coding: utf-8 -*- import t_const """巫师指令定义方面客户端和服务端公用,其他的函数为客户端专用""" WIZARD_CHANGE_SUN = 0x01 #改变阳光数量 WIZARD_END_GAME = 0x02 #立刻结束游戏 WIZARD_ADD_ZOMBIE = 0x03 #立刻刷新僵尸 #帮助文字字典 HELP_TEXT = {WIZARD_CHANGE_SUN : "改变阳光数量指令//change_sun:参数1:整数(可正负,代表阳光数量的改变值),示例://change_sun 100", \ WIZARD_END_GAM...
Python
# -*- coding: utf-8 -*- import base_object import t_cmd import cg_network import cPickle import tgame_room_logic import tgame_mapmgr inst = None #模块初始化函数 def init(): global inst if not inst: inst = CCommand() #模块自清理函数,释放引用 def destroy(): global inst if inst: inst.destroy() inst = None ...
Python
''' main.py Main file for 2 Pints 2 Pints is an implementation of Quarto written in Python Dave Schwantes 2010 www.dinosaurseateverybody.com ''' from QuartoGame import * def main(): print "2 Pints" print "a Quarto implementation by Dave Schwantes" print "" game = QuartoGame() print "The Boa...
Python
import sys from copy import deepcopy class QuartoBoard: def __init__(self): self.spots = [None] * 4 for i in range(4): self.spots[i] = [None] * 4 def placePiece(self,piece,x,y): if not self.spots[x][y]: self.spots[x][y] = deepcopy(piece) return True r...
Python
''' QuartoGame.py Class for the QuartoGame object ''' import math from QuartoBoard import * from QuartoPiece import * class QuartoGame: def __init__(self): self.board = QuartoBoard() self.turn = 0 self.availablePieces = [] self.buildPieces() self.history ...
Python
''' main.py Main file for 2 Pints 2 Pints is an implementation of Quarto written in Python Dave Schwantes 2010 www.dinosaurseateverybody.com ''' from QuartoGame import * from TwoPints import * def main(): print "2 Pints" print "a Quarto playing bot by Dave Schwantes" print "" game = QuartoGame() ...
Python
''' TwoPints.py Class for TwoPints Object Two Pints is the computer "player" ''' import random from copy import deepcopy class TwoPints: def __init__(self): pass def makeMove(self): pass def selectPiece(self,game): # for the opening move select a random piece if len(game.ava...
Python
''' QuartoPiece.py Class for the QuartoPiece object def of ''' class QuartoPiece: def __init__(self, height, color, shape, fill): self.attributes = (height, color, shape, fill) self.onBoard = False self.placedBy = None pass def displayPiece(self): print self.at...
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 custo...
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 custo...
Python
from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() from django.views.generic.simple import direct_to_template import settings urlpatterns = patterns('', (r'^$', 'Exam.views.exam_list'), (r'^exams/?$', 'Exam.views.exam_list'), (r'^view...
Python
import os.path # Django settings for YourSchool 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', ...
Python
from django.db import models class Exam(models.Model): name = models.CharField(max_length=64) created = models.DateField() deadline = models.DateField() author = models.CharField(max_length=64) class ExamQuestion(models.Model): question = models.CharField(max_length=64) exam = models.ForeignKey(...
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...
Python
# Create your views here. # -*- coding: utf-8 -*- from audioop import reverse from datetime import datetime, date import string from django.http import HttpResponseRedirect from django.shortcuts import render_to_response, redirect, HttpResponse, RequestContext, get_object_or_404 from django.contrib.auth import l...
Python
import simplejson, flickrapi, liblo, pyglet, math, rabbyt from urllib import urlopen class skreenPics: """class to hold the pictures from flickr""" api_key = '59725ca9f32547bd79f608c18a2b7669' flickr = flickrapi.FlickrAPI(api_key) def jsonPstrip(self,str): """strip jsonP style function call wrappers""" return...
Python
import liblo, math #import pyglet, rabbyt class touchList(list): """a class that responds to OSC messages with TUIO data""" lastAlive=[] lastSet=[] def tuioAlive(self,pointsList): """process the arguments of a TUIO Alive message""" for x in self: if x[0] not in pointsList: self.remove(x) self.statsR...
Python
#!/usr/bin/python # gameswf_batch_test.py -Thatcher Ulrich <tu@tulrich.com> 2005 # This source code has been donated to the Public Domain. Do # whatever you want with it. # Script for batch regression tests on gameswf. import string import sys import commands import difflib import re GAMESWF = "./g...
Python
#!/usr/bin/python # gameswf_batch_test.py -Thatcher Ulrich <tu@tulrich.com> 2005 # This source code has been donated to the Public Domain. Do # whatever you want with it. # Script to interactively run all the .swf's in samples/ one-by-one. # # Pass a path argument to start with a particular test file. i...
Python
#!/usr/bin/python # gameswf_batch_test.py -Thatcher Ulrich <tu@tulrich.com> 2005 # This source code has been donated to the Public Domain. Do # whatever you want with it. # Script for batch regression tests on gameswf. import string import sys import commands import difflib import re GAMESWF = "./g...
Python
#!/usr/bin/python # gameswf_batch_test.py -Thatcher Ulrich <tu@tulrich.com> 2005 # This source code has been donated to the Public Domain. Do # whatever you want with it. # Script to interactively run all the .swf's in samples/ one-by-one. # # Pass a path argument to start with a particular test file. i...
Python
# See http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: from pkgutil import extend_path __path__ = extend_path(__path__, __name__)
Python
import unittest from zope.testing import doctestunit from zope.component import testing from Testing import ZopeTestCase as ztc from Products.Five import zcml from Products.Five import fiveconfigure from Products.PloneTestCase import PloneTestCase as ptc from Products.PloneTestCase.layer import PloneSite ptc.setupPlo...
Python
from plone.theme.interfaces import IDefaultPloneLayer class IThemeSpecific(IDefaultPloneLayer): """Marker interface that defines a Zope 3 browser layer. If you need to register a viewlet only for the "My315okTheme" theme, this interface must be its layer (in my315oktheme/viewlets/configure.zcm...
Python
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile from plone.app.layout.viewlets.common import ViewletBase # Sample code for a basic viewlet (In order to use it, you'll have to): # - Un-comment the following useable piece of code (viewlet python class). # - Rename the viewlet template file ('brow...
Python
#
Python
def setupVarious(context): # Ordinarily, GenericSetup handlers check for the existence of XML files. # Here, we are not parsing an XML file, but we use this text file as a # flag to check that we actually meant for this import step to be run. # The file is found in profiles/default. if context.rea...
Python
def initialize(context): """Initializer called when used as a Zope 2 product."""
Python
from setuptools import setup, find_packages import os version = '1.0' setup(name='Products.my315oktheme', version=version, description="A theme that integrated portletmanager function to Ptortal-header,portal-footer and body", long_description=open("README.txt").read() + "\n" + ...
Python
# Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Base class for fixers (optional, but recommended).""" # Python imports import logging import itertools # Local imports from .patcomp import PatternCompiler from . import pygram from .fixer_util import does_tree_imp...
Python
"Utility functions used by the btm_matcher module" from . import pytree from .pgen2 import grammar, token from .pygram import pattern_symbols, python_symbols syms = pattern_symbols.__dict__ pysyms = python_symbols.__dict__ tokens = grammar.opmap token_labels = token.__dict__ TYPE_ANY = -1 TYPE_ALTERNATIVES = -2 TYPE...
Python
""" Main program for 2to3. """ from __future__ import with_statement import sys import os import difflib import logging import shutil import optparse from . import refactor def diff_texts(a, b, filename): """Return a unified diff of two strings.""" a = a.splitlines() b = b.splitlines() return diffl...
Python
# Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Pattern compiler. The grammer is taken from PatternGrammar.txt. The compiler compiles a pattern to a pytree.*Pattern instance. """ __author__ = "Guido van Rossum <guido@python.org>" # Python imports import os # ...
Python
# Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Export the Python grammar and symbols.""" # Python imports import os # Local imports from .pgen2 import token from .pgen2 import driver from . import pytree # The grammar file _GRAMMAR_FILE = os.path.join(os.path....
Python
"""Utility functions, node construction macros, etc.""" # Author: Collin Winter # Local imports from .pgen2 import token from .pytree import Leaf, Node from .pygram import python_symbols as syms from . import patcomp ########################################################### ### Common node-construction "macros" ##...
Python
#! /usr/bin/env python3 """Token constants (from "token.h").""" # Taken from Python (r53757) and modified to include some tokens # originally monkeypatched in by pgen2.tokenize #--start constants-- ENDMARKER = 0 NAME = 1 NUMBER = 2 STRING = 3 NEWLINE = 4 INDENT = 5 DEDENT = 6 LPAR = 7 RPAR = 8 LSQB = 9 RSQB = 10 ...
Python
#! /usr/bin/env python3 """Token constants (from "token.h").""" # Taken from Python (r53757) and modified to include some tokens # originally monkeypatched in by pgen2.tokenize #--start constants-- ENDMARKER = 0 NAME = 1 NUMBER = 2 STRING = 3 NEWLINE = 4 INDENT = 5 DEDENT = 6 LPAR = 7 RPAR = 8 LSQB = 9 RSQB = 10 ...
Python
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation. # All rights reserved. """Tokenization help for Python programs. generate_tokens(readline) is a generator that breaks a stream of text into Python tokens. It accepts a readline-like method which is called repeatedly to get the next line o...
Python
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Convert graminit.[ch] spit out by pgen to Python code. Pgen is the Python parser generator. It is useful to quickly create a parser from a grammar file in Python's grammar notation. But I don't wa...
Python
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Safely evaluate Python string literals without using eval().""" import re simple_escapes = {"a": "\a", "b": "\b", "f": "\f", "n": "\n", ...
Python
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. # Pgen imports from . import grammar, token, tokenize class PgenGrammar(grammar.Grammar): pass class ParserGenerator(object): def __init__(self, filename, stream=None): close_stream =...
Python
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """This module defines the data structures used to represent a grammar. These are a bit arcane because they are derived from the data structures used by Python's 'pgen' parser generator. There's also ...
Python
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """The pgen2 package."""
Python
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. # Modifications: # Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Parser driver. This provides a high-level interface to parse a file into a synta...
Python
# Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """ Python parse tree definitions. This is a very concrete parse tree; we need to keep every token and even the comments and whitespace between tokens. There's also a pattern matching implementation here. """ __autho...
Python
"""A bottom-up tree matching algorithm implementation meant to speed up 2to3's matching process. After the tree patterns are reduced to their rarest linear path, a linear Aho-Corasick automaton is created. The linear automaton traverses the linear paths from the leaves to the root of the AST and returns a set of nodes ...
Python
# Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer that turns <> into !=.""" # Local imports from .. import pytree from ..pgen2 import token from .. import fixer_base class FixNe(fixer_base.BaseFix): # This is so simple that we don't need the pattern com...
Python
"""Fixer for generator.throw(E, V, T). g.throw(E) -> g.throw(E) g.throw(E, V) -> g.throw(E(V)) g.throw(E, V, T) -> g.throw(E(V).with_traceback(T)) g.throw("foo"[, V[, T]]) will warn about string exceptions.""" # Author: Collin Winter # Local imports from .. import pytree from ..pgen2 import token from .. im...
Python
# Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for apply(). This converts apply(func, v, k) into (func)(*v, **k).""" # Local imports from .. import pytree from ..pgen2 import token from .. import fixer_base from ..fixer_util import Call, Comma, parenthesi...
Python
"""Fixer for import statements. If spam is being imported from the local directory, this import: from spam import eggs Becomes: from .spam import eggs And this import: import spam Becomes: from . import spam """ # Local imports from .. import fixer_base from os.path import dirname, join, exists, sep f...
Python
"""Fixer for 'raise E, V, T' raise -> raise raise E -> raise E raise E, V -> raise E(V) raise E, V, T -> raise E(V).with_traceback(T) raise (((E, E'), E''), E'''), V -> raise E(V) raise "foo", V, T -> warns about string exceptions CAVEATS: 1) "raise E, V" will be incorrectly translate...
Python
# Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for print. Change: 'print' into 'print()' 'print ...' into 'print(...)' 'print ... ,' into 'print(..., end=" ")' 'print >>x, ...' into 'print(..., file=x)' No changes are appl...
Python
"""Fixer that changes input(...) into eval(input(...)).""" # Author: Andre Roberge # Local imports from .. import fixer_base from ..fixer_util import Call, Name from .. import patcomp context = patcomp.compile_pattern("power< 'eval' trailer< '(' any ')' > >") class FixInput(fixer_base.BaseFix): BM_compatible ...
Python
"""Fixer that changes 'a ,b' into 'a, b'. This also changes '{a :b}' into '{a: b}', but does not touch other uses of colons. It does not touch other uses of whitespace. """ from .. import pytree from ..pgen2 import token from .. import fixer_base class FixWsComma(fixer_base.BaseFix): explicit = True # The use...
Python
"""Adjust some old Python 2 idioms to their modern counterparts. * Change some type comparisons to isinstance() calls: type(x) == T -> isinstance(x, T) type(x) is T -> isinstance(x, T) type(x) != T -> not isinstance(x, T) type(x) is not T -> not isinstance(x, T) * Change "while 1:" into "while True:"....
Python
# Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for StandardError -> Exception.""" # Local imports from .. import fixer_base from ..fixer_util import Name class FixStandarderror(fixer_base.BaseFix): BM_compatible = True PATTERN = """ ...
Python
"""Fix incompatible renames Fixes: * sys.maxint -> sys.maxsize """ # Author: Christian Heimes # based on Collin Winter's fix_import # Local imports from .. import fixer_base from ..fixer_util import Name, attr_chain MAPPING = {"sys": {"maxint" : "maxsize"}, } LOOKUP = {} def alternates(members): re...
Python
# Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer that changes xrange(...) into range(...).""" # Local imports from .. import fixer_base from ..fixer_util import Name, Call, consuming_calls from .. import patcomp class FixXrange(fixer_base.BaseFix): BM...
Python
# Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer that turns 'long' into 'int' everywhere. """ # Local imports from lib2to3 import fixer_base from lib2to3.fixer_util import is_probably_builtin class FixLong(fixer_base.BaseFix): BM_compatible = True ...
Python
# Copyright 2008 Armin Ronacher. # Licensed to PSF under a Contributor Agreement. """Fixer that cleans up a tuple argument to isinstance after the tokens in it were fixed. This is mainly used to remove double occurrences of tokens as a leftover of the long -> int / unicode -> str conversion. eg. isinstance(x, (int,...
Python
""" Fixer for itertools.(imap|ifilter|izip) --> (map|filter|zip) and itertools.ifilterfalse --> itertools.filterfalse (bugs 2360-2363) imports from itertools are fixed in fix_itertools_import.py If itertools is imported as something else (ie: import itertools as it; it.izip(spam, eggs)) method calls w...
Python
"""Fix changes imports of urllib which are now incompatible. This is rather similar to fix_imports, but because of the more complex nature of the fixing for urllib, it has its own fixer. """ # Author: Nick Edds # Local imports from .fix_imports import alternates, FixImports from .. import fixer_base from ..fixer...
Python
# Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer that changes buffer(...) into memoryview(...).""" # Local imports from .. import fixer_base from ..fixer_util import Name class FixBuffer(fixer_base.BaseFix): BM_compatible = True explicit = True #...
Python
"""Fixer for __metaclass__ = X -> (metaclass=X) methods. The various forms of classef (inherits nothing, inherits once, inherints many) don't parse the same in the CST so we look at ALL classes for a __metaclass__ and if we find one normalize the inherits to all be an arglist. For one-liner classes ('c...
Python
# Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for has_key(). Calls to .has_key() methods are expressed in terms of the 'in' operator: d.has_key(k) -> k in d CAVEATS: 1) While the primary target of this fixer is dict.has_key(), the fixer will chan...
Python
""" Fixer that changes os.getcwdu() to os.getcwd(). """ # Author: Victor Stinner # Local imports from .. import fixer_base from ..fixer_util import Name class FixGetcwdu(fixer_base.BaseFix): BM_compatible = True PATTERN = """ power< 'os' trailer< dot='.' name='getcwdu' > any* > "...
Python
# Copyright 2006 Georg Brandl. # Licensed to PSF under a Contributor Agreement. """Fixer for intern(). intern(s) -> sys.intern(s)""" # Local imports from .. import pytree from .. import fixer_base from ..fixer_util import Name, Attr, touch_import class FixIntern(fixer_base.BaseFix): BM_compatible = True ...
Python
"""Fix incompatible imports and module references.""" # Authors: Collin Winter, Nick Edds # Local imports from .. import fixer_base from ..fixer_util import Name, attr_chain MAPPING = {'StringIO': 'io', 'cStringIO': 'io', 'cPickle': 'pickle', '__builtin__' : 'builtins', 'c...
Python
# Copyright 2008 Armin Ronacher. # Licensed to PSF under a Contributor Agreement. """Fixer for reduce(). Makes sure reduce() is imported from the functools module if reduce is used in that module. """ from lib2to3 import fixer_base from lib2to3.fixer_util import touch_import class FixReduce(fixer_base.BaseFix): ...
Python
"""Fixer for basestring -> str.""" # Author: Christian Heimes # Local imports from .. import fixer_base from ..fixer_util import Name class FixBasestring(fixer_base.BaseFix): BM_compatible = True PATTERN = "'basestring'" def transform(self, node, results): return Name("str", prefix=node.prefix)...
Python
""" Optional fixer to transform set() calls to set literals. """ # Author: Benjamin Peterson from lib2to3 import fixer_base, pytree from lib2to3.fixer_util import token, syms class FixSetLiteral(fixer_base.BaseFix): BM_compatible = True explicit = True PATTERN = """power< 'set' trailer< '(' ...
Python
"""Fixer for function definitions with tuple parameters. def func(((a, b), c), d): ... -> def func(x, d): ((a, b), c) = x ... It will also support lambdas: lambda (x, y): x + y -> lambda t: t[0] + t[1] # The parens are a syntax error in Python 3 lambda (x): x + y -> lambda x: x + y """...
Python
""" Convert use of sys.exitfunc to use the atexit module. """ # Author: Benjamin Peterson from lib2to3 import pytree, fixer_base from lib2to3.fixer_util import Name, Attr, Call, Comma, Newline, syms class FixExitfunc(fixer_base.BaseFix): keep_line_order = True BM_compatible = True PATTERN = """ ...
Python
"""Fixer that turns 1L into 1, 0755 into 0o755. """ # Copyright 2007 Georg Brandl. # Licensed to PSF under a Contributor Agreement. # Local imports from ..pgen2 import token from .. import fixer_base from ..fixer_util import Number class FixNumliterals(fixer_base.BaseFix): # This is so simple that we don't need ...
Python
"""Fix "for x in f.xreadlines()" -> "for x in f". This fixer will also convert g(f.xreadlines) into g(f.__iter__).""" # Author: Collin Winter # Local imports from .. import fixer_base from ..fixer_util import Name class FixXreadlines(fixer_base.BaseFix): BM_compatible = True PATTERN = """ power< c...
Python
# Dummy file to make this directory a package.
Python
# Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for execfile. This converts usages of the execfile function into calls to the built-in exec() function. """ from .. import fixer_base from ..fixer_util import (Comma, Name, Call, LParen, RParen, Dot, Node, ...
Python
"""Fixer that changes unicode to str, unichr to chr, and u"..." into "...". """ import re from ..pgen2 import token from .. import fixer_base _mapping = {"unichr" : "chr", "unicode" : "str"} _literal_re = re.compile(r"[uU][rR]?[\'\"]") class FixUnicode(fixer_base.BaseFix): BM_compatible = True PATTERN = "...
Python
""" Fixer for imports of itertools.(imap|ifilter|izip|ifilterfalse) """ # Local imports from lib2to3 import fixer_base from lib2to3.fixer_util import BlankLine, syms, token class FixItertoolsImports(fixer_base.BaseFix): BM_compatible = True PATTERN = """ import_from< 'from' 'itertools' 'i...
Python
# Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for dict methods. d.keys() -> list(d.keys()) d.items() -> list(d.items()) d.values() -> list(d.values()) d.iterkeys() -> iter(d.keys()) d.iteritems() -> iter(d.items()) d.itervalues() -> iter(d.values()) d.v...
Python
"""Fixer for __nonzero__ -> __bool__ methods.""" # Author: Collin Winter # Local imports from .. import fixer_base from ..fixer_util import Name, syms class FixNonzero(fixer_base.BaseFix): BM_compatible = True PATTERN = """ classdef< 'class' any+ ':' suite< any* fu...
Python
"""Fixer for except statements with named exceptions. The following cases will be converted: - "except E, T:" where T is a name: except E as T: - "except E, T:" where T is not a name, tuple or list: except E as t: T = t This is done because the target of an "except" clause must be a ...
Python
# Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer that changes filter(F, X) into list(filter(F, X)). We avoid the transformation if the filter() call is directly contained in iter(<>), list(<>), tuple(<>), sorted(<>), ...join(<>), or for V in <>:. NOTE: This...
Python
""" Fixer that changes zip(seq0, seq1, ...) into list(zip(seq0, seq1, ...) unless there exists a 'from future_builtins import zip' statement in the top-level namespace. We avoid the transformation if the zip() call is directly contained in iter(<>), list(<>), tuple(<>), sorted(<>), ...join(<>), or for V in <>:. """ #...
Python
"""Fix incompatible imports and module references that must be fixed after fix_imports.""" from . import fix_imports MAPPING = { 'whichdb': 'dbm', 'anydbm': 'dbm', } class FixImports2(fix_imports.FixImports): run_order = 7 mapping = MAPPING
Python