code
stringlengths
1
1.72M
language
stringclasses
1 value
import thread from pypy.interpreter.error import OperationError from pypy.interpreter.baseobjspace import Wrappable from pypy.interpreter.typedef import TypeDef, interp2app from pypy.interpreter.typedef import GetSetProperty, descr_get_dict from pypy.interpreter.typedef import descr_set_dict from pypy.interpreter.gatew...
Python
# Package initialisation from pypy.interpreter.mixedmodule import MixedModule class Module(MixedModule): appleveldefs = { 'exit': 'app_thread.exit', 'exit_thread': 'app_thread.exit', # obsolete synonym 'error': 'app_thread.error', } ...
Python
import py import time, gc from pypy.conftest import gettestobjspace, option from pypy.interpreter.gateway import ObjSpace, W_Root, interp2app_temp def waitfor(space, w_condition, timeout=300.0): w_sleep = space.appexec([], "():\n import time; return time.sleep") adaptivedelay = 0.04 limit = time.time() + ...
Python
#
Python
import errno def get_errorcode(space): return space.wrap(errno.errorcode)
Python
# Package initialisation from pypy.interpreter.mixedmodule import MixedModule import errno class Module(MixedModule): """This module makes available standard errno system symbols. The value of each symbol is the corresponding integer value, e.g., on most systems, errno.ENOENT equals the integer 2. Th...
Python
from pypy.interpreter.baseobjspace import Wrappable from pypy.interpreter.typedef import GetSetProperty, TypeDef from pypy.interpreter.typedef import interp_attrproperty, interp_attrproperty_w from pypy.interpreter.error import OperationError from pypy.interpreter.gateway import interp2app, ObjSpace, W_Root class I...
Python
from Numeric import zeros,array,ArrayType from Numeric import Float,TOWER_TYPES,TOWER_TYPES_VALUES def assertRaises(block,exception=Exception,shout='This should raise an exception'): try: block() except exception: pass else: assert False,shout """ PyPy issues : >>>> 1=1 prod...
Python
from pypy.interpreter.mixedmodule import MixedModule class Module(MixedModule): """An RPython reimplementation of the Numeric module """ appleveldefs = { } interpleveldefs = { 'Float' : "space.wrap('d')", 'Int' : "space.wrap('l')", # 'array' : 'interp_numeric.w_array', ...
Python
from pypy.interpreter.gateway import ObjSpace, W_Root, NoneNotWrapped from pypy.module._socket.interp_socket import converted_error, W_RSocket from pypy.rlib import rsocket from pypy.rlib.rsocket import SocketError from pypy.interpreter.error import OperationError def gethostname(space): """gethostname() -> string...
Python
from pypy.interpreter.baseobjspace import Wrappable from pypy.interpreter.typedef import TypeDef, make_weakref_descr from pypy.interpreter.gateway import ObjSpace, W_Root, NoneNotWrapped from pypy.interpreter.gateway import interp2app from pypy.rlib.rarithmetic import intmask from pypy.rlib.rsocket import RSocket, AF_I...
Python
# Package initialisation from pypy.interpreter.mixedmodule import MixedModule import sys class Module(MixedModule): applevel_name = '_socket' appleveldefs = { 'error' : 'app_socket.error', 'herror' : 'app_socket.herror', 'gaierror' : 'app_socket.gaierror', 'timeout' ...
Python
"""Implementation module for socket operations. See the socket module for documentation.""" class error(Exception): pass class herror(error): pass class gaierror(error): pass class timeout(error): pass
Python
# UNICODE CHARACTER DATABASE # This file was generated with the command: # ./generate_unicodedb.py -o unicodedb_4_1_0.py UnicodeData-4.1.0.txt CompositionExclusions-4.1.0.txt EastAsianWidth-4.1.0.txt UnihanNumeric-4.1.0.txt version = '4.1.0' _charnames = { 32: 'SPACE', 33: 'EXCLAMATION MARK', 34: 'QUOTATION MARK'...
Python
#!/usr/bin/env python MAXUNICODE = 0x10FFFF # the value of sys.maxunicode of wide Python builds class Fraction: def __init__(self, numerator, denominator): self.numerator = numerator self.denominator = denominator def __repr__(self): return '%r / %r' % (self.numerator, self.denomi...
Python
""" Implementation of the interpreter-level functions in the module unicodedata. """ from pypy.interpreter.gateway import W_Root, ObjSpace, NoneNotWrapped from pypy.interpreter.gateway import interp2app from pypy.interpreter.baseobjspace import Wrappable from pypy.interpreter.error import OperationError from pypy.inte...
Python
#!/usr/bin/env python MAXUNICODE = 0x10FFFF # the value of sys.maxunicode of wide Python builds class Fraction: def __init__(self, numerator, denominator): self.numerator = numerator self.denominator = denominator def __repr__(self): return '%r / %r' % (self.numerator, self.denomi...
Python
# UNICODE CHARACTER DATABASE # This file was generated with the command: # ./generate_unicodedb.py -o unicodedb_3_2_0.py UnicodeData-3.2.0.txt CompositionExclusions-3.2.0.txt EastAsianWidth-3.2.0.txt UnihanNumeric-3.2.0.txt version = '3.2.0' _charnames = { 32: 'SPACE', 33: 'EXCLAMATION MARK', 34: 'QUOTATION MARK'...
Python
# UNICODE CHARACTER DATABASE # This file was generated with the command: # ./generate_unicodedb.py -o unicodedb_5_0_0.py UnicodeData-5.0.0.txt CompositionExclusions-5.0.0.txt EastAsianWidth-5.0.0.txt UnihanNumeric-5.0.0.txt version = '5.0.0' _charnames = { 32: 'SPACE', 33: 'EXCLAMATION MARK', 34: 'QUOTATION MARK'...
Python
from pypy.interpreter.mixedmodule import MixedModule class Module(MixedModule): appleveldefs = { } interpleveldefs = { 'unidata_version' : 'space.wrap(interp_ucd.ucd.version)', 'ucd_3_2_0' : 'space.wrap(interp_ucd.ucd_3_2_0)', #'ucd_4_1_0' : 'space.wrap(interp_ucd.uc...
Python
from pypy.rpython.rctypes.tool import ctypes_platform from pypy.rpython.rctypes.tool.libc import libc import pypy.rpython.rctypes.implementation # this defines rctypes magic from pypy.rpython.rctypes.aerrno import geterrno from pypy.interpreter.error import OperationError from pypy.interpreter.baseobjspace import W_Roo...
Python
from pypy.interpreter.mixedmodule import MixedModule class Module(MixedModule): interpleveldefs = { 'fcntl': 'interp_fcntl.fcntl', 'flock': 'interp_fcntl.flock', 'lockf': 'interp_fcntl.lockf', 'ioctl': 'interp_fcntl.ioctl' } appleveldefs = { '_conv_descriptor': 'app...
Python
def _conv_descriptor(f): if hasattr(f, "fileno"): return f.fileno() elif isinstance(f, (int, long)): return f else: raise TypeError, "argument must be an int, or have a fileno() method." __doc__ = """This module performs file control and I/O control on file descriptors. It is an i...
Python
""" Termios module. I'm implementing it directly here, as I see little use of termios module on RPython level by itself """ from pypy.interpreter.baseobjspace import ObjSpace, W_Root from pypy.interpreter.error import OperationError from pypy.rpython.module import ll_termios from pypy.rlib.objectmodel import we_are_t...
Python
class error(Exception): pass
Python
from pypy.interpreter.mixedmodule import MixedModule import termios from pypy.rlib.nonconst import NonConstant class Module(MixedModule): "This module provides an interface to the Posix calls for tty I/O control.\n\ For a complete description of these calls, see the Posix or Unix manual\n\ pages. It is on...
Python
"""Mixed module for dynamic grammar modification""" from pypy.interpreter.mixedmodule import MixedModule class Module(MixedModule): """dyngram module definition""" name = 'dyngram' appleveldefs = {} interpleveldefs = { 'insert_grammar_rule' : 'pypy.interpreter.pycompiler.insert_grammar_r...
Python
# empty
Python
# NOT_RPYTHON class StaticMethodWrapper(object): __slots__ = ('class_name', 'meth_name',) def __init__(self, class_name, meth_name): self.class_name = class_name self.meth_name = meth_name def __call__(self, *args): import clr return clr.call_staticmethod(self.class_name, ...
Python
from pypy.interpreter.baseobjspace import W_Root from pypy.objspace.std.intobject import W_IntObject from pypy.objspace.std.floatobject import W_FloatObject from pypy.objspace.std.boolobject import W_BoolObject from pypy.objspace.std.noneobject import W_NoneObject from pypy.objspace.std.stringobject import W_StringObje...
Python
import os.path from pypy.interpreter.baseobjspace import ObjSpace, W_Root, Wrappable from pypy.interpreter.error import OperationError from pypy.interpreter.gateway import interp2app, ApplevelClass from pypy.interpreter.typedef import TypeDef from pypy.rpython.ootypesystem import ootype from pypy.translator.cli.dotnet ...
Python
# Package initialisation from pypy.interpreter.mixedmodule import MixedModule import boxing_rules # with side effects class Module(MixedModule): """CLR module""" appleveldefs = {} interpleveldefs = { '_CliObject_internal': 'interp_clr.W_CliObject', 'call_staticmethod': 'interp_clr.ca...
Python
"""This module defines an object type which can efficiently represent an array of basic values: characters, integers, floating point numbers. Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained. The type is specified at object creation time by using...
Python
from pypy.interpreter.mixedmodule import MixedModule class Module(MixedModule): appleveldefs = { '__doc__' : 'app_array.__doc__', '__name__' : 'app_array.__name__', 'array' : 'app_array.array', 'ArrayType' : 'app_array.ArrayType', } interpleveldefs = { }
Python
__doc__ = """The python bz2 module provides a comprehensive interface for the bz2 compression library. It implements a complete file interface, one shot (de)compression functions, and types for sequential (de)compression.""" class BZ2File(file): """BZ2File(name [, mode='r', buffering=0, compresslevel=9]) -> file ...
Python
from ctypes import * STRING = c_char_p __darwin_nl_item = c_int __darwin_wctrans_t = c_int __darwin_wctype_t = c_ulong class bz_stream(Structure): pass bz_stream._fields_ = [ ('next_in', POINTER(c_char)), ('avail_in', c_uint), ('total_in_lo32', c_uint), ('total_in_hi32', c_uint), ('next_out', ...
Python
from pypy.rpython.rctypes.tool import ctypes_platform import pypy.rpython.rctypes.implementation # this defines rctypes magic from pypy.interpreter.error import OperationError from pypy.interpreter.baseobjspace import Wrappable from pypy.interpreter.typedef import TypeDef, GetSetProperty from pypy.interpreter.typedef i...
Python
# REVIEWME from pypy.interpreter.mixedmodule import MixedModule class Module(MixedModule): interpleveldefs = { 'BZ2Compressor': 'interp_bz2.W_BZ2Compressor', 'BZ2Decompressor': 'interp_bz2.W_BZ2Decompressor', 'compress': 'interp_bz2.compress', 'decompress': 'interp_bz2.decompress', ...
Python
import py from pypy.interpreter.baseobjspace import Wrappable, W_Root from pypy.interpreter.argument import Arguments from pypy.interpreter.error import OperationError from pypy.interpreter.typedef import GetSetProperty, TypeDef from pypy.interpreter.gateway import interp2app, ObjSpace from pypy.rlib.objectmodel import...
Python
from pypy.interpreter.mixedmodule import MixedModule class Module(MixedModule): appleveldefs = { } interpleveldefs = { 'ref': 'interp__weakref.W_Weakref', 'getweakrefcount': 'interp__weakref.getweakrefcount', 'getweakrefs': 'interp__weakref.getweakrefs', 'ReferenceType':...
Python
"""Dynamic replacement for the stdlib 'symbol' module. This module exports the symbol values computed by the grammar parser at run-time. """ from pypy.interpreter.mixedmodule import MixedModule # Forward imports so they run at startup time import pypy.interpreter.pyparser.pythonlexer import pypy.interpreter.pyparse...
Python
import pypy from pypy.module.pypyjit.interp_jit import PORTAL from pypy.module.pypyjit.newbool import NewBoolDesc from pypy.translator.translator import graphof from pypy.annotation.specialize import getuniquenondirectgraph from pypy.jit.hintannotator.policy import ManualGraphPolicy class PyPyHintAnnotatorPolicy(Manua...
Python
"""This is not the JIT :-) The pypyjit module helpers set the 'jit_enable' flag on code objects. The code below makes two identical copies of the interpreter's main loop, and the flag controls which of them is used. One of them (dispatch_jit) is transformed to become a JIT by code elsewhere: pypy/jit/* """ import py ...
Python
from pypy.rpython.lltypesystem import lltype, llmemory from pypy.rpython.annlowlevel import cachedtype from pypy.annotation import model as annmodel from pypy.jit.timeshifter import rvalue, rcontainer from pypy.objspace.std.boolobject import W_BoolObject class NewBoolDesc: __metaclass__ = cachedtype def __in...
Python
from pypy.interpreter.mixedmodule import MixedModule class Module(MixedModule): appleveldefs = { } interpleveldefs = { 'enable': 'interp_jit.enable', } def setup_after_space_initialization(self): # force the setup() to run early import pypy.module.pypyjit.interp_jit
Python
import py Option = py.test.config.Option option = py.test.config.addoptions("ppc options", Option('--pypy-c', action="store", default=None, dest="pypy_c", help=""))
Python
#
Python
# Empty
Python
__all__ = ['ContractAspect', 'ContractError', 'PreconditionError', 'PostConditionError'] from aop import * from copy import deepcopy class ContractAspect: __metaclass__ = Aspect def __init__(self): self.initial_state = {} @around(PointCut(func='[^_].*', klass='.+').execution()) def contract_che...
Python
""" application level support module for transparent proxies. """ from __pypy__ import tproxy from types import MethodType _dummy = object() origtype = type def make_proxy(controller, type=_dummy, obj=_dummy): """ return a tranparent proxy controlled by the given 'controller' callable. The proxy wi...
Python
#import autopath try: from cslib import Repository from cslib.fd import FiniteDomain as fd print 'using pypy.lib.cslib' except ImportError: print 'using logilab.constraint' from logilab.constraint import Repository from logilab.constraint.fd import FiniteDomain as fd from logilab.constraint....
Python
from pyparsing import CaselessLiteral, Word, Upcase, delimitedList, Optional, \ Combine, Dict, Group, alphas, nums, alphanums, ParseException, Forward, oneOf, \ ZeroOrMore, restOfLine, Keyword, srange, OneOrMore, sglQuotedString, dblQuotedString, quotedString, \ TokenConverter, Empty, Suppress, NoMatch,...
Python
{'application':{'type':'Application', 'name':'Minimal', 'backgrounds': [ {'type':'Background', 'name':'bgMin', 'title':u'Query Answering in LT World', 'size':(1024, 768), 'menubar': {'type':'MenuBar', 'menus': [ {'type':'Menu', ...
Python
# Directory hosting ontodemo code demodir="d:\\PyPy-svn\\pypy-dist\\pypy\\lib\\pyontology\\ontodemo" # Directory for the PyPy distribution distdir="d:\\PyPy-svn\\pypy-dist" # Directory hosting the pyontology dependencies depssir="d:\\PyPy-svn\\pyontology-deps"
Python
{'application':{'type':'Application', 'name':'Minimal', 'backgrounds': [ {'type':'Background', 'name':'bgMin', 'title':u'Query Answering in LT World', 'size':(1280, 1024), 'menubar': {'type':'MenuBar', 'menus': [ {'type':'Menu', ...
Python
#!/usr/bin/env python """ Demo of the PyPy SPARQL handling functionality. """ from PythonCard import model import webbrowser import queries import commands import paths import xmlrpclib from os.path import join ltworld = "file:" + join(paths.demodir, "lt-world.html") class Server: def __init__(self): #...
Python
#!/usr/bin/env python import SimpleXMLRPCServer port = 9000 class Ontology: def sparql(self, sparql): return "Answer to SPARQL query:\n%s" % sparql def constr(self, sparql): return "Constraints for SPARQL query:\n%s" % sparql if __name__ == "__main__": import SimpleXMLRPCServer se...
Python
#!/usr/bin/env python import sys import paths from os.path import join sys.path.insert(0, paths.distdir) sys.path.insert(0, paths.depssir) from pypy.lib.pyontology.pyontology import Ontology import SimpleXMLRPCServer port = 9000 class OntologyWrapper(Ontology): def sparql(self, query): ans = [] ...
Python
ontodemo.py
Python
ontodemo.py
Python
#!/usr/bin/env python import SimpleXMLRPCServer port = 9000 class Ontology: def sparql(self, sparql): return "Answer to SPARQL query:\n%s" % sparql def constr(self, sparql): return "Constraints for SPARQL query:\n%s" % sparql if __name__ == "__main__": import SimpleXMLRPCServer se...
Python
#!/usr/bin/env python import sys import paths from os.path import join sys.path.insert(0, paths.distdir) sys.path.insert(0, paths.depssir) from pypy.lib.pyontology.pyontology import Ontology import SimpleXMLRPCServer port = 9000 class OntologyWrapper(Ontology): def sparql(self, query): ans = [] ...
Python
import sys from pypy.lib.pyontology.pyontology import Ontology def query(sparqlfile, ontofile): # return "An answer string" O = Ontology() O.add_file(ontofile, 'xml') q = file(sparqlfile).read() res = O.sparql(q) return res if __name__ == '__main__': if len(sys.argv) != 3: prin...
Python
from os.path import join import paths # !!!! We now ignore the RDF file and assume the server will use the # same preset ontology for all SPARQL queries !!! ontodir = paths.demodir sparqldir = paths.demodir def ontofile(query): if queries[query][1]: return join(ontodir, queries[query][1]) else: ...
Python
#!/usr/bin/env python """ Demo of the PyPy SPARQL handling functionality. """ from PythonCard import model import webbrowser import queries import commands import paths import xmlrpclib from os.path import join ltworld = "file:" + join(paths.demodir, "lt-world.html") class Server: def __init__(self): #...
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
from logilab.constraint.propagation import AbstractDomain, AbstractConstraint,\ ConsistencyFailure, Solver from logilab.constraint.distributors import DichotomyDistributor, SplitDistributor from logilab.constraint.fd import Expression from rdflib import URIRef try: # not sure if we have this when running on ...
Python
"""runpy.py - locating and running Python code using the module namespace Provides support for locating and running Python scripts using the Python module namespace instead of the native filesystem. Also provides support to make it easier to execute other code without affecting the current function namespace. This al...
Python
# temporary from _marshal import __doc__ from _marshal import *
Python
code = """ def foo(b, c): ''' pre: b < c ''' print 'foo' a = 2 d = bar(a) print d return b+a+c+d def bar(val): print 'bar', val return 42 def baz(b,c): try: return foo(b,c) finally: bar(3) class Mumble: def __init__(self, param): se...
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
#
Python
"""High performance data structures """ # # Copied and completed from the sandbox of CPython # (nondist/sandbox/collections/pydeque.py rev 1.1, Raymond Hettinger) # import operator try: from thread import get_ident as _thread_ident except ImportError: def _thread_ident(): return -1 n = 30 LFTLNK = ...
Python
"""tentative API for AOP in python. heavily influenced by Aspect++""" __all__ = ('around', 'before', 'after', 'introduce', 'PointCut', 'Aspect') ########################### # API ########################### import parser import re import sys import os import os.path as osp # advices # ------- class Advice(parser.AS...
Python
from pypy.lib import binascii def test_uu(): assert binascii.b2a_uu('1234567') == "',3(S-#4V-P \n" assert binascii.b2a_uu('123456789012345678901234567890123456789012345') == 'M,3(S-#4V-S@Y,#$R,S0U-C<X.3 Q,C,T-38W.#DP,3(S-#4V-S@Y,#$R,S0U\n' try: assert binascii.b2a_uu('1234567890123456789012345678...
Python
""" Disabled for now. This should run at app-level, too. """ import pickle class Picklable(object): def __init__(self, a=555): self.a = a def __eq__(self, other): return self.a == other.a def __str__(self): return '%s(%r)' % (self.__class__.__name__, self.a) __repr__ = __str__ ...
Python
#
Python
"""Higher order functions, and operations on callables. partial(fn,*args,**kw) - function resulting from partial application of a callable i.e. acts like that callable with some arguments already supplied. Examples: clamp = partial(max,0) # clamps negative values to...
Python
class StrategyDistributionMismatch(Exception): pass from collections import deque class Depth: pass class Breadth: pass #-- pythonic lazy solve_all (takes space) def lazily_iter_solve_all(space, direction=Depth): sp_stack = deque([]) sp_stack.append(space) if direction == Depth: def coll...
Python
""" This file is responsible for faking types """ class GetSetDescriptor(object): def __init__(self, protocol, name): self.protocol = protocol self.name = name def __get__(self, obj, type=None): return self.protocol.get(self.name, obj, type) def __set__(self, obj, value): ...
Python
""" Distributed controller(s) for use with transparent proxy objects First idea: 1. We use py.execnet to create a connection to wherever 2. We run some code there (RSync in advance makes some sense) 3. We access remote objects like normal ones, with a special protocol Local side: - Request an object from remote s...
Python
""" Some random support functions """ def get_remote_view(protocol): # this is dynamic to provide needed level of laziness class RemoteView(object): pass for key in protocol.remote_keys(): getter = lambda self: protocol.get_remote(key) setattr(RemoteView, key, property(getter)) ...
Python
""" objkeeper - Storage for remoteprotocol """ from types import FunctionType from distributed import faker class ObjKeeper(object): def __init__(self, exported_names = {}): self.exported_objects = [] # list of object that we've exported outside self.exported_names = exported_names # dictionary o...
Python
try: from protocol import RemoteProtocol, test_env, remote_loop, ObjectNotFound except ImportError: # XXX fix it # UGH. This is needed for tests pass
Python
import py from socket import socket from py.__.green.msgstruct import decodemessage, message from socket import socket, AF_INET, SOCK_STREAM import marshal import sys TRACE = False def trace(msg): if TRACE: print >>sys.stderr, msg class Finished(Exception): pass class SocketWrapper(object): def ...
Python
""" This is sample demo about how flexible pypy distribution is. Not counting __doc__ and initialization this is 2 line, fully operational file server, sample client which is in fileclient.py is included as well. Note that you must run it with pypy-c compiled with transparent proxy and allworkingmodules (or at least s...
Python
""" This is sample client for a server based in fileserver.py, not counting initialization and __doc__ has just 2 lines. Usage: pypy-c -i fileclient.py """ HOST = '127.0.0.1' PORT = 12221 from distributed.socklayer import connect file_opener = connect((HOST, PORT)).open # now you can do for example file_opener('/et...
Python
from distributed import RemoteProtocol, remote_loop from distributed.socklayer import Finished, socket_listener, socket_connecter PORT = 12122 class X: def __init__(self, z): self.z = z def meth(self, x): return self.z + x() def raising(self): 1/0 x = X(3) def remote()...
Python
""" Supplies the internal functions for functools.py in the standard library """ class partial: """ partial(func, *args, **keywords) - new function with partial application of the given arguments and keywords. """ __slots__ = ['func', 'args', 'keywords'] def __init__(self, func, *args, **keywo...
Python
# # One-liner implementation of cPickle # from pickle import * from pickle import __doc__, __version__, format_version, compatible_formats BadPickleGet = KeyError UnpickleableError = PicklingError # ____________________________________________________________ # XXX some temporary dark magic to produce pickled dumps ...
Python
""" Implementation helper: a struct that looks like a tuple. See timemodule and posixmodule for example uses. """ class structseqfield(object): """Definition of field of a structseq. The 'index' is for positional tuple-like indexing. Fields whose index is after a gap in the numbers cannot be accessed li...
Python
import parser, marshal, os, __future__ DUMPFILE = 'this_is_the_marshal_file' def reallycompile(tuples_or_src, filename, mode, flag_names): if type(tuples_or_src) is str: flags = 0 if 'nested_scopes' in flag_names: flags |= __future__.CO_NESTED if 'generators' in flag_names: ...
Python
""" This module provides the components needed to build your own __import__ function. """ # XXX partial implementation # XXX to be reviewed PY_SOURCE = 1 PY_COMPILED = 2 C_EXTENSION = 3 PY_RESOURCE = 4 PKG_DIRECTORY = 5 C_BUILTIN = 6 PY_FROZEN = 7 PY_CODERESOURCE = 8 import new impor...
Python
""" distributors - part of constraint satisfaction solver. """ import math, random def make_new_domains(domains): """return a shallow copy of dict of domains passed in argument""" domain = {} for key, value in domains.items(): domain[key] = value.copy() return domain class AbstractDistributor...
Python
from _cslib import DefaultDistributor
Python
from _cslib import Repository, Solver
Python
"""Tools to work with finite domain variables and constraints This module provides the following usable classes: * FiniteDomain: a class for storing FiniteDomains * Expression: a constraint represented as an expression * BinaryExpression: a binary constraint represented as an expression * various BasicConstraint c...
Python
"""The code of the constraint propagation algorithms""" import operator #from time import strftime class ConsistencyFailure(Exception): """The repository is not in a consistent state""" pass class Repository(object): """Stores variables, domains and constraints Propagates domain changes to constraint...
Python
from _cslib import FiniteDomain, _make_expression, AllDistinct def make_expression(variables, formula): func = 'lambda %s:%s' % (','.join(variables), formula) return _make_expression(variables, formula, eval(func))
Python
"""Tools to work with finite interval domain interval and constraints """ from propagation import AbstractDomain, BasicConstraint, \ ConsistencyFailure, AbstractConstraint from distributors import AbstractDistributor class Interval: """representation of an interval This class is used to give back result...
Python