code
stringlengths
1
1.72M
language
stringclasses
1 value
# empty
Python
""" a generic recursive descent parser the grammar is defined as a composition of objects the objects of the grammar are : Alternative : as in S -> A | B | C Sequence : as in S -> A B C KleeneStar : as in S -> A* or S -> A+ Token : a lexer token """ try: from pypy.interpreter.baseobjspace import Wrappabl...
Python
# A replacement for the token module # # adds a new map token_values to avoid doing getattr on the module # from PyPy RPython N_TOKENS = 0 # This is used to replace None NULLTOKEN = -1 tok_name = {-1 : 'NULLTOKEN'} tok_values = {'NULLTOKEN' : -1} # tok_rpunct = {} def setup_tokens( parser ): # global tok_rpunc...
Python
"""SyntaxTree class definition""" # try: # # from pypy.interpreter.pyparser.pysymbol import sym_values # from pypy.interpreter.pyparser.pytoken import tok_values # except ImportError: # # from pysymbol import sym_values # from pytoken import tok_values from pypy.tool.uid import uid from pypy.tool.uid im...
Python
from grammar import AbstractBuilder, AbstractContext, Parser class StackElement: """wraps TupleBuilder's tuples""" class Terminal(StackElement): def __init__(self, num, value, lineno=-1): self.nodes = [(num, value, lineno)] self.num = num def as_tuple(self, lineno=False): if line...
Python
import autopath import py from test_astcompiler import compile_with_astcompiler def setup_module(mod): import sys if sys.version[:3] != "2.4": py.test.skip("expected to work only on 2.4") import pypy.conftest mod.std_space = pypy.conftest.gettestobjspace('std') def check_file_compile(filename)...
Python
class FakeSpace: w_None = None w_str = str w_basestring = basestring w_int = int def wrap(self, obj): return obj def unwrap(self, obj): return obj def isinstance(self, obj, wtype ): return isinstance(obj,wtype) def is_true(self, obj): return obj ...
Python
"""test module for CPython / PyPy nested tuples comparison""" import os, os.path as osp import sys from pypy.interpreter.pyparser.pythonutil import python_parse, pypy_parse from pprint import pprint from pypy.interpreter.pyparser import grammar grammar.DEBUG = False from symbol import sym_name def name(elt): ret...
Python
""" list of tested expressions / suites (used by test_parser and test_astbuilder) """ constants = [ "0", "7", "-3", "053", "0x18", "14L", "1.0", "3.9", "-3.6", "1.8e19", "90000000000000", "90000000000000.", "3j" ] expressions = [ "x = a + 1", "x = 1 - a"...
Python
""" self cloning, automatic path configuration copy this into any subdirectory of pypy from which scripts need to be run, typically all of the test subdirs. The idea is that any such script simply issues import autopath and this will make sure that the parent directory containing "pypy" is in sys.path. If y...
Python
# EXPECT: Module(None, Stmt([From('__future__', [('with_statement', None)]), With(Name('acontext'), Stmt([Pass()]), None)])) from __future__ import with_statement with acontext: pass
Python
# -*- coding: ISO-8859-1 -*- a = 1 # keep this statement for now (see test_only_one_comment.py)
Python
print >> f
Python
# coding: ISO-8859-1 # encoding on the third line <=> no encoding a = 1
Python
class A: def with_white_spaces_before(self): pass def another_method(self, foo): bar = foo class B(object, A): def foo(self, bar): a = 2 return "spam"
Python
[i for i in range(10) if i%2 == 0] # same list on several lines [i for i in range(10) if i%2 == 0] [i for i in 1,2] [(i,j) for i in 1,2 for j in 3,4]
Python
import os import os.path as osp from sets import Set, ImmutableSet
Python
class A: def with_white_spaces_before(self): pass def another_method(self, foo): """with a docstring on several lines # with a sharpsign """ self.bar = foo
Python
#!/usr/bin/env python # coding: ISO_LATIN_1 a = 1
Python
# EXPECT: Module(None, Stmt([From('__future__', [('with_statement', None)]), With(Name('acontext'), Stmt([Pass()]), AssName('avariable', OP_ASSIGN))])) from __future__ import with_statement with acontext as avariable: pass
Python
for x in range(10): pass for x in range(5): a += x b += 2 if False: break else: continue else: c = 3 for index, val in enumerate(range(5)): val *= 2
Python
l = [ "foo", "bar", "baz"] l = [ "foo", "bar", "baz", ] l = [] l = [ ]
Python
a[1:]
Python
f() f(a) f(a,) f(a,b) f(a, b,) f(*args) f(**kwargs) f(*args, **kwargs) f(a, *args, **kwargs) f(a, b, *args, **kwargs) a = 1
Python
while (a < b and c < d and e < f): pass while (a < b and c < d and e < f): pass while (a < b and c < d and e < f): pass while (a < b and c < d and e < f): pass
Python
x = 1
Python
l = [] l . append ( 12 )
Python
"""module docstring""" """hello """ class A: """class doctring on several lines """ def foo(self): """function docstring""" def boo(x): """Docstring""";print 1 """world"""
Python
L = [] print L[0:10] def f(): print 1 # commentaire foireux x = 1 s = "asd" class A: def f(): pass
Python
# Function(Decorators([Name('foo')]), 'f', ['a', 'b'], [], 0, None, Stmt([Pass()])) @foo def f(a, b): pass @accepts(int, (int,float)) @returns((int,float)) def func0(arg1, arg2): return arg1 * arg2 ## Stmt([Function(Decorators([CallFunc(Getattr(Getattr(Name('mod1'), 'mod2'), 'accepts'), [Name('int'), Tuple([...
Python
index = 0 while index < 10: index += 1 foo = 10 - index if False: break else: foo = 12
Python
try: a b except: pass try: a b except NameError: pass try: a b except NameError, err: pass try: a b except (NameError, ValueError): pass try: a b except (NameError, ValueError), err: pass try: a except NameError, err: pass except ValueError, err:...
Python
#!/usr/bin/env python # coding: ISO_LATIN_1 a = 1
Python
def f(n): for i in range(n): yield n
Python
# only one comment
Python
x = 0x1L # comment a = 1 # yo # hello # world a = 2 # end
Python
x in range(10)
Python
from foo import bar, \ baz if True and \ False \ and True: print "excellent !"
Python
def f(a, b=1, *args, **kwargs): if args: a += len(args) if kwargs: a += len(kwargs) return a*b
Python
a = 1 a = -1 a = 1. a = .2 a = 1.2 a = 1e3 a = 1.3e4 a = -1.3
Python
x = y + 1
Python
"""This module does nothing""";print 1
Python
a = 1 b = 2 c = a + b
Python
import os, os.path as osp import sys from ebnf import parse_grammar from python import python_parse, pypy_parse, set_debug from pprint import pprint import grammar grammar.DEBUG = False from symbol import sym_name def name(elt): return "%s[%d]"% (sym_name.get(elt,elt),elt) def read_samples_dir(): return [...
Python
a is not None
Python
a[1:]
Python
from pypy.interpreter import error from pypy.interpreter import baseobjspace, module, main import sys import code import time class Completer: """ Stolen mostly from CPython's rlcompleter.py """ def __init__(self, space, w_globals): self.space = space self.w_globals = w_globals def comple...
Python
""" Module objects. """ from pypy.interpreter.baseobjspace import Wrappable class Module(Wrappable): """A module.""" def __init__(self, space, w_name, w_dict=None): self.space = space if w_dict is None: w_dict = space.newdict(track_builtin_shadowing=True) self.w_dict = w_...
Python
""" This module defines the abstract base classes that support execution: Code and Frame. """ from pypy.interpreter.error import OperationError from pypy.interpreter.baseobjspace import Wrappable from pypy.rlib import rstack # for resume points class Code(Wrappable): """A code is a compiled version of some source...
Python
""" Two bytecodes to speed up method calls. Here is how a method call looks like: (on the left, without the new bytecodes; on the right, with them) <push self> <push self> LOAD_ATTR name LOOKUP_METHOD name <push arg 0> <push arg 0> ... ...
Python
w_foo2 = space.wrap("hello") foo2 = "never mind" # should be hidden by w_foo2 def foobuilder(w_name): name = space.unwrap(w_name) return space.wrap("hi, %s!" % name) from __applevel__ import bar fortytwo = bar(space.wrap(6), space.wrap(7))
Python
### a trivial program to test strings, lists, functions and methods ### ## tiny change wrt goal so far needed: explicit parameter to str.split def addstr(s1,s2): return s1 + s2 str = "an interesting string" str2 = 'another::string::xxx::y:aa' str3 = addstr(str,str2) arr = [] for word in str.split(' '): if wo...
Python
def somefunc(space): return space.w_True def initpath(space): print "got to initpath", space return space.wrap(3)
Python
from pypy.interpreter.mixedmodule import MixedModule class Module(MixedModule): interpleveldefs = { '__name__' : '(space.wrap("mixedmodule"))', '__doc__' : '(space.wrap("mixedmodule doc"))', 'somefunc' : 'file1.somefunc', 'value' : '(space.w_None)', 'path' : 'f...
Python
def someappfunc(x): return x + 1
Python
def main(aStr): print len(aStr) map(main, ["hello world", "good bye"]) apply(main, ("apply works, too",)) apply(main, (), {"aStr": "it really works"}) print chr(65)
Python
""" A custom graphic renderer for the '.plain' files produced by dot. """ from __future__ import generators import re, os, math import pygame from pygame.locals import * this_dir = os.path.dirname(os.path.abspath(__file__)) FONT = os.path.join(this_dir, 'cyrvetic.ttf') FIXEDFONT = os.path.join(this_dir, 'VeraMoBd.t...
Python
#! /usr/bin/env python """ Usage: graphserver.py <port number> Start a server listening for connexions on the given port. """ import sys import msgstruct from cStringIO import StringIO class Server(object): def __init__(self, io): self.io = io self.display = None def run(self, only_on...
Python
import sys, os from struct import pack, unpack, calcsize MAGIC = -0x3b83728b CMSG_INIT = 'i' CMSG_START_GRAPH = '[' CMSG_ADD_NODE = 'n' CMSG_ADD_EDGE = 'e' CMSG_ADD_LINK = 'l' CMSG_FIXED_FONT = 'f' CMSG_STOP_GRAPH = ']' CMSG_MISSING_LINK= 'm' CMSG_SAY = 's' MSG_OK = 'O' MSG_ERROR ...
Python
import py Option = py.test.config.Option option = py.test.config.addoptions("dotviewer options", Option('--pygame', action="store_true", dest="pygame", default=False, help="allow interactive tests using Pygame"), )
Python
#! /usr/bin/env python """ Command-line interface for a dot file viewer. dotviewer.py filename.dot dotviewer.py filename.plain dotviewer.py --server [interface:]port In the first form, show the graph contained in a .dot file. In the second form, the graph was already compiled to a .plain file. In the thir...
Python
#! /usr/bin/env python """ Usage: graphserver.py <port number> Start a server listening for connexions on the given port. """ import sys import msgstruct from cStringIO import StringIO class Server(object): def __init__(self, io): self.io = io self.display = None def run(self, only_on...
Python
import os, sys, re import msgstruct this_dir = os.path.dirname(os.path.abspath(__file__)) GRAPHSERVER = os.path.join(this_dir, 'graphserver.py') def display_dot_file(dotfile, wait=True, save_tmp_file=None): """ Display the given dot file in a subprocess. """ if not os.path.exists(str(dotfile)): r...
Python
from __future__ import generators import os, time, sys import pygame from pygame.locals import * from drawgraph import GraphRenderer, FIXEDFONT from drawgraph import Node, Edge from drawgraph import EventQueue, wait_for_events METAKEYS = dict([ (ident[len('KMOD_'):].lower(), getattr(pygame.locals, ident)) for...
Python
#! /usr/bin/env python """ Command-line interface for a dot file viewer. dotviewer.py filename.dot dotviewer.py filename.plain dotviewer.py --server [interface:]port In the first form, show the graph contained in a .dot file. In the second form, the graph was already compiled to a .plain file. In the thir...
Python
""" Graph file parsing. """ import os, sys, re import msgstruct re_nonword = re.compile(r'([^0-9a-zA-Z_.]+)') re_plain = re.compile(r'graph [-0-9.]+ [-0-9.]+ [-0-9.]+$', re.MULTILINE) re_digraph = re.compile(r'\b(graph|digraph)\b', re.IGNORECASE) def guess_type(content): # try to see whether it is a directed g...
Python
class GraphPage(object): """Base class for the client-side content of one of the 'pages' (one graph) sent over to and displayed by the external process. """ save_tmp_file = None def __init__(self, *args): self.args = args def content(self): """Compute the content of the page. ...
Python
import sys, os def get_terminal_width(): try: import termios,fcntl,struct call = fcntl.ioctl(0,termios.TIOCGWINSZ,"\000"*8) height,width = struct.unpack( "hhhh", call ) [:2] terminal_width = width except (SystemExit, KeyboardInterrupt), e: raise except: # FAL...
Python
import py import errno class Error(EnvironmentError): __module__ = 'py.error' def __repr__(self): return "%s.%s %r: %s " %(self.__class__.__module__, self.__class__.__name__, self.__class__.__doc__, " ".join(...
Python
""" A utility to build a Python extension module from C, wrapping distutils. """ import py # XXX we should distutils in a subprocess, because it messes up the # environment and who knows what else. Currently we just save # and restore os.environ. def make_module_from_c(cfile): import os, sys, imp ...
Python
import py import sys, os, re from distutils import sysconfig from distutils import core winextensions = 1 if sys.platform == 'win32': try: import _winreg, win32gui, win32con except ImportError: winextensions = 0 class Params: """ a crazy hack to convince distutils to please inst...
Python
import py _time_desc = { 1 : 'second', 60 : 'minute', 3600 : 'hour', 86400 : 'day', 2628000 : 'month', 31536000 : 'year', } def worded_diff_time(ctime): difftime = py.std.time.time() - ctime keys = _time_desc.keys() keys.sort() for i, key in py.builtin.enumerate(keys): if ke...
Python
import sys class Std(object): """ makes all standard python modules available as a lazily computed attribute. """ def __init__(self): self.__dict__ = sys.modules def __getattr__(self, name): try: m = __import__(name) except ImportError: rais...
Python
""" """ import py import sys log = py.log.get("dynpkg", info=py.log.STDOUT, debug=py.log.STDOUT, command=None) # py.log.STDOUT) from distutils import util class DistPython: def __init__(self, location=None, python=None): if python is None: ...
Python
import py import sys, os, traceback import re if hasattr(sys.stdout, 'fileno') and os.isatty(sys.stdout.fileno()): def log(msg): print msg else: def log(msg): pass def convert_rest_html(source, source_path, stylesheet=None, encoding='latin1'): from py.__.rest import directive """ retu...
Python
#!/usr/bin/env python import py import inspect import types def report_strange_docstring(name, obj): if obj.__doc__ is None: print "%s misses a docstring" % (name, ) elif obj.__doc__ == "": print "%s has an empty" % (name, ) elif "XXX" in obj.__doc__: print "%s has an 'XXX' in its...
Python
#!/usr/bin/env python # hands on script to compute the non-empty Lines of Code # for tests and non-test code import py curdir = py.path.local() def nodot(p): return p.check(dotfile=0) class FileCounter(object): def __init__(self): self.file2numlines = {} self.numlines = 0 s...
Python
#
Python
#!/usr/bin/env python # hands on script to compute the non-empty Lines of Code # for tests and non-test code import py curdir = py.path.local() def nodot(p): return p.check(dotfile=0) class FileCounter(object): def __init__(self): self.file2numlines = {} self.numlines = 0 s...
Python
import py class ChangeItem: def __init__(self, repo, revision, line): self.repo = py.path.local(repo) self.revision = int(revision) self.action = action = line[:4] self.path = line[4:].strip() self.added = action[0] == "A" self.modified = action[0] == "M" se...
Python
""" Put this file as 'conftest.py' somewhere upwards from py-trunk, modify the "socketserveradr" below to point to a windows/linux host running "py/execnet/script/loop_socketserver.py" and invoke e.g. from linux: py.test --session=MySession some_path_to_what_you_want_to_test This should ad-hoc distribute the r...
Python
#
Python
#!/usr/bin/env python import py import inspect import types def report_strange_docstring(name, obj): if obj.__doc__ is None: print "%s misses a docstring" % (name, ) elif obj.__doc__ == "": print "%s has an empty" % (name, ) elif "XXX" in obj.__doc__: print "%s has an 'XXX' in its...
Python
#
Python
import py import os, sys def killproc(pid): if sys.platform == "win32": py.process.cmdexec("taskkill /F /PID %d" %(pid,)) else: os.kill(pid, 15)
Python
""" This module contains multithread-safe cache implementations. Caches mainly have a __getitem__ and getorbuild() method where the latter either just return a cached value or first builds the value. These are the current cache implementations: BuildcostAccessCache tracks building-time and accesses. Evi...
Python
import py, os, stat, md5 from Queue import Queue class RSync(object): """ This class allows to send a directory structure (recursively) to one or multiple remote filesystems. There is limited support for symlinks, which means that symlinks pointing to the sourcetree will be send "as is" w...
Python
import struct #import marshal # ___________________________________________________________________________ # # Messages # ___________________________________________________________________________ # the header format HDR_FORMAT = "!hhii" HDR_SIZE = struct.calcsize(HDR_FORMAT) class Message: """ encapsulates M...
Python
import threading, weakref, sys import Queue if 'Message' not in globals(): from py.__.execnet.message import Message class RemoteError(EOFError): """ Contains an Exceptions from the other side. """ def __init__(self, formatted): self.formatted = formatted EOFError.__init__(self) def __...
Python
#! /usr/bin/env python """ a remote python shell for injection into startserver.py """ import sys, os, socket, select try: clientsock except NameError: print "client side starting" import sys host, port = sys.argv[1].split(':') port = int(port) myself = open(os.path.abspath(sys.argv[0]), 'rU'...
Python
import os, sys import subprocess if __name__ == '__main__': directory = os.path.dirname(os.path.abspath(sys.argv[0])) script = os.path.join(directory, 'socketserver.py') while 1: cmdlist = ["python", script] cmdlist.extend(sys.argv[1:]) print "starting subcommand:", " ".join(cmdlis...
Python
#! /usr/bin/env python """ start socket based minimal readline exec server """ # this part of the program only executes on the server side # progname = 'socket_readline_exec_server-1.2' debug = 0 import sys, socket, os try: import fcntl except ImportError: fcntl = None if debug: # and not os.isatty(sys...
Python
#! /usr/bin/env python """ a remote python shell for injection into startserver.py """ import sys, os, socket, select try: clientsock except NameError: print "client side starting" import sys host, port = sys.argv[1].split(':') port = int(port) myself = open(os.path.abspath(sys.argv[0]), 'rU'...
Python
#! /usr/bin/env python """ start socket based minimal readline exec server """ # this part of the program only executes on the server side # progname = 'socket_readline_exec_server-1.2' debug = 0 import sys, socket, os try: import fcntl except ImportError: fcntl = None if debug: # and not os.isatty(sys...
Python
""" A windows service wrapper for the py.execnet socketserver. To use, run: python socketserverservice.py register net start ExecNetSocketServer """ import sys import os import time import win32serviceutil import win32service import win32event import win32evtlogutil import servicemanager import threading import soc...
Python
""" send a "quit" signal to a remote server """ import sys import socket hostport = sys.argv[1] host, port = hostport.split(':') hostport = (host, int(port)) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(hostport) sock.sendall('"raise KeyboardInterrupt"\n')
Python
import rlcompleter2 rlcompleter2.setup() import register, sys try: hostport = sys.argv[1] except: hostport = ':8888' gw = register.ServerGateway(hostport)
Python
import os, inspect, socket import sys from py.magic import autopath ; mypath = autopath() import py # the list of modules that must be send to the other side # for bootstrapping gateways # XXX we'd like to have a leaner and meaner bootstrap mechanism startup_modules = [ 'py.__.thread.io', 'py.__.thread.p...
Python
def f(): import os, stat, shutil, md5 destdir, options = channel.receive() modifiedfiles = [] def remove(path): assert path.startswith(destdir) try: os.unlink(path) except OSError: # assume it's a dir shutil.rmtree(path) def receive_dir...
Python
#
Python